Thursday, 9 April 2015
Code natural selection
Tuesday, 7 April 2015
Ruby-style digit separator for C-98?
Until we get to C++14 we don't have a nice alternative, but we have an ugly hack we can use: instead of writing 1000000 write "1 ## 000 ## 000".
It works, '##' is the preprocessor's token pasting operator, and it will paste two tokens together. Looks ugly, breaks the GUI highlighting, but at least you can count how many zeros you've got.
Nitpicker's corner: multiplying by 10 is easier, but there is no job-safety involved in that.
Nitpicker's corner II: The evaluation order of a chain of '##' is not defined, but I don't expect this to cause any problems; any order of evaluation should result in the same result for this case.
Thursday, 2 April 2015
Vim Tip: I want more menus!
Say, for example, you like to encrypt your text. Not always, but every once in a while. Enough to make a shortcut for it but not enough to remember what the shortcut is. You can try to grep your ~/.vimrc. You might find something like:
" Encrypt my stuff
map <leader>e ggg?G<CR>
(Yes, that command will actually encrypt your text in Vim. Try it!)
Wouldn't it be nice if you had a simpler way, though?
Turns out you can add your "encrypt" command to your gui. Then "menu" commands work just like the "map" family, but they create a GUI menu instead. Change your vimrc to something like this:
" Encrypt my stuff
map <leader>e ggg?G<CR>
menu Project.Encrypt ggg?G<CR>
Now if you reload your vimrc you'll find a new GUI menu created, from which you can easily encrypt your text. Decrypting is left as an exercise to the reader.
Extra tip: Want to try to learn the actual shortcut, like a real vim'er? Then try this:
menu Project.Encrypt<TAB>ggg?G ggg?G<CR>
Everything after the TAB will be right-aligned: you can use that space to annotate the key-combo you should use next time.
As usual, for more info check :help menu
Tuesday, 31 March 2015
Scope ending in C++
const int x = 42;
void f() {
int x[x];
x[24] = 0;
}
Unfortunately, it is. According to 3.3.2 in the standard, a definition is available in a child scope up to the point where it's shadowed, and that means "x" will first be interpreted as the global const int, being an index for a vector named "x". Any new references to "x" will point to the new declaration.
Fun stuff, right?
Tuesday, 18 November 2014
Gdb hit count: ignoring breakpoints (for a while)
One way would be to set up a watch expression. If you can't setup a watch expression, say, because you're using an iterator and it'd be hard to set one, you can also tell gdb to setup a breakpoint, and then ignore it N times.
Let's see how this works with this example:
#include <vector>
int main() {
std::vector<int> v = {1,2,3,4,5,0,7,8,9};
int x = 42;
for (auto i = v.begin(); i != v.end(); ++i) {
x = x / *i;
}
return 0;
}
After compiling we run it to see it crash; let's start it on gdb, then set a brakepoint on the line where it crashes.
(gdb) break foo.cpp:8
Breakpoint 1 at 0x4007bc: file foo.cpp, line 8.
(gdb) info breakpoints
Num Type Disp Enb Address What
1 breakpoint keep y 0x00000000004007bc in main() at foo.cpp:8
Typing "info breakpoints" will tell you the breakpoint number; then we can tell gdb to ignore this breakpoint forever (where forever is a very large number, so the program will run until it crashes):
(gdb) ignore 1 99999
Will ignore next 99999 crossings of breakpoint 1.
(gdb) run
Starting program: /home/nico/src/a.out
Program received signal SIGFPE, Arithmetic exception.
0x00000000004007d5 in main () at foo.cpp:8
8 x = x / *i;
(gdb) info breakpoints
Num Type Disp Enb Address What
1 breakpoint keep y 0x00000000004007bc in main() at foo.cpp:8
breakpoint already hit 6 times
ignore next 99993 hits
(gdb)
By doing this now we know the program crashes the sixth time it goes through that breakpoint. Now we can actually debug the problem:
(gdb) ignore 1 5
Will ignore next 5 crossings of breakpoint 1.
(gdb) run
Starting program: /home/nico/src/a.out
Breakpoint 1, main () at foo.cpp:8
8 x = x / *i;
(gdb) p *i
$1 = (int &) @0x603024: 0
This time gdb will break exactly on the spot we want.
Tuesday, 7 January 2014
Extending the life of a temp variable in C++
Take a look at this code: what does it do?
struct X {
X() { cout << "X"; }
~X() { cout << "~X"; }
};
void foo() {
X x;
}
It's not hard to see this code will print "X", then "~X" immediately after it: X() is created as a temporary variable which gets constructed and then immediately destructed. Any side effects this object may have should happen in the constructor or the destructor.
Now that we know a bit more about the lifetime of temp objects, is this valid C++?
struct X {
int y;
X(int y) : y(y) {}
};
int foo() {
const X &ref = X(42);
return ref.y;
}
It looks a bit strange: ref is a reference to a temporary object. Temporary objects get destroyed as soon as they are created, so ref.y should be an undefined data access. Right? Not quite, the C++ standard has a special consideration for const references using a temporary object: according to 12.2.3 this is a valid read, as long as ref is a "const X&". Even more interesting, in this case the lifetime of the temporary object "X(42)" gets extended until ref goes out of scope: only when the reference is gone the destructor for X will be run!
Tuesday, 3 December 2013
Static initialization in C++
Let's analyze this seemingly simple code sample:
struct X {
X();
};
void foo() {
static X a;
}
X b;
void bar() {
foo();
X c;
}
Do you know what the order of initialization will be for a, b and c? b is rather easy: it's a plain global variable and it should be initialized first of all, even before main runs. c is also easy, it will be initialized only when the execution reaches the line where it is defined. How about a?
a is static, so just like b it should be initialized only once. Unlike b, though, it belongs to foo's scope, and it will only be initialized the first time foo is executed. Let's see how that happens in gcc by taking an even simpler example:
struct X {
X() throw();
};
void foo() throw() {
static X x;
}
Note: the throw()'s are in there only to tell the compiler we don't want any kind of exception handling code, that will make the assembly inspection a bit easier. Let's compile, disassemble and c++filt this. You should see something very interesting in the first few lines:
.file "foo.cpp"
.local guard variable for foo()::x
.comm guard variable for foo()::x,8,8
.text
# Skipping the actual foo definition, we'll see that later
.LFE0:
.size foo(), .-foo()
.local foo()::x
.comm foo()::x,1,1
Inside the definition for foo gcc reserved some space for our static variable; interestingly, it also reserved 8 bytes for something called "Guard variable for foo()::x" (when demangled, of course). This means that there is a flag to determine whether foo()::x was already initialized, or not.
Let's analyze now the assembly for foo() to understand how the guard is used:
foo():
movl guard variable for foo()::x, %eax
movzbl (%rax), %eax
testb %al, %al
jne .L1
movl guard variable for foo()::x, %edi
call __cxa_guard_acquire
testl %eax, %eax
setne %al
testb %al, %al
je .L1
movl foo()::x, %edi
call X::X()
movl guard variable for foo()::x, %edi
call __cxa_guard_release
.L1:
# Rest of the method (empty, in our example)
This is also interesting: initializing a static variable depends on libcpp (which is dependant on the compiler's ABI). We could translate the whole thing to, more or less, the following pseudocode:
void foo() {
static X x;
static guard x_is_initialized;
if ( __cxa_guard_acquire(x_is_initialized) ) {
X::X();
x_is_initialized = true;
__cxa_guard_release(x_is_initialized);
}
}
(Note: exception safety ignored, which of course is not the case for a proper libcpp)
Eventually, __cxa_guard_acquire will check if this object was already initialized or if anyone else is trying to initialize this object, and then it will signal the calling method to run x's constructor if it's safe to do so.
There's another bit of information in here which is not immediately obvious: in case X's constructor fails (ie an exception is thrown within this method), x_is_initialized won't be set to true. Assuming the exception is caught somewhere else, if foo() is called again the initialization for foo()::x will be attempted to run once again.
Tuesday, 19 November 2013
Vim tim: quickly switch from header to impl
Add it to your bundles in vim and, for extra magic, just map some key to :AT in your vimrc. I have added this one:
map <F4> :AT<CR>
I don't know how I lived without this for such a long time.
Thursday, 14 November 2013
Setting up a Linux GW VIII: Proxy and content filtering
Now that we have a basic gateway we can do crazy stuff, like installing a proxy. You may want to manually configure a proxy for each client, but you can also choose to install a transparent proxy for all your users. This can be done with squid, let's see how.
Start by installing squid on your gateway. You can choose a different machine, but you'll have to do some magic with iptales. It's easier to just use the same machine.
Once squid is installed head to /etc/squid/ to vim squid.conf. Yes, it's very scary to see such a long config file, but it's mostly just comments. Luckily squid has reasonable defaults, so you can just ignore most of this file. Just to test if your squid installation was successful, before changing anything, you can tail -f /var/log/squid/access.log and set your browser's proxy to your gateway's IP, port 3128 (squid's default port). If everything works you should be able to browse and also see the access logs scrolling by.
If you are getting a 'denied' page on every request, you may have to configure squid to allow http access. Search for the 'http_access deny all' and comment it. You may also have to search for the local networks definitions and set it up correctly (something like 'acl localnet src 192.168.0.0/24').
Once you have verified that your proxy is working, you can configure it to run on transparent mode. Search for the http_port directive, and change it to something like 'http_port 8213 transparent' (noticed I changed the default port). It is also a good practice to specify IP and port, so squid can bind only to the local interface (you are probably not interested in serving as a proxy for the outside world, unless you plan to run a reverse proxy).
Changing squid to run on transparent mode is not enough, though. You will also need to tell your router to redirect every incoming packet from port 80 to squid. Assuming your LAN is on the 192.168.10.0/24 address and squid is listenning on port 1234, you can use this magic command to setup your iptables rule:
iptables -t nat -A PREROUTING -s 192.168.10.0/24 -p tcp --dport 80 -j DNAT --to :1234
If this doesn't work for you, or you want a more detailed explanation, you can check my post about this iptables rule.
Everything ready, you should be able to unconfigure the proxy from your browser and start using squid right away, no configuration needed. tail -f /var/log/squid/access.log for hours of (thought-policing) fun.
Adding a content filter to squid
Now that you have a gateway and a transparent proxy, it's time to install a content filter too. It's not hard, just go to your squid's config file and search for the acl section. Over there, add the following two lines:
acl blocksites url_regex "/home/router/blocked_sites.acl"
http_access deny blocksites
This will include the blocked_sites.acl file and deny access to every URL on it. There are many blacklist services out there, from which you can download a nice filter to suit your needs.
Of course, you probably don't want to restart squid each time a new site is added to your blocklist. For this you can use "squid -k reconfigure" to make squid reload its configuration.
Some random tips for squid:
- If you think your squid is responding too slowly, you can manually setup your DNS servers. Considering squid will most likely be installed on the gateway, it might be easier to just use the gateway's gateway for the DNS, instead of the bind service running on the box. You can set this option with the directive "dns_nameservers xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy" on squid.conf.
- The TCP_MISS on the access.log means that a request was successfully served, but the content was not cached. You can review your cache limits if you get this message too much, may be you can increase the caching limit.
- You don't need to restart squid each time you change the configuration. That would be ackward if you have a lot of users. Try "squid -k reconfigure" instead.
Tuesday, 12 November 2013
Human friendly c declarations
To decipher weird c declarations go to http://cdecl.org/ and type your type. It works for most cases... good luck trying to figure out templates, though, for template metaprogramming you are on your own.
Thursday, 7 November 2013
Setting up a Linux GW VII: Fun with iptables, setting up port forwardings
In any LAN you'll probably want to expose some services to the outer world, be it for a bittorrent connection or because you have internal servers you need to access from outside your internal LAN. To do this, you'll have to tell your router to forward some external port to an internal one, like this:
iptables -t nat -A PREROUTING -i eth0 -p tcp
--dport PORT -j DNAT --to INTERNAL_IP:INTERNAL_PORT
# This rule may not be needed, depending on other chain confings
iptables -A INPUT -i eth0 -p tcp -m state --state NEW
--dport PORT -j DNAT --to INTERNAL_IP:INTERNAL_PORT
This is enough to expose a private server to the world, but it will not be very useful when your dynamic IP changes, so you'll need to set INTERNAL_IP to be a static IP.
Of course, this commands are little less than black magic. iptables are rather complex and quite difficult to master, but as a short description we can say they are a way of applying a set of rules to incoming network packets. In iptables you have different tables of rules (in this case we use -t[able] nat) and specify that we want our rule to be applied in the PREROUTING phase. -i specifies that this rule should be applied only to packets incoming from eth0, and --dport means this rule applies only to packets incoming from a certain port. Of course, if you are going to specify a port then you need to specify the protocol (in this case, tcp).
Now we have replicated in our setup almost all the functionalities a small COTS router has. Next time we'll see how to improve that by adding a proxy.
Tuesday, 5 November 2013
Automagically setup breakpoints with gdb
Luckily you can easily restore your state if you just write all the gdb commands you need into a file, then start gdb with "--command=state.gdb". Magic! All your breakpoints are there.
Alternatively, an even better solution: just don't exit gdb after recompiling, simply "kill" your currently under-debug process (ie type "kill" inside gdb, do not kill gdb itself!) and gdb will be smart enough to reload your binary if it changed.
Thursday, 31 October 2013
Setting up a Linux GW VI: Configuring a console friendly router and setting up static DHCP IPs
Moving DHCP config files
Since I want to keep everything together for easy administration, I will move the configuration files for DHCP to /home/router/dhcp. Changing the dhcpd.conf file itself is easy, just move the subnets declarations and add this line:
include "/home/router/dhcp/subnets.conf";
include "/home/router/dhcp/static_hosts.conf";
Like we did before with bind, we need to configure apparmor. vim /etc/apparmor.d/usr.sbin.dhcpd and add this two lines:
/home/router/dhcp/ rw,
/home/router/dhcp/** rw,
Restart apparmor service, then restart dhcpd. Everything should work just fine.
Setting up static IPs
Remember the static_hosts file we created before? We can use that to define a static IP. Add the following to set a static IP host:
host HostName {
hardware ethernet 00:00:00:00:00:00
fixed-address 192.168.10.50;
}
After that, just restart the DHCP service and renew your client's IP. Done, it's static now!
Wait a minute: how do you find the MAC for your host? I'm to lazy to copy and type it, so I did the following:
cd /home/router/dhcp
ln -s /var/lib/dhcp leases
Then you can check the hardware address in the leases/dhcpd.leases file. I created a symlink to keep this directory at hand, since it gives you a status of the current leases.
Tuesday, 29 October 2013
Have you checked your stack?
Luckily gcc seems to have an option to verify that your functions do not use an unbounded amount of stack space: just compile with the option "-fstack-usage" and a file .su will be generated with stack information for each function.
You probably want to see only static or bounded stack usages; an unbounded stack usage might be a sign that you should be storing that object on the stack instead.
Thursday, 24 October 2013
Setting up a Linux GW V: DCHP
Edit /etc/dhcp/dhcpd.conf, set the domain-name and the domain-name-servers, like this:
option domain-name "lan";
option domain-name-servers 192.168.10.1 192.168.0.1;
default-lease-time 86400;
max-lease-time 172800;
authoritative;
I'm not sure if the first line is needed. The other two will set the DNS servers for your clients. Also, increasing your lease time is recommended, I used one day for default leases. I set this DHCP server as the authoritative server. If this is your router, that's probably what you want.
Now we need to define the network topology:
# This is the WAN network, and we won't provide a service here
subnet 192.168.0.0 netmask 255.255.255.0 {
}
# Define the service we provide for the LAN
subnet 192.168.10.1 netmask 255.255.255.0 {
range 192.168.10.100 192.168.10.200;
option routers 192.168.10.1;
}
Now we need to restart ISC:
sudo /./etc/init.d/isc-dhcp-server restart
And now we need to check if everything worked in the client. It's easy this time, we just ask for an IP:
sudo dhclient
ifconfig
If everything went fine, we should now have an IP in the 100-200 range, as well as the DNS server in /etc/resolv.conf. We have now setup a very basic router and should be able to server several clients for basic browsing capabilities.
Next time we'll see how to tidy up everything, for easier administration.
Tuesday, 22 October 2013
Some gratuitous MSVC bashing
I can only imagine how incredibly ugly their lexer must be to say it's not a fixable problem.
Thursday, 17 October 2013
Setting up a Linux GW IV: Setting up apparmor
After installing bind9 we should get a new file in /etc/apparmor.d/usr.sbin.named. Add the following lines at the bottom:
/home/router/named/** rw,
/home/router/named/ rw,
And restart apparmor service:
/./etc/init.d/apparmor restart
Since we were modifying apparmor to allow a non-standard bind installation, now restart bind too. This time it will start without any errors, and you should be able to tail -f /home/router/named/dns.log to see the DNS queries on real time. If it doesn't, check that /home/router/named is writable to the bind user (I did a chgrp -R bind named).
Tuesday, 15 October 2013
A C++ template device to obtain an underlying type
template <typename T> struct get_real_type { typedef T type; };
template <typename T> struct get_real_type<T*> { typedef T type; };
template <typename T> struct get_real_type<T&> { typedef T type; };
template <class T>
int foo() {
return get_real_type<T>::type::N;
}
struct Bar {
static const int N=24;
};
#include <iostream>
using namespace std;
int main() {
cout << foo<Bar*>() << endl;
cout << foo<Bar&>() << endl;
cout << foo<Bar>() << endl;
}
Incidentally, this is also the basis for the implementation of std::remove_reference. Actually you'd be better of using std::remove_reference, for your own sanity.
Thursday, 10 October 2013
Setting up a Linux GW III: Setting up DNS with bind9
ping google.com
You should get a message saying the host is unknown. Can you guess why? Right, there's no DNS.
Setting up DNS
DNS will be necessary to resolve domains to IPs. bind9 is the default option for Debian based servers (are there others? no idea).
sudo apt-get install bind9
This will get your DNS server up and running, but you will still need to add this server manually to your client (again, because there's no DHCP running):
sudo echo "nameserver 192.168.10.1" > /etc/resolv.conf
And now:
ping google.com
Magic again, it (may) work. If it doesn't, you may need to open /etc/bind/named.conf and setup your router (192.168.0.1) as a forwarder, then restart the bind server.
Of course this is rather boring. If you are going to install a DNS you might as well create a custom TLD for your LAN.
Setting up a custom TLD with bind9 for your LAN
So far on the series about how to install a Linux based router, we set up a Linux router with NAT and a basic DNS. Now we'll setup a custom TLD, so you can have custom domains for your LAN. For example, if you want your router to have a nice user friendly name, instead of just an IP.
Let's start by adding a local zone to /etc/bind/named.conf.local, for a domain we'll call "lan":
zone "lan" {
type master;
file "/home/router/named/lan.db";
};
Now we need to add a reverse zone. Note how the name is the IP reversed:
zone "10.168.192.in-addr.arpa" {
type master;
file "/home/router/named/rev.10.168.192.in-addr.arpa";
};
We still need to create both files (lan.db and rev.10.168.192.in-addr.arpa), but will do that later. Lets setup a place to log all the DNS queries (optional):
logging {
channel query.log {
file "/home/router/named/dns.log";
severity debug 3;
print-time yes;
};
category queries { query.log; };
};
For the log entry I have chosen /home/router/named as the log directory, just because for this project I'm keeping everything together (config and logs) so it's easy for people not used to administer a Linux box, but of course this means that apparmor must be configured to allow reads and writes for bind in this directory. We'll get to that in a second, first let's create the needed zone files for our new TLD.
Remember our two zone files? I put them on /home/router/named, but usually they are on /etc/bind. Again, I did this so I can have all the config files together. These are my two files:
For lan.db
lan. IN SOA ns1.lan. admin.lan. (
2006081401
28800
3600
604800
38400
)
lan. IN NS ns1.lan.
wiki IN A 192.168.0.66
ns1 IN A 192.168.0.1
router IN A 192.168.0.1
For rev.10.168.192.in-addr.arpa
@ IN SOA ns1.lan. admin.example.com. (
2006081401;
28800;
604800;
604800;
86400
)
IN NS ns1.lan.
1 IN PTR lan
Most of these lines are black magic, and since an explanation of both DNS and Bind is out of scope (feel free to read the RFC if you need more info) let's just say you can add new DNS entries by adding lines like this:
NICE_NAME IN A REAL_IP
This will make bind translate NICE_NAME.lan to REAL_IP. Of course, this will depend on the TLD you defined. Now restart bind to get a crapton of errors. It will complain about not being able to load a master file in /home/router/named. Remember that apparmor thing I mentioned?
Tuesday, 8 October 2013
Gcc tip: better disassembly
While you won't escape the need to learn some assembly to get any meaningful information out of gcc's assembly listing, there are some tips which might make your life much easier:
C++ filt
c++filt is part of the build essentials package, and will turn mangled names into proper C++ names. You won't need to remember that _Znwm is the mangled version of "operator new", just run "g++ -E foo.cpp -o /dev/stdout | c++filt" and you'll get an assembly with unmangled names.
fverbose-asm
Some people have the ability to read assembly and automatically understand how the data flows between registers and variables very quickly. For the mere mortals like us, gcc has a very helpful flag called "-fverbose-asm" which will add a comment to each line where a variable is referenced. This will let you keep track of the data flow inside a function.
Extra, unrelated, tip:
As far as I know, gcc has no option to write to stdout; just use "-o /dev/stdout" to let it write to a fake file which Linux will helpfully create for you, then you can pipe the hell out of gcc's output.