[fpc-devel] Dangerous optimization in CASE..OF
Florian Klämpfl
florian at freepascal.org
Sun Jul 16 20:42:38 CEST 2017
Am 16.07.2017 um 20:25 schrieb Ondrej Pokorny:
> For now, Pascal enumerated types work as aliases for underlying ordinal values - a concept that is
> exactly the same as C enums:
>
Very good point:
florian at ubuntu64:~$ cat test.cc
#include <stdio.h>
enum tenum { e1,e2,e3,e4,e5,e6,e7,e8 };
int f(tenum e)
{
switch (e)
{
case e1:
printf("Hello 1 %d\n",e1);
return 1;
case e2:
return 354;
case e3:
return 351;
case e4:
return 315;
case e5:
return 35;
case e6:
printf("Hello asdf\n");
return 1;
case e7:
printf("Hello \n");
return 2;
case e8:
printf("Hello\n");
return 3;
}
}
int main()
{
f(tenum(12));
}
florian at ubuntu64:~$ clang test.cc
florian at ubuntu64:~$ ./a.out
Ungültiger Maschinenbefehl (Speicherabzug geschrieben)
florian at ubuntu64:~$ clang test.cc -O3
florian at ubuntu64:~$ ./a.out
florian at ubuntu64:~$ clang --version
clang version 3.8.0-2ubuntu4 (tags/RELEASE_380/final)
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
"Ungültiger Maschinenbefehl (Speicherabzug geschrieben)" = Invalid opcode (memory dump written).
Why? Because it does not range check before entering the jump table.
Funnily enough clang does not create crashing code with -O3 as it removes all code :), to get a
crash, compile probably both function separately, the assembler code for f() suggests this.
More information about the fpc-devel
mailing list