Skip to contentSkip to conversation

Errors compiling QEMU with Mingw

Qemu-devel Vladimir N. Oleynik 6 participants 16 messages Jun 19, 2004 – Jun 24, 2004 1 message not in the archive

lore
Share & tools
lore

A message that is not in the archive (sent off-list or not yet received): [email protected]

#1 lore raw

Filip,

Review

Quoted 10 lines

Hi! I sent a patch for this few days ago. It's attached...

+#ifndef _WIN32
extern FILE *stdout;

(quoted diff) +6 -0
+#else
+struct FILE { int opaque; };
+extern FILE (*_imp___iob)[];
+#define _iob	(*_imp___iob)
+#define stdout	(&_iob[1])
+#endif

But in fact this very dirty correction.
May be
#include <stdio.h>
is more true.

--w
vodz

#2 lore raw

Re: [Qemu-devel] [PATCH] security_20040618

In reply to a message not in the archive

Tim,

monitor.c

Quoted 8 lines

Updates to this, from the previous version two days ago, include additional strcpy replacements,

monitor.c +1 -1
                 str = qemu_malloc(strlen(buf) + 1);
-                strcpy(str, buf);
+                pstrcpy(str, strlen(buf) + 1,  buf);

In my opinion, it already absolutely unnecessary correction. There is in this place no problem.

--w
vodz

#3 lore raw

Re: [Qemu-devel] [PATCH] security_20040618

Quoted 8 lines

monitor.c

Quoted 5 lines
monitor.c +1 -1
                 str = qemu_malloc(strlen(buf) + 1);
-                strcpy(str, buf);
+                pstrcpy(str, strlen(buf) + 1,  buf);

In my opinion, it already absolutely unnecessary correction. There is in this place no problem.

Yeah, you are probably right. I looked at that one on 3 seperate occasions before making the change, since I recognized that there are very few conditions where it could possibly be a problem, and come to think of it, this fix doesn't mitigate those conditions.

That chunk of code makes me uncomfortable for other reasons though (does qemu_malloc() return NULL ever? could buf possibly be missing a trailing '\0' ever?) so I'll re-visit it again and see what makes the most sense. The pstrcpy isn't hurting anything though. Slightly slower copy, due to the length checking, but it isn't in a critical piece of code (monitor.c is just for the user interface command prompt, right?), so I also don't see a reason to remove it, esp if changes in the future open up the possibility of an overflow.

thanks for the comment,
tim

#4 lore raw

[Qemu-devel] Re: [PATCH] security_20040618

"Tim" <[email protected]> wrote in message news:[email protected]...

Quoted 14 lines
Quoted 8 lines

monitor.c 2004-06-17 22:12:49.000000000 -0700

Quoted 5 lines
monitor.c 2004-06-17 22:12:49.000000000 -0700 renamed from monitor.c 2004-06-16 20:49:59.000000000 -0700 +1 -1
                 str = qemu_malloc(strlen(buf) + 1);
-                strcpy(str, buf);
+                pstrcpy(str, strlen(buf) + 1,  buf);

In my opinion, it already absolutely unnecessary correction. There is in this place no problem.

Yeah, you are probably right. I looked at that one on 3 seperate occasions before making the change, since I recognized that there are very few conditions where it could possibly be a problem, and come to think of it, this fix doesn't mitigate those conditions.

Quoted 8 lines

That chunk of code makes me uncomfortable for other reasons though (does qemu_malloc() return NULL ever? could buf possibly be missing a trailing '\0' ever?) so I'll re-visit it again and see what makes the most sense. The pstrcpy isn't hurting anything though. Slightly slower copy, due to the length checking, but it isn't in a critical piece of code (monitor.c is just for the user interface command prompt, right?), so I also don't see a reason to remove it, esp if changes in the future open up the possibility of an overflow.

No, he is ABSOLUTELY right ! This patch is useless and confusing. pstrcpy's second argument is the size of the buffer the first argument points to, computing it a second time is error prone as it duplicates qemu_malloc size argument calculation. Many modifications down the road, these two lines may become sufficiently distant that a modification to one will not be reflected in the other. Furthermore, it is completely innane to require protection from buffer overflow in pstrcpy by passing the exact size of the third argument ! It reminds me of an overtly cautious programmer I met a few years ago who made sure 'strings were properly null terminated by adding : str[strlen(str)] = '\0'; what a joke!

Thus I see no reason to ACCEPT such a patch, removing it a just a matter of cleanliness.

Still there was a more constructive remark to make on the above code as it would definitely be better written as

str = qemu_strdup(buf);

with obvious semantics for qemu_strdup.

Anyone to write such a patch and use qemu_strdup in other places as appropriate ?

Charlie Gordon.

PS: I fully agree with Fabrice about strncpy, disbelievers should read man strncpy carefully and learn.

#5 lore raw

Re: [Qemu-devel] Re: [PATCH] security_20040618

Quoted 35 lines
Quoted 5 lines

Yeah, you are probably right. I looked at that one on 3 seperate occasions before making the change, since I recognized that there are very few conditions where it could possibly be a problem, and come to think of it, this fix doesn't mitigate those conditions.

Quoted 8 lines

That chunk of code makes me uncomfortable for other reasons though (does qemu_malloc() return NULL ever? could buf possibly be missing a trailing '\0' ever?) so I'll re-visit it again and see what makes the most sense. The pstrcpy isn't hurting anything though. Slightly slower copy, due to the length checking, but it isn't in a critical piece of code (monitor.c is just for the user interface command prompt, right?), so I also don't see a reason to remove it, esp if changes in the future open up the possibility of an overflow.

No, he is ABSOLUTELY right ! This patch is useless and confusing. pstrcpy's second argument is the size of the buffer the first argument points to, computing it a second time is error prone as it duplicates qemu_malloc size argument calculation. Many modifications down the road, these two lines may become sufficiently distant that a modification to one will not be reflected in the other. Furthermore, it is completely innane to require protection from buffer overflow in pstrcpy by passing the exact size of the third argument ! It reminds me of an overtly cautious programmer I met a few years ago who made sure 'strings were properly null terminated by adding : str[strlen(str)] = '\0'; what a joke!

Thus I see no reason to ACCEPT such a patch, removing it a just a matter of cleanliness.

Still there was a more constructive remark to make on the above code as it would definitely be better written as

str = qemu_strdup(buf);

with obvious semantics for qemu_strdup.

Quoted 7 lines

Anyone to write such a patch and use qemu_strdup in other places as appropriate ?

Charlie Gordon.

PS: I fully agree with Fabrice about strncpy, disbelievers should read man strncpy carefully and learn.

Based on comments received thus far, including yours, I am reviewing that section of code (as I mentioned above), and will be releasing a new revision of the patch in a day or two. I admit, I am not a perfect programmer. I am merely trying to help out by fixing the tiny problems that are often missed by programmers that have more important things to worry about. I appreciate it when people show me where I am wrong, but could you please keep your criticism a bit more constructive?

thanks,
tim

#6 lore raw

[Qemu-devel] Re: Re: [PATCH] security_20040618

Quoted 7 lines

Based on comments received thus far, including yours, I am reviewing that section of code (as I mentioned above), and will be releasing a new revision of the patch in a day or two. I admit, I am not a perfect programmer. I am merely trying to help out by fixing the tiny problems that are often missed by programmers that have more important things to worry about. I appreciate it when people show me where I am wrong, but could you please keep your criticism a bit more constructive?

Sorry if I sounded a bit harsh, I'm sure every contribution is appreciated, and your submitting patches is more helpful than my criticizing them...

I merely wanted to emphasize how broken strncpy is and how much more useful pstrcpy is.

My suggestion on qemu_strdup is imho constructive :-) and about the only reason this is not completely off topic ;-)

But as far as strnpy is concerned, I *want* to be destructive : this C library function is a mess, it doesn't do what most C programmers believe. It causes bugs, or blatant inefficiencies due to the inept null padding on large buffers.
It is so unlikely that the precise behaviour of that horrible thing be what is needed in any C program...
There are quite a few problems around uses of this function even in gnu software or the linux kernel.

There are other candidates for libc functions every programmer should reject disgruntedly : sprintf, gets, strtok, mktemp, tmpnam,
tempnam... or any of the C library functions duly tagged in the man pages as never to be used
Similarly, extreme care is needed in do/while loops...

Charlie the C teaser.
---------------------
one of my favorite Q/As : what is wrong with : enum BOOL { FALSE=0, TRUE=1 }; ?

#7 lore raw

Re: [Qemu-devel] Re: Re: [PATCH] security_20040618

Quoted 10 lines
Quoted 7 lines

Based on comments received thus far, including yours, I am reviewing that section of code (as I mentioned above), and will be releasing a new revision of the patch in a day or two. I admit, I am not a perfect programmer. I am merely trying to help out by fixing the tiny problems that are often missed by programmers that have more important things to worry about. I appreciate it when people show me where I am wrong, but could you please keep your criticism a bit more constructive?

Sorry if I sounded a bit harsh, I'm sure every contribution is appreciated, and your submitting patches is more helpful than my criticizing them...

That's ok, I was just taken aback a bit.

Quoted 6 lines

I merely wanted to emphasize how broken strncpy is and how much more useful pstrcpy is.

My suggestion on qemu_strdup is imho constructive :-) and about the only reason this is not completely off topic ;-)

Quoted 8 lines

But as far as strnpy is concerned, I *want* to be destructive : this C library function is a mess, it doesn't do what most C programmers believe. It causes bugs, or blatant inefficiencies due to the inept null padding on large buffers.
It is so unlikely that the precise behaviour of that horrible thing be what is needed in any C program...
There are quite a few problems around uses of this function even in gnu software or the linux kernel.

Yes, since Fabrice pointed out the differences between my version of pstrcpy() and his, I have come to appreciate pstrcpy()'s correctness and speed. I see what you mean by the problems with strncpy(), and I'll make an effort to eliminate it with the same prejudice I have tried to eliminate most strcpy() and sprintf() calls.

Quoted 5 lines

There are other candidates for libc functions every programmer should reject disgruntedly : sprintf, gets, strtok, mktemp, tmpnam,
tempnam... or any of the C library functions duly tagged in the man pages as never to be used
Similarly, extreme care is needed in do/while loops...

Agreed. In this day and age, there's really no excuse to use unsafe functions such as these. That's why I attempt to eliminate them with my patch even though there may be no immediately obvious overflow issue.

Thanks for the additional comments & information.

cheers,
tim

#8 lore raw

OT: C Q/As, was Re: [Qemu-devel] security_20040618

In reply to Charlie Gordon
Quoted 4 lines · Charlie Gordon

Charlie the C teaser.
---------------------
one of my favorite Q/As : what is wrong with : enum BOOL { FALSE=0, TRUE=1 }; ?

can you enlighten me? The only drawback I see is that with plain C (no C++) typedef enum { ... } BOOL; would be more appropriate.

I would propose
#ifndef __cplusplus
typedef enum { false, true } bool;
#endif
as the optimal solution for a problem I hardly have (since I usually don't go back to coding in C)

Christof

PS: I used to ask: Why does this crash later (if you are lucky)

const char *itoa(int i)
{ char x[20];
snprintf(x,sizeof x,"%d",i);
return x;
}

#9 lore raw

[Qemu-devel] OT: C Q/As, was Re: security_20040618

Quoted 6 lines
Quoted 2 lines

one of my favorite Q/As : what is wrong with : enum BOOL { FALSE=0, TRUE=1 }; ?

can you enlighten me? The only drawback I see is that with plain C (no C++) typedef enum { ... } BOOL; would be more appropriate.

defensive programming would require that TRUE be also defined as

#define TRUE 1

as many unsuspecting programmers will expect TRUE and FALSE to be handled in the preprocessor phase eg:

#if TRUE
    ...
    somecode();
    ...

#endif

if TRUE is defined solely as en enum value, it will expand to 0 inside preprocessing directive expressions without warning : quite a headache to debug this type of mistake !

Quoted 7 lines

PS: I used to ask: Why does this crash later (if you are lucky)

const char *itoa(int i)

{  char x[20];
    snprintf(x,sizeof x,"%d",i);
    return x;
}

This code will abviously fail, unless you are very lucky and use the returned value right away, as the x buffer is in automatic stack space and will be overwritten by subsequent function calls or possibly signal handlers.

I can think of 4 ways it may crash later when the pointer is dereferenced :
- you are using an advanced C compiler/runtime that checks pointer validity (such as valgrind, checker, tinycc...)
- after the end of the thread that called itoa.
- if pages in the stack are unmapped for another reason like the stack being swapped out and having shrunk below the depth it had when itoa was called (quite unlikely).
- if the stack contains no zero byte till the end of its mapped space (you would have to be so lucky for this!)

Anything more casual ?

Charlie, the C teaser.

#10 lore raw

Re: [Qemu-devel] OT: C Q/As, was Re: security_20040618

Quoted 18 lines · Charlie Gordon
Quoted 6 lines
Quoted 2 lines

one of my favorite Q/As : what is wrong with : enum BOOL { FALSE=0, TRUE=1 }; ?

can you enlighten me? The only drawback I see is that with plain C (no C++) typedef enum { ... } BOOL; would be more appropriate.

defensive programming would require that TRUE be also defined as

#define TRUE 1

as many unsuspecting programmers will expect TRUE and FALSE to be handled in the preprocessor phase eg:

#if TRUE
    ...
    somecode();
    ...
Quoted 5 lines

#endif

if TRUE is defined solely as en enum value, it will expand to 0 inside preprocessing directive expressions without warning : quite a headache to debug this type of mistake !

Thank you, I did not think of #if as a target for TRUE. That explains the numerous defines in gtk+ (instead of using enums).

Do you know what happens if you use '#define XYZ TRUE \n #if XYZ == TRUE' [If I read your answer correctly both == TRUE and == FALSE would be true :-( ]

Quoted 7 lines
Quoted 7 lines

PS: I used to ask: Why does this crash later (if you are lucky)

const char *itoa(int i)

{  char x[20];
   snprintf(x,sizeof x,"%d",i);
   return x;
}

Oh I did not expect you to answer the obvious (to me). I just wanted to share my old would-be-employee test.

Quoted 8 lines

This code will abviously fail, unless you are very lucky and use the returned value right away, as the x buffer is in automatic stack space and will be overwritten by subsequent function calls or possibly signal handlers.

I can think of 4 ways it may crash later when the pointer is dereferenced :
- you are using an advanced C compiler/runtime that checks pointer validity (such as valgrind, checker, tinycc...)

can valgrind really check it if you dereference the pointer in a subroutine deeply enough to reuse the memory again?

Quoted 8 lines

- after the end of the thread that called itoa.
- if pages in the stack are unmapped for another reason like the stack being swapped out and having shrunk below the depth it had when itoa was called (quite unlikely).
- if the stack contains no zero byte till the end of its mapped space (you would have to be so lucky for this!)

Anything more casual ?

that's more than I ever expected ;-) You are right, crashing is far more unlikely than giving strange characters. If you rely on the length or content of the string returned, that might easily lead to a crash (if you make other mistakes).

actually knowing that a static will fix the bug (but introduce new problems) should be enough for most C programmers.

Christof

#11 lore raw

Re: OT: C Q/As, was Re: [Qemu-devel] security_20040618

In reply to Charlie Gordon
Quoted 9 lines · Christof Petig

can you enlighten me? The only drawback I see is that with plain C (no C++) typedef enum { ... } BOOL; would be more appropriate.

I would propose
#ifndef __cplusplus
typedef enum { false, true } bool;
#endif
as the optimal solution for a problem I hardly have (since I usually don't go back to coding in C)

There are two problems with using enum's and/or #define's for TRUE/FALSE. They should not be used in boolean expressions except where the return value is of that same typedef (e.g., the function returns bool) or is generated from the same set of #define's. While false is always 0, true is not always 1. True is non-zero.

Quoted 5 lines

const char *itoa(int i)

{  char x[20];
   snprintf(x,sizeof x,"%d",i);
   return x;
}

Forgot "static" before char x[20];, or to be more threadsafe, either malloc() or pass in a buffer and max size.

Quoted 4 lines

defensive programming would require that TRUE be also defined as

#define TRUE 1

Quoted 8 lines

as many unsuspecting programmers will expect TRUE and FALSE to be handled in the preprocessor phase eg:

#if TRUE
    ...
    somecode();
    ...

#endif

I disagree strongly. Anyone who writes "#if TRUE" or "#if FALSE" is just asking for trouble; (s)he needs to be taught a lesson. "#if 0" and "#if 1" are just as obvious, and both "#if 1" and "#if TRUE" are equally ridiculous.

A better technique would be something more like this:

#define UNUSED_CODE_BLOCK 0

#if UNUSED_CODE_BLOCK
...
#else /* used code below */
...
#endif

But even then it isn't as clean and readable as 1 or 0. Plus, you've still failed to solve the problem that true may or may not be 1.

Michael

Signature · 5 lines
Michael Jennings (a.k.a. KainX)  http://www.kainx.org/  <[email protected]>
n + 1, Inc., http://www.nplus1.net/       Author, Eterm (www.eterm.org)
-----------------------------------------------------------------------
 "You can accomplish much if you don't care who gets the credit."
                                                      -- Ronald Reagan
#12 lore raw

[Qemu-devel] Re: completely OT: C Q/As, was Re: security_20040618

"Michael Jennings" <[email protected]> wrote in message news:[email protected]...

Quoted 5 lines

There are two problems with using enum's and/or #define's for TRUE/FALSE. They should not be used in boolean expressions except where the return value is of that same typedef (e.g., the function returns bool) or is generated from the same set of #define's. While false is always 0, true is not always 1. True is non-zero.

This is a common misunderstanding. your last statement doesn't make sense :
in C, false IS 0 and true IS 1. That is the result of a false comparison is 0 (eg: 2 == 3) and the result of a true comparison is 1 (as in 2 == 2). As such boolean expressions can only have 2 values : 0 and 1, appropriately defined as FALSE and TRUE, be it via #define or enum.
Unlike its distant cousin Java, C allows non boolean expressions to control test statements such as 'if', 'for', and 'while'. In such constructs, falseness is not limited to the integer value 0 : '\0', 0.0, and NULL pointers also convert to false, while all other values convert to true. Further confusion is caused by the convention used in the standard C library where boolean valued function do not necessarily return 1 for trueness. Furthermore, it is perfectly OK to compare values from different typedefs but identical implementation types.
I do agree with you that there is room for confusion, especially for java bred programmers, and it is usually better to avoid the extra clutter of comparing to FALSE or TRUE in test expressions : just use the plain expression or bang (!) it for the reverse condition.

Quoted 2 lines

Forgot "static" before char x[20];, or to be more threadsafe, either malloc() or pass in a buffer and max size.

These are obvious solutions to the problem, the latter (buffer and size) is actually the one used in the C library for that very function (itoa). But the question was a different one : Why does this crash later (if you are lucky) ?

Quoted 5 lines
Quoted 5 lines

defensive programming would require that TRUE be also defined as

#define TRUE 1

as many unsuspecting programmers will expect TRUE and FALSE to be

handled in

Quoted 8 lines
Quoted 7 lines

the preprocessor phase eg:

#if TRUE
    ...
    somecode();
    ...

#endif

Quoted 4 lines

I disagree strongly. Anyone who writes "#if TRUE" or "#if FALSE" is just asking for trouble; (s)he needs to be taught a lesson. "#if 0" and "#if 1" are just as obvious, and both "#if 1" and "#if TRUE" are equally ridiculous.

You use #if 0 yourself, try pretending you never switch those to #if 1 ? I used to be harsh like this and show contempt for imperfect programming. I've had to grow more tolerant, as 99% of C or C++ code is indeed imperfect, and most programmers are more focussed on problem solving than clean coding. The truth is that *anyone* who writes C code is just asking for trouble. Yet this is still my favorite language. I do use #if 0 or #if 1 sometimes, never #if TRUE or #if FALSE, but I do not believe people that do should be taught such a difficult lesson : after all, it is an accepted convention that all uppercase identifiers be preprocessor defined. Christof Petig provided a more compelling example :

#define USE_MORE_CAUTION TRUE

#if USE_MORE_CAUTION == TRUE
    // this code would compile
#endif
#if USE_MORE_CAUTION == FALSE
    // this code would compile as well

#endif

My point is that if you define TRUE and FALSE in a header file, your job is to make sure that you are not setting up boobytraps for the unsuspecting (and imperfect) programmer to trigger.

I took a look at libast and you DO redefine TRUE and FALSE so as to setup such a trap !!! have pity on your users!

/* from libast/types.h */
...
#undef false
#undef False
#undef FALSE
#undef true
#undef True
#undef TRUE

typedef enum {
#ifndef __cplusplus
false = 0,
#endif
False = 0,
FALSE = 0,
#ifndef __cplusplus
true = 1,
#endif
True = 1,
TRUE = 1
} spif_bool_t;
...

While your code is amazingly consistent and readable (except for line length), you can learn from this very thread and fix it : you use strncpy 10 times. 7 of those are incorrect and at least 5 will lead to potential buffer overflow and inefficiencies, the remaining 3 could be replaced directly with calls to memcpy. You make one incorrect use of strncat, that may overflow by just one byte. pstrcpy provides the very semantics you require in most of these cases.

Cheers,

Chqrlie.

#13 lore raw

Re: [Qemu-devel] Re: completely OT: C Q/As, was Re: security_20040618

Something else...............I'm new to C++ ( but this is C code but the same in C++) so don't shoot me.......
Isn't enum { FALSE=0 , TRUE=1 } compleetly stupid anyway. I mean........is FALSE=0 then enum will automaticly make TRUE 1 right? So then enum {FALSE=0 , TRUE } ; would be better right?
Again don't shoot me I'm just trying to learn this language......

Op dinsdag 22 juni 2004 11:57 am, schreef Charlie Gordon:

Quoted 128 lines

"Michael Jennings" <[email protected]> wrote in message news:[email protected]...

Quoted 5 lines

There are two problems with using enum's and/or #define's for TRUE/FALSE. They should not be used in boolean expressions except where the return value is of that same typedef (e.g., the function returns bool) or is generated from the same set of #define's. While false is always 0, true is not always 1. True is non-zero.

This is a common misunderstanding. your last statement doesn't make sense : in C, false IS 0 and true IS 1. That is the result of a false comparison is 0 (eg: 2 == 3) and the result of a true comparison is 1 (as in 2 == 2). As such boolean expressions can only have 2 values : 0 and 1, appropriately defined as FALSE and TRUE, be it via #define or enum.
Unlike its distant cousin Java, C allows non boolean expressions to control test statements such as 'if', 'for', and 'while'. In such constructs, falseness is not limited to the integer value 0 : '\0', 0.0, and NULL pointers also convert to false, while all other values convert to true. Further confusion is caused by the convention used in the standard C library where boolean valued function do not necessarily return 1 for trueness. Furthermore, it is perfectly OK to compare values from different typedefs but identical implementation types.
I do agree with you that there is room for confusion, especially for java bred programmers, and it is usually better to avoid the extra clutter of comparing to FALSE or TRUE in test expressions : just use the plain expression or bang (!) it for the reverse condition.

Quoted 2 lines

Forgot "static" before char x[20];, or to be more threadsafe, either malloc() or pass in a buffer and max size.

These are obvious solutions to the problem, the latter (buffer and size) is actually the one used in the C library for that very function (itoa). But the question was a different one : Why does this crash later (if you are lucky) ?

Quoted 5 lines
Quoted 5 lines

defensive programming would require that TRUE be also defined as

#define TRUE 1

as many unsuspecting programmers will expect TRUE and FALSE to be

handled in

Quoted 8 lines
Quoted 7 lines

the preprocessor phase eg:

#if TRUE
    ...
    somecode();
    ...

#endif

Quoted 4 lines

I disagree strongly. Anyone who writes "#if TRUE" or "#if FALSE" is just asking for trouble; (s)he needs to be taught a lesson. "#if 0" and "#if 1" are just as obvious, and both "#if 1" and "#if TRUE" are equally ridiculous.

You use #if 0 yourself, try pretending you never switch those to #if 1 ? I used to be harsh like this and show contempt for imperfect programming. I've had to grow more tolerant, as 99% of C or C++ code is indeed imperfect, and most programmers are more focussed on problem solving than clean coding. The truth is that *anyone* who writes C code is just asking for trouble. Yet this is still my favorite language. I do use #if 0 or #if 1 sometimes, never #if TRUE or #if FALSE, but I do not believe people that do should be taught such a difficult lesson : after all, it is an accepted convention that all uppercase identifiers be preprocessor defined. Christof Petig provided a more compelling example :

#define USE_MORE_CAUTION TRUE

#if USE_MORE_CAUTION == TRUE
    // this code would compile
#endif
#if USE_MORE_CAUTION == FALSE
    // this code would compile as well

#endif

My point is that if you define TRUE and FALSE in a header file, your job is to make sure that you are not setting up boobytraps for the unsuspecting (and imperfect) programmer to trigger.

I took a look at libast and you DO redefine TRUE and FALSE so as to setup such a trap !!! have pity on your users!

/* from libast/types.h */
...
#undef false
#undef False
#undef FALSE
#undef true
#undef True
#undef TRUE

typedef enum {
#ifndef __cplusplus
false = 0,
#endif
False = 0,
FALSE = 0,
#ifndef __cplusplus
true = 1,
#endif
True = 1,
TRUE = 1
} spif_bool_t;
...

While your code is amazingly consistent and readable (except for line length), you can learn from this very thread and fix it : you use strncpy 10 times. 7 of those are incorrect and at least 5 will lead to potential buffer overflow and inefficiencies, the remaining 3 could be replaced directly with calls to memcpy. You make one incorrect use of strncat, that may overflow by just one byte. pstrcpy provides the very semantics you require in most of these cases.

Cheers,

Chqrlie.

_______________________________________________
Qemu-devel mailing list
[email protected]
http://lists.nongnu.org/mailman/listinfo/qemu-devel

#14 lore raw

[Qemu-devel] Re: Re: completely OT: C Q/As, was Re: security_20040618

"Sander Nagtegaal" <[email protected]> wrote in message news:[email protected]...

Quoted 1 line

Something else...............I'm new to C++ ( but this is C code but the

same

Quoted 1 line

in C++) so don't shoot me.......

I'm just a teaser, not an executionner.

Quoted 3 lines

Isn't enum { FALSE=0 , TRUE=1 } compleetly stupid anyway. I mean........is FALSE=0 then enum will automaticly make TRUE 1 right? So then enum {FALSE=0 , TRUE } ; would be better right?

Well, yes and no. You correctly analyse that the initializer for TRUE is redundant, as a matter of fact both initialisers are useless. So I could have written :

enum BOOL { FALSE, TRUE };
or whatever typedef is appropriate.

But I prefer to make certain things more explicit. I find it more readable. Not exactly what you call "completely stupid" !

Now if you want to flame something completely stupid, look at this one :

#define FALSE 0==1
#define TRUE 1==1

Why will this fail ?

Chqrlie.

#15 lore raw

Re: [Qemu-devel] Re: completely OT: C Q/As

In reply to Charlie Gordon
Quoted 6 lines · Charlie Gordon

This is a common misunderstanding. your last statement doesn't make sense : in C, false IS 0 and true IS 1. That is the result of a false comparison is 0 (eg: 2 == 3) and the result of a true comparison is 1 (as in 2 == 2). As such boolean expressions can only have 2 values : 0 and 1, appropriately defined as FALSE and TRUE, be it via #define or enum.

Incorrect. The result of a boolean operator is guaranteed to be 1 or
0. However, values evaluated in a boolean context such as those in an if statement are not bound by that rule.

Quoted 5 lines

Unlike its distant cousin Java, C allows non boolean expressions to control test statements such as 'if', 'for', and 'while'. In such constructs, falseness is not limited to the integer value 0 : '\0', 0.0, and NULL pointers also convert to false, while all other values convert to true.

All the values you mentioned evaluate to (int) 0 in a boolean context.

Quoted 3 lines

Further confusion is caused by the convention used in the standard C library where boolean valued function do not necessarily return 1 for trueness.

As there is no such thing as a "boolean value" in C, no standard C function returns a boolean value. Some do, however, return an integer that may be successfully used in a boolean context (albeit possibly negated).

Quoted 4 lines

I do agree with you that there is room for confusion, especially for java bred programmers, and it is usually better to avoid the extra clutter of comparing to FALSE or TRUE in test expressions : just use the plain expression or bang (!) it for the reverse condition.

That was not my statement. Again, it depends on what you're doing. If you're guaranteed a return of 0 or non-zero, best to use == 0 or !=
0. With pointers, the value itself is fine, negated or not, but other valid approaches include == NULL, != NULL, or even a macro like ISNULL().

Quoted 4 lines

These are obvious solutions to the problem, the latter (buffer and size) is actually the one used in the C library for that very function (itoa). But the question was a different one : Why does this crash later (if you are lucky) ?

You found my answer to be obvious. I found the question to be obvious. So we're even. :-)

The answer you were looking for (regarding the stack) had already been given. I was simply taking a different tack.

Quoted 1 line

You use #if 0 yourself, try pretending you never switch those to #if 1 ?

In production-quality code? Never. For testing purposes where only I was meant to see it? Absolutely.

Quoted 4 lines

I used to be harsh like this and show contempt for imperfect programming. I've had to grow more tolerant, as 99% of C or C++ code is indeed imperfect, and most programmers are more focussed on problem solving than clean coding.

And a lackadaisical attitude such as this is why so many programmers just don't know any better. Be tolerant in what you accept, but strict in what you create. And just because something doesn't generate an error doesn't mean it shouldn't generate a warning.

Quoted 2 lines

The truth is that *anyone* who writes C code is just asking for trouble.

Don't agree there.

Quoted 2 lines

after all, it is an accepted convention that all uppercase identifiers be preprocessor defined.

We agree on that point at least. :-)

Quoted 9 lines

Christof Petig provided a more compelling example :

#define USE_MORE_CAUTION TRUE

#if USE_MORE_CAUTION == TRUE
    // this code would compile
#endif
#if USE_MORE_CAUTION == FALSE
    // this code would compile as well

#endif

Again, it's more properly written as "#if USE_MORE_CAUTION" or "#if !USE_MORE_CAUTION"

Quoted 3 lines

My point is that if you define TRUE and FALSE in a header file, your job is to make sure that you are not setting up boobytraps for the unsuspecting (and imperfect) programmer to trigger.

And again, I disagree. By defining something in a header file that other programmers will use, you're defining an API. What is most important is that it is clear and consistent, not that it follows any one particular religion.

Quoted 12 lines

I took a look at libast and you DO redefine TRUE and FALSE so as to setup such a trap !!! have pity on your users!

/* from libast/types.h */
...
#undef false
#undef False
#undef FALSE
#undef true
#undef True
#undef TRUE

Quoted 13 lines

typedef enum {
#ifndef __cplusplus
false = 0,
#endif
False = 0,
FALSE = 0,
#ifndef __cplusplus
true = 1,
#endif
True = 1,
TRUE = 1
} spif_bool_t;
...

First off, I'm creating a well-defined API. I use an enum to create an actual type I can return, manipulate, check against, blah blah blah. I undefine those macros to prevent situations where some platforms may expand one or more of the LHS values to something that's no longer valid for the enum while others may not.

Secondly, libast headers are API headers, and are really not all that different from system headers. If a programmer wishes to use them, (s)he should #include them BEFORE any custom headers (s)he may also be using. Nothing is stopping a programmer from redefining those macros as (s)he sees fit. But for my purposes, the correct choice is clear.

Besides, several other items which are more intended for preprocessor use (e.g., FIXME_BLOCK and UNUSED_BLOCK) are defined separately.

Quoted 2 lines

While your code is amazingly consistent and readable (except for line length),

LOL You've got me there; I use GNU Emacs under X11, so my maximum line length is largely dependent on how big the Emacs window was in which I wrote that code. :-)

Wrapping code at 80 chars can result in some really ugly messes, so I gave up on that. I just haven't found a really good alternative yet.

Quoted 3 lines

you can learn from this very thread and fix it : you use strncpy 10 times. 7 of those are incorrect and at least 5 will lead to potential buffer overflow and inefficiencies,

My analysis of the code disagrees, but I'd like to look at any evidence you may have.

Quoted 3 lines

the remaining 3 could be replaced directly with calls to memcpy. You make one incorrect use of strncat, that may overflow by just one byte.

You're right, thanks.

Michael

Signature · 6 lines
Michael Jennings (a.k.a. KainX)  http://www.kainx.org/  <[email protected]>
n + 1, Inc., http://www.nplus1.net/       Author, Eterm (www.eterm.org)
-----------------------------------------------------------------------
 "Did you really have to die for me?  All I am for all You are because
  What I need and what I believe are worlds apart."
                                       -- Jars of Clay, "Worlds Apart"
#16 lore raw

[Qemu-devel] Re: Re: completely OT: C Q/As : let's feed the troll

Quoted 4 lines

As there is no such thing as a "boolean value" in C, no standard C function returns a boolean value. Some do, however, return an integer that may be successfully used in a boolean context (albeit possibly negated).

In C there is no boolean type, but there are boolean values : results of boolean operators as you pointed out.
I agree that most standard C functions do not return booleans values, which is the cause of numerous bugs by unsuspecting but bold programmers, not necessarily newbies. look at these examples:

if (isspace(*p) == isspace(*q)) ... // stupid optimisation!
if (isdir(path1) & isdir(path2)) ... // lack of C experience or plain
typo

These are horrible things to write, but I've seen much worse examples of non portable code like this, that do work in a lot of environments, and will fail without warning on others.
One would need to define an integer type that can only be compared to 0. strcmp provides even more horrible semantics: C newbies routinely compare the result to -1 !
Do you know any tool that can detect such horrors ? I agree with teaching offenders a lesson, that's what compile time warnings and errors are for. If you let bugs like this crawl into production software, end users will become victims, and maintainers will do the hard work... Original authors/sinners will have already moved on to other projects, and commit more trash.

My point is this : C is difficult enough as a language, try not to add more
traps unnecessarily.

Quoted 3 lines

And just because something doesn't
generate an error doesn't mean it shouldn't generate a warning.

I agree completely, as a matter of fact, I always compile with almost all warnings on, and make gcc treat them as errors.

Quoted 29 lines
Quoted 9 lines

/* from libast/types.h */
...
#undef false
#undef False
#undef FALSE
#undef true
#undef True
#undef TRUE

Quoted 13 lines

typedef enum {
#ifndef __cplusplus
false = 0,
#endif
False = 0,
FALSE = 0,
#ifndef __cplusplus
true = 1,
#endif
True = 1,
TRUE = 1
} spif_bool_t;
...

First off, I'm creating a well-defined API. I use an enum to create an actual type I can return, manipulate, check against, blah blah blah. I undefine those macros to prevent situations where some platforms may expand one or more of the LHS values to something that's no longer valid for the enum while others may not.

Quoted 5 lines

Secondly, libast headers are API headers, and are really not all that different from system headers. If a programmer wishes to use them, (s)he should #include them BEFORE any custom headers (s)he may also be using. Nothing is stopping a programmer from redefining those macros as (s)he sees fit. But for my purposes, the correct choice is clear.

In the case of FALSE/TRUE, you know damn well you are not "creating" the API, you are potentially redefining it, the fact that you first undef those symbols proves my point. I cannot understand why you define upto 3 different symbols for each boolean value !
In my original post, I was pointing out how such a redefinition has subtle side-effects that you probably didn't anticipate.

For completeness, TRUE and FALSE are defined by numerous API headers. Apache for one has a bogus definition in several header files :
apache/ap_ctx.h:
#ifndef FALSE
#define FALSE 0
#define TRUE !FALSE
#endif

The missing parentheses should strike as an obvious mistake. Further thinking may convince you otherwise... Wrong ! here is a contrived counterexample :

    printf("this should print 98 : TRUE[\"ab\"]=%d\n", TRUE["ab"]);

will print 0 instead of 98 with that definition.

C IS DIFFICULT ! There is always one more bug.

Quoted 9 lines
Quoted 2 lines

While your code is amazingly consistent and readable (except for line length),

LOL You've got me there; I use GNU Emacs under X11, so my maximum line length is largely dependent on how big the Emacs window was in which I wrote that code. :-)

Wrapping code at 80 chars can result in some really ugly messes, so I gave up on that. I just haven't found a really good alternative yet.

Good for you ! I can read C code much faster when it doesn't extend beyond 80 columns.
You get ugly messes because you do too much on one line, use too many verbose macros...

    self->items = SPIF_CAST_C(spif_obj_t *) REALLOC(self->items,

SPIF_SIZEOF_TYPE(obj) * (--(self->len)));

Since REALLOC, and MALLOC always need a cast in C++, why not pass the type ? Since realloc has despicable behaviour when running out of memory, why not pass the address of the pointer ?
Then wrap the ugly mess in a macro (you know about that)...
This is much safer, more concise, and fits in 80 columns, and you could even check the boolean return value :

    REALLOC(&self->items, --self->len, spif_obj_t);
Quoted 6 lines
Quoted 3 lines

you can learn from this very thread and fix it : you use strncpy 10 times. 7 of those are incorrect and at least 5 will lead to potential buffer overflow and inefficiencies,

My analysis of the code disagrees, but I'd like to look at any evidence you may have.

Lets go:

socket.c line 717

    addr->sun_path[0] = 0;
    strncat(addr->sun_path, SPIF_STR_STR(spif_url_get_path(self)),

sizeof(addr->sun_path));

strncat will copy upto sizeof(addr->sun_path) bytes from the source, and tack a '\0'.
the destination happens to be empty (why use strncat ?), so this code can only overflow addr->sun_path by 1 byte, it would be much worse if actual concatenation took place.

file.c line 51:

    if (len) {
        strncpy(ftemplate, buff, len);
        ftemplate[len - 1] = 0;
    }

this is just inefficient and cumbersome. pstrcpy is what you want. also len is a misleading name for the buffer size.

mem.c line 78:

    strncpy(p->file, filename, LIBAST_FNAME_LEN);
    p->file[LIBAST_FNAME_LEN] = 0;

inefficiency again, luckily the buffer size is LIBAST_FNAME_LEN + 1, pstrcpy fixes this.

mem.c line 135

   strncpy(p->file, filename, LIBAST_FNAME_LEN);

no extra null setting here ! code is inconsistent, I guess you rely on magic side effects : the ptr_t structure is not allocated here and most likely the last byte of the file buffer has already been set to 0. This is unsafe. pstrcpy fixes this.

strings.c line 99. line 120:

    tmpstr = (char *) MALLOC(cnt + 1);
    strncpy(tmpstr, str, cnt);
    tmpstr[cnt] = 0;
    return (tmpstr);

inefficiency ! pstrcpy fixes this.

conf.c line 485:

                  strncpy(newbuff + j, getenv("HOME"), max - j);
                  cnt1 = strlen(getenv("HOME")) - 1;
                  cnt2 = max - j - 1;
                  j += MIN(cnt1, cnt2);

given CONFIG_BUFF is defined as 20480, (max - j) is likely very large. So inefficient!
It is also bogus as newbuff is not guarantied to be null terminated. getting $HOME twice is childish.
relying on MIN to fix the unsigned overflow in case $HOME is the empty string is nothing to be proud of.
Similar code is repeated 3 more times in the same function with similar problems.

conf.c line 741:

        if (n > 0 && n <= maxpathlen) {
            /* Compose the /path/file combo */
            strncpy(full_path, path, n);
            if (full_path[n - 1] != '/') {
                full_path[n++] = '/';
            }
            full_path[n] = '\0';
            strcat(full_path, name);

strncpy is OK here, but not needed as memcpy can be used directly. strcpy(full_path + n, name) would be more efficient as well.

I'll grant you that the bugs are very remote, but that makes them completely unlikely to be caught
before production.

Just don't use strncpy, steal pstrcpy from here and use it, and propagate to message !

Cheers,

Charlie Gordon.

PS: please let's stop polluting qemu, address further remarks to me directly.