[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Tinycc-devel] segfault with static array initialized by a macro

From: Thomas Preud'homme
Subject: Re: [Tinycc-devel] segfault with static array initialized by a macro
Date: Sun, 21 Oct 2012 13:48:18 +0200
User-agent: KMail/1.13.7 (Linux/3.2.0-4-amd64; KDE/4.8.4; x86_64; ; )

Le samedi 20 octobre 2012 19:03:19, Didier Barvaux a écrit :
> Hello all,
> In encountered what seems to be a bug in TCC (git revision
> ad5f3758c38f2364f03205dcb9fd48142d2d4499). I narrowed it down to the
> following test case.
> $ cat segfault_with_static_array.c
> #include <stdio.h>
> #define LENGTH1  10
> #define LENGTH2  20
> #define max(a, b)  (((a) > (b)) ? (a) : (b))
> int main(int argc, char *argv[])
> {
>       static unsigned char data[max(LENGTH1, LENGTH2)];
>       printf("max(%d, %d) = %d\n", LENGTH1, LENGTH2, max(LENGTH1,
>       LENGTH2)); printf("data = %p\n", data);
>       data[0] = 0x42;
>       return 0;
> }
> $ tcc -o segfault_with_static_array -Wall -Werror \
>   segfault_with_static_array.c
> $ ./segfault_with_static_array
> max(10, 20) = 20
> data = (nil)
> Erreur de segmentation
> $ echo $?
> 139
> The program above works with GCC 4.5, GCC 4.6, GCC 4.7 and Clang 3.1.
> It does not fail with TCC if I do not use the max() macro or remove the
> 'static' keyword for the 'data' array.

Ok, I found what happens. It's because the handling of ternary operator inside 
the declaration of a VLA (Variable Length Array) generates some code.

[the following text is both for myself and anybody who might want to fix it 
instead of me]

What happens is that post_type, which handles VLA consider wether a VLA is 
possible or not by testing !localstack || nocode_wanted. If this returns true, 
then it will try to parse the expression between square braces (the 
MAX(LENGTH1, LENGTH2) here) as an integer constant. Else, it parses it as a 
general expression. In this mode, (10) > (20) is correctly evaluated to 0 but 
the ternary operator, which is handled by expr_cond, behaves differently and 
generates code, even if everything is constant.

To me there is 2 mistakes. I didn't read the code deeply but it sounds wrong 
to generate code in expr_cond if everything is constant. The only effect of 
const_wanted in this function should be to give an error if the expression is 
not constant. If the expression is constant, the result should be the same.

The second mistake is that nocode_wanted should be 1 if processing some static 
variable since it will be outside any function. This is probably the easiest 
fix but really both problems should be fixed IMHO.

> Regards,
> Didier

Thanks for the report.

Best regards,

Thomas Preud'homme

Attachment: signature.asc
Description: This is a digitally signed message part.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]