<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>seg fault</title>
	<atom:link href="http://psomas.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://psomas.wordpress.com</link>
	<description>Random computer-related stuff</description>
	<lastBuildDate>Fri, 19 Apr 2013 10:35:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='psomas.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/82d0ed921b0ed4c44853dfdcd5973e02?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>seg fault</title>
		<link>http://psomas.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://psomas.wordpress.com/osd.xml" title="seg fault" />
	<atom:link rel='hub' href='http://psomas.wordpress.com/?pushpress=hub'/>
		<item>
		<title>gcc / ld madness</title>
		<link>http://psomas.wordpress.com/2012/11/07/gcc-ld-madness/</link>
		<comments>http://psomas.wordpress.com/2012/11/07/gcc-ld-madness/#comments</comments>
		<pubDate>Wed, 07 Nov 2012 17:53:14 +0000</pubDate>
		<dc:creator>psomas</dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[FOSS]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[OS]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Virtualization]]></category>
		<category><![CDATA[XEN]]></category>
		<category><![CDATA[64bit]]></category>
		<category><![CDATA[amd64]]></category>
		<category><![CDATA[Assembly]]></category>
		<category><![CDATA[gcc]]></category>
		<category><![CDATA[ld]]></category>
		<category><![CDATA[linker]]></category>
		<category><![CDATA[x86_64]]></category>

		<guid isPermaLink="false">http://psomas.wordpress.com/?p=239</guid>
		<description><![CDATA[So, I started reading [The Definitive Guide to the Xen Hypervisor] (again ), and I thought it would be fun to start with the example guest kernel, provided by the author, and extend it a bit (ye, there&#8217;s mini-os already in extras/, but I wanted to struggle with all the peculiarities of extended inline asm, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=239&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>So, I started reading <a href="http://www.amazon.com/The-Definitive-Guide-Xen-Hypervisor/dp/013234971X" target="_blank">[The Definitive Guide to the Xen Hypervisor]</a> (again <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ), and I thought it would be fun to start with the example guest kernel, provided by the author, and extend it a bit (ye, there&#8217;s mini-os already in extras/, but I wanted to struggle with all the peculiarities of extended inline asm, x86_64 asm, linker scripts, C macros etc, myself <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ).</p>
<p>After doing some reading about x86_64 asm, I &#8216;ported&#8217; the example kernel to 64bit, and gave it a try. And of course, it crashed. While I was responsible for the first couple of crashes (for which btw, I can write at least 2-3 additional blog posts <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ), I got stuck with this error: </p>
<pre class="brush: plain; title: ; notranslate">traps.c:470:d100 Unhandled bkpt fault/trap [#3] on VCPU 0 [ec=0000]
RIP:    e033:&lt;0000000000002271&gt;</pre>
<p>when trying to boot the example kernel as a domU (under xen-unstable).</p>
<p>0&#215;2000 is the address where XEN maps the hypercall page inside the domU&#8217;s address space. The guest crashed when trying to issue any hypercall (HYPERCALL_console_io in this case). At first, I thought I had screwed up with the x86_64 extended inline asm, used to perform the hypercall, so I checked how the hypercall macros were implemented both in the Linux kernel (wow btw, it&#8217;s pretty scary), and in the mini-os kernel. But, I got the same crash with both of them.</p>
<p>After some more debugging, I made it work. In my Makefile, I used gcc to link all of the object files into the guest kernel. When I switched to ld, it worked. Apparently, when using gcc to link object files, it calls the linker with a lot of options you might not want. Invoking gcc using the -v option will reveal that gcc calls collect2 (a wrapper around the linker), which then calls ld with various options (certainly not only the ones I was passing to my &#8216;linker&#8217;). One of them was &#8211;build-id, which generates a .note.gnu.build-id&#8221; ELF note section in the output file, which contains some hash to identify the linked file.</p>
<p>Apparently, this note changes the layout of the resulting ELF file, and &#8216;shifts&#8217; the .text section to 0&#215;30 from 0&#215;0, and hypercall_page ends up at 0&#215;2030 instead of 0&#215;2000. Thus, when I &#8216;called&#8217; into the hypercall page, I ended up at some arbitrary location instead of the start of the specific hypercall handler I was going for. But it took me quite some time of debugging before I did an objdump -dS [kernel] (and objdump -x [kernel]), and found out what was going on.</p>
<p>The code from bootstrap.x86_64.S looks like this (notice the .org 0&#215;2000 before the hypercall_page global symbol):</p>
<pre class="brush: plain; title: ; notranslate">
        .text
        .code64
	.globl	_start, shared_info, hypercall_page
_start:
	cld
	movq stack_start(%rip),%rsp
	movq %rsi,%rdi
	call start_kernel

stack_start:
	.quad stack + 8192
	
	.org 0x1000
shared_info:
	.org 0x2000

hypercall_page:
	.org 0x3000	
</pre>
<p>One solution, mentioned earlier, is to switch to ld (which probalby makes more sense), instead of using gcc. The other solution is to tweak the ELF file layout, through the linker script (actually this is pretty much what the Linux kernel does, to work around this):</p>
<pre class="brush: plain; title: ; notranslate">
OUTPUT_FORMAT(&quot;elf64-x86-64&quot;, &quot;elf64-x86-64&quot;, &quot;elf64-x86-64&quot;)
OUTPUT_ARCH(i386:x86-64)
ENTRY(_start)

PHDRS {
	text PT_LOAD FLAGS(5);		/* R_E */
	data PT_LOAD FLAGS(7);		/* RWE */
	note PT_NOTE FLAGS(0);		/* ___ */
}

SECTIONS
{
	. = 0x0;			/* Start of the output file */
	_text = .;			/* Text and ro data */
	.text : {
		*(.text)
	} :text = 0x9090 

	_etext = .;			/* End ot text section */

	.rodata : {			/* ro data section */
		*(.rodata)
		*(.rodata.*)
	} :text

	.note : { 
		*(.note.*)
	} :note

	_data = .;
	.data : {			/* Data */
		*(.data)
	} :data

	_edata = .;			/* End of data section */	
}
</pre>
<p>And now that my kernel boots, I can go back to copy-pasting code from the book &#8230; erm hacking. <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>Disclaimer: I&#8217;m not very familiar with lds scripts or x86_64 asm, so don&#8217;t trust this post too much. <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/psomas.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/psomas.wordpress.com/239/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=239&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://psomas.wordpress.com/2012/11/07/gcc-ld-madness/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/abc7e2b649baa48e52fda25c1bd7a82e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">psomas</media:title>
		</media:content>
	</item>
		<item>
		<title>Launching Gentoo VMs on okeanos.io</title>
		<link>http://psomas.wordpress.com/2012/10/23/launching-gentoo-vms-on-okeanos-io/</link>
		<comments>http://psomas.wordpress.com/2012/10/23/launching-gentoo-vms-on-okeanos-io/#comments</comments>
		<pubDate>Tue, 23 Oct 2012 13:50:29 +0000</pubDate>
		<dc:creator>psomas</dc:creator>
				<category><![CDATA[FOSS]]></category>
		<category><![CDATA[Gentoo Linux]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[okeanos]]></category>
		<category><![CDATA[cloud]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[iaas]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[OpenStack]]></category>
		<category><![CDATA[synnefo]]></category>
		<category><![CDATA[Virtualization]]></category>

		<guid isPermaLink="false">http://psomas.wordpress.com/?p=212</guid>
		<description><![CDATA[Update: Corrected fallocate and parted commands, and removed diratime mount option. Thanks to axil Long time, no post. For about a year now, I&#8217;ve been working at GRNET on its (OpenStack API compliant) open source IaaS cloud platform Synnefo, which powers the ~okeanos service. Since ~okeanos is mainly aimed towards the Greek academic community (and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=212&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Update: Corrected fallocate and parted commands, and removed <a href="https://lwn.net/Articles/244941/" target="_blank">diratime</a> mount option. Thanks to <a href="https://twitter.com/_axil" target="_blank">axil</a></p>
<p>Long time, no post.</p>
<p>For about a year now, I&#8217;ve been working at <a href="http://www.grnet.gr/default.asp?pid=1&amp;la=2">GRNET</a> on its (<a href="http://www.openstack.org">OpenStack</a> API compliant) open source IaaS cloud platform <a href="http://docs.dev.grnet.gr/synnefo/latest/index.html">Synnefo</a>, which powers the <a href="https://okeanos.grnet.gr">~okeanos</a> service.</p>
<p>Since ~okeanos is mainly aimed towards the Greek academic community (and thus has restrictions on who can use the service), we set up a <a href="https://okeanos.io">&#8216;playground&#8217; &#8216;bleeding-edge&#8217; installation (okeanos.io)</a> of Synnefo, where anyone can get a free trial account, experiment with the the Web UI, and have fun scripting with the <a href="http://code.grnet.gr/projects/kamaki">kamaki</a> API client. So, you get to try the latest features of Synnefo, while we get valuable feedback. Sounds like a fair deal. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Unfortunately, being the only one in our team that actually uses <a href="http://gentoo.org">Gentoo Linux</a>, up until recently Gentoo VMs were not available. So, a couple of days ago I decided it was about time to get a serious distro running on ~okeanos (the load of our servers had been ridiculously low after all <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ). For future reference, and in case anyone wants to upload their own image on okeanos.io or ~okeanos, I&#8217;ll briefly describe the steps I followed.</p>
<p>1) Launch a Debian-base (who needs a GUI?) VM on okeanos.io</p>
<p>Everything from here on is done inside our Debian-base VM.</p>
<p>2) Use fallocate or dd seek= to create an (empty) file large enough to hold our image (5GB)<br />
<code><br />
fallocate -o $((5 * 1024 * 1024 *1024)) -l 1 gentoo.img<br />
</code></p>
<p>3) Losetup the image, partition and mount it<br />
<code><br />
losetup -f gentoo.img<br />
parted /dev/loop0 mklabel msdos<br />
parted /dev/loop0 mkpart primary ext4 2048s 5G<br />
kpartx -a /dev/loop0<br />
mkfs.ext4 /dev/mapper/loop0p1<br />
losetup /dev/loop1 /dev/mapper/loop0p1 (trick needed for grub2 installation later on)<br />
mount /dev/loop1 /mnt/gentoo -t ext4 -o noatime<br />
</code></p>
<p>4) Chroot and install Gentoo in /mnt/gentoo. Just follow the <a href="http://www.gentoo.org/doc/en/handbook/">handbook</a>. At a minimum you&#8217;ll need to extract the base system and portage, and set up some basic configs, like networking. It&#8217;s up to you how much you want to customize the image. For the Linux Kernel, I just copied directly the Debian /boot/[vmlinuz|initrd|System.map] and /lib/modules/ of the VM (and it worked! <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ).</p>
<p>5) Install sys-boot/grub-2.00 (I had some *minor* issues with grub-0.97 <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ).</p>
<p>6) Install grub2 in /dev/loop0 (<a href="http://superuser.com/questions/130955/how-to-install-grub-into-an-img-file?answertab=active#tab-top">this should help</a>). Make sure your device.map inside the Gentoo chroot looks like this:<br />
<code><br />
(hd0) /dev/loop0<br />
(hd1) /dev/loop1<br />
</code><br />
and make sure you have a sane grub.cfg (I&#8217;d suggest replacing all references to UUIDs in grub.cfg and /etc/fstab to /dev/vda[1]).<br />
Now, outside the chroot, run:<br />
<code><br />
grub-install  --root-directory=/mnt --grub-mkdevicemap=/mnt/boot/grub/device.map /dev/loop0<br />
</code></p>
<p>Cleanup everything (umount, losetup -d, kpartx -d etc), and we&#8217;re ready to upload the image, with <a href="http://code.grnet.gr/projects/snf-image-creator">snf-image-creator</a>. </p>
<p>snf-image-creator takes a diskdump as input, launches a helper VM, cleans up the diskdump / image (cleanup of sensitive data etc), and optionally uploads and registers our image with ~okeanos. </p>
<p>For more information on how snf-image-creator and Synnefo image registry works, visit the relevant docs <a href="https://code.grnet.gr/projects/snf-image-creator/repository/revisions/master/show/docs">[1]</a><a href="http://docs.dev.grnet.gr/synnefo/latest/plankton.html">[2]</a><a href="http://docs.dev.grnet.gr/synnefo/latest/pithos.html">[3]</a>.</p>
<p>0) Since snf-image-creator will use qemu/kvm to spawn a helper VM, and we&#8217;re inside a VM, let&#8217;s make sure that nested virtualization (<a href="www.usenix.org/event/osdi10/tech/slides/ben-yehuda.pdf">OSDI &#8217;10 Best Paper award</a> btw <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) works.</p>
<p>First, we need to make sure that kvm_[amd|intel] is modprobe&#8217;d on the host machine / hypervisor with the nested = 1 parameter, and that the vcpu, that qemu/kvm creates, thinks that it has &#8216;virtual&#8217; virtualization extensions (that&#8217;s actually our responsibility, and it&#8217;s enabled on the okeanos.io servers).</p>
<p>Inside our Debian VM, let&#8217;s verify that everything is ok.<br />
<code><br />
grep [vmx | svm] /proc/cpuinfo<br />
modprobe -v kvm kvm_intel<br />
</code></p>
<p>1) Clone snf-image-creator repo<br />
<code><br />
git clone <a href="https://code.grnet.gr/git/snf-image-creator" rel="nofollow">https://code.grnet.gr/git/snf-image-creator</a><br />
</code></p>
<p>2) <a>Install</a> snf-image-creator using setuptools (./setup.py install) and optionally virtualenv. You&#8217;ll need to install (pip install / aptitude install etc) setuptools, (python-)libguestfs and python-dialog manually. setuptools will take care of the rest of the deps.</p>
<p>3) Use snf-image-creator to prepare and upload / register the image:<br />
<code><br />
snf-image-creator -u gentoo.diskdump -r "Gentoo Linux" -a [okeanos.io username] -t [okeanos.io user token] gentoo.img -o gentoo.img --force<br />
</code></p>
<p>If everything goes as planned, after snf-image-creator terminates, you should be able to see your newly uploaded image in <a href="https://pithos.okeanos.io" rel="nofollow">https://pithos.okeanos.io</a>, inside the Images container. You should also be able to choose your image to create a new VM (either via the Web UI, or using the kamaki client).</p>
<p>And, let&#8217;s install kamaki to spawn some Gentoo VMs:<br />
<code><br />
git clone <a href="https://code.grnet.gr/git/kamaki" rel="nofollow">https://code.grnet.gr/git/kamaki</a><br />
</code><br />
and install it using setuptools (just like snf-image-creator). Alternatively, you could use our <a href="http://apt.dev.grnet.gr">Debian repo</a> (you can find the GPG key <a href="https://dev.grnet.gr/files/apt-grnetpub.key">here</a>).</p>
<p>Modify .kamakirc to match your credentials:<br />
<code><br />
[astakos]<br />
enable = on<br />
url = <a href="https://astakos.okeanos.io" rel="nofollow">https://astakos.okeanos.io</a><br />
[compute]<br />
cyclades_extensions = on<br />
enable = on<br />
url = <a href="https://cyclades.okeanos.io/api/v1.1" rel="nofollow">https://cyclades.okeanos.io/api/v1.1</a><br />
[global]<br />
colors = on<br />
token = [token]<br />
[image]<br />
enable = on<br />
url = <a href="https://cyclades.okeanos.io/plankton" rel="nofollow">https://cyclades.okeanos.io/plankton</a><br />
[storage]<br />
account = [username]<br />
container = pithos<br />
enable = on<br />
pithos_extensions = on<br />
url = <a href="https://pithos.okeanos.io/v1" rel="nofollow">https://pithos.okeanos.io/v1</a><br />
</code></p>
<p>Now, let&#8217;s create our first Gentoo VM:<br />
<code><br />
kamaki server create LarryTheCow 37 `kamaki image list | grep Gentoo | cut -f -d ' '` --personality /root/.ssh/authorized_keys<br />
</code></p>
<p>That&#8217;s all for now. Hopefully, I&#8217;ll return soon with another more detailed post on scripting with kamaki (<a href="http://www.cslab.ece.ntua.gr/~vkoukis/">vkoukis</a> has a nice script using kamaki python lib to create from scratch a small MPI cluster on ~okeanos <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ).</p>
<p>Cheers!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/psomas.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/psomas.wordpress.com/212/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=212&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://psomas.wordpress.com/2012/10/23/launching-gentoo-vms-on-okeanos-io/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/abc7e2b649baa48e52fda25c1bd7a82e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">psomas</media:title>
		</media:content>
	</item>
		<item>
		<title>Abusing the C preprocessor</title>
		<link>http://psomas.wordpress.com/2011/08/29/abusing-the-c-preprocessor/</link>
		<comments>http://psomas.wordpress.com/2011/08/29/abusing-the-c-preprocessor/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 13:58:15 +0000</pubDate>
		<dc:creator>psomas</dc:creator>
				<category><![CDATA[FOSS]]></category>
		<category><![CDATA[Gentoo]]></category>
		<category><![CDATA[Gentoo Linux]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[OS]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[Kernel]]></category>
		<category><![CDATA[Preprocessor]]></category>
		<category><![CDATA[Trick]]></category>

		<guid isPermaLink="false">http://psomas.wordpress.com/?p=192</guid>
		<description><![CDATA[Both tricks shown here are related with a change (by Peter Zijlstra) in the kmap_atomic() and kunmap_atomic() macros/functions. LWN has an excellent article about what that change involved. It basically &#8216;dropped&#8217; support for atomic kmap slots, switching to a more general stack-based approach. Now with this change, the number of arguments passed to the kmap_atomic() [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=192&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Both tricks shown here are related with a change (by Peter Zijlstra) in the kmap_atomic() and kunmap_atomic() macros/functions. LWN has an excellent <a href="http://lwn.net/Articles/356378/">article</a> about what that change involved. It basically &#8216;dropped&#8217; support for atomic kmap slots, switching to a more general stack-based approach. </p>
<p>Now with this change, the number of arguments passed to the kmap_atomic() function changed too, and thus you end up with a huge patch covering all the tree, which fixed the issue (changing kmap_atomic(p, KM_TYPE) to kmap_atomic(p)).</p>
<p>But there was another way to go. Some C preprocessor magic.</p>
<pre class="brush: plain; title: ; notranslate">#define kmap_atomic(page, args...) __kmap_atomic(page)</pre>
<p>Yes, the C preprocessor supports <a href="http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html">va_args</a>. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
(which I found out when going through the <a href="https://github.com/nelhage/reptyr">reptyr</a> code, but I&#8217;ll talk about it in an other post.)</p>
<p>Today, I saw a thread at the lkml, which actually did the cleanup I described. Andrew Morton responded:</p>
<blockquote><p>
I&#8217;m OK with cleaning all these up, but I suggest that we leave the back-compatibility macros in place for a while, to make sure that various stragglers get converted. Extra marks will be awarded for working out how to make unconverted code generate a compile warning
</p></blockquote>
<p>And Nick Bowler responded with a very clever way to do this (which involved abusing heavily the C preprocessor <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ):</p>
<pre class="brush: plain; title: ; notranslate">  #include &lt;stdio.h&gt;

  int foo(int x)
  {
     return x;
  }

  /* Deprecated; call foo instead. */
  static inline int __attribute__((deprecated)) foo_unconverted(int x, int unused)
  {
     return foo(x);
  }

  #define PASTE(a, b) a ## b
  #define PASTE2(a, b) PASTE(a, b)
  
  #define NARG_(_9, _8, _7, _6, _5, _4, _3, _2, _1, n, ...) n
  #define NARG(...) NARG_(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)

  #define foo1(...) foo(__VA_ARGS__)
  #define foo2(...) foo_unconverted(__VA_ARGS__)
  #define foo(...) PASTE2(foo, NARG(__VA_ARGS__)(__VA_ARGS__))

  int main(void)
  {
    printf(&quot;%d\n&quot;, foo(42));
    printf(&quot;%d\n&quot;, foo(54, 42));
    return 0;
  }
</pre>
<p>The actual warning is printed due to the deprecated attribute of the foo_unconverted() function.</p>
<p>The fun part, however, is how we get to use the foo &#8216;identifier&#8217;/name to call either foo() or foo_uncoverted() depending on the number of arguments given. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>The trick is to use the __VA_ARGS__ to &#8216;shift&#8217; the numbers 9-0 in the NARG macro, so that when calling the NARG_ macro, _9 will match with the first __VA_ARGS__ argument, _8 with the second etc, and so n will match with actual number of arguments (I&#8217;m not sure I described it very well, but if you try doing it by hand, you&#8217;ll understand how it&#8217;s working).</p>
<p>Now that we have the number of arguments given to foo, we use the PASTE macro to &#8216;concatenate&#8217; the number of the arguments with the function name, and the actual arguments given, and call the appropriate wrapper macro (foo1, foo2 etc).</p>
<p>Another interesting thing, which I didn&#8217;t know, is about <a href="http://gcc.gnu.org/onlinedocs/gcc-4.6.1/cpp/Argument-Prescan.html#Argument-Prescan">argument expansion</a> in macros. For macros that concatenate (##) or stringify (#) the arguments are not expanded beforehand. That&#8217;s why we have to use PASTE2 as a wrapper, to get the NARG() argument/macro fully expanded before concatenating.</p>
<p>Ok, C code can get at times a bit obfuscated, and yes you don&#8217;t have type safety etc etc, but, man, you can be really creative with the C language (and the C preprocessor)!<br />
And the Linux kernel development(/-ers) prove just that. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/psomas.wordpress.com/192/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/psomas.wordpress.com/192/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=192&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://psomas.wordpress.com/2011/08/29/abusing-the-c-preprocessor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/abc7e2b649baa48e52fda25c1bd7a82e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">psomas</media:title>
		</media:content>
	</item>
		<item>
		<title>ARG_MAX and the Linux Kernel</title>
		<link>http://psomas.wordpress.com/2011/07/15/arg_max-and-the-linux-kernel/</link>
		<comments>http://psomas.wordpress.com/2011/07/15/arg_max-and-the-linux-kernel/#comments</comments>
		<pubDate>Fri, 15 Jul 2011 12:56:35 +0000</pubDate>
		<dc:creator>psomas</dc:creator>
				<category><![CDATA[Administration]]></category>
		<category><![CDATA[FOSS]]></category>
		<category><![CDATA[Gentoo Linux]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[OS]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Kernel]]></category>
		<category><![CDATA[libc]]></category>
		<category><![CDATA[limits]]></category>
		<category><![CDATA[xargs]]></category>

		<guid isPermaLink="false">http://psomas.wordpress.com/?p=184</guid>
		<description><![CDATA[For some reason, whenever I open up the Wikipedia, I end up with tons of tabs in my web browser, and usually the tabs are completely unrelated to each other. Yesterday, I ended up looking the xargs Wikipedia article, and there I found an interesting note: Under the Linux kernel before version 2.6.23, arbitrarily long [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=184&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>For some reason, whenever I open up the Wikipedia, I end up with tons of tabs in my web browser, and usually the tabs are completely unrelated to each other. <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>Yesterday, I ended up looking the <a href="http://en.wikipedia.org/wiki/Xargs">xargs Wikipedia article</a>, and there I found an interesting note:</p>
<blockquote><p>Under the Linux kernel before version 2.6.23, arbitrarily long lists of parameters could not be passed to a command,[1] so xargs breaks the list of arguments into sublists small enough to be acceptable.</p></blockquote>
<p>Along with a link to the <a href="http://www.gnu.org/software/coreutils/faq/coreutils-faq.html#Argument-list-too-long">GNU coreutils FAQ</a>. </p>
<p>And from there a link to the <a href="http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=b6a2fea39318e43fee84fa7b0b90d68bed92d2ba">Linux Kernel mainline git repository</a>.</p>
<p>After a bit of googling, I found a very nice <a href="http://www.in-ulm.de/~mascheck/various/argmax/">article</a> describing in great detail the ARG_MAX variable, which defines the maximum length of the arguments passed to execve.</p>
<p>Traditionally Linux used a hardcoded:</p>
<pre class="brush: plain; title: ; notranslate">#define MAX_ARG_PAGES 32</pre>
<p>to limit the total size of the arguments passed to the execve() (including the size of the &#8216;environment&#8217;). That limited the maxlen of the arguments passed to about 128KB (minus the size of the &#8216;environment&#8217;).</p>
<p>(Note: actually, very early Linux kernels did not have support for ARG_MAX and didn&#8217;t use MAX_ARG_PAGES, but back then I was probably 2-3 years old, so it&#8217;s ancient history for me <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> )</p>
<p>With Linux-2.6.33, this hardcoded limit was removed. Actually it was replaced by a more &#8216;flexible&#8217; limit. The maximum length of the arguments can now be as big as the 1/4th of the user-space stack. For example, in my desktop, using ulimit -s I get a stack size of 8192KB, which means 2097152 maxlength for the arguments passed. The same value you can obtain by using getconf. Now, if I increase the soft limit on the stack size, the maxlength allowed will also increase, although with a 8192KB soft limit, the &#8216;ARGS_MAX&#8217; is already big enough. Two new limits where also introduced, one on the maxlength of each argument (equal to PAGE_SIZE * 32), and the total number of arguments, equal to 0x7FFFFFFF, or as big as a signed integer can be.</p>
<p>Linux headers however use the MAX_ARG_STRLEN, I think, as the ARG_MAX limit, which forces libc to #undef it in its own header files. I&#8217;m not sure, since I haven&#8217;t looked into code yet, but at least for Linux, ARG_MAX is not statically defined anymore by libc (ie in a header file), but libc computes its value from the userspace stack size.<br />
(edit: that&#8217;s indeed how it works for &gt;=linux-2.6.33 &#8212; code in sysdeps/unix/sysv/linux/sysconf.c:</p>
<pre class="brush: plain; title: ; notranslate">
    case _SC_ARG_MAX:
  #if __LINUX_KERNEL_VERSION &lt; 0x020617
        /* Determine whether this is a kernel 2.6.23 or later.  Only
           then do we have an argument limit determined by the stack
           size.  */
        if (GLRO(dl_discover_osversion) () &gt;= 0x020617)
  #endif
          {
            /* Use getrlimit to get the stack limit.  */
            struct rlimit rlimit;
            if (__getrlimit (RLIMIT_STACK, &amp;rlimit) == 0)
              return MAX (legacy_ARG_MAX, rlimit.rlim_cur / 4);
          }
  
        return legacy_ARG_MAX;
</pre>
<p>).</p>
<p>And the kernel code that enforces that limit:</p>
<pre class="brush: plain; title: ; notranslate">
               struct rlimit *rlim = current-&gt;signal-&gt;rlim;
               unsigned long size = bprm-&gt;vma-&gt;vm_end - bprm-&gt;vma-&gt;vm_start;

               /*
                * Limit to 1/4-th the stack size for the argv+env strings.
                * This ensures that:
                *  - the remaining binfmt code will not run out of stack space,
                *  - the program will have a reasonable amount of stack left
                *    to work from.
                */
               if (size &gt; rlim[RLIMIT_STACK].rlim_cur / 4) {
                       put_page(page);
                       return NULL;
               }
</pre>
<p>The whole kernel patch is a bit complicated for me to understand, since I don&#8217;t have digged much into kernel mm code, but from what I understand, instead of copying the arguments into pages, and then mapping those pages into the new process address space, it setups a new mm_struct, and populates it with a stack VMA. It then copies the arguments into this VMA (expanding it as needed), and then takes care to &#8216;position&#8217; it correctly into the new process. But since I&#8217;m not very familiar with the Linux Kernel mm API, it&#8217;s very likely that what I said is totally wrong (I really have to read the mm chapters from &#8220;Understanding the Linux Kernel&#8221; <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ).</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/psomas.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/psomas.wordpress.com/184/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=184&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://psomas.wordpress.com/2011/07/15/arg_max-and-the-linux-kernel/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/abc7e2b649baa48e52fda25c1bd7a82e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">psomas</media:title>
		</media:content>
	</item>
		<item>
		<title>ketchup, or how to manage your kernel sources more efficiently</title>
		<link>http://psomas.wordpress.com/2011/07/15/ketchup-or-how-to-manage-your-kernel-sources-more-efficiently/</link>
		<comments>http://psomas.wordpress.com/2011/07/15/ketchup-or-how-to-manage-your-kernel-sources-more-efficiently/#comments</comments>
		<pubDate>Fri, 15 Jul 2011 10:47:11 +0000</pubDate>
		<dc:creator>psomas</dc:creator>
				<category><![CDATA[Gentoo Linux]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Kernel]]></category>
		<category><![CDATA[ketchup]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Script]]></category>
		<category><![CDATA[Sources]]></category>

		<guid isPermaLink="false">http://psomas.wordpress.com/?p=159</guid>
		<description><![CDATA[A couple of months ago I found out about ketchup (credits to Daniel Drake, and his blog). ketchup is an awesome utility/script, written by Matt Mackall in Python, which makes it very easy to manage kernel sources. You can very easily upgrade to a newer kernel version, downgrade to older releases, and even switch between [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=159&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>A couple of months ago I found out about <a href="http://github.com/psomas/ketchup" title="ketchup">ketchup</a> (credits to <a href="http://www.reactivated.net/weblog/archives/2007/04/using-ketchup-to-quickly-install-kernel-sources/" title="dsd">Daniel Drake</a>, and his blog).</p>
<p>ketchup is an awesome utility/script, written by Matt Mackall in Python, which makes it very easy to manage kernel sources. You can very easily upgrade to a newer kernel version, downgrade to older releases, and even switch between different patchsets. The ketchup ebuild I found in Portage (and in every Linux distro I know about) was  fetching the <a href="http://www.selenic.com/ketchup/">original and out-of-date</a> version of ketchup. Steven Rostedt had pulled the original ketchup code (v0.9) into his git repo @ kernel.org. However, there were no commits/updates to ketchup for 1-2 years, I think.</p>
<p>So, I decided to cleanup some of the old trees that ketchup supported, but were no longer maintained, and add support for new trees (or some updated &#8216;versions&#8217; of the old trees). I sent the patches to Steven Rostedt, and he proposed that I take over and maintain ketchup. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I cloned the ketchup git repo to Github, applied the patches I&#8217;d written, plus quite a lot of patches that the Debian ketchup package provided. </p>
<p>Now, with the Linux-3.0 release approaching, I tried to add (at least) partial support for the new 2 digit version numbers, but there are still some issues, which will hopefully get resolved once Linux-3.0 gets released, and the new versioning scheme gets standarized (for example the EXTRAVERSION Makefile variable will probably not get removed from 3.0, as it breaks some userspace utils, like uptime etc from procps utils, some depmod issues etc).</p>
<p>The new code for 3.x kernels is currently in the linux-3 branch, from which I took a snapshot and pushed it to Portage as dev-util/ketchup-1.1_beta. I will hopefully merge it back with master, after the first -stable release comes out (Linux-3.0.1), just to make sure that everything works.</p>
<p>Feel free to give it a try, and report any bugs/issues.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/psomas.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/psomas.wordpress.com/159/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=159&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://psomas.wordpress.com/2011/07/15/ketchup-or-how-to-manage-your-kernel-sources-more-efficiently/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/abc7e2b649baa48e52fda25c1bd7a82e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">psomas</media:title>
		</media:content>
	</item>
		<item>
		<title>Hey!</title>
		<link>http://psomas.wordpress.com/2011/07/09/hey/</link>
		<comments>http://psomas.wordpress.com/2011/07/09/hey/#comments</comments>
		<pubDate>Sat, 09 Jul 2011 13:41:22 +0000</pubDate>
		<dc:creator>psomas</dc:creator>
				<category><![CDATA[Gentoo]]></category>
		<category><![CDATA[Gentoo Linux]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[New Developer]]></category>

		<guid isPermaLink="false">http://psomas.wordpress.com/?p=170</guid>
		<description><![CDATA[I finally became a Gentoo Developer. I&#8217;ll be helping the Gentoo Kernel Project, with bug fixing at first, and help with the maintenance of some of the kernel sources in the tree. Many thanks to mpagano for mentoring me, tampakrap for his help with the quizzes, and of course hwoarang, who had no problem to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=170&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I finally became a Gentoo Developer. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I&#8217;ll be helping the Gentoo Kernel Project, with bug fixing at first, and help with the maintenance of some of the kernel sources in the tree.</p>
<p>Many thanks to mpagano for mentoring me, tampakrap for his help with the quizzes, and of course hwoarang, who had no problem to do all of the review sessions during his vacations. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/psomas.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/psomas.wordpress.com/170/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=170&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://psomas.wordpress.com/2011/07/09/hey/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/abc7e2b649baa48e52fda25c1bd7a82e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">psomas</media:title>
		</media:content>
	</item>
		<item>
		<title>OpenVPN/iproute2/iptables &#8212; Part 2</title>
		<link>http://psomas.wordpress.com/2011/05/07/openvpniproute2iptables-part-2/</link>
		<comments>http://psomas.wordpress.com/2011/05/07/openvpniproute2iptables-part-2/#comments</comments>
		<pubDate>Sat, 07 May 2011 16:20:30 +0000</pubDate>
		<dc:creator>psomas</dc:creator>
				<category><![CDATA[Administration]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[Networking]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Gentoo]]></category>
		<category><![CDATA[Kernel]]></category>
		<category><![CDATA[Netlabel]]></category>

		<guid isPermaLink="false">http://psomas.wordpress.com/?p=151</guid>
		<description><![CDATA[I had blogged about this some time ago. The configuration I described in that post worked fine on my laptop, with Debian installed, but when I tried it on my Desktop, where I use Gentoo, it wouldn&#8217;t work. It took me *3 days* of &#8216;debugging&#8217;, until I was able to find why that happened! I [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=151&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I had <a href="https://psomas.wordpress.com/2010/01/19/openvpniptablesiproute2/">blogged</a> about this some time ago. The configuration I described in that post worked fine on my laptop, with Debian installed, but when I tried it on my Desktop, where I use Gentoo, it wouldn&#8217;t work. </p>
<p>It took me *3 days* of &#8216;debugging&#8217;, until I was able to find why that happened!</p>
<p>I tried various changes to the iptables and iproute2 configuration, giving more hints to both utilities in order to use the correct routing table, mark the packets correctly etc, but it still wouldn&#8217;t work. </p>
<p>After a lot of time tweaking the configuration, without results, I saw that, although ping -Ieth0 ${VPN_SERVER}, didn&#8217;t &#8216;work&#8217; (with openvpn running, and tap0 configured with the correct address/netmask), I could see with tcpdump the &#8216;ECHO REPLY&#8217; packets sent by the VPN server, with correct source and destination addresses. </p>
<p>After stracing the ping command, I saw that when ping issued a recvmsg syscall, recvmsg returned with -EAGAIN. So, now I know that the packets do arrive to the interface with correct addresses, but they couldn&#8217;t &#8216;reach&#8217; the upper network stacks of the kernel. </p>
<p>The problem was that both machines were running vanilla kernels, so I couldn&#8217;t blame any Debian or Gentoo specific patches. But since I knew that the problem was in the kernel, I tried to see if any kernel .config options, regarding NETFILTER, and multiple routing tables didn&#8217;t match between the two configs. But I couldn&#8217;t find anything that could cause that &#8216;bug&#8217;. </p>
<p>So since the kernel sources are the same, and I can&#8217;t find anything in the .configs that could cause the problem, I try tweaking some /proc/sys/net &#8216;files&#8217;, although I couldn&#8217;t see why these would differ between the two machines. And then I saw some /proc/sys/net/ipv4/ files in Gentoo, that didn&#8217;t show up in Debian (/proc/sys/net/ipv4/cipso*). </p>
<p>I googled to find what cipso is, and I finally found out that it was part of the <a href="http://netlabel.sourceforge.net/">NetLabel project</a>. CIPSO (Common IP Security Option) is an IETF draft (it&#8217;s quite old actually) and  is implemented like a &#8216;security module&#8217; in the Linux Kernel, and it was what it caused the problem, probably because it tried to do some verification on the inbound packets, which failed, and therefore the packets were &#8216;silently&#8217; dropped. LWN has an <a href="http://lwn.net/Articles/204905/">article</a> with more infromation about packet labeling and CIPSO, and there&#8217;s also related <a href="http://www.mjmwired.net/kernel/Documentation/netlabel/">Documentation</a> in the Linux Kernel.</p>
<p>make defconfig enbales Netlabel, but Debian&#8217;s default configuration had it disabled, and that&#8217;s why Openvpn/iproute2/iptables configuration worked with Debian, but failed on Gentoo. </p>
<p>Instead of compiling a new kernel, one can just do<br />
<code><br />
echo 0 &gt; /proc/sys/net/ipv4/cipso_rbm_strict_valid<br />
</code><br />
and disable CIPSO verification on inbound packets, so that multiple routing tables and packet marking work as expected.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/psomas.wordpress.com/151/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/psomas.wordpress.com/151/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=151&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://psomas.wordpress.com/2011/05/07/openvpniproute2iptables-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/abc7e2b649baa48e52fda25c1bd7a82e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">psomas</media:title>
		</media:content>
	</item>
		<item>
		<title>Minoan Lines Wifi &#8212; Part 2</title>
		<link>http://psomas.wordpress.com/2011/04/16/minoan-lines-wifi-part-2/</link>
		<comments>http://psomas.wordpress.com/2011/04/16/minoan-lines-wifi-part-2/#comments</comments>
		<pubDate>Sat, 16 Apr 2011 19:59:13 +0000</pubDate>
		<dc:creator>psomas</dc:creator>
				<category><![CDATA[Administration]]></category>
		<category><![CDATA[FOSS]]></category>
		<category><![CDATA[Greek]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[Networking]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Captive Portals]]></category>
		<category><![CDATA[DNS tunneling]]></category>
		<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Wifi]]></category>

		<guid isPermaLink="false">http://psomas.wordpress.com/?p=142</guid>
		<description><![CDATA[A couple of days ago, we did some presentations about DNS at a FOSS NTUA meeting. I prepared a presentation about DNS tunneling and how to bypass Captive Portals at Wifi Hotspots, which require authentication. (We want to do another presentation, to test ICMP/ping tunnel too ). I had blogged on that topic some time [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=142&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>A couple of days ago, we did some presentations about DNS at a <a href="http://foss.ntua.gr">FOSS NTUA</a> meeting. </p>
<p>I prepared a presentation about <a href="http://cc.ece.ntua.gr/~psomas/dnstunnel_presentation.pdf">DNS tunneling</a> and how to bypass <a href="http://en.wikipedia.org/wiki/Captive_portal">Captive Portals</a> at  Wifi Hotspots, which require authentication.<br />
(We want to do another presentation, to test ICMP/ping tunnel too <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ).</p>
<p>I had <a href="https://psomas.wordpress.com/2010/09/12/greeks-only-p-minoan-lines-wifi/">blogged</a> on that topic some time ago.<br />
It was about time for a test-drive. <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>I set up <a href="http://code.kryo.se/iodine/">iodine</a>, a DNS tunneling server(and client), and I was ready to test it, since I would be travelling with Minoan Lines the next day.</p>
<p>I first did some tests from my home 24Mbps ADSL connection, and the results weren&#8217;t very encouraging. Although the tunnel did work, and I could route all of my traffic through the DNS tunnel, and over a second OpenVPN secure tunnel, bandwidth dropped to ~30Kbps, when using the <a href="http://ftp.ntua.gr">NTUA FTP Server</a>, through the DNS tunnel.<br />
(The tunnel also worked with the NTUA Wifi Captive Portal, although at first we had some &#8216;technical issues&#8217;, ie I hadn&#8217;t set up NAT on the server to masquarade and forward the traffic coming from the tunnel <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ).</p>
<p>The problem is that the bandwidth of the Minoan Lines(actually Forthnet &#8216;runs&#8217; it afaik) Wifi(not inside the &#8216;local&#8217; network of course) was ~30Kbps(terrible, I know), without using DNS tunneling. So, I wasn&#8217;t very optimistic. (I think they have some satelite connection, or something like that from the Wifi to the Internet).</p>
<p>When I was on the ship, I tried to test it. At first, I encountered another technical issue(the local DNS had an IP inside the Wifi local network, and due to NAT the IP our server was &#8216;seeing&#8217;, was different than the IP of the DNS packets, so we had to run iodined with the -c flag). Luckily, FOSS NTUA members(who had root access on the computer running iodined) are 1337 and fixed that in no time. <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>And at last, I had a &#8216;working&#8217; DNS tunnel, but with extremely high ping times(2sec RTT) to the other end of the tunnel, and when I tried to route all traffic through the tunnel I had a ridiculous 22sec RTT to ntua.gr. Of course even browsing the Web was impossible, since all the HTTP requests timed out before an answer could reach my laptop. <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>However, because I am a Forthnet customer(for my ADSL connection), I was able to use my Username/Password of my home ADSL connection, and have free access to the Internet, from their hotspot(with the amaing bandwidth of ~30Kbps <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ). At least they do the authentication over SSL. <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' />  </p>
<p>Although DNS tunneling didn&#8217;t really work in this case(the tunnel itself worked, but due to the bandwidth being so low, I didn&#8217;t have a &#8216;usable&#8217; connection to the Internet), I think that in other hotspots, which provide better bandwidth/connection, it can be a very effective way to bypass the authentication and use them for free. <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Probably, there&#8217;ll be a Part 3, with results from bandwidth benchmarks inside the NTUA Wifi, and maybe some ICMP tunneling stuff.</p>
<p> Cheers! <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/psomas.wordpress.com/142/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/psomas.wordpress.com/142/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=142&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://psomas.wordpress.com/2011/04/16/minoan-lines-wifi-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/abc7e2b649baa48e52fda25c1bd7a82e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">psomas</media:title>
		</media:content>
	</item>
		<item>
		<title>linux + x86 segmentation + APM!</title>
		<link>http://psomas.wordpress.com/2011/04/09/linux-x86-segmentation-apm/</link>
		<comments>http://psomas.wordpress.com/2011/04/09/linux-x86-segmentation-apm/#comments</comments>
		<pubDate>Sat, 09 Apr 2011 16:10:41 +0000</pubDate>
		<dc:creator>psomas</dc:creator>
				<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[OS]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[APM]]></category>
		<category><![CDATA[inline assembly]]></category>
		<category><![CDATA[Linux Kernel]]></category>
		<category><![CDATA[segmentation]]></category>

		<guid isPermaLink="false">http://psomas.wordpress.com/?p=132</guid>
		<description><![CDATA[Thanks to the &#8220;Understanding the Linux Kernel&#8221; I spent several hours trying to understand the APM code used to &#8216;call&#8217; the APM Protected Mode 32-bit Interface Connect. Of course APM is deprecated since ages I think, but I was curious. As the APM 1.2 specification states: The APM BIOS 32-bit protected mode interface requires 3 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=132&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Thanks to the &#8220;Understanding the Linux Kernel&#8221; I spent several hours trying to understand the <a href="http://en.wikipedia.org/wiki/Advanced_power_management">APM</a> code used to &#8216;call&#8217; the APM Protected Mode 32-bit Interface Connect.<br />
Of course APM is deprecated since ages I think, but I was curious. <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>As the APM 1.2 specification states:</p>
<blockquote><p>The APM BIOS 32-bit protected mode interface requires 3 consecutive<br />
selector/segment descriptors for use as 32-bit code, 16-bit code, and data segments,<br />
respectively. Both 32-bit and 16-bit code segment descriptors are necessary so the<br />
APM BIOS 32-bit interface can call other BIOS routines in a 16-bit code segment if<br />
necessary. The caller must initialize these descriptors using the segment base and<br />
length information returned from this call to the APM BIOS. These selectors may<br />
either be in the GDT or LDT, but must be valid when the APM BIOS is called in<br />
protected mode.</p></blockquote>
<p>So, at boot time, Linux will query the BIOS/APM for information about the base and length of the segments that APM code uses(query_apm_bios()):</p>
<pre class="brush: plain; title: ; notranslate">
        /* 32-bit connect */
	ireg.al = 0x03;
	intcall(0x15, &amp;ireg, &amp;oreg);

	boot_params.apm_bios_info.cseg        = oreg.ax;
	boot_params.apm_bios_info.offset      = oreg.ebx;
	boot_params.apm_bios_info.cseg_16     = oreg.cx;
	boot_params.apm_bios_info.dseg        = oreg.dx;
	boot_params.apm_bios_info.cseg_len    = oreg.si;
	boot_params.apm_bios_info.cseg_16_len = oreg.hsi;
	boot_params.apm_bios_info.dseg_len    = oreg.di;
</pre>
<p>These are the values that Linux will use to set-up the appropriate segments in the Global Descriptor Table(GDT).</p>
<pre class="brush: plain; title: ; notranslate">
	/*
	 * Set up the long jump entry point to the APM BIOS, which is called
	 * from inline assembly.
	 */
	apm_bios_entry.offset = apm_info.bios.offset;
	apm_bios_entry.segment = APM_CS;
	/*
	 * The APM 1.1 BIOS is supposed to provide limit information that it
	 * recognizes.  Many machines do this correctly, but many others do
	 * not restrict themselves to their claimed limit.  When this happens,
	 * they will cause a segmentation violation in the kernel at boot time.
	 * Most BIOS's, however, will respect a 64k limit, so we use that.
	 *
	 * Note we only set APM segments on CPU zero, since we pin the APM
	 * code to that CPU.
	 */
	gdt = get_cpu_gdt_table(0);
	set_desc_base(&amp;gdt[APM_CS &gt;&gt; 3],
		 (unsigned long)__va((unsigned long)apm_info.bios.cseg &lt;&lt; 4));
	set_desc_base(&amp;gdt[APM_CS_16 &gt;&gt; 3],
		 (unsigned long)__va((unsigned long)apm_info.bios.cseg_16 &lt;&lt; 4));
	set_desc_base(&amp;gdt[APM_DS &gt;&gt; 3],
		 (unsigned long)__va((unsigned long)apm_info.bios.dseg &lt;&lt; 4));
</pre>
<p>So, now the APM segments(their descriptors) are ready to use.</p>
<p>The code used to make an APM BIOS call looks like this:</p>
<pre class="brush: plain; title: ; notranslate">
static inline void apm_bios_call_asm(u32 func, u32 ebx_in, u32 ecx_in,
					u32 *eax, u32 *ebx, u32 *ecx,
					u32 *edx, u32 *esi)
{
	/*
	 * N.B. We do NOT need a cld after the BIOS call
	 * because we always save and restore the flags.
	 */
	__asm__ __volatile__(APM_DO_ZERO_SEGS
		&quot;pushl %%edi\n\t&quot;
		&quot;pushl %%ebp\n\t&quot;
		&quot;lcall *%%cs:apm_bios_entry\n\t&quot;
		&quot;setc %%al\n\t&quot;
		&quot;popl %%ebp\n\t&quot;
		&quot;popl %%edi\n\t&quot;
		APM_DO_POP_SEGS
		: &quot;=a&quot; (*eax), &quot;=b&quot; (*ebx), &quot;=c&quot; (*ecx), &quot;=d&quot; (*edx),
		  &quot;=S&quot; (*esi)
		: &quot;a&quot; (func), &quot;b&quot; (ebx_in), &quot;c&quot; (ecx_in)
		: &quot;memory&quot;, &quot;cc&quot;);
}
</pre>
<p>It took me a while to figure out the long jump.</p>
<pre class="brush: plain; title: ; notranslate">
lcall *%%cs:apm_bios_entry
</pre>
<p>because apm_bios_entry is defined as:</p>
<pre class="brush: plain; title: ; notranslate">
static struct {
        unsigned long   offset;
        unsigned short  segment;
} apm_bios_entry;
</pre>
<p>At first I though that the struct should be defined the other way around(first the segment and then the offset).<br />
I experimented a bit with inline asm, and after lots of segmentation faults, and some time going over Intel x86 manuals about the ljmp instruction, I figured it out.</p>
<p>Well, I think it took much much longer than it should to understand was going on. :S</p>
<p>The ljmp expects a mem16:mem32 operand, where mem16 is the segment, and mem32 the offset.<br />
And that&#8217;s exactly how the struct apm_bios_entry is stored in memory.<br />
However, as I &#8216;read&#8217; mem16:mem32, I thought that mem16 should be stored before mem32. :S</p>
<p>And thus I lost several hours writing and experimenting with segfaulting C code. <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /><br />
For something pretty obvious&#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/psomas.wordpress.com/132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/psomas.wordpress.com/132/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=132&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://psomas.wordpress.com/2011/04/09/linux-x86-segmentation-apm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/abc7e2b649baa48e52fda25c1bd7a82e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">psomas</media:title>
		</media:content>
	</item>
		<item>
		<title>my first kernel patch!</title>
		<link>http://psomas.wordpress.com/2011/03/11/my-first-kernel-patch/</link>
		<comments>http://psomas.wordpress.com/2011/03/11/my-first-kernel-patch/#comments</comments>
		<pubDate>Fri, 11 Mar 2011 18:19:38 +0000</pubDate>
		<dc:creator>psomas</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[OS]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[asm]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Kernel]]></category>
		<category><![CDATA[Patch]]></category>

		<guid isPermaLink="false">http://psomas.wordpress.com/?p=131</guid>
		<description><![CDATA[Here it is! Well, the patch itself isn&#8217;t a big deal, since I didn&#8217;t write any code. It was a cleanup of asm-offsets. Afaik, Linux has quite a lot of assembly code, which needs the offsets of various struct members. Of course, assembly code(or even toplevel inline assembly) cannot use the offsetof marco. That&#8217;s also [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=131&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://git.kernel.org/?p=linux/kernel/git/x86/linux-2.6-tip.git;a=commitdiff;h=7bf04be8f48ceeeffa5b5a79734d6d6e0d59e5f8">Here</a> it is! <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>Well, the patch itself isn&#8217;t a big deal, since I didn&#8217;t write any code. It was a cleanup of asm-offsets. </p>
<p>Afaik, Linux has quite a lot of assembly code, which needs the offsets of various struct members. Of course, assembly code(or even toplevel inline assembly) cannot use the <a href="https://psomas.wordpress.com/2009/07/01/weird-kernel-macros-container_of/">offsetof</a> marco. That&#8217;s also the case for some C constants, eg:</p>
<pre class="brush: plain; title: ; notranslate">
#define PAGE_SIZE (1UL &lt;&lt; PAGE_SHIFT)) 
</pre>
<p>Thus, these offsets and constants are &#8216;calcualted&#8217; at build time as &#8216;absolute values&#8217; so that gas will be ok. <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /><br />
Using the macros defined in incldue/linux/kbuild.h</p>
<pre class="brush: plain; title: ; notranslate">
#define DEFINE(sym, val) \
        asm volatile(&quot;\n-&gt;&quot; #sym &quot; %0 &quot; #val : : &quot;i&quot; (val))

#define BLANK() asm volatile(&quot;\n-&gt;&quot; : : )

#define OFFSET(sym, str, mem) \
	DEFINE(sym, offsetof(struct str, mem))

#define COMMENT(x) \
	asm volatile(&quot;\n-&gt;#&quot; x)
</pre>
<p>the asm-offsets.c is used to create a &#8216;special&#8217; asm fle, which is then parsed by the kernel build system, in order to create the include/generated/asm-offsets.h file.</p>
<p>However, a patch introduced two new macros in include/linux/const.h</p>
<pre class="brush: plain; title: ; notranslate">
#ifdef __ASSEMBLY__
#define _AC(X,Y)	X
#define _AT(T,X)	X
#else
#define __AC(X,Y)	(X##Y)
#define _AC(X,Y)	__AC(X,Y)
#define _AT(T,X)	((T)(X))
#endif
</pre>
<p>so that some constants defined in C work with gas too.</p>
<p>And now, the PAGE_SIZE is defined as</p>
<pre class="brush: plain; title: ; notranslate">
#define PAGE_SIZE       (_AC(1,UL) &lt;&lt; PAGE_SHIFT
</pre>
<p>and thus, the PAGE_SIZE_asm defined in x86/asm-offsets.c, and used in some places in x86 code was no longer needed(that&#8217;s also the case with PAGE_SHIFT and THREAD_SIZE). </p>
<p>So, I deleted PAGE_SIZE_asm/PAGE_SHIFT_asm/THREAD_SIZE_asm from x86/kernel/asm-offsets.c, and replaced them with their non-asm counterparts, in the code that used them.</p>
<p>I posted it to lkml(after some hours experimenting with git format-patch and git send-email <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ), and it got accepted. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/psomas.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/psomas.wordpress.com/131/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=psomas.wordpress.com&#038;blog=8328509&#038;post=131&#038;subd=psomas&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://psomas.wordpress.com/2011/03/11/my-first-kernel-patch/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/abc7e2b649baa48e52fda25c1bd7a82e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">psomas</media:title>
		</media:content>
	</item>
	</channel>
</rss>
