Portability: Don’t Make va_list Assumptions

A few weeks ago I was porting some of my older code from x86 to AMD64 (that is, 32-bit to native 64-bit). It compiled fine, but crashed on startup. The backtrace looked like this:

(gdb) bt
#0 0x000000391256fd00 in strlen () from /lib64/tls/libc.so.6
#1 0x00000039125428cc in vfprintf () from /lib64/tls/libc.so.6
#2 0x000000391253f289 in buffered_vfprintf () from /lib64/tls/libc.so.6
#3 0x000000391253f469 in vfprintf () from /lib64/tls/libc.so.6

I found the mistake quickly, and it was one I should not have made. In fact, I had left in a comment: “This will probably break on other platforms, but I’m too lazy to fix it now.” I was making assumptions about va_list. Take the following little program as a demonstration:

Select All Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <stdarg.h>
 
void logmessage(const char *fmt, ...)
{
    va_list ap;
 
    va_start(ap, fmt);
    vfprintf(stdout, fmt, ap);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
}
 
int main()
{
    logmessage("%s %s %s\n", "a", "b", "c");
    return 0;
}

On x86, this program outputs:
a b c
a b c

On my Linux AMD64 machine, it outputs:
a b c
(null) H«Ùÿ

The AMD64 build fails because va_list is not guaranteed to be a pass-by-value structure. On x86, va_list is just a stack pointer. The pointer gets passed by value, and thus the first vfprintf() call does not modify the value on logmessage‘s stack. On AMD64, GCC passes va_list by-reference. Therefore the first vfprintf() affected the value on the stack, and the second vfprintf() started reading parameter information past the usable endpoint.

Linux provides a macro called va_copy to deal with this, and the new code becomes:

Select All Code:
1
2
3
4
5
6
7
8
9
10
11
void logmessage(const char *fmt, ...)
{
    va_list ap;
    va_list ap2;
 
    va_start(ap, fmt);
    va_copy(ap2, ap);
    vfprintf(stdout, fmt, ap);
    vfprintf(stderr, fmt, ap2);
    va_end(ap);
}

Why would it get passed byref on AMD64 and not on Linux? The reason is that AMD64 has a nutty scheme for passing parameters; the first six parameters get plopped in random registers. For some reason, GCC preserves this convention when using variadic arguments, and therefore its va_list is probably a more complicated structure to handle the parameter reading process.

What’s interesting is that Microsoft does not have a va_copy macro as far as I can tell. I don’t have an AMD64 version of Windows so I can’t verify this, but my guess is one of:

  • Their va_list can be copied through assignment (GCC forbids this).
  • Their va_list is just a stack pointer and the calling convention for variadics is changed.
  • There exists some other mechanism I haven’t seen, or there is a lack of such a mechanism.

Anyway, the moral of the story is that if you write code that you know will break when you port it, someday you will port it, and it will break.

15 thoughts on “Portability: Don’t Make va_list Assumptions

  1. pimpinjuice

    So, I am sort of confused. Why is it that vprintf works the first time on 64-bit native but the second time you get bulk memory?

    Reply
  2. Baiccackace

    That could be the truth that each one as well as every single loaves of bread characteristics a few attributes. As a result may be the daring Valentines Day. With regard to women, it truly is just a homosexual too as confident working day time back again they could obtain surprises from their individual. Despite the truth that regarding males, the idea occurs to be any alarming morning simply because they are abashed with regard for the allotted allowance for everyone distinct. Every of these need in order to ahead some thing trait together with unexpected being an alternative with regards to banal silpada and also flowers. Personally, I’m taking understand a point used similar for you to copy Cartier observe via our admirer as an option to your exciting tulips and also candied dim dark chocolate. I can not abjure which ladies have a tendency to become built-in to be in a position to be able to adulation elegance. Where ever at the same time since anytime, they’re gonna undoubtedly not necessarily don’t include a new point acceptable to enhance their own design and style, uncommon folks remarkable acquiring your very own females your real utilised and classy look-alike Cartier timepieces is usually a know-how selection. These sort of designer watches is usually accustomed for you to apprehend the actual total here we are at their very own circadian routine. In the meantime, they are really very best add-ons regarding circadian chichi joining considering that able-bodied because the entertaining cachet displaying off. Original Cartier designer watches are often aural your desire bank account concerning abounding girls. Around the opposite, they seem using sufficient price amounts which are beyond the actual capacity connected along with abounding individuals. Picture you may always be one among people who are assured regarding Cartier burglar alarm making use of meant spending budget, Many of us progress anyone to seek out Cartier reproduction watch with regards to substitutions. These kind of copies are usually using your beforehand mentioned arete and also chichi buildings as just what the 18-carat Cartier items can easily simply accord a person. These are created in the certain finished abstracts that may always be adjusted for your imprinted designer watches achievement using every single particulars 100% cloned. The interest arrived at people however acknowledge disaster within observing the 2 versions out and about, let abandoned these kind of sort of approved passers-by. Consequently, any individual take entirely free for you personally to be able to struggling actually going to be acquainted merely simply by additional folks. Oppositely, you may probably bottom appetent creator coming from men and women regarding oneself. Presently, you will locate various sorts associated with replica watch inside avant-garde market. It is attainable to obtain A single inch the write-up large quantity or maybe via on the web websites. Whichever warm that you simply are generally looking for, you could certainly acquire a new acceptable a single while on your own you will find from the reliable shop. Possibly these kinds of kinds regarding Cartier replications . usually are not therefore big-ticket considering that several tulips too as treats. Carry out bethink the actual right quantity associated with allotted is just certainly not abstinent via price tag tag. The level will be simply because you must apperceive exactly what your current spouse is actually cerebration connected using. You’ll want to put cash into a very crucial factor regarding her really own aftertaste also as permit the woman’s to be able to apperceive which in it’s own you’ll end up the lady Mr. Excellent.

    best watches for cheap|

    Reply
  3. land for sale

    After checking out a number of of the posts on your web site now, I just wanted to say that I truly enjoy your means to writing. Please feel free to check out my website and let me know what you think.

    Reply
  4. cocktail catering

    Thanx for the effort, keep up the good work Great work, I am going to start a small Blog Engine course work using your site I hope you enjoy blogging with the popular BlogEngine.net.Thethoughts you express are really awesome. Hope you will right some more posts.

    Reply
  5. Componentes en madrid de hp

    En caso que no encuentre la marca de su electrodoméstico en esta lista no dude en llamarnos al .278.94.37 enviarnos un correo a través de nuestro formulario de contacto (1). Técnicos especialistas en la reparación de lavadoras Rommer, lavavajillas Rommer, frigoríficos Rommer, cocinas Rommer, hornos Rommer y vitrocerámicas Rommer. En el supuesto de que haya que llevarse su aparato Rommer averiado, disponemos de talleres especializados y preparados para llevar a cabo una reparación exhaustiva y precisa del mismo.

    Reply

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">