Compare commits

...

1720 Commits

Author SHA1 Message Date
Marko Semet ed0d315ebb Support basic libc function 2020-05-23 01:35:11 +02:00
Marko Semet 785af9373a TCC tools don't run exec command. 2020-05-21 04:27:31 +02:00
Marko Semet d5bd2531b0 Implemenations for the cstring header. 2020-05-21 04:19:56 +02:00
Marko Semet 15ec4e90f2 Add basic bootstrap code. 2020-05-16 19:15:10 +02:00
grischka d348a9a51d final update for 0.9.27
tccgen.c:
- fix ldouble asm hack
- fix a VLA problem on Win64 (also x86_64-gen.c)
- patch_type(): make sure that no symbol ever changes
  from global to static

tcc.c:
- tcc -vv: print libtcc1.a path also on win32

tccpe.c, tcctools.c:
- use unix LF mode to for .def output files (that is for
  creating reproducible output trees)

Makefile:
- suppress some warnings when makeinfo is missing
- call 'which install' only on win32

tests/Makefile:
- change PATH only on WINNT systems (i.e. not if cross-compiling
  on linux for win32)
- asm-c-connect.test: slim output and do diff

tccrun.c tccpe.c *-link.c:
- integrate former 'pe_relocate_rva()' into normal relocation
  This also fixes linkage of the unwind data on WIN64 for -run
  (reported by Janus Lynggaard Thorborg)

tccasm.c, tests/tcctest.c:
- fix dot (sym_index of -1 crashed in put_elf_reloc)
- massage .set a bit (see test)

other:
- #define SECTION_ABS removed
- ST_DATA Section *strtab_section: removed
- put_extern_sym2(): take int section number

Conflicts:
	tccelf.c
	tccpe.c

Conflicts:
	tccelf.c
2017-12-12 17:57:20 +01:00
grischka 1a4d4b76e8 tccgen_begin/end_file
This is supposed to make compilation and linking with
multiple source files (tcc f1.c f2.S ...) behave just
the same as linking object files.

tccgen.c:put_extern_sym2():
- use put_elf_sym to enter new symbols unconditionally

tccelf.c:
- save section state before compilation
- disable symbol hashing during compilation
- merge symbols and update relocations after compilation

tccpe.c:
- re-create s1->uw_sym for each compilation (because it
  may change)
2017-12-12 17:33:37 +01:00
Michael Matz 8490c54dbd Fix some multi-file corner cases with asm
for this we have to create also asm symbols as VT_STATIC initially
except if there's an indication that it should be global (.globl
or undefined at end of unit).  For this to work we need to
be able to globalize symbols after they were local and enter them
into the ELF hash tables, and also adjust the symbols that were
potentially already used in relocs when they were still local.

The easiest is to do a proper symbol resolution step also in multi-file
mode, for regular symbols (the non-dynamic ones, i.e. not from shared
libs).
2017-12-10 06:50:58 +01:00
grischka 3ae1a2af1c tccgen: unify type redefinition checks
tccgen.c:
- improved function patch_storage() and added new function
  patch_type() for more consistent type redefinition and
  instance redefinition checks.
2017-12-05 02:06:26 +01:00
grischka 877e164d6a tccasm: use global(_symbol)_stack
* removed asm_label stack
* removed asm_free_labels() post-processing
* using "impossible C type" for asm labels (VT_ASM)
* tccgen.c:update_storage(): use it to refresh symbol attributes
* tccelf.c:find_elf_sym(): ignore STB_LOCAL symbols
* tccgen.c:unary(): asm symbols are supposed to be undeclared in C
2017-12-05 01:54:49 +01:00
Michael Matz cc6cb7f0e2 Fix another corner case with C/asm symtable
See testcase (from grischka).  If the asm has no .globl,
but there's a (non-static) C definition the symbol should
be exported, even if the first reference comes from asm.
2017-12-04 03:51:14 +01:00
Michael Matz 529b44c0d5 tccasm: Accept suffixed cmovCC
The length suffix for cmovCC isn't necessary as the required register
operands always allow length deduction.  But let's be nice to users
and accept them anyway.  Do that without blowing up tables, which means
we don't detect invalid suffixes for the given operands, but so be it.
2017-12-03 04:53:50 +01:00
Michael Matz 9e0d23cc47 tccasm: Unify C and asm symbol table
This makes the asm symbols use the same members as the C symbols
for global decls, e.g. using the ELF symbol to hold offset and
section.  That allows us to use only one symbol table for C and
asm symbols and to get rid of hacks to synch between them.

We still need some special handling for symbols that come purely
from asm sources.
2017-11-27 04:59:29 +01:00
Michael Matz 3494e5de3a Adjust asm-c-connect testcase for Windows
Calling conventions are different, let's use functions without
any arguments.
2017-11-27 01:09:50 +01:00
Michael Matz 4266ebd69c tccasm: Don't abuse dllexport/dllimport
For tracking if asm symbols are connected with a C symbol,
and if asm symbols need to be global use new flags, instead of
reusing dllimport/dllexport, which would cause unrequested exported
entries on Windows.

This is a stop-gap until the C and asm symtable are unified.
2017-11-25 19:41:03 +01:00
Michael Matz e7c71e2473 tccasm: synch C and asm symtab tighter
See testcase.  The C and asm symtab are still separate,
but integrated tighter: the asm labels are only synched at file
end, not after each asm snippet (this fixes references from one
to another asm block), the C and asm syms are synched both ways,
so defining things in asm and refering from C, or the other way
around works.  In effect this model reflects what happens with
GCC better.

For this the asm labels aren't using the C label namespace anymore,
but their own, which increases the size of each TokenSym by a pointer.
2017-11-22 17:57:43 +01:00
Michael Matz 330c01bfc6 Adjust testcase for PIE compilers
one some systems GCC defaults to PIC/PIE code which is incompatible
with a unannotated asm call to a function (getenv here).  TCC doesn't
support these PIC annotations (yet), so play some pre-processor games.
2017-11-19 15:36:47 +01:00
Michael Matz d0db21757a Fix forward asm labels differently
while last change fixed one part of label behaviour (undefined ones
must be global) it again broke a different aspect (forward defs
without .globl must stay local).  This fixes both aspects.
That a label is local instead of global is difficult to test without
resorting to look at the symbol table or using two-file testcases,
so we do without.  In essence the local/global-ness of symbols
should be the same between GAS and TCC for this input:

    .globl glob1
    glob1:
    call glob1

    .globl glob2
    call glob2
    glob2:

    glob3:
    .globl glob3
    call glob3

    glob4:
    call glob4
    .globl glob4

    call glob5
    .globl glob5
    glob5:

    call glob6
    glob6:
    .globl glob6

    locl1:
    call locl1

    call locl2
    locl2:

    unref1:
    unref2:
    .globl unref2
    .globl unref3
    unref3:
    call undef
2017-11-19 03:04:11 +01:00
Michael Matz a8ece0f2ce Don't make forard asm symbols static by default
fixes the problem in the testcase.  A symbolic reference
from asm, which remains undefined at the end of processing is
always a global reference, not a static (STB_LOCAL) one.
This also affected the linux kernel.
2017-11-16 13:29:59 +01:00
Michael Matz 348dd9f4a6 Fix absolute memory references
This properly fixes what 870271ea tried to fix.  Absolute memory
references can't use %rip relative addressing, and additionally,
if the address doesn't fit 32bit (signed) it must be loaded via
movabs.  No good testcase added, it would require catching signals
and still be unreliable.
2017-11-15 13:39:28 +01:00
Michael Matz 74463eb954 Revert "gen_addrpc32: absolute ptr needs *ABS* relocation"
This reverts commit 870271ea07.

The commit is broken, you can't unconditionally emit a PC-relative
relocation without a symbol.  And if there's a symbol the addend
need to be in the relocation, not the section.
2017-11-14 16:43:22 +01:00
janus.lt 32c9b51401 Win64/PE: Changed runtime function unwind info to be added after relocation, fixes SEH + long jmps 2017-11-04 00:18:37 +01:00
emekoi fc0188ffbc fixed dylib typo in libtcc.c 2017-10-19 00:55:42 -05:00
grischka da8c62f75d various stuff
win32/Makefile ("for cygwin") removed
- On cygwin, the normal ./configure && make can be used with either
  cygwin's "GCC for Win32 Toolchain"
      ./configure --cross-prefix=i686-w64-mingw32-
  or with an existing tcc:
      ./configure --cc=<old-tccdir>/tcc.exe

tcctest.c:
- exclude test_high_clobbers() on _WIN64 (does not work)

tests2/95_bitfield.c:
- use 'signed char' for ARM (where default 'char' is unsigned)

tests:
- remove -I "expr" diff option to allow tests with
  busybox-diff.

libtcc.c, tcc.c:
- removed -iwithprefix option.  It is supposed to be
  combined with -iprefix which we don't have either.

tccgen.c:
- fix assignments and return of 'void', as in
     void f() {
         void *p, *q;
         *p = *q:
         return *p;
     }
  This appears to be allowed but should do nothing.

tcc.h, libtcc.c, tccpp.c:
- Revert "Introduce VIP sysinclude paths which are always searched first"
  This reverts commit 1d5e386b0a.

  The patch was giving tcc's system includes priority over -I which
  is not how it should be.

tccelf.c:
- add DT_TEXTREL tag only if text relocations are actually
  used (which is likely not the case on x86_64)
- prepare_dynamic_rel(): avoid relocation of unresolved
  (weak) symbols

tccrun.c:
- for HAVE_SELINUX, use two mappings to the same (real) file.
  (it was so once except the RX mapping wasn't used at all).

tccpe.c:
- fix relocation constant used for x86_64 (by Andrei E. Warentin)
- #ifndef _WIN32 do "chmod 755 ..." to get runnable exes on cygwin.

tccasm.c:
- keep forward asm labels static, otherwise they will endup
  in dynsym eventually.

configure, Makefile:
- mingw32: respect ./configure options --bindir --docdir --libdir
- allow overriding tcc when building libtcc1.a and libtcc.def with
      make XTCC=<tcc program to use>
- use $(wildcard ...) for install to allow installing just
  a cross compiler for example
      make cross-arm
      make install
- use name <target>-libtcc1.a

build-tcc.bat:
- add  options: -clean, -b bindir
2017-10-11 18:13:43 +02:00
YX Hao faa9744f5d Win: crt, initialize global __argc, __targv and _tenviron of msvcrt
_tenviron: as far as possible, not in ASC '-run' mode.
__argc and __targv are shortcuts for _tWinMain, when you want to use program parameters.
2017-10-10 20:39:05 +08:00
Steffen Nurpmeso 6f1860e200 Fix Windows++ compilation of previous (YX Hao, Joel Bodenmann) 2017-10-09 14:52:56 +02:00
Steffen Nurpmeso 1d5e386b0a Introduce VIP sysinclude paths which are always searched first 2017-10-03 17:58:45 +02:00
Steffen Nurpmeso a1c9051313 Adjust va_list to work with musl 2017-09-30 16:11:54 +02:00
Christian Jullien 2e5751caf1 tools directory no more exists, removed in win32 tarball Makefile target. 2017-09-29 07:26:21 +02:00
Larry Doolittle 8deb05c3e2 Use more conventional punctuation for sequential assignments 2017-09-25 22:16:23 -07:00
Avi Halachmi (:avih) abd1532ad4 freebsd: allow building tcc which targets windows
Currently tcc doesn't have a compile-time config indicating that the target
is freebsd, and as a result, the tcc binary adds freebsh stuff to elf headers
if the compile-time (of tcc) *host* is freebsd.

Test also that the target is not PE while generating an elf header.

This still likely fails (but untested) when tcc targets other non-freebsd
systems on a freebsd system, but for now fix it only when targetting windows.
2017-09-25 18:39:35 +03:00
Larry Doolittle 560188711d Fix some spelling in documentation 2017-09-24 18:22:42 -07:00
Larry Doolittle 1b6806e5bb Spelling fixes
Comments only, no change to functionality
2017-09-24 18:03:26 -07:00
Larry Doolittle 44d4da62bb Convert two .c files to LF line endings
... matching the other 157 .c files in the tree
2017-09-24 16:48:08 -07:00
grischka 1443039416 'long' review
add some features for more complete 'long' support

tcc.h:
- use LONG_SIZE=4/8 instead of TCC_LONG_ARE_64_BIT
tccgen.c:
- add ptrdiff_type, update size_type
- support shift and ?: operations
- support long enum types
- display 'long' from type_to_str
- nwchar_t is unsigned short on windows
- unrelated: use memcpy in init_putv for long doubles to avoid
  random bytes in the image (if tcc was compiled by gcc) for
  diff purposes.
tccpp.c:
- make parse_number return correct types
- improve multi-character-constants 'XX' 'abcd'
Changelog:
- update
2017-09-24 18:57:48 +02:00
Zdenek Pavlas 870271ea07 gen_addrpc32: absolute ptr needs *ABS* relocation
Dereferencing of absolute pointers is broken on x86_64, eg:

*(int*)NULL does not segfault but returns -4 instead
*(char*)(-10L << 20) does not return 0x55 (vsyscall page, push rbp)
2017-09-11 06:36:16 -07:00
Zhang Boyang 078d8c2c5a Add test case for fastcall calling convention 2017-09-10 18:22:48 +08:00
Zhang Boyang f406f63a38 Add test case for AL/AX extending problem 2017-09-10 17:03:34 +08:00
Zhang Boyang 978d1ecce0 Add test case for wide char handling in wide string literal 2017-09-10 16:50:19 +08:00
Zhang Boyang b39810ff78 Fix calling function pointers casted from intergers in DLL
The code generated for "((void (*)(void))0x12345678)()" will be a single "CALL 0x12345678" in previous code.
However, this will not work for DLLs, because "CALL imm" is PC related, DLL relocation will break the code.
This commit fixed the problem by forcing TCC generates indirect CALLs in this situation.
2017-09-09 21:11:56 +08:00
Zhang Boyang 02370acdc9 Fix AL/AX is not extended to EAX when calling indirectly
AL/AX should be extended to EAX when calling functions. However, the previous code did this only for direct calls, indirect calls were ignored.
New code also avoid redundant code when generating JMP instruction. (i.e. expanding code should be generated with CALL instruction only)
2017-09-09 21:01:42 +08:00
Zhang Boyang a82c11f4b4 Fix wide char handling in wide string literal
This commit fixed the problem that TCC directly cast each byte in wide string literal to wchar_t, which is wrong when wide string literal contains real wide chars.
It fixed the problem by assuming input charset is UTF-8, and wchar_t stores wide chars in UTF-16 (Windows) or UTF-32 (others).
The UTF-8 decoder is coded according to The Unicode Standard Version 10.
2017-09-09 20:37:43 +08:00
Zhang Boyang b8fe8fc210 called function should pop the arguments when using fastcall 2017-08-21 19:38:11 +08:00
Edmund Grimley Evans ac41e015f1 Convert from ISO-8859-1 to UTF-8. See aa812e8. 2017-07-26 13:07:14 +01:00
Matthias Gatto 4f15d08ea1 Revert "use int for ssize_t, (u)intptr_t instead of long in stddef.h"
This reverts commit 52622c3c03.

Because 28b7c9 was right.
2017-07-26 10:25:52 +02:00
matthias c18fc950d7 Revert "simplify VT_LONG parsing"
Too simple long parsion.
Take me a long long long time to see my mistake,
Sorry

(long long long wasn't see as an error)
This reverts commit a4cd2805f9.
2017-07-25 22:04:24 +02:00
Christian Jullien 023d4e0b59 Remove debug echo in Cygwin Makefile 2017-07-25 19:17:10 +02:00
Christian Jullien 421a1c48bb Update Cygwin Makefile to use -B. for bootstrap 2017-07-25 19:12:04 +02:00
Matthias Gatto 52622c3c03 use int for ssize_t, (u)intptr_t instead of long in stddef.h 2017-07-25 18:56:41 +02:00
Matthias Gatto 23064b1734 check that _Generic match 'signed long int' as 'long' 2017-07-25 18:56:41 +02:00
Matthias Gatto a4cd2805f9 simplify VT_LONG parsing 2017-07-25 18:56:41 +02:00
Christian Jullien 8258abeb80 Update Cygwin Makefile to work with recent changes about ONE_SOURCE and CONFG_TCCDIR 2017-07-25 17:50:28 +02:00
Matthias Gatto 28b7c9b34e define __SIZE_TYPE__ and __PTRDIFF_TYPE__ as unsigned int and int.
As long is now a qualifier, and because compare_type will notice
that variables are not the same type, we can't use long as int anymore.

So, I've redefine __SIZE_TYPE__ as unsigned int and __PTRDIFF_TYPE__ as int.
2017-07-25 16:25:27 +02:00
Matthias Gatto b72cddaa6e remove inside_generic hack
define uint64_t and int64_t as 'long' instead of 'long long'
when __LP64__ is define.
2017-07-24 11:52:15 +02:00
grischka 4b3c6e74ab tccgen: nodata_wanted fix, default ONE_SOURCE, etc...
tccgen.c:
  doubles need to be aligned, on ARM.  The section_reserve()
  in init_putv does not do that.
-D ONE_SOURCE: is now the default and not longer needed. Also,
  tcc.h now sets the default native target.  These both make
  compiling tcc simple as "gcc tcc.c -o tcc -ldl" again.
arm-asm.c:
  enable pseudo asm also for inline asm
tests/tests2/Makefile:
  disable bitfield tests except on windows and x86_64
  and don't generate-always
tcc.c:
  fix a loop with -dt on errors
configure:
  print compiler version (as recognized)
tccpp.c:
  actually define symbols for tcc -dt
  clear static variables (needed for -dt or libtcc usage)
96_nodata_wanted.c:
  use __label__ instead of asm
lib/files:
  use native symbols (__i386__ etc.) instead of TCC_TARGET_...
2017-07-23 21:24:11 +02:00
matthias fdc18d307a mutiples fix for _Generic
* check that _Generic don't match unsigned char * with char *
  this case is usefull as with -funsigned-char, 'char *' are unsigned

* change VT_LONG so it's now a qualifier

  VT_LONG are never use for code generation, but only durring parsing state,
  in _Generic we need to be able to make diference between
  'long' and 'long long'
  So VT_LONG is now use as a type qualifier, it's old behaviour is still
  here, but we can keep trace of what was a long and what wasn't

* add TOK_CLONG and TOK_CULONG

  tcc was directly converting value like '7171L' into TOK_CLLONG or
  TOK_CINT depending of the machine architecture.

  because of that, we was unable to make diference between a long and a
  long long, which doesn't work with _Generic.

  So now 7171L is a TOK_CLONG, and we can handle _Generic properly

* check that _Generic can make diference between long and long long

* uncomment "type match twice" as it should now pass tests on any platforms

* add inside_generic global

  the point of this variable is to use VT_LONG in comparaison only
  when we are evaluating a _Generic.
  problem is with my lastest patchs tcc can now make the diference between
  a 'long long' and a 'long', but in 64 bit stddef.h typedef uint64_t as
  typedef signed long long int int64_t and stdint.h as unsigned long int, so tcc
  break when stdint.h and stddef.h are include together.

  Another solution woud be to modifie include/stddef.h so it define uint64_t as
  unsigned long int when processor is 64 bit, but this could break some
  legacy code, so for now, VT_LONG are use only inside generc.

* check that _Generic parse first argument correctly

* check that _Generic evaluate correctly exresion like "f() / 2"
2017-07-21 19:30:31 +02:00
grischka 0cc24d0e84 tcc -dt -run ... : simpler is better
* -dt now with lowercase t

* test snippets now separated by real preprocessor statements
  which is valid C also for other compilers

    #if defined test_xxx
       < test snippet x >
    #elif defined test_yyy
       < test snippet y >
    #elif ...
    #endif

* simpler implementation, behaves like -run if no 'test_...' macros
  are seen, works with -E too

* for demonstration I combined some of the small tests for errors
  and warnings (56..63,74) in "60_errors_and_warnings.c"

Also:
* libtcc.c:
  put tcc_preprocess() and tcc_assemble() under the setjmp clause
  to let them return to caller after errors.  This is for -dt -E.
* tccgen.c:
  - get rid of save/restore_parse_state(), macro_ptr is saved
    by begin_macro anyway, now line_num too.
  - use expr_eq for parsing _Generic's controlling_type
  - set nocode_wanted with const_wanted. too, This is to keep
    VT_JMP on vtop when parsing preprocessor expressions.
* tccpp.c: tcc -E: suppress trailing whitespace from lines with
  comments (that -E removes) such as
       NO_GOTPLT_ENTRY,\t    /* never generate ... */
2017-07-20 22:21:27 +02:00
Matthias Gatto ba2b25e4ea fix typo sellector -> selector 2017-07-18 20:28:51 +02:00
matthias 2821644553 fix typo: march -> match 2017-07-18 20:28:51 +02:00
Matthias Gatto 2020a312ca unqualify volatile in _Generic type checking 2017-07-18 20:28:51 +02:00
Michael Matz 3f13e33872 Fix cross compilers
Only native compilers support -run and hence the new -dT.
2017-07-16 21:03:25 +02:00
grischka 7f1ab9b1e1 tccgen: nodata_wanted
The existing variable 'nocode_wanted' is now used to control
output of static data too. So...

(nocode_wanted == 0)
    code and data (normal within functions)
(nocode_wanted < 0)
    means: no code, but data (global or static data)
(nocode_wanted > 0)
    means: no code and no data (code and data suppressed)
(nocode_wanted & 0xC0000000)
    means:  we're in declaration of static data

Also: new option '-dT' to be used with -run
    tcc -dT -run file.c
This will look in file.c for certain comment-boundaries:
    /*-* test-xxx: ...some description */
and then for each test below run it from memory.  This way
various features and error messages can be tested with one
single file.  See 96_nodata_wanted.c for an example.

Also: tccgen.c: one more bitfield fix
2017-07-16 12:10:00 +02:00
grischka 69a137ff88 #pragma comment(option,"-..."), bitfields test, etc...
tccpp.c:
* #pragma comment(option,"-some-option")
  to set commandline option from C code.  May work only
  for some options.
libtcc.c:
* option "-d1..9": sets a 'g_debug' global variable.
  (for development)
tests2/Makefile:
* new make targets: tests2.37 / tests2.37+
  run single test from tests2,  optionally update .expect
* new variable GEN-ALWAYS to always generate certain .expects
* bitfields test
tccgen.c:
* bitfields: fix a bug and improve slightly more
* _Generic: ignore "type match twice"
2017-07-14 19:26:01 +02:00
Michael Matz 04418c7add Fix function types
various cases of function type uses were broken by recent
attribute refactoring, this fixes and adds testcases for them.
2017-07-14 17:42:48 +02:00
Michael Matz 2acb04f7f2 tccasm: Fix local statics referenced from asms
The assembler uses the ->sym_scope member to walk up the symbols
until finding a non-automatic symbol.  Since reordering the
members of Sym the sym_scope member contains a scope even for local
statics.  Formerly the use of asm_label for statics was implicitely
clearing sym_scope, now we have to do that explicitely.

Add a testcase for that, and one I encountered when moving the
clearing of sym_scope too deep into the call chain (into put_extern_sym).
2017-07-10 22:29:28 +02:00
Michael Matz 9bea88d616 Fix statement exprs returning a local label
Like returned local variables also labels local to a statement expression
can be returned, and so their symbols must not be immediately freed
(though they need to be removed from the symbol table).
2017-07-10 22:25:11 +02:00
Michael Matz 2240422da9 enums: Accept GNU extension
See testcase.  Happens e.g. in the linux kernel.
2017-07-10 22:20:34 +02:00
grischka a9e502cc3b refactor bitfields
Use 2 level strategy to access packed bitfields cleanly:

1) Allow to override the original declaration type with
   an auxilary "access type".  This solves cases such as

    struct {
        ...
        unsigned f1:1;
    };

    by using VT_BYTE to access f1.

2) Allow byte-wise split accesses using two new functions
   load/store_packed_bf. This solves any cases, also ones
   such as

    struct __attribute((packed)) _s {
        unsigned x : 12;
        unsigned char y : 7;
        unsigned z : 28;
        unsigned a: 3;
        unsigned b: 3;
        unsigned c: 3;
    };

    where for field 'z':
    - VT_INT access from offset 2 would be unaligned
    - VT_LLONG from offset 0 would go past the total
      struct size (7)

    and for field 'a' because it is in two bytes and
    aligned access with VT_SHORT/INT is not possible.

Also, static bitfield initializers are stored byte-wise always.
Also, cleanup the struct_layout function a bit.
2017-07-09 12:38:59 +02:00
grischka f87afa72e0 refactor enums
Eliminate VT_ENUM as a basic type.  Instead use the integral
types VT_InT/VT_LLONG with an additional flag to indicate
that it is an enum.
2017-07-09 12:38:25 +02:00
grischka 9ba76ac834 refactor sym & attributes
tcc.h:
* cleanup struct 'Sym'
* include some 'Attributes' into 'Sym'
* in turn get rid of VT_IM/EXPORT, VT_WEAK
* re-number VT_XXX flags
* replace some 'long' function args by 'int'

tccgen.c:
* refactor parse_btype()
2017-07-09 12:34:11 +02:00
grischka 9f79b62ec4 unsorted adjustments
- configure
  * use aarch64 instead of arm64

- Makefile
  * rename the custom include file to "config-extra.mak"
  * Also avoid "rm -r /*" if $(tccdir) is empty

- pp/Makefile
  * fix .expect generation with gcc

- tcc.h
  * cleanup #defines for _MSC_VER

- tccgen.c:
  * fix const-propagation for &,|
  * fix anonymous named struct (ms-extension) and enable
    -fms-extension by default

- i386-gen.c
  * clear VT_DEFSIGN

- x86_64-gen.c/win64:
  * fix passing structs in registers
  * fix alloca (need to keep "func_scratch" below each alloca area on stack)
    (This allows to compile a working gnu-make on win64)

- tccpp.c
  * alternative approach to 37999a4fbf
    This is to avoid some slowdown with ## token pasting.
  * get_tok_str() : return <eof> for TOK_EOF
  * -funsigned-char: apply to "string" literals as well

- tccpe/tools.c: -impdef: support both 32 and 64 bit dlls anyway
2017-07-09 12:07:40 +02:00
grischka 6c468c10f7 tccpp: allow "#define X defined Y ..."
That means: we do not macro-expand the argument of 'defined'

Also: store the last token position into the TokenString
structure in order to get rid of the tok_last function.
2017-07-09 11:46:14 +02:00
Michael Matz 824dcebe59 tccpp: Implement __COUNTER__
This requires one more change in how macro arguments are expanded:
the standard requires that macro args are expanded before substituting
into the replacement list.  This implies expanding them only once
even when they occur multiple times in the list.  TCC expanded
them repeatedly in that case.  Without __COUNTER__ that's harmless.

So, simply always expand arguments (when used without # and ##) once
and store the resulting tokens.
2017-07-09 05:30:47 +02:00
Michael Matz 1f3d3957c4 tccpp: Cleanup
With last change the can_read_stream flag is unneeded, so tidy this
a bit.
2017-07-09 04:53:24 +02:00
Michael Matz d8fdd380f3 tccpp: Fix corner case
See added testcase 19.c from a bug report.  The problem is reading outside
the arguments buffers, even though we aren't allowed to.  The single
can_read_stream variable is not enough, sometimes we need to be able
to pop into outer contexts but not into arbitrarily outside contexts.

The trick is to terminate argument tokens with a EOF (and not just with
0 that makes us pop contexts), and deal with that in the few places
we have to,

This enables some cleanups of the can_read_stream variable use.
2017-07-09 04:38:56 +02:00
Matthias Gatto 16d3dbf2d0 add _Generic test 2017-07-05 17:59:42 +02:00
Matthias Gatto 157bad52cd add C11's _Generic
Simple implementation, I'm not even sure to respect C standart here,
but it should work with most use case.

This add an case in unary(), and generate TokString depending of _Generic
controlling exression, use begin_macro to "push"
the generated TokString, then call unary() again before exiting the switch
so the just add token are reevaluate again.
2017-07-05 10:57:50 +02:00
Michael Matz 9ed8b54f6c Revert "String literals are always const"
This reverts commit d4fe9aba3f.
I was confused by the fact that string literals aren't writable.
Nevertheless the type isn't const.  As extension in GCC it's const
with -Wwrite-string, which is exactly what we had before.

GCC also wonders in a comment if it's really a good idea to change
expression types based on warning flags (IMHO it's not), but let's
be compatible.  So restore the state from before.
2017-07-04 16:37:49 +02:00
Michael Matz 580ad5f24c Extend skip_or_save_block
Make it stop also before outer level closing parens.  This way
we can now also skip/save the expression inside "foobar(42 + 41)".
2017-07-03 19:15:16 +02:00
Michael Matz 27ca303874 Improve skip_or_save_block
Stop at level 0 only for matching outer '}' (which is added).
Otherwise stop only at stop tokens (which aren't added).
2017-07-03 18:13:15 +02:00
Michael Matz d4fe9aba3f String literals are always const
Don't make the standard mandated types of string literals
depends on warning options.  Instead make them always const,
but limit the emission of the warning by that option.
2017-07-03 18:02:57 +02:00
Christian Jullien b68df809eb Align 'implicit-function-declaration' option comment with other comments (cosmetic change) 2017-06-10 06:45:51 +02:00
Christian Jullien 6d559d651f Add -O2 when compiling tcc on Windows. Not sure this flag is really used by tcc. 2017-06-10 06:35:11 +02:00
Emil 3e028af453 When creating a staticaly linked ELF program should not include
any dyn symbols. The if( !s1->static_link ) prevents tcc from
crashing when buiding a program linked to dietlibc.

The section header should not contain the number of local symbols when
the sh_size is null. This makes the header compliant and IDA will not
issue any warnings when an executable is disassembled.
2017-06-09 19:44:29 +01:00
U-NELSON\jullien 3e4b7693bf force i386-win32-tcc.exe to be a 32bit binary. Run tests in both 32/64 bits on Windows. 2017-06-05 08:18:11 +02:00
U-NELSON\jullien 2a348896dd Add more common tests to be run from win32/Makefile 2017-06-04 09:27:48 +02:00
Christian Jullien 0cc4e570bc Windows test Makefile target also test pp tests. 2017-05-28 07:12:57 +02:00
Michael Matz 31e5ad789a Limit access end-of-struct warning a bit
Only warn if the struct has a non-zero size.  You can't create objects
of zero-sized structs, but they can be used inside sizeof (e.g.
"sizeof (struct {int :0;})".  The warning would always trigger for these,
but as no objects can be created no accesses can ever happen.
2017-05-27 22:44:53 +02:00
Michael Matz 7cd1ae7710 x86-64: Fix psABI stdarg prologue
If there were more than 6 integer arguments before the ellipsis, or
there were used more than 8 slots used until the ellipsis (e.g. by
a large intermediate struct) we generated wrong code.  See testcase.
2017-05-27 22:42:18 +02:00
Michael Matz 53c5fc2246 x86-64: Rewrite linux parameter passing
This fixes two ABI testcases involving large arguments when there
are still registers available for later args.
2017-05-27 21:23:13 +02:00
Aron BARATH 307b7b183d the R_X86_64_GOTOFF64 relocation was missing 2017-05-16 07:03:26 +02:00
grischka 28435ec58c configure: --config-musl/-uClibc switch & misc cleanups
- configure:
  - add --config-uClibc,-musl switch and suggest to use
    it if uClibc/musl is detected
  - make warning options magic clang compatible
  - simplify (use $confvars instead of individual options)
- Revert "Remove some unused-parameter lint"
  7443db0d5f
  rather use -Wno-unused-parameter (or just not -Wextra)
- #ifdef functions that are unused on some targets
- tccgen.c: use PTR_SIZE==8 instead of (X86_64 || ARM64)
- tccpe.c: fix some warnings
- integrate dummy arm-asm better
2017-05-13 08:59:06 +02:00
Aron BARATH 3a9d6b3655 added 64-bit relocation types that required to linking against 64-bit (large model) libraries 2017-05-12 09:31:09 +02:00
grischka 1ed20a01c9 bitfields: promote to signed int
For integer promotion with for example arithmetics or
expr_cond (x ? y : z), integral types need to be promoted
to signed if they fit.

According to latest standards, this also applies to bit-field
types taking into account their specific width.

In tcc, VT_BITFIELD set means width < original type width
Field-widths between 33 and 63 are promoted to signed long long
accordingly.

    struct { unsigned long long ullb:35; } s = { 1 };
    #define X (s.ullb - 2)

    int main (void)
    {
        long long Y = X;
        printf("%d %016llx %016llx\n", X < 0, -X, -Y);
        return 0;
    }

Results:
    GCC 4.7 : 0 0000000000000001 FFFFFFF800000001
    MSVC    : 1 0000000000000001 0000000000000001
    TCC     : 1 0000000000000001 0000000000000001

Also, gcc would promote long long bitfields of size < 32
to int as well.  Example:

    struct { unsigned long long x:20; } t = { 123 };
    /* with gcc: */ printf("%d %d\n", t.x, 456);
    /* with tcc: */ printf("%lld %d\n", t.x, 456);
2017-05-09 18:36:24 +02:00
grischka d242706f3b bitfields: one more hack and a "-Wgcc-compat" switch
bit_pos + bit_size > type_size * 8

must NEVER happen because the code generator can read/write
only the basic integral types.

Warn if tcc has to break GCC compatibility for that reason
and if -Wgcc-compat is given.

Example:
    struct __attribute__((packed)) _s
    {
        unsigned int x  : 12;
        unsigned char y :  7;
        unsigned int z  : 28;
    };

Expected (GCC) layout (sizeof struct = 6)
.xxxxxxxx.xxxxyyyy.yyyzzzzz.zzzzzzzz.zzzzzzzz.zzzzzzz0.

But we cannot read/write 'char y'from 2 bytes in memory.
So we have to adjust:
.xxxxxxxx.xxxx0000.yyyyyyyz.zzzzzzzz.zzzzzzzz.zzzzzzzz.zzz00000

Now 'int z' cannot be accessed from 5 bytes.  So we arrive
at this (sizeof struct = 7):
.xxxxxxxx.xxxx0000.yyyyyyy0.zzzzzzzz.zzzzzzzz.zzzzzzzz.zzzz0000

Otherwise the bitfield load/store generator needs to be
changed to allow byte-wise accesses.

Also we may touch memory past the struct in some cases
currently.  The patch adds a warning for that too.

   0:	55                   	push   %ebp
   1:	89 e5                	mov    %esp,%ebp
   3:	81 ec 04 00 00 00    	sub    $0x4,%esp
   9:	90                   	nop

    struct __attribute__((packed)) { unsigned x : 5; } b = {0} ;

   a:	8b 45 ff             	mov    -0x1(%ebp),%eax
   d:	83 e0 e0             	and    $0xffffffe0,%eax
  10:	89 45 ff             	mov    %eax,-0x1(%ebp)

This touches -0x1 ... +0x3(%ebp), hence 3 bytes beyond
stack space.  Since the data is not changed, nothing
else happens here.
2017-05-09 18:10:02 +02:00
Larry Doolittle 3f5fd305af Touch up previous "s"[i<2] patch
The real equivalence is between the original "s" + (i<2)
and &"s"[i<2].
2017-05-09 07:08:43 -07:00
Larry Doolittle 3c0a73822d Give clang one less thing to complain about
"s"[i<2] and "s" + (i<2) are literally identical, but the latter triggers
a warning from clang because it looks so much like a noob is trying to
concatenate an integer and a string.  The former is arguably more clear.
2017-05-08 21:56:38 -07:00
Michael Matz dfb75d9b6c Remove some unused arguments
these ones are really superfluous.
2017-05-08 20:26:59 +02:00
Michael Matz 377e8e5e68 bitfields: fix long bitfields
now the testcase works on i386-linux as well.
2017-05-08 19:58:31 +02:00
Marc Vertes 1094891e67 Improve musl and uclibc detection
Do not enable musl or uclibc native support if a GNU linker is
already present. This avoids interference for example on a
Debian platform with musl-dev installed. More work is required
to select musl libc in that case, with additional configure flags.
2017-05-08 16:14:35 +00:00
Larry Doolittle 70fca7f799 Fix spelling in help message
"seach" becomes "search" in help2 when not TCC_TARGET_PE
2017-05-08 08:44:52 -07:00
Larry Doolittle 7443db0d5f Remove some unused-parameter lint
Mark TCCState parameter as unused in tcc_undefine_symbol(), tcc_add_symbol(),
tcc_print_stats(), asm_get_local_label_name(), use_section1(), tccpp_delete(),
tcc_tool_ar(), tcc_tool_impdef(), and tcc_tool_cross().
Also mark it unused in tcc_add_bcheck() unless CONFIG_TCC_BCHECK.
Remove it entirely in ld_next().
2017-05-08 08:30:43 -07:00
Christian Jullien 56df27502c C string litteral is const, fix return type of default_elfinterp. Remove #ifndef TCC_IS_NATIVE in arm-gen.c as suggested by grischka. 2017-05-08 09:18:27 +02:00
Larry Doolittle 19d8b8a173 Spelling fixes in C comments only 2017-05-07 21:38:09 -07:00
Larry Doolittle 1b9935cf36 Add missing const and add warning flags 2017-05-07 21:28:05 -07:00
Michael Matz 524f6dff17 Fix a warning
"missing intitializer for field op_type" with gcc -Wextra.  It's
zero-initialized anyway, and not that much a hassle to explicitely
initialize either, so let's be nice and make it not warn.
2017-05-08 05:29:54 +02:00
grischka 44abffe33a more minor fixes
* tccgen: re-allow long double constants for x87 cross
  sizeof (long double) may be 12 or 16 depending on host platform
  (i386/x86_64 on unix/windows).
  Except that it's 8 if the host is on windows and not gcc
  was used to compile tcc.

* win64: fix builtin_va_start after VT_REF removal
  See also a8b83ce43a

* tcctest.c: remove outdated limitation for ll-bitfield test
  It always worked, there is no reason why it should not work
  in future.

* libtcc1.c: exclude long double conversion on ARM

* Makefile: remove CFLAGS from link recipes

* lib/Makefile: use target DEFINES as passed from main Makefile

* lib/armflush.c lib/va_list.c: factor out from libtcc1.c

* arm-gen.c: disable "depreciated" warnings for now
2017-05-07 12:41:29 +02:00
Michael Matz 94ac9f2b49 Accept extern initialized file-scope variables
'extern int i = 42;' at file scope (but not in function scope!) is
allowed and is a proper definition, even though questionable style;
some compilers warn about this.
2017-05-07 08:10:06 +02:00
Michael Matz 5732a1882e elf: Fix last commit
Forgot to mark tccelf.c as to be committed in last commit :-/
2017-05-07 04:52:21 +02:00
Michael Matz 680e84fe42 elf: Support STB_LOCAL dynamic symbols
local symbols can be resolved statically, they don't have to be
done dynamically, so this is a slight speedup at load time for
produced executables and shared libs.  The musl libc also rejects
any STB_LOCAL symbols for dynamic symbol resolution, so there it
also fixes use of shared libs created by tcc.
2017-05-07 04:41:40 +02:00
Michael Matz 600018ce47 elf: Ignore SHF_COMPRESSED sections
some newer systems have debug sections compressed by default, which
includes those in the crt[1in].o startup files.  These can't simply
be concatenated like all others (which leads to invalid section contents
ultimately making gdb fail) but need special handling.

Instead of that special handling (decompressing, which in turn requires
linking against zlib) let's just ignore such sections, even though that
means to also ignore all other debug sections from that particular input
file.  Our own generated files of course don't have the problem.
2017-05-06 07:30:44 +02:00
Michael Matz ff998900b1 struct-init: Fix zero initialization with multi-level designators
See the added testcase.  When one used designators like .a.x to initialize
sub-members of members, and didn't then initialize all of them the
required zero-initialization of the other sub-members wasn't done.
The fix also enables tiny code cleanups.
2017-05-06 05:28:13 +02:00
Michael Matz 0757234560 Fix unsigned enum bit-fields
See testcase.  If an enum has only positive values, fits N bits,
and is placed in a N-bit bit-field that bit-fields must be treated
as unsigned, not signed.
2017-05-05 23:16:43 +02:00
Michael Matz a7a3627ab2 Fix segfault with invalid function def
This invalid function definition:
  int f()[] {}
was tried to be handled but there was no testcase if it actually worked.
This fixes it and adds a TCC only testcase.
2017-05-05 22:01:02 +02:00
Michael Matz d4878985e8 Rebuild cross compilers when sources change
ONE_SOURCE=yes cross-compilers currently only depend on tcc.c, which
itself has no further deps.  So e.g. changing tccgen.c or tcctok.h
don't automatically rebuild cross compilers.  Let's go over
the intermediate $(X)tcc.o file which automatically depends on
LIBTCC_INC, which are all relevant source files.
2017-05-02 03:14:05 +02:00
Michael Matz 149678e888 Tidy decl_designator
Removing the need for the notfirst local variable, and tidy loop structure
and error messaging a bit.
2017-05-02 03:14:05 +02:00
Michael Matz 9839b60177 Remove label_or_decl
The only use of this function can be rewritten in terms of
is_label (if one other use of that one are a bit amended).
2017-05-02 03:14:05 +02:00
Michael Matz c7dbc900c8 Cleanups (float consts, sections, symbols)
introduce common_section (SHN_COMMON), factorize some handling
in decl_initializer_alloc, add section_add and use it to factorize
some code that allocates stuff in sections (at the same time also fixing
harmless bugs re section alignment), use init_putv to emit float consts
into .data from gv() (fixing an XXX).
2017-05-02 03:13:55 +02:00
Michael Matz 25522e4799 Merge func_decl_list into decl0
Removes some code duplication and also implements one feature:
checking for duplicate decls for old style parameters.
2017-05-02 03:07:37 +02:00
Michael Matz 7aef0522b0 Tidy decl_designator
The fixme therein is long solved.
2017-05-02 03:07:37 +02:00
Michael Matz 8ca98e23c4 Tidy unary() a bit
factor code a bit for transforming tokens into SValues.  This revealed
a bug in TOK_GET (see testcase), which happened to be harmless before.
So fix that as well.
2017-05-02 03:07:37 +02:00
Michael Matz 21b12ea10d Factor some code
Three places that skip (and store) tokens in some fashion can
be factored a bit.
2017-05-02 03:07:37 +02:00
Michael Matz 328b06a3fc Extend type_to_str
to also print storage-class specifiers.
2017-05-02 03:07:36 +02:00
Michael Matz 182367e232 Reorganize type parsing
Various corner cases for declarator parsing were incorrect.  This
reorganizes and fixes it, and somewhat simplifies it as well.
2017-05-02 03:07:36 +02:00
Michael Matz 5891fbc0c8 Tidy typename parsing a bit 2017-05-02 03:07:36 +02:00
Michael Matz 51314932e3 Tidy arg parsing for builtins
Saves some lines of code.
2017-05-02 03:07:36 +02:00
Michael Matz 10551d6961 Clarify that the CIL target code is dead
This backend doesn't work anymore since a long time.
Don't remove it yet, it might be an inspiration.
2017-05-02 03:07:36 +02:00
Michael Matz a8b83ce43a Remove VT_REF
The canonical way to describe a local variable that actually holds
the address of an lvalue is VT_LLOCAL.  Remove the last user of VT_REF,
and handling of it, thereby freeing a flag for SValue.r.
2017-05-02 03:07:36 +02:00
Michael Matz 8b9697ca6b Fix bogus check for VT_LLOCAL types
VT_LLOCAL is a flag on .r, not on type.t.  Fixing this requires
minor surgery for compound literals which accidentally happened
to be subsumed by the bogus test.
2017-05-02 03:07:36 +02:00
Michael Matz 24420bb5c0 elf: Tidy section headers
Don't emit useless section headers and also sort them in allocated
order.  Doesn't change behaviour except makes the resulting files
a tiny bit smaller (though at the expense of some very tiny compile
time and code size increase of tcc itself; not 100% it's worth it).
2017-05-02 03:07:36 +02:00
Michael Matz 3c39cb5cd8 fix __builtin_expect
the second argument can be an arbitrary expression (including
side-effects), not just a constant.  This removes the last user
of expr_lor_const and hence also that function (and expr_land_const).
Also the argument to __builtin_constant_p can be only a non-comma
expression (like all functions arguments).
2017-05-02 03:07:36 +02:00
Michael Matz 8d9dd3c008 Fix more bitfield corner cases
Our code generation assumes that it can load/store with the
bit-fields base type, so bit_pos/bit_size must be in range for this.
We could change the fields type or adjust offset/bit_pos; we do the
latter.
2017-05-01 06:18:48 +02:00
Michael Matz 4ce73354fc Fix last change
Skipping anonymous bit-fields is correct, but not other
anonymous ones like unions or structs.
2017-05-01 06:04:19 +02:00
Michael Matz f775d68725 Remove a bit-field TODO
Checked the lcc testsuite for bitfield stuff (in cq.c and fields.c),
fixed one more error in initializing unnamed members (which have
to be skipped), removed the TODO.
2017-04-29 22:09:10 +02:00
Michael Matz 28084420fe Fix char bitfields corner case
See testcase.
2017-04-29 21:25:31 +02:00
Thomas Stalder 76e16465bf arm: Fix build_got_entries 2017-04-27 14:16:49 +02:00
Christian Jullien f12851e388 Add -static to be in sync with Windows bat. 2017-04-27 07:01:46 +02:00
grischka a35752d233 configure: fix permissions
There must be something with git on windows that it
messes up x permissions sometimes.
2017-04-26 00:01:23 +02:00
Larry Doolittle 37999a4fbf Simple-minded fix for bug #50847
bug #50847: #line directive corrupts #include search path
Keep a second copy of the filename, that isn't changed by the #line directive,
and use that on the initial search path for #include files.
2017-04-25 12:32:41 -07:00
grischka 7acf9aa862 final adjustments for release
- configure/Makefiles: minor adjustments

- build-tcc.bat: add -static to gcc options
  (avoids libgcc_s*.dll dependency with some mingw versions)

- tccpe.c/tcctools.c: eliminate MAX_PATH
  (not available for cross compilers)

- tccasm.c: use uint64_t/strtoull in unary()
  (unsigned long sometimes is only uint32_t, as always on windows)

- tccgen.c: Revert (f077d16c) "tccgen: gen_cast: cast FLOAT to DOUBLE"
  Was a rather experimental, tentative commit, not really necessary
  and somewhat ugly too.

- cleanup recent osx support:
  - Makefile/libtcc.c: cleanup copy&paste code
  - tccpp.c: restore deleted function
2017-04-25 21:01:54 +02:00
Andrei Warkentin fb4f57666c tcc: report Darwin when building for Mach-O binaries.
Somewhat revert c4c3f50, but key off the config, not
host system.

Signed-off-by: Andrei Warkentin <andrey.warkentin@gmail.com>
2017-04-25 13:57:33 +03:00
Andrei Warkentin 63b2f907bd tcc: fixup clang warnings
The O(xxx) stuff in i386-asm.c had me scratching my head. Extracting
the macro and trying it out in a separate program doesn't give
me any warnings, so I'm confused about what could be going on there.
Any cast will make things happy. I used a uint64_t to catch actual
cases of overflow, which will still cause a -Wconstant-conversion
warning.

Signed-off-by: Andrei Warkentin <andrey.warkentin@gmail.com>
2017-04-25 13:55:18 +03:00
Andrei Warkentin 91cd148a05 tcc: early OSX native support
- build scripts
- working '-run' mode, e.g.:

./tcc -B. -I./include -I. -I.. -D_ANSI_SOURCE -run examples/ex1.c

Note: we don't bother parsing Mach-O/Fat images yet. We blindly
dlopen the image.

Signed-off-by: Andrei Warkentin <andrey.warkentin@gmail.com>
2017-04-25 13:55:18 +03:00
Marc Vertes 0ac29b53dc Add support of musl-libc
The port is functional. Bound checking is not supported yet.
2017-04-20 22:01:50 +02:00
Michael Matz 328b826e8a tccpp: Fix corner case of fnlike macro invocation
Arg substitution leaves placeholder marker in the stream for
empty arguments.  Those need to be skipped when searching for
a fnlike macro invocation in the replacement list itself.  See
testcase.
2017-04-15 19:34:55 +02:00
grischka 536ed76d5a tccgen/win32: let __declspec(dllimport) imply extern
Also, retain storage qualifiers in type_decl, in particular
also for function pointers.  This allows to get rid of this
very early hack in decl()
    type.t |= (btype.t & VT_STATIC); /* Retain "static". */
which was to fix the case of
    int main() { static int (*foo)(); ...

Also:
- missing __declspec(dllimport) is an error now
- except if the symbol is "_imp__symbol"
- demonstrate export/import of data in the dll example (while
  'extern' isn't strictly required with dllimport anymore)
- new function 'patch_storage()' replaces 'weaken_symbol()'
  and 'apply_visibility()'
- new function 'update_storage()' applies storage attributes
  to Elf symbols.
- put_extern_sym/2 accepts new pseudo section SECTION_COMMON
- add -Wl,-export-all-symbols as alias for -rdynamic
- add -Wl,-subsystem=windows for mingw compatibility
- redefinition of 'sym' error for initialized global data
2017-04-04 08:34:52 +02:00
Christian Jullien c4c3f5009e Even on Darwin, tcc should display Linux 2017-02-26 16:28:52 +01:00
Avi Halachmi (:avih) 2da36731da win: tests Makefile: fix global path
Commit bb93064 changed the path seperator from ':' to ';', which was
likely accidental. While path seperator on Windows is generally ';', the
Makefile clearly expects a posix-y shell, and in such environments the
separator is ':'.

This fixes the test run in MSYS2 and MSYS(1) environments, which got
broken on bb93064 .
2017-02-26 15:41:26 +02:00
Christian Jullien 206829415a Linux was incorrectly identified in banner when compiled on macOS Darwin 2017-02-26 08:02:53 +01:00
grischka bb93064d78 makefile: unify cross with native builds
supports building cross compilers on the fly without need
for configure --enable-cross

   $ make cross          # all compilers
   $ make cross-TARGET   # only TARGET-compiler & its libtcc1.a

with TARGET one from
   i386 x86_64 i386-win32 x86_64-win32 arm arm64 arm-wince c67

Type 'make help' for more information
2017-02-25 12:51:04 +01:00
Christian Jullien 669f61117d Cygwin Makefile was to aggresive to remove entire lib/ 2017-02-24 22:51:10 +01:00
Christian Jullien 2e0a8f9b37 Update Cygwin Makefile for new libtcc1-xx.a layout 2017-02-24 22:39:06 +01:00
grischka 569255e6c4 cross-compilers: allow individual configuration
since configure supports only native configuration
a file 'cross-tcc.mak' needs to be created manually.
It is included in the Makefile if present.

# ----------------------------------------------------
# Example config-cross.mak:
#
# windows -> i386-linux cross-compiler
# (it expects the linux files in <prefix>/i386-linux)

ROOT-i386 = {B}/i386-linux
CRT-i386 = $(ROOT-i386)/usr/lib
LIB-i386 = $(ROOT-i386)/lib:$(ROOT-i386)/usr/lib
INC-i386 = {B}/lib/include:$(ROOT-i386)/usr/include
DEF-i386 += -D__linux__

# ----------------------------------------------------

Also:
- use libtcc1-<target>.a instead of directories
- add dummy arm assembler
- remove include dependencies from armeabi.c/lib-arm64.c
- tccelf/ld_add_file: add SYSROOT (when defined) to absolute
  filenames coming from ld-scripts
2017-02-23 08:41:57 +01:00
Christian Jullien 576bee9a37 Add note about native Windows bootstrap using Cygwin. 2017-02-23 06:45:26 +01:00
Michael Matz 3e4c296eba x86-64-asm: Fix mov im64,rax encoding
the avoidance of mov im32->reg64 wasn't working when reg64 was rax.
While fixing this also fix instructions which had the REX prefix
hardcoded in opcode and so didn't support extended registers which
would have added another REX prefix.
2017-02-23 00:16:25 +01:00
Michael Matz e209b7dac4 Update ChangeLog
with more things I remember having done :)
2017-02-20 20:24:30 +01:00
grischka 5f33d313c8 tcc: re-enable correct option -r support
Forgot about it.  It allows to compile several
sources (and other .o's) to one single .o file;

    tcc -r -o all.o f1.c f2.c f3.S o4.o ...

Also:
- option -fold-struct-init-code removed, no effect anymore
- (tcc_)set_environment() moved to tcc.c
- win32/lib/(win)crt1 minor fix & add dependency
- debug line output for asm (tcc -c -g xxx.S) enabled
- configure/Makefiles: x86-64 -> x86_64 changes
- README: cleanup
2017-02-20 18:58:08 +01:00
Christian Jullien 399237850d Update cygwin Makefile after recent Windows source changes 2017-02-18 14:53:31 +01:00
grischka 5286529632 tcc -hh: show more options 2017-02-18 09:55:46 +01:00
grischka 2d3b9559bf tcctools.c: integrate tiny_libmaker/_impdef
usage:
    tcc -ar [rcsv] lib files...
    tcc -impdef lib.dll [-v] [-o lib.def]

also:
- support more files with -c: tcc -c f1.c f2.c ...
- fix a bug which caused tcc f1.c f2.S to produce no asm
- allow tcc -ar @listfile too
- change prototype: _void_ tcc_set_options(...)
- apply -Wl,-whole-archive when a librariy is given
  as libxxx.a also (not just for -lxxx)
2017-02-18 09:55:34 +01:00
Steffen Nurpmeso f34b1feaca -Wl, --enable-new-dtags for DT_RUNPATH instead of DT_RPATH
Today by accident i had to deal with linker problems of some
software and found an issue that mentioned DT_RUNPATH, which
mentioned that DT_RPATH is legacy and searched for
$LD_LIBRARY_PATH, whereas the newer DT_RUNPATH is searched
thereafter.  Completely unencrypted!  Well.  For what's it worth,
i for one am astonished because of course i want to override
$LD_LIBRARY_PATH, but it surely has its merites, smart people came
to the conclusion, did they.

The attached diff below seems to be sufficient to support
DT_RUNPATH instead of DT_RPATH with tcc(1).  But i have no insight
in what --enable-new-dtags is supposed to change in addition, so
i wonder.

Ciao!

--steffen

 libtcc.c     | 2 ++
 tcc-doc.texi | 4 ++++
 tcc.h        | 1 +
 tccelf.c     | 3 ++-
 4 files changed, 9 insertions(+), 1 deletion(-)
2017-02-18 09:54:41 +01:00
grischka 096125d963 win32: adjust new unicode support
- lib/Makefile: add (win)crt1_w.o

- crt1.c/_runtmain: return to tcc & only use for UNICODE
  (because it might be not 100% reliable with for example
  wildcards (tcc *.c -run ...)

- tccrun.c/tccpe.c: load -run startup_code only if called
  from tcc_run(). Otherwise main may not be defined.  See
  libtcc_test.c

- tests2/Makefile: pass extra options in FLAGS to allow
  overriding TCC

Also:
- tccpe.c: support weak attribute.  (I first tried to solve
  the problem above by using it but then didn't)
2017-02-18 09:51:23 +01:00
Christian Jullien 39b2afeb7c Temporary remove 76_dollards_in_identifiers when run on Windows as this test failes. To be checked why. 2017-02-18 08:12:00 +01:00
Christian Jullien 9bd04fa000 Makefile for Windows native tcc handles recent UNICODE support 2017-02-18 08:00:58 +01:00
YX Hao 86e3cd0c5a Add support for Unicode entries 'wmain' and 'wWinMain' on Windows
'-run' suported. argvs are converted.
But don't use compliled Unicode CLI exe-file to get inputs interactively in other codepage!
Please add other compliling supports than 'build-tcc.bat' (Who is good at them).
2017-02-17 21:09:26 +08:00
Christian Jullien f33801e25e Add entry to run tests2 tests 2017-02-17 08:05:38 +01:00
Christian Jullien d61985b37a tiny_impldef.exe was not built by Makefile 2017-02-16 07:01:44 +01:00
Christian Jullien 7b99c3ac2c Fix wrong name for 85 test. 2017-02-15 09:00:38 +01:00
Vlad Vissoultchev 67fe371f84 win32: build-tcc.bat: figure out correct bitness of cl.exe 2017-02-14 11:45:35 +02:00
Christian Jullien 5550e4336f Improve cygwin Makefile that now support TARGET=32/64 to force final version for 32/64 platform 2017-02-14 05:51:45 +01:00
grischka 43d9a7de9b updates & cleanups (tcc-doc/Changelog/TODO ...)
- tcc-doc.texi: commandline option info update
- Changelog/TODO: update
- tests/tcctest.py: removed
- tests/Makefile: weaktest fixed
- tests/tests2: some files renamed and/or converted to unix LF
- configure/Makefile: --enable-static option (no dll on win32)
- win32/build-tcc.bat: msvc support
- win32/tcc-win32.txt: build info update
- win32/vs2015/: VS solution removed
- win32/include/tcc/tcc_libm.h: #include statement fixed
- tcc.c: -include <file> option help info
- .gitignore: cleanup
2017-02-13 19:03:29 +01:00
grischka 13056da039 mems & leaks
- define_start: set above preprocess_start because now
  preprocess_start is defining macros.

- free "cmd_include_files"
- free defines always (after error-longjmps)
- close all files (after error-longjmps)
- tccpe.c: free imports always
- libtcc.c: call tcc_memstats only after all states have
  been deleted.
2017-02-13 18:23:55 +01:00
grischka a4a20360e9 fixes & cleanups
- tccgen.c/tcc.h: allow function declaration after use:
      int f() { return g(); }
      int g() { return 1; }
  may be a warning but not an error
  see also 76cb1144ef

- tccgen.c: redundant code related to inline functions removed
  (functions used anywhere have sym->c set automatically)

- tccgen.c: make 32bit llop non-equal test portable
  (probably not on C67)

- dynarray_add: change prototype to possibly avoid aliasing
  problems or at least warnings

- lib/alloca*.S: ".section .note.GNU-stack,"",%progbits" removed
  (has no effect)

- tccpe: set SizeOfCode field (for correct upx decompression)

- libtcc.c: fixed alternative -run invocation
      tcc "-run -lxxx ..." file.c
  (meant to load the library after file).
  Also supported now:
      tcc files ... options ... -run @ arguments ...
2017-02-13 18:23:43 +01:00
Christian Jullien 9817204d8a Detect native version from default gcc target. 2017-02-12 17:06:27 +01:00
grischka ec6a997f80 tccgen: yet another nocode_wanted fix
Some code in gen_opl was depending on a gvtst label
which in nocode_wanted mode is not set.

This was causing vstack leaks and crashes with for example

  long long ll;
  if (0)
      return ll - 10 < 0;
2017-02-12 13:21:20 +01:00
Christian Jullien 417a1ed384 Add Makefile to build native tcc 32/64 on Windows using cygwin 2017-02-12 12:14:27 +01:00
Michael Matz 983520d721 arm64: Fix 42_function_test
Like in 77d7ea04a some relocs need to be handled as possibly
needing a PLT/GOT slot in TCC until TCC can transfer dynamic relocs
to executables.
2017-02-11 10:16:55 +01:00
Michael Matz 15f990bf71 Fix testsuite invocations
The return code of $(FILTER) clobbers the return code of
TCC itself.  So just prepend messages to the generated output file
and ignore return codes.
2017-02-11 14:27:21 +01:00
grischka ee5425fe95 libtcc: support multiple -Wl,-rpath=...'s 2017-02-11 09:54:01 +01:00
grischka 362cafb471 arm: libtcc1.a needs gcc with -fPIC 2017-02-11 09:30:20 +01:00
Vlad Vissoultchev 910a6bc859 Add pre-build step in VS2015 projects to generate config.h from VERSION 2017-02-09 13:31:12 +02:00
grischka 5efa75d9b8 update VERSION to 0.9.27
Also:
- in tests: generate .expect files only if not yet present,
  because
  1) some files were adjusted manually
  2) switching git branche might change timestamps and
     cause unwanted update
2017-02-08 19:56:15 +01:00
grischka aa0a45be05 win32: build-tcc.bat: add some options
In particular:

-c <compiler> : Allow using tcc to compile itself
-i <dir>      : Create installation in dir

Summary:

usage: build-tcc.bat [ options ... ]
options:
  -c prog              use prog (gcc or tcc) to compile tcc
  -c "prog options"    use prog with options to compile tcc
  -t 32/64             force 32/64 bit default target
  -v "version"         set tcc version
  -i dir               install tcc into dir
  -d                   create tcc-doc.html too (needs makeinfo)
2017-02-08 19:53:49 +01:00
grischka e596b871a9 win32: include/winapi: remove more files
Also: use _assert, older msvcrt does not have _wassert
2017-02-08 19:53:02 +01:00
grischka 90316c7c26 tcc: don't use pstrcpy, fix win32 spanwn quoting
- we're now exporting tcc_prefixed symbols from libtcc only

- On windows, the msvcrt startup code would remove backslashes
  from commandline arguments such as
      -DFOO=\"foo\"
  which would appear in argv as
      -DFOO="foo"
  Therefor before passing these to spawnvp, we need to restore
  the backslashes.
2017-02-08 19:49:28 +01:00
grischka 68666eee2a tccgen: factor out gfunc_return
Also:
- on windows i386 and x86-64, structures of size <= 8 are
  NOT returned in registers if size is not one of 1,2,4,8.
- cleanup: put all tv-push/pop/swap/rot into one place
2017-02-08 19:45:31 +01:00
grischka f077d16c20 tccgen: gen_cast: cast FLOAT to DOUBLE
... to avoid precision loss when casting to int,
also when saving FLOATs to stack
2017-02-05 14:30:20 +01:00
grischka 3b84e61ead Revert "partial revert of the commit 4ad186c5ef61"
There seems nothing wrong.  With

    int t1 = 176401255;
    float f = 0.25;
    int t2 = t1 * f; // 176401255 * 0.25 = 44100313.75

according to the arithmetic conversion rules, the number
176401255 needs to be converted to float, and the compiler
can choose either the nearest higher or nearest lower
representable number "in an implementation-defined manner".

Which may be 176401248 or 176401264.  So as result both
44100312 and 44100313 are correct.

This reverts commit 664c19ad5e.
2017-02-05 14:30:19 +01:00
grischka 85fca9e924 tccrun: sort sections
Sort executable before other sections.

Also, apply RUN_SECTION_ALIGNMENT=63 for TCC_TARGET_I386
as well.
2017-02-05 14:00:42 +01:00
grischka ea2c36c5a9 tccrun: 'selinux' mmap: use only one mapping
In the previous implementation, the rx mapping was never
used.  Therefor it is assumed that it is not needed.

With only one mapping there is no reason to use a real
/tmp/.xxxx file either as we can use an anonymous mapping.
2017-02-05 13:58:14 +01:00
David Mertens 5420bb8a67 SECTION_ALIGNMENT -> RUN_SECTION_ALIGNMENT, and tweaks
Based on feedback from grischka, this commit
(1) updates the name of the alignment constant to be more specific
(2) aligns all sections, including the first (which previosly was
    not aligned)
(3) reduces the x86-64 alignment from 512 to 64 bytes.

The original x86-64 alignment of 512 bytes was based on testing.
After ensuring that the initial section is also aligned, the same
tests indicated that 64 bytes is sufficient.
2017-01-08 07:27:24 -05:00
David Mertens 5d1bc3fbd4 Architecture-specific section alignment
Tests found excessive cache thrashing on x86-64 architectures. The
problem was traced to the alignment of sections. This patch sets up
an architecture-specific alignment of 512 bytes for x86-64 and 16
bytes for all others. It uses preprocessor directives that, hopefully,
make it easy to tweak for other architectures.
2017-01-06 16:56:23 -05:00
Pavlas, Zdenek 0486939291 win32: support "-Wl,--large-address-aware" option 2016-12-30 03:01:33 -08:00
Avi Halachmi (:avih) 9b3e4c5895 tests: don't assume $(CC) is gcc
This also allows self hosting + testing when $(CC) is tcc.
2016-12-24 20:59:10 +02:00
grischka 71c5ce5ced tests: OOT build fixes etc.
tests/Makefile: fix out-of-tree build issues

Also:

- win64: align(16) MEM_DEBUG user memory
  on win64 the struct jmp_buf in the TCCState structure which we
  allocate by tcc_malloc needs alignment 16 because the msvcrt
  setjmp uses MMX instructions.

- libtcc_test.c: win32/64 need __attribute__((dllimport)) for
  extern data objects

- tcctest.c: exclude stuff that gcc does not compile
  except for relocation_test() the other issues are mostly ASM
  related.  We should probably check GCC versions but I have
  no idea which mingw/gcc versions support what and which don't.

- lib/Makefile: use tcc to compile libtcc1.a (except on arm
  which needs arm-asm
2016-12-20 18:05:33 +01:00
Michael Matz 4beb469c91 Fix pseudo leak
Once-allocated buffers (here a string) that aren't explicitely freed
at program end but rather freed at _exit about 1 nanosecond later
are regarded a leak with MEM_DEBUG, so explicitely free it.  Blaeh :-/
2016-12-20 05:42:25 +01:00
Michael Matz 42e2a67f23 Fix some code suppression fallout
Some more subtle issues with code suppression:
- outputting asms but not their operand setup is broken
- but global asms must always be output
- statement expressions are transparent to code suppression
- vtop can't be transformed from VT_CMP/VT_JMP when nocode_wanted

Also remove .exe files from tests2 if they don't fail.
2016-12-20 04:58:34 +01:00
grischka 559ee1e940 i386-gen: fix USE_EBX
Restore ebx from *ebp because alloca might change esp.

Also disable USE_EBX for upcoming release.

Actually the benefit is less than one would expect, it
appears that tcc can't do much with more than 3 registers
except with extensive use of long longs where the disassembly
looks much prettier (and shorter also).

Also: tccgen/expr_cond() : fix wrong gv/save_regs order
2016-12-19 00:33:01 +01:00
grischka d2332396e4 libtcc.c: -m option cleanup
handle mms-bitfields as sub-options of -m. (-mfloat-abi
is still special because it requires arguments)

tcc.c: help():
- list -mms-bitfields under 'Target specific options'

libtcc.c/MEM_DEBUG
- add check for past buffer writes
2016-12-18 22:57:03 +01:00
grischka a1c12b9fb9 tests: add memory leak test
Also ...

tcctest.c:
- exclude stuff that gcc doesn't compile on windows.

libtcc.c/tccpp.c:
- use unsigned for memory sizes to avoid printf format warnings
- use "file:line: message" to make IDE error parsers happy.

tccgen.c: fix typo
2016-12-18 22:05:42 +01:00
grischka f7fc4f02cf tccgen: nocode_wanted++/--
uses 'nocode_wanted' as a level couter instead of
'saved_nocode_wanted' everywhere.
2016-12-18 18:58:33 +01:00
grischka e5efd18435 tccgen: fix expr_cond for alt. nocode_wanted
making shure that both the active and the passive branches
do exacly the same thing.
2016-12-18 18:55:55 +01:00
grischka f843cadb6b tccgen: nocode_wanted alternatively
tccgen.c: remove any 'nocode_wanted' checks, except in
- greloca(), disables output elf symbols and relocs
- get_reg(), will return just the first suitable reg)
- save_regs(), will do nothing

Some minor adjustments were made where nocode_wanted is set.

xxx-gen.c: disable code output directly where it happens
in functions:
- g(), output disabled
- gjmp(), will do nothing
- gtst(), dto.
2016-12-18 18:53:21 +01:00
Michael Matz 77d7ea04ac Fix gawk miscompile
See testcase.  Function pointer use was hosed when the destination
function wasn't also called normally by the program.
2016-12-18 05:20:14 +01:00
Michael Matz cd9514abc4 i386: Fix various testsuite issues
on 32bit long long support was sometimes broken.  This fixes
code-gen for long long values in switches, disables a x86-64 specific
testcase and avoid an undefined shift amount.  It comments out
a bitfield test involving long long bitfields > 32 bit; with GCC layout
they can straddle multiple words and code generation isn't prepared
for this.
2016-12-15 17:53:09 +01:00
Michael Matz 3980e07fe5 arm64: Handle R_AARCH64_PREL32 again
This got lost when splitting reloc handling to individual files.
2016-12-15 17:49:57 +01:00
Michael Matz b155432b65 arm64: Fix largeptr test
VT_PTR needs to be handled like VT_LLONG.
2016-12-15 17:49:56 +01:00
Michael Matz b5b12b89a0 arm64: Fix a case of dead code suppression
82_nocode_wanted.c:kb_wait_2_1 was miscompiled on arm64.
2016-12-15 17:49:56 +01:00
Michael Matz f5ae4daa5f struct-layout: Allow lowering of member alignment
when an alignment is explicitely given on the member itself,
or on its types attributes then respect it always.  Was only
allowed to increase before, but GCC is allowing it.
2016-12-15 17:49:56 +01:00
Michael Matz 8859dc9e6d Support large alignment requests
The linux kernel has some structures that are page aligned,
i.e. 4096.  Instead of enlarging the bit fields to specify this,
use the fact that alignment is always power of two, and store only
the log2 minus 1 of it.  The 5 bits are enough to specify an alignment
of 1 << 30.
2016-12-15 17:49:56 +01:00
Michael Matz d815a0f658 struct-layout: cleanup code a bit 2016-12-15 17:49:56 +01:00
Michael Matz 23b257a8d2 bitfields: Fix MS layout some more
Another corner case:
  struct foo6_1
  {
    char x;
    short p:8;
    short :0;
    short :0;
    short p2:8;
    char y;
  };

In MS layout the second anon :0 bit-field does _not_ adjust size or
alignment of the struct again.  The first one does, though.
2016-12-15 17:49:56 +01:00
Michael Matz ed680da951 bitfields: fix PCC layout
Fixes some corner cases in PCC layout.  Testcases coming
up.
2016-12-15 17:49:56 +01:00
Michael Matz bd69bce20f bitfields: Implement MS compatible layout
Bit-fields are layed out differently in visual C, this implements
a compatible mode.  Checked against Visual C/C++ 2016.
Unfortunately the GCC implementation of MS layout (behind
-mms-bitfields) actually is different, and hence not compatible
with MS in all cases :-/
2016-12-15 17:49:56 +01:00
Michael Matz 78c7096162 Fix struct layout some more
Anonymous sub-sub-members weren't handled correctly.  Bit-fields
neither: this implements PCC layout for now.  It temporarily disables
MS-compatible bit-field layout.
2016-12-15 17:49:56 +01:00
Michael Matz ddecb0e685 Split off record layouting
Such struct decl:

  struct S { char a; int i;} __attribute__((packed));

should be accepted and cause S to be five bytes long (i.e.
the packed attribute should matter).  So we can't layout
the members during parsing already.  Split off the offset
and alignment calculation for this.
2016-12-15 17:49:56 +01:00
Michael Matz 5d6a9e797a x86-asm: Fix segfault
We need to access cur_text_section, not text_section.
2016-12-15 17:49:56 +01:00
Michael Matz 22f5fccc2c Fix 64bit enums and switch cases
See testcases.  We now support 64bit case constants.  At the same time
also 64bit enum constants on L64 platforms (otherwise the Sym struct
isn't large enough for now).  The testcase also checks for various
cases where sign/zero extension was confused.
2016-12-15 17:49:56 +01:00
Michael Matz 3e77bfb6e9 tccpp: Fix token pasting
See testcase.  We must always paste tokens (at least if not
currently substing a normal argument, which is a speed optimization
only now) but at the same time must not regard a ## token
coming from argument expansion as the token-paste operator, nor
if we constructed a ## token due to pasting itself (that was already
checked by pp/01.c).
2016-12-15 17:49:56 +01:00
Michael Matz 3db037387c libtcc1: Don't use stdlib functions
libtcc1 is the compiler support library and therefore needs
to function in a freestanding environment.  In particular
it can't just use fprintf or stderr, which it was on x86-64
(but only when compiled by GCC).  The tight integration between
libtcc1 and tcc itself makes it impossible to ever reach that
case so the abort() there is enough.  abort() is strictly speaking
also not available in a freestanding environment, but it often is
nevertheless.
2016-12-15 17:49:56 +01:00
Michael Matz d042e71e9f Fix miscompile with dead switches
In certain very specific situations (involving switches
with asms inside dead statement expressions) we could generate
invalid code (clobbering the buffer so much that we generated
invalid instructions).  Don't emit the decision table if the
switch itself is dead.
2016-12-15 17:49:55 +01:00
Michael Matz 7ae35bf1bb Handle multiple -O options
the last one wins, i.e. "-O2 -O0" does _not_ set __OPTIMIZ__.
2016-12-15 17:49:55 +01:00
Michael Matz a158260e84 build: Respect CPPFLAGS override
so that e.g. make CPPFLAGS=-DSOMETHING works.
2016-12-15 17:49:55 +01:00
Michael Matz 235711f3d3 64bit: Fix addends > 32 bits
If a symbolic reference is offsetted by a constant > 32bit
the backends can't deal with that, so don't construct such
values.
2016-12-15 17:49:55 +01:00
Michael Matz a2a596e767 x86-64-asm: Accept high register in clobbers
The callee saved registers (among them r12-r15) really need
saving/restoring if mentioned in asm clobbers, even if TCC
itself doesn't use them.  E.g. the linux kernel relies on that
in its switch_to() implementation.
2016-12-15 17:49:55 +01:00
Michael Matz ddd461dcc8 Fix initializing members multiple times
When intializing members where the initializer needs relocations
and the member is initialized multiple times we can't allow
that to lead to multiple relocations to the same place.  The last
one must win.
2016-12-15 17:49:53 +01:00
Michael Matz f081acbfba Support local register variables
Similar to GCC a local asm register variable enforces the use of a
specified register in asm operands (and doesn't otherwise
matter).  Works only if the variable is directly mentioned as
operand.  For that we now generally store a backpointer from
an SValue to a Sym when the SValue was the result of unary()
parsing a symbol identifier.
2016-12-15 17:47:13 +01:00
Michael Matz 3bc9c325c5 Fix const folding of 64bit pointer constants
See testcase.
2016-12-15 17:47:12 +01:00
Michael Matz 0b0e64c2c9 x86-asm: Correct register size for pointer ops
A pointer is 64 bit as well, so it needs a full
register for register operands.
2016-12-15 17:47:12 +01:00
Michael Matz 7ab35c6265 struct-init: Copy relocs for compound literals
When copying the content of compound literals we must
include relocations as well.
2016-12-15 17:47:12 +01:00
Michael Matz 0bca6cab06 x86_64-asm: fix copy-out registers
If the destination is an indirect pointer access (which ends up
as VT_LLOCAL) the intermediate pointer must be loaded as VT_PTR,
not as whatever the pointed to type is.
2016-12-15 17:47:12 +01:00
Michael Matz ad723a419f x86_64: Add -mno-sse option
This disables generation of any SSE instructions (in particular
in stdarg function prologues).  Necessary for kernel compiles.
2016-12-15 17:47:12 +01:00
Michael Matz b5669a952b x86-64: relocation addend is 64bit
Some routines were using the wrong type (int) in passing addends,
truncating it.  This matters when bit 31 isn't set and the high
32 bits are set: the truncation would make it unsigned where in
reality it's signed (happen e.g. on the x86-64 with it's load
address at top-2GB).
2016-12-15 17:47:12 +01:00
Michael Matz 975c74c1f5 x86-64: Prefer 32S relocations
This target has _32 and _32S relocs (the latter being for signed
32 bit entities).  All instruction displacements have to use
the 32S variants.  Normal references like
  .long s
normally would use the _32 variant.  For normal executables this
doesn't matter.  For shared libraries neither (which use PC-relative
relocs).  But it matters for things like the kernel that are linked
to high addresses (signed ones).  There the GNU linker would error
out on overflow for the _32 variant.

To keep life simple we simply switch from _32 to _32S altogether.
Strictly speaking it's still wrong, but in practice using _32 is
more often wrong than using _32S ;)
2016-12-15 17:47:12 +01:00
Michael Matz ad8e14b740 opt: Don't emit inline functions from dead code
Inside dead code don't regard inline functions as being
referenced.
2016-12-15 17:47:12 +01:00
Michael Matz ce55d03eef Handle __builtin_extract_return_addr
Our architectures don't need anything special for this
builtin, just pass through the argument.
2016-12-15 17:47:12 +01:00
Michael Matz fb933ae0eb opt: constprop also 'cond && 0'
We didn't handle constants in logical expressions when they weren't
the first operand.  Some reordering in the loop structure is enough
to handle them.
2016-12-15 17:47:12 +01:00
Michael Matz ca435dc2e3 opt: Make break and goto not fallthrough
As we can optimize dead code a bit already it's fitting
to disable code emission after break and goto.
2016-12-15 17:47:12 +01:00
Michael Matz 31c7ea0165 opt: Start optimizing dead code a bit
If a condition is always zero/non-zero we can omit the
then or else code.  This is complicated a bit by having to
deal with labels that might make such code reachable without
us yet knowing during parsing.
2016-12-15 17:47:12 +01:00
Michael Matz b303a00ce0 Revert "Reject jumping inside stmtexprs"
Not fully thought out.  You can't jump inside stmt exprs,
but you can jump out of them.  So there's a difference
between undefined but declared labels at the end of stmt
exprs and those defined inside.  Additionally it should
also be checked if a label defined inside a stmt expr
was tentatively created as declared from outside.

I'm not prepared doing that right now, so simply revert.

This reverts commit 9160e4cab9147d77840cc44a285031fdb4640cf9.
2016-12-15 17:47:11 +01:00
Michael Matz d4d3144e75 Factor out const condition detection
Creating condition_3way for this.
2016-12-15 17:47:11 +01:00
Michael Matz 892c3d996f Reject jumping inside stmtexprs
One can't jump into statement expressions from outside
them, like the following:

  int i = ({ label: foo(); 42; });
  goto label;

We reject this by making the labels simply not available
outside (GCC has a nicer error message about jumping into
a statement expression).
2016-12-15 17:47:11 +01:00
Michael Matz 1602998751 Fix more nocode_wanted jump problems
In statement expression we really mustn't emit backward jumps
under nocode_wanted (they will form infinte loops as no expressions
are evaluated).  Do-while and explicit loop with gotos weren't
handled.
2016-12-15 17:47:11 +01:00
Michael Matz f2a071e808 Fix aliases on 64 bit
Use correct width ELF structure.
2016-12-15 17:47:11 +01:00
Michael Matz 9656560f14 Fix sizeof(char[a])
The sizes of VLAs need to be evaluated even inside sizeof,
i.e. when nocode_wanted is set.
2016-12-15 17:47:11 +01:00
Michael Matz 49bb5a7e06 Fix __builtin_constant_p(1000/x)
was incorrectly treated as constant because the vpop removed
all traces of non-constness.
2016-12-15 17:47:11 +01:00
Michael Matz 5bd8aeb917 tccasm: Support refs to anon symbols from asm
This happens when e.g. string constants (or other static data)
are passed as operands to inline asm as immediates.  The produced
symbol ref wouldn't be found.  So tighten the connection between
C and asm-local symbol table even more.
2016-12-15 17:47:11 +01:00
Michael Matz dd57a34866 tccasm: Don't ignore # in preprocessor directives
Our preprocessor throws away # line-comments in asm mode.
It did so also inside preprocessor directives, thereby
removing stringification.  Parse defines in non-asm mode (but
retain '.' as identifier character inside macro definitions).
2016-12-15 17:47:11 +01:00
Michael Matz e7ef087598 x86-asm: Accept all 32bit immediates
In particular don't care if they're signed or unsigned, they're all
acceptable as immediates.
2016-12-15 17:47:11 +01:00
Michael Matz 372f4b6a4e Fix enum bitfields passed to stdarg functions
VT_ENUM types use the .ref member and can be VT_BITFIELD,
so we need to copy it as well.  Simply do it always.
2016-12-15 17:47:11 +01:00
Michael Matz d720865fb6 Addresses of non-weak symbols are non-zero
Use this fact in some foldings of comparisons.  See testcase.
2016-12-15 17:47:10 +01:00
Michael Matz be6d8ffc10 Fix access-after-free with statement expressions
The return value of statement expressions might refer to local
symbols, so those can't be popped.  The old error message always
was just a band-aid, and since disabling it for pointer types it
wasn't effective anyway.  It also never considered that also the
vtop->sym member might have referred to such symbols (see the
testcase with the local static, that used to segfault).

For fixing this (can be seen better with valgrind and SYM_DEBUG)
simply leave local symbols of stmt exprs on the stack.
2016-12-15 17:47:10 +01:00
Michael Matz d0d25ec7df tccpp: Allow computed include like 42.h
The include directive needs to be parsed as pp-tokens, not
as token (i.e. no conversion to TOK_STR or TOK_NUM).  Also fix
parsing computed includes using quoted strings.
2016-12-15 17:47:10 +01:00
Michael Matz 0381387640 x86-asm: Correctly infer register size for bools
Register operands of type _Bool weren't correctly getting
the 8-bit sized registers (but rather used the default 32-bit
ones).
2016-12-15 17:47:10 +01:00
Michael Matz 9e0af6d2b5 x86-64-asm: Implement cmpxchg16b 2016-12-15 17:47:10 +01:00
Michael Matz ca8c1cd643 x86-64: Allow loads from some structs/unions
GCC allows register loads for asms based on type mode,
and correctly sized structs/union have an allowed mode
(basically 1,2,4,8 sized aggregates).
2016-12-15 17:47:10 +01:00
Michael Matz 9ae10cad1f tccasm: Lookup C symbols from ASM blocks
It's now possible to use symbols defined in C code to be used
from later inline asm blocks.  See testcase.
2016-12-15 17:47:10 +01:00
Michael Matz c4edfb4e08 tccasm: Implement .set sym, expr
That, as well as "sym = expr", if expr contains symbols.
Slightly tricky because a definition from .set is overridable,
whereas proper definitions aren't.

This doesn't yet allow using this for override tricks from C
and global asm blocks because the symbol tables from C and asm
are separate.
2016-12-15 17:47:10 +01:00
Michael Matz 34fc6435ee enums and ints are compatible
But like GCC do warn about changes in signedness.  The latter
leads to some changes in gen_assign_cast to not also warn about
  unsigned* = int*
(where GCC warns, but only with extra warnings).
2016-12-15 17:47:10 +01:00
Michael Matz b1a906b970 enums and ints are compatible 2016-12-15 17:47:10 +01:00
Michael Matz c0368604e1 x86-64-asm: Fix ltr/str and push/pop operands
str accepts rm16/r32/r64, and push/pop defaults to 64 when given
memory operands (to 32 on i386).
2016-12-15 17:47:10 +01:00
Michael Matz 45b24c37a0 x86-64-asm: Implement high %cr registers 2016-12-15 17:47:09 +01:00
Michael Matz 4e46c22d5c struct-init: Support range inits for local vars
Implement missing support for range init for local variables.
2016-12-15 17:47:09 +01:00
Michael Matz 4cb7047f0f x86-64-asm: Support high registers %r8 - %r15
This requires correctly handling the REX prefix.
As bonus we now also support the four 8bit registers
spl,bpl,sil,dil, which are decoded as ah,ch,dh,bh in non-long-mode
(and require a REX prefix as well).
2016-12-15 17:47:09 +01:00
Michael Matz 8765826465 inline-asm: Accept "flags" clobber 2016-12-15 17:47:09 +01:00
Michael Matz b7ca74577b struct-init: Allow member initialization from qualified lvalues
See testcase.
2016-12-15 17:47:09 +01:00
Michael Matz 9e86ebee94 struct-init: Correctly parse unnamed member initializers
For
  union U { struct {int a,b}; int c; };
  union U u = {{ 1, 2, }};
The unnamed first member of union U needs to actually exist in the
structure so initializer parsing isn't confused about the double braces.
That means also the a and b members must be part of _that_, not of
union U directly.  Which in turn means we need to do a bit more work
for field lookup.

See the testcase extension for more things that need to work.
2016-12-15 17:47:09 +01:00
Michael Matz 21da73c383 struct-init: Cleanup some more
Some parameters aren't actually necessary.  Also join the
two parsing loops for the initializer list of arrays and structs.
2016-12-15 17:47:09 +01:00
Michael Matz 7bf323843e struct-init: Cleanup
Remove dead code and variables.  Properly check for unions when
skipping fields in initializers.  Make tests2/*.expect depend
on the .c files so they are automatically rebuilt when the latter
change.
2016-12-15 17:47:09 +01:00
Michael Matz ed7d54651d struct-init: Implement initializing subaggregates
E.g. "struct { struct S s; int a;} = { others, 42 };"
if 'others' is also a 'struct S'.  Also when the value is a
compound literal.  See added testcases.
2016-12-15 17:47:09 +01:00
Michael Matz 968bccdd2a struct-init: Reimplement
Start reimplementing the whole initializer handling to be
conforming to ISO C.  This patch just reimplements current
functionality to prepare for further changes, all tests pass.
2016-12-15 17:47:09 +01:00
Michael Matz 5d0c16a884 Support attribute between double pointer stars
"int * __attribute__((something)) *" is supported by GCC.
2016-12-15 17:47:09 +01:00
Michael Matz 662338f116 Fix function to pointer conversion
This snippet is valid:
  void foo(void);
  ... foo + 42 ...
the function designator is converted to pointer to function
implicitely.  gen_op didn't do that and bailed out.
2016-12-15 17:47:08 +01:00
Michael Matz e034853b38 Fix parsing array typedefs of unknown size
This must compile:
 typedef int arrtype1[];
 arrtype1 sinit19 = {1};
 arrtype1 sinit20 = {2,3};
and generate two arrays of one resp. two elements.  Before the fix
the determined size of the first array was encoded in the type
directly, so sinit20 couldn't be parsed anymore (because arrtype1
was thought to be only one element long).
2016-12-15 17:47:08 +01:00
Michael Matz b7e0b693a6 tccpp: Implement __BASE_FILE__ macro
Like __FILE__ but always refers to the command line file name also
from inside headers.
2016-12-15 17:47:08 +01:00
Michael Matz 8a1a2a6033 Implement __builtin_choose_expr
Follows GCC implementation.
2016-12-15 17:47:08 +01:00
Michael Matz 10e4db45dc x86-asm: Implement prefetchw opcode 2016-12-15 17:47:08 +01:00
Michael Matz 5692716770 x86-asm: Fix lar opcode operands
lar can accept multiple sizes as well (wlx), like lsl.  When using
autosize it's important to look at the destination operand first;
when it's a register that one determines the size, not the input
operand.
2016-12-15 17:47:08 +01:00
Michael Matz e3f2a68311 tcc-asm: Parse .size directive correctly
When the .size directive was closed with a ';' tcc eat everything after
it up to lineend.
2016-12-15 17:47:08 +01:00
Michael Matz 6a5ec8cb3c x86-asm: More opcodes
Some new opcodes and some aliases: ljmp[wl], prefetch{nta,t0,t1,t2},
bswap[lq], sysretq, swapgs.
2016-12-15 17:47:08 +01:00
Michael Matz d9d029006c x86-asm: Add [sl][ig]dtq opcodes
GAS has alias lgdtq for lgdt (similar for saves and GDT).  It doesn't
have the same for LDT.
2016-12-15 17:47:08 +01:00
Michael Matz 75e8df126f inline asm: Accept 'R' constraint
This is like 'r' but only accepts the eight legacy regs.  Currently
that's the same as 'r' because we don't support the high ones.
2016-12-15 17:47:08 +01:00
Michael Matz f6c1eb10e2 x86-asm: Implement fxrstorq and fxsaveq 2016-12-15 17:47:08 +01:00
Michael Matz 2b618c1ab4 Fix parsing attributes for struct decls
Given this code:

  struct __attribute__((...)) Name {...};

TCC was eating "Name", hence generating an anonymous struct.
It also didn't apply any packed attributes to the parsed
members.  Both fixed.  The testcase also contains a case
that isn't yet handled by TCC (under a BROKEN #define).
2016-12-15 17:47:08 +01:00
Michael Matz 7e51546624 x86-asm: Implement clflush opcode 2016-12-15 17:47:08 +01:00
Michael Matz e5f4f8d0e7 inline asm: Accept "e" constraint
This is meant to be a (sign-extended) 32bit constant (possibly
symbolic).  We don't do any checks and simply regard it as "i".
2016-12-15 17:47:08 +01:00
Michael Matz bbce31552e inline asm: accept concatenated strings in constraints
This really should be handled implicitly in the preprocessor,
but for now this is enough.
2016-12-15 17:47:08 +01:00
Michael Matz f9423ff3fa inline asm: Fix 'P' and accept some r<nr> registers
A 'P' template modifier should avoid adding a '$' to literal
arguments.  Also accept the numbered r8+ registers in an inline
asm clobber list (ignoring them for now).
2016-12-15 17:47:07 +01:00
Michael Matz 10c3514889 Accept symbols in initializers also on 64 bit
Those should use long or long long type, and generate a 64bit reloc.
2016-12-15 17:47:07 +01:00
Michael Matz 920474115c x86-64-asm: More opcodes
Implement some more opcodes, syscall, sysret, lfence, mfence, sfence.
2016-12-15 17:47:07 +01:00
Michael Matz 1a5eacb445 tccasm: Implement compare expressions
I.e. implement < > <= >= == !=.  Comparisons are signed and result
is -1 if true, 0 if false.
2016-12-15 17:47:07 +01:00
Michael Matz ff5561ff7d x86-64-asm: Accept expressions for .quad
The x86-64 target has 64bit relocs, and hence can accept
generic expressions for '.quad'.
2016-12-15 17:47:07 +01:00
Michael Matz 253afeed1e inline asm: Accept 'p' constraint and 'P' template mod
'p' is conservatively the same as 'r' and 'P' as template
modifier can be ignored in TCC.
2016-12-15 17:47:07 +01:00
Michael Matz 63e3ff7cca tccasm: Accept .balign 2016-12-15 17:47:07 +01:00
Michael Matz 8e4da42384 Accept more asm expressions
In particular subtracting a defined symbol from current section
makes the value PC relative, and .org accepts symbolic expressions
as well, if the symbol is from the current section.
2016-12-15 17:47:07 +01:00
Michael Matz c82e52d55b tccasm: Implement .pushsection and .popsection 2016-12-15 17:47:06 +01:00
Michael Matz 6763b02abc Accept empty struct member decls
struct S { /*nothing*/; int a; };

is an acceptable struct declaration, there may be stray semicolons
in the member list.
2016-12-15 17:47:06 +01:00
Michael Matz d5d881d9e9 x86-asm: Accept 'q' modifier
In inline extended asm '%q1' refers to the 64bit register of operand 1.
2016-12-15 17:47:06 +01:00
Michael Matz 8531de319a Accept concatenated strings in attributes
attribute(section("one" "two")) should be accepted (the section
name being "onetwo"), it's normal string concatenation.
2016-12-15 17:47:06 +01:00
Michael Matz b6799ccd2e Accept -Wp,args
These are preprocessor cmdline arguments, but even in GCC they
aren't specified but rather left as being subject to changes.
Nobody should use them, but let's to a half-assed attempt
at accepting them.
2016-12-15 17:47:06 +01:00
Michael Matz 2b3c7d2287 Change dependency file format a bit
The linux fixdep parse is very stupid and only recognizes
a target token when ':' is part of it.  A space is permitted
in Makefile syntax, but it's easier to change our emitter
than all fixdep parsers out there.
2016-12-15 17:47:06 +01:00
Michael Matz b285fc50f3 Add --param, reject -mARG if ARG not 32 or 64 2016-12-15 17:47:06 +01:00
Michael Matz 9285149548 Implement -include cmdline option
This option includes a file as if '#include "file"' is the first
line of compiled files.  It's processed after all -D/-U options
and is processed per input file.
2016-12-15 17:47:06 +01:00
Michael Matz 21d2b71b5c Free defines before gen_inline_functions
gen_inline_functions uses the macro facilities of the preprocessor,
which would interact when macros would still be defined in a
different pre-processor implementation I'm working on.
So always free defines before generating inline functions, they
are all macro expanded already.
2016-12-15 17:47:06 +01:00
Michael Matz 38e5cf0983 tccpp: Fix macro_is_equal
When tokens in macro definitions need cstr_buf inside get_tok_str,
the second might overwrite the first (happens when tokens are
multi-character non-identifiers, see testcase) in macro_is_equal,
failing to diagnose a difference.  Use a real local buffer.
2016-12-15 17:47:05 +01:00
Michael Matz 8080401ab0 tccpp: free defines also with PP_BENCH
When benchmarking preprocessing of multiple files we need to
free the defines like when not benchmarking.
2016-12-15 17:47:05 +01:00
Michael Matz e2f489aaff x86-asm: Get rid of OPC_JMP and OPC_SHORTJMP
Those two insn types are nicer to handle as operand types, because
the pressure for bits on instr_type is higher than for operands.
2016-12-15 17:47:05 +01:00
Michael Matz 4094f7c5fc x86-64-asm: Tidy 2016-12-15 17:47:05 +01:00
Michael Matz 58963828ab x86-asm: Correct mem64->xmm movq
Now we can express prefixes with 0x0fxx opcodes we can correct the
movq mem64->xmm opcode, and restrict the movq xmm->mem64 movq to
not invalidly accept mmx.
2016-12-15 17:47:05 +01:00
Michael Matz 5a222588a8 x86-asm: Remove OPC_D16
Now that we can store prefixes even for 0x0fXX opcodes we can remove
the OPC_D16 bit.
2016-12-15 17:47:05 +01:00
Michael Matz 8a10a442ff x86-asm: Fix register order
Inserting random registers in the middle of the 8-blocks
breaks register assignment.
2016-12-15 17:47:05 +01:00
Michael Matz bde802df29 x86-asm: Reorganize instr_type
Disjoint instruction types don't need to be a bit field, so
introduce an enumeration (3 bits).  Also the 0x0f prefix can
be expressed by a bit, doesn't need a byte in the opcode field.
That enables to encode further prefixes still in 16 bit.
To not have to touch all insns do some macro fiddling filtering
out a 0x0f byte in the second position.
2016-12-15 17:47:05 +01:00
Michael Matz 4af6e087dd x86-asm: move stats code
The old place (tccasm.c) didn't have access to the variables anymore
and was ifdefed out.  Move it to i386-asm.c.
2016-12-15 17:47:05 +01:00
Michael Matz ed35ac841b x86-asm: Add more SSE2 instructions
In particular those that are extensions of existing mmx (or sse1)
instructions by a simple 0x66 prefix.  There's one caveat for
x86-64: as we don't yet correctly handle the 0xf3 prefix
the movq mem64->xmm is wrong (tested in asmtest.S).  Needs
some refactoring of the instr_type member.
2016-12-15 17:47:05 +01:00
grischka 2b7ee000cd tests: add .so/.dll creation test
Also remove bitfield test from tcctest.c because gcc
versions don't agree among each other.
2016-12-15 17:04:07 +01:00
grischka ca92bfc3c6 tccelf: some linker cleanup
- generate and use SYM@PLT for plt addresses
- get rid of patch_dynsym_undef hack (no idea what it did on FreeBSD)
- use sym_attrs instead of symtab_to_dynsym
- special case for function pointers into .so on i386
- libtcc_test: test tcc_add_symbol with data object
- move target specicic code to *-link.c files
- add R_XXX_RELATIVE (needed for PE)
2016-12-15 17:01:22 +01:00
Thomas Preud'homme fe6453f8f0 Use functions to get relocation info
MSVC does not support array designator so cannot compile source using
relocs_info. This commit replace the relocs_info array into a set of
functions, each returning the value given by a given field of the struct
reloc_info.
2016-12-10 18:14:10 +00:00
Thomas Preud'homme d31226c873 Remove now useless pltoff_addend reloc info
Last use for pltoff_addend field of relocs_info array was removed in
commit 25927df3b7. It is now useless so
this commit removes it and all initialization related to it.
2016-12-10 18:13:23 +00:00
Thomas Preud'homme ee2108d07d Add missing relocation info for C67 target
Fill in relocs_info table for C67 and fix R_C60_NUM value to really be
greater than all relocation values known to TCC.
2016-12-10 17:31:20 +00:00
Thomas Preud'homme 11747fe5d0 Error out in put_got_entry if no dynamic symbol 2016-12-10 19:22:02 +08:00
Thomas Preud'homme dfed9babfc Allow PLT/GOT entry for weak static symbol 2016-12-10 19:12:36 +08:00
Thomas Preud'homme 0bf262864c Fix PLT creation for i386
i386 target does not have PC relative loads. Its ABI therefore require
ebx register to points to the GOT when executing a PLT entry. This means
that PLT entry cannot be used transparently, the compiler needs to
expect execution of a PLT entry to be able to use one, that is a PLT
entry should only be created if the relocation explicitely asks for it
(eg. R_386_PLT32).

This patch creates a new target macro PCRELATIVE_DLLPLT to indicate
whether a target can do a PC relative load in PLT entry when building a
dynamic library. Executable do not normally pose a problem because they
are loaded at a fixed address and thus the absolute address of GOT can
be used.

Note that in such a case, if the compiler does not use a PLT aware
relocation for external access then the code relocation will fall on the
dynamic loader since there is no PLT entry to relocate too.
2016-12-10 09:44:09 +00:00
Edmund Grimley Evans e0fe69050d arm64: Fix regression introduced by 6245db9. 2016-12-05 23:29:25 +00:00
Thomas Preud'homme 2372639e9d Fix set but not used error in arm64-link.c 2016-12-05 21:34:30 +00:00
Thomas Preud'homme 3811794048 Fix tcc_error params for R_AARCH64_(JUMP|CALL)26 2016-12-05 21:34:30 +00:00
Thomas Preud'homme e22249b81c Error on unrecognized relocations 2016-12-05 20:58:00 +00:00
Thomas Preud'homme 557c5c1f11 Add relocs_info array to c67 backend 2016-12-05 20:52:02 +00:00
Thomas Preud'homme 59391d5520 Fix relocs_info declaration in tcc.h
C standard specifies that array should be declared with a non null size
or with * for standard array. Declaration of relocs_info in tcc.h was
not respecting this rule. This commit add a R_NUM macro that maps to the
R_<ARCH>_NUM macros and declare relocs_info using it. This commit also
moves all linker-related macros from <arch>-gen.c files to <arch>-link.c
ones.
2016-12-05 20:51:10 +00:00
Thomas Preud'homme 097cf3aa5e Control symbol table of which to relocate symbols
Pass pointer to symbol table to relocate the symbols of in relocate_syms
2016-12-03 17:26:51 +00:00
Thomas Preud'homme c4bec037be Code simplification in relocate_syms 2016-12-03 17:26:51 +00:00
Thomas Preud'homme 25927df3b7 Consolidate all relocations in relocate_section
Static relocation of functions in dynamic libraries must use the PLT
entry as the target. Before this commit, it used to be done in 2 parts
for ARM, with the offset of the PLT entry from the beginning of the PLT
being put in the relocated place in build_got_entries () and then the
address of the PLT being added in relocate_section.

This led to code dealing with reading the offset of a bl instruction in
build_got_entries. Furthermore, the addition of the address of the start
of the PLT was done based on the relocation type which does not convey
whether a PLT entry should be used to reach the symbol.

This commit moves the decision to use the PLT as the target in
relocate_section, therefore having the instruction aware code contained
to the target-specific bit of that function (in <target>-link.c).

Note that relocate_syms is *not* the right place to do this because two
different relocations for the same symbol can make different decision.
This is the case in tcc -run mode where the static and dynamic
relocation are done by tcc.

Storing the PLT entry address in the symbol's st_value field and relying
on the specific relocation type being used for dynamic relocation would
work but the PLT entry address would then appear in the static symbol
table (symtab). This would also make the static symbol table entry
differ from the dynamic symbol table entry.
2016-12-03 17:26:51 +00:00
Thomas Preud'homme 2c38800bbe Allow to get sym attr and fail if no entry
Change alloc_sym_attr into get_sym_attr and add a parameter to control
whether to allocate a new symattr structure or return NULL if symbol is
not found;
2016-12-03 17:26:51 +00:00
Thomas Preud'homme a11b0a67e3 Consolidate GOT creation in build_got_entries
Currently GOT/PLT creation happens in two locations depending on whether
the GOT/PLT [entry] is required by the symbol or the relocation:

- bind_exe_dynsym for relocations to undefined symbol
- build_got_entries/put_got_entry for relocations that require a GOT/PLT
  entry

This commit consolidate GOT/PLT creation in build_got_entries by
reducing bind_exe_dynsym's job to create a dynamic symbol for undefined
symbols. build_got_entries then invoke put_got_entry if the symbol being
relocated is undefined or the relocation asks for a PLT or GOT [entry].
put_got_entry is also modified to only export a symbol in the dynamic
symbol table when we are in the case of PLT/GOT [entry] required by the
relocation (since undefined symbol are already exported by
bind_exe_dynsym).
2016-12-03 17:26:51 +00:00
Thomas Preud'homme 1c811a4d1d Make build_got_entries more target independent
Factor most of common logic between targets in build_got_entries by
defining target specific info into structures in the backends.
2016-12-03 17:26:51 +00:00
Thomas Preud'homme 523b55d82d Only create GOT or GOT entry when needed
Currently we always build a GOT when we recognize a relocation in
build_got_entries even if the relocation does not require one. In the
same spirit, when the relocation does require one we always create a GOT
entry even if not entry is necessary. This patch restricts the creation
of a GOT and a GOT entry to relocations that needs it, ie:
- do not create a GOT if relocation is not related to GOT and symbol is
  not UNDEF
- do not create a GOT entry if relocation only relates to beginning of
  GOT
2016-12-03 17:26:51 +00:00
Thomas Preud'homme 6cd23d1d8c Recognize more relocations as needing GOT/PLT entry 2016-12-03 17:26:51 +00:00
Thomas Preud'homme cb273fdad8 Do section relocation in architecture backend 2016-12-03 17:26:51 +00:00
Thomas Preud'homme 60374d01ae Add address of GOT + 8 in PLT + 16 and fix PLT0
On ARM targets, the jump to ld.so resolution routine is done in PLT0 by
loading the offset to the GOT found in PLT+16 and from there loading the
address in GOT+8 and jumping to it.

Currently tcc starts the first regular PLT entry at PLT+16 which thus
does not contain the offset to the GOT. This commit fixes that.

Note that calls via PLT still worked nonetheless because of some missing
dynamic tag which makes ld.so behaves as if RTLD_BIND_NOW was specified
in the environment for all executable created by tcc.
2016-12-03 17:26:51 +00:00
Thomas Preud'homme f924d0ca96 Improve put_got_entry doc and structure 2016-12-03 17:26:51 +00:00
Thomas Preud'homme 64b5ee2dea Rename add_elf_sym to set_elf_sym
add_elf_sym is a confusing name because it is not clear what the
function does compared to put_elf_sym. As a matter of fact, put_elf_sym
also adds a symbol in a symbol table. Besides, "add_elf_sym" fails to
convey that the function can be used to update a symbol (for instance
its value). "set_elf_sym" seems like a more appropriate name: it will
set a symbol to a given set of properties (value, size, etc.) and create
a new one if non exist for that name as one would expect.
2016-12-03 17:26:51 +00:00
Thomas Preud'homme 9e6610b0aa Improve comments for symbol export and binding 2016-12-03 17:26:51 +00:00
Thomas Preud'homme e9769a7249 Do not add symbol if it is already there
Do not create a new symbol in add_elf_sym if a symbol with same properties
(value, size, info, etc.) already exists. This prevents symbols from
being exported twice in the dynamic symbol table.
2016-12-03 17:26:51 +00:00
Thomas Preud'homme bf692af31b Fix error logic for undefined reference in library
Prior to this patch, an error would only be given when a library has an
unresolved undefined symbol if there is no undefined reference for the
same symbol in the executable itself. This patch changes the logic to
check both that the executable has the symbol in its static symbol table
*and* that it is defined to decide if the error path should be followed.
2016-12-03 17:26:51 +00:00
root ccf9ed7d54 Clear SHF_GROUP flag when linking
SHF_GROUP flag set on a section indicates that it is part of a section
group and that if the section is removed, the other sections in the same
group should be removed as well [1]. Since section group are guide for
the linking process, they do not have any meaning after linking has
occured. TCC rightfully [2] discard such sections (by not recognizing the
section type) but keeps the SHF_GROUP flag set on sections that were
part of a section group which confuses binutils (objdump and gdb at
least). Clearing that bit makes objdump and gdb accept binaries created
by TCC.

[1] https://docs.oracle.com/cd/E19683-01/816-1386/chapter7-26/index.html
[2] GNU ld does the same
2016-12-03 17:26:50 +00:00
Christian Jullien ed99f3608d Remove warning when __builtin_frame_address is used with gcc >= 6. 2016-11-30 06:18:48 +01:00
David Mertens d2e2f42382 Implement gcc bitfield algorithm; add -mms-bitfields 2016-11-28 09:01:12 -05:00
David Mertens 3c68a8c6c0 Minor grammar fixes to docs 2016-11-28 08:59:53 -05:00
grischka 0d14e7e698 configure: prefer lib64 on 64-bit platforms
use lib64 if
- "/usr/lib/multi-arch-triplet" does not work and
- we are on a 64-bit platform and
- lib64 exists and does contain crti.o
2016-11-28 14:48:54 +01:00
grischka a52a39179a tccelf: introduce add32/64le() 2016-11-20 14:52:56 +01:00
grischka 4a3741bf02 x86_64-asm: =m operand fixes
The problem was with tcctest.c:

    unsigned set;
    __asm__("btsl %1,%0" : "=m"(set) : "Ir"(20) : "cc");

when with tcc compiled with the HAVE_SELINUX option, run with
tcc -run, it would use large addresses far beyond the 32bits
range when tcc did not use the pc-relative mode for accessing
'set' in global data memory.  In fact the assembler did not
know about %rip at all.

Changes:
- memory operands use (%rax) not (%eax)
- conversion from VT_LLOCAL: use type VT_PTR
- support 'k' modifier
- support %rip register
- support X(%rip) pc-relative addresses

The test in tcctest.c is from Michael Matz.
2016-11-20 14:50:56 +01:00
Thomas Stalder 47fd807f9b arm: Fix relocate_section with TCC_OUTPUT_MEMORY 2016-11-13 11:52:28 +01:00
Thomas Stalder 4af25aed92 remove warnings 2016-11-13 11:45:55 +01:00
grischka 59216d3db0 tccgen: fix inline_functions double free fix 2016-11-11 20:25:13 +01:00
grischka 7c28c9b13f tccgen: inline_functions double free fix
Fix double free of the inline function token_string which
could happen when an error/longjmp occurred while compiling
the inline function.
2016-11-11 18:29:45 +01:00
Pavlas, Zdenek 7e7f2e5d1b bcheck: access fields of local structs w/o bcheck
Revert previous commit, this is probably a better fix.
2016-11-10 05:15:07 -08:00
Pavlas, Zdenek 550e861bf7 bcheck: add structs to local regions
int test()
{
  struct { int i; } s = { 42 };
  return s.i; // bound checked
}
2016-11-09 04:11:40 -08:00
Pavlas, Zdenek cdf715a0b5 i386 + bcheck: fix __bound_local_new
With -b, this produces garbage. Code to call __bound_local_new
is put at wrong place, overwriting the regparam setup code.
Fix copied from x86_64-gen.c.

void __attribute__((regparm(3)))
fun(int unused)
{
  char local[1];
}
2016-11-09 01:04:45 -08:00
grischka 3054a76249 i386-gen: use EBX as 4th register
May be enabled/disabled by changing this line:
    #define USE_EBX 1
2016-10-19 19:22:15 +02:00
grischka 02642bc94c lib/libtcc1.c: cleanup
- remove #include dependencies from libtcc1.c
  for easier cross compilation
- clear_cache only on ARM
- error-message for mprotect failure
2016-10-19 19:21:36 +02:00
grischka bfd1c08d6c tccrun/win64: cleanup runtime function table
- call RtlDeleteFunctionTable
  (important for multiple compilations)

- the RUNTIME_FUNCTION* is now at the beginning of the
  runtime memory.  Therefor when tcc_relocate is called
  with user memory, this should be done manually before
  it is free'd:
      RtlDeleteFunctionTable(*(void**)user_mem);
      [ free(user_mem); ]

- x86_64-gen.c: expand char/short return values to int
2016-10-19 19:21:27 +02:00
grischka 02919cd275 configure: --triplet= option, Makefile: cleanup 2016-10-17 23:24:10 +02:00
grischka 0be098929a tccpp_new/delete and other cleanups 2016-10-17 23:24:01 +02:00
Michael Matz 6fbcc14a5d system-hacks: define __GNUC__ for FreeBSD
FreeBSDs system headers contain unconditional usage of
macros like __aligned(x), which are only conditionally defined
in sys/cdefs.h (conditional on __GNUC__ or __INTEL_COMPILER).

Bug in FreeBSD, but as work-around we can define __GNUC__ which
picks up these defs.

[This also moves back the glibc defines we had before into the
non-BSD ifdef branch]
2016-10-17 01:08:29 +02:00
Michael Matz 68a7af632c x86-64: Fix long long bug
With the last improvements to lexpand it's now harmful
to use on native 64bit platforms when not necessary.  For gv_dup
it's not necessary there.  It can still be used with really
transforming a 64bit value into two 32bit ones.
2016-10-17 00:57:16 +02:00
grischka d9b7f018ce i386: do not 'lexpand' into registers necessarily
Previously, long longs were 'lexpand'ed into two registers
always.

Now, it expands
- constants into two constants (lo-part, hi-part)
- variables into two lvalues with offset+4 for the hi-part.

This makes long long operations look a bit nicer.

Also: don't apply i386 'inc/dec' optimization if carry
generation is wanted.
2016-10-16 19:04:40 +02:00
grischka 6245db9fca tccgen/32bits: fix unsigned long long -> int cast
gen_cast() failed to truncate long long's if they
were unsigned, which was causing mess on the vstack.

There was a similar bug here
    tccgen: 32bits: fix PTR +/- long long
    ed15cddacd

Both were not visible until this patch
    tccgen: arm/i386: save_reg_upstack
    b691585785

I'd still assume that this patch is correct per se.

Also:
- remove 2x !nocode_wanted (we are already under a general
  "else if (!nocode_wanted)" clause above).
2016-10-16 11:03:57 +02:00
Christian Jullien 4ac0e1971e Actual complete name for DragonFly is 'DragonFly BSD'. 2016-10-16 06:12:55 +02:00
Christian Jullien 06db384f8a No 'Thread Storage Local' on FreeBSD with tcc. 2016-10-15 18:47:31 +02:00
Christian Jullien f7bfa0970e Backslash was missing after reindentation to let code be < 80 col. 2016-10-15 18:13:01 +02:00
grischka f3c1ea6c2d #define __GNUC__ = 2.1
__GNUC__ nowadays as macro seems to mean the "GNU C dialect"
rather than the compiler itself.  See also

  http://gcc.gnu.org/ml/gcc/2008-07/msg00026.html

This patch will probably cause problems of various kinds but
maybe we should try nonetheless.
2016-10-15 16:01:16 +02:00
grischka 4d247c00a3 tccgen/tccelf: move code from libtcc.c 2016-10-15 15:55:31 +02:00
Christian Jullien 3e32479594 Add more OpenBSD support. 2016-10-15 15:08:44 +02:00
Christian Jullien 70dec93f2b OpenBSD does not support -v option in rm command. 2016-10-15 14:59:52 +02:00
Christian Jullien 36759ddacf Start support of OpenBSD, tcc compiler can be produced from source tree 2016-10-15 14:50:17 +02:00
Christian Jullien 18a5d8188a World is not reduced to either Windows or Linux 2016-10-15 09:47:08 +02:00
Michael Matz 383f568a64 Fix misleading indentation 2016-10-14 17:46:04 +02:00
Michael Matz 682ecc1745 arm64: Fix -run
With -run the call instruction and a defined function can be
far away, if the function is defined in the executable itself,
not in the to be compiled code.  So we always need PLT slots
for -run, not just for undefined symbols.
2016-10-14 17:32:10 +02:00
Michael Matz 7600b03f35 arm64: Support PREL32 relocation
A PC-relative 32bit value is stored.
2016-10-14 16:47:43 +02:00
Michael Matz c232af7ddb Support archives with 64 bit indices
Some systems started using SYM64 .a libraries, so start
supporting them.
2016-10-14 16:47:43 +02:00
grischka ed15cddacd tccgen: 32bits: fix PTR +/- long long
Previously in order to perform a ll+ll operation tcc
was trying to 'lexpand' PTR in gen_opl which did
not work well.  The case:


    int printf(const char *, ...);
    char t[] = "012345678";

    int main(void)
    {
        char *data = t;
        unsigned long long r = 4;
        unsigned a = 5;
        unsigned long long b = 12;

        *(unsigned*)(data + r) += a - b;

        printf("data %s\n", data);
        return 0;
    }
2016-10-13 19:21:43 +02:00
Christian Jullien 8986bc8af4 Use ISO C string functions instead of obsolete BSD ones that used to be in strings.h. It allows more systems -- i.e. Windows -- to use those tests 2016-10-12 06:18:38 +02:00
Edmund Grimley Evans 07ca2df588 Use R_AARCH64_MOVW_UABS_G* instead of R_AARCH64_CALL26.
This is a work-around for TCC's linker, on AArch64, not building a PLT
when TCC is invoked with "-run". Fixing the linker should be possible:
it works on arm and x86_64, apparently.
2016-10-11 18:56:10 +01:00
Pavlas, Zdenek 7bd30a488a gcase() clean up
remove tail recursion, simplify
2016-10-11 02:05:02 -07:00
Edmund Grimley Evans 7dddd65b46 In gen_vla_sp_restore, use X30 rather than get_reg. 2016-10-10 20:15:57 +01:00
Edmund Grimley Evans 94d8d12c26 Fix handling of case_reg in switch statement.
The back end functions gen_op(comparison) and gtst() might allocate
registers so case_reg should be left on the value stack while they
are called and set again afterwards.

This bug fix was first applied as ff3f9aa (20 Feb 2015), but the fix
was reverted by fc0fc6a (21 Sep 2016, "switch: collect case ranges
first, then generate code"). Here the fix is updated for the new code.
2016-10-10 20:15:20 +01:00
Avi Halachmi (:avih) 5a0ca53a4a build: strip: unify win32 and use the configured $STRIP
- There's no need to force STRIP_BINARIES on windows since --enable-strip (at
  configure) already does exactly that, if one wants to.
- Use the contigured $STRIP instead of the native 'strip', useful when
  cross building tcc.
- 'make install-strip' now also strips libtcc.dll on windows (it already does
  so now with --enable-strip, and previously it always stripped it).

Summary of current strip options for all platforms:
- configure --enable strip -> 'install -s' for the binaries.
- make install-strip: installs and then configured $STRIP the binaries.
- Otherwise -> no stripping.
2016-10-10 15:17:58 +03:00
Avi Halachmi (:avih) 35b7bf9382 build: win: detect also mingw64 in msys2 setup
MSYS2 installs 3 environments, with uname (e.g. on win8.1 64) as follows:
- MINGW32_NT-6.3  gcc -> stand-alone native i686 binaries
- MINGW64_NT-6.3  gcc -> stand-alone native x86_64 binaries
- MSYS_NT-6.3     gcc -> posix-ish binaries which can only run in this env

Therefore 'MINGW' is more generic and detects both 32/64 native
environments, where previously 'MINGW32' detected only the 32 one.
2016-10-10 14:55:34 +03:00
Avi Halachmi (:avih) 07818ec6a7 build: out-of-tree: fix docs 2016-10-10 14:54:04 +03:00
Avi Halachmi (:avih) 61894e17cd build: win32: don't use mklink - use ln or fallback to cp
For the following reasons:
- Native windows links are rarely used in general.
- Require elevated privileges even if the current user has administrator
  privileges (needs further "run as administrator").
- Most/all windows shell environments capable of running configure already
  support ln (msys[1], msys2, most probably cygwin too).
- If cross building tcc on linux for windows then native mklink is not
  available, as well as 'cmd' (in this scenario the build later fails
  for other reasons, but at least configures succeeds now).
- cp is good enough as fallback since we only copy 5 makefiles anyway.
- The only environment I'm aware of which doesn't support ln -s is busybox
  for windows, and with this patch it falls back to cp and completes
  configure successfully (and the build later succeeds, assuming valid
  $CC and $AR).
2016-10-10 14:50:48 +03:00
grischka 71b16f4e18 tccpp : "tcc -E -P" : suppress empty lines
Also:
- regenerate all tests/pp/*.expect with gcc
- test "insert one space" feature
- test "0x1E-1" in asm mode case
- PARSE_FLAG_SPACES: ignore \f\v\r better
- tcc.h: move some things
2016-10-09 20:33:14 +02:00
Daniel Glöckner 78c08898ae arm-gen.c: support VLAs 2016-10-09 00:14:40 +02:00
Daniel Glöckner bf10bca192 tccgen.c: make vla_runtime_type_size always return the alignment 2016-10-09 00:13:31 +02:00
Daniel Glöckner 52a152235e arm-gen.c: replace register constants with enum values
and support sp in intr
2016-10-09 00:11:51 +02:00
Daniel Glöckner 6775c7cb3a tccgen.c: fix multi-register structure return when not on stack
We need to preserve the type of the pointer to the structure, f.ex.
when a global structure is returned.

This is not a perfect solution. Registers loaded in the first iteration
might be overwritten in a following iteration as the register is no
longer on vtop. This is not a problem for ARM32 as gfunc_sret returns
a maximum of 1 in the integer case.
2016-10-08 19:03:01 +02:00
Daniel Glöckner c09b6ce975 tccgen.c: use correct type for storing long double constants 2016-10-08 18:52:28 +02:00
Daniel Glöckner 3dfee1d290 arm-gen.c: detect long double structures as HFA
when long double is equal to double
2016-10-08 18:47:35 +02:00
grischka b42cb16b65 Misc. fixes
Makefile :
- do not 'uninstall' peoples /usr/local/doc entirely
libtcc.c :
- MEM_DEBUG : IDE-friendly output "file:line: ..."
- always ELF for objects
tccgen.c :
- fix memory leak in new switch code
- move static 'in_sizeof' out of function
profiling :
- define 'static' to empty
resolve_sym() :
- replace by dlsym()

win32/64: fix R_XXX_RELATIVE fixme
- was fixed for i386 already in
  8e4d64be2f
- do not -Lsystemdir if compiling to .o
2016-10-05 18:34:17 +02:00
grischka b691585785 tccgen: arm/i386: save_reg_upstack
tccgen.c:gv() when loading long long from lvalue, before
was saving all registers which caused problems in the arm
function call register parameter preparation, as with

    void foo(long long y, int x);
    int main(void)
    {
      unsigned int *xx[1], x;
      unsigned long long *yy[1], y;
      foo(**yy, **xx);
      return 0;
    }

Now only the modified register is saved if necessary,
as in this case where it is used to store the result
of the post-inc:

        long long *p, v, **pp;
        v = 1;
        p = &v;
        p[0]++;
        printf("another long long spill test : %lld\n", *p);

i386-gen.c :
- found a similar problem with TOK_UMULL caused by the
  vstack juggle in tccgen:gen_opl()
  (bug seen only when using EBX as 4th register)
2016-10-04 17:36:51 +02:00
grischka 1c4cf18556 tccpp: no cache for include if #elif seen
#ifndef guards are cached, however after #elif on the
same level, the file must be re-read.

Also: preprocess asm as such even when there is no
assembler (arm).
2016-10-04 17:31:40 +02:00
grischka 5805b07218 Alternative fix for "Incorrect function call code on ARMv6"
"make test" crashes without that "save_regs()".

This partially reverts
commit 49d3118621.

Found another solution:  In a 2nd pass Just look if
any of the argument registers has been saved again,
and restore if so.
2016-10-03 12:33:41 +02:00
grischka 78f1c10e0f configure: fix tcc_lddir, cpu
... and other minor cosmetic fixes
2016-10-03 12:33:40 +02:00
Pavlas, Zdenek f795e1be83 switch: binary search 2016-10-03 03:14:34 -07:00
Pavlas, Zdenek da63695cf3 switch: fix label sorting 2016-10-03 00:43:28 -07:00
grischka c2ad11ac70 tccgen: fix long long -> char/short cast
This was causing assembler bugs in a tcc compiled by itself
at i386-asm.c:352 when ExprValue.v was changed to uint64_t:

    if (op->e.v == (int8_t)op->e.v)
        op->type |= OP_IM8S;

A general test case:

    #include <stdio.h>
    int main(int argc, char **argv)
    {
        long long ll = 4000;
        int i = (char)ll;
        printf("%d\n", i);
        return 0;
    }

Output was "4000", now "-96".

Also: add "asmtest2" as asmtest with tcc compiled by itself
2016-10-02 01:39:14 +02:00
grischka f350487e1e win32/64: msys2 support
Support ./configure && make under msys2 (a new msys fork)
on win32 and win64.

Get rid of CONFIG_WIN64 make-var. (On windows, WIN32 in
general is used for both 32 and 64 bit platforms)

Also:
- cleanup win32/build-tcc.bat
- adjust win32/(doc/)tcc-win32.tx
2016-10-02 01:39:07 +02:00
Balazs Kezes 49d3118621 Incorrect function call code on ARMv6
On 2016-08-11 09:24 +0100, Balazs Kezes wrote:
> I think it's just that that copy_params() never restores the spilled
> registers. Maybe it needs some extra code at the end to see if any
> parameters have been spilled to stack and then restore them?

I've spent some time on this and I've found an alternative solution.
Although I'm not entirely sure about it but I've attached a patch
nevertheless.

And while poking at that I've found another problem affecting the
unsigned long long division on arm and I've attached a patch for that
too.

More details in the patches themselves. Please review and consider them
for merging! Thank you!

--
Balazs

[PATCH 1/2] Fix slow unsigned long long division on ARM

The macro AEABI_UXDIVMOD expands to this bit:

  #define AEABI_UXDIVMOD(name,type, rettype, typemacro)                     \
  ...
      while (num >= den) {                                                  \
  ...
          while ((q << 1) * den <= num && q * den <= typemacro ## _MAX / 2) \
              q <<= 1;                                                      \
  ...

With the current ULONG_MAX version the inner loop goes only until 4
billion so the outer loop will progress very slowly if num is large.
With ULLONG_MAX the inner loop works as expected. The current version is
probably a result of a typo.

The following bash snippet demonstrates the bug:

  $ uname -a
  Linux eper 4.4.16-2-ARCH #1 Wed Aug 10 20:03:13 MDT 2016 armv6l GNU/Linux
  $ cat div.c
  int printf(const char *, ...);
  int main(void) {
    unsigned long long num, denom;
    num = 12345678901234567ULL;
    denom = 7;
    printf("%lld\n", num / denom);
    return 0;
  }
  $ time tcc -run div.c
  1763668414462081

  real    0m16.291s
  user    0m15.860s
  sys     0m0.020s

[PATCH 2/2] Fix long long dereference during argument passing on ARMv6

For some reason the code spills the register to the stack. copy_params
in arm-gen.c doesn't expect this so bad code is generated. It's not
entirely clear why the saving part is necessary. It was added in commit
59c35638 with the comment "fixed long long code gen bug" with no further
clarification. Given that tcctest.c passes without this, maybe it's no
longer needed? Let's remove it.

Also add a new testcase just for this. After I've managed to make the
tests compile on a raspberry pi, I get the following diff without this
patch:

  --- test.ref    2016-08-22 22:12:43.380000000 +0100
  +++ test.out3   2016-08-22 22:12:49.990000000 +0100
  @@ -499,7 +499,7 @@
   2
   1 0 1 0
   4886718345
  -shift: 9 9 9312
  +shift: 291 291 291
   shiftc: 36 36 2328
   shiftc: 0 0 9998683865088
   manyarg_test:

More discussion on this thread:
https://lists.nongnu.org/archive/html/tinycc-devel/2016-08/msg00004.html
2016-10-01 23:10:11 +02:00
orbea d25948c5a7 Fix building man pages.
The path for texi2pod.pl in the makefile was wrong
causing the perl script to not be found.
2016-10-01 13:25:46 -07:00
grischka e03306d170 tccelf: allow multiple declaration of bss/common symbols
also in combination with one initialized:

For example
  1.c
     int xxx;
  2.c
     int xxx = 2;
  3.c
     int xxx;

tcc 1.c 2.c 3.c
2016-10-01 22:01:33 +02:00
grischka 332cf5327f tccpp: parse_line_comment: fix possible buffer overrun 2016-10-01 22:01:25 +02:00
grischka 5a23a72aed tccpp: allow "0x1e+1" in asm 2016-10-01 21:58:02 +02:00
grischka 8afb8ccba2 tccpp: token ## pasting: preserve parts if pasting fails
for example
    #define LBL(name) _ ## name ## :
    LBL(main)
will give two tokens
    '_main' and ':'
and the warning
2016-10-01 21:57:40 +02:00
grischka c5b9ae4e3f Revert "-fnormalize-inc-dirs"
Too much code. gcc 3.x doesn't have that either.

This reverts commit 41785a0bf9.
This reverts commit 21665f4338.
2016-10-01 21:57:22 +02:00
grischka 643a1b8848 tcc -E: add one space in cases: tiny solution
replaces f5f82abc99

Also: fix tcc flags in Makefile, fix tcc -E
2016-10-01 21:52:11 +02:00
grischka afdbc5b815 build: restore out-of-tree support 2016-10-01 21:06:53 +02:00
grischka 0a624782df build: revert Makefiles to 0.9.26 state (mostly)
Except
- that libtcc1.a is now installed in subdirs i386/ etc.
- the support for arm and arm64
- some of the "Darwin" fixes
- tests are mosly unchanged

Also
- removed the "legacy links for cross compilers" (was total mess)
- removed "out-of-tree" build support (was broken anyway)
2016-10-01 21:06:33 +02:00
grischka 6d2be31b93 test/pp: cleanup 2016-10-01 21:05:42 +02:00
grischka 0d9f88ea67 libtcc: reimplement option -Wl,[-no]-whöle-archive
- taking advantage of previous commit "incremental -Wl parsing"
2016-10-01 20:54:45 +02:00
grischka 2f1174550e libtcc: -Wl,... incremental parsing
parse -Wl linker options immediately
2016-10-01 20:49:38 +02:00
grischka 2d6aa65067 Revert "output all sections if we produce an executable file"
-- Not a fix
This reverts commit 089ce6235c.

Revert "handle a -s option by executing sstrip/strip program"
-- related, not a fix.
This reverts commit 5cd4393a54.
2016-10-01 20:48:01 +02:00
grischka 9c5bb16447 Revert part of "fix installation amd bcheck for Windows"
tccelf.c : force linking bcheck by adding elf symbol __bound_init
bcheck.c : use (size_t)1 for x86_64

Fixes 7e7e6148fd
2016-10-01 20:47:36 +02:00
grischka acac35c125 libtcc: filetype cleanup
- does not change signature of tcc_add_file
2016-10-01 20:46:16 +02:00
grischka 8637c1d0ad Remove misc. files
- from win32/include/winapi: various .h

  The winapi header set cannot be complete no matter what.  So
  lets have just the minimal set necessary to compile the examples.

- remove CMake support (hard to keep up to date)
- some other files

Also, drop useless changes in win32/lib/(win)crt1.c
2016-10-01 20:27:41 +02:00
grischka 766ba3694d tccpp: cleanup
- "utf8 in identifiers"
  from 936819a1b9

- CValue: remove member str.data_allocated
- make tiny allocator private to tccpp

- allocate macro_stack objects on heap
  because otherwise it could crash after error/setjmp
  in preprocess_delete():end_macro()

- mov "TinyAlloc" defs to tccpp.c

- define_push: take int* str again
2016-10-01 20:26:50 +02:00
grischka eacdc426d7 libtcc: cleanup @listfile
Also:
- allow more than one item per line
- respect "quoted items" and escaped quotes \"
  (also for LIBTCCAPI tcc_setoptions)

- cleanup some copy & paste
2016-10-01 20:19:37 +02:00
grischka 09a487eb2b libtcc: cleanup -x<filetype> switch code
Abusing filename[0] as type is just too much of a hack.
-- From 0536407204
2016-10-01 20:04:58 +02:00
grischka e630113771 Revert "ability to compile multiple *.c files with -c switch"
copy & paste coding, twisted control flow
This reverts commit a13f183e4c.

Also, set linker args for DLLs also.
2016-10-01 20:04:33 +02:00
grischka 3ddbfe1a82 tccpp: #pragma once: make it work
after several "fixes" and "improvements"
   b3782c3cf5
   5fb57bead4
feature did not work at all

- Use 'once' flag, not 'ifndef_macro'
- Ignore filename letter case on _WIN32
- Increment global pp_once for each compilation
2016-10-01 20:03:48 +02:00
grischka 07e47b3dd6 tccpp: restore -D symbols for multiple sources
... also for built-in defines

The case:
    $ tcc -D FOO a.c b.c
with
    // a.c
    #undef FOO

    // b.c
    #ifndef FOO
    # error -D FOO has been lost
    #endif
2016-10-01 19:58:13 +02:00
grischka cf32bb8812 Revert "--whole-archive support"
- would parse linker args in two different places
- would mess up "tcc -v ..." output:
  	tcc -v test.c
  	-> test.c
  	+> test.c
- would use function "tcc_load_alacarte()" to do the contrary of
  what its name suggests.

This reverts commit 19a169ceb8.
2016-10-01 19:56:25 +02:00
Pavlas, Zdenek e238e6521b gtst_addr(): short conditional jumps (i386, x86_64) 2016-09-30 07:33:20 -07:00
Pavlas, Zdenek fc0fc6aba3 switch: collect case ranges first, then generate code
Collect cases first, then emit lookup code. Elliminates
jumps to implement pass-through and jumps to link cases.
2016-09-30 07:33:20 -07:00
Jean-Claude Beaudoin d5a1e32ac3 Prevent tail spin crash when option -pthread is used. 2016-09-29 16:23:11 -04:00
Jean-Claude Beaudoin beab3f8c71 Use etags to produce target TAGS. 2016-09-29 16:18:23 -04:00
Jean-Claude Beaudoin 889ee28ed5 Rein in unintended external functions on Windows. 2016-09-27 01:43:40 -04:00
Jean-Claude Beaudoin 08335c1548 More properly propagate ONE_SOURCE. 2016-09-27 01:40:49 -04:00
Christian Jullien e037fd3364 pstrcpy looks to be needed by Windows win32/win64 builds. Reverted as PUB_FUNC to allow tcc.exe build again. 2016-09-26 07:02:42 +02:00
Christian Jullien 6db7a2157b Merge branch 'mob' of git://repo.or.cz/tinycc into mypatch
Add Visual Studio processor identification
2016-09-26 06:42:43 +02:00
Christian Jullien 30238b1ebd Add Microsoft processor identification 2016-09-26 06:41:31 +02:00
Jean-Claude Beaudoin ff158bffe6 Rein in unintended external functions. 2016-09-25 22:32:41 -04:00
Christian Jullien e38f49e32a Fix test for __*LP*__ predefined macros 2016-09-25 12:13:17 +02:00
Christian Jullien c1b101cbaf Improve __*LP*__ predefined macros 2016-09-25 12:03:23 +02:00
Christian Jullien e91ce66dad Add test for __*LP*__ predefined macros 2016-09-25 12:01:10 +02:00
Pavlas, Zdenek c948732efa x86_64/elf: only variadic calls need rax 2016-08-17 06:23:15 -07:00
David Mertens 0373fe0e2a Remove vestiges of earlier type merger 2016-08-16 15:25:09 -04:00
Pavlas, Zdenek 71b6220963 tccgen: return: avoid jmp to retsym if possible
When 'return' is the last statement of the top-level block
(very common and often recommended case) jump is not needed.
2016-08-11 05:02:40 -07:00
David Mertens 0a402f6e91 Avoid conflicting definition for va_list on 64-bit Macs 2016-08-04 13:14:52 -04:00
grischka 41349948f8 win64: fix va_arg
fixes 5c35ba66c5

Implementation was consistent within tcc but incompatible
with the ABI (for example library functions vprintf etc)

Also:
- tccpp.c/get_tok_str() : avoid "unknown format "%llu" warning
- x86_64_gen.c/gen_vla_alloc() : fix vstack leak
2016-07-10 20:44:49 +02:00
Vincent Lefevre 0360905124 fix typo in -Wl,-rpath documentation
Signed-off-by: Vincent Lefevre <vincent@vinc17.net>
2016-07-05 15:48:31 +02:00
Avi Halachmi (:avih) 1751588435 tiny_libmaker: fix a comment 2016-06-19 22:19:06 +03:00
Avi Halachmi (:avih) 3f21d81073 win32: _mingw.h: add definition for _TRUNCATE from newer _mingw.h 2016-06-19 14:44:31 +03:00
Avi Halachmi (:avih) ab8422c8e7 win32: malloc.h: use alloca instead of (missing) _alloca
_alloca is not part of msvcrt (and therefore not found if used), and tcc has
an internal implementation for alloca for x86[_64] since d778bde7 - initally
as _alloca and later changed to alloca. Use it instead.
2016-06-19 14:44:18 +03:00
Avi Halachmi (:avih) b67951bed4 win32: wchar.h: don't redifine WCHAR_MIN[/MAX] (after stdint.h) 2016-06-19 14:44:07 +03:00
Avi Halachmi (:avih) 100f94be99 tiny_libmaker: more robust arguments interpretation
- Syntax is now much closer to gnu ar, but still supports whatever was
  supported before, with the following exceptions (which gnu ar has too):
  - lib is now mandatory (was optional and defaulted to ar_test.a before).
  - Path cannot start with '-' (but ./-myfile.o is OK).
- Unlike gnu ar, modes are still optional (as before).
- Now supports also (like gnu ar):
  - First argument as options doesn't have to start with '-', later options do.
  - Now supports mode v (verbose) with same output format as gnu ar.
  - Any names for lib/objs (were limited to .a/.o - broke cmake on windows).
  - Now explicitly fail on options which would be destructive for the user.
  - Now doesn't get confused by options between file arguments.
- Still ignores other unknown options - as before.
- Now doesn't read out-of-bounds if an option is one char.

- As a result, cmake for windows can now use tiny_libmaker as ar, and
  configure can also detect tiny_libmaker as a valid ar (both couldn't before).

Ignoring all options could previously cause to misinterpret the mode in a
destructive way, e.g. if the user wanted to do something with an existing
archive (such as p - print, or x - extract, etc), then it would instead just
delete (re-create) the archive.

Modes which can be destructive if ignored now explicitly fail. These include
[habdioptxN]. Note that 'h' can be ignored, but this way we also implicitly
print the usage for -h/--help.

The .a/.o name limitations previously resulted in complete failure on some
cases, such as cmake on windows which uses <filename>.obj and <libname>.lib .

Fixed: e.g. 'tiny_libmaker r x.a x.o' was reading out of bounds [-1] for 'r'.
2016-06-19 14:43:46 +03:00
grischka 1ca685f887 tccgen: gen_assign_cast(): cannot cast struct to scalar
The case below previously was causing an assertion failure
in the target specific generator.

It probably is not incorrect not to allow this even if
gcc does.

    struct S { long b; };

    void f(struct S *x)
    {
        struct S y[1] = { *x };
    }
2016-05-25 18:52:08 +02:00
grischka 9e0e05eb4e Redo "fix line number in macro redefined message"
Smaller change to fix more cases

This reverts commit 0f36f60faa.
2016-05-25 18:51:36 +02:00
seyko bab4519617 Allow to perform tests from the custom build dir:
mkdir build; cd build
    ../configure --prefix=./package
    make
    make test
    make install
2016-05-20 16:02:42 +03:00
seyko d0e48c51c7 [avih] a custom build dir fix for lib/Makefile
mkdir build; cd build
    ../configure && make
    ../../lib/libtcc1.c:31: error: include file 'stddef.h' not found

    Author: Avi Halachmi
    Date:   Sat Nov 14 18:40:36 2015 +0200
    When building from the root tcc dir, $TOP and $top_srcdir
    are the same, but with a custom build dir, we need top_srcdir
2016-05-20 15:55:36 +03:00
seyko 18cbe62e69 fix a mingw64 build on Linux with --enable-tcc64-mingw
* define CONFIG_WIN64=yes when ARCH=x86-64 (not CONFIG_WIN32=yes)
    * CONFIG_WIN64 now use a windows install part (not a Linux one)
2016-05-20 15:48:02 +03:00
seyko 824b1b582f make and install tiny_libmaker on all platforms
not only on Windows/Darwin.
2016-05-20 15:33:53 +03:00
seyko 778ec44adc [avih] configure: support custom ar with --ar=
Author: Avi Halachmi (:avih)
    Date:   Mon Nov 2 18:46:32 2015 +0200

    configure: support custom ar with --ar=
2016-05-20 15:27:22 +03:00
seyko 4e7a8906a1 configure: docdir fix
was /usr/local/share/doc/usr/local/lib/tcc
    now /usr/local/share/doc
2016-05-20 15:21:26 +03:00
seyko 19a169ceb8 --whole-archive support
A patch is implemented as suggested in tinycc-devel mail list.

    From: Reuben Thomas
    Date: Thu, 31 Jul 2014 16:52:53 +0100
    Subject: [PATCH] Add --{no,}-whole-archive support

    I resurrected the patch supplied to the mailing list in 2009
    Since --whole-archive is a useful flag to get tcc working with
    autotools, and of course in its own right, I suggest you have a look
    at the patch and see if it is acceptable. I cannot see any suggestion
    that it was actively rejected last time round, just no evidence that
    it was ever added.
2016-05-20 15:12:32 +03:00
Christian Jullien 1339d04759 Microsoft says that _spawnp must be used instead of spawnp. It fixes a warning when compiled with MinGW 32/64 gcc compilers 2016-05-16 17:58:56 +02:00
seyko 3f233ab127 fix asm_expr_unary()
keep unary unsigned.
    problem is exposed on i386 with unary like 0xC0000000.
    In this case a sign is extended in
        pe->v = n;
    if n declared as long.
2016-05-16 08:53:24 +03:00
Michael Matz f2a4cb0a0e x86-asm: Reject some invalid arith imm8 instruction
There were two errors in the arithmetic imm8 instruction.  They accept
only REGW, and in case the user write a xxxb opcode that variant
needs to be rejected as well (it's not automatically rejected by REGW
in case the destination is memory).
2016-05-16 05:10:21 +02:00
seyko 0f36f60faa fix line number in macro redefined message 2016-05-16 03:21:26 +03:00
seyko a37f8cfc80 short_call_convention patch from tcc bugzilla
BUGZILLA:
    interfacing with other compilers

    extend the return value to the whole register if necessary.
    visual studio and gcc do not always set the whole eax register
    when assigning the return value of a function.

    We've encountered wrong execution results on i386 platforms with an
    application that uses both code compiled with TCC and code compiled
    with other compilers (namely: Visual Studio on Windows, and GCC on
    Linux).

    When calling a function that returns an integer value shorter than 32
    bits, TCC reads the return value from the whole EAX register,
    although the code generated by the other compilers can only sets AL
    for 8 bit values or AX for 16 bits values, and the rest of EAX can be
    anything.

    We worked around this with the attached patch on i386 for the version
    0.9.26, but we did not look at other platforms to find if there are
    similar issues.
2016-05-15 21:10:06 +03:00
seyko 9d679e3916 memory model macros __{L,}LP64__
a patch from tcc bugzilla.
    From: Reuben Thomas
    Date: Thu, 31 Jul 2014 13:50:13 +0100
    Subject: [PATCH] libtcc.c: add memory model macros __{L,}LP64__
2016-05-15 21:07:05 +03:00
Michael Matz 7cfd21440b x86-asm: Add .fill test 2016-05-14 04:41:06 +02:00
Michael Matz 4f27e217a8 x86-asm: Fix signed constants and opcode order
Two things: negative constants were rejected (e.g. "add $-15,%eax").
Second the insn order was such that the arithmetic IM8S forms
weren't used (always the IM32 ones).  Switching them prefers those
but requires a fix for size calculation in case the opcodes were
OPC_ARITH and OPC_WLX (whose size starts with 1, not zero).
2016-05-14 04:33:41 +02:00
Michael Matz 080ec9fadd x86-asm: Consolidate insn descriptions
Use OPC_BWLX and OPC_WLX in i386-asm.h and x86_64-asm.h to
reduce number of differences between both.
2016-05-14 04:05:34 +02:00
grischka 5e4d0718ff tcc -E -P10 : output all numbers as decimals
This may be used to preprocess Fabrice Bellards initial revision
in this repository to demonstrate its capability to compile and
run itself (on i386 32-bit linux or windows).

Initial revision: 27f6e16bae

Also needed:
* an empty stdio.h
* a wrapper named tc.c with

  void expr(void);
  void decl(int);
  void next(void);
  #include "tcc.c"

* an hello.c such as

  int main()
  {
      printf("Hello World\n");
      return 0;
  }

All files with unix LF only lines.  Then ...

* preprocess the source
  $ tcc -E -P10 -I. tcc.c -o tc1.c
* compile the compiler
  $ tcc -w -I. tc.c -o tc -ldl
* run it to compile and
   run itself to compile and
    run itself to compile and
     run itself to compile and
      run hello.c
$ ./tc tc1.c tc1.c tc1.c hello.c

--> Hello World!

------------------------------------------------------
* On i386 windows this may be added to the tc.c wrapper

  #ifdef _WIN32
  #include <windows.h>
  void *dlsym(int x, const char *func)
  {
      if (0 == strcmp(func, "dlsym"))
          return &dlsym;
      return GetProcAddress(LoadLibrary("msvcrt"), func);
  }
  #endif
2016-05-12 10:25:50 +02:00
Michael Matz a66ba1f2a1 Error out on operations on structs
The check for structs was too late and on amd64 and aarch64 could
lead to accepting and then asserting with code like:
  struct S {...} s;
  char *c = (char*)0x10 - s;
2016-05-12 01:12:04 +02:00
Michael Matz 6bd8c936e3 x86-64-asm: Add mov[sz]xq opcodes
This adds the zero/sign-extending opcodes with 64bit destinations.
2016-05-12 00:57:02 +02:00
Michael Matz b9f01dffc6 x86-64-asm: Clean up 64bit immediate support
Fix it to actually be able to parse 64bit immediates (enlarge
operand value type).  Then, generally there's no need for accepting
IM64 anywhere, except in the 0xba+r mov opcodes, so OP_IM is
unnecessary, as is OPT_IMNO64.  Improve the generated code a bit
by preferring the 0xc7 opcode for im32->reg64, instead of the
im64->reg64 form (which we therefore hardcode).
2016-05-11 23:47:02 +02:00
Michael Matz f3cee9ceff x86-asm: Get rid of is_short_jump
Can be implemented differently.
2016-05-11 23:45:14 +02:00
Michael Matz 55bd08c5ae x86-asm: Remove old ASM_16 code
This code was inactive since a long time (and was deactivated because
it was wrong to start with) and just clutters the sources.  Remove
it.
2016-05-11 19:13:38 +02:00
Michael Matz f0fa5603cf x86-64: Run asmtest as well
This fixes and activates the asm test that's part of tcctest.c
also on x86-64, requiring a small fix for the 'm' constraint.
2016-05-11 19:00:02 +02:00
Michael Matz 4d68828259 tests: Compile asmtest.S without -m32
Don't hardcode that option, if you want it do make CC="gcc -m32".
The test assembles with -m64 as well now.
2016-05-11 18:58:14 +02:00
Michael Matz 613962e353 x86-64 asm: Remove useless jmp opcode
Also remove the hacky mod/rm byte emission during
disp/imm writing.
2016-05-11 18:56:19 +02:00
Michael Matz bd93dc6923 x86: Improve cmov handling
cmov can accept multi sizes, but is also a OPC_TEST opcode,
deal with this.
2016-05-11 18:54:24 +02:00
Michael Matz 9645b62a65 x86_64: Use addend on relocs
Traditional behaviour on x86-64 is to encode the relocation
addend in r_addend, not in the relocated field (after all,
that's the reason to use RELA relocs to begin with).  Our
linker can deal with both, other linkers as well.  But using
e.g. the GNU assembler one can detect differences (equivalent
code in the end, but still a difference).

Now there's only a trivial difference in tests/asmtest.S
(having to do with ordering of prefixes).
2016-05-09 23:17:47 +02:00
Michael Matz 5e47b08dc8 [x86] Fix some asm problems
A bag of assembler fixes, to be either compatible with GAS
(e.g. order of 'test' operands), accept more instructions,
count correct foo{bwlq} variants on x86_64, fix modrm/sib bytes
on x86_64 to not use %rip relative addressing mode, to not use
invalid insns in tests/asmtest.S for x86_64.

Result is that now output of GAS and of tcc on tests/asmtest.S
is mostly the same.
2016-05-09 23:17:47 +02:00
Edmund Grimley Evans f5f82abc99 Insert spaces between certain tokens when tcc is invoked with -E.
Insert a space when it is required to prevent mistokenisation of
the output, and also in a few cases where it is not strictly
required, imitating GCC's behaviour.
2016-05-09 19:27:31 +01:00
seyko 75243f744c TOK_PPNUM in asm (Edmund Grimley Evans version) 2016-05-08 05:14:03 +03:00
grischka a94e8d439a tccgen: scopes levels for local symbols (update 2)
allow
    typedef int xxx;
    typedef int xxx;
in the same scope as long as it is the same type
2016-05-06 08:32:54 +02:00
grischka d48662d496 tccgen: scopes levels for local symbols (update 1)
Catch top level redeclarations too.

Also fix mistakes in tcctest.c and the tcc sources (win32)
showing up now.
2016-05-05 20:04:00 +02:00
grischka fe845cf53d tccpp: cleanup options -dD -dM, remove -C
The lexer is for reading files, not for writing.

Also :
- macro_is_equal(): avoid crash if redefining __FILE__
2016-05-05 14:12:53 +02:00
grischka caebbc3ee1 tccgen: scope levels for local symbols
... for fast redeclaration checks

Also, check function parameters too:
    void foo(int a) { int a; ... }

Also, try to fix struct/union/enum's on different scopes:
    { struct xxx { int x; };
         { struct xxx { int y; }; ... }}
and some (probably not all) combination with incomplete
declarations "struct xxx;"

Replaces 2bfedb1867
and 07d896c8e5

Fixes cf95ac399c
2016-05-05 10:39:09 +02:00
Edmund Grimley Evans 0fbc77cac6 tests/tests2/Makefile: Make 85-asm-outside-function Intel-only. 2016-05-04 21:23:25 +01:00
Edmund Grimley Evans a348513569 Revert 78e4ee5. 2016-05-04 20:27:39 +01:00
Edmund Grimley Evans 6015840583 Revert 3283c26 and a1c1390 in tccpp.c. 2016-05-04 20:14:39 +01:00
seyko 07d896c8e5 sym_push2 optimized for the local_stack case.
A constant expression removed from the loop.
    If subroutine have 50000+ local variables, then currently
    compilation of such code takes obly 15 sec. Was 2 min.
    gcc-4.1.2 compiles such code in 7 sec. pcc -- 3.44 min.

    A test generator:
    #include <stdio.h>
    int main() {
        puts("#include <stdio.h>"); puts("int main()"); puts("{");
        for (int i = 0; i < 50000; ++i) printf("int X%d = 1;\n", i);
        for (int i = 0; i < 50000; ++i) puts("scanf(\"%d\", &X0);");
        puts("}");
        return 0;
    }
2016-05-04 17:23:25 +03:00
seyko 2bfedb1867 -fno-type-redefinition-check
don't catch redefinition for local vars. With this option on
    tcc accepts the following code:
    int main()
    {
        int a = 0;
        long a = 0;
    }
    But if you shure there is no problem with your local variables,
    then a compilation speed can be improved if you have a lots of
    the local variables (50000+)
2016-05-04 17:17:51 +03:00
seyko 78e4ee55b7 PP_NUM in ASM mode
oxe+1 is parsed as 0xe +1 if (parse_flags & PARSE_FLAG_ASM_FILE)
        Helps to compile a code:
        __asm__("mov $0xe" "+1", "%eax\n")
2016-05-04 16:54:40 +03:00
Michael Matz 78ee3759b8 x86-asm: Fix lcall/ljmp, xchg and inc/dec
Various x86 asm fixes: 64bit lcall/ljmp like 32bit a commit before,
xchgw accepted wrong operands on 32 and 64bit, and 64bit used
0x40/0x48+reg for incw/decw, but those are REX prefixes, not
instructions.
2016-05-03 01:16:43 +02:00
Michael Matz d1515a0536 i386-asm: correct lcall/ljmp encoding
The 0xff/3 form of lcall needs a mod/rm byte, so reflect this.
2016-05-02 04:50:12 +02:00
seyko 6afe668ec7 __asm__() outside function
gcc/pcc allow __asm__() outside a function body:
    extern void vide(void);
    __asm__("vide: ret");

    There is many such code in the Linux kernels.
2016-05-01 22:38:38 +03:00
seyko 09a78412f0 lcall hex code correction 2016-05-01 22:14:00 +03:00
seyko 3283c26827 clearing "output space after TOK_PPNUM ..." 2016-05-01 16:36:19 +03:00
seyko a1c139063b output space after TOK_PPNUM which followed by '+' or '-'
* correct -E output for the case ++ + ++ concatenation
        do this only for expanded from macro string
        and only when tcc_state->output_type == TCC_OUTPUT_PREPROCESS
2016-05-01 05:43:57 +03:00
grischka 256078933c tccpp: macro subst fix
#define Y(x) Z(x)
#define X Y
return X(X(1));

was : return Z(Y(1));
now : return Z(Z(1));
2016-04-29 19:00:33 +02:00
Edmund Grimley Evans 68ce8639bb TODO: Add two issues. 2016-04-24 22:44:57 +01:00
seyko b4125ba0c1 fix for the "Reduce allocations overhead"
Now no trap when compiling tccboot
2016-04-22 20:32:15 +03:00
seyko 1f49441a27 .rept asm directive
and '.' alone is a token now in *.S (not an identifier)
    representing a current position in the code (PC).
2016-04-22 18:29:56 +03:00
seyko edcb15c31f section alignment
Alignment of unknown sections changed from 32 to PTR_SIZE
    This is gcc/pcc default value. This helps to use
    tcc as linux kernel compiler.
2016-04-22 18:25:40 +03:00
seyko 8db7a0f7af Source and destination overlap in memcpy, cstr_cat (tccpp.c:322)
This code is from "Improve hash performance"
2016-04-22 18:21:09 +03:00
Michael Matz d25f67ec12 Run testcases in sorted order
Without sorting they run in whatever order readdir returns,
I like it better when the order is reliable (and alphanumeric).
2016-04-22 15:57:23 +02:00
Vlad Vissoultchev cdc16d428f Reduce allocations overhead
- uses new `TinyAlloc`-ators for small `TokenSym`, `CString` and
  `TokenString` instances
- conditional `TAL_DEBUG` for mem leaks and double frees detection
- on `TAL_DEBUG` collects allocation origin (file + line)
- conditional `TAL_INFO` for allocators stats (in release mode too)
- chain a new allocator twice current capacity on buffer exhaustion
2016-04-17 17:26:10 +03:00
Vlad Vissoultchev 224236f57c Improve hash performance
- better `TOK_HASH_FUNC`
- increases `hash_ident` initial size to 16k (from 8k)
- `cstr_cat` uses single `realloc` + `memcpy`
- `cstr_cat` can append terminating zero
- `tok_str_realloc` initial size to 16 (from 8)
- `parse_define` uses static `tokstr_buf`
- `next` uses static `tokstr_buf`
- fixes two latent bugs (wrong deallocations in libtcc.c:482 and
  tccpp.c:2987)
2016-04-17 17:25:55 +03:00
Vlad Vissoultchev acc8f602e5 Revert "Fix tests Makefiles on Windows"
This reverts commit fa2472c172.
2016-04-17 17:24:17 +03:00
Vlad Vissoultchev f021a7cd94 Add travis tests integration 2016-04-17 17:24:07 +03:00
seyko 587aacedf3 simplify -C printing
parse_print_line_comment() and parse_print_comment() are
    combined and made more simply:
        * don't worry about speed with -E option
        * don't handle straya in comments
            Do we need to handle strays in regular
            parse_line_comment() and
            parse_comment() ?
2016-04-17 10:07:55 +03:00
seyko e010b1396b __builtin_expect no-op
Taken from David Mertens tcc branch on github
    https://github.com/run4flat/tinycc.git
2016-04-16 12:41:53 +03:00
seyko 5ee097fce9 allow to compile tcc by pcc
* pcc have only __linux__ macro (and no __linux)
    * pcc don't have __clear_cache proc
2016-04-15 17:41:49 +03:00
seyko c6dc756d4e preprocessor oprtion -C (keep comments)
This is done by impression of the pcc -C option.
    Usual execution path and speed are not changed.
2016-04-15 17:15:11 +03:00
seyko 16cbca281f fix preprocessing *.S with ` ' chars in #comments
with a test program. Problem detected when trying to
    compile linux-2.4.37.9 with tcc.
2016-04-14 21:46:46 +03:00
seyko 5fb57bead4 fix for thev "#pragna once" guard
gcc 3.4.6 don't understand "#if PATHCMP==stricmp"
    where "#define PATHCMP stricmp"
2016-04-14 21:39:34 +03:00
Vlad Vissoultchev 34feee0ed6 Move utility functions `trimfront/back` to tccpp.c
These are used in `libtcc.c` now and cannot remain in `tccpe.c`
2016-04-13 14:33:21 +03:00
Vlad Vissoultchev cb5f6b063b Simplify @listfiles parsing
This moves listfiles parsing inline in `tcc_parse_args1`
2016-04-13 11:35:24 +03:00
Vlad Vissoultchev b3782c3cf5 Better pragma once guard
This takes care of case-insensitive filenames (like on win32)
2016-04-13 11:18:40 +03:00
Vlad Vissoultchev 98ffeaa0c5 win32: Better VS2015 solution and project files
These include all header and source files from source directory
2016-04-13 11:10:13 +03:00
Vlad Vissoultchev 810a677d32 tccpp.c: Guard against ppfp being NULL
Missed these in e946eb2a41
2016-04-13 10:58:42 +03:00
seyko 6a49afb3ed correct version of "Identifiers can start and/or contain"
A problem was in TOK_ASMDIR_text:
    -    sprintf(sname, ".%s", get_tok_str(tok1, NULL));
    +    sprintf(sname, "%s", get_tok_str(tok1, NULL));
    When tok1 is '.text', then sname is '..text'
2016-04-13 10:23:46 +03:00
seyko 989b5ee8ae Allow tcc arguments to be read from @listfiles
From: Vlad Vissoultchev
    Date: Tue, 12 Apr 2016 20:43:15 +0300
    Subject: Allow tcc arguments to be read from @listfiles

    This allows all @ prefixed arguments to be treated as listfiles
    containing list of source files or tcc options where each one is on a
    separate line. Can be used to benchmark compilation speed with
    non-trivial amount of source files.

    The impl of `tcc_parse_args` had to be moved to a new function that is
    able to be called recursively w/ the original one remaining as a driver
    of the new one. Listfiles parsing happens in a new
    `args_parser_add_listfile` function that uses `tcc_open`/`tcc_close/inp`
    for buffered file input.
2016-04-13 07:05:38 +03:00
seyko a1a5c81e6c win32: Add missing header files for nginx compilation
From: Vlad Vissoultchev
    Date: Tue, 12 Apr 2016 21:02:43 +0300
    Subject: win32: Add missing header files for nginx compilation

    The new ones are hoisted from mingw-w64 as most other headers under
    `win32/include/winapi`
2016-04-13 06:51:59 +03:00
seyko 52d194a1e6 VS2015 solution and project files
From: Vlad Vissoultchev
    Date: Mon, 11 Apr 2016 01:32:28 +0300
    Subject: Add VS2015 solution and project files to `win32/vs2015`
             directory

    This allows release/debug builds for both x86 and x64 targets. Some
    warnings had to be suppressed.

    Output libtcc.dll and tcc.exe are copied to parent `win32` directory
    w/ a post-build action.
2016-04-13 06:29:24 +03:00
seyko b5b3e89f9e Fix pragma once guard
From: Vlad Vissoultchev
    Date: Mon, 11 Apr 2016 01:26:32 +0300
    Subject: Fix pragma once guard when compiling multiple source files

    When compiling multiple source files directly to executable cached
    include files guard was incorrectly checked for TOK_once in ifndef_macro
    member.

    If two source files included the same header guarded by pragma once, then
    the second one erroneously skipped it as `cached_includes` is not cleared
    on second `tcc_compile`
2016-04-13 06:17:02 +03:00
seyko b0296139a8 fix for the -dM patch
assign fopen("/dev/null","w") to the s->ppfp insteed of NULL
2016-04-13 05:17:13 +03:00
seyko f869dfb47f document -dM in "tcc -h" output 2016-04-13 04:27:27 +03:00
seyko 131d776d66 revert of the 'Identifiers can start and/or contain'
When tccboot kernels compiles with
    'Identifiers can start and/or', this kernel don't start.
    It is hard to find what is wrong.

    PS: there was no test for identifiers in *.S with '.'
2016-04-13 03:52:07 +03:00
Vlad Vissoultchev 174d06a3ff Skip math library if not found when -lm option is used
This only silences "cannot find library" error and allows Makefiles targeting gcc to not complain about missing libraries

If there is custom libm then standard handling applies.
2016-04-08 12:18:31 +03:00
Vlad Vissoultchev e946eb2a41 Implement -dM preprocessor option as in gcc
There was already support for -dD option but in contrast -dM dumps only `#define` directives w/o actual preprocessor output.

The original -dD output differs from gcc output by additional comment in front of `#define`s so this quirk is left for -dM as well.
2016-04-06 18:57:11 +03:00
Vlad Vissoultchev 0691b7630b tccgen.c: Allow type attributes to prefix enum/struct/union name
From gcc docs: "You may also specify attributes between the enum, struct or union tag and the name of the type rather than after the closing brace."

Adds `82_attribs_position.c` in `tests/tests2`
2016-04-06 14:32:52 +03:00
seyko effc7d9ed4 cleaning "Identifiers can start and/or contain"
more logical algorithm of the isidnum_table[] changing
2016-04-05 15:06:47 +03:00
seyko 983c40f58b compilation speed of the tccboot correction
we use gnu extension "case 0x80 ... 0xFF" for tcc & gcc
    and perform test
        if(c & 0x80)
    for other compilers
2016-04-05 13:38:53 +03:00
seyko 936819a1b9 utf8 in identifiers
made like in pcc
    (pcc.ludd.ltu.se/ftp/pub/pcc-docs/pcc-utf8-ver3.pdf)
    We treat all chars with high bit set as alphabetic.
    This allow code like

    #include <stdio.h>
    int Lefèvre=2;
    int main() {
        printf("Lefèvre=%d\n",Lefèvre);
        return 0;
    }
2016-04-05 13:05:09 +03:00
seyko c9473a7529 nocode_wanted with while/for inside ({})
a test included.
2016-04-05 11:47:20 +03:00
seyko 5a704457e2 optimization of the previous patch
compilation speed of the tccboot restored
    (patch remove testing of the parse_flags in loop)
2016-04-05 11:19:09 +03:00
seyko d3e85e80fd Identifiers can start and/or contain '.' in *.S
modified version of the old one which don't allow '.'
    in #define Identifiers. This allow correctly preprocess
    the following code in *.S

        #define SRC(y...)               \
        9999: y;                        \
        .section __ex_table, "a";       \
        .long 9999b, 6001f      ;       \
        // .previous

        SRC(1: movw (%esi), %bx)
        6001:

    A test included.
2016-04-05 10:43:50 +03:00
seyko 21665f4338 describe -fnormalize-inc-dirs in tcc-doc.texi 2016-04-04 19:22:52 +03:00
seyko 5278d217ff R_386_COPY
This reloction must copy initialized data from the library
    to the program .bss segment. Currently made like for ARM
    (to remove noise of defaukt case). Is this true?
2016-04-03 18:13:53 +03:00
seyko 41785a0bf9 -fnormalize-inc-dirs
remove non-existent or duplicate directories from include paths
    if -fnormalize-inc-dirs is specified. This will help
    to compile current coreutils package
2016-04-03 11:42:15 +03:00
seyko 2bf43b5483 reverse of the "Identifiers can start and/or contain '.'"
- Identifiers can start and/or contain '.' in PARSE_FLAG_ASM_FILE
    - Move all GAS directives under TOK_ASMDIR prefix

    This patches breaks compilation of the tccboot (linux 2.4.26
    kernel). A test.S which fails with this patches:

    #define SRC(y...) \
    9999: y; \
    .section __ex_table, "a"; \
    .long 9999b, 6001f<---->; \
    .previous

    SRC(1:<>movw (%esi), %bx<------>)
    // 029-test.S:7: error: macro 'SRC' used with too many args
2016-04-03 11:01:05 +03:00
Michael Matz 80343ab7d8 Fix assignment to/from volatile types
Code like this was broken:

   char volatile vi = i;

See testcase, happens in ideosyncratic legacy code sprinkling
volatile all over.
2016-03-26 17:57:22 +01:00
Michael Matz 8fc5a6a2a4 Fix tokenization of TOK_DOTS
We really need to use PEEKC during tokenization so as to
skip line continuations automatically.
2016-03-24 15:58:32 +01:00
Michael Matz f85db99ff0 Fix type parsing
the check on incomplete struct/union/enum types was too early,
disallowing mixed specifiers and qualifiers.  Simply rely on
the size (->c) field for that.  See testcases.
2016-03-24 15:44:01 +01:00
Vlad Vissoultchev aa1ed616eb Move all GAS directives under TOK_ASMDIR prefix to include leading '.'
Use only these tokens in `asm_parse_directive` and don't recycle others' tokens (like TOK_SECTION1)
2016-03-15 10:00:50 +02:00
Vlad Vissoultchev 05ec6654a7 Identifiers can start and/or contain '.' in PARSE_FLAG_ASM_FILE
Including labels, directives and section names
2016-03-14 18:37:39 +02:00
Vlad Vissoultchev 17395ea507 tccpp.c: Fix failing `PPTest 03` by reverting rogue modification in `macro_arg_subst` 2016-03-14 18:26:41 +02:00
Vlad Vissoultchev fa2472c172 Fix tests Makefiles on Windows
Compiled tcc.exe location is under $(top_srcdir)/win32
2016-03-14 18:11:49 +02:00
Vlad Vissoultchev 5175b1ad87 Use proper ifdef for x64 check in winnt.h 2016-03-14 18:07:38 +02:00
Vlad Vissoultchev 712eca44d5 Revert spawnvp param cast and use `no-incompatible-pointer-types` in build-tcc.bat 2016-03-14 18:06:42 +02:00
Vlad Vissoultchev 9d778c7bb6 Keep lvalue category on structs when evaluating ternary operator 2016-03-13 04:32:18 +02:00
Vlad Vissoultchev 32755dbea9 Migrate static STRING_MAX_SIZE buffers to CString instances for large macros expansion 2016-03-13 04:26:45 +02:00
Vlad Vissoultchev d715ebdae0 Add x64 SEH decls. Add exports to kernel32.def 2016-03-13 04:23:15 +02:00
Vlad Vissoultchev 95aac21130 Move WIN32_LEAN_AND_MEAN to windows.h (silence redeclarations) 2016-03-13 04:21:23 +02:00
Vlad Vissoultchev 2dc7161453 Win32 build script handles `x64` and `debug` params 2016-03-13 04:19:32 +02:00
Vlad Vissoultchev 8e4d64be2f Silence FIXME and compiler warning 2016-03-13 04:18:43 +02:00
Michael Matz ceccd3ead3 tccgen.c: Fix flex array members some more
Last fix didn't work for function f1int in the added testcase.
2016-03-11 22:35:44 +01:00
Henry Kroll III 7e0ad4fdd2 tccgen.c: off by one in flexible array members
tccgen.c: fix fexible array member breaking struct alignment
2016-03-10 08:28:26 -08:00
Edmund Grimley Evans f75f89fc8f tccgen.c: In parse_btype, handle type qualifiers applied to arrays.
Also add some test cases in tests/tests2/39_typedef.c.
2016-01-11 07:51:58 +00:00
Edmund Grimley Evans 541b33591c CodingStyle: Remove reference to misaligned struct CString.
This was fixed by 1c2dfa1 on 2015-11-21.
2016-01-06 19:09:28 +00:00
Thomas Preud'homme 933c2235e5 i386: Add support for new psABI relocation
R_386_GOT32X can occur in object files assembled by new binutils, and in
particular do appear in glibc startup code (crt*.o). This patch is
modeled after the x86_64 one, handling the new relocation in the same
trivial way.
2015-12-27 12:09:45 +08:00
Michael Matz f15c0a9333 x86-64: fix shared libs
The introduction of read32le everywhere created a subtle issue, going
from
   x = *(int*)p;
to
   x = read32le(p);
is not equivalent if x is a larger than 32bit quantity, like an
address on x86_64, because read32le returns an unsigned int.  The first
sign extends, the latter zero extends.  This broke shared library
creation for gawk.  It's enough to amend the case of the above
situation, cases like "write32le(p, read32le(p) +- something)" are okay,
no extensions happen or matter.
2015-12-17 19:41:20 +01:00
Michael Matz e264243adc x86-64: Define symbol constant for new relocs
Whoops, we have our own <elf.h> copy, so I can just as well add
the symbol defines for the relocs instead of hard-coding numbers
in tccelf.c.
2015-12-17 07:30:35 +01:00
Michael Matz c4d0498b3a x86-64: Add support for new psABI relocations
R_X86_64_GOTPCRELX and R_X86_64_REX_GOTPCRELX can occur in object files
comiled by new binutils.  They are not dynamic relocations, so normally
wouldn't be a problem for tcc (one doesn't normally mix object files
created by different compiler/binutils, static archives are so out :)).
If it weren't for the glibc startup code, crt*.o, of course.  They now
do contain such relocs --> boom.  Handle them in the trivial way.
2015-12-17 07:17:34 +01:00
Vincent Lefevre d1e15514aa Fixed a dependency (error with make -j8).
Signed-off-by: Vincent Lefevre <vincent@vinc17.net>
2015-12-15 13:47:07 +01:00
Edmund Grimley Evans 1c2dfa1f4b Change the way struct CStrings are handled.
A CString used to be copied into a token string, which is an int array.
On a 64-bit architecture the pointers were misaligned, so ASan gave
lots of warnings. On a 64-bit architecture that required memory
accesses to be correctly aligned it would not work at all.

The CString is now included in CValue instead.
2015-11-26 12:40:50 +00:00
Edmund Grimley Evans 4886d2c640 TODO: Add two issues. 2015-11-26 12:31:23 +00:00
Edmund Grimley Evans 99372bb1d3 tccgen.c: Give error if statement expression found when const wanted.
Some test cases:

#define SE ({ switch (0) { } 0; })

// Should give error:
int x = SE;
void f(void) { static int x = SE; }
void f(void) { enum e { a = SE }; }
void f(void) { switch (0) { case SE: break; } }

// Correct:
int f(void) { return SE; }
int f(void) { return sizeof(SE); }
2015-11-26 12:28:42 +00:00
Edmund Grimley Evans 51c3465a49 tcc.h: Change order of built-in include paths: put TCC's own dir first.
There may be compiler-specific header files that should override
system headers. See TCC's include paths by running "tcc -vv".
2015-11-23 12:50:16 +00:00
Edmund Grimley Evans 7301b42e36 tccgen.c: Try to make sizeof(!x) work.
tests/tests2/27_sizeof.*: Add test.
2015-11-22 00:00:36 +00:00
Edmund Grimley Evans 737f984213 tccgen.c: Bug fix for 992cbda and 3ff77a1: set nocode_wanted.
tests/tests2/78_vla_label.*: Add test.
2015-11-21 23:58:58 +00:00
Edmund Grimley Evans cfef9ac3f5 TODO: Add note on handling of floating-point values. 2015-11-21 10:35:47 +00:00
Edmund Grimley Evans dd40d6a068 TODO: Add some issues. 2015-11-21 00:04:58 +00:00
Edmund Grimley Evans 5bd5fd488d CodingStyle: Add notes on language and testing. 2015-11-20 23:41:01 +00:00
Edmund Grimley Evans 3ff77a1d6f Improve constant propagation with "&&" and "||". 2015-11-20 23:33:49 +00:00
Edmund Grimley Evans c7067aeb84 tccelf.c: On arm64, use read64le, and use uint64_t to check range. 2015-11-20 23:29:08 +00:00
Edmund Grimley Evans 4ae626451e Bug fix for commit 553242c18a.
In gtst, vtop->c.i is not usually zero, but it is when compiling:

int f(void) { return 1 && 1 ? 1 : 1; }
2015-11-20 23:17:24 +00:00
grischka 8dd1859176 tccpp: allow .. in token stream
for gas comments lonely on a line such as

    # .. more stuff

where tcc would try to parse .. as a preprocessor directive

See also: 0b3612631f
2015-11-20 18:25:00 +01:00
grischka 0b3612631f tccpp: cleanup #include_next
tcc_normalize_inc_dirs: normally no problem to be absolutly
gcc compatible as long as it can be done the tiny way.

This reverts to the state before recent related commits and
reimplements a (small) part of it to fix the reported problem.


Also: Revert "parsing "..." sequence"
c3975cf27c

	&& p[1] == '.'

is not a reliable way to lookahead
2015-11-20 12:05:55 +01:00
grischka 54cf57ab1a tccgen: asm_label cleanup
- avoid memory allocation by using its (int) token number
- avoid additional function parameter by using Attribute

Also: fix some strange looking error messages
2015-11-20 11:22:56 +01:00
Edmund Grimley Evans 992cbda8d0 tccgen.c: Recognise constant expressions with conditional operator.
tests/tests2/78_vla_label.c: Check that int a[1 ? 1 : 1] is not a VLA.
2015-11-20 00:24:46 +00:00
Edmund Grimley Evans 30c54c9d43 tccgen.c: In parse_btype, handle typedef types with added type qualifiers.
In a case like

    typedef int T[1];
    const T x;

we must make a copy of the typedef type so that we can add the type
qualifiers to it.

The following code used to give

error: incompatible types for redefinition of 'f'

    typedef int T[1];
    void f(const int [1]);
    void f(const T);
2015-11-19 23:45:33 +00:00
Edmund Grimley Evans 58a34d22c9 tccgen.c: Improvements to type_to_str (only used for error messages).
1. Handle array types.
2. Print the type qualifiers of pointers.
2015-11-19 23:35:36 +00:00
Edmund Grimley Evans ba99a70cd8 Trivial changes to avoid some compiler warnings. 2015-11-19 18:26:47 +00:00
Edmund Grimley Evans 553242c18a Replace pointer casts with calls to (read|write)(16|32|64)le.
This stops UBSan from giving runtime misaligned address errors
and might eventually allow building on a non-little-endian host.
2015-11-19 18:21:14 +00:00
Edmund Grimley Evans 5d496b1695 tccgen.c: Avoid undefined behaviour in constant propagation. 2015-11-17 19:34:31 +00:00
Edmund Grimley Evans 569fba6db9 Merge the integer members of union CValue into "uint64_t i". 2015-11-17 19:09:35 +00:00
Edmund Grimley Evans 3712c958f4 tests/tests2/79_vla_continue.c: Fix off-by-one error. 2015-11-13 21:49:29 +00:00
Edmund Grimley Evans c39bc9caa7 libtcc.c: Completely replace tcc_normalize_inc_dirs. 2015-11-11 21:18:01 +00:00
Edmund Grimley Evans a7334f791d arm64-gen.c: Avoid some cases of undefined behaviour.
Also make some functions more portable.
2015-11-09 23:06:05 +00:00
Edmund Grimley Evans c52128c581 tccelf.c: Avoid two trivial instances of undefined behaviour. 2015-11-09 22:57:58 +00:00
Avi Halachmi (:avih) 951c23f257 win: include dirs: add some docs, minor refactor 2015-11-08 16:28:00 +02:00
seyko 37e815eee1 lib/Makefile: filter-out -b flag from XFLAGS
to build tcc with bound checking
    ./configure --cc=tcc --extra-cflags-b
2015-11-08 12:26:17 +03:00
seyko 763dd22b35 fix tcc_mormalize_inc_dirs naming 2015-11-08 11:42:56 +03:00
Avi Halachmi (:avih) ec67dc482f win: fix incorrect directory detection
Allow other flags too...
2015-11-08 04:33:30 +02:00
Avi Halachmi (:avih) acbab220c8 win: fix dir comparison during include dirs processing
Use native Windows API via wrapper with stat-like API.
2015-11-08 03:56:25 +02:00
Avi Halachmi (:avih) 9d33388b29 win: libm: add implementation for round/fmin/fmax and variants
round and fmin/fmax are relatively commonly used functions but were not
implemented anywhere in the tcc Windows distribution package. Newer mingw(64)
math.h stil doesn't include these implementations.

Add C implementations for these functions and place it as inline functions at
win32/include/tcc/tcc_libm.h - which is already included from math.h .

The code is mostly taken from musl-libc rs-1.0 (MIT) [*],

musl-libc: http://git.musl-libc.org/cgit/musl/tree/src/math?h=rs-1.0
license:   http://git.musl-libc.org/cgit/musl/tree/COPYRIGHT?h=rs-1.0

Potential enhancements:
- Check how many useful libm implementations are still missing and consider
  adding them (some of them already work via the MS runtime).
- Consider putting libm implementations in an actual libm.a file, or add a dummy
  one such that build processes which try to link with libm will not fail.
2015-11-07 22:31:57 +02:00
Avi Halachmi (:avih) 9c52ba48b3 win: math.h: fix fpclassify/signbit/etc - use C instead of broken asm
The asm code cannot currently be used with tcc since tcc doesn't support 't'
constraint.

Use inline C implementation instead, place it win32/include/tcc/tcc_libm.h, and
include it from win32/include/math.h.

Since fpclassify now works, it also fixes few other macros which depend on it.
Implicitly fixed: isfinite, isinf, isnan, isnormal.

The implementations were taken from musl-libc rs-1.0 (MIT license).

musl-libc: http://git.musl-libc.org/cgit/musl/tree/src/math?h=rs-1.0
license:   http://git.musl-libc.org/cgit/musl/tree/COPYRIGHT?h=rs-1.0
2015-11-07 22:18:46 +02:00
Avi Halachmi (:avih) 6e261a107c win: math.h: isnan: use macro, similar to others (still broken)
It was broken due to tcc not able to compile asm with 't' constraint, and it's
still broken because fpclassify on which it now depends has the same issue. Next
commit will fix this.
2015-11-07 22:17:21 +02:00
Avi Halachmi (:avih) 7307a6a3cb Revert "win32/include/math.h: remoing a "t" modifier usage"
This reverts commit 45bc505968.

The new asm code did not work as expected. Coordinated with seiko.
2015-11-07 21:30:56 +02:00
seyko 8fc9c79705 TOK_INCLUDE: fix for the "normalize inc dirs"
A case for the absolute path: prevent an error after openening
2015-11-06 02:50:36 +03:00
seyko 7cb921a44b TOK_INCLUDE: streamline
goto removed
2015-11-06 02:40:14 +03:00
Edmund Grimley Evans eb00777309 tcctok.h: Put TOK_memmove in the correct places (I hope).
This should have been part of b051549. Someone should test on ARM.
2015-11-05 19:37:04 +00:00
Edmund Grimley Evans 7f0b798418 tcctok.h: Revert 41408f2, which moved TOK_memmove. 2015-11-05 19:33:46 +00:00
seyko 97916c9d04 tcc.h: remove CONFIG_TCCBOOT part
curremtly no one will try to compile a linux kernel
    from the boot loader. With current tcc it is not
    possible w/o additional tuning.
2015-11-05 20:30:51 +03:00
seyko 41408f2104 fix for the "tccgen.c: Use memmove for struct assignment"
./configure --enable-cross
    make
    tcc -o i386-tcc tcc.c
    tcc -o x86_64-tcc tcc.c
    tcc -o i386-win-tcc tcc.c
    In file included from tcc.c:22:
    In file included from libtcc.c:39:
    tccgen.c:2580: error: 'TOK_memmove' undeclared
2015-11-05 20:24:04 +03:00
seyko 0ad87a094c fix for the previous commit
a cross-compilation from unix to win32 need a "sys/stat.h"
    include file
2015-11-05 20:14:42 +03:00
seyko a6276b7a78 normalize inc dirs, symplify include_next
include dirs are prepared as in gcc
    - for each duplicate path keep just the first one
    - remove each include_path that exists in sysinclude_paths

    include_next streamlined by introducing inc_path_index
    in the BufferedFile
2015-11-05 19:52:49 +03:00
seyko 45bc505968 win32/include/math.h: remoing a "t" modifier usage
replaced by loading a float argument from memory and
    using the "m" modifier
2015-11-05 14:27:41 +03:00
Edmund Grimley Evans f7dd3d49cc lib/libtcc1.c: Replace "long" with "unsigned int" in union float_long. 2015-11-04 23:22:00 +00:00
Edmund Grimley Evans 24308fd292 tccpp.c: In TOK_GET, add comment warning about illegal cast.
Also, in tok_str_add2, use memcpy instead of the illegal cast.

Unfortunately, I can't see an easy way of fixing the bug.
2015-11-04 20:27:54 +00:00
Edmund Grimley Evans 20f0c179da tccpp.c: Define and use tok_last for checking if last token is space. 2015-11-04 20:25:26 +00:00
Edmund Grimley Evans b051549f2e tccgen.c: Use memmove for struct assignment: dest and src may be equal. 2015-11-04 20:23:17 +00:00
Edmund Grimley Evans 8eab556ac5 tccgen.c: Fix memory leak involving asm_label. 2015-11-04 20:22:30 +00:00
Edmund Grimley Evans 9bf0e57509 tests/tcctest.c: Fix up format strings. 2015-11-04 20:20:26 +00:00
Edmund Grimley Evans f4082851ea Enable variable-length arrays on arm64.
arm64-gen.c: Implement gen_vla_sp_save, gen_vla_sp_restore, gen_vla_alloc.
tests/Makefile: Run vla_test on arm64.
2015-10-31 11:04:52 +00:00
seyko 35e715a1e3 defined twice: revert
An error message is changed to suggest -fcommon
2015-10-29 17:10:04 +03:00
seyko c07785a1ea comment out tcc_error_noabort("'%s' defined twice"...
gcc-3.4.6 don't give such error by default
    example file1
	char __version_303_xxxxxxxx;
	void func1() {}
    example file2
	char __version_303_xxxxxxxx;
	void func2() {}
	int main() { return 0; }
2015-10-25 00:41:17 +03:00
seyko 12f94f2770 include/stddef.h: define NULL only if undefined 2015-10-25 00:19:12 +03:00
seyko f3ce1be333 tcc help output for the -xc -xa - options 2015-10-24 23:39:17 +03:00
seyko 003c532bf3 fix for the #include_next, v4 (final)
This version looks rigth. Comparing to the original
    algorithm:

    1) Loop breaking. We remember a start point after wich
    we can try next path. Do not search include stack after
    this.

    2) But compare next file patch with the start point.
    Skip if it the same. Remove "./" before comparing.

    PS: a problems with compaling a coreutils-8.24.51-8802e
    remain. There are errors messages like:
    src/chgrp
        src/chown-core.c:42: multiple definition of `make_timespec'
        src/chgrp.c:42: first defined here
    A problem is in the lib/config.h
        #define _GL_INLINE_ extern inline // gcc
        #define _GL_INLINE_ inline        // tcc

    A long description from the lib/config.h
    * suppress extern inline with HP-UX cc, as it appears to be broken
    * suppress extern inline with Sun C in standards-conformance mode
    * suppress extern inline on configurations that mistakenly use
      'static inline' to implement functions or macros in standard
      C headers like <ctype.h>.

    GCC and Clang are excluded from this list. Why not tcc?
2015-10-20 07:32:53 +03:00
seyko ad1c01f96c fix for the #include_next, v3
don't give an error and simply ingnore directive
  if we detect a loop of the #include_next.

  With this aproach coreutils-8.24.51-8802e
  compiles, but with errors:
  	lib/libcoreutils.a: error: 'xnmalloc' defined twice
	lib/libcoreutils.a: error: 'xnrealloc' defined twice
2015-10-19 17:55:26 +03:00
seyko 6b9490b6ff fix for the #include_next, v2
A more correct fix. This one don't break old logic.
    But if include file is not found, we try to search
    again with the new compare rule.

    A description of the problem:
    http://permalink.gmane.org/gmane.comp.compilers.tinycc.devel/2769
2015-10-17 15:48:10 +03:00
seyko ad524bb6c7 reverse a previous patch
a next version of the patch will follow
2015-10-17 15:32:33 +03:00
seyko 285292992f fix for the #include_next
skip include file only if include_file_name=current_file_name
2015-10-17 14:45:51 +03:00
seyko c3975cf27c parsing "..." sequence
don't panic with
	error: '.' expected
    if there is only two '.' chars. Return tok='.' in such case.
    An asm code to test:
	jz	do_move0	# .. then we have a normal low
				# .. or else we have a high
2015-10-17 13:54:58 +03:00
Edmund Grimley Evans f0b7566181 tccelf.c: Reset sym after call to build_got.
The call to build_got can cause symtab_section->data to be reallocated
(build_got -> add_elf_sym -> put_elf_sym -> section_ptr_add ->
section_realloc -> tcc_realloc). This is not obvious on a cursory
inspection, but fortunately Valgrind spotted it immediately.
Are there other, similar bugs that Valgrind did not detect?
2015-10-16 20:33:41 +01:00
Edmund Grimley Evans 743684fe39 tccpp.c: Avoid infinite loop on: printf '/**' | ./tcc - 2015-10-15 19:02:58 +01:00
Edmund Grimley Evans c899659d39 tccgen.c: Remove undefined shift of negative signed value. 2015-10-15 19:02:57 +01:00
Edmund Grimley Evans eafd7a7d3b Correct prototype: void __clear_cache(void *, void *). 2015-10-15 19:02:54 +01:00
Kamil Rytarowski a16f862cf6 Define CONFIG_TCC_ELFINTERP on NetBSD as /usr/libexec/ld.elf_so 2015-10-11 12:22:41 +02:00
Kamil Rytarowski 6cb74ecacf Define __WINT_TYPE__ as int in NetBSD 2015-10-11 11:59:20 +02:00
Kamil Rytarowski 5860b639c6 Add support for -D__NetBSD__ 2015-10-11 03:12:35 +02:00
seyko 00ba4b7625 win32: UUID typedef added 2015-09-25 03:42:44 +03:00
seyko 8077f0acc7 a number as a field name (part 2)
don't crash
    a test program:
    ================
    typedef struct X { int len; } X;
    #define init(s,len)  s.len = len;
    int main(void) {
	X myX;
	init(myX,10);
	return 0;
    }
    ================
    After a patch:
    	error: field name expected
2015-09-25 02:31:34 +03:00
seyko e7e7a0d301 a number as a field name
a test program:
    ========
    typedef struct X { int len; } X;
    int main(void) {
       X myX;
       myX.10 = 10;
       return 0;
    }
    ========
    Error message before a patch:
	error: ';' expected (got "(null)")
    After a patch:
	error: field name expected
2015-09-25 01:44:23 +03:00
seyko eb870b006c SSE opcodes to TCC assembler (i386, x86_64)
patch from Anaël Seghezzi
    a test program:
    ============================
    #include <stdio.h>
    struct fl4{ float x, y, z, w; };
    void asm_test(void)
    {
	struct fl4 v1, v2, v3;
	v1.x = 0.1;
	v1.y = 0.2;
	v1.z = 0.4;
	v1.w = 0.3;
	v2.x = 0.11;
	v2.y = 0.0;
	v2.z = 0.01;
	v2.w = 0.04;
	asm volatile (
	    "movups %0, %%xmm0;"
	    "movups %1, %%xmm1;"
	    "addps %%xmm1, %%xmm0;"
	    "movups %%xmm0, %2"
	:: "g" (v1), "g" (v2), "g" (v3) : "memory");
	printf("sse fl4 add : %f %f %f %f\n", v3.x, v3.y, v3.z, v3.w);
	printf("expected : %f %f %f %f\n", v1.x+v2.x, v1.y+v2.y, v1.z+v2.z, v1.w+v2.w);
    }
    int main() { asm_test(); }
    /*
	sse fl4 add : 0.210000 0.200000 0.410000 0.340000
	expected : 0.210000 0.200000 0.410000 0.340000
    */
    ============================
2015-09-23 14:58:06 +03:00
gus knight 8f620c8af8 Adding two more people to the RELICENSING file.
They also responded to my mail with a YES.
2015-07-31 16:56:23 -04:00
gus knight ef3d38c5c9 Revert "fix-mixed-struct (patch by Pip Cet)"
This reverts commit 4e04f67c94. Requested by grischka.
2015-07-29 16:57:41 -04:00
gus knight 89ad24e7d6 Revert all of my changes to directories & codingstyle. 2015-07-29 16:57:12 -04:00
gus knight 5a16f5ea98 Fix Makefile. 2015-07-29 09:59:17 -04:00
gus knight 7f5b95ea32 Fix formatting breakage from "rogue tabs" commit. 2015-07-29 09:59:11 -04:00
gus knight 271abe7117 Add a root Makefile for running targets in subdirectories. 2015-07-29 09:59:07 -04:00
gus knight 770fd39bd1 Relicensing TinyCC.
I've been sending a lot of mails out asking contributors if they
approve the license change, so I'm adding the ones who reply here.
2015-07-29 09:58:59 -04:00
Vincent Lefevre 07c6263732 typo in RELICENSING 2015-07-29 15:29:22 +02:00
Vincent Lefevre e667d0cc9c Relicensing TinyCC 2015-07-29 15:24:56 +02:00
gus knight 47e06c6d4e Reorganize the source tree.
* Documentation is now in "docs".
 * Source code is now in "src".
 * Misc. fixes here and there so that everything still works.

I think I got everything in this commit, but I only tested this
on Linux (Make) and Windows (CMake), so I might've messed
something up on other platforms...
2015-07-27 16:03:25 -04:00
gus knight 694d0fdade clang-format on arm-gen.c and tcccoff.c.
They now mostly follow the same coding style as everything else.
2015-07-27 14:26:15 -04:00
gus knight 9e1b6bf517 Update CodingStyle. 2015-07-27 14:25:50 -04:00
gus knight d6b64e2574 Clean up lots of rogue tabs.
Still some more tabs to be taken care of. arm-gen.c and tcccoff.c
have so many style issues that I'm just going to throw clang-format
at them.
2015-07-27 14:14:41 -04:00
gus knight 41031221c8 Trim trailing spaces everywhere. 2015-07-27 12:43:40 -04:00
gus knight 5e67f24e6b Relicensing TinyCC.
I haven't contributed anything yet, but I might as well add this :)
2015-07-27 12:39:54 -04:00
seyko 4e04f67c94 fix-mixed-struct (patch by Pip Cet)
Jsut for testing. It works for me (don't break anything)
    Small fixes for x86_64-gen.c in "tccpp: fix issues, add tests"
    are dropped in flavor of this patch.

    Pip Cet:

    Okay, here's a first patch that fixes the problem (but I've found
    another bug, yet unfixed, in the process), though it's not
    particularly pretty code (I tried hard to keep the changes to the
    minimum necessary). If we decide to actually get rid of VT_QLONG and
    VT_QFLOAT (please, can we?), there are some further simplifications in
    tccgen.c that might offset some of the cost of this patch.

    The idea is that an integer is no longer enough to describe how an
    argument is stored in registers. There are a number of possibilities
    (none, integer register, two integer registers, float register, two
    float registers, integer register plus float register, float register
    plus integer register), and instead of enumerating them I've
    introduced a RegArgs type that stores the offsets for each of our
    registers (for the other architectures, it's simply an int specifying
    the number of registers). If someone strongly prefers an enum, we
    could do that instead, but I believe this is a place where keeping
    things general is worth it, because this way it should be doable to
    add SSE or AVX support.

    There is one line in the patch that looks suspicious:

             } else {
                 addr = (addr + align - 1) & -align;
                 param_addr = addr;
                 addr += size;
    -            sse_param_index += reg_count;
             }
             break;

    However, this actually fixes one half of a bug we have when calling a
    function with eight double arguments "interrupted" by a two-double
    structure after the seventh double argument:

    f(double,double,double,double,double,double,double,struct { double
    x,y; },double);

    In this case, the last argument should be passed in %xmm7. This patch
    fixes the problem in gfunc_prolog, but not the corresponding problem
    in gfunc_call, which I'll try tackling next.
2015-05-14 07:32:24 +03:00
seyko 101cc8747f win32/include/winapi changes from https://github.com/run4flat/tinycc.git
just for testing. Is it needed? I'm not a MSYS citizen.

        run4flat is a tcc fork by David Mertens that knows how to work with
        multiple symbol tables. Excelent work. A good descriptions of the
        tcc internals inside a code comments.
2015-05-14 01:27:46 +03:00
seyko 80322adaa0 redo of the -dD option
functionality was broken some time ago and was removed
    by the "tccpp: fix issues, add tests"

    fix: LINE_MACRO_OUTPUT_FORMAT_NONE in pp_line()
    means: output '\n' and not "don't output at all"
2015-05-13 12:16:00 +03:00
seyko cf92f7aacb some -bench fixes
print stats to stderr, not to stdout
2015-05-12 22:02:51 +03:00
seyko 06e0753fce minor pp optimizations
* remove free_defines() from tcc_preprocess()
        all cleanup will be done in tcc_delete
    * move a preprocessor file closing to tcc_delete too
2015-05-12 21:32:32 +03:00
seyko 1234beccb8 restore a max memory usage printing for a new MEM_DEBUG when -bench 2015-05-12 16:07:09 +03:00
seyko c52e1a9af5 SYMBOL_NAME_LABEL(X) X##:
In the linux kernel sources:
      #ifdef __STDC__
        #define SYMBOL_NAME_LABEL(X) X##:
      #else
        #define SYMBOL_NAME_LABEL(X) X/**/:
      #endif
    tcc is a STDC compiler and must handle 'X##:' case.
2015-05-12 15:24:41 +03:00
seyko 121e95d115 a new version of the MEM_DEBUG 2015-05-12 11:56:39 +03:00
seyko a98fd13090 a mem leak fix for "ability to compile multiple *.c files with -c switch"
A new version of the MEM_DEBUG will be submitted next. This version is
    not depend on the malloc_usable_size() presense in the libc and
    print a places where a leaked chunks of memory was allocated.
2015-05-12 10:58:04 +03:00
seyko ae09051c81 allow to use MEM_DEBUG with libtcc 2015-05-11 18:05:31 +03:00
seyko cb7e820eae tcc_add_dll is not used if TCC_TARGET_PE
after "tccpp: fix issues, add tests"
2015-05-10 11:37:36 +03:00
seyko ff06d4258e define __OPTIMIZE__ if -ON (N != 0)
this is gcc behaviour
2015-05-10 10:21:37 +03:00
seyko c497f9c82c warn if multile -o option is given 2015-05-10 10:13:35 +03:00
seyko 87a0109604 restore "./configure --enable-tcc32-mingw" on linux
commit "tccpp: fix issues, add tests" also include
        - configure/Makefile : build on windows (MSYS) was broken
    which breaks a cross compilation on linux
2015-05-10 09:57:11 +03:00
grischka 30df3189b1 tccpp: fix issues, add tests
* fix some macro expansion issues
* add some pp tests in tests/pp
* improved tcc -E output for better diff'ability
* remove -dD feature (quirky code, exotic feature,
  didn't work well)

Based partially on ideas / researches from PipCet

Some issues remain with VA_ARGS macros (if used in a
rather tricky way).

Also, to keep it simple, the pp doesn't automtically
add any extra spaces to separate tokens which otherwise
would form wrong tokens if re-read from tcc -E output
(such as '+' '=')  GCC does that, other compilers don't.

 * cleanups
  - #line 01 "file" / # 01 "file" processing
  - #pragma comment(lib,"foo")
  - tcc -E: forward some pragmas to output (pack, comment(lib))
  - fix macro parameter list parsing mess from
    a3fc543459
    a715d7143d
    (some coffee might help, next time ;)
  - introduce TOK_PPSTR - to have character constants as
    written in the file (similar to TOK_PPNUM)
  - allow '\' appear in macros
  - new functions begin/end_macro to:
      - fix switching macro levels during expansion
      - allow unget_tok to unget more than one tok
  - slight speedup by using bitflags in isidnum_table

Also:
  - x86_64.c : fix decl after statements
  - i386-gen,c : fix a vstack leak with VLA on windows
  - configure/Makefile : build on windows (MSYS) was broken
  - tcc_warning: fflush stderr to keep output order (win32)
2015-05-09 14:29:39 +02:00
Philip 70a6c4601e VLA code: minor fix
Don't try to call get_flags() on the mob branch, where it's not defined.
2015-05-04 03:42:02 +00:00
seyko c75d0deecf VLA code minor fix 2015-05-04 04:19:24 +03:00
seyko 999274ca90 a lot simpler VLA code
Author: Philip <pipcet@gmail.com>
    Our VLA code can be made a lot simpler (simple enough for
    even me to understand it) by giving up on the optimization idea, which
    is very tempting. There's a patch to do that attached, feel free to
    test and commit it if you like. (It passes all the tests, at least
2015-05-04 04:09:05 +03:00
seyko fca58734fb -traditional and -iwithprefix options 2015-05-03 20:10:57 +03:00
seyko 576aeb3aa9 fix "tcc test.c -Wl,,--oformat,binary"
set linker options only when "s->output_type == TCC_OUTPUT_EXE"
    otherwise tcc will produce a wrong object file
2015-05-03 14:17:18 +03:00
seyko 2ba219f781 fix "tcc test.c -UAAA -UBBB"
no need to call tcc_free() inside tcc_undefine_symbol()
    Otherwise we get segmentation fault inside tcc_delete()
2015-05-03 13:58:27 +03:00
Philip 929d171f47 Mostly revert "tccpp.c: minor fix I'd accidentally not committed"
This reverts commit 27ec4f67a3.

Sorry about that, I included changes which are still being tested, by
accident.
2015-05-02 20:30:07 +00:00
Philip 27ec4f67a3 tccpp.c: minor fix I'd accidentally not committed
Sorry about that. This should definitely fix Sergey's issue.
2015-05-02 17:14:07 +00:00
Philip 3b4c42c3c0 minor fix
Fixes the issue reported by Sergey at
http://lists.nongnu.org/archive/html/tinycc-devel/2015-05/msg00007.html

I hope.
2015-05-02 16:49:12 +00:00
Philip 823d0583dc tccpp.c: unterminated macro argument error message
#define a(x) x
    a((

would produce "error: , expected" when what's actually expected is a
')'.
2015-05-02 14:47:11 +00:00
Philip 2f90db434e tccpp.c: fix GNU comma handling
This requires moving TOK_PLCHLDR handling, but the new logic should make
things easier even if (when?) GNU comma handling is removed.

(Somewhat confusingly, GCC no longer supports GNU commas. See
http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html for a description
of past and current GCC behaviour.)
2015-05-02 14:27:49 +00:00
Philip 2f50cefbd4 tccpp.c: restore whitespace after failed macro
This fixes test7 described in:

http://lists.nongnu.org/archive/html/tinycc-devel/2015-05/msg00002.html

Note that the current code still adds excessive forced blank characters
to its output, so this patch might not change visible behaviour.
2015-05-02 13:55:42 +00:00
Philip a6e6a954f5 tccpp.c: correct # stringification
Fix handling of escape characters, spaces, and line feeds in macros or
macro arguments that might yet be subject to # stringification.

Should this be an -f option? I think memory usage increases only very
slightly (in particular, while line feeds, stray \s, and spaces are
preserved, comments are not), so it's probably not worth it to make it
one.

Note that macro_subst now checks for stray \s which are still left in
the input stream after macro substitution, if desired.

This patch depends on the previous patch, so if you revert that, please
revert this patch, too.

See http://lists.nongnu.org/archive/html/tinycc-devel/2015-05/msg00002.html
2015-05-02 13:19:14 +00:00
Philip 0877ba7cbf tccpp.c: parse flag to accept stray \
This adds a PARSE_FLAG_ACCEPT_STRAYS parse flag to accept stray
backslashes in the source code, and uses it for pure preprocessing.

For absolutely correct behaviour of # stringification, we need to use
this flag when parsing macro definitions and in macro arguments, as
well; this patch does not yet do so. The test case for that is something
like

    #define STRINGIFY2(x) #x
    #define STRINGIFY(x) STRINGIFY2(x)

    STRINGIFY(\n)

which should produce "\n", not a parse error or "\\n".

See http://lists.nongnu.org/archive/html/tinycc-devel/2015-05/msg00002.html
2015-05-02 12:58:37 +00:00
Philip a3d78b95d7 tccpp.c: fix endless loop
Perhaps a better fix would be to ensure tok is set to TOK_EOF rather
than 0 at the end of a macro stream.

This partially fixes test2 of the examples given in:
http://lists.nongnu.org/archive/html/tinycc-devel/2015-05/msg00002.html

It's still failing, but at least it's not running out of memory now.
2015-05-02 12:33:45 +00:00
Philip 1e878200f7 tccpp.c: reset spc after macro_subst_tok()
This bug doesn't seem to affect anything currently, but does interfere
with miscellaneous tccpp.c fixes for the test cases described here:

http://lists.nongnu.org/archive/html/tinycc-devel/2015-05/msg00002.html
2015-05-02 12:26:10 +00:00
Philip 3a922ad2ba tccpp.c: fix ##-in-macros logic
The old code had an inverted condition, so

    #define a(b)## b

would be accepted while

    #define a(b,c) b ## ## c

would be rejected with the confusing error message "'##' invalid at
start of macro".
2015-05-02 12:14:14 +00:00
Philip a6b94eff79 tccpp.c: fix empty stringify
#define STRINGIFY2(x) #x
    #define STRINGIFY(x) STRINGIFY2(x)
    STRINGIFY()

should produce "", not "\301".
2015-05-01 14:48:25 +00:00
Philip 951a43ea6c fix a potential end-of-buffer issue in tccelf.c
also read characters one at a time when PARSE_DEBUG is set; after this
patch, things seem to work with that.
2015-04-30 21:35:21 +00:00
Philip 2e04fa8872 fix end-of-buffer error in tccpp.c
Quick fix for
http://lists.nongnu.org/archive/html/tinycc-devel/2015-04/msg00160.html.

I don't fully understand the intended semantics of when file->buf_ptr[0]
is valid, but the rest of the code doesn't have any obvious spots with
the same bug.

Feel free to revert this if I'm mistaken or we need to discuss this
change further.
2015-04-30 19:27:43 +00:00
Philip 4126056fbe fix vstack leak
I think this code only affects the ARM EABI target, and only when
returning small structures that might be unaligned. However, it was both
leaking vstack entries and failing to achieve what I think is its
purpose, to ensure the sret argument would be aligned properly. Both
issues fixed.
2015-04-29 21:48:30 +00:00
Philip 44c330d647 VLA fix: save stack pointer right after modification
This patch disables the optimization of saving stack pointers lazily,
which didn't fully take into account that control flow might not reach
the stack-saving instructions. I've decided to leave in the extra calls
to vla_sp_save() in case anyone wants to restore this optimization.

Tests added and enabled.

There are two remaining bugs: VLA variables can be modified, and jumping
into the scope of a declared VLA will cause a segfault rather than a
compiler error. Both of these do not affect correct C code, but should
be fixed at some point. Once VLA variables have been made properly
immutable, we can share them with the saved stack pointer and save stack
and instructions.
2015-04-28 09:23:29 +00:00
Philip d2dd6fdbfb fix VLA/continue issue
as reported in
http://lists.nongnu.org/archive/html/tinycc-devel/2015-04/msg00131.html. Note
that this is one of two separate VLA bugs:

 A. labels aren't reached by program execution, so the stack pointer is
 never saved
 B. continue doesn't restore the stack pointer as goto does

This fixes only B. I'm not sure whether the same issue applies to break
as well as continue.

Add a test case, but disable tests #78 and #79 for now as they're not
fully fixed until the issue described in
http://lists.nongnu.org/archive/html/tinycc-devel/2015-04/msg00110.html
is resolved.
2015-04-27 16:42:27 +00:00
Philip bd489a4815 add test case for VLA segfaults
This test obviously shouldn't segfault, but currently does so. The
problem is in the VLA code, which fails to save the stack pointer before
taking a conditional branch in some cases.

See this thread:
http://lists.nongnu.org/archive/html/tinycc-devel/2015-04/msg00130.html
2015-04-27 14:55:23 +00:00
seyko bbcb54a1f4 replace PARSE_FLAG_ASM_COMMENTS with PARSE_FLAG_ASM_FILE
after "assign PARSE_FLAG_ASM_COMMENTS only for asm files"
    functions of this flags are identical
2015-04-27 16:36:58 +03:00
Philip 2e51f0ee63 warn about declarations after statements when compiling with gcc. 2015-04-27 13:28:03 +00:00
seyko 1351de6ad1 fixes for "tcc -E -dD"
* print "// #pragma push_macro(XXX)"
    * keep output line numbers in sync with source
      (don't output \n in printf)
2015-04-27 16:04:54 +03:00
seyko 2df290073b preprocess: "assign PARSE_FLAG_ASM_COMMENTS only for asm files"
resolve a problem with the following test.c program, tcc -E test.c

    #ifdef	_XOPEN_SOURCE
    # define __USE_XOPEN	1
    # if (_XOPEN_SOURCE - 0) >= 500
    #  define __USE_XOPEN_EXTENDED	1
    #  define __USE_UNIX98	1
    #  undef _LARGEFILE_SOURCE
    #  define _LARGEFILE_SOURCE	1
    #  if (_XOPEN_SOURCE - 0) >= 600
    #   define __USE_XOPEN2K	1
    #   undef __USE_ISOC99
    #   define __USE_ISOC99		1
    #  endif
    # else
    #  ifdef _XOPEN_SOURCE_EXTENDED
    #   define __USE_XOPEN_EXTENDED	1
    #  endif
    # endif
    #endif

    int main() {}

    // # 17 "aaa.c"
    // aaa.c:17: error: #endif without matching #if
2015-04-27 15:25:49 +03:00
Philip 2d3458363e fix another x86_64 ABI bug
The old code assumed that if an argument doesn't fit into the available
registers, none of the subsequent arguments do, either. But that's
wrong: passing 7 doubles, then a two-double struct, then another double
should generate code that passes the 9th argument in the 8th register
and the two-double struct on the stack. We now do so.

However, this patch does not yet fix the function calling code to do the
right thing in the same case.
2015-04-26 17:31:39 +00:00
Philip 8d44851d65 Fix zero-length struct/union test. Remove nonsensical test.
The comment suggests this was meant to detect unions, but in fact it
compared f->c, the union/struct size, against f->next->c, the first
element's offset.

This affected only zero-length structs/unions with a first (zero-length)
element, as in this code:

    struct u2 {
    };

    struct u {
      struct u2 u2;
    } u;

    struct u f(struct u x)
    {
      return x;
    }

However, such structures turned out to be broken anyway, as code like this
was generated for the above f:

0000000000000000 <f>:
   0:   55                      push   %rbp
   1:   48 89 e5                mov    %rsp,%rbp
   4:   48 81 ec 10 00 00 00    sub    $0x10,%rsp
   b:   66 0f d6 45 f8          movq   %xmm0,-0x8(%rbp)
  10:   66 0f 6e 45 f8          movd   -0x8(%rbp),%xmm0
  15:   e9 00 00 00 00          jmpq   1a <f+0x1a>
  1a:   c9                      leaveq
  1b:   c3                      retq
2015-04-25 19:25:23 +00:00
Philip 1dd3f88f3b x86_64 ABI tests, which currently cause failures
With the x86_64 Linux ELF ABI, we're currently failing two of these
three tests, which have been disabled for now.  The problem is mixed
structures such as struct { double x; char c; }, which the x86_64 ABI
specifies are to be passed/returned in one integer register and one SSE
register; our current approach, marking the structure as VT_QLONG or
VT_QFLOAT, fails in this case.

(It's possible to fix this by getting rid of VT_QLONG and VT_QFLOAT
entirely as at https://github.com/pipcet/tinycc, but the changes aren't
properly isolated at present. Anyway, there might be a less disruptive
fix.)
2015-04-25 18:51:26 +00:00
seyko 9cbab3630e a test for the #pragma push/pop_macro 2015-04-25 15:03:50 +03:00
grischka 72e8ff11e9 tccpp: alternative #pragma push/pop_macro
using next_nomacro() so that for example
    #define push_macro foobar
does not affect how the pragma works (same behavior
as gcc, albeit not MS's cl).
2015-04-23 23:27:36 +02:00
grischka 7c27186a83 Revert "* and #pragma pop_macro("macro_name")"
- pop_macro incorrect with initially undefined macro
- horrible implementation (tcc_open_bf)
- crashes eventually (abuse of Sym->prev_tok)

- the (unrelated) asm_label part is the opposite of a fix
  (Despite of its name this variable has nothing to do with
  the built-in assembler)

This reverts commit 0c8447db79.
2015-04-23 23:26:46 +02:00
Philip 059aea5d35 fix a subtle x86-64 calling bug
I ran into an issue playing with tinycc, and tracked it down to a rather
weird assumption in the function calling code. This breaks only when
varargs and float/double arguments are combined, I think, and only when
calling GCC-generated (or non-TinyCC, at least) code. The problem is we
sometimes generate code like this:

804a468: 4c 89 d9 mov %r11,%rcx
804a46b: b8 01 00 00 00 mov $0x1,%eax
804a470: 48 8b 45 c0 mov -0x40(%rbp),%rax
804a474: 4c 8b 18 mov (%rax),%r11
804a477: 41 ff d3 callq *%r11

for a function call. Note how $eax is first set to the correct value,
then clobbered when we try to load the function pointer into R11. With
the patch, the code generated is:

804a468: 4c 89 d9 mov %r11,%rcx
804a46b: b8 01 00 00 00 mov $0x1,%eax
804a470: 4c 8b 5d c0 mov -0x40(%rbp),%r11
804a474: 4d 8b 1b mov (%r11),%r11
804a477: 41 ff d3 callq *%r11

which is correct.

This becomes an issue when get_reg(RC_INT) is modified not always to
return %rax after a save_regs(0), because then another register (%ecx,
say) is clobbered, and the function passed an invalid argument.

A rather convoluted test case that generates the above code is
included. Please note that the test will not cause a failure because
TinyCC code ignores the %rax argument, but it will cause incorrect
behavior when combined with GCC code, which might wrongly fail to save
XMM registers and cause data corruption.
2015-04-23 18:08:28 +00:00
Philip aacf65bbfa Bugfix: 32-bit vs 64-bit bug in x86_64-gen.c:gcall_or_jmp
Verify an immediate value fits into 32 bits before jumping to it/calling
it with a 32-bit immediate operand. Without this fix, code along the
lines of

  ((int (*)(const char *, ...))140244834372944LL)("hi\n");

will fail mysteriously, even if that decimal constant is the correct
address for printf.

See https://github.com/pipcet/tinycc/tree/bugfix-1
2015-04-23 17:30:16 +00:00
seyko b08ce88082 "#pragma once" implementation 2015-04-21 15:46:29 +03:00
seyko 0c8447db79 * and #pragma pop_macro("macro_name")
* give warning if pragma is unknown for tcc
    * don't free asm_label in sym_free(),
      it's a job of the asm_free_labels().

    The above pragmas are used in the mingw headers.
    Thise pragmas are implemented in gcc-4.5+ and current
    clang.
2015-04-21 06:34:35 +03:00
Ramsay Jones 5e8fb713c4 add missing test from -fdollar-in-identifiers commit
Commit 5ce2154c ("-fdollar-in-identifiers addon", 20-04-2015) forgot
to include the test files from Daniel's patch.

Signed-off-by: Ramsay Jones <ramsay@ramsay1.demon.co.uk>
2015-04-20 12:03:45 +01:00
seyko 5ce2154c74 -fdollar-in-identifiers addon
* disable a -fdollar-in-identifiers option in assembler files
    * a test is added

    This is a patch addon from Daniel Holden.
2015-04-20 03:44:08 +03:00
Thomas Preud'homme 9336fa7ae5 Fix program symbols exported in dynsym section
Prior to this commit TinyCC was exporting symbols defined in programs
only when they resolve an undefined symbol of a library. However, the
expected behavior (see --export-dynamic in GNU ld manpage) is that all
symbols used by libraries and defined by a program should be exported in
dynsym section. This is because symbol resolution search first in
program and then in libraries, thus allowing program symbol to interpose
symbol defined in a library.
2015-04-18 15:34:04 +08:00
seyko b472d53672 clarify error message when library not found
a prior error message: cannot find 'program_resolve_lib'
    after a patch: cannot find library 'libprogram_resolve_lib'
2015-04-16 07:30:24 +03:00
Steven G. Messervey aeaff94ec1 implement #pragma comment(lib,...) 2015-04-15 22:56:21 -04:00
Steven G. Messervey e50d68e417 Revert "implement #pragma comment(lib,...)"
This reverts commit 8615bb40fb.

Reverting as it breaks on MinGW targets
2015-04-15 21:24:15 -04:00
Steven G. Messervey 8615bb40fb implement #pragma comment(lib,...) 2015-04-15 17:00:26 -04:00
seyko a13f183e4c ability to compile multiple *.c files with -c switch
Usage example: tcc -c -xc ex5.cgi -xn ex2.c ex7.c ex6.cgi
2015-04-12 15:39:48 +03:00
seyko 0536407204 ability to specify a type of the input file with the -x switch
Usage example: tcc -xc ex5.cgi
    From a gcc docs:

    You can specify the input language explicitly with the -x option:

    -x language
    Specify explicitly the language for the following input files
    (rather than letting the compiler choose a default based on the file
    name suffix). This option applies to all following input files until
    the next -x option. Possible values for language are:

        c  c-header  c-cpp-output
        c++  c++-header  c++-cpp-output
        objective-c  objective-c-header  objective-c-cpp-output
        objective-c++ objective-c++-header objective-c++-cpp-output
        assembler  assembler-with-cpp
        ada
        f77  f77-cpp-input f95  f95-cpp-input
        java

    -x none
    Turn off any specification of a language, so that subsequent files
    are handled according to their file name suffixes (as they are if -x
    has not been used at all)
2015-04-12 15:35:37 +03:00
seyko dcb36587b5 -fdollar-in-identifiers switch which enables '$' in identifiers
library Cello: http://libcello.org/ which uses `$` and several
    variations of as macros.

    There is also RayLanguage which also uses it as a macro for a kind of
    ObjC style message passing: https://github.com/kojiba/RayLanguage

    This is a patch from Daniel Holden.
2015-04-12 15:32:03 +03:00
seyko e8ad336ac5 A new file CodingStyle with rules for indentation 2015-04-12 09:26:28 +03:00
seyko e7a60e4d01 replace a method to force bcheck.o linking
* define __bound_init as external_global_sym insteed of the compiling
      a tiny program
    * remove warning about buf[] when CONFIG_TCC_BCHECK is not defined
2015-04-12 04:47:15 +03:00
seyko 4bb9dd44f1 Fix for Microsoft compilers
Correction for the commit db08122d31
    As pointed Thomas Preud'homme buf[] may be used outside of the block
    whit code:
        name = block;
2015-04-11 16:22:34 +03:00
seyko 5c9dde7255 option to use an old algorithm of the array in struct initialization
This is for a case when no '{' is used in the initialization code.
    An option name is -fold-struct-init-code. A linux 2.4.26 can't
    find initrd when compiled with a new algorithm.
2015-04-10 23:44:10 +03:00
seyko 92efee6e52 fix "handle a -s option" commit
for targets which don't support variable length arrays.
2015-04-10 17:35:54 +03:00
seyko d81611b641 fix a preprocessor for .S
Lets assume that in *.S files a preprocessor directive
    follow '#' char w/o spaces between. Otherwise there is
    too many problems with the content of the comments.
2015-04-10 16:53:29 +03:00
seyko 8037a1ce39 fix a preprocessor for .S
A test program (tcc -E test.S):
      # .. or else we have a high. This is a test.S
2015-04-10 16:40:30 +03:00
seyko 70dbe169b2 fix a preprocessor for .S
* tell a right line number in error message
      if a #line directive is wrong

    * don't print an error message if we preprocess a .S file
      and #line directive is wrong. This is the case of
      the
        # 4026 bytes
      comment in *.S file.

    * preprocess_skip: skip a line with
	    if (parse_flags & PARSE_FLAG_ASM_COMMENTS)
       		p = parse_line_comment(p);
      if line starts with # and a preprocessor command not found.

      A test program:
      #if defined(CONFIG_EDD) || defined(CONFIG_EDD_MODULE)
	# This repeats until either a device doesn't exist, or until
      #endif

    * remove a second definition of the TOK_FLAG_* and PARSE_FLAG_*
      from the tccpp.c
2015-04-10 16:31:12 +03:00
seyko 559675b90a a bounds checking code for the ARCH=x86_64 2015-04-10 15:17:22 +03:00
seyko e92dc595cd Add a demo.bat file to the examples directory on Windows
And a new console demo program: taxi and passengers simulator
2015-04-10 07:46:04 +03:00
seyko 7e7e6148fd fix installation amd bcheck for Windows
* define targetos=Windows when --enable-tcc32-mingw, --enable-cygwin, ...
    * use TARGETOS insteed HOST_OS when selecting PROGS
    * use "$(tccdir)" insteed $(tccdir) on install (spaces in path)
    * install tcc.exe too
    * produce bcheck.o when cross-compiling too (lib/Makefile)
    * force bcheck.o linking by compiling inside tcc_set_output_type()
      a dummy program with local array. Otherwise bcheck.o may be not linked.
    * replace %xz format specifier with %p in bcheck (don't supported on
      Windows)
    * call a __bound_init when __bound_ptr_add, __bound_ptr_indir,
      __bound_new_region, __bound_delete_region called.
      This is because a __bound_init inside ".init" section is not called
      on Windows for unknown reason.
    * print on stderr a message when an illegal pointer is returned:
        there is no segmentation violation on Windows for a program
        compiled with "tcc -b"
    * remove "C:" subdir on clean if $HOST_OS = "Linux"
    * default CFLAGS="-Wall -g -O0" insteed CFLAGS="-Wall -g -O2"
      to speed up compilation and more precise debugging.
2015-04-10 07:37:31 +03:00
seyko 5cd4393a54 handle a -s option by executing sstrip/strip program 2015-04-10 06:53:48 +03:00
seyko 089ce6235c output all sections if we produce an executable file
tcc w/o -g option generate an executable file which format
    is not recognized by binutils. It is like stripped one but
    binutils don't think so. Solution: generate not stripped
    file which can be correctly stripped by external utils.

    may be there is a need to handle a -s option and call
    a sstrip/strip program to do a job.
2015-04-10 06:49:24 +03:00
seyko 3c372b4c8a remove a compilation warnings for libtest and test3
------------ libtest ------------
    ./libtcc_test lib_path=..
    <string>:11: warning: implicit declaration of function 'printf'
    <string>:13: warning: implicit declaration of function 'add'
    ------------ test3 ------------
    tcctest.c:1982: warning: implicit declaration of function 'putchar'
    tcctest.c:2133: warning: implicit declaration of function 'strlen'
2015-04-10 06:44:34 +03:00
seyko dec959358a fix the bug #31403: parser bug in structure
- a warning: unnamed struct/union that defines no instances
    - allow a nested named struct declaration w/o identifier
      only when option -fms-extensions is used
2015-04-10 06:31:58 +03:00
Raphael Cohn 9fc3d66f1b Fix to accommodate missing i386/bcheck.o during install on Mac OS X 2015-04-07 16:34:37 +01:00
Raphael Cohn aa6946b92c Fix to test for HOST_OS not TARGETOS 2015-04-07 16:06:43 +01:00
Raphael Cohn 50fc86a447 Fixing bug for Linux x86_64 introduced in previous macosx commit 2015-04-07 15:55:41 +01:00
Raphael Cohn 2ba7542e4b Adjusted configure host_os to use uname for Darwin
Adjusted Makefile to make it Darwin (Mac OS X 10.10)-friendly for cross-compilers
by removing the creation of arm64 cross-compilers on this platform.
2015-04-07 15:44:54 +01:00
Raphael Cohn fa0eff949d Adjusted configure to be more BSD friendly 2015-04-07 15:18:34 +01:00
seyko 96debc72f8 a small revers for bcheck.o changes (d80593bc4d)
replacing (addr > e->size) with (addr >= e->size)
    was correct only in one place, a second replacing
    is reversed by this commit.
2015-03-30 06:15:47 +03:00
seyko db08122d31 Fix for Microsoft compilers
Miccrosoft Visual Sudio (Express) 2008 and 2010 do not accept variable
    definitions C99 style, reported by Fabio <oldfaber@gmail.com>
2015-03-29 11:52:16 +03:00
seyko d80593bc4d fix for the bcheck.o (bug #14958)
- care about __attribute__ redefinition in the system headers
    - an invalid pointer must be returned when (addr >= e->size),
      and not (addr > e->size)

    A test program:
    #include <stdio.h>
    #include <stdlib.h>
    int main ()
    {
	int v[10];
	fprintf(stderr, "&v[0]  = %p\n", &v[0]);
	fprintf(stderr, "&v[10] = %p\n", &v[10]);
	exit(1);
	return 0;
    }
    // tcc -b test.c

    The output before a patch:
    &v[0]  = 0xbf929d8c
    &v[10] = 0xbf929db4

    The output after a patch:
    &v[0]  = 0xbff6e33c
    &v[10] = 0xfffffffe
2015-03-29 11:28:02 +03:00
seyko f2cfc07554 fix: try to add a bounds.o only if __bounds_init not found
/usr/local/lib/tcc/i386/bcheck.o: error: '__bound_error_msg' defined twice
    #include <stdio.h>
    int main ()
    {
        #if 1
    	    int v[10];
            v[10] = 0;
            fprintf(stderr, "is bounds error catched?\n");
        #endif
        return 0;
    }
    // tcc -b test.c
2015-03-28 19:41:01 +03:00
seyko 3b7f5008fd fix for the previous commit (compilation on RPi) 2015-03-26 11:28:11 +03:00
seyko acef4ff244 make a bound checking more compatible with Windows 64
On Linux 32:   sizeof(long)=32 == sizeof(void *)=32
    on Linux 64:   sizeof(long)=64 == sizeof(void *)=64
    on Windows 64: sizeof(long)=32 != sizeof(void *)=64
2015-03-26 07:47:45 +03:00
seyko 548a55eda5 fix for the previous commit: tcc_add_support() was used before definition 2015-03-26 06:22:37 +03:00
seyko a105837aae fix: enforce bcheck.o linking when -b option is used
fixes a crash for the empry program (tcc -b empty.c)
    empty.c: int main() { return 0; }
2015-03-26 06:04:36 +03:00
seyko cde79a805e fix a bug #43984: tcc -run reports errno=2
The following program (errno.c) reports errno=2 when run
    using "tcc -run errno.c"

    #include <errno.h>
    #include <stdio.h>
    int main(void) { printf("errno=%d\n", errno); return 0; }
2015-03-25 13:26:11 +03:00
seyko 724425addf fix for a -dumpversion option: move it before -dD
Options must be sorted and a long one must preceed a short one.
What was before:
    tcc -dumpversion
    tcc: error: invalid option -- '-dumpversion'
2015-03-23 20:58:27 +03:00
seyko 8f6390061d fix for: x86_64-tcc compiled by i386-tcc is wrong
A test program (must be compiled by the above version of the tcc):

    /* Tickle a bug in TinyC on 64-bit systems:
     * the LSB of the top word or ARGP gets set
     * for no obvious reason.
     *
     * Source: a legacy language interpreter which
     * has a little stack / stack pointer for arguments.
     *
     * Output is: 0x8049620 0x10804961c
     * Should be: 0x8049620 0x804961c
     */
    #include <stdio.h>
    #define NARGS 20000
    int ARG[NARGS];
    int *ARGSPACE = ARG;
    int *ARGP = ARG - 1;
    main() { printf("%p %p\n", ARGSPACE, ARGP); }
2015-03-23 19:24:55 +03:00
seyko 8dbe129ab7 fix a gcc compiler warning for the previous commit
mark a constant as long long (or -std=gnu99 is needed)
2015-03-23 16:36:09 +03:00
seyko c2efd7c53b revert a commit: Work around for the issue TCC doesn't handle -2147483648 properly
because a tcc handle now -2147483648 properly. Look a commit:
    Make integer constant parsing C99 compliant
2015-03-23 15:31:10 +03:00
seyko bd531ec1fd A right fix for the array in struct initialization w/o '{'
Parse a type if there is only one '(' before a type token.
Otherwise a recursion will perform a job.
2015-03-23 08:27:16 +03:00
seyko 367bb6f4b7 Revert of the commit: fix for the array in struct initialization w/o '{', case 2
A right solution for this problem will follow.
2015-03-23 07:40:41 +03:00
seyko aba2d648f4 quick fix for the native tcc on debian/ubuntu
Force to use a NATIVE_DEFINES insteed of the DEFINES for the
    native tcc. After this change we have on debian/ubuntu

    # ./x86_64-tcc -vv
    tcc version 0.9.26 (x86-64, Linux)
    install: /usr/local/lib/tcc
    crt:
      /usr/lib/x86_64-linux-gnu
    libraries:
      /usr/lib/x86_64-linux-gnu
      /usr/lib
      /lib/x86_64-linux-gnu
      /lib
      /usr/local/lib/x86_64-linux-gnu
      /usr/local/lib
    include:
      /usr/local/include/x86_64-linux-gnu
      /usr/local/include
      /usr/include/x86_64-linux-gnu
      /usr/include
      /usr/local/lib/tcc/include
    elfinterp:
      /lib64/ld-linux-x86-64.so.2

    Before this change the output was
    # ./x86_64-tcc -vv
    tcc version 0.9.26 (x86-64, Linux)
    install: /usr/local/lib/tcc
    crt:
      /usr/lib
    libraries:
      /usr/lib
      /lib
      /usr/local/lib
    include:
      /usr/local/include
      /usr/include
      /usr/local/lib/tcc/include
    elfinterp:
      /lib64/ld-linux-x86-64.so.2

    This change don't fix a cross compilers
2015-03-22 18:05:29 +03:00
seyko b5d25654d8 configure: don't output CONFIG_LDDIR when build_cross = "yes"
This fixes i386-tcc on CentOS 7. After patch
    [root@centos7 tinycc]# ./i386-tcc -vv
    tcc version 0.9.26 (i386, Linux)
    install: /usr/local/lib/tcc
    crt:
      /usr/lib
    libraries:
      /usr/lib
      /lib
      /usr/local/lib

Before patch:
    [root@centos7 tinycc]# ./i386-tcc -vv
    tcc version 0.9.26 (i386, Linux)
    install: /usr/local/lib/tcc
    crt:
      /usr/lib64
    libraries:
      /usr/lib64
      /lib64
      /usr/local/lib64
2015-03-21 07:16:33 +03:00
seyko 63d068d3f2 skip 73_arm64,test on ARCH=x86-64: it fails on this ARCH 2015-03-20 16:01:06 +03:00
seyko 78c076a70f restore a linux 2.4.26 kernel compilation (commit 5bcc3eed7b correction)
The following check in tccgen.c is removed
    if (nocode_wanted)
	tcc_error("statement expression in global scope");
This check is introduced in commit 5bcc3eed7b and breaks compilation
of the linux 2.4.26 kernel.
2015-03-20 10:44:26 +03:00
seyko e3851d233f correction for the previous commit
use "x86-64" as a directory name for the libtcc1.a installation when cross-compiling.
2015-03-20 09:27:59 +03:00
seyko cfaa165e62 libtcc1.a while "configure --enable-cross"
build and install libtcc1.a for i386, x86_64 and arm64
    (libtcc1.a for x86_64 was not installed on i386)
2015-03-20 08:52:01 +03:00
seyko 3dba9cc13d "configure --enable-cross" on x86: build a libtcc1.a for x86_64 2015-03-19 13:07:02 +03:00
seyko e2650608cd fix to allow build tcc by build-tcc.bat
move call to print_defines() from tcc.c to the libtcc.c
    define a print_defines() as a ST_FUNC
2015-03-19 08:07:35 +03:00
Edmund Grimley Evans aa812e8745 Convert some lines from ISO-8859-1 to UTF-8.
perl -i -pe 'use Text::Iconv;
$c1 = Text::Iconv->new("utf-8", "utf-8");
$c2 = Text::Iconv->new("iso-8859-1", "utf-8");
if (!$c1->convert($_)) { $_ = $c2->convert($_); }' \
`find * -type f`
2015-03-11 07:30:03 +00:00
Edmund Grimley Evans 5de8b5638f .gitignore: Add lib/arm64. 2015-03-10 22:38:26 +00:00
Edmund Grimley Evans 0e79df499a tccgen.c: (!nocode_wanted) -> (nocode_wanted) in arm64 part. 2015-03-10 22:37:36 +00:00
Thomas Preud'homme 5bcc3eed7b Add some missing nocode_wanted guard
int i = i++ causes a segfault because of missing guard. Looking
recursively at all backend functions called from middle end several more
guard appeared to be missing.
2015-03-10 23:27:14 +08:00
Edmund Grimley Evans 68605ab4d4 lib/Makefile: Partial revert of 896a0c881a.
lib/lib-arm64.c must be compiled by tcc.
2015-03-10 14:08:42 +00:00
seyko 4ba7e5dc5a A correction for the commit: revert a grischka patch: gdb refused to know "main"
keep revert (check SHF_ALLOC) only for x86 target and keep a grishka patch for
other targets
2015-03-10 14:21:14 +03:00
seyko 896a0c881a don't use a *-tcc to compile *.S files for ARM*
A tcc for ARM* don't have an assembler. This is partial reverse of the commit
  build-libtcc1-by-tcc: use a new tcc to compile a libtcc1.c and alloca.S
2015-03-10 13:54:12 +03:00
seyko 87ec08ecc8 A native tcc for MSYS (Windows) must be i386-win-tcc.exe and not i386-tcc.exe
i386-tcc.exe is a compiler for i386 Linux. A HOST_OS variable in Makefile is
introduced and used to select a native compiler (which one to name as tcc.exe)
2015-03-10 13:39:26 +03:00
Michael Matz 25b2779c3d x86-64: Fix stdarg for large non-float structs
Some structs are passed in registers.  When they need more than
one the implementation of __va_arg on x86-64 didn't correctly account
for this.  This fixes only the cases where the structs consist of
integer types, as there the register save area is consecutive.

Fixes some tests from 73_arm64.c, but still leaves those failing
that use floating point in the large-but-regpassed structs.
2015-03-09 03:54:33 +01:00
Michael Matz 2eb4f4a3ba Remove incorrect comment
Not the code was confused, I was :)
2015-03-09 01:33:42 +01:00
Michael Matz 0ecee0072d Find libtcc1.a on arm32
The directory is called "arm", not "ARM".
2015-03-09 00:47:27 +01:00
Michael Matz 50899e30ab Fix stack overwrite on structure return
The common code to move a returned structure packed into
registers into memory on the caller side didn't take the
register size into account when allocating local storage,
so sometimes that lead to stack overwrites (e.g. in 73_arm64.c),
on x86_64.  This fixes it by generally making gfunc_sret also return
the register size.
2015-03-09 00:19:59 +01:00
Edmund Grimley Evans d73b488401 arm64: Implement __clear_cache.
__clear_cache is defined in lib-arm64.c with a single call to
__arm64_clear_cache, which is the real built-in function and is
turned into inline assembler by gen_clear_cache in arm64-gen.c
2015-03-08 00:10:44 +00:00
Edmund Grimley Evans 03303628c7 tests/Makefile: Quote to avoid: /bin/sh: 1: [: !=: unexpected operator 2015-03-07 18:10:45 +00:00
Edmund Grimley Evans d854dede03 arm64: Optimise some integer operations with a constant operand. 2015-03-07 17:42:08 +00:00
Edmund Grimley Evans ac70e6b840 tccgen.c: Optimise 0<<x, 0>>x, -1>>x, x&0, x*0, x|-1, x%1.
More precisely, treat (0 << x) and so on as constant expressions, but
not if const_wanted as we do not want to allow "case (x*0):", ...

Do not optimise (0 / x) and (0 % x) here as x might be zero, though
for an architecture that does not generate an exception for division
by zero the back end might choose to optimise those.
2015-03-07 17:32:39 +00:00
Edmund Grimley Evans 9163393476 arm64-gen.c: In load(), do not sign-extend 32-bit VT_CONST. 2015-03-07 17:32:39 +00:00
seyko 8d4c861144 fix for the array in struct initialization w/o '{', case 2
a test program:

    struct {
    int a[2], b[2];
    } cases[] = {
	{ ((int)0), (((int)0)) },
	((int)0), (((int)0)) /* error: ',' expected (got ")") */
    };
    int main() { return 0; }

This commit allow to skip ')' in the decl_initializer() and to see ','
2015-03-07 09:40:12 +03:00
Edmund Grimley Evans 238e760a29 Add __builtin_return_address.
Implementation is mostly shared with __builtin_frame_address.
It seems to work on arm64, i386 and x86_64. It may need to be
adapted for other targets.
2015-03-06 21:01:14 +00:00
seyko 8764993c0d Makefile: install tcc$(EXESUF) as symlink to the $(ARCH)-tcc 2015-03-06 17:13:45 +03:00
seyko 65a4fbd1d4 Makefile: add dependencies for $($(I386_CROSS)_LINK), ...
This is another solution for the make process.
    Commit 4b92dbf923 is reverted.
2015-03-06 16:19:10 +03:00
Roy 883aafc6bb Makefile leftover of rev 44c6e99 2015-03-06 10:25:47 +08:00
seyko d9b87c087c fixing decl_initializer() for size_only: don't eat ')'
a test program:

    struct { int c[1]; } s1[] = { (int)0       }; /* OK */
    struct { int c[1]; } s2[] = { { ((int)0) } }; /* OK */
    struct { int c[1]; } s3[] = { 0            }; /* OK */
    struct { int c[1]; } sx[] = { ((int)0)     }; /* error: ')' expected (got "}") */
    int main() { return 0; }
2015-03-05 20:18:25 +03:00
seyko 4b92dbf923 Add a dependency for a PROGS and TCCLIBS to a Makefile
Simply assume this is all *.c and *.h files in a tcc top directory.
    Now a tcc compiler is recompiled if any of this files is changed.
2015-03-05 16:39:25 +03:00
Roy 44c6e992bd Fix compiling in MinGW/MSYS 2015-03-05 09:12:42 +08:00
Edmund Grimley Evans 3fb8b14806 tccelf.c: File path component is "arm64", not "ARM64". 2015-03-04 19:43:29 +00:00
seyko 664c19ad5e partial revert of the commit 4ad186c5ef
A test program:

    /* result of the new version inroduced in 4ad186c5ef61: t2a = 44100312 */
    #include<stdio.h>
    int main() {
	int t1 = 176401255;
	float f = 0.25f;
	int t2a = (int)(t1 * f); // must be 44100313
	int t2b = (int)(t1 * (float)0.25f);
	printf("t2a=%d t2b=%d \n",t2a,t2b);
	return 0;
    }
2015-03-04 16:25:51 +03:00
seyko bfb7b0d959 --enable-tcc32-mingw option: build windows version on linux with i386-win-tcc
--enable-tcc64-mingw option: build windows version on linux with x86_64-win-tcc
2015-03-04 12:02:13 +03:00
seyko 48d12e42ad gcc options and mingw: move a gcc options detection from a makefile to the configure
+ define XCC and XAR if mingw32 defined
    + use XCC and XAR in lib/Makefile if defined
    Try "./configure --enable-mingw32; make". This must work
2015-03-04 11:47:52 +03:00
seyko 76af948623 install-clean-tuning
* Don't use /usr/local/lib/tcc/libtcc1.a for i386 and x86_64
      A $(tccdir)/i386 directory was used to install a libtcc1.a
      but only when cross compiling. And no x86_64 directory.

    * Build/install i386-tcc/x86_64-tcc and not a tcc
    * Build/install i386-win-tcc/x86_64-win-tcc and not a i386-win-mingw32-tcc/...
    * DEFINES = -DTCC_TARGET_I386... also for i386-tcc and i386-win-tcc
    * Make a symlink tcc to the i386-tcc/x86_64-tcc for a "make test"
    * Build a $(ARCH) directory with a symlink to the libtcc1.a for a "make test"
    * Remove a /usr/local/lib/tcc directory on uninstall
    * Remove a /usr/local/share/doc/tcc directory on uninstall
    * Remove a $(ARCH) directory on "make clean"
    * Remove a *-tcc files on "make clean"
2015-03-04 11:40:33 +03:00
seyko 54fc439e9e an unification of the tcc cross names for a windows
produce a
      i386-win-mingw32-tcc
      i386-win-tcc
      x86_64-win-mingw32-tcc
      x86_64-win-tcc
      arm-win-mingw32ce-tcc
      arm-win-tcc

    instead of the
      i386-w64-mingw32-tcc
      i386-win32-tcc
      x86_64-w64-mingw32-tcc
      x86_64-win32-tcc
      arm-wince-mingw32ce-tcc
      arm-win32-tcc

    Replacing a *-win32 directory names with a *-win names
    because this names are based on the names of the tcc
    	x86_64-win32-tcc, i386-win32-tcc
2015-03-04 11:19:39 +03:00
seyko 1cbb4d322b build-libtcc1-by-tcc: use a new tcc to compile a libtcc1.c and alloca.S
This will allow to build a libtcc1.a even if a bootstrap compiler
don't support a target arch.

There was alrady this feature but only for OS Darwin.
2015-03-04 11:08:16 +03:00
seyko 7ed4341538 a libraries paths
* x86_64-tcc: use /usr/lib64,.. instead of /usr/lib,..
    * don't set tcc_lddir="lib64" if cpu="x86"
    * put a definition of the CONFIG_LDDIR into config.h instead
      of the config.mak  Otherwise a "lib" string may be used by default.
      This is a usual case when building a x86_64-tcc (there was
      no -DCONFIG_LDDIR building this binary).

    * suppress -Wdeprecated-declarations for gcc which complain on malloc hooks
      in bcheck.c if glibc is quite new.
2015-03-04 10:57:13 +03:00
seyko 7ec39e2288 reverse a commit a6149c6dbb41: Set CONFIG_MULTIARCHDIR for cross compilers.
Set CONFIG_MULTIARCHDIR for cross compilers.
    Chances a cross-compiler will find a working crt*.o
    in /usr/lib are more or less 0.

This commit breaks x86 / x86_64 compilres for linux. A solution for the crt*.o
must be discussed.
must be:
    # ./x86_64-tcc -vv
    tcc version 0.9.26 (x86-64, Linux)
    install: /usr/local/lib/tcc
    crt:
      /usr/lib64
    libraries:
      /usr/lib64
      /lib64
      /usr/local/lib64
    include:
      /usr/local/include
      /usr/include
      /usr/local/lib/tcc/include
    elfinterp:
      /lib64/ld-linux-x86-64.so.2

and with MULTIARCH we have:
    # ./x86_64-tcc -vv
    tcc version 0.9.26 (x86-64 Linux)
    install: /usr/local/lib/tcc/
    crt:
      /usr/lib/x86_64-linux-gnu ???????????????????
    libraries:
      /usr/lib/x86_64-linux-gnu
      /usr/lib                  ???????????????????
      /lib/x86_64-linux-gnu
      /lib                      ???????????????????
      /usr/local/lib/x86_64-linux-gnu
      /usr/local/lib            ???????????????????
    include:
      /usr/local/include/x86_64-linux-gnu
      /usr/local/include
      /usr/include/x86_64-linux-gnu
      /usr/include
      /usr/local/lib/tcc/include
    elfinterp:
      /lib64/ld-linux-x86-64.so.2

And CONFIG_MULTIARCHDIR don't handle C67.
On Linux x86 we have:
    # ./c67-tcc -vv
    tcc version 0.9.26 (C67, Linux)
    install: /usr/local/lib/tcc
    crt:
      /usr/lib
    libraries:
      /usr/lib
      /lib
      /usr/local/lib
    include:
      /usr/local/include
      /usr/include
      /usr/local/lib/tcc/include
    elfinterp:
      /lib/ld-linux.so.2
2015-03-04 10:50:33 +03:00
seyko 149c2a9cc9 a cpu option of the configure script as a method to specify a target cpu
* don't setup a cpu before scanning for --cpu=
    * --cpu= option sets a 'cpu' variable, not a 'build_cpu', 'build_cpu' was not used anywhere.
    * if cpu="" and ARCH != "" then cpu=$ARCH else cpu=`uname -m`
    * replace "Build CPU" with "Target CPU" in the output of the configure script.
      output this value only when not builing a cross compilers.
    * remove a HOST_I386, ... defines from a config.h file.
      thise defines are not used anywhere and cpu is now used to define a target cpu
2015-03-04 10:03:40 +03:00
seyko d972472c53 Disable floating-point test for ARM soft-float
From: Matteo Cypriani <mcy@lm7.fr>
    Date: Fri, 5 Sep 2014 23:22:56 -0400
    Subject: Disable floating-point test for ARM soft-float

    tcc is not yet capable of doing softfloat floating-point operations on
    ARM, therefore we disable this test for these platforms. Note that tcc
    displays a warning to warn ARM users about this limitation
    (debian)
2015-03-04 09:52:47 +03:00
seyko f1e4b2b7f3 disable-BTESTS 2015-03-04 09:49:19 +03:00
seyko b8925960ec correct a DllMain() declaration in dllcrt1.c and dllmain.c
There is a DllMain() declaration in the mingw-runtime-4.0.3.1
and it differs from a tcc one.
2015-03-03 22:51:13 +03:00
seyko 7b96ddd045 win32/include/winsock2.h (look previous commit) 2015-03-03 22:45:50 +03:00
seyko 351e2ec334 add declaration of the "double trunc (double _x)" and winsock2.h
This allow to build a windows version of the nimrod compiler.
2015-03-03 22:41:55 +03:00
seyko 4b61f7f04b A lrint functions in win32/include/math.h are rewrittem because tcc can't handle "t" constraint 2015-03-03 22:38:31 +03:00
seyko dfbb00c106 wincrt1.c: add definition of the __TRY__ if not defined
Some i686-pc-mingw32-gcc don't know about __TRY__
2015-03-03 22:35:33 +03:00
seyko 859ce5e47f Report a mingw as a execution environment instead of the
Win32, Win64, WinCE when executing "tcc -v". Example
	$ ./i386-win-tcc -v
	tcc version 0.9.26 (i386, mingw)
instead of the
	tcc version 0.9.26 (i386, Win32)

There is a cpu info already about bits of the excution environment
And display C67 for the TCC_TARGET_C67
2015-03-03 22:30:24 +03:00
seyko 2e6626a4b3 Don't add a slash to the install path of the tcc in display_info() 2015-03-03 21:41:22 +03:00
seyko d70440b406 A 32/64 bit tcc on linux: an arch specific path for libtcc1.a
Don't use /usr/local/lib/tcc/libtcc1.a for i386 and x86_64
A $(tccdir)/i386 directory was used to install a libtcc1.a
but only when cross compiling. And no x86_64 directory.
And this directory location was unknown inside tccelf.c
2015-03-03 18:34:22 +03:00
seyko 43e4a406b4 Disable floating-point test for ARM soft-float
From: Matteo Cypriani <mcy@lm7.fr>
    Date: Fri, 5 Sep 2014 23:22:56 -0400
    Subject: Disable floating-point test for ARM soft-float

    tcc is not yet capable of doing softfloat floating-point operations on
    ARM, therefore we disable this test for these platforms. Note that tcc
    displays a warning to warn ARM users about this limitation
    (debian)
2015-03-03 17:28:13 +03:00
seyko 774f0611cc arm-unused-warnings: remove problems with defined but unused wariables
arm-gen.c: In function `gfunc_call':
	arm-gen.c:1202: warning: unused variable `variadic'
	arm-gen.c: In function `gfunc_prolog':
	arm-gen.c:1258: warning: unused variable `avregs'
	arm-gen.c:1340: warning: label `from_stack' defined but not used
	arm-gen.c:222: warning: 'default_elfinterp' defined but not used
2015-03-03 17:16:52 +03:00
seyko 6cbf4fb740 tcc_add_runtime() for a CONFIG_USE_LIBGCC case: reducing a complexity 2015-03-03 17:11:18 +03:00
seyko cd4f3d962d x86_64-win-tcc elfinterp: a bug correction
./x86_64-win-tcc -vv
Before
	elfinterp:
	  /lib64/ld-linux-x86-64.so.2
After
	elfinterp:
	  -
This output is identical to the output of the i386-win-tcc
2015-03-03 17:05:44 +03:00
seyko 2d83ec7aa3 lddir-on-x86-64: let CONFIG_LDDIR=lib64 by default if TCC_TARGET_X86_64
This is done for the case when CONFIG_LDDIR is not configured. Example:
./configure --enable-cross
2015-03-03 16:37:44 +03:00
seyko b5f88b593a Turn on a implicit-function-declaration warning by default.
A non declared function leads to a seriuos problems. And while
gcc don't turn this warning on lets tcc do it. This warning
can be turned off by -Wno-implicit-function-declaration option.
And autor must explicitly do this if program must be compiled
with this warning off.
2015-03-03 16:32:25 +03:00
seyko 7f36abd3f2 x86_64-tcc and libtcc1.c: size_t definition is needed for a x86_64-tcc to parse memset() 2015-03-03 16:29:00 +03:00
seyko e374a733d6 -std=c99 option for the tcc: allow to use a tcc as a reference compiler for "make test"
tcc will igmore this option.
2015-03-03 16:25:02 +03:00
seyko 4c8ffb353d remove a gcc warning for bcheck on x86_64 arch: conversion to pointer from integer of different size 2015-03-03 16:18:24 +03:00
seyko 20074d8862 Use a display_info() to output a header of the tcc help listing
tcc version 0.9.26 (i386 Linux)
    Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard
    Usage: tcc [options...] [-o outfile] [-c] infile(s)...
	   tcc [options...] -run infile [arguments...]
    ...

instead of the

    tcc version 0.9.26 - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard
    Usage: tcc [options...] [-o outfile] [-c] infile(s)...
	   tcc [options...] -run infile [arguments...]
    ...

Displaing a "Hard Float" info for the ARM arch is restored. It was broken by the AArm64 patch.
2015-03-03 16:08:33 +03:00
seyko 2437ccdc76 A partial reverse for commit eda2c756ed
Author: Thomas Preud'homme <robotux@celest.fr>
	Date:   Tue Dec 31 23:51:20 2013 +0800

	Move logic for if (int value) to tccgen.c
	Move the logic to do a test of an integer value (ex if (0)) out of
	arch-specific code to tccgen.c to avoid code duplication. This also
        fixes test of long long value which was only testing the bottom half of
	such values on 32 bits architectures.

I don't understand why if () in gtst(i) was removed.
This patch allows to compile a linux kernel v.2.4.26
W/o this patch a tcc simply crashes.
2015-03-03 15:51:09 +03:00
seyko c45a8695eb A reverse of the commit 14745bdeb because of the problems while compiling linux 2.4.26
A test program:
    ///////////
    typedef unsigned int __u32;
    static inline const __u32 __fswab32(__u32 x)
    {
	return ({ __u32 __tmp = (x) ; ___swab32(__tmp); });
    }
    void func()
    {
	int aaa = 1;
	int snd_wnd = 2;
	int TCP_FLAG_ACK = 3;
	int pred_flags = (__builtin_constant_p((__u32)
	    (((aaa << 26) |
	    (__builtin_constant_p((__u32)((TCP_FLAG_ACK))) ?
		({ __u32 __x = (((TCP_FLAG_ACK))); ((__u32)( (((__u32)(__x) & (__u32)0x000000ffUL) << 24) | (((__u32)(__x) & (__u32)0x0000ff00UL) << 8) | (((__u32)(__x) & (__u32)0x00ff0000UL) >> 8) | (((__u32)(__x) & (__u32)0xff000000UL) >> 24) )); }) : __fswab32(((TCP_FLAG_ACK)))) | snd_wnd))) ? ({ __u32 __x = ((((aaa << 26) | (__builtin_constant_p((__u32)((TCP_FLAG_ACK))) ? ({ __u32 __x = (((TCP_FLAG_ACK))); ((__u32)( (((__u32)(__x) & (__u32)0x000000ffUL) << 24) | (((__u32)(__x) & (__u32)0x0000ff00UL) << 8) | (((__u32)(__x) & (__u32)0x00ff0000UL) >> 8) | (((__u32)(__x) & (__u32)0xff000000UL) >> 24) )); }) : __fswab32(((TCP_FLAG_ACK)))) | snd_wnd))); ((__u32)( (((__u32)(__x) & (__u32)0x000000ffUL) << 24) | (((__u32)(__x) & (__u32)0x0000ff00UL) << 8) | (((__u32)(__x) & (__u32)0x00ff0000UL) >> 8) | (((__u32)(__x) & (__u32)0xff000000UL) >> 24) )); }) : __fswab32((((aaa << 26) | (__builtin_constant_p((__u32)((TCP_FLAG_ACK))) ? ({ __u32 __x = (((TCP_FLAG_ACK))); ((__u32)( (((__u32)(__x) & (__u32)0x000000ffUL) << 24) | (((__u32)(__x) & (__u32)0x0000ff00UL) << 8) | (((__u32)(__x) & (__u32)0x00ff0000UL) >> 8) | (((__u32)(__x) & (__u32)0xff000000UL) >> 24) )); })
		: __fswab32(((TCP_FLAG_ACK)))) | snd_wnd))));
    }
    ////////////
error: ';' expected (got "(")
2015-03-03 15:44:29 +03:00
seyko 6fd4e5bace a void to void cast.
Allow tcc to compile the following program
    ///////
	void func1() {}
	void func2() {
	  return func1();
	}
    //////
gcc accepts this program
2015-03-03 15:39:57 +03:00
seyko 09feeca5df a statement expressions with a pointer return type
A test program:
    //////////////
    int main()
    {
	void *p = ({ 0 ; ((void *)1); });
    }
    /////////////
Porblem is introduced in a commit a80acab: Display error on statement expressions with complex return type
This error is exposed when compiling a linux 2.4.26. tcc 0.9.23 can sucessfully compile
this version of the linux.
2015-03-03 15:29:14 +03:00
seyko 1a1e9548fb iitialisation of the empty struct
Current tcc don't understand an initialization of the empty struct
This problem was found trying to compile a linux kernel 2.4.26
which can be compiled by tcc 0.9.23

  A test program:
  ////////////////////
  // ./tcc -c test_3.c
  // test_3.c:31: error: too many field init
  #undef __GNUC__
  #undef __GNUC_MINOR__
  #define __GNUC__  2
  #define __GNUC_MINOR__ 95
  typedef struct { } rwlock_t;
  struct fs_struct {
   int count;
   rwlock_t lock;
   int umask;
  };
  #define INIT_FS { \
	1, \
	RW_LOCK_UNLOCKED, \
	0022, \
  }
  #if (__GNUC__ > 2 || __GNUC_MINOR__ > 91)
    typedef struct { } rwlock_t;
    #define RW_LOCK_UNLOCKED (rwlock_t) { }
  #else
    typedef struct { int gcc_is_buggy; } rwlock_t;
    #define RW_LOCK_UNLOCKED (rwlock_t) { 0 }
  #endif
  static struct fs_struct init_fs = INIT_FS;
  // static struct fs_struct init_fs = { { (1) }, (rwlock_t) { 0 }, 0022, };
  //                                                           ^ with this all Ok
  // static struct fs_struct init_fs = { { (1) }, (rwlock_t) { }, 0022, };
  //                                                          ^ current tcc don't understand, but tcc 0.9.23 can
  int main()
  {
    return 0;
  }
  ////////////////////
  A regression is detected after a patch 69fdb57edd
  ////////////////////
  // A test for patch 69fdb57edd
  // Author: grischka <grischka>
  // Date:   Wed Jun 17 02:09:07 2009 +0200
  //     unions: initzialize only one field
  //         struct {
  //           union {
  //             int a,b;
  //           };
  //           int c;
  //         } sss = { 1,2 };
  //     This had previously assigned 1,2 to a,b and 0 to c which is wrong.
  //
  // Expected: sss.a=1 sss.b=1 sss.c=2
  int main()
  {
    struct {
      union {
        int a,b;
      };
      int c;
    } sss = { 1, 2 };

    printf ("sss.a=%d sss.b=%d sss.c=%d\n", sss.a, sss.b, sss.c);
    return 0;
  }
  ////////////////////
2015-03-03 15:15:48 +03:00
seyko bbf8221ec3 tcc don't understand am extern array of structs.
A regression was found trying to compile a linux kernel 2.4.26
  which can be compiled by tcc 0.9.23

    ///////////////////
    #include <stdio.h>

    // test for a bug:
    // compiler don't understand am extern array of structs
    // $ tcc test_1.c
    // test_1.c:8: error: unknown struct/union/enum

    extern struct FILE std_files[4];

    int main()
    {
	return 0;
    }
    //////////////////

  tcc-current
  /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
  static void struct_decl(CType *type, int u, int tdef)
  ...
    if (tok != '{') {
        v = tok;
        next();
        /* struct already defined ? return it */
        if (v < TOK_IDENT)
            expect("struct/union/enum name");
        s = struct_find(v);
        if (s) {
            if (s->type.t != a)
                tcc_error("invalid type");
            goto do_decl;
        } else if (tok >= TOK_IDENT && !tdef)
            tcc_error("unknown struct/union/enum");
    } else {
        v = anon_sym++;
    }

  tcc-0.9.23 which don't have such error
  /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
  static void struct_decl(CType *type, int u)
  ....
    if (tok != '{') {
        v = tok;
        next();
        /* struct already defined ? return it */
        if (v < TOK_IDENT)
            expect("struct/union/enum name");
        s = struct_find(v);
        if (s) {
            if (s->type.t != a)
                error("invalid type");
            goto do_decl;
        }
    } else {
        v = anon_sym++;
    }
2015-03-03 15:00:13 +03:00
seyko a429d40f06 tcc_free(table_ident) in preprocess_new() if table_ident != NULL 2015-03-03 14:54:46 +03:00
seyko e2a8fd4520 tcc_undefine_symbol(): free an alloced symbol 2015-03-03 14:50:41 +03:00
seyko 8d10c5788f Add a debug info when a #line directive is handled.
The problem was: a debug info for the file which contain a #line
directive (for example a preprocessed one) was wrong.
2015-03-03 14:46:44 +03:00
seyko 09d4e4f408 Revert a grischka patch: gdb refused to know "main"
It is a strange patch because before this commit a gdb is working well
and after this commit there is exactly the same problem on Linux:
gdb refuses to know "main"

    Author: grischka <grischka>
    Date:   Tue Feb 5 21:18:29 2013 +0100
    tccelf: fix debug section relocation
    With:
       tcc -g hello.c
       gdb a.out
         b main
    gdb refused to know "main" because of broken dwarf info.
2015-03-03 14:39:27 +03:00
seyko 252a151fc6 pp-many-files: don't drop a preprocessor defines when tcc going to preprocess a next file
in the same pass like
    tcc -E one.c two.c three.c -o combined.i
This will allow to speed up a compilation process by using a commamd like
    tcc -E *.c | tcc -o program.exe -xc -

It looks that multi-times initialization don't affect anything.
Only call to the free_defines(define_start) in tcc_preprocess()
is removed in assumption that free_defines(NULL) in
tcc_cleanup() will free all defines.
2015-03-03 14:31:47 +03:00
seyko b7b9f9f511 A gcc preprocessor option -dD added
With this option on a defines are included into the output
(inside comments). This will allow to debug a problems like:

    In file included from math.c:8:
    In file included from /usr/include/math.h:43:
    /usr/include/bits/nan.h:52: warning: NAN redefined
2015-03-03 14:25:57 +03:00
seyko 50cdccf3ef Added a gcc preprocessor options -P, -P1
tcc -E -P
  do not output a #line directive, a gcc compatible option

tcc -E -P1
  don't follow a gcc preprocessor style and do output a standard
  #line directive. In such case we don't lose a location info when
  we going to compile a resulting file wtith a compiler not
  understanding a gnu style line info.
2015-03-03 14:19:14 +03:00
seyko 40418f87c7 Move a line_ref variable from tcc_preprocess() function into struct BufferedFile.
This id needed for a right ouput in other places,
precisely to calculate a number of empty lines which are waiting to output.
2015-03-03 14:15:28 +03:00
seyko 5e3e321474 A preprocessor should Interpret an input line "# NUM FILENAME" as "#line NUM FILENAME"
A cpp from gcc do this.
A test case:
     tcc -E tccasm.c -o tccasm.i
     tcc -E tccasm.i -o tccasm.ii
After a patch the line numbers in tccasm.ii are the same
as in tccasm.i
2015-03-03 14:06:05 +03:00
Edmund Grimley Evans 1706d2254b arm64-gen.c: Improve generation of stack offsets. 2015-03-02 20:51:03 +00:00
Edmund Grimley Evans 1d41da9590 arm64-gen.c: Rename some functions and add comments. 2015-03-02 20:45:58 +00:00
Edmund Grimley Evans 86e8dcd5e2 arm64: Improve constant generation, with tests. 2015-03-02 20:39:28 +00:00
Edmund Grimley Evans 883fd365c7 arm64-gen.c: Better explanation of relocation choice. 2015-03-01 11:31:10 +00:00
Edmund Grimley Evans fc119f9840 73_arm64.c: Avoid taking address of return value. 2015-02-26 12:27:00 +00:00
Edmund Grimley Evans 8329facdfa Add 73_arm64 for testing some arm64 things, mostly PCS. 2015-02-25 22:51:41 +00:00
Edmund Grimley Evans a4d43618fb arm64-gen.c: In gen_va_arg, handle the remaining HFA cases. 2015-02-25 22:51:41 +00:00
Edmund Grimley Evans 36bb8994dd Relicensing TinyCC 2015-02-25 07:52:39 +00:00
Edmund Grimley Evans 97e08be344 tests/tcctest.c: Test COMPAT_TYPE(char *, signed char *). 2015-02-24 19:35:31 +00:00
Edmund Grimley Evans 40f7e11c53 tccgen.c: Make sure that gen_op always returns an rvalue.
Either this fix, or an alternative one, is required for arm64.
2015-02-23 22:51:10 +00:00
Michael Matz 6d055312a2 aarch64: Fix -run.
This adds some more support for properly transfering some
offsets over the different stages of a relocations life.
Still not at all psABI compliant and DSOs can't yet be generated.
But it runs the testsuite in qemu-arm64.
2015-02-23 22:51:10 +00:00
Edmund Grimley Evans b14ef0e24b Add arm64 (AArch64) as a target architecture. 2015-02-23 22:51:03 +00:00
Edmund Grimley Evans 738606dbd5 Use RELA relocations properly for R_DATA_PTR on x86_64.
libtcc.c: Add greloca, a generalisation of greloc that takes an addend.
tcc.h: Add greloca and put_elf_reloca.
tccelf.c: Add put_elf_reloca, a generalisation of put_elf_reloc.
tccgen.c: On x86_64, use greloca instead of greloc in init_putv.
2015-02-21 21:29:03 +00:00
Edmund Grimley Evans 86c850fc58 tcc-doc.texi: Explain VT_LLOCAL a bit better.
And delete the sentence about it being removed.
2015-02-20 23:29:21 +00:00
Edmund Grimley Evans ff3f9aa6ba Fix handling of case_reg in switch statement.
The back end functions gen_op(comparison) and gtst() might allocate
registers so case_reg should be left on the value stack while they
are called and set again afterwards.
2015-02-20 23:16:00 +00:00
Thomas Preud'homme a6c3ce6ec0 The "open a whisky and cut your finger open" patch
Make integer constant parsing C99 compliant
2015-02-18 07:01:03 +00:00
Reimar Döffinger ff783b94c7 Add support for .p2align asm directive.
Signed-off-by: Reimar Döffinger <Reimar.Doeffinger@gmx.de>
2015-01-20 08:49:49 +01:00
Reimar Döffinger fb6331e0fa Fix macro expansion of empty args.
Signed-off-by: Reimar Döffinger <Reimar.Doeffinger@gmx.de>
2015-01-18 22:00:10 +01:00
Reimar Döffinger a6149c6dbb Set CONFIG_MULTIARCHDIR for cross compilers.
Chances a cross-compiler will find a working crt*.o
in /usr/lib are more or less 0.

Signed-off-by: Reimar Döffinger <Reimar.Doeffinger@gmx.de>
2015-01-18 21:21:59 +01:00
Reimar Döffinger ae09558d71 Build also WinCE cross compiler when cross compilers enabled.
Signed-off-by: Reimar Döffinger <Reimar.Doeffinger@gmx.de>
2015-01-18 21:16:34 +01:00
seyko e260b03686 Allow tcc to understand a setob,... opcodes as alias to seto,...
PS: http://lists.cs.uiuc.edu/pipermail/llvm-commits/Week-of-Mon-20101122/112576.html
This is fix PR8686 for llvm: accepting a 'b' suffix at the end
of all the setcc instructions.
2015-01-06 22:59:19 +03:00
seyko c334b59142 Warn about a conflicting compile options spectified on the command line.
Try "tcc -E -c tccasm.c -o tccasm.o"
2015-01-06 22:19:45 +03:00
seyko b93179f3c0 .i as file extension
Add a ".i" extension as alias for ".c"
 GCC and file extensions:
 .i C source code which should not be preprocessed.

Before a patch:
 ./tcc -E tccasm.c -o tccasm.i
 ./tcc -c tccasm.i -o tccasm.o
 tccasm.i:1: error: unrecognized file type
2015-01-06 16:01:41 +03:00
seyko 524abd46b4 round() in test (24_math_library) fail because there are no defs included.
gcc complain but work right and tcc simply fail to compile right.
2015-01-05 18:23:32 +03:00
Carlos Montiers 77ef3b2929 crt1.c revision 2014-12-30 00:25:52 -03:00
Lee Duhem 5a76c5d2f3 Fix parsing of binary floating point number
* tccpp.c (parse_number): `shift' should be 1 while parsing binary
floating point number.
* tests/tests2/70_floating_point_literals.c: New test cases for
floating point number parsing.
2014-12-15 16:32:08 +08:00
Lee Duhem 20a5845a47 tcc.h (BufferedFile): Remove unnecessary static memory allocation
The memory needed by `buffer' will be allocated in `tcc_open_bf',
these is no need to allocate them in BufferedFile statically.
2014-12-11 10:04:22 +08:00
Lee Duhem f1703e2b2f libtcc.c (put_extern_sym2): Extend the scope of buf to match its use
After leaving the code block that `buf' is defined, `buf' will not
exist, so `name' will point to a variable that does not exist.
2014-12-11 10:04:22 +08:00
Lee Duhem 4bf3f6c965 .gitignore: Ignore Emacs temporary files 2014-12-11 10:04:22 +08:00
Lee Duhem 73e8f6b60a Makefile: Add rules to create tags and TAGS. 2014-11-28 23:25:05 +08:00
Lee Duhem 4ae462b668 .gitignore: Ignore generated files. 2014-11-28 23:24:55 +08:00
Carlos Montiers 9b14e8715a little optimization to crt1 2014-11-23 01:51:38 -03:00
Carlos Montiers f40b82295e __getmainargs compatibility checking success 2014-11-22 19:00:49 -03:00
James Buren 1e07ea71d3 win32: fix implicit function warning
This includes windows.h to fix a warning about
an implicit function usage of ExitProcess().
2014-11-03 16:17:15 -06:00
Matteo Cypriani 26b26f355f Filter-out warning about softfloat in tests2 2014-10-17 16:37:54 -04:00
grischka 9d7fb33360 tccgen: use lvalue as result from bitfield assignment
test case:

    #include <stdio.h>
    int main(int argc, char **argv)
    {
        struct _s { unsigned a:9, b:5, c:7; } _s, *s = &_s;
        int n = 250;
        s->a = s->b = s->c = n + 4;
        printf("--> %d / %d / %d\n", s->a, s->b, s->c);
        return 0;
    }

before:
--> 254 / 30 / 126
now:
--> 30 / 30 / 126
2014-09-23 12:30:08 +02:00
Matteo Cypriani 87d879aa7b Accept CPPFLAGS from the environment
Don't override CPPFLAGS so that it can be passed through the
environment.

(This is a patch Thomas Preud'homme wrote for Debian in February 2013.)
2014-09-07 12:07:04 -04:00
Matteo Cypriani 63376d7712 tccelf: layout_sections: add missing param strsec
This fixes compilation on (k)FreeBSD.
2014-09-07 12:04:53 -04:00
Matteo Cypriani b84cdf6214 Clear CFLAGS & LDFLAGS in tests
Clear CFLAGS and LDFLAGS to build the tests, in case the main Makefile
passes some flags that aren't handled by tcc (we are not compiling tcc
here, we are using tcc to compile the tests).
2014-09-07 11:15:31 -04:00
Matteo Cypriani 178275dc0c Don't build libtcc1 with -fstack-protector-strong
Prevent libtcc1.a to be compiled with -fstack-protector-strong, so that
linking with tcc doesn't fail because symbol '__stack_chk_fail_local' is
not present in libtcc1.a. This is useful only if the CFLAGS passed from
the main Makefile contain this flag.
2014-09-07 10:56:03 -04:00
grischka 14745bdeb7 tccgen: nocode_wanted: do not output constants
This for example suppresses string constants such as with

    int main()
    {
        return sizeof "foo";
    }

Actually, setting

    nocode_wanted = 1;

in libtcc.c for the initial global level seemed wrong, since
obviously "nocode_wanted" means code as any side effects, also
such as string constants.

This reverts a part of 2de1b2d14c
(documented as "Some in-between fixes" in Changelog)
2014-08-01 10:59:38 +02:00
grischka 12f43953ed win64: fix resource file support 2014-08-01 10:51:28 +02:00
Carlos Montiers 73a7dd79af Removed the error message and minor changes. 2014-07-17 01:08:47 -04:00
Carlos Montiers 7c474b4da3 __getmainargs return int, not void, and on error, it return -1 and let argv untouched, also argc. Added a if checking the result of it. 2014-07-16 22:22:05 -04:00
Carlos Montiers f2ee6b1759 Fix mistake. Change jb by jbe. tiny c round (INT_MAX = 0x7FFFFFFF) to a DWORD boundary and it becomes 0x80000000. Jle treats as -214783648, but Jbe treats as 214783648. Thanks to Jason Hood for explain me this. 2014-07-10 20:41:51 -04:00
Carlos Montiers 8257829623 Fix problem using alloca function, executable crashed even with a exception handler function, when try to allocate INT_MAX. Patch provided by Jason Hood in private e-mail, when I ask to him for help. He say: Feel free to pass it on to the mailing list. 2014-07-10 00:37:20 -04:00
jiang 89000c18dc Rename:
68_macro_concat.c -> 68_macro_param_list_err_1.c
69_macro_concat.c -> 69_macro_param_list_err_2.c
and Remove spaces
2014-07-01 23:54:49 +08:00
Thomas Preud'homme b31e80a43a Specify license of lib/armeabi.c 2014-07-01 22:01:49 +08:00
jiang a3fc543459 bug:
----------------------------------------------------------------------
#define hexCh(c (c >= 10 ? 'a' + c - 10 : '0' + c)
  hexCh(c);

out:
jiang@jiang:~/test$ ./tcc -E c4.c
# 1 "c4.c"

(c >= 10 ? 'a' + c - 10 : '0' + c);
---------------------------------------------------------------

#define hexCh(c/3) (c >= 10 ? 'a' + c - 10 : '0' + c)
hexCh(c);

out:
jiang@jiang:~/test$ ./tcc -E c4.c
# 1 "c4.c"

/3) (c >= 10 ? 'a' + c - 10 : '0' + c);
jiang@jiang:~/test$

after patch:

# 1 "c4.c"
c4.c:1: error: may not appear in macro parameter list: "("
jiang@jiang:~/test$

jiang@jiang:~/test$ ./tcc -E c4.c
# 1 "c4.c"
c4.c:1: error: may not appear in macro parameter list: "/"
jiang@jiang:~/test$
2014-06-29 20:35:57 +08:00
David Mertens 799512388c Revert the many un-reviewed commits starting from early April
Starting early April, a number of commits were pushed to the mob branch
that did not reflect the interest, wishes, or code quality of the tcc
community. This commit reverts those commits, while cherry-picking
grishka's commit for win64 linkage issues.
2014-06-24 22:42:57 -04:00
grischka 6e0a658e96 win64: try to fix linkage
- revert to R_X86_64_PC32 for near calls on PE
- revert to s1->section_align set to zero by default

Untested. Compared to release_0_9_26 the pe-image looks back to
normal.  There are some differences in dissassembly (r10/r11 usage)
but maybe that's ok.
2014-06-24 22:09:12 -04:00
jiang f26fdaefd8 revert vstore() 2014-06-23 01:08:54 +08:00
Thomas Coudray 1fa0fe2786 Revert "Win: Enable use "*.def + *.c" files as library instead of *.a by "-l" option"
This reverts commit 7a3f6d4941.
2014-06-20 13:26:29 +01:00
YX Hao 7a3f6d4941 Win: Enable use "*.def + *.c" files as library instead of *.a by "-l" option
example: "-lshell32" will try "shell32.def + shell32.c"

Add lib type "%s/%s.c" for tcc_add_library() ('-l' option parse)

So tcc can use all files as scripts.
2014-06-16 16:00:46 +08:00
jiang d316836008 Let init_putz one-time generation.
At the same time, increase the GCC style warning
---------------------------------------------------------------------------
int main()
{
	int a[10] = {[5]=5};
	return 0;
}

Disassembly of section .text:

0000000000000000 <main>:
   0:	55                   	push   %rbp
   1:	48 89 e5             	mov    %rsp,%rbp
   4:	48 81 ec 30 00 00 00 	sub    $0x30,%rsp
   b:	b8 05 00 00 00       	mov    $0x5,%eax
  10:	89 45 ec             	mov    %eax,-0x14(%rbp)
  13:	48 b8 14 00 00 00 00 	movabs $0x14,%rax
  1a:	00 00 00
  1d:	49 89 c2             	mov    %rax,%r10
  20:	b8 00 00 00 00       	mov    $0x0,%eax
  25:	48 89 c6             	mov    %rax,%rsi
  28:	48 8d 45 d8          	lea    -0x28(%rbp),%rax
  2c:	48 89 c7             	mov    %rax,%rdi
  2f:	4c 89 d2             	mov    %r10,%rdx
  32:	b8 00 00 00 00       	mov    $0x0,%eax
  37:	e8 fc ff ff ff       	callq  38 <main+0x38>
  3c:	48 b8 10 00 00 00 00 	movabs $0x10,%rax
  43:	00 00 00
  46:	49 89 c2             	mov    %rax,%r10
  49:	b8 00 00 00 00       	mov    $0x0,%eax
  4e:	48 89 c6             	mov    %rax,%rsi
  51:	48 8d 45 f0          	lea    -0x10(%rbp),%rax
  55:	48 89 c7             	mov    %rax,%rdi
  58:	4c 89 d2             	mov    %r10,%rdx
  5b:	b8 00 00 00 00       	mov    $0x0,%eax
  60:	e8 fc ff ff ff       	callq  61 <main+0x61>
  65:	b8 00 00 00 00       	mov    $0x0,%eax
  6a:	e9 00 00 00 00       	jmpq   6f <main+0x6f>
  6f:	c9                   	leaveq
  70:	c3                   	retq

After the patch

0000000000000000 <main>:
   0:	55                   	push   %rbp
   1:	48 89 e5             	mov    %rsp,%rbp
   4:	48 81 ec 30 00 00 00 	sub    $0x30,%rsp
   b:	48 b8 28 00 00 00 00 	movabs $0x28,%rax
  12:	00 00 00
  15:	49 89 c2             	mov    %rax,%r10
  18:	b8 00 00 00 00       	mov    $0x0,%eax
  1d:	48 89 c6             	mov    %rax,%rsi
  20:	48 8d 45 d8          	lea    -0x28(%rbp),%rax
  24:	48 89 c7             	mov    %rax,%rdi
  27:	4c 89 d2             	mov    %r10,%rdx
  2a:	b8 00 00 00 00       	mov    $0x0,%eax
  2f:	e8 fc ff ff ff       	callq  30 <main+0x30>
  34:	b8 05 00 00 00       	mov    $0x5,%eax
  39:	89 45 ec             	mov    %eax,-0x14(%rbp)
  3c:	b8 00 00 00 00       	mov    $0x0,%eax
  41:	e9 00 00 00 00       	jmpq   46 <main+0x46>
  46:	c9                   	leaveq
  47:	c3                   	retq
 -----------------------------------------------------------------------------------
"c5.c"
int main()
{
  // union st
   struct st
   {
    char c;
    short s;
   // char cc[];
    };
   // union st
  struct st
    ss = { 1, 2, 3};
   // int a = ss;
    char cb[1] = {1,2,3};
    return 0;
}

c5.c:12: warning: excess elements in struct initializer
c5.c:14: warning: excess elements in array initializer
c5.c:14: warning: excess elements in array initializer
2014-05-28 22:09:49 +08:00
jiang 89134dd7b0 Considering the effect of CH_EOF on line_num 2014-05-28 21:51:50 +08:00
jiang 698b16960a Modify the 66_macro_concat_end.expect
I was busy recently, forget test. Thank Austin
2014-05-28 10:38:26 +08:00
jiang bcf60562e0 The number of rows to display warning is wrong
For example:
#define TOK_ASM_weak TOK_WEAK1
#define TOK_ASM_weak TOK_WEAK
Output:
C8.c:3: warning: TOK_ASM_weak redefined
2014-05-23 15:46:08 +08:00
jiang 9c78da8a32 forget Delete __va_ld_reg 2014-05-21 12:50:12 +08:00
jiang 3d608d4b54 Delete a = (a > = 0)? A: -a; \ 2014-05-20 15:23:55 +08:00
jiang 0199123dd7 clean '\t' 2014-05-20 15:18:59 +08:00
jiang f8b4f59f8b In the local use of local stack, use a global stack in the global time 2014-05-20 14:59:37 +08:00
jiang e5e7f488e2 int main()
{
	struct st {
		int aa:16;
		int bb:16;
	} s;
	s.aa = 1;
	s.bb = 2;
	return 0;
}
objdump -d:
elf64-x86-64
Disassembly of section .text:

0000000000000000 <main>:
   0:	55                   	push   %rbp
   1:	48 89 e5             	mov    %rsp,%rbp
   4:	48 81 ec 10 00 00 00 	sub    $0x10,%rsp
   b:	b8 01 00 00 00       	mov    $0x1,%eax
  10:	48 89 c1             	mov    %rax,%rcx
  13:	81 e1 ff ff 00 00    	and    $0xffff,%ecx
  19:	8b 55 fc             	mov    -0x4(%rbp),%edx
  1c:	81 e2 00 00 ff ff    	and    $0xffff0000,%edx
  22:	09 d1                	or     %edx,%ecx
  24:	89 4d fc             	mov    %ecx,-0x4(%rbp)
  27:	b8 02 00 00 00       	mov    $0x2,%eax
  2c:	48 89 c1             	mov    %rax,%rcx
  2f:	81 e1 ff ff 00 00    	and    $0xffff,%ecx
  35:	c1 e1 10             	shl    $0x10,%ecx
  38:	8b 55 fc             	mov    -0x4(%rbp),%edx
  3b:	81 e2 ff ff 00 00    	and    $0xffff,%edx
  41:	09 d1                	or     %edx,%ecx
  43:	89 4d fc             	mov    %ecx,-0x4(%rbp)
  46:	b8 00 00 00 00       	mov    $0x0,%eax
  4b:	e9 00 00 00 00       	jmpq   50 <main+0x50>
  50:	c9                   	leaveq
  51:	c3                   	retq

After the patch

Disassembly of section .text:

0000000000000000 <main>:
   0:	55                   	push   %rbp
   1:	48 89 e5             	mov    %rsp,%rbp
   4:	48 81 ec 10 00 00 00 	sub    $0x10,%rsp
   b:	8b 45 fc             	mov    -0x4(%rbp),%eax
   e:	81 e0 00 00 ff ff    	and    $0xffff0000,%eax
  14:	83 c8 01             	or     $0x1,%eax
  17:	89 45 fc             	mov    %eax,-0x4(%rbp)
  1a:	8b 45 fc             	mov    -0x4(%rbp),%eax
  1d:	81 e0 ff ff 00 00    	and    $0xffff,%eax
  23:	81 c8 00 00 02 00    	or     $0x20000,%eax
  29:	89 45 fc             	mov    %eax,-0x4(%rbp)
  2c:	b8 00 00 00 00       	mov    $0x0,%eax
  31:	e9 00 00 00 00       	jmpq   36 <main+0x36>
  36:	c9                   	leaveq
  37:	c3                   	retq
2014-05-17 12:32:00 +08:00
jiang a94ed43094 Improved '\ n' output effect (# pragma pack (push, 8), # pragma pack (pop)) 2014-05-17 12:06:18 +08:00
jiang 196c999515 1 macro_push and macro_pop work I made a mistake, no matter the definition does not define can be macro_push.
And the modified tcctest.c test
2, pack: in the compiler under the mode of s1->ppfp, I have no clear ideas1->ppfp
Some advice thank you Roy to me.This patch, I hope I can pass the Roy test
2014-05-17 00:55:02 +08:00
jiang 276553c6b2 add push_macro test again 2014-05-16 15:44:51 +08:00
jiang 52891b6ff6 fix push_macro, asked Tom to help me testfix push_macro 2014-05-16 12:15:00 +08:00
jiang 5a514107c4 When tcc.exe update, abitest-tcc.exe not updated. For security, you must first clean up 2014-05-15 12:09:43 +08:00
jiang 5d0785d0e1 Add warning 4
num en{a1,a2,a3};
enum en ee;
ee = 0xffffffffff;
    char a;
    a = 0xffff;
2014-05-14 21:01:00 +08:00
jiang fcb3772a34 Add warning 3
struct st {int a;} ss;
int b;
b = ss;
2014-05-14 20:44:53 +08:00
jiang 07614b5e22 clean '\t' 2014-05-14 12:45:58 +08:00
jiang c6345b5a8a restore 2dd8587c2f32d17a2cd0443a60a614a3fa9bbe29 2014-05-13 22:05:38 +08:00
jiang 72f466c24c Modify tcc_error ("invalid type",); 2014-05-13 22:00:42 +08:00
jiang 8d5e0cf083 fix 14d0aa450f 2014-05-13 21:57:35 +08:00
jiang 03687729ec Add warning 2
For example:
struct A {
int b: 16;
int c: 16
};
sizeof (struct A);
2014-05-09 22:41:45 +08:00
jiang 14d0aa450f Add warning
For example:
struct A {
int b [];
};
2014-05-09 22:35:19 +08:00
grischka 0f51ccd4e4 win64: try to fix linkage
- revert to R_X86_64_PC32 for near calls on PE
- revert to s1->section_align set to zero by default

Untested. Compared to release_0_9_26 the pe-image looks back to
normal.  There are some differences in dissassembly (r10/r11 usage)
but maybe that's ok.
2014-05-08 17:32:29 +02:00
jiang ad787abea6 fix bug if (seen_reg_num + reg_count <= 8) 2014-05-08 15:39:50 +08:00
grischka 899d26605c Revert "update static void parse_number()"
because:
- Constructing fp numbers isn't quite trivial
- 3 additional calls to strchr per number is noticeable slow

Also: exclude abitest.c:ret_longdouble_test2 on _WIN32
for mixed gcc/tcc scenario

test case:
- make -k test (on win32):
  -2.120000 0.500000 23000000000.000000
  +2.120000 0.500000 22999999999.999996
  ...
  ret_longdouble_test2... failure

This reverts 857f7dbfa6
and deaee6c249
2014-05-06 18:24:41 +02:00
jiang 5e56fb635a Return to: e20c1eb99e
1: The new patch for the other machines still have the problem.
2: libcrt Rename (what if gcc had libcrt as well)
3: parse_number exact problem
4: VT_VLS is to allow tcc
     Compile the following
     int b = 9;
     struct st {
     int a;
     int b [b]
     };
     struct st st1;
     st1.b [8] = 9;
     printf ("% d \ n", st1.b [8]);

     tcc a problem. Due to problems in front, and now can not be improved
5: they commit much, bug difficult to lock, you can not let other people help develop.
6: ('\ t') too

Thanks to Michael and Ray
Their criticism I have benefited!
2014-05-04 13:18:31 +08:00
jiang 089dea355a tcc on i386 are still having problems at work.Thank Roy report again. Struck on several variables can be connected to commit in the register. I am worried whether tcc can run the os. Since my machine is ubuntu 64 bits I can test my machine. 2014-05-03 23:51:09 +08:00
jiang a0d45c1bcd forget commit tccge.c for i386 2014-05-03 00:39:40 +08:00
jiang 6755b4a3de Modify i386-gen.c,
Thank Roy Tam reported problems
2014-05-03 00:33:19 +08:00
jiang e647c3137d Fix x86-64 vla
For example, it should look like this
High stack
-------------
----- Func_ret_sub
------------
---- Vla stack
-------------
---- Known loc
--------------
Low

Increased loc_stack () function is used for temporary stack management, call save_reg (), released by load ()
Like this
Before use
High
----- Known loc
----
---
----
---- Pop_stack
Low
loc_stack (size, 1)
After use
High
----- Known loc
---- Pop_stack
---
----
----
Low
2014-05-02 23:45:48 +08:00
jiang 6c8207633f Fixes include the double quotes bug
Added push_macro, pop_macro support
Fix pack bug, when output with-E will pack the bug
2014-05-02 11:23:54 +08:00
jiang 5b52a44b52 gen_putz () and struct_copy (), is to reduce the third-party call that
generates faster code tcc
Now only for x86-64
parse_number also to reduce the reliance on third-party libraries, allowing
faster analysis tcc
2014-05-02 09:42:33 +08:00
jiang ee99fd45ab Add a comment.
ref: 2a8905c93b
Sorry, I used the wrong command, I did not mean it.
Thank grischka
2014-05-02 00:39:50 +08:00
grischka 504d40a328 Attention: never use hard tabs other than 8 (eight) wide
The attached fix (libcrt.c) is just one example.  There seem
many more such introduced from latest commits that look badly
formatted in anyone else's editors and should be fixed.

General recommended policy:
- if possible, do not add new hard tabs ('\t') at all.
  Use spaces (soft tabs) instead
- in any case, configure your editor to read/write hard tabs
  with width of 8 (eight)

Also:
- Avoid merge commits (unless for very good reason).  Instead
  use "git cherry-pick" or "git rebase" to put your commits on
  top of the public branch.  ref: 2a8905c93b

Also:
- jiang: please explain what you are doing, in the commit message
  and on the list. Subscribe to the mailing list to receive feedback
  from people for your work.

  For example, what was wrong with 'parse_number'? Show a test
  case and how your version fixes it (it is slower btw).
2014-05-01 15:33:29 +02:00
jiang 59a22d59a2 update for x86_64-gen.c 2014-05-01 20:58:43 +08:00
jiang 2742fbcf95 clean 2014-05-01 15:19:03 +08:00
jiang 87a850f553 fix its own making bug. Improved init_putz (). Modify the tests / Makefile to make the test more secure 2014-05-01 15:15:01 +08:00
jiang 9e3713facd Expansion code again for x86_64-gen 2014-05-01 01:48:50 +08:00
jiang 2b2e7f85d7 rename i386-tok.h i386-asm.c, add PRINTF_ASM_CODE 2014-04-30 19:30:30 +08:00
jiang ba61fd9cd1 rename libtcc1.c 2014-04-30 17:35:44 +08:00
jiang 5af0ea7fb8 Fix va_arg bug, Fix type conversion bug, an increase of loc_stack () function is used to manage loc 2014-04-30 15:26:45 +08:00
jiang 9ff288648b Restore eda2c756ed 2014-04-30 14:24:44 +08:00
jiang 515169f21b Reduce the generation of machine code for x86_64, Less of size 2014-04-29 23:57:22 +08:00
jiang 2a8905c93b So that the generated code, and more short 2014-04-29 16:05:16 +08:00
Thomas Preud'homme 02e2fe3c26 Add support for load/store of _Bool value
Add support for loading _Bool value in i386, x86_64 and arm as well as
support for storing _Bool value on arm.
2014-04-29 16:01:57 +08:00
jiang e20c1eb99e fix test3 for x86_64-gen.c 2014-04-28 19:43:02 +08:00
jiang 89f7aea980 fix abitest.c for x86_64 bug 2014-04-28 14:05:55 +08:00
jiang deaee6c249 fix tccpp.c 2014-04-28 12:53:18 +08:00
jiang 857f7dbfa6 update static void parse_number(const char *p) for tccpp.c 2014-04-28 12:42:36 +08:00
jiang 4b50557553 add test for abitest.c 2014-04-28 12:28:56 +08:00
grischka 2ac238fc50 tccpe: adjust for new 'hidden' symbols feature
in order to avoid conflicts with windows specific (ab)usage
of the Elf32_Sym -> st_other field.
2014-04-17 17:01:28 +02:00
Thomas Preud'homme 6b7a6fcbc8 Improve efficiency of macro concatenation
As per grischka comment, always output a space after macro concatenation
instead of trying to detect if it's necessary as the current approach
has a huge cost.
2014-04-14 20:49:14 +08:00
Michael Matz 356c6f6293 Remove unused variable 2014-04-14 05:41:57 +02:00
Michael Matz e69c506617 x86_64: Handle PLT relocs to hidden symbols
For calls to hidden symbols we don't need a PLT slot, rewrite
the reloc into PC32.
2014-04-14 04:58:05 +02:00
Michael Matz a9fda392a0 Parse assembler .hidden directive
This makes TCCs assembler understand the '.hidden symbol' directive
(and emits a STV_HIDDEN ELF symbol then).
2014-04-14 03:33:50 +02:00
Michael Matz fbda78aefe Parse and emit hidden visibility
This adds parsing of (GCC compatible) visibility attribute
in order to mark selected global symbols as hidden.  The generated
.o files contain hidden symbols already, the TCC linker doesn't
yet do the right thing.
2014-04-14 02:53:11 +02:00
grischka 112148172b tccpe: speed up .def file loading
The fgets replacement meant to work with "int fd"
was just too slow.
2014-04-13 20:30:46 +02:00
minux aa255f37f2 tests2: fix and enable 46_grep test. 2014-04-12 14:04:10 -04:00
minux 0a51386960 tests2: fix 30_hanoi test and enable it. 2014-04-12 13:37:37 -04:00
Thomas Preud'homme 0e3d2e0bea Make build CPU detection a tad more flexible 2014-04-12 16:20:12 +08:00
Thomas Preud'homme 6e56bb387d Fix preprocessor concat with empty arg 2014-04-12 16:11:42 +08:00
minux 9714d2e75f build: add initial NetBSD support.
Not able to generate ELF files on NetBSD yet (lacks the note and crt1.o
is actually named crt0.o on NetBSD), but -run works with these extra
defines:
-D__lint__ -D"__symbolrename(x)=asm(#x)" -D__NetBSD__

The -D__lint__ is an ugly hack, TCC should be able to emulate GCC just
fine, but it seems TCC doesn't support __builtin_va_list yet?
	typedef __builtin_va_list __va_list;
/usr/include/sys/ansi.h:72: error: ';' expected (got "__va_list")
2014-04-12 01:42:46 -04:00
minux 469ae3a7e5 build: ignore and properly clean tests/vla_test 2014-04-12 01:10:58 -04:00
minux b8eb7dd8e8 tcc.h: add ELF interpreter for DragonFly BSD. 2014-04-12 01:10:12 -04:00
minux 8d3e0b3080 tccrun: fix build on DragonFly BSD. 2014-04-12 00:52:20 -04:00
minux 5f7cdd29b6 win32/include/process.h: update prototypes to match mingw.
This eliminates an argument type mismatch warning during tcc
self-compilation on windows.
2014-04-12 00:09:57 -04:00
minux df0267b287 tcc, libtcc: fix build on windows with latest mingw. 2014-04-11 23:49:53 -04:00
minux bba1c381f4 tiny_impdef: remove artificial length restriction. 2014-04-11 23:23:05 -04:00
Urs Janssen 822f4630e3 add missing prototypes 2014-04-10 11:53:54 +02:00
Thomas Preud'homme a715d7143d Prevent ## to appear at start or end of macro 2014-04-08 22:19:48 +08:00
Thomas Preud'homme 91d4db600b Add new tests for macro nesting 2014-04-07 23:30:57 +08:00
Thomas Preud'homme c2422ba87f Fix test for macro nesting 2014-04-07 21:16:04 +08:00
Vincent Lefevre 3e9a7e9d69 Corrected spelling mistakes in comments and strings 2014-04-07 13:31:00 +02:00
Vincent Lefevre d09a46d655 corrected a typo 2014-04-07 13:20:49 +02:00
grischka f90bad0925 tests2: cleanup
- remove -norunsrc switch
  Meaning and usage (-run -norun...???) look sort of screwed.  Also
  general usefulness is unclear, so it was actually to support exactly
  one (not even very interesting) test

This partially reverts e31579b076
2014-04-07 11:20:45 +02:00
grischka 76accfb8d5 win32: libtcc1.a needs to be built with tcc
gcc/mingw produces msvc compatible pecoff objects, tcc only
knows ELF.
2014-04-07 11:16:06 +02:00
Michael Matz f01373765b stdbool.h: Make conformant to ISOC99
For conformance to ISO C the stdbool.h header has to provide
the macro __bool_true_false_are_defined (defined to 1).  Yep,
that name is really in the standard.
2014-04-07 00:30:31 +02:00
Michael Matz 0961a38493 Declare wint_t in <stddef.h> when needed
Some old glibcs <wctype.h> require <stddef.h> to provide
wint_t, accomodate them.
2014-04-07 00:27:46 +02:00
grischka 0e43f3aef4 win32: warn people about using undeclared WINAPI functions
*** UNCONDITIONALLY ***

Esp. sihce tinycc winapi headers are not as complete as people might
expect this can otherwise lead to obscure problems that are difficult
to debug.

(Originally 'warn_implicit_function_declaration' was set to 1
always for windows but someone must have deleted that line)
2014-04-06 10:59:40 +02:00
Michael Matz 6a947d9d26 ELF: Remove traces of old RUNTIME_PLTGOT code
The last users of it went away, no use in keeping
this code.
2014-04-06 01:59:35 +02:00
Michael Matz 01c0419234 arm: Use proper PLT/GOT for -run.
Same as with x86_64, disable the runtime_plt_and_got hack
for -run on arm as well.  For that we need to handle several
relocations as (potentially) generating PLT slots as well.
Tested with mpfr-3.1.2 and gawk (both using --disable-shared),
there are two resp. five pre-existing problems, so no regressions.

This also works toward enabling real shared libs for arm,
but it's not there yet.
2014-04-06 01:50:35 +02:00
Michael Matz 9750d0b725 x86_64: Create proper PLT and GOT also for -run
This makes us use the normal PLT/GOT codepaths also for -run,
which formerly used an on-the-side blob for the jump tables.
For x86_64 only for now, arm coming up.
2014-04-06 00:30:22 +02:00
Michael Matz c4427747e6 arm: Provide alloca()
This provides a simple implementation of alloca for ARM (and enables
the associated testcase).  As tcc for ARM doesn't contain an assembler,
we'll have to resort using gcc for compiling it.
2014-04-05 22:54:11 +02:00
Michael Matz b0f8ca5e03 Git should ignore tests2 executables. 2014-04-05 22:52:17 +02:00
Michael Matz 3d18c9aa64 tests2: Build executables as well
The individual tests in tests2 are checked only with -run.  Build
(and check) executables as well, to test also building executables.
2014-04-05 17:35:00 +02:00
Michael Matz 0688afdd34 arm: Handle R_ARM_NONE relocs
These relocations are used to express a dependency on a certain
symbol (e.g. for EABIs exception handling to the
__aeabi_unwind_cpp_pr{0,1,2} routines).  Just ignore them in
reloc processing.
2014-04-04 23:33:04 +02:00
grischka 5879c854fb tccgen: x86_64: fix garbage in the SValue upper bits
This was going wrong (case TOK_LAND in unary: computed labels)
-        vset(&s->type, VT_CONST | VT_SYM, 0);
-        vtop->sym = s;

This does the right thing and is shorter:

+        vpushsym(&s->type, s);


Test case was:

    int main(int argc, char **argv)
    {
        int x;
        static void *label_return = &&lbl_return;
        printf("label_return = %p\n", label_return);
        goto *label_return; //<<<<< here segfault on linux X86_64 without the memset on vset
        printf("unreachable\n");
    lbl_return:
        return 0;
    }


Also::
- Rename "void* CValue.ptr" to more usable "addr_t ptr_offset"
  and start to use it in obvious cases.

- use __attribute__ ((noreturn)) only with gnu compiler

- Revert CValue memsets ("After several days searching ...")
  commit 4bc83ac393

Doesn't mean that the vsetX/vpush thingy isn't brittle and
there still might be bugs as to differences in how the CValue
union  was set and is then interpreted later on.

However the big memset hammer was just too slow (-3% overall).
2014-04-04 20:20:44 +02:00
Michael Matz 2024c44541 run: Always create .got relocs
When output is memory we applied the correct GOT offset for certain
relocations (e.g. _GOT32), but we forgot to actually fill the got
entries with the final symbol values, so unconditionally create relocs
against .got as well.
2014-04-04 17:54:52 +02:00
Michael Matz f2c8491fc0 ELF: Make first PT_LOAD cover headers
This makes it so that the first PT_LOAD segment covers
ELF and program header and .interp (contained in the same page anyway,
right before the start of the first loaded section).  binutils
strip creates invalid output otherwise (which strictly is a binutils
bug, but let's be nice anyway).
2014-04-03 18:00:44 +02:00
Michael Matz a913ee6082 x86-64: Use correct ELF values
The x86-64 uses different segment alignment (2MB) and a different
start address.
2014-04-03 17:59:41 +02:00
Michael Matz ea2805f097 shared libs: Build libtcc1.a with -fPIC
TCCs runtime library must be compiled as position independend code,
so it can be linked into shared libraries.
2014-04-02 21:27:22 +02:00
Thomas Preud'homme 3e56584223 Allow local redefinition of enumerator 2014-03-31 22:59:10 +08:00
Vincent Lefevre a620b12dc1 Fixed typo from commit 0ac8aaab1b 2014-03-31 15:24:32 +02:00
Thomas Preud'homme 01cf514e59 Update Changelog from git changelog entries 2014-03-31 19:42:42 +08:00
Michael Matz 0bd1282059 x86-64: shared libs improvement
This correctly resolves local references to global functions from
shared libs to their PLT slot (instead of directly to the target
symbol), so that interposition works.

This is still not 100% conforming (executables don't export symbols
that are also defined in linked shared libs, as they must), but
normal shared lib situations work.
2014-03-31 05:36:12 +02:00
Michael Matz 080ad7e62a x86-64: Add basic shared lib support
Initial support for shared libraries on x86-64.
2014-03-31 03:45:35 +02:00
mingodad 5a5fee867a Add __attribute__ ((noreturn)) to tcc_error and expect functions.
This make use of static analysis tools like scan-build report less false positives.
2014-03-30 10:18:18 +01:00
Thomas Preud'homme 80811671d4 Add tests for previous fixes
Add tests for the fixes made in commits
76cb1144ef,
a465b7f58f,
0f522fb32a,
82969f045c and
673befd2d7.
2014-03-30 12:56:55 +08:00
Thomas Preud'homme fdc31e152b Update Changelog from git changelog entries 2014-03-30 12:35:22 +08:00
Daniel Glöckner 3900b235e0 x86_64: pass va_list as pointer
The ABI requires that va_list is passed as a pointer although its
contents is a kept in a structure. Therefore make it a single element
array.
2014-03-30 00:13:58 +01:00
grischka 0ac8aaab1b tccpp: reorder some tokens
... and make future reordering possibly easier

related to 9a6ee577f6
2014-03-29 19:37:26 +01:00
Daniel Glöckner 1075087241 ARM: Fix passing arrays to varadic functions
TinyCC miscompiled

void g(int,...);

void f(void)
{
        char b[4000];
        g(1, 2, 3, 4, b);
}

in two ways:
 1. It didn't align the stack to 8 bytes before the call
 2. It added sizeof(b) to the stack pointer after the call
2014-03-29 17:50:40 +01:00
Thomas Preud'homme f272407353 Fix typo in code added by b018bac9c8 2014-03-29 14:57:59 +08:00
Thomas Preud'homme b018bac9c8 Fix again GOT32 + PLT32 reloc commit
Fix commit aa561d7011 by setting
has_plt_entry once the plt has been created, not before.
2014-03-29 14:46:26 +08:00
Thomas Preud'homme b125743323 Create bcheck region for argv and arge argument
For program manipulating argv or arge as pointer with construct such as:

(while *argv++) {
  do_something_with_argv;
}

it is necessary to have argv and arge inside a region. This patch create
regions argv and arge) if main is declared with those parameters.
2014-03-29 14:46:26 +08:00
Thomas Preud'homme 9a6ee577f6 Make get_tok_str support NULL as second param.
As was pointed out on tinycc-devel, many uses of get_tok_str gives as
second parameter the value NULL. However, that pointer was
unconditionally dereferenced in get_tok_ptr. This commit explicitely add
support for thas case.
2014-03-29 14:46:26 +08:00
mingodad 5c233f2cf3 The hack to allow valgrind works with tcc compiled programs
have the undesired side effect of programs compiled with
debug info segfaulting after debug info been striped
more tought must be done here
2014-03-28 21:07:06 +00:00
mingodad c025478d7c New implementation of va_list/va_start/var_copy that do not use dynamic memory, with this when compiling fossil-scm with tcc on linux X86_64 it works fine. 2014-03-28 20:28:19 +00:00
mingodad 700c2f769b Remove the fix from my last commit, it was pointed by scan-build and is a false positive, thanks to grischka for pointing it. 2014-03-28 20:25:39 +00:00
mingodad 0ba7c8670c This allow valgrind to work on linux, some how the PHDR is missing and then valgrind complain with:
Inconsistency detected by ld.so: rtld.c: 1284: dl_main: Assertion `_rtld_local._dl_rtld_map.l_libname' failed!
2014-03-28 11:44:00 +00:00
mingodad 14bb8302c4 Fix a incorrect size for malloc. 2014-03-27 22:15:45 +00:00
mingodad 4bc83ac393 After several days searching why my code refactoring to remove globals was crashing,
I found the problem it was because CValue stack variables have rubish as it inital values
and assigning to a member that is smaller than the big union item and trying to
recover it later as a different member gives bak garbage.

ST_FUNC void vset(TCCState* tcc_state, CType *type, int r, int v)
{
    CValue cval;
    memset(&cval, 0, sizeof(CValue));

    cval.i = v; //,<<<<<<<<<<< here is the main bug that mix with garbage
    vsetc(tcc_state, type, r, &cval);
}

/* store a value or an expression directly in global data or in local array */
static void init_putv(TCCState* tcc_state, CType *type, Section *sec, unsigned long c,
                      int v, int expr_type)
{
...
        case VT_PTR:
            if (tcc_state->tccgen_vtop->r & VT_SYM) {
                greloc(tcc_state, sec, tcc_state->tccgen_vtop->sym, c, R_DATA_PTR);
            }

//<<< on the next line is where we try to get the assigned value to cvalue.i as cvalue.ull

            *(addr_t *)ptr |= (tcc_state->tccgen_vtop->c.ull & bit_mask) << bit_pos;
            break;

Also this patch makes vla tests pass on linux 32 bits
2014-03-26 20:18:48 +00:00
Thomas Preud'homme aa561d7011 Simplify and fix GOT32 + PLT32 reloc commit
Introduce a new attribute to check the existence of a PLT entry for a
given symbol has the presence of an entry for that symbol in the dynsym
section is not proof that a PLT entry exists.

This fixes commit dc8ea93b13.
2014-03-26 23:13:28 +08:00
mingodad bed865275d Add the generated executables ending with "-cc" and "-tcc" to the makefile "clean" 2014-03-26 14:32:03 +00:00
mingodad ad9568060e A possible fix for the memory leak reported by valgrind when running tcctest.c with tcc. 2014-03-25 18:06:14 +00:00
Thomas Preud'homme dc8ea93b13 Support GOT32 and PLT32 reloc for same symbol
Some symbol (such as __gmon_start__ but this one does not matter to tcc)
can have both a R_386_GOT32 and R_386_PLT32 relocation. It is thus not
enough to test if a GOT reloc was already done when deciding whether to
return early from put_got_entry.
2014-03-25 22:35:11 +08:00
Thomas Preud'homme 078ba241d9 Always link libtcc1.a in (useful for va_* on x86)
On x86 tcc call to function in libtcc1.a to implement va_* functions.
2014-03-25 21:18:57 +08:00
Thomas Preud'homme f1f45a47ef Add test for previous commit
* Adapt tests2 Makefile to support testing tcc error reporting
* Add test for previous commit
2014-03-25 20:54:19 +08:00
Thomas Preud'homme 6f6ed8acc7 Warn about soft float ABI not being supported
For ARM target, tcc uses the soft float ABI when not asked to use hard
float ABI. This means machine without a VFP co-processor generate code
that they cannot run. This commit add a warning for such cases.
2014-03-25 19:58:12 +08:00
Thomas Preud'homme b8610f14b0 Deprecate FPA and OABI support for ARM 2014-03-25 19:58:03 +08:00
Thomas Preud'homme b68499e971 Make parse_btype only accept one basic type
This makes int char c; and struct {} int c; generate an error. Thanks
Mobi Phil for reporting.
2014-03-24 23:40:39 +08:00
Thomas Preud'homme ec1c83081d Fix relocation of __bound_init
When bound check is enabled, tcc tries to relocate a call to
__bound_init in _init. This means that relocation (in tcc_add_bcheck)
must be done after libtcc1.a (which countains __bound_init) is loaded
but before crtn.o is loaded as this finalize _init.
2014-03-17 23:14:38 +08:00
Thomas Preud'homme 40e3859739 Fix __clear_cache implementation
Forgot to give the parameters to syscall function, doh!
2014-03-11 22:57:22 +08:00
Thomas Preud'homme b2192fc50b Adjust relocation offset for thumb to ARM veneer 2014-03-11 21:45:52 +08:00
Thomas Preud'homme d3d89900f6 Don't hardcode gcc in tests Makefile 2014-03-09 22:54:48 +08:00
Thomas Preud'homme 62d1da1b3e Fix warning of clang 2014-03-09 22:54:30 +08:00
Thomas Preud'homme 98afe11c85 Use intptr_t to cast pointer 2014-03-09 22:22:43 +08:00
Thomas Preud'homme 73ac39c317 Undefine __va* in libtcc1 to avoid errors w/ clang 2014-03-09 22:22:21 +08:00
Thomas Preud'homme e50f08faa1 Make condition in libtcc1 based on target
Prior to this commit runtime library was compiled according to the host
because of the macro used to detec what architecture to choose. This
commit fixes this by using the TARGET_* macro instead.
2014-03-09 22:15:01 +08:00
Thomas Preud'homme 33cea54dc7 Fix type_to_str test for unsigned int 2014-03-09 13:32:40 +08:00
Thomas Preud'homme fdb3b10d06 Fix various errors uncovered by static analysis
Reported-by: Carlos Montiers <cmontiers@gmail.com>
2014-03-08 18:38:49 +08:00
Austin English ba286136bf libtcc: ignore linker optizimization and as-needed options. This allows compiling some packages from Gentoo's portage 2014-03-06 12:29:19 -08:00
Thomas Preud'homme 361ec4f98e Call fill_got_entry unconditionally
Call fill_got_entry unconditionally from fill_got so as to avoid
warnings on !x86-64 architectures. This can be done since this code path
is only followed by x86-64 architecture anyway.
2014-02-10 21:35:00 +08:00
Thomas Preud'homme c6017182f6 Define float_eabi only in arm-gen.o 2014-02-09 23:31:58 +08:00
Austin English 497f9393e0 conftest: fix globbing to match MSVC 2014-02-08 14:38:41 -08:00
Christian Jullien b46f7461a3 Fix warning about undeclared __clear_cache function call. 2014-02-08 08:31:32 +01:00
Thomas Preud'homme d0dae7f241 Ignore VT_DEFSIGN in load on x86-64 arch
This fixes commit b0b5165d16 for x86-64
targets.
2014-02-07 22:31:44 +08:00
Thomas Preud'homme b0b5165d16 Def signedness != signed != unsigned for char
When checking for exact compatibility between types (such as in
__builtin_types_compatible_p) consider the case of default signedness to
be incompatible with both of the explicit signedness for char. That is,
char is incompatible with signed char *and* unsigned char, no matter
what the default signedness for char is.
2014-02-06 21:40:22 +08:00
Thomas Preud'homme e571850d79 Add support of Thumb to ARM branch relocation 2014-02-06 21:38:24 +08:00
Thomas Preud'homme 4aec2902ca Split elf_output_file in smaller functions 2014-02-06 19:38:28 +08:00
Thomas Preud'homme 55f751ac6d Add macro to browse reloc and sym entries
Introduce for_each_elem to browse relocation entries and symbols of a
section.
2014-02-06 19:38:24 +08:00
Thomas Preud'homme 88c9f1bb4e Round mode of ll -> float conversion to nearest
Change rounding mode of long long to float conversion to nearest in
libtcc1.
2014-02-05 20:56:36 +08:00
Thomas Preud'homme d029507494 Fix negative long long to float conversion on ARM 2014-02-05 16:56:27 +08:00
Thomas Preud'homme 0ab07f39a6 Fix float to long long conversion on ARM
Fix float to long long conversion on ARM when the result would fit in an
int.
2014-02-05 16:09:54 +08:00
Thomas Preud'homme 02d2ca8ac7 Fix and extend *FCAST test in tcctest.c
Result of float to unsigned integer conversion is undefined if float is
negative. This commit take the absolute value of the float before doing
the conversion to unsigned integer and add more float to integer
conversion test.
2014-02-05 15:26:46 +08:00
Thomas Preud'homme 17314a1fb3 Fix parameter passing of long long bitfield 2014-02-04 20:55:24 +08:00
Thomas Preud'homme 4e5f15c685 switch last 2 params of TOK_memset on ARM
On ARM, TOK_memset is executed via __aeabi_memset which reverse the
order of the last two parameters.
2014-02-03 22:28:08 +08:00
Thomas Preud'homme 1415d7e6b6 Don't perform builtin_frame_address on ARM 2014-02-03 12:28:25 +08:00
Thomas Preud'homme 4760804dba Fix fct param passing of struct with size < 4 2014-02-03 11:13:42 +08:00
Thomas Preud'homme 9fc57302f8 Switch float abi to softfp for int <--> float conv
This improves commit 5cbe03b9c4 by
avoiding a double transfer when the default float ABI is already softfp.
It's also more clean by expliciting that the ABI is simply changed for
runtime ABI functions.
2014-02-02 20:29:24 +08:00
Thomas Preud'homme 2eb844f8b5 Revert "Add macro to browse reloc and sym entries"
This reverts commit 3cbc7a2dcc.
2014-02-02 20:02:12 +08:00
Thomas Preud'homme e5a706a091 Revert "Split elf_output_file in smaller functions"
This reverts commit b5b82df3e3.
2014-02-02 20:02:11 +08:00
Thomas Preud'homme f62e97e0ed Revert "Add support of Thumb to ARM branch relocation"
This reverts commit 8635939b8d.
2014-02-02 20:02:08 +08:00
Thomas Preud'homme 8635939b8d Add support of Thumb to ARM branch relocation 2014-02-02 17:23:15 +08:00
Thomas Preud'homme b5b82df3e3 Split elf_output_file in smaller functions 2014-02-02 17:23:15 +08:00
Thomas Preud'homme 3cbc7a2dcc Add macro to browse reloc and sym entries
Introduce for_each_elem to browse relocation entries and symbols of a
section.
2014-02-02 17:23:15 +08:00
Thomas Preud'homme 599677a5e2 Give ARM asm mnemonic of PLT entries
Give ARM assembly mnemonic of PLT entries in put_got_entry
2014-02-02 17:23:15 +08:00
Thomas Preud'homme 3d4b57ffe3 Clean tccelf.c
- remove debug printf and commented out code
- remove C++-like comments
- remove whitespace at end of lines
- replace tabs by spaces
2014-02-02 17:23:14 +08:00
Thomas Preud'homme 6f3569e4e2 Ignore abitest-cc and abitest-tcc test programs 2014-02-02 17:23:14 +08:00
Thomas Preud'homme c88c2706a2 Test long long to float conversions 2014-02-01 15:31:28 +08:00
Thomas Preud'homme 5cbe03b9c4 Move result of itof double conv back to VFP reg
EABI functions to convert an int to a double register take the integer
value in core registers and also give the result in core registers.
It is thus necessary to move the result back to VFP register after the
function call. This only affected integer to double conversion because
integer to float conversion used a VFP instruction to do the conversion
and this obviously left the result in VFP register. Note that the
behavior is left untouched for !EABI as the correct behavior in this
case is unknown to the author of this patch.
2014-02-01 14:25:13 +08:00
Iavael fad8e13ccd Ordinary and implicit rules cannot be mixed in the same string in Makefile 2014-01-23 21:40:08 +04:00
grischka 32a4962593 tcctest: add back testXb (self compile with -b)
- Thanks to Kirill "tcc -b itself" should work now
  (was removed in d5f4df09ff)

Also:

- tests/Makefile:
  - fix spurious --I from 767410b875
  - lookup boundtest.c via VPATH (for out-of-tree build)
  - test[123]b?: fail on diff error
  - Windows: test3 now works (from e31579b076)
  - abitest: a libtcc.a made by gcc is not usable for tcc
    on WIndows - using source instead (libtcc.c)

- tccpe:
  - avoid gcc warning (x86_64)
2014-01-21 13:25:14 +01:00
Austin English 48ad93983f workaround a wine cmd bug in build-tcc.bat 2014-01-20 02:23:34 -08:00
Kirill Smelkov 75118780da tccrun: Mark argv area as valid for bcheck
On my x86_64 box in i386 mode with address space randomization turned off,
I've observed the following:

    tests$ ../tcc -B.. -b -run boundtest.c 1
    Runtime error: dereferencing invalid pointer
    boundtest.c:222: at 0x808da73 main()

With diagnostic patch (like in efd9d92b "lib/bcheck: Don't assume heap
goes right after bss") and bcheck traces for __bound_new_region,
__bound_ptr_indir, etc... here is how the program run looks like:

    >>> TCC

    etext:   0x8067ed8
    edata:   0x807321d
    end:     0x807d95c
    brk:     0x807e000
    stack:  0xffffd0b4
    &errno: 0xf7dbd688
    mark_invalid  0xfff80000 -      (nil)
    mark_invalid   0x80fa000 - 0x100fa000
    new  808fdb0  808ff40  101  101  fd0  ff0
    new  808ff44  808ff48  101  101  ff0  ff0
    new  808ff49  8090049  101  101  ff0 1000
    new  808fd20  808fd29  101  101  fd0  fd0
    new  808fd2c  808fd6c  101  101  fd0  fd0
    new  808fd6d  808fda0  101  101  fd0  fd0
    E: __bound_ptr_indir4(0xffffd184, 0x4)
    Runtime error: dereferencing invalid pointer
    boundtest.c:222: at 0x808ea83 main()

So we are accessing something on stack, above stack entry for compiled
main. Investigating with gdb shows that this is argv:

    tests$ gdb ../tcc
    Reading symbols from /home/kirr/src/tools/tinycc/tcc...done.
    (gdb) set args -B.. -b -run boundtest.c 1
    (gdb) r
    Starting program: /home/kirr/src/tools/tinycc/tests/../tcc -B.. -b -run boundtest.c 1
    warning: Could not load shared library symbols for linux-gate.so.1.
    Do you need "set solib-search-path" or "set sysroot"?

    >>> TCC

    etext:   0x8067ed8
    edata:   0x807321d
    end:     0x807d95c
    brk:     0x807e000
    stack:  0xffffd074
    &errno: 0xf7dbd688
    mark_invalid  0xfff80000 -      (nil)
    mark_invalid   0x80fa000 - 0x100fa000
    new  808fdb0  808ff40  101  101  fd0  ff0
    new  808ff44  808ff48  101  101  ff0  ff0
    new  808ff49  8090049  101  101  ff0 1000
    new  808fd20  808fd29  101  101  fd0  fd0
    new  808fd2c  808fd6c  101  101  fd0  fd0
    new  808fd6d  808fda0  101  101  fd0  fd0
    E: __bound_ptr_indir4(0xffffd144, 0x4)

    Program received signal SIGSEGV, Segmentation fault.
    0x0808ea83 in ?? ()
    (gdb) bt
    #0  0x0808ea83 in ?? ()
    #1  0x080639b3 in tcc_run (s1=s1@entry=0x807e008, argc=argc@entry=2, argv=argv@entry=0xffffd144) at tccrun.c:132
    #2  0x080492b0 in main (argc=6, argv=0xffffd134) at tcc.c:346
    (gdb) f 1
    #1  0x080639b3 in tcc_run (s1=s1@entry=0x807e008, argc=argc@entry=2, argv=argv@entry=0xffffd144) at tccrun.c:132
    132             ret = (*prog_main)(argc, argv);
    132             ret = (*prog_main)(argc, argv);
    (gdb) p argv
    $1 = (char **) 0xffffd144

So before running compiled program, mark argv as valid region and we are
done - now the test passes.

P.S. maybe it would be better to just mark the whole vector kernel passes to
program (argv, env, auxv, etc...) as valid all at once...
2014-01-19 16:47:51 +04:00
Vincent Lefevre 262eec3e83 Fixed the LDBL_* macros in include/float.h for x86-64: as said
when x86-64 support was added, "for long double, we use x87 FPU".
And indeed, tests show that Intel's extended precision is used,
not double precision.
2014-01-12 22:26:09 +01:00
Iavael 8e724128e8 Revert "Use anonymous file instead of regular file to back mmap"
This reverts commit 935d8169b8,
because two anonymous mappings would have different content,
while they must have the same one.
2014-01-12 09:29:30 +04:00
Michael Matz f42a02efda tcctest: One more signed zero test
This also checks that -(-0.0) is +0.0.
2014-01-12 04:53:29 +01:00
Michael Matz 05c9b76131 Fix floating point unary minus and plus
negate(x) is subtract(-0,x), not subtract(+0,x), which makes
a difference with signed zeros.  Also +x was expressed as x+0,
in order for the integer promotions to happen, but also mangles signed
zeros, so just don't do that with floating types.
2014-01-12 04:44:27 +01:00
Michael Matz 9c6ddbfe90 Fix compile on ARM non-eabi and non-vfp
Adjust arm_init prototype to match declaration.
2014-01-11 23:44:41 +01:00
Michael Matz 9e11476e15 Fix Fixes for PE x86_64 for fail in code
Applying 64bit relocs assumes that the CVal is initialized to zero
for the whole 64bit.  Consolidate this a bit, at the same time
zeroing the .ull member more consistently when needed.  Fixes segfault
on x86_64-linux using global vars in tcctest.c.
2014-01-11 23:42:58 +01:00
keren 80b36ab628 Fix missing mem_size assignment when using mmap() 2014-01-10 10:23:11 -08:00
Archidemon fdf9fba578 Fixes previous fixes 2014-01-10 11:58:16 +06:00
Archidemon ea7b17f641 Fixes for PE x86_64 for fail in code
int (*fn1)=0x13fde16b5;

and

int fn1(int a) {...}

struct {
  int (*fn2)(int a);
} b = { fn1 };
2014-01-10 09:45:18 +06:00
keren 935d8169b8 Use anonymous file instead of regular file to back mmap
Signed-off-by: Keren Tan <tankeren@gmail.com>
2014-01-09 14:00:19 -08:00
Thomas Preud'homme 767410b875 Various Makefile fixes for cross-compilation
- Build libtcc1 for cross-compiler on arm (arm to X cross compilers)
- Install libtcc1 and includes for arm to i386 cross compiler
- Add basic check of cross-compilers (compile ex1.c)
2014-01-09 17:15:08 +08:00
Thomas Preud'homme da0601e490 Remove WITHOUT_LIBTCC macro: no more user 2014-01-08 21:32:53 +08:00
Thomas Preud'homme bf2854d2a2 Use GNU triplet prefix for cross tcc compilers
Compatibility symlinks are put in place in case some script were relying
on former names except for CMake since it was added after last release.
2014-01-08 21:07:59 +08:00
Thomas Preud'homme 3352cb8aef Shared libraries also have entry points
This fix commit 32734680cb
2014-01-08 18:10:02 +08:00
Thomas Preud'homme 32734680cb Improve ELF on ARM
* set whether soft or hardfloat calling convention is used
* mark ELF file has having an entry point when there is
2014-01-08 17:59:16 +08:00
Thomas Preud'homme 28f0286479 Update elf.h 2014-01-08 17:38:31 +08:00
Thomas Preud'homme b6247d1f3c Add support for runtime selection of float ABI 2014-01-08 15:00:52 +08:00
Thomas Preud'homme 70a088af87 Explicit that EABI only supports VFP for now 2014-01-07 23:20:31 +08:00
Thomas Preud'homme 58f3b7781b Don't say compiler flags are warning options 2014-01-07 23:20:31 +08:00
Vincent Lefevre 99851b0d9e fixed permissions for install on Unix
Signed-off-by: Vincent Lefevre <vincent@vinc17.net>
2014-01-07 16:05:31 +01:00
grischka 3fe2a95d7f be stricter with aliasing
Refactoring (no logical changes):
- use memcpy in tccgen.c:ieee_finite(double d)
- use union to store attribute flags in Sym
Makefile: "CFLAGS+=-fno-strict-aliasing" basically not necessary
anymore but I left it for now because gcc sometimes behaves
unexpectedly without.

Also:
- configure: back to mode 100755
- tcc.h: remove unused variables tdata/tbss_section
- x86_64-gen.c: adjust gfunc_sret for prototype
2014-01-07 14:57:07 +01:00
grischka 2bd0daabbe misc. fixes
- tccgen: error out for cast to void, as in
      void foo(void) { return 1; }
  This avoids an assertion failure in x86_64-gen.c, also.
  also fix tests2/03_struct.c accordingly

- Error: "memory full" - be more specific

- Makefiles: remove circular dependencies, lookup tcctest.c from VPATH

- tcc.h: cleanup lib, include, crt and libgcc search paths"
  avoid duplication or trailing slashes with no CONFIG_MULTIARCHDIR
  (as from 9382d6f1a0)

- tcc.h: remove ";{B}" from PE search path
  in ce5e12c2f9 James Lyon wrote:
  "... I'm not sure this is the right way to fix this problem."
  And the answer is: No, please. (copying libtcc1.a for tests instead)

- win32/build_tcc.bat: do not move away a versioned file
2014-01-06 19:56:26 +01:00
grischka d443644de3 tccpe: cleanup "imports per ordinal"
- tccpe.c: avoid conflict with imp_sym->st_value, cleanup
- _parseLibs.bat, _tcc.bat: no instructions for usage, removed.

from commit 642b6d0f50
2014-01-06 19:32:50 +01:00
grischka 4ad186c5ef i386: use __fixdfdi instead of __tcc_cvt_ftol
Variants __fixsfdi/__fixxfdi are not needed for now because
the value is converted to double always.

Also:
- remove __tcc_fpinit for unix as it seems redundant by the
  __setfpucw call in the startup code
- avoid reference to s->runtime_main in cross compilers
- configure: fix --with-libgcc help
- tcctok.h: cleanup
2014-01-06 19:07:08 +01:00
Thomas Preud'homme 8efaa71190 Fix struct ret in variadic fct with ARM hardfloat
The procedure calling standard for ARM architecture mandate the use of
the base standard for variadic function. Therefore, hgen float aggregate
must be returned via stack when greater than 4 bytes and via core
registers else in case of variadic function.

This patch improve gfunc_sret() to take into account whether the
function is variadic or not and make use of gfunc_sret() return value to
determine whether to pass a structure via stack in gfunc_prolog(). It
also take advantage of knowing if a function is variadic or not move
float result value from VFP register to core register in gfunc_epilog().
2014-01-06 22:57:05 +08:00
Thomas Preud'homme bcc1904f9c Don't call __tcc_fpinit if using libgcc 2014-01-06 11:26:09 +08:00
Thomas Preud'homme a01d83d783 Don't enable bound check if libgcc is used
Bound check rely on some functions provided by libtcc. It should
therefore not be enabled when libgcc is used.
2014-01-06 11:26:09 +08:00
Daniel Glöckner 5078a06e91 Relicensing TinyCC
I'm fine with relicensing all my contributions to files other than
arm-gen.c.
2014-01-04 15:35:26 +01:00
Thomas Preud'homme eda2c756ed Move logic for if (int value) to tccgen.c
Move the logic to do a test of an integer value (ex if (0)) out of
arch-specific code to tccgen.c to avoid code duplication. This also
fixes test of long long value which was only testing the bottom half of
such values on 32 bits architectures.
2014-01-04 21:10:05 +08:00
Thomas Preud'homme c634c797c5 Update Changelog from git changelog entries 2014-01-04 21:10:05 +08:00
Daniel Glöckner 9e9e5c2929 Relicensing TinyCC 2014-01-04 10:59:04 +01:00
Thomas Preud'homme 3eed3506b4 Fix negation of 0.0 and -0.0 2014-01-04 17:07:58 +08:00
Thomas Preud'homme 0382131c6f Provide install-strip target in Makefile 2014-01-04 09:48:45 +08:00
Thomas Preud'homme 9e79b18bca Use libtcc.a for static link even with USE_LIBGCC
When statically linking, runtime library should be static as well. tcc
could link with libgcc.a but it's in a gcc version specific directory.
Another solution, followed by this patch, is to use libtcc.a when
statically linking, even if USE_LIBGCC was configured.
2014-01-03 18:20:51 +08:00
Thomas Preud'homme e0e9a2a295 Report error on NaN comparison
Use comisd / fcompp for float comparison (except TOK_EQ and TOK_NE)
instead of ucomisd / fucompp to detect NaN comparison.

Thanks Vincent Lefèvre for the bug report and for also giving the
solution.
2014-01-03 10:19:38 +08:00
Thomas Preud'homme 59b8007f98 Always set *palign in classify_x86_64_arg
Set *palign for VT_BITFIELD and VT_ARRAY types in classify_x86_64_arg as
else you happen to have in *palign what was already there. This can
cause gfunc_call on !PE systems to consider an array as 16 bytes align
and trigger the assert if the previous argument was 16 bytes aligned.
2014-01-03 10:19:38 +08:00
grischka fbc8810334 Fix "Add support for struct > 4B returned via registers"
- avoid assumption "ret_align == register_size" which is
  false for non-arm targets
- rename symbol "sret" to more descriptive "ret_nregs"

This fixes commit dcec8673f2

Also:
- remove multiple definitions in win32/include/math.h
2013-12-16 15:38:10 +01:00
Thomas Preud'homme 46dd2971ab make git ignore lib/arm directory 2013-12-15 09:49:20 +08:00
Thomas Preud'homme a24e31e85d Fix signed integer division in ARM runtime ABI
- fix computation of absolute value (clearing the sign bit does not
  since integers are encoded in 2's complement)
- test sign of integer in a more conventional way (binary and with the
  high bit does not work for long long due to a bug in gtst)
- spacing in include
2013-12-15 09:44:20 +08:00
Thomas Preud'homme f2dbcf7594 Add ARM aeabi functions needed to run tcctest
Add implementation for float / integer conversion functions:
  __aeabi_d2lz, __aeabi_d2ulz, __aeabi_f2lz, __aeabi_f2ulz, __aeabi_l2d,
  __aeabi_l2f, __aeabi_ul2d, __aeabi_ul2f

Add implementation for long long helper functions:
  __aeabi_ldivmod, __aeabi_uldivmod, __aeabi_llsl, __aeabi_llsr, __aeabi_lasr

Add implementation for integer division functions:
  __aeabi_uidiv, __aeabi_uidivmod, __aeabi_idiv, __aeabi_idivmod,
2013-12-11 10:15:30 +08:00
Thomas Preud'homme 389c25c4b9 Support special calling convention for runtime ABI
Add infrastructure to support special calling convention for runtime ABI
function no matter what is the current calling convention. This involve
2 changes:
- behave as per base standard in gfunc_call
- move result back in VFP register in gen_cvt_itof1
2013-12-11 10:15:29 +08:00
Thomas Preud'homme 3676f61983 Define __ARM_EABI__ and __ARMEL__ when applicable 2013-11-26 12:06:21 +08:00
Thomas Preud'homme 5919da6f05 Make abitest.c have predictable result
stdarg_test in abitest.c relies on a sum of some parameters made by both
the caller and the callee to reach the same result. However, the
variables used to store the temporary result of the additions are not
initialized to 0, leading to uncertainty as to the results. This commit
add this needed initialization.
2013-11-25 11:25:04 +08:00
Thomas Preud'homme 4260ce1889 Add va_* macro implementation for ARM 2013-11-25 11:24:02 +08:00
Thomas Preud'homme 82b257c29c Add comment to explain the code added by 41ce391c
Add a comment in arm-gen.c to explain how commit
41ce391c86 solves the register corruption
when passing a structure in a function call.
2013-11-25 11:00:51 +08:00
Thomas Preud'homme 48fc746652 Fix structure passing in ARM calling convention
Fix the address on stack where a structure is copied when it is a
parameter of a function call. This address must be computed from the
stack pointer and a possible padding offset.
2013-11-25 10:58:00 +08:00
Thomas Preud'homme dcec8673f2 Add support for struct > 4B returned via registers
On ARM with hardfloat calling convention, structure containing 4 fields
or less of the same float type are returned via float registers. This
means that a structure can be returned in up to 4 double registers in a
structure is composed of 4 doubles. This commit adds support for return
of structures in several registers.
2013-11-22 09:27:15 +08:00
Thomas Preud'homme d9d60a1ebd Remove code in arm-gen.c for struct packing in reg
Struct packing in register is now handled since commit 2bbfaf43 by
tccgen.c proper.
2013-11-22 00:15:34 +08:00
Thomas Preud'homme 63a84713ee Correctly identify homogeneous float aggregate
First related symbol of a structure justs indicate its size. This first
member is the second related symbol.
2013-11-22 00:13:05 +08:00
Thomas Preud'homme c3e7c725b5 Fix counting of VFP regs in ARM's gfunc_prolog
Fix in gfunc_prolog for ARM the counting of the highest numbered VFP
float register used for parameter passing, rounded to 2. It can be
computed from the range of VFP float register with the highest range
start and adding the number of VFP float register occupied. This ensure
that parameter of type struct that spans over more than 2 float
registers are correctly taken into account.
2013-11-21 22:27:15 +08:00
Thomas Preud'homme 41ce391c86 Fix register corruption at function call on ARM
Prior to this commit, params could use some registers that do not appear
in the value stack. Therefore when generating function call, one of such
register could be reused, leading to wrong parameter content. This
happens when a structure is passed via core register, as only the first
register would appear in the value stack.
2013-11-21 21:09:44 +08:00
Thomas Preud'homme 1b606d1884 Allow thumb transition for R_ARM_PC24
Allow bl -> blx conversion in the case of R_ARM_PC24 relocation with
instruction being an unconditional bl. Also make spacing more uniform.
2013-11-18 00:03:38 +08:00
Thomas Preud'homme 0c40bc8982 Correctly align and reclaim stack at function call
* Correctly align stack in case of structure split between core
  registers and stack
* Correctly reclaim stack space after function call in the case where
  the stack needed padding to be aligned at function call.
2013-11-17 18:26:56 +08:00
Thomas Preud'homme 1528a08540 Refactor and simplify gfunc_call() on arm 2013-11-15 17:57:31 +08:00
Joseph Poirier 0650ab01c8 struct variable behind guard, proper macro check, and remove some whitespace.
Wrap runtime_main as per its declaration in tcc.h.
Fix preprocessor check for TCC_ARM_EABI macro definition.

Signed-off-by: Joseph Poirier <jdpoirier@gmail.com>
2013-11-08 13:24:15 -06:00
Thomas Preud'homme fbb4841606 Add __clear_cache implementation in libtcc1
Add __clear_cache function for flushing caches to libtcc1.
2013-11-05 19:29:43 +08:00
Thomas Preud'homme b7d017dec8 Fix allocation of struct in registers on ARM
Allocation of struct in core and/or VFP registers on ARM is made by
manipulating the value stack to create 3 distinct zones: parameters
allocated on stack, parameters of type struct allocated in core
registers and parameters of type struct allocated in VFP registers.
Parameters of primitive type can be in any zone. This commit change the
order of the zones from stack, VFP, core to stack, core, VFP (from
highest addresses to lowest ones) in order to correctly deal the
situation when structures are allocated both in core and VFP registers.
2013-11-05 17:50:30 +08:00
Thomas Preud'homme cf02f920c1 Revert "Add support for thread-local storage variables"
TLS support in tinyCC is absolutely not ready:
- segment register not select in load and store
- no relocation added for computing offset of per-thread symbol
- no support for TLS-specific relocations
- no program header added as per Drepper document about TLS

This reverts commit 1c4afd1350.
2013-11-03 18:55:54 +08:00
Thomas Preud'homme 1c4afd1350 Add support for thread-local storage variables 2013-10-29 22:10:02 +08:00
Amine Najahi 3b07a15fd1 Detect usage of incomplete types inside struct/union
Make sure the only exception is for a flexible array member
as the last element of a structure
2013-10-06 14:51:29 +02:00
Ramsay Jones d0c2f00df2 Fix CONFIG_TCC_SYSINCLUDEPATHS on !win32 systems
Commit 9382d6f1 ("Fix lib, include, crt and libgcc search paths",
07-09-2013) inadvertently included an initial empty entry to the
CONFIG_TCC_SYSINCLUDEPATHS variable (for non win32 targets). In
addition to an empty line in the 'tcc -vv' display, this leads
to the preprocessor attempting to read an include file from the
root of the filesystem (i.e. '/header.h').

Signed-off-by: Ramsay Jones <ramsay@ramsay1.demon.co.uk>
2013-10-02 21:49:55 +02:00
Thomas Preud'homme 385a86b000 Fix commit 0f5942c6b3 2013-10-01 17:11:44 +02:00
Thomas Preud'homme 0f5942c6b3 Avoid warnings with gcc 4.8 + default CFLAGS 2013-09-24 15:37:12 +02:00
Thomas Preud'homme a1a691a030 Detect correct instruction with incorrect operands
Display a different warning when an instruction is recognized by tcc but
the operands found do not correspond to the constraints of the
instruction.
2013-09-24 15:37:11 +02:00
Vittorio Giovara 45b35a3d66 set the user-defined library search paths first 2013-09-23 09:40:06 +02:00
Thomas Preud'homme 673befd2d7 Report error when redefining enumerator
Prevent the following code from compiling:

enum color {RED, GREEN, BLUE};
enum rgb {RED, G, B};
2013-09-20 22:49:49 +02:00
Thomas Preud'homme 82969f045c Report error when using undefined enum
Prevent the following code from compiling:

int main(void)
{
	enum rgb c = 42;
	return c;
}

Reported-by: John Haque <j.eh@mchsi.com>
2013-09-20 21:22:11 +02:00
Thomas Preud'homme 0f522fb32a Forbid enum redefinition.
Prevent the following code from compiling:

enum color {RED, GREEN, BLUE};
enum color {R, G, B};

int main()
{
        return R;
}

Reported-by: John Haque <j.eh@mchsi.com>
2013-09-20 01:06:43 +02:00
Thomas Preud'homme a465b7f58f Forbid the use of array of functions
Prevent the following code from compiling:

int (*fct)[42](int x);

Reported-by: Abdul Wadud Mohammad Mohibur Rashid <mohibur_rashid@yahoo.com>
2013-09-19 18:58:46 +02:00
YX Hao 642b6d0f50 Add the possibility to use noname functions by ordinal
tcc.c:
process.h:177:20: note: expected 'char * const*' but argument is of type 'char const*const*'

tccpe.c:
Add the possibility to use noname functions by ordinal.
use def file: "AliasName @n"

build-tcc.bat:
1. Enable 32 bits mode on 64 bits OS.
2. build doc.

_parseLibs.bat:
Convenient to use "*.def + *.c" instead of *.a, just use -l*

_tcc.bat:
a practice of _parseLibs.bat

Signed-off-by: YX Hao <lifenjoiner@163.com>
2013-09-19 21:50:38 +08:00
Thomas Preud'homme 76cb1144ef Generate an error when a function is redefined
Use one more bit in AttributeDef to differenciate between declared
function (only its prototype is known) and defined function (its body is
also known). This allows to generate an error in cases like:

int f(){return 0;}
int f(){return 1;}
2013-09-16 14:48:33 +02:00
grischka 13b997668e win32: fix libtcc support
For "tcc -run file.c", I was trying to initialize the FP control
in a function in libtcc1.a (_runmain) before calling main.

Unfortunately that turned out to cause problems with for example
libtcc_test since such usage doesn't necessarily define a 'main'
function.

So for tcc -run we're back to relying on the FP control word
that is set in the startup code of tcc.exe rsp. libtcc.dll.

This fixes part of commit 73faaea227
2013-09-10 15:36:56 +02:00
Ramsay Jones 235a65033f libtcc1.c: Fix __asm__() in __tcc_fpinit and __tcc_cvt_ftol
Signed-off-by: Ramsay Jones <ramsay@ramsay1.demon.co.uk>
2013-09-09 23:59:09 +02:00
Thomas Preud'homme 9382d6f1a0 Fix lib, include, crt and libgcc search paths 2013-09-07 19:28:06 +02:00
grischka 73faaea227 i386-gen: preserve fp control word in gen_cvt_ftoi
- Use runtime function for conversion
- Also initialize fp with tcc -run on windows

This fixes a bug where
  double x = 1.0;
  double y = 1.0000000000000001;
  double z = x < y ? 0 : sqrt (x*x - y*y);
caused a bad sqrt because rounding precision for the x < y comparison
was different to the one used within the sqrt function.

This also fixes a bug where
  printf("%d, %d", (int)pow(10, 2), (int)pow(10, 2));
would print
  100, 99

Unrelated:
  win32: document relative include & lib lookup
  win32: normalize_slashes: do not mirror silly gcc behavior
  This reverts part of commit 8a81f9e103
  winapi: add missing WINAPI decl. for some functions
2013-08-28 22:55:05 +02:00
grischka 69c2e7f96c tccgen: fix crash with undeclared struct
... as in:
    #include<stdio.h>
    int main()
    {
        struct asdasd x;
        printf("%d\n", sizeof(x));
    }
This fixes commit 17571298f3
2013-07-24 17:06:13 +02:00
Frédéric Féret 8c033a1461 Relicensing TinyCC 2013-06-22 16:18:49 +02:00
Thomas Preud'homme 37b0348993 Define __ARM_PCS_VFP in hardfloat compilation mode 2013-06-15 00:26:07 +02:00
Thomas Preud'homme f6b50558fc Add support for load/store of _Bool value
Add support for loading _Bool value in i386, x86_64 and arm as well as
support for storing _Bool value on arm.
2013-06-14 16:19:51 +02:00
Roy 807dc7c8de tccpe: pstrcpy() will truncate .stabstr section name, use strncpy() instead. 2013-06-06 09:26:31 +08:00
Thomas Preud'homme d0c4138ac2 Improve texi2html -> makeinfo conversion 2013-05-29 13:16:54 +02:00
Fabrice Bellard 47d9f08c6f Relicensing TinyCC 2013-05-23 10:40:12 +02:00
Shinichiro Hamaji 47305d427d Relicensing TinyCC 2013-05-06 06:55:16 +09:00
Thomas Preud'homme 6f512a7f1c Relicensing TinyCC 2013-05-05 23:51:58 +02:00
grischka e670435500 Relicensing TinyCC
It has been discussed on the list whether it would be good
to relicense TinyCC under a more permissive BSD-like license.

The discussion started here:
http://lists.gnu.org/archive/html/tinycc-devel/2013-04/msg00052.html

Opinions varied but mostly were positive so it appears to
be worth to start the process and see how far we can get.

For that purpose I've committed a new file RELICENSING with the
suggested new license clause and a list for people to confirm
their agreement (or disagreement).

If you have contributed to TinyCC in the past, in particular if
you are one of the copyright owners for an entire file, please
add yourself to that file (rsp. replace the question mark) and
commit the change to the "mob" brancn with log message:

     Relicensing TinyCC

Thanks.
2013-05-05 23:45:51 +02:00
Daniel Glöckner 4d86b20701 ARM hardfloat: fix struct return with float/double args
Fixes the case where the structure is not returned in registers.
2013-05-01 16:17:54 +02:00
grischka be1b6ba7b7 avoid "decl after statement" please
for compiling tcc with msc
2013-04-30 00:33:34 +02:00
James Lyon 41b3c7a507 Improved variable length array support.
VLA storage is now freed when it goes out of scope. This makes it
possible to use a VLA inside a loop without consuming an unlimited
amount of memory.

Combining VLAs with alloca() should work as in GCC - when a VLA is
freed, memory allocated by alloca() after the VLA was created is also
freed. There are some exceptions to this rule when using goto: if a VLA
is in scope at the goto, jumping to a label will reset the stack pointer
to where it was immediately after the last VLA was created prior to the
label, or to what it was before the first VLA was created if the label
is outside the scope of any VLA. This means that in some cases combining
alloca() and VLAs will free alloca() memory where GCC would not.
2013-04-27 22:58:52 +01:00
James Lyon 6ee366e765 Fixed x86-64 long double passing.
long double arguments require 16-byte alignment on the stack, which
requires adjustment when the the stack offset is not an evven number of
8-byte words.
2013-04-26 16:42:12 +01:00
James Lyon 41d76e1fcb Fixed silly error in Windows build of tests (abitest-cc not linking to libtcc)
I really should do this when less tired; I keep breaking one platform
while fixing another. I've also fixed some Windows issues with tcctest
since Windows printf() uses different format flags to those on Linux,
and removed some conditional compilation tests in tcctest since they
now should work.
2013-04-26 01:27:04 +01:00
James Lyon ae2ece93da Fixed i386 calling convention issue and CMake build on i386.
The i386 calling convention expects the callee to pop 1 word of the
stack when performing a struct ret.
2013-04-26 00:31:46 +01:00
James Lyon 1caee8ab3b Sorted out CMake on x86-64 and fixed silly XMM# bug introduced when working on Win64 stdargs.
I removed the XMM6/7 registers from the register list because they are not used
on Win64 however they are necessary for parameter passing on x86-64. I have now
restored them but not marked them with RC_FLOAT so they will not be used except
for parameter passing.
2013-04-25 22:30:53 +01:00
James Lyon e7a7efed11 Added cross compilation to CMake build system.
Brings it more into line with make based system. I've tested on 32- and 64-bit
Windows, but not yet Linux.
2013-04-25 01:08:18 +01:00
James Lyon 5c35ba66c5 64-bit tests now pass (well, nearly).
tcctest1-3 fail, but this appears to be due to bugs in GCC rather than TCC
(from manual inspection of the output).
2013-04-24 02:19:15 +01:00
James Lyon 8a81f9e103 Added CMake build system (to facilitate Win64 builds)
Win32 build and tests work under CMake, however I haven't added
install code yet. Win64 build fails due to chkstk.S failing to
assemble.
2013-04-21 11:20:20 +01:00
James Lyon 05fa2e754b Workaround for MinGWs use of 80-bit long double on Win32.
This is incompatible with MSVC and TCC on Win32.

Bounds checking appears to be broken (test4).
2013-04-19 23:21:33 +01:00
James Lyon 23f73e92f3 Fixed 64-bit integer bug introduced by x86-64 ABI work.
Now I need to check that the x86-64 stuff still works.
2013-04-19 22:55:09 +01:00
James Lyon cbce6d2bac Improved x86-64 XMM register argument passing.
Also made XMM0-7 available for use as temporary registers, since they
are not used by the ABI. I'd like to do the same with RSI and RDI but
that's trickier since they can be used by gv() as temporary registers
and there isn't a way to disable that.
2013-04-19 22:05:49 +01:00
James Lyon 946afd2343 Fixed problems with XMM1 use on Linux/x86-64.
All tests pass. I think I've caught all the cases assuming only XMM0 is
used. I expect that Win64 is horribly broken by this point though,
because I haven't altered it to cope with XMM1.
2013-04-19 18:33:30 +01:00
James Lyon 0e17671f72 Most x86-64 tests now work; only on error in test1-3.
I've had to introduce the XMM1 register to get the calling convention
to work properly, unfortunately this has broken a fair bit of code
which assumes that only XMM0 is used.
2013-04-19 15:33:16 +01:00
James Lyon b961ba5396 Got test1-3 working on x86-64.
There are probably still issues on x86-64 I've missed.
I've added a few new tests to abitest, which fail (2x long long and 2x double
in a struct should be passed in registers).
2013-04-19 11:10:13 +01:00
James Lyon 55ea6d3fc1 x86-64 ABI fixes.
abitest now passes; however test1-3 fail in init_test. All other tests
pass. I need to re-test Win32 and Linux-x86.

I've added a dummy implementation of gfunc_sret to c67-gen.c so it
should now compile, and I think it should behave as before I created
gfunc_sret.
2013-04-19 00:46:49 +01:00
James Lyon 3f1d900007 Added some additional tests to abitest.c
This is just to ensure that I haven't (and don't) really mess anything up.
2013-04-18 17:55:00 +01:00
James Lyon 2bbfaf436f Tests in abitest.c now work on Win32.
I expect that Linux-x86 is probably fine. All other architectures
except ARM are definitely broken since I haven't yet implemented
gfunc_sret for these, although replicating the current behaviour
should be straightforward.
2013-04-18 17:27:34 +01:00
James Lyon ce5e12c2f9 Added ABI compatibility tests with native compiler using libtcc.
Only one test so far, which fails on Windows (with MinGW as the native
compiler - I've tested the MinGW output against MSVC and it appears the
two are compatible).

I've also had to modify tcc.h so that tcc_set_lib_path can point to the
directory containing libtcc1.a on Windows to make the libtcc dependent
tests work. I'm not sure this is the right way to fix this problem.
2013-04-17 21:52:44 +01:00
James Lyon e31579b076 Fixed tests on Windows (including out-of-tree problems)
Modified tcctest.c so that it uses 'double' in place of 'long double'
with MinGW since this is what TCC does, and what Visual C++ does. Added
an option -norunsrc to tcc to allow argv[0] to be set independently of
the compiled source when using tcc -run, which allows tests that rely on
the value of argv[0] to work in out-of-tree builds.

Also added Makefile rules to automatically update out-of-tree build
Makefiles when in-tree Makefiles have changed.
2013-04-17 20:32:07 +01:00
James Lyon 1d673cbfd6 Fixed out of tree build problem on Windows.
Some files installed are not generated so need to be copied from the
source tree rather than the build tree.

I also switched texi2html for makeinfo --html since texi2html is
apparently unmaintained.
2013-04-17 17:32:18 +01:00
Thomas Preud'homme 1ef95ea342 Fix building instruction wrt make/gmake
Revert building instruction to mention the use of make instead of gmake
but add a note to tell FreeBSD and OSX users to use gmake instead of
make.
2013-04-08 23:26:27 +02:00
Jov 0de6fe6c41 Update README,add x86_64/arm,FreeBSD/OSX etc.
Change make to gmake because make will not be gnu make in some OS like
FreeBSD
2013-03-25 22:51:52 +08:00
Thomas Preud'homme c68af2db9d Fix synchronization between data and instr caches 2013-03-19 14:03:15 +01:00
Thomas Preud'homme 6ed6a36a51 Flush caches before -running program
On some architectures, ARM for instance, the data and instruction caches
are not coherent with each other. This is a problem for the -run feature
since instructions are written in memory, and are thus written in the
data cache first and then later flushed to the main memory. If the
instructions are executed before they are pushed out of the cache, then
the processor will fetch the old content from the memory and not the
newly generated code. The solution is to flush from the data cache all
the data in the memory region containing the instructions and to
invalidate the same region in the instruction cache.
2013-03-18 10:08:39 +01:00
Thomas Preud'homme d9dfd9cded Fix configure script on FreeBSD
* x86-64 architectures are reported as amd64 by uname -r
* FreeBSD platform don't need -ldl for linking
2013-03-14 18:15:32 +01:00
Thomas Preud'homme c219a53402 Update .gitignore with regards to test changes 2013-03-11 22:32:28 +01:00
Urs Janssen 243c699009 document $CPATH, $C_INCLUDE_PATH, $LIBRARY_PATH 2013-02-20 14:23:44 +01:00
Urs Janssen 183b2ab14c don't confuse LD_LIBRARY_PATH (run time) with LIBRARY_PATH (link time) 2013-02-19 14:41:58 +01:00
Andrew Aladjev 0ad857c80e added CPATH, C_INCLUDE_PATH and LD_LIBRARY_PATH 2013-02-19 14:47:36 +03:00
Urs Janssen 0db7f616ad remove doubled prototype
fix documentation about __TINYC__
define __STDC_HOSTED__ like __STDC__
2013-02-18 15:44:18 +01:00
Thomas Preud'homme 5d6cfe855a Fix GNU Hurd interpreter path 2013-02-18 11:53:00 +01:00
Thomas Preud'homme e946c3583f Add support for KfreeBSD 64bits 2013-02-18 11:42:49 +01:00
Roy 322743eef8 libtcc: tcc_define_symbol() uses strings, fix segfault 2013-02-18 08:32:03 +08:00
Thomas Preud'homme 3ad64ffe2e Define __STDC_HOSTED__ to a sane value
Define __STDC_HOSTED__ to one as the correct values should be either 1
or 0. Since tinycc is hosted, it should be set to 1.

Thanks Christian Jullien for the report.
2013-02-17 22:13:41 +01:00
Thomas Preud'homme fe64a4d005 Define __STDC_HOSTED__
Quoting Michael Matz on tinycc-devel:

"__STDC_HOSTED__  : not set (incorrectly, it should probably be set to 1
                    given that tcc assumes a normal main() and that the
                    rest of the provided facilities is provided by the C
                    library not under tcc control)"
2013-02-17 19:44:55 +01:00
Urs Janssen 0bdbd49eac add version number to manpage
avoid c++/c99 style comments in preprocessor directives
avoid leadings whitespaces in preprocessor directives
mention implemented variable length arrays in documentation
fixed ambiguous option in texi2html call (Austin English)
2013-02-17 00:48:51 +01:00
Thomas Preud'homme d5e22108a0 Release TinyCC 0.9.26 2013-02-15 14:23:58 +01:00
Urs Janssen bfde339b8c fixed pasto in in 108b2876; background for the additional $CC test is:
GCC_MAJOR may be set even is $CC not realy gcc (but i.e. clang, which (as
of 3.1) requires an addtional CFLAG to accept the non portable (gnuisms all
over the place; try to cimpile tcc with Sun^HOracle, Intel, Pathscale, ...
compiler) code).
2013-02-15 13:04:39 +01:00
Urs Janssen cec76c8b8a - document -dumpversion
- fixed a broken prototype
2013-02-15 12:48:33 +01:00
Urs Janssen 108b287665 - don't use GCC_MAJOR to see if we're not using gcc as GCC_MAJOR might be set
during configure even with --cc=notgcc as long as gcc is installed.
2013-02-15 00:53:33 +01:00
Thomas Preud'homme 0928761257 Revert "Don't search libgcc_s.so.1 on /lib64"
This reverts commit b9f089fc4a.
2013-02-14 23:52:11 +01:00
grischka c4397b2b02 configure: detect ARM variants
Using gnu make's variable variable-names.
2013-02-14 21:15:56 +01:00
Thomas Preud'homme b9f089fc4a Don't search libgcc_s.so.1 on /lib64
It seems libgcc_s.so.1 is systematically on /lib/ (whether
/lib/$triplet for multiarch systems or just /lib for other systems).
2013-02-14 18:05:55 +01:00
grischka 762a43877b configure: pass CONFIG_xxxDIR/PATH options via commandline
- except for CONFIG_SYSROOT and CONFIG_TCCDIR

Strictly neccessary it is only for CONFIG_MULTIARCHDIR
because otherwise if it's in config.h it is impossible to
leave it undefined.

But it is also nicer not to use these definitions for
cross-compilers.

- Also:
lib/Makefile : include ../Makefile for CFLAGS
lib/libtcc1.c : fix an issue compiling tcc with tcc on x64
2013-02-14 17:43:24 +01:00
Thomas Preud'homme 99b801dafc Add missing heading slash to detect /lib64 systems 2013-02-14 16:57:27 +01:00
Thomas Preud'homme b4656f3191 Add arm ABI detection in conftest.c 2013-02-14 16:40:16 +01:00
Thomas Preud'homme b1a8233562 Another attempt to "detect" multiarch 2013-02-14 15:39:35 +01:00
Urs Janssen 062efe6ab8 - make clang accept unportable code in libtcc1.c
- add -dumpversion cmd.line opt
2013-02-14 08:24:51 +01:00
grischka 944627c479 configure: cleanup
- add quotes: eval opt=\"$opt\"
- use $source_path/conftest.c for OOT build
- add fn_makelink() for OOT build
- do not check lddir etc. on Windows/MSYS
- formatting

config-print.c
- rename to conftest.c (for consistency)
- change option e to b
- change output from that from "yes" to "no"
- remove inttypes.h dependency
- simpify version output

Makefile:
- improve GCC warning flag checks

tcc.h:
- add back default CONFIG_LDDIR
- add default CONFIG_TCCDIR also (just for fun)

tccpp.c:
- fix Christian's last warning
  tccpp.c: In function ‘macro_subst’:
  tccpp.c:2803:12: warning: ‘*((void *)&cval+4)’ is used uninitialized
     in this function [-Wuninitialized]
  That the change fixes the warning doesn't make sense but anyway.

libtcc.c:
- tcc_error/warning: print correct source filename/line for
  token :paste: (also inline :asm:)

lddir and multiarch logic still needs fixing.
2013-02-14 06:53:07 +01:00
Thomas Preud'homme e298f60838 Create config-print program to test $cc
Create a helper program called config-print to print informations
relative to the BUILD/HOST environment in the case of native
compilation.
2013-02-13 22:35:36 +01:00
Thomas Preud'homme a4cbd9b002 Various fixes for f9ac2013 2013-02-13 22:28:41 +01:00
Thomas Preud'homme f9ac201377 Detect multiarch triplet and lddir from ldd output 2013-02-13 20:14:13 +01:00
Thomas Preud'homme af4b27f0fd Fix previous commit
Fix commit f6cfaa6d25
2013-02-13 17:58:58 +01:00
Thomas Preud'homme f6cfaa6d25 Improve multiarch detection
* Detect multiarch at configure time
* Detect based on the place where crti.o is
* Define multiarch triplet in tcc.h
2013-02-13 17:03:30 +01:00
grischka 05108a3b0a libtcc: new LIBTCCAPI tcc_set_options(TCCState*, const char*str)
This replaces       -> use instead:
-----------------------------------
- tcc_set_linker    -> tcc_set_options(s, "-Wl,...");
- tcc_set_warning   -> tcc_set_options(s, "-W...");
- tcc_enable_debug  -> tcc_set_options(s, "-g");

parse_args is moved to libtcc.c (now tcc_parse_args).

Also some cleanups:
- reorder TCCState members
- add some comments here and there
- do not use argv's directly, make string copies
- use const char* in tcc_set_linker
- tccpe: use fd instead of fp

tested with -D MEM_DEBUG: 0 bytes left
2013-02-12 19:13:28 +01:00
grischka 829655949b tcc --help: update option summary
tcc-doc.texi: also
2013-02-10 20:39:05 +01:00
grischka 8042121d74 tcc -vv/--print-search-dirs: print more info
tests/Makefile:
- print-search-dirs when 'hello' fails
- split off hello-run

win32/include/_mingw.h:
- fix for compatibility with mingw headers
  (While our headers in win32 are from mingw-64 and don't have
  the problem)

tiny_libmaker:
- don't use "dangerous" mktemp
2013-02-10 00:38:40 +01:00
grischka d6d7686b60 tcc.h: declare CValue.tab[LDOUBLE_SIZE/4]
Should fix some warnings wrt. access out of array bounds.

tccelf.c: fix "static function unused" warning
x86_64-gen.c: fix "ctype.ref uninitialzed" warning and cleanup
tcc-win32.txt: remove obsolete limitation notes.
2013-02-08 19:07:11 +01:00
Thomas Preud'homme 4b8e7f1f39 Fix fn_dirname in configure script
Use ${parameter%word} construct to fix fn_dirname in configure script.
Bonus: on less fork.
2013-02-08 11:07:22 +01:00
grischka 7a477d70ca lib/Makefile: use CC, add bcheck to libtcc1.a
Also:
- fix "make tcc_p" (profiling version)
- remove old gcc flags:
  -mpreferred-stack-boundary=2 -march=i386 -falign-functions=0
- remove test "hello" for Darwin (cannot compile to file)
2013-02-06 19:01:07 +01:00
grischka 92024ab07a tccelf: fix debug section relocation
With:
   tcc -g hello.c
   gdb a.out
     b main
gdb refused to know "main" because of broken dwarf info.

This partially reverts commit 0d598aca08.
I don't remember what the problem was but it was the wrong way
to fix it.
2013-02-05 21:18:29 +01:00
grischka d5f4df09ff tests: cleanup
tests:
- add "hello" to test first basic compilation to file/memory
- add "more" test (tests2 suite)
- remove some tests

tests2:
- move into tests dir
- Convert some files from DOS to unix LF
- remove 2>&1 redirection

win32:
- tccrun.c: modify exception filter to exit correctly (needed for btest)
- tcctest.c: exclude weak_test() (feature does not exist on win32)
2013-02-05 14:27:38 +01:00
grischka 60cf64612c tests2: move into tests 2013-02-05 13:22:36 +01:00
Thomas Preud'homme 6c4d3244da Align on 4n bytes when copying fct args on stack
When copying function arguments on stack in prolog, use multiple of 4
bytes for alignment.
2013-02-05 10:48:42 +01:00
grischka e0aee4f455 portability: make tcc_get_symbol() available for non-native
For consistency with tcc_add_symbol().
Use uintptr_t here also.
2013-02-04 20:57:57 +01:00
Thomas Preud'homme 60e647f856 Slightly improved support for !gcc compilers
Hack before a complete solution after 0.9.26's release to be able to
compile tcc with clang.
2013-02-04 18:14:06 +01:00
grischka 248dc67506 win32: Honor "-Wl,-subsystem=console/gui" option 2013-02-04 17:58:37 +01:00
grischka 4b539aa67d tccrun.c: unify rt_get_caller_pc prototype 2013-02-04 17:24:03 +01:00
grischka 97c279f5ea Makefile: fix "allow CONFIG_LDDIR=lib64 configuration"
I forgot the commas.
2013-02-04 17:10:47 +01:00
grischka 82bcbd027f portability: fix void* <-> target address conversion confusion
- #define addr_t as ElfW(Addr)
- replace uplong by addr_t
- #define TCC_HAS_RUNTIME_PLTGOT and use it
2013-02-04 16:24:59 +01:00
grischka 3186455599 Makefile: allow CONFIG_LDDIR=lib64 configuration 2013-02-04 16:24:58 +01:00
grischka 4c2941d248 win32: wincrt1.c: include stdlib.h for exit() 2013-02-04 16:24:57 +01:00
grischka 263dc93cfa c67: remove global #define's for TRUE/FALSE/BOOL
Also use uppercase TRUE/FALSE instead of true/false
2013-02-04 16:24:56 +01:00
Thomas Preud'homme f715207249 arm-gen.c: fix var initialization in gfunc_call
Fix initialization of args_size before doing register allocation.
When adding hardfloat calling convention the initialization stopped
being performed when !defined (TCC_ARM_EABI).
2013-02-04 11:01:58 +01:00
Daniel Glöckner 61a4fd1d6e arm: force rounding towards zero on cast to integer with VFP
Cast to integer should not be affected by the current rounding mode
as set by fesetround.
2013-02-04 09:17:01 +01:00
Daniel Glöckner f7f6025bd1 arm: fix conversion from float/double to signed integer with VFP
The signed flag was not encoded in the instruction.
2013-02-03 23:47:52 +01:00
Daniel Glöckner 506193724f arm: fix conversion from integer to float/double with VFP
The source register was not encoded in the instruction.
2013-02-03 17:51:33 +01:00
Thomas Preud'homme 6f4983af5b Revert "Add predictability in CType initialization."
This reverts commit 93785149ed.
2013-01-31 13:43:04 +01:00
Thomas Preud'homme ae33c30b49 Revert "Don't call elf_hash on NULL value"
This reverts commit 505329b5b3.
2013-01-31 13:43:04 +01:00
grischka 2f6b8469cc safety: replace occurrences of strcpy by pstrcpy 2013-01-31 13:23:19 +01:00
Thomas Preud'homme 370547a550 Revert "Check whether structure fields have a type"
This reverts commit 981eb84d8a.
2013-01-31 13:02:04 +01:00
Thomas Preud'homme 981eb84d8a Check whether structure fields have a type 2013-01-31 12:32:31 +01:00
Domingo Alvarez Duarte 505329b5b3 Don't call elf_hash on NULL value
Make sur elf_hash is never invoked with a NULL value.

Signed-off-by: Thomas Preud'homme <robotux@celest.fr>
2013-01-31 12:07:20 +01:00
Domingo Alvarez Duarte 93785149ed Add predictability in CType initialization.
Initialize the ref field to 0 when manipulating a CType.

Signed-off-by: Thomas Preud'homme <robotux@celest.fr>
2013-01-31 12:04:10 +01:00
Thomas Preud'homme 1b1e7ee1fd Fix cross-compilation out-of-tree build
Add tcc.c as a prerequesite of the %-tcc$(EXESUF) target and compile $<
instead of tcc.c to make sure tcc.c is search in directories specified
by VPATH.
2013-01-30 19:39:29 +01:00
grischka 913cd6270b Changelog: cleanup 2013-01-30 18:50:02 +01:00
grischka 828ccde9fc arm: define TCC_ARM_VERSION for cross compiler 2013-01-30 18:39:36 +01:00
grischka b7e75ccdb0 tccpe: no debug, no stabs 2013-01-30 18:39:26 +01:00
grischka 17cf0dcf70 configure: use relative paths for in-tree build
Also
- move CPPFLAGS to Makefile
- Use top_srcdir in lib/Makefile
2013-01-30 18:39:09 +01:00
Thomas Preud'homme 6ccee6edb3 Add my copyright for changes in arm-gen.c 2013-01-30 17:34:19 +01:00
Thomas Preud'homme 5fa135f9eb Changelog update 2013-01-30 17:13:40 +01:00
Thomas Preud'homme 01e1eecdbe Update Changelog 2013-01-30 17:07:18 +01:00
Thomas Preud'homme 52947e5844 Favor arm hardfloat over arm softfloat.
Favor ARM hardfloat over ARM softfloat calling convention. In
particular, this solve the problem of the raspbian distribution where
the softfloat ld.so pathname (lib/ld-linux.so.3) is actually a symlink
to the hardfloat ld.so pathname (/lib/arm-linux-gnueabihf/ld-2.13.so).
2013-01-29 18:15:23 +01:00
Thomas Preud'homme bcac413c30 Fix overflow detection in ARM relocation
Fix overflow detection for R_ARM_CALL, R_ARM_PC24, R_ARM_JUMP24 and
R_ARM_PLT32 relocations on ARM. 26 bits means 25 bits for positive and
negative offsets !
2013-01-28 19:13:25 +01:00
Thomas Preud'homme 0f81512d7d Fix stack alignment on 8 bytes at function call
Ensure stack pointer is correctly adjusted in prolog to be aligned on 8
bytes after the change of frame linking.
2013-01-27 01:08:01 +01:00
Thomas Preud'homme f3e5649150 Don't do builtin_frame_address test with ARM gcc
gcc fails the builtin_frame_address test on ARM so we disable it. As a
consequence, the diff between gcc and tcc's output is unecessarily
bigger. Given the big size of the diff currently, this doesn't make a
big difference but may allow to detect a regression in tcc's
implementation of builtin_frame_address.
2013-01-26 20:31:14 +01:00
Thomas Preud'homme f63c750942 Organize frames in a real linked list on ARM
Change the linking of the frames on ARM. Instead of having fp points 12
bytes above where the old fp is stored, let fp points where the old fp
is stored. That is, we switch from:

|   .    |
|   .    |
|   .    |
|        |
| params | <-- fp
 --------
| oldlr  |
 --------
| oldip  |
 --------
| oldfp  |
 --------

to:

|   .    |
|   .    |
|   .    |
|        |
| params |
 --------
| oldlr  |
 --------
| oldip  |
 --------
| oldfp  | <-- fp
 --------
2013-01-26 20:09:04 +01:00
Thomas Preud'homme de35a3389f Use gcc to generate tcctest.gcc 2013-01-25 20:14:10 +01:00
Thomas Preud'homme f8cde52984 Link STT_GNU_IFUNC into STT_FUNC in executable.
Indirect functions shall have STT_FUNC type in executable dynsym
section. Indeed, a dlsym call following a lazy resolution would pick the
symbol value from the executable dynsym entry. This would contain the
address of the function wanted by the caller of dlsym instead of the
address of the function that would return that address.
2013-01-25 20:06:51 +01:00
grischka b89793d10a win32: _mingw.h: do not undef NULL
Not wise if stddef.h was already included. This is related to commit

    3aa26a794e

Instead hack stddef.h to have identical definition and thus
avoid the issue mentionned there.
2013-01-24 19:49:58 +01:00
Thomas Preud'homme 6b6eea60f3 Fix [f]getc return value usage in 40_stdio test
Store [f]getc return value into an int instead of char, as per
prototype. This fix an issue when char is unsigned (as is on arm for
both tcc and gcc).
2013-01-24 10:55:18 +01:00
grischka c5892fe4f5 Revert "Optimize vswap()"
This reverts commit 63193d1794.

Had some problems (_STATIC_ASSERT) and was too ugly anyway.
For retry, I'd suggest to implement a general function
    static inline void memswap (void *p1, void* p2, size_t n);
and then use that.  If you do so, please keep the original code
as comment.
2013-01-14 18:41:37 +01:00
grischka 2daf8b96a8 Revert mistake in "win32: malloc.h: fix win32 ... _STATIC_ASSERT"
from commit fc574f1498.

The files from include are copied to win32/include with make
install or build-tcc.bat.
2013-01-14 18:41:36 +01:00
Thomas Preud'homme f7b417723e Fix out-of-tree build with relative path to root
Fix path of Makefile symlinks in a out-of-tree build where the root
directory of the source is given as a relative path.
2013-01-14 18:18:27 +01:00
Thomas Preud'homme a4e630c7d9 Install libtcc.h when invoking make install
This fix commit e79281f58e
2013-01-14 18:16:17 +01:00
Thomas Preud'homme 8c56b0cf90 Revert "Added what I call virtual io to tinycc this way we can make a monolitic executable or library that contains all needed to compile programs, truly tinycc portable."
This reverts commit 59e18aee0e.
tcc is being stabilized now in order to do a new release soon.
Therefore, such a change is not appropriate now.
2013-01-14 17:34:07 +01:00
Thomas Preud'homme 60a3ff5f2c Revert "pe: fix tcc not linking to user32 and gdi32"
This reverts commit 943574aba5.
The empty string in "libs" was intended behavior, as can be seen from
the "if (0 == *p)" below.
2013-01-14 17:21:06 +01:00
Thomas Preud'homme 5e7954b408 Stop setting -Wno-unused-result switch in Makefile
This commit revert commit 061b5799cc and
subsequent commits to detect whether -Wno-unused-result is supported or
not by the compiler used to compile tcc. No warning about unused results
is issued in a normal build and thus this switch is only needed if
calling make with extra switches in CFLAGS or CPPFLAGS. It should thus
be added with the extra switches when calling make and not in the
Makefile.
2013-01-13 23:38:33 +01:00
Thomas Preud'homme ea583f7b8a Fix C99ism in vswap()
Declare vtopl in vswap at the beginning of the function before any
assignments. Doing otherwise means C99 is assumed when compiling.
2013-01-13 23:38:33 +01:00
mingodad 59e18aee0e Added what I call virtual io to tinycc this way we can make a monolitic executable or library that contains all needed to compile programs, truly tinycc portable.
Tested under linux exec the "mk-it" shell script and you'll end up with a portable tinycc executable that doesn't depend on anything else.
2013-01-11 00:04:38 +00:00
grischka 0a8c7d143e Fix "Optimize cstr_reset() to only reset string to empty"
This fixes commit 8eb92e6052

Remove memory leak.
2013-01-06 17:21:33 +01:00
grischka 2358b378b3 tccpp: alternative fix for #include_next infinite loop bug
This replaces commit 3d409b0889

- revert old fix in libtcc.c
- #include_next: look up the file in the include stack to see
  if it is already included.
Also:
- streamline include code
- remove 'type' from struct CachedInclude (obsolete because we check
  full filename anyway)
- remove inc_type & inc_filename from struct Bufferedfile (obsolete)
- fix bug with TOK_FLAG_ENDIF not being reset
- unrelated: get rid of an 'variable potentially uninitialized' warning
2013-01-06 17:20:44 +01:00
Thomas Preud'homme e92dbe4686 Stop returning 0 in cmp_comparison_test
cmp_comparison_test has no return value and should thus not return 0.
2013-01-06 12:26:53 +01:00
Thomas Preud'homme eb028a8f42 Honor CC when testing for -Wno-unused-result
The compiler used for compiling tcc is the one referenced in the
CC variable. As such, the check for -Wno-unused-result presence should
be done on CC.
2013-01-06 12:22:56 +01:00
Roy fc574f1498 win32: malloc.h: fix win32 tcc-tcc complication by correcting _STATIC_ASSERT, ideas from mingw-w64 changeset 4293
stdarg.h, stddef.h: _mingw.h needs them
2012-12-31 08:59:50 +08:00
Kirill Smelkov 63193d1794 Optimize vswap()
vswap() is called often enough and shows in profile and it was easy to
hand optimize swapping vtop[-1] and vtop[0] - instead of large (28 bytes
on i386) tmp variable and two memory to memory copies, let's swap areas
by longs through registers with streamlined assembly.

For

    $ ./tcc -B. -bench -DONE_SOURCE -DCONFIG_MULTIARCHDIR=\"i386-linux-gnu\" -c tcc.c

before:

 # Overhead      Command        Shared Object                                          Symbol
 # ........  ...........  ...................  ..............................................
 #
     15.19%          tcc  tcc                  [.] next_nomacro1
      5.19%          tcc  libc-2.13.so         [.] _int_malloc
      4.57%          tcc  tcc                  [.] next
      3.36%          tcc  tcc                  [.] tok_str_add2
      3.03%          tcc  tcc                  [.] macro_subst_tok
      2.93%          tcc  tcc                  [.] macro_subst
      2.53%          tcc  tcc                  [.] next_nomacro_spc
      2.49%          tcc  tcc                  [.] vswap
      2.36%          tcc  libc-2.13.so         [.] _int_free

       │    ST_FUNC void vswap(void)
       │    {
  1,96 │      push   %edi
  2,65 │      push   %esi
  1,08 │      sub    $0x20,%esp
       │        SValue tmp;
       │
       │        /* cannot let cpu flags if other instruction are generated. Also
       │           avoid leaving VT_JMP anywhere except on the top of the stack
       │           because it would complicate the code generator. */
       │        if (vtop >= vstack) {
  0,98 │      mov    0x8078cac,%eax
       │      cmp    $0x8078d3c,%eax
  1,18 │   ┌──jb     24
       │   │        int v = vtop->r & VT_VALMASK;
  1,08 │   │  mov    0x8(%eax),%edx
  0,78 │   │  and    $0x3f,%edx
       │   │        if (v == VT_CMP || (v & ~1) == VT_JMP)
  0,78 │   │  cmp    $0x33,%edx
  0,69 │   │↓ je     54
  0,59 │   │  and    $0xfffffffe,%edx
  0,49 │   │  cmp    $0x34,%edx
  0,29 │   │↓ je     54
       │   │            gv(RC_INT);
       │   │    }
       │   │    tmp = vtop[0];
  1,08 │24:└─→lea    0x4(%esp),%edi
  0,39 │      mov    $0x7,%ecx
       │      mov    %eax,%esi
 14,41 │      rep    movsl %ds:(%esi),%es:(%edi)
       │        vtop[0] = vtop[-1];
  9,51 │      lea    -0x1c(%eax),%esi
  1,96 │      mov    $0x7,%cl
       │      mov    %eax,%edi
 17,06 │      rep    movsl %ds:(%esi),%es:(%edi)
       │        vtop[-1] = tmp;
 10,20 │      mov    0x8078cac,%edi
  2,35 │      sub    $0x1c,%edi
  0,78 │      lea    0x4(%esp),%esi
       │      mov    $0x7,%cl
 15,20 │      rep    movsl %ds:(%esi),%es:(%edi)
       │    }
  9,90 │      add    $0x20,%esp
  2,25 │      pop    %esi
  1,67 │      pop    %edi
  0,69 │      ret

after:

 # Overhead      Command        Shared Object                                          Symbol
 # ........  ...........  ...................  ..............................................
 #
     15.27%          tcc  tcc                  [.] next_nomacro1
      5.08%          tcc  libc-2.13.so         [.] _int_malloc
      4.57%          tcc  tcc                  [.] next
      3.17%          tcc  tcc                  [.] tok_str_add2
      3.12%          tcc  tcc                  [.] macro_subst
      2.99%          tcc  tcc                  [.] macro_subst_tok
      2.43%          tcc  tcc                  [.] next_nomacro_spc
      2.32%          tcc  libc-2.13.so         [.] _int_free

      . . .

      0.71%          tcc  tcc                  [.] vswap

       │    ST_FUNC void vswap(void)
       │    {
  7,22 │      push   %eax
       │        /* cannot let cpu flags if other instruction are generated. Also
       │           avoid leaving VT_JMP anywhere except on the top of the stack
       │           because it would complicate the code generator. */
       │        if (vtop >= vstack) {
 11,34 │      mov    0x8078cac,%eax
  2,75 │      cmp    $0x8078d3c,%eax
  0,34 │   ┌──jb     20
       │   │        int v = vtop->r & VT_VALMASK;
  0,34 │   │  mov    0x8(%eax),%edx
  8,93 │   │  and    $0x3f,%edx
       │   │        if (v == VT_CMP || (v & ~1) == VT_JMP)
  2,06 │   │  cmp    $0x33,%edx
  2,41 │   │↓ je     74
  2,41 │   │  and    $0xfffffffe,%edx
  0,34 │   │  cmp    $0x34,%edx
  2,41 │   │↓ je     74
       │   │        vtopl[-1*VSIZEL + i] = tmpl;    \
       │   │      } do {} while (0)
       │   │
       │   │    VSWAPL(15); VSWAPL(14); VSWAPL(13); VSWAPL(12);
       │   │    VSWAPL(11); VSWAPL(10); VSWAPL( 9); VSWAPL( 8);
       │   │    VSWAPL( 7); VSWAPL( 6); VSWAPL( 5); VSWAPL( 4);
  2,06 │20:└─→mov    0x18(%eax),%edx
  1,37 │      mov    -0x4(%eax),%ecx
  2,06 │      mov    %ecx,0x18(%eax)
  1,37 │      mov    %edx,-0x4(%eax)
  2,06 │      mov    0x14(%eax),%edx
  2,06 │      mov    -0x8(%eax),%ecx
  2,41 │      mov    %ecx,0x14(%eax)
  3,09 │      mov    %edx,-0x8(%eax)
  3,09 │      mov    0x10(%eax),%edx
  1,72 │      mov    -0xc(%eax),%ecx
  2,75 │      mov    %ecx,0x10(%eax)
  1,72 │      mov    %edx,-0xc(%eax)
       │        VSWAPL( 3); VSWAPL( 2); VSWAPL( 1); VSWAPL( 0);
  2,41 │      mov    0xc(%eax),%edx
  2,41 │      mov    -0x10(%eax),%ecx
  2,41 │      mov    %ecx,0xc(%eax)
  0,69 │      mov    %edx,-0x10(%eax)
  1,72 │      mov    0x8(%eax),%edx
  0,69 │      mov    -0x14(%eax),%ecx
  1,03 │      mov    %ecx,0x8(%eax)
  1,37 │      mov    %edx,-0x14(%eax)
  1,37 │      mov    0x4(%eax),%edx
  0,69 │      mov    -0x18(%eax),%ecx
  3,09 │      mov    %ecx,0x4(%eax)
  2,06 │      mov    %edx,-0x18(%eax)
  1,37 │      mov    (%eax),%edx
  2,41 │      mov    -0x1c(%eax),%ecx
  1,37 │      mov    %ecx,(%eax)
  4,12 │      mov    %edx,-0x1c(%eax)
       │        }
       │
       │    #   undef VSWAPL
       │    #   undef VSIZEL
       │    }
  1,03 │      pop    %eax
  3,44 │      ret

Overal speedup:

    # best of 5 runs
    before: 8268 idents, 47203 lines, 1526763 bytes, 0.148 s, 319217 lines/s, 10.3 MB/s
    after:  8273 idents, 47231 lines, 1527685 bytes, 0.146 s, 324092 lines/s, 10.5 MB/s

Static ASSERT macro taken from CCAN's[1] build_assert[2] which is in
public domain.

[1] http://ccodearchive.net/
[2] http://git.ozlabs.org/?p=ccan;a=blob;f=ccan/build_assert/build_assert.h;h=24e59c44cd930173178ac9b6e101b0af64a879e9;hb=HEAD
2012-12-21 20:46:26 +04:00
Kirill Smelkov 8eb92e6052 Optimize cstr_reset() to only reset string to empty, not call free() and later malloc()
A CString could be reset to empty just setting its .size to 0.

If memory was already allocated, that would be remembered in
.data_allocated and .size_allocated and on consequent string
manipulations that memory will be used without immediate need to call
malloc().

For

    $ ./tcc -B. -bench -DONE_SOURCE -DCONFIG_MULTIARCHDIR=\"i386-linux-gnu\" -c tcc.c

after the patch malloc/free are called less often:

(tcc is run in loop; perf record -a sleep 10 && perf report)
before:

 # Overhead      Command       Shared Object                                      Symbol
 # ........  ...........  ..................  ..........................................
 #
     13.89%          tcc  tcc                 [.] next_nomacro1
      4.73%          tcc  libc-2.13.so        [.] _int_malloc
      4.39%          tcc  tcc                 [.] next
      2.94%          tcc  tcc                 [.] tok_str_add2
      2.78%          tcc  tcc                 [.] macro_subst_tok
      2.75%          tcc  libc-2.13.so        [.] free
      2.74%          tcc  tcc                 [.] macro_subst
      2.63%          tcc  libc-2.13.so        [.] _int_free
      2.28%          tcc  tcc                 [.] vswap
      2.24%          tcc  tcc                 [.] next_nomacro_spc
      2.06%          tcc  libc-2.13.so        [.] realloc
      2.00%          tcc  libc-2.13.so        [.] malloc
      1.99%          tcc  tcc                 [.] unary
      1.85%          tcc  libc-2.13.so        [.] __i686.get_pc_thunk.bx
      1.76%  kworker/0:1  [kernel.kallsyms]   [k] delay_tsc
      1.70%          tcc  tcc                 [.] next_nomacro
      1.62%          tcc  tcc                 [.] preprocess
      1.41%          tcc  libc-2.13.so        [.] __memcmp_ssse3
      1.38%          tcc  [kernel.kallsyms]   [k] memset
      1.10%          tcc  tcc                 [.] g
      1.06%          tcc  tcc                 [.] parse_btype
      1.05%          tcc  tcc                 [.] sym_push2
      1.04%          tcc  libc-2.13.so        [.] _int_realloc
      1.00%          tcc  libc-2.13.so        [.] malloc_consolidate

after:

 # Overhead      Command       Shared Object                                          Symbol
 # ........  ...........  ..................  ..............................................
 #
     15.26%          tcc  tcc                 [.] next_nomacro1
      5.07%          tcc  libc-2.13.so        [.] _int_malloc
      4.62%          tcc  tcc                 [.] next
      3.22%          tcc  tcc                 [.] tok_str_add2
      3.03%          tcc  tcc                 [.] macro_subst_tok
      3.02%          tcc  tcc                 [.] macro_subst
      2.59%          tcc  tcc                 [.] next_nomacro_spc
      2.44%          tcc  tcc                 [.] vswap
      2.39%          tcc  libc-2.13.so        [.] _int_free
      2.28%          tcc  libc-2.13.so        [.] free
      2.22%          tcc  tcc                 [.] unary
      2.07%          tcc  libc-2.13.so        [.] realloc
      1.97%          tcc  libc-2.13.so        [.] malloc
      1.70%          tcc  tcc                 [.] preprocess
      1.69%          tcc  libc-2.13.so        [.] __i686.get_pc_thunk.bx
      1.68%          tcc  tcc                 [.] next_nomacro
      1.59%          tcc  [kernel.kallsyms]   [k] memset
      1.55%          tcc  libc-2.13.so        [.] __memcmp_ssse3
      1.22%          tcc  tcc                 [.] parse_comment
      1.11%          tcc  tcc                 [.] g
      1.11%          tcc  tcc                 [.] sym_push2
      1.10%          tcc  tcc                 [.] parse_btype
      1.10%          tcc  libc-2.13.so        [.] _int_realloc
      1.06%          tcc  tcc                 [.] vsetc
      0.98%          tcc  libc-2.13.so        [.] malloc_consolidate

and this gains small speedup for tcc:

    # best of 5 runs
    before: 8268 idents, 47191 lines, 1526670 bytes, 0.153 s, 307997 lines/s, 10.0 MB/s
    after:  8268 idents, 47203 lines, 1526763 bytes, 0.148 s, 319217 lines/s, 10.3 MB/s
2012-12-21 20:46:26 +04:00
Akim Demaille e79281f58e build: fix out-of-tree install
Makefile (install): Fix installation of headers.
Do not try to install twice libtcc.h, once should be enough.
2012-12-21 14:23:28 +01:00
Akim Demaille 7667a8887a build: fix out-of-tree build
* Makefile (TCC-VERSION): Use top_srcdir.
2012-12-21 14:17:23 +01:00
Akim Demaille 8adfb4a419 build: simplify the makefiles
* Makefile: use "else if" to improve readability.
2012-12-21 14:17:16 +01:00
Akim Demaille 017bbbfee1 configure: support absolete out-of-tree builds
configure: handle the case of absolute paths.
Reported by grishka.
2012-12-21 13:57:22 +01:00
Akim Demaille d7264e0218 configure: style changes
* configure: use more here-documents.
2012-12-21 13:49:15 +01:00
Akim Demaille ba49862de6 configure: prefer here-documents
* configure: use here-documents to improve readability and
reduce the clutter.
2012-12-21 13:47:00 +01:00
Akim Demaille 9c9ca2032b configure: style changes
* configure (case $targetos): Improve readibility.
(case $cpu): New, to improve readability compare to if + test.
2012-12-21 13:45:22 +01:00
grischka 5ebc6a964d Makefile: revamp "tar" target
- Creates release tarball from *current* git branch
- Includes tcc-doc.html
- converts important windows files files to CRLF
  (requirement for the cmd.exe batch processor, convenience for
   reading the txt in notepad)
2012-12-20 21:29:57 +01:00
grischka b174399340 win32: build-tcc.bat: get rid of hardcoded VERSION string
Also:
 - put libtcc.def into libtcc dir
 - remove ar references
 - remove libtcc_test from build
2012-12-20 21:20:54 +01:00
Akim Demaille 3f09b90d21 build: fix VPATH builds
* configure (fn_dirname): New.
Use it to ensure the creation of proper symlinks to Makefiles.
(config.mak): Define top_builddir and top_srcdir.
(CPPFLAGS): Be sure to find the headers.
* Makefile, lib/Makefile, tests/Makefile, tests2/Makefile: Adjust
to set VPATH properly.
Fix confusion between top_builddir and top_srcdir.
2012-12-18 10:06:20 +01:00
Roy d815896d4c bcheck: there is no unistd.h in win32. 2012-12-10 09:51:49 +08:00
Kirill Smelkov a55ecf6d2c Repair bounds-checking more, this time `tcc -b -run tcc.c -run tcc.c -run tcctest.c` works
Hello up there. On the list Grischka made a point that we can't recommend using
-b as long as tcc -b tcc.c doesn't produce anything useful. Now it does, so
please don't treat -b mode as second class citizen anymore.

Thanks,
Kirill

* bcheck2:
  tests: Add tests for compile/run tcc.c with `tcc -b` then compile tcc.c again, then run tcctest.c
  lib/bcheck: Fix code typo in __bound_delete_region()
  lib/bcheck: Don't assume heap goes right after bss
  Make tcc work after self-compiling with bounds-check enabled
2012-12-09 19:51:20 +04:00
Kirill Smelkov 031ff872be tests: Add tests for compile/run tcc.c with `tcc -b` then compile tcc.c again, then run tcctest.c
Just like with test[123] add their test[123]b variants. After previous 3
patchs all test pass here on Debian GNU/Linux on i385 with gcc-4.7 with
or without memory randomization turned on.
2012-12-09 19:43:40 +04:00
Kirill Smelkov dbeb4faf21 lib/bcheck: Fix code typo in __bound_delete_region()
We were calling get_page() with t2 index which is not correct, since
get_page() operate on t1 indices. The bug is here from day-1, from
60f781c4 (first version of bounds checker) and show as a crash in
__bound_delete_region() at program exit:

    $ ./tcc   -B. -DTCC_TARGET_I386 -DCONFIG_MULTIARCHDIR=\"i386-linux-gnu\" -b -run -DONE_SOURCE \
      ./tcc.c -B. -DTCC_TARGET_I386 -DCONFIG_MULTIARCHDIR=\"i386-linux-gnu\"    -run -DONE_SOURCE \
      ./tcc.c -B. -run tests/tcctest.c

    (lot's of correct output from tcctest)
    Runtime error: dereferencing invalid pointer
    at 0xa7c21cc4 __bound_delete_region()
    by (nil) ???
    Segmentation fault

The fix is simple - last page should be get through t1_end, like it is
done in __bound_new_region().

After this patch, tcc is being able to compile itself with -b, then
compile itself again and run tcctest with correct output. Tests follow.
2012-12-09 19:33:47 +04:00
Kirill Smelkov efd9d92b7c lib/bcheck: Don't assume heap goes right after bss
At startup __bound_init() wants to mark malloc zone as invalid memory,
so that any access to memory on heap, not allocated through malloc be
invalid. Other pages are initialized as empty regions, access to which
is not treated as invalid by bounds-checking.

The problem is code incorrectly assumed that heap goes right after bss,
and that is not correct for two cases:

    1) if we are running from `tcc -b -run`, program text data and bss
       will be already in malloced memory, possibly in mmaped region
       insead of heap, and marking memory as invalid from _end
       will not cover heap and probably wrongly mark correct regions.

    2) if address space randomization is turned on, again heap does not
       start from _end, and we'll mark as invalid something else instead
       of malloc area.

For example with the following diagnostic patch ...

    diff --git a/tcc.c b/tcc.c
    index 5dd5725..31c46e8 100644
    --- a/tcc.c
    +++ b/tcc.c
    @@ -479,6 +479,8 @@ static int parse_args(TCCState *s, int argc, char **argv)
         return optind;
     }

    +extern int _etext, _edata, _end;
    +
     int main(int argc, char **argv)
     {
         int i;
    @@ -487,6 +489,18 @@ int main(int argc, char **argv)
         int64_t start_time = 0;
         const char *default_file = NULL;

    +    void *brk;
    +
    +    brk = sbrk(0);
    +
    +    fprintf(stderr, "\n>>> TCC\n\n");
    +    fprintf(stderr, "etext:\t%10p\n",  &_etext);
    +    fprintf(stderr, "edata:\t%10p\n",  &_edata);
    +    fprintf(stderr, "end:\t%10p\n",    &_end);
    +    fprintf(stderr, "brk:\t%10p\n",    brk);
    +    fprintf(stderr, "stack:\t%10p\n",  &brk);
    +
    +    fprintf(stderr, "&errno: %p\n", &errno);
         s = tcc_new();

         output_type = TCC_OUTPUT_EXE;

    diff --git a/tccrun.c b/tccrun.c
    index 531f46a..25ed30a 100644
    --- a/tccrun.c
    +++ b/tccrun.c
    @@ -91,6 +91,8 @@ LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv)
         int (*prog_main)(int, char **);
         int ret;

    +    fprintf(stderr, "\n\ntcc_run() ...\n\n");
    +
         if (tcc_relocate(s1, TCC_RELOCATE_AUTO) < 0)
             return -1;

    diff --git a/lib/bcheck.c b/lib/bcheck.c
    index ea5b233..8b26a5f 100644
    --- a/lib/bcheck.c
    +++ b/lib/bcheck.c
    @@ -296,6 +326,8 @@ static void mark_invalid(unsigned long addr, unsigned long size)
         start = addr;
         end = addr + size;

    +    fprintf(stderr, "mark_invalid  %10p - %10p\n", (void *)addr, (void *)end);
    +
         t2_start = (start + BOUND_T3_SIZE - 1) >> BOUND_T3_BITS;
         if (end != 0)
             t2_end = end >> BOUND_T3_BITS;

... Look how memory is laid out for `tcc -b -run ...`:

    $ ./tcc -B. -b -DTCC_TARGET_I386 -DCONFIG_MULTIARCHDIR=\"i386-linux-gnu\"  -run   \
        -DONE_SOURCE ./tcc.c -B. -c x.c

    >>> TCC

    etext:   0x8065477
    edata:   0x8070220
    end:     0x807a95c
    brk:     0x807b000
    stack:  0xaffff0f0
    &errno: 0xa7e25688

    tcc_run() ...

    mark_invalid  0xfff80000 -      (nil)
    mark_invalid  0xa7c31d98 - 0xafc31d98

    >>> TCC

    etext:  0xa7c22767
    edata:  0xa7c2759c
    end:    0xa7c31d98
    brk:     0x8211000
    stack:  0xafffeff0
    &errno: 0xa7e25688
    Runtime error: dereferencing invalid pointer
    ./tccpp.c:1953: at 0xa7beebdf parse_number() (included from ./libtcc.c, ./tcc.c)
    ./tccpp.c:3003: by 0xa7bf0708 next() (included from ./libtcc.c, ./tcc.c)
    ./tccgen.c:4465: by 0xa7bfe348 block() (included from ./libtcc.c, ./tcc.c)
    ./tccgen.c:4440: by 0xa7bfe212 block() (included from ./libtcc.c, ./tcc.c)
    ./tccgen.c:5529: by 0xa7c01929 gen_function() (included from ./libtcc.c, ./tcc.c)
    ./tccgen.c:5767: by 0xa7c02602 decl0() (included from ./libtcc.c, ./tcc.c)

The second mark_invalid goes right after in-memory-compiled program's
_end, and oops, that's not where malloc zone is (starts from brk), and oops
again, mark_invalid covers e.g. errno. Then compiled tcc is crasshing by
bcheck on errno access:

    1776 static void parse_number(const char *p)
    1777 {
    1778     int b, t, shift, frac_bits, s, exp_val, ch;
         ...
    1951             *q = '\0';
    1952             t = toup(ch);
    1953             errno = 0;

The solution here is to use sbrk(0) as approximation for the program
break start instead of &_end:

    - if we are a separately compiled program, __bound_init() runs early,
      and sbrk(0) should be equal or very near to start_brk (in case other
      constructors malloc something), or

    - if we are running from under `tcc -b -run`, sbrk(0) will return
      start of heap portion which is under this program control, and not
      mark as invalid earlier allocated memory.

With this patch `tcc -b -run tcc.c ...` succeeds compiling above
small-test program (diagnostic patch is still applied too):

    $ ./tcc -B. -b -DTCC_TARGET_I386 -DCONFIG_MULTIARCHDIR=\"i386-linux-gnu\"  -run   \
        -DONE_SOURCE ./tcc.c -B. -c x.c

    >>> TCC

    etext:   0x8065477
    edata:   0x8070220
    end:     0x807a95c
    brk:     0x807b000
    stack:  0xaffff0f0
    &errno: 0xa7e25688

    tcc_run() ...

    mark_invalid  0xfff80000 -      (nil)
    mark_invalid   0x8211000 - 0x10211000

    >>> TCC

    etext:  0xa7c22777
    edata:  0xa7c275ac
    end:    0xa7c31da8
    brk:     0x8211000
    stack:  0xafffeff0
    &errno: 0xa7e25688

    (completes ok)

but running `tcc -b -run tcc.c -run tests/tcctest.c` sigsegv's - that's
the plot for the next patch.
2012-12-09 19:05:36 +04:00
Kirill Smelkov 43a11a7ed1 Make tcc work after self-compiling with bounds-check enabled
For vstack Fabrice used the trick to initialize vtop to &vstack[-1], so
that on first push, vtop becomes &vstack[0] and a value is also stored
there - everything works.

Except that when tcc is compiled with bounds-checking enabled, vstack - 1
returns INVALID_POINTER and oops...

Let's workaround it with artificial 1 vstack slot which will not be
used, but only serve as an indicator that pointing to &vstack[-1] is ok.

Now, tcc, after being self-compiled with -b works:

    $ ./tcc -B. -o tccb  -DONE_SOURCE -DCONFIG_MULTIARCHDIR=\"i386-linux-gnu\" tcc.c  -ldl
    $ cd tests
    $ ../tcc -B.. -run tcctest.c >1
    $ ../tccb -B.. -run tcctest.c >2
    $ diff -u 1 2

and note, tcc's compilation speed is not affected:

    $ ./tcc -B. -bench -DONE_SOURCE -DCONFIG_MULTIARCHDIR=\"i386-linux-gnu\" -c tcc.c

    before: 8270 idents, 47221 lines, 1527730 bytes, 0.152 s, 309800 lines/s, 10.0 MB/s
    after:  8271 idents, 47221 lines, 1527733 bytes, 0.152 s, 310107 lines/s, 10.0 MB/s

But note, that `tcc -b -run tcc` is still broken - for example it crashes
on
    $ cat x.c
    double get100 () { return 100.0; }

    $ ./tcc -B. -b -DTCC_TARGET_I386 -DCONFIG_MULTIARCHDIR=\"i386-linux-gnu\"  -run   \
        -DONE_SOURCE ./tcc.c -B. -c x.c
    Runtime error: dereferencing invalid pointer
    ./tccpp.c:1953: at 0xa7beebdf parse_number() (included from ./libtcc.c, ./tcc.c)
    ./tccpp.c:3003: by 0xa7bf0708 next() (included from ./libtcc.c, ./tcc.c)
    ./tccgen.c:4465: by 0xa7bfe348 block() (included from ./libtcc.c, ./tcc.c)
    ./tccgen.c:4440: by 0xa7bfe212 block() (included from ./libtcc.c, ./tcc.c)
    ./tccgen.c:5529: by 0xa7c01929 gen_function() (included from ./libtcc.c, ./tcc.c)
    ./tccgen.c:5767: by 0xa7c02602 decl0() (included from ./libtcc.c, ./tcc.c)

that's because lib/bcheck.c runtime needs more fixes -- see next
patches.
2012-12-09 18:06:09 +04:00
Thomas Preud'homme c4a18f47a2 Detect ARM CPU version in configure
Instead of guessing the ARM CPU version to compile for from tcc.h, we
now detect it in configure and output the value in config.h
2012-12-04 11:17:51 +01:00
Thomas Preud'homme 05b02a5581 arm-gen.c: Invalid operator test always false
Invalid operator test is always false in gen_opf for arm (found with
cppcheck). This patch fixes the issue.
2012-11-28 22:26:39 +01:00
Thomas Preud'homme 8d90205fd9 Fix OABI calling convention
OABI calling convention was broken since the addition of the hardfloat
calling convention in commit 7f6095bfec.
This commit fixes the breakage.
2012-11-28 22:26:39 +01:00
Kirill Smelkov 168aed4984 tests: btest should only run on targets supporting bcheck
After 40a54c43 (Repair bounds-checking runtime), and in particular
5d648485 (Now btest pass!) `make test` was broken on ARCH != i386,
because I've changed btest to unconditionally run on all arches.

But bounds-checking itsels is only supported on i386 and oops...

Fix it.

Reported-by: Thomas Preud'homme <robotux@celest.fr>
2012-11-24 12:54:03 +04:00
Kirill Smelkov 4744269494 Update .gitignore
The following files were not ignored (produced by build on i386 with
--enable-cross):

    arm-eabi-tcc
    arm-fpa-ld-tcc
    arm-fpa-tcc
    arm-vfp-tcc
    c67-tcc
    i386-win32-tcc
    lib/i386-win32/
    lib/x86_64-win32/
    x86_64-tcc
    x86_64-win32-tcc
2012-11-22 10:40:02 +04:00
Thomas Preud'homme 6eec931038 Only reference vfpr when available
A line in gfunc_call in arm-gen.c is referencing vfpr unconditionally.
Yet, this function is only available when TCC_ARM_VFP is set. While this
code is only triggered when TCC_ARM_VFP, it fails at compile time. This
commit fix the problem.
2012-11-21 12:21:51 +01:00
Thomas Preud'homme 15a315f4a5 Define TCC_ARM_EABI if using hardfloat ABI
TCC_ARM_EABI should be defined when compiling with hardfloat calling
convention. This commit rework the Makefile to distinguish between
calling convention and multiarch and define TCC_ARM_EABI when hardfloat
calling convention is used. The result is to first guess the calling
convention and then add the multiarch triplet if necessary.
2012-11-20 11:36:13 +01:00
Thomas Preud'homme e2212738d4 Generate PLT thumb stub only when necessary
Generate PLT thumb stub for an ARM PLT entry only when at least one
Thumb instruction branches to that entry. This is a rewrite of the
previous patch.
2012-11-17 10:01:11 +01:00
Kirill Smelkov ab24aaeca3 i386: We can change 'lea 0(%ebp),r' to 'mov %ebp,r'
Because that mov is 1 byte shorter, look:

    int *func()
    {
        return __builtin_frame_address(0);
    }

before patch:

00000000 <func>:
   0:   55                      push   %ebp
   1:   89 e5                   mov    %esp,%ebp
   3:   81 ec 00 00 00 00       sub    $0x0,%esp
   9:   8d 45 00                lea    0x0(%ebp),%eax   // <- here
   c:   e9 00 00 00 00          jmp    11 <func+0x11>
  11:   c9                      leave
  12:   c3                      ret

after patch:

00000000 <func>:
   0:   55                      push   %ebp
   1:   89 e5                   mov    %esp,%ebp
   3:   81 ec 00 00 00 00       sub    $0x0,%esp
   9:   89 e8                   mov    %ebp,%eax        // <- here
   b:   e9 00 00 00 00          jmp    10 <func+0x10>
  10:   c9                      leave
  11:   c3                      ret
2012-11-16 10:22:45 +04:00
Kirill Smelkov b2a02961b4 Add support for __builtin_frame_address(level)
Continuing d6072d37 (Add __builtin_frame_address(0)) implement
__builtin_frame_address for levels greater than zero, in order for
tinycc to be able to compile its own lib/bcheck.c after
cffb7af9 (lib/bcheck: Prevent __bound_local_new / __bound_local_delete
from being miscompiled).

I'm new to the internals, and used the most simple way to do it.
Generated code is not very good for levels >= 2, compare

                gcc                         tcc

    level=0     mov    %ebp,%eax            lea    0x0(%ebp),%eax

    level=1     mov    0x0(%ebp),%eax       mov    0x0(%ebp),%eax

    level=2     mov    0x0(%ebp),%eax       mov    0x0(%ebp),%eax
                mov    (%eax),%eax          mov    %eax,-0x10(%ebp)
                                            mov    -0x10(%ebp),%eax
                                            mov    (%eax),%eax

    level=3     mov    0x0(%ebp),%eax       mov    0x0(%ebp),%eax
                mov    (%eax),%eax          mov    (%eax),%ecx
                mov    (%eax),%eax          mov    (%ecx),%eax

But this is still an improvement and for bcheck we need level=1 for
which the code is good.

For the tests I had to force gcc use -O0 to not inline the functions.
And -fno-omit-frame-pointer just in case.

If someone knows how to improve the generated code - help is
appreciated.

Thanks,
Kirill

Cc: Michael Matz <matz@suse.de>
Cc: Shinichiro Hamaji <shinichiro.hamaji@gmail.com>
2012-11-16 10:22:14 +04:00
Milutin Jovanović e79c3533ec -Wno-unused-result now added only on gcc >= 4.4
This option does not exist in gcc 4.3 and earlier, and it breaks the build on
systems with older compilers. The makefile has been enhanced to test for the
version and adds it only if a newer compiler is detected.
2012-11-14 17:45:15 -05:00
Kirill Smelkov 40a54c4399 Repair bounds-checking runtime
On this weekend a thought came to me again that tinycc could be used for
scripting. Only its bounds-checking mode turned out to be broken, which
is a pity because bounds-checking is sometimes handy especially for
quickly written scripts.

Since tinycc is one of those small beautiful things, seldomly happening
in our times, I couldn't resist trying to fix it.

Thanks,
Kirill

* bcheck:
  Now btest pass!
  lib/bcheck: Prevent __bound_local_new / __bound_local_delete from being miscompiled
  lib/bcheck: Prevent libc_malloc/libc_free etc from being miscompiled
2012-11-14 10:50:34 +04:00
Kirill Smelkov 5d648485bd Now btest pass!
Thanks to two previous commits now btest tests pass, at least on Linux.

Signed-off-by: Kirill Smelkov <kirr@navytux.spb.ru>
2012-11-13 22:23:01 +04:00
Kirill Smelkov cffb7af9f9 lib/bcheck: Prevent __bound_local_new / __bound_local_delete from being miscompiled
On i386 and gcc-4.7 I found that __bound_local_new was miscompiled -
look:

    #ifdef __i386__
    /* return the frame pointer of the caller */
    #define GET_CALLER_FP(fp)\
    {\
        unsigned long *fp1;\
        __asm__ __volatile__ ("movl %%ebp,%0" :"=g" (fp1));\
        fp = fp1[0];\
    }
    #endif

    /* called when entering a function to add all the local regions */
    void FASTCALL __bound_local_new(void *p1)
    {
        unsigned long addr, size, fp, *p = p1;
        GET_CALLER_FP(fp);
        for(;;) {
            addr = p[0];
            if (addr == 0)
                break;
            addr += fp;
            size = p[1];
            p += 2;
            __bound_new_region((void *)addr, size);
        }
    }

    __bound_local_new:
    .LFB40:
            .cfi_startproc
            pushl   %esi
            .cfi_def_cfa_offset 8
            .cfi_offset 6, -8
            pushl   %ebx
            .cfi_def_cfa_offset 12
            .cfi_offset 3, -12
            subl    $8, %esp            // NOTE prologue does not touch %ebp
            .cfi_def_cfa_offset 20
    #APP
    # 235 "lib/bcheck.c" 1
            movl %ebp,%edx              // %ebp -> fp1
    # 0 "" 2
    #NO_APP
            movl    (%edx), %esi        // fp1[0] -> fp
            movl    (%eax), %edx
            movl    %eax, %ebx
            testl   %edx, %edx
            je      .L167
            .p2align 2,,3
    .L173:
            movl    4(%ebx), %eax
            addl    $8, %ebx
            movl    %eax, 4(%esp)
            addl    %esi, %edx
            movl    %edx, (%esp)
            call    __bound_new_region
            movl    (%ebx), %edx
            testl   %edx, %edx
            jne     .L173
    .L167:
            addl    $8, %esp
            .cfi_def_cfa_offset 12
            popl    %ebx
            .cfi_restore 3
            .cfi_def_cfa_offset 8
            popl    %esi
            .cfi_restore 6
            .cfi_def_cfa_offset 4
            ret

here GET_CALLER_FP() assumed that its using function setups it's stack
frame, i.e. first save, then set %ebp to stack frame start, and then it
has to do perform two lookups: 1) to get current stack frame through
%ebp, and 2) get caller stack frame through (%ebp).

And here is the problem: gcc decided not to setup %ebp for
__bound_local_new and in such case GET_CALLER_FP actually becomes
GET_CALLER_CALLER_FP and oops, wrong regions are registered in bcheck
tables...

The solution is to stop using hand written assembly and rely on gcc's
__builtin_frame_address(1) to get callers frame stack(*). I think for the
builtin gcc should generate correct code, independent of whether it
decides or not to omit frame pointer in using function - it knows it.

(*) judging by gcc history, __builtin_frame_address was there almost
    from the beginning - at least it is present in 1992 as seen from the
    following commit:

    http://gcc.gnu.org/git/?p=gcc.git;a=commit;h=be07f7bdbac76d87d3006c89855491504d5d6202

    so we can rely on it being supported by all versions of gcc.

In my environment the assembly of __bound_local_new changes as follows:

    diff --git a/bcheck0.s b/bcheck1.s
    index 4c02a5f..ef68918 100644
    --- a/bcheck0.s
    +++ b/bcheck1.s
    @@ -1409,20 +1409,17 @@ __bound_init:
     __bound_local_new:
     .LFB40:
            .cfi_startproc
    -       pushl   %esi
    +       pushl   %ebp                // NOTE prologue saves %ebp ...
            .cfi_def_cfa_offset 8
    -       .cfi_offset 6, -8
    +       .cfi_offset 5, -8
    +       movl    %esp, %ebp          // ... and reset it to local stack frame
    +       .cfi_def_cfa_register 5
    +       pushl   %esi
            pushl   %ebx
    -       .cfi_def_cfa_offset 12
    -       .cfi_offset 3, -12
            subl    $8, %esp
    -       .cfi_def_cfa_offset 20
    -#APP
    -# 235 "lib/bcheck.c" 1
    -       movl %ebp,%edx
    -# 0 "" 2
    -#NO_APP
    -       movl    (%edx), %esi
    +       .cfi_offset 6, -12
    +       .cfi_offset 3, -16
    +       movl    0(%ebp), %esi       // stkframe -> stkframe.parent -> fp
            movl    (%eax), %edx
            movl    %eax, %ebx
            testl   %edx, %edx
    @@ -1440,13 +1437,13 @@ __bound_local_new:
            jne     .L173
     .L167:
            addl    $8, %esp
    -       .cfi_def_cfa_offset 12
            popl    %ebx
            .cfi_restore 3
    -       .cfi_def_cfa_offset 8
            popl    %esi
            .cfi_restore 6
    -       .cfi_def_cfa_offset 4
    +       popl    %ebp
    +       .cfi_restore 5
    +       .cfi_def_cfa 4, 4
            ret
            .cfi_endproc

i.e. now it compiles correctly.

Though I do not have x86_64 to test, my guess is that
__builtin_frame_address(1) should work there too. If not - please revert
only x86_64 part of the patch. Thanks.

Cc: Michael Matz <matz@suse.de>
2012-11-13 22:17:58 +04:00
Kirill Smelkov 646b51833f lib/bcheck: Prevent libc_malloc/libc_free etc from being miscompiled
On i386 and gcc-4.7 I found that libc_malloc was miscompiled - look:

static void *libc_malloc(size_t size)
{
    void *ptr;
    restore_malloc_hooks();     // __malloc_hook = saved_malloc_hook
    ptr = malloc(size);
    install_malloc_hooks();     // saved_malloc_hook = __malloc_hook, __malloc_hook = __bound_malloc
    return ptr;
}

	.type	libc_malloc, @function
libc_malloc:
.LFB56:
	.cfi_startproc
	pushl	%edx
	.cfi_def_cfa_offset 8
	movl	%eax, (%esp)
	call	malloc
	movl	$__bound_malloc, __malloc_hook
	movl	$__bound_free, __free_hook
	movl	$__bound_realloc, __realloc_hook
	movl	$__bound_memalign, __memalign_hook
	popl	%ecx
	.cfi_def_cfa_offset 4
	ret

Here gcc inlined both restore_malloc_hooks() and install_malloc_hooks()
and decided that

    saved_malloc_hook -> __malloc_hook -> saved_malloc_hook

stores are not needed and could be ommitted. Only it did not know
__molloc_hook affects malloc()...

So add compiler barrier to both install and restore hooks functions and
be done with it - the code is now ok:

    diff --git a/bcheck0.s b/bcheck1.s
    index 5f50293..4c02a5f 100644
    --- a/bcheck0.s
    +++ b/bcheck1.s
    @@ -42,8 +42,24 @@ libc_malloc:
            .cfi_startproc
            pushl   %edx
            .cfi_def_cfa_offset 8
    +       movl    saved_malloc_hook, %edx
    +       movl    %edx, __malloc_hook
    +       movl    saved_free_hook, %edx
    +       movl    %edx, __free_hook
    +       movl    saved_realloc_hook, %edx
    +       movl    %edx, __realloc_hook
    +       movl    saved_memalign_hook, %edx
    +       movl    %edx, __memalign_hook
            movl    %eax, (%esp)
            call    malloc
    +       movl    __malloc_hook, %edx
    +       movl    %edx, saved_malloc_hook
    +       movl    __free_hook, %edx
    +       movl    %edx, saved_free_hook
    +       movl    __realloc_hook, %edx
    +       movl    %edx, saved_realloc_hook
    +       movl    __memalign_hook, %edx
    +       movl    %edx, saved_memalign_hook
            movl    $__bound_malloc, __malloc_hook
            movl    $__bound_free, __free_hook
            movl    $__bound_realloc, __realloc_hook

For barrier I use

    __asm__ __volatile__ ("": : : "memory")

which is used as compiler barrier by Linux kernel, and mentioned in gcc
docs and in wikipedia [1].

Without this patch any program compiled with tcc -b crashes in startup
because of infinite recursion in libc_malloc.

[1] http://en.wikipedia.org/wiki/Memory_ordering#Compiler_memory_barrier
2012-11-13 22:17:51 +04:00
Thomas Preud'homme 1af3bca4ea Revert "Generate PLT thumb stub only when necessary"
Revert commit 891dfcdf3f since it assumes
*all* architectures supported by tcc have GOT offsets aligned on 2. A
rework of this commit is being done since without it all PLT entries
grow by 4 bytes.
2012-11-12 23:14:21 +01:00
Thomas Preud'homme 3c986eeae3 Add armv6l to ARM supported processors
Add armv6l to the list of supported ARM architecture (as returned by
uname -m) in ./configure
2012-11-11 20:01:01 +01:00
Thomas Preud'homme 14c99236da Call to veneers in ARM mode
Since commit c6630ef92a, Call to a veneer
when the final symbol to be reached is thumb is made through a blx
instruction. This is a mistake since veneers are ARM instructions and
should thus be called with a simple bl. This commit prevent the bl ->
blx conversion when a veneer is used.
2012-11-09 10:59:06 +01:00
Thomas Preud'homme 061b5799cc Allow source fortification
Source fortification now works correctly : it compiles without warning
except unused result and the resulting tcc is working fine. Hence let's
stop disabling source fortification and hide unused result instead.
2012-11-07 21:15:07 +01:00
Thomas Preud'homme 891dfcdf3f Generate PLT thumb stub only when necessary
Generate PLT thumb stub for an ARM PLT entry only when at least one
Thumb instruction branches to that entry.

Warning: To save space, this commit reuses the bit 0 of entries of
got_offsets array. The GOT offset is thus saved in a 31 bit value.
Make sure to divide by 2 (right shift by 1) an offset before storing it
there and conversely to multiply the value by 2 (left shift by 1) before
using it.
2012-11-07 20:51:33 +01:00
Thomas Preud'homme e07802e39d Support R_ARM_THM_JUMP24 relocation to plt
Add thumb stubs switching from thumb mode to arm mode to *all* PLT
entries so that R_ARM_THM_JUMP24 relocations to PLT entries can be
satisfied.
2012-11-07 20:48:14 +01:00
Thomas Preud'homme b0f08ace94 Create a clean target for tests2/Makefile
the absence of a clean target in tests2/Makefile make the clean target
in the main Makefile fails to complete. This commit create such a target
which removes the only file created when tests pass successfully.
2012-11-07 14:56:37 +01:00
Thomas Preud'homme a7f010ee8a Honour *FLAGS everywhere
Add CPPFLAGS, CFLAGS and LDFLAGS everywhere it's missing.
2012-11-06 15:20:53 +01:00
Hitoshi Mitake 5eb64357b1 forbid invalid comparison of struct
Current tcc permits comparison of structs and comparison between
struct and other typed values.
2012-11-05 22:34:43 +09:00
Roy Tam 943574aba5 pe: fix tcc not linking to user32 and gdi32 2012-11-02 16:59:21 +08:00
Thomas Preud'homme 034dce4f04 Enable arm hardfloat calling convention
Use arm hardfloat calling convention when the system is using it
(detected by searching for hardfloat multiarch directory).
2012-10-28 19:55:23 +01:00
Thomas Preud'homme fad68c9163 Add support for R_ARM_THM_{JUMP24,CALL} relocs
Add support for relocations R_ARM_THM_JUMP24 and R_ARM_THM_CALL. These
are encountered with gcc when compiling for armv6 or greater with
-mthumb flag and a call (conditional or not) is done.
2012-10-28 19:55:12 +01:00
Thomas Preud'homme 508df168f4 Fix commit 85f6fad3a6
Don't reset nocode_wanted with saved_nocode_wanted if it hasn't been
modified (and hence saved_nocode_wanted is uninitialized).
2012-10-25 20:14:55 +02:00
Thomas Preud'homme cf95ac399c Error out in case of variable name clash
Error out when two local variable with same name are defined in the same
scope. This fixes bug #15597 in savannah's BTS.
2012-10-25 19:40:50 +02:00
Thomas Preud'homme 85f6fad3a6 Forbid VLA as static variables
Currently, VLA are not forbidden for static variable. This leads to
problems even if for fixed-size array when the size expression uses the
ternary operator (cond ? then-value : else-value) because it is parsed
as a general expression which leads to code generated in this case.

This commit solve the problem by forbidding VLA for static variables.
Although not required for the fix, avoiding code generation when the
expression is constant would be a nice addition though.
2012-10-25 18:07:13 +02:00
Thomas Preud'homme 9966fd4eae Only use blx if available
Introduce ARM version for the target architecture in order to determine
if blx instruction can be used or not. Availability of blx instruction
allows for more scenarii supported in R_ARM_CALL relocation. It should
also be useful when introducing support for the R_ARM_THM_CALL
relocation.
2012-10-16 00:31:56 +02:00
Thomas Preud'homme c6630ef92a Fix R_ARM_CALL when target fonction is Thumb
With R_ARM_CALL, if target function is to be entered in Thumb mode, the
relocation is supposed to transform bl in blx. This is not the case
actually so this commit is there to fix it.
2012-10-10 00:21:26 +02:00
Thomas Preud'homme 2fe7fd9e87 Support for R_ARM_[THM_]MOV{W,T}_ABS[_NC} relocs
Add support for relocations R_ARM_MOVW_ABS_NC and R_ARM_MOVT_ABS as well
as their Thumb2 counterpart R_ARM_THM_MOVW_ABS_NC and
R_ARM_THM_MOVT_ABS. These are encountered with gcc when compiling for
armv7-a and a data is loaded in a register, either in arm or Thumb2
mode. The first half of the data is loaded with movw ; the second half
is loaded with movt.
2012-10-10 00:19:43 +02:00
Sergey Vinokurov 3d409b0889 fix #include_next infinite loop bug, see http://savannah.nongnu.org/bugs/?31357 2012-09-20 22:12:05 +03:00
grischka ca38792df1 tccrun: another incompatible change to the tcc_relocate API
We are now compatible with the 0.9,25 version though.  A special
value for the second (ptr) argument is used to get the simple
behavior as with the 0.9.24 version.
2012-09-01 11:33:34 +02:00
Thomas Preud'homme 56e23984b9 Disable callsave_test for arm
Disable callsave_test for arm since it uses alloca which is unavailable
on this platform.
2012-07-30 22:52:34 +08:00
Thomas Preud'homme c9a2fbaad1 Add multiarch directory for arm hardfloat variant
Arm hardfloat variant uses a different ABI than arm and uses thus a
different multiarch directory for headers and libraries. This commit
detect whether the system uses the hardfloat variant and configure the
multiarch directory accordingly.
2012-07-29 23:46:45 +08:00
Thomas Preud'homme d1694f7d7e get_reg(): try to free r2 for an SValue first
To be able to load a long long value correctly on i386, gv() rely on the
fact that when get_reg() look at an SValue it tries first to free the
register in r2 and then r. More information about the context can be
found at
http://lists.nongnu.org/archive/html/tinycc-devel/2012-06/msg00017.html
and later at
http://lists.nongnu.org/archive/html/tinycc-devel/2012-07/msg00021.html
2012-07-11 23:39:05 +02:00
Thomas Preud'homme ed9c6b132a Fix R_ARM_REL32 relocation
Add missing break in the code handling R_ARM_REL32 relocation.
2012-07-09 18:41:55 +02:00
Vincent Lefevre d27a0b3548 Incorrect shift result type on unsigned short first argument.
The code for shifts is now similar to code for binary arithmetic operations,
except that only the first argument is considered, as required by the ISO C
standard.
2012-07-06 14:22:37 +02:00
Vincent Lefevre 09b98a42a3 Tests on left-shift type. 2012-07-06 13:26:43 +02:00
Milutin Jovanović d54e24cc0e tests: Minor adjustments selecting which tests are run on each platform.
The intent is for 'make test' to pass cleanly on each platform, and thus easier
spotting of regressions. Linux is best supported by most tests running and
passing. Mac OSX passes mosts tests that do not make/link with binary files,
due to lack of mach-o file support.

!!! I have very limited knowledge of Windows platform, and cannot comment why
all tests(1) fail. I have posted to newsgroup asking for someone to test
Windows platform.
2012-06-27 14:48:08 -04:00
Vincent Lefevre 240064c03b Incorrect shift result type with 64-bit ABI
On 2012-06-26 15:07:57 +0200, Vincent Lefevre wrote:
> ISO C99 TC3 says: [6.5.7#3] "The integer promotions are performed on
> each of the operands. The type of the result is that of the promoted
> left operand."

I've written a patch (attached). Now the shift problems no longer
occur with the testcase and with GNU MPFR's "make check".

--
Vincent Lefèvre <vincent@vinc17.net> - Web: <http://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <http://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)
2012-06-27 08:23:52 -04:00
Milutin Jovanović 42c1b6ba38 tests: Added numerous tests.
The tests are taken almost verbatim from the open source project PicoC. It can
be found at https://code.google.com/p/picoc/.

The tests range from very simple/trivial ones to more complicated. My view is
that the more tests the better. Without tests like this I was very reluctant to
make any changes to tcc for the fear of breaking things.

The tests pass on Win32, OSX, Linux x86 and x86_64. One or two tests fail on
each platform due to differences in the runtime library.
2012-06-18 15:11:39 -04:00
Thomas Preud'homme b0ebcfa7ba Detect multiarch on Kfreebsd and Hurd 2012-06-13 18:28:24 +02:00
Thomas Preud'homme 2e7a1af5d5 Evaluate configure arguments
Evaluate configure arguments to reproduce autotools behavior. Autotools
actually only expands a few variable and do it at make time but it makes
the change much simpler.
2012-06-12 20:48:01 +02:00
grischka ad5f3758c3 Revert "Make ex1.c and ex4.c be executable on any systems"
Using /usr/bin/env tcc doesn't work as it was reported.  Revert to
using the full path which fails if the user installs tcc in non-default
location.  Then again this is just an example.

This reverts commit 27a428cd0f.
2012-06-12 15:45:13 +02:00
grischka 27d38bf23f tcc.c: fix argv index for parse_args
I probably broke that myself earlier.  In any case parse_args
needs to start with index 0 because it is is used also recursively
to expand the shebang command from scripts such as
    #!/usr/local/bin/tcc -run -L/usr/X11R6/lib -lX11
which arrives at tcc as only two argv's
    "tcc" "-run -L/usr/X11R6/lib -lX11"
2012-06-12 15:32:44 +02:00
Milutin Jovanović 32cd070c96 osx: Removed some optimizations for x86 builds as they were causing seg faults.
When using gcc compiler (as opposed to llvm) to build 32 bit tcc, compiler flags
-mpreferred-stack-boundary=2, -march=i386 and -falign-functions=2 were being
used. -march is redundant as -m32 is already being used. The other two seem to
be corrupting stack. I am not sure why this is the case, as the explanation of
the flags states that only running code size should be affected, but it does.

I think that is is safe to remove these flags altogether for all compilers and
platforms, especially since they are not being used for 64 bit builds. However
I do not want to apply such wide change without agreement from the people on the
mailing list.
2012-06-10 20:58:48 -04:00
Michael Matz a42b029101 x86-64: Fix call saved register restore
Loads of VT_LLOCAL values (which effectively represent saved
addresses of lvalues) were done in VT_INT type, loosing the upper
32 bits.  Needs to be done in VT_PTR type.
2012-06-10 09:01:26 +02:00
Thomas Preud'homme 9a81dcab0a tccelf.c: Add R_ARM_REL32 relocation 2012-06-05 23:09:55 +02:00
Thomas Preud'homme 7f6095bfec Add support for arm hardfloat calling convention
See Procedure Call Standard for the ARM Architecture (AAPCS) for more
details.
2012-06-05 23:09:55 +02:00
Thomas Preud'homme bfb00494eb Fix removal of vnrott
Make vrotb ST_FUNC so that arm-gen.c can use vrotb.
2012-06-05 23:09:55 +02:00
Thomas Preud'homme 731e07f175 Only warn for unknown options in configure script
This follows discussion started at
http://lists.nongnu.org/archive/html/tinycc-devel/2012-05/msg00015.html
2012-05-28 21:16:39 +02:00
Thomas Preud'homme b56edc7b90 Several multiarch/biarch fixes
* Add multiarch directories for arm and i386
* Fix detection of biarch: /lib64/ld-linux-x86-64.so.2 is mandated by
  ABI and is thus always present, even if there is no biarch
* Define CONFIG_LDDIR directly with the right value in case of multiarch
  instead of defining it to /lib and then redifining it.
2012-05-23 00:14:15 +02:00
Thomas Preud'homme a2c71af1ea Fix CONFIG_LDDIR usage
This patch fix 2 bugs in CONFIG_LDDIR usage:

* CONFIG_LDDIR used for 2 purposes

  there is confusion between the directory to find libraries, crt* files
  and headers and the directory in which the program interpreter is.
  These two directories are not related. The latter is specified by the
  ABI and should not be configurable while the former depends on the
  system (single arch, biarch, multiarch). This end a longstanding issue
  with amd64 program interpreter later propagated to other architecture
  interpreters.

* If multiarch is in effect, then the library directory should be /lib.
  /lib64 denotes biarch architecture, everything which is here would be
  in /lib/x86_64-linux-gnu instead.
2012-05-22 23:44:03 +02:00
Michael Matz 2daae0dc99 x86_64: Fix compares with NaNs.
Comparisons with unordered doubles was broken, NaNs always
compare unequal (and unordered) to everything, including
to itself.
2012-05-13 02:21:51 +02:00
Michael Matz 0394caf784 Emit spaces for -MD
TCCs make dependency generator is incompatible with the GNU
depcomp script which is widely used.  For TCC it has to go over
the output of -MD, (it detects it as ICC compatible), but the
sed commands it uses are confused by tabs in the output, so that
some rewrites aren't done.

Those tabs will then finally confuse make itself when the
generated .d files are included.  It reads them as goal commands
(leading tab), and is totally lost then.

Short of changing depcomp (hard because distributed with all kinds
of software), simply emit spaces for -MD.
2012-05-13 02:03:47 +02:00
Michael Matz 9ca9c82ff8 Fix comparing comparisons
Sometimes the result of a comparison is not directly used in a jump,
but in arithmetic or further comparisons.  If those further things
do a vswap() with the VT_CMP as current top, and then generate
instructions for the new top, this most probably destroys the flags
(e.g. if it's a bitfield load like in the example).

vswap() must do the same like vsetc() and not allow VT_CMP vtops
to be moved down.
2012-04-18 20:57:14 +02:00
Michael Matz 718fd591fa Make sizeof() be of type size_t
This matters when sizeof is directly used in arithmetic,
ala "uintptr_t t; t &= -sizeof(long)" (for alignment).  When sizeof
isn't size_t (as it's specified to be) this masking will truncate
the high bits of the uintptr_t object (if uintptr_t is larger than
uint).
2012-04-18 20:57:14 +02:00
Michael Matz b068e29df7 x86_64: Implement GET_CALLER_FP
TCC always uses %rbp frames, so we can use that one.
2012-04-18 20:57:13 +02:00
Michael Matz 4c0d70ab07 Fix parsing function macro invocations
If a function macro name is separated from the parentheses in
an macro invocation the substitution doesn't take place.
Fix this by handling comments.
2012-04-18 20:57:13 +02:00
Michael Matz 15f4ac2b1a Fix detection of labels with a typedef name
This needs to be accepted:
  typedef int foo;
  void f (void) { foo: return; }
namespaces for labels and types are different.  The problem is that
the block parser always tries to find a decl first and that routine
doesn't peek enough to detect this case.  Needs some adjustments
to unget_tok() so that we can call it even when we already called
it once, but next() didn't come around restoring the buffer yet.
(It lazily does so not when the buffer becomes empty, but rather
when the next call detects that the buffer is empty, i.e. it requires
two next() calls until the unget buffer gets switched back).
2012-04-18 20:57:13 +02:00
Michael Matz 1d0a5c2515 x86_64: Fix segfault for global data
When offsetted addresses of global non-static data are computed
multiple times in the same statement the x86_64 backend uses
gen_gotpcrel with offset, which implements an add insn on the
register given.  load() uses the R member of the to-be-loaded
value, which doesn't yet have a reg assigned in all cases.

So use the register we're supposed to load the value into as
that register.
2012-04-18 20:57:13 +02:00
Michael Matz 86ac6b9bee x86_64: Fix indirection in struct paramaters
The first loop setting up struct arguments must not remove
elements from the vstack (via vtop--), as gen_reg needs them to
potentially evict some argument still held in registers to stack.

Swapping the arg in question to top (and back to its place) also
simplifies the vstore call itself, as not funny save/restore
or some "non-existing" stack elements need to be done.

Generally for a stack a vop-- operation conceptually clobbers
that element, so further references to it aren't allowed anymore.
2012-04-18 20:57:13 +02:00
Michael Matz 5c0a2366a3 Fix bitfield loads into char/short.
Removes a premature optimization of char/short loads
rewriting the source type.  It did so also for bitfield
loads, thereby removing all the shifts/maskings.
2012-04-18 20:57:13 +02:00
Michael Matz 6471ec0a2b Fix conversion in a?0:ptr.
(cond ? 0 : ptr)->member wasn't handled correctly.  If one arm
is a null pointer constant (which also can be a pointer) the result
type is that of the other arm.
2012-04-18 20:57:13 +02:00
grischka f98c2306a0 libtcc: tcc_get_symbol uses the TCCState parameter
This allows using tcc_get_symbol on some other than the
current TCCState. (Suggested by David Mertens)
2012-04-18 18:48:26 +02:00
grischka 32a411914b support "x86_64-linux-gnu" subdirs with lib & include
suggested for newer ubuntu by Damian Gryski
2012-04-18 18:44:39 +02:00
grischka f1b5c2ef4f tcc_realloc: auto "memory full" error 2012-04-18 18:43:55 +02:00
grischka 3c59f84240 tcc.h: unify multiple #ifdef CONFIG_TCC_BACKTRACE 2012-04-18 18:43:29 +02:00
grischka ab936aeb8c cleanup some partially broken patches
- tests/Makefile:
  fix commit de54586d5b
  This hunk it unrelated to the other changes (which are about MacOSX).
  It is not useful and partially wrong.  Optional tests are meant to
  stay optional, btest would work only for i386

- tcc.h:
  fix commit c52d79605a by unknown
  The message says it's for MINTW but the patch has obviously
  no effect for MINGW (which defines __GNUC__).  However the patch
  seems useful for MSC which however needs _strto(u)i64 with underscore.

- Makefile:
  fix commit 5280293d6b
  Do not build tcc.o with -DONE_SOURCE because we finally build tcc
  from tcc.o and libtcc.a/so
2012-04-18 18:43:09 +02:00
grischka 5aaa067af4 win32: tcc.exe uses libtcc.dll 2012-04-18 18:38:11 +02:00
grischka 4274c44de7 tcc.c: fix previous commit "Use CString to concat linker options"
- remove redunant else branch
- zero-terminate linker_arg
- declare cstr_xxx as PUB_FUNC
  (which are functions used in tcc.c but not in the libtcc API.
   Useful for a tcc(.exe) that uses the libtcc.(so/dll))
- while at it, export PUB_FUNCs from dll
2012-04-18 18:32:37 +02:00
Gabriel Corneanu 214564b1dc Re-enable "Use CString to concat linker options"
This reverts commit 16202e054f.

Changed win32 build to use ONE_SOURCE just like libtcc.dll
Therefore CString can be used again...
2012-04-18 10:01:45 +02:00
Gabriel Corneanu 176876e5de add "nostdlib" option to libtcc 2012-04-18 09:48:57 +02:00
Thomas Preud'homme 16202e054f Revert "Use CString to concat linker options"
This reverts commit 1c11b857fe.

On windows, libtcc.c is compiled with ONE_SOURCE and then tcc.c is
linked to it. Thus tcc.c can only use public functions which cstr_* are
not.
2012-04-10 16:33:39 +02:00
Thomas Preud'homme 1c11b857fe Use CString to concat linker options
As suggested, change type of linker_arg variable to the more appropriate CString
type, since linker_arg is about dynamically grown string.
2012-03-20 16:01:12 +01:00
Thomas Preud'homme 2eee100c37 Fix use after free for linker_arg
elements in linker_arg are used in TCCState structure and must thus not
be freed when option parsing is finished. Declare linker_arg as a global
static variable and free it after tcc_delete has been called on TCCState
structure.

This fix commit 7fb0482a46
2012-03-16 19:23:54 +01:00
unknown c52d79605a fix mingw compliation 2012-03-16 08:54:29 +08:00
Thomas Preud'homme 7fb0482a46 Support linker options passed in several -Wl param
ld support arguments to multiple-letter options being passed in two
ways:
* -opt=arg
* -opt arg

libtool generate command line of the second form. This commit add
support for the second form so that libtool works with tcc. The way it
is done is to concatenate all -Wl options into one and then pass it to
set_linker.
2012-03-15 00:25:40 +01:00
Thomas Preud'homme 1736a71b71 Consider long int constant as 64 bits on x86-64
Quick and dirty hack to consider long int constant (as in 1UL or 1L) as
64 bits integer on x86-64 non Windows systems.
2012-03-14 15:47:42 +01:00
Thomas Preud'homme 53c5715cca Remove vnrott (duplicate vrotb) 2012-03-14 15:39:16 +01:00
Thomas Preud'homme 3d25213c16 Inform user that -b only exists on i386. 2012-03-13 19:43:43 +01:00
Milutin Jovanovic de54586d5b Further changes improving the OSX build. Everything builds. libtest passes.
Other tests still have issues, currently with weak linking.

One of the primary stumbling blocks on OSX is the lack of support for
mach-o binaries. Therefore all tcc usage on OSX has to be limited to elf
binaries, presumably produced by tcc itself.

Therefore I had to enable building of tiny_libmaker for OSX. Then changed
the make to use tcc and tiny_libmaker to compile the tcclib1.

In order to compile the tests, specifically the parts that use weak linking,
I have had to define MACOSX_DEPLOYMENT_TARGET to 10.2, which seems like a
hack, but extensive searching seems to indicate that this is the only way
to make apple gcc allow weak linking. Using any other value, bigger or smaller
breaks weak linking.

Also added _ANSI_SOURCE define required by some OSX headers, and some cosmetic
gitignore changes. I believe these changes should not impact other platforms.
2012-03-06 13:26:36 -05:00
grischka ae191c3a61 x86_64: fix loading of LLOCAL floats
See also commit 9527c4949f

On x86_64 we need to extend the reg_classes array because load()
is called for (at least) R11 too, which was not part of reg_classes
previously.
2012-03-05 20:19:28 +01:00
grischka a35b3059bb tcc.h: define TCC_IS_NATIVE
- disable tccrun feature for non-native (cross-) compilers
- define uplong for target adress size
- fix using -Wl,-Ttext=... for Win64 (tccpe: ADDR3264 imagebase)
2012-03-05 20:15:56 +01:00
Andrew Mulbrook a0db7162af Fix assumption of 32bit long on portions of Elf
Modify tcc to accept convert full 64bits of specified text section
when converting on Win64. Write high bytes to the elf section address
as well. This allows creation of elf binaries located in offsets using
full 64 bit addresses.

Signed-off-by: Andrew Mulbrook <andrew262@gmail.com>
2012-03-03 11:10:15 -06:00
Andrew Mulbrook 5775911dad Revert "Multiple fixes for 64 bit sections"
This reverts commit d7a7c3769d.
2012-03-03 10:12:06 -06:00
Ramsay Jones e343b1dfd4 Add __REDIRECT needed for Large File Support API on linux
Since commit 9b09fc3 ("Add support of asm label for functions",
05-09-2010) tcc has had the capability to rename functions at the
assembly level. This capability was subsequently used by commit
2596273 ("Add support for __REDIRECT_NTH needed with eglibc",
11-09-2010) to redirect long double functions on platforms which
did not support long double.

Here we add the companion macro __REDIRECT which is used (along
with __REDIRECT_NTH) in the glibc headers on Linux to support the
Large File API (when _FILE_OFFSET_BITS is set to 64).

Signed-off-by: Ramsay Jones <ramsay@ramsay1.demon.co.uk>
2012-02-29 16:38:24 +00:00
mob d7a7c3769d Multiple fixes for 64 bit sections
This changeset attempts to fix a few problems when giving using
the high 32bits of a 64bit section offset. There are likely more
issues (or perhaps regressions) lurking in the muck here. In general,
this moves a few data type declarations to use uplong.  Also, add
support for 64bit mingw32 building under cygwin.  Because native
types are used for 64 bit offsets, this won't fix challenges with
cross compiling from 32bit -> 64bit.

Tested under cygwin, against binary compiled with
-Wl,-Ttext=0xffffff8000000000

Signed-off-by: Andrew Mulbrook <andrew262@gmail.com>
2012-02-26 19:02:51 -06:00
Milutin Jovanovic 6e13c35334 Attempt to fix 32 bit OSX build. The fix consists of adding -m32 and -m64
to the appropriate CFLAGS. In addition, memory hooks are very different
on OSX, so build of bcheck.c had to be disabled for now.

Change of the CFLAGS does affect builds on other platforms, and this needs
to be tested.
2012-02-16 11:24:14 -05:00
Milutin Jovanovic 8ca8b08890 Patch attempting to build OSX TinyCC.
Applied patch found on stackoverflow (link below). I also found some
related changes that looked like logically needed. The stackoverflow
changes addressed only two registers which were breaking a compile.
However reading the code in the same file shows two other register
accesses that, while not breaking the build, should have the same fix.

http://stackoverflow.com/questions/3712902/problems-compiling-tcc-on-os-x/3713144#3713144

The test driver was changed by changing 'cp -u' into 'cp' as '-u' is not
supported on mac osx.

I found that osx build required the WITHOUT_LIBTCC define. I suspect the
reason for this is tcc unability to handle mach-o files. In order to
properly address this I had to change 'configure' to propagate target os
name to Makefile.

Current state is that simple tests work, but not the whole 'make test'
suite runs.

To the best of my knowledge, these changes should not impact other
platforms.
2012-02-09 12:53:17 -05:00
Daniel Glöckner 9527c4949f i386: fix loading of LLOCAL floats
These loads clobbered ebx as TinyCC wanted to load the address into st0.
2012-01-23 01:45:11 +01:00
Thomas Preud'homme 3ab269c56a Error out when assigning void value.
tcc should now error out when compiling code like:

VOID ExitProcess(UINT uExitCode);
(…)
retCode = ExitProcess(pi.dwProcessId);
2012-01-22 21:18:38 +01:00
Thomas Preud'homme 9c25ed13b4 s/derefencing/dereferencing/ in i386-gen.c 2012-01-08 18:03:17 +01:00
Thomas Preud'homme 519a9040a1 Compile tccasm.c conditionally (TCC_CONFIG_ASM)
Only compile the content of tccasm.c if inline assembly is supported for
this architecture by testing the presence of macro TCC_CONFIG_ASM.
2012-01-06 18:34:21 +01:00
Thomas Preud'homme 83d57c06f4 Fix linkage of named file in loader script.
Remove the previous logic to link a named file with a loader script by
using tcc_add_dll instead. Hence, all files can be linked, not only
files ending in .so/.def.
2012-01-04 14:40:03 +01:00
Nicolas Limare 5f99fe2ff1 libtcc: add missing tcc_enable_debug() 2011-10-03 22:36:16 +02:00
Thomas Preud'homme 2dd3fb103e Don't define strtold and strtof on *BSD + uClibc
Don't define strtold and strtof on *BSD and uClibc as they are already
defined there since:

* 2001 (FreeBSD 4.4)
* 2009 (OpenBSD 4.5)
* 2009 (DragonFlyBSD)
* 2002 (uClibc)

See
http://lists.nongnu.org/archive/html/tinycc-devel/2011-07/msg00025.html
for a bit more details.
2011-08-12 18:43:37 +02:00
Daniel Glöckner ab7ed48ee8 Fix problem with PLT and GOT relocs on armel.
TinyCC fails to link correctly to libraries when both R_ARM_PLT32 and
R_ARM_GOT32 relocation to a same symbol exist (see
http://lists.nongnu.org/archive/html/tinycc-devel/2010-05/msg00032.html
for more details).
The patch marks all undefined weak symbols found in external libraries
as strong. The value of all remaining weak symbols is set to zero just
before the section is output.

Note by Thomas Preud'homme: it's been 2 months in Debian without any new
bug report, hence commiting.
2011-08-12 18:28:45 +02:00
grischka bf374a5f23 rename error/warning -> tcc_(error/warning) 2011-08-11 17:07:56 +02:00
grischka 74a24d77fd libtcc: minor adjustments
- use {B} to substitute tcc_lih_path (instead of \b)

- expand CONFIG_TCC_CRTPREFIX in CONFIG_TCC_LIBPATHS
  which fixes duplicate CONFIG_SYSROOT.

- put default CONFIG_SYSROOT ("") into tcc.h

- remove hack from commit db6fcce78f
  because $(tccdir)/include is already in sysincludes

- configure: error out for unrecognized options.

- win32/build-tcc.bat: put libtcc into base dir where it will
  find lib/include automatically, and build libtcc_test example.
2011-08-11 16:55:30 +02:00
Gabriel Corneanu fd0cea8895 dll build + small adjustments 2011-08-10 12:42:14 +02:00
grischka e844fb11c2 libtcc: support more than one crtprefix
Looks like gcc has that.  Oh Deer!
2011-08-06 16:49:30 +02:00
grischka e6f3bf7f08 libtcc: cleanup the 'gen_makedeps' stuff 2011-08-06 16:11:58 +02:00
grischka 39a07cca58 tcc: fix -m32/64 & simplify
This cleans up the mess from commit
   8f98573658
and preceeding.

- make tcc -m64 work on windows
- execvp on windows returns 0 always, replace by spawnvp
- remove bizarre support for i386-win32-tcc -m64
2011-08-06 16:11:58 +02:00
grischka 5e5e29f8fd tcctest: switch weak_toolate proto with impl
gcc -O0 didn't like this.
2011-08-06 16:11:57 +02:00
grischka f115c12346 x86-64: fix flags and zero-pad long doubles
This fixes a bug introduced in commit
    8d107d9ffd
that produced wrong code because of interference between
0x10 bits VT_CONST and x86_64-gen.c:TREG_MEM

Also fully zero-pad long doubles on x86-64 to avoid random
bytes in output files which disturb file comparison.
2011-08-06 16:11:56 +02:00
grischka 81cd0cf6fd configure: add switches to set search paths
--sysincludepaths=.. specify system include paths, colon separated"
     Sets CONFIG_TCC_SYSINCLUDEPATHS

   --libpaths=...       specify system library paths, colon separated"
     Sets CONFIG_TCC_LIBPATHS

   --crtprefix=...      specify location of crt?.o"
     Sets CONFIG_TCC_CRTPREFIX

   --elfinterp=...      specify elf interpreter"
     Sets CONFIG_TCC_ELFINTERP

Also the CONFIG_TCC_XXX were renamed to make them look
more consistent.

Also move the elf_interp definitions to tcc.h.
2011-08-06 16:11:12 +02:00
Thomas Preud'homme 9ffd77f18d Remove semicolon in x86-64 va_arg definition. 2011-08-05 20:32:57 +02:00
Thomas Preud'homme 0b6652003c Revert "Add a --multiarch-triplet switch to configure"
This reverts commit 76adc5770f.
2011-08-03 22:26:39 +02:00
Thomas Preud'homme 76adc5770f Add a --multiarch-triplet switch to configure
Add a --multiarch-triplet switch to configure. The switch will allow
files to be search for each default path in path/<triplet> and then
path.
Default paths handled that way:
- CONFIG_TCC_SYSINCLUDE_PATHS
- CONFIG_TCC_LIBPATH
- path to crt*.o
- path to libgcc_s.so.1

Path missing: elf interpreter path (will be handled in another commit)
2011-08-02 00:31:17 +02:00
Thomas Preud'homme 5e954fef32 Set CONFIG_TCC_CRT_PREFIX relative to CONFIG_SYSROOT
Set CONFIG_TCC_CRT_PREFIX relative to CONFIG_SYSROOT for consistency
with CONFIG_TCC_LDDIR.
2011-08-01 15:39:38 +02:00
grischka df9cce24a8 Accept colon separated paths with -L and -I
This allows passing colon separated paths to
  tcc_add_library_path
  tcc_add_sysinclude_path
  tcc_add_include_path

Also there are new configure variables
  CONFIG_TCC_LIBPATH
  CONFIG_TCC_SYSINCLUDE_PATHS
which define the lib/sysinclude paths all in one and can
be overridden from configure/make

For TCC_TARGET_PE semicolons (;) are used as separators

Also, \b in the path string is replaced by s->tcc_lib_path
(CONFIG_TCCDIR rsp. -B option)
2011-08-01 01:10:36 +02:00
Thomas Preud'homme 626a907451 Revert "Force const. expr. in expr_cond outside function"
This reverts commit b2f5ee9b2d as it's
useless on mob.
2011-07-31 17:18:19 +02:00
Thomas Preud'homme b2f5ee9b2d Force const. expr. in expr_cond outside function
Since no code should be generated outside a function, force expr_cond to
only consider constant expression when outside a function since the
generic code can generate some code.
2011-07-31 00:19:13 +02:00
Joe Soroka 339f961c11 fixed Makefile test targets 2011-07-22 02:12:49 -07:00
Joe Soroka 9b52e16a50 re-added negative-array-size testcase and fixed fix for it 2011-07-22 02:09:28 -07:00
grischka d7d8458888 Revert "better constant handling for expr_cond"
It produced wrong code with one of my test projects.
This reverts commit cd3d1a45f3.
2011-07-16 15:53:30 +02:00
grischka adc80009c8 elf.h: define SHF_MERGE etc. 2011-07-14 19:35:20 +02:00
grischka 8d107d9ffd win64: va_arg with structures 2011-07-14 19:24:53 +02:00
grischka aa80e5b1ff tccpe: cleanup ELFW() macros etc. 2011-07-14 19:23:04 +02:00
grischka d483ab322f tccrun: win32: improve exception handler 2011-07-14 19:11:12 +02:00
grischka 08083ddb21 tccrun: win32: improve rt_get_caller_pc 2011-07-14 19:11:11 +02:00
grischka d59bd8be8e tccrun: rt_printline: fix no-stabs case 2011-07-14 19:11:10 +02:00
grischka af83993810 tccrun: improve rt_printline output format
Prefix line with "file:linenumber:" such that editors
can easily jump to the source location
2011-07-14 19:11:08 +02:00
grischka df4c0892f3 tccrun: win64: add unwind function table for dynamic code
This works only when tcc.exe is compiled using MSC.  MinGW does
something in the startup code that defeats it.
2011-07-14 19:09:49 +02:00
grischka 232650f8b3 tccgen: reset aligned attribute for next type
Basically, with:
    typedef __attribute__((aligned(16))) struct _xyz {
         ...
    } xyz, *pxyz;

we want the struct aligned but not the pointer.

FIXME: This patch is a hack, waiting for someone in the knowledge
of correct __attribute__ semantics.
2011-07-14 19:00:46 +02:00
grischka 5280293d6b make: create native tcc from separate objects
This was already possible using
    make NOTALLINONE=1
and is now the default.

To build as previously from one big source, use
    make ONE_SOURCE=1

Cross compilers are still build from one source because using
separate objects requires separate build directories one per
platform which currently is not (yet) supported by the makefile.

We could probably use gnu-makeish target variables like
    $(I386_CROSS): OUTDIR=build/i386
    $(X64_CROSS): OUTDIR=build/x86-64
and so on ...

Also NEED_FLOAT_TYPES for arm-gen is removed.  It was about
variables that are referenced from outside (libtcc, tccgen).
We could declare them in tcc.h (as with reg_classes) or have
them twice in arm-gen.c.  I chose option 2.
2011-07-14 18:45:37 +02:00
Thomas Preud'homme 4ccb5662cb Fix array_test: move params to local vars
array_test is declared and called with no parameters but defined with
one parameter. Compilation succeed (definition is after the use so the
compiler consider the declaration) as well as link (the function exist
and has the right name) but running the test segfault on i386 platforms.

This patch moves the parameter to local variable. If the intention was
to call it with an array parameter then feel free to fix it again.
2011-07-12 15:10:59 +02:00
grischka 45184e01d8 win32: add -Wl,--stack=xxx switch
For example:

    $ tcc -Wl,--stack=4194309

which means 4 MB.  Default is 1 MB.
2011-07-11 18:47:16 +02:00
grischka 7b573dc239 win32/include: enable _timezone etc variables.
which live in msvcrt.dll and need __declspec(import) which
works by now.

Also:
- _mingw.h: conditionally define WIN32_LEAN_AND_MEAN
- malloc.h: don't undef alloca
2011-07-11 18:44:47 +02:00
Joe Soroka 436c1a734f allow defining sysroot at compile-time 2011-07-11 00:20:48 -07:00
Joe Soroka c71798c376 handle arrays with a flexible member but no initializer 2011-07-11 00:18:36 -07:00
Joe Soroka cd3d1a45f3 better constant handling for expr_cond 2011-07-11 00:00:47 -07:00
Joe Soroka 38756b506f fix self-referential token pasting 2011-07-08 02:51:06 -07:00
Thomas Preud'homme 5cf5871aaf Use CONFIG_TCC_LDDIR for ld.so on all linux archs 2011-07-08 11:16:34 +02:00
Thomas Preud'homme 13121e220c Fix problem spotted in <4E15F966.4090102@gmx.de>
* Rename tcc_split_path_components
* Move tcc_split_path below memory wrapper section
* Ident tcc_split_path by 4
* Remove prefix and suffix clutter in tcc_split_path
* Don't dereference beyond the end of the search paths string
2011-07-08 10:51:26 +02:00
Joe Soroka d01f65ef93 fix end-of-scope for self-referential macros 2011-07-08 00:55:34 -07:00
Thomas Preud'homme f8656fbc3c Remove useless changes from 31ca000d in configure
After commit 4d6a4a26e0, the changes in
configure are no longer needed.
2011-07-07 15:32:20 +02:00
Thomas Preud'homme 27a428cd0f Make ex1.c and ex4.c be executable on any systems
Use /usr/bin/env to make ex1.c and ex4.c on any systems, wherever is
installed tcc.
2011-07-07 12:17:04 +02:00
Thomas Preud'homme a03346c06e Document in README that ex4.c can be executed. 2011-07-07 12:15:43 +02:00
Thomas Preud'homme 571465d32b Revert "Make examples' shebang use target tcc bindir path"
This reverts commit cb2138f8b0.
2011-07-07 12:14:08 +02:00
Thomas Preud'homme 4d6a4a26e0 Add configuration of include subdirectories
Add the possibility to search headers in several subdirectories of
/usr/local/include and /usr/include. A possible use case would be for
tcc to search for headers in /usr/local/include/x86_64-linux-gnu,
/usr/local/include, /usr/include/x86_64-linux-gnu and /usr/include in
turn.
2011-07-07 12:10:57 +02:00
Thomas Preud'homme a6775fc154 Introduce tcc_split_path_component for 31ca000d
Rewrite code introduced by 31ca000d and following commits around a new
function tcc_split_path_component.
2011-07-07 11:48:37 +02:00
Thomas Preud'homme ca6ff4fada Free extra_libdir_str after use. 2011-07-06 10:26:46 +02:00
Thomas Preud'homme 38de06e334 Fix commit 31ca000d
* CONFIG_TCC_*LDDIR should not be exported if no --*lddir option is used.
* Don't write a : at the beginning of extralddir
2011-07-05 23:49:53 +02:00
Thomas Preud'homme 31ca000d72 Add multiarch dirs to linker search path
By default, tcc search libraries in /lib and /usr/local/lib while crt*.o
files are searched in /usr/lib and ld.so is searched in /lib.
Unfortunetely the path are hardcoded in source code. This patch allow
tcc to look in an other directory and also to look in extra directories.
It's then possible to make tcc search libraries in /lib/x86_64-linux-gnu
and /usr/local/lib/x86_64-linux-gnu while crt*.o files are searched in
/usr/lib/x86_64-linux-gnu and ld.so is searched in
/lib/x86_64-linux-gnu.
2011-07-05 11:16:12 +02:00
Thomas Preud'homme cb2138f8b0 Make examples' shebang use target tcc bindir path
Use @BINDIR@ in shebang of examples to put the right path on the target
system. That is, use #!/usr/local/bin/tcc if tcc is installed in /usr/local/bin
and #!/usr/bin/tcc if tcc is installed in /usr/bin/tcc.
2011-06-18 00:45:20 +02:00
Thomas Preud'homme 3511e6e2a8 Default to create progs with symbols (incl. debug)
* Set CFLAGS entirely in configure if not already set.
* Compile bcheck.c with the same flags as the other source files
* Don't strip binaries by default (GB are cheap now) but provide a
  --strip-binaries option in configure script.
2011-06-17 22:22:04 +02:00
Thomas Preud'homme 330d2ee0fa Update Changelog
* Mention the various ARM improvement
* Make changelog consistent with regards to initial capital letters
* Fix credits for VLA
* Fix entry about asm label (variable are also supported)
2011-05-17 23:40:49 +02:00
Thomas Preud'homme eb152022a0 make test work when LIBTCC1 not defined
Make libtest depends on LIBTCC1 instead of ../libtcc1.a and define
LIBTCC1 to $(TOP)/$(LIBTCC1) if LIBTCC1 is defined
2011-05-17 23:30:32 +02:00
grischka c449ef2e1f tcc-doc: remove obsolete '-o option must also be given' 2011-05-17 21:55:05 +02:00
Daniel Glöckner 28a5b702f4 Fix calling ARM EABI functions returning big structures
The wrong type was tested to determine the size of the structure.
2011-05-17 02:24:45 +02:00
Thomas Preud'homme 8123e334e9 Support scratchbox, Nokia N900 and qemu arm archs
Add arm, armv5tejl and armv7l to the list of supported arm architectures
2011-05-16 15:30:52 +02:00
Thomas Preud'homme 66d992d883 Remove unused variables
Declare float type conditionally to not declare them conditionally when
they are not used.
2011-05-16 15:21:25 +02:00
Thomas Preud'homme ee06ef9dd3 Remove unused variables
Remove unused local variables and declare them conditionally when they
are used only on some architectures.
2011-05-16 14:15:32 +02:00
Thomas Preud'homme db9d5f0fa4 Improve weak aliases handling
* Include only the STB_GLOBAL alias symbol in .dynsym section
* Stop the loop when STB_GLOBAL symbol is found
* Reword / simplify comment
2011-05-16 13:49:08 +02:00
Thomas Preud'homme 921f002a6d make clean work when LIBTCC1 not defined
Don't call make -C lib clean if LIBTCC1 is not defined, else make clean
fails (for example of arm).
2011-05-14 16:21:45 +02:00
Joe Soroka 7391cf01a7 fix spurious vstack-leak warnings on error 2011-05-02 00:05:36 -07:00
Joe Soroka 48d81a796e libtcc.c: report vstack "leaks" only if compile succeeded 2011-04-14 01:02:42 -07:00
Joe Soroka 2b7a8eb8f5 use of TOK_alloca breaks cross compiler build
VLA inserts a call to alloca via enum TOK_alloca, but TOK_alloca
only exists on I386 and X86_64 targets.  This patch just emits an
error at compile-time if someone tries to compile some VLA code
for a TOK_alloca-less target. The best solution might be to just
push the problem to link-time, since the existence-or-not of a
alloca implementation can only be determined by linking.  It seems
like just declaring TOK_alloca unconditionally would achieve that,
but for now, this at least gets the cross compilers to build.
2011-04-12 00:17:08 -07:00
Joe Soroka 46e2dd7c32 tcctok.h: fix ifdef target/host confusion 2011-04-12 00:11:47 -07:00
Joe Soroka 812781cd11 simplify/rollback VLA pointer subtraction
I don't know if it makes a difference to gen_op(TOK_PDIV) or not,
but logically the ptr1_is_vla test in TP's VLA patch seems out of
order, where the patch to fix it would be:
------------------------------------------------------------------
@@ -1581,15 +1581,15 @@ ST_FUNC void gen_op(int op)
                 u = pointed_size(&vtop[-1].type);
             }
             gen_opic(op);
+            if (ptr1_is_vla)
+                vswap();
             /* set to integer type */
 #ifdef TCC_TARGET_X86_64
             vtop->type.t = VT_LLONG;
 #else
             vtop->type.t = VT_INT;
 #endif
-            if (ptr1_is_vla)
-                vswap();
-            else
+            if (!ptr1_is_vla)
                 vpushi(u);
             gen_op(TOK_PDIV);
         } else {
------------------------------------------------------------------

Instead of that patch, which increases the complexity of the code,
this one fixes the problem by just rolling back and retrying with
a simpler approach.
2011-04-11 23:39:27 -07:00
Joe Soroka 1b0f42f8ad update documentation to reflect VLA changes 2011-04-09 23:41:16 -07:00
Joe Soroka 1b8c094f39 remove no-longer-necessary naive fix for vla vstack leak 2011-04-09 23:04:01 -07:00
Joe Soroka c85f77de70 prevent internal segfault on apparent VLA at file scope 2011-04-09 22:59:35 -07:00
Joe Soroka 1446b543ae VLA fix [3/3]: store VLA sizeofs in anonymous runtime stack vars 2011-04-09 22:52:25 -07:00
Joe Soroka 7c7ca3c6aa VLA fix [2/3]: removed VT_ARRAY from VT_VLA types
A VLA is not really an array, it's a pointer-to-an-array.
Making this explicit allows us to back out a few parts
of the original VLA patch and paves the way for the next
part of the fix, where a VLA will be stored on the runtime
stack as a pointer-to-an-array, rather than on the compile-
time stack as a Sym*.
2011-04-08 01:09:39 -07:00
Joe Soroka cb2fa5eab9 VLA fix [1/3]: added testcase demonstrating VLA bug 2011-04-08 01:07:17 -07:00
Joe Soroka 174d61a56e move a comment to its correct location 2011-04-08 00:46:32 -07:00
Joe Soroka b714af0405 add naive workaround for VLA vstack leak 2011-04-08 00:44:01 -07:00
Joe Soroka 6eb97c70b7 VLA leaks vstack. added warning to detect future leaks 2011-04-08 00:41:55 -07:00
Joe Soroka c94f80502e VLA bcheck works via bound alloca; add test, remove warning 2011-04-06 15:27:45 -07:00
Joe Soroka 810aca9e68 clarify post_type() VT_STORAGE handling by moving it out 2011-04-06 12:08:50 -07:00
Joe Soroka ace0f7f259 re-apply VLA by Thomas Preud'homme 2011-04-06 09:17:03 -07:00
Joe Soroka 17571298f3 handle c99 flexible array members less hackily 2011-03-18 17:50:42 -07:00
Joe Soroka 06a7c415a9 revert complicated & broken flexible array member handling 2011-03-18 17:47:35 -07:00
Joe Soroka 4062d787da sizeof(struct with "flexible array member") is wrong 2011-03-18 17:45:43 -07:00
Joe Soroka 0b8aa909a3 fix c99 for-loop init decl scope (thanks: grischka)
see http://lists.nongnu.org/archive/html/tinycc-devel/2011-03/msg00005.html
2011-03-08 15:19:54 -08:00
Joe Soroka 9ff91d4c6f clarify support for functions returning an array (try#2)
fixes first attempt:
http://repo.or.cz/w/tinycc.git/commitdiff/31fe1cc
2011-03-08 15:12:09 -08:00
Joe Soroka 91163f167e revert last commit. fails "make test"
test target in Makefile does not depend on tcc.
i'm not sure why, but i can think of at least one
good reason.  in my local tree I have it modified
to do so, but somehow inadvertently reverted that
so when i did "make test" before committing, it
didn't actually test my changes.  sorry.
2011-03-08 14:58:02 -08:00
Joe Soroka 31fe1cc62b clarify support for functions returning an array
previously, tcc would accept a prototype of a function returning
an array, but not giving those functions bodies nor calling them.
it seems that gcc has never supported them, so we should probably
just error out... but it's possible that someone already using
tcc includes some header that contains an unused prototype for
one, so let's continue to support that.
2011-03-08 14:13:08 -08:00
Joe Soroka 5eb82755db support c99 for-loop init decls (2nd attempt) 2011-03-08 13:36:04 -08:00
Joe Soroka 7fc2eee55c partially revert e23194a
see http://lists.nongnu.org/archive/html/tinycc-devel/2011-03/msg00002.html
2011-03-08 13:22:48 -08:00
Joe Soroka b3a8eed49e revert last 3 commits. will find better way. 2011-03-08 12:56:13 -08:00
Joe Soroka 2d292e69a1 small change to previous whitespace-only commit 2011-03-08 09:26:36 -08:00
Joe Soroka 545a37b306 some indentation made prev patch pretty; removed it 2011-03-08 01:59:50 -08:00
Joe Soroka 89059f94c0 refactor post_type() to be explicit about its recursion 2011-03-08 01:47:31 -08:00
Joe Soroka 772b302187 added a note clarifying post_type() recursion
some ancient pre-K&R C allows a function to return an array
and the array brackets to be put after the arguments, such
that "int c()[]" means the same as "int[] c()"
see:
http://llvm.org/bugs/show_bug.cgi?id=2399
http://java.sun.com/docs/books/jls/third_edition/html/classes.html#38703
2011-03-08 01:33:17 -08:00
Joe Soroka 585027aa96 tccelf: allow multiply defined weak symbols 2011-03-07 12:18:54 -08:00
Joe Soroka e23194a1fa support c99 for-loop init decls 2011-03-07 11:28:31 -08:00
Joe Soroka 4fbe3cda33 use new weaken_symbol() to fix another real-world corner case 2011-03-07 01:05:09 -08:00
Joe Soroka 8bcb2ae1b2 factor out symbol weakening into new function 2011-03-07 01:02:23 -08:00
Joe Soroka 0f0c2d9c02 weak redefinition of a symbol should weaken the original 2011-03-07 00:25:27 -08:00
Joe Soroka 38cbb40e90 __typeof(t) should not include storage modifiers of t 2011-03-06 22:32:35 -08:00
grischka 5d55647a3c tccpp: fix problem in preprocess_skip with empty #
for example:

   #ifdef stuff
   # /* some comment */
   #endif
2011-03-06 19:13:12 +01:00
Changming Xu c27e76aa2a unlink outfile first
file mode problem if the outfile already exists
2011-03-03 21:09:18 +08:00
Joe Soroka c93eca4fe4 tccgen: handle __attribute((alias("target"))) 2011-03-03 01:58:45 -08:00
Joe Soroka ce8c1886a5 collapse branch in decl(), making way for next patch 2011-03-03 01:07:36 -08:00
Joe Soroka 3beb383236 handle post-asm-label attributes on variables 2011-03-03 00:55:02 -08:00
Joe Soroka 823f832630 tcc: fix weak attribute handling 2011-03-02 13:31:09 -08:00
Changming Xu 684723488d Replace comment by a blank
- fix my prev commit:
	put declaration above statements to stay c89 compatible
- replace commit by a blank
        #define con(a, b) a/**/b
	this should yield a b, not ab
2011-03-01 09:19:43 +08:00
Changming Xu 185fba4189 tcc -E: append a ' ' after subst
We need a ' ' after subst of m in the following case

    #define m(name,r)  name ## r
    #define m0(a,b,c) int m(a,b)   c
    #define m1(a,b,c) int m(a,b)c
    m0(a, b, c);
    m1(a, b, c);
2011-02-27 10:15:15 +08:00
Joe Soroka 1b85b55059 i386-asm: support "pause" opcode 2011-02-24 09:38:13 -08:00
Joe Soroka bec84fa00a tccasm: support alternate .type syntaxes 2011-02-24 09:24:02 -08:00
Joe Soroka 15b8a57096 tccpp: treat gas comments in .S files as raw text, not tokens 2011-02-23 15:13:08 -08:00
Jaroslav Kysela 85642f887c fix warning for tcctest.c introduced with my last commit 2011-02-22 13:55:21 +01:00
Jaroslav Kysela ab73c9bc4e fix another static struct init issue (arrays with unknown size at end) 2011-02-22 12:15:45 +01:00
Jaroslav Kysela dbefae52b0 Fix complex static initializers (handle additional '}' and '{' brackets)
- added an example to test suite
- the "warning: assignment discards qualifiers from pointer target type"
  is present but harmless
2011-02-22 12:15:44 +01:00
grischka a3ebdd0aeb tccpe: support leading underscore for symbols
To make this the default, enable this line in libtcc.c:tcc_new:

    #if defined(TCC_TARGET_PE) && 0
        s->leading_underscore = 1;

and then recompile tcc and also libtcc1.a
2011-02-13 17:44:12 +01:00
Thomas Preud'homme 11b2d33523 Add support of asm label for variables.
Add support for asm labels for variables, that is the ability to rename
a variable at assembly level with __asm__ ("newname") appended in
its declaration.
See http://gcc.gnu.org/onlinedocs/gcc-4.4.4/gcc/Asm-Labels.html for more
details.
2011-02-09 00:12:57 +01:00
Thomas Preud'homme 32a682b88f Fix fct asm label: only valid for declaration
- Fix function assembly label mechanism introduced in commit
  9b09fc376e to only accept alternative
  name for function declaration.
- merge the code with the one introduced in commit
  264a103610.
- Don't memorize token for asm label but directly the asm label.
2011-02-09 00:12:57 +01:00
Thomas Preud'homme c23400278a Fix incorrect use of basic type as bitflags.
Fix incorrect use of basic types as bitflags and inefficiency in commit
cf36410e30
2011-02-07 23:46:20 +01:00
Thomas Preud'homme cf36410e30 Complain for static fct declared w/o file scope
Error out on static function without file scope and give an explaination
to the user

This is a rewrite of e9406c09a3 but
considering problems raised about static local function pointers in
632ee5a540.
2011-02-06 22:50:05 +01:00
Joe Soroka 3b4b3b75a6 revert "update VT_STRUCT_SHIFT for new VT_VLA" 2011-02-04 17:54:08 -08:00
Thomas Preud'homme db560e9439 Revert "Implement C99 Variable Length Arrays"
This reverts commit a5a50eaafe.
2011-02-05 02:33:46 +01:00
Thomas Preud'homme 38f6467c06 Revert "Reorder increasingly VT_* constants in tcc.h"
This reverts commit 7f00523e2e.
2011-02-05 02:33:46 +01:00
Thomas Preud'homme c1b7267a2f Revert "Make TOK_alloca available for x86-64"
This reverts commit af26ac56bf.
2011-02-05 02:33:45 +01:00
Thomas Preud'homme 4b8470f3ae Revert "Disable C99 VLA when alloca is unavailable."
This reverts commit e3e5d4ad7a.
2011-02-05 02:33:45 +01:00
Joe Soroka b0c50fbd4d update VT_STRUCT_SHIFT for new VT_VLA 2011-02-04 14:33:38 -08:00
grischka 2775173d4d fix crash with get_tok_str() in skip()
crash was triggered by numbers etc. as unexpected token, i.e.
everything that requires additional information with the token.
2011-02-04 20:23:43 +01:00
Thomas Preud'homme e3e5d4ad7a Disable C99 VLA when alloca is unavailable.
* Disable C99 VLA detection when alloca is unavailable and protect the
  new reference to TOK_alloca in decl_initializer in order to compile
  and run for architecture without working alloca.

  Not all code of C99 VLA is commented as it would required many ifdef
  stanza. Just the detection is commented so that VT_VLA is never set
  any type and the C99 VLA code is compiled but never called. However
  vpush_global_sym(&func_old_type, TOK_alloca) in decl_initializer needs
  to be protected by an ifdef stanza as well because it uses TOK_alloca.

* include alloca and C99 VLA tests according to availability of
  TOK_alloca instead of relying on the current architecture
2011-02-04 15:24:48 +01:00
Thomas Preud'homme af26ac56bf Make TOK_alloca available for x86-64
TOK_alloca is now available on x86-64 so make put definition of
TOK_alloca outside the BCHECK conditional macro definition but test if
arch is i386 or x86-64. This makes C99 VLA works (understand compile) on
x86-64.
2011-02-04 13:25:38 +01:00
Thomas Preud'homme 7f00523e2e Reorder increasingly VT_* constants in tcc.h 2011-02-04 02:22:25 +01:00
Thomas Preud'homme a5a50eaafe Implement C99 Variable Length Arrays
Implement C99 Variable Length Arrays in tinycc:
- Support VLA with multiple level (nested vla)
- Update documentation with regards to VT_VLA
- Add a testsuite in tcctest.c
2011-02-04 02:22:25 +01:00
Thomas Preud'homme d35a3ac375 Correct Changelog wrt. to fix attribution
Correctly attribute the patch bringing support for Debian GNU/kFreeBSD
kernels to Pierre Chifflier.
2011-02-04 02:22:15 +01:00
Joe Soroka db6fcce78f tcc: add sysinclude path with -B, like gcc does 2011-02-02 00:00:12 -08:00
Joe Soroka e939c4072c add -isystem cmdline option 2011-02-01 23:32:53 -08:00
Joe Soroka b88677454b tcctest: plugged memleak (was polluting valgrind reports) 2011-02-01 16:05:57 -08:00
Joe Soroka 0d9376da70 tccasm: accept bracketed offset expressions 2011-02-01 15:53:48 -08:00
Joe Soroka 47b4cf22cd tccasm: accept "fmul/fadd st(0),st(n)" (dietlibc ipow/atanh) 2011-02-01 15:49:37 -08:00
Joe Soroka 87d84b7cb8 tccasm: allow one-line prefix+op things like "rep stosb" 2011-02-01 15:37:58 -08:00
Joe Soroka a25325e9be tccasm: define __ASSEMBLER__ for .S files, like gcc does 2011-02-01 15:26:21 -08:00
Joe Soroka 75c6695932 tccpp: fix bug in handling of recursive macros 2011-02-01 13:23:40 -08:00
Joe Soroka cf08675702 weak definitions overrule non-weak prototypes 2011-02-01 09:41:03 -08:00
Joe Soroka c59d3426b8 tccasm: support .weak labels 2011-02-01 08:43:54 -08:00
Joe Soroka 4d5105c8f1 support weak attribute on variables 2011-02-01 00:37:53 -08:00
Joe Soroka 6839382480 asmtest: avoid testing against complex nop alignment in gas
.align #,0x90 in gas ignores the 0x90 and outputs any kind
of nop it feels like.  the one avoided by this patch is a 7
byte nop, which gas has been doing since at least 1999:
http://sourceware.org/ml/binutils/1999-10/msg00083.html

In order to match what gas does, we would need to make
code alignment target-specific, import a lot of code, and
face the question: exactly which gas {version,target,tune}
combo are we trying to match?  see i386_align_code in:
http://sourceware.org/cgi-bin/cvsweb.cgi/src/gas/config/tc-i386.c?annotate=1.460&cvsroot=src

The smart noppery is turned on via the special casing of 0x90
at line 438 in md_do_align in:
http://sourceware.org/cgi-bin/cvsweb.cgi/src/gas/config/tc-i386.h?annotate=1.1&cvsroot=src
2011-01-23 16:46:24 -08:00
Joe Soroka 2047f88334 i386-asm: accept retl as a synonym for ret 2011-01-21 01:35:28 -08:00
Joe Soroka f43fafc680 accept multiple comma separated symbols for .globl/.global directives, like gas does 2011-01-20 02:00:50 -08:00
Sergei Trofimovich 0a50e6c933 tcc.c: fix an error when you build an object file with '-pthread' key set
The problem was partially fixed by Henry in the following patch:

    tcc.c: skip -lpthread when -c option specified

But that patch had one brawback: it is sensitive to argument order,
as decision is taken during commandline parsing:

    $ tcc -c a.c -o a.o -pthread # 1. works fine
    tcc: error: file 'a.c' not found

    $ tcc -pthread -c a.c -o a.o # 2. blows
    tcc: error: cannot specify libraries with -c

This patch fixes case 2.

Signed-off-by: Sergei Trofimovich <st@anti-virus.by>
2011-01-04 11:17:52 +02:00
Sergei Trofimovich d97a25fbdd lib/alloca*: mark ELF stack access flags as nonexecutable
Signed-off-by: Sergei Trofimovich <st@anti-virus.by>
2011-01-04 10:38:52 +02:00
Sergei Trofimovich 288831854b Makefile: respect LDFLAGS (set via --extra-ldflags=)
Signed-off-by: Sergei Trofimovich <st@anti-virus.by>
2011-01-04 10:22:02 +02:00
Shinichiro Hamaji 0ed7ba3f5e Support struct arguments with stdarg.h
- add __builtin_va_arg_types to check how arguments were passed
- move most code of stdarg into libtcc1.c
- remove __builtin_malloc and __builtin_free
- add a test case based on the bug report
  (http://www.mail-archive.com/tinycc-devel@nongnu.org/msg03036.html)
2010-12-28 19:32:40 +09:00
Shinichiro Hamaji 07fd82b411 Make alignments for struct arguments 8 bytes
The ABI (http://www.x86-64.org/documentation/abi.pdf) says
"The size of each argument gets rounded up to eightbytes"
2010-12-28 19:09:59 +09:00
Shinichiro Hamaji 83f0a7b6f8 Test va_copy in tcctest.c 2010-12-28 17:53:56 +09:00
Shinichiro Hamaji 45e1ae2896 One more fix for tcc -run
We don't need r_addend for addresses in PLT.
2010-12-28 17:44:51 +09:00
Shinichiro Hamaji d457addfc3 Fix for the previous commit.
R_X86_64_PLT32 for .so doesn't need DLL relocation.
2010-12-28 16:52:21 +09:00
Shinichiro Hamaji 0ae39f1957 Handle r_addend and R_X86_64_PLT32 properly.
- r_addend should be applied for PLT entries as well
- R_X86_64_PLT32 should be handled just like R_X86_64_PC32
- spec says GLOB_DAT and JUMP_SLOT don't need r_addend (not tested)
  http://www.x86-64.org/documentation/abi.pdf

Now we can -run ELF objects generated by GCC.
2010-12-28 16:14:30 +09:00
Henry Kroll III 48e325df3c configure: --sharedir defaults to /usr/local/share 2010-12-23 06:36:07 -08:00
Henry Kroll III f449f98dec configure: --sharedir documentation root 2010-12-22 04:42:39 -08:00
Henry Kroll III 44f7055a04 make: fix cannot find -ltcc with --disable-rpath 2010-12-21 09:47:17 -08:00
Henry Kroll III 73cb4392ab make: fix install with CC=tcc and potential link problem 2010-12-20 06:20:08 -08:00
Henry Kroll III 90355c78ed configure: add --disable-rpath option (Fedora) 2010-12-20 05:55:54 -08:00
Henry Kroll III 3b3a7cc8ba configure: improvements to option --tccdir 2010-12-20 05:38:59 -08:00
Henry Kroll III d16722481f tcc: add unsupported option -pedantic 2010-12-20 04:23:30 -08:00
Henry Kroll III 8f98573658 tcc: -m32 prefix "win32-" when file extension is present 2010-12-13 00:00:18 -08:00
Henry Kroll III c6f5d819af tcc: fix format string in error handler 2010-12-08 01:05:50 -08:00
Henry Kroll III ffb9fcc5a2 tcc: oops, error handler does not accept format strings 2010-12-08 00:52:33 -08:00
Henry Kroll III b3be007afa tcc: fix -m32 and add -m64 option 2010-12-08 00:27:06 -08:00
Henry Kroll III f3d3ab5a69 tcc: move undef out of if block 2010-12-06 16:36:00 -08:00
Henry Kroll III 10a08a372f Merge branch 'mob' of git://repo.or.cz/tinycc into kroll 2010-12-06 16:25:33 -08:00
Henry Kroll III bb7bb37fe2 tcc: add -m32 option to x86_64 cross compilers 2010-12-06 16:17:20 -08:00
Shinichiro Hamaji f2d7998a96 Copy tcclib.h to tests directory so GCC uses its own headers.
86ffc48129

removed this cp command. However, it was necessary to pass tests on x86-64
because include/stdarg.h is different from GCC's definition on x86-64.
2010-12-07 03:04:45 +09:00
Henry Kroll III 33f86ada92 trim unnecessary bits from my previous 3 commits 2010-12-05 12:47:50 -08:00
Henry Kroll III 1c821373ad make: i386/libtcc1.a for i386-tcc (x86_64 to i386 cross) 2010-12-05 01:04:28 -08:00
Henry Kroll III 50ff5ed790 make: cross compilers exist before using them (fixes parallel make) 2010-12-04 20:15:37 -08:00
Henry Kroll III eb550ed23b tcc: add option -s for gcc compatibility (ignored) 2010-12-04 16:04:33 -08:00
grischka 69fe7585a2 tiny_libmaker: strip leading directory to avoid buffer overrun
The arhdr.ar_name has 16 bytes.  Long object names esp. with
leading directory were causing a buffer overrun which was
detected by glibc.
2010-12-04 16:56:58 +01:00
grischka 21c2a68aa0 tccelf/tcccoff: fix some type conversion warnings 2010-12-04 16:48:15 +01:00
grischka 86ffc48129 make: new lib/Makefile for libtcc1.a on more platforms
win32/64 cross-compilers now build libtcc1.a and install it
together with the windows headers in a 'win32' sub-directory
of TCCDIR.
2010-12-04 16:47:08 +01:00
Henry Kroll III 2ce9a0e2fe needs lib path on bcheck.o fixes undefined symbol '__try__' 2010-12-02 21:43:46 -08:00
Henry Kroll III 3b8b290a45 make cross compilers an expert option in configure --help 2010-12-02 20:33:11 -08:00
Henry Kroll III 94e72b16e7 Add --enable-cygwin option to build on windows with cygwin+mingw32 2010-12-02 20:16:32 -08:00
Henry Kroll III c5d3ce684a Changelog: document some of the recent changes 2010-12-02 14:41:26 -08:00
Henry Kroll III 2215567d7a Makefile: fix clean target, bcheck, add comments 2010-12-02 14:39:34 -08:00
Henry Kroll III a2779556b4 split cross libtcc1.a to separate directories 2010-12-02 03:08:57 -08:00
Henry Kroll III 03b23994f1 tccpe.c: fallback to libtcc1.a for other targets (ARM) 2010-11-30 18:52:43 -08:00
Henry Kroll III 165d136614 Makefile: cleanup leftovers on cross build. really works now 2010-11-30 16:17:37 -08:00
Henry Kroll III 93ef24e6fe Makefile: fix typo and resulting workaround 2010-11-30 16:08:33 -08:00
Henry Kroll III b7d89ff822 Makefile: fix Linux cross install, cleanup 2010-11-30 15:35:32 -08:00
Henry Kroll III c1a437add7 tccpe.c: Makefile: --enable-cross win64 cross library build 2010-11-30 15:15:55 -08:00
Henry Kroll III 9e406656c7 tcc.c: skip -lpthread when -c option specified 2010-11-30 13:58:18 -08:00
Henry Kroll III 0d38e3b663 make CC=tcc install: fixes strip:tcc: File format not recognized 2010-11-30 13:34:09 -08:00
Henry Kroll III 8185070841 Makefile: Add .PHONY targets 2010-11-30 13:09:16 -08:00
Henry Kroll III 52b75c5fa0 Makefile: Put i386-win32-tcc back into --enable-cross install 2010-11-30 02:42:38 -08:00
Henry Kroll III 7b18df138d Makefile: build --config-cross libtcc1.a directly to win32/lib 2010-11-30 01:49:34 -08:00
Henry Kroll III 48a2a8dabd Remove unnecessary $(PROGS_CROSS) from non-cross builds. 2010-11-29 21:09:20 -08:00
Henry Kroll III ddea94daea Makefile: TCC=tcc 2010-11-28 16:11:40 -08:00
Henry Kroll III 9a986f374e configure: allow changing installation directory 2010-11-28 15:54:27 -08:00
Henry Kroll III 3d35b6b36d Makefile: --enable-cross on x86_64 simplified 2010-11-28 15:51:03 -08:00
grischka f332bb3bca tccpe: typedef unsigned int DWORD for cross compilers.
This fixes the i386-win32-tcc cross-compiler on x86-64 linux
platform.

I verified that it produces identical binaries for 'hello_win.exe'
and 'tcc.exe' (tcc compiled by itself) compared to the output of
the native tcc on windows.
2010-11-27 15:02:57 +01:00
grischka 9bd69bf49f build: remove #include "config.h" from target dependent files
This is to make cross build of libtcc1.a easier.
2010-11-26 20:46:54 +01:00
grischka c4eef48025 libtcc: fix s->include_stack_ptr used uninitialized in tcc_open 2010-11-26 20:46:50 +01:00
Henry Kroll III 77e4679aec x86_64: finish biarch path fixup 2010-11-25 10:08:58 -08:00
grischka 44e84bb22a tccpp: fix token pasting ##
This patch takes advantage of new function tcc_open_bf
from previous commit.
2010-11-25 13:30:31 +01:00
grischka e97bf88bad libtcc: new function tcc_open_bf to create BufferedFile
Use it in:
- tcc_open
- tcc_compile_string
- tcc_define_symbol
- tcc_assemble_inline
2010-11-25 13:29:15 +01:00
Henry Kroll III f1c9f649da x86_64: fix --with-libgcc and simplify biarch paths 2010-11-25 02:57:19 -08:00
Henry Kroll III 9036c18170 tcc: Linux -pthread option sets -D_REENTRANT and -lpthread 2010-11-24 16:42:08 -08:00
Henry Kroll III f0afec709e Makefile: x86_64 win32-cross add clean: target 2010-11-06 02:39:28 -07:00
Henry K e250ffb319 Makefile: edit comments 2010-10-29 00:40:16 -07:00
Henry Kroll III 24d6a93f44 Makefile: cross-copiler tcc1.def is now libtcc1.a, ignore mv errors 2010-10-29 00:40:06 -07:00
Henry Kroll III c635976cd7 Force gcc for x86_64 --enable-cross 2010-10-28 22:08:44 -07:00
Henry Kroll III fb498eb925 selinux: correct ftruncate, fix bus error in tcc -run 2010-10-27 03:54:12 -07:00
Ben Bacarisse 14673d0c49 Fix binding of assignment expressions. 2010-10-25 15:40:30 +01:00
grischka 9228842fa7 win32: register SEH in startup code (i386 only)
Needed to handle signal() etc. with msvcrt
2010-10-19 13:15:06 +02:00
Thomas Preud'homme 036d94112d Remove ifdef STT_GNU_IFUNC test in tccrun.c
STT_GNU_IFUNC is always defined (there is no conditional definition of
it) so the ifdef test for STT_GNU_IFUNC in tccrun.c has no reason to
be.
2010-10-10 16:25:41 +02:00
Thomas Preud'homme c1c4040d75 Explicit license in tiny_libmaker.c
Explicit the license in tiny_libmaker.c to LGPLv2. Confirmation of the
license of this file can be found at
http://lists.nongnu.org/archive/html/tinycc-devel/2010-07/msg00004.html
2010-10-07 10:43:22 +02:00
Sergei Trofimovich 872cc430c0 info doc: fix --infodir to respect DESTDIR for 'make install'
info files are introduced by commit 3f829d11ff

This patch helps packagers to avoid problems when install to $DESTDIR

    >>> Starting src_install
    make -j3 bindir=/tmp/paludis/dev-lang-tcc-9999/image//usr/bin libdir=/tmp/paludis/dev-lang-tcc-9999/image//usr/lib tccdir=/tmp/paludis/dev-lang-tcc-9999/image//usr/lib/tcc includedir=/tmp/paludis/dev-lang-tcc-9999/image//usr/include docdir=/tmp/paludis/dev-lang-tcc-9999/image//usr/share/doc/tcc-9999 mandir=/tmp/paludis/dev-lang-tcc-9999/image//usr/share/man install
    mkdir -p "/tmp/paludis/dev-lang-tcc-9999/image//usr/bin"
    install -m755 tcc "/tmp/paludis/dev-lang-tcc-9999/image//usr/bin"
    mkdir -p "/tmp/paludis/dev-lang-tcc-9999/image//usr/share/man/man1"
    install tcc.1 "/tmp/paludis/dev-lang-tcc-9999/image//usr/share/man/man1"
    mkdir -p /usr/share/info
    install  tcc-doc.info "/usr/share/info"
    ACCESS DENIED  open_wr:      /usr/share/info/tcc-doc.info
    install: cannot create regular file `/usr/share/info/tcc-doc.info': Permission denied
    make: *** [install] Error 1
    /usr/libexec/paludis/utils/emake: emake returned error 2

Signed-off-by: Sergei Trofimovich <st@anti-virus.by>
2010-09-21 10:04:05 +03:00
Thomas Preud'homme b8adf0090e Move asm label functions from tccasm.c to tccgen.c
* Move functions parse_asm_str and asm_label_instr from tccasm.c to
  tccgen.c
* Remove CONFIG_TCC_ASM_LABEL macro as asm label are available on all
  archs.
See:
http://lists.nongnu.org/archive/html/tinycc-devel/2010-09/msg00026.html
for the rationale.
2010-09-14 23:21:15 +02:00
Thomas Preud'homme 2596273fce Add support for __REDIRECT_NTH needed with eglibc.
Add support for __REDIRECT_NTH as eglibc makes use of this macro to
redirect long double functions to long functions on arch not supporting
long double.
2010-09-12 01:19:19 +02:00
Thomas Preud'homme 3f829d11ff Add info file creation into tcc build process
Add info file creation in tcc Makefile
2010-09-10 21:19:01 +02:00
Thomas Preud'homme 36f74e46b4 Add missing dircategory and direntry to texi file 2010-09-10 21:11:45 +02:00
Thomas Preud'homme 776364f395 Add support for __FreeBSD_kernel__ kernel
Add support for kfreebsd-i386 and kfreebsd-amd64 Debian arch with
thanks to Pierre Chifflier <chifflier@cpe.fr>.
2010-09-10 21:09:07 +02:00
Thomas Preud'homme 2887f40f76 Add support for GNU/Hurd
+ Add i686-AT386 to the list of x86 platform
+ Define SA_SIGINFO is not defined
2010-09-10 20:55:54 +02:00
Thomas Preud'homme 9b09fc376e Add support of asm label for functions.
Add support for asm labels for functions, that is the ability to rename
a function at assembly level with __asm__ ("newname") appended in
function declaration.
2010-09-10 20:15:03 +02:00
grischka a7fb00e887 tccmain: simplify option help 2010-09-08 19:13:36 +02:00
Shinichiro Hamaji c31dc7aa0c Fix casts from 32bit integer types to 64bit integer types.
This bug was reported in
http://lists.gnu.org/archive/html/tinycc-devel/2010-08/msg00050.html

In this case, we should not emit any code when we cast from VT_FUNC to VT_PTR.
2010-08-31 08:35:31 +09:00
Shinichiro Hamaji 9d347f8742 Probably wrong stack alignment for struct on Win64 2010-08-27 02:49:09 +09:00
Shinichiro Hamaji 1f6781f0ee Fix alignment around struct for SSE.
- Fix a wrong calculation for size of struct
- Handle cases where struct size isn't multple of 8
- Recover vstack after memcpy for pushing struct
- Add a float parameter for struct_assign_test1 to check SSE alignment
2010-08-27 02:32:19 +09:00
grischka 4ab4efd3a6 Revert "implemented C99 for loop with variable declaration"
This reverts commit 433ecdfc9d.

The patch breaks e.g. with
    for ((i = 10); --i;);

In particular to check for a type decl. this is not sufficient:
    if (tok < TOK_UIDENT) {

A future approach to c99 loop variables might instead use:
    if (parse_btype(...)) {

plus refactor function decl() accordingly.
2010-08-21 13:39:12 +02:00
Kirill Smelkov 7901d1e3ad tcc_set_linker: mimic all option forms as supported by GNU ld
Namely

 *  `-option' or `--option'  (start with double or single dash)
 *  `-param=val' or `-param,val'

See GNU ld manual (2.1 Command Line Options)
2010-08-12 23:30:21 +04:00
Thomas Preud'homme bcc9137a10 Add support for indirect functions as externals.
Add link support to use indirect functions defined in external modules
2010-08-09 20:20:09 +02:00
grischka 82c5edb31c Avoid crash with "Avoid a crash with weak symbols for "make test""
This fixes commit 197a6acb30
which fixed commit 95b9a477b6

Also remove useless example files
2010-06-30 20:25:04 +02:00
Thomas Preud'homme 5e6fabefd7 Revert "Use mktemp to generate temp files."
Doesn't seem to work on windows
This reverts commit 27988c5e66.
2010-06-23 14:10:22 +02:00
Thomas Preud'homme 27988c5e66 Use mktemp to generate temp files.
Fix the $RANDOM bashism properly by using mktemp.
mktemp is part of MSYS so this should work on UNIXes and Windows
2010-06-22 18:40:35 +02:00
Kirill Smelkov 9775aea1ab Merge branch 'kirr/tcc-MD' into mob
Hello up there.

I'm trying to change gcc to tcc for faster develpment on slow machines,
and the first obstacle that turned out was lack of dependency generation
on tcc side.

Attached patches try to fix that.

Thanks,
Kirill

* tcc-MD:
  .gitignore += tags
  tcc: Explicitly require -l<lib> for libraries
  Document what tcc_fileextension does
  tcc -E: Let output_default be <file>.o instead of a.out
  tcc: Draft suppoprt for -MD/-MF options
  tcc: Refactor "compute default outfile name" into libtcc function
  Add input files/libs and reloc_output switch to TCCState
  tcc: Fix typo in error (it's '%s', not '%s)
  chmod a-x i386-gen.c
  .gitignore += *.o *.a
  .cvsignore -> .gitignore
2010-06-21 20:50:41 +04:00
Kirill Smelkov 2fe5210a33 .gitignore += tags 2010-06-21 20:49:46 +04:00
Kirill Smelkov 93de8d8038 tcc: Explicitly require -l<lib> for libraries
Previously it was possible to specify e.g. -q<lib> and still link with
lib. Avoid such behaviour by checking for '-l' instead of '-l.'
2010-06-21 20:49:46 +04:00
Kirill Smelkov 441a089aa4 Document what tcc_fileextension does
This is evident, but won't hurt
2010-06-21 20:49:46 +04:00
Kirill Smelkov 1203348302 tcc -E: Let output_default be <file>.o instead of a.out
This affectes where `tcc -E -MD file.c` will place generated dependency
information -- previously, for `tcc -E` output_default was a.out, and so
deps were put into a.d .

Avoid this behaviour, by treating `tcc -E` as `tcc -c` with respect to
output_default computation.

This will not hurt anything else (preprocessor outputs to either stdout,
or to explicitely given (-o <file>) destination, so no default filename
is used here), and on the other hand `tcc -E -MD file.c` now puts
dependencies into file.d (the same behaviour as for gcc -E).

v2:

- restructured condition a bit to make it more clear
2010-06-21 20:49:46 +04:00
Kirill Smelkov 0c928da96d tcc: Draft suppoprt for -MD/-MF options
In build systems, this is used to automatically collect target
dependencies, e.g.

    ---- 8< (hello.c) ----
    #include "hello.h"
    #include <stdio.h>

    int main()
    {
        printf("Hello World!\n");
        return 0;
    }

$ tcc -MD -c hello.c    # -> hello.o, hello.d
$ cat hello.d
hello.o : \
        hello.c \
        hello.h \
        /usr/include/stdio.h \
        /usr/include/features.h \
        /usr/include/bits/predefs.h \
        /usr/include/sys/cdefs.h \
        /usr/include/bits/wordsize.h \
        /usr/include/gnu/stubs.h \
        /usr/include/bits/wordsize.h \
        /usr/include/gnu/stubs-32.h \
        /home/kirr/local/tcc/lib/tcc/include/stddef.h \
        /usr/include/bits/types.h \
        /usr/include/bits/wordsize.h \
        /usr/include/bits/typesizes.h \
        /usr/include/libio.h \
        /usr/include/_G_config.h \
        /usr/include/wchar.h \
        /home/kirr/local/tcc/lib/tcc/include/stdarg.h \
        /usr/include/bits/stdio_lim.h \
        /usr/include/bits/sys_errlist.h \

NOTE: gcc supports -MD only for .c -> .o, but in tcc, we generate
dependencies for whatever action is being taken. E.g. for .c -> exe, the
result will be:

$ tcc -MD -o hello hello.c  # -> hello, hello.d
hello: \
        /usr/lib/crt1.o \
        /usr/lib/crti.o \
        hello.c \
        hello.h \
        /usr/include/stdio.h \
        /usr/include/features.h \
        /usr/include/bits/predefs.h \
        /usr/include/sys/cdefs.h \
        /usr/include/bits/wordsize.h \
        /usr/include/gnu/stubs.h \
        /usr/include/bits/wordsize.h \
        /usr/include/gnu/stubs-32.h \
        /home/kirr/local/tcc/lib/tcc/include/stddef.h \
        /usr/include/bits/types.h \
        /usr/include/bits/wordsize.h \
        /usr/include/bits/typesizes.h \
        /usr/include/libio.h \
        /usr/include/_G_config.h \
        /usr/include/wchar.h \
        /home/kirr/local/tcc/lib/tcc/include/stdarg.h \
        /usr/include/bits/stdio_lim.h \
        /usr/include/bits/sys_errlist.h \
        /usr/lib/libc.so \
        /lib/libc.so.6 \
        /usr/lib/ld-linux.so.2 \
        /lib/ld-linux.so.2 \
        /usr/lib/libc_nonshared.a \
        /lib/libc.so.6 \
        /usr/lib/libc_nonshared.a \
        /home/kirr/local/tcc/lib/tcc/libtcc1.a \
        /usr/lib/crtn.o \

So tcc dependency generator is a bit more clever than one used in gcc :)

Also, I've updated TODO and Changelog (in not-yet-released section).

v2:

(Taking inputs from grischka and me myself)

- put code to generate deps file into a function.
- used tcc_fileextension() instead of open-coding
- generate deps only when compilation/preprocessing was successful

v3:

- use pstrcpy instead of snprintf(buf, sizeof(buf), "%s", ...)
2010-06-21 20:49:02 +04:00
grischka 3ba37e1e3f tccgen: Revert yuanbin's recent patches
This reverts commits 670993..d35138
Maybe these commits fixed something but also seemed to cause problems.
2010-06-21 18:21:44 +02:00
Claudio Bley 433ecdfc9d implemented C99 for loop with variable declaration 2010-06-21 11:57:32 +02:00
Kirill Smelkov bdae4a59c3 tcc: Refactor "compute default outfile name" into libtcc function
Since for upcoming -MD support default _compile_ output file be needed
even when preprocesssing (tcc -E), let's move this code out of one
particular condition block into a common function, so that we could use
it in deps generation code too.

v2:

- As suggested by grischka, moved into libtcc function instead of always
  computing near start of main()
- There is a FIXME about how to return result - I don't want to bother
  callers with allocating temp buffers, not I think it will be a good
  idea to hook default_target to TCCState. Clearly, I'm to used to
  things like std::string and python's str...
2010-06-20 21:36:47 +04:00
Kirill Smelkov a919a373da Add input files/libs and reloc_output switch to TCCState
files[0], and reloc_outpu will be needed for (upcoming in the next
patch) "compute default outfile name" refactored into libtcc function.

Also, since for symmetry and from libification point of view, it makes
some sense to also put all information about what was given as input to
compilation into TCCState, let's not only put files[0], but all
files and all libraries given explicitely by user.

One point: I've used bitfield for reloc_output & trimmed down
output_type to 8 bits so that TCCState stays the same in size, and also
access to output_type is (hopefully) is not slower.

By the way -- as of today, sizeof(TCCState) on i686-pc-linux-gnu is 2884
bytes...
2010-06-20 20:30:01 +04:00
Kirill Smelkov 66b54af8ea tcc: Fix typo in error (it's '%s', not '%s) 2010-06-16 16:51:55 +04:00
Kirill Smelkov 87db8b637e chmod a-x i386-gen.c
No need to keep executable bit on plain C source.
2010-06-16 14:37:30 +04:00
grischka 632ee5a540 Revert "Complain for static fct declared w/o file scope"
This reverts commit e9406c09a3.

We don't want errors for static local function pointers, such as:
  {
    static void (*fn)();
    ...
  }
2010-06-15 17:03:23 +02:00
grischka 10b4802869 Fix "Fix bashims in configure ..." for MSYS
Fixes commit dc265feb63
2010-06-15 17:02:35 +02:00
grischka 5fcd1fef1c Fix last commits: remove CRLF, chmod 644 tccgen.c 2010-06-15 17:02:09 +02:00
yuanbin d351384fdc tccgen: skip ')' in front of ',' for initializer 2010-06-13 14:50:53 +08:00
yuanbin 952e83e0ca tccgen: skip fields from same union 2010-06-13 02:37:28 +08:00
yuanbin d6ce75b4d6 tccgen.c: skip fields from same union 2010-06-13 01:12:36 +08:00
Kirill Smelkov 5344b2e73b .gitignore += *.o *.a
Ignores libtcc.o, libtcc.a and a bunch of other files (see previous
patch for details)
2010-06-12 18:26:37 +04:00
Kirill Smelkov de7a214c17 .cvsignore -> .gitignore
We no longer use CVS, so let's teach Git about what files to ignore...

... though doing `git status` after make + `make test` still gives
untracked content:

    # Untracked files:
    #   (use "git add <file>..." to include in what will be committed)
    #
    #       alloca86-bt.o
    #       alloca86.o
    #       bcheck.o
    #       libtcc.a
    #       libtcc.o
    #       libtcc1.a
    #       libtcc1.o
    #       tcc.o

See next patch about this stuff.
2010-06-12 18:18:19 +04:00
yuanbin dd72577759 tccgen: initial the last member of union 2010-06-11 21:18:05 +08:00
yuanbin 6709933d78 tccgen: initial last member of union 2010-06-11 20:48:33 +08:00
Thomas Preud'homme dc265feb63 Fix bashims in configure and gcctestsuite.sh.
configure and gcctestsuite.sh shell scripts contains bashisms although being
bourne shell script. This patch fixes the following bashisms:
* Use of $RANDOM variable (replaced by reading in /dev/urandom)
* Use == in tests instead of just =
* Use $[] for arithmetic computation istead of $(())
2010-05-26 14:08:29 +02:00
Daniel Glöckner a867f42597 don't discard SHT_((PRE)INIT|FINI)_ARRAY sections 2010-05-15 01:26:56 +02:00
Daniel Glöckner 128e46f91b ARM: add support for R_ARM_V4BX 2010-05-15 01:23:34 +02:00
Daniel Glöckner 20a1cba286 ARM: implement rt_get_caller_pc 2010-05-14 14:22:32 +02:00
Daniel Glöckner 741841d863 ARM: allow jumps > 32MB on -run
This is needed to reach tinycc's PLT from the compiled program.
2010-05-14 13:07:59 +02:00
Daniel Glöckner a64727ba7d append ULL to big constants 2010-05-13 22:18:33 +02:00
Daniel Glöckner 3de023b6c6 ARM: use uint32_t for opcodes
fixes cross compiling on x86_64
2010-05-13 22:17:09 +02:00
Daniel Glöckner 6eac6b7254 Revert "tccpp: Allow local labels to start with a dot"
This reverts commit f740485a5a.

It breaks access to structure elements starting with L
2010-05-06 21:42:37 +02:00
Thomas Preud'homme 8eb86ab78d Add nan, snan and inf float constants 2010-05-06 02:20:35 +02:00
Thomas Preud'homme 2220467fcf Don't load libtcc1 on arch where it doesn't exist
ARM architecture doesn't have any libtcc1 implementation but tcc load
libtcc1.a in all case. This patch add a conditional preprocessor
instruction to load libtcc1.a only when there is an implementation for
the target architecture.
2010-05-01 17:20:28 +02:00
Thomas Preud'homme a28b18fa16 Link alias symbols together
Make sure alias symbols resolve to the same address in program .bss or .data
section. This ensure for example that if a program reference environ (via an
extern char **environ declaration) and the libc change its value via the
__environ alias after the R_ARCH_COPY relocation have been performed, then
the program will see the new value.
2010-05-01 16:45:36 +02:00
Henry Kroll III 036ff17916 reverse another unnecessary change
-m32 is set elsewhere now.
2010-04-29 23:52:20 -07:00
Henry Kroll III 1f62f2253c recursive Makefiles should use $(MAKE), not "make"
add clean: target for lib/tcc1.def
2010-04-29 23:06:23 -07:00
Henry Kroll III c7a4e11bf1 remove superfluous LIBS=. (leftover from work on --disable-statc) 2010-04-28 16:15:19 -07:00
Henry Kroll III 209caeedee Summary of commits + added some brief comments to Makefile
Summary of what was changed or added so far:
    These won't work on Win32

* --disable-static option builds libtcca.so.1.0 and associated simlinks.
  This replaces libtcca.a, which is a static library with a dynamic one.

* --with-selinux option uses mmap to enable tcc -run to work with Selinux.

* attempt to build tcc1.def on i386 / x86_64 when --enable-cross is used.

  If successful, this gets around the "_start not found" or "_winstart not
  found" messages when i386-win32-tcc is run on these systems. I say "if"
  because it gave me fits of trouble on my system and not all others have
  been tested yet. tcc1.def is not a real .def file by the way, but it works,
  so it's kind of a dancing bear at this point. We're not concerned that
  it's getting the steps wrong. We're just happy it's not eating us for lunch.
2010-04-26 23:20:35 -07:00
Henry Kroll III ac0b7d82d8 don't build tcc1.def on Windows.
I think the Windows build portion of the Makefile already
provides their own version. If not, we can remove the check.
2010-04-26 01:27:15 -07:00
Henry Kroll III 765992396f Makefile fixup:
* additional make target for lib/tcc1.def on non-win32 builds
  tcc1.def was formerly lib/libtcc1.a but has bee made into its
  own Makefile target, tcc1.def

* use mv instead of cp on config.h
  this fixes a mistake I made which caused Makefile to rebuild
  all targets every time

* make links from libtcc.so.1.0 to libtcc.so.1 and libtcc.so
2010-04-25 13:34:02 -07:00
Henry Kroll III 07eb850608 make --enable-cross work properly on x86_64
merge more changes from Fedora spec file into Makefile
I did a lot of reading on Makefiles. It should be a lot less hacked now that I got rid of my temporary cross-build script. I had to build i386-win32-tcc as 32 bit in order to use it to build the windows version of libtcc1.a and move that into lib directory. Still testing, but it does build windows fib.exe smoothly now and generates shard lib, libtcc.so.1.0 and test links against it.
2010-04-25 00:35:25 -07:00
Henry Kroll III 1a8e7d9fbb Merge branch 'mob' of ssh://repo.or.cz/srv/git/tinycc into makefile 2010-04-25 00:32:10 -07:00
Henry Kroll III 239fdf0b87 remove make_libtcc1_win32.sh shell script
and merge commands into Makefile
2010-04-24 22:16:39 -07:00
Henry Kroll III eb78e94300 reverse make win32 version of libtcc1.a patch 2010-04-24 21:58:12 -07:00
Henry Kroll III 80b4c698c2 make win32 version of libtcc1.a for cross-compiler on x86 / x86_64 2010-04-24 13:27:56 -07:00
Henry Kroll III b0b29d8013 put tcc in /usr/lib64/tcc on distros that have it 2010-04-24 03:30:46 -07:00
Henry Kroll III 2ab42855cb make --with-selinux work with libtcc, too 2010-04-24 03:28:54 -07:00
Henry Kroll III a4ed587f61 add --disable-static option to build libtcc.so instead of libtcc.a
for distros that want static libs
2010-04-24 02:35:43 -07:00
Henry Kroll III 1578322b06 fix typo in configure 2010-04-24 02:32:41 -07:00
Henry Kroll III 4686236091 i386-win32-tcc fails to build a valid win32 executable if built
on x86_64 using --enable-cross. The easiest way to fix this is
to put -m32 in the Makefile.

Committer: Henry Kroll <henry@comptune.com>

Committer: Henry Kroll <henry@comptune.com>
2010-04-23 18:36:12 -07:00
Henry Kroll III be7e339d8a Use mmap instead of exec mem for Selinux machines. Fixes crash on Fedora. 2010-04-20 23:43:02 -07:00
Thomas Preud'homme a64a6f36a0 Replace malloc+strcpy by tcc_strdup in ld_load_file_list 2010-04-20 22:25:16 +02:00
Thomas Preud'homme 6525a15919 Fix "already done" test in libname_to_filename()
if "(libname == '\0')" should be instead "if (libname != '\0')"
2010-04-20 16:21:13 +02:00
Thomas Preud'homme 4d5fcfb971 Delete unused vtop_saved variable in unary_type 2010-04-20 16:12:41 +02:00
Thomas Preud'homme 3ad3168125 Clean changes introduced by 47abdbd
* Replace the save/load_buffer_state by a dynarray approach:
  - Filename and libname are added to a dynarray when first encountered
  - Load repeatedly the files in the dynarray until no new undefined
    symbol are encountered
* Replace snprintf by sprintf in libname_to_filename
* Use tcc_fileextension in filename_to_libname
* Introduce a tcc_strcpy_part fonction to copy only a subset of a
  string
* Move new_undef_syms declaration from tcc.h to tccelf.c
2010-04-20 16:02:42 +02:00
Timo VJ Lahde 809f489662 WinCE PE subsystem 2010-04-19 16:34:59 +03:00
Timo VJ Lahde 2cb1fd6a10 PE ARM: jump IAT arm code 2010-04-19 15:50:22 +03:00
Sergei Trofimovich 83b0bd3095 libtcc.c: fix compilation failure (inconsistent tcc_add_file_internal)
gcc -o libtcc1.o -c lib/libtcc1.c -O2 -Wall
libtcc.c: At top level:
libtcc.c:1063: error: static declaration of 'tcc_add_file_internal' follows non-static declaration
tccelf.c:2915: note: previous implicit declaration of 'tcc_add_file_internal' was here

Signed-off-by: Sergei Trofimovich <st@anti-virus.by>
2010-04-19 11:46:36 +03:00
Thomas Preud'homme e4ed4e7f4f Support more arm EABI compatible architectures
Add support for:
  - armv5tel
  - armv6j
  - armv7a
2010-04-18 19:29:11 +02:00
Thomas Preud'homme e9406c09a3 Complain for static fct declared w/o file scope
Error out on static function without file scope and give an explaination
to the user
2010-04-15 19:33:47 +02:00
Thomas Preud'homme 47abdbd3d5 Better handle ld scripts
* search file from INPUT and GROUP commands in the library path in
  addition to the current directory
* handle libraries specified by -lfoo options
* Search lib in GROUP command repeatedly
2010-04-15 19:30:00 +02:00
Thomas Preud'homme 6d4166df61 Don't prefix $prefix with $(DESTDIR) in configure
Prefixing $prefix with $(DESTDIR) is an error as it could lead for
example to mandir being equal to $(DESTDIR)$prefix/man where
$prefix itself is equal to $(DESTDIR)/usr/local which make man be equal
to $(DESTDIR)$(DESTDIR)/usr/local/man
2010-04-15 19:10:59 +02:00
Thomas Preud'homme 8de9b7a631 Correctly support all unary expression with sizeof
Unary expression can start with a parenthesis. Thus, the current test
to detect which sizeof form is being parsed is inaccurate. This patch
makes tcc able to handle things like sizeof (x)[1] where x is declared
as char x[5]; wich is a valid unary expression
2010-04-15 19:05:53 +02:00
Romain Francoise 6655e06ec8 Error out on bad char array initialization
Error out with an explicit message when trying to initialize a
character array with something that's not a literal (optionally
enclosed in braces) as per C99 6.7.8:14; thanks to Antti-Juhani
Kaijanaho <ajk@debian.org> who did all the work.
2010-04-15 19:04:25 +02:00
grischka d2cf970a41 tccelf: fix warning 2010-04-13 18:30:01 +02:00
grischka e6f43dd0c6 win32: sys/timeb.h use _ftime instead of _ftime32 2010-04-12 20:56:13 +02:00
Detlef Riekenberg a3b932b3f9 tccgen: Fix broken use of ATTR_MODE
Sorry for that.

--
By by ... Detlef
2010-04-06 22:53:16 +02:00
Detlef Riekenberg 264a103610 tccgen: Detect (but ignore) function redirection
tcc is now able to parse <stdio.h> from gcc, when
__GNUC__ is also defined

--
By by ... Detlef
2010-04-06 00:33:15 +02:00
Detlef Riekenberg 34dabe496f libtcc: Detect (but ignore) -init and -fini for -Wl
--
By by ... Detlef
2010-04-05 22:56:33 +02:00
Detlef Riekenberg 87574de8ed libtcc: Support -soname for the linker
--
By  by ... Detlef
2010-04-05 21:37:54 +02:00
Detlef Riekenberg 78e83d8761 libtcc: Allow multiple options for -Wl separated with ','
I moved the code to libtcc to prepare for a later tiny_ld

--
By by ... Detlef
2010-04-05 21:21:58 +02:00
Detlef Riekenberg a135dd50c6 tccasm: Detect (but ignore) .ident directive
tcc is now able to compile many asm files generated by gcc

--
By by ... Detlef
2010-04-05 12:45:52 +02:00
Detlef Riekenberg 558258a301 tccasm: Detect (but ignore) .size directive
--
By by ... Detlef
2010-04-05 12:43:51 +02:00
Detlef Riekenberg 6825c5db72 tccasm: Support .type directive (only name,@function)
--
By by ... Detlef
2010-04-05 12:31:45 +02:00
Detlef Riekenberg f740485a5a tccpp: Allow local labels to start with a dot
--
By by ... Detlef
2010-04-05 12:28:27 +02:00
Detlef Riekenberg 9ff7a0bc98 tccasm: Detect (but ignore) the .file directive
Some patches, to allow tcc to compile asm sources generated by gcc
and help tcc with the autoconf stuff used in Wine
( http://source.winehq.org/git/wine.git/ )

--
By by ... Detlef
2010-04-05 12:19:49 +02:00
Timo VJ Lähde 197a6acb30 Avoid a crash with weak symbols for "make test"
Patch from the mailing list by Timo VJ Lähde

--
By by ... Detlef
2010-04-05 01:08:49 +02:00
U-UNIT1\dennis d3c432244c generate inc and dec for smaller code 2010-04-03 21:20:34 +03:00
unknown 27bcc8f583 tinylibmaker: On error situation tempfile was not removed 2010-04-03 11:31:38 +03:00
Detlef Riekenberg 95bc36a149 tccpp: Add missing bracket in an error message 2010-03-31 00:42:39 +02:00
Daniel Glöckner 4d05a6319d Catch array[index] with unknown sizeof(*array)
We could support this for index == 0, but GCC doesn't bother, so why should we?
2010-03-15 22:51:19 +01:00
Manuel Simoni 95b9a477b6 weak function symbols 2010-02-27 17:37:59 +01:00
Ali Gholami Rudi d63ec6f20d fill got table for static linking 2010-02-05 08:25:48 +03:30
Alexandre Becoulet b9aeac0a64 Fixed bug which prevent tcc preprocessor to ignore line number directives 2010-02-01 18:08:51 +01:00
Nikos Mavrogiannopoulos 253bad7993 Added patch to detect and use the paths for 64bit libraries as
used by CentOS (affects X86_64 only).
2010-01-28 08:27:38 +01:00
Detlef Riekenberg 900871ca8d Dump the current token in skip(), when it's not the expected token 2010-01-27 00:02:33 +01:00
Detlef Riekenberg 62ba135228 Add support for --help 2010-01-26 22:58:48 +01:00
Detlef Riekenberg a975008ae7 Add support for the __mode__ attribute
--
By by ... Detlef
2010-01-26 22:56:22 +01:00
Detlef Riekenberg 2650584ac4 Recognize -Wl,-Bsymbolic
Without -Bsymbolic, a symbol/function in a *.so can be overridden
by a symbol/function in the main module.
That is the default search order, but not supported by tcc.

With -Bsymbolic, the linker tries to resolve a symbol/function in
the current module first.
The loader in tcc implements this search order.

We do not distinguish -Bsymbolic and -Bsymbolic-function

--
By by ... Detlef
2010-01-26 22:55:14 +01:00
Detlef Riekenberg 5caf6235cf Makefile: Delete tcc-doc.html during 'make distclean' 2010-01-26 22:53:52 +01:00
grischka 3aa26a794e win32: adjust for mingw32 winapi packages
Note: the files in tcc/win32/include/winapi are now from the
mingw-w64 project, however with this fix using mingw32 winapi
should still work.
2010-01-26 22:18:03 +01:00
grischka a40814cc9d tccpp: signal missing #endif error 2010-01-14 21:00:05 +01:00
grischka 4e5170d4a5 tccpp: convert TOK_GET macro into function 2010-01-14 20:59:44 +01:00
grischka 280e20b1d3 tccpp: warn about #define redefinition 2010-01-14 20:59:44 +01:00
grischka e20bf69ac5 win64: defined size_t and ptrdiff_t to unsigned long long 2010-01-14 20:59:43 +01:00
grischka b0abcfde9d win32: cleanup include 2010-01-14 20:59:43 +01:00
grischka 5299142286 x86-64: use uplong for symbol values 2010-01-14 20:59:42 +01:00
grischka 2341ee5142 tccpe: improve dllimport/export and use for tcc_add_symbol 2010-01-14 20:59:42 +01:00
grischka bdb9387a74 win32: readme: add libtcc_test example 2010-01-14 20:59:41 +01:00
grischka 903b6001e7 update Makefiles 2009-12-20 20:34:35 +01:00
grischka 0de95730ad build from multiple objects: fix other targets 2009-12-20 20:33:41 +01:00
grischka b54862406e x86-64: fix gtst, back to only 5 regs for now 2009-12-20 20:33:21 +01:00
grischka 070b86a870 x86-64: use r8/r9 as generic integer registers 2009-12-20 02:19:51 +01:00
grischka 0e5c0ee045 x86-64: use r8,r9 as load/store registers 2009-12-20 01:54:39 +01:00
grischka cda8c41ef3 win32: add size_t to _mingw.h 2009-12-20 01:54:38 +01:00
grischka 4a01eb09d8 use vpushv in some places 2009-12-20 01:54:38 +01:00
grischka 50b040ef83 win64: add tiny unwind data for setjmp/longjmp
This enables native unwind semantics with longjmp on
win64 by putting an entry into the .pdata section for
each compiled fuction.

Also, the function now use a fixed stack and store arguments
into X(%rsp) rather than using push.
2009-12-20 01:54:37 +01:00
grischka 88a3ccab9f allow tcc be build from separate objects
If you want that, run: make NOTALLINONE=1
2009-12-20 01:53:49 +01:00
grischka 7fa712e00c win32: enable bounds checker & exception handler
exception handler borrowed from k1w1. Thanks.
2009-12-19 22:22:43 +01:00
grischka 8bbde91f62 tcc_relocate: revert to 0.9.24 behavior 2009-12-19 22:16:23 +01:00
grischka 3db219477a tccrun: new file
factor out -run support
2009-12-19 22:16:22 +01:00
grischka 41e112360f fix uninitialized warnings with 'type.ref' 2009-12-19 22:16:22 +01:00
grischka 3020a4765d tccpe: with -l try also with "lib" prefix
-lfoo searches: foo.def, libfoo.def, foo.dll, libfoo.dll
2009-12-19 22:16:21 +01:00
grischka 94bf4d2c22 tccpe: improve dllimport 2009-12-19 22:16:21 +01:00
grischka 1308e8ebcf integrate x86_64-asm.c into i386-asm.c
Also, disable 16bit support for now as it causes bugs
in 32bit mode.  #define I386_ASM_16 if you want it.
2009-12-19 22:16:20 +01:00
grischka e81569bc70 tcc: add "-Wl,-rpath=path" option (library search path) 2009-12-19 22:16:20 +01:00
grischka dd3d4f7295 x86-64: fix udiv, add cqto instruction 2009-12-19 22:16:19 +01:00
grischka 1445fea582 tccpe: allow linkage to extern symbols from asm 2009-12-19 22:16:18 +01:00
grischka b5e2238483 tccasm: make VT_VOID symbols ST_NOTYPE, elf-wise
This was confusing objdump such that it did not print
disassembly with -d.

Also, put filename as with C compilation
2009-12-19 22:16:18 +01:00
grischka ab4a4ab25e x86-64: in gv(): ignore second register 2009-12-19 22:16:17 +01:00
grischka d79b867d55 win64: adjust for two args with setjmp(buf,ctx) 2009-12-19 22:16:17 +01:00
Christian Jullien 614790dc14 x86-64: Fix Wrong comparisonbetweenpointerandlongcste
main (int argc, char *argv[])
{
    char *p = (char *)0x12345678ABCD000F;
    int res;
    res = (p != (char *)0x12345678ABCD000F);
    return res;
}
2009-12-19 22:16:16 +01:00
grischka e500c9118a i386-asm: fix imul
With imul the 3rd operand defaults to the 2nd on.  The previous
logic left 'op_type[2]' uninitialized which caused the bug to
show up only sometimes.
2009-12-06 17:41:22 +01:00
grischka 56d6abdb3d tccgen: propagate alignment from typedef
Store (part of) the AttributeDef structure in the (int)sym-r
field of the typedef symbol (kludgy).
2009-12-06 17:37:33 +01:00
372 changed files with 38991 additions and 16801 deletions

View File

@ -1,37 +0,0 @@
tcc_g
tcc
tc2.c
doc
tc3s.c
p3.c
tc1.c
error.c
i386-gen1.c
test.out2
test.out3
web.sh
memdebug.c
bench
Makefile.uClibc
boundtest
prog.ref
test.ref
test.out
tcc-doc.html
ideas
tcctest.ref
linux.tcc
ldtest
libtcc_test
instr.S
p.c
p2.c
tcctest[1234]
test[1234].out
.gdb_history
tcc.1
tcc.pod
config.h
config.mak
config.texi
tests

57
.gitignore vendored 100644
View File

@ -0,0 +1,57 @@
*~
\#*
.#*
*.o
*.a
*.exe
*.dll
*.obj
*.pdb
*.lib
*.exp
*.log
*.bz2
*.zip
.gdb_history
a.out
tcc_g
tcc
*-tcc
libtcc*.def
config*.h
config*.mak
config.texi
conftest*
tags
TAGS
tcc.1
tcc.pod
tcc-doc.html
tcc-doc.info
win32/doc
win32/libtcc
win32/lib/32
win32/lib/64
win32/include/float.h
win32/include/stdarg.h
win32/include/stdbool.h
win32/include/stddef.h
win32/include/varargs.h
win32/include/tcclib.h
tests/tcctest[1234]
tests/tcctest.gcc
tests/*.out*
tests/*.ref
tests/*.txt
tests/*.gcc
tests/*-cc*
tests/*-tcc*
tests/libtcc_test
tests/asm-c-connect
tests/asm-c-connect-sep
tests/vla_test
tests/hello
tests/tests2/fred.txt

View File

@ -1,7 +1,78 @@
Version 0.9.27:
User interface:
- -x[c|a|n] filetype option (Sergey Korshunoff)
- -P[1], -dD, -dM preprocessor options (Sergey Korshunoff)
- -Wl,-(no-)whole-archive linker option (Reuben Thomas)
- -mms-bitfields option (David Mertens)
- -include <file> option (Michael Matz)
- -mno-sse on x86-64 disables use of SSE instructions
- @listfile support (Vlad Vissoultchev)
- tcc -ar/-impdef - formerly tiny_xxx tools integrated (grischka)
- CPATH, C_INCLUDE_PATH and LIBRARY_PATH environment variables support
(Andrew Aladjev, Urs Janssen)
Platforms:
- new AARCH64 (arm64) target (Edmund Grimley Evans)
- vastly improved support for ARM hard float calling convention
(Thomas Preud'homme, Daniel Glöckner)
- provide a runtime library for ARM (Thomas Preud'homme)
- many x86_64 ABI fixes incl. XMM register passing and tests (James Lyon)
- ABI tests with native compiler using libtcc (James Lyon)
- UNICODE startup code supports wmain and wWinMain (YX Hao)
- shared libraries for x86_64 (Michael Matz)
- Bootstrap native Windows 32/64 compiler using Cygwin+gcc (Christian Jullien)
Features:
- VLA (variable length array) improved (James Lyon, Pip Cet)
- import functions by ordinal in .def files on windows (YX Hao)
- x86/x86_64 assembler much improved (Michael Matz)
- simple dead code suppression (Edmund Grimley Evans, Michael Matz, grischka)
- implement round/fmin/fmax etc. math on windows (Avi Halachmi)
- #pragma once support (Sergey Korshunoff, Vlad Vissoultchev, ...)
- switch/case code improved (Zdenek Pavlas)
- ~15% faster by TinyAlloc fast memory allocator (Vlad Vissoultchev)
- standard conforming (and GCC compatible) struct initialization
(Michael Matz)
- bit-field layout made compatible with GCC (Michael Matz)
- UTF8 in string literals supported (Zdenek Pavlas)
_ _Generic(...) supported (Matthias Gatto)
Licensing:
- TinyCC partly relicensed to MIT license (See RELICENSING file).
version 0.9.26:
User interface:
- -MD/-MF (automatically generate dependencies for make)
- -pthread option (same as -D_REENTRANT -lpthread) (Henry Kroll III)
- -m32/-m64 to re-exec cross compiler (Henry Kroll III)
- -Wl, Mimic all GNU -option forms supported by ld (Kirill Smelkov)
- new LIBTCCAPI tcc_set_options() (grischka)
Platforms:
- Many improvements for x86-64 target (Shinichiro Hamaji, Michael Matz, grischka)
- x86-64 assembler (Frederic Feret)
- Many improvements for ARM target (Daniel Glöckner, Thomas Preud'homme)
- Support WinCE PE ARM (Timo VJ Lahde)
- Support ARM hardfloat calling convention (Thomas Preud'homme)
- Support SELinux (Security-Enhanced Linux) (Henry Kroll III)
- Support Debian GNU/kFreeBSD kernels (Pierre Chifflier)
- Support GNU/Hurd kernels (Thomas Preud'homme)
- Support OSX (tcc -run only) (Milutin Jovanovic)
- Support multiarch configuration (Thomas Preud'homme)
- Support out-of-tree build (Akim Demaille)
Features:
- C99 variable length arrays (Thomas Preud'homme & Joe Soroka)
- Asm labels for variables and functions (Thomas Preud'homme)
- STT_GNU_IFUNC (Indirect functions as externals) (Thomas Preud'homme)
- More tests (tests2) (Milutin Jovanovic)
version 0.9.25:
- first support for x86-64 target (Shinichiro Hamaji)
- support オClibc
- support µClibc
- split tcc.c into tcc.h libtcc.c tccpp.c tccgen.c tcc.c
- improved preprocess output with linenumbers and spaces preserved
- tcc_relocate now copies code into user buffer

71
CodingStyle 100644
View File

@ -0,0 +1,71 @@
In general, use the same coding style as the surrounding code.
However, do not make any unnecessary changes as that complicates
the VCS (git) history and makes it harder to merge patches. So
do not modify code just to make it conform to a coding style.
Indentation
Turn on a "fill tabs with spaces" option in your editor.
Remove tabs and trailing spaces from any lines that are modified.
Note that some files are indented with 2 spaces (when they
have large indentation) while most are indented with 4 spaces.
Language
TCC is mostly implemented in C90. Do not use any non-C90 features
that are not already in use.
Non-C90 features currently in use, as revealed by
./configure --extra-cflags="-std=c90 -Wpedantic":
- long long (including "LL" constants)
- inline
- very long string constants
- assignment between function pointer and 'void *'
- "//" comments
- empty macro arguments (DEF_ASMTEST in i386-tok.h)
- unnamed struct and union fields (in struct Sym), a C11 feature
Testing
A simple "make test" is sufficient for some simple changes. However,
before committing a change consider performing some of the following
additional tests:
- Build and run "make test" on several architectures.
- Build with ./configure --enable-cross.
- If the generation of relocations has been changed, try compiling
with TCC and linking with GCC/Clang. If the linker has been
modified, try compiling with GCC/Clang and linking with TCC.
- Test with ASan/UBSan to detect memory corruption and undefined behaviour:
make clean
./configure
make
make test
cp libtcc.a libtcc.a.hide
make clean
./configure --extra-cflags="-fsanitize=address,undefined -g"
make
cp libtcc.a.hide libtcc.a
make test
- Test with Valgrind to detect some uses of uninitialised values:
make clean
./configure
make
# On Intel, because Valgrind does floating-point arithmetic differently:
( cd tests && gcc -I.. tcctest.c && valgrind -q ./a.out > test.ref )
make test TCC="valgrind -q --leak-check=full `pwd`/tcc -B`pwd` -I`pwd`"
(Because of how VLAs are implemented, invalid reads are expected
with 79_vla_continue.)

594
Makefile
View File

@ -1,281 +1,403 @@
# --------------------------------------------------------------------------
#
# Tiny C Compiler Makefile
#
TOP ?= .
ifndef TOP
TOP = .
INCLUDED = no
endif
include $(TOP)/config.mak
CFLAGS+=-g -Wall
CFLAGS_P=$(CFLAGS) -pg -static -DCONFIG_TCC_STATIC
LIBS_P=
ifneq ($(GCC_MAJOR),2)
CFLAGS+=-fno-strict-aliasing
ifneq ($(GCC_MAJOR),3)
CFLAGS+=-Wno-pointer-sign -Wno-sign-compare -D_FORTIFY_SOURCE=0
endif
ifeq (-$(CC)-$(GCC_MAJOR)-$(findstring $(GCC_MINOR),56789)-,-gcc-4--)
CFLAGS += -D_FORTIFY_SOURCE=0
endif
ifeq ($(ARCH),i386)
CFLAGS+=-mpreferred-stack-boundary=2
ifeq ($(GCC_MAJOR),2)
CFLAGS+=-m386 -malign-functions=0
else
CFLAGS+=-march=i386 -falign-functions=0
endif
endif
ifndef CONFIG_WIN32
LIBS=-lm
ifndef CONFIG_NOLDL
LIBS+=-ldl
endif
endif
ifeq ($(ARCH),i386)
NATIVE_TARGET=-DTCC_TARGET_I386
LIBTCC1=libtcc1.a
BCHECK_O=bcheck.o
ALLOCA_O=alloca86.o alloca86-bt.o
else
ifeq ($(ARCH),x86-64)
NATIVE_TARGET=-DTCC_TARGET_X86_64
LIBTCC1=libtcc1.a
BCHECK_O=
ALLOCA_O=alloca86_64.o
endif
endif
ifeq ($(ARCH),arm)
NATIVE_TARGET=-DTCC_TARGET_ARM
NATIVE_TARGET+=$(if $(wildcard /lib/ld-linux.so.3),-DTCC_ARM_EABI)
NATIVE_TARGET+=$(if $(shell grep -l "^Features.* \(vfp\|iwmmxt\) " /proc/cpuinfo),-DTCC_ARM_VFP)
endif
LIBTCC = libtcc.a
LIBTCC1 = libtcc1.a
LINK_LIBTCC =
LIBS =
CFLAGS += -I$(TOP)
CFLAGS += $(CPPFLAGS)
VPATH = $(TOPSRC)
ifdef CONFIG_WIN32
NATIVE_TARGET+=-DTCC_TARGET_PE
BCHECK_O=
endif
ifneq ($(wildcard /lib/ld-uClibc.so.0),)
NATIVE_TARGET+=-DTCC_UCLIBC
BCHECK_O=
endif
ifdef CONFIG_USE_LIBGCC
LIBTCC1=
endif
ifeq ($(TOP),.)
PROGS=tcc$(EXESUF)
I386_CROSS = i386-tcc$(EXESUF)
WIN32_CROSS = i386-win32-tcc$(EXESUF)
WIN64_CROSS = x86_64-win32-tcc$(EXESUF)
WINCE_CROSS = arm-win32-tcc$(EXESUF)
X64_CROSS = x86_64-tcc$(EXESUF)
ARM_CROSS = arm-tcc-fpa$(EXESUF) arm-tcc-fpa-ld$(EXESUF) \
arm-tcc-vfp$(EXESUF) arm-tcc-vfp-eabi$(EXESUF)
C67_CROSS = c67-tcc$(EXESUF)
CORE_FILES = tcc.c libtcc.c tccpp.c tccgen.c tccelf.c tccasm.c \
tcc.h config.h libtcc.h tcctok.h
I386_FILES = $(CORE_FILES) i386-gen.c i386-asm.c i386-asm.h i386-tok.h
WIN32_FILES = $(CORE_FILES) i386-gen.c i386-asm.c i386-asm.h i386-tok.h tccpe.c
WIN64_FILES = $(CORE_FILES) x86_64-gen.c x86_64-asm.c x86_64-asm.h x86_64-tok.h tccpe.c
WINCE_FILES = $(CORE_FILES) arm-gen.c tccpe.c
X86_64_FILES = $(CORE_FILES) x86_64-gen.c x86_64-asm.c x86_64-asm.h x86_64-tok.h
ARM_FILES = $(CORE_FILES) arm-gen.c
C67_FILES = $(CORE_FILES) c67-gen.c tcccoff.c
ifdef CONFIG_WIN32
PROGS+=tiny_impdef$(EXESUF) tiny_libmaker$(EXESUF)
NATIVE_FILES=$(WIN32_FILES)
PROGS_CROSS=$(WIN64_CROSS) $(I386_CROSS) $(X64_CROSS) $(ARM_CROSS) $(C67_CROSS)
ifneq ($(CONFIG_static),yes)
LIBTCC = libtcc$(DLLSUF)
LIBTCCDEF = libtcc.def
endif
CFGWIN = -win
NATIVE_TARGET = $(ARCH)-win$(if $(findstring arm,$(ARCH)),ce,32)
else
ifeq ($(ARCH),i386)
NATIVE_FILES=$(I386_FILES)
PROGS_CROSS=$(X64_CROSS) $(WIN32_CROSS) $(WIN64_CROSS) $(ARM_CROSS) $(C67_CROSS)
else
ifeq ($(ARCH),x86-64)
NATIVE_FILES=$(X86_64_FILES)
PROGS_CROSS=$(I386_CROSS) $(WIN32_CROSS) $(WIN64_CROSS) $(ARM_CROSS) $(C67_CROSS)
else
ifeq ($(ARCH),arm)
NATIVE_FILES=$(ARM_FILES)
PROGS_CROSS=$(I386_CROSS) $(X64_CROSS) $(WIN32_CROSS) $(WIN64_CROSS) $(C67_CROSS)
LIBS=-lm
ifneq ($(CONFIG_ldl),no)
LIBS+=-ldl
endif
# make libtcc as static or dynamic library?
ifeq ($(CONFIG_static),no)
LIBTCC=libtcc$(DLLSUF)
export LD_LIBRARY_PATH := $(CURDIR)/$(TOP)
ifneq ($(CONFIG_rpath),no)
LINK_LIBTCC += -Wl,-rpath,"$(libdir)"
endif
endif
CFGWIN =-unx
NATIVE_TARGET = $(ARCH)
ifdef CONFIG_OSX
NATIVE_TARGET = $(ARCH)-osx
LDFLAGS += -flat_namespace -undefined warning
export MACOSX_DEPLOYMENT_TARGET := 10.2
endif
endif
# run local version of tcc with local libraries and includes
TCCFLAGS-unx = -B$(TOP) -I$(TOPSRC)/include -I$(TOPSRC) -I$(TOP)
TCCFLAGS-win = -B$(TOPSRC)/win32 -I$(TOPSRC)/include -I$(TOPSRC) -I$(TOP) -L$(TOP)
TCCFLAGS = $(TCCFLAGS$(CFGWIN))
TCC = $(TOP)/tcc$(EXESUF) $(TCCFLAGS)
ifdef CONFIG_OSX
TCCFLAGS += -D_ANSI_SOURCE
endif
CFLAGS_P = $(CFLAGS) -pg -static -DCONFIG_TCC_STATIC -DTCC_PROFILE
LIBS_P = $(LIBS)
LDFLAGS_P = $(LDFLAGS)
CONFIG_$(ARCH) = yes
NATIVE_DEFINES_$(CONFIG_i386) += -DTCC_TARGET_I386
NATIVE_DEFINES_$(CONFIG_x86_64) += -DTCC_TARGET_X86_64
NATIVE_DEFINES_$(CONFIG_WIN32) += -DTCC_TARGET_PE
NATIVE_DEFINES_$(CONFIG_OSX) += -DTCC_TARGET_MACHO
NATIVE_DEFINES_$(CONFIG_uClibc) += -DTCC_UCLIBC
NATIVE_DEFINES_$(CONFIG_musl) += -DTCC_MUSL
NATIVE_DEFINES_$(CONFIG_libgcc) += -DCONFIG_USE_LIBGCC
NATIVE_DEFINES_$(CONFIG_selinux) += -DHAVE_SELINUX
NATIVE_DEFINES_$(CONFIG_arm) += -DTCC_TARGET_ARM
NATIVE_DEFINES_$(CONFIG_arm_eabihf) += -DTCC_ARM_EABI -DTCC_ARM_HARDFLOAT
NATIVE_DEFINES_$(CONFIG_arm_eabi) += -DTCC_ARM_EABI
NATIVE_DEFINES_$(CONFIG_arm_vfp) += -DTCC_ARM_VFP
NATIVE_DEFINES_$(CONFIG_arm64) += -DTCC_TARGET_ARM64
NATIVE_DEFINES += $(NATIVE_DEFINES_yes)
ifeq ($(INCLUDED),no)
# --------------------------------------------------------------------------
# running top Makefile
PROGS = tcc$(EXESUF)
TCCLIBS = $(LIBTCC1) $(LIBTCC) $(LIBTCCDEF)
TCCDOCS = tcc.1 tcc-doc.html tcc-doc.info
all: $(PROGS) $(TCCLIBS) $(TCCDOCS)
# cross compiler targets to build
TCC_X = i386 x86_64 i386-win32 x86_64-win32 x86_64-osx arm arm64 arm-wince c67
# TCC_X += arm-fpa arm-fpa-ld arm-vfp arm-eabi
# cross libtcc1.a targets to build
LIBTCC1_X = i386 x86_64 i386-win32 x86_64-win32 x86_64-osx arm arm64 arm-wince
PROGS_CROSS = $(foreach X,$(TCC_X),$X-tcc$(EXESUF))
LIBTCC1_CROSS = $(foreach X,$(LIBTCC1_X),$X-libtcc1.a)
# build cross compilers & libs
cross: $(LIBTCC1_CROSS) $(PROGS_CROSS)
# build specific cross compiler & lib
cross-%: %-tcc$(EXESUF) %-libtcc1.a ;
install: ; @$(MAKE) --no-print-directory install$(CFGWIN)
install-strip: ; @$(MAKE) --no-print-directory install$(CFGWIN) CONFIG_strip=yes
uninstall: ; @$(MAKE) --no-print-directory uninstall$(CFGWIN)
ifdef CONFIG_cross
all : cross
endif
# --------------------------------------------
T = $(or $(CROSS_TARGET),$(NATIVE_TARGET),unknown)
X = $(if $(CROSS_TARGET),$(CROSS_TARGET)-)
DEF-i386 = -DTCC_TARGET_I386
DEF-x86_64 = -DTCC_TARGET_X86_64
DEF-i386-win32 = -DTCC_TARGET_PE -DTCC_TARGET_I386
DEF-x86_64-win32= -DTCC_TARGET_PE -DTCC_TARGET_X86_64
DEF-x86_64-osx = -DTCC_TARGET_MACHO -DTCC_TARGET_X86_64
DEF-arm-wince = -DTCC_TARGET_PE -DTCC_TARGET_ARM -DTCC_ARM_EABI -DTCC_ARM_VFP -DTCC_ARM_HARDFLOAT
DEF-arm64 = -DTCC_TARGET_ARM64
DEF-c67 = -DTCC_TARGET_C67 -w # disable warnigs
DEF-arm-fpa = -DTCC_TARGET_ARM
DEF-arm-fpa-ld = -DTCC_TARGET_ARM -DLDOUBLE_SIZE=12
DEF-arm-vfp = -DTCC_TARGET_ARM -DTCC_ARM_VFP
DEF-arm-eabi = -DTCC_TARGET_ARM -DTCC_ARM_VFP -DTCC_ARM_EABI
DEF-arm-eabihf = -DTCC_TARGET_ARM -DTCC_ARM_VFP -DTCC_ARM_EABI -DTCC_ARM_HARDFLOAT
DEF-arm = $(DEF-arm-eabihf)
DEF-$(NATIVE_TARGET) = $(NATIVE_DEFINES)
DEFINES += $(DEF-$T) $(DEF-all)
DEFINES += $(if $(ROOT-$T),-DCONFIG_SYSROOT="\"$(ROOT-$T)\"")
DEFINES += $(if $(CRT-$T),-DCONFIG_TCC_CRTPREFIX="\"$(CRT-$T)\"")
DEFINES += $(if $(LIB-$T),-DCONFIG_TCC_LIBPATHS="\"$(LIB-$T)\"")
DEFINES += $(if $(INC-$T),-DCONFIG_TCC_SYSINCLUDEPATHS="\"$(INC-$T)\"")
DEFINES += $(DEF-$(or $(findstring win,$T),unx))
ifneq ($(X),)
ifeq ($(CONFIG_WIN32),yes)
DEF-win += -DTCC_LIBTCC1="\"$(X)libtcc1.a\""
DEF-unx += -DTCC_LIBTCC1="\"lib/$(X)libtcc1.a\""
else
DEF-all += -DTCC_LIBTCC1="\"$(X)libtcc1.a\""
DEF-win += -DCONFIG_TCCDIR="\"$(tccdir)/win32\""
endif
endif
ifdef CONFIG_CROSS
PROGS+=$(PROGS_CROSS)
# include custom configuration (see make help)
-include config-extra.mak
CORE_FILES = tcc.c tcctools.c libtcc.c tccpp.c tccgen.c tccelf.c tccasm.c tccrun.c
CORE_FILES += tcc.h config.h libtcc.h tcctok.h
i386_FILES = $(CORE_FILES) i386-gen.c i386-link.c i386-asm.c i386-asm.h i386-tok.h
i386-win32_FILES = $(i386_FILES) tccpe.c
x86_64_FILES = $(CORE_FILES) x86_64-gen.c x86_64-link.c i386-asm.c x86_64-asm.h
x86_64-win32_FILES = $(x86_64_FILES) tccpe.c
x86_64-osx_FILES = $(x86_64_FILES)
arm_FILES = $(CORE_FILES) arm-gen.c arm-link.c arm-asm.c
arm-wince_FILES = $(arm_FILES) tccpe.c
arm64_FILES = $(CORE_FILES) arm64-gen.c arm64-link.c
c67_FILES = $(CORE_FILES) c67-gen.c c67-link.c tcccoff.c
# libtcc sources
LIBTCC_SRC = $(filter-out tcc.c tcctools.c,$(filter %.c,$($T_FILES)))
ifeq ($(ONE_SOURCE),yes)
LIBTCC_OBJ = $(X)libtcc.o
LIBTCC_INC = $($T_FILES)
TCC_FILES = $(X)tcc.o
tcc.o : DEFINES += -DONE_SOURCE=0
else
LIBTCC_OBJ = $(patsubst %.c,$(X)%.o,$(LIBTCC_SRC))
LIBTCC_INC = $(filter %.h %-gen.c %-link.c,$($T_FILES))
TCC_FILES = $(X)tcc.o $(LIBTCC_OBJ)
$(TCC_FILES) : DEFINES += -DONE_SOURCE=0
endif
all: $(PROGS) $(LIBTCC1) $(BCHECK_O) libtcc.a tcc-doc.html tcc.1 libtcc_test$(EXESUF)
# target specific object rule
$(X)%.o : %.c $(LIBTCC_INC)
$(CC) -o $@ -c $< $(DEFINES) $(CFLAGS)
# additional dependencies
$(X)tcc.o : tcctools.c
# Host Tiny C Compiler
tcc$(EXESUF): $(NATIVE_FILES)
$(CC) -o $@ $< $(NATIVE_TARGET) $(CFLAGS) $(LIBS)
tcc$(EXESUF): tcc.o $(LIBTCC)
$(CC) -o $@ $^ $(LIBS) $(LDFLAGS) $(LINK_LIBTCC)
# Cross Tiny C Compilers
i386-tcc$(EXESUF): $(I386_FILES)
$(CC) -o $@ $< -DTCC_TARGET_I386 $(CFLAGS) $(LIBS)
%-tcc$(EXESUF): FORCE
@$(MAKE) --no-print-directory $@ CROSS_TARGET=$* ONE_SOURCE=$(or $(ONE_SOURCE),yes)
i386-win32-tcc$(EXESUF): $(WIN32_FILES)
$(CC) -o $@ $< -DTCC_TARGET_PE $(CFLAGS) $(LIBS)
x86_64-win32-tcc$(EXESUF): $(WIN32_FILES)
$(CC) -o $@ $< -DTCC_TARGET_PE -DTCC_TARGET_X86_64 $(CFLAGS) $(LIBS)
x86_64-tcc$(EXESUF): $(X86_64_FILES)
$(CC) -o $@ $< -DTCC_TARGET_X86_64 $(CFLAGS) $(LIBS)
c67-tcc$(EXESUF): $(C67_FILES)
$(CC) -o $@ $< -DTCC_TARGET_C67 $(CFLAGS) $(LIBS)
arm-win32-tcc$(EXESUF): $(WIN32_FILES)
$(CC) -o $@ $< -DTCC_TARGET_PE -DTCC_TARGET_ARM $(CFLAGS) $(LIBS)
arm-tcc-fpa$(EXESUF): $(ARM_FILES)
$(CC) -o $@ $< -DTCC_TARGET_ARM $(CFLAGS) $(LIBS)
arm-tcc-fpa-ld$(EXESUF): $(ARM_FILES)
$(CC) -o $@ $< -DTCC_TARGET_ARM -DLDOUBLE_SIZE=12 $(CFLAGS) $(LIBS)
arm-tcc-vfp$(EXESUF): $(ARM_FILES)
$(CC) -o $@ $< -DTCC_TARGET_ARM -DTCC_ARM_VFP $(CFLAGS) $(LIBS)
arm-tcc-vfp-eabi$(EXESUF): $(ARM_FILES)
$(CC) -o $@ $< -DTCC_TARGET_ARM -DTCC_ARM_EABI $(CFLAGS) $(LIBS)
# libtcc generation and test
libtcc.o: $(NATIVE_FILES)
$(CC) -o $@ -c libtcc.c $(NATIVE_TARGET) $(CFLAGS)
libtcc.a: libtcc.o
$(AR) rcs $@ $^
libtcc_test$(EXESUF): tests/libtcc_test.c libtcc.a
$(CC) -o $@ $^ -I. $(CFLAGS) $(LIBS)
libtest: libtcc_test$(EXESUF) $(LIBTCC1)
./libtcc_test$(EXESUF) lib_path=.
$(CROSS_TARGET)-tcc$(EXESUF): $(TCC_FILES)
$(CC) -o $@ $^ $(LIBS) $(LDFLAGS)
# profiling version
tcc_p$(EXESUF): $(NATIVE_FILES)
$(CC) -o $@ $< $(NATIVE_TARGET) $(CFLAGS_P) $(LIBS_P)
tcc_p$(EXESUF): $($T_FILES)
$(CC) -o $@ $< $(DEFINES) $(CFLAGS_P) $(LIBS_P) $(LDFLAGS_P)
# windows utilities
tiny_impdef$(EXESUF): win32/tools/tiny_impdef.c
$(CC) -o $@ $< $(CFLAGS)
tiny_libmaker$(EXESUF): win32/tools/tiny_libmaker.c
$(CC) -o $@ $< $(CFLAGS)
# TinyCC runtime libraries
LIBTCC1_OBJS=libtcc1.o $(ALLOCA_O)
LIBTCC1_CC=$(CC)
VPATH+=lib
ifdef CONFIG_WIN32
# for windows, we must use TCC because we generate ELF objects
LIBTCC1_OBJS+=crt1.o wincrt1.o dllcrt1.o dllmain.o chkstk.o
LIBTCC1_CC=./tcc.exe -Bwin32 -Iinclude $(NATIVE_TARGET)
VPATH+=win32/lib
endif
%.o: %.c
$(LIBTCC1_CC) -o $@ -c $< -O2 -Wall
%.o: %.S
$(LIBTCC1_CC) -o $@ -c $<
libtcc1.a: $(LIBTCC1_OBJS)
# static libtcc library
libtcc.a: $(LIBTCC_OBJ)
$(AR) rcs $@ $^
bcheck.o: bcheck.c
$(CC) -o $@ -c $< -O2 -Wall
# dynamic libtcc library
libtcc.so: $(LIBTCC_OBJ)
$(CC) -shared -Wl,-soname,$@ -o $@ $^ $(LDFLAGS)
# install
TCC_INCLUDES = stdarg.h stddef.h stdbool.h float.h varargs.h tcclib.h
INSTALL=install
libtcc.so: CFLAGS+=-fPIC
libtcc.so: LDFLAGS+=-fPIC
ifndef CONFIG_WIN32
install: $(PROGS) $(LIBTCC1) $(BCHECK_O) libtcc.a tcc.1 tcc-doc.html
mkdir -p "$(bindir)"
$(INSTALL) -s -m755 $(PROGS) "$(bindir)"
mkdir -p "$(mandir)/man1"
$(INSTALL) tcc.1 "$(mandir)/man1"
mkdir -p "$(tccdir)"
mkdir -p "$(tccdir)/include"
ifneq ($(LIBTCC1),)
$(INSTALL) -m644 $(LIBTCC1) "$(tccdir)"
endif
ifneq ($(BCHECK_O),)
$(INSTALL) -m644 $(BCHECK_O) "$(tccdir)"
endif
$(INSTALL) -m644 $(addprefix include/,$(TCC_INCLUDES)) "$(tccdir)/include"
mkdir -p "$(docdir)"
$(INSTALL) -m644 tcc-doc.html "$(docdir)"
mkdir -p "$(libdir)"
$(INSTALL) -m644 libtcc.a "$(libdir)"
mkdir -p "$(includedir)"
$(INSTALL) -m644 libtcc.h "$(includedir)"
# windows dynamic libtcc library
libtcc.dll : $(LIBTCC_OBJ)
$(CC) -shared -o $@ $^ $(LDFLAGS)
libtcc.dll : DEFINES += -DLIBTCC_AS_DLL
uninstall:
rm -fv $(foreach P,$(PROGS),"$(bindir)/$P")
rm -fv $(foreach P,$(LIBTCC1) $(BCHECK_O),"$(tccdir)/$P")
rm -fv $(foreach P,$(TCC_INCLUDES),"$(tccdir)/include/$P")
rm -fv "$(docdir)/tcc-doc.html" "$(mandir)/man1/tcc.1"
rm -fv "$(libdir)/libtcc.a" "$(includedir)/libtcc.h"
# import file for windows libtcc.dll
libtcc.def : libtcc.dll tcc$(EXESUF)
$(XTCC) -impdef $< -o $@
XTCC ?= ./tcc$(EXESUF)
else
install: $(PROGS) $(LIBTCC1) libtcc.a tcc-doc.html
mkdir -p "$(tccdir)"
mkdir -p "$(tccdir)/lib"
mkdir -p "$(tccdir)/include"
mkdir -p "$(tccdir)/examples"
mkdir -p "$(tccdir)/doc"
mkdir -p "$(tccdir)/libtcc"
$(INSTALL) -s -m755 $(PROGS) "$(tccdir)"
$(INSTALL) -m644 $(LIBTCC1) win32/lib/*.def "$(tccdir)/lib"
cp -r win32/include/. "$(tccdir)/include"
cp -r win32/examples/. "$(tccdir)/examples"
$(INSTALL) -m644 $(addprefix include/,$(TCC_INCLUDES)) "$(tccdir)/include"
$(INSTALL) -m644 tcc-doc.html win32/tcc-win32.txt "$(tccdir)/doc"
$(INSTALL) -m644 libtcc.a libtcc.h "$(tccdir)/libtcc"
endif
# TinyCC runtime libraries
libtcc1.a : tcc$(EXESUF) FORCE
@$(MAKE) -C lib DEFINES='$(DEF-$T)'
# Cross libtcc1.a
%-libtcc1.a : %-tcc$(EXESUF) FORCE
@$(MAKE) -C lib DEFINES='$(DEF-$*)' CROSS_TARGET=$*
.PRECIOUS: %-libtcc1.a
FORCE:
# --------------------------------------------------------------------------
# documentation and man page
tcc-doc.html: tcc-doc.texi
-texi2html -monolithic -number $<
makeinfo --no-split --html --number-sections -o $@ $< || true
tcc.1: tcc-doc.texi
-./texi2pod.pl $< tcc.pod
-pod2man --section=1 --center=" " --release=" " tcc.pod > $@
$(TOPSRC)/texi2pod.pl $< tcc.pod \
&& pod2man --section=1 --center="Tiny C Compiler" --release="$(VERSION)" tcc.pod >tmp.1 \
&& mv tmp.1 $@ || rm -f tmp.1
# tar release (use 'make -k tar' on a checkouted tree)
TCC-VERSION=tcc-$(shell cat VERSION)
tar:
rm -rf /tmp/$(TCC-VERSION)
cp -r . /tmp/$(TCC-VERSION)
( cd /tmp ; tar zcvf ~/$(TCC-VERSION).tar.gz $(TCC-VERSION) --exclude CVS )
rm -rf /tmp/$(TCC-VERSION)
tcc-doc.info: tcc-doc.texi
makeinfo $< || true
# in tests subdir
test clean:
$(MAKE) -C tests $@
# --------------------------------------------------------------------------
# install
INSTALL = install -m644
INSTALLBIN = install -m755 $(STRIP_$(CONFIG_strip))
STRIP_yes = -s
LIBTCC1_W = $(filter %-win32-libtcc1.a %-wince-libtcc1.a,$(LIBTCC1_CROSS))
LIBTCC1_U = $(filter-out $(LIBTCC1_W),$(LIBTCC1_CROSS))
IB = $(if $1,mkdir -p $2 && $(INSTALLBIN) $1 $2)
IBw = $(call IB,$(wildcard $1),$2)
IF = $(if $1,mkdir -p $2 && $(INSTALL) $1 $2)
IFw = $(call IF,$(wildcard $1),$2)
IR = mkdir -p $2 && cp -r $1/. $2
# install progs & libs
install-unx:
$(call IBw,$(PROGS) $(PROGS_CROSS),"$(bindir)")
$(call IFw,$(LIBTCC1) $(LIBTCC1_U),"$(tccdir)")
$(call IF,$(TOPSRC)/include/*.h $(TOPSRC)/tcclib.h,"$(tccdir)/include")
$(call $(if $(findstring .so,$(LIBTCC)),IBw,IFw),$(LIBTCC),"$(libdir)")
$(call IF,$(TOPSRC)/libtcc.h,"$(includedir)")
$(call IFw,tcc.1,"$(mandir)/man1")
$(call IFw,tcc-doc.info,"$(infodir)")
$(call IFw,tcc-doc.html,"$(docdir)")
ifneq "$(wildcard $(LIBTCC1_W))" ""
$(call IFw,$(TOPSRC)/win32/lib/*.def $(LIBTCC1_W),"$(tccdir)/win32/lib")
$(call IR,$(TOPSRC)/win32/include,"$(tccdir)/win32/include")
$(call IF,$(TOPSRC)/include/*.h $(TOPSRC)/tcclib.h,"$(tccdir)/win32/include")
endif
# uninstall
uninstall-unx:
@rm -fv $(foreach P,$(PROGS) $(PROGS_CROSS),"$(bindir)/$P")
@rm -fv "$(libdir)/libtcc.a" "$(libdir)/libtcc.so" "$(includedir)/libtcc.h"
@rm -fv "$(mandir)/man1/tcc.1" "$(infodir)/tcc-doc.info"
@rm -fv "$(docdir)/tcc-doc.html"
rm -r "$(tccdir)"
# install progs & libs on windows
install-win:
$(call IBw,$(PROGS) $(PROGS_CROSS) $(subst libtcc.a,,$(LIBTCC)),"$(bindir)")
$(call IF,$(TOPSRC)/win32/lib/*.def,"$(tccdir)/lib")
$(call IFw,libtcc1.a $(LIBTCC1_W),"$(tccdir)/lib")
$(call IF,$(TOPSRC)/include/*.h $(TOPSRC)/tcclib.h,"$(tccdir)/include")
$(call IR,$(TOPSRC)/win32/include,"$(tccdir)/include")
$(call IR,$(TOPSRC)/win32/examples,"$(tccdir)/examples")
$(call IF,$(TOPSRC)/tests/libtcc_test.c,"$(tccdir)/examples")
$(call IFw,$(TOPSRC)/libtcc.h $(subst .dll,.def,$(LIBTCC)),"$(libdir)")
$(call IFw,$(TOPSRC)/win32/tcc-win32.txt tcc-doc.html,"$(docdir)")
ifneq "$(wildcard $(LIBTCC1_U))" ""
$(call IFw,$(LIBTCC1_U),"$(tccdir)/lib")
$(call IF,$(TOPSRC)/include/*.h $(TOPSRC)/tcclib.h,"$(tccdir)/lib/include")
endif
# the msys-git shell works to configure && make except it does not have install
ifeq "$(and $(CONFIG_WIN32),$(shell which install >/dev/null 2>&1 || echo no))" "no"
install-win : INSTALL = cp
install-win : INSTALLBIN = cp
endif
# uninstall on windows
uninstall-win:
@rm -fv $(foreach P,$(PROGS) $(PROGS_CROSS) libtcc.dll,"$(bindir)/$P")
@rm -fv $(foreach F,tcc-doc.html tcc-win32.txt,"$(docdir)/$F")
@rm -fv $(foreach F,libtcc.h libtcc.def libtcc.a,"$(libdir)/$F")
rm -r "$(tccdir)"
# --------------------------------------------------------------------------
# other stuff
TAGFILES = *.[ch] include/*.h lib/*.[chS]
tags : ; ctags $(TAGFILES)
# cannot have both tags and TAGS on windows
ETAGS : ; etags $(TAGFILES)
# create release tarball from *current* git branch (including tcc-doc.html
# and converting two files to CRLF)
TCC-VERSION = tcc-$(VERSION)
tar: tcc-doc.html
mkdir $(TCC-VERSION)
( cd $(TCC-VERSION) && git --git-dir ../.git checkout -f )
cp tcc-doc.html $(TCC-VERSION)
for f in tcc-win32.txt build-tcc.bat ; do \
cat win32/$$f | sed 's,\(.*\),\1\r,g' > $(TCC-VERSION)/win32/$$f ; \
done
tar cjf $(TCC-VERSION).tar.bz2 $(TCC-VERSION)
rm -rf $(TCC-VERSION)
git reset
config.mak:
@echo Running configure ...
@./configure
$(if $(wildcard $@),,@echo "Please run ./configure." && exit 1)
# clean
clean: local_clean
local_clean:
rm -vf $(PROGS) tcc_p$(EXESUF) tcc.pod *~ *.o *.a *.out libtcc_test$(EXESUF)
# run all tests
test:
$(MAKE) -C tests
# run test(s) from tests2 subdir (see make help)
tests2.%:
$(MAKE) -C tests/tests2 $@
clean:
rm -f tcc$(EXESUF) tcc_p$(EXESUF) *-tcc$(EXESUF) tcc.pod
rm -f *~ *.o *.a *.so* *.out *.log lib*.def *.exe *.dll a.out tags TAGS
@$(MAKE) -C lib $@
@$(MAKE) -C tests $@
distclean: clean
rm -vf config.h config.mak config.texi tcc.1
rm -f config.h config.mak config.texi tcc.1 tcc-doc.info tcc-doc.html
endif # ifeq ($(TOP),.)
.PHONY: all clean test tar tags ETAGS distclean install uninstall FORCE
help:
@echo "make"
@echo " build native compiler (from separate objects)"
@echo ""
@echo "make cross"
@echo " build cross compilers (from one source)"
@echo ""
@echo "make ONE_SOURCE=yes / no"
@echo " force building from one source / separate objects"
@echo ""
@echo "make cross-TARGET"
@echo " build one specific cross compiler for 'TARGET', as in"
@echo " $(TCC_X)"
@echo ""
@echo "Custom configuration:"
@echo " The makefile includes a file 'config-extra.mak' if it is present."
@echo " This file may contain some custom configuration. For example:"
@echo ""
@echo " NATIVE_DEFINES += -D..."
@echo ""
@echo " Or for example to configure the search paths for a cross-compiler"
@echo " that expects the linux files in <tccdir>/i386-linux:"
@echo ""
@echo " ROOT-i386 = {B}/i386-linux"
@echo " CRT-i386 = {B}/i386-linux/usr/lib"
@echo " LIB-i386 = {B}/i386-linux/lib:{B}/i386-linux/usr/lib"
@echo " INC-i386 = {B}/lib/include:{B}/i386-linux/usr/include"
@echo " DEF-i386 += -D__linux__"
@echo ""
@echo "make test"
@echo " run all tests"
@echo ""
@echo "make tests2.all / make tests2.37 / make tests2.37+"
@echo " run all/single test(s) from tests2, optionally update .expect"
@echo ""
@echo "Other supported make targets:"
@echo " install install-strip tags ETAGS tar clean distclean help"
@echo ""
# --------------------------------------------------------------------------
endif # ($(INCLUDED),no)

13
README
View File

@ -28,15 +28,19 @@ Features:
Documentation:
-------------
1) Installation on a i386 Linux host (for Windows read tcc-win32.txt)
1) Installation on a i386/x86_64/arm Linux/OSX/FreeBSD host
./configure
make
make test
make install
By default, tcc is installed in /usr/local/bin.
./configure --help shows configuration options.
Notes: For OSX and FreeBSD, gmake should be used instead of make.
For Windows read tcc-win32.txt.
makeinfo must be installed to compile the doc. By default, tcc is
installed in /usr/local/bin. ./configure --help shows configuration
options.
2) Introduction
@ -65,7 +69,8 @@ operations given a list of numbers (benchmark).
ex3.c: compute fibonacci numbers (benchmark).
ex4.c: more complicated: X11 program. Very complicated test in fact
because standard headers are being used !
because standard headers are being used ! As for ex1.c, can also be launched
directly as a script: './ex4.c'.
ex5.c: 'hello world' with standard glibc headers.

60
RELICENSING 100644
View File

@ -0,0 +1,60 @@
Relicensing TinyCC
------------------
The authors listed below hereby confirm their agreement to relicense TinyCC
including their past contributions under the following terms:
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
Author (name) I agree (YES/NO) Files/Features (optional)
------------------------------------------------------------------------------
Adam Sampson YES makefiles
Daniel Glöckner NO arm-gen.c
Daniel Glöckner YES not arm-gen.c
Edmund Grimley Evans YES arm64
Fabrice Bellard YES original author
Frédéric Féret YES x86 64/16 bit asm
grischka YES tccpe.c
Henry Kroll YES
Joe Soroka YES
Kirill Smelkov YES
mingodad YES
Pip Cet YES
Shinichiro Hamaji YES x86_64-gen.c
Vincent Lefèvre YES
Thomas Preud'homme YES arm-gen.c
Timo VJ Lähde (Timppa) ? tiny_libmaker.c
TK ? tcccoff.c c67-gen.c
Urs Janssen YES
waddlesplash YES
Christian Jullien YES Windows Cygwin build and tests
------------------------------------------------------------------------------
Please add yourself to the list above (rsp. replace the question mark)
and (after fetching the latest version) commit to the "mob" branch with
commit message:
Relicensing TinyCC
Thanks.

45
TODO
View File

@ -2,17 +2,9 @@ TODO list:
Bugs:
- fix macro substitution with nested definitions (ShangHongzhang)
- i386 fastcall is mostly wrong
- FPU st(0) is left unclean (kwisatz haderach). Incompatible with
optimized gcc/msc code
- constructors
- cast bug (Peter Wang)
- define incomplete type if defined several times (Peter Wang).
- configure --cc=tcc (still one bug in libtcc1.c)
- test binutils/gcc compile
- tci patch + argument.
- see -lxxx bug (Michael Charity).
- see transparent union pb in /urs/include/sys/socket.h
- precise behaviour of typeof with arrays ? (__put_user macro)
but should suffice for most cases)
@ -21,19 +13,30 @@ Bugs:
- transform functions to function pointers in function parameters
(net/ipv4/ip_output.c)
- fix function pointer type display
- check lcc test suite -> fix bitfield binary operations
- check section alignment in C
- fix invalid cast in comparison 'if (v == (int8_t)v)'
- finish varargs.h support (gcc 3.2 testsuite issue)
- fix static functions declared inside block
- fix multiple unions init
- sizeof, alignof, typeof can still generate code in some cases.
- Fix the remaining libtcc memory leaks.
- make libtcc fully reentrant (except for the compilation stage itself).
- struct/union/enum definitions in nested scopes (see also Debian bug #770657)
- __STDC_IEC_559__: float f(void) { static float x = 0.0 / 0.0; return x; }
- memory may be leaked after errors (longjmp).
Portability:
- it is assumed that int is 32-bit and sizeof(int) == 4
- int is used when host or target size_t would make more sense
- TCC handles target floating-point (fp) values using the host's fp
arithmetic, which is simple and fast but may lead to exceptions
and inaccuracy and wrong representations when cross-compiling
Linking:
- static linking (-static) does not work
Bound checking:
- '-b' bug.
- fix bound exit on RedHat 7.3
- setjmp is not supported properly in bound checking.
- fix bound check code with '&' on local variables (currently done
@ -45,13 +48,10 @@ Missing features:
- disable-asm and disable-bcheck options
- __builtin_expect()
- improve '-E' option.
- add '-MD' option
- atexit (Nigel Horne)
- packed attribute
- C99: add variable size arrays (gcc 3.2 testsuite issue)
- C99: add complex types (gcc 3.2 testsuite issue)
- postfix compound literals (see 20010124-1.c)
- interactive mode / integrated debugger
Optimizations:
@ -67,17 +67,17 @@ Not critical:
normative example - only relevant when using gotos! -> must add
boolean variable to tell if compound literal was already
initialized).
- add PowerPC or ARM code generator and improve codegen for RISC (need
- add PowerPC generator and improve codegen for RISC (need
to suppress VT_LOCAL and use a base register instead).
- interactive mode / integrated debugger
- fix preprocessor symbol redefinition
- better constant opt (&&, ||, ?:)
- add portable byte code generator and interpreter for other
unsupported architectures.
- C++: variable declaration in for, minimal 'class' support.
- win32: __intxx. use resolve for bchecked malloc et al.
check exception code (exception filter func).
- handle void (__attribute__() *ptr)()
- VLAs are implemented in a way that is not compatible with signals:
http://lists.gnu.org/archive/html/tinycc-devel/2015-11/msg00018.html
Fixed (probably):
@ -93,3 +93,8 @@ Fixed (probably):
- #include_next support for /usr/include/limits ?
- function pointers/lvalues in ? : (linux kernel net/core/dev.c)
- win32: add __stdcall, check GetModuleHandle for dlls.
- macro substitution with nested definitions (ShangHongzhang)
- with "-run" and libtcc, a PLT is now built.
- '-E' option was improved
- packed attribute is now supported
- ARM and ARM64 code generators have been added.

View File

@ -1 +1 @@
0.9.25
0.9.27

94
arm-asm.c 100644
View File

@ -0,0 +1,94 @@
/*************************************************************/
/*
* ARM dummy assembler for TCC
*
*/
#ifdef TARGET_DEFS_ONLY
#define CONFIG_TCC_ASM
#define NB_ASM_REGS 16
ST_FUNC void g(int c);
ST_FUNC void gen_le16(int c);
ST_FUNC void gen_le32(int c);
/*************************************************************/
#else
/*************************************************************/
#include "tcc.h"
static void asm_error(void)
{
tcc_error("ARM asm not implemented.");
}
/* XXX: make it faster ? */
ST_FUNC void g(int c)
{
int ind1;
if (nocode_wanted)
return;
ind1 = ind + 1;
if (ind1 > cur_text_section->data_allocated)
section_realloc(cur_text_section, ind1);
cur_text_section->data[ind] = c;
ind = ind1;
}
ST_FUNC void gen_le16 (int i)
{
g(i);
g(i>>8);
}
ST_FUNC void gen_le32 (int i)
{
gen_le16(i);
gen_le16(i>>16);
}
ST_FUNC void gen_expr32(ExprValue *pe)
{
gen_le32(pe->v);
}
ST_FUNC void asm_opcode(TCCState *s1, int opcode)
{
asm_error();
}
ST_FUNC void subst_asm_operand(CString *add_str, SValue *sv, int modifier)
{
asm_error();
}
/* generate prolog and epilog code for asm statement */
ST_FUNC void asm_gen_code(ASMOperand *operands, int nb_operands,
int nb_outputs, int is_output,
uint8_t *clobber_regs,
int out_reg)
{
}
ST_FUNC void asm_compute_constraints(ASMOperand *operands,
int nb_operands, int nb_outputs,
const uint8_t *clobber_regs,
int *pout_reg)
{
}
ST_FUNC void asm_clobber(uint8_t *clobber_regs, const char *str)
{
asm_error();
}
ST_FUNC int asm_parse_regvar (int t)
{
asm_error();
return -1;
}
/*************************************************************/
#endif /* ndef TARGET_DEFS_ONLY */

1174
arm-gen.c

File diff suppressed because it is too large Load Diff

398
arm-link.c 100644
View File

@ -0,0 +1,398 @@
#ifdef TARGET_DEFS_ONLY
#define EM_TCC_TARGET EM_ARM
/* relocation type for 32 bit data relocation */
#define R_DATA_32 R_ARM_ABS32
#define R_DATA_PTR R_ARM_ABS32
#define R_JMP_SLOT R_ARM_JUMP_SLOT
#define R_GLOB_DAT R_ARM_GLOB_DAT
#define R_COPY R_ARM_COPY
#define R_RELATIVE R_ARM_RELATIVE
#define R_NUM R_ARM_NUM
#define ELF_START_ADDR 0x00008000
#define ELF_PAGE_SIZE 0x1000
#define PCRELATIVE_DLLPLT 1
#define RELOCATE_DLLPLT 0
enum float_abi {
ARM_SOFTFP_FLOAT,
ARM_HARD_FLOAT,
};
#else /* !TARGET_DEFS_ONLY */
#include "tcc.h"
/* Returns 1 for a code relocation, 0 for a data relocation. For unknown
relocations, returns -1. */
int code_reloc (int reloc_type)
{
switch (reloc_type) {
case R_ARM_MOVT_ABS:
case R_ARM_MOVW_ABS_NC:
case R_ARM_THM_MOVT_ABS:
case R_ARM_THM_MOVW_ABS_NC:
case R_ARM_ABS32:
case R_ARM_REL32:
case R_ARM_GOTPC:
case R_ARM_GOTOFF:
case R_ARM_GOT32:
case R_ARM_COPY:
case R_ARM_GLOB_DAT:
case R_ARM_NONE:
return 0;
case R_ARM_PC24:
case R_ARM_CALL:
case R_ARM_JUMP24:
case R_ARM_PLT32:
case R_ARM_THM_PC22:
case R_ARM_THM_JUMP24:
case R_ARM_PREL31:
case R_ARM_V4BX:
case R_ARM_JUMP_SLOT:
return 1;
}
tcc_error ("Unknown relocation type: %d", reloc_type);
return -1;
}
/* Returns an enumerator to describe whether and when the relocation needs a
GOT and/or PLT entry to be created. See tcc.h for a description of the
different values. */
int gotplt_entry_type (int reloc_type)
{
switch (reloc_type) {
case R_ARM_NONE:
case R_ARM_COPY:
case R_ARM_GLOB_DAT:
case R_ARM_JUMP_SLOT:
return NO_GOTPLT_ENTRY;
case R_ARM_PC24:
case R_ARM_CALL:
case R_ARM_JUMP24:
case R_ARM_PLT32:
case R_ARM_THM_PC22:
case R_ARM_THM_JUMP24:
case R_ARM_MOVT_ABS:
case R_ARM_MOVW_ABS_NC:
case R_ARM_THM_MOVT_ABS:
case R_ARM_THM_MOVW_ABS_NC:
case R_ARM_PREL31:
case R_ARM_ABS32:
case R_ARM_REL32:
case R_ARM_V4BX:
return AUTO_GOTPLT_ENTRY;
case R_ARM_GOTPC:
case R_ARM_GOTOFF:
return BUILD_GOT_ONLY;
case R_ARM_GOT32:
return ALWAYS_GOTPLT_ENTRY;
}
tcc_error ("Unknown relocation type: %d", reloc_type);
return -1;
}
ST_FUNC unsigned create_plt_entry(TCCState *s1, unsigned got_offset, struct sym_attr *attr)
{
Section *plt = s1->plt;
uint8_t *p;
unsigned plt_offset;
/* when building a DLL, GOT entry accesses must be done relative to
start of GOT (see x86_64 example above) */
if (s1->output_type == TCC_OUTPUT_DLL)
tcc_error("DLLs unimplemented!");
/* empty PLT: create PLT0 entry that push address of call site and
jump to ld.so resolution routine (GOT + 8) */
if (plt->data_offset == 0) {
p = section_ptr_add(plt, 20);
write32le(p, 0xe52de004); /* push {lr} */
write32le(p+4, 0xe59fe004); /* ldr lr, [pc, #4] */
write32le(p+8, 0xe08fe00e); /* add lr, pc, lr */
write32le(p+12, 0xe5bef008); /* ldr pc, [lr, #8]! */
/* p+16 is set in relocate_plt */
}
plt_offset = plt->data_offset;
if (attr->plt_thumb_stub) {
p = section_ptr_add(plt, 4);
write32le(p, 0x4778); /* bx pc */
write32le(p+2, 0x46c0); /* nop */
}
p = section_ptr_add(plt, 16);
/* Jump to GOT entry where ld.so initially put address of PLT0 */
write32le(p, 0xe59fc004); /* ldr ip, [pc, #4] */
write32le(p+4, 0xe08fc00c); /* add ip, pc, ip */
write32le(p+8, 0xe59cf000); /* ldr pc, [ip] */
/* p + 12 contains offset to GOT entry once patched by relocate_plt */
write32le(p+12, got_offset);
return plt_offset;
}
/* relocate the PLT: compute addresses and offsets in the PLT now that final
address for PLT and GOT are known (see fill_program_header) */
ST_FUNC void relocate_plt(TCCState *s1)
{
uint8_t *p, *p_end;
if (!s1->plt)
return;
p = s1->plt->data;
p_end = p + s1->plt->data_offset;
if (p < p_end) {
int x = s1->got->sh_addr - s1->plt->sh_addr - 12;
write32le(s1->plt->data + 16, x - 16);
p += 20;
while (p < p_end) {
if (read32le(p) == 0x46c04778) /* PLT Thumb stub present */
p += 4;
add32le(p + 12, x + s1->plt->data - p);
p += 16;
}
}
}
void relocate_init(Section *sr) {}
void relocate(TCCState *s1, ElfW_Rel *rel, int type, unsigned char *ptr, addr_t addr, addr_t val)
{
ElfW(Sym) *sym;
int sym_index;
sym_index = ELFW(R_SYM)(rel->r_info);
sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
switch(type) {
case R_ARM_PC24:
case R_ARM_CALL:
case R_ARM_JUMP24:
case R_ARM_PLT32:
{
int x, is_thumb, is_call, h, blx_avail, is_bl, th_ko;
x = (*(int *) ptr) & 0xffffff;
#ifdef DEBUG_RELOC
printf ("reloc %d: x=0x%x val=0x%x ", type, x, val);
#endif
(*(int *)ptr) &= 0xff000000;
if (x & 0x800000)
x -= 0x1000000;
x <<= 2;
blx_avail = (TCC_CPU_VERSION >= 5);
is_thumb = val & 1;
is_bl = (*(unsigned *) ptr) >> 24 == 0xeb;
is_call = (type == R_ARM_CALL || (type == R_ARM_PC24 && is_bl));
x += val - addr;
#ifdef DEBUG_RELOC
printf (" newx=0x%x name=%s\n", x,
(char *) symtab_section->link->data + sym->st_name);
#endif
h = x & 2;
th_ko = (x & 3) && (!blx_avail || !is_call);
if (th_ko || x >= 0x2000000 || x < -0x2000000)
tcc_error("can't relocate value at %x,%d",addr, type);
x >>= 2;
x &= 0xffffff;
/* Only reached if blx is avail and it is a call */
if (is_thumb) {
x |= h << 24;
(*(int *)ptr) = 0xfa << 24; /* bl -> blx */
}
(*(int *) ptr) |= x;
}
return;
/* Since these relocations only concern Thumb-2 and blx instruction was
introduced before Thumb-2, we can assume blx is available and not
guard its use */
case R_ARM_THM_PC22:
case R_ARM_THM_JUMP24:
{
int x, hi, lo, s, j1, j2, i1, i2, imm10, imm11;
int to_thumb, is_call, to_plt, blx_bit = 1 << 12;
Section *plt;
/* weak reference */
if (sym->st_shndx == SHN_UNDEF &&
ELFW(ST_BIND)(sym->st_info) == STB_WEAK)
return;
/* Get initial offset */
hi = (*(uint16_t *)ptr);
lo = (*(uint16_t *)(ptr+2));
s = (hi >> 10) & 1;
j1 = (lo >> 13) & 1;
j2 = (lo >> 11) & 1;
i1 = (j1 ^ s) ^ 1;
i2 = (j2 ^ s) ^ 1;
imm10 = hi & 0x3ff;
imm11 = lo & 0x7ff;
x = (s << 24) | (i1 << 23) | (i2 << 22) |
(imm10 << 12) | (imm11 << 1);
if (x & 0x01000000)
x -= 0x02000000;
/* Relocation infos */
to_thumb = val & 1;
plt = s1->plt;
to_plt = (val >= plt->sh_addr) &&
(val < plt->sh_addr + plt->data_offset);
is_call = (type == R_ARM_THM_PC22);
if (!to_thumb && !to_plt && !is_call) {
int index;
uint8_t *p;
char *name, buf[1024];
Section *text_section;
name = (char *) symtab_section->link->data + sym->st_name;
text_section = s1->sections[sym->st_shndx];
/* Modify reloc to target a thumb stub to switch to ARM */
snprintf(buf, sizeof(buf), "%s_from_thumb", name);
index = put_elf_sym(symtab_section,
text_section->data_offset + 1,
sym->st_size, sym->st_info, 0,
sym->st_shndx, buf);
to_thumb = 1;
val = text_section->data_offset + 1;
rel->r_info = ELFW(R_INFO)(index, type);
/* Create a thumb stub function to switch to ARM mode */
put_elf_reloc(symtab_section, text_section,
text_section->data_offset + 4, R_ARM_JUMP24,
sym_index);
p = section_ptr_add(text_section, 8);
write32le(p, 0x4778); /* bx pc */
write32le(p+2, 0x46c0); /* nop */
write32le(p+4, 0xeafffffe); /* b $sym */
}
/* Compute final offset */
x += val - addr;
if (!to_thumb && is_call) {
blx_bit = 0; /* bl -> blx */
x = (x + 3) & -4; /* Compute offset from aligned PC */
}
/* Check that relocation is possible
* offset must not be out of range
* if target is to be entered in arm mode:
- bit 1 must not set
- instruction must be a call (bl) or a jump to PLT */
if (!to_thumb || x >= 0x1000000 || x < -0x1000000)
if (to_thumb || (val & 2) || (!is_call && !to_plt))
tcc_error("can't relocate value at %x,%d",addr, type);
/* Compute and store final offset */
s = (x >> 24) & 1;
i1 = (x >> 23) & 1;
i2 = (x >> 22) & 1;
j1 = s ^ (i1 ^ 1);
j2 = s ^ (i2 ^ 1);
imm10 = (x >> 12) & 0x3ff;
imm11 = (x >> 1) & 0x7ff;
(*(uint16_t *)ptr) = (uint16_t) ((hi & 0xf800) |
(s << 10) | imm10);
(*(uint16_t *)(ptr+2)) = (uint16_t) ((lo & 0xc000) |
(j1 << 13) | blx_bit | (j2 << 11) |
imm11);
}
return;
case R_ARM_MOVT_ABS:
case R_ARM_MOVW_ABS_NC:
{
int x, imm4, imm12;
if (type == R_ARM_MOVT_ABS)
val >>= 16;
imm12 = val & 0xfff;
imm4 = (val >> 12) & 0xf;
x = (imm4 << 16) | imm12;
if (type == R_ARM_THM_MOVT_ABS)
*(int *)ptr |= x;
else
*(int *)ptr += x;
}
return;
case R_ARM_THM_MOVT_ABS:
case R_ARM_THM_MOVW_ABS_NC:
{
int x, i, imm4, imm3, imm8;
if (type == R_ARM_THM_MOVT_ABS)
val >>= 16;
imm8 = val & 0xff;
imm3 = (val >> 8) & 0x7;
i = (val >> 11) & 1;
imm4 = (val >> 12) & 0xf;
x = (imm3 << 28) | (imm8 << 16) | (i << 10) | imm4;
if (type == R_ARM_THM_MOVT_ABS)
*(int *)ptr |= x;
else
*(int *)ptr += x;
}
return;
case R_ARM_PREL31:
{
int x;
x = (*(int *)ptr) & 0x7fffffff;
(*(int *)ptr) &= 0x80000000;
x = (x * 2) / 2;
x += val - addr;
if((x^(x>>1))&0x40000000)
tcc_error("can't relocate value at %x,%d",addr, type);
(*(int *)ptr) |= x & 0x7fffffff;
}
case R_ARM_ABS32:
*(int *)ptr += val;
return;
case R_ARM_REL32:
*(int *)ptr += val - addr;
return;
case R_ARM_GOTPC:
*(int *)ptr += s1->got->sh_addr - addr;
return;
case R_ARM_GOTOFF:
*(int *)ptr += val - s1->got->sh_addr;
return;
case R_ARM_GOT32:
/* we load the got offset */
*(int *)ptr += s1->sym_attrs[sym_index].got_offset;
return;
case R_ARM_COPY:
return;
case R_ARM_V4BX:
/* trade Thumb support for ARMv4 support */
if ((0x0ffffff0 & *(int*)ptr) == 0x012FFF10)
*(int*)ptr ^= 0xE12FFF10 ^ 0xE1A0F000; /* BX Rm -> MOV PC, Rm */
return;
case R_ARM_GLOB_DAT:
case R_ARM_JUMP_SLOT:
*(addr_t *)ptr = val;
return;
case R_ARM_NONE:
/* Nothing to do. Normally used to indicate a dependency
on a certain symbol (like for exception handling under EABI). */
return;
case R_ARM_RELATIVE:
#ifdef TCC_TARGET_PE
add32le(ptr, val - s1->pe_imagebase);
#endif
/* do nothing */
return;
default:
fprintf(stderr,"FIXME: handle reloc type %x at %x [%p] to %x\n",
type, (unsigned)addr, ptr, (unsigned)val);
return;
}
}
#endif /* !TARGET_DEFS_ONLY */

1837
arm64-gen.c 100644

File diff suppressed because it is too large Load Diff

256
arm64-link.c 100644
View File

@ -0,0 +1,256 @@
#ifdef TARGET_DEFS_ONLY
#define EM_TCC_TARGET EM_AARCH64
#define R_DATA_32 R_AARCH64_ABS32
#define R_DATA_PTR R_AARCH64_ABS64
#define R_JMP_SLOT R_AARCH64_JUMP_SLOT
#define R_GLOB_DAT R_AARCH64_GLOB_DAT
#define R_COPY R_AARCH64_COPY
#define R_RELATIVE R_AARCH64_RELATIVE
#define R_NUM R_AARCH64_NUM
#define ELF_START_ADDR 0x00400000
#define ELF_PAGE_SIZE 0x1000
#define PCRELATIVE_DLLPLT 1
#define RELOCATE_DLLPLT 1
#else /* !TARGET_DEFS_ONLY */
#include "tcc.h"
/* Returns 1 for a code relocation, 0 for a data relocation. For unknown
relocations, returns -1. */
int code_reloc (int reloc_type)
{
switch (reloc_type) {
case R_AARCH64_ABS32:
case R_AARCH64_ABS64:
case R_AARCH64_PREL32:
case R_AARCH64_MOVW_UABS_G0_NC:
case R_AARCH64_MOVW_UABS_G1_NC:
case R_AARCH64_MOVW_UABS_G2_NC:
case R_AARCH64_MOVW_UABS_G3:
case R_AARCH64_ADR_PREL_PG_HI21:
case R_AARCH64_ADD_ABS_LO12_NC:
case R_AARCH64_ADR_GOT_PAGE:
case R_AARCH64_LD64_GOT_LO12_NC:
case R_AARCH64_GLOB_DAT:
case R_AARCH64_COPY:
return 0;
case R_AARCH64_JUMP26:
case R_AARCH64_CALL26:
case R_AARCH64_JUMP_SLOT:
return 1;
}
tcc_error ("Unknown relocation type: %d", reloc_type);
return -1;
}
/* Returns an enumerator to describe whether and when the relocation needs a
GOT and/or PLT entry to be created. See tcc.h for a description of the
different values. */
int gotplt_entry_type (int reloc_type)
{
switch (reloc_type) {
case R_AARCH64_PREL32:
case R_AARCH64_MOVW_UABS_G0_NC:
case R_AARCH64_MOVW_UABS_G1_NC:
case R_AARCH64_MOVW_UABS_G2_NC:
case R_AARCH64_MOVW_UABS_G3:
case R_AARCH64_ADR_PREL_PG_HI21:
case R_AARCH64_ADD_ABS_LO12_NC:
case R_AARCH64_GLOB_DAT:
case R_AARCH64_JUMP_SLOT:
case R_AARCH64_COPY:
return NO_GOTPLT_ENTRY;
case R_AARCH64_ABS32:
case R_AARCH64_ABS64:
case R_AARCH64_JUMP26:
case R_AARCH64_CALL26:
return AUTO_GOTPLT_ENTRY;
case R_AARCH64_ADR_GOT_PAGE:
case R_AARCH64_LD64_GOT_LO12_NC:
return ALWAYS_GOTPLT_ENTRY;
}
tcc_error ("Unknown relocation type: %d", reloc_type);
return -1;
}
ST_FUNC unsigned create_plt_entry(TCCState *s1, unsigned got_offset, struct sym_attr *attr)
{
Section *plt = s1->plt;
uint8_t *p;
unsigned plt_offset;
if (s1->output_type == TCC_OUTPUT_DLL)
tcc_error("DLLs unimplemented!");
if (plt->data_offset == 0) {
section_ptr_add(plt, 32);
}
plt_offset = plt->data_offset;
p = section_ptr_add(plt, 16);
write32le(p, got_offset);
write32le(p + 4, (uint64_t) got_offset >> 32);
return plt_offset;
}
/* relocate the PLT: compute addresses and offsets in the PLT now that final
address for PLT and GOT are known (see fill_program_header) */
ST_FUNC void relocate_plt(TCCState *s1)
{
uint8_t *p, *p_end;
if (!s1->plt)
return;
p = s1->plt->data;
p_end = p + s1->plt->data_offset;
if (p < p_end) {
uint64_t plt = s1->plt->sh_addr;
uint64_t got = s1->got->sh_addr;
uint64_t off = (got >> 12) - (plt >> 12);
if ((off + ((uint32_t)1 << 20)) >> 21)
tcc_error("Failed relocating PLT (off=0x%lx, got=0x%lx, plt=0x%lx)", off, got, plt);
write32le(p, 0xa9bf7bf0); // stp x16,x30,[sp,#-16]!
write32le(p + 4, (0x90000010 | // adrp x16,...
(off & 0x1ffffc) << 3 | (off & 3) << 29));
write32le(p + 8, (0xf9400211 | // ldr x17,[x16,#...]
(got & 0xff8) << 7));
write32le(p + 12, (0x91000210 | // add x16,x16,#...
(got & 0xfff) << 10));
write32le(p + 16, 0xd61f0220); // br x17
write32le(p + 20, 0xd503201f); // nop
write32le(p + 24, 0xd503201f); // nop
write32le(p + 28, 0xd503201f); // nop
p += 32;
while (p < p_end) {
uint64_t pc = plt + (p - s1->plt->data);
uint64_t addr = got + read64le(p);
uint64_t off = (addr >> 12) - (pc >> 12);
if ((off + ((uint32_t)1 << 20)) >> 21)
tcc_error("Failed relocating PLT (off=0x%lx, addr=0x%lx, pc=0x%lx)", off, addr, pc);
write32le(p, (0x90000010 | // adrp x16,...
(off & 0x1ffffc) << 3 | (off & 3) << 29));
write32le(p + 4, (0xf9400211 | // ldr x17,[x16,#...]
(addr & 0xff8) << 7));
write32le(p + 8, (0x91000210 | // add x16,x16,#...
(addr & 0xfff) << 10));
write32le(p + 12, 0xd61f0220); // br x17
p += 16;
}
}
}
void relocate_init(Section *sr) {}
void relocate(TCCState *s1, ElfW_Rel *rel, int type, unsigned char *ptr, addr_t addr, addr_t val)
{
int sym_index = ELFW(R_SYM)(rel->r_info);
#ifdef DEBUG_RELOC
ElfW(Sym) *sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
#endif
switch(type) {
case R_AARCH64_ABS64:
write64le(ptr, val);
return;
case R_AARCH64_ABS32:
write32le(ptr, val);
return;
case R_AARCH64_PREL32:
write32le(ptr, val - addr);
return;
case R_AARCH64_MOVW_UABS_G0_NC:
write32le(ptr, ((read32le(ptr) & 0xffe0001f) |
(val & 0xffff) << 5));
return;
case R_AARCH64_MOVW_UABS_G1_NC:
write32le(ptr, ((read32le(ptr) & 0xffe0001f) |
(val >> 16 & 0xffff) << 5));
return;
case R_AARCH64_MOVW_UABS_G2_NC:
write32le(ptr, ((read32le(ptr) & 0xffe0001f) |
(val >> 32 & 0xffff) << 5));
return;
case R_AARCH64_MOVW_UABS_G3:
write32le(ptr, ((read32le(ptr) & 0xffe0001f) |
(val >> 48 & 0xffff) << 5));
return;
case R_AARCH64_ADR_PREL_PG_HI21: {
uint64_t off = (val >> 12) - (addr >> 12);
if ((off + ((uint64_t)1 << 20)) >> 21)
tcc_error("R_AARCH64_ADR_PREL_PG_HI21 relocation failed");
write32le(ptr, ((read32le(ptr) & 0x9f00001f) |
(off & 0x1ffffc) << 3 | (off & 3) << 29));
return;
}
case R_AARCH64_ADD_ABS_LO12_NC:
write32le(ptr, ((read32le(ptr) & 0xffc003ff) |
(val & 0xfff) << 10));
return;
case R_AARCH64_JUMP26:
case R_AARCH64_CALL26:
#ifdef DEBUG_RELOC
printf ("reloc %d @ 0x%lx: val=0x%lx name=%s\n", type, addr, val,
(char *) symtab_section->link->data + sym->st_name);
#endif
if (((val - addr) + ((uint64_t)1 << 27)) & ~(uint64_t)0xffffffc)
tcc_error("R_AARCH64_(JUMP|CALL)26 relocation failed"
" (val=%lx, addr=%lx)", val, addr);
write32le(ptr, (0x14000000 |
(uint32_t)(type == R_AARCH64_CALL26) << 31 |
((val - addr) >> 2 & 0x3ffffff)));
return;
case R_AARCH64_ADR_GOT_PAGE: {
uint64_t off =
(((s1->got->sh_addr +
s1->sym_attrs[sym_index].got_offset) >> 12) - (addr >> 12));
if ((off + ((uint64_t)1 << 20)) >> 21)
tcc_error("R_AARCH64_ADR_GOT_PAGE relocation failed");
write32le(ptr, ((read32le(ptr) & 0x9f00001f) |
(off & 0x1ffffc) << 3 | (off & 3) << 29));
return;
}
case R_AARCH64_LD64_GOT_LO12_NC:
write32le(ptr,
((read32le(ptr) & 0xfff803ff) |
((s1->got->sh_addr +
s1->sym_attrs[sym_index].got_offset) & 0xff8) << 7));
return;
case R_AARCH64_COPY:
return;
case R_AARCH64_GLOB_DAT:
case R_AARCH64_JUMP_SLOT:
/* They don't need addend */
#ifdef DEBUG_RELOC
printf ("reloc %d @ 0x%lx: val=0x%lx name=%s\n", type, addr,
val - rel->r_addend,
(char *) symtab_section->link->data + sym->st_name);
#endif
write64le(ptr, val - rel->r_addend);
return;
case R_AARCH64_RELATIVE:
#ifdef TCC_TARGET_PE
add32le(ptr, val - s1->pe_imagebase);
#endif
/* do nothing */
return;
default:
fprintf(stderr, "FIXME: handle reloc type %x at %x [%p] to %x\n",
type, (unsigned)addr, ptr, (unsigned)val);
return;
}
}
#endif /* !TARGET_DEFS_ONLY */

2
bootstrap/.gitignore vendored 100644
View File

@ -0,0 +1,2 @@
/libc.a
/tcc

View File

@ -0,0 +1,4 @@
#ifndef CONFIG_TCCDIR
# define CONFIG_TCCDIR "/usr/lib/tcc"
#endif
#define TCC_VERSION "0.9.27"

View File

@ -0,0 +1,14 @@
#! /usr/bin/env sh
cd "$(dirname "$0")" &&
# Compile dietlibc
gcc -r -nostdlib -o libc.a -Ilibc/include -I../include \
libc/src/cstring.c libc/src/cstdio.c libc/src/syscalls.c &&
# Build compiler
ln -fs base_config.h config.h &&
gcc -o tcc -static -nostdlib \
-DNDEBUG -DTCC_NOT_NATIVE -DCONFIG_LDDIR="\"lib64\"" -DTCC_TARGET_X86_64 -DONE_SOURCE=0 -I. -I../include -Ilibc/include \
../tcc.c ../libtcc.c ../tccpp.c ../tccgen.c ../tccelf.c ../tccasm.c ../tccrun.c ../x86_64-gen.c ../x86_64-link.c ../i386-asm.c\
./libc.a

View File

@ -0,0 +1,17 @@
#include <stddef.h>
#ifndef __STDIO_H__
#define __STDIO_H__
// Type definitions
typedef void FILE;
// Values
extern FILE* stdout;
extern FILE* stderr;
extern FILE* stdin;
// Basic file handlers
extern FILE* fopen(const char* filename, const char* mode);
#endif

View File

@ -0,0 +1,22 @@
#ifndef __STRING_H__
#define __STRING_H__
#include <stddef.h>
// Memory
const void* memchr(const void* ptr, int value, size_t size);
int memcmp(const void* ptr1, const void* ptr2, size_t num);
void* memcpy(void* destination, const void* source, size_t num);
void* memmove(void* destination, const void* source, size_t num);
void* memset(void* ptr, int value, size_t num);
// Strings
char* strchr(const char* str, int character);
int strcmp(const char* str1, const char* str2);
char* strcpy(char* destination, const char* source);
size_t strlen(const char* str);
int strncmp(const char* str1, const char* str2, size_t num);
char* strrchr(const char* str, int character);
char* strstr(const char* str1, const char* str2);
#endif

View File

@ -0,0 +1,34 @@
.global _start
.global __syscall
.text
_start:
// Run main
call main
// Exit process
mov %rax, %rdi
mov $60, %rax
syscall
__syscall:
// Save the config (except rax)
push %rdi
push %rsi
push %rdx
push %r10
// Make the syscall
mov %rdi, %rax
mov %rsi, %rdi
mov %rdx, %rsi
mov %rcx, %rdx
mov %r8d, %r10d
syscall
// Restore and return
pop %r10
pop %rdx
pop %rsi
pop %rdi
retq

View File

@ -0,0 +1,18 @@
#include "syscalls.h"
// File definition
typedef void FILE;
// Values TODO: Make it correct
//FILE* stdout = 0;
//FILE* stderr = 1;
//FILE* stdin = 2;
// Base file writer
FILE* fopen(const char* filename, const char* mode) {
int inode = open(filename, 0, 0x1a4);
if(inode < 0) {
return NULL;
}
return (FILE*) (size_t) inode;
}

View File

@ -0,0 +1,154 @@
#include <stddef.h>
// Tools
size_t min(size_t a, size_t b) {
if(a < b) {
return a;
}
else {
return b;
}
}
// Memory
const void* memchr(const void* ptr, int value, size_t size) {
const char* ptr_real = (const char*) ptr;
char value_real = value;
for(size_t i = 0; i < size; i++) {
if(ptr_real[i] == value_real) {
return &(ptr_real[i]);
}
}
return NULL;
}
int memcmp(const void* ptr1, const void* ptr2, size_t num) {
const char* ptr1_real = (const char*) ptr1;
const char* ptr2_real = (const char*) ptr2;
for(size_t i = 0; i < num; i++) {
if(ptr1_real[i] < ptr2_real[i]) {
return -1;
}
else if(ptr1_real[i] > ptr2_real[i]) {
return 1;
}
}
return 0;
}
void* memcpy(void* destination, const void* source, size_t num) {
char* destination_real = (char*) destination;
const char* source_real = (const char*) source;
if(source > destination) {
for(size_t i = 0; i < num; i++) {
destination_real[i] = source_real[i];
}
}
else {
for(size_t i = 0; i < num; i++) {
destination_real[num - i - 1] = source_real[num - i - 1];
}
}
return destination;
}
void* memmove(void* destination, const void* source, size_t num) {
return memcpy(destination, source, num);
}
void* memset(void* ptr, int value, size_t num) {
char* ptr_real = (char*) ptr;
char value_real = value;
for(size_t i = 0; i < num; i++) {
ptr_real[i] = value_real;
}
return ptr;
}
// String
size_t strlen(const char* str);
char* strchr(const char* str, int character) {
while((*str) == 0) {
if((*str) == character) {
return (char*) str;
}
str++;
}
return NULL;
}
int strcmp(const char* str1, const char* str2) { // TODO: Make faster
size_t len_str1 = strlen(str1);
size_t len_str2 = strlen(str2);
size_t min_len = min(len_str1, len_str2);
int result = memcmp(str1, str2, min_len);
if(result != 0) {
return result;
}
else if(len_str1 > min_len) {
return 1;
}
else {
return -1;
}
}
char* strcpy(char* destination, const char* source) {
char* result = destination;
while((*source) == 0) {
(*destination) = (*source);
destination++;
source++;
}
return result;
}
size_t strlen(const char* str) {
size_t size = 0;
while(str[size] != 0) {
size++;
}
return size;
}
int strncmp(const char* str1, const char* str2, size_t num) { // TODO: Make faster
size_t len_str1 = strlen(str1);
size_t len_str2 = strlen(str2);
size_t min_len = min(min(len_str1, len_str2), num);
int result = memcmp(str1, str2, min_len);
if(min_len == num) {
return result;
}
else if(result != 0) {
return result;
}
else if(len_str1 > min_len) {
return 1;
}
else {
return -1;
}
}
char* strrchr(const char* str, int character) {
char* result = NULL;
while((*str) != 0) {
if((*str) == character) {
result = (char*) str;
}
str++;
}
if(character == 0) {
result = (char*) str;
}
return result;
}
char* strstr(const char* str1, const char* str2) {
size_t len_str1 = strlen(str1);
size_t len_str2 = strlen(str2);
for(size_t i = 0; i <= len_str1 - len_str2; i++) {
int valid = 1;
for(size_t j = 0; j < len_str2; j++) {
if(str1[i + j] != str2[j]) {
valid = 0;
break;
}
}
if(valid != 0) {
return (char*) &(str1[i]);
}
}
return NULL;
}

View File

@ -0,0 +1,18 @@
#include "syscalls.h"
#ifdef __x86_64__
#define SYSCALL_READ 0
#define SYSCALL_WRITE 1
#define SYSCALL_OPEN 2
#define SYSCALL_CLOSE 3
#else
#error Unsupported architecture
#endif
int open(const char* path, int flags, int mode) {
return __syscall(SYSCALL_OPEN, (size_t) path, (size_t) flags, (size_t) mode,
0);
}
int close(int fd) {
return __syscall(SYSCALL_CLOSE, (size_t) fd, 0, 0, 0);
}

View File

@ -0,0 +1,6 @@
#include <stddef.h>
extern volatile size_t __syscall(size_t code, size_t arg1, size_t arg2,
size_t arg3, size_t arg4);
int open(const char* path, int flags, int mode);

2
bootstrap/libc/test/.gitignore vendored 100644
View File

@ -0,0 +1,2 @@
*.test
libc.a

View File

@ -0,0 +1,3 @@
int main() {
return 0;
}

View File

@ -0,0 +1,3 @@
int main() {
return 1;
}

View File

@ -0,0 +1,3 @@
int main() {
return 2;
}

View File

@ -0,0 +1,30 @@
#! /usr/bin/env bash
# Args: <compiler>
# Test exists
cd "$(dirname "$0")" &&
(
echo TEST: exit_0 &&
$1 -I../../../include -o exit_0.test exit_0.c ../libc.a &&
(
./exit_0.test
if [ "$?" != "0" ]; then exit 1; fi
) || ( echo FAILED; exit 1 )
) &&
(
echo TEST: exit_1 &&
$1 -I../../../include -o exit_1.test exit_1.c ../libc.a &&
(
./exit_1.test
if [ "$?" != "1" ]; then exit 1; fi
) || ( echo FAILED; exit 1 )
) &&
(
echo TEST: exit_2 &&
$1 -I../../../include -o exit_2.test exit_2.c ../libc.a &&
(
./exit_2.test
if [ "$?" != "2" ]; then exit 1; fi
) || ( echo FAILED; exit 1 )
)

View File

@ -0,0 +1,13 @@
#include <stddef.h>
#include <stdio.h>
int main() {
FILE* file = fopen("not_exists", "r");
if(file == NULL) {
return 0;
}
else {
return 1;
}
}

View File

@ -0,0 +1,13 @@
#include <stddef.h>
#include <stdio.h>
int main() {
FILE* file = fopen("fopen_success.c", "r");
if(file == NULL) {
return 1;
}
else {
return 0;
}
}

View File

@ -0,0 +1,14 @@
#! /usr/bin/env bash
cd "$(dirname "$0")" &&
(
echo TEST: fopen_fail
gcc -nostdlib -O0 -I ../../include -o fopen_fail.test fopen_fail.c ../libc.a &&
./fopen_fail.test || ( echo ERROR; exit 1)
) &&
(
echo TEST: fopen_success
gcc -nostdlib -O0 -I ../../include -o fopen_success.test fopen_success.c ../libc.a &&
./fopen_success.test || ( echo ERROR; exit 1)
)

View File

@ -0,0 +1,13 @@
#! /usr/bin/env bash
# Args: <compiler>
# Build libc
cd "$(dirname "$0")" &&
echo BUILD libc.a &&
$1 -r -o libc.a -I../include \
../src/cstring.c ../src/cstdio.c ../src/syscalls.c ../src/base_x86_64.s &&
# Test
./base/test.sh "$1" &&
./stdio/test.sh "$1"

View File

@ -0,0 +1,3 @@
#! /usr/bin/env sh
exec "$(dirname "$0")"/libc/test/test_x86_64.sh "gcc -nostdlib -g"

235
c67-gen.c
View File

@ -18,7 +18,9 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
//#define ASSEMBLY_LISTING_C67
#ifdef TARGET_DEFS_ONLY
/* #define ASSEMBLY_LISTING_C67 */
/* number of available registers */
#define NB_REGS 24
@ -85,12 +87,38 @@ enum {
TREG_C67_B13,
};
const int reg_classes[NB_REGS] = {
/* eax */ RC_INT | RC_FLOAT | RC_EAX,
// only allow even regs for floats (allow for doubles)
/* return registers for function */
#define REG_IRET TREG_C67_A4 /* single word int return register */
#define REG_LRET TREG_C67_A5 /* second word return register (for long long) */
#define REG_FRET TREG_C67_A4 /* float return register */
/* defined if function parameters must be evaluated in reverse order */
/* #define INVERT_FUNC_PARAMS */
/* defined if structures are passed as pointers. Otherwise structures
are directly pushed on stack. */
/* #define FUNC_STRUCT_PARAM_AS_PTR */
/* pointer size, in bytes */
#define PTR_SIZE 4
/* long double size and alignment, in bytes */
#define LDOUBLE_SIZE 12
#define LDOUBLE_ALIGN 4
/* maximum alignment (for aligned attribute support) */
#define MAX_ALIGN 8
/******************************************************/
#else /* ! TARGET_DEFS_ONLY */
/******************************************************/
#include "tcc.h"
ST_DATA const int reg_classes[NB_REGS] = {
/* eax */ RC_INT | RC_FLOAT | RC_EAX,
// only allow even regs for floats (allow for doubles)
/* ecx */ RC_INT | RC_ECX,
/* edx */ RC_INT | RC_INT_BSIDE | RC_FLOAT | RC_EDX,
// only allow even regs for floats (allow for doubles)
/* edx */ RC_INT | RC_INT_BSIDE | RC_FLOAT | RC_EDX,
// only allow even regs for floats (allow for doubles)
/* st0 */ RC_INT | RC_INT_BSIDE | RC_ST0,
/* A4 */ RC_C67_A4,
/* A5 */ RC_C67_A5,
@ -114,68 +142,36 @@ const int reg_classes[NB_REGS] = {
/* B13 */ RC_C67_B11
};
/* return registers for function */
#define REG_IRET TREG_C67_A4 /* single word int return register */
#define REG_LRET TREG_C67_A5 /* second word return register (for long long) */
#define REG_FRET TREG_C67_A4 /* float return register */
#define ALWAYS_ASSERT(x) \
do {\
if (!(x))\
error("internal compiler error file at %s:%d", __FILE__, __LINE__);\
} while (0)
// although tcc thinks it is passing parameters on the stack,
// the C67 really passes up to the first 10 params in special
// regs or regs pairs (for 64 bit params). So keep track of
// the stack offsets so we can translate to the appropriate
// reg (pair)
#define NoCallArgsPassedOnStack 10
int NoOfCurFuncArgs;
int TranslateStackToReg[NoCallArgsPassedOnStack];
int ParamLocOnStack[NoCallArgsPassedOnStack];
int TotalBytesPushedOnStack;
/* defined if function parameters must be evaluated in reverse order */
#ifndef FALSE
# define FALSE 0
# define TRUE 1
#endif
//#define INVERT_FUNC_PARAMS
#undef BOOL
#define BOOL int
/* defined if structures are passed as pointers. Otherwise structures
are directly pushed on stack. */
//#define FUNC_STRUCT_PARAM_AS_PTR
/* pointer size, in bytes */
#define PTR_SIZE 4
/* long double size and alignment, in bytes */
#define LDOUBLE_SIZE 12
#define LDOUBLE_ALIGN 4
/* maximum alignment (for aligned attribute support) */
#define MAX_ALIGN 8
#define ALWAYS_ASSERT(x) \
do {\
if (!(x))\
tcc_error("internal compiler error file at %s:%d", __FILE__, __LINE__);\
} while (0)
/******************************************************/
/* ELF defines */
#define EM_TCC_TARGET EM_C60
/* relocation type for 32 bit data relocation */
#define R_DATA_32 R_C60_32
#define R_DATA_PTR R_C60_32
#define R_JMP_SLOT R_C60_JMP_SLOT
#define R_COPY R_C60_COPY
#define ELF_START_ADDR 0x00000400
#define ELF_PAGE_SIZE 0x1000
/******************************************************/
static unsigned long func_sub_sp_offset;
static int func_ret_sub;
static BOOL C67_invert_test;
static int C67_compare_reg;
@ -183,11 +179,11 @@ static int C67_compare_reg;
FILE *f = NULL;
#endif
void C67_g(int c)
{
int ind1;
if (nocode_wanted)
return;
#ifdef ASSEMBLY_LISTING_C67
fprintf(f, " %08X", c);
#endif
@ -236,15 +232,15 @@ void gsym(int t)
}
// these are regs that tcc doesn't really know about,
// but asign them unique values so the mapping routines
// can distinquish them
// but assign them unique values so the mapping routines
// can distinguish them
#define C67_A0 105
#define C67_SP 106
#define C67_B3 107
#define C67_FP 108
#define C67_B2 109
#define C67_CREG_ZERO -1 // Special code for no condition reg test
#define C67_CREG_ZERO -1 /* Special code for no condition reg test */
int ConvertRegToRegClass(int r)
@ -1553,23 +1549,23 @@ void C67_SHR(int r, int v)
void load(int r, SValue * sv)
{
int v, t, ft, fc, fr, size = 0, element;
BOOL Unsigned = false;
BOOL Unsigned = FALSE;
SValue v1;
fr = sv->r;
ft = sv->type.t;
fc = sv->c.ul;
fc = sv->c.i;
v = fr & VT_VALMASK;
if (fr & VT_LVAL) {
if (v == VT_LLOCAL) {
v1.type.t = VT_INT;
v1.r = VT_LOCAL | VT_LVAL;
v1.c.ul = fc;
v1.c.i = fc;
load(r, &v1);
fr = r;
} else if ((ft & VT_BTYPE) == VT_LDOUBLE) {
error("long double not supported");
tcc_error("long double not supported");
} else if ((ft & VT_TYPE) == VT_BYTE) {
size = 1;
} else if ((ft & VT_TYPE) == (VT_BYTE | VT_UNSIGNED)) {
@ -1717,13 +1713,13 @@ void store(int r, SValue * v)
int fr, bt, ft, fc, size, t, element;
ft = v->type.t;
fc = v->c.ul;
fc = v->c.i;
fr = v->r & VT_VALMASK;
bt = ft & VT_BTYPE;
/* XXX: incorrect if float reg to reg */
if (bt == VT_LDOUBLE) {
error("long double not supported");
tcc_error("long double not supported");
} else {
if (bt == VT_SHORT)
size = 2;
@ -1870,6 +1866,13 @@ static void gcall_or_jmp(int is_jmp)
}
}
/* Return the number of registers needed to return the struct, or 0 if
returning via struct pointer. */
ST_FUNC int gfunc_sret(CType *vt, int variadic, CType *ret, int *ret_align, int *regsize) {
*ret_align = 1; // Never have to re-align return values for x86-64
return 0;
}
/* generate function call with address in (vtop->t, vtop->c) and free function
context. Stack entry is popped */
void gfunc_call(int nb_args)
@ -1878,24 +1881,22 @@ void gfunc_call(int nb_args)
int args_sizes[NoCallArgsPassedOnStack];
if (nb_args > NoCallArgsPassedOnStack) {
error("more than 10 function params not currently supported");
tcc_error("more than 10 function params not currently supported");
// handle more than 10, put some on the stack
}
for (i = 0; i < nb_args; i++) {
if ((vtop->type.t & VT_BTYPE) == VT_STRUCT) {
ALWAYS_ASSERT(FALSE);
} else if ((vtop->type.t & VT_BTYPE) == VT_STRUCT) {
ALWAYS_ASSERT(FALSE);
} else {
/* simple type (currently always same size) */
/* XXX: implicit cast ? */
if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
error("long long not supported");
tcc_error("long long not supported");
} else if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
error("long double not supported");
tcc_error("long double not supported");
} else if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE) {
size = 8;
} else {
@ -1950,11 +1951,12 @@ void gfunc_prolog(CType * func_type)
CType *type;
sym = func_type->ref;
func_call = sym->r;
func_call = sym->f.func_call;
addr = 8;
/* if the function returns a structure, then add an
implicit pointer parameter */
func_vt = sym->type;
func_var = (sym->f.func_type == FUNC_ELLIPSIS);
if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
func_vc = addr;
addr += 4;
@ -2037,6 +2039,8 @@ void gfunc_epilog(void)
int gjmp(int t)
{
int ind1 = ind;
if (nocode_wanted)
return t;
C67_MVKL(C67_A0, t); //r=reg to load, constant
C67_MVKH(C67_A0, t); //r=reg to load, constant
@ -2069,7 +2073,9 @@ int gtst(int inv, int t)
int v, *p;
v = vtop->r & VT_VALMASK;
if (v == VT_CMP) {
if (nocode_wanted) {
;
} else if (v == VT_CMP) {
/* fast case : can jump directly since flags are set */
// C67 uses B2 sort of as flags register
ind1 = ind;
@ -2091,13 +2097,12 @@ int gtst(int inv, int t)
/* && or || optimization */
if ((v & 1) == inv) {
/* insert vtop->c jump list in t */
p = &vtop->c.i;
// I guess the idea is to traverse to the
// null at the end of the list and store t
// there
n = *p;
n = vtop->c.i;
while (n != 0) {
p = (int *) (cur_text_section->data + n);
@ -2113,37 +2118,6 @@ int gtst(int inv, int t)
t = gjmp(t);
gsym(vtop->c.i);
}
} else {
if (is_float(vtop->type.t)) {
vpushi(0);
gen_op(TOK_NE);
}
if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
/* constant jmp optimization */
if ((vtop->c.i != 0) != inv)
t = gjmp(t);
} else {
// I think we need to get the value on the stack
// into a register, test it, and generate a branch
// return the address of the branch, so it can be
// later patched
v = gv(RC_INT); // get value into a reg
ind1 = ind;
C67_MVKL(C67_A0, t); //r=reg to load, constant
C67_MVKH(C67_A0, t); //r=reg to load, constant
if (v != TREG_EAX && // check if not already in a conditional test reg
v != TREG_EDX && v != TREG_ST0 && v != C67_B2) {
C67_MV(v, C67_B2);
v = C67_B2;
}
C67_IREG_B_REG(inv, v, C67_A0); // [!R] B.S2x A0
C67_NOP(5);
t = ind1; //return where we need to patch
ind1 = ind;
}
}
vtop--;
return t;
@ -2179,34 +2153,34 @@ void gen_opi(int op)
if (op == TOK_LT) {
C67_CMPLT(r, fr, C67_B2);
C67_invert_test = false;
C67_invert_test = FALSE;
} else if (op == TOK_GE) {
C67_CMPLT(r, fr, C67_B2);
C67_invert_test = true;
C67_invert_test = TRUE;
} else if (op == TOK_GT) {
C67_CMPGT(r, fr, C67_B2);
C67_invert_test = false;
C67_invert_test = FALSE;
} else if (op == TOK_LE) {
C67_CMPGT(r, fr, C67_B2);
C67_invert_test = true;
C67_invert_test = TRUE;
} else if (op == TOK_EQ) {
C67_CMPEQ(r, fr, C67_B2);
C67_invert_test = false;
C67_invert_test = FALSE;
} else if (op == TOK_NE) {
C67_CMPEQ(r, fr, C67_B2);
C67_invert_test = true;
C67_invert_test = TRUE;
} else if (op == TOK_ULT) {
C67_CMPLTU(r, fr, C67_B2);
C67_invert_test = false;
C67_invert_test = FALSE;
} else if (op == TOK_UGE) {
C67_CMPLTU(r, fr, C67_B2);
C67_invert_test = true;
C67_invert_test = TRUE;
} else if (op == TOK_UGT) {
C67_CMPGTU(r, fr, C67_B2);
C67_invert_test = false;
C67_invert_test = FALSE;
} else if (op == TOK_ULE) {
C67_CMPGTU(r, fr, C67_B2);
C67_invert_test = true;
C67_invert_test = TRUE;
} else if (op == '+')
C67_ADD(fr, r); // ADD r,fr,r
else if (op == '-')
@ -2251,7 +2225,7 @@ void gen_opi(int op)
r = vtop[-1].r;
fr = vtop[0].r;
vtop--;
C67_MPYI(fr, r); // 32 bit bultiply fr,r,fr
C67_MPYI(fr, r); // 32 bit multiply fr,r,fr
C67_NOP(8); // NOP 8 for worst case
break;
case TOK_SHL:
@ -2308,7 +2282,7 @@ void gen_opi(int op)
}
/* generate a floating point operation 'v = t1 op t2' instruction. The
two operands are guaranted to have the same floating point type */
two operands are guaranteed to have the same floating point type */
/* XXX: need to use ST1 too */
void gen_opf(int op)
{
@ -2320,13 +2294,13 @@ void gen_opf(int op)
gv2(RC_FLOAT, RC_FLOAT); // make sure src2 is on b side
ft = vtop->type.t;
fc = vtop->c.ul;
fc = vtop->c.i;
r = vtop->r;
fr = vtop[-1].r;
if ((ft & VT_BTYPE) == VT_LDOUBLE)
error("long doubles not supported");
tcc_error("long doubles not supported");
if (op >= TOK_ULT && op <= TOK_GT) {
@ -2341,42 +2315,42 @@ void gen_opf(int op)
else
C67_CMPLTSP(r, fr, C67_B2);
C67_invert_test = false;
C67_invert_test = FALSE;
} else if (op == TOK_GE) {
if ((ft & VT_BTYPE) == VT_DOUBLE)
C67_CMPLTDP(r, fr, C67_B2);
else
C67_CMPLTSP(r, fr, C67_B2);
C67_invert_test = true;
C67_invert_test = TRUE;
} else if (op == TOK_GT) {
if ((ft & VT_BTYPE) == VT_DOUBLE)
C67_CMPGTDP(r, fr, C67_B2);
else
C67_CMPGTSP(r, fr, C67_B2);
C67_invert_test = false;
C67_invert_test = FALSE;
} else if (op == TOK_LE) {
if ((ft & VT_BTYPE) == VT_DOUBLE)
C67_CMPGTDP(r, fr, C67_B2);
else
C67_CMPGTSP(r, fr, C67_B2);
C67_invert_test = true;
C67_invert_test = TRUE;
} else if (op == TOK_EQ) {
if ((ft & VT_BTYPE) == VT_DOUBLE)
C67_CMPEQDP(r, fr, C67_B2);
else
C67_CMPEQSP(r, fr, C67_B2);
C67_invert_test = false;
C67_invert_test = FALSE;
} else if (op == TOK_NE) {
if ((ft & VT_BTYPE) == VT_DOUBLE)
C67_CMPEQDP(r, fr, C67_B2);
else
C67_CMPEQSP(r, fr, C67_B2);
C67_invert_test = true;
C67_invert_test = TRUE;
} else {
ALWAYS_ASSERT(FALSE);
}
@ -2478,7 +2452,7 @@ void gen_cvt_ftoi(int t)
r = vtop->r;
if (t != VT_INT)
error("long long not supported");
tcc_error("long long not supported");
else {
if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE) {
C67_DPTRUNC(r, r);
@ -2545,5 +2519,22 @@ void ggoto(void)
vtop--;
}
/* end of X86 code generator */
/* Save the stack pointer onto the stack and return the location of its address */
ST_FUNC void gen_vla_sp_save(int addr) {
tcc_error("variable length arrays unsupported for this target");
}
/* Restore the SP from a location on the stack */
ST_FUNC void gen_vla_sp_restore(int addr) {
tcc_error("variable length arrays unsupported for this target");
}
/* Subtract from the stack pointer, and push the resulting value onto the stack */
ST_FUNC void gen_vla_alloc(CType *type, int align) {
tcc_error("variable length arrays unsupported for this target");
}
/* end of C67 code generator */
/*************************************************************/
#endif
/*************************************************************/

131
c67-link.c 100644
View File

@ -0,0 +1,131 @@
#ifdef TARGET_DEFS_ONLY
#define EM_TCC_TARGET EM_C60
/* relocation type for 32 bit data relocation */
#define R_DATA_32 R_C60_32
#define R_DATA_PTR R_C60_32
#define R_JMP_SLOT R_C60_JMP_SLOT
#define R_GLOB_DAT R_C60_GLOB_DAT
#define R_COPY R_C60_COPY
#define R_RELATIVE R_C60_RELATIVE
#define R_NUM R_C60_NUM
#define ELF_START_ADDR 0x00000400
#define ELF_PAGE_SIZE 0x1000
#define PCRELATIVE_DLLPLT 0
#define RELOCATE_DLLPLT 0
#else /* !TARGET_DEFS_ONLY */
#include "tcc.h"
/* Returns 1 for a code relocation, 0 for a data relocation. For unknown
relocations, returns -1. */
int code_reloc (int reloc_type)
{
switch (reloc_type) {
case R_C60_32:
case R_C60LO16:
case R_C60HI16:
case R_C60_GOT32:
case R_C60_GOTOFF:
case R_C60_GOTPC:
case R_C60_COPY:
return 0;
case R_C60_PLT32:
return 1;
}
tcc_error ("Unknown relocation type: %d", reloc_type);
return -1;
}
/* Returns an enumerator to describe whether and when the relocation needs a
GOT and/or PLT entry to be created. See tcc.h for a description of the
different values. */
int gotplt_entry_type (int reloc_type)
{
switch (reloc_type) {
case R_C60_32:
case R_C60LO16:
case R_C60HI16:
case R_C60_COPY:
return NO_GOTPLT_ENTRY;
case R_C60_GOTOFF:
case R_C60_GOTPC:
return BUILD_GOT_ONLY;
case R_C60_PLT32:
case R_C60_GOT32:
return ALWAYS_GOTPLT_ENTRY;
}
tcc_error ("Unknown relocation type: %d", reloc_type);
return -1;
}
ST_FUNC unsigned create_plt_entry(TCCState *s1, unsigned got_offset, struct sym_attr *attr)
{
tcc_error("C67 got not implemented");
return 0;
}
/* relocate the PLT: compute addresses and offsets in the PLT now that final
address for PLT and GOT are known (see fill_program_header) */
ST_FUNC void relocate_plt(TCCState *s1)
{
uint8_t *p, *p_end;
if (!s1->plt)
return;
p = s1->plt->data;
p_end = p + s1->plt->data_offset;
if (p < p_end) {
/* XXX: TODO */
while (p < p_end) {
/* XXX: TODO */
}
}
}
void relocate_init(Section *sr) {}
void relocate(TCCState *s1, ElfW_Rel *rel, int type, unsigned char *ptr, addr_t addr, addr_t val)
{
switch(type) {
case R_C60_32:
*(int *)ptr += val;
break;
case R_C60LO16:
{
uint32_t orig;
/* put the low 16 bits of the absolute address add to what is
already there */
orig = ((*(int *)(ptr )) >> 7) & 0xffff;
orig |= (((*(int *)(ptr+4)) >> 7) & 0xffff) << 16;
/* patch both at once - assumes always in pairs Low - High */
*(int *) ptr = (*(int *) ptr & (~(0xffff << 7)) ) |
(((val+orig) & 0xffff) << 7);
*(int *)(ptr+4) = (*(int *)(ptr+4) & (~(0xffff << 7)) ) |
((((val+orig)>>16) & 0xffff) << 7);
}
break;
case R_C60HI16:
break;
default:
fprintf(stderr,"FIXME: handle reloc type %x at %x [%p] to %x\n",
type, (unsigned) addr, ptr, (unsigned) val);
break;
}
}
#endif /* !TARGET_DEFS_ONLY */

8
coff.h
View File

@ -22,7 +22,7 @@ struct filehdr {
/*------------------------------------------------------------------------*/
#define F_RELFLG 0x01 /* relocation info stripped from file */
#define F_EXEC 0x02 /* file is executable (no unresolved refs) */
#define F_LNNO 0x04 /* line nunbers stripped from file */
#define F_LNNO 0x04 /* line numbers stripped from file */
#define F_LSYMS 0x08 /* local symbols stripped from file */
#define F_GSP10 0x10 /* 34010 version */
#define F_GSP20 0x20 /* 34020 version */
@ -37,8 +37,8 @@ struct filehdr {
#define F_BYTE_ORDER (F_LITTLE | F_BIG)
#define FILHDR struct filehdr
//#define FILHSZ sizeof(FILHDR)
#define FILHSZ 22 // above rounds to align on 4 bytes which causes problems
/* #define FILHSZ sizeof(FILHDR) */
#define FILHSZ 22 /* above rounds to align on 4 bytes which causes problems */
#define COFF_C67_MAGIC 0x00c2
@ -150,7 +150,7 @@ struct scnhdr {
/*------------------------------------------------------------------------*/
/* Define constants for names of "special" sections */
/*------------------------------------------------------------------------*/
//#define _TEXT ".text"
/* #define _TEXT ".text" */
#define _DATA ".data"
#define _BSS ".bss"
#define _CINIT ".cinit"

686
configure vendored
View File

@ -1,25 +1,22 @@
#!/bin/sh
#
# tcc configure script (c) 2003 Fabrice Bellard
#
# set temporary file name
if test ! -z "$TMPDIR" ; then
TMPDIR1="${TMPDIR}"
elif test ! -z "$TEMPDIR" ; then
TMPDIR1="${TEMPDIR}"
else
TMPDIR1="/tmp"
fi
TMPC="${TMPDIR1}/tcc-conf-${RANDOM}-$$-${RANDOM}.c"
TMPO="${TMPDIR1}/tcc-conf-${RANDOM}-$$-${RANDOM}.o"
TMPE="${TMPDIR1}/tcc-conf-${RANDOM}-$$-${RANDOM}"
TMPS="${TMPDIR1}/tcc-conf-${RANDOM}-$$-${RANDOM}.S"
TMPH="${TMPDIR1}/tcc-conf-${RANDOM}-$$-${RANDOM}.h"
# set temporary file name
# if test ! -z "$TMPDIR" ; then
# TMPDIR1="${TMPDIR}"
# elif test ! -z "$TEMPDIR" ; then
# TMPDIR1="${TEMPDIR}"
# else
# TMPDIR1="/tmp"
# fi
#
# bashism: TMPN="${TMPDIR1}/tcc-conf-${RANDOM}-$$-${RANDOM}.c"
TMPN="./conftest-$$"
TMPH=$TMPN.h
# default parameters
build_cross="no"
use_libgcc="no"
prefix=""
execprefix=""
bindir=""
@ -27,63 +24,48 @@ libdir=""
tccdir=""
includedir=""
mandir=""
infodir=""
sysroot=""
cross_prefix=""
cc="gcc"
host_cc="gcc"
ar="ar"
strip="strip"
cpu=`uname -m`
case "$cpu" in
i386|i486|i586|i686|i86pc|BePC)
cpu="x86"
;;
x86_64)
cpu="x86-64"
;;
armv4l)
cpu="armv4l"
;;
alpha)
cpu="alpha"
;;
"Power Macintosh"|ppc|ppc64)
cpu="powerpc"
;;
mips)
cpu="mips"
;;
s390)
cpu="s390"
;;
*)
cpu="unknown"
;;
esac
gprof="no"
bigendian="no"
mingw32="no"
LIBSUF=".a"
EXESUF=""
DLLSUF=".so"
tcc_sysincludepaths=""
tcc_libpaths=""
tcc_crtprefix=""
tcc_elfinterp=""
triplet=
tcc_lddir=
confvars=
suggest="yes"
cpu=
cpuver=
gcc_major=0
gcc_minor=0
# OS specific
targetos=`uname -s`
targetos=`uname`
case $targetos in
MINGW32*)
mingw32="yes"
;;
DragonFly)
noldl="yes"
;;
OpenBSD)
noldl="yes"
;;
*) ;;
Darwin)
confvars="$confvars OSX"
DLLSUF=".dylib"
;;
MINGW*|MSYS*|CYGWIN*)
mingw32=yes
;;
DragonFly|OpenBSD|FreeBSD|NetBSD)
confvars="$confvars ldl=no"
;;
*)
;;
esac
# find source path
# XXX: we assume an absolute path is given when launching configure,
# except in './configure' case.
source_path=${0%configure}
source_path=${source_path%/}
source_path_used="yes"
@ -93,19 +75,28 @@ if test -z "$source_path" -o "$source_path" = "." ; then
fi
for opt do
eval opt=\"$opt\"
case "$opt" in
--prefix=*) prefix=`echo $opt | cut -d '=' -f 2`
;;
--exec-prefix=*) execprefix=`echo $opt | cut -d '=' -f 2`
;;
--tccdir=*) tccdir=`echo $opt | cut -d '=' -f 2`
;;
--bindir=*) bindir=`echo $opt | cut -d '=' -f 2`
;;
--libdir=*) libdir=`echo $opt | cut -d '=' -f 2`
;;
--includedir=*) includedir=`echo $opt | cut -d '=' -f 2`
;;
--sharedir=*) sharedir=`echo $opt | cut -d '=' -f 2`
;;
--mandir=*) mandir=`echo $opt | cut -d '=' -f 2`
;;
--infodir=*) infodir=`echo $opt | cut -d '=' -f 2`
;;
--docdir=*) docdir=`echo $opt | cut -d '=' -f 2`
;;
--sysroot=*) sysroot=`echo $opt | cut -d '=' -f 2`
;;
--source-path=*) source_path=`echo $opt | cut -d '=' -f 2`
@ -114,266 +105,386 @@ for opt do
;;
--cc=*) cc=`echo $opt | cut -d '=' -f 2`
;;
--ar=*) ar=`echo $opt | cut -d '=' -f 2`
;;
--extra-cflags=*) CFLAGS="${opt#--extra-cflags=}"
;;
--extra-ldflags=*) LDFLAGS="${opt#--extra-ldflags=}"
;;
--extra-libs=*) extralibs=${opt#--extra-libs=}
--extra-libs=*) extralibs="${opt#--extra-libs=}"
;;
--sysincludepaths=*) tcc_sysincludepaths=`echo $opt | cut -d '=' -f 2`
;;
--libpaths=*) tcc_libpaths=`echo $opt | cut -d '=' -f 2`
;;
--crtprefix=*) tcc_crtprefix=`echo $opt | cut -d '=' -f 2`
;;
--elfinterp=*) tcc_elfinterp=`echo $opt | cut -d '=' -f 2`
;;
--triplet=*) triplet=`echo $opt | cut -d '=' -f 2`
;;
--cpu=*) cpu=`echo $opt | cut -d '=' -f 2`
;;
--enable-gprof) gprof="yes"
--enable-cross) confvars="$confvars cross"
;;
--enable-mingw32) mingw32="yes" ; cross_prefix="i386-mingw32-"
;;
--enable-cross) build_cross="yes"
--disable-static) confvars="$confvars static=no"
;;
--with-libgcc) use_libgcc="yes"
--enable-static) confvars="$confvars static"
;;
--disable-rpath) confvars="$confvars rpath=no"
;;
--strip-binaries) confvars="$confvars strip"
;;
--with-libgcc) confvars="$confvars libgcc"
;;
--with-selinux) confvars="$confvars selinux"
;;
--config-mingw32*) mingw32=$(echo "$opt=yes" | cut -d '=' -f 2)
;;
--config-*) confvars="$confvars ${opt#--config-}"; suggest="no"
;;
--help|-h) show_help="yes"
;;
*) echo "configure: WARNING: unrecognized option $opt"
;;
esac
done
if test -z "$cpu" ; then
if test -n "$ARCH" ; then
cpu="$ARCH"
else
cpu=`uname -m`
fi
fi
case "$cpu" in
x86|i386|i486|i586|i686|i86pc|BePC|i686-AT386)
cpu="i386"
;;
x86_64|amd64|x86-64)
cpu="x86_64"
;;
arm*)
case "$cpu" in
arm|armv4l)
cpuver=4
;;
armv5tel|armv5tejl)
cpuver=5
;;
armv6j|armv6l)
cpuver=6
;;
armv7a|armv7l)
cpuver=7
;;
esac
cpu="arm"
;;
aarch64)
cpu="aarch64"
;;
alpha)
cpu="alpha"
;;
"Power Macintosh"|ppc|ppc64)
cpu="ppc"
;;
mips)
cpu="mips"
;;
s390)
cpu="s390"
;;
*)
echo "Unsupported CPU"
exit 1
;;
esac
# Checking for CFLAGS
if test -z "$CFLAGS"; then
CFLAGS="-O2"
CFLAGS="-Wall -g -O2"
fi
if test "$mingw32" = "yes" ; then
if test "$source_path_used" = "no"; then
source_path="."
fi
if test "$cc" = gcc; then
test -z "$LDFLAGS" && LDFLAGS="-static"
fi
test -z "$prefix" && prefix="C:/Program Files/tcc"
test -z "$tccdir" && tccdir="${prefix}"
test -z "$bindir" && bindir="${tccdir}"
test -z "$docdir" && docdir="${tccdir}/doc"
test -z "$libdir" && libdir="${tccdir}/libtcc"
confvars="$confvars WIN32"
LIBSUF=".lib"
EXESUF=".exe"
DLLSUF=".dll"
else
if test -z "$prefix" ; then
prefix="/usr/local"
fi
if test -z "$sharedir" ; then
sharedir="${prefix}/share"
fi
if test x"$execprefix" = x""; then
execprefix="${prefix}"
fi
if test x"$libdir" = x""; then
libdir="${execprefix}/lib"
fi
if test x"$bindir" = x""; then
bindir="${execprefix}/bin"
fi
if test x"$docdir" = x""; then
docdir="${sharedir}/doc"
fi
if test x"$mandir" = x""; then
mandir="${sharedir}/man"
fi
if test x"$infodir" = x""; then
infodir="${sharedir}/info"
fi
if test x"$tccdir" = x""; then
tccdir="${libdir}/tcc"
fi
if test x"$includedir" = x""; then
includedir="${prefix}/include"
fi
fi # mingw32
if test x"$show_help" = "xyes" ; then
cat << EOF
Usage: configure [options]
Options: [defaults in brackets after descriptions]
Standard options:
--help print this message
--prefix=PREFIX install in PREFIX [$prefix]
--exec-prefix=EPREFIX install architecture-dependent files in EPREFIX
[same as prefix]
--bindir=DIR user executables in DIR [EPREFIX/bin]
--libdir=DIR object code libraries in DIR [EPREFIX/lib]
--tccdir=DIR installation directory [EPREFIX/lib/tcc]
--includedir=DIR C header files in DIR [PREFIX/include]
--sharedir=DIR documentation root DIR [PREFIX/share]
--docdir=DIR documentation in DIR [SHAREDIR/doc/tcc]
--mandir=DIR man documentation in DIR [SHAREDIR/man]
--infodir=DIR info documentation in DIR [SHAREDIR/info]
Advanced options (experts only):
--source-path=PATH path of source code [$source_path]
--cross-prefix=PREFIX use PREFIX for compile tools [$cross_prefix]
--sysroot=PREFIX prepend PREFIX to library/include paths []
--cc=CC use C compiler CC [$cc]
--ar=AR create archives using AR [$ar]
--extra-cflags= specify compiler flags [$CFLAGS]
--extra-ldflags= specify linker options []
--cpu=CPU CPU [$cpu]
--strip-binaries strip symbol tables from resulting binaries
--disable-static make libtcc.so instead of libtcc.a
--enable-static make libtcc.a instead of libtcc.dll (win32)
--disable-rpath disable use of -rpath with the above
--with-libgcc use libgcc_s.so.1 instead of libtcc1.a
--enable-cross build cross compilers
--with-selinux use mmap for executable memory (with tcc -run)
--sysincludepaths=... specify system include paths, colon separated
--libpaths=... specify system library paths, colon separated
--crtprefix=... specify locations of crt?.o, colon separated
--elfinterp=... specify elf interpreter
--triplet=... specify system library/include directory triplet
--config-uClibc,-musl,-mingw32... enable system specific configurations
EOF
#echo "NOTE: The object files are build at the place where configure is launched"
exit 1
fi
cc="${cross_prefix}${cc}"
ar="${cross_prefix}${ar}"
strip="${cross_prefix}${strip}"
if test "$mingw32" = "yes" ; then
LIBSUF=".lib"
EXESUF=".exe"
fi
if test -z "$cross_prefix" ; then
CONFTEST=./conftest$EXESUF
if ! $cc -o $CONFTEST $source_path/conftest.c 2>/dev/null ; then
echo "configure: error: '$cc' failed to compile conftest.c."
else
gcc_major="$($CONFTEST version)"
gcc_minor="$($CONFTEST minor)"
fi
bigendian="$($CONFTEST bigendian)"
if test "$mingw32" = "no" ; then
# ---
# big/little endian test
cat > $TMPC << EOF
#include <inttypes.h>
int main(int argc, char ** argv){
volatile uint32_t i=0x01234567;
return (*((uint8_t*)(&i))) == 0x67;
}
EOF
if test -z "$triplet"; then
tt="$($CONFTEST triplet)"
if test -n "$tt" -a -f "/usr/lib/$tt/crti.o" ; then
triplet="$tt"
fi
fi
if $cc -o $TMPE $TMPC 2>/dev/null ; then
$TMPE && bigendian="yes"
if test -z "$triplet"; then
if test $cpu = "x86_64" -o $cpu = "aarch64" ; then
if test -f "/usr/lib64/crti.o" ; then
tcc_lddir="lib64"
fi
fi
fi
if test "$cpu" = "arm" ; then
if test "${triplet%eabihf}" != "$triplet" ; then
confvars="$confvars arm_eabihf"
elif test "${triplet%eabi}" != "$triplet" ; then
confvars="$confvars arm_eabi"
fi
if grep -s -q "^Features.* \(vfp\|iwmmxt\) " /proc/cpuinfo ; then
confvars="$confvars arm_vfp"
fi
fi
if test "$suggest" = "yes"; then
if test -f "/lib/ld-uClibc.so.0" ; then
echo "Perhaps you want ./configure --config-uClibc"
fi
if test -f "/lib/ld-musl-$cpu.so.1"; then
echo "Perhaps you want ./configure --config-musl"
fi
fi
fi
else
echo big/little test failed
# if cross compiling, cannot launch a program, so make a static guess
case $cpu in
ppc|mips|s390) bigendian=yes;;
esac
fi
else
# if cross compiling, cannot launch a program, so make a static guess
if test "$cpu" = "powerpc" -o "$cpu" = "mips" -o "$cpu" = "s390" ; then
bigendian="yes"
if test "$bigendian" = "yes" ; then
confvars="$confvars BIGENDIAN"
fi
# a final configuration tuning
if ! echo "$cc" | grep -q "tcc"; then
OPT1="-Wdeclaration-after-statement -fno-strict-aliasing"
# we want -Wno- but gcc does not always reject unknown -Wno- options
OPT2="-Wpointer-sign -Wsign-compare -Wunused-result"
if echo "$cc" | grep -q "clang"; then
OPT1="$OPT1 -fheinous-gnu-extensions"
OPT2="$OPT2 -Wstring-plus-int"
fi
$cc $OPT1 $OPT2 -o a.out -c -xc - < /dev/null > cc_msg.txt 2>&1
for o in $OPT1; do # enable these options
if ! grep -q -- $o cc_msg.txt; then CFLAGS="$CFLAGS $o"; fi
done
for o in $OPT2; do # disable these options
if ! grep -q -- $o cc_msg.txt; then CFLAGS="$CFLAGS -Wno-${o#-W*}"; fi
done
# cat cc_msg.txt
# echo $CFLAGS
rm -f cc_msg.txt a.out
fi
# check gcc version
cat > $TMPC <<EOF
int main(void) {
#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)
return 0;
#else
#error gcc < 3.2
#endif
}
EOF
gcc_major="2"
if $cc -o $TMPO $TMPC 2> /dev/null ; then
gcc_major="3"
fi
cat > $TMPC <<EOF
int main(void) {
#if __GNUC__ >= 4
return 0;
#else
#error gcc < 4
#endif
}
EOF
if $cc -o $TMPO $TMPC 2> /dev/null ; then
gcc_major="4"
fi
if test x"$show_help" = "xyes" ; then
cat << EOF
Usage: configure [options]
Options: [defaults in brackets after descriptions]
EOF
echo "Standard options:"
echo " --help print this message"
echo " --prefix=PREFIX install in PREFIX [$prefix]"
echo " --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX"
echo " [same as prefix]"
echo " --bindir=DIR user executables in DIR [EPREFIX/bin]"
echo " --libdir=DIR object code libraries in DIR [EPREFIX/lib]"
echo " --includedir=DIR C header files in DIR [PREFIX/include]"
echo " --mandir=DIR man documentation in DIR [PREFIX/man]"
echo " --enable-cross build cross compilers"
echo ""
echo "Advanced options (experts only):"
echo " --source-path=PATH path of source code [$source_path]"
echo " --cross-prefix=PREFIX use PREFIX for compile tools [$cross_prefix]"
echo " --sysroot=PREFIX prepend PREFIX to library/include paths []"
echo " --cc=CC use C compiler CC [$cc]"
echo " --with-libgcc use /lib/libgcc_s.so.1 instead of libtcc1.a"
echo ""
#echo "NOTE: The object files are build at the place where configure is launched"
exit 1
fi
if test "$mingw32" = "yes" ; then
if test -z "$prefix" ; then
prefix="C:/Program Files/tcc"
fi
execprefix="$prefix"
bindir="$prefix"
tccdir="$prefix"
docdir="$prefix/doc"
else
if test -z "$prefix" ; then
prefix="/usr/local"
fi
if test x"$execprefix" = x""; then
execprefix="${prefix}"
fi
if test x"$bindir" = x""; then
bindir="${execprefix}/bin"
fi
if test x"$docdir" = x""; then
docdir="$prefix/share/doc/tcc"
fi
fi # mingw32
if test x"$libdir" = x""; then
libdir="${execprefix}/lib"
fi
if test x"$tccdir" = x""; then
tccdir="${execprefix}/lib/tcc"
fi
if test x"$mandir" = x""; then
mandir="${prefix}/man"
fi
if test x"$includedir" = x""; then
includedir="${prefix}/include"
fi
echo "Binary directory $bindir"
echo "TinyCC directory $tccdir"
echo "Library directory $libdir"
echo "Include directory $includedir"
echo "Manual directory $mandir"
echo "Doc directory $docdir"
echo "Target root prefix $sysroot"
echo "Source path $source_path"
echo "C compiler $cc"
echo "CPU $cpu"
echo "Big Endian $bigendian"
echo "gprof enabled $gprof"
echo "cross compilers $build_cross"
echo "use libgcc $use_libgcc"
fcho() { if test -n "$2"; then echo "$1$2"; fi }
fcho "Binary directory " "$bindir"
fcho "TinyCC directory " "$tccdir"
fcho "Library directory " "$libdir"
fcho "Include directory " "$includedir"
fcho "Manual directory " "$mandir"
fcho "Info directory " "$infodir"
fcho "Doc directory " "$docdir"
fcho "Target root prefix " "$sysroot"
echo "Source path $source_path"
echo "C compiler $cc ($gcc_major.$gcc_minor)"
echo "Target OS $targetos"
echo "CPU $cpu"
fcho "Triplet " "$triplet"
fcho "Config " "${confvars# }"
echo "Creating config.mak and config.h"
echo "# Automatically generated by configure - do not modify" > config.mak
cat >config.mak <<EOF
# Automatically generated by configure - do not modify
prefix=$prefix
bindir=\$(DESTDIR)$bindir
tccdir=\$(DESTDIR)$tccdir
libdir=\$(DESTDIR)$libdir
includedir=\$(DESTDIR)$includedir
mandir=\$(DESTDIR)$mandir
infodir=\$(DESTDIR)$infodir
docdir=\$(DESTDIR)$docdir
CC=$cc
GCC_MAJOR=$gcc_major
GCC_MINOR=$gcc_minor
AR=$ar
STRIP=$strip -s -R .comment -R .note
CFLAGS=$CFLAGS
LDFLAGS=$LDFLAGS
LIBSUF=$LIBSUF
EXESUF=$EXESUF
DLLSUF=$DLLSUF
EOF
print_inc() {
if test -n "$2"; then
echo "#ifndef $1" >> $TMPH
echo "# define $1 \"$2\"" >> $TMPH
echo "#endif" >> $TMPH
fi
}
print_mak() {
if test -n "$2"; then
echo "NATIVE_DEFINES+=-D$1=\"\\\"$2\\\"\"" >> config.mak
fi
}
print_mak_int() {
if test -n "$2"; then
echo "NATIVE_DEFINES+=-D$1=$2" >> config.mak
fi
}
echo "/* Automatically generated by configure - do not modify */" > $TMPH
echo "prefix=\$(DESTDIR)$prefix" >> config.mak
echo "bindir=\$(DESTDIR)$bindir" >> config.mak
echo "tccdir=\$(DESTDIR)$tccdir" >> config.mak
echo "libdir=\$(DESTDIR)$libdir" >> config.mak
echo "includedir=\$(DESTDIR)$includedir" >> config.mak
echo "mandir=\$(DESTDIR)$mandir" >> config.mak
echo "docdir=\$(DESTDIR)$docdir" >> config.mak
print_inc CONFIG_SYSROOT "$sysroot"
print_inc CONFIG_TCCDIR "$tccdir"
print_mak CONFIG_TCC_SYSINCLUDEPATHS "$tcc_sysincludepaths"
print_mak CONFIG_TCC_LIBPATHS "$tcc_libpaths"
print_mak CONFIG_TCC_CRTPREFIX "$tcc_crtprefix"
print_mak CONFIG_TCC_ELFINTERP "$tcc_elfinterp"
print_mak CONFIG_LDDIR "$tcc_lddir"
print_mak CONFIG_TRIPLET "$triplet"
print_mak_int TCC_CPU_VERSION "$cpuver"
echo "#define CONFIG_SYSROOT \"$sysroot\"" >> $TMPH
echo "#define CONFIG_TCCDIR \"$tccdir\"" >> $TMPH
echo "CC=$cc" >> config.mak
echo "GCC_MAJOR=$gcc_major" >> config.mak
echo "#define GCC_MAJOR $gcc_major" >> $TMPH
echo "HOST_CC=$host_cc" >> config.mak
echo "AR=$ar" >> config.mak
echo "STRIP=$strip -s -R .comment -R .note" >> config.mak
echo "CFLAGS=$CFLAGS" >> config.mak
echo "LDFLAGS=$LDFLAGS" >> config.mak
echo "LIBSUF=$LIBSUF" >> config.mak
echo "EXESUF=$EXESUF" >> config.mak
if test "$cpu" = "x86" ; then
echo "ARCH=i386" >> config.mak
echo "#define HOST_I386 1" >> $TMPH
elif test "$cpu" = "x86-64" ; then
echo "ARCH=x86-64" >> config.mak
echo "#define HOST_X86_64 1" >> $TMPH
elif test "$cpu" = "armv4l" ; then
echo "ARCH=arm" >> config.mak
echo "#define HOST_ARM 1" >> $TMPH
elif test "$cpu" = "powerpc" ; then
echo "ARCH=ppc" >> config.mak
echo "#define HOST_PPC 1" >> $TMPH
elif test "$cpu" = "mips" ; then
echo "ARCH=mips" >> config.mak
echo "#define HOST_MIPS 1" >> $TMPH
elif test "$cpu" = "s390" ; then
echo "ARCH=s390" >> config.mak
echo "#define HOST_S390 1" >> $TMPH
elif test "$cpu" = "alpha" ; then
echo "ARCH=alpha" >> config.mak
echo "#define HOST_ALPHA 1" >> $TMPH
if test "$cpu" = "aarch64" ; then
echo "ARCH=arm64" >> config.mak
else
echo "Unsupported CPU"
exit 1
fi
if test "$noldl" = "yes" ; then
echo "CONFIG_NOLDL=yes" >> config.mak
fi
if test "$mingw32" = "yes" ; then
echo "CONFIG_WIN32=yes" >> config.mak
echo "#define CONFIG_WIN32 1" >> $TMPH
fi
if test "$bigendian" = "yes" ; then
echo "WORDS_BIGENDIAN=yes" >> config.mak
echo "#define WORDS_BIGENDIAN 1" >> $TMPH
fi
if test "$gprof" = "yes" ; then
echo "TARGET_GPROF=yes" >> config.mak
echo "#define HAVE_GPROF 1" >> $TMPH
fi
if test "$build_cross" = "yes" ; then
echo "CONFIG_CROSS=yes" >> config.mak
fi
if test "$use_libgcc" = "yes" ; then
echo "#define CONFIG_USE_LIBGCC" >> $TMPH
echo "CONFIG_USE_LIBGCC=yes" >> config.mak
echo "ARCH=$cpu" >> config.mak
fi
echo "TARGETOS=$targetos" >> config.mak
for v in $confvars ; do
if test "${v%=*}" = "$v"; then
echo "CONFIG_$v=yes" >> config.mak
else
echo "CONFIG_$v" >> config.mak
fi
done
version=`head $source_path/VERSION`
echo "VERSION=$version" >>config.mak
echo "VERSION = $version" >> config.mak
echo "#define TCC_VERSION \"$version\"" >> $TMPH
echo "@set VERSION $version" > config.texi
# build tree in object directory if source path is different from current one
if test "$source_path_used" = "yes" ; then
DIRS="tests"
FILES="Makefile tests/Makefile"
for dir in $DIRS ; do
mkdir -p $dir
done
for f in $FILES ; do
ln -sf $source_path/$f $f
done
case $source_path in
/*) echo "TOPSRC=$source_path";;
*) echo "TOPSRC=\$(TOP)/$source_path";;
esac >>config.mak
else
echo 'TOPSRC=$(TOP)' >>config.mak
fi
echo "SRC_PATH=$source_path" >> config.mak
diff $TMPH config.h >/dev/null 2>&1
if test $? -ne 0 ; then
@ -382,4 +493,35 @@ else
echo "config.h is unchanged"
fi
rm -f $TMPO $TMPC $TMPE $TMPS $TMPH
rm -f $TMPN* $CONFTEST
# ---------------------------------------------------------------------------
# build tree in object directory if source path is different from current one
fn_makelink()
{
tgt=$1/$2
case $2 in
*/*) dn=${2%/*}
test -d $dn || mkdir -p $dn
case $1 in
/*) ;;
*) while test $dn ; do
tgt=../$tgt; dn=${dn#${dn%%/*}}; dn=${dn#/}
done
;;
esac
;;
esac
ln -sfn $tgt $2 || ( echo "ln failed. Using cp instead."; cp -f $1/$2 $2 )
}
if test "$source_path_used" = "yes" ; then
FILES="Makefile lib/Makefile tests/Makefile tests/tests2/Makefile tests/pp/Makefile"
for f in $FILES ; do
fn_makelink $source_path $f
done
fi
# ---------------------------------------------------------------------------

87
conftest.c 100644
View File

@ -0,0 +1,87 @@
#include <stdio.h>
/* Define architecture */
#if defined(__i386__) || defined _M_IX86
# define TRIPLET_ARCH "i386"
#elif defined(__x86_64__) || defined _M_AMD64
# define TRIPLET_ARCH "x86_64"
#elif defined(__arm__)
# define TRIPLET_ARCH "arm"
#elif defined(__aarch64__)
# define TRIPLET_ARCH "aarch64"
#else
# define TRIPLET_ARCH "unknown"
#endif
/* Define OS */
#if defined (__linux__)
# define TRIPLET_OS "linux"
#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
# define TRIPLET_OS "kfreebsd"
#elif defined _WIN32
# define TRIPLET_OS "win32"
#elif !defined (__GNU__)
# define TRIPLET_OS "unknown"
#endif
/* Define calling convention and ABI */
#if defined (__ARM_EABI__)
# if defined (__ARM_PCS_VFP)
# define TRIPLET_ABI "gnueabihf"
# else
# define TRIPLET_ABI "gnueabi"
# endif
#else
# define TRIPLET_ABI "gnu"
#endif
#if defined _WIN32
# define TRIPLET TRIPLET_ARCH "-" TRIPLET_OS
#elif defined __GNU__
# define TRIPLET TRIPLET_ARCH "-" TRIPLET_ABI
#else
# define TRIPLET TRIPLET_ARCH "-" TRIPLET_OS "-" TRIPLET_ABI
#endif
#if defined(_WIN32)
int _CRT_glob = 0;
#endif
int main(int argc, char *argv[])
{
switch(argc == 2 ? argv[1][0] : 0) {
case 'b':
{
volatile unsigned foo = 0x01234567;
puts(*(unsigned char*)&foo == 0x67 ? "no" : "yes");
break;
}
#ifdef __GNUC__
case 'm':
printf("%d\n", __GNUC_MINOR__);
break;
case 'v':
printf("%d\n", __GNUC__);
break;
#elif defined __TINYC__
case 'v':
puts("0");
break;
case 'm':
printf("%d\n", __TINYC__);
break;
#else
case 'm':
case 'v':
puts("0");
break;
#endif
case 't':
puts(TRIPLET);
break;
default:
break;
}
return 0;
}

4083
elf.h

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
#! /usr/local/bin/tcc -run
#!/usr/local/bin/tcc -run
#include <tcclib.h>
int main()

View File

@ -1,5 +1,4 @@
#include <stdlib.h>
#include <stdio.h>
#include <tcclib.h>
int fib(n)
{

View File

@ -1,4 +1,4 @@
#!./tcc -run -L/usr/X11R6/lib -lX11
#!/usr/local/bin/tcc -run -L/usr/X11R6/lib -lX11
#include <stdlib.h>
#include <stdio.h>
#include <X11/Xlib.h>

1331
i386-asm.c

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +1,12 @@
DEF_ASM_OP0(pusha, 0x60) /* must be first OP0 */
DEF_ASM_OP0(popa, 0x61)
DEF_ASM_OP0(clc, 0xf8)
DEF_ASM_OP0(clc, 0xf8) /* must be first OP0 */
DEF_ASM_OP0(cld, 0xfc)
DEF_ASM_OP0(cli, 0xfa)
DEF_ASM_OP0(clts, 0x0f06)
DEF_ASM_OP0(cmc, 0xf5)
DEF_ASM_OP0(lahf, 0x9f)
DEF_ASM_OP0(sahf, 0x9e)
DEF_ASM_OP0(pusha, 0x60)
DEF_ASM_OP0(popa, 0x61)
DEF_ASM_OP0(pushfl, 0x9c)
DEF_ASM_OP0(popfl, 0x9d)
DEF_ASM_OP0(pushf, 0x9c)
@ -33,53 +33,53 @@
DEF_ASM_OP0(iret, 0xcf)
DEF_ASM_OP0(rsm, 0x0faa)
DEF_ASM_OP0(hlt, 0xf4)
DEF_ASM_OP0(wait, 0x9b)
DEF_ASM_OP0(nop, 0x90)
DEF_ASM_OP0(pause, 0xf390)
DEF_ASM_OP0(xlat, 0xd7)
/* strings */
ALT(DEF_ASM_OP0L(cmpsb, 0xa6, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(scmpb, 0xa6, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(cmpsb, 0xa6, 0, OPC_BWLX))
ALT(DEF_ASM_OP0L(scmpb, 0xa6, 0, OPC_BWLX))
ALT(DEF_ASM_OP0L(insb, 0x6c, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(outsb, 0x6e, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(lodsb, 0xac, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(slodb, 0xac, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(lodsb, 0xac, 0, OPC_BWLX))
ALT(DEF_ASM_OP0L(slodb, 0xac, 0, OPC_BWLX))
ALT(DEF_ASM_OP0L(movsb, 0xa4, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(smovb, 0xa4, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(movsb, 0xa4, 0, OPC_BWLX))
ALT(DEF_ASM_OP0L(smovb, 0xa4, 0, OPC_BWLX))
ALT(DEF_ASM_OP0L(scasb, 0xae, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(sscab, 0xae, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(scasb, 0xae, 0, OPC_BWLX))
ALT(DEF_ASM_OP0L(sscab, 0xae, 0, OPC_BWLX))
ALT(DEF_ASM_OP0L(stosb, 0xaa, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(sstob, 0xaa, 0, OPC_BWL))
ALT(DEF_ASM_OP0L(stosb, 0xaa, 0, OPC_BWLX))
ALT(DEF_ASM_OP0L(sstob, 0xaa, 0, OPC_BWLX))
/* bits */
ALT(DEF_ASM_OP2(bsfw, 0x0fbc, 0, OPC_MODRM | OPC_WL, OPT_REGW | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(bsrw, 0x0fbd, 0, OPC_MODRM | OPC_WL, OPT_REGW | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(bsfw, 0x0fbc, 0, OPC_MODRM | OPC_WLX, OPT_REGW | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(bsrw, 0x0fbd, 0, OPC_MODRM | OPC_WLX, OPT_REGW | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(btw, 0x0fa3, 0, OPC_MODRM | OPC_WL, OPT_REGW, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btw, 0x0fba, 4, OPC_MODRM | OPC_WL, OPT_IM8, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btw, 0x0fa3, 0, OPC_MODRM | OPC_WLX, OPT_REGW, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btw, 0x0fba, 4, OPC_MODRM | OPC_WLX, OPT_IM8, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btsw, 0x0fab, 0, OPC_MODRM | OPC_WL, OPT_REGW, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btsw, 0x0fba, 5, OPC_MODRM | OPC_WL, OPT_IM8, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btsw, 0x0fab, 0, OPC_MODRM | OPC_WLX, OPT_REGW, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btsw, 0x0fba, 5, OPC_MODRM | OPC_WLX, OPT_IM8, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btrw, 0x0fb3, 0, OPC_MODRM | OPC_WL, OPT_REGW, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btrw, 0x0fba, 6, OPC_MODRM | OPC_WL, OPT_IM8, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btrw, 0x0fb3, 0, OPC_MODRM | OPC_WLX, OPT_REGW, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btrw, 0x0fba, 6, OPC_MODRM | OPC_WLX, OPT_IM8, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btcw, 0x0fbb, 0, OPC_MODRM | OPC_WL, OPT_REGW, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btcw, 0x0fba, 7, OPC_MODRM | OPC_WL, OPT_IM8, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btcw, 0x0fbb, 0, OPC_MODRM | OPC_WLX, OPT_REGW, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP2(btcw, 0x0fba, 7, OPC_MODRM | OPC_WLX, OPT_IM8, OPT_REGW | OPT_EA))
/* prefixes */
DEF_ASM_OP0(wait, 0x9b)
DEF_ASM_OP0(fwait, 0x9b)
DEF_ASM_OP0(aword, 0x67)
DEF_ASM_OP0(addr16, 0x67)
DEF_ASM_OP0(a32, 0x67)
ALT(DEF_ASM_OP0(word, 0x66))
DEF_ASM_OP0(data16, 0x66)
DEF_ASM_OP0(o32, 0x66)
DEF_ASM_OP0(lock, 0xf0)
DEF_ASM_OP0(rep, 0xf3)
DEF_ASM_OP0(repe, 0xf3)
@ -97,43 +97,43 @@ ALT(DEF_ASM_OP2(btcw, 0x0fba, 7, OPC_MODRM | OPC_WL, OPT_IM8, OPT_REGW | OPT_EA)
DEF_ASM_OP0(ud2, 0x0f0b)
/* NOTE: we took the same order as gas opcode definition order */
ALT(DEF_ASM_OP2(movb, 0xa0, 0, OPC_BWL, OPT_ADDR, OPT_EAX))
ALT(DEF_ASM_OP2(movb, 0xa2, 0, OPC_BWL, OPT_EAX, OPT_ADDR))
ALT(DEF_ASM_OP2(movb, 0x88, 0, OPC_MODRM | OPC_BWL, OPT_REG, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(movb, 0x8a, 0, OPC_MODRM | OPC_BWL, OPT_EA | OPT_REG, OPT_REG))
ALT(DEF_ASM_OP2(movb, 0xb0, 0, OPC_REG | OPC_BWL, OPT_IM, OPT_REG))
ALT(DEF_ASM_OP2(movb, 0xc6, 0, OPC_MODRM | OPC_BWL, OPT_IM, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP2(movb, 0xa0, 0, OPC_BWLX, OPT_ADDR, OPT_EAX))
ALT(DEF_ASM_OP2(movb, 0xa2, 0, OPC_BWLX, OPT_EAX, OPT_ADDR))
ALT(DEF_ASM_OP2(movb, 0x88, 0, OPC_MODRM | OPC_BWLX, OPT_REG, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(movb, 0x8a, 0, OPC_MODRM | OPC_BWLX, OPT_EA | OPT_REG, OPT_REG))
ALT(DEF_ASM_OP2(movb, 0xb0, 0, OPC_REG | OPC_BWLX, OPT_IM, OPT_REG))
ALT(DEF_ASM_OP2(movb, 0xc6, 0, OPC_MODRM | OPC_BWLX, OPT_IM, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP2(movw, 0x8c, 0, OPC_MODRM | OPC_WL, OPT_SEG, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(movw, 0x8e, 0, OPC_MODRM | OPC_WL, OPT_EA | OPT_REG, OPT_SEG))
ALT(DEF_ASM_OP2(movw, 0x8c, 0, OPC_MODRM | OPC_WLX, OPT_SEG, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(movw, 0x8e, 0, OPC_MODRM | OPC_WLX, OPT_EA | OPT_REG, OPT_SEG))
ALT(DEF_ASM_OP2(movw, 0x0f20, 0, OPC_MODRM | OPC_WL, OPT_CR, OPT_REG32))
ALT(DEF_ASM_OP2(movw, 0x0f21, 0, OPC_MODRM | OPC_WL, OPT_DB, OPT_REG32))
ALT(DEF_ASM_OP2(movw, 0x0f24, 0, OPC_MODRM | OPC_WL, OPT_TR, OPT_REG32))
ALT(DEF_ASM_OP2(movw, 0x0f22, 0, OPC_MODRM | OPC_WL, OPT_REG32, OPT_CR))
ALT(DEF_ASM_OP2(movw, 0x0f23, 0, OPC_MODRM | OPC_WL, OPT_REG32, OPT_DB))
ALT(DEF_ASM_OP2(movw, 0x0f26, 0, OPC_MODRM | OPC_WL, OPT_REG32, OPT_TR))
ALT(DEF_ASM_OP2(movw, 0x0f20, 0, OPC_MODRM | OPC_WLX, OPT_CR, OPT_REG32))
ALT(DEF_ASM_OP2(movw, 0x0f21, 0, OPC_MODRM | OPC_WLX, OPT_DB, OPT_REG32))
ALT(DEF_ASM_OP2(movw, 0x0f24, 0, OPC_MODRM | OPC_WLX, OPT_TR, OPT_REG32))
ALT(DEF_ASM_OP2(movw, 0x0f22, 0, OPC_MODRM | OPC_WLX, OPT_REG32, OPT_CR))
ALT(DEF_ASM_OP2(movw, 0x0f23, 0, OPC_MODRM | OPC_WLX, OPT_REG32, OPT_DB))
ALT(DEF_ASM_OP2(movw, 0x0f26, 0, OPC_MODRM | OPC_WLX, OPT_REG32, OPT_TR))
ALT(DEF_ASM_OP2(movsbl, 0x0fbe, 0, OPC_MODRM, OPT_REG8 | OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(movsbw, 0x0fbe, 0, OPC_MODRM | OPC_D16, OPT_REG8 | OPT_EA, OPT_REG16))
ALT(DEF_ASM_OP2(movsbw, 0x660fbe, 0, OPC_MODRM, OPT_REG8 | OPT_EA, OPT_REG16))
ALT(DEF_ASM_OP2(movswl, 0x0fbf, 0, OPC_MODRM, OPT_REG16 | OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(movzbw, 0x0fb6, 0, OPC_MODRM | OPC_WL, OPT_REG8 | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(movzbw, 0x0fb6, 0, OPC_MODRM | OPC_WLX, OPT_REG8 | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(movzwl, 0x0fb7, 0, OPC_MODRM, OPT_REG16 | OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP1(pushw, 0x50, 0, OPC_REG | OPC_WL, OPT_REGW))
ALT(DEF_ASM_OP1(pushw, 0xff, 6, OPC_MODRM | OPC_WL, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP1(pushw, 0x68, 0, OPC_WL, OPT_IM32))
ALT(DEF_ASM_OP1(pushw, 0x06, 0, OPC_WL, OPT_SEG))
DEF_ASM_OP1(pushb, 0x6a, 0, OPC_B, OPT_IM8S)
ALT(DEF_ASM_OP1(pushw, 0x50, 0, OPC_REG | OPC_WLX, OPT_REGW))
ALT(DEF_ASM_OP1(pushw, 0xff, 6, OPC_MODRM | OPC_WLX, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP1(pushw, 0x6a, 0, OPC_WLX, OPT_IM8S))
ALT(DEF_ASM_OP1(pushw, 0x68, 0, OPC_WLX, OPT_IM32))
ALT(DEF_ASM_OP1(pushw, 0x06, 0, OPC_WLX, OPT_SEG))
ALT(DEF_ASM_OP1(popw, 0x58, 0, OPC_REG | OPC_WL, OPT_REGW))
ALT(DEF_ASM_OP1(popw, 0x8f, 0, OPC_MODRM | OPC_WL, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP1(popw, 0x07, 0, OPC_WL, OPT_SEG))
ALT(DEF_ASM_OP1(popw, 0x58, 0, OPC_REG | OPC_WLX, OPT_REGW))
ALT(DEF_ASM_OP1(popw, 0x8f, 0, OPC_MODRM | OPC_WLX, OPT_REGW | OPT_EA))
ALT(DEF_ASM_OP1(popw, 0x07, 0, OPC_WLX, OPT_SEG))
ALT(DEF_ASM_OP2(xchgw, 0x90, 0, OPC_REG | OPC_WL, OPT_REG, OPT_EAX))
ALT(DEF_ASM_OP2(xchgw, 0x90, 0, OPC_REG | OPC_WL, OPT_EAX, OPT_REG))
ALT(DEF_ASM_OP2(xchgb, 0x86, 0, OPC_MODRM | OPC_BWL, OPT_REG, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(xchgb, 0x86, 0, OPC_MODRM | OPC_BWL, OPT_EA | OPT_REG, OPT_REG))
ALT(DEF_ASM_OP2(xchgw, 0x90, 0, OPC_REG | OPC_WLX, OPT_REGW, OPT_EAX))
ALT(DEF_ASM_OP2(xchgw, 0x90, 0, OPC_REG | OPC_WLX, OPT_EAX, OPT_REGW))
ALT(DEF_ASM_OP2(xchgb, 0x86, 0, OPC_MODRM | OPC_BWLX, OPT_REG, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(xchgb, 0x86, 0, OPC_MODRM | OPC_BWLX, OPT_EA | OPT_REG, OPT_REG))
ALT(DEF_ASM_OP2(inb, 0xe4, 0, OPC_BWL, OPT_IM8, OPT_EAX))
ALT(DEF_ASM_OP1(inb, 0xe4, 0, OPC_BWL, OPT_IM8))
@ -145,7 +145,7 @@ ALT(DEF_ASM_OP1(outb, 0xe6, 0, OPC_BWL, OPT_IM8))
ALT(DEF_ASM_OP2(outb, 0xee, 0, OPC_BWL, OPT_EAX, OPT_DX))
ALT(DEF_ASM_OP1(outb, 0xee, 0, OPC_BWL, OPT_DX))
ALT(DEF_ASM_OP2(leaw, 0x8d, 0, OPC_MODRM | OPC_WL, OPT_EA, OPT_REG))
ALT(DEF_ASM_OP2(leaw, 0x8d, 0, OPC_MODRM | OPC_WLX, OPT_EA, OPT_REG))
ALT(DEF_ASM_OP2(les, 0xc4, 0, OPC_MODRM, OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(lds, 0xc5, 0, OPC_MODRM, OPT_EA, OPT_REG32))
@ -154,78 +154,80 @@ ALT(DEF_ASM_OP2(lfs, 0x0fb4, 0, OPC_MODRM, OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(lgs, 0x0fb5, 0, OPC_MODRM, OPT_EA, OPT_REG32))
/* arith */
ALT(DEF_ASM_OP2(addb, 0x00, 0, OPC_ARITH | OPC_MODRM | OPC_BWL, OPT_REG, OPT_EA | OPT_REG)) /* XXX: use D bit ? */
ALT(DEF_ASM_OP2(addb, 0x02, 0, OPC_ARITH | OPC_MODRM | OPC_BWL, OPT_EA | OPT_REG, OPT_REG))
ALT(DEF_ASM_OP2(addb, 0x04, 0, OPC_ARITH | OPC_BWL, OPT_IM, OPT_EAX))
ALT(DEF_ASM_OP2(addb, 0x80, 0, OPC_ARITH | OPC_MODRM | OPC_BWL, OPT_IM, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(addw, 0x83, 0, OPC_ARITH | OPC_MODRM | OPC_WL, OPT_IM8S, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(addb, 0x00, 0, OPC_ARITH | OPC_MODRM | OPC_BWLX, OPT_REG, OPT_EA | OPT_REG)) /* XXX: use D bit ? */
ALT(DEF_ASM_OP2(addb, 0x02, 0, OPC_ARITH | OPC_MODRM | OPC_BWLX, OPT_EA | OPT_REG, OPT_REG))
ALT(DEF_ASM_OP2(addb, 0x04, 0, OPC_ARITH | OPC_BWLX, OPT_IM, OPT_EAX))
ALT(DEF_ASM_OP2(addw, 0x83, 0, OPC_ARITH | OPC_MODRM | OPC_WLX, OPT_IM8S, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP2(addb, 0x80, 0, OPC_ARITH | OPC_MODRM | OPC_BWLX, OPT_IM, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(testb, 0x84, 0, OPC_MODRM | OPC_BWL, OPT_EA | OPT_REG, OPT_REG))
ALT(DEF_ASM_OP2(testb, 0x84, 0, OPC_MODRM | OPC_BWL, OPT_REG, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(testb, 0xa8, 0, OPC_BWL, OPT_IM, OPT_EAX))
ALT(DEF_ASM_OP2(testb, 0xf6, 0, OPC_MODRM | OPC_BWL, OPT_IM, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(testb, 0x84, 0, OPC_MODRM | OPC_BWLX, OPT_REG, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(testb, 0x84, 0, OPC_MODRM | OPC_BWLX, OPT_EA | OPT_REG, OPT_REG))
ALT(DEF_ASM_OP2(testb, 0xa8, 0, OPC_BWLX, OPT_IM, OPT_EAX))
ALT(DEF_ASM_OP2(testb, 0xf6, 0, OPC_MODRM | OPC_BWLX, OPT_IM, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP1(incw, 0x40, 0, OPC_REG | OPC_WL, OPT_REGW))
ALT(DEF_ASM_OP1(incb, 0xfe, 0, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(decw, 0x48, 0, OPC_REG | OPC_WL, OPT_REGW))
ALT(DEF_ASM_OP1(decb, 0xfe, 1, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(incw, 0x40, 0, OPC_REG | OPC_WLX, OPT_REGW))
ALT(DEF_ASM_OP1(incb, 0xfe, 0, OPC_MODRM | OPC_BWLX, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(decw, 0x48, 0, OPC_REG | OPC_WLX, OPT_REGW))
ALT(DEF_ASM_OP1(decb, 0xfe, 1, OPC_MODRM | OPC_BWLX, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(notb, 0xf6, 2, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(negb, 0xf6, 3, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(notb, 0xf6, 2, OPC_MODRM | OPC_BWLX, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(negb, 0xf6, 3, OPC_MODRM | OPC_BWLX, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(mulb, 0xf6, 4, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(imulb, 0xf6, 5, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(mulb, 0xf6, 4, OPC_MODRM | OPC_BWLX, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP1(imulb, 0xf6, 5, OPC_MODRM | OPC_BWLX, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP2(imulw, 0x0faf, 0, OPC_MODRM | OPC_WL, OPT_REG | OPT_EA, OPT_REG))
ALT(DEF_ASM_OP3(imulw, 0x6b, 0, OPC_MODRM | OPC_WL, OPT_IM8S, OPT_REGW | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(imulw, 0x6b, 0, OPC_MODRM | OPC_WL, OPT_IM8S, OPT_REGW))
ALT(DEF_ASM_OP3(imulw, 0x69, 0, OPC_MODRM | OPC_WL, OPT_IMW, OPT_REGW | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(imulw, 0x69, 0, OPC_MODRM | OPC_WL, OPT_IMW, OPT_REGW))
ALT(DEF_ASM_OP2(imulw, 0x0faf, 0, OPC_MODRM | OPC_WLX, OPT_REG | OPT_EA, OPT_REG))
ALT(DEF_ASM_OP3(imulw, 0x6b, 0, OPC_MODRM | OPC_WLX, OPT_IM8S, OPT_REGW | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(imulw, 0x6b, 0, OPC_MODRM | OPC_WLX, OPT_IM8S, OPT_REGW))
ALT(DEF_ASM_OP3(imulw, 0x69, 0, OPC_MODRM | OPC_WLX, OPT_IMW, OPT_REGW | OPT_EA, OPT_REGW))
ALT(DEF_ASM_OP2(imulw, 0x69, 0, OPC_MODRM | OPC_WLX, OPT_IMW, OPT_REGW))
ALT(DEF_ASM_OP1(divb, 0xf6, 6, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP2(divb, 0xf6, 6, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA, OPT_EAX))
ALT(DEF_ASM_OP1(idivb, 0xf6, 7, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP2(idivb, 0xf6, 7, OPC_MODRM | OPC_BWL, OPT_REG | OPT_EA, OPT_EAX))
ALT(DEF_ASM_OP1(divb, 0xf6, 6, OPC_MODRM | OPC_BWLX, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP2(divb, 0xf6, 6, OPC_MODRM | OPC_BWLX, OPT_REG | OPT_EA, OPT_EAX))
ALT(DEF_ASM_OP1(idivb, 0xf6, 7, OPC_MODRM | OPC_BWLX, OPT_REG | OPT_EA))
ALT(DEF_ASM_OP2(idivb, 0xf6, 7, OPC_MODRM | OPC_BWLX, OPT_REG | OPT_EA, OPT_EAX))
/* shifts */
ALT(DEF_ASM_OP2(rolb, 0xc0, 0, OPC_MODRM | OPC_BWL | OPC_SHIFT, OPT_IM8, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(rolb, 0xd2, 0, OPC_MODRM | OPC_BWL | OPC_SHIFT, OPT_CL, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP1(rolb, 0xd0, 0, OPC_MODRM | OPC_BWL | OPC_SHIFT, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(rolb, 0xc0, 0, OPC_MODRM | OPC_BWLX | OPC_SHIFT, OPT_IM8, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP2(rolb, 0xd2, 0, OPC_MODRM | OPC_BWLX | OPC_SHIFT, OPT_CL, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP1(rolb, 0xd0, 0, OPC_MODRM | OPC_BWLX | OPC_SHIFT, OPT_EA | OPT_REG))
ALT(DEF_ASM_OP3(shldw, 0x0fa4, 0, OPC_MODRM | OPC_WL, OPT_IM8, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP3(shldw, 0x0fa5, 0, OPC_MODRM | OPC_WL, OPT_CL, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP2(shldw, 0x0fa5, 0, OPC_MODRM | OPC_WL, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP3(shrdw, 0x0fac, 0, OPC_MODRM | OPC_WL, OPT_IM8, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP3(shrdw, 0x0fad, 0, OPC_MODRM | OPC_WL, OPT_CL, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP2(shrdw, 0x0fad, 0, OPC_MODRM | OPC_WL, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP3(shldw, 0x0fa4, 0, OPC_MODRM | OPC_WLX, OPT_IM8, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP3(shldw, 0x0fa5, 0, OPC_MODRM | OPC_WLX, OPT_CL, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP2(shldw, 0x0fa5, 0, OPC_MODRM | OPC_WLX, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP3(shrdw, 0x0fac, 0, OPC_MODRM | OPC_WLX, OPT_IM8, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP3(shrdw, 0x0fad, 0, OPC_MODRM | OPC_WLX, OPT_CL, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP2(shrdw, 0x0fad, 0, OPC_MODRM | OPC_WLX, OPT_REGW, OPT_EA | OPT_REGW))
ALT(DEF_ASM_OP1(call, 0xff, 2, OPC_MODRM, OPT_INDIR))
ALT(DEF_ASM_OP1(call, 0xe8, 0, OPC_JMP, OPT_ADDR))
ALT(DEF_ASM_OP1(call, 0xe8, 0, 0, OPT_DISP))
ALT(DEF_ASM_OP1(jmp, 0xff, 4, OPC_MODRM, OPT_INDIR))
ALT(DEF_ASM_OP1(jmp, 0xeb, 0, OPC_SHORTJMP | OPC_JMP, OPT_ADDR))
ALT(DEF_ASM_OP1(jmp, 0xff, 0, OPC_JMP | OPC_WL, OPT_REGW))
ALT(DEF_ASM_OP1(jmp, 0xeb, 0, 0, OPT_DISP8))
ALT(DEF_ASM_OP2(lcall, 0x9a, 0, 0, OPT_IM16, OPT_IM32))
ALT(DEF_ASM_OP1(lcall, 0xff, 3, 0, OPT_EA))
ALT(DEF_ASM_OP1(lcall, 0xff, 3, OPC_MODRM, OPT_EA))
ALT(DEF_ASM_OP2(ljmp, 0xea, 0, 0, OPT_IM16, OPT_IM32))
ALT(DEF_ASM_OP1(ljmp, 0xff, 5, 0, OPT_EA))
ALT(DEF_ASM_OP1(ljmp, 0xff, 5, OPC_MODRM, OPT_EA))
ALT(DEF_ASM_OP1(int, 0xcd, 0, 0, OPT_IM8))
ALT(DEF_ASM_OP1(seto, 0x0f90, 0, OPC_MODRM | OPC_TEST, OPT_REG8 | OPT_EA))
ALT(DEF_ASM_OP1(setob, 0x0f90, 0, OPC_MODRM | OPC_TEST, OPT_REG8 | OPT_EA))
DEF_ASM_OP2(enter, 0xc8, 0, 0, OPT_IM16, OPT_IM8)
DEF_ASM_OP0(leave, 0xc9)
DEF_ASM_OP0(ret, 0xc3)
DEF_ASM_OP0(retl,0xc3)
ALT(DEF_ASM_OP1(retl,0xc2, 0, 0, OPT_IM16))
ALT(DEF_ASM_OP1(ret, 0xc2, 0, 0, OPT_IM16))
DEF_ASM_OP0(lret, 0xcb)
ALT(DEF_ASM_OP1(lret, 0xca, 0, 0, OPT_IM16))
ALT(DEF_ASM_OP1(jo, 0x70, 0, OPC_SHORTJMP | OPC_JMP | OPC_TEST, OPT_ADDR))
DEF_ASM_OP1(loopne, 0xe0, 0, OPC_SHORTJMP, OPT_ADDR)
DEF_ASM_OP1(loopnz, 0xe0, 0, OPC_SHORTJMP, OPT_ADDR)
DEF_ASM_OP1(loope, 0xe1, 0, OPC_SHORTJMP, OPT_ADDR)
DEF_ASM_OP1(loopz, 0xe1, 0, OPC_SHORTJMP, OPT_ADDR)
DEF_ASM_OP1(loop, 0xe2, 0, OPC_SHORTJMP, OPT_ADDR)
DEF_ASM_OP1(jecxz, 0xe3, 0, OPC_SHORTJMP, OPT_ADDR)
ALT(DEF_ASM_OP1(jo, 0x70, 0, OPC_TEST, OPT_DISP8))
DEF_ASM_OP1(loopne, 0xe0, 0, 0, OPT_DISP8)
DEF_ASM_OP1(loopnz, 0xe0, 0, 0, OPT_DISP8)
DEF_ASM_OP1(loope, 0xe1, 0, 0, OPT_DISP8)
DEF_ASM_OP1(loopz, 0xe1, 0, 0, OPT_DISP8)
DEF_ASM_OP1(loop, 0xe2, 0, 0, OPT_DISP8)
DEF_ASM_OP1(jecxz, 0xe3, 0, 0, OPT_DISP8)
/* float */
/* specific fcomp handling */
@ -233,6 +235,8 @@ ALT(DEF_ASM_OP0L(fcomp, 0xd8d9, 0, 0))
ALT(DEF_ASM_OP1(fadd, 0xd8c0, 0, OPC_FARITH | OPC_REG, OPT_ST))
ALT(DEF_ASM_OP2(fadd, 0xd8c0, 0, OPC_FARITH | OPC_REG, OPT_ST, OPT_ST0))
ALT(DEF_ASM_OP2(fadd, 0xdcc0, 0, OPC_FARITH | OPC_REG, OPT_ST0, OPT_ST))
ALT(DEF_ASM_OP2(fmul, 0xdcc8, 0, OPC_FARITH | OPC_REG, OPT_ST0, OPT_ST))
ALT(DEF_ASM_OP0L(fadd, 0xdec1, 0, OPC_FARITH))
ALT(DEF_ASM_OP1(faddp, 0xdec0, 0, OPC_FARITH | OPC_REG, OPT_ST))
ALT(DEF_ASM_OP2(faddp, 0xdec0, 0, OPC_FARITH | OPC_REG, OPT_ST, OPT_ST0))
@ -275,7 +279,6 @@ ALT(DEF_ASM_OP1(fiadds, 0xde, 0, OPC_FARITH | OPC_MODRM, OPT_EA))
DEF_ASM_OP0(fninit, 0xdbe3)
DEF_ASM_OP0(fnclex, 0xdbe2)
DEF_ASM_OP0(fnop, 0xd9d0)
DEF_ASM_OP0(fwait, 0x9b)
/* fp load */
DEF_ASM_OP1(fld, 0xd9c0, 0, OPC_REG, OPT_ST)
@ -338,12 +341,12 @@ ALT(DEF_ASM_OP1(fstsw, 0xdd, 7, OPC_MODRM | OPC_FWAIT, OPT_EA ))
/* segments */
DEF_ASM_OP2(arpl, 0x63, 0, OPC_MODRM, OPT_REG16, OPT_REG16 | OPT_EA)
DEF_ASM_OP2(lar, 0x0f02, 0, OPC_MODRM, OPT_REG32 | OPT_EA, OPT_REG32)
ALT(DEF_ASM_OP2(larw, 0x0f02, 0, OPC_MODRM | OPC_WLX, OPT_REG | OPT_EA, OPT_REG))
DEF_ASM_OP1(lgdt, 0x0f01, 2, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(lidt, 0x0f01, 3, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(lldt, 0x0f00, 2, OPC_MODRM, OPT_EA | OPT_REG)
DEF_ASM_OP1(lmsw, 0x0f01, 6, OPC_MODRM, OPT_EA | OPT_REG)
ALT(DEF_ASM_OP2(lslw, 0x0f03, 0, OPC_MODRM | OPC_WL, OPT_EA | OPT_REG, OPT_REG))
ALT(DEF_ASM_OP2(lslw, 0x0f03, 0, OPC_MODRM | OPC_WLX, OPT_EA | OPT_REG, OPT_REG))
DEF_ASM_OP1(ltr, 0x0f00, 3, OPC_MODRM, OPT_EA | OPT_REG)
DEF_ASM_OP1(sgdt, 0x0f01, 0, OPC_MODRM, OPT_EA)
DEF_ASM_OP1(sidt, 0x0f01, 1, OPC_MODRM, OPT_EA)
@ -353,31 +356,20 @@ ALT(DEF_ASM_OP2(lslw, 0x0f03, 0, OPC_MODRM | OPC_WL, OPT_EA | OPT_REG, OPT_REG))
DEF_ASM_OP1(verr, 0x0f00, 4, OPC_MODRM, OPT_REG | OPT_EA)
DEF_ASM_OP1(verw, 0x0f00, 5, OPC_MODRM, OPT_REG | OPT_EA)
/* 386 */
DEF_ASM_OP0(loadall386, 0x0f07)
/* 486 */
DEF_ASM_OP1(bswap, 0x0fc8, 0, OPC_REG, OPT_REG32 )
ALT(DEF_ASM_OP2(xaddb, 0x0fc0, 0, OPC_MODRM | OPC_BWL, OPT_REG, OPT_REG | OPT_EA ))
ALT(DEF_ASM_OP2(cmpxchgb, 0x0fb0, 0, OPC_MODRM | OPC_BWL, OPT_REG, OPT_REG | OPT_EA ))
ALT(DEF_ASM_OP2(xaddb, 0x0fc0, 0, OPC_MODRM | OPC_BWLX, OPT_REG, OPT_REG | OPT_EA ))
ALT(DEF_ASM_OP2(cmpxchgb, 0x0fb0, 0, OPC_MODRM | OPC_BWLX, OPT_REG, OPT_REG | OPT_EA ))
DEF_ASM_OP1(invlpg, 0x0f01, 7, OPC_MODRM, OPT_EA )
DEF_ASM_OP2(boundl, 0x62, 0, OPC_MODRM, OPT_REG32, OPT_EA)
DEF_ASM_OP2(boundw, 0x62, 0, OPC_MODRM | OPC_D16, OPT_REG16, OPT_EA)
DEF_ASM_OP2(boundw, 0x6662, 0, OPC_MODRM, OPT_REG16, OPT_EA)
/* pentium */
DEF_ASM_OP1(cmpxchg8b, 0x0fc7, 1, OPC_MODRM, OPT_EA )
/* pentium pro */
ALT(DEF_ASM_OP2(cmovo, 0x0f40, 0, OPC_MODRM | OPC_TEST, OPT_REG32 | OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(cmovno, 0x0f41, 0, OPC_MODRM | OPC_TEST, OPT_REG32 | OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(cmovc, 0x0f42, 0, OPC_MODRM | OPC_TEST, OPT_REG32 | OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(cmovnc, 0x0f43, 0, OPC_MODRM | OPC_TEST, OPT_REG32 | OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(cmovz, 0x0f44, 0, OPC_MODRM | OPC_TEST, OPT_REG32 | OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(cmovnz, 0x0f45, 0, OPC_MODRM | OPC_TEST, OPT_REG32 | OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(cmovna, 0x0f46, 0, OPC_MODRM | OPC_TEST, OPT_REG32 | OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(cmova, 0x0f47, 0, OPC_MODRM | OPC_TEST, OPT_REG32 | OPT_EA, OPT_REG32))
ALT(DEF_ASM_OP2(cmovo, 0x0f40, 0, OPC_MODRM | OPC_TEST | OPC_WLX, OPT_REGW | OPT_EA, OPT_REGW))
DEF_ASM_OP2(fcmovb, 0xdac0, 0, OPC_REG, OPT_ST, OPT_ST0 )
DEF_ASM_OP2(fcmove, 0xdac8, 0, OPC_REG, OPT_ST, OPT_ST0 )
DEF_ASM_OP2(fcmovbe, 0xdad0, 0, OPC_REG, OPT_ST, OPT_ST0 )
@ -394,62 +386,91 @@ ALT(DEF_ASM_OP2(cmova, 0x0f47, 0, OPC_MODRM | OPC_TEST, OPT_REG32 | OPT_EA, OPT_
/* mmx */
DEF_ASM_OP0(emms, 0x0f77) /* must be last OP0 */
DEF_ASM_OP2(movd, 0x0f6e, 0, OPC_MODRM, OPT_EA | OPT_REG32, OPT_MMX )
ALT(DEF_ASM_OP2(movd, 0x0f7e, 0, OPC_MODRM, OPT_MMX, OPT_EA | OPT_REG32 ))
DEF_ASM_OP2(movd, 0x0f6e, 0, OPC_MODRM, OPT_EA | OPT_REG32, OPT_MMXSSE )
DEF_ASM_OP2(movq, 0x0f6f, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(movd, 0x0f7e, 0, OPC_MODRM, OPT_MMXSSE, OPT_EA | OPT_REG32 ))
ALT(DEF_ASM_OP2(movq, 0x0f7f, 0, OPC_MODRM, OPT_MMX, OPT_EA | OPT_MMX ))
DEF_ASM_OP2(packssdw, 0x0f6b, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(packsswb, 0x0f63, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(packuswb, 0x0f67, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(paddb, 0x0ffc, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(paddw, 0x0ffd, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(paddd, 0x0ffe, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(paddsb, 0x0fec, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(paddsw, 0x0fed, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(paddusb, 0x0fdc, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(paddusw, 0x0fdd, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pand, 0x0fdb, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pandn, 0x0fdf, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pcmpeqb, 0x0f74, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pcmpeqw, 0x0f75, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pcmpeqd, 0x0f76, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pcmpgtb, 0x0f64, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pcmpgtw, 0x0f65, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pcmpgtd, 0x0f66, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pmaddwd, 0x0ff5, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pmulhw, 0x0fe5, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pmullw, 0x0fd5, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(por, 0x0feb, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(psllw, 0x0ff1, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(psllw, 0x0f71, 6, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(pslld, 0x0ff2, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(pslld, 0x0f72, 6, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(psllq, 0x0ff3, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(psllq, 0x0f73, 6, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(psraw, 0x0fe1, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(psraw, 0x0f71, 4, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(psrad, 0x0fe2, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(psrad, 0x0f72, 4, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(psrlw, 0x0fd1, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(psrlw, 0x0f71, 2, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(psrld, 0x0fd2, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(psrld, 0x0f72, 2, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(psrlq, 0x0fd3, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(psrlq, 0x0f73, 2, OPC_MODRM, OPT_IM8, OPT_MMX ))
DEF_ASM_OP2(psubb, 0x0ff8, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(psubw, 0x0ff9, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(psubd, 0x0ffa, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(psubsb, 0x0fe8, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(psubsw, 0x0fe9, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(psubusb, 0x0fd8, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(psubusw, 0x0fd9, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(punpckhbw, 0x0f68, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(punpckhwd, 0x0f69, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(punpckhdq, 0x0f6a, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(punpcklbw, 0x0f60, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(punpcklwd, 0x0f61, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(punpckldq, 0x0f62, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
DEF_ASM_OP2(pxor, 0x0fef, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_MMX )
ALT(DEF_ASM_OP2(movq, 0x660fd6, 0, OPC_MODRM, OPT_SSE, OPT_EA | OPT_SSE ))
ALT(DEF_ASM_OP2(movq, 0xf30f7e, 0, OPC_MODRM, OPT_EA | OPT_SSE, OPT_SSE ))
DEF_ASM_OP2(packssdw, 0x0f6b, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(packsswb, 0x0f63, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(packuswb, 0x0f67, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(paddb, 0x0ffc, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(paddw, 0x0ffd, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(paddd, 0x0ffe, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(paddsb, 0x0fec, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(paddsw, 0x0fed, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(paddusb, 0x0fdc, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(paddusw, 0x0fdd, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pand, 0x0fdb, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pandn, 0x0fdf, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pcmpeqb, 0x0f74, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pcmpeqw, 0x0f75, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pcmpeqd, 0x0f76, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pcmpgtb, 0x0f64, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pcmpgtw, 0x0f65, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pcmpgtd, 0x0f66, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pmaddwd, 0x0ff5, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pmulhw, 0x0fe5, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pmullw, 0x0fd5, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(por, 0x0feb, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(psllw, 0x0ff1, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
ALT(DEF_ASM_OP2(psllw, 0x0f71, 6, OPC_MODRM, OPT_IM8, OPT_MMXSSE ))
DEF_ASM_OP2(pslld, 0x0ff2, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
ALT(DEF_ASM_OP2(pslld, 0x0f72, 6, OPC_MODRM, OPT_IM8, OPT_MMXSSE ))
DEF_ASM_OP2(psllq, 0x0ff3, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
ALT(DEF_ASM_OP2(psllq, 0x0f73, 6, OPC_MODRM, OPT_IM8, OPT_MMXSSE ))
DEF_ASM_OP2(psraw, 0x0fe1, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
ALT(DEF_ASM_OP2(psraw, 0x0f71, 4, OPC_MODRM, OPT_IM8, OPT_MMXSSE ))
DEF_ASM_OP2(psrad, 0x0fe2, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
ALT(DEF_ASM_OP2(psrad, 0x0f72, 4, OPC_MODRM, OPT_IM8, OPT_MMXSSE ))
DEF_ASM_OP2(psrlw, 0x0fd1, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
ALT(DEF_ASM_OP2(psrlw, 0x0f71, 2, OPC_MODRM, OPT_IM8, OPT_MMXSSE ))
DEF_ASM_OP2(psrld, 0x0fd2, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
ALT(DEF_ASM_OP2(psrld, 0x0f72, 2, OPC_MODRM, OPT_IM8, OPT_MMXSSE ))
DEF_ASM_OP2(psrlq, 0x0fd3, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
ALT(DEF_ASM_OP2(psrlq, 0x0f73, 2, OPC_MODRM, OPT_IM8, OPT_MMXSSE ))
DEF_ASM_OP2(psubb, 0x0ff8, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(psubw, 0x0ff9, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(psubd, 0x0ffa, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(psubsb, 0x0fe8, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(psubsw, 0x0fe9, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(psubusb, 0x0fd8, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(psubusw, 0x0fd9, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(punpckhbw, 0x0f68, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(punpckhwd, 0x0f69, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(punpckhdq, 0x0f6a, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(punpcklbw, 0x0f60, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(punpcklwd, 0x0f61, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(punpckldq, 0x0f62, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pxor, 0x0fef, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
/* sse */
DEF_ASM_OP2(movups, 0x0f10, 0, OPC_MODRM, OPT_EA | OPT_REG32, OPT_SSE )
ALT(DEF_ASM_OP2(movups, 0x0f11, 0, OPC_MODRM, OPT_SSE, OPT_EA | OPT_REG32 ))
DEF_ASM_OP2(movaps, 0x0f28, 0, OPC_MODRM, OPT_EA | OPT_REG32, OPT_SSE )
ALT(DEF_ASM_OP2(movaps, 0x0f29, 0, OPC_MODRM, OPT_SSE, OPT_EA | OPT_REG32 ))
DEF_ASM_OP2(movhps, 0x0f16, 0, OPC_MODRM, OPT_EA | OPT_REG32, OPT_SSE )
ALT(DEF_ASM_OP2(movhps, 0x0f17, 0, OPC_MODRM, OPT_SSE, OPT_EA | OPT_REG32 ))
DEF_ASM_OP2(addps, 0x0f58, 0, OPC_MODRM, OPT_EA | OPT_SSE, OPT_SSE )
DEF_ASM_OP2(cvtpi2ps, 0x0f2a, 0, OPC_MODRM, OPT_EA | OPT_MMX, OPT_SSE )
DEF_ASM_OP2(cvtps2pi, 0x0f2d, 0, OPC_MODRM, OPT_EA | OPT_SSE, OPT_MMX )
DEF_ASM_OP2(cvttps2pi, 0x0f2c, 0, OPC_MODRM, OPT_EA | OPT_SSE, OPT_MMX )
DEF_ASM_OP2(divps, 0x0f5e, 0, OPC_MODRM, OPT_EA | OPT_SSE, OPT_SSE )
DEF_ASM_OP2(maxps, 0x0f5f, 0, OPC_MODRM, OPT_EA | OPT_SSE, OPT_SSE )
DEF_ASM_OP2(minps, 0x0f5d, 0, OPC_MODRM, OPT_EA | OPT_SSE, OPT_SSE )
DEF_ASM_OP2(mulps, 0x0f59, 0, OPC_MODRM, OPT_EA | OPT_SSE, OPT_SSE )
DEF_ASM_OP2(pavgb, 0x0fe0, 0, OPC_MODRM, OPT_EA | OPT_SSE, OPT_SSE )
DEF_ASM_OP2(pavgw, 0x0fe3, 0, OPC_MODRM, OPT_EA | OPT_SSE, OPT_SSE )
DEF_ASM_OP2(pmaxsw, 0x0fee, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pmaxub, 0x0fde, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pminsw, 0x0fea, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(pminub, 0x0fda, 0, OPC_MODRM, OPT_EA | OPT_MMXSSE, OPT_MMXSSE )
DEF_ASM_OP2(rcpss, 0x0f53, 0, OPC_MODRM, OPT_EA | OPT_SSE, OPT_SSE )
DEF_ASM_OP2(rsqrtps, 0x0f52, 0, OPC_MODRM, OPT_EA | OPT_SSE, OPT_SSE )
DEF_ASM_OP2(sqrtps, 0x0f51, 0, OPC_MODRM, OPT_EA | OPT_SSE, OPT_SSE )
DEF_ASM_OP2(subps, 0x0f5c, 0, OPC_MODRM, OPT_EA | OPT_SSE, OPT_SSE )
#undef ALT
#undef DEF_ASM_OP0

View File

@ -18,8 +18,12 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef TARGET_DEFS_ONLY
/* number of available registers */
#define NB_REGS 4
#define NB_REGS 5
#define NB_ASM_REGS 8
#define CONFIG_TCC_ASM
/* a register can belong to several classes. The classes must be
sorted from more general to more precise (see gv2() code which does
@ -30,6 +34,8 @@
#define RC_ST0 0x0008
#define RC_ECX 0x0010
#define RC_EDX 0x0020
#define RC_EBX 0x0040
#define RC_IRET RC_EAX /* function return: integer register */
#define RC_LRET RC_EDX /* function return: second integer register */
#define RC_FRET RC_ST0 /* function return: float register */
@ -39,14 +45,9 @@ enum {
TREG_EAX = 0,
TREG_ECX,
TREG_EDX,
TREG_EBX,
TREG_ST0,
};
const int reg_classes[NB_REGS] = {
/* eax */ RC_INT | RC_EAX,
/* ecx */ RC_INT | RC_ECX,
/* edx */ RC_INT | RC_EDX,
/* st0 */ RC_FLOAT | RC_ST0,
TREG_ESP = 4
};
/* return registers for function */
@ -59,7 +60,7 @@ const int reg_classes[NB_REGS] = {
/* defined if structures are passed as pointers. Otherwise structures
are directly pushed on stack. */
//#define FUNC_STRUCT_PARAM_AS_PTR
/* #define FUNC_STRUCT_PARAM_AS_PTR */
/* pointer size, in bytes */
#define PTR_SIZE 4
@ -71,29 +72,34 @@ const int reg_classes[NB_REGS] = {
#define MAX_ALIGN 8
/******************************************************/
/* ELF defines */
#define EM_TCC_TARGET EM_386
/* relocation type for 32 bit data relocation */
#define R_DATA_32 R_386_32
#define R_DATA_PTR R_386_32
#define R_JMP_SLOT R_386_JMP_SLOT
#define R_COPY R_386_COPY
#define ELF_START_ADDR 0x08048000
#define ELF_PAGE_SIZE 0x1000
#else /* ! TARGET_DEFS_ONLY */
/******************************************************/
#include "tcc.h"
/* define to 1/0 to [not] have EBX as 4th register */
#define USE_EBX 0
ST_DATA const int reg_classes[NB_REGS] = {
/* eax */ RC_INT | RC_EAX,
/* ecx */ RC_INT | RC_ECX,
/* edx */ RC_INT | RC_EDX,
/* ebx */ (RC_INT | RC_EBX) * USE_EBX,
/* st0 */ RC_FLOAT | RC_ST0,
};
static unsigned long func_sub_sp_offset;
static unsigned long func_bound_offset;
static int func_ret_sub;
#ifdef CONFIG_TCC_BCHECK
static addr_t func_bound_offset;
static unsigned long func_bound_ind;
#endif
/* XXX: make it faster ? */
void g(int c)
ST_FUNC void g(int c)
{
int ind1;
if (nocode_wanted)
return;
ind1 = ind + 1;
if (ind1 > cur_text_section->data_allocated)
section_realloc(cur_text_section, ind1);
@ -101,7 +107,7 @@ void g(int c)
ind = ind1;
}
void o(unsigned int c)
ST_FUNC void o(unsigned int c)
{
while (c) {
g(c);
@ -109,7 +115,13 @@ void o(unsigned int c)
}
}
void gen_le32(int c)
ST_FUNC void gen_le16(int v)
{
g(v);
g(v >> 8);
}
ST_FUNC void gen_le32(int c)
{
g(c);
g(c >> 8);
@ -118,50 +130,52 @@ void gen_le32(int c)
}
/* output a symbol and patch all calls to it */
void gsym_addr(int t, int a)
ST_FUNC void gsym_addr(int t, int a)
{
int n, *ptr;
while (t) {
ptr = (int *)(cur_text_section->data + t);
n = *ptr; /* next value */
*ptr = a - t - 4;
unsigned char *ptr = cur_text_section->data + t;
uint32_t n = read32le(ptr); /* next value */
write32le(ptr, a - t - 4);
t = n;
}
}
void gsym(int t)
ST_FUNC void gsym(int t)
{
gsym_addr(t, ind);
}
/* psym is used to put an instruction with a data field which is a
reference to a symbol. It is in fact the same as oad ! */
#define psym oad
/* instruction + 4 bytes data. Return the address of the data */
static int oad(int c, int s)
{
int ind1;
int t;
if (nocode_wanted)
return s;
o(c);
ind1 = ind + 4;
if (ind1 > cur_text_section->data_allocated)
section_realloc(cur_text_section, ind1);
*(int *)(cur_text_section->data + ind) = s;
s = ind;
ind = ind1;
return s;
t = ind;
gen_le32(s);
return t;
}
/* generate jmp to a label */
#define gjmp2(instr,lbl) oad(instr,lbl)
/* output constant with relocation if 'r & VT_SYM' is true */
static void gen_addr32(int r, Sym *sym, int c)
ST_FUNC void gen_addr32(int r, Sym *sym, int c)
{
if (r & VT_SYM)
greloc(cur_text_section, sym, ind, R_386_32);
gen_le32(c);
}
/* generate a modrm reference. 'op_reg' contains the addtionnal 3
ST_FUNC void gen_addrpc32(int r, Sym *sym, int c)
{
if (r & VT_SYM)
greloc(cur_text_section, sym, ind, R_386_PC32);
gen_le32(c - 4);
}
/* generate a modrm reference. 'op_reg' contains the additional 3
opcode bits */
static void gen_modrm(int op_reg, int r, Sym *sym, int c)
{
@ -184,55 +198,33 @@ static void gen_modrm(int op_reg, int r, Sym *sym, int c)
}
}
#ifdef TCC_TARGET_PE
static void mk_pointer(CType *type);
static void indir(void);
int handle_dllimport(int r, SValue *sv, void (*fn)(int r, SValue *sv))
{
if ((sv->r & (VT_VALMASK|VT_SYM|VT_CONST)) != (VT_SYM|VT_CONST))
return 0;
if (0 == (sv->sym->type.t & VT_IMPORT))
return 0;
printf("import %d %04x %s\n", r, ind, get_tok_str(sv->sym->v, NULL));
sv->sym->type.t &= ~VT_IMPORT;
++vtop;
*vtop = *sv;
mk_pointer(&vtop->type);
indir();
fn(r, vtop);
--vtop;
sv->sym->type.t |= VT_IMPORT;
return 1;
}
#endif
/* load 'r' from value 'sv' */
void load(int r, SValue *sv)
ST_FUNC void load(int r, SValue *sv)
{
int v, t, ft, fc, fr;
SValue v1;
#ifdef TCC_TARGET_PE
if (handle_dllimport(r, sv, load))
return;
SValue v2;
sv = pe_getimport(sv, &v2);
#endif
fr = sv->r;
ft = sv->type.t;
fc = sv->c.ul;
ft = sv->type.t & ~VT_DEFSIGN;
fc = sv->c.i;
ft &= ~(VT_VOLATILE | VT_CONSTANT);
v = fr & VT_VALMASK;
if (fr & VT_LVAL) {
if (v == VT_LLOCAL) {
v1.type.t = VT_INT;
v1.r = VT_LOCAL | VT_LVAL;
v1.c.ul = fc;
load(r, &v1);
v1.c.i = fc;
fr = r;
if (!(reg_classes[fr] & RC_INT))
fr = get_reg(RC_INT);
load(fr, &v1);
}
if ((ft & VT_BTYPE) == VT_FLOAT) {
o(0xd9); /* flds */
@ -243,7 +235,7 @@ void load(int r, SValue *sv)
} else if ((ft & VT_BTYPE) == VT_LDOUBLE) {
o(0xdb); /* fldt */
r = 5;
} else if ((ft & VT_TYPE) == VT_BYTE) {
} else if ((ft & VT_TYPE) == VT_BYTE || (ft & VT_TYPE) == VT_BOOL) {
o(0xbe0f); /* movsbl */
} else if ((ft & VT_TYPE) == (VT_BYTE | VT_UNSIGNED)) {
o(0xb60f); /* movzbl */
@ -260,8 +252,13 @@ void load(int r, SValue *sv)
o(0xb8 + r); /* mov $xx, r */
gen_addr32(fr, sv->sym, fc);
} else if (v == VT_LOCAL) {
o(0x8d); /* lea xxx(%ebp), r */
gen_modrm(r, VT_LOCAL, sv->sym, fc);
if (fc) {
o(0x8d); /* lea xxx(%ebp), r */
gen_modrm(r, VT_LOCAL, sv->sym, fc);
} else {
o(0x89);
o(0xe8 + r); /* mov %ebp, r */
}
} else if (v == VT_CMP) {
oad(0xb8 + r, 0); /* mov $0, r */
o(0x0f); /* setxx %br */
@ -281,17 +278,19 @@ void load(int r, SValue *sv)
}
/* store register 'r' in lvalue 'v' */
void store(int r, SValue *v)
ST_FUNC void store(int r, SValue *v)
{
int fr, bt, ft, fc;
#ifdef TCC_TARGET_PE
if (handle_dllimport(r, v, store))
return;
SValue v2;
v = pe_getimport(v, &v2);
#endif
ft = v->type.t;
fc = v->c.ul;
fc = v->c.i;
fr = v->r & VT_VALMASK;
ft &= ~(VT_VOLATILE | VT_CONSTANT);
bt = ft & VT_BTYPE;
/* XXX: incorrect if float reg to reg */
if (bt == VT_FLOAT) {
@ -331,37 +330,94 @@ static void gadd_sp(int val)
}
}
#if defined CONFIG_TCC_BCHECK || defined TCC_TARGET_PE
static void gen_static_call(int v)
{
Sym *sym;
sym = external_global_sym(v, &func_old_type, 0);
oad(0xe8, -4);
greloc(cur_text_section, sym, ind-4, R_386_PC32);
}
#endif
/* 'is_jmp' is '1' if it is a jump */
static void gcall_or_jmp(int is_jmp)
{
int r;
if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
/* constant case */
if (vtop->r & VT_SYM) {
/* relocation case */
greloc(cur_text_section, vtop->sym,
ind + 1, R_386_PC32);
} else {
/* put an empty PC32 relocation */
put_elf_reloc(symtab_section, cur_text_section,
ind + 1, R_386_PC32, 0);
}
oad(0xe8 + is_jmp, vtop->c.ul - 4); /* call/jmp im */
if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST && (vtop->r & VT_SYM)) {
/* constant and relocation case */
greloc(cur_text_section, vtop->sym, ind + 1, R_386_PC32);
oad(0xe8 + is_jmp, vtop->c.i - 4); /* call/jmp im */
} else {
/* otherwise, indirect call */
r = gv(RC_INT);
o(0xff); /* call/jmp *r */
o(0xd0 + r + (is_jmp << 4));
}
if (!is_jmp) {
int rt;
/* extend the return value to the whole register if necessary
visual studio and gcc do not always set the whole eax register
when assigning the return value of a function */
rt = vtop->type.ref->type.t;
switch (rt & VT_BTYPE) {
case VT_BYTE:
if (rt & VT_UNSIGNED) {
o(0xc0b60f); /* movzx %al, %eax */
}
else {
o(0xc0be0f); /* movsx %al, %eax */
}
break;
case VT_SHORT:
if (rt & VT_UNSIGNED) {
o(0xc0b70f); /* movzx %ax, %eax */
}
else {
o(0xc0bf0f); /* movsx %ax, %eax */
}
break;
default:
break;
}
}
}
static uint8_t fastcall_regs[3] = { TREG_EAX, TREG_EDX, TREG_ECX };
static uint8_t fastcallw_regs[2] = { TREG_ECX, TREG_EDX };
/* Return the number of registers needed to return the struct, or 0 if
returning via struct pointer. */
ST_FUNC int gfunc_sret(CType *vt, int variadic, CType *ret, int *ret_align, int *regsize)
{
#ifdef TCC_TARGET_PE
int size, align;
*ret_align = 1; // Never have to re-align return values for x86
*regsize = 4;
size = type_size(vt, &align);
if (size > 8 || (size & (size - 1)))
return 0;
if (size == 8)
ret->t = VT_LLONG;
else if (size == 4)
ret->t = VT_INT;
else if (size == 2)
ret->t = VT_SHORT;
else
ret->t = VT_BYTE;
ret->ref = NULL;
return 1;
#else
*ret_align = 1; // Never have to re-align return values for x86
return 0;
#endif
}
/* Generate function call. The function address is pushed first, then
all the parameters in call order. This functions pops all the
parameters and the function address. */
void gfunc_call(int nb_args)
ST_FUNC void gfunc_call(int nb_args)
{
int size, align, r, args_size, i, func_call;
Sym *func_sym;
@ -415,7 +471,7 @@ void gfunc_call(int nb_args)
}
save_regs(0); /* save used temporary registers */
func_sym = vtop->type.ref;
func_call = FUNC_CALL(func_sym->r);
func_call = func_sym->f.func_call;
/* fast call case */
if ((func_call >= FUNC_FASTCALL1 && func_call <= FUNC_FASTCALL3) ||
func_call == FUNC_FASTCALLW) {
@ -436,25 +492,25 @@ void gfunc_call(int nb_args)
args_size -= 4;
}
}
gcall_or_jmp(0);
#ifdef TCC_TARGET_PE
if ((func_sym->type.t & VT_BTYPE) == VT_STRUCT)
#ifndef TCC_TARGET_PE
else if ((vtop->type.ref->type.t & VT_BTYPE) == VT_STRUCT)
args_size -= 4;
#endif
if (args_size && func_call != FUNC_STDCALL)
gcall_or_jmp(0);
if (args_size && func_call != FUNC_STDCALL && func_call != FUNC_FASTCALLW)
gadd_sp(args_size);
vtop--;
}
#ifdef TCC_TARGET_PE
#define FUNC_PROLOG_SIZE 10
#define FUNC_PROLOG_SIZE (10 + USE_EBX)
#else
#define FUNC_PROLOG_SIZE 9
#define FUNC_PROLOG_SIZE (9 + USE_EBX)
#endif
/* generate function prolog of type 't' */
void gfunc_prolog(CType *func_type)
ST_FUNC void gfunc_prolog(CType *func_type)
{
int addr, align, size, func_call, fastcall_nb_regs;
int param_index, param_addr;
@ -463,7 +519,7 @@ void gfunc_prolog(CType *func_type)
CType *type;
sym = func_type->ref;
func_call = FUNC_CALL(sym->r);
func_call = sym->f.func_call;
addr = 8;
loc = 0;
func_vc = 0;
@ -485,7 +541,14 @@ void gfunc_prolog(CType *func_type)
/* if the function returns a structure, then add an
implicit pointer parameter */
func_vt = sym->type;
func_var = (sym->f.func_type == FUNC_ELLIPSIS);
#ifdef TCC_TARGET_PE
size = type_size(&func_vt,&align);
if (((func_vt.t & VT_BTYPE) == VT_STRUCT)
&& (size > 8 || (size & (size - 1)))) {
#else
if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
#endif
/* XXX: fastcall case ? */
func_vc = addr;
addr += 4;
@ -517,61 +580,69 @@ void gfunc_prolog(CType *func_type)
param_index++;
}
func_ret_sub = 0;
/* pascal type call ? */
if (func_call == FUNC_STDCALL)
/* pascal type call or fastcall ? */
if (func_call == FUNC_STDCALL || func_call == FUNC_FASTCALLW)
func_ret_sub = addr - 8;
#ifdef TCC_TARGET_PE
#ifndef TCC_TARGET_PE
else if (func_vc)
func_ret_sub = 4;
#endif
#ifdef CONFIG_TCC_BCHECK
/* leave some room for bound checking code */
if (tcc_state->do_bounds_check) {
func_bound_offset = lbounds_section->data_offset;
func_bound_ind = ind;
oad(0xb8, 0); /* lbound section pointer */
oad(0xb8, 0); /* call to function */
func_bound_offset = lbounds_section->data_offset;
}
#endif
}
/* generate function epilog */
void gfunc_epilog(void)
ST_FUNC void gfunc_epilog(void)
{
int v, saved_ind;
addr_t v, saved_ind;
#ifdef CONFIG_TCC_BCHECK
if (tcc_state->do_bounds_check
&& func_bound_offset != lbounds_section->data_offset) {
int saved_ind;
int *bounds_ptr;
Sym *sym, *sym_data;
addr_t saved_ind;
addr_t *bounds_ptr;
Sym *sym_data;
/* add end of table info */
bounds_ptr = section_ptr_add(lbounds_section, sizeof(int));
bounds_ptr = section_ptr_add(lbounds_section, sizeof(addr_t));
*bounds_ptr = 0;
/* generate bound local allocation */
saved_ind = ind;
ind = func_sub_sp_offset;
ind = func_bound_ind;
sym_data = get_sym_ref(&char_pointer_type, lbounds_section,
func_bound_offset, lbounds_section->data_offset);
greloc(cur_text_section, sym_data,
ind + 1, R_386_32);
oad(0xb8, 0); /* mov %eax, xxx */
sym = external_global_sym(TOK___bound_local_new, &func_old_type, 0);
greloc(cur_text_section, sym,
ind + 1, R_386_PC32);
oad(0xe8, -4);
gen_static_call(TOK___bound_local_new);
ind = saved_ind;
/* generate bound check local freeing */
o(0x5250); /* save returned value, if any */
greloc(cur_text_section, sym_data,
ind + 1, R_386_32);
greloc(cur_text_section, sym_data, ind + 1, R_386_32);
oad(0xb8, 0); /* mov %eax, xxx */
sym = external_global_sym(TOK___bound_local_delete, &func_old_type, 0);
greloc(cur_text_section, sym,
ind + 1, R_386_PC32);
oad(0xe8, -4);
gen_static_call(TOK___bound_local_delete);
o(0x585a); /* restore returned value, if any */
}
#endif
/* align local size to word & save local variables */
v = (-loc + 3) & -4;
#if USE_EBX
o(0x8b);
gen_modrm(TREG_EBX, VT_LOCAL, NULL, -(v+4));
#endif
o(0xc9); /* leave */
if (func_ret_sub == 0) {
o(0xc3); /* ret */
@ -580,38 +651,34 @@ void gfunc_epilog(void)
g(func_ret_sub);
g(func_ret_sub >> 8);
}
/* align local size to word & save local variables */
v = (-loc + 3) & -4;
saved_ind = ind;
ind = func_sub_sp_offset - FUNC_PROLOG_SIZE;
#ifdef TCC_TARGET_PE
if (v >= 4096) {
Sym *sym = external_global_sym(TOK___chkstk, &func_old_type, 0);
oad(0xb8, v); /* mov stacksize, %eax */
oad(0xe8, -4); /* call __chkstk, (does the stackframe too) */
greloc(cur_text_section, sym, ind-4, R_386_PC32);
gen_static_call(TOK___chkstk); /* call __chkstk, (does the stackframe too) */
} else
#endif
{
o(0xe58955); /* push %ebp, mov %esp, %ebp */
o(0xec81); /* sub esp, stacksize */
gen_le32(v);
#if FUNC_PROLOG_SIZE == 10
#ifdef TCC_TARGET_PE
o(0x90); /* adjust to FUNC_PROLOG_SIZE */
#endif
}
o(0x53 * USE_EBX); /* push ebx */
ind = saved_ind;
}
/* generate a jump to a label */
int gjmp(int t)
ST_FUNC int gjmp(int t)
{
return psym(0xe9, t);
return gjmp2(0xe9, t);
}
/* generate a jump to a fixed address */
void gjmp_addr(int a)
ST_FUNC void gjmp_addr(int a)
{
int r;
r = a - ind - 2;
@ -623,53 +690,64 @@ void gjmp_addr(int a)
}
}
/* generate a test. set 'inv' to invert test. Stack entry is popped */
int gtst(int inv, int t)
ST_FUNC void gtst_addr(int inv, int a)
{
int v, *p;
v = vtop->r & VT_VALMASK;
int v = vtop->r & VT_VALMASK;
if (v == VT_CMP) {
inv ^= (vtop--)->c.i;
a -= ind + 2;
if (a == (char)a) {
g(inv - 32);
g(a);
} else {
g(0x0f);
oad(inv - 16, a - 4);
}
} else if ((v & ~1) == VT_JMP) {
if ((v & 1) != inv) {
gjmp_addr(a);
gsym(vtop->c.i);
} else {
gsym(vtop->c.i);
o(0x05eb);
gjmp_addr(a);
}
vtop--;
}
}
/* generate a test. set 'inv' to invert test. Stack entry is popped */
ST_FUNC int gtst(int inv, int t)
{
int v = vtop->r & VT_VALMASK;
if (nocode_wanted) {
;
} else if (v == VT_CMP) {
/* fast case : can jump directly since flags are set */
g(0x0f);
t = psym((vtop->c.i - 16) ^ inv, t);
t = gjmp2((vtop->c.i - 16) ^ inv, t);
} else if (v == VT_JMP || v == VT_JMPI) {
/* && or || optimization */
if ((v & 1) == inv) {
/* insert vtop->c jump list in t */
p = &vtop->c.i;
while (*p != 0)
p = (int *)(cur_text_section->data + *p);
*p = t;
t = vtop->c.i;
uint32_t n1, n = vtop->c.i;
if (n) {
while ((n1 = read32le(cur_text_section->data + n)))
n = n1;
write32le(cur_text_section->data + n, t);
t = vtop->c.i;
}
} else {
t = gjmp(t);
gsym(vtop->c.i);
}
} else {
if (is_float(vtop->type.t) ||
(vtop->type.t & VT_BTYPE) == VT_LLONG) {
vpushi(0);
gen_op(TOK_NE);
}
if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
/* constant jmp optimization */
if ((vtop->c.i != 0) != inv)
t = gjmp(t);
} else {
v = gv(RC_INT);
o(0x85);
o(0xc0 + v * 9);
g(0x0f);
t = psym(0x85 ^ inv, t);
}
}
vtop--;
return t;
}
/* generate an integer binary operation */
void gen_opi(int op)
ST_FUNC void gen_opi(int op)
{
int r, fr, opc, c;
@ -685,10 +763,16 @@ void gen_opi(int op)
vswap();
c = vtop->c.i;
if (c == (char)c) {
/* XXX: generate inc and dec for smaller code ? */
o(0x83);
o(0xc0 | (opc << 3) | r);
g(c);
/* generate inc and dec for smaller code */
if (c==1 && opc==0 && op != TOK_ADDC1) {
o (0x40 | r); // inc
} else if (c==1 && opc==5 && op != TOK_SUBC1) {
o (0x48 | r); // dec
} else {
o(0x83);
o(0xc0 | (opc << 3) | r);
g(c);
}
} else {
o(0x81);
oad(0xc0 | (opc << 3) | r, c);
@ -774,6 +858,8 @@ void gen_opi(int op)
fr = vtop[0].r;
vtop--;
save_reg(TREG_EDX);
/* save EAX too if used otherwise */
save_reg_upstack(TREG_EAX, 1);
if (op == TOK_UMULL) {
o(0xf7); /* mul fr */
o(0xe0 + fr);
@ -801,9 +887,9 @@ void gen_opi(int op)
}
/* generate a floating point operation 'v = t1 op t2' instruction. The
two operands are guaranted to have the same floating point type */
two operands are guaranteed to have the same floating point type */
/* XXX: need to use ST1 too */
void gen_opf(int op)
ST_FUNC void gen_opf(int op)
{
int a, ft, fc, swapped, r;
@ -840,7 +926,10 @@ void gen_opf(int op)
swapped = 0;
if (swapped)
o(0xc9d9); /* fxch %st(1) */
o(0xe9da); /* fucompp */
if (op == TOK_EQ || op == TOK_NE)
o(0xe9da); /* fucompp */
else
o(0xd9de); /* fcompp */
o(0xe0df); /* fnstsw %ax */
if (op == TOK_EQ) {
o(0x45e480); /* and $0x45, %ah */
@ -886,7 +975,7 @@ void gen_opf(int op)
break;
}
ft = vtop->type.t;
fc = vtop->c.ul;
fc = vtop->c.i;
if ((ft & VT_BTYPE) == VT_LDOUBLE) {
o(0xde); /* fxxxp %st, %st(1) */
o(0xc1 + (a << 3));
@ -898,7 +987,7 @@ void gen_opf(int op)
r = get_reg(RC_INT);
v1.type.t = VT_INT;
v1.r = VT_LOCAL | VT_LVAL;
v1.c.ul = fc;
v1.c.i = fc;
load(r, &v1);
fc = 0;
}
@ -915,7 +1004,7 @@ void gen_opf(int op)
/* convert integers to fp 't' type. Must handle 'int', 'unsigned int'
and 'long long' cases. */
void gen_cvt_itof(int t)
ST_FUNC void gen_cvt_itof(int t)
{
save_reg(TREG_ST0);
gv(RC_INT);
@ -944,65 +1033,31 @@ void gen_cvt_itof(int t)
}
/* convert fp to int 't' type */
/* XXX: handle long long case */
void gen_cvt_ftoi(int t)
ST_FUNC void gen_cvt_ftoi(int t)
{
int r, r2, size;
Sym *sym;
CType ushort_type;
ushort_type.t = VT_SHORT | VT_UNSIGNED;
gv(RC_FLOAT);
if (t != VT_INT)
size = 8;
else
size = 4;
o(0x2dd9); /* ldcw xxx */
sym = external_global_sym(TOK___tcc_int_fpu_control,
&ushort_type, VT_LVAL);
greloc(cur_text_section, sym,
ind, R_386_32);
gen_le32(0);
oad(0xec81, size); /* sub $xxx, %esp */
if (size == 4)
o(0x1cdb); /* fistpl */
int bt = vtop->type.t & VT_BTYPE;
if (bt == VT_FLOAT)
vpush_global_sym(&func_old_type, TOK___fixsfdi);
else if (bt == VT_LDOUBLE)
vpush_global_sym(&func_old_type, TOK___fixxfdi);
else
o(0x3cdf); /* fistpll */
o(0x24);
o(0x2dd9); /* ldcw xxx */
sym = external_global_sym(TOK___tcc_fpu_control,
&ushort_type, VT_LVAL);
greloc(cur_text_section, sym,
ind, R_386_32);
gen_le32(0);
r = get_reg(RC_INT);
o(0x58 + r); /* pop r */
if (size == 8) {
if (t == VT_LLONG) {
vtop->r = r; /* mark reg as used */
r2 = get_reg(RC_INT);
o(0x58 + r2); /* pop r2 */
vtop->r2 = r2;
} else {
o(0x04c483); /* add $4, %esp */
}
}
vtop->r = r;
vpush_global_sym(&func_old_type, TOK___fixdfdi);
vswap();
gfunc_call(1);
vpushi(0);
vtop->r = REG_IRET;
vtop->r2 = REG_LRET;
}
/* convert from one floating point type to another */
void gen_cvt_ftof(int t)
ST_FUNC void gen_cvt_ftof(int t)
{
/* all we have to do on i386 is to put the float in a register */
gv(RC_FLOAT);
}
/* computed goto support */
void ggoto(void)
ST_FUNC void ggoto(void)
{
gcall_or_jmp(1);
vtop--;
@ -1012,33 +1067,28 @@ void ggoto(void)
#ifdef CONFIG_TCC_BCHECK
/* generate a bounded pointer addition */
void gen_bounded_ptr_add(void)
ST_FUNC void gen_bounded_ptr_add(void)
{
Sym *sym;
/* prepare fast i386 function call (args in eax and edx) */
gv2(RC_EAX, RC_EDX);
/* save all temporary registers */
vtop -= 2;
save_regs(0);
/* do a fast function call */
sym = external_global_sym(TOK___bound_ptr_add, &func_old_type, 0);
greloc(cur_text_section, sym,
ind + 1, R_386_PC32);
oad(0xe8, -4);
gen_static_call(TOK___bound_ptr_add);
/* returned pointer is in eax */
vtop++;
vtop->r = TREG_EAX | VT_BOUNDED;
/* address of bounding function call point */
vtop->c.ul = (cur_text_section->reloc->data_offset - sizeof(Elf32_Rel));
vtop->c.i = (cur_text_section->reloc->data_offset - sizeof(Elf32_Rel));
}
/* patch pointer addition in vtop so that pointer dereferencing is
also tested */
void gen_bounded_ptr_deref(void)
ST_FUNC void gen_bounded_ptr_deref(void)
{
int func;
int size, align;
addr_t func;
int size, align;
Elf32_Rel *rel;
Sym *sym;
@ -1060,14 +1110,14 @@ void gen_bounded_ptr_deref(void)
case 12: func = TOK___bound_ptr_indir12; break;
case 16: func = TOK___bound_ptr_indir16; break;
default:
error("unhandled size when derefencing bounded pointer");
tcc_error("unhandled size when dereferencing bounded pointer");
func = 0;
break;
}
/* patch relocation */
/* XXX: find a better solution ? */
rel = (Elf32_Rel *)(cur_text_section->reloc->data + vtop->c.ul);
rel = (Elf32_Rel *)(cur_text_section->reloc->data + vtop->c.i);
sym = external_global_sym(func, &func_old_type, 0);
if (!sym->c)
put_extern_sym(sym, NULL, 0, 0);
@ -1075,6 +1125,40 @@ void gen_bounded_ptr_deref(void)
}
#endif
/* Save the stack pointer onto the stack */
ST_FUNC void gen_vla_sp_save(int addr) {
/* mov %esp,addr(%ebp)*/
o(0x89);
gen_modrm(TREG_ESP, VT_LOCAL, NULL, addr);
}
/* Restore the SP from a location on the stack */
ST_FUNC void gen_vla_sp_restore(int addr) {
o(0x8b);
gen_modrm(TREG_ESP, VT_LOCAL, NULL, addr);
}
/* Subtract from the stack pointer, and push the resulting value onto the stack */
ST_FUNC void gen_vla_alloc(CType *type, int align) {
#ifdef TCC_TARGET_PE
/* alloca does more than just adjust %rsp on Windows */
vpush_global_sym(&func_old_type, TOK_alloca);
vswap(); /* Move alloca ref past allocation size */
gfunc_call(1);
#else
int r;
r = gv(RC_INT); /* allocation size */
/* sub r,%rsp */
o(0x2b);
o(0xe0 | r);
/* We align to 16 bytes rather than align */
/* and ~15, %esp */
o(0xf0e483);
vpop();
#endif
}
/* end of X86 code generator */
/*************************************************************/
#endif
/*************************************************************/

247
i386-link.c 100644
View File

@ -0,0 +1,247 @@
#ifdef TARGET_DEFS_ONLY
#define EM_TCC_TARGET EM_386
/* relocation type for 32 bit data relocation */
#define R_DATA_32 R_386_32
#define R_DATA_PTR R_386_32
#define R_JMP_SLOT R_386_JMP_SLOT
#define R_GLOB_DAT R_386_GLOB_DAT
#define R_COPY R_386_COPY
#define R_RELATIVE R_386_RELATIVE
#define R_NUM R_386_NUM
#define ELF_START_ADDR 0x08048000
#define ELF_PAGE_SIZE 0x1000
#define PCRELATIVE_DLLPLT 0
#define RELOCATE_DLLPLT 0
#else /* !TARGET_DEFS_ONLY */
#include "tcc.h"
/* Returns 1 for a code relocation, 0 for a data relocation. For unknown
relocations, returns -1. */
int code_reloc (int reloc_type)
{
switch (reloc_type) {
case R_386_RELATIVE:
case R_386_16:
case R_386_32:
case R_386_GOTPC:
case R_386_GOTOFF:
case R_386_GOT32:
case R_386_GOT32X:
case R_386_GLOB_DAT:
case R_386_COPY:
return 0;
case R_386_PC16:
case R_386_PC32:
case R_386_PLT32:
case R_386_JMP_SLOT:
return 1;
}
tcc_error ("Unknown relocation type: %d", reloc_type);
return -1;
}
/* Returns an enumerator to describe whether and when the relocation needs a
GOT and/or PLT entry to be created. See tcc.h for a description of the
different values. */
int gotplt_entry_type (int reloc_type)
{
switch (reloc_type) {
case R_386_RELATIVE:
case R_386_16:
case R_386_GLOB_DAT:
case R_386_JMP_SLOT:
case R_386_COPY:
return NO_GOTPLT_ENTRY;
case R_386_32:
/* This relocations shouldn't normally need GOT or PLT
slots if it weren't for simplicity in the code generator.
See our caller for comments. */
return AUTO_GOTPLT_ENTRY;
case R_386_PC16:
case R_386_PC32:
return AUTO_GOTPLT_ENTRY;
case R_386_GOTPC:
case R_386_GOTOFF:
return BUILD_GOT_ONLY;
case R_386_GOT32:
case R_386_GOT32X:
case R_386_PLT32:
return ALWAYS_GOTPLT_ENTRY;
}
tcc_error ("Unknown relocation type: %d", reloc_type);
return -1;
}
ST_FUNC unsigned create_plt_entry(TCCState *s1, unsigned got_offset, struct sym_attr *attr)
{
Section *plt = s1->plt;
uint8_t *p;
int modrm;
unsigned plt_offset, relofs;
/* on i386 if we build a DLL, we add a %ebx offset */
if (s1->output_type == TCC_OUTPUT_DLL)
modrm = 0xa3;
else
modrm = 0x25;
/* empty PLT: create PLT0 entry that pushes the library identifier
(GOT + PTR_SIZE) and jumps to ld.so resolution routine
(GOT + 2 * PTR_SIZE) */
if (plt->data_offset == 0) {
p = section_ptr_add(plt, 16);
p[0] = 0xff; /* pushl got + PTR_SIZE */
p[1] = modrm + 0x10;
write32le(p + 2, PTR_SIZE);
p[6] = 0xff; /* jmp *(got + PTR_SIZE * 2) */
p[7] = modrm;
write32le(p + 8, PTR_SIZE * 2);
}
plt_offset = plt->data_offset;
/* The PLT slot refers to the relocation entry it needs via offset.
The reloc entry is created below, so its offset is the current
data_offset */
relofs = s1->got->reloc ? s1->got->reloc->data_offset : 0;
/* Jump to GOT entry where ld.so initially put the address of ip + 4 */
p = section_ptr_add(plt, 16);
p[0] = 0xff; /* jmp *(got + x) */
p[1] = modrm;
write32le(p + 2, got_offset);
p[6] = 0x68; /* push $xxx */
write32le(p + 7, relofs);
p[11] = 0xe9; /* jmp plt_start */
write32le(p + 12, -(plt->data_offset));
return plt_offset;
}
/* relocate the PLT: compute addresses and offsets in the PLT now that final
address for PLT and GOT are known (see fill_program_header) */
ST_FUNC void relocate_plt(TCCState *s1)
{
uint8_t *p, *p_end;
if (!s1->plt)
return;
p = s1->plt->data;
p_end = p + s1->plt->data_offset;
if (p < p_end) {
add32le(p + 2, s1->got->sh_addr);
add32le(p + 8, s1->got->sh_addr);
p += 16;
while (p < p_end) {
add32le(p + 2, s1->got->sh_addr);
p += 16;
}
}
}
static ElfW_Rel *qrel; /* ptr to next reloc entry reused */
void relocate_init(Section *sr)
{
qrel = (ElfW_Rel *) sr->data;
}
void relocate(TCCState *s1, ElfW_Rel *rel, int type, unsigned char *ptr, addr_t addr, addr_t val)
{
int sym_index, esym_index;
sym_index = ELFW(R_SYM)(rel->r_info);
switch (type) {
case R_386_32:
if (s1->output_type == TCC_OUTPUT_DLL) {
esym_index = s1->sym_attrs[sym_index].dyn_index;
qrel->r_offset = rel->r_offset;
if (esym_index) {
qrel->r_info = ELFW(R_INFO)(esym_index, R_386_32);
qrel++;
return;
} else {
qrel->r_info = ELFW(R_INFO)(0, R_386_RELATIVE);
qrel++;
}
}
add32le(ptr, val);
return;
case R_386_PC32:
if (s1->output_type == TCC_OUTPUT_DLL) {
/* DLL relocation */
esym_index = s1->sym_attrs[sym_index].dyn_index;
if (esym_index) {
qrel->r_offset = rel->r_offset;
qrel->r_info = ELFW(R_INFO)(esym_index, R_386_PC32);
qrel++;
return;
}
}
add32le(ptr, val - addr);
return;
case R_386_PLT32:
add32le(ptr, val - addr);
return;
case R_386_GLOB_DAT:
case R_386_JMP_SLOT:
write32le(ptr, val);
return;
case R_386_GOTPC:
add32le(ptr, s1->got->sh_addr - addr);
return;
case R_386_GOTOFF:
add32le(ptr, val - s1->got->sh_addr);
return;
case R_386_GOT32:
case R_386_GOT32X:
/* we load the got offset */
add32le(ptr, s1->sym_attrs[sym_index].got_offset);
return;
case R_386_16:
if (s1->output_format != TCC_OUTPUT_FORMAT_BINARY) {
output_file:
tcc_error("can only produce 16-bit binary files");
}
write16le(ptr, read16le(ptr) + val);
return;
case R_386_PC16:
if (s1->output_format != TCC_OUTPUT_FORMAT_BINARY)
goto output_file;
write16le(ptr, read16le(ptr) + val - addr);
return;
case R_386_RELATIVE:
#ifdef TCC_TARGET_PE
add32le(ptr, val - s1->pe_imagebase);
#endif
/* do nothing */
return;
case R_386_COPY:
/* This relocation must copy initialized data from the library
to the program .bss segment. Currently made like for ARM
(to remove noise of default case). Is this true?
*/
return;
default:
fprintf(stderr,"FIXME: handle reloc type %d at %x [%p] to %x\n",
type, (unsigned)addr, ptr, (unsigned)val);
return;
}
}
#endif /* !TARGET_DEFS_ONLY */

View File

@ -1,5 +1,7 @@
/* ------------------------------------------------------------------ */
/* WARNING: relative order of tokens is important. */
/* register */
DEF_ASM(al)
DEF_ASM(cl)
DEF_ASM(dl)
@ -24,6 +26,16 @@
DEF_ASM(ebp)
DEF_ASM(esi)
DEF_ASM(edi)
#ifdef TCC_TARGET_X86_64
DEF_ASM(rax)
DEF_ASM(rcx)
DEF_ASM(rdx)
DEF_ASM(rbx)
DEF_ASM(rsp)
DEF_ASM(rbp)
DEF_ASM(rsi)
DEF_ASM(rdi)
#endif
DEF_ASM(mm0)
DEF_ASM(mm1)
DEF_ASM(mm2)
@ -79,65 +91,83 @@
DEF_ASM(fs)
DEF_ASM(gs)
DEF_ASM(st)
DEF_ASM(rip)
DEF_BWL(mov)
#ifdef TCC_TARGET_X86_64
/* The four low parts of sp/bp/si/di that exist only on
x86-64 (encoding aliased to ah,ch,dh,dh when not using REX). */
DEF_ASM(spl)
DEF_ASM(bpl)
DEF_ASM(sil)
DEF_ASM(dil)
#endif
/* generic two operands */
DEF_BWL(add)
DEF_BWL(or)
DEF_BWL(adc)
DEF_BWL(sbb)
DEF_BWL(and)
DEF_BWL(sub)
DEF_BWL(xor)
DEF_BWL(cmp)
DEF_BWLX(mov)
DEF_BWLX(add)
DEF_BWLX(or)
DEF_BWLX(adc)
DEF_BWLX(sbb)
DEF_BWLX(and)
DEF_BWLX(sub)
DEF_BWLX(xor)
DEF_BWLX(cmp)
/* unary ops */
DEF_BWL(inc)
DEF_BWL(dec)
DEF_BWL(not)
DEF_BWL(neg)
DEF_BWL(mul)
DEF_BWL(imul)
DEF_BWL(div)
DEF_BWL(idiv)
DEF_BWLX(inc)
DEF_BWLX(dec)
DEF_BWLX(not)
DEF_BWLX(neg)
DEF_BWLX(mul)
DEF_BWLX(imul)
DEF_BWLX(div)
DEF_BWLX(idiv)
DEF_BWL(xchg)
DEF_BWL(test)
DEF_BWLX(xchg)
DEF_BWLX(test)
/* shifts */
DEF_BWL(rol)
DEF_BWL(ror)
DEF_BWL(rcl)
DEF_BWL(rcr)
DEF_BWL(shl)
DEF_BWL(shr)
DEF_BWL(sar)
DEF_BWLX(rol)
DEF_BWLX(ror)
DEF_BWLX(rcl)
DEF_BWLX(rcr)
DEF_BWLX(shl)
DEF_BWLX(shr)
DEF_BWLX(sar)
DEF_ASM(shldw)
DEF_ASM(shldl)
DEF_ASM(shld)
DEF_ASM(shrdw)
DEF_ASM(shrdl)
DEF_ASM(shrd)
DEF_WLX(shld)
DEF_WLX(shrd)
DEF_ASM(pushw)
DEF_ASM(pushl)
#ifdef TCC_TARGET_X86_64
DEF_ASM(pushq)
#endif
DEF_ASM(push)
DEF_ASM(popw)
DEF_ASM(popl)
#ifdef TCC_TARGET_X86_64
DEF_ASM(popq)
#endif
DEF_ASM(pop)
DEF_BWL(in)
DEF_BWL(out)
DEF_WL(movzb)
DEF_WLX(movzb)
DEF_ASM(movzwl)
DEF_ASM(movsbw)
DEF_ASM(movsbl)
DEF_ASM(movswl)
#ifdef TCC_TARGET_X86_64
DEF_ASM(movsbq)
DEF_ASM(movswq)
DEF_ASM(movzwq)
DEF_ASM(movslq)
#endif
DEF_WL(lea)
DEF_WLX(lea)
DEF_ASM(les)
DEF_ASM(lds)
@ -150,26 +180,28 @@
DEF_ASM(lcall)
DEF_ASM(ljmp)
DEF_ASMTEST(j)
DEF_ASMTEST(j,)
DEF_ASMTEST(set)
DEF_ASMTEST(cmov)
DEF_ASMTEST(set,)
DEF_ASMTEST(set,b)
DEF_ASMTEST(cmov,)
DEF_WL(bsf)
DEF_WL(bsr)
DEF_WL(bt)
DEF_WL(bts)
DEF_WL(btr)
DEF_WL(btc)
DEF_WLX(bsf)
DEF_WLX(bsr)
DEF_WLX(bt)
DEF_WLX(bts)
DEF_WLX(btr)
DEF_WLX(btc)
DEF_WL(lsl)
DEF_WLX(lar)
DEF_WLX(lsl)
/* generic FP ops */
DEF_FP(add)
DEF_FP(mul)
DEF_ASM(fcom)
DEF_ASM(fcom_1) /* non existant op, just to have a regular table */
DEF_ASM(fcom_1) /* non existent op, just to have a regular table */
DEF_FP1(com)
DEF_FP(comp)
@ -178,32 +210,35 @@
DEF_FP(div)
DEF_FP(divr)
DEF_BWL(xadd)
DEF_BWL(cmpxchg)
DEF_BWLX(xadd)
DEF_BWLX(cmpxchg)
/* string ops */
DEF_BWL(cmps)
DEF_BWL(scmp)
DEF_BWLX(cmps)
DEF_BWLX(scmp)
DEF_BWL(ins)
DEF_BWL(outs)
DEF_BWL(lods)
DEF_BWL(slod)
DEF_BWL(movs)
DEF_BWL(smov)
DEF_BWL(scas)
DEF_BWL(ssca)
DEF_BWL(stos)
DEF_BWL(ssto)
DEF_BWLX(lods)
DEF_BWLX(slod)
DEF_BWLX(movs)
DEF_BWLX(smov)
DEF_BWLX(scas)
DEF_BWLX(ssca)
DEF_BWLX(stos)
DEF_BWLX(ssto)
/* generic asm ops */
#define ALT(x)
#define DEF_ASM_OP0(name, opcode) DEF_ASM(name)
#define DEF_ASM_OP0L(name, opcode, group, instr_type)
#define DEF_ASM_OP1(name, opcode, group, instr_type, op0)
#define DEF_ASM_OP2(name, opcode, group, instr_type, op0, op1)
#define DEF_ASM_OP3(name, opcode, group, instr_type, op0, op1, op2)
#include "i386-asm.h"
#ifdef TCC_TARGET_X86_64
# include "x86_64-asm.h"
#else
# include "i386-asm.h"
#endif
#define ALT(x)
#define DEF_ASM_OP0(name, opcode)
@ -211,4 +246,8 @@
#define DEF_ASM_OP1(name, opcode, group, instr_type, op0) DEF_ASM(name)
#define DEF_ASM_OP2(name, opcode, group, instr_type, op0, op1) DEF_ASM(name)
#define DEF_ASM_OP3(name, opcode, group, instr_type, op0, op1, op2) DEF_ASM(name)
#include "i386-asm.h"
#ifdef TCC_TARGET_X86_64
# include "x86_64-asm.h"
#else
# include "i386-asm.h"
#endif

View File

@ -18,6 +18,8 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#error this code has bit-rotted since 2003
/* number of available registers */
#define NB_REGS 3
@ -53,11 +55,11 @@ const int reg_classes[NB_REGS] = {
#define REG_FRET REG_ST0 /* float return register */
/* defined if function parameters must be evaluated in reverse order */
//#define INVERT_FUNC_PARAMS
/* #define INVERT_FUNC_PARAMS */
/* defined if structures are passed as pointers. Otherwise structures
are directly pushed on stack. */
//#define FUNC_STRUCT_PARAM_AS_PTR
/* #define FUNC_STRUCT_PARAM_AS_PTR */
/* pointer size, in bytes */
#define PTR_SIZE 4
@ -193,7 +195,7 @@ static void il_type_to_str(char *buf, int buf_size,
pstrcat(buf, buf_size, tstr);
break;
case VT_STRUCT:
error("structures not handled yet");
tcc_error("structures not handled yet");
break;
case VT_FUNC:
s = sym_find((unsigned)t >> VT_STRUCT_SHIFT);
@ -387,7 +389,7 @@ void gfunc_start(GFuncContext *c, int func_call)
void gfunc_param(GFuncContext *c)
{
if ((vtop->t & VT_BTYPE) == VT_STRUCT) {
error("structures passed as value not handled yet");
tcc_error("structures passed as value not handled yet");
} else {
/* simply push on stack */
gv(RC_ST0);
@ -441,6 +443,7 @@ void gfunc_prolog(int t)
/* if the function returns a structure, then add an
implicit pointer parameter */
func_vt = sym->t;
func_var = (sym->c == FUNC_ELLIPSIS);
if ((func_vt & VT_BTYPE) == VT_STRUCT) {
func_vc = addr;
addr++;
@ -528,19 +531,6 @@ int gtst(int inv, int t)
t = gjmp(t);
gsym(vtop->c.i);
}
} else {
if (is_float(vtop->t)) {
vpushi(0);
gen_op(TOK_NE);
}
if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_FORWARD)) == VT_CONST) {
/* constant jmp optimization */
if ((vtop->c.i != 0) != inv)
t = gjmp(t);
} else {
v = gv(RC_INT);
t = out_opj(IL_OP_BRTRUE - inv, t);
}
}
vtop--;
return t;
@ -612,7 +602,7 @@ void gen_opi(int op)
}
/* generate a floating point operation 'v = t1 op t2' instruction. The
two operands are guaranted to have the same floating point type */
two operands are guaranteed to have the same floating point type */
void gen_opf(int op)
{
/* same as integer */

View File

@ -27,7 +27,7 @@
#define DBL_MAX_10_EXP 308
/* horrible intel long double */
#ifdef __i386__
#if defined __i386__ || defined __x86_64__
#define LDBL_MANT_DIG 64
#define LDBL_DIG 18

View File

@ -3,10 +3,10 @@
#ifdef __x86_64__
#ifndef _WIN64
#include <stdlib.h>
//This should be in sync with the declaration on our lib/libtcc1.c
/* GCC compatible definition of va_list. */
struct __va_list_struct {
typedef struct {
unsigned int gp_offset;
unsigned int fp_offset;
union {
@ -14,49 +14,55 @@ struct __va_list_struct {
char *overflow_arg_area;
};
char *reg_save_area;
};
} __va_list_struct;
typedef struct __va_list_struct *va_list;
typedef __va_list_struct va_list[1];
/* we use __builtin_(malloc|free) to avoid #define malloc tcc_malloc */
/* XXX: this lacks the support of aggregated types. */
#define va_start(ap, last) \
(ap = (va_list)__builtin_malloc(sizeof(struct __va_list_struct)), \
*ap = *(struct __va_list_struct*)( \
(char*)__builtin_frame_address(0) - 16), \
ap->overflow_arg_area = ((char *)__builtin_frame_address(0) + \
ap->overflow_offset), \
ap->reg_save_area = (char *)__builtin_frame_address(0) - 176 - 16 \
)
#define va_arg(ap, type) \
(*(type*)(__builtin_types_compatible_p(type, long double) \
? (ap->overflow_arg_area += 16, \
ap->overflow_arg_area - 16) \
: __builtin_types_compatible_p(type, double) \
? (ap->fp_offset < 128 + 48 \
? (ap->fp_offset += 16, \
ap->reg_save_area + ap->fp_offset - 16) \
: (ap->overflow_arg_area += 8, \
ap->overflow_arg_area - 8)) \
: (ap->gp_offset < 48 \
? (ap->gp_offset += 8, \
ap->reg_save_area + ap->gp_offset - 8) \
: (ap->overflow_arg_area += 8, \
ap->overflow_arg_area - 8)) \
))
#define va_copy(dest, src) \
((dest) = (va_list)malloc(sizeof(struct __va_list_struct)), \
*(dest) = *(src))
#define va_end(ap) __builtin_free(ap)
void __va_start(__va_list_struct *ap, void *fp);
void *__va_arg(__va_list_struct *ap, int arg_type, int size, int align);
#define va_start(ap, last) __va_start(ap, __builtin_frame_address(0))
#define va_arg(ap, type) \
(*(type *)(__va_arg(ap, __builtin_va_arg_types(type), sizeof(type), __alignof__(type))))
#define va_copy(dest, src) (*(dest) = *(src))
#define va_end(ap)
/* avoid conflicting definition for va_list on Macs. */
#define _VA_LIST_T
#else /* _WIN64 */
typedef char *va_list;
#define va_start(ap,last) ap = ((char *)&(last)) + ((sizeof(last)+7)&~7)
#define va_arg(ap,type) (ap += (sizeof(type)+7)&~7, *(type *)(ap - ((sizeof(type)+7)&~7)))
#define va_copy(dest, src) (dest) = (src)
#define va_start(ap,last) __builtin_va_start(ap,last)
#define va_arg(ap, t) ((sizeof(t) > 8 || (sizeof(t) & (sizeof(t) - 1))) \
? **(t **)((ap += 8) - 8) : *(t *)((ap += 8) - 8))
#define va_copy(dest, src) ((dest) = (src))
#define va_end(ap)
#endif
#elif __arm__
typedef char *va_list;
#define _tcc_alignof(type) ((int)&((struct {char c;type x;} *)0)->x)
#define _tcc_align(addr,type) (((unsigned)addr + _tcc_alignof(type) - 1) \
& ~(_tcc_alignof(type) - 1))
#define va_start(ap,last) ap = ((char *)&(last)) + ((sizeof(last)+3)&~3)
#define va_arg(ap,type) (ap = (void *) ((_tcc_align(ap,type)+sizeof(type)+3) \
&~3), *(type *)(ap - ((sizeof(type)+3)&~3)))
#define va_copy(dest, src) (dest) = (src)
#define va_end(ap)
#elif defined(__aarch64__)
typedef struct {
void *__stack;
void *__gr_top;
void *__vr_top;
int __gr_offs;
int __vr_offs;
} va_list;
#define va_start(ap, last) __va_start(ap, last)
#define va_arg(ap, type) __va_arg(ap, type)
#define va_end(ap)
#define va_copy(dest, src) ((dest) = (src))
#else /* __i386__ */
typedef char *va_list;
/* only correct for i386 */

View File

@ -6,5 +6,6 @@
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif /* _STDBOOL_H */

View File

@ -1,20 +1,54 @@
#ifndef _STDDEF_H
#define _STDDEF_H
#define NULL ((void *)0)
typedef __SIZE_TYPE__ size_t;
typedef __PTRDIFF_TYPE__ ssize_t;
typedef __WCHAR_TYPE__ wchar_t;
typedef __PTRDIFF_TYPE__ ptrdiff_t;
#define offsetof(type, field) ((size_t) &((type *)0)->field)
typedef __PTRDIFF_TYPE__ intptr_t;
typedef __SIZE_TYPE__ uintptr_t;
#ifndef __int8_t_defined
#define __int8_t_defined
typedef char int8_t;
typedef short int int16_t;
typedef int int32_t;
typedef long long int int64_t;
typedef signed char int8_t;
typedef signed short int int16_t;
typedef signed int int32_t;
#ifdef __LP64__
typedef signed long int int64_t;
#else
typedef signed long long int int64_t;
#endif
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;
typedef unsigned int uint32_t;
#ifdef __LP64__
typedef unsigned long int uint64_t;
#else
typedef unsigned long long int uint64_t;
#endif
#endif
#ifndef NULL
#define NULL ((void*)0)
#endif
#define offsetof(type, field) ((size_t)&((type *)0)->field)
void *alloca(size_t size);
#endif
/* Older glibc require a wint_t from <stddef.h> (when requested
by __need_wint_t, as otherwise stddef.h isn't allowed to
define this type). Note that this must be outside the normal
_STDDEF_H guard, so that it works even when we've included the file
already (without requiring wint_t). Some other libs define _WINT_T
if they've already provided that type, so we can use that as guard.
TCC defines __WINT_TYPE__ for us. */
#if defined (__need_wint_t)
#ifndef _WINT_T
#define _WINT_T
typedef __WINT_TYPE__ wint_t;
#endif
#undef __need_wint_t
#endif

73
lib/Makefile 100644
View File

@ -0,0 +1,73 @@
#
# Tiny C Compiler Makefile for libtcc1.a
#
TOP = ..
include $(TOP)/Makefile
VPATH = $(TOPSRC)/lib $(TOPSRC)/win32/lib
T = $(or $(CROSS_TARGET),$(NATIVE_TARGET),unknown)
X = $(if $(CROSS_TARGET),$(CROSS_TARGET)-)
BIN = $(TOP)/$(X)libtcc1.a
XTCC ?= $(TOP)/$(X)tcc$(EXESUF)
XCC = $(XTCC)
XAR = $(XTCC) -ar
XFLAGS-unx = -B$(TOPSRC)
XFLAGS-win = -B$(TOPSRC)/win32 -I$(TOPSRC)/include
XFLAGS = $(XFLAGS$(XCFG))
XCFG = $(or $(findstring -win,$T),-unx)
# in order to use gcc, tyoe: make <target>-libtcc1-usegcc=yes
arm-libtcc1-usegcc ?= no
ifeq "$($(T)-libtcc1-usegcc)" "yes"
XCC = $(CC)
XAR = $(AR)
XFLAGS = $(CFLAGS) -fPIC
endif
# only for native compiler
$(X)BCHECK_O = bcheck.o
ifeq ($(CONFIG_musl)$(CONFIG_uClibc),yes)
BCHECK_O =
endif
ifdef CONFIG_OSX
XFLAGS += -D_ANSI_SOURCE
endif
I386_O = libtcc1.o alloca86.o alloca86-bt.o
X86_64_O = libtcc1.o alloca86_64.o alloca86_64-bt.o
ARM_O = libtcc1.o armeabi.o alloca-arm.o armflush.o
ARM64_O = lib-arm64.o
WIN_O = crt1.o crt1w.o wincrt1.o wincrt1w.o dllcrt1.o dllmain.o
OBJ-i386 = $(I386_O) $(BCHECK_O)
OBJ-x86_64 = $(X86_64_O) va_list.o $(BCHECK_O)
OBJ-x86_64-osx = $(X86_64_O) va_list.o
OBJ-i386-win32 = $(I386_O) chkstk.o bcheck.o $(WIN_O)
OBJ-x86_64-win32 = $(X86_64_O) chkstk.o bcheck.o $(WIN_O)
OBJ-arm64 = $(ARM64_O)
OBJ-arm = $(ARM_O)
OBJ-arm-fpa = $(ARM_O)
OBJ-arm-fpa-ld = $(ARM_O)
OBJ-arm-vfp = $(ARM_O)
OBJ-arm-eabi = $(ARM_O)
OBJ-arm-eabihf = $(ARM_O)
OBJ-arm-wince = $(ARM_O) $(WIN_O)
$(BIN) : $(patsubst %.o,$(X)%.o,$(OBJ-$T))
$(XAR) rcs $@ $^
$(X)%.o : %.c
$(XCC) -c $< -o $@ $(XFLAGS)
$(X)%.o : %.S
$(XCC) -c $< -o $@ $(XFLAGS)
$(X)crt1w.o : crt1.c
$(X)wincrt1w.o : wincrt1.c
clean :
rm -f *.a *.o $(BIN)

17
lib/alloca-arm.S 100644
View File

@ -0,0 +1,17 @@
.text
.align 2
.global alloca
.type alloca, %function
alloca:
#ifdef __TINYC__
.int 0xe060d00d
.int 0xe3cdd007
.int 0xe1a0000d
.int 0xe1a0f00e
#else
rsb sp, r0, sp
bic sp, sp, #7
mov r0, sp
mov pc, lr
#endif
.size alloca, .-alloca

View File

@ -1,8 +1,6 @@
/* ---------------------------------------------- */
/* alloca86-bt.S */
#include "../config.h"
.globl __bound_alloca
__bound_alloca:
@ -13,13 +11,13 @@ __bound_alloca:
and $-4,%eax
jz p6
#ifdef TCC_TARGET_PE
#ifdef _WIN32
p4:
cmp $4096,%eax
jle p5
jbe p5
test %eax,-4096(%esp)
sub $4096,%esp
sub $4096,%eax
test %eax,(%esp)
jmp p4
p5:
@ -42,4 +40,8 @@ p6:
push %edx
ret
/* mark stack as nonexecutable */
#if defined __ELF__ && defined __linux__
.section .note.GNU-stack,"",@progbits
#endif
/* ---------------------------------------------- */

View File

@ -1,8 +1,6 @@
/* ---------------------------------------------- */
/* alloca86.S */
#include "../config.h"
.globl alloca
alloca:
@ -12,13 +10,13 @@ alloca:
and $-4,%eax
jz p3
#ifdef TCC_TARGET_PE
#ifdef _WIN32
p1:
cmp $4096,%eax
jle p2
jbe p2
test %eax,-4096(%esp)
sub $4096,%esp
sub $4096,%eax
test %eax,(%esp)
jmp p1
p2:
#endif

View File

@ -0,0 +1,56 @@
/* ---------------------------------------------- */
/* alloca86_64.S */
.globl __bound_alloca
__bound_alloca:
#ifdef _WIN32
# bound checking is not implemented
pop %rdx
mov %rcx,%rax
add $15,%rax
and $-16,%rax
jz p3
p1:
cmp $4096,%rax
jbe p2
test %rax,-4096(%rsp)
sub $4096,%rsp
sub $4096,%rax
jmp p1
p2:
sub %rax,%rsp
mov %rsp,%rax
add $32,%rax
p3:
push %rdx
ret
#else
pop %rdx
mov %rdi,%rax
mov %rax,%rsi # size, a second parm to the __bound_new_region
add $15,%rax
and $-16,%rax
jz p3
sub %rax,%rsp
mov %rsp,%rdi # pointer, a first parm to the __bound_new_region
mov %rsp,%rax
push %rdx
push %rax
call __bound_new_region
pop %rax
pop %rdx
p3:
push %rdx
ret
#endif
/* ---------------------------------------------- */

View File

@ -1,13 +1,11 @@
/* ---------------------------------------------- */
/* alloca86_64.S */
#include "../config.h"
.globl alloca
alloca:
pop %rdx
#ifdef TCC_TARGET_PE
#ifdef _WIN32
mov %rcx,%rax
#else
mov %rdi,%rax
@ -16,23 +14,19 @@ alloca:
and $-16,%rax
jz p3
#ifdef TCC_TARGET_PE
#ifdef _WIN32
p1:
cmp $4096,%rax
jle p2
jbe p2
test %rax,-4096(%rsp)
sub $4096,%rsp
sub $4096,%rax
test %rax,(%rsp)
jmp p1
p2:
#endif
sub %rax,%rsp
mov %rsp,%rax
#ifdef TCC_TARGET_PE
add $32,%rax
#endif
p3:
push %rdx
ret

501
lib/armeabi.c 100644
View File

@ -0,0 +1,501 @@
/* TCC ARM runtime EABI
Copyright (C) 2013 Thomas Preud'homme
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
#ifdef __TINYC__
#define INT_MIN (-2147483647 - 1)
#define INT_MAX 2147483647
#define UINT_MAX 0xffffffff
#define LONG_MIN (-2147483647L - 1)
#define LONG_MAX 2147483647L
#define ULONG_MAX 0xffffffffUL
#define LLONG_MAX 9223372036854775807LL
#define LLONG_MIN (-9223372036854775807LL - 1)
#define ULLONG_MAX 0xffffffffffffffffULL
#else
#include <limits.h>
#endif
/* We rely on the little endianness and EABI calling convention for this to
work */
typedef struct double_unsigned_struct {
unsigned low;
unsigned high;
} double_unsigned_struct;
typedef struct unsigned_int_struct {
unsigned low;
int high;
} unsigned_int_struct;
#define REGS_RETURN(name, type) \
void name ## _return(type ret) {}
/* Float helper functions */
#define FLOAT_EXP_BITS 8
#define FLOAT_FRAC_BITS 23
#define DOUBLE_EXP_BITS 11
#define DOUBLE_FRAC_BITS 52
#define ONE_EXP(type) ((1 << (type ## _EXP_BITS - 1)) - 1)
REGS_RETURN(unsigned_int_struct, unsigned_int_struct)
REGS_RETURN(double_unsigned_struct, double_unsigned_struct)
/* float -> integer: (sign) 1.fraction x 2^(exponent - exp_for_one) */
/* float to [unsigned] long long conversion */
#define DEFINE__AEABI_F2XLZ(name, with_sign) \
void __aeabi_ ## name(unsigned val) \
{ \
int exp, high_shift, sign; \
double_unsigned_struct ret; \
\
/* compute sign */ \
sign = val >> 31; \
\
/* compute real exponent */ \
exp = val >> FLOAT_FRAC_BITS; \
exp &= (1 << FLOAT_EXP_BITS) - 1; \
exp -= ONE_EXP(FLOAT); \
\
/* undefined behavior if truncated value cannot be represented */ \
if (with_sign) { \
if (exp > 62) /* |val| too big, double cannot represent LLONG_MAX */ \
return; \
} else { \
if ((sign && exp >= 0) || exp > 63) /* if val < 0 || val too big */ \
return; \
} \
\
val &= (1 << FLOAT_FRAC_BITS) - 1; \
if (exp >= 32) { \
ret.high = 1 << (exp - 32); \
if (exp - 32 >= FLOAT_FRAC_BITS) { \
ret.high |= val << (exp - 32 - FLOAT_FRAC_BITS); \
ret.low = 0; \
} else { \
high_shift = FLOAT_FRAC_BITS - (exp - 32); \
ret.high |= val >> high_shift; \
ret.low = val << (32 - high_shift); \
} \
} else { \
ret.high = 0; \
ret.low = 1 << exp; \
if (exp > FLOAT_FRAC_BITS) \
ret.low |= val << (exp - FLOAT_FRAC_BITS); \
else \
ret.low |= val >> (FLOAT_FRAC_BITS - exp); \
} \
\
/* encode negative integer using 2's complement */ \
if (with_sign && sign) { \
ret.low = ~ret.low; \
ret.high = ~ret.high; \
if (ret.low == UINT_MAX) { \
ret.low = 0; \
ret.high++; \
} else \
ret.low++; \
} \
\
double_unsigned_struct_return(ret); \
}
/* float to unsigned long long conversion */
DEFINE__AEABI_F2XLZ(f2ulz, 0)
/* float to long long conversion */
DEFINE__AEABI_F2XLZ(f2lz, 1)
/* double to [unsigned] long long conversion */
#define DEFINE__AEABI_D2XLZ(name, with_sign) \
void __aeabi_ ## name(double_unsigned_struct val) \
{ \
int exp, high_shift, sign; \
double_unsigned_struct ret; \
\
/* compute sign */ \
sign = val.high >> 31; \
\
/* compute real exponent */ \
exp = (val.high >> (DOUBLE_FRAC_BITS - 32)); \
exp &= (1 << DOUBLE_EXP_BITS) - 1; \
exp -= ONE_EXP(DOUBLE); \
\
/* undefined behavior if truncated value cannot be represented */ \
if (with_sign) { \
if (exp > 62) /* |val| too big, double cannot represent LLONG_MAX */ \
return; \
} else { \
if ((sign && exp >= 0) || exp > 63) /* if val < 0 || val too big */ \
return; \
} \
\
val.high &= (1 << (DOUBLE_FRAC_BITS - 32)) - 1; \
if (exp >= 32) { \
ret.high = 1 << (exp - 32); \
if (exp >= DOUBLE_FRAC_BITS) { \
high_shift = exp - DOUBLE_FRAC_BITS; \
ret.high |= val.high << high_shift; \
ret.high |= val.low >> (32 - high_shift); \
ret.low = val.low << high_shift; \
} else { \
high_shift = DOUBLE_FRAC_BITS - exp; \
ret.high |= val.high >> high_shift; \
ret.low = val.high << (32 - high_shift); \
ret.low |= val.low >> high_shift; \
} \
} else { \
ret.high = 0; \
ret.low = 1 << exp; \
if (exp > DOUBLE_FRAC_BITS - 32) { \
high_shift = exp - DOUBLE_FRAC_BITS - 32; \
ret.low |= val.high << high_shift; \
ret.low |= val.low >> (32 - high_shift); \
} else \
ret.low |= val.high >> (DOUBLE_FRAC_BITS - 32 - exp); \
} \
\
/* encode negative integer using 2's complement */ \
if (with_sign && sign) { \
ret.low = ~ret.low; \
ret.high = ~ret.high; \
if (ret.low == UINT_MAX) { \
ret.low = 0; \
ret.high++; \
} else \
ret.low++; \
} \
\
double_unsigned_struct_return(ret); \
}
/* double to unsigned long long conversion */
DEFINE__AEABI_D2XLZ(d2ulz, 0)
/* double to long long conversion */
DEFINE__AEABI_D2XLZ(d2lz, 1)
/* long long to float conversion */
#define DEFINE__AEABI_XL2F(name, with_sign) \
unsigned __aeabi_ ## name(unsigned long long v) \
{ \
int s /* shift */, flb /* first lost bit */, sign = 0; \
unsigned p = 0 /* power */, ret; \
double_unsigned_struct val; \
\
/* fraction in negative float is encoded in 1's complement */ \
if (with_sign && (v & (1ULL << 63))) { \
sign = 1; \
v = ~v + 1; \
} \
val.low = v; \
val.high = v >> 32; \
/* fill fraction bits */ \
for (s = 31, p = 1 << 31; p && !(val.high & p); s--, p >>= 1); \
if (p) { \
ret = val.high & (p - 1); \
if (s < FLOAT_FRAC_BITS) { \
ret <<= FLOAT_FRAC_BITS - s; \
ret |= val.low >> (32 - (FLOAT_FRAC_BITS - s)); \
flb = (val.low >> (32 - (FLOAT_FRAC_BITS - s - 1))) & 1; \
} else { \
flb = (ret >> (s - FLOAT_FRAC_BITS - 1)) & 1; \
ret >>= s - FLOAT_FRAC_BITS; \
} \
s += 32; \
} else { \
for (s = 31, p = 1 << 31; p && !(val.low & p); s--, p >>= 1); \
if (p) { \
ret = val.low & (p - 1); \
if (s <= FLOAT_FRAC_BITS) { \
ret <<= FLOAT_FRAC_BITS - s; \
flb = 0; \
} else { \
flb = (ret >> (s - FLOAT_FRAC_BITS - 1)) & 1; \
ret >>= s - FLOAT_FRAC_BITS; \
} \
} else \
return 0; \
} \
if (flb) \
ret++; \
\
/* fill exponent bits */ \
ret |= (s + ONE_EXP(FLOAT)) << FLOAT_FRAC_BITS; \
\
/* fill sign bit */ \
ret |= sign << 31; \
\
return ret; \
}
/* unsigned long long to float conversion */
DEFINE__AEABI_XL2F(ul2f, 0)
/* long long to float conversion */
DEFINE__AEABI_XL2F(l2f, 1)
/* long long to double conversion */
#define __AEABI_XL2D(name, with_sign) \
void __aeabi_ ## name(unsigned long long v) \
{ \
int s /* shift */, high_shift, sign = 0; \
unsigned tmp, p = 0; \
double_unsigned_struct val, ret; \
\
/* fraction in negative float is encoded in 1's complement */ \
if (with_sign && (v & (1ULL << 63))) { \
sign = 1; \
v = ~v + 1; \
} \
val.low = v; \
val.high = v >> 32; \
\
/* fill fraction bits */ \
for (s = 31, p = 1 << 31; p && !(val.high & p); s--, p >>= 1); \
if (p) { \
tmp = val.high & (p - 1); \
if (s < DOUBLE_FRAC_BITS - 32) { \
high_shift = DOUBLE_FRAC_BITS - 32 - s; \
ret.high = tmp << high_shift; \
ret.high |= val.low >> (32 - high_shift); \
ret.low = val.low << high_shift; \
} else { \
high_shift = s - (DOUBLE_FRAC_BITS - 32); \
ret.high = tmp >> high_shift; \
ret.low = tmp << (32 - high_shift); \
ret.low |= val.low >> high_shift; \
if ((val.low >> (high_shift - 1)) & 1) { \
if (ret.low == UINT_MAX) { \
ret.high++; \
ret.low = 0; \
} else \
ret.low++; \
} \
} \
s += 32; \
} else { \
for (s = 31, p = 1 << 31; p && !(val.low & p); s--, p >>= 1); \
if (p) { \
tmp = val.low & (p - 1); \
if (s <= DOUBLE_FRAC_BITS - 32) { \
high_shift = DOUBLE_FRAC_BITS - 32 - s; \
ret.high = tmp << high_shift; \
ret.low = 0; \
} else { \
high_shift = s - (DOUBLE_FRAC_BITS - 32); \
ret.high = tmp >> high_shift; \
ret.low = tmp << (32 - high_shift); \
} \
} else { \
ret.high = ret.low = 0; \
double_unsigned_struct_return(ret); \
} \
} \
\
/* fill exponent bits */ \
ret.high |= (s + ONE_EXP(DOUBLE)) << (DOUBLE_FRAC_BITS - 32); \
\
/* fill sign bit */ \
ret.high |= sign << 31; \
\
double_unsigned_struct_return(ret); \
}
/* unsigned long long to double conversion */
__AEABI_XL2D(ul2d, 0)
/* long long to double conversion */
__AEABI_XL2D(l2d, 1)
/* Long long helper functions */
/* TODO: add error in case of den == 0 (see §4.3.1 and §4.3.2) */
#define define_aeabi_xdivmod_signed_type(basetype, type) \
typedef struct type { \
basetype quot; \
unsigned basetype rem; \
} type
#define define_aeabi_xdivmod_unsigned_type(basetype, type) \
typedef struct type { \
basetype quot; \
basetype rem; \
} type
#define AEABI_UXDIVMOD(name,type, rettype, typemacro) \
static inline rettype aeabi_ ## name (type num, type den) \
{ \
rettype ret; \
type quot = 0; \
\
/* Increase quotient while it is less than numerator */ \
while (num >= den) { \
type q = 1; \
\
/* Find closest power of two */ \
while ((q << 1) * den <= num && q * den <= typemacro ## _MAX / 2) \
q <<= 1; \
\
/* Compute difference between current quotient and numerator */ \
num -= q * den; \
quot += q; \
} \
ret.quot = quot; \
ret.rem = num; \
return ret; \
}
#define __AEABI_XDIVMOD(name, type, uiname, rettype, urettype, typemacro) \
void __aeabi_ ## name(type numerator, type denominator) \
{ \
unsigned type num, den; \
urettype uxdiv_ret; \
rettype ret; \
\
if (numerator >= 0) \
num = numerator; \
else \
num = 0 - numerator; \
if (denominator >= 0) \
den = denominator; \
else \
den = 0 - denominator; \
uxdiv_ret = aeabi_ ## uiname(num, den); \
/* signs differ */ \
if ((numerator & typemacro ## _MIN) != (denominator & typemacro ## _MIN)) \
ret.quot = 0 - uxdiv_ret.quot; \
else \
ret.quot = uxdiv_ret.quot; \
if (numerator < 0) \
ret.rem = 0 - uxdiv_ret.rem; \
else \
ret.rem = uxdiv_ret.rem; \
\
rettype ## _return(ret); \
}
define_aeabi_xdivmod_signed_type(long long, lldiv_t);
define_aeabi_xdivmod_unsigned_type(unsigned long long, ulldiv_t);
define_aeabi_xdivmod_signed_type(int, idiv_t);
define_aeabi_xdivmod_unsigned_type(unsigned, uidiv_t);
REGS_RETURN(lldiv_t, lldiv_t)
REGS_RETURN(ulldiv_t, ulldiv_t)
REGS_RETURN(idiv_t, idiv_t)
REGS_RETURN(uidiv_t, uidiv_t)
AEABI_UXDIVMOD(uldivmod, unsigned long long, ulldiv_t, ULLONG)
__AEABI_XDIVMOD(ldivmod, long long, uldivmod, lldiv_t, ulldiv_t, LLONG)
void __aeabi_uldivmod(unsigned long long num, unsigned long long den)
{
ulldiv_t_return(aeabi_uldivmod(num, den));
}
void __aeabi_llsl(double_unsigned_struct val, int shift)
{
double_unsigned_struct ret;
if (shift >= 32) {
val.high = val.low;
val.low = 0;
shift -= 32;
}
if (shift > 0) {
ret.low = val.low << shift;
ret.high = (val.high << shift) | (val.low >> (32 - shift));
double_unsigned_struct_return(ret);
return;
}
double_unsigned_struct_return(val);
}
#define aeabi_lsr(val, shift, fill, type) \
type ## _struct ret; \
\
if (shift >= 32) { \
val.low = val.high; \
val.high = fill; \
shift -= 32; \
} \
if (shift > 0) { \
ret.high = val.high >> shift; \
ret.low = (val.high << (32 - shift)) | (val.low >> shift); \
type ## _struct_return(ret); \
return; \
} \
type ## _struct_return(val);
void __aeabi_llsr(double_unsigned_struct val, int shift)
{
aeabi_lsr(val, shift, 0, double_unsigned);
}
void __aeabi_lasr(unsigned_int_struct val, int shift)
{
aeabi_lsr(val, shift, val.high >> 31, unsigned_int);
}
/* Integer division functions */
AEABI_UXDIVMOD(uidivmod, unsigned, uidiv_t, UINT)
int __aeabi_idiv(int numerator, int denominator)
{
unsigned num, den;
uidiv_t ret;
if (numerator >= 0)
num = numerator;
else
num = 0 - numerator;
if (denominator >= 0)
den = denominator;
else
den = 0 - denominator;
ret = aeabi_uidivmod(num, den);
if ((numerator & INT_MIN) != (denominator & INT_MIN)) /* signs differ */
ret.quot *= -1;
return ret.quot;
}
unsigned __aeabi_uidiv(unsigned num, unsigned den)
{
return aeabi_uidivmod(num, den).quot;
}
__AEABI_XDIVMOD(idivmod, int, uidivmod, idiv_t, uidiv_t, INT)
void __aeabi_uidivmod(unsigned num, unsigned den)
{
uidiv_t_return(aeabi_uidivmod(num, den));
}

58
lib/armflush.c 100644
View File

@ -0,0 +1,58 @@
/* armflush.c - flush the instruction cache
__clear_cache is used in tccrun.c, It is a built-in
intrinsic with gcc. However tcc in order to compile
itself needs this function */
#ifdef __TINYC__
/* syscall wrapper */
unsigned syscall(unsigned syscall_nr, ...);
/* arm-tcc supports only fake asm currently */
__asm__(
".global syscall\n"
"syscall:\n"
".int 0xe92d4080\n" // push {r7, lr}
".int 0xe1a07000\n" // mov r7, r0
".int 0xe1a00001\n" // mov r0, r1
".int 0xe1a01002\n" // mov r1, r2
".int 0xe1a02003\n" // mov r2, r3
".int 0xef000000\n" // svc 0x00000000
".int 0xe8bd8080\n" // pop {r7, pc}
);
/* from unistd.h: */
#if defined(__thumb__) || defined(__ARM_EABI__)
# define __NR_SYSCALL_BASE 0x0
#else
# define __NR_SYSCALL_BASE 0x900000
#endif
#define __ARM_NR_BASE (__NR_SYSCALL_BASE+0x0f0000)
#define __ARM_NR_cacheflush (__ARM_NR_BASE+2)
#else
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <stdio.h>
#endif
/* Flushing for tccrun */
void __clear_cache(void *beginning, void *end)
{
/* __ARM_NR_cacheflush is kernel private and should not be used in user space.
* However, there is no ARM asm parser in tcc so we use it for now */
#if 1
syscall(__ARM_NR_cacheflush, beginning, end, 0);
#else
__asm__ ("push {r7}\n\t"
"mov r7, #0xf0002\n\t"
"mov r2, #0\n\t"
"swi 0\n\t"
"pop {r7}\n\t"
"ret");
#endif
}

View File

@ -21,60 +21,83 @@
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#if !defined(__FreeBSD__) && !defined(__DragonFly__) && !defined(__OpenBSD__)
#if !defined(__FreeBSD__) \
&& !defined(__FreeBSD_kernel__) \
&& !defined(__DragonFly__) \
&& !defined(__OpenBSD__) \
&& !defined(__NetBSD__)
#include <malloc.h>
#endif
//#define BOUND_DEBUG
#if !defined(_WIN32)
#include <unistd.h>
#endif
/* #define BOUND_DEBUG */
#ifdef BOUND_DEBUG
#define dprintf(a...) fprintf(a)
#else
#define dprintf(a...)
#endif
/* define so that bound array is static (faster, but use memory if
bound checking not used) */
//#define BOUND_STATIC
/* #define BOUND_STATIC */
/* use malloc hooks. Currently the code cannot be reliable if no hooks */
#define CONFIG_TCC_MALLOC_HOOKS
#define HAVE_MEMALIGN
#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__dietlibc__) \
|| defined(__UCLIBC__) || defined(__OpenBSD__)
#warning Bound checking not fully supported in this environment.
#if defined(__FreeBSD__) \
|| defined(__FreeBSD_kernel__) \
|| defined(__DragonFly__) \
|| defined(__OpenBSD__) \
|| defined(__NetBSD__) \
|| defined(__dietlibc__) \
|| defined(_WIN32)
//#warning Bound checking does not support malloc (etc.) in this environment.
#undef CONFIG_TCC_MALLOC_HOOKS
#undef HAVE_MEMALIGN
#endif
#define BOUND_T1_BITS 13
#define BOUND_T2_BITS 11
#define BOUND_T3_BITS (32 - BOUND_T1_BITS - BOUND_T2_BITS)
#define BOUND_T3_BITS (sizeof(size_t)*8 - BOUND_T1_BITS - BOUND_T2_BITS)
#define BOUND_E_BITS (sizeof(size_t))
#define BOUND_T1_SIZE (1 << BOUND_T1_BITS)
#define BOUND_T2_SIZE (1 << BOUND_T2_BITS)
#define BOUND_T3_SIZE (1 << BOUND_T3_BITS)
#define BOUND_E_BITS 4
#define BOUND_T1_SIZE ((size_t)1 << BOUND_T1_BITS)
#define BOUND_T2_SIZE ((size_t)1 << BOUND_T2_BITS)
#define BOUND_T3_SIZE ((size_t)1 << BOUND_T3_BITS)
#define BOUND_T23_BITS (BOUND_T2_BITS + BOUND_T3_BITS)
#define BOUND_T23_SIZE (1 << BOUND_T23_BITS)
#define BOUND_T23_SIZE ((size_t)1 << BOUND_T23_BITS)
/* this pointer is generated when bound check is incorrect */
#define INVALID_POINTER ((void *)(-2))
/* size of an empty region */
#define EMPTY_SIZE 0xffffffff
#define EMPTY_SIZE ((size_t)(-1))
/* size of an invalid region */
#define INVALID_SIZE 0
typedef struct BoundEntry {
unsigned long start;
unsigned long size;
size_t start;
size_t size;
struct BoundEntry *next;
unsigned long is_invalid; /* true if pointers outside region are invalid */
size_t is_invalid; /* true if pointers outside region are invalid */
} BoundEntry;
/* external interface */
void __bound_init(void);
void __bound_new_region(void *p, unsigned long size);
void __bound_new_region(void *p, size_t size);
int __bound_delete_region(void *p);
#ifdef __attribute__
/* an __attribute__ macro is defined in the system headers */
#undef __attribute__
#endif
#define FASTCALL __attribute__((regparm(3)))
void *__bound_malloc(size_t size, const void *caller);
@ -93,16 +116,13 @@ static void *saved_realloc_hook;
static void *saved_memalign_hook;
#endif
/* linker definitions */
extern char _end;
/* TCC definitions */
extern char __bounds_start; /* start of static bounds table */
/* error message, just for TCC */
const char *__bound_error_msg;
/* runtime error output */
extern void rt_error(unsigned long pc, const char *fmt, ...);
extern void rt_error(size_t pc, const char *fmt, ...);
#ifdef BOUND_STATIC
static BoundEntry *__bound_t1[BOUND_T1_SIZE]; /* page table */
@ -114,12 +134,12 @@ static BoundEntry *__bound_invalid_t2; /* invalid page, for invalid pointers */
static BoundEntry *__bound_find_region(BoundEntry *e1, void *p)
{
unsigned long addr, tmp;
size_t addr, tmp;
BoundEntry *e;
e = e1;
while (e != NULL) {
addr = (unsigned long)p;
addr = (size_t)p;
addr -= e->start;
if (addr <= e->size) {
/* put region at the head */
@ -144,7 +164,8 @@ static BoundEntry *__bound_find_region(BoundEntry *e1, void *p)
static void bound_error(const char *fmt, ...)
{
__bound_error_msg = fmt;
*(int *)0 = 0; /* force a runtime error */
fprintf(stderr,"%s %s: %s\n", __FILE__, __FUNCTION__, fmt);
*(void **)0 = 0; /* force a runtime error */
}
static void bound_alloc_error(void)
@ -152,18 +173,17 @@ static void bound_alloc_error(void)
bound_error("not enough memory for bound checking code");
}
/* currently, tcc cannot compile that because we use GNUC extensions */
#if !defined(__TINYC__)
/* return '(p + offset)' for pointer arithmetic (a pointer can reach
the end of a region in this case */
void * FASTCALL __bound_ptr_add(void *p, int offset)
void * FASTCALL __bound_ptr_add(void *p, size_t offset)
{
unsigned long addr = (unsigned long)p;
size_t addr = (size_t)p;
BoundEntry *e;
#if defined(BOUND_DEBUG)
printf("add: 0x%x %d\n", (int)p, offset);
#endif
dprintf(stderr, "%s %s: %p %x\n",
__FILE__, __FUNCTION__, p, (unsigned)offset);
__bound_init();
e = __bound_t1[addr >> (BOUND_T2_BITS + BOUND_T3_BITS)];
e = (BoundEntry *)((char *)e +
@ -172,22 +192,29 @@ void * FASTCALL __bound_ptr_add(void *p, int offset)
addr -= e->start;
if (addr > e->size) {
e = __bound_find_region(e, p);
addr = (unsigned long)p - e->start;
addr = (size_t)p - e->start;
}
addr += offset;
if (addr > e->size)
if (addr >= e->size) {
fprintf(stderr,"%s %s: %p is outside of the region\n",
__FILE__, __FUNCTION__, p + offset);
return INVALID_POINTER; /* return an invalid pointer */
}
return p + offset;
}
/* return '(p + offset)' for pointer indirection (the resulting must
be strictly inside the region */
#define BOUND_PTR_INDIR(dsize) \
void * FASTCALL __bound_ptr_indir ## dsize (void *p, int offset) \
void * FASTCALL __bound_ptr_indir ## dsize (void *p, size_t offset) \
{ \
unsigned long addr = (unsigned long)p; \
size_t addr = (size_t)p; \
BoundEntry *e; \
\
dprintf(stderr, "%s %s: %p %x start\n", \
__FILE__, __FUNCTION__, p, (unsigned)offset); \
\
__bound_init(); \
e = __bound_t1[addr >> (BOUND_T2_BITS + BOUND_T3_BITS)]; \
e = (BoundEntry *)((char *)e + \
((addr >> (BOUND_T3_BITS - BOUND_E_BITS)) & \
@ -195,30 +222,47 @@ void * FASTCALL __bound_ptr_indir ## dsize (void *p, int offset) \
addr -= e->start; \
if (addr > e->size) { \
e = __bound_find_region(e, p); \
addr = (unsigned long)p - e->start; \
addr = (size_t)p - e->start; \
} \
addr += offset + dsize; \
if (addr > e->size) \
if (addr > e->size) { \
fprintf(stderr,"%s %s: %p is outside of the region\n", \
__FILE__, __FUNCTION__, p + offset); \
return INVALID_POINTER; /* return an invalid pointer */ \
} \
dprintf(stderr, "%s %s: return p+offset = %p\n", \
__FILE__, __FUNCTION__, p + offset); \
return p + offset; \
}
#ifdef __i386__
BOUND_PTR_INDIR(1)
BOUND_PTR_INDIR(2)
BOUND_PTR_INDIR(4)
BOUND_PTR_INDIR(8)
BOUND_PTR_INDIR(12)
BOUND_PTR_INDIR(16)
#if defined(__GNUC__) && (__GNUC__ >= 6)
/*
* At least gcc 6.2 complains when __builtin_frame_address is used with
* nonzero argument.
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wframe-address"
#endif
/* return the frame pointer of the caller */
#define GET_CALLER_FP(fp)\
{\
unsigned long *fp1;\
__asm__ __volatile__ ("movl %%ebp,%0" :"=g" (fp1));\
fp = fp1[0];\
fp = (size_t)__builtin_frame_address(1);\
}
#else
#error put code to extract the calling frame pointer
#endif
/* called when entering a function to add all the local regions */
void FASTCALL __bound_local_new(void *p1)
{
unsigned long addr, size, fp, *p = p1;
size_t addr, size, fp, *p = p1;
dprintf(stderr, "%s, %s start p1=%p\n", __FILE__, __FUNCTION__, p);
GET_CALLER_FP(fp);
for(;;) {
addr = p[0];
@ -229,12 +273,13 @@ void FASTCALL __bound_local_new(void *p1)
p += 2;
__bound_new_region((void *)addr, size);
}
dprintf(stderr, "%s, %s end\n", __FILE__, __FUNCTION__);
}
/* called when leaving a function to delete all the local regions */
void FASTCALL __bound_local_delete(void *p1)
{
unsigned long addr, fp, *p = p1;
size_t addr, fp, *p = p1;
GET_CALLER_FP(fp);
for(;;) {
addr = p[0];
@ -246,38 +291,14 @@ void FASTCALL __bound_local_delete(void *p1)
}
}
#else
void __bound_local_new(void *p)
{
}
void __bound_local_delete(void *p)
{
}
void *__bound_ptr_add(void *p, int offset)
{
return p + offset;
}
#define BOUND_PTR_INDIR(dsize) \
void *__bound_ptr_indir ## dsize (void *p, int offset) \
{ \
return p + offset; \
}
#if defined(__GNUC__) && (__GNUC__ >= 6)
#pragma GCC diagnostic pop
#endif
BOUND_PTR_INDIR(1)
BOUND_PTR_INDIR(2)
BOUND_PTR_INDIR(4)
BOUND_PTR_INDIR(8)
BOUND_PTR_INDIR(12)
BOUND_PTR_INDIR(16)
static BoundEntry *__bound_new_page(void)
{
BoundEntry *page;
int i;
size_t i;
page = libc_malloc(sizeof(BoundEntry) * BOUND_T2_SIZE);
if (!page)
@ -305,11 +326,11 @@ static void bound_free_entry(BoundEntry *e)
libc_free(e);
}
static inline BoundEntry *get_page(int index)
static BoundEntry *get_page(size_t index)
{
BoundEntry *page;
page = __bound_t1[index];
if (page == __bound_empty_t2 || page == __bound_invalid_t2) {
if (!page || page == __bound_empty_t2 || page == __bound_invalid_t2) {
/* create a new page if necessary */
page = __bound_new_page();
__bound_t1[index] = page;
@ -318,11 +339,11 @@ static inline BoundEntry *get_page(int index)
}
/* mark a region as being invalid (can only be used during init) */
static void mark_invalid(unsigned long addr, unsigned long size)
static void mark_invalid(size_t addr, size_t size)
{
unsigned long start, end;
size_t start, end;
BoundEntry *page;
int t1_start, t1_end, i, j, t2_start, t2_end;
size_t t1_start, t1_end, i, j, t2_start, t2_end;
start = addr;
end = addr + size;
@ -334,7 +355,7 @@ static void mark_invalid(unsigned long addr, unsigned long size)
t2_end = 1 << (BOUND_T1_BITS + BOUND_T2_BITS);
#if 0
printf("mark_invalid: start = %x %x\n", t2_start, t2_end);
dprintf(stderr, "mark_invalid: start = %x %x\n", t2_start, t2_end);
#endif
/* first we handle full pages */
@ -373,10 +394,18 @@ static void mark_invalid(unsigned long addr, unsigned long size)
void __bound_init(void)
{
int i;
size_t i;
BoundEntry *page;
unsigned long start, size;
int *p;
size_t start, size;
size_t *p;
static int inited;
if (inited)
return;
inited = 1;
dprintf(stderr, "%s, %s() start\n", __FILE__, __FUNCTION__);
/* save malloc hooks and install bound check hooks */
install_malloc_hooks();
@ -402,34 +431,71 @@ void __bound_init(void)
__bound_invalid_t2 = page;
/* invalid pointer zone */
start = (unsigned long)INVALID_POINTER & ~(BOUND_T23_SIZE - 1);
start = (size_t)INVALID_POINTER & ~(BOUND_T23_SIZE - 1);
size = BOUND_T23_SIZE;
mark_invalid(start, size);
#if !defined(__TINYC__) && defined(CONFIG_TCC_MALLOC_HOOKS)
#if defined(CONFIG_TCC_MALLOC_HOOKS)
/* malloc zone is also marked invalid. can only use that with
hooks because all libs should use the same malloc. The solution
would be to build a new malloc for tcc. */
start = (unsigned long)&_end;
* hooks because all libs should use the same malloc. The solution
* would be to build a new malloc for tcc.
*
* usually heap (= malloc zone) comes right after bss, i.e. after _end, but
* not always - either if we are running from under `tcc -b -run`, or if
* address space randomization is turned on(a), heap start will be separated
* from bss end.
*
* So sbrk(0) will be a good approximation for start_brk:
*
* - if we are a separately compiled program, __bound_init() runs early,
* and sbrk(0) should be equal or very near to start_brk(b) (in case other
* constructors malloc something), or
*
* - if we are running from under `tcc -b -run`, sbrk(0) will return
* start of heap portion which is under this program control, and not
* mark as invalid earlier allocated memory.
*
*
* (a) /proc/sys/kernel/randomize_va_space = 2, on Linux;
* usually turned on by default.
*
* (b) on Linux >= v3.3, the alternative is to read
* start_brk from /proc/self/stat
*/
start = (size_t)sbrk(0);
size = 128 * 0x100000;
mark_invalid(start, size);
#endif
/* add all static bound check values */
p = (int *)&__bounds_start;
p = (size_t *)&__bounds_start;
while (p[0] != 0) {
__bound_new_region((void *)p[0], p[1]);
p += 2;
}
dprintf(stderr, "%s, %s() end\n\n", __FILE__, __FUNCTION__);
}
void __bound_main_arg(void **p)
{
void *start = p;
while (*p++);
dprintf(stderr, "%s, %s calling __bound_new_region(%p %x)\n",
__FILE__, __FUNCTION__, start, (unsigned)((void *)p - start));
__bound_new_region(start, (void *) p - start);
}
void __bound_exit(void)
{
dprintf(stderr, "%s, %s()\n", __FILE__, __FUNCTION__);
restore_malloc_hooks();
}
static inline void add_region(BoundEntry *e,
unsigned long start, unsigned long size)
size_t start, size_t size)
{
BoundEntry *e1;
if (e->start == 0) {
@ -449,13 +515,18 @@ static inline void add_region(BoundEntry *e,
}
/* create a new region. It should not already exist in the region list */
void __bound_new_region(void *p, unsigned long size)
void __bound_new_region(void *p, size_t size)
{
unsigned long start, end;
size_t start, end;
BoundEntry *page, *e, *e2;
int t1_start, t1_end, i, t2_start, t2_end;
size_t t1_start, t1_end, i, t2_start, t2_end;
start = (unsigned long)p;
dprintf(stderr, "%s, %s(%p, %x) start\n",
__FILE__, __FUNCTION__, p, (unsigned)size);
__bound_init();
start = (size_t)p;
end = start + size;
t1_start = start >> (BOUND_T2_BITS + BOUND_T3_BITS);
t1_end = end >> (BOUND_T2_BITS + BOUND_T3_BITS);
@ -466,10 +537,7 @@ void __bound_new_region(void *p, unsigned long size)
((BOUND_T2_SIZE - 1) << BOUND_E_BITS);
t2_end = (end >> (BOUND_T3_BITS - BOUND_E_BITS)) &
((BOUND_T2_SIZE - 1) << BOUND_E_BITS);
#ifdef BOUND_DEBUG
printf("new %lx %lx %x %x %x %x\n",
start, end, t1_start, t1_end, t2_start, t2_end);
#endif
e = (BoundEntry *)((char *)page + t2_start);
add_region(e, start, size);
@ -511,16 +579,17 @@ void __bound_new_region(void *p, unsigned long size)
}
add_region(e, start, size);
}
dprintf(stderr, "%s, %s end\n", __FILE__, __FUNCTION__);
}
/* delete a region */
static inline void delete_region(BoundEntry *e,
void *p, unsigned long empty_size)
static inline void delete_region(BoundEntry *e, void *p, size_t empty_size)
{
unsigned long addr;
size_t addr;
BoundEntry *e1;
addr = (unsigned long)p;
addr = (size_t)p;
addr -= e->start;
if (addr <= e->size) {
/* region found is first one */
@ -544,7 +613,7 @@ static inline void delete_region(BoundEntry *e,
/* region not found: do nothing */
if (e == NULL)
break;
addr = (unsigned long)p - e->start;
addr = (size_t)p - e->start;
if (addr <= e->size) {
/* found: remove entry */
e1->next = e->next;
@ -559,11 +628,15 @@ static inline void delete_region(BoundEntry *e,
/* return non zero if error */
int __bound_delete_region(void *p)
{
unsigned long start, end, addr, size, empty_size;
size_t start, end, addr, size, empty_size;
BoundEntry *page, *e, *e2;
int t1_start, t1_end, t2_start, t2_end, i;
size_t t1_start, t1_end, t2_start, t2_end, i;
start = (unsigned long)p;
dprintf(stderr, "%s %s() start\n", __FILE__, __FUNCTION__);
__bound_init();
start = (size_t)p;
t1_start = start >> (BOUND_T2_BITS + BOUND_T3_BITS);
t2_start = (start >> (BOUND_T3_BITS - BOUND_E_BITS)) &
((BOUND_T2_SIZE - 1) << BOUND_E_BITS);
@ -575,7 +648,7 @@ int __bound_delete_region(void *p)
if (addr > e->size)
e = __bound_find_region(e, p);
/* test if invalid region */
if (e->size == EMPTY_SIZE || (unsigned long)p != e->start)
if (e->size == EMPTY_SIZE || (size_t)p != e->start)
return -1;
/* compute the size we put in invalid regions */
if (e->is_invalid)
@ -621,7 +694,7 @@ int __bound_delete_region(void *p)
}
}
/* last page */
page = get_page(t2_end);
page = get_page(t1_end);
e2 = (BoundEntry *)((char *)page + t2_end);
for(e=page;e<e2;e++) {
e->start = 0;
@ -629,14 +702,17 @@ int __bound_delete_region(void *p)
}
delete_region(e, p, empty_size);
}
dprintf(stderr, "%s %s() end\n", __FILE__, __FUNCTION__);
return 0;
}
/* return the size of the region starting at p, or EMPTY_SIZE if non
existant region. */
static unsigned long get_region_size(void *p)
existent region. */
static size_t get_region_size(void *p)
{
unsigned long addr = (unsigned long)p;
size_t addr = (size_t)p;
BoundEntry *e;
e = __bound_t1[addr >> (BOUND_T2_BITS + BOUND_T3_BITS)];
@ -646,13 +722,16 @@ static unsigned long get_region_size(void *p)
addr -= e->start;
if (addr > e->size)
e = __bound_find_region(e, p);
if (e->start != (unsigned long)p)
if (e->start != (size_t)p)
return EMPTY_SIZE;
return e->size;
}
/* patched memory functions */
/* force compiler to perform stores coded up to this point */
#define barrier() __asm__ __volatile__ ("": : : "memory")
static void install_malloc_hooks(void)
{
#ifdef CONFIG_TCC_MALLOC_HOOKS
@ -664,6 +743,8 @@ static void install_malloc_hooks(void)
__free_hook = __bound_free;
__realloc_hook = __bound_realloc;
__memalign_hook = __bound_memalign;
barrier();
#endif
}
@ -674,6 +755,8 @@ static void restore_malloc_hooks(void)
__free_hook = saved_free_hook;
__realloc_hook = saved_realloc_hook;
__memalign_hook = saved_memalign_hook;
barrier();
#endif
}
@ -707,6 +790,10 @@ void *__bound_malloc(size_t size, const void *caller)
if (!ptr)
return NULL;
dprintf(stderr, "%s, %s calling __bound_new_region(%p, %x)\n",
__FILE__, __FUNCTION__, ptr, (unsigned)size);
__bound_new_region(ptr, size);
return ptr;
}
@ -736,6 +823,10 @@ void *__bound_memalign(size_t size, size_t align, const void *caller)
if (!ptr)
return NULL;
dprintf(stderr, "%s, %s calling __bound_new_region(%p, %x)\n",
__FILE__, __FUNCTION__, ptr, (unsigned)size);
__bound_new_region(ptr, size);
return ptr;
}
@ -753,7 +844,7 @@ void __bound_free(void *ptr, const void *caller)
void *__bound_realloc(void *ptr, size_t size, const void *caller)
{
void *ptr1;
int old_size;
size_t old_size;
if (size == 0) {
__bound_free(ptr, caller);
@ -788,23 +879,23 @@ void *__bound_calloc(size_t nmemb, size_t size)
static void bound_dump(void)
{
BoundEntry *page, *e;
int i, j;
size_t i, j;
printf("region dump:\n");
fprintf(stderr, "region dump:\n");
for(i=0;i<BOUND_T1_SIZE;i++) {
page = __bound_t1[i];
for(j=0;j<BOUND_T2_SIZE;j++) {
e = page + j;
/* do not print invalid or empty entries */
if (e->size != EMPTY_SIZE && e->start != 0) {
printf("%08x:",
fprintf(stderr, "%08x:",
(i << (BOUND_T2_BITS + BOUND_T3_BITS)) +
(j << BOUND_T3_BITS));
do {
printf(" %08lx:%08lx", e->start, e->start + e->size);
fprintf(stderr, " %08lx:%08lx", e->start, e->start + e->size);
e = e->next;
} while (e != NULL);
printf("\n");
fprintf(stderr, "\n");
}
}
}
@ -818,19 +909,28 @@ static void __bound_check(const void *p, size_t size)
{
if (size == 0)
return;
p = __bound_ptr_add((void *)p, size);
p = __bound_ptr_add((void *)p, size - 1);
if (p == INVALID_POINTER)
bound_error("invalid pointer");
}
void *__bound_memcpy(void *dst, const void *src, size_t size)
{
void* p;
dprintf(stderr, "%s %s: start, dst=%p src=%p size=%x\n",
__FILE__, __FUNCTION__, dst, src, (unsigned)size);
__bound_check(dst, size);
__bound_check(src, size);
/* check also region overlap */
if (src >= dst && src < dst + size)
bound_error("overlapping regions in memcpy()");
return memcpy(dst, src, size);
p = memcpy(dst, src, size);
dprintf(stderr, "%s %s: end, p=%p\n", __FILE__, __FUNCTION__, p);
return p;
}
void *__bound_memmove(void *dst, const void *src, size_t size)
@ -850,7 +950,7 @@ void *__bound_memset(void *dst, int c, size_t size)
int __bound_strlen(const char *s)
{
const char *p;
int len;
size_t len;
len = 0;
for(;;) {
@ -866,8 +966,14 @@ int __bound_strlen(const char *s)
char *__bound_strcpy(char *dst, const char *src)
{
int len;
len = __bound_strlen(src);
return __bound_memcpy(dst, src, len + 1);
}
size_t len;
void *p;
dprintf(stderr, "%s %s: strcpy start, dst=%p src=%p\n",
__FILE__, __FUNCTION__, dst, src);
len = __bound_strlen(src);
p = __bound_memcpy(dst, src, len + 1);
dprintf(stderr, "%s %s: strcpy end, p = %p\n",
__FILE__, __FUNCTION__, p);
return p;
}

664
lib/lib-arm64.c 100644
View File

@ -0,0 +1,664 @@
/*
* TCC runtime library for arm64.
*
* Copyright (c) 2015 Edmund Grimley Evans
*
* Copying and distribution of this file, with or without modification,
* are permitted in any medium without royalty provided the copyright
* notice and this notice are preserved. This file is offered as-is,
* without any warranty.
*/
#ifdef __TINYC__
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef short int16_t;
typedef unsigned short uint16_t;
typedef int int32_t;
typedef unsigned uint32_t;
typedef long long int64_t;
typedef unsigned long long uint64_t;
void *memcpy(void*,void*,__SIZE_TYPE__);
#else
#include <stdint.h>
#include <string.h>
#endif
void __clear_cache(void *beg, void *end)
{
__arm64_clear_cache(beg, end);
}
typedef struct {
uint64_t x0, x1;
} u128_t;
static long double f3_zero(int sgn)
{
long double f;
u128_t x = { 0, (uint64_t)sgn << 63 };
memcpy(&f, &x, 16);
return f;
}
static long double f3_infinity(int sgn)
{
long double f;
u128_t x = { 0, (uint64_t)sgn << 63 | 0x7fff000000000000 };
memcpy(&f, &x, 16);
return f;
}
static long double f3_NaN(void)
{
long double f;
#if 0
// ARM's default NaN usually has just the top fraction bit set:
u128_t x = { 0, 0x7fff800000000000 };
#else
// GCC's library sets all fraction bits:
u128_t x = { -1, 0x7fffffffffffffff };
#endif
memcpy(&f, &x, 16);
return f;
}
static int fp3_convert_NaN(long double *f, int sgn, u128_t mnt)
{
u128_t x = { mnt.x0,
mnt.x1 | 0x7fff800000000000 | (uint64_t)sgn << 63 };
memcpy(f, &x, 16);
return 1;
}
static int fp3_detect_NaNs(long double *f,
int a_sgn, int a_exp, u128_t a,
int b_sgn, int b_exp, u128_t b)
{
// Detect signalling NaNs:
if (a_exp == 32767 && (a.x0 | a.x1 << 16) && !(a.x1 >> 47 & 1))
return fp3_convert_NaN(f, a_sgn, a);
if (b_exp == 32767 && (b.x0 | b.x1 << 16) && !(b.x1 >> 47 & 1))
return fp3_convert_NaN(f, b_sgn, b);
// Detect quiet NaNs:
if (a_exp == 32767 && (a.x0 | a.x1 << 16))
return fp3_convert_NaN(f, a_sgn, a);
if (b_exp == 32767 && (b.x0 | b.x1 << 16))
return fp3_convert_NaN(f, b_sgn, b);
return 0;
}
static void f3_unpack(int *sgn, int32_t *exp, u128_t *mnt, long double f)
{
u128_t x;
memcpy(&x, &f, 16);
*sgn = x.x1 >> 63;
*exp = x.x1 >> 48 & 32767;
x.x1 = x.x1 << 16 >> 16;
if (*exp)
x.x1 |= (uint64_t)1 << 48;
else
*exp = 1;
*mnt = x;
}
static u128_t f3_normalise(int32_t *exp, u128_t mnt)
{
int sh;
if (!(mnt.x0 | mnt.x1))
return mnt;
if (!mnt.x1) {
mnt.x1 = mnt.x0;
mnt.x0 = 0;
*exp -= 64;
}
for (sh = 32; sh; sh >>= 1) {
if (!(mnt.x1 >> (64 - sh))) {
mnt.x1 = mnt.x1 << sh | mnt.x0 >> (64 - sh);
mnt.x0 = mnt.x0 << sh;
*exp -= sh;
}
}
return mnt;
}
static u128_t f3_sticky_shift(int32_t sh, u128_t x)
{
if (sh >= 128) {
x.x0 = !!(x.x0 | x.x1);
x.x1 = 0;
return x;
}
if (sh >= 64) {
x.x0 = x.x1 | !!x.x0;
x.x1 = 0;
sh -= 64;
}
if (sh > 0) {
x.x0 = x.x0 >> sh | x.x1 << (64 - sh) | !!(x.x0 << (64 - sh));
x.x1 = x.x1 >> sh;
}
return x;
}
static long double f3_round(int sgn, int32_t exp, u128_t x)
{
long double f;
int error;
if (exp > 0) {
x = f3_sticky_shift(13, x);
}
else {
x = f3_sticky_shift(14 - exp, x);
exp = 0;
}
error = x.x0 & 3;
x.x0 = x.x0 >> 2 | x.x1 << 62;
x.x1 = x.x1 >> 2;
if (error == 3 || ((error == 2) & (x.x0 & 1))) {
if (!++x.x0) {
++x.x1;
if (x.x1 == (uint64_t)1 << 48)
exp = 1;
else if (x.x1 == (uint64_t)1 << 49) {
++exp;
x.x0 = x.x0 >> 1 | x.x1 << 63;
x.x1 = x.x1 >> 1;
}
}
}
if (exp >= 32767)
return f3_infinity(sgn);
x.x1 = x.x1 << 16 >> 16 | (uint64_t)exp << 48 | (uint64_t)sgn << 63;
memcpy(&f, &x, 16);
return f;
}
static long double f3_add(long double fa, long double fb, int neg)
{
u128_t a, b, x;
int32_t a_exp, b_exp, x_exp;
int a_sgn, b_sgn, x_sgn;
long double fx;
f3_unpack(&a_sgn, &a_exp, &a, fa);
f3_unpack(&b_sgn, &b_exp, &b, fb);
if (fp3_detect_NaNs(&fx, a_sgn, a_exp, a, b_sgn, b_exp, b))
return fx;
b_sgn ^= neg;
// Handle infinities and zeroes:
if (a_exp == 32767 && b_exp == 32767 && a_sgn != b_sgn)
return f3_NaN();
if (a_exp == 32767)
return f3_infinity(a_sgn);
if (b_exp == 32767)
return f3_infinity(b_sgn);
if (!(a.x0 | a.x1 | b.x0 | b.x1))
return f3_zero(a_sgn & b_sgn);
a.x1 = a.x1 << 3 | a.x0 >> 61;
a.x0 = a.x0 << 3;
b.x1 = b.x1 << 3 | b.x0 >> 61;
b.x0 = b.x0 << 3;
if (a_exp <= b_exp) {
a = f3_sticky_shift(b_exp - a_exp, a);
a_exp = b_exp;
}
else {
b = f3_sticky_shift(a_exp - b_exp, b);
b_exp = a_exp;
}
x_sgn = a_sgn;
x_exp = a_exp;
if (a_sgn == b_sgn) {
x.x0 = a.x0 + b.x0;
x.x1 = a.x1 + b.x1 + (x.x0 < a.x0);
}
else {
x.x0 = a.x0 - b.x0;
x.x1 = a.x1 - b.x1 - (x.x0 > a.x0);
if (x.x1 >> 63) {
x_sgn ^= 1;
x.x0 = -x.x0;
x.x1 = -x.x1 - !!x.x0;
}
}
if (!(x.x0 | x.x1))
return f3_zero(0);
x = f3_normalise(&x_exp, x);
return f3_round(x_sgn, x_exp + 12, x);
}
long double __addtf3(long double a, long double b)
{
return f3_add(a, b, 0);
}
long double __subtf3(long double a, long double b)
{
return f3_add(a, b, 1);
}
long double __multf3(long double fa, long double fb)
{
u128_t a, b, x;
int32_t a_exp, b_exp, x_exp;
int a_sgn, b_sgn, x_sgn;
long double fx;
f3_unpack(&a_sgn, &a_exp, &a, fa);
f3_unpack(&b_sgn, &b_exp, &b, fb);
if (fp3_detect_NaNs(&fx, a_sgn, a_exp, a, b_sgn, b_exp, b))
return fx;
// Handle infinities and zeroes:
if ((a_exp == 32767 && !(b.x0 | b.x1)) ||
(b_exp == 32767 && !(a.x0 | a.x1)))
return f3_NaN();
if (a_exp == 32767 || b_exp == 32767)
return f3_infinity(a_sgn ^ b_sgn);
if (!(a.x0 | a.x1) || !(b.x0 | b.x1))
return f3_zero(a_sgn ^ b_sgn);
a = f3_normalise(&a_exp, a);
b = f3_normalise(&b_exp, b);
x_sgn = a_sgn ^ b_sgn;
x_exp = a_exp + b_exp - 16352;
{
// Convert to base (1 << 30), discarding bottom 6 bits, which are zero,
// so there are (32, 30, 30, 30) bits in (a3, a2, a1, a0):
uint64_t a0 = a.x0 << 28 >> 34;
uint64_t b0 = b.x0 << 28 >> 34;
uint64_t a1 = a.x0 >> 36 | a.x1 << 62 >> 34;
uint64_t b1 = b.x0 >> 36 | b.x1 << 62 >> 34;
uint64_t a2 = a.x1 << 32 >> 34;
uint64_t b2 = b.x1 << 32 >> 34;
uint64_t a3 = a.x1 >> 32;
uint64_t b3 = b.x1 >> 32;
// Use 16 small multiplications and additions that do not overflow:
uint64_t x0 = a0 * b0;
uint64_t x1 = (x0 >> 30) + a0 * b1 + a1 * b0;
uint64_t x2 = (x1 >> 30) + a0 * b2 + a1 * b1 + a2 * b0;
uint64_t x3 = (x2 >> 30) + a0 * b3 + a1 * b2 + a2 * b1 + a3 * b0;
uint64_t x4 = (x3 >> 30) + a1 * b3 + a2 * b2 + a3 * b1;
uint64_t x5 = (x4 >> 30) + a2 * b3 + a3 * b2;
uint64_t x6 = (x5 >> 30) + a3 * b3;
// We now have (64, 30, 30, ...) bits in (x6, x5, x4, ...).
// Take the top 128 bits, setting bottom bit if any lower bits were set:
uint64_t y0 = (x5 << 34 | x4 << 34 >> 30 | x3 << 34 >> 60 |
!!(x3 << 38 | (x2 | x1 | x0) << 34));
uint64_t y1 = x6;
// Top bit may be zero. Renormalise:
if (!(y1 >> 63)) {
y1 = y1 << 1 | y0 >> 63;
y0 = y0 << 1;
--x_exp;
}
x.x0 = y0;
x.x1 = y1;
}
return f3_round(x_sgn, x_exp, x);
}
long double __divtf3(long double fa, long double fb)
{
u128_t a, b, x;
int32_t a_exp, b_exp, x_exp;
int a_sgn, b_sgn, x_sgn, i;
long double fx;
f3_unpack(&a_sgn, &a_exp, &a, fa);
f3_unpack(&b_sgn, &b_exp, &b, fb);
if (fp3_detect_NaNs(&fx, a_sgn, a_exp, a, b_sgn, b_exp, b))
return fx;
// Handle infinities and zeroes:
if ((a_exp == 32767 && b_exp == 32767) ||
(!(a.x0 | a.x1) && !(b.x0 | b.x1)))
return f3_NaN();
if (a_exp == 32767 || !(b.x0 | b.x1))
return f3_infinity(a_sgn ^ b_sgn);
if (!(a.x0 | a.x1) || b_exp == 32767)
return f3_zero(a_sgn ^ b_sgn);
a = f3_normalise(&a_exp, a);
b = f3_normalise(&b_exp, b);
x_sgn = a_sgn ^ b_sgn;
x_exp = a_exp - b_exp + 16395;
a.x0 = a.x0 >> 1 | a.x1 << 63;
a.x1 = a.x1 >> 1;
b.x0 = b.x0 >> 1 | b.x1 << 63;
b.x1 = b.x1 >> 1;
x.x0 = 0;
x.x1 = 0;
for (i = 0; i < 116; i++) {
x.x1 = x.x1 << 1 | x.x0 >> 63;
x.x0 = x.x0 << 1;
if (a.x1 > b.x1 || (a.x1 == b.x1 && a.x0 >= b.x0)) {
a.x1 = a.x1 - b.x1 - (a.x0 < b.x0);
a.x0 = a.x0 - b.x0;
x.x0 |= 1;
}
a.x1 = a.x1 << 1 | a.x0 >> 63;
a.x0 = a.x0 << 1;
}
x.x0 |= !!(a.x0 | a.x1);
x = f3_normalise(&x_exp, x);
return f3_round(x_sgn, x_exp, x);
}
long double __extendsftf2(float f)
{
long double fx;
u128_t x;
uint32_t a;
uint64_t aa;
memcpy(&a, &f, 4);
aa = a;
x.x0 = 0;
if (!(a << 1))
x.x1 = aa << 32;
else if (a << 1 >> 24 == 255)
x.x1 = (0x7fff000000000000 | aa >> 31 << 63 | aa << 41 >> 16 |
(uint64_t)!!(a << 9) << 47);
else
x.x1 = (aa >> 31 << 63 | ((aa >> 23 & 255) + 16256) << 48 |
aa << 41 >> 16);
memcpy(&fx, &x, 16);
return fx;
}
long double __extenddftf2(double f)
{
long double fx;
u128_t x;
uint64_t a;
memcpy(&a, &f, 8);
x.x0 = a << 60;
if (!(a << 1))
x.x1 = a;
else if (a << 1 >> 53 == 2047)
x.x1 = (0x7fff000000000000 | a >> 63 << 63 | a << 12 >> 16 |
(uint64_t)!!(a << 12) << 47);
else
x.x1 = a >> 63 << 63 | ((a >> 52 & 2047) + 15360) << 48 | a << 12 >> 16;
memcpy(&fx, &x, 16);
return fx;
}
float __trunctfsf2(long double f)
{
u128_t mnt;
int32_t exp;
int sgn;
uint32_t x;
float fx;
f3_unpack(&sgn, &exp, &mnt, f);
if (exp == 32767 && (mnt.x0 | mnt.x1 << 16))
x = 0x7fc00000 | (uint32_t)sgn << 31 | (mnt.x1 >> 25 & 0x007fffff);
else if (exp > 16510)
x = 0x7f800000 | (uint32_t)sgn << 31;
else if (exp < 16233)
x = (uint32_t)sgn << 31;
else {
exp -= 16257;
x = mnt.x1 >> 23 | !!(mnt.x0 | mnt.x1 << 41);
if (exp < 0) {
x = x >> -exp | !!(x << (32 + exp));
exp = 0;
}
if ((x & 3) == 3 || (x & 7) == 6)
x += 4;
x = ((x >> 2) + (exp << 23)) | (uint32_t)sgn << 31;
}
memcpy(&fx, &x, 4);
return fx;
}
double __trunctfdf2(long double f)
{
u128_t mnt;
int32_t exp;
int sgn;
uint64_t x;
double fx;
f3_unpack(&sgn, &exp, &mnt, f);
if (exp == 32767 && (mnt.x0 | mnt.x1 << 16))
x = (0x7ff8000000000000 | (uint64_t)sgn << 63 |
mnt.x1 << 16 >> 12 | mnt.x0 >> 60);
else if (exp > 17406)
x = 0x7ff0000000000000 | (uint64_t)sgn << 63;
else if (exp < 15308)
x = (uint64_t)sgn << 63;
else {
exp -= 15361;
x = mnt.x1 << 6 | mnt.x0 >> 58 | !!(mnt.x0 << 6);
if (exp < 0) {
x = x >> -exp | !!(x << (64 + exp));
exp = 0;
}
if ((x & 3) == 3 || (x & 7) == 6)
x += 4;
x = ((x >> 2) + ((uint64_t)exp << 52)) | (uint64_t)sgn << 63;
}
memcpy(&fx, &x, 8);
return fx;
}
int32_t __fixtfsi(long double fa)
{
u128_t a;
int32_t a_exp;
int a_sgn;
int32_t x;
f3_unpack(&a_sgn, &a_exp, &a, fa);
if (a_exp < 16369)
return 0;
if (a_exp > 16413)
return a_sgn ? -0x80000000 : 0x7fffffff;
x = a.x1 >> (16431 - a_exp);
return a_sgn ? -x : x;
}
int64_t __fixtfdi(long double fa)
{
u128_t a;
int32_t a_exp;
int a_sgn;
int64_t x;
f3_unpack(&a_sgn, &a_exp, &a, fa);
if (a_exp < 16383)
return 0;
if (a_exp > 16445)
return a_sgn ? -0x8000000000000000 : 0x7fffffffffffffff;
x = (a.x1 << 15 | a.x0 >> 49) >> (16446 - a_exp);
return a_sgn ? -x : x;
}
uint32_t __fixunstfsi(long double fa)
{
u128_t a;
int32_t a_exp;
int a_sgn;
f3_unpack(&a_sgn, &a_exp, &a, fa);
if (a_sgn || a_exp < 16369)
return 0;
if (a_exp > 16414)
return -1;
return a.x1 >> (16431 - a_exp);
}
uint64_t __fixunstfdi(long double fa)
{
u128_t a;
int32_t a_exp;
int a_sgn;
f3_unpack(&a_sgn, &a_exp, &a, fa);
if (a_sgn || a_exp < 16383)
return 0;
if (a_exp > 16446)
return -1;
return (a.x1 << 15 | a.x0 >> 49) >> (16446 - a_exp);
}
long double __floatsitf(int32_t a)
{
int sgn = 0;
int exp = 16414;
uint32_t mnt = a;
u128_t x = { 0, 0 };
long double f;
int i;
if (a) {
if (a < 0) {
sgn = 1;
mnt = -mnt;
}
for (i = 16; i; i >>= 1)
if (!(mnt >> (32 - i))) {
mnt <<= i;
exp -= i;
}
x.x1 = ((uint64_t)sgn << 63 | (uint64_t)exp << 48 |
(uint64_t)(mnt << 1) << 16);
}
memcpy(&f, &x, 16);
return f;
}
long double __floatditf(int64_t a)
{
int sgn = 0;
int exp = 16446;
uint64_t mnt = a;
u128_t x = { 0, 0 };
long double f;
int i;
if (a) {
if (a < 0) {
sgn = 1;
mnt = -mnt;
}
for (i = 32; i; i >>= 1)
if (!(mnt >> (64 - i))) {
mnt <<= i;
exp -= i;
}
x.x0 = mnt << 49;
x.x1 = (uint64_t)sgn << 63 | (uint64_t)exp << 48 | mnt << 1 >> 16;
}
memcpy(&f, &x, 16);
return f;
}
long double __floatunsitf(uint32_t a)
{
int exp = 16414;
uint32_t mnt = a;
u128_t x = { 0, 0 };
long double f;
int i;
if (a) {
for (i = 16; i; i >>= 1)
if (!(mnt >> (32 - i))) {
mnt <<= i;
exp -= i;
}
x.x1 = (uint64_t)exp << 48 | (uint64_t)(mnt << 1) << 16;
}
memcpy(&f, &x, 16);
return f;
}
long double __floatunditf(uint64_t a)
{
int exp = 16446;
uint64_t mnt = a;
u128_t x = { 0, 0 };
long double f;
int i;
if (a) {
for (i = 32; i; i >>= 1)
if (!(mnt >> (64 - i))) {
mnt <<= i;
exp -= i;
}
x.x0 = mnt << 49;
x.x1 = (uint64_t)exp << 48 | mnt << 1 >> 16;
}
memcpy(&f, &x, 16);
return f;
}
static int f3_cmp(long double fa, long double fb)
{
u128_t a, b;
memcpy(&a, &fa, 16);
memcpy(&b, &fb, 16);
return (!(a.x0 | a.x1 << 1 | b.x0 | b.x1 << 1) ? 0 :
((a.x1 << 1 >> 49 == 0x7fff && (a.x0 | a.x1 << 16)) ||
(b.x1 << 1 >> 49 == 0x7fff && (b.x0 | b.x1 << 16))) ? 2 :
a.x1 >> 63 != b.x1 >> 63 ? (int)(b.x1 >> 63) - (int)(a.x1 >> 63) :
a.x1 < b.x1 ? (int)(a.x1 >> 63 << 1) - 1 :
a.x1 > b.x1 ? 1 - (int)(a.x1 >> 63 << 1) :
a.x0 < b.x0 ? (int)(a.x1 >> 63 << 1) - 1 :
b.x0 < a.x0 ? 1 - (int)(a.x1 >> 63 << 1) : 0);
}
int __eqtf2(long double a, long double b)
{
return !!f3_cmp(a, b);
}
int __netf2(long double a, long double b)
{
return !!f3_cmp(a, b);
}
int __lttf2(long double a, long double b)
{
return f3_cmp(a, b);
}
int __letf2(long double a, long double b)
{
return f3_cmp(a, b);
}
int __gttf2(long double a, long double b)
{
return -f3_cmp(b, a);
}
int __getf2(long double a, long double b)
{
return -f3_cmp(b, a);
}

View File

@ -103,14 +103,14 @@ union double_long {
union float_long {
float f;
long l;
unsigned int l;
};
/* XXX: we don't support several builtin supports for now */
#ifndef __x86_64__
#if !defined __x86_64__ && !defined __arm__
/* XXX: use gcc/tcc intrinsic ? */
#if defined(__i386__)
#if defined __i386__
#define sub_ddmmss(sh, sl, ah, al, bh, bl) \
__asm__ ("subl %5,%1\n\tsbbl %3,%0" \
: "=r" ((USItype) (sh)), \
@ -162,7 +162,7 @@ static UDWtype __udivmoddi4 (UDWtype n, UDWtype d, UDWtype *rp)
n0 = nn.s.low;
n1 = nn.s.high;
#if !UDIV_NEEDS_NORMALIZATION
#if !defined(UDIV_NEEDS_NORMALIZATION)
if (d1 == 0)
{
if (d0 > n1)
@ -478,13 +478,6 @@ long long __ashldi3(long long a, int b)
#endif
}
#if defined(__i386__)
/* FPU control word for rounding to nearest mode */
unsigned short __tcc_fpu_control = 0x137f;
/* FPU control word for round to zero mode for int conversion */
unsigned short __tcc_int_fpu_control = 0x137f | 0x0c00;
#endif
#endif /* !__x86_64__ */
/* XXX: fix tcc's code generator to do this instead */
@ -557,6 +550,13 @@ unsigned long long __fixunssfdi (float a1)
return 0;
}
long long __fixsfdi (float a1)
{
long long ret; int s;
ret = __fixunssfdi((s = a1 >= 0) ? a1 : -a1);
return s ? ret : -ret;
}
unsigned long long __fixunsdfdi (double a1)
{
register union double_long dl1;
@ -582,6 +582,14 @@ unsigned long long __fixunsdfdi (double a1)
return 0;
}
long long __fixdfdi (double a1)
{
long long ret; int s;
ret = __fixunsdfdi((s = a1 >= 0) ? a1 : -a1);
return s ? ret : -ret;
}
#ifndef __arm__
unsigned long long __fixunsxfdi (long double a1)
{
register union ldouble_long dl1;
@ -605,3 +613,10 @@ unsigned long long __fixunsxfdi (long double a1)
return 0;
}
long long __fixxfdi (long double a1)
{
long long ret; int s;
ret = __fixunsxfdi((s = a1 >= 0) ? a1 : -a1);
return s ? ret : -ret;
}
#endif /* !ARM */

65
lib/va_list.c 100644
View File

@ -0,0 +1,65 @@
/* va_list.c - tinycc support for va_list on X86_64 */
#if defined __x86_64__
/* Avoid include files, they may not be available when cross compiling */
extern void *memset(void *s, int c, __SIZE_TYPE__ n);
extern void abort(void);
/* This should be in sync with our include/stdarg.h */
enum __va_arg_type {
__va_gen_reg, __va_float_reg, __va_stack
};
/* GCC compatible definition of va_list. */
typedef struct {
unsigned int gp_offset;
unsigned int fp_offset;
union {
unsigned int overflow_offset;
char *overflow_arg_area;
};
char *reg_save_area;
} __va_list_struct;
void __va_start(__va_list_struct *ap, void *fp)
{
memset(ap, 0, sizeof(__va_list_struct));
*ap = *(__va_list_struct *)((char *)fp - 16);
ap->overflow_arg_area = (char *)fp + ap->overflow_offset;
ap->reg_save_area = (char *)fp - 176 - 16;
}
void *__va_arg(__va_list_struct *ap,
enum __va_arg_type arg_type,
int size, int align)
{
size = (size + 7) & ~7;
align = (align + 7) & ~7;
switch (arg_type) {
case __va_gen_reg:
if (ap->gp_offset + size <= 48) {
ap->gp_offset += size;
return ap->reg_save_area + ap->gp_offset - size;
}
goto use_overflow_area;
case __va_float_reg:
if (ap->fp_offset < 128 + 48) {
ap->fp_offset += 16;
return ap->reg_save_area + ap->fp_offset - 16;
}
size = 8;
goto use_overflow_area;
case __va_stack:
use_overflow_area:
ap->overflow_arg_area += size;
ap->overflow_arg_area = (char*)((long long)(ap->overflow_arg_area + align - 1) & -align);
return ap->overflow_arg_area - size;
default: /* should never happen */
abort();
}
}
#endif

3378
libtcc.c

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,8 @@
#ifndef LIBTCC_H
#define LIBTCC_H
#ifdef LIBTCC_AS_DLL
#define LIBTCCAPI __declspec(dllexport)
#else
#define LIBTCCAPI
#ifndef LIBTCCAPI
# define LIBTCCAPI
#endif
#ifdef __cplusplus
@ -21,15 +19,15 @@ LIBTCCAPI TCCState *tcc_new(void);
/* free a TCC compilation context */
LIBTCCAPI void tcc_delete(TCCState *s);
/* add debug information in the generated code */
LIBTCCAPI void tcc_enable_debug(TCCState *s);
/* set CONFIG_TCCDIR at runtime */
LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path);
/* set error/warning display callback */
LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
void (*error_func)(void *opaque, const char *msg));
void (*error_func)(void *opaque, const char *msg));
/* set/reset a warning */
LIBTCCAPI int tcc_set_warning(TCCState *s, const char *warning_name, int value);
/* set options as from command line (multiple supported) */
LIBTCCAPI void tcc_set_options(TCCState *s, const char *str);
/*****************************/
/* preprocessor */
@ -49,29 +47,22 @@ LIBTCCAPI void tcc_undefine_symbol(TCCState *s, const char *sym);
/*****************************/
/* compiling */
/* add a file (either a C file, dll, an object, a library or an ld
script). Return -1 if error. */
/* add a file (C file, dll, object, library, ld script). Return -1 if error. */
LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename);
/* compile a string containing a C source. Return non zero if
error. */
/* compile a string containing a C source. Return -1 if error. */
LIBTCCAPI int tcc_compile_string(TCCState *s, const char *buf);
/*****************************/
/* linking commands */
/* set output type. MUST BE CALLED before any compilation */
#define TCC_OUTPUT_MEMORY 0 /* output will be ran in memory (no
output file) (default) */
#define TCC_OUTPUT_EXE 1 /* executable file */
#define TCC_OUTPUT_DLL 2 /* dynamic library */
#define TCC_OUTPUT_OBJ 3 /* object file */
#define TCC_OUTPUT_PREPROCESS 4 /* preprocessed file (used internally) */
LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type);
#define TCC_OUTPUT_FORMAT_ELF 0 /* default output format: ELF */
#define TCC_OUTPUT_FORMAT_BINARY 1 /* binary image output */
#define TCC_OUTPUT_FORMAT_COFF 2 /* COFF */
#define TCC_OUTPUT_MEMORY 1 /* output will be run in memory (default) */
#define TCC_OUTPUT_EXE 2 /* executable file */
#define TCC_OUTPUT_DLL 3 /* dynamic library */
#define TCC_OUTPUT_OBJ 4 /* object file */
#define TCC_OUTPUT_PREPROCESS 5 /* only preprocess (used internally) */
/* equivalent to -Lpath option */
LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname);
@ -80,7 +71,7 @@ LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname);
LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname);
/* add a symbol to the compiled program */
LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, void *val);
LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val);
/* output an executable, library or object file. DO NOT call
tcc_relocate() before. */
@ -90,17 +81,18 @@ LIBTCCAPI int tcc_output_file(TCCState *s, const char *filename);
tcc_relocate() before. */
LIBTCCAPI int tcc_run(TCCState *s, int argc, char **argv);
/* copy code into memory passed in by the caller and do all relocations
(needed before using tcc_get_symbol()).
returns -1 on error and required size if ptr is NULL */
/* do all relocations (needed before using tcc_get_symbol()) */
LIBTCCAPI int tcc_relocate(TCCState *s1, void *ptr);
/* possible values for 'ptr':
- TCC_RELOCATE_AUTO : Allocate and manage memory internally
- NULL : return required memory size for the step below
- memory address : copy code to memory passed by the caller
returns -1 if error. */
#define TCC_RELOCATE_AUTO (void*)1
/* return symbol value or NULL if not found */
LIBTCCAPI void *tcc_get_symbol(TCCState *s, const char *name);
/* set CONFIG_TCCDIR at runtime */
LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path);
#ifdef __cplusplus
}
#endif

View File

@ -2,6 +2,10 @@
@c %**start of header
@setfilename tcc-doc.info
@settitle Tiny C Compiler Reference Documentation
@dircategory Software development
@direntry
* TCC: (tcc-doc). The Tiny C Compiler.
@end direntry
@c %**end of header
@include config.texi
@ -64,7 +68,7 @@ ports for the ARM (@code{arm-tcc}) and the TMS320C67xx targets
(@code{c67-tcc}). More information about the ARM port is available at
@url{http://lists.gnu.org/archive/html/tinycc-devel/2003-10/msg00044.html}.
For usage on Windows, see also tcc-win32.txt.
For usage on Windows, see also @url{tcc-win32.txt}.
@node Invoke
@chapter Command line invocation
@ -153,47 +157,34 @@ General Options:
@c man begin OPTIONS
@table @option
@item -v
Display current TCC version, increase verbosity.
@item -print-search-dirs
Print the name of the configured installation directory and a list
of program and library directories tcc will search.
@item -c
Generate an object file (@option{-o} option must also be given).
Generate an object file.
@item -o outfile
Put object file, executable, or dll into output file @file{outfile}.
@item -Bdir
Set the path where the tcc internal libraries can be found (default is
@file{PREFIX/lib/tcc}).
@item -bench
Output compilation statistics.
@item -run source [args...]
Compile file @var{source} and run it with the command line arguments
@var{args}. In order to be able to give more than one argument to a
script, several TCC options can be given @emph{after} the
@option{-run} option, separated by spaces. Example:
@option{-run} option, separated by spaces:
@example
tcc "-run -L/usr/X11R6/lib -lX11" ex4.c
@end example
In a script, it gives the following header:
@example
#!/usr/local/bin/tcc -run -L/usr/X11R6/lib -lX11
#include <stdlib.h>
int main(int argc, char **argv)
@{
...
@}
@end example
@item -v
Display TCC version.
@item -vv
Show included files. As sole argument, print search dirs. -vvv shows tries too.
@item -bench
Display compilation statistics.
@end table
Preprocessor options:
@ -215,11 +206,15 @@ also be defined: @option{-DF(a)=a+1}
@item -Usym
Undefine preprocessor symbol @samp{sym}.
@item -E
Preprocess only, to stdout or file (with -o).
@end table
Compilation flags:
Note: each of the following warning options has a negative form beginning with
Note: each of the following options has a negative form beginning with
@option{-fno-}.
@table @option
@ -235,6 +230,14 @@ Do not generate common symbols for uninitialized data.
@item -fleading-underscore
Add a leading underscore at the beginning of each C symbol.
@item -fms-extensions
Allow a MS C compiler extensions to the language. Currently this
assumes a nested named structure declaration without an identifier
behaves like an unnamed one.
@item -fdollars-in-identifiers
Allow dollar signs in identifiers
@end table
Warning options:
@ -278,28 +281,37 @@ default library paths are @file{/usr/local/lib}, @file{/usr/lib} and @file{/lib}
@item -lxxx
Link your program with dynamic library libxxx.so or static library
libxxx.a. The library is searched in the paths specified by the
@option{-L} option.
@option{-L} option and @env{LIBRARY_PATH} variable.
@item -Bdir
Set the path where the tcc internal libraries (and include files) can be
found (default is @file{PREFIX/lib/tcc}).
@item -shared
Generate a shared library instead of an executable (@option{-o} option
must also be given).
Generate a shared library instead of an executable.
@item -soname name
set name for shared library to be used at runtime
@item -static
Generate a statically linked executable (default is a shared linked
executable) (@option{-o} option must also be given).
executable).
@item -rdynamic
Export global symbols to the dynamic linker. It is useful when a library
opened with @code{dlopen()} needs to access executable symbols.
@item -r
Generate an object file combining all input files (@option{-o} option must
also be given).
Generate an object file combining all input files.
@item -Wl,-Ttext,address
Set the start of the .text section to @var{address}.
@item -Wl,-rpath=path
Put custom search path for dynamic libraries into executable.
@item -Wl,--oformat,fmt
@item -Wl,--enable-new-dtags
When putting a custom search path for dynamic libraries into the executable,
create the new ELF dynamic tag DT_RUNPATH instead of the old legacy DT_RPATH.
@item -Wl,--oformat=fmt
Use @var{fmt} as output format. The supported output formats are:
@table @code
@item elf32-i386
@ -310,6 +322,18 @@ Binary image (only for executable output)
COFF output format (only for executable output for TMS320C67xx target)
@end table
@item -Wl,-subsystem=console/gui/wince/...
Set type for PE (Windows) executables.
@item -Wl,-[Ttext=# | section-alignment=# | file-alignment=# | image-base=# | stack=#]
Modify executable layout.
@item -Wl,-Bsymbolic
Set DT_SYMBOLIC tag.
@item -Wl,-(no-)whole-archive
Turn on/off linking of all objects in archives.
@end table
Debugger options:
@ -326,22 +350,79 @@ Generate additional support code to check
memory allocations and array/pointer bounds. @option{-g} is implied. Note
that the generated code is slower and bigger in this case.
Note: @option{-b} is only available on i386 when using libtcc for the moment.
@item -bt N
Display N callers in stack traces. This is useful with @option{-g} or
@option{-b}.
@end table
Misc options:
@table @option
@item -MD
Generate makefile fragment with dependencies.
@item -MF depfile
Use @file{depfile} as output for -MD.
@item -print-search-dirs
Print the configured installation directory and a list of library
and include directories tcc will search.
@item -dumpversion
Print version.
@end table
Target specific options:
@table @option
@item -mms-bitfields
Use an algorithm for bitfield alignment consistent with MSVC. Default is
gcc's algorithm.
@item -mfloat-abi (ARM only)
Select the float ABI. Possible values: @code{softfp} and @code{hard}
@item -mno-sse
Do not use sse registers on x86_64
@item -m32, -m64
Pass command line to the i386/x86_64 cross compiler.
@end table
Note: GCC options @option{-Ox}, @option{-fx} and @option{-mx} are
ignored.
@c man end
@c man begin ENVIRONMENT
Environment variables that affect how tcc operates.
@table @option
@item CPATH
@item C_INCLUDE_PATH
A colon-separated list of directories searched for include files,
directories given with @option{-I} are searched first.
@item LIBRARY_PATH
A colon-separated list of directories searched for libraries for the
@option{-l} option, directories given with @option{-L} are searched first.
@end table
@c man end
@ignore
@setfilename tcc
@settitle Tiny C Compiler
@c man begin SEEALSO
cpp(1),
gcc(1)
@c man end
@ -363,13 +444,14 @@ and floating point numbers (@code{long double}, @code{double}, and
@section ISOC99 extensions
TCC implements many features of the new C standard: ISO C99. Currently
missing items are: complex and imaginary numbers and variable length
arrays.
missing items are: complex and imaginary numbers.
Currently implemented ISOC99 features:
@itemize
@item variable length arrays.
@item 64 bit @code{long long} types are fully supported.
@item The boolean type @code{_Bool} is supported.
@ -571,8 +653,7 @@ are supported.
@itemize
@item @code{__TINYC__} is a predefined macro to @code{1} to
indicate that you use TCC.
@item @code{__TINYC__} is a predefined macro to indicate that you use TCC.
@item @code{#!} at the start of a line is ignored to allow scripting.
@ -588,7 +669,7 @@ indicate that you use TCC.
Since version 0.9.16, TinyCC integrates its own assembler. TinyCC
assembler supports a gas-like syntax (GNU assembler). You can
desactivate assembler support if you want a smaller TinyCC executable
deactivate assembler support if you want a smaller TinyCC executable
(the C compiler does not rely on the assembler).
TinyCC Assembler is used to handle files with @file{.S} (C
@ -677,7 +758,7 @@ They can be defined several times in the same source. Use 'b'
@cindex asciz directive
@cindex ascii directive
All directives are preceeded by a '.'. The following directives are
All directives are preceded by a '.'. The following directives are
supported:
@itemize
@ -896,7 +977,7 @@ reverse order, a first pass is done to reverse the argument order.
@section Types
The types are stored in a single 'int' variable. It was choosen in the
The types are stored in a single 'int' variable. It was chosen in the
first stages of development when tcc was much simpler. Now, it may not
be the best solution.
@ -919,9 +1000,13 @@ be the best solution.
#define VT_BTYPE 0x000f /* mask for basic type */
#define VT_UNSIGNED 0x0010 /* unsigned type */
#define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
#define VT_VLA 0x20000 /* VLA type (also has VT_PTR and VT_ARRAY) */
#define VT_BITFIELD 0x0040 /* bitfield modifier */
#define VT_CONSTANT 0x0800 /* const modifier */
#define VT_VOLATILE 0x1000 /* volatile modifier */
#define VT_DEFSIGN 0x2000 /* signed type */
#define VT_STRUCT_SHIFT 16 /* structure/enum name shift (16 bits left) */
#define VT_STRUCT_SHIFT 18 /* structure/enum name shift (14 bits left) */
@end example
When a reference to another type is needed (for pointers, functions and
@ -932,7 +1017,8 @@ The @code{VT_UNSIGNED} flag can be set for chars, shorts, ints and long
longs.
Arrays are considered as pointers @code{VT_PTR} with the flag
@code{VT_ARRAY} set.
@code{VT_ARRAY} set. Variable length arrays are considered as special
arrays and have flag @code{VT_VLA} set instead of @code{VT_ARRAY}.
The @code{VT_BITFIELD} flag can be set for chars, shorts, ints and long
longs. If it is set, then the bitfield position is stored from bits
@ -948,6 +1034,10 @@ integer:
#define VT_EXTERN 0x00000080 /* extern definition */
#define VT_STATIC 0x00000100 /* static variable */
#define VT_TYPEDEF 0x00000200 /* typedef definition */
#define VT_INLINE 0x00000400 /* inline definition */
#define VT_IMPORT 0x00004000 /* win32: extern data imported from dll */
#define VT_EXPORT 0x00008000 /* win32: data exported from dll */
#define VT_WEAK 0x00010000 /* win32: data exported from dll */
@end example
@section Symbols
@ -956,10 +1046,13 @@ All symbols are stored in hashed symbol stacks. Each symbol stack
contains @code{Sym} structures.
@code{Sym.v} contains the symbol name (remember
an idenfier is also a token, so a string is never necessary to store
an identifier is also a token, so a string is never necessary to store
it). @code{Sym.t} gives the type of the symbol. @code{Sym.r} is usually
the register in which the corresponding variable is stored. @code{Sym.c} is
usually a constant associated to the symbol.
usually a constant associated to the symbol like its address for normal
symbols, and the number of entries for symbols representing arrays.
Variable length array types use @code{Sym.c} as a location on the stack
which holds the runtime sizeof for the type.
Four main symbol stacks are defined:
@ -996,7 +1089,7 @@ global stack.
@section Sections
The generated code and datas are written in sections. The structure
The generated code and data are written in sections. The structure
@code{Section} contains all the necessary information for a given
section. @code{new_section()} creates a new section. ELF file semantics
is assumed for each section.
@ -1021,7 +1114,7 @@ are used when bound checking is activated
@item stab_section
@itemx stabstr_section
are used when debugging is actived to store debug information
are used when debugging is active to store debug information
@item symtab_section
@itemx strtab_section
@ -1121,8 +1214,10 @@ if the lvalue has an integer type, then these flags give its real
type. The type alone is not enough in case of cast optimisations.
@item VT_LLOCAL
is a saved lvalue on the stack. @code{VT_LLOCAL} should be eliminated
ASAP because its semantics are rather complicated.
is a saved lvalue on the stack. @code{VT_LVAL} must also be set with
@code{VT_LLOCAL}. @code{VT_LLOCAL} can arise when a @code{VT_LVAL} in
a register has to be saved to the stack, or it can come from an
architecture-specific calling convention.
@item VT_MUSTCAST
indicates that a cast to the value type must be performed if the value
@ -1181,13 +1276,13 @@ should generate a function prolog/epilog.
@item gen_opi(op)
must generate the binary integer operation @var{op} on the two top
entries of the stack which are guaranted to contain integer types.
entries of the stack which are guaranteed to contain integer types.
The result value should be put on the stack.
@item gen_opf(op)
same as @code{gen_opi()} for floating point operations. The two top
entries of the stack are guaranted to contain floating point values of
entries of the stack are guaranteed to contain floating point values of
same types.
@item gen_cvt_itof()

854
tcc.c
View File

@ -18,580 +18,354 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef TCC_USE_LIBTCC
#include "tcc.h"
#else
#include "libtcc.c"
#if ONE_SOURCE
# include "libtcc.c"
#endif
#include "tcctools.c"
void help(void)
{
printf("tcc version " TCC_VERSION " - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
"usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
" [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
" [-static] [infile1 infile2...] [-run infile args...]\n"
"\n"
"General options:\n"
" -v display current version, increase verbosity\n"
" -c compile only - generate an object file\n"
" -o outfile set output filename\n"
" -Bdir set tcc internal library path\n"
" -bench output compilation statistics\n"
" -run run compiled source\n"
" -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
" -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
" -w disable all warnings\n"
"Preprocessor options:\n"
" -E preprocess only\n"
" -Idir add include path 'dir'\n"
" -Dsym[=val] define 'sym' with value 'val'\n"
" -Usym undefine 'sym'\n"
"Linker options:\n"
" -Ldir add library path 'dir'\n"
" -llib link with dynamic or static library 'lib'\n"
" -shared generate a shared library\n"
" -soname set name for shared library to be used at runtime\n"
" -static static linking\n"
" -rdynamic export all global symbols to dynamic linker\n"
" -r generate (relocatable) object file\n"
"Debugger options:\n"
" -g generate runtime debug info\n"
static const char help[] =
"Tiny C Compiler "TCC_VERSION" - Copyright (C) 2001-2006 Fabrice Bellard\n"
"Usage: tcc [options...] [-o outfile] [-c] infile(s)...\n"
" tcc [options...] -run infile [arguments...]\n"
"General options:\n"
" -c compile only - generate an object file\n"
" -o outfile set output filename\n"
" -run run compiled source\n"
" -fflag set or reset (with 'no-' prefix) 'flag' (see tcc -hh)\n"
" -Wwarning set or reset (with 'no-' prefix) 'warning' (see tcc -hh)\n"
" -w disable all warnings\n"
" -v -vv show version, show search paths or loaded files\n"
" -h -hh show this, show more help\n"
" -bench show compilation statistics\n"
" - use stdin pipe as infile\n"
" @listfile read arguments from listfile\n"
"Preprocessor options:\n"
" -Idir add include path 'dir'\n"
" -Dsym[=val] define 'sym' with value 'val'\n"
" -Usym undefine 'sym'\n"
" -E preprocess only\n"
"Linker options:\n"
" -Ldir add library path 'dir'\n"
" -llib link with dynamic or static library 'lib'\n"
" -r generate (relocatable) object file\n"
" -shared generate a shared library/dll\n"
" -rdynamic export all global symbols to dynamic linker\n"
" -soname set name for shared library to be used at runtime\n"
" -Wl,-opt[=val] set linker option (see tcc -hh)\n"
"Debugger options:\n"
" -g generate runtime debug info\n"
#ifdef CONFIG_TCC_BCHECK
" -b compile with built-in memory and bounds checker (implies -g)\n"
" -b compile with built-in memory and bounds checker (implies -g)\n"
#endif
#ifdef CONFIG_TCC_BACKTRACE
" -bt N show N callers in stack traces\n"
" -bt N show N callers in stack traces\n"
#endif
);
"Misc. options:\n"
" -x[c|a|n] specify type of the next infile\n"
" -nostdinc do not use standard system include paths\n"
" -nostdlib do not link with standard crt and libraries\n"
" -Bdir set tcc's private include/library dir\n"
" -MD generate dependency file for make\n"
" -MF file specify dependency file name\n"
" -m32/64 defer to i386/x86_64 cross compiler\n"
"Tools:\n"
" create library : tcc -ar [rcsv] lib.a files\n"
#ifdef TCC_TARGET_PE
" create def file : tcc -impdef lib.dll [-v] [-o lib.def]\n"
#endif
;
static const char help2[] =
"Tiny C Compiler "TCC_VERSION" - More Options\n"
"Special options:\n"
" -P -P1 with -E: no/alternative #line output\n"
" -dD -dM with -E: output #define directives\n"
" -pthread same as -D_REENTRANT and -lpthread\n"
" -On same as -D__OPTIMIZE__ for n > 0\n"
" -Wp,-opt same as -opt\n"
" -include file include 'file' above each input file\n"
" -isystem dir add 'dir' to system include path\n"
" -static link to static libraries (not recommended)\n"
" -dumpversion print version\n"
" -print-search-dirs print search paths\n"
" -dt with -run/-E: auto-define 'test_...' macros\n"
"Ignored options:\n"
" --param -pedantic -pipe -s -std -traditional\n"
"-W... warnings:\n"
" all turn on some (*) warnings\n"
" error stop after first warning\n"
" unsupported warn about ignored options, pragmas, etc.\n"
" write-strings strings are const\n"
" implicit-function-declaration warn for missing prototype (*)\n"
"-f[no-]... flags:\n"
" unsigned-char default char is unsigned\n"
" signed-char default char is signed\n"
" common use common section instead of bss\n"
" leading-underscore decorate extern symbols\n"
" ms-extensions allow anonymous struct in struct\n"
" dollars-in-identifiers allow '$' in C symbols\n"
"-m... target specific options:\n"
" ms-bitfields use MSVC bitfield layout\n"
#ifdef TCC_TARGET_ARM
" float-abi hard/softfp on arm\n"
#endif
#ifdef TCC_TARGET_X86_64
" no-sse disable floats on x86_64\n"
#endif
"-Wl,... linker options:\n"
" -nostdlib do not link with standard crt/libs\n"
" -[no-]whole-archive load lib(s) fully/only as needed\n"
" -export-all-symbols same as -rdynamic\n"
" -image-base= -Ttext= set base address of executable\n"
" -section-alignment= set section alignment in executable\n"
#ifdef TCC_TARGET_PE
" -file-alignment= set PE file alignment\n"
" -stack= set PE stack reserve\n"
" -large-address-aware set related PE option\n"
" -subsystem=[console/windows] set PE subsystem\n"
" -oformat=[pe-* binary] set executable output format\n"
"Predefined macros:\n"
" tcc -E -dM - < nul\n"
#else
" -rpath= set dynamic library search path\n"
" -enable-new-dtags set DT_RUNPATH instead of DT_RPATH\n"
" -soname= set DT_SONAME elf tag\n"
" -Bsymbolic set DT_SYMBOLIC elf tag\n"
" -oformat=[elf32/64-* binary] set executable output format\n"
" -init= -fini= -as-needed -O (ignored)\n"
"Predefined macros:\n"
" tcc -E -dM - < /dev/null\n"
#endif
"See also the manual for more details.\n"
;
static const char version[] =
"tcc version "TCC_VERSION" ("
#ifdef TCC_TARGET_I386
"i386"
#elif defined TCC_TARGET_X86_64
"x86_64"
#elif defined TCC_TARGET_C67
"C67"
#elif defined TCC_TARGET_ARM
"ARM"
#elif defined TCC_TARGET_ARM64
"AArch64"
#endif
#ifdef TCC_ARM_HARDFLOAT
" Hard Float"
#endif
#ifdef TCC_TARGET_PE
" Windows"
#elif defined(TCC_TARGET_MACHO)
" Darwin"
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
" FreeBSD"
#else
" Linux"
#endif
")\n"
;
static void print_dirs(const char *msg, char **paths, int nb_paths)
{
int i;
printf("%s:\n%s", msg, nb_paths ? "" : " -\n");
for(i = 0; i < nb_paths; i++)
printf(" %s\n", paths[i]);
}
static char **files;
static int nb_files, nb_libraries;
static int multiple_files;
static int print_search_dirs;
static int output_type;
static int reloc_output;
static const char *outfile;
static int do_bench = 0;
#define TCC_OPTION_HAS_ARG 0x0001
#define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
typedef struct TCCOption {
const char *name;
uint16_t index;
uint16_t flags;
} TCCOption;
enum {
TCC_OPTION_HELP,
TCC_OPTION_I,
TCC_OPTION_D,
TCC_OPTION_U,
TCC_OPTION_L,
TCC_OPTION_B,
TCC_OPTION_l,
TCC_OPTION_bench,
TCC_OPTION_bt,
TCC_OPTION_b,
TCC_OPTION_g,
TCC_OPTION_c,
TCC_OPTION_static,
TCC_OPTION_shared,
TCC_OPTION_soname,
TCC_OPTION_o,
TCC_OPTION_r,
TCC_OPTION_Wl,
TCC_OPTION_W,
TCC_OPTION_O,
TCC_OPTION_m,
TCC_OPTION_f,
TCC_OPTION_nostdinc,
TCC_OPTION_nostdlib,
TCC_OPTION_print_search_dirs,
TCC_OPTION_rdynamic,
TCC_OPTION_run,
TCC_OPTION_v,
TCC_OPTION_w,
TCC_OPTION_pipe,
TCC_OPTION_E,
TCC_OPTION_x,
};
static const TCCOption tcc_options[] = {
{ "h", TCC_OPTION_HELP, 0 },
{ "?", TCC_OPTION_HELP, 0 },
{ "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
{ "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
{ "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
{ "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
{ "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
{ "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
{ "bench", TCC_OPTION_bench, 0 },
{ "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
#ifdef CONFIG_TCC_BCHECK
{ "b", TCC_OPTION_b, 0 },
static void print_search_dirs(TCCState *s)
{
printf("install: %s\n", s->tcc_lib_path);
/* print_dirs("programs", NULL, 0); */
print_dirs("include", s->sysinclude_paths, s->nb_sysinclude_paths);
print_dirs("libraries", s->library_paths, s->nb_library_paths);
printf("libtcc1:\n %s/"TCC_LIBTCC1"\n", s->tcc_lib_path);
#ifndef TCC_TARGET_PE
print_dirs("crt", s->crt_paths, s->nb_crt_paths);
printf("elfinterp:\n %s\n", DEFAULT_ELFINTERP(s));
#endif
{ "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
{ "c", TCC_OPTION_c, 0 },
{ "static", TCC_OPTION_static, 0 },
{ "shared", TCC_OPTION_shared, 0 },
{ "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
{ "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
{ "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
{ "rdynamic", TCC_OPTION_rdynamic, 0 },
{ "r", TCC_OPTION_r, 0 },
{ "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
{ "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
{ "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
{ "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
{ "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
{ "nostdinc", TCC_OPTION_nostdinc, 0 },
{ "nostdlib", TCC_OPTION_nostdlib, 0 },
{ "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
{ "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
{ "w", TCC_OPTION_w, 0 },
{ "pipe", TCC_OPTION_pipe, 0},
{ "E", TCC_OPTION_E, 0},
{ "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
{ NULL },
};
}
static int64_t getclock_us(void)
static void set_environment(TCCState *s)
{
char * path;
path = getenv("C_INCLUDE_PATH");
if(path != NULL) {
tcc_add_sysinclude_path(s, path);
}
path = getenv("CPATH");
if(path != NULL) {
tcc_add_include_path(s, path);
}
path = getenv("LIBRARY_PATH");
if(path != NULL) {
tcc_add_library_path(s, path);
}
}
static char *default_outputfile(TCCState *s, const char *first_file)
{
char buf[1024];
char *ext;
const char *name = "a";
if (first_file && strcmp(first_file, "-"))
name = tcc_basename(first_file);
snprintf(buf, sizeof(buf), "%s", name);
ext = tcc_fileextension(buf);
#ifdef TCC_TARGET_PE
if (s->output_type == TCC_OUTPUT_DLL)
strcpy(ext, ".dll");
else
if (s->output_type == TCC_OUTPUT_EXE)
strcpy(ext, ".exe");
else
#endif
if (s->output_type == TCC_OUTPUT_OBJ && !s->option_r && *ext)
strcpy(ext, ".o");
else
strcpy(buf, "a.out");
return tcc_strdup(buf);
}
static unsigned getclock_ms(void)
{
#ifdef _WIN32
struct _timeb tb;
_ftime(&tb);
return (tb.time * 1000LL + tb.millitm) * 1000LL;
return GetTickCount();
#else
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000000LL + tv.tv_usec;
return tv.tv_sec*1000 + (tv.tv_usec+500)/1000;
#endif
}
static int strstart(const char *str, const char *val, const char **ptr)
int main(int argc0, char **argv0)
{
const char *p, *q;
p = str;
q = val;
while (*q != '\0') {
if (*p != *q)
return 0;
p++;
q++;
}
if (ptr)
*ptr = p;
return 1;
}
/* convert 'str' into an array of space separated strings */
static int expand_args(char ***pargv, const char *str)
{
const char *s1;
char **argv, *arg;
int argc, len;
argc = 0;
argv = NULL;
for(;;) {
while (is_space(*str))
str++;
if (*str == '\0')
break;
s1 = str;
while (*str != '\0' && !is_space(*str))
str++;
len = str - s1;
arg = tcc_malloc(len + 1);
memcpy(arg, s1, len);
arg[len] = '\0';
dynarray_add((void ***)&argv, &argc, arg);
}
*pargv = argv;
return argc;
}
int parse_args(TCCState *s, int argc, char **argv)
{
int optind;
const TCCOption *popt;
const char *optarg, *p1, *r1;
char *r;
optind = 0;
while (optind < argc) {
r = argv[optind++];
if (r[0] != '-' || r[1] == '\0') {
/* add a new file */
dynarray_add((void ***)&files, &nb_files, r);
if (!multiple_files) {
optind--;
/* argv[0] will be this file */
break;
}
} else {
/* find option in table (match only the first chars */
popt = tcc_options;
for(;;) {
p1 = popt->name;
if (p1 == NULL)
error("invalid option -- '%s'", r);
r1 = r + 1;
for(;;) {
if (*p1 == '\0')
goto option_found;
if (*r1 != *p1)
break;
p1++;
r1++;
}
popt++;
}
option_found:
if (popt->flags & TCC_OPTION_HAS_ARG) {
if (*r1 != '\0' || (popt->flags & TCC_OPTION_NOSEP)) {
optarg = r1;
} else {
if (optind >= argc)
error("argument to '%s' is missing", r);
optarg = argv[optind++];
}
} else {
if (*r1 != '\0')
return 0;
optarg = NULL;
}
switch(popt->index) {
case TCC_OPTION_HELP:
return 0;
case TCC_OPTION_I:
if (tcc_add_include_path(s, optarg) < 0)
error("too many include paths");
break;
case TCC_OPTION_D:
{
char *sym, *value;
sym = (char *)optarg;
value = strchr(sym, '=');
if (value) {
*value = '\0';
value++;
}
tcc_define_symbol(s, sym, value);
}
break;
case TCC_OPTION_U:
tcc_undefine_symbol(s, optarg);
break;
case TCC_OPTION_L:
tcc_add_library_path(s, optarg);
break;
case TCC_OPTION_B:
/* set tcc utilities path (mainly for tcc development) */
tcc_set_lib_path(s, optarg);
break;
case TCC_OPTION_l:
dynarray_add((void ***)&files, &nb_files, r);
nb_libraries++;
break;
case TCC_OPTION_bench:
do_bench = 1;
break;
#ifdef CONFIG_TCC_BACKTRACE
case TCC_OPTION_bt:
num_callers = atoi(optarg);
break;
#endif
#ifdef CONFIG_TCC_BCHECK
case TCC_OPTION_b:
s->do_bounds_check = 1;
s->do_debug = 1;
break;
#endif
case TCC_OPTION_g:
s->do_debug = 1;
break;
case TCC_OPTION_c:
multiple_files = 1;
output_type = TCC_OUTPUT_OBJ;
break;
case TCC_OPTION_static:
s->static_link = 1;
break;
case TCC_OPTION_shared:
output_type = TCC_OUTPUT_DLL;
break;
case TCC_OPTION_soname:
s->soname = optarg;
break;
case TCC_OPTION_o:
multiple_files = 1;
outfile = optarg;
break;
case TCC_OPTION_r:
/* generate a .o merging several output files */
reloc_output = 1;
output_type = TCC_OUTPUT_OBJ;
break;
case TCC_OPTION_nostdinc:
s->nostdinc = 1;
break;
case TCC_OPTION_nostdlib:
s->nostdlib = 1;
break;
case TCC_OPTION_print_search_dirs:
print_search_dirs = 1;
break;
case TCC_OPTION_run:
{
int argc1;
char **argv1;
argc1 = expand_args(&argv1, optarg);
if (argc1 > 0) {
parse_args(s, argc1, argv1);
}
multiple_files = 0;
output_type = TCC_OUTPUT_MEMORY;
}
break;
case TCC_OPTION_v:
do {
if (0 == s->verbose++)
printf("tcc version %s\n", TCC_VERSION);
} while (*optarg++ == 'v');
break;
case TCC_OPTION_f:
if (tcc_set_flag(s, optarg, 1) < 0 && s->warn_unsupported)
goto unsupported_option;
break;
case TCC_OPTION_W:
if (tcc_set_warning(s, optarg, 1) < 0 &&
s->warn_unsupported)
goto unsupported_option;
break;
case TCC_OPTION_w:
s->warn_none = 1;
break;
case TCC_OPTION_rdynamic:
s->rdynamic = 1;
break;
case TCC_OPTION_Wl:
{
const char *p;
if (strstart(optarg, "-Ttext,", &p)) {
s->text_addr = strtoul(p, NULL, 16);
s->has_text_addr = 1;
} else if (strstart(optarg, "--section-alignment,", &p)) {
s->section_align = strtoul(p, NULL, 16);
} else if (strstart(optarg, "--image-base,", &p)) {
s->text_addr = strtoul(p, NULL, 16);
s->has_text_addr = 1;
#ifdef TCC_TARGET_PE
} else if (strstart(optarg, "--file-alignment,", &p)) {
s->pe_file_align = strtoul(p, NULL, 16);
} else if (strstart(optarg, "--subsystem,", &p)) {
#if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
if (!strcmp(p, "native"))
s->pe_subsystem = 1;
else if (!strcmp(p, "console"))
s->pe_subsystem = 3;
else if (!strcmp(p, "gui"))
s->pe_subsystem = 2;
else if (!strcmp(p, "posix"))
s->pe_subsystem = 7;
else if (!strcmp(p, "efiapp"))
s->pe_subsystem = 10;
else if (!strcmp(p, "efiboot"))
s->pe_subsystem = 11;
else if (!strcmp(p, "efiruntime"))
s->pe_subsystem = 12;
else if (!strcmp(p, "efirom"))
s->pe_subsystem = 13;
#elif defined(TCC_TARGET_ARM)
if (!strcmp(p, "wince"))
s->pe_subsystem = 9;
#endif
else {
error("invalid subsystem '%s'", p);
}
#endif
} else if (strstart(optarg, "--oformat,", &p)) {
#if defined(TCC_TARGET_PE)
if (strstart(p, "pe-", NULL)) {
#else
#if defined(TCC_TARGET_X86_64)
if (strstart(p, "elf64-", NULL)) {
#else
if (strstart(p, "elf32-", NULL)) {
#endif
#endif
s->output_format = TCC_OUTPUT_FORMAT_ELF;
} else if (!strcmp(p, "binary")) {
s->output_format = TCC_OUTPUT_FORMAT_BINARY;
} else
#ifdef TCC_TARGET_COFF
if (!strcmp(p, "coff")) {
s->output_format = TCC_OUTPUT_FORMAT_COFF;
} else
#endif
{
error("target %s not found", p);
}
} else {
error("unsupported linker option '%s'", optarg);
}
}
break;
case TCC_OPTION_E:
output_type = TCC_OUTPUT_PREPROCESS;
break;
case TCC_OPTION_x:
break;
default:
if (s->warn_unsupported) {
unsupported_option:
warning("unsupported option '%s'", r);
}
break;
}
}
}
return optind + 1;
}
int main(int argc, char **argv)
{
int i;
TCCState *s;
int nb_objfiles, ret, optind;
char objfilename[1024];
int64_t start_time = 0;
int ret, opt, n = 0, t = 0;
unsigned start_time = 0;
const char *first_file;
int argc; char **argv;
FILE *ppfp = stdout;
redo:
argc = argc0, argv = argv0;
s = tcc_new();
opt = tcc_parse_args(s, &argc, &argv, 1);
output_type = TCC_OUTPUT_EXE;
outfile = NULL;
multiple_files = 1;
files = NULL;
nb_files = 0;
nb_libraries = 0;
reloc_output = 0;
print_search_dirs = 0;
ret = 0;
optind = parse_args(s, argc - 1, argv + 1);
if (print_search_dirs) {
/* enough for Linux kernel */
printf("install: %s/\n", s->tcc_lib_path);
return 0;
}
if (optind == 0 || nb_files == 0) {
if (optind && s->verbose)
return 0;
help();
return 1;
}
nb_objfiles = nb_files - nb_libraries;
/* if outfile provided without other options, we output an
executable */
if (outfile && output_type == TCC_OUTPUT_MEMORY)
output_type = TCC_OUTPUT_EXE;
/* check -c consistency : only single file handled. XXX: checks file type */
if (output_type == TCC_OUTPUT_OBJ && !reloc_output) {
/* accepts only a single input file */
if (nb_objfiles != 1)
error("cannot specify multiple files with -c");
if (nb_libraries != 0)
error("cannot specify libraries with -c");
}
if (output_type == TCC_OUTPUT_PREPROCESS) {
if (!outfile) {
s->outfile = stdout;
} else {
s->outfile = fopen(outfile, "w");
if (!s->outfile)
error("could not open '%s", outfile);
}
} else if (output_type != TCC_OUTPUT_MEMORY) {
if (!outfile) {
/* compute default outfile name */
char *ext;
const char *name =
strcmp(files[0], "-") == 0 ? "a" : tcc_basename(files[0]);
pstrcpy(objfilename, sizeof(objfilename), name);
ext = tcc_fileextension(objfilename);
if ((n | t) == 0) {
if (opt == OPT_HELP)
return printf(help), 1;
if (opt == OPT_HELP2)
return printf(help2), 1;
if (opt == OPT_M32 || opt == OPT_M64)
tcc_tool_cross(s, argv, opt); /* never returns */
if (s->verbose)
printf(version);
if (opt == OPT_AR)
return tcc_tool_ar(s, argc, argv);
#ifdef TCC_TARGET_PE
if (output_type == TCC_OUTPUT_DLL)
strcpy(ext, ".dll");
else
if (output_type == TCC_OUTPUT_EXE)
strcpy(ext, ".exe");
else
if (opt == OPT_IMPDEF)
return tcc_tool_impdef(s, argc, argv);
#endif
if (output_type == TCC_OUTPUT_OBJ && !reloc_output && *ext)
strcpy(ext, ".o");
else
pstrcpy(objfilename, sizeof(objfilename), "a.out");
outfile = objfilename;
if (opt == OPT_V)
return 0;
if (opt == OPT_PRINT_DIRS) {
/* initialize search dirs */
set_environment(s);
tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
print_search_dirs(s);
return 0;
}
}
if (do_bench) {
start_time = getclock_us();
}
tcc_set_output_type(s, output_type);
/* compile or add each files or library */
for(i = 0; i < nb_files && ret == 0; i++) {
const char *filename;
filename = files[i];
if (filename[0] == '-' && filename[1]) {
if (tcc_add_library(s, filename + 2) < 0) {
error_noabort("cannot find %s", filename);
ret = 1;
}
} else {
if (1 == s->verbose)
printf("-> %s\n", filename);
if (tcc_add_file(s, filename) < 0)
ret = 1;
}
}
/* free all files */
tcc_free(files);
if (0 == ret) {
if (do_bench)
tcc_print_stats(s, getclock_us() - start_time);
n = s->nb_files;
if (n == 0)
tcc_error("no input files\n");
if (s->output_type == TCC_OUTPUT_PREPROCESS) {
if (outfile)
fclose(s->outfile);
} else if (s->output_type == TCC_OUTPUT_MEMORY)
ret = tcc_run(s, argc - optind, argv + optind);
else
ret = tcc_output_file(s, outfile) ? 1 : 0;
if (s->outfile) {
ppfp = fopen(s->outfile, "w");
if (!ppfp)
tcc_error("could not write '%s'", s->outfile);
}
} else if (s->output_type == TCC_OUTPUT_OBJ && !s->option_r) {
if (s->nb_libraries)
tcc_error("cannot specify libraries with -c");
if (n > 1 && s->outfile)
tcc_error("cannot specify output file with -c many files");
} else {
if (s->option_pthread)
tcc_set_options(s, "-lpthread");
}
if (s->do_bench)
start_time = getclock_ms();
}
tcc_delete(s);
set_environment(s);
if (s->output_type == 0)
s->output_type = TCC_OUTPUT_EXE;
tcc_set_output_type(s, s->output_type);
s->ppfp = ppfp;
#ifdef MEM_DEBUG
if (do_bench) {
printf("memory: %d bytes, max = %d bytes\n", mem_cur_size, mem_max_size);
if ((s->output_type == TCC_OUTPUT_MEMORY
|| s->output_type == TCC_OUTPUT_PREPROCESS) && (s->dflag & 16))
s->dflag |= t ? 32 : 0, s->run_test = ++t, n = s->nb_files;
/* compile or add each files or library */
for (first_file = NULL, ret = 0;;) {
struct filespec *f = s->files[s->nb_files - n];
s->filetype = f->type;
s->alacarte_link = f->alacarte;
if (f->type == AFF_TYPE_LIB) {
if (tcc_add_library_err(s, f->name) < 0)
ret = 1;
} else {
if (1 == s->verbose)
printf("-> %s\n", f->name);
if (!first_file)
first_file = f->name;
if (tcc_add_file(s, f->name) < 0)
ret = 1;
}
s->filetype = 0;
s->alacarte_link = 1;
if (--n == 0 || ret
|| (s->output_type == TCC_OUTPUT_OBJ && !s->option_r))
break;
}
if (s->run_test) {
t = 0;
} else if (s->output_type == TCC_OUTPUT_PREPROCESS) {
;
} else if (0 == ret) {
if (s->output_type == TCC_OUTPUT_MEMORY) {
#ifdef TCC_IS_NATIVE
ret = tcc_run(s, argc, argv);
#endif
} else {
if (!s->outfile)
s->outfile = default_outputfile(s, first_file);
if (tcc_output_file(s, s->outfile))
ret = 1;
else if (s->gen_deps)
gen_makedeps(s, s->outfile, s->deps_outfile);
}
}
if (s->do_bench && (n | t | ret) == 0)
tcc_print_stats(s, getclock_ms() - start_time);
tcc_delete(s);
if (ret == 0 && n)
goto redo; /* compile more files with -c */
if (t)
goto redo; /* run more tests with -dt -run */
if (ppfp && ppfp != stdout)
fclose(ppfp);
return ret;
}

1687
tcc.h

File diff suppressed because it is too large Load Diff

752
tccasm.c

File diff suppressed because it is too large Load Diff

View File

@ -18,7 +18,8 @@
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "coff.h"
#include "tcc.h"
#define MAXNSCNS 255 /* MAXIMUM NUMBER OF SECTIONS */
#define MAX_STR_TABLE 1000000
@ -37,7 +38,7 @@ int EndAddress[MAX_FUNCS];
int LastLineNo[MAX_FUNCS];
int FuncEntries[MAX_FUNCS];
BOOL OutputTheSection(Section * sect);
int OutputTheSection(Section * sect);
short int GetCoffFlags(const char *s);
void SortSymbolTable(void);
Section *FindSection(TCCState * s1, const char *sname);
@ -73,7 +74,7 @@ typedef struct {
unsigned short dummy4;
} AUXEF;
int tcc_output_coff(TCCState *s1, FILE *f)
ST_FUNC int tcc_output_coff(TCCState *s1, FILE *f)
{
Section *tcc_sect;
SCNHDR *coff_sec;
@ -532,7 +533,7 @@ int tcc_output_coff(TCCState *s1, FILE *f)
} else {
if (pCoff_str_table - Coff_str_table + strlen(name) >
MAX_STR_TABLE - 1)
error("String table too large");
tcc_error("String table too large");
csym._n._n_n._n_zeroes = 0;
csym._n._n_n._n_offset =
@ -562,11 +563,7 @@ int tcc_output_coff(TCCState *s1, FILE *f)
}
if (k >= nFuncs) {
char s[256];
sprintf(s, "debug info can't find function: %s", name);
error(s);
tcc_error("debug info can't find function: %s", name);
}
// put a Function Name
@ -733,13 +730,7 @@ void SortSymbolTable(void)
}
if (k >= nFuncs) {
char s[256];
sprintf(s,
"debug (sort) info can't find function: %s",
name2);
error(s);
tcc_error("debug (sort) info can't find function: %s", name2);
}
if (strcmp(AssociatedFile[k], name) == 0) {
@ -766,7 +757,7 @@ void SortSymbolTable(void)
}
if (n != nb_syms)
error("Internal Compiler error, debug info");
tcc_error("Internal Compiler error, debug info");
// copy it all back
@ -823,14 +814,14 @@ int FindCoffSymbolIndex(const char *func_name)
return n; // total number of symbols
}
BOOL OutputTheSection(Section * sect)
int OutputTheSection(Section * sect)
{
const char *s = sect->name;
if (!strcmp(s, ".text"))
return true;
return 1;
else if (!strcmp(s, ".data"))
return true;
return 1;
else
return 0;
}
@ -863,11 +854,11 @@ Section *FindSection(TCCState * s1, const char *sname)
return s;
}
error("could not find section %s", sname);
tcc_error("could not find section %s", sname);
return 0;
}
int tcc_load_coff(TCCState * s1, int fd)
ST_FUNC int tcc_load_coff(TCCState * s1, int fd)
{
// tktk TokenSym *ts;
@ -881,39 +872,39 @@ int tcc_load_coff(TCCState * s1, int fd)
f = fdopen(fd, "rb");
if (!f) {
error("Unable to open .out file for input");
tcc_error("Unable to open .out file for input");
}
if (fread(&file_hdr, FILHSZ, 1, f) != 1)
error("error reading .out file for input");
tcc_error("error reading .out file for input");
if (fread(&o_filehdr, sizeof(o_filehdr), 1, f) != 1)
error("error reading .out file for input");
tcc_error("error reading .out file for input");
// first read the string table
if (fseek(f, file_hdr.f_symptr + file_hdr.f_nsyms * SYMESZ, SEEK_SET))
error("error reading .out file for input");
tcc_error("error reading .out file for input");
if (fread(&str_size, sizeof(int), 1, f) != 1)
error("error reading .out file for input");
tcc_error("error reading .out file for input");
Coff_str_table = (char *) tcc_malloc(str_size);
if (fread(Coff_str_table, str_size - 4, 1, f) != 1)
error("error reading .out file for input");
tcc_error("error reading .out file for input");
// read/process all the symbols
// seek back to symbols
if (fseek(f, file_hdr.f_symptr, SEEK_SET))
error("error reading .out file for input");
tcc_error("error reading .out file for input");
for (i = 0; i < file_hdr.f_nsyms; i++) {
if (fread(&csym, SYMESZ, 1, f) != 1)
error("error reading .out file for input");
tcc_error("error reading .out file for input");
if (csym._n._n_n._n_zeroes == 0) {
name = Coff_str_table + csym._n._n_n._n_offset - 4;
@ -942,13 +933,13 @@ int tcc_load_coff(TCCState * s1, int fd)
if (name[0] == '_' && strcmp(name, "_main") != 0)
name++;
tcc_add_symbol(s1, name, (void*)csym.n_value);
tcc_add_symbol(s1, name, (void*)(uintptr_t)csym.n_value);
}
// skip any aux records
if (csym.n_numaux == 1) {
if (fread(&csym, SYMESZ, 1, f) != 1)
error("error reading .out file for input");
tcc_error("error reading .out file for input");
i++;
}
}

3177
tccelf.c

File diff suppressed because it is too large Load Diff

5991
tccgen.c

File diff suppressed because it is too large Load Diff

View File

@ -39,6 +39,7 @@ int getchar(void);
char *gets(char *s);
int ungetc(int c, FILE *stream);
int fflush(FILE *stream);
int putchar (int c);
int printf(const char *format, ...);
int fprintf(FILE *stream, const char *format, ...);
@ -64,6 +65,7 @@ void *memcpy(void *dest, const void *src, size_t n);
void *memmove(void *dest, const void *src, size_t n);
void *memset(void *s, int c, size_t n);
char *strdup(const char *s);
size_t strlen(const char *s);
/* dlfcn.h */
#define RTLD_LAZY 0x001

984
tccpe.c

File diff suppressed because it is too large Load Diff

2799
tccpp.c

File diff suppressed because it is too large Load Diff

844
tccrun.c 100644
View File

@ -0,0 +1,844 @@
/*
* TCC - Tiny C Compiler - Support for -run switch
*
* Copyright (c) 2001-2004 Fabrice Bellard
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "tcc.h"
/* only native compiler supports -run */
#ifdef TCC_IS_NATIVE
#ifndef _WIN32
# include <sys/mman.h>
#endif
#ifdef CONFIG_TCC_BACKTRACE
# ifndef _WIN32
# include <signal.h>
# ifndef __OpenBSD__
# include <sys/ucontext.h>
# endif
# else
# define ucontext_t CONTEXT
# endif
ST_DATA int rt_num_callers = 6;
ST_DATA const char **rt_bound_error_msg;
ST_DATA void *rt_prog_main;
static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level);
static void rt_error(ucontext_t *uc, const char *fmt, ...);
static void set_exception_handler(void);
#endif
static void set_pages_executable(void *ptr, unsigned long length);
static int tcc_relocate_ex(TCCState *s1, void *ptr, addr_t ptr_diff);
#ifdef _WIN64
static void *win64_add_function_table(TCCState *s1);
static void win64_del_function_table(void *);
#endif
/* ------------------------------------------------------------- */
/* Do all relocations (needed before using tcc_get_symbol())
Returns -1 on error. */
LIBTCCAPI int tcc_relocate(TCCState *s1, void *ptr)
{
int size;
addr_t ptr_diff = 0;
if (TCC_RELOCATE_AUTO != ptr)
return tcc_relocate_ex(s1, ptr, 0);
size = tcc_relocate_ex(s1, NULL, 0);
if (size < 0)
return -1;
#ifdef HAVE_SELINUX
{
/* Using mmap instead of malloc */
void *prx;
char tmpfname[] = "/tmp/.tccrunXXXXXX";
int fd = mkstemp(tmpfname);
unlink(tmpfname);
ftruncate(fd, size);
ptr = mmap (NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
prx = mmap (NULL, size, PROT_READ|PROT_EXEC, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED || prx == MAP_FAILED)
tcc_error("tccrun: could not map memory");
dynarray_add(&s1->runtime_mem, &s1->nb_runtime_mem, (void*)(addr_t)size);
dynarray_add(&s1->runtime_mem, &s1->nb_runtime_mem, prx);
ptr_diff = (char*)prx - (char*)ptr;
}
#else
ptr = tcc_malloc(size);
#endif
tcc_relocate_ex(s1, ptr, ptr_diff); /* no more errors expected */
dynarray_add(&s1->runtime_mem, &s1->nb_runtime_mem, ptr);
return 0;
}
ST_FUNC void tcc_run_free(TCCState *s1)
{
int i;
for (i = 0; i < s1->nb_runtime_mem; ++i) {
#ifdef HAVE_SELINUX
unsigned size = (unsigned)(addr_t)s1->runtime_mem[i++];
munmap(s1->runtime_mem[i++], size);
munmap(s1->runtime_mem[i], size);
#else
#ifdef _WIN64
win64_del_function_table(*(void**)s1->runtime_mem[i]);
#endif
tcc_free(s1->runtime_mem[i]);
#endif
}
tcc_free(s1->runtime_mem);
}
/* launch the compiled program with the given arguments */
LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv)
{
int (*prog_main)(int, char **);
s1->runtime_main = "main";
if ((s1->dflag & 16) && !find_elf_sym(s1->symtab, s1->runtime_main))
return 0;
if (tcc_relocate(s1, TCC_RELOCATE_AUTO) < 0)
return -1;
prog_main = tcc_get_symbol_err(s1, s1->runtime_main);
#ifdef CONFIG_TCC_BACKTRACE
if (s1->do_debug) {
set_exception_handler();
rt_prog_main = prog_main;
}
#endif
errno = 0; /* clean errno value */
#ifdef CONFIG_TCC_BCHECK
if (s1->do_bounds_check) {
void (*bound_init)(void);
void (*bound_exit)(void);
void (*bound_new_region)(void *p, addr_t size);
int (*bound_delete_region)(void *p);
int i, ret;
/* set error function */
rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
/* XXX: use .init section so that it also work in binary ? */
bound_init = tcc_get_symbol_err(s1, "__bound_init");
bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
bound_new_region = tcc_get_symbol_err(s1, "__bound_new_region");
bound_delete_region = tcc_get_symbol_err(s1, "__bound_delete_region");
bound_init();
/* mark argv area as valid */
bound_new_region(argv, argc*sizeof(argv[0]));
for (i=0; i<argc; ++i)
bound_new_region(argv[i], strlen(argv[i]) + 1);
ret = (*prog_main)(argc, argv);
/* unmark argv area */
for (i=0; i<argc; ++i)
bound_delete_region(argv[i]);
bound_delete_region(argv);
bound_exit();
return ret;
}
#endif
return (*prog_main)(argc, argv);
}
#if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
#define RUN_SECTION_ALIGNMENT 63
#else
#define RUN_SECTION_ALIGNMENT 15
#endif
/* relocate code. Return -1 on error, required size if ptr is NULL,
otherwise copy code into buffer passed by the caller */
static int tcc_relocate_ex(TCCState *s1, void *ptr, addr_t ptr_diff)
{
Section *s;
unsigned offset, length, fill, i, k;
addr_t mem;
if (NULL == ptr) {
s1->nb_errors = 0;
#ifdef TCC_TARGET_PE
pe_output_file(s1, NULL);
#else
tcc_add_runtime(s1);
resolve_common_syms(s1);
build_got_entries(s1);
#endif
if (s1->nb_errors)
return -1;
}
offset = 0, mem = (addr_t)ptr;
fill = -mem & RUN_SECTION_ALIGNMENT;
#ifdef _WIN64
offset += sizeof (void*);
#endif
for (k = 0; k < 2; ++k) {
for(i = 1; i < s1->nb_sections; i++) {
s = s1->sections[i];
if (0 == (s->sh_flags & SHF_ALLOC))
continue;
if (k != !(s->sh_flags & SHF_EXECINSTR))
continue;
offset += fill;
if (!mem)
s->sh_addr = 0;
else if (s->sh_flags & SHF_EXECINSTR)
s->sh_addr = mem + offset + ptr_diff;
else
s->sh_addr = mem + offset;
#if 0
if (mem)
printf("%-16s +%02lx %p %04x\n",
s->name, fill, (void*)s->sh_addr, (unsigned)s->data_offset);
#endif
offset += s->data_offset;
fill = -(mem + offset) & 15;
}
#if RUN_SECTION_ALIGNMENT > 15
/* To avoid that x86 processors would reload cached instructions each time
when data is written in the near, we need to make sure that code and data
do not share the same 64 byte unit */
fill = -(mem + offset) & RUN_SECTION_ALIGNMENT;
#endif
}
/* relocate symbols */
relocate_syms(s1, s1->symtab, 1);
if (s1->nb_errors)
return -1;
if (0 == mem)
return offset + RUN_SECTION_ALIGNMENT;
#ifdef TCC_TARGET_PE
s1->pe_imagebase = mem;
#endif
/* relocate each section */
for(i = 1; i < s1->nb_sections; i++) {
s = s1->sections[i];
if (s->reloc)
relocate_section(s1, s);
}
relocate_plt(s1);
for(i = 1; i < s1->nb_sections; i++) {
s = s1->sections[i];
if (0 == (s->sh_flags & SHF_ALLOC))
continue;
length = s->data_offset;
ptr = (void*)s->sh_addr;
if (s->sh_flags & SHF_EXECINSTR)
ptr = (char*)ptr - ptr_diff;
if (NULL == s->data || s->sh_type == SHT_NOBITS)
memset(ptr, 0, length);
else
memcpy(ptr, s->data, length);
/* mark executable sections as executable in memory */
if (s->sh_flags & SHF_EXECINSTR)
set_pages_executable((char*)ptr + ptr_diff, length);
}
#ifdef _WIN64
*(void**)mem = win64_add_function_table(s1);
#endif
return 0;
}
/* ------------------------------------------------------------- */
/* allow to run code in memory */
static void set_pages_executable(void *ptr, unsigned long length)
{
#ifdef _WIN32
unsigned long old_protect;
VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
#else
void __clear_cache(void *beginning, void *end);
# ifndef HAVE_SELINUX
addr_t start, end;
# ifndef PAGESIZE
# define PAGESIZE 4096
# endif
start = (addr_t)ptr & ~(PAGESIZE - 1);
end = (addr_t)ptr + length;
end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
if (mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC))
tcc_error("mprotect failed: did you mean to configure --with-selinux?");
# endif
# if defined TCC_TARGET_ARM || defined TCC_TARGET_ARM64
__clear_cache(ptr, (char *)ptr + length);
# endif
#endif
}
#ifdef _WIN64
static void *win64_add_function_table(TCCState *s1)
{
void *p = NULL;
if (s1->uw_pdata) {
p = (void*)s1->uw_pdata->sh_addr;
RtlAddFunctionTable(
(RUNTIME_FUNCTION*)p,
s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
s1->pe_imagebase
);
s1->uw_pdata = NULL;
}
return p;
}
static void win64_del_function_table(void *p)
{
if (p) {
RtlDeleteFunctionTable((RUNTIME_FUNCTION*)p);
}
}
#endif
/* ------------------------------------------------------------- */
#ifdef CONFIG_TCC_BACKTRACE
ST_FUNC void tcc_set_num_callers(int n)
{
rt_num_callers = n;
}
/* print the position in the source file of PC value 'pc' by reading
the stabs debug information */
static addr_t rt_printline(addr_t wanted_pc, const char *msg)
{
char func_name[128], last_func_name[128];
addr_t func_addr, last_pc, pc;
const char *incl_files[INCLUDE_STACK_SIZE];
int incl_index, len, last_line_num, i;
const char *str, *p;
Stab_Sym *stab_sym = NULL, *stab_sym_end, *sym;
int stab_len = 0;
char *stab_str = NULL;
if (stab_section) {
stab_len = stab_section->data_offset;
stab_sym = (Stab_Sym *)stab_section->data;
stab_str = (char *) stabstr_section->data;
}
func_name[0] = '\0';
func_addr = 0;
incl_index = 0;
last_func_name[0] = '\0';
last_pc = (addr_t)-1;
last_line_num = 1;
if (!stab_sym)
goto no_stabs;
stab_sym_end = (Stab_Sym*)((char*)stab_sym + stab_len);
for (sym = stab_sym + 1; sym < stab_sym_end; ++sym) {
switch(sym->n_type) {
/* function start or end */
case N_FUN:
if (sym->n_strx == 0) {
/* we test if between last line and end of function */
pc = sym->n_value + func_addr;
if (wanted_pc >= last_pc && wanted_pc < pc)
goto found;
func_name[0] = '\0';
func_addr = 0;
} else {
str = stab_str + sym->n_strx;
p = strchr(str, ':');
if (!p) {
pstrcpy(func_name, sizeof(func_name), str);
} else {
len = p - str;
if (len > sizeof(func_name) - 1)
len = sizeof(func_name) - 1;
memcpy(func_name, str, len);
func_name[len] = '\0';
}
func_addr = sym->n_value;
}
break;
/* line number info */
case N_SLINE:
pc = sym->n_value + func_addr;
if (wanted_pc >= last_pc && wanted_pc < pc)
goto found;
last_pc = pc;
last_line_num = sym->n_desc;
/* XXX: slow! */
strcpy(last_func_name, func_name);
break;
/* include files */
case N_BINCL:
str = stab_str + sym->n_strx;
add_incl:
if (incl_index < INCLUDE_STACK_SIZE) {
incl_files[incl_index++] = str;
}
break;
case N_EINCL:
if (incl_index > 1)
incl_index--;
break;
case N_SO:
if (sym->n_strx == 0) {
incl_index = 0; /* end of translation unit */
} else {
str = stab_str + sym->n_strx;
/* do not add path */
len = strlen(str);
if (len > 0 && str[len - 1] != '/')
goto add_incl;
}
break;
}
}
no_stabs:
/* second pass: we try symtab symbols (no line number info) */
incl_index = 0;
if (symtab_section)
{
ElfW(Sym) *sym, *sym_end;
int type;
sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
for(sym = (ElfW(Sym) *)symtab_section->data + 1;
sym < sym_end;
sym++) {
type = ELFW(ST_TYPE)(sym->st_info);
if (type == STT_FUNC || type == STT_GNU_IFUNC) {
if (wanted_pc >= sym->st_value &&
wanted_pc < sym->st_value + sym->st_size) {
pstrcpy(last_func_name, sizeof(last_func_name),
(char *) symtab_section->link->data + sym->st_name);
func_addr = sym->st_value;
goto found;
}
}
}
}
/* did not find any info: */
fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
fflush(stderr);
return 0;
found:
i = incl_index;
if (i > 0)
fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
if (last_func_name[0] != '\0')
fprintf(stderr, " %s()", last_func_name);
if (--i >= 0) {
fprintf(stderr, " (included from ");
for (;;) {
fprintf(stderr, "%s", incl_files[i]);
if (--i < 0)
break;
fprintf(stderr, ", ");
}
fprintf(stderr, ")");
}
fprintf(stderr, "\n");
fflush(stderr);
return func_addr;
}
/* emit a run time error at position 'pc' */
static void rt_error(ucontext_t *uc, const char *fmt, ...)
{
va_list ap;
addr_t pc;
int i;
fprintf(stderr, "Runtime error: ");
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
for(i=0;i<rt_num_callers;i++) {
if (rt_get_caller_pc(&pc, uc, i) < 0)
break;
pc = rt_printline(pc, i ? "by" : "at");
if (pc == (addr_t)rt_prog_main && pc)
break;
}
}
/* ------------------------------------------------------------- */
#ifndef _WIN32
/* signal handler for fatal errors */
static void sig_error(int signum, siginfo_t *siginf, void *puc)
{
ucontext_t *uc = puc;
switch(signum) {
case SIGFPE:
switch(siginf->si_code) {
case FPE_INTDIV:
case FPE_FLTDIV:
rt_error(uc, "division by zero");
break;
default:
rt_error(uc, "floating point exception");
break;
}
break;
case SIGBUS:
case SIGSEGV:
if (rt_bound_error_msg && *rt_bound_error_msg)
rt_error(uc, *rt_bound_error_msg);
else
rt_error(uc, "dereferencing invalid pointer");
break;
case SIGILL:
rt_error(uc, "illegal instruction");
break;
case SIGABRT:
rt_error(uc, "abort() called");
break;
default:
rt_error(uc, "caught signal %d", signum);
break;
}
exit(255);
}
#ifndef SA_SIGINFO
# define SA_SIGINFO 0x00000004u
#endif
/* Generate a stack backtrace when a CPU exception occurs. */
static void set_exception_handler(void)
{
struct sigaction sigact;
/* install TCC signal handlers to print debug info on fatal
runtime errors */
sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
sigact.sa_sigaction = sig_error;
sigemptyset(&sigact.sa_mask);
sigaction(SIGFPE, &sigact, NULL);
sigaction(SIGILL, &sigact, NULL);
sigaction(SIGSEGV, &sigact, NULL);
sigaction(SIGBUS, &sigact, NULL);
sigaction(SIGABRT, &sigact, NULL);
}
/* ------------------------------------------------------------- */
#ifdef __i386__
/* fix for glibc 2.1 */
#ifndef REG_EIP
#define REG_EIP EIP
#define REG_EBP EBP
#endif
/* return the PC at frame level 'level'. Return negative if not found */
static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
{
addr_t fp;
int i;
if (level == 0) {
#if defined(__APPLE__)
*paddr = uc->uc_mcontext->__ss.__eip;
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
*paddr = uc->uc_mcontext.mc_eip;
#elif defined(__dietlibc__)
*paddr = uc->uc_mcontext.eip;
#elif defined(__NetBSD__)
*paddr = uc->uc_mcontext.__gregs[_REG_EIP];
#elif defined(__OpenBSD__)
*paddr = uc->sc_eip;
#else
*paddr = uc->uc_mcontext.gregs[REG_EIP];
#endif
return 0;
} else {
#if defined(__APPLE__)
fp = uc->uc_mcontext->__ss.__ebp;
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
fp = uc->uc_mcontext.mc_ebp;
#elif defined(__dietlibc__)
fp = uc->uc_mcontext.ebp;
#elif defined(__NetBSD__)
fp = uc->uc_mcontext.__gregs[_REG_EBP];
#elif defined(__OpenBSD__)
*paddr = uc->sc_ebp;
#else
fp = uc->uc_mcontext.gregs[REG_EBP];
#endif
for(i=1;i<level;i++) {
/* XXX: check address validity with program info */
if (fp <= 0x1000 || fp >= 0xc0000000)
return -1;
fp = ((addr_t *)fp)[0];
}
*paddr = ((addr_t *)fp)[1];
return 0;
}
}
/* ------------------------------------------------------------- */
#elif defined(__x86_64__)
/* return the PC at frame level 'level'. Return negative if not found */
static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
{
addr_t fp;
int i;
if (level == 0) {
/* XXX: only support linux */
#if defined(__APPLE__)
*paddr = uc->uc_mcontext->__ss.__rip;
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
*paddr = uc->uc_mcontext.mc_rip;
#elif defined(__NetBSD__)
*paddr = uc->uc_mcontext.__gregs[_REG_RIP];
#else
*paddr = uc->uc_mcontext.gregs[REG_RIP];
#endif
return 0;
} else {
#if defined(__APPLE__)
fp = uc->uc_mcontext->__ss.__rbp;
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
fp = uc->uc_mcontext.mc_rbp;
#elif defined(__NetBSD__)
fp = uc->uc_mcontext.__gregs[_REG_RBP];
#else
fp = uc->uc_mcontext.gregs[REG_RBP];
#endif
for(i=1;i<level;i++) {
/* XXX: check address validity with program info */
if (fp <= 0x1000)
return -1;
fp = ((addr_t *)fp)[0];
}
*paddr = ((addr_t *)fp)[1];
return 0;
}
}
/* ------------------------------------------------------------- */
#elif defined(__arm__)
/* return the PC at frame level 'level'. Return negative if not found */
static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
{
addr_t fp, sp;
int i;
if (level == 0) {
/* XXX: only supports linux */
#if defined(__linux__)
*paddr = uc->uc_mcontext.arm_pc;
#else
return -1;
#endif
return 0;
} else {
#if defined(__linux__)
fp = uc->uc_mcontext.arm_fp;
sp = uc->uc_mcontext.arm_sp;
if (sp < 0x1000)
sp = 0x1000;
#else
return -1;
#endif
/* XXX: specific to tinycc stack frames */
if (fp < sp + 12 || fp & 3)
return -1;
for(i = 1; i < level; i++) {
sp = ((addr_t *)fp)[-2];
if (sp < fp || sp - fp > 16 || sp & 3)
return -1;
fp = ((addr_t *)fp)[-3];
if (fp <= sp || fp - sp < 12 || fp & 3)
return -1;
}
/* XXX: check address validity with program info */
*paddr = ((addr_t *)fp)[-1];
return 0;
}
}
/* ------------------------------------------------------------- */
#elif defined(__aarch64__)
static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
{
if (level < 0)
return -1;
else if (level == 0) {
*paddr = uc->uc_mcontext.pc;
return 0;
}
else {
addr_t *fp = (addr_t *)uc->uc_mcontext.regs[29];
int i;
for (i = 1; i < level; i++)
fp = (addr_t *)fp[0];
*paddr = fp[1];
return 0;
}
}
/* ------------------------------------------------------------- */
#else
#warning add arch specific rt_get_caller_pc()
static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
{
return -1;
}
#endif /* !__i386__ */
/* ------------------------------------------------------------- */
#else /* WIN32 */
static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
{
EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
CONTEXT *uc = ex_info->ContextRecord;
switch (er->ExceptionCode) {
case EXCEPTION_ACCESS_VIOLATION:
if (rt_bound_error_msg && *rt_bound_error_msg)
rt_error(uc, *rt_bound_error_msg);
else
rt_error(uc, "access violation");
break;
case EXCEPTION_STACK_OVERFLOW:
rt_error(uc, "stack overflow");
break;
case EXCEPTION_INT_DIVIDE_BY_ZERO:
rt_error(uc, "division by zero");
break;
default:
rt_error(uc, "exception caught");
break;
}
return EXCEPTION_EXECUTE_HANDLER;
}
/* Generate a stack backtrace when a CPU exception occurs. */
static void set_exception_handler(void)
{
SetUnhandledExceptionFilter(cpu_exception_handler);
}
/* return the PC at frame level 'level'. Return non zero if not found */
static int rt_get_caller_pc(addr_t *paddr, CONTEXT *uc, int level)
{
addr_t fp, pc;
int i;
#ifdef _WIN64
pc = uc->Rip;
fp = uc->Rbp;
#else
pc = uc->Eip;
fp = uc->Ebp;
#endif
if (level > 0) {
for(i=1;i<level;i++) {
/* XXX: check address validity with program info */
if (fp <= 0x1000 || fp >= 0xc0000000)
return -1;
fp = ((addr_t*)fp)[0];
}
pc = ((addr_t*)fp)[1];
}
*paddr = pc;
return 0;
}
#endif /* _WIN32 */
#endif /* CONFIG_TCC_BACKTRACE */
/* ------------------------------------------------------------- */
#ifdef CONFIG_TCC_STATIC
/* dummy function for profiling */
ST_FUNC void *dlopen(const char *filename, int flag)
{
return NULL;
}
ST_FUNC void dlclose(void *p)
{
}
ST_FUNC const char *dlerror(void)
{
return "error";
}
typedef struct TCCSyms {
char *str;
void *ptr;
} TCCSyms;
/* add the symbol you want here if no dynamic linking is done */
static TCCSyms tcc_syms[] = {
#if !defined(CONFIG_TCCBOOT)
#define TCCSYM(a) { #a, &a, },
TCCSYM(printf)
TCCSYM(fprintf)
TCCSYM(fopen)
TCCSYM(fclose)
#undef TCCSYM
#endif
{ NULL, NULL },
};
ST_FUNC void *dlsym(void *handle, const char *symbol)
{
TCCSyms *p;
p = tcc_syms;
while (p->str != NULL) {
if (!strcmp(p->str, symbol))
return p->ptr;
p++;
}
return NULL;
}
#endif /* CONFIG_TCC_STATIC */
#endif /* TCC_IS_NATIVE */
/* ------------------------------------------------------------- */

266
tcctok.h
View File

@ -36,7 +36,9 @@
DEF(TOK_RESTRICT2, "__restrict")
DEF(TOK_RESTRICT3, "__restrict__")
DEF(TOK_EXTENSION, "__extension__") /* gcc keyword */
DEF(TOK_GENERIC, "_Generic")
DEF(TOK_FLOAT, "float")
DEF(TOK_DOUBLE, "double")
DEF(TOK_BOOL, "_Bool")
@ -59,6 +61,10 @@
DEF(TOK_ASM2, "__asm")
DEF(TOK_ASM3, "__asm__")
#ifdef TCC_TARGET_ARM64
DEF(TOK_UINT128, "__uint128_t")
#endif
/*********************************************************************/
/* the following are not keywords. They are included to ease parsing */
/* preprocessor only */
@ -81,10 +87,16 @@
DEF(TOK___TIME__, "__TIME__")
DEF(TOK___FUNCTION__, "__FUNCTION__")
DEF(TOK___VA_ARGS__, "__VA_ARGS__")
DEF(TOK___COUNTER__, "__COUNTER__")
/* special identifiers */
DEF(TOK___FUNC__, "__func__")
/* special floating point values */
DEF(TOK___NAN__, "__nan__")
DEF(TOK___SNAN__, "__snan__")
DEF(TOK___INF__, "__inf__")
/* attribute identifiers */
/* XXX: handle all tokens generically since speed is not critical */
DEF(TOK_SECTION1, "section")
@ -93,6 +105,10 @@
DEF(TOK_ALIGNED2, "__aligned__")
DEF(TOK_PACKED1, "packed")
DEF(TOK_PACKED2, "__packed__")
DEF(TOK_WEAK1, "weak")
DEF(TOK_WEAK2, "__weak__")
DEF(TOK_ALIAS1, "alias")
DEF(TOK_ALIAS2, "__alias__")
DEF(TOK_UNUSED1, "unused")
DEF(TOK_UNUSED2, "__unused__")
DEF(TOK_CDECL1, "cdecl")
@ -104,21 +120,38 @@
DEF(TOK_FASTCALL1, "fastcall")
DEF(TOK_FASTCALL2, "__fastcall")
DEF(TOK_FASTCALL3, "__fastcall__")
DEF(TOK_REGPARM1, "regparm")
DEF(TOK_REGPARM2, "__regparm__")
DEF(TOK_MODE, "__mode__")
DEF(TOK_MODE_QI, "__QI__")
DEF(TOK_MODE_DI, "__DI__")
DEF(TOK_MODE_HI, "__HI__")
DEF(TOK_MODE_SI, "__SI__")
DEF(TOK_MODE_word, "__word__")
DEF(TOK_DLLEXPORT, "dllexport")
DEF(TOK_DLLIMPORT, "dllimport")
DEF(TOK_NORETURN1, "noreturn")
DEF(TOK_NORETURN2, "__noreturn__")
DEF(TOK_VISIBILITY1, "visibility")
DEF(TOK_VISIBILITY2, "__visibility__")
DEF(TOK_builtin_types_compatible_p, "__builtin_types_compatible_p")
DEF(TOK_builtin_choose_expr, "__builtin_choose_expr")
DEF(TOK_builtin_constant_p, "__builtin_constant_p")
DEF(TOK_builtin_frame_address, "__builtin_frame_address")
#ifdef TCC_TARGET_X86_64
DEF(TOK_builtin_malloc, "__builtin_malloc")
DEF(TOK_builtin_free, "__builtin_free")
DEF(TOK_malloc, "malloc")
DEF(TOK_free, "free")
DEF(TOK_builtin_return_address, "__builtin_return_address")
DEF(TOK_builtin_expect, "__builtin_expect")
/*DEF(TOK_builtin_va_list, "__builtin_va_list")*/
#if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
DEF(TOK_builtin_va_start, "__builtin_va_start")
#elif defined TCC_TARGET_X86_64
DEF(TOK_builtin_va_arg_types, "__builtin_va_arg_types")
#elif defined TCC_TARGET_ARM64
DEF(TOK___va_start, "__va_start")
DEF(TOK___va_arg, "__va_arg")
#endif
DEF(TOK_REGPARM1, "regparm")
DEF(TOK_REGPARM2, "__regparm__")
/* pragma */
DEF(TOK_pack, "pack")
@ -127,25 +160,44 @@
DEF(TOK_ASM_push, "push")
DEF(TOK_ASM_pop, "pop")
#endif
DEF(TOK_comment, "comment")
DEF(TOK_lib, "lib")
DEF(TOK_push_macro, "push_macro")
DEF(TOK_pop_macro, "pop_macro")
DEF(TOK_once, "once")
DEF(TOK_option, "option")
/* builtin functions or variables */
#ifdef TCC_ARM_EABI
DEF(TOK_memcpy, "__aeabi_memcpy")
DEF(TOK_memcpy4, "__aeabi_memcpy4")
DEF(TOK_memcpy8, "__aeabi_memcpy8")
DEF(TOK_memset, "__aeabi_memset")
DEF(TOK___aeabi_ldivmod, "__aeabi_ldivmod")
DEF(TOK___aeabi_uldivmod, "__aeabi_uldivmod")
#else
#ifndef TCC_ARM_EABI
DEF(TOK_memcpy, "memcpy")
DEF(TOK_memmove, "memmove")
DEF(TOK_memset, "memset")
DEF(TOK___divdi3, "__divdi3")
DEF(TOK___moddi3, "__moddi3")
DEF(TOK___udivdi3, "__udivdi3")
DEF(TOK___umoddi3, "__umoddi3")
DEF(TOK___ashrdi3, "__ashrdi3")
DEF(TOK___lshrdi3, "__lshrdi3")
DEF(TOK___ashldi3, "__ashldi3")
DEF(TOK___floatundisf, "__floatundisf")
DEF(TOK___floatundidf, "__floatundidf")
# ifndef TCC_ARM_VFP
DEF(TOK___floatundixf, "__floatundixf")
DEF(TOK___fixunsxfdi, "__fixunsxfdi")
# endif
DEF(TOK___fixunssfdi, "__fixunssfdi")
DEF(TOK___fixunsdfdi, "__fixunsdfdi")
#endif
#if defined(TCC_TARGET_ARM)
#ifdef TCC_ARM_EABI
#if defined TCC_TARGET_ARM
# ifdef TCC_ARM_EABI
DEF(TOK_memcpy, "__aeabi_memcpy")
DEF(TOK_memcpy4, "__aeabi_memcpy4")
DEF(TOK_memcpy8, "__aeabi_memcpy8")
DEF(TOK_memmove, "__aeabi_memmove")
DEF(TOK_memset, "__aeabi_memset")
DEF(TOK___aeabi_ldivmod, "__aeabi_ldivmod")
DEF(TOK___aeabi_uldivmod, "__aeabi_uldivmod")
DEF(TOK___aeabi_idivmod, "__aeabi_idivmod")
DEF(TOK___aeabi_uidivmod, "__aeabi_uidivmod")
DEF(TOK___divsi3, "__aeabi_idiv")
@ -154,36 +206,6 @@
DEF(TOK___floatdidf, "__aeabi_l2d")
DEF(TOK___fixsfdi, "__aeabi_f2lz")
DEF(TOK___fixdfdi, "__aeabi_d2lz")
#else
DEF(TOK___modsi3, "__modsi3")
DEF(TOK___umodsi3, "__umodsi3")
DEF(TOK___divsi3, "__divsi3")
DEF(TOK___udivsi3, "__udivsi3")
DEF(TOK___floatdisf, "__floatdisf")
DEF(TOK___floatdidf, "__floatdidf")
#ifndef TCC_ARM_VFP
DEF(TOK___floatdixf, "__floatdixf")
DEF(TOK___fixunssfsi, "__fixunssfsi")
DEF(TOK___fixunsdfsi, "__fixunsdfsi")
DEF(TOK___fixunsxfsi, "__fixunsxfsi")
DEF(TOK___fixxfdi, "__fixxfdi")
#endif
DEF(TOK___fixsfdi, "__fixsfdi")
DEF(TOK___fixdfdi, "__fixdfdi")
#endif
#elif defined(TCC_TARGET_C67)
DEF(TOK__divi, "_divi")
DEF(TOK__divu, "_divu")
DEF(TOK__divf, "_divf")
DEF(TOK__divd, "_divd")
DEF(TOK__remi, "_remi")
DEF(TOK__remu, "_remu")
#endif
#ifdef TCC_TARGET_I386
DEF(TOK___tcc_int_fpu_control, "__tcc_int_fpu_control")
DEF(TOK___tcc_fpu_control, "__tcc_fpu_control")
#endif
#ifdef TCC_ARM_EABI
DEF(TOK___ashrdi3, "__aeabi_lasr")
DEF(TOK___lshrdi3, "__aeabi_llsr")
DEF(TOK___ashldi3, "__aeabi_llsl")
@ -191,22 +213,72 @@
DEF(TOK___floatundidf, "__aeabi_ul2d")
DEF(TOK___fixunssfdi, "__aeabi_f2ulz")
DEF(TOK___fixunsdfdi, "__aeabi_d2ulz")
#else
DEF(TOK___ashrdi3, "__ashrdi3")
DEF(TOK___lshrdi3, "__lshrdi3")
DEF(TOK___ashldi3, "__ashldi3")
DEF(TOK___floatundisf, "__floatundisf")
DEF(TOK___floatundidf, "__floatundidf")
#ifndef TCC_ARM_VFP
DEF(TOK___floatundixf, "__floatundixf")
DEF(TOK___fixunsxfdi, "__fixunsxfdi")
# else
DEF(TOK___modsi3, "__modsi3")
DEF(TOK___umodsi3, "__umodsi3")
DEF(TOK___divsi3, "__divsi3")
DEF(TOK___udivsi3, "__udivsi3")
DEF(TOK___floatdisf, "__floatdisf")
DEF(TOK___floatdidf, "__floatdidf")
# ifndef TCC_ARM_VFP
DEF(TOK___floatdixf, "__floatdixf")
DEF(TOK___fixunssfsi, "__fixunssfsi")
DEF(TOK___fixunsdfsi, "__fixunsdfsi")
DEF(TOK___fixunsxfsi, "__fixunsxfsi")
DEF(TOK___fixxfdi, "__fixxfdi")
# endif
DEF(TOK___fixsfdi, "__fixsfdi")
DEF(TOK___fixdfdi, "__fixdfdi")
# endif
#endif
DEF(TOK___fixunssfdi, "__fixunssfdi")
DEF(TOK___fixunsdfdi, "__fixunsdfdi")
#if defined TCC_TARGET_C67
DEF(TOK__divi, "_divi")
DEF(TOK__divu, "_divu")
DEF(TOK__divf, "_divf")
DEF(TOK__divd, "_divd")
DEF(TOK__remi, "_remi")
DEF(TOK__remu, "_remu")
#endif
#ifdef TCC_TARGET_PE
#if defined TCC_TARGET_I386
DEF(TOK___fixsfdi, "__fixsfdi")
DEF(TOK___fixdfdi, "__fixdfdi")
DEF(TOK___fixxfdi, "__fixxfdi")
#endif
#if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
DEF(TOK_alloca, "alloca")
#endif
#if defined TCC_TARGET_PE
DEF(TOK___chkstk, "__chkstk")
#endif
#ifdef TCC_TARGET_ARM64
DEF(TOK___arm64_clear_cache, "__arm64_clear_cache")
DEF(TOK___addtf3, "__addtf3")
DEF(TOK___subtf3, "__subtf3")
DEF(TOK___multf3, "__multf3")
DEF(TOK___divtf3, "__divtf3")
DEF(TOK___extendsftf2, "__extendsftf2")
DEF(TOK___extenddftf2, "__extenddftf2")
DEF(TOK___trunctfsf2, "__trunctfsf2")
DEF(TOK___trunctfdf2, "__trunctfdf2")
DEF(TOK___fixtfsi, "__fixtfsi")
DEF(TOK___fixtfdi, "__fixtfdi")
DEF(TOK___fixunstfsi, "__fixunstfsi")
DEF(TOK___fixunstfdi, "__fixunstfdi")
DEF(TOK___floatsitf, "__floatsitf")
DEF(TOK___floatditf, "__floatditf")
DEF(TOK___floatunsitf, "__floatunsitf")
DEF(TOK___floatunditf, "__floatunditf")
DEF(TOK___eqtf2, "__eqtf2")
DEF(TOK___netf2, "__netf2")
DEF(TOK___lttf2, "__lttf2")
DEF(TOK___letf2, "__letf2")
DEF(TOK___gttf2, "__gttf2")
DEF(TOK___getf2, "__getf2")
#endif
/* bound checking symbols */
#ifdef CONFIG_TCC_BCHECK
@ -217,50 +289,62 @@
DEF(TOK___bound_ptr_indir8, "__bound_ptr_indir8")
DEF(TOK___bound_ptr_indir12, "__bound_ptr_indir12")
DEF(TOK___bound_ptr_indir16, "__bound_ptr_indir16")
DEF(TOK___bound_main_arg, "__bound_main_arg")
DEF(TOK___bound_local_new, "__bound_local_new")
DEF(TOK___bound_local_delete, "__bound_local_delete")
#if 0
# ifdef TCC_TARGET_PE
DEF(TOK_malloc, "malloc")
DEF(TOK_free, "free")
DEF(TOK_realloc, "realloc")
DEF(TOK_memalign, "memalign")
DEF(TOK_calloc, "calloc")
#endif
DEF(TOK_memmove, "memmove")
# endif
DEF(TOK_strlen, "strlen")
DEF(TOK_strcpy, "strcpy")
DEF(TOK_alloca, "alloca")
#endif
/* Tiny Assembler */
DEF_ASM(byte)
DEF_ASM(word)
DEF_ASM(align)
DEF_ASM(skip)
DEF_ASM(space)
DEF_ASM(string)
DEF_ASM(asciz)
DEF_ASM(ascii)
DEF_ASM(globl)
DEF_ASM(global)
DEF_ASM(text)
DEF_ASM(data)
DEF_ASM(bss)
DEF_ASM(previous)
DEF_ASM(fill)
DEF_ASM(org)
DEF_ASM(quad)
DEF_ASMDIR(byte) /* must be first directive */
DEF_ASMDIR(word)
DEF_ASMDIR(align)
DEF_ASMDIR(balign)
DEF_ASMDIR(p2align)
DEF_ASMDIR(set)
DEF_ASMDIR(skip)
DEF_ASMDIR(space)
DEF_ASMDIR(string)
DEF_ASMDIR(asciz)
DEF_ASMDIR(ascii)
DEF_ASMDIR(file)
DEF_ASMDIR(globl)
DEF_ASMDIR(global)
DEF_ASMDIR(weak)
DEF_ASMDIR(hidden)
DEF_ASMDIR(ident)
DEF_ASMDIR(size)
DEF_ASMDIR(type)
DEF_ASMDIR(text)
DEF_ASMDIR(data)
DEF_ASMDIR(bss)
DEF_ASMDIR(previous)
DEF_ASMDIR(pushsection)
DEF_ASMDIR(popsection)
DEF_ASMDIR(fill)
DEF_ASMDIR(rept)
DEF_ASMDIR(endr)
DEF_ASMDIR(org)
DEF_ASMDIR(quad)
#if defined(TCC_TARGET_I386)
DEF_ASM(code16)
DEF_ASM(code32)
DEF_ASMDIR(code16)
DEF_ASMDIR(code32)
#elif defined(TCC_TARGET_X86_64)
DEF_ASM(code64)
DEF_ASMDIR(code64)
#endif
DEF_ASMDIR(short)
DEF_ASMDIR(long)
DEF_ASMDIR(int)
DEF_ASMDIR(section) /* must be last directive */
#ifdef TCC_TARGET_I386
#if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
#include "i386-tok.h"
#elif TCC_TARGET_X86_64
#include "x86_64-tok.h"
#endif

529
tcctools.c 100644
View File

@ -0,0 +1,529 @@
/* -------------------------------------------------------------- */
/*
* TCC - Tiny C Compiler
*
* tcctools.c - extra tools and and -m32/64 support
*
*/
/* -------------------------------------------------------------- */
/*
* This program is for making libtcc1.a without ar
* tiny_libmaker - tiny elf lib maker
* usage: tiny_libmaker [lib] files...
* Copyright (c) 2007 Timppa
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "tcc.h"
//#define ARMAG "!<arch>\n"
#define ARFMAG "`\n"
typedef struct {
char ar_name[16];
char ar_date[12];
char ar_uid[6];
char ar_gid[6];
char ar_mode[8];
char ar_size[10];
char ar_fmag[2];
} ArHdr;
static unsigned long le2belong(unsigned long ul) {
return ((ul & 0xFF0000)>>8)+((ul & 0xFF000000)>>24) +
((ul & 0xFF)<<24)+((ul & 0xFF00)<<8);
}
/* Returns 1 if s contains any of the chars of list, else 0 */
static int contains_any(const char *s, const char *list) {
const char *l;
for (; *s; s++) {
for (l = list; *l; l++) {
if (*s == *l)
return 1;
}
}
return 0;
}
static int ar_usage(int ret) {
fprintf(stderr, "usage: tcc -ar [rcsv] lib file...\n");
fprintf(stderr, "create library ([abdioptxN] not supported).\n");
return ret;
}
ST_FUNC int tcc_tool_ar(TCCState *s1, int argc, char **argv)
{
static ArHdr arhdr = {
"/ ",
" ",
"0 ",
"0 ",
"0 ",
" ",
ARFMAG
};
static ArHdr arhdro = {
" ",
" ",
"0 ",
"0 ",
"0 ",
" ",
ARFMAG
};
FILE *fi, *fh = NULL, *fo = NULL;
ElfW(Ehdr) *ehdr;
ElfW(Shdr) *shdr;
ElfW(Sym) *sym;
int i, fsize, i_lib, i_obj;
char *buf, *shstr, *symtab = NULL, *strtab = NULL;
int symtabsize = 0;//, strtabsize = 0;
char *anames = NULL;
int *afpos = NULL;
int istrlen, strpos = 0, fpos = 0, funccnt = 0, funcmax, hofs;
char tfile[260], stmp[20];
char *file, *name;
int ret = 2;
const char *ops_conflict = "habdioptxN"; // unsupported but destructive if ignored.
int verbose = 0;
i_lib = 0; i_obj = 0; // will hold the index of the lib and first obj
for (i = 1; i < argc; i++) {
const char *a = argv[i];
if (*a == '-' && strstr(a, "."))
ret = 1; // -x.y is always invalid (same as gnu ar)
if ((*a == '-') || (i == 1 && !strstr(a, "."))) { // options argument
if (contains_any(a, ops_conflict))
ret = 1;
if (strstr(a, "v"))
verbose = 1;
} else { // lib or obj files: don't abort - keep validating all args.
if (!i_lib) // first file is the lib
i_lib = i;
else if (!i_obj) // second file is the first obj
i_obj = i;
}
}
if (!i_obj) // i_obj implies also i_lib. we require both.
ret = 1;
if (ret == 1)
return ar_usage(ret);
if ((fh = fopen(argv[i_lib], "wb")) == NULL)
{
fprintf(stderr, "tcc: ar: can't open file %s \n", argv[i_lib]);
goto the_end;
}
sprintf(tfile, "%s.tmp", argv[i_lib]);
if ((fo = fopen(tfile, "wb+")) == NULL)
{
fprintf(stderr, "tcc: ar: can't create temporary file %s\n", tfile);
goto the_end;
}
funcmax = 250;
afpos = tcc_realloc(NULL, funcmax * sizeof *afpos); // 250 func
memcpy(&arhdro.ar_mode, "100666", 6);
// i_obj = first input object file
while (i_obj < argc)
{
if (*argv[i_obj] == '-') { // by now, all options start with '-'
i_obj++;
continue;
}
if ((fi = fopen(argv[i_obj], "rb")) == NULL) {
fprintf(stderr, "tcc: ar: can't open file %s \n", argv[i_obj]);
goto the_end;
}
if (verbose)
printf("a - %s\n", argv[i_obj]);
fseek(fi, 0, SEEK_END);
fsize = ftell(fi);
fseek(fi, 0, SEEK_SET);
buf = tcc_malloc(fsize + 1);
fread(buf, fsize, 1, fi);
fclose(fi);
// elf header
ehdr = (ElfW(Ehdr) *)buf;
if (ehdr->e_ident[4] != ELFCLASSW)
{
fprintf(stderr, "tcc: ar: Unsupported Elf Class: %s\n", argv[i_obj]);
goto the_end;
}
shdr = (ElfW(Shdr) *) (buf + ehdr->e_shoff + ehdr->e_shstrndx * ehdr->e_shentsize);
shstr = (char *)(buf + shdr->sh_offset);
for (i = 0; i < ehdr->e_shnum; i++)
{
shdr = (ElfW(Shdr) *) (buf + ehdr->e_shoff + i * ehdr->e_shentsize);
if (!shdr->sh_offset)
continue;
if (shdr->sh_type == SHT_SYMTAB)
{
symtab = (char *)(buf + shdr->sh_offset);
symtabsize = shdr->sh_size;
}
if (shdr->sh_type == SHT_STRTAB)
{
if (!strcmp(shstr + shdr->sh_name, ".strtab"))
{
strtab = (char *)(buf + shdr->sh_offset);
//strtabsize = shdr->sh_size;
}
}
}
if (symtab && symtabsize)
{
int nsym = symtabsize / sizeof(ElfW(Sym));
//printf("symtab: info size shndx name\n");
for (i = 1; i < nsym; i++)
{
sym = (ElfW(Sym) *) (symtab + i * sizeof(ElfW(Sym)));
if (sym->st_shndx &&
(sym->st_info == 0x10
|| sym->st_info == 0x11
|| sym->st_info == 0x12
)) {
//printf("symtab: %2Xh %4Xh %2Xh %s\n", sym->st_info, sym->st_size, sym->st_shndx, strtab + sym->st_name);
istrlen = strlen(strtab + sym->st_name)+1;
anames = tcc_realloc(anames, strpos+istrlen);
strcpy(anames + strpos, strtab + sym->st_name);
strpos += istrlen;
if (++funccnt >= funcmax) {
funcmax += 250;
afpos = tcc_realloc(afpos, funcmax * sizeof *afpos); // 250 func more
}
afpos[funccnt] = fpos;
}
}
}
file = argv[i_obj];
for (name = strchr(file, 0);
name > file && name[-1] != '/' && name[-1] != '\\';
--name);
istrlen = strlen(name);
if (istrlen >= sizeof(arhdro.ar_name))
istrlen = sizeof(arhdro.ar_name) - 1;
memset(arhdro.ar_name, ' ', sizeof(arhdro.ar_name));
memcpy(arhdro.ar_name, name, istrlen);
arhdro.ar_name[istrlen] = '/';
sprintf(stmp, "%-10d", fsize);
memcpy(&arhdro.ar_size, stmp, 10);
fwrite(&arhdro, sizeof(arhdro), 1, fo);
fwrite(buf, fsize, 1, fo);
tcc_free(buf);
i_obj++;
fpos += (fsize + sizeof(arhdro));
}
hofs = 8 + sizeof(arhdr) + strpos + (funccnt+1) * sizeof(int);
fpos = 0;
if ((hofs & 1)) // align
hofs++, fpos = 1;
// write header
fwrite("!<arch>\n", 8, 1, fh);
sprintf(stmp, "%-10d", (int)(strpos + (funccnt+1) * sizeof(int)));
memcpy(&arhdr.ar_size, stmp, 10);
fwrite(&arhdr, sizeof(arhdr), 1, fh);
afpos[0] = le2belong(funccnt);
for (i=1; i<=funccnt; i++)
afpos[i] = le2belong(afpos[i] + hofs);
fwrite(afpos, (funccnt+1) * sizeof(int), 1, fh);
fwrite(anames, strpos, 1, fh);
if (fpos)
fwrite("", 1, 1, fh);
// write objects
fseek(fo, 0, SEEK_END);
fsize = ftell(fo);
fseek(fo, 0, SEEK_SET);
buf = tcc_malloc(fsize + 1);
fread(buf, fsize, 1, fo);
fwrite(buf, fsize, 1, fh);
tcc_free(buf);
ret = 0;
the_end:
if (anames)
tcc_free(anames);
if (afpos)
tcc_free(afpos);
if (fh)
fclose(fh);
if (fo)
fclose(fo), remove(tfile);
return ret;
}
/* -------------------------------------------------------------- */
/*
* tiny_impdef creates an export definition file (.def) from a dll
* on MS-Windows. Usage: tiny_impdef library.dll [-o outputfile]"
*
* Copyright (c) 2005,2007 grischka
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifdef TCC_TARGET_PE
ST_FUNC int tcc_tool_impdef(TCCState *s1, int argc, char **argv)
{
int ret, v, i;
char infile[260];
char outfile[260];
const char *file;
char *p, *q;
FILE *fp, *op;
#ifdef _WIN32
char path[260];
#endif
infile[0] = outfile[0] = 0;
fp = op = NULL;
ret = 1;
p = NULL;
v = 0;
for (i = 1; i < argc; ++i) {
const char *a = argv[i];
if ('-' == a[0]) {
if (0 == strcmp(a, "-v")) {
v = 1;
} else if (0 == strcmp(a, "-o")) {
if (++i == argc)
goto usage;
strcpy(outfile, argv[i]);
} else
goto usage;
} else if (0 == infile[0])
strcpy(infile, a);
else
goto usage;
}
if (0 == infile[0]) {
usage:
fprintf(stderr,
"usage: tcc -impdef library.dll [-v] [-o outputfile]\n"
"create export definition file (.def) from dll\n"
);
goto the_end;
}
if (0 == outfile[0]) {
strcpy(outfile, tcc_basename(infile));
q = strrchr(outfile, '.');
if (NULL == q)
q = strchr(outfile, 0);
strcpy(q, ".def");
}
file = infile;
#ifdef _WIN32
if (SearchPath(NULL, file, ".dll", sizeof path, path, NULL))
file = path;
#endif
ret = tcc_get_dllexports(file, &p);
if (ret || !p) {
fprintf(stderr, "tcc: impdef: %s '%s'\n",
ret == -1 ? "can't find file" :
ret == 1 ? "can't read symbols" :
ret == 0 ? "no symbols found in" :
"unknown file type", file);
ret = 1;
goto the_end;
}
if (v)
printf("-> %s\n", file);
op = fopen(outfile, "wb");
if (NULL == op) {
fprintf(stderr, "tcc: impdef: could not create output file: %s\n", outfile);
goto the_end;
}
fprintf(op, "LIBRARY %s\n\nEXPORTS\n", tcc_basename(file));
for (q = p, i = 0; *q; ++i) {
fprintf(op, "%s\n", q);
q += strlen(q) + 1;
}
if (v)
printf("<- %s (%d symbol%s)\n", outfile, i, &"s"[i<2]);
ret = 0;
the_end:
/* cannot free memory received from tcc_get_dllexports
if it came from a dll */
/* if (p)
tcc_free(p); */
if (fp)
fclose(fp);
if (op)
fclose(op);
return ret;
}
#endif /* TCC_TARGET_PE */
/* -------------------------------------------------------------- */
/*
* TCC - Tiny C Compiler
*
* Copyright (c) 2001-2004 Fabrice Bellard
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* re-execute the i386/x86_64 cross-compilers with tcc -m32/-m64: */
#if !defined TCC_TARGET_I386 && !defined TCC_TARGET_X86_64
ST_FUNC void tcc_tool_cross(TCCState *s, char **argv, int option)
{
tcc_error("-m%d not implemented.", option);
}
#else
#ifdef _WIN32
#include <process.h>
static char *str_replace(const char *str, const char *p, const char *r)
{
const char *s, *s0;
char *d, *d0;
int sl, pl, rl;
sl = strlen(str);
pl = strlen(p);
rl = strlen(r);
for (d0 = NULL;; d0 = tcc_malloc(sl + 1)) {
for (d = d0, s = str; s0 = s, s = strstr(s, p), s; s += pl) {
if (d) {
memcpy(d, s0, sl = s - s0), d += sl;
memcpy(d, r, rl), d += rl;
} else
sl += rl - pl;
}
if (d) {
strcpy(d, s0);
return d0;
}
}
}
static int execvp_win32(const char *prog, char **argv)
{
int ret; char **p;
/* replace all " by \" */
for (p = argv; *p; ++p)
if (strchr(*p, '"'))
*p = str_replace(*p, "\"", "\\\"");
ret = _spawnvp(P_NOWAIT, prog, (const char *const*)argv);
if (-1 == ret)
return ret;
_cwait(&ret, ret, WAIT_CHILD);
exit(ret);
}
#define execvp execvp_win32
#endif /* _WIN32 */
ST_FUNC void tcc_tool_cross(TCCState *s, char **argv, int target)
{
tcc_error("-m%d not implemented.", target);
}
#endif /* TCC_TARGET_I386 && TCC_TARGET_X86_64 */
/* -------------------------------------------------------------- */
/* enable commandline wildcard expansion (tcc -o x.exe *.c) */
#ifdef _WIN32
int _CRT_glob = 1;
#ifndef _CRT_glob
int _dowildcard = 1;
#endif
#endif
/* -------------------------------------------------------------- */
/* generate xxx.d file */
ST_FUNC void gen_makedeps(TCCState *s, const char *target, const char *filename)
{
FILE *depout;
char buf[1024];
int i;
if (!filename) {
/* compute filename automatically: dir/file.o -> dir/file.d */
snprintf(buf, sizeof buf, "%.*s.d",
(int)(tcc_fileextension(target) - target), target);
filename = buf;
}
if (s->verbose)
printf("<- %s\n", filename);
/* XXX return err codes instead of error() ? */
depout = fopen(filename, "w");
if (!depout)
tcc_error("could not open '%s'", filename);
fprintf(depout, "%s: \\\n", target);
for (i=0; i<s->nb_target_deps; ++i)
fprintf(depout, " %s \\\n", s->target_deps[i]);
fprintf(depout, "\n");
fclose(depout);
}
/* -------------------------------------------------------------- */

13
tests/42test.h 100644
View File

@ -0,0 +1,13 @@
/* This file is to test compute #include directives. It's named so
that it starts with a pre-processing number which isn't a valid
number (42test.h). Including this must work. */
#ifndef INC42_FIRST
int have_included_42test_h;
#define INC42_FIRST
#elif !defined INC42_SECOND
#define INC42_SECOND
int have_included_42test_h_second;
#else
#define INC42_THIRD
int have_included_42test_h_third;
#endif

View File

@ -2,83 +2,151 @@
# Tiny C Compiler Makefile - tests
#
# what tests to run
TESTS = libtest test3
# these should work too
# TESTS += test1 test2 speedtest btest
# these don't work as they should
# TESTS += test4 asmtest
TOP = ..
include $(TOP)/Makefile
VPATH = $(TOPSRC)/tests $(TOPSRC) $(TOP)
CFLAGS := $(filter-out -W% -g% -O%,$(CFLAGS)) -I$(TOPSRC) $(LDFLAGS)
# run local version of tcc with local libraries and includes
TCC = ../tcc -B..
RUN_TCC = $(NATIVE_TARGET) -run ../tcc.c -B..
DISAS=objdump -d
# what tests to run
TESTS = \
hello-exe \
hello-run \
libtest \
test3 \
memtest \
dlltest \
abitest \
asm-c-connect-test \
vla_test-run \
cross-test \
tests2-dir \
pp-dir
all test : $(TESTS)
BTESTS = test1b test3b btest
# make sure that tcc exists
$(TESTS) : ../tcc
# test4 -- problem with -static
# asmtest / asmtest2 -- minor differences with gcc
# btest -- works on i386 (including win32)
../tcc ../libtcc.a :
$(MAKE) -C ..
# bounds-checking is supported only on i386
ifneq ($(ARCH),i386)
TESTS := $(filter-out $(BTESTS),$(TESTS))
endif
ifdef CONFIG_WIN32
TESTS := $(filter-out $(BTESTS),$(TESTS))
endif
ifdef CONFIG_OSX # -run only
TESTS := hello-run libtest tests2-dir pp-dir
endif
ifeq (,$(filter arm64 i386 x86_64,$(ARCH)))
TESTS := $(filter-out vla_test-run,$(TESTS))
endif
ifeq ($(CONFIG_arm_eabi),yes)
TESTS := $(filter-out test3,$(TESTS))
endif
ifeq (,$(filter i386 x86_64,$(ARCH)))
TESTS := $(filter-out dlltest asm-c-connect-test,$(TESTS))
endif
ifndef CONFIG_cross
TESTS := $(filter-out cross-%,$(TESTS))
endif
ifeq ($(OS),Windows_NT) # for libtcc_test to find libtcc.dll
PATH := $(CURDIR)/$(TOP)$(if $(findstring :\,$(PATH)),;,:)$(PATH)
endif
RUN_TCC = $(NATIVE_DEFINES) -run $(TOPSRC)/tcc.c $(TCCFLAGS)
DISAS = objdump -d
DUMPTCC = (set -x; $(TOP)/tcc -vv; ldd $(TOP)/tcc; exit 1)
all test : clean-s $(TESTS)
hello-exe: ../examples/ex1.c
@echo ------------ $@ ------------
$(TCC) $< -o hello$(EXESUF) && ./hello$(EXESUF) || $(DUMPTCC)
hello-run: ../examples/ex1.c
@echo ------------ $@ ------------
$(TCC) -run $< || $(DUMPTCC)
# libtcc test
libtest: libtcc_test$(EXESUF)
@echo ------------ $@ ------------
./libtcc_test lib_path=..
./libtcc_test$(EXESUF) $(TCCFLAGS)
libtcc_test$(EXESUF): libtcc_test.c ../libtcc.a
$(CC) -o $@ $^ -I.. $(CFLAGS) $(LIBS)
libtcc_test$(EXESUF): libtcc_test.c $(LIBTCC)
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
# test.ref - generate using gcc
%-dir:
@echo ------------ $@ ------------
$(MAKE) -k -C $*
# test.ref - generate using cc
test.ref: tcctest.c
cp -u ../include/tcclib.h .
$(CC) -o tcctest.gcc $< -I. -w $(CFLAGS)
$(CC) -o tcctest.gcc $< $(NATIVE_DEFINES) $(CFLAGS) -w -O0 -std=gnu99 -fno-omit-frame-pointer
./tcctest.gcc > $@
# auto test
test1: test.ref
test1 test1b: tcctest.c test.ref
@echo ------------ $@ ------------
$(TCC) -run tcctest.c > test.out1
@if diff -u test.ref test.out1 ; then echo "Auto Test OK"; fi
$(TCC) -run $< > test.out1
@diff -u test.ref test.out1 && echo "Auto Test OK"
# iterated test2 (compile tcc then compile tcctest.c !)
test2: test.ref
test2 test2b: tcctest.c test.ref
@echo ------------ $@ ------------
$(TCC) $(RUN_TCC) $(RUN_TCC) -run tcctest.c > test.out2
@if diff -u test.ref test.out2 ; then echo "Auto Test2 OK"; fi
$(TCC) $(RUN_TCC) $(RUN_TCC) -run $< > test.out2
@diff -u test.ref test.out2 && echo "Auto Test2 OK"
# iterated test3 (compile tcc then compile tcc then compile tcctest.c !)
test3: test.ref
test3 test3b: tcctest.c test.ref
@echo ------------ $@ ------------
$(TCC) $(RUN_TCC) $(RUN_TCC) $(RUN_TCC) -run tcctest.c > test.out3
@if diff -u test.ref test.out3 ; then echo "Auto Test3 OK"; fi
$(TCC) $(RUN_TCC) $(RUN_TCC) $(RUN_TCC) -run $< > test.out3
@diff -u test.ref test.out3 && echo "Auto Test3 OK"
test%b : TCCFLAGS += -b
# binary output test
test4: test.ref
test4: tcctest.c test.ref
@echo ------------ $@ ------------
# dynamic output
$(TCC) -o tcctest1 tcctest.c
./tcctest1 > test1.out
@if diff -u test.ref test1.out ; then echo "Dynamic Auto Test OK"; fi
# object + link output
$(TCC) -c -o tcctest3.o tcctest.c
$(TCC) -c -o tcctest3.o $<
$(TCC) -o tcctest3 tcctest3.o
./tcctest3 > test3.out
@if diff -u test.ref test3.out ; then echo "Object Auto Test OK"; fi
# static output
$(TCC) -static -o tcctest2 tcctest.c
./tcctest2 > test2.out
@if diff -u test.ref test2.out ; then echo "Static Auto Test OK"; fi
# dynamic output
$(TCC) -o tcctest1 $<
./tcctest1 > test1.out
@if diff -u test.ref test1.out ; then echo "Dynamic Auto Test OK"; fi
# dynamic output + bound check
$(TCC) -b -o tcctest4 tcctest.c
$(TCC) -b -o tcctest4 $<
./tcctest4 > test4.out
@if diff -u test.ref test4.out ; then echo "BCheck Auto Test OK"; fi
# static output
$(TCC) -static -o tcctest2 $<
./tcctest2 > test2.out
@if diff -u test.ref test2.out ; then echo "Static Auto Test OK"; fi
# use tcc to create libtcc.so/.dll and the tcc(.exe) frontend and run them
dlltest:
@echo ------------ $@ ------------
$(TCC) $(NATIVE_DEFINES) -DLIBTCC_AS_DLL $(TOPSRC)/libtcc.c $(LIBS) -shared -o libtcc2$(DLLSUF)
$(TCC) $(NATIVE_DEFINES) -DONE_SOURCE=0 $(TOPSRC)/tcc.c libtcc2$(DLLSUF) $(LIBS) -Wl,-rpath=. -o tcc2$(EXESUF)
./tcc2$(EXESUF) $(TCCFLAGS) $(RUN_TCC) -run $(TOPSRC)/examples/ex1.c
ifndef CONFIG_WIN32
@echo ------------ $@ with PIC ------------
$(CC) $(CFLAGS) -fPIC $(NATIVE_DEFINES) -DLIBTCC_AS_DLL -c $(TOPSRC)/libtcc.c
$(TCC) libtcc.o $(LIBS) -shared -o libtcc2$(DLLSUF)
$(TCC) $(NATIVE_DEFINES) -DONE_SOURCE=0 $(TOPSRC)/tcc.c libtcc2$(DLLSUF) $(LIBS) -Wl,-rpath=. -o tcc2$(EXESUF)
./tcc2$(EXESUF) $(TCCFLAGS) $(RUN_TCC) -run $(TOPSRC)/examples/ex1.c
endif
@rm tcc2$(EXESUF) libtcc2$(DLLSUF)
memtest:
@echo ------------ $@ ------------
$(CC) $(CFLAGS) $(NATIVE_DEFINES) -DMEM_DEBUG=2 $(TOPSRC)/tcc.c $(LIBS) -o memtest-tcc$(EXESUF)
./memtest-tcc$(EXESUF) $(TCCFLAGS) $(NATIVE_DEFINES) $(TOPSRC)/tcc.c $(LIBS)
./memtest-tcc$(EXESUF) $(TCCFLAGS) $(NATIVE_DEFINES) -run $(TOPSRC)/tcc.c $(TCCFLAGS) $(TOPSRC)/tests/tcctest.c
# memory and bound check auto test
BOUNDS_OK = 1 4 8 10 14
@ -88,15 +156,15 @@ btest: boundtest.c
@echo ------------ $@ ------------
@for i in $(BOUNDS_OK); do \
echo ; echo --- boundtest $$i ---; \
if $(TCC) -b -run boundtest.c $$i ; then \
echo succeded as expected; \
if $(TCC) -b -run $< $$i ; then \
echo succeeded as expected; \
else\
echo Failed positive test $$i ; exit 1 ; \
fi ;\
done ;\
for i in $(BOUNDS_FAIL); do \
echo ; echo --- boundtest $$i ---; \
if $(TCC) -b -run boundtest.c $$i ; then \
if $(TCC) -b -run $< $$i ; then \
echo Failed negative test $$i ; exit 1 ;\
else\
echo failed as expected; \
@ -108,11 +176,18 @@ btest: boundtest.c
speedtest: ex2 ex3
@echo ------------ $@ ------------
time ./ex2 1238 2 3 4 10 13 4
time $(TCC) -run ../examples/ex2.c 1238 2 3 4 10 13 4
time $(TCC) -run $(TOPSRC)/examples/ex2.c 1238 2 3 4 10 13 4
time ./ex3 35
time $(TCC) -run ../examples/ex3.c 35
time $(TCC) -run $(TOPSRC)/examples/ex3.c 35
ex%: ../examples/ex%.c
weaktest: tcctest.c test.ref
$(TCC) -c $< -o weaktest.tcc.o
$(CC) -c $< -o weaktest.gcc.o $(NATIVE_DEFINES) $(CFLAGS) -w -O0 -std=gnu99 -fno-omit-frame-pointer
objdump -t weaktest.tcc.o | grep ' w ' | sed -e 's/.* \([a-zA-Z0-9_]*\)$$/\1/' | LC_ALL=C sort > weaktest.tcc.o.txt
objdump -t weaktest.gcc.o | grep ' w ' | sed -e 's/.* \([a-zA-Z0-9_]*\)$$/\1/' | LC_ALL=C sort > weaktest.gcc.o.txt
diff weaktest.gcc.o.txt weaktest.tcc.o.txt && echo "Weak Auto Test OK"
ex%: $(TOPSRC)/examples/ex%.c
$(CC) -o $@ $< $(CFLAGS)
# tiny assembler testing
@ -120,12 +195,71 @@ asmtest.ref: asmtest.S
$(CC) -Wa,-W -o asmtest.ref.o -c asmtest.S
objdump -D asmtest.ref.o > asmtest.ref
asmtest: asmtest.ref
asmtest asmtest2: asmtest.ref
@echo ------------ $@ ------------
$(TCC) -c asmtest.S
$(TCC) $(MAYBE_RUN_TCC) -c asmtest.S
objdump -D asmtest.o > asmtest.out
@if diff -u --ignore-matching-lines="file format" asmtest.ref asmtest.out ; then echo "ASM Auto Test OK"; fi
# test assembler with tcc compiled by itself
asmtest2: MAYBE_RUN_TCC = $(RUN_TCC)
# Check that code generated by libtcc is binary compatible with
# that generated by CC
abitest-cc$(EXESUF): abitest.c $(LIBTCC)
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) -w
abitest-tcc$(EXESUF): abitest.c libtcc.c
$(TCC) -o $@ $^ $(NATIVE_DEFINES) $(LIBS)
ABITESTS := abitest-cc$(EXESUF)
ifneq ($(CONFIG_arm_eabi),yes) # not ARM soft-float
ABITESTS += abitest-tcc$(EXESUF)
endif
abitest: $(ABITESTS)
@echo ------------ $@ ------------
./abitest-cc$(EXESUF) $(TCCFLAGS)
ifneq ($(CONFIG_arm_eabi),yes) # not ARM soft-float
./abitest-tcc$(EXESUF) $(TCCFLAGS)
endif
vla_test$(EXESUF): vla_test.c
$(TCC) -o $@ $^
vla_test-run: vla_test$(EXESUF)
@echo ------------ $@ ------------
./vla_test$(EXESUF)
asm-c-connect$(EXESUF): asm-c-connect-1.c asm-c-connect-2.c
$(TCC) -o $@ $^
asm-c-connect-%.o: asm-c-connect-%.c
$(TCC) -c -o $@ $<
asm-c-connect-sep$(EXESUF): asm-c-connect-1.o asm-c-connect-2.o
$(TCC) -o $@ $^
asm-c-connect-test: asm-c-connect$(EXESUF) asm-c-connect-sep$(EXESUF)
@echo ------------ $@ ------------
./asm-c-connect$(EXESUF) > asm-c-connect.out1 && cat asm-c-connect.out1
./asm-c-connect-sep$(EXESUF) > asm-c-connect.out2 && cat asm-c-connect.out2
@diff -u asm-c-connect.out1 asm-c-connect.out2 && echo "ok"
cross-test :
@echo ------------ $@ ------------
$(TOP)/i386-tcc$(EXESUF) $(TCCFLAGS-unx) -c $(TOPSRC)/examples/ex3.c && echo "ok"
$(TOP)/i386-win32-tcc$(EXESUF) $(TCCFLAGS-win) $(TOPSRC)/examples/ex3.c && echo "ok"
$(TOP)/x86_64-tcc$(EXESUF) $(TCCFLAGS-unx) -c $(TOPSRC)/examples/ex3.c && echo "ok"
$(TOP)/x86_64-win32-tcc$(EXESUF) $(TCCFLAGS-win) $(TOPSRC)/examples/ex3.c && echo "ok"
$(TOP)/arm-tcc$(EXESUF) $(TCCFLAGS-unx) -c $(TOPSRC)/examples/ex3.c && echo "ok"
$(TOP)/arm-wince-tcc$(EXESUF) $(TCCFLAGS-win) -c $(TOPSRC)/examples/ex3.c && echo "ok"
$(TOP)/arm64-tcc$(EXESUF) $(TCCFLAGS-unx) -c $(TOPSRC)/examples/ex3.c && echo "ok"
$(TOP)/c67-tcc$(EXESUF) $(TCCFLAGS-unx) -c $(TOPSRC)/examples/ex3.c && echo "ok"
$(TOP)/i386-win32-tcc$(EXESUF) $(TCCFLAGS-win) $(TOPSRC)/win32/examples/hello_win.c && echo "ok"
$(TOP)/x86_64-win32-tcc$(EXESUF) $(TCCFLAGS-win) $(TOPSRC)/win32/examples/hello_win.c && echo "ok"
$(TOP)/arm-wince-tcc$(EXESUF) $(TCCFLAGS-win) -c $(TOPSRC)/win32/examples/hello_win.c && echo "ok"
# targets for development
%.bin: %.c tcc
$(TCC) -g -o $@ $<
@ -143,5 +277,13 @@ cache: tcc_g
# clean
clean:
rm -vf *~ *.o *.a *.bin *.i *.ref *.out *.out? *.gcc \
tcctest[1234] ex? libtcc_test$(EXESUF) tcc_g tcclib.h
rm -f *~ *.o *.a *.bin *.i *.ref *.out *.out? *.out?b *.cc *.gcc
rm -f *-cc *-gcc *-tcc *.exe hello libtcc_test vla_test tcctest[1234]
rm -f asm-c-connect$(EXESUF)
rm -f ex? tcc_g weaktest.*.txt *.def
@$(MAKE) -C tests2 $@
@$(MAKE) -C pp $@
# silent clean, used before running tests
clean-s:
@$(MAKE) -s --no-print-directory clean

691
tests/abitest.c 100644
View File

@ -0,0 +1,691 @@
#include <libtcc.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
// MinGW has 80-bit rather than 64-bit long double which isn't compatible with TCC or MSVC
#if defined(_WIN32) && defined(__GNUC__)
#define LONG_DOUBLE double
#define LONG_DOUBLE_LITERAL(x) x
#else
#define LONG_DOUBLE long double
#define LONG_DOUBLE_LITERAL(x) x ## L
#endif
static int g_argc;
static char **g_argv;
static void set_options(TCCState *s, int argc, char **argv)
{
int i;
for (i = 1; i < argc; ++i) {
char *a = argv[i];
if (a[0] == '-') {
if (a[1] == 'B')
tcc_set_lib_path(s, a+2);
else if (a[1] == 'I')
tcc_add_include_path(s, a+2);
else if (a[1] == 'L')
tcc_add_library_path(s, a+2);
}
}
}
typedef int (*callback_type) (void*);
/*
* Compile source code and call a callback with a pointer to the symbol "f".
*/
static int run_callback(const char *src, callback_type callback) {
TCCState *s;
int result;
void *ptr;
s = tcc_new();
if (!s)
return -1;
set_options(s, g_argc, g_argv);
if (tcc_set_output_type(s, TCC_OUTPUT_MEMORY) == -1)
return -1;
if (tcc_compile_string(s, src) == -1)
return -1;
if (tcc_relocate(s, TCC_RELOCATE_AUTO) == -1)
return -1;
ptr = tcc_get_symbol(s, "f");
if (!ptr)
return -1;
result = callback(ptr);
tcc_delete(s);
return result;
}
#define STR2(x) #x
#define STR(x) STR2(x)
#define RET_PRIMITIVE_TEST(name, type, val) \
static int ret_ ## name ## _test_callback(void *ptr) { \
type (*callback) (type) = (type(*)(type))ptr; \
type x = val; \
type y = callback(x); \
return (y == x+x) ? 0 : -1; \
} \
\
static int ret_ ## name ## _test(void) { \
const char *src = STR(type) " f(" STR(type) " x) {return x+x;}"; \
return run_callback(src, ret_ ## name ## _test_callback); \
}
RET_PRIMITIVE_TEST(int, int, 70000)
RET_PRIMITIVE_TEST(longlong, long long, 4333369356528LL)
RET_PRIMITIVE_TEST(float, float, 63.0)
RET_PRIMITIVE_TEST(double, double, 14789798.0)
RET_PRIMITIVE_TEST(longdouble, LONG_DOUBLE, LONG_DOUBLE_LITERAL(378943892.0))
/*
* ret_2float_test:
*
* On x86-64, a struct with 2 floats should be packed into a single
* SSE register (VT_DOUBLE is used for this purpose).
*/
typedef struct ret_2float_test_type_s {float x, y;} ret_2float_test_type;
typedef ret_2float_test_type (*ret_2float_test_function_type) (ret_2float_test_type);
static int ret_2float_test_callback(void *ptr) {
ret_2float_test_function_type f = (ret_2float_test_function_type)ptr;
ret_2float_test_type a = {10, 35};
ret_2float_test_type r;
r = f(a);
return ((r.x == a.x*5) && (r.y == a.y*3)) ? 0 : -1;
}
static int ret_2float_test(void) {
const char *src =
"typedef struct ret_2float_test_type_s {float x, y;} ret_2float_test_type;"
"ret_2float_test_type f(ret_2float_test_type a) {\n"
" ret_2float_test_type r = {a.x*5, a.y*3};\n"
" return r;\n"
"}\n";
return run_callback(src, ret_2float_test_callback);
}
/*
* ret_2double_test:
*
* On x86-64, a struct with 2 doubles should be passed in two SSE
* registers.
*/
typedef struct ret_2double_test_type_s {double x, y;} ret_2double_test_type;
typedef ret_2double_test_type (*ret_2double_test_function_type) (ret_2double_test_type);
static int ret_2double_test_callback(void *ptr) {
ret_2double_test_function_type f = (ret_2double_test_function_type)ptr;
ret_2double_test_type a = {10, 35};
ret_2double_test_type r;
r = f(a);
return ((r.x == a.x*5) && (r.y == a.y*3)) ? 0 : -1;
}
static int ret_2double_test(void) {
const char *src =
"typedef struct ret_2double_test_type_s {double x, y;} ret_2double_test_type;"
"ret_2double_test_type f(ret_2double_test_type a) {\n"
" ret_2double_test_type r = {a.x*5, a.y*3};\n"
" return r;\n"
"}\n";
return run_callback(src, ret_2double_test_callback);
}
/*
* ret_8plus2double_test:
*
* This catches a corner case in the x86_64 ABI code: the first 7
* arguments fit into registers, the 8th doesn't, but the 9th argument
* fits into the 8th XMM register.
*
* Note that the purpose of the 10th argument is to avoid a situation
* in which gcc would accidentally put the double at the right
* address, thus causing a success message even though TCC actually
* generated incorrect code.
*/
typedef ret_2double_test_type (*ret_8plus2double_test_function_type) (double, double, double, double, double, double, double, ret_2double_test_type, double, double);
static int ret_8plus2double_test_callback(void *ptr) {
ret_8plus2double_test_function_type f = (ret_8plus2double_test_function_type)ptr;
ret_2double_test_type a = {10, 35};
ret_2double_test_type r;
r = f(0, 0, 0, 0, 0, 0, 0, a, 37, 38);
return ((r.x == 37) && (r.y == 37)) ? 0 : -1;
}
static int ret_8plus2double_test(void) {
const char *src =
"typedef struct ret_2double_test_type_s {double x, y;} ret_2double_test_type;"
"ret_2double_test_type f(double x1, double x2, double x3, double x4, double x5, double x6, double x7, ret_2double_test_type a, double x8, double x9) {\n"
" ret_2double_test_type r = { x8, x8 };\n"
" return r;\n"
"}\n";
return run_callback(src, ret_8plus2double_test_callback);
}
/*
* ret_mixed_test:
*
* On x86-64, a struct with a double and a 64-bit integer should be
* passed in one SSE register and one integer register.
*/
typedef struct ret_mixed_test_type_s {double x; long long y;} ret_mixed_test_type;
typedef ret_mixed_test_type (*ret_mixed_test_function_type) (ret_mixed_test_type);
static int ret_mixed_test_callback(void *ptr) {
ret_mixed_test_function_type f = (ret_mixed_test_function_type)ptr;
ret_mixed_test_type a = {10, 35};
ret_mixed_test_type r;
r = f(a);
return ((r.x == a.x*5) && (r.y == a.y*3)) ? 0 : -1;
}
static int ret_mixed_test(void) {
const char *src =
"typedef struct ret_mixed_test_type_s {double x; long long y;} ret_mixed_test_type;"
"ret_mixed_test_type f(ret_mixed_test_type a) {\n"
" ret_mixed_test_type r = {a.x*5, a.y*3};\n"
" return r;\n"
"}\n";
return run_callback(src, ret_mixed_test_callback);
}
/*
* ret_mixed2_test:
*
* On x86-64, a struct with two floats and two 32-bit integers should
* be passed in one SSE register and one integer register.
*/
typedef struct ret_mixed2_test_type_s {float x,x2; int y,y2;} ret_mixed2_test_type;
typedef ret_mixed2_test_type (*ret_mixed2_test_function_type) (ret_mixed2_test_type);
static int ret_mixed2_test_callback(void *ptr) {
ret_mixed2_test_function_type f = (ret_mixed2_test_function_type)ptr;
ret_mixed2_test_type a = {10, 5, 35, 7 };
ret_mixed2_test_type r;
r = f(a);
return ((r.x == a.x*5) && (r.y == a.y*3)) ? 0 : -1;
}
static int ret_mixed2_test(void) {
const char *src =
"typedef struct ret_mixed2_test_type_s {float x, x2; int y,y2;} ret_mixed2_test_type;"
"ret_mixed2_test_type f(ret_mixed2_test_type a) {\n"
" ret_mixed2_test_type r = {a.x*5, 0, a.y*3, 0};\n"
" return r;\n"
"}\n";
return run_callback(src, ret_mixed2_test_callback);
}
/*
* ret_mixed3_test:
*
* On x86-64, this struct should be passed in two integer registers.
*/
typedef struct ret_mixed3_test_type_s {float x; int y; float x2; int y2;} ret_mixed3_test_type;
typedef ret_mixed3_test_type (*ret_mixed3_test_function_type) (ret_mixed3_test_type);
static int ret_mixed3_test_callback(void *ptr) {
ret_mixed3_test_function_type f = (ret_mixed3_test_function_type)ptr;
ret_mixed3_test_type a = {10, 5, 35, 7 };
ret_mixed3_test_type r;
r = f(a);
return ((r.x == a.x*5) && (r.y2 == a.y*3)) ? 0 : -1;
}
static int ret_mixed3_test(void) {
const char *src =
"typedef struct ret_mixed3_test_type_s {float x; int y; float x2; int y2;} ret_mixed3_test_type;"
"ret_mixed3_test_type f(ret_mixed3_test_type a) {\n"
" ret_mixed3_test_type r = {a.x*5, 0, 0, a.y*3};\n"
" return r;\n"
"}\n";
return run_callback(src, ret_mixed3_test_callback);
}
/*
* reg_pack_test: return a small struct which should be packed into
* registers (Win32) during return.
*/
typedef struct reg_pack_test_type_s {int x, y;} reg_pack_test_type;
typedef reg_pack_test_type (*reg_pack_test_function_type) (reg_pack_test_type);
static int reg_pack_test_callback(void *ptr) {
reg_pack_test_function_type f = (reg_pack_test_function_type)ptr;
reg_pack_test_type a = {10, 35};
reg_pack_test_type r;
r = f(a);
return ((r.x == a.x*5) && (r.y == a.y*3)) ? 0 : -1;
}
static int reg_pack_test(void) {
const char *src =
"typedef struct reg_pack_test_type_s {int x, y;} reg_pack_test_type;"
"reg_pack_test_type f(reg_pack_test_type a) {\n"
" reg_pack_test_type r = {a.x*5, a.y*3};\n"
" return r;\n"
"}\n";
return run_callback(src, reg_pack_test_callback);
}
/*
* reg_pack_longlong_test: return a small struct which should be packed into
* registers (x86-64) during return.
*/
typedef struct reg_pack_longlong_test_type_s {long long x, y;} reg_pack_longlong_test_type;
typedef reg_pack_longlong_test_type (*reg_pack_longlong_test_function_type) (reg_pack_longlong_test_type);
static int reg_pack_longlong_test_callback(void *ptr) {
reg_pack_longlong_test_function_type f = (reg_pack_longlong_test_function_type)ptr;
reg_pack_longlong_test_type a = {10, 35};
reg_pack_longlong_test_type r;
r = f(a);
return ((r.x == a.x*5) && (r.y == a.y*3)) ? 0 : -1;
}
static int reg_pack_longlong_test(void) {
const char *src =
"typedef struct reg_pack_longlong_test_type_s {long long x, y;} reg_pack_longlong_test_type;"
"reg_pack_longlong_test_type f(reg_pack_longlong_test_type a) {\n"
" reg_pack_longlong_test_type r = {a.x*5, a.y*3};\n"
" return r;\n"
"}\n";
return run_callback(src, reg_pack_longlong_test_callback);
}
/*
* ret_6plus2longlong_test:
*
* This catches a corner case in the x86_64 ABI code: the first 5
* arguments fit into registers, the 6th doesn't, but the 7th argument
* fits into the 6th argument integer register, %r9.
*
* Note that the purpose of the 10th argument is to avoid a situation
* in which gcc would accidentally put the longlong at the right
* address, thus causing a success message even though TCC actually
* generated incorrect code.
*/
typedef reg_pack_longlong_test_type (*ret_6plus2longlong_test_function_type) (long long, long long, long long, long long, long long, reg_pack_longlong_test_type, long long, long long);
static int ret_6plus2longlong_test_callback(void *ptr) {
ret_6plus2longlong_test_function_type f = (ret_6plus2longlong_test_function_type)ptr;
reg_pack_longlong_test_type a = {10, 35};
reg_pack_longlong_test_type r;
r = f(0, 0, 0, 0, 0, a, 37, 38);
return ((r.x == 37) && (r.y == 37)) ? 0 : -1;
}
static int ret_6plus2longlong_test(void) {
const char *src =
"typedef struct reg_pack_longlong_test_type_s {long long x, y;} reg_pack_longlong_test_type;"
"reg_pack_longlong_test_type f(long long x1, long long x2, long long x3, long long x4, long long x5, reg_pack_longlong_test_type a, long long x8, long long x9) {\n"
" reg_pack_longlong_test_type r = { x8, x8 };\n"
" return r;\n"
"}\n";
return run_callback(src, ret_6plus2longlong_test_callback);
}
/*
* sret_test: Create a struct large enough to be returned via sret
* (hidden pointer as first function argument)
*/
typedef struct sret_test_type_s {long long a, b, c;} sret_test_type;
typedef sret_test_type (*sret_test_function_type) (sret_test_type);
static int sret_test_callback(void *ptr) {
sret_test_function_type f = (sret_test_function_type)(ptr);
sret_test_type x = {5436LL, 658277698LL, 43878957LL};
sret_test_type r = f(x);
return ((r.a==x.a*35)&&(r.b==x.b*19)&&(r.c==x.c*21)) ? 0 : -1;
}
static int sret_test(void) {
const char *src =
"typedef struct sret_test_type_s {long long a, b, c;} sret_test_type;\n"
"sret_test_type f(sret_test_type x) {\n"
" sret_test_type r = {x.a*35, x.b*19, x.c*21};\n"
" return r;\n"
"}\n";
return run_callback(src, sret_test_callback);
}
/*
* one_member_union_test:
*
* In the x86-64 ABI a union should always be passed on the stack. However
* it appears that a single member union is treated by GCC as its member.
*/
typedef union one_member_union_test_type_u {int x;} one_member_union_test_type;
typedef one_member_union_test_type (*one_member_union_test_function_type) (one_member_union_test_type);
static int one_member_union_test_callback(void *ptr) {
one_member_union_test_function_type f = (one_member_union_test_function_type)ptr;
one_member_union_test_type a, b;
a.x = 34;
b = f(a);
return (b.x == a.x*2) ? 0 : -1;
}
static int one_member_union_test(void) {
const char *src =
"typedef union one_member_union_test_type_u {int x;} one_member_union_test_type;\n"
"one_member_union_test_type f(one_member_union_test_type a) {\n"
" one_member_union_test_type b;\n"
" b.x = a.x * 2;\n"
" return b;\n"
"}\n";
return run_callback(src, one_member_union_test_callback);
}
/*
* two_member_union_test:
*
* In the x86-64 ABI a union should always be passed on the stack.
*/
typedef union two_member_union_test_type_u {int x; long y;} two_member_union_test_type;
typedef two_member_union_test_type (*two_member_union_test_function_type) (two_member_union_test_type);
static int two_member_union_test_callback(void *ptr) {
two_member_union_test_function_type f = (two_member_union_test_function_type)ptr;
two_member_union_test_type a, b;
a.x = 34;
b = f(a);
return (b.x == a.x*2) ? 0 : -1;
}
static int two_member_union_test(void) {
const char *src =
"typedef union two_member_union_test_type_u {int x; long y;} two_member_union_test_type;\n"
"two_member_union_test_type f(two_member_union_test_type a) {\n"
" two_member_union_test_type b;\n"
" b.x = a.x * 2;\n"
" return b;\n"
"}\n";
return run_callback(src, two_member_union_test_callback);
}
/*
* Win64 calling convention test.
*/
typedef struct many_struct_test_type_s {long long a, b, c;} many_struct_test_type;
typedef many_struct_test_type (*many_struct_test_function_type) (many_struct_test_type,many_struct_test_type,many_struct_test_type,many_struct_test_type,many_struct_test_type,many_struct_test_type);
static int many_struct_test_callback(void *ptr) {
many_struct_test_function_type f = (many_struct_test_function_type)ptr;
many_struct_test_type v = {1, 2, 3};
many_struct_test_type r = f(v,v,v,v,v,v);
return ((r.a == 6) && (r.b == 12) && (r.c == 18))?0:-1;
}
static int many_struct_test(void) {
const char *src =
"typedef struct many_struct_test_type_s {long long a, b, c;} many_struct_test_type;\n"
"many_struct_test_type f(many_struct_test_type x1, many_struct_test_type x2, many_struct_test_type x3, many_struct_test_type x4, many_struct_test_type x5, many_struct_test_type x6) {\n"
" many_struct_test_type y;\n"
" y.a = x1.a + x2.a + x3.a + x4.a + x5.a + x6.a;\n"
" y.b = x1.b + x2.b + x3.b + x4.b + x5.b + x6.b;\n"
" y.c = x1.c + x2.c + x3.c + x4.c + x5.c + x6.c;\n"
" return y;\n"
"}\n";
return run_callback(src, many_struct_test_callback);
}
/*
* Win64 calling convention test.
*/
typedef struct many_struct_test_2_type_s {int a, b;} many_struct_test_2_type;
typedef many_struct_test_2_type (*many_struct_test_2_function_type) (many_struct_test_2_type,many_struct_test_2_type,many_struct_test_2_type,many_struct_test_2_type,many_struct_test_2_type,many_struct_test_2_type);
static int many_struct_test_2_callback(void *ptr) {
many_struct_test_2_function_type f = (many_struct_test_2_function_type)ptr;
many_struct_test_2_type v = {1,2};
many_struct_test_2_type r = f(v,v,v,v,v,v);
return ((r.a == 6) && (r.b == 12))?0:-1;
}
static int many_struct_test_2(void) {
const char *src =
"typedef struct many_struct_test_2_type_s {int a, b;} many_struct_test_2_type;\n"
"many_struct_test_2_type f(many_struct_test_2_type x1, many_struct_test_2_type x2, many_struct_test_2_type x3, many_struct_test_2_type x4, many_struct_test_2_type x5, many_struct_test_2_type x6) {\n"
" many_struct_test_2_type y;\n"
" y.a = x1.a + x2.a + x3.a + x4.a + x5.a + x6.a;\n"
" y.b = x1.b + x2.b + x3.b + x4.b + x5.b + x6.b;\n"
" return y;\n"
"}\n";
return run_callback(src, many_struct_test_2_callback);
}
/*
* Win64 calling convention test.
*/
typedef struct many_struct_test_3_type_s {int a, b;} many_struct_test_3_type;
typedef many_struct_test_3_type (*many_struct_test_3_function_type) (many_struct_test_3_type,many_struct_test_3_type,many_struct_test_3_type,many_struct_test_3_type,many_struct_test_3_type,many_struct_test_3_type, ...);
typedef struct many_struct_test_3_struct_type { many_struct_test_3_function_type f; many_struct_test_3_function_type *f2; } many_struct_test_3_struct_type;
static void many_struct_test_3_dummy(double d, ...)
{
volatile double x = d;
}
static int many_struct_test_3_callback(void *ptr) {
many_struct_test_3_struct_type s = { ptr, };
many_struct_test_3_struct_type *s2 = &s;
s2->f2 = &s2->f;
many_struct_test_3_dummy(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, &s2);
many_struct_test_3_function_type f = *(s2->f2);
many_struct_test_3_type v = {1,2};
many_struct_test_3_type r = (*((s2->f2=&f)+0))(v,v,v,v,v,v,1.0);
return ((r.a == 6) && (r.b == 12))?0:-1;
}
static int many_struct_test_3(void) {
const char *src =
"typedef struct many_struct_test_3_type_s {int a, b;} many_struct_test_3_type;\n"
"many_struct_test_3_type f(many_struct_test_3_type x1, many_struct_test_3_type x2, many_struct_test_3_type x3, many_struct_test_3_type x4, many_struct_test_3_type x5, many_struct_test_3_type x6, ...) {\n"
" many_struct_test_3_type y;\n"
" y.a = x1.a + x2.a + x3.a + x4.a + x5.a + x6.a;\n"
" y.b = x1.b + x2.b + x3.b + x4.b + x5.b + x6.b;\n"
" return y;\n"
"}\n";
return run_callback(src, many_struct_test_3_callback);
}
/*
* stdarg_test: Test variable argument list ABI
*/
typedef struct {long long a, b, c;} stdarg_test_struct_type;
typedef void (*stdarg_test_function_type) (int,int,int,...);
static int stdarg_test_callback(void *ptr) {
stdarg_test_function_type f = (stdarg_test_function_type)ptr;
int x;
double y;
stdarg_test_struct_type z = {1, 2, 3}, w;
f(10, 10, 5,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, &x,
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, &y,
z, z, z, z, z, &w);
return ((x == 55) && (y == 55) && (w.a == 5) && (w.b == 10) && (w.c == 15)) ? 0 : -1;
}
static int stdarg_test(void) {
const char *src =
"#include <stdarg.h>\n"
"typedef struct {long long a, b, c;} stdarg_test_struct_type;\n"
"void f(int n_int, int n_float, int n_struct, ...) {\n"
" int i, ti = 0;\n"
" double td = 0.0;\n"
" stdarg_test_struct_type ts = {0,0,0}, tmp;\n"
" va_list ap;\n"
" va_start(ap, n_struct);\n"
" for (i = 0, ti = 0; i < n_int; ++i)\n"
" ti += va_arg(ap, int);\n"
" *va_arg(ap, int*) = ti;\n"
" for (i = 0, td = 0; i < n_float; ++i)\n"
" td += va_arg(ap, double);\n"
" *va_arg(ap, double*) = td;\n"
" for (i = 0; i < n_struct; ++i) {\n"
" tmp = va_arg(ap, stdarg_test_struct_type);\n"
" ts.a += tmp.a; ts.b += tmp.b; ts.c += tmp.c;"
" }\n"
" *va_arg(ap, stdarg_test_struct_type*) = ts;\n"
" va_end(ap);"
"}\n";
return run_callback(src, stdarg_test_callback);
}
typedef struct {long long a, b;} stdarg_many_test_struct_type;
typedef void (*stdarg_many_test_function_type) (int, int, int, int, int,
stdarg_many_test_struct_type,
int, int, ...);
static int stdarg_many_test_callback(void *ptr)
{
stdarg_many_test_function_type f = (stdarg_many_test_function_type)ptr;
int x;
stdarg_many_test_struct_type l = {10, 11};
f(1, 2, 3, 4, 5, l, 6, 7, &x, 44);
return x == 44 ? 0 : -1;
}
static int stdarg_many_test(void)
{
const char *src =
"#include <stdarg.h>\n"
"typedef struct {long long a, b;} stdarg_many_test_struct_type;\n"
"void f (int a, int b, int c, int d, int e, stdarg_many_test_struct_type l, int f, int g, ...){\n"
" va_list ap;\n"
" int *p;\n"
" va_start (ap, g);\n"
" p = va_arg(ap, int*);\n"
" *p = va_arg(ap, int);\n"
" va_end (ap);\n"
"}\n";
return run_callback(src, stdarg_many_test_callback);
}
/*
* Test Win32 stdarg handling, since the calling convention will pass a pointer
* to the struct and the stdarg pointer must point to that pointer initially.
*/
typedef struct {long long a, b, c;} stdarg_struct_test_struct_type;
typedef int (*stdarg_struct_test_function_type) (stdarg_struct_test_struct_type a, ...);
static int stdarg_struct_test_callback(void *ptr) {
stdarg_struct_test_function_type f = (stdarg_struct_test_function_type)ptr;
stdarg_struct_test_struct_type v = {10, 35, 99};
int x = f(v, 234);
return (x == 378) ? 0 : -1;
}
static int stdarg_struct_test(void) {
const char *src =
"#include <stdarg.h>\n"
"typedef struct {long long a, b, c;} stdarg_struct_test_struct_type;\n"
"int f(stdarg_struct_test_struct_type a, ...) {\n"
" va_list ap;\n"
" va_start(ap, a);\n"
" int z = va_arg(ap, int);\n"
" va_end(ap);\n"
" return z + a.a + a.b + a.c;\n"
"}\n";
return run_callback(src, stdarg_struct_test_callback);
}
/* Test that x86-64 arranges the stack correctly for arguments with alignment >8 bytes */
typedef LONG_DOUBLE (*arg_align_test_callback_type) (LONG_DOUBLE,int,LONG_DOUBLE,int,LONG_DOUBLE);
static int arg_align_test_callback(void *ptr) {
arg_align_test_callback_type f = (arg_align_test_callback_type)ptr;
long double x = f(12, 0, 25, 0, 37);
return (x == 74) ? 0 : -1;
}
static int arg_align_test(void) {
const char *src =
"long double f(long double a, int b, long double c, int d, long double e) {\n"
" return a + c + e;\n"
"}\n";
return run_callback(src, arg_align_test_callback);
}
#define RUN_TEST(t) \
if (!testname || (strcmp(#t, testname) == 0)) { \
fputs(#t "... ", stdout); \
fflush(stdout); \
if (t() == 0) { \
fputs("success\n", stdout); \
} else { \
fputs("failure\n", stdout); \
retval = EXIT_FAILURE; \
} \
}
int main(int argc, char **argv) {
int i;
const char *testname = NULL;
int retval = EXIT_SUCCESS;
/* if tcclib.h and libtcc1.a are not installed, where can we find them */
for (i = 1; i < argc; ++i) {
if (!memcmp(argv[i], "run_test=", 9))
testname = argv[i] + 9;
}
g_argv = argv, g_argc = argc;
RUN_TEST(ret_int_test);
RUN_TEST(ret_longlong_test);
RUN_TEST(ret_float_test);
RUN_TEST(ret_double_test);
RUN_TEST(ret_longdouble_test);
RUN_TEST(ret_2float_test);
RUN_TEST(ret_2double_test);
RUN_TEST(ret_8plus2double_test);
RUN_TEST(ret_6plus2longlong_test);
#if !defined __x86_64__ || defined _WIN32
/* currently broken on x86_64 linux */
RUN_TEST(ret_mixed_test);
RUN_TEST(ret_mixed2_test);
#endif
RUN_TEST(ret_mixed3_test);
RUN_TEST(reg_pack_test);
RUN_TEST(reg_pack_longlong_test);
RUN_TEST(sret_test);
RUN_TEST(one_member_union_test);
RUN_TEST(two_member_union_test);
RUN_TEST(many_struct_test);
RUN_TEST(many_struct_test_2);
RUN_TEST(many_struct_test_3);
RUN_TEST(stdarg_test);
RUN_TEST(stdarg_many_test);
RUN_TEST(stdarg_struct_test);
RUN_TEST(arg_align_test);
return retval;
}

View File

@ -0,0 +1,57 @@
#include <stdio.h>
#if defined _WIN32 && !defined __TINYC__
# define _ "_"
#else
# define _
#endif
static int x1_c(void)
{
printf(" x1");
return 1;
}
asm(".text;"_"x1: call "_"x1_c; ret");
void callx4(void);
void callx5_again(void);
void x6()
{
printf(" x6-1");
}
int main(int argc, char *argv[])
{
printf("*");
asm("call "_"x1");
asm("call "_"x2");
asm("call "_"x3");
callx4();
asm("call "_"x5");
callx5_again();
x6();
printf(" *\n");
return 0;
}
static
int x2(void)
{
printf(" x2");
return 2;
}
extern int x3(void);
void x4(void)
{
printf(" x4");
}
void x5(void);
void x5(void)
{
printf(" x5");
}

View File

@ -0,0 +1,36 @@
#include <stdio.h>
#if defined _WIN32 && !defined __TINYC__
# define _ "_"
#else
# define _
#endif
int x3(void)
{
printf(" x3");
return 3;
}
/* That callx4 is defined globally (as if ".globl callx4")
is a TCC extension. GCC doesn't behave like this. */
void callx4(void);
__asm__(_"callx4: call "_"x4; ret;"
#ifndef __TINYC__
" .global "_"callx4"
#endif
);
extern void x5(void);
void callx5_again(void);
void callx5_again(void)
{
x5();
asm("call "_"x6");
}
static void x6()
{
printf(" x6-2");
}

View File

@ -1,3 +1,4 @@
# gas comment with ``gnu'' style quotes
/* some directive tests */
@ -9,14 +10,23 @@
.int 1, 2, 3
.align 8
.byte 1
.align 16, 0x90
/* .align 16, 0x90 gas is too clever for us with 0x90 fill */
.balign 4, 0x92
.align 16, 0x91 /* 0x91 tests the non-clever behaviour */
.skip 3
.skip 15, 0x90
.string "hello\0world"
/* Macro expansion should work like with C, the #n shouldn't be parsed
as asm line comment */
#define __stringify(n) #n
#define stringify(n) __stringify(n)
.skip 8,0x90
.asciz stringify(BLA)
.skip 8,0x90
# 28 "asmtest.S" # a line directive (and a line comment)
movl %eax, %ebx # some more asm comment
/* some label tests */
movl %eax, %ebx
L1:
movl %eax, %ebx
mov 0x10000, %eax
@ -36,7 +46,7 @@ mov %al, 0x10000
mov $1, %edx
mov $1, %dx
mov $1, %dl
mov $1, %cl
movb $2, 0x100(%ebx,%edx,2)
movw $2, 0x100(%ebx,%edx,2)
movl $2, 0x100(%ebx,%edx,2)
@ -44,17 +54,55 @@ movl %eax, 0x100(%ebx,%edx,2)
movl 0x100(%ebx,%edx,2), %edx
movw %ax, 0x100(%ebx,%edx,2)
movw $0x1122,%si
movl $0x112233,%edx
movl $0x80000000, %esi
movl $-0x7fffffff, %edi
#ifdef __x86_64__
mov $0x11223344,%rbx
movq $0x11223344,%rbx
mov $0x1122334455,%rbx
movq $0x1122334455,%rbx
movl $0x11334455,(%rbx)
#endif
mov %eax, 0x12(,%edx,2)
#ifdef __i386__
mov %cr3, %edx
mov %ecx, %cr3
movl %cr3, %eax
movl %tr3, %eax
movl %db3, %ebx
movl %dr6, %eax
#else
mov %cr3, %rdx
mov %rcx, %cr3
movq %cr3, %rax
movq %db3, %rbx
movq %dr6, %rax
mov %cr8, %rsi
mov %rdi, %cr8
#endif
movl %fs, %ecx
movl %ebx, %fs
#ifdef __x86_64__
movq %r8, %r9
movq %r10, %r11
movq %r12, %r13
movq %r14, %r15
movq %rax, %r9
movq %r15, %rsi
inc %r9b
dec %r10w
not %r11d
negq %r12
decb %r13b
incw %r14w
notl %r15d
#endif
movsbl 0x1000, %eax
movsbw 0x1000, %ax
movswl 0x1000, %eax
@ -66,19 +114,47 @@ movl %ebx, %fs
movzb 0x1000, %eax
movzb 0x1000, %ax
mov $0x12345678,%eax
#ifdef __x86_64__
movzb 0x1000, %rax
movzbq 0x1000, %rbx
movsbq 0x1000, %rdx
movzwq 0x1000, %rdi
movswq 0x1000, %rdx
movslq %eax, %rcx
mov $0x12345678,%rax
mov $0x12345678,%rdx
mov $0x12345678,%r10
mov $0x123456789abcdef0,%rax
mov $0x123456789abcdef0,%rcx
mov $0x123456789abcdef0,%r11
#endif
#ifdef __i386__
pushl %eax
pushw %ax
push %eax
push %cs
#else
pushq %rax
push %rax
#endif
pushw %ax
push %gs
push $1
push $100
push 0x42(%eax)
pop 0x43(%esi)
#ifdef __i386__
popl %eax
popw %ax
pop %eax
pop %ds
#else
popq %rax
pop %rax
#endif
popw %ax
pop %fs
xchg %eax, %ecx
@ -109,22 +185,61 @@ movl %ebx, %fs
leal 0x1000(%ebx), %ecx
lea 0x1000(%ebx), %ecx
#ifdef __i386__
les 0x2000, %eax
lds 0x2000, %ebx
lss 0x2000, %edx
#endif
lfs 0x2000, %ecx
lgs 0x2000, %edx
lss 0x2000, %edx
addl $0x123, %eax
add $0x123, %ebx
add $-16, %ecx
add $-0x123, %esi
add $1, %bx
add $1, %ebx
add $-1, %bx
add $-1, %ebx
add $127, %bx
addl $127, %ebx
addl $-128, %ebx
addl $-128, %ebx
addl $-129, %ebx
addl $128, %ebx
addl $255, %ebx
addl $256, %ebx
andb $0xf, %ah
andb $-15, %cl
xorb $127, %dh
cmpb $42, (%eax)
addl $0x123, 0x100
addl $0x123, 0x100(%ebx)
addl $0x123, 0x100(%ebx,%edx,2)
addl $0x123, 0x100(%esp)
addl $0x123, (3*8)(%esp)
addl $0x123, (%ebp)
addl $0x123, (%esp)
cmpl $0x123, (%esp)
#ifdef __x86_64__
xor %bl,%ah
xor %bl,%r8b
xor %r9b,%bl
xor %sil,%cl
add %eax,(%r8d)
add %ebx,(%r9)
add %edx,(%r10d,%r11d)
add %ecx,(%r12,%r13)
add %esi,(%r14,%r15,4)
add %edi,0x1000(%rbx,%r12,8)
add %r11,0x1000(%ebp,%r9d,8)
movb $12, %ah
movb $13, %bpl
movb $14, %dil
movb $15, %r12b
#endif
add %eax, (%ebx)
add (%ebx), %eax
@ -176,6 +291,8 @@ add (%ebx), %dl
div %bl
div %ecx, %eax
and $15,%bx
and $-20,%edx
shl %edx
shl $10, %edx
@ -192,21 +309,53 @@ shrd %eax, %edx
L4:
call 0x1000
call L4
#ifdef __i386__
call *%eax
#else
call *%rax
#endif
call *0x1000
call func1
.global L5,L6
L5:
L6:
#ifdef __i386__
lcall $0x100, $0x1000
#else
lcall *0x100
lcall *(%rax)
#endif
jmp 0x1000
jmp *(%edi)
#ifdef __i386__
jmp *%eax
#else
jmp *%rax
#endif
jmp *0x1000
#ifdef __i386__
ljmp $0x100, $0x1000
#else
ljmp *0x100
ljmp *(%rdi)
ljmpl *(%esi)
ljmpw *(%esi)
#endif
ret
ret $10
#ifdef __i386__
retl
retl $10
#else
retq
retq $10
#endif
lret
@ -234,14 +383,20 @@ L3:
seto %al
setc %al
setcb %al
setnp 0x1000
setl 0xaaaa
setg %dl
fadd
fadd %st(1), %st
fadd %st(0), %st(1)
fadd %st(3)
fmul %st(0),%st(0)
fmul %st(0),%st(1)
faddp %st(5)
faddp
faddp %st(1), %st
@ -387,6 +542,7 @@ L3:
fwait
bswap %edx
bswapl %ecx
xadd %ecx, %edx
xaddb %dl, 0x1000
xaddw %ax, 0x1000
@ -397,6 +553,10 @@ cmpxchgw %ax, 0x1000
cmpxchgl %eax, 0x1000
invlpg 0x1000
cmpxchg8b 0x1002
#ifdef __x86_64__
cmpxchg16b (%rax)
cmpxchg16b (%r10,%r11)
#endif
fcmovb %st(5), %st
fcmove %st(5), %st
@ -416,32 +576,51 @@ fucomip %st(5), %st
cmovo 0x1000, %eax
cmovs 0x1000, %eax
cmovns %edx, %edi
cmovne %ax, %si
cmovbw %ax, %di
cmovnbel %edx, %ecx
#ifdef __x86_64__
bswapq %rsi
bswapq %r10
cmovz %rdi,%rbx
cmovpeq %rsi, %rdx
#endif
int $3
int $0x10
#ifdef __i386__
pusha
popa
clc
cld
#endif
clc # another comment
cld # a comment with embedded ' tick
cli
clts
cmc
lahf
sahf
#ifdef __i386__
pushfl
popfl
#else
pushfq
popfq
#endif
pushf
popf
stc
std
sti
#ifdef __i386__
aaa
aas
daa
das
aad
aam
into
#endif
cbw
cwd
cwde
@ -452,7 +631,6 @@ int $0x10
cltd
leave
int3
into
iret
rsm
hlt
@ -470,6 +648,24 @@ int $0x10
repz
repne
repnz
nop
lock ;negl (%eax)
wait ;pushf
rep ;stosb
repe ;lodsb
repz ;cmpsb
repne;movsb
repnz;outsb
/* handle one-line prefix + ops */
lock negl (%eax)
wait pushf
rep stosb
repe lodsb
repz cmpsb
repne movsb
repnz outsb
invd
wbinvd
@ -479,7 +675,34 @@ int $0x10
rdmsr
rdpmc
ud2
#ifdef __x86_64__
syscall
sysret
sysretq
lfence
mfence
sfence
prefetchnta 0x18(%rdx)
prefetcht0 (%rcx)
prefetcht1 (%rsi)
prefetcht2 (%rdi)
prefetchw (%rdi)
clflush 0x1000(%rax,%rcx)
fxsaveq (%rdx)
fxsaveq (%r11)
fxrstorq (%rcx)
fxrstorq (%r10)
#endif
lar %ax,%dx
lar %eax,%dx
lar %ax,%edx
lar %eax,%edx
#ifdef __x86_64__
lar %ax,%rdx
lar %eax,%rdx
#endif
emms
movd %edx, %mm3
movd 0x1000, %mm2
@ -524,35 +747,232 @@ int $0x10
#ifdef __i386__
boundl %edx, 0x10000
boundw %bx, 0x1000
arpl %bx, 0x1000
#endif
lar 0x1000, %eax
lgdt 0x1000
lidt 0x1000
lldt 0x1000
lmsw 0x1000
lsl 0x1000, %ecx
ltr 0x1000
sgdt 0x1000
sidt 0x1000
sldt 0x1000
#ifdef __x86_64__
lgdtq 0x1000
lidtq 0x1000
sgdtq 0x1000
sidtq 0x1000
swapgs
str %rdx
str %r9
#endif
lmsw 0x1000
lsl 0x1000, %ecx
ltr 0x1000
ltr %si
smsw 0x1000
str 0x1000
str %ecx
str %dx
verr 0x1000
verw 0x1000
#ifdef __i386__
push %ds
pushw %ds
pushl %ds
pop %ds
popw %ds
popl %ds
#endif
fxsave 1(%ebx)
fxrstor 1(%ecx)
#ifdef __i386__
pushl $1
#else
pushq $1
#endif
pushw $1
push $1
#ifdef __ASSEMBLER__ // should be defined, for S files
inc %eax
#endif
#ifndef _WIN32
ft1: ft2: ft3: ft4: ft5: ft6: ft7: ft8: ft9:
xor %eax, %eax
ret
.type ft1,STT_FUNC
.type ft2,@STT_FUNC
.type ft3,%STT_FUNC
.type ft4,"STT_FUNC"
.type ft5,function
.type ft6,@function
.type ft7,%function
.type ft8,"function"
#endif
pause
.rept 6
nop
.endr
.fill 4,1,0x90
.section .text.one,"ax"
nop
.previous
.pushsection .text.one,"ax"
nop
.pushsection .text.two,"ax"
nop
.popsection
.popsection
1: ud2
.pushsection __bug_table,"a"
.align 8
2: .long 1b - 2b
.long 0x600000 - 2b
.long 1b + 42
.long 43 + 1b
.long 2b + 144
.long 145 + 2b
.word 164, 0
.org 2b+32
#ifdef __x86_64__
.quad 1b
#else
.long 1b
#endif
.popsection
3: mov %eax,%ecx
4:
.pushsection .text.three, "ax"
nop
.skip (-((4b-3b) > 0) * 2) , 0x90
.popsection
.globl overrideme
.weak overrideme
nop
.globl notimplemented
notimplemented:
ret
.set overrideme, notimplemented
overrideme = notimplemented
overrideme:
ret
movd %esi, %mm1
movd %edi, %xmm2
movd (%ebx), %mm3
movd (%ebx), %xmm3
movd %mm1, %esi
movd %xmm2, %edi
movd %mm3, (%edx)
movd %xmm3, (%edx)
#ifdef __x86_64__
movd %rsi, %mm1
movd %rdi, %xmm2
movd (%rbx), %mm3
movd (%rbx), %xmm3
movd %mm1, %r12
movd %xmm2, %rdi
movd %mm3, (%r8)
movd %xmm3, (%r13)
#endif
movq (%ebp), %mm1
movq %mm2, (%edi)
movq (%edi), %xmm3
movq %mm4, %mm5
#ifdef __x86_64__
movq %rcx, %mm1
movq %rdx, %xmm2
movq %r13, %xmm3
/* movq mem64->xmm is encoded as f30f7e by GAS, but as
660f6e by tcc (which really is a movd and would need
a REX.W prefix to be movq). */
movq (%rsi), %xmm3
movq %mm1, %rdx
movq %xmm3, %rcx
movq %xmm4, (%rsi)
#endif
#define TEST_MMX_SSE(insn) \
insn %mm1, %mm2; \
insn %xmm2, %xmm3; \
insn (%ebx), %xmm3;
#define TEST_MMX_SSE_I8(insn) \
TEST_MMX_SSE(insn) \
insn $0x42, %mm4; \
insn $0x42, %xmm4;
TEST_MMX_SSE(packssdw)
TEST_MMX_SSE(packsswb)
TEST_MMX_SSE(packuswb)
TEST_MMX_SSE(paddb)
TEST_MMX_SSE(paddw)
TEST_MMX_SSE(paddd)
TEST_MMX_SSE(paddsb)
TEST_MMX_SSE(paddsw)
TEST_MMX_SSE(paddusb)
TEST_MMX_SSE(paddusw)
TEST_MMX_SSE(pand)
TEST_MMX_SSE(pandn)
TEST_MMX_SSE(pcmpeqb)
TEST_MMX_SSE(pcmpeqw)
TEST_MMX_SSE(pcmpeqd)
TEST_MMX_SSE(pcmpgtb)
TEST_MMX_SSE(pcmpgtw)
TEST_MMX_SSE(pcmpgtd)
TEST_MMX_SSE(pmaddwd)
TEST_MMX_SSE(pmulhw)
TEST_MMX_SSE(pmullw)
TEST_MMX_SSE(por)
TEST_MMX_SSE(psllw)
TEST_MMX_SSE_I8(psllw)
TEST_MMX_SSE(pslld)
TEST_MMX_SSE_I8(pslld)
TEST_MMX_SSE(psllq)
TEST_MMX_SSE_I8(psllq)
TEST_MMX_SSE(psraw)
TEST_MMX_SSE_I8(psraw)
TEST_MMX_SSE(psrad)
TEST_MMX_SSE_I8(psrad)
TEST_MMX_SSE(psrlw)
TEST_MMX_SSE_I8(psrlw)
TEST_MMX_SSE(psrld)
TEST_MMX_SSE_I8(psrld)
TEST_MMX_SSE(psrlq)
TEST_MMX_SSE_I8(psrlq)
TEST_MMX_SSE(psubb)
TEST_MMX_SSE(psubw)
TEST_MMX_SSE(psubd)
TEST_MMX_SSE(psubsb)
TEST_MMX_SSE(psubsw)
TEST_MMX_SSE(psubusb)
TEST_MMX_SSE(psubusw)
TEST_MMX_SSE(punpckhbw)
TEST_MMX_SSE(punpckhwd)
TEST_MMX_SSE(punpckhdq)
TEST_MMX_SSE(punpcklbw)
TEST_MMX_SSE(punpcklwd)
TEST_MMX_SSE(punpckldq)
TEST_MMX_SSE(pxor)
cvtpi2ps %mm1, %xmm2
cvtpi2ps (%ebx), %xmm2
TEST_MMX_SSE(pmaxsw)
TEST_MMX_SSE(pmaxub)
TEST_MMX_SSE(pminsw)
TEST_MMX_SSE(pminub)

View File

@ -1,5 +1,6 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define NB_ITS 1000000
//#define NB_ITS 1
@ -49,12 +50,15 @@ int test4(void)
int i, sum = 0;
int *tab4;
fprintf(stderr, "%s start\n", __FUNCTION__);
tab4 = malloc(20 * sizeof(int));
for(i=0;i<20;i++) {
sum += tab4[i];
}
free(tab4);
fprintf(stderr, "%s end\n", __FUNCTION__);
return sum;
}
@ -64,12 +68,15 @@ int test5(void)
int i, sum = 0;
int *tab4;
fprintf(stderr, "%s start\n", __FUNCTION__);
tab4 = malloc(20 * sizeof(int));
for(i=0;i<21;i++) {
sum += tab4[i];
}
free(tab4);
fprintf(stderr, "%s end\n", __FUNCTION__);
return sum;
}
@ -186,8 +193,43 @@ int test15(void)
return strlen(p);
}
/* ok */
int test16()
{
char *demo = "This is only a test.";
char *p;
fprintf(stderr, "%s start\n", __FUNCTION__);
p = alloca(16);
strcpy(p,"12345678901234");
printf("alloca: p is %s\n", p);
/* Test alloca embedded in a larger expression */
printf("alloca: %s\n", strcpy(alloca(strlen(demo)+1),demo) );
fprintf(stderr, "%s end\n", __FUNCTION__);
}
/* error */
int test17()
{
char *demo = "This is only a test.";
char *p;
fprintf(stderr, "%s start\n", __FUNCTION__);
p = alloca(16);
strcpy(p,"12345678901234");
printf("alloca: p is %s\n", p);
/* Test alloca embedded in a larger expression */
printf("alloca: %s\n", strcpy(alloca(strlen(demo)),demo) );
fprintf(stderr, "%s end\n", __FUNCTION__);
}
int (*table_test[])(void) = {
test1,
test1,
test2,
test3,
@ -203,23 +245,33 @@ int (*table_test[])(void) = {
test13,
test14,
test15,
test16,
test17,
};
int main(int argc, char **argv)
{
int index;
int (*ftest)(void);
int index_max = sizeof(table_test)/sizeof(table_test[0]);
if (argc < 2) {
printf("usage: boundtest n\n"
"test TCC bound checking system\n"
);
printf(
"test TCC bound checking system\n"
"usage: boundtest N\n"
" 1 <= N <= %d\n", index_max);
exit(1);
}
index = 0;
if (argc >= 2)
index = atoi(argv[1]);
index = atoi(argv[1]) - 1;
if ((index < 0) || (index >= index_max)) {
printf("N is outside of the valid range (%d)\n", index);
exit(2);
}
/* well, we also use bounds on this ! */
ftest = table_test[index];
ftest();

View File

@ -8,11 +8,11 @@ nb_failed="0"
for src in $TESTSUITE_PATH/compile/*.c ; do
echo $TCC -o /tmp/test.o -c $src
$TCC -o /tmp/test.o -c $src >> tcc.log 2>&1
if [ "$?" == "0" ] ; then
if [ "$?" = "0" ] ; then
result="PASS"
else
result="FAIL"
nb_failed=$[ $nb_failed + 1 ]
nb_failed=$(( $nb_failed + 1 ))
fi
echo "$result: $src" >> tcc.sum
done
@ -20,11 +20,11 @@ done
for src in $TESTSUITE_PATH/execute/*.c ; do
echo $TCC $src
$TCC $src >> tcc.log 2>&1
if [ "$?" == "0" ] ; then
if [ "$?" = "0" ] ; then
result="PASS"
else
result="FAIL"
nb_failed=$[ $nb_failed + 1 ]
nb_failed=$(( $nb_failed + 1 ))
fi
echo "$result: $src" >> tcc.sum
done

View File

@ -15,7 +15,16 @@ int add(int a, int b)
return a + b;
}
/* this strinc is referenced by the generated code */
const char hello[] = "Hello World!";
char my_program[] =
"#include <tcclib.h>\n" /* include the "Simple libc header for TCC" */
"extern int add(int a, int b);\n"
"#ifdef _WIN32\n" /* dynamically linked data needs 'dllimport' */
" __attribute__((dllimport))\n"
"#endif\n"
"extern const char hello[];\n"
"int fib(int n)\n"
"{\n"
" if (n <= 2)\n"
@ -26,7 +35,7 @@ char my_program[] =
"\n"
"int foo(int n)\n"
"{\n"
" printf(\"Hello World!\\n\");\n"
" printf(\"%s\\n\", hello);\n"
" printf(\"fib(%d) = %d\\n\", n, fib(n));\n"
" printf(\"add(%d, %d) = %d\\n\", n, 2 * n, add(n, 2 * n));\n"
" return 0;\n"
@ -35,9 +44,8 @@ char my_program[] =
int main(int argc, char **argv)
{
TCCState *s;
int i;
int (*func)(int);
void *mem;
int size;
s = tcc_new();
if (!s) {
@ -46,8 +54,17 @@ int main(int argc, char **argv)
}
/* if tcclib.h and libtcc1.a are not installed, where can we find them */
if (argc == 2 && !memcmp(argv[1], "lib_path=",9))
tcc_set_lib_path(s, argv[1]+9);
for (i = 1; i < argc; ++i) {
char *a = argv[i];
if (a[0] == '-') {
if (a[1] == 'B')
tcc_set_lib_path(s, a+2);
else if (a[1] == 'I')
tcc_add_include_path(s, a+2);
else if (a[1] == 'L')
tcc_add_library_path(s, a+2);
}
}
/* MUST BE CALLED before any compilation */
tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
@ -55,30 +72,25 @@ int main(int argc, char **argv)
if (tcc_compile_string(s, my_program) == -1)
return 1;
/* as a test, we add a symbol that the compiled program can use.
/* as a test, we add symbols that the compiled program can use.
You may also open a dll with tcc_add_dll() and use symbols from that */
tcc_add_symbol(s, "add", add);
tcc_add_symbol(s, "hello", hello);
/* get needed size of the code */
size = tcc_relocate(s, NULL);
if (size == -1)
/* relocate the code */
if (tcc_relocate(s, TCC_RELOCATE_AUTO) < 0)
return 1;
/* allocate memory and copy the code into it */
mem = malloc(size);
tcc_relocate(s, mem);
/* get entry symbol */
func = tcc_get_symbol(s, "foo");
if (!func)
return 1;
/* delete the state */
tcc_delete(s);
/* run the code */
func(32);
free(mem);
/* delete the state */
tcc_delete(s);
return 0;
}

6
tests/pp/01.c 100644
View File

@ -0,0 +1,6 @@
#define hash_hash # ## #
#define mkstr(a) # a
#define in_between(a) mkstr(a)
#define join(c, d) in_between(c hash_hash d)
char p[] = join(x, y);
// char p[] = "x ## y";

View File

@ -0,0 +1 @@
char p[] = "x ## y";

28
tests/pp/02.c 100644
View File

@ -0,0 +1,28 @@
#define x 3
#define f(a) f(x * (a))
#undef x
#define x 2
#define g f
#define z z[0]
#define h g(~
#define m(a) a(w)
#define w 0,1
#define t(a) a
#define p() int
#define q(x) x
#define r(x,y) x ## y
#define str(x) # x
f(y+1) + f(f(z)) % t(t(g)(0) + t)(1);
g(x+(3,4)-w) | h 5) & m
(f)^m(m);
char c[2][6] = { str(hello), str() };
/*
* f(2 * (y+1)) + f(2 * (f(2 * (z[0])))) % f(2 * (0)) + t(1);
* f(2 * (2+(3,4)-0,1)) | f(2 * (~ 5)) & f(2 * (0,1))^m(0,1);
* char c[2][6] = { "hello", "" };
*/
#define L21 f(y+1) + f(f(z)) % t(t(g)(0) + t)(1);
#define L22 g(x+(3,4)-w) | h 5) & m\
(f)^m(m);
L21
L22

View File

@ -0,0 +1,5 @@
f(2 * (y+1)) + f(2 * (f(2 * (z[0])))) % f(2 * (0)) + t(1);
f(2 * (2 +(3,4)-0,1)) | f(2 * (~ 5)) & f(2 * (0,1))^m(0,1);
char c[2][6] = { "hello", "" };
f(2 * (y+1)) + f(2 * (f(2 * (z[0])))) % f(2 * (0)) + t(1);
f(2 * (2 +(3,4)-0,1)) | f(2 * (~ 5)) & f(2 * (0,1))^m(0,1);

15
tests/pp/03.c 100644
View File

@ -0,0 +1,15 @@
#define str(s) # s
#define xstr(s) str(s)
#define debug(s, t) printf("x" # s "= %d, x" # t "= %s", \
x ## s, x ## t)
#define INCFILE(n) vers ## n
#define glue(a, b) a ## b
#define xglue(a, b) glue(a, b)
#define HIGHLOW "hello"
#define LOW LOW ", world"
debug(1, 2);
fputs(str(strncmp("abc\0d", "abc", '\4') // this goes away
== 0) str(: @\n), s);
\#include xstr(INCFILE(2).h)
glue(HIGH, LOW);
xglue(HIGH, LOW)

View File

@ -0,0 +1,5 @@
printf("x" "1" "= %d, x" "2" "= %s", x1, x2);
fputs("strncmp(\"abc\\0d\", \"abc\", '\\4') == 0" ": @\n", s);
\#include "vers2.h"
"hello";
"hello" ", world"

4
tests/pp/04.c 100644
View File

@ -0,0 +1,4 @@
#define foobar 1
#define C(x,y) x##y
#define D(x) (C(x,bar))
D(foo)

View File

@ -0,0 +1 @@
(1)

7
tests/pp/05.c 100644
View File

@ -0,0 +1,7 @@
#define t(x,y,z) x ## y ## z
#define xxx(s) int s[] = { t(1,2,3), t(,4,5), t(6,,7), t(8,9,), \
t(10,,), t(,11,), t(,,12), t(,,) };
int j[] = { t(1,2,3), t(,4,5), t(6,,7), t(8,9,),
t(10,,), t(,11,), t(,,12), t(,,) };
xxx(j)

View File

@ -0,0 +1,3 @@
int j[] = { 123, 45, 67, 89,
10, 11, 12, };
int j[] = { 123, 45, 67, 89, 10, 11, 12, };

5
tests/pp/06.c 100644
View File

@ -0,0 +1,5 @@
#define X(a,b, \
c,d) \
foo
X(1,2,3,4)

Some files were not shown because too many files have changed in this diff Show More