Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | Download | RSS feed

  1. This is tcc-doc.info, produced by makeinfo version 4.13 from
  2. D:\VSProjects\msys-kos32-4.8.2\ktcc\branch-0.9.27\source\tcc-doc.texi.
  3.  
  4. INFO-DIR-SECTION Software development
  5. START-INFO-DIR-ENTRY
  6. * TCC: (tcc-doc).               The Tiny C Compiler.
  7. END-INFO-DIR-ENTRY
  8.  
  9. 
  10. File: tcc-doc.info,  Node: Top,  Next: Introduction,  Prev: (dir),  Up: (dir)
  11.  
  12. Tiny C Compiler Reference Documentation
  13. ***************************************
  14.  
  15. This manual documents version 0.9.26 of the Tiny C Compiler.
  16.  
  17. * Menu:
  18.  
  19. * Introduction::                Introduction to tcc.
  20. * Invoke::                      Invocation of tcc (command line, options).
  21. * Clang::                       ANSI C and extensions.
  22. * asm::                         Assembler syntax.
  23. * linker::                      Output file generation and supported targets.
  24. * Bounds::                      Automatic bounds-checking of C code.
  25. * Libtcc::                      The libtcc library.
  26. * devel::                       Guide for Developers.
  27.  
  28. 
  29. File: tcc-doc.info,  Node: Introduction,  Next: Invoke,  Prev: Top,  Up: Top
  30.  
  31. 1 Introduction
  32. **************
  33.  
  34. TinyCC (aka TCC) is a small but hyper fast C compiler. Unlike other C
  35. compilers, it is meant to be self-relying: you do not need an external
  36. assembler or linker because TCC does that for you.
  37.  
  38.    TCC compiles so _fast_ that even for big projects `Makefile's may
  39. not be necessary.
  40.  
  41.    TCC not only supports ANSI C, but also most of the new ISO C99
  42. standard and many GNUC extensions including inline assembly.
  43.  
  44.    TCC can also be used to make _C scripts_, i.e. pieces of C source
  45. that you run as a Perl or Python script. Compilation is so fast that
  46. your script will be as fast as if it was an executable.
  47.  
  48.    TCC can also automatically generate memory and bound checks (*note
  49. Bounds::) while allowing all C pointers operations. TCC can do these
  50. checks even if non patched libraries are used.
  51.  
  52.    With `libtcc', you can use TCC as a backend for dynamic code
  53. generation (*note Libtcc::).
  54.  
  55.    TCC mainly supports the i386 target on Linux and Windows. There are
  56. alpha ports for the ARM (`arm-tcc') and the TMS320C67xx targets
  57. (`c67-tcc'). More information about the ARM port is available at
  58. `http://lists.gnu.org/archive/html/tinycc-devel/2003-10/msg00044.html'.
  59.  
  60.    For usage on Windows, see also `tcc-win32.txt'.
  61.  
  62. 
  63. File: tcc-doc.info,  Node: Invoke,  Next: Clang,  Prev: Introduction,  Up: Top
  64.  
  65. 2 Command line invocation
  66. *************************
  67.  
  68. 2.1 Quick start
  69. ===============
  70.  
  71.      usage: tcc [options] [INFILE1 INFILE2...] [`-run' INFILE ARGS...]
  72.  
  73. TCC options are a very much like gcc options. The main difference is
  74. that TCC can also execute directly the resulting program and give it
  75. runtime arguments.
  76.  
  77.    Here are some examples to understand the logic:
  78.  
  79. ``tcc -run a.c''
  80.      Compile `a.c' and execute it directly
  81.  
  82. ``tcc -run a.c arg1''
  83.      Compile a.c and execute it directly. arg1 is given as first
  84.      argument to the `main()' of a.c.
  85.  
  86. ``tcc a.c -run b.c arg1''
  87.      Compile `a.c' and `b.c', link them together and execute them. arg1
  88.      is given as first argument to the `main()' of the resulting
  89.      program.
  90.  
  91. ``tcc -o myprog a.c b.c''
  92.      Compile `a.c' and `b.c', link them and generate the executable
  93.      `myprog'.
  94.  
  95. ``tcc -o myprog a.o b.o''
  96.      link `a.o' and `b.o' together and generate the executable `myprog'.
  97.  
  98. ``tcc -c a.c''
  99.      Compile `a.c' and generate object file `a.o'.
  100.  
  101. ``tcc -c asmfile.S''
  102.      Preprocess with C preprocess and assemble `asmfile.S' and generate
  103.      object file `asmfile.o'.
  104.  
  105. ``tcc -c asmfile.s''
  106.      Assemble (but not preprocess) `asmfile.s' and generate object file
  107.      `asmfile.o'.
  108.  
  109. ``tcc -r -o ab.o a.c b.c''
  110.      Compile `a.c' and `b.c', link them together and generate the
  111.      object file `ab.o'.
  112.  
  113.  
  114.    Scripting:
  115.  
  116.    TCC can be invoked from _scripts_, just as shell scripts. You just
  117. need to add `#!/usr/local/bin/tcc -run' at the start of your C source:
  118.  
  119.      #!/usr/local/bin/tcc -run
  120.      #include <stdio.h>
  121.  
  122.      int main()
  123.      {
  124.          printf("Hello World\n");
  125.          return 0;
  126.      }
  127.  
  128.    TCC can read C source code from _standard input_ when `-' is used in
  129. place of `infile'. Example:
  130.  
  131.      echo 'main(){puts("hello");}' | tcc -run -
  132.  
  133. 2.2 Option summary
  134. ==================
  135.  
  136. General Options:
  137.  
  138. `-c'
  139.      Generate an object file.
  140.  
  141. `-o outfile'
  142.      Put object file, executable, or dll into output file `outfile'.
  143.  
  144. `-run source [args...]'
  145.      Compile file SOURCE and run it with the command line arguments
  146.      ARGS. In order to be able to give more than one argument to a
  147.      script, several TCC options can be given _after_ the `-run'
  148.      option, separated by spaces:
  149.           tcc "-run -L/usr/X11R6/lib -lX11" ex4.c
  150.      In a script, it gives the following header:
  151.           #!/usr/local/bin/tcc -run -L/usr/X11R6/lib -lX11
  152.  
  153. `-mfloat-abi (ARM only)'
  154.      Select the float ABI. Possible values: `softfp' and `hard'
  155.  
  156. `-dumpversion'
  157.      Print only the compiler version and nothing else.
  158.  
  159. `-v'
  160.      Display TCC version.
  161.  
  162. `-vv'
  163.      Show included files.  As sole argument, print search dirs (as
  164.      below).
  165.  
  166. `-bench'
  167.      Display compilation statistics.
  168.  
  169. `-print-search-dirs'
  170.      Print the configured installation directory and a list of library
  171.      and include directories tcc will search.
  172.  
  173.  
  174.    Preprocessor options:
  175.  
  176. `-Idir'
  177.      Specify an additional include path. Include paths are searched in
  178.      the order they are specified.
  179.  
  180.      System include paths are always searched after. The default system
  181.      include paths are: `/usr/local/include', `/usr/include' and
  182.      `PREFIX/lib/tcc/include'. (`PREFIX' is usually `/usr' or
  183.      `/usr/local').
  184.  
  185. `-Dsym[=val]'
  186.      Define preprocessor symbol `sym' to val. If val is not present,
  187.      its value is `1'. Function-like macros can also be defined:
  188.      `-DF(a)=a+1'
  189.  
  190. `-Usym'
  191.      Undefine preprocessor symbol `sym'.
  192.  
  193.    Compilation flags:
  194.  
  195.    Note: each of the following options has a negative form beginning
  196. with `-fno-'.
  197.  
  198. `-funsigned-char'
  199.      Let the `char' type be unsigned.
  200.  
  201. `-fsigned-char'
  202.      Let the `char' type be signed.
  203.  
  204. `-fno-common'
  205.      Do not generate common symbols for uninitialized data.
  206.  
  207. `-fleading-underscore'
  208.      Add a leading underscore at the beginning of each C symbol.
  209.  
  210. `-fms-extensions'
  211.      Allow a MS C compiler extensions to the language. Curretly this
  212.      assume a nested named structure declaration without identifier
  213.      behave like an unnamed one.
  214.  
  215. `-fdollars-in-identifiers'
  216.      Allow a dollars in identifiers.
  217.  
  218. `-fnormalize-inc-dirs'
  219.      Be more gcc compatible and remove non-existent or duplicate
  220.      directories from include paths. This helps to compile such
  221.      packages as coreutils.
  222.  
  223.  
  224.    Warning options:
  225.  
  226. `-w'
  227.      Disable all warnings.
  228.  
  229.  
  230.    Note: each of the following warning options has a negative form
  231. beginning with `-Wno-'.
  232.  
  233. `-Wimplicit-function-declaration'
  234.      Warn about implicit function declaration.
  235.  
  236. `-Wunsupported'
  237.      Warn about unsupported GCC features that are ignored by TCC.
  238.  
  239. `-Wwrite-strings'
  240.      Make string constants be of type `const char *' instead of `char
  241.      *'.
  242.  
  243. `-Werror'
  244.      Abort compilation if warnings are issued.
  245.  
  246. `-Wall'
  247.      Activate all warnings, except `-Werror', `-Wunusupported' and
  248.      `-Wwrite-strings'.
  249.  
  250.  
  251.    Linker options:
  252.  
  253. `-Ldir'
  254.      Specify an additional static library path for the `-l' option. The
  255.      default library paths are `/usr/local/lib', `/usr/lib' and `/lib'.
  256.  
  257. `-lxxx'
  258.      Link your program with dynamic library libxxx.so or static library
  259.      libxxx.a. The library is searched in the paths specified by the
  260.      `-L' option and `LIBRARY_PATH' variable.
  261.  
  262. `-Bdir'
  263.      Set the path where the tcc internal libraries (and include files)
  264.      can be found (default is `PREFIX/lib/tcc').
  265.  
  266. `-shared'
  267.      Generate a shared library instead of an executable.
  268.  
  269. `-soname name'
  270.      set name for shared library to be used at runtime
  271.  
  272. `-static'
  273.      Generate a statically linked executable (default is a shared linked
  274.      executable).
  275.  
  276. `-rdynamic'
  277.      Export global symbols to the dynamic linker. It is useful when a
  278.      library opened with `dlopen()' needs to access executable symbols.
  279.  
  280. `-r'
  281.      Generate an object file combining all input files.
  282.  
  283. `-Wl,-rpath=path'
  284.      Put custom seatch path for dynamic libraries into executable.
  285.  
  286. `-Wl,--oformat=fmt'
  287.      Use FMT as output format. The supported output formats are:
  288.     `elf32-i386'
  289.           ELF output format (default)
  290.  
  291.     `binary'
  292.           Binary image (only for executable output)
  293.  
  294.     `coff'
  295.           COFF output format (only for executable output for
  296.           TMS320C67xx target)
  297.  
  298. `-Wl,-subsystem=console/gui/wince/...'
  299.      Set type for PE (Windows) executables.
  300.  
  301. `-Wl,-[Ttext=# | section-alignment=# | file-alignment=# | image-base=# | stack=#]'
  302.      Modify executable layout.
  303.  
  304. `-Wl,-Bsymbolic'
  305.      Set DT_SYMBOLIC tag.
  306.  
  307.  
  308.    Debugger options:
  309.  
  310. `-g'
  311.      Generate run time debug information so that you get clear run time
  312.      error messages: ` test.c:68: in function 'test5()': dereferencing
  313.      invalid pointer' instead of the laconic `Segmentation fault'.
  314.  
  315. `-b'
  316.      Generate additional support code to check memory allocations and
  317.      array/pointer bounds. `-g' is implied. Note that the generated
  318.      code is slower and bigger in this case.
  319.  
  320.      Note: `-b' is only available on i386 when using libtcc for the
  321.      moment.
  322.  
  323. `-bt N'
  324.      Display N callers in stack traces. This is useful with `-g' or
  325.      `-b'.
  326.  
  327.  
  328.    Misc options:
  329.  
  330. `-MD'
  331.      Generate makefile fragment with dependencies.
  332.  
  333. `-MF depfile'
  334.      Use `depfile' as output for -MD.
  335.  
  336.  
  337.    Note: GCC options `-Ox', `-fx' and `-mx' are ignored.
  338.  
  339.    Environment variables that affect how tcc operates.
  340.  
  341. `CPATH'
  342.  
  343. `C_INCLUDE_PATH'
  344.      A colon-separated list of directories searched for include files,
  345.      directories given with `-I' are searched first.
  346.  
  347. `LIBRARY_PATH'
  348.      A colon-separated list of directories searched for libraries for
  349.      the `-l' option, directories given with `-L' are searched first.
  350.  
  351.  
  352. 
  353. File: tcc-doc.info,  Node: Clang,  Next: asm,  Prev: Invoke,  Up: Top
  354.  
  355. 3 C language support
  356. ********************
  357.  
  358. 3.1 ANSI C
  359. ==========
  360.  
  361. TCC implements all the ANSI C standard, including structure bit fields
  362. and floating point numbers (`long double', `double', and `float' fully
  363. supported).
  364.  
  365. 3.2 ISOC99 extensions
  366. =====================
  367.  
  368. TCC implements many features of the new C standard: ISO C99. Currently
  369. missing items are: complex and imaginary numbers.
  370.  
  371.    Currently implemented ISOC99 features:
  372.  
  373.    * variable length arrays.
  374.  
  375.    * 64 bit `long long' types are fully supported.
  376.  
  377.    * The boolean type `_Bool' is supported.
  378.  
  379.    * `__func__' is a string variable containing the current function
  380.      name.
  381.  
  382.    * Variadic macros: `__VA_ARGS__' can be used for    function-like
  383.      macros:
  384.               #define dprintf(level, __VA_ARGS__) printf(__VA_ARGS__)
  385.  
  386.      `dprintf' can then be used with a variable number of parameters.
  387.  
  388.    * Declarations can appear anywhere in a block (as in C++).
  389.  
  390.    * Array and struct/union elements can be initialized in any order by
  391.       using designators:
  392.               struct { int x, y; } st[10] = { [0].x = 1, [0].y = 2 };
  393.  
  394.               int tab[10] = { 1, 2, [5] = 5, [9] = 9};
  395.  
  396.    * Compound initializers are supported:
  397.               int *p = (int []){ 1, 2, 3 };
  398.      to initialize a pointer pointing to an initialized array. The same
  399.      works for structures and strings.
  400.  
  401.    * Hexadecimal floating point constants are supported:
  402.                     double d = 0x1234p10;
  403.  
  404.      is the same as writing
  405.                     double d = 4771840.0;
  406.  
  407.    * `inline' keyword is ignored.
  408.  
  409.    * `restrict' keyword is ignored.
  410.  
  411. 3.3 GNU C extensions
  412. ====================
  413.  
  414. TCC implements some GNU C extensions:
  415.  
  416.    * array designators can be used without '=':
  417.               int a[10] = { [0] 1, [5] 2, 3, 4 };
  418.  
  419.    * Structure field designators can be a label:
  420.               struct { int x, y; } st = { x: 1, y: 1};
  421.      instead of
  422.               struct { int x, y; } st = { .x = 1, .y = 1};
  423.  
  424.    * `\e' is ASCII character 27.
  425.  
  426.    * case ranges : ranges can be used in `case's:
  427.               switch(a) {
  428.               case 1 ... 9:
  429.                     printf("range 1 to 9\n");
  430.                     break;
  431.               default:
  432.                     printf("unexpected\n");
  433.                     break;
  434.               }
  435.  
  436.    * The keyword `__attribute__' is handled to specify variable or
  437.      function attributes. The following attributes are supported:
  438.         * `aligned(n)': align a variable or a structure field to n bytes
  439.           (must be a power of two).
  440.  
  441.         * `packed': force alignment of a variable or a structure field
  442.           to   1.
  443.  
  444.         * `section(name)': generate function or data in assembly section
  445.           name (name is a string containing the section name) instead
  446.           of the default section.
  447.  
  448.         * `unused': specify that the variable or the function is unused.
  449.  
  450.         * `cdecl': use standard C calling convention (default).
  451.  
  452.         * `stdcall': use Pascal-like calling convention.
  453.  
  454.         * `regparm(n)': use fast i386 calling convention. N must be
  455.           between 1 and 3. The first N function parameters are
  456.           respectively put in registers `%eax', `%edx' and `%ecx'.
  457.  
  458.         * `dllexport': export function from dll/executable (win32 only)
  459.  
  460.  
  461.      Here are some examples:
  462.               int a __attribute__ ((aligned(8), section(".mysection")));
  463.  
  464.      align variable `a' to 8 bytes and put it in section `.mysection'.
  465.  
  466.               int my_add(int a, int b) __attribute__ ((section(".mycodesection")))
  467.               {
  468.                   return a + b;
  469.               }
  470.  
  471.      generate function `my_add' in section `.mycodesection'.
  472.  
  473.    * GNU style variadic macros:
  474.               #define dprintf(fmt, args...) printf(fmt, ## args)
  475.  
  476.               dprintf("no arg\n");
  477.               dprintf("one arg %d\n", 1);
  478.  
  479.    * `__FUNCTION__' is interpreted as C99 `__func__' (so it has not
  480.      exactly the same semantics as string literal GNUC where it is a
  481.      string literal).
  482.  
  483.    * The `__alignof__' keyword can be used as `sizeof' to get the
  484.      alignment of a type or an expression.
  485.  
  486.    * The `typeof(x)' returns the type of `x'.  `x' is an expression or
  487.      a type.
  488.  
  489.    * Computed gotos: `&&label' returns a pointer of type `void *' on
  490.      the goto label `label'. `goto *expr' can be used to jump on the
  491.      pointer resulting from `expr'.
  492.  
  493.    * Inline assembly with asm instruction:
  494.           static inline void * my_memcpy(void * to, const void * from, size_t n)
  495.           {
  496.           int d0, d1, d2;
  497.           __asm__ __volatile__(
  498.                   "rep ; movsl\n\t"
  499.                   "testb $2,%b4\n\t"
  500.                   "je 1f\n\t"
  501.                   "movsw\n"
  502.                   "1:\ttestb $1,%b4\n\t"
  503.                   "je 2f\n\t"
  504.                   "movsb\n"
  505.                   "2:"
  506.                   : "=&c" (d0), "=&D" (d1), "=&S" (d2)
  507.                   :"0" (n/4), "q" (n),"1" ((long) to),"2" ((long) from)
  508.                   : "memory");
  509.           return (to);
  510.           }
  511.  
  512.      TCC includes its own x86 inline assembler with a `gas'-like (GNU
  513.      assembler) syntax. No intermediate files are generated. GCC 3.x
  514.      named operands are supported.
  515.  
  516.    * `__builtin_types_compatible_p()' and `__builtin_constant_p()' are
  517.      supported.
  518.  
  519.    * `#pragma pack' is supported for win32 compatibility.
  520.  
  521.  
  522. 3.4 TinyCC extensions
  523. =====================
  524.  
  525.    * `__TINYC__' is a predefined macro to indicate that you use TCC.
  526.  
  527.    * `#!' at the start of a line is ignored to allow scripting.
  528.  
  529.    * Binary digits can be entered (`0b101' instead of `5').
  530.  
  531.    * `__BOUNDS_CHECKING_ON' is defined if bound checking is activated.
  532.  
  533.  
  534. 
  535. File: tcc-doc.info,  Node: asm,  Next: linker,  Prev: Clang,  Up: Top
  536.  
  537. 4 TinyCC Assembler
  538. ******************
  539.  
  540. Since version 0.9.16, TinyCC integrates its own assembler. TinyCC
  541. assembler supports a gas-like syntax (GNU assembler). You can
  542. desactivate assembler support if you want a smaller TinyCC executable
  543. (the C compiler does not rely on the assembler).
  544.  
  545.    TinyCC Assembler is used to handle files with `.S' (C preprocessed
  546. assembler) and `.s' extensions. It is also used to handle the GNU
  547. inline assembler with the `asm' keyword.
  548.  
  549. 4.1 Syntax
  550. ==========
  551.  
  552. TinyCC Assembler supports most of the gas syntax. The tokens are the
  553. same as C.
  554.  
  555.    * C and C++ comments are supported.
  556.  
  557.    * Identifiers are the same as C, so you cannot use '.' or '$'.
  558.  
  559.    * Only 32 bit integer numbers are supported.
  560.  
  561.  
  562. 4.2 Expressions
  563. ===============
  564.  
  565.    * Integers in decimal, octal and hexa are supported.
  566.  
  567.    * Unary operators: +, -, ~.
  568.  
  569.    * Binary operators in decreasing priority order:
  570.  
  571.        1. *, /, %
  572.  
  573.        2. &, |, ^
  574.  
  575.        3. +, -
  576.  
  577.    * A value is either an absolute number or a label plus an offset.
  578.      All operators accept absolute values except '+' and '-'. '+' or
  579.      '-' can be used to add an offset to a label. '-' supports two
  580.      labels only if they are the same or if they are both defined and
  581.      in the same section.
  582.  
  583.  
  584. 4.3 Labels
  585. ==========
  586.  
  587.    * All labels are considered as local, except undefined ones.
  588.  
  589.    * Numeric labels can be used as local `gas'-like labels.  They can
  590.      be defined several times in the same source. Use 'b' (backward) or
  591.      'f' (forward) as suffix to reference them:
  592.  
  593.            1:
  594.                 jmp 1b /* jump to '1' label before */
  595.                 jmp 1f /* jump to '1' label after */
  596.            1:
  597.  
  598.  
  599. 4.4 Directives
  600. ==============
  601.  
  602. All directives are preceded by a '.'. The following directives are
  603. supported:
  604.  
  605.    * .align n[,value]
  606.  
  607.    * .skip n[,value]
  608.  
  609.    * .space n[,value]
  610.  
  611.    * .byte value1[,...]
  612.  
  613.    * .word value1[,...]
  614.  
  615.    * .short value1[,...]
  616.  
  617.    * .int value1[,...]
  618.  
  619.    * .long value1[,...]
  620.  
  621.    * .quad immediate_value1[,...]
  622.  
  623.    * .globl symbol
  624.  
  625.    * .global symbol
  626.  
  627.    * .section section
  628.  
  629.    * .text
  630.  
  631.    * .data
  632.  
  633.    * .bss
  634.  
  635.    * .fill repeat[,size[,value]]
  636.  
  637.    * .org n
  638.  
  639.    * .previous
  640.  
  641.    * .string string[,...]
  642.  
  643.    * .asciz string[,...]
  644.  
  645.    * .ascii string[,...]
  646.  
  647. 4.5 X86 Assembler
  648. =================
  649.  
  650. All X86 opcodes are supported. Only ATT syntax is supported (source
  651. then destination operand order). If no size suffix is given, TinyCC
  652. tries to guess it from the operand sizes.
  653.  
  654.    Currently, MMX opcodes are supported but not SSE ones.
  655.  
  656. 
  657. File: tcc-doc.info,  Node: linker,  Next: Bounds,  Prev: asm,  Up: Top
  658.  
  659. 5 TinyCC Linker
  660. ***************
  661.  
  662. 5.1 ELF file generation
  663. =======================
  664.  
  665. TCC can directly output relocatable ELF files (object files),
  666. executable ELF files and dynamic ELF libraries without relying on an
  667. external linker.
  668.  
  669.    Dynamic ELF libraries can be output but the C compiler does not
  670. generate position independent code (PIC). It means that the dynamic
  671. library code generated by TCC cannot be factorized among processes yet.
  672.  
  673.    TCC linker eliminates unreferenced object code in libraries. A
  674. single pass is done on the object and library list, so the order in
  675. which object files and libraries are specified is important (same
  676. constraint as GNU ld). No grouping options (`--start-group' and
  677. `--end-group') are supported.
  678.  
  679. 5.2 ELF file loader
  680. ===================
  681.  
  682. TCC can load ELF object files, archives (.a files) and dynamic
  683. libraries (.so).
  684.  
  685. 5.3 PE-i386 file generation
  686. ===========================
  687.  
  688. TCC for Windows supports the native Win32 executable file format
  689. (PE-i386).  It generates EXE files (console and gui) and DLL files.
  690.  
  691.    For usage on Windows, see also tcc-win32.txt.
  692.  
  693. 5.4 GNU Linker Scripts
  694. ======================
  695.  
  696. Because on many Linux systems some dynamic libraries (such as
  697. `/usr/lib/libc.so') are in fact GNU ld link scripts (horrible!), the
  698. TCC linker also supports a subset of GNU ld scripts.
  699.  
  700.    The `GROUP' and `FILE' commands are supported. `OUTPUT_FORMAT' and
  701. `TARGET' are ignored.
  702.  
  703.    Example from `/usr/lib/libc.so':
  704.      /* GNU ld script
  705.         Use the shared library, but some functions are only in
  706.         the static library, so try that secondarily.  */
  707.      GROUP ( /lib/libc.so.6 /usr/lib/libc_nonshared.a )
  708.  
  709. 
  710. File: tcc-doc.info,  Node: Bounds,  Next: Libtcc,  Prev: linker,  Up: Top
  711.  
  712. 6 TinyCC Memory and Bound checks
  713. ********************************
  714.  
  715. This feature is activated with the `-b' (*note Invoke::).
  716.  
  717.    Note that pointer size is _unchanged_ and that code generated with
  718. bound checks is _fully compatible_ with unchecked code. When a pointer
  719. comes from unchecked code, it is assumed to be valid. Even very obscure
  720. C code with casts should work correctly.
  721.  
  722.    For more information about the ideas behind this method, see
  723. `http://www.doc.ic.ac.uk/~phjk/BoundsChecking.html'.
  724.  
  725.    Here are some examples of caught errors:
  726.  
  727. Invalid range with standard string function:
  728.           {
  729.               char tab[10];
  730.               memset(tab, 0, 11);
  731.           }
  732.  
  733. Out of bounds-error in global or local arrays:
  734.           {
  735.               int tab[10];
  736.               for(i=0;i<11;i++) {
  737.                   sum += tab[i];
  738.               }
  739.           }
  740.  
  741. Out of bounds-error in malloc'ed data:
  742.           {
  743.               int *tab;
  744.               tab = malloc(20 * sizeof(int));
  745.               for(i=0;i<21;i++) {
  746.                   sum += tab4[i];
  747.               }
  748.               free(tab);
  749.           }
  750.  
  751. Access of freed memory:
  752.           {
  753.               int *tab;
  754.               tab = malloc(20 * sizeof(int));
  755.               free(tab);
  756.               for(i=0;i<20;i++) {
  757.                   sum += tab4[i];
  758.               }
  759.           }
  760.  
  761. Double free:
  762.           {
  763.               int *tab;
  764.               tab = malloc(20 * sizeof(int));
  765.               free(tab);
  766.               free(tab);
  767.           }
  768.  
  769.  
  770. 
  771. File: tcc-doc.info,  Node: Libtcc,  Next: devel,  Prev: Bounds,  Up: Top
  772.  
  773. 7 The `libtcc' library
  774. **********************
  775.  
  776. The `libtcc' library enables you to use TCC as a backend for dynamic
  777. code generation.
  778.  
  779.    Read the `libtcc.h' to have an overview of the API. Read
  780. `libtcc_test.c' to have a very simple example.
  781.  
  782.    The idea consists in giving a C string containing the program you
  783. want to compile directly to `libtcc'. Then you can access to any global
  784. symbol (function or variable) defined.
  785.  
  786. 
  787. File: tcc-doc.info,  Node: devel,  Prev: Libtcc,  Up: Top
  788.  
  789. 8 Developer's guide
  790. *******************
  791.  
  792. This chapter gives some hints to understand how TCC works. You can skip
  793. it if you do not intend to modify the TCC code.
  794.  
  795. 8.1 File reading
  796. ================
  797.  
  798. The `BufferedFile' structure contains the context needed to read a
  799. file, including the current line number. `tcc_open()' opens a new file
  800. and `tcc_close()' closes it. `inp()' returns the next character.
  801.  
  802. 8.2 Lexer
  803. =========
  804.  
  805. `next()' reads the next token in the current file. `next_nomacro()'
  806. reads the next token without macro expansion.
  807.  
  808.    `tok' contains the current token (see `TOK_xxx') constants.
  809. Identifiers and keywords are also keywords. `tokc' contains additional
  810. infos about the token (for example a constant value if number or string
  811. token).
  812.  
  813. 8.3 Parser
  814. ==========
  815.  
  816. The parser is hardcoded (yacc is not necessary). It does only one pass,
  817. except:
  818.  
  819.    * For initialized arrays with unknown size, a first pass is done to
  820.      count the number of elements.
  821.  
  822.    * For architectures where arguments are evaluated in reverse order,
  823.      a first pass is done to reverse the argument order.
  824.  
  825.  
  826. 8.4 Types
  827. =========
  828.  
  829. The types are stored in a single 'int' variable. It was chosen in the
  830. first stages of development when tcc was much simpler. Now, it may not
  831. be the best solution.
  832.  
  833.      #define VT_INT        0  /* integer type */
  834.      #define VT_BYTE       1  /* signed byte type */
  835.      #define VT_SHORT      2  /* short type */
  836.      #define VT_VOID       3  /* void type */
  837.      #define VT_PTR        4  /* pointer */
  838.      #define VT_ENUM       5  /* enum definition */
  839.      #define VT_FUNC       6  /* function type */
  840.      #define VT_STRUCT     7  /* struct/union definition */
  841.      #define VT_FLOAT      8  /* IEEE float */
  842.      #define VT_DOUBLE     9  /* IEEE double */
  843.      #define VT_LDOUBLE   10  /* IEEE long double */
  844.      #define VT_BOOL      11  /* ISOC99 boolean type */
  845.      #define VT_LLONG     12  /* 64 bit integer */
  846.      #define VT_LONG      13  /* long integer (NEVER USED as type, only
  847.                                  during parsing) */
  848.      #define VT_BTYPE      0x000f /* mask for basic type */
  849.      #define VT_UNSIGNED   0x0010  /* unsigned type */
  850.      #define VT_ARRAY      0x0020  /* array type (also has VT_PTR) */
  851.      #define VT_VLA        0x20000 /* VLA type (also has VT_PTR and VT_ARRAY) */
  852.      #define VT_BITFIELD   0x0040  /* bitfield modifier */
  853.      #define VT_CONSTANT   0x0800  /* const modifier */
  854.      #define VT_VOLATILE   0x1000  /* volatile modifier */
  855.      #define VT_DEFSIGN    0x2000  /* signed type */
  856.  
  857.      #define VT_STRUCT_SHIFT 18   /* structure/enum name shift (14 bits left) */
  858.  
  859.    When a reference to another type is needed (for pointers, functions
  860. and structures), the `32 - VT_STRUCT_SHIFT' high order bits are used to
  861. store an identifier reference.
  862.  
  863.    The `VT_UNSIGNED' flag can be set for chars, shorts, ints and long
  864. longs.
  865.  
  866.    Arrays are considered as pointers `VT_PTR' with the flag `VT_ARRAY'
  867. set. Variable length arrays are considered as special arrays and have
  868. flag `VT_VLA' set instead of `VT_ARRAY'.
  869.  
  870.    The `VT_BITFIELD' flag can be set for chars, shorts, ints and long
  871. longs. If it is set, then the bitfield position is stored from bits
  872. VT_STRUCT_SHIFT to VT_STRUCT_SHIFT + 5 and the bit field size is stored
  873. from bits VT_STRUCT_SHIFT + 6 to VT_STRUCT_SHIFT + 11.
  874.  
  875.    `VT_LONG' is never used except during parsing.
  876.  
  877.    During parsing, the storage of an object is also stored in the type
  878. integer:
  879.  
  880.      #define VT_EXTERN  0x00000080  /* extern definition */
  881.      #define VT_STATIC  0x00000100  /* static variable */
  882.      #define VT_TYPEDEF 0x00000200  /* typedef definition */
  883.      #define VT_INLINE  0x00000400  /* inline definition */
  884.      #define VT_IMPORT  0x00004000  /* win32: extern data imported from dll */
  885.      #define VT_EXPORT  0x00008000  /* win32: data exported from dll */
  886.      #define VT_WEAK    0x00010000  /* win32: data exported from dll */
  887.  
  888. 8.5 Symbols
  889. ===========
  890.  
  891. All symbols are stored in hashed symbol stacks. Each symbol stack
  892. contains `Sym' structures.
  893.  
  894.    `Sym.v' contains the symbol name (remember an idenfier is also a
  895. token, so a string is never necessary to store it). `Sym.t' gives the
  896. type of the symbol. `Sym.r' is usually the register in which the
  897. corresponding variable is stored. `Sym.c' is usually a constant
  898. associated to the symbol like its address for normal symbols, and the
  899. number of entries for symbols representing arrays.  Variable length
  900. array types use `Sym.c' as a location on the stack which holds the
  901. runtime sizeof for the type.
  902.  
  903.    Four main symbol stacks are defined:
  904.  
  905. `define_stack'
  906.      for the macros (`#define's).
  907.  
  908. `global_stack'
  909.      for the global variables, functions and types.
  910.  
  911. `local_stack'
  912.      for the local variables, functions and types.
  913.  
  914. `global_label_stack'
  915.      for the local labels (for `goto').
  916.  
  917. `label_stack'
  918.      for GCC block local labels (see the `__label__' keyword).
  919.  
  920.  
  921.    `sym_push()' is used to add a new symbol in the local symbol stack.
  922. If no local symbol stack is active, it is added in the global symbol
  923. stack.
  924.  
  925.    `sym_pop(st,b)' pops symbols from the symbol stack ST until the
  926. symbol B is on the top of stack. If B is NULL, the stack is emptied.
  927.  
  928.    `sym_find(v)' return the symbol associated to the identifier V. The
  929. local stack is searched first from top to bottom, then the global stack.
  930.  
  931. 8.6 Sections
  932. ============
  933.  
  934. The generated code and datas are written in sections. The structure
  935. `Section' contains all the necessary information for a given section.
  936. `new_section()' creates a new section. ELF file semantics is assumed
  937. for each section.
  938.  
  939.    The following sections are predefined:
  940.  
  941. `text_section'
  942.      is the section containing the generated code. IND contains the
  943.      current position in the code section.
  944.  
  945. `data_section'
  946.      contains initialized data
  947.  
  948. `bss_section'
  949.      contains uninitialized data
  950.  
  951. `bounds_section'
  952. `lbounds_section'
  953.      are used when bound checking is activated
  954.  
  955. `stab_section'
  956. `stabstr_section'
  957.      are used when debugging is active to store debug information
  958.  
  959. `symtab_section'
  960. `strtab_section'
  961.      contain the exported symbols (currently only used for debugging).
  962.  
  963.  
  964. 8.7 Code generation
  965. ===================
  966.  
  967. 8.7.1 Introduction
  968. ------------------
  969.  
  970. The TCC code generator directly generates linked binary code in one
  971. pass. It is rather unusual these days (see gcc for example which
  972. generates text assembly), but it can be very fast and surprisingly
  973. little complicated.
  974.  
  975.    The TCC code generator is register based. Optimization is only done
  976. at the expression level. No intermediate representation of expression is
  977. kept except the current values stored in the _value stack_.
  978.  
  979.    On x86, three temporary registers are used. When more registers are
  980. needed, one register is spilled into a new temporary variable on the
  981. stack.
  982.  
  983. 8.7.2 The value stack
  984. ---------------------
  985.  
  986. When an expression is parsed, its value is pushed on the value stack
  987. (VSTACK). The top of the value stack is VTOP. Each value stack entry is
  988. the structure `SValue'.
  989.  
  990.    `SValue.t' is the type. `SValue.r' indicates how the value is
  991. currently stored in the generated code. It is usually a CPU register
  992. index (`REG_xxx' constants), but additional values and flags are
  993. defined:
  994.  
  995.      #define VT_CONST     0x00f0
  996.      #define VT_LLOCAL    0x00f1
  997.      #define VT_LOCAL     0x00f2
  998.      #define VT_CMP       0x00f3
  999.      #define VT_JMP       0x00f4
  1000.      #define VT_JMPI      0x00f5
  1001.      #define VT_LVAL      0x0100
  1002.      #define VT_SYM       0x0200
  1003.      #define VT_MUSTCAST  0x0400
  1004.      #define VT_MUSTBOUND 0x0800
  1005.      #define VT_BOUNDED   0x8000
  1006.      #define VT_LVAL_BYTE     0x1000
  1007.      #define VT_LVAL_SHORT    0x2000
  1008.      #define VT_LVAL_UNSIGNED 0x4000
  1009.      #define VT_LVAL_TYPE     (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
  1010.  
  1011. `VT_CONST'
  1012.      indicates that the value is a constant. It is stored in the union
  1013.      `SValue.c', depending on its type.
  1014.  
  1015. `VT_LOCAL'
  1016.      indicates a local variable pointer at offset `SValue.c.i' in the
  1017.      stack.
  1018.  
  1019. `VT_CMP'
  1020.      indicates that the value is actually stored in the CPU flags (i.e.
  1021.      the value is the consequence of a test). The value is either 0 or
  1022.      1. The actual CPU flags used is indicated in `SValue.c.i'.
  1023.  
  1024.      If any code is generated which destroys the CPU flags, this value
  1025.      MUST be put in a normal register.
  1026.  
  1027. `VT_JMP'
  1028. `VT_JMPI'
  1029.      indicates that the value is the consequence of a conditional jump.
  1030.      For VT_JMP, it is 1 if the jump is taken, 0 otherwise. For VT_JMPI
  1031.      it is inverted.
  1032.  
  1033.      These values are used to compile the `||' and `&&' logical
  1034.      operators.
  1035.  
  1036.      If any code is generated, this value MUST be put in a normal
  1037.      register. Otherwise, the generated code won't be executed if the
  1038.      jump is taken.
  1039.  
  1040. `VT_LVAL'
  1041.      is a flag indicating that the value is actually an lvalue (left
  1042.      value of an assignment). It means that the value stored is
  1043.      actually a pointer to the wanted value.
  1044.  
  1045.      Understanding the use `VT_LVAL' is very important if you want to
  1046.      understand how TCC works.
  1047.  
  1048. `VT_LVAL_BYTE'
  1049. `VT_LVAL_SHORT'
  1050. `VT_LVAL_UNSIGNED'
  1051.      if the lvalue has an integer type, then these flags give its real
  1052.      type. The type alone is not enough in case of cast optimisations.
  1053.  
  1054. `VT_LLOCAL'
  1055.      is a saved lvalue on the stack. `VT_LVAL' must also be set with
  1056.      `VT_LLOCAL'. `VT_LLOCAL' can arise when a `VT_LVAL' in a register
  1057.      has to be saved to the stack, or it can come from an
  1058.      architecture-specific calling convention.
  1059.  
  1060. `VT_MUSTCAST'
  1061.      indicates that a cast to the value type must be performed if the
  1062.      value is used (lazy casting).
  1063.  
  1064. `VT_SYM'
  1065.      indicates that the symbol `SValue.sym' must be added to the
  1066.      constant.
  1067.  
  1068. `VT_MUSTBOUND'
  1069. `VT_BOUNDED'
  1070.      are only used for optional bound checking.
  1071.  
  1072.  
  1073. 8.7.3 Manipulating the value stack
  1074. ----------------------------------
  1075.  
  1076. `vsetc()' and `vset()' pushes a new value on the value stack. If the
  1077. previous VTOP was stored in a very unsafe place(for example in the CPU
  1078. flags), then some code is generated to put the previous VTOP in a safe
  1079. storage.
  1080.  
  1081.    `vpop()' pops VTOP. In some cases, it also generates cleanup code
  1082. (for example if stacked floating point registers are used as on x86).
  1083.  
  1084.    The `gv(rc)' function generates code to evaluate VTOP (the top value
  1085. of the stack) into registers. RC selects in which register class the
  1086. value should be put. `gv()' is the _most important function_ of the
  1087. code generator.
  1088.  
  1089.    `gv2()' is the same as `gv()' but for the top two stack entries.
  1090.  
  1091. 8.7.4 CPU dependent code generation
  1092. -----------------------------------
  1093.  
  1094. See the `i386-gen.c' file to have an example.
  1095.  
  1096. `load()'
  1097.      must generate the code needed to load a stack value into a
  1098.      register.
  1099.  
  1100. `store()'
  1101.      must generate the code needed to store a register into a stack
  1102.      value lvalue.
  1103.  
  1104. `gfunc_start()'
  1105. `gfunc_param()'
  1106. `gfunc_call()'
  1107.      should generate a function call
  1108.  
  1109. `gfunc_prolog()'
  1110. `gfunc_epilog()'
  1111.      should generate a function prolog/epilog.
  1112.  
  1113. `gen_opi(op)'
  1114.      must generate the binary integer operation OP on the two top
  1115.      entries of the stack which are guaranted to contain integer types.
  1116.  
  1117.      The result value should be put on the stack.
  1118.  
  1119. `gen_opf(op)'
  1120.      same as `gen_opi()' for floating point operations. The two top
  1121.      entries of the stack are guaranted to contain floating point
  1122.      values of same types.
  1123.  
  1124. `gen_cvt_itof()'
  1125.      integer to floating point conversion.
  1126.  
  1127. `gen_cvt_ftoi()'
  1128.      floating point to integer conversion.
  1129.  
  1130. `gen_cvt_ftof()'
  1131.      floating point to floating point of different size conversion.
  1132.  
  1133. `gen_bounded_ptr_add()'
  1134.  
  1135. `gen_bounded_ptr_deref()'
  1136.      are only used for bounds checking.
  1137.  
  1138.  
  1139. 8.8 Optimizations done
  1140. ======================
  1141.  
  1142. Constant propagation is done for all operations. Multiplications and
  1143. divisions are optimized to shifts when appropriate. Comparison
  1144. operators are optimized by maintaining a special cache for the
  1145. processor flags. &&, || and ! are optimized by maintaining a special
  1146. 'jump target' value. No other jump optimization is currently performed
  1147. because it would require to store the code in a more abstract fashion.
  1148.  
  1149. Concept Index
  1150. *************
  1151.  
  1152. [index]
  1153. * Menu:
  1154.  
  1155. * __asm__:                               Clang.               (line 141)
  1156. * align directive:                       asm.                 (line  68)
  1157. * aligned attribute:                     Clang.               (line  84)
  1158. * ascii directive:                       asm.                 (line  68)
  1159. * asciz directive:                       asm.                 (line  68)
  1160. * assembler:                             asm.                 (line 116)
  1161. * assembler directives:                  asm.                 (line  68)
  1162. * assembly, inline:                      Clang.               (line 141)
  1163. * bound checks:                          Bounds.              (line   6)
  1164. * bss directive:                         asm.                 (line  68)
  1165. * byte directive:                        asm.                 (line  68)
  1166. * caching processor flags:               devel.               (line 356)
  1167. * cdecl attribute:                       Clang.               (line  84)
  1168. * code generation:                       devel.               (line 181)
  1169. * comparison operators:                  devel.               (line 356)
  1170. * constant propagation:                  devel.               (line 356)
  1171. * CPU dependent:                         devel.               (line 308)
  1172. * data directive:                        asm.                 (line  68)
  1173. * directives, assembler:                 asm.                 (line  68)
  1174. * dllexport attribute:                   Clang.               (line  84)
  1175. * ELF:                                   linker.              (line   9)
  1176. * FILE, linker command:                  linker.              (line  40)
  1177. * fill directive:                        asm.                 (line  68)
  1178. * flags, caching:                        devel.               (line 356)
  1179. * gas:                                   Clang.               (line 160)
  1180. * global directive:                      asm.                 (line  68)
  1181. * globl directive:                       asm.                 (line  68)
  1182. * GROUP, linker command:                 linker.              (line  40)
  1183. * inline assembly:                       Clang.               (line 141)
  1184. * int directive:                         asm.                 (line  68)
  1185. * jump optimization:                     devel.               (line 356)
  1186. * linker:                                linker.              (line   6)
  1187. * linker scripts:                        linker.              (line  40)
  1188. * long directive:                        asm.                 (line  68)
  1189. * memory checks:                         Bounds.              (line   6)
  1190. * optimizations:                         devel.               (line 356)
  1191. * org directive:                         asm.                 (line  68)
  1192. * OUTPUT_FORMAT, linker command:         linker.              (line  40)
  1193. * packed attribute:                      Clang.               (line  84)
  1194. * PE-i386:                               linker.              (line  32)
  1195. * previous directive:                    asm.                 (line  68)
  1196. * quad directive:                        asm.                 (line  68)
  1197. * regparm attribute:                     Clang.               (line  84)
  1198. * scripts, linker:                       linker.              (line  40)
  1199. * section attribute:                     Clang.               (line  84)
  1200. * section directive:                     asm.                 (line  68)
  1201. * short directive:                       asm.                 (line  68)
  1202. * skip directive:                        asm.                 (line  68)
  1203. * space directive:                       asm.                 (line  68)
  1204. * stdcall attribute:                     Clang.               (line  84)
  1205. * strength reduction:                    devel.               (line 356)
  1206. * string directive:                      asm.                 (line  68)
  1207. * TARGET, linker command:                linker.              (line  40)
  1208. * text directive:                        asm.                 (line  68)
  1209. * unused attribute:                      Clang.               (line  84)
  1210. * value stack:                           devel.               (line 290)
  1211. * value stack, introduction:             devel.               (line 200)
  1212. * word directive:                        asm.                 (line  68)
  1213.  
  1214.  
  1215. 
  1216. Tag Table:
  1217. Node: Top265
  1218. Node: Introduction985
  1219. Node: Invoke2306
  1220. Node: Clang9971
  1221. Node: asm15669
  1222. Node: linker18270
  1223. Node: Bounds20001
  1224. Node: Libtcc21566
  1225. Node: devel22065
  1226. 
  1227. End Tag Table
  1228.