Subversion Repositories Kolibri OS

Rev

Rev 9517 | Rev 9557 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
6429 siemargl 1
/*
2
 *  TCC - Tiny C Compiler
3
 *
4
 *  Copyright (c) 2001-2004 Fabrice Bellard
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2 of the License, or (at your option) any later version.
10
 *
11
 * This library is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
 */
20
 
21
#include "tcc.h"
22
 
23
/********************************************************/
24
/* global variables */
25
 
26
/* use GNU C extensions */
27
ST_DATA int gnu_ext = 1;
28
 
29
/* use TinyCC extensions */
30
ST_DATA int tcc_ext = 1;
31
 
32
/* XXX: get rid of this ASAP */
33
ST_DATA struct TCCState *tcc_state;
34
 
35
/********************************************************/
36
 
37
#ifdef ONE_SOURCE
38
#include "tccpp.c"
39
#include "tccgen.c"
40
#include "tccelf.c"
41
#ifdef TCC_IS_NATIVE
42
# include "tccrun.c"
43
#endif
44
#ifdef TCC_TARGET_I386
45
#include "i386-gen.c"
46
#endif
47
#ifdef TCC_TARGET_ARM
48
#include "arm-gen.c"
49
#endif
50
#ifdef TCC_TARGET_ARM64
51
#include "arm64-gen.c"
52
#endif
53
#ifdef TCC_TARGET_C67
54
#include "c67-gen.c"
55
#endif
56
#ifdef TCC_TARGET_X86_64
57
#include "x86_64-gen.c"
58
#endif
59
#ifdef CONFIG_TCC_ASM
60
#include "tccasm.c"
61
#if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
62
#include "i386-asm.c"
63
#endif
64
#endif
65
#ifdef TCC_TARGET_COFF
66
#include "tcccoff.c"
67
#endif
68
#if defined(TCC_TARGET_PE) || defined(TCC_TARGET_MEOS)
69
#include "tccpe.c"
70
#endif
71
#ifdef TCC_TARGET_MEOS
72
#include "tccmeos.c"
73
#endif
9284 Coldy 74
#ifdef TCC_TARGET_KX
75
#include "tcckx.c"
76
#endif
8272 superturbo 77
#ifdef TCC_TARGET_MEOS_LINUX
78
#include 
79
#endif
6429 siemargl 80
 
8272 superturbo 81
 
6429 siemargl 82
#endif /* ONE_SOURCE */
83
 
84
/********************************************************/
85
#ifndef CONFIG_TCC_ASM
86
ST_FUNC void asm_instr(void)
87
{
88
    tcc_error("inline asm() not supported");
89
}
90
ST_FUNC void asm_global_instr(void)
91
{
92
    tcc_error("inline asm() not supported");
93
}
94
#endif
95
 
7520 siemargl 96
 
97
 
6429 siemargl 98
/********************************************************/
99
#ifdef _WIN32
100
static char *normalize_slashes(char *path)
101
{
102
    char *p;
103
    for (p = path; *p; ++p)
104
        if (*p == '\\')
105
            *p = '/';
106
    return path;
107
}
108
 
109
static HMODULE tcc_module;
110
 
111
/* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
112
static void tcc_set_lib_path_w32(TCCState *s)
113
{
114
    char path[1024], *p;
115
    GetModuleFileNameA(tcc_module, path, sizeof path);
9517 Coldy 116
#ifdef TCC_TARGET_KX
9513 Coldy 117
	kx_fix_root_directory(path, sizeof path);
118
    normalize_slashes(strlwr(path));
119
#else
6429 siemargl 120
    p = tcc_basename(normalize_slashes(strlwr(path)));
121
    if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
122
        p -= 5;
123
    else if (p > path)
124
        p--;
125
    *p = 0;
9513 Coldy 126
#endif
6429 siemargl 127
    tcc_set_lib_path(s, path);
128
}
129
 
130
#ifdef TCC_TARGET_PE
131
static void tcc_add_systemdir(TCCState *s)
132
{
133
    char buf[1000];
134
    GetSystemDirectory(buf, sizeof buf);
135
    tcc_add_library_path(s, normalize_slashes(buf));
136
}
137
#endif
138
 
139
#ifndef CONFIG_TCC_STATIC
140
void dlclose(void *p)
141
{
142
    FreeLibrary((HMODULE)p);
143
}
144
#endif
145
 
146
#ifdef LIBTCC_AS_DLL
147
BOOL WINAPI DllMain (HINSTANCE hDll, DWORD dwReason, LPVOID lpReserved)
148
{
149
    if (DLL_PROCESS_ATTACH == dwReason)
150
        tcc_module = hDll;
151
    return TRUE;
152
}
153
#endif
7520 siemargl 154
#else // _WIN32
8272 superturbo 155
#if defined TCC_TARGET_MEOS
7520 siemargl 156
/* on Kolibri host, we suppose the lib and includes are at the location of 'tcc' /lib, /include */
157
static void tcc_set_lib_path_kos(TCCState *s)
9517 Coldy 158
{
7520 siemargl 159
	char** argv0 = (char**)0x20; // path in kolibri header
9517 Coldy 160
    char path[1024], *p;
7520 siemargl 161
	strncpy(path, *argv0, sizeof path);
9517 Coldy 162
#ifdef TCC_TARGET_KX
9513 Coldy 163
	kx_fix_root_directory(path, sizeof path);
9517 Coldy 164
#else
7520 siemargl 165
	p = tcc_basename(path);
166
    if (p > path) p--;
167
    *p = 0;
9513 Coldy 168
#endif
7520 siemargl 169
    tcc_set_lib_path(s, path);
170
}
8272 superturbo 171
 
172
#if defined TCC_TARGET_MEOS_LINUX
173
static void tcc_set_lib_path_linux(TCCState *s)
174
{
175
    char buff[4096+1];
176
    readlink("/proc/self/exe", buff, 4096);
9517 Coldy 177
#ifdef TCC_TARGET_KX
9545 turbocat 178
	kx_fix_root_directory(buff, sizeof buff);
9513 Coldy 179
	const char *path = buff;
180
#else
8272 superturbo 181
    const char *path = dirname(buff);
9513 Coldy 182
#endif
8272 superturbo 183
    tcc_set_lib_path(s, path);
184
}
185
 
6429 siemargl 186
#endif
7520 siemargl 187
#endif
8272 superturbo 188
#endif
6429 siemargl 189
/********************************************************/
190
/* copy a string and truncate it. */
191
PUB_FUNC char *pstrcpy(char *buf, int buf_size, const char *s)
192
{
193
    char *q, *q_end;
194
    int c;
195
 
196
    if (buf_size > 0) {
197
        q = buf;
198
        q_end = buf + buf_size - 1;
199
        while (q < q_end) {
200
            c = *s++;
201
            if (c == '\0')
202
                break;
203
            *q++ = c;
204
        }
205
        *q = '\0';
206
    }
207
    return buf;
208
}
209
 
210
/* strcat and truncate. */
211
PUB_FUNC char *pstrcat(char *buf, int buf_size, const char *s)
212
{
213
    int len;
214
    len = strlen(buf);
215
    if (len < buf_size)
216
        pstrcpy(buf + len, buf_size - len, s);
217
    return buf;
218
}
219
 
220
PUB_FUNC char *pstrncpy(char *out, const char *in, size_t num)
221
{
222
    memcpy(out, in, num);
223
    out[num] = '\0';
224
    return out;
225
}
226
 
227
/* extract the basename of a file */
228
PUB_FUNC char *tcc_basename(const char *name)
229
{
230
    char *p = strchr(name, 0);
231
    while (p > name && !IS_DIRSEP(p[-1]))
232
        --p;
233
    return p;
234
}
235
 
236
/* extract extension part of a file
237
 *
238
 * (if no extension, return pointer to end-of-string)
239
 */
240
PUB_FUNC char *tcc_fileextension (const char *name)
241
{
242
    char *b = tcc_basename(name);
243
    char *e = strrchr(b, '.');
244
    return e ? e : strchr(b, 0);
245
}
246
 
247
/********************************************************/
248
/* memory management */
249
 
250
#undef free
251
#undef malloc
252
#undef realloc
253
 
254
#ifndef MEM_DEBUG
255
 
256
PUB_FUNC void tcc_free(void *ptr)
257
{
258
    free(ptr);
259
}
260
 
261
PUB_FUNC void *tcc_malloc(unsigned long size)
262
{
263
    void *ptr;
264
    ptr = malloc(size);
265
    if (!ptr && size)
266
        tcc_error("memory full (malloc)");
267
    return ptr;
268
}
269
 
270
PUB_FUNC void *tcc_mallocz(unsigned long size)
271
{
272
    void *ptr;
273
    ptr = tcc_malloc(size);
274
    memset(ptr, 0, size);
275
    return ptr;
276
}
277
 
278
PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
279
{
280
    void *ptr1;
281
    ptr1 = realloc(ptr, size);
282
    if (!ptr1 && size)
283
        tcc_error("memory full (realloc)");
284
    return ptr1;
285
}
286
 
287
PUB_FUNC char *tcc_strdup(const char *str)
288
{
289
    char *ptr;
290
    ptr = tcc_malloc(strlen(str) + 1);
291
    strcpy(ptr, str);
292
    return ptr;
293
}
294
 
295
PUB_FUNC void tcc_memstats(int bench)
296
{
297
}
298
 
299
#else
300
 
301
#define MEM_DEBUG_MAGIC1 0xFEEDDEB1
302
#define MEM_DEBUG_MAGIC2 0xFEEDDEB2
303
#define MEM_DEBUG_FILE_LEN 15
304
 
305
struct mem_debug_header {
306
    size_t      magic1;
307
    size_t      size;
308
    struct mem_debug_header *prev;
309
    struct mem_debug_header *next;
310
    size_t      line_num;
311
    char        file_name[MEM_DEBUG_FILE_LEN + 1];
312
    size_t      magic2;
313
};
314
 
315
typedef struct mem_debug_header mem_debug_header_t;
316
 
317
static mem_debug_header_t *mem_debug_chain;
318
static size_t mem_cur_size;
319
static size_t mem_max_size;
320
 
321
PUB_FUNC void *tcc_malloc_debug(unsigned long size, const char *file, int line)
322
{
323
    void *ptr;
324
    int ofs;
325
 
326
    mem_debug_header_t *header;
327
 
328
    ptr = malloc(sizeof(mem_debug_header_t) + size);
329
    if (!ptr)
330
        tcc_error("memory full (malloc)");
331
 
332
    mem_cur_size += size;
333
    if (mem_cur_size > mem_max_size)
334
        mem_max_size = mem_cur_size;
335
 
336
    header = (mem_debug_header_t *)ptr;
337
 
338
    header->magic1 = MEM_DEBUG_MAGIC1;
339
    header->magic2 = MEM_DEBUG_MAGIC2;
340
    header->size = size;
341
    header->line_num = line;
342
 
343
    ofs = strlen(file) - MEM_DEBUG_FILE_LEN;
344
    strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), MEM_DEBUG_FILE_LEN);
345
    header->file_name[MEM_DEBUG_FILE_LEN] = 0;
346
 
347
    header->next = mem_debug_chain;
348
    header->prev = NULL;
349
 
350
    if (header->next)
351
        header->next->prev = header;
352
 
353
    mem_debug_chain = header;
354
 
355
    ptr = (char *)ptr + sizeof(mem_debug_header_t);
356
    return ptr;
357
}
358
 
359
PUB_FUNC void tcc_free_debug(void *ptr)
360
{
361
    mem_debug_header_t *header;
362
 
363
    if (!ptr)
364
        return;
365
 
366
    ptr = (char *)ptr - sizeof(mem_debug_header_t);
367
    header = (mem_debug_header_t *)ptr;
368
    if (header->magic1 != MEM_DEBUG_MAGIC1 ||
369
        header->magic2 != MEM_DEBUG_MAGIC2 ||
370
        header->size == (size_t)-1 )
371
    {
372
        tcc_error("tcc_free check failed");
373
    }
374
 
375
    mem_cur_size -= header->size;
376
    header->size = (size_t)-1;
6441 siemargl 377
 
6429 siemargl 378
    if (header->next)
379
        header->next->prev = header->prev;
380
 
381
    if (header->prev)
382
        header->prev->next = header->next;
383
 
384
    if (header == mem_debug_chain)
385
        mem_debug_chain = header->next;
386
 
387
    free(ptr);
388
}
389
 
390
 
391
PUB_FUNC void *tcc_mallocz_debug(unsigned long size, const char *file, int line)
392
{
393
    void *ptr;
394
    ptr = tcc_malloc_debug(size,file,line);
395
    memset(ptr, 0, size);
396
    return ptr;
397
}
398
 
399
PUB_FUNC void *tcc_realloc_debug(void *ptr, unsigned long size, const char *file, int line)
400
{
401
    mem_debug_header_t *header;
402
    int mem_debug_chain_update = 0;
403
 
404
    if (!ptr) {
405
        ptr = tcc_malloc_debug(size, file, line);
406
        return ptr;
407
    }
408
 
409
    ptr = (char *)ptr - sizeof(mem_debug_header_t);
410
    header = (mem_debug_header_t *)ptr;
411
    if (header->magic1 != MEM_DEBUG_MAGIC1 ||
412
        header->magic2 != MEM_DEBUG_MAGIC2 ||
413
        header->size == (size_t)-1 )
414
    {
415
        check_error:
416
            tcc_error("tcc_realloc check failed");
417
    }
418
 
419
    mem_debug_chain_update = (header == mem_debug_chain);
420
 
421
    mem_cur_size -= header->size;
422
    ptr = realloc(ptr, sizeof(mem_debug_header_t) + size);
423
    if (!ptr)
424
        tcc_error("memory full (realloc)");
425
 
426
    header = (mem_debug_header_t *)ptr;
427
    if (header->magic1 != MEM_DEBUG_MAGIC1 ||
428
        header->magic2 != MEM_DEBUG_MAGIC2)
429
    {
430
        goto check_error;
431
    }
432
 
433
    mem_cur_size += size;
434
    if (mem_cur_size > mem_max_size)
435
        mem_max_size = mem_cur_size;
436
 
437
    header->size = size;
438
    if (header->next)
439
        header->next->prev = header;
440
 
441
    if (header->prev)
442
        header->prev->next = header;
443
 
444
    if (mem_debug_chain_update)
445
        mem_debug_chain = header;
446
 
447
    ptr = (char *)ptr + sizeof(mem_debug_header_t);
448
    return ptr;
449
}
450
 
451
PUB_FUNC char *tcc_strdup_debug(const char *str, const char *file, int line)
452
{
453
    char *ptr;
454
    ptr = tcc_malloc_debug(strlen(str) + 1, file, line);
455
    strcpy(ptr, str);
456
    return ptr;
457
}
458
 
459
PUB_FUNC void tcc_memstats(int bench)
460
{
461
    if (mem_cur_size) {
462
        mem_debug_header_t *header = mem_debug_chain;
463
 
464
        fprintf(stderr, "MEM_DEBUG: mem_leak= %d bytes, mem_max_size= %d bytes\n",
465
            mem_cur_size, mem_max_size);
466
 
467
        while (header) {
468
            fprintf(stderr, "  file %s, line %u: %u bytes\n",
469
                header->file_name, header->line_num, header->size);
470
            header = header->next;
471
        }
472
    }
473
    else if (bench)
474
        fprintf(stderr, "mem_max_size= %d bytes\n", mem_max_size);
475
}
476
 
477
#undef MEM_DEBUG_MAGIC1
478
#undef MEM_DEBUG_MAGIC2
479
#undef MEM_DEBUG_FILE_LEN
480
 
481
#endif
482
 
483
#define free(p) use_tcc_free(p)
484
#define malloc(s) use_tcc_malloc(s)
485
#define realloc(p, s) use_tcc_realloc(p, s)
486
 
487
/********************************************************/
488
/* dynarrays */
489
 
490
ST_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data)
491
{
492
    int nb, nb_alloc;
493
    void **pp;
494
 
495
    nb = *nb_ptr;
496
    pp = *ptab;
497
    /* every power of two we double array size */
498
    if ((nb & (nb - 1)) == 0) {
499
        if (!nb)
500
            nb_alloc = 1;
501
        else
502
            nb_alloc = nb * 2;
503
        pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
504
        *ptab = pp;
505
    }
506
    pp[nb++] = data;
507
    *nb_ptr = nb;
508
}
509
 
510
ST_FUNC void dynarray_reset(void *pp, int *n)
511
{
512
    void **p;
513
    for (p = *(void***)pp; *n; ++p, --*n)
514
        if (*p)
515
            tcc_free(*p);
516
    tcc_free(*(void**)pp);
517
    *(void**)pp = NULL;
518
}
519
 
520
static void tcc_split_path(TCCState *s, void ***p_ary, int *p_nb_ary, const char *in)
521
{
522
    const char *p;
523
    do {
524
        int c;
525
        CString str;
526
 
527
        cstr_new(&str);
528
        for (p = in; c = *p, c != '\0' && c != PATHSEP; ++p) {
529
            if (c == '{' && p[1] && p[2] == '}') {
530
                c = p[1], p += 2;
531
                if (c == 'B')
532
                    cstr_cat(&str, s->tcc_lib_path, -1);
533
            } else {
534
                cstr_ccat(&str, c);
535
            }
536
        }
537
        cstr_ccat(&str, '\0');
538
        dynarray_add(p_ary, p_nb_ary, tcc_strdup(str.data));
539
        cstr_free(&str);
540
        in = p+1;
541
    } while (*p);
542
}
543
 
544
/********************************************************/
545
 
546
ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
547
{
548
    Section *sec;
549
 
550
    sec = tcc_mallocz(sizeof(Section) + strlen(name));
551
    strcpy(sec->name, name);
552
    sec->sh_type = sh_type;
553
    sec->sh_flags = sh_flags;
554
    switch(sh_type) {
555
    case SHT_HASH:
556
    case SHT_REL:
557
    case SHT_RELA:
558
    case SHT_DYNSYM:
559
    case SHT_SYMTAB:
560
    case SHT_DYNAMIC:
561
        sec->sh_addralign = 4;
562
        break;
563
    case SHT_STRTAB:
564
        sec->sh_addralign = 1;
565
        break;
566
    default:
567
        sec->sh_addralign =  PTR_SIZE; /* gcc/pcc default aligment */
568
        break;
569
    }
570
 
571
    if (sh_flags & SHF_PRIVATE) {
572
        dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
573
    } else {
574
        sec->sh_num = s1->nb_sections;
575
        dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
576
    }
577
 
578
    return sec;
579
}
580
 
581
static void free_section(Section *s)
582
{
583
    tcc_free(s->data);
584
}
585
 
586
/* realloc section and set its content to zero */
587
ST_FUNC void section_realloc(Section *sec, unsigned long new_size)
588
{
589
    unsigned long size;
590
    unsigned char *data;
591
 
592
    size = sec->data_allocated;
593
    if (size == 0)
594
        size = 1;
595
    while (size < new_size)
596
        size = size * 2;
597
    data = tcc_realloc(sec->data, size);
598
    memset(data + sec->data_allocated, 0, size - sec->data_allocated);
599
    sec->data = data;
600
    sec->data_allocated = size;
601
}
602
 
603
/* reserve at least 'size' bytes in section 'sec' from
604
   sec->data_offset. */
605
ST_FUNC void *section_ptr_add(Section *sec, addr_t size)
606
{
607
    size_t offset, offset1;
608
 
609
    offset = sec->data_offset;
610
    offset1 = offset + size;
611
    if (offset1 > sec->data_allocated)
612
        section_realloc(sec, offset1);
613
    sec->data_offset = offset1;
614
    return sec->data + offset;
615
}
616
 
617
/* reserve at least 'size' bytes from section start */
618
ST_FUNC void section_reserve(Section *sec, unsigned long size)
619
{
620
    if (size > sec->data_allocated)
621
        section_realloc(sec, size);
622
    if (size > sec->data_offset)
623
        sec->data_offset = size;
624
}
625
 
626
/* return a reference to a section, and create it if it does not
627
   exists */
628
ST_FUNC Section *find_section(TCCState *s1, const char *name)
629
{
630
    Section *sec;
631
    int i;
632
    for(i = 1; i < s1->nb_sections; i++) {
633
        sec = s1->sections[i];
634
        if (!strcmp(name, sec->name))
635
            return sec;
636
    }
637
    /* sections are created as PROGBITS */
638
    return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
639
}
640
 
641
/* update sym->c so that it points to an external symbol in section
642
   'section' with value 'value' */
643
ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
644
                            addr_t value, unsigned long size,
645
                            int can_add_underscore)
646
{
647
    int sym_type, sym_bind, sh_num, info, other;
648
    ElfW(Sym) *esym;
649
    const char *name;
650
    char buf1[256];
651
 
652
#ifdef CONFIG_TCC_BCHECK
653
    char buf[32];
654
#endif
655
 
656
    if (section == NULL)
657
        sh_num = SHN_UNDEF;
658
    else if (section == SECTION_ABS)
659
        sh_num = SHN_ABS;
660
    else
661
        sh_num = section->sh_num;
662
 
663
    if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
664
        sym_type = STT_FUNC;
665
    } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
666
        sym_type = STT_NOTYPE;
667
    } else {
668
        sym_type = STT_OBJECT;
669
    }
670
 
671
    if (sym->type.t & VT_STATIC)
672
        sym_bind = STB_LOCAL;
673
    else {
674
        if (sym->type.t & VT_WEAK)
675
            sym_bind = STB_WEAK;
676
        else
677
            sym_bind = STB_GLOBAL;
678
    }
679
 
680
    if (!sym->c) {
681
        name = get_tok_str(sym->v, NULL);
682
#ifdef CONFIG_TCC_BCHECK
683
        if (tcc_state->do_bounds_check) {
684
            /* XXX: avoid doing that for statics ? */
685
            /* if bound checking is activated, we change some function
686
               names by adding the "__bound" prefix */
687
            switch(sym->v) {
688
#ifdef TCC_TARGET_PE
689
            /* XXX: we rely only on malloc hooks */
690
            case TOK_malloc:
691
            case TOK_free:
692
            case TOK_realloc:
693
            case TOK_memalign:
694
            case TOK_calloc:
695
#endif
696
            case TOK_memcpy:
697
            case TOK_memmove:
698
            case TOK_memset:
699
            case TOK_strlen:
700
            case TOK_strcpy:
701
            case TOK_alloca:
702
                strcpy(buf, "__bound_");
703
                strcat(buf, name);
704
                name = buf;
705
                break;
706
            }
707
        }
708
#endif
709
        other = 0;
710
 
711
#ifdef TCC_TARGET_PE
712
        if (sym->type.t & VT_EXPORT)
713
            other |= ST_PE_EXPORT;
714
        if (sym_type == STT_FUNC && sym->type.ref) {
715
            Sym *ref = sym->type.ref;
716
            if (ref->a.func_export)
717
                other |= ST_PE_EXPORT;
718
            if (ref->a.func_call == FUNC_STDCALL && can_add_underscore) {
719
                sprintf(buf1, "_%s@%d", name, ref->a.func_args * PTR_SIZE);
720
                name = buf1;
721
                other |= ST_PE_STDCALL;
722
                can_add_underscore = 0;
723
            }
724
        } else {
725
            if (find_elf_sym(tcc_state->dynsymtab_section, name))
726
                other |= ST_PE_IMPORT;
727
            if (sym->type.t & VT_IMPORT)
728
                other |= ST_PE_IMPORT;
729
        }
730
#else
731
        if (! (sym->type.t & VT_STATIC))
732
	    other = (sym->type.t & VT_VIS_MASK) >> VT_VIS_SHIFT;
733
#endif
734
        if (tcc_state->leading_underscore && can_add_underscore) {
735
            buf1[0] = '_';
736
            pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
737
            name = buf1;
738
        }
739
        if (sym->asm_label) {
740
            name = get_tok_str(sym->asm_label, NULL);
741
        }
742
        info = ELFW(ST_INFO)(sym_bind, sym_type);
743
        sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
744
    } else {
745
        esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
746
        esym->st_value = value;
747
        esym->st_size = size;
748
        esym->st_shndx = sh_num;
749
    }
750
}
751
 
752
ST_FUNC void put_extern_sym(Sym *sym, Section *section,
753
                           addr_t value, unsigned long size)
754
{
755
    put_extern_sym2(sym, section, value, size, 1);
756
}
757
 
758
/* add a new relocation entry to symbol 'sym' in section 's' */
759
ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type,
760
                     addr_t addend)
761
{
762
    int c = 0;
763
    if (sym) {
764
        if (0 == sym->c)
765
            put_extern_sym(sym, NULL, 0, 0);
766
        c = sym->c;
767
    }
768
    /* now we can add ELF relocation info */
769
    put_elf_reloca(symtab_section, s, offset, type, c, addend);
770
}
771
 
772
ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
773
{
774
    greloca(s, sym, offset, type, 0);
775
}
776
 
777
/********************************************************/
778
 
779
static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
780
{
781
    int len;
782
    len = strlen(buf);
783
    vsnprintf(buf + len, buf_size - len, fmt, ap);
784
}
785
 
786
static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
787
{
788
    va_list ap;
789
    va_start(ap, fmt);
790
    strcat_vprintf(buf, buf_size, fmt, ap);
791
    va_end(ap);
792
}
793
 
794
static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
795
{
796
    char buf[2048];
797
    BufferedFile **pf, *f;
798
 
799
    buf[0] = '\0';
800
    /* use upper file if inline ":asm:" or token ":paste:" */
801
    for (f = file; f && f->filename[0] == ':'; f = f->prev)
802
     ;
803
    if (f) {
804
        for(pf = s1->include_stack; pf < s1->include_stack_ptr; pf++)
805
            strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
806
                (*pf)->filename, (*pf)->line_num);
807
        if (f->line_num > 0) {
808
            strcat_printf(buf, sizeof(buf), "%s:%d: ",
809
                f->filename, f->line_num);
810
        } else {
811
            strcat_printf(buf, sizeof(buf), "%s: ",
812
                f->filename);
813
        }
814
    } else {
815
        strcat_printf(buf, sizeof(buf), "tcc: ");
816
    }
817
    if (is_warning)
818
        strcat_printf(buf, sizeof(buf), "warning: ");
819
    else
820
        strcat_printf(buf, sizeof(buf), "error: ");
821
    strcat_vprintf(buf, sizeof(buf), fmt, ap);
822
 
823
    if (!s1->error_func) {
824
        /* default case: stderr */
825
        if (s1->ppfp) /* print a newline during tcc -E */
826
            fprintf(s1->ppfp, "\n"), fflush(s1->ppfp);
6574 siemargl 827
#ifndef TCC_TARGET_MEOS
6429 siemargl 828
        fprintf(stderr, "%s\n", buf);
829
        fflush(stderr); /* print error/warning now (win32) */
6574 siemargl 830
#else
831
        fprintf(stdout, "%s\n", buf);
832
        fflush(stdout); /* print error/warning now (win32) */
833
#endif
6429 siemargl 834
    } else {
835
        s1->error_func(s1->error_opaque, buf);
836
    }
837
    if (!is_warning || s1->warn_error)
838
        s1->nb_errors++;
839
}
840
 
841
LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
842
                        void (*error_func)(void *opaque, const char *msg))
843
{
844
    s->error_opaque = error_opaque;
845
    s->error_func = error_func;
846
}
847
 
848
/* error without aborting current compilation */
849
PUB_FUNC void tcc_error_noabort(const char *fmt, ...)
850
{
851
    TCCState *s1 = tcc_state;
852
    va_list ap;
853
 
854
    va_start(ap, fmt);
855
    error1(s1, 0, fmt, ap);
856
    va_end(ap);
857
}
858
 
859
PUB_FUNC void tcc_error(const char *fmt, ...)
860
{
861
    TCCState *s1 = tcc_state;
862
    va_list ap;
863
 
864
    va_start(ap, fmt);
865
    error1(s1, 0, fmt, ap);
866
    va_end(ap);
867
    /* better than nothing: in some cases, we accept to handle errors */
868
    if (s1->error_set_jmp_enabled) {
869
        longjmp(s1->error_jmp_buf, 1);
870
    } else {
871
        /* XXX: eliminate this someday */
872
        exit(1);
873
    }
874
}
875
 
876
PUB_FUNC void tcc_warning(const char *fmt, ...)
877
{
878
    TCCState *s1 = tcc_state;
879
    va_list ap;
880
 
881
    if (s1->warn_none)
882
        return;
883
 
884
    va_start(ap, fmt);
885
    error1(s1, 1, fmt, ap);
886
    va_end(ap);
887
}
888
 
889
/********************************************************/
890
/* I/O layer */
891
 
892
ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
893
{
894
    BufferedFile *bf;
895
    int buflen = initlen ? initlen : IO_BUF_SIZE;
896
 
897
    bf = tcc_mallocz(sizeof(BufferedFile) + buflen);
898
    bf->buf_ptr = bf->buffer;
899
    bf->buf_end = bf->buffer + initlen;
900
    bf->buf_end[0] = CH_EOB; /* put eob symbol */
901
    pstrcpy(bf->filename, sizeof(bf->filename), filename);
902
#ifdef _WIN32
903
    normalize_slashes(bf->filename);
904
#endif
905
    bf->line_num = 1;
906
    bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
907
    bf->fd = -1;
908
    bf->prev = file;
909
    file = bf;
910
}
911
 
912
ST_FUNC void tcc_close(void)
913
{
914
    BufferedFile *bf = file;
915
    if (bf->fd > 0) {
916
        close(bf->fd);
917
        total_lines += bf->line_num;
918
    }
919
    file = bf->prev;
920
    tcc_free(bf);
921
}
922
 
923
ST_FUNC int tcc_open(TCCState *s1, const char *filename)
924
{
925
    int fd;
926
    if (strcmp(filename, "-") == 0)
927
        fd = 0, filename = "";
928
    else
929
        fd = open(filename, O_RDONLY | O_BINARY);
930
    if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
931
        printf("%s %*s%s\n", fd < 0 ? "nf":"->",
932
               (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
933
    if (fd < 0)
934
        return -1;
935
 
936
    tcc_open_bf(s1, filename, 0);
937
    file->fd = fd;
938
    return fd;
939
}
940
 
941
/* compile the C file opened in 'file'. Return non zero if errors. */
942
static int tcc_compile(TCCState *s1)
943
{
944
    Sym *define_start;
945
    char buf[512];
946
    volatile int section_sym;
947
 
948
#ifdef INC_DEBUG
949
    printf("%s: **** new file\n", file->filename);
950
#endif
951
    preprocess_init(s1);
952
 
953
    cur_text_section = NULL;
954
    funcname = "";
955
    anon_sym = SYM_FIRST_ANOM;
956
 
957
    /* file info: full path + filename */
958
    section_sym = 0; /* avoid warning */
959
    if (s1->do_debug) {
960
        section_sym = put_elf_sym(symtab_section, 0, 0,
961
                                  ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
962
                                  text_section->sh_num, NULL);
963
        getcwd(buf, sizeof(buf));
964
#ifdef _WIN32
965
        normalize_slashes(buf);
966
#endif
967
        pstrcat(buf, sizeof(buf), "/");
968
        put_stabs_r(buf, N_SO, 0, 0,
969
                    text_section->data_offset, text_section, section_sym);
970
        put_stabs_r(file->filename, N_SO, 0, 0,
971
                    text_section->data_offset, text_section, section_sym);
972
    }
973
    /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
974
       symbols can be safely used */
975
    put_elf_sym(symtab_section, 0, 0,
976
                ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
977
                SHN_ABS, file->filename);
978
 
979
    /* define some often used types */
980
    int_type.t = VT_INT;
981
 
982
    char_pointer_type.t = VT_BYTE;
983
    mk_pointer(&char_pointer_type);
984
 
985
#if PTR_SIZE == 4
986
    size_type.t = VT_INT;
987
#else
988
    size_type.t = VT_LLONG;
989
#endif
990
 
991
    func_old_type.t = VT_FUNC;
992
    func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
993
#ifdef TCC_TARGET_ARM
994
    arm_init(s1);
995
#endif
996
 
997
#if 0
998
    /* define 'void *alloca(unsigned int)' builtin function */
999
    {
1000
        Sym *s1;
1001
 
1002
        p = anon_sym++;
1003
        sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
1004
        s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
1005
        s1->next = NULL;
1006
        sym->next = s1;
1007
        sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
1008
    }
1009
#endif
1010
 
1011
    define_start = define_stack;
1012
    nocode_wanted = 1;
1013
 
1014
    if (setjmp(s1->error_jmp_buf) == 0) {
1015
        s1->nb_errors = 0;
1016
        s1->error_set_jmp_enabled = 1;
1017
 
1018
        ch = file->buf_ptr[0];
1019
        tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
1020
        parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | PARSE_FLAG_TOK_STR;
1021
        next();
1022
        decl(VT_CONST);
1023
        if (tok != TOK_EOF)
1024
            expect("declaration");
1025
        check_vstack();
1026
 
1027
        /* end of translation unit info */
1028
        if (s1->do_debug) {
1029
            put_stabs_r(NULL, N_SO, 0, 0,
1030
                        text_section->data_offset, text_section, section_sym);
1031
        }
1032
    }
1033
 
1034
    s1->error_set_jmp_enabled = 0;
1035
 
1036
    /* reset define stack, but leave -Dsymbols (may be incorrect if
1037
       they are undefined) */
1038
    free_defines(define_start);
1039
 
1040
    gen_inline_functions();
1041
 
1042
    sym_pop(&global_stack, NULL);
1043
    sym_pop(&local_stack, NULL);
1044
 
1045
    return s1->nb_errors != 0 ? -1 : 0;
1046
}
1047
 
1048
LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
1049
{
1050
    int len, ret;
1051
 
1052
    len = strlen(str);
1053
    tcc_open_bf(s, "", len);
1054
    memcpy(file->buffer, str, len);
1055
    ret = tcc_compile(s);
1056
    tcc_close();
1057
    return ret;
1058
}
1059
 
1060
/* define a preprocessor symbol. A value can also be provided with the '=' operator */
1061
LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
1062
{
1063
    int len1, len2;
1064
    /* default value */
1065
    if (!value)
1066
        value = "1";
1067
    len1 = strlen(sym);
1068
    len2 = strlen(value);
1069
 
1070
    /* init file structure */
1071
    tcc_open_bf(s1, "", len1 + len2 + 1);
1072
    memcpy(file->buffer, sym, len1);
1073
    file->buffer[len1] = ' ';
1074
    memcpy(file->buffer + len1 + 1, value, len2);
1075
 
1076
    /* parse with define parser */
1077
    ch = file->buf_ptr[0];
1078
    next_nomacro();
1079
    parse_define();
1080
 
1081
    tcc_close();
1082
}
1083
 
1084
/* undefine a preprocessor symbol */
1085
LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
1086
{
1087
    TokenSym *ts;
1088
    Sym *s;
1089
    ts = tok_alloc(sym, strlen(sym));
1090
    s = define_find(ts->tok);
1091
    /* undefine symbol by putting an invalid name */
1092
    if (s)
1093
        define_undef(s);
1094
}
1095
 
1096
/* cleanup all static data used during compilation */
1097
static void tcc_cleanup(void)
1098
{
1099
    if (NULL == tcc_state)
1100
        return;
1101
    tcc_state = NULL;
1102
 
1103
    preprocess_delete();
1104
 
1105
    /* free sym_pools */
1106
    dynarray_reset(&sym_pools, &nb_sym_pools);
1107
    /* reset symbol stack */
1108
    sym_free_first = NULL;
1109
}
1110
 
1111
LIBTCCAPI TCCState *tcc_new(void)
1112
{
1113
    TCCState *s;
1114
    char buffer[100];
1115
    int a,b,c;
1116
 
1117
    tcc_cleanup();
1118
 
1119
    s = tcc_mallocz(sizeof(TCCState));
1120
    if (!s)
1121
        return NULL;
1122
    tcc_state = s;
1123
#ifdef _WIN32
1124
    tcc_set_lib_path_w32(s);
1125
#else
8272 superturbo 1126
 
8250 superturbo 1127
#if defined TCC_TARGET_MEOS && ! TCC_TARGET_MEOS_LINUX
7520 siemargl 1128
    tcc_set_lib_path_kos(s);
1129
#else
8272 superturbo 1130
 
1131
#ifdef TCC_TARGET_MEOS_LINUX
1132
    tcc_set_lib_path_linux(s);
1133
#else
6429 siemargl 1134
    tcc_set_lib_path(s, CONFIG_TCCDIR);
1135
#endif
7520 siemargl 1136
#endif
8272 superturbo 1137
#endif
6429 siemargl 1138
    s->output_type = 0;
1139
    preprocess_new();
1140
    s->include_stack_ptr = s->include_stack;
1141
 
1142
    /* we add dummy defines for some special macros to speed up tests
1143
       and to have working defined() */
1144
    define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
1145
    define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
1146
    define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
1147
    define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
1148
 
1149
    /* define __TINYC__ 92X  */
1150
    sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
1151
    sprintf(buffer, "%d", a*10000 + b*100 + c);
1152
    tcc_define_symbol(s, "__TINYC__", buffer);
1153
 
1154
    /* standard defines */
1155
    tcc_define_symbol(s, "__STDC__", NULL);
1156
    tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
1157
    tcc_define_symbol(s, "__STDC_HOSTED__", NULL);
1158
 
1159
    /* target defines */
1160
#if defined(TCC_TARGET_I386)
1161
    tcc_define_symbol(s, "__i386__", NULL);
1162
    tcc_define_symbol(s, "__i386", NULL);
1163
    tcc_define_symbol(s, "i386", NULL);
1164
#elif defined(TCC_TARGET_X86_64)
1165
    tcc_define_symbol(s, "__x86_64__", NULL);
1166
#elif defined(TCC_TARGET_ARM)
1167
    tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
1168
    tcc_define_symbol(s, "__arm_elf__", NULL);
1169
    tcc_define_symbol(s, "__arm_elf", NULL);
1170
    tcc_define_symbol(s, "arm_elf", NULL);
1171
    tcc_define_symbol(s, "__arm__", NULL);
1172
    tcc_define_symbol(s, "__arm", NULL);
1173
    tcc_define_symbol(s, "arm", NULL);
1174
    tcc_define_symbol(s, "__APCS_32__", NULL);
1175
    tcc_define_symbol(s, "__ARMEL__", NULL);
1176
#if defined(TCC_ARM_EABI)
1177
    tcc_define_symbol(s, "__ARM_EABI__", NULL);
1178
#endif
1179
#if defined(TCC_ARM_HARDFLOAT)
1180
    s->float_abi = ARM_HARD_FLOAT;
1181
    tcc_define_symbol(s, "__ARM_PCS_VFP", NULL);
1182
#else
1183
    s->float_abi = ARM_SOFTFP_FLOAT;
1184
#endif
1185
#elif defined(TCC_TARGET_ARM64)
1186
    tcc_define_symbol(s, "__aarch64__", NULL);
1187
#endif
1188
 
1189
#ifdef TCC_TARGET_PE
1190
    tcc_define_symbol(s, "_WIN32", NULL);
1191
# ifdef TCC_TARGET_X86_64
1192
    tcc_define_symbol(s, "_WIN64", NULL);
1193
# endif
9153 turbocat 1194
#elif defined(TCC_TARGET_MEOS) || defined(TCC_TARGET_MEOS_LINUX)
1195
    tcc_define_symbol(s, "KOLIBRI",  NULL);
1196
    tcc_define_symbol(s, "_KOLIBRI", NULL);
1197
    tcc_define_symbol(s, "_KOLIBRI_",NULL);
9305 Coldy 1198
#ifdef TCC_TARGET_KX
1199
	tcc_define_symbol(s, "__KX__", NULL);
1200
#endif
6429 siemargl 1201
#else
1202
    tcc_define_symbol(s, "__unix__", NULL);
1203
    tcc_define_symbol(s, "__unix", NULL);
1204
    tcc_define_symbol(s, "unix", NULL);
1205
# if defined(__linux__)
1206
    tcc_define_symbol(s, "__linux__", NULL);
1207
    tcc_define_symbol(s, "__linux", NULL);
1208
# endif
1209
# if defined(__FreeBSD__)
1210
#  define str(s) #s
1211
    tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
1212
#  undef str
1213
# endif
1214
# if defined(__FreeBSD_kernel__)
1215
    tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
1216
# endif
1217
#endif
1218
# if defined(__NetBSD__)
1219
#  define str(s) #s
1220
    tcc_define_symbol(s, "__NetBSD__", str( __NetBSD__));
1221
#  undef str
1222
# endif
9153 turbocat 1223
 
6429 siemargl 1224
    /* TinyCC & gcc defines */
1225
#if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
1226
    tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
1227
    tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
1228
#else
1229
    tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
1230
    tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
1231
#endif
1232
 
1233
#ifdef TCC_TARGET_PE
1234
    tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
1235
    tcc_define_symbol(s, "__WINT_TYPE__", "unsigned short");
1236
#else
1237
    tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
1238
    /* wint_t is unsigned int by default, but (signed) int on BSDs
1239
       and unsigned short on windows.  Other OSes might have still
1240
       other conventions, sigh.  */
1241
#if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__NetBSD__)
1242
    tcc_define_symbol(s, "__WINT_TYPE__", "int");
1243
#else
1244
    tcc_define_symbol(s, "__WINT_TYPE__", "unsigned int");
1245
#endif
1246
#endif
1247
 
1248
#ifndef TCC_TARGET_PE
1249
    /* glibc defines */
1250
    tcc_define_symbol(s, "__REDIRECT(name, proto, alias)", "name proto __asm__ (#alias)");
1251
    tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)", "name proto __asm__ (#alias) __THROW");
1252
    /* paths for crt objects */
1253
    tcc_split_path(s, (void ***)&s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
1254
#endif
1255
 
1256
    /* no section zero */
1257
    dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1258
 
1259
    /* create standard sections */
1260
    text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1261
    data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1262
    bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1263
 
1264
    /* symbols are always generated for linking stage */
1265
    symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1266
                                ".strtab",
1267
                                ".hashtab", SHF_PRIVATE);
1268
    strtab_section = symtab_section->link;
1269
    s->symtab = symtab_section;
1270
 
1271
    /* private symbol table for dynamic symbols */
1272
    s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1273
                                      ".dynstrtab",
1274
                                      ".dynhashtab", SHF_PRIVATE);
1275
    s->alacarte_link = 1;
1276
    s->nocommon = 1;
1277
    s->warn_implicit_function_declaration = 1;
1278
 
1279
#ifdef CHAR_IS_UNSIGNED
1280
    s->char_is_unsigned = 1;
1281
#endif
1282
    /* enable this if you want symbols with leading underscore on windows: */
1283
#if 0 /* def TCC_TARGET_PE */
1284
    s->leading_underscore = 1;
1285
#endif
1286
#if 0 /* TCC_TARGET_MEOS */
1287
    s->leading_underscore = 1;
1288
#endif
1289
#ifdef TCC_TARGET_I386
1290
    s->seg_size = 32;
1291
#endif
1292
#ifdef TCC_IS_NATIVE
1293
    s->runtime_main = "main";
1294
#endif
1295
    return s;
1296
}
1297
 
1298
LIBTCCAPI void tcc_delete(TCCState *s1)
1299
{
1300
    int i;
1301
    int bench = s1->do_bench;
1302
 
1303
    tcc_cleanup();
1304
 
1305
    /* close a preprocessor output */
1306
    if (s1->ppfp && s1->ppfp != stdout)
1307
        fclose(s1->ppfp);
1308
    if (s1->dffp && s1->dffp != s1->ppfp)
1309
        fclose(s1->dffp);
1310
 
1311
    /* free all sections */
1312
    for(i = 1; i < s1->nb_sections; i++)
1313
        free_section(s1->sections[i]);
1314
    dynarray_reset(&s1->sections, &s1->nb_sections);
1315
 
1316
    for(i = 0; i < s1->nb_priv_sections; i++)
1317
        free_section(s1->priv_sections[i]);
1318
    dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1319
 
1320
    /* free any loaded DLLs */
1321
#ifdef TCC_IS_NATIVE
1322
    for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1323
        DLLReference *ref = s1->loaded_dlls[i];
1324
        if ( ref->handle )
1325
            dlclose(ref->handle);
1326
    }
1327
#endif
1328
 
1329
    /* free loaded dlls array */
1330
    dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1331
 
1332
    /* free library paths */
1333
    dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1334
    dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
1335
 
1336
    /* free include paths */
1337
    dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1338
    dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1339
    dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1340
 
1341
    tcc_free(s1->tcc_lib_path);
1342
    tcc_free(s1->soname);
1343
    tcc_free(s1->rpath);
1344
    tcc_free(s1->init_symbol);
1345
    tcc_free(s1->fini_symbol);
1346
    tcc_free(s1->outfile);
1347
    tcc_free(s1->deps_outfile);
1348
    dynarray_reset(&s1->files, &s1->nb_files);
1349
    dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
1350
    dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
1351
 
1352
#ifdef TCC_IS_NATIVE
1353
# ifdef HAVE_SELINUX
1354
    munmap (s1->write_mem, s1->mem_size);
1355
    munmap (s1->runtime_mem, s1->mem_size);
1356
# else
1357
    tcc_free(s1->runtime_mem);
1358
# endif
1359
#endif
1360
 
1361
    tcc_free(s1->sym_attrs);
1362
    tcc_free(s1);
1363
    tcc_memstats(bench);
1364
}
1365
 
1366
LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
1367
{
1368
    tcc_split_path(s, (void ***)&s->include_paths, &s->nb_include_paths, pathname);
1369
    return 0;
1370
}
1371
 
1372
LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
1373
{
1374
    tcc_split_path(s, (void ***)&s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
1375
    return 0;
1376
}
1377
 
1378
ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags, int filetype)
1379
{
1380
    ElfW(Ehdr) ehdr;
1381
    int fd, ret, size;
1382
 
1383
    parse_flags = 0;
1384
#ifdef CONFIG_TCC_ASM
1385
    /* if .S file, define __ASSEMBLER__ like gcc does */
1386
    if ((filetype == TCC_FILETYPE_ASM) || (filetype == TCC_FILETYPE_ASM_PP)) {
1387
        tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1388
        parse_flags = PARSE_FLAG_ASM_FILE;
1389
    }
1390
#endif
1391
 
1392
    /* open the file */
1393
    ret = tcc_open(s1, filename);
1394
    if (ret < 0) {
1395
        if (flags & AFF_PRINT_ERROR)
1396
            tcc_error_noabort("file '%s' not found", filename);
1397
        return ret;
1398
    }
1399
 
1400
    /* update target deps */
1401
    dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1402
            tcc_strdup(filename));
1403
 
1404
    if (flags & AFF_PREPROCESS) {
1405
        ret = tcc_preprocess(s1);
1406
        goto the_end;
1407
    }
1408
 
1409
    if (filetype == TCC_FILETYPE_C) {
1410
        /* C file assumed */
1411
        ret = tcc_compile(s1);
1412
        goto the_end;
1413
    }
1414
 
1415
#ifdef CONFIG_TCC_ASM
1416
    if (filetype == TCC_FILETYPE_ASM_PP) {
1417
        /* non preprocessed assembler */
1418
        ret = tcc_assemble(s1, 1);
1419
        goto the_end;
1420
    }
1421
 
1422
    if (filetype == TCC_FILETYPE_ASM) {
1423
        /* preprocessed assembler */
1424
        ret = tcc_assemble(s1, 0);
1425
        goto the_end;
1426
    }
1427
#endif
1428
 
1429
    fd = file->fd;
1430
    /* assume executable format: auto guess file type */
1431
    size = read(fd, &ehdr, sizeof(ehdr));
1432
    lseek(fd, 0, SEEK_SET);
1433
    if (size <= 0) {
1434
        tcc_error_noabort("could not read header");
1435
        goto the_end;
1436
    }
1437
 
1438
    if (size == sizeof(ehdr) &&
1439
        ehdr.e_ident[0] == ELFMAG0 &&
1440
        ehdr.e_ident[1] == ELFMAG1 &&
1441
        ehdr.e_ident[2] == ELFMAG2 &&
1442
        ehdr.e_ident[3] == ELFMAG3) {
1443
 
1444
        /* do not display line number if error */
1445
        file->line_num = 0;
1446
        if (ehdr.e_type == ET_REL) {
1447
            ret = tcc_load_object_file(s1, fd, 0);
1448
            goto the_end;
1449
 
1450
        }
1451
#if !defined(TCC_TARGET_PE) && !defined(TCC_TARGET_MEOS)
1452
        if (ehdr.e_type == ET_DYN) {
1453
            if (s1->output_type == TCC_OUTPUT_MEMORY) {
1454
#ifdef TCC_IS_NATIVE
1455
                void *h;
1456
                h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1457
                if (h)
1458
#endif
1459
                    ret = 0;
1460
            } else {
1461
                ret = tcc_load_dll(s1, fd, filename,
1462
                                   (flags & AFF_REFERENCED_DLL) != 0);
1463
            }
1464
            goto the_end;
1465
        }
1466
#endif
1467
        tcc_error_noabort("unrecognized ELF file");
1468
        goto the_end;
1469
    }
1470
 
1471
    if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
1472
        file->line_num = 0; /* do not display line number if error */
1473
        ret = tcc_load_archive(s1, fd);
1474
        goto the_end;
1475
    }
1476
 
1477
#ifdef TCC_TARGET_COFF
1478
    if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
1479
        ret = tcc_load_coff(s1, fd);
1480
        goto the_end;
1481
    }
1482
#endif
1483
 
9284 Coldy 1484
#if defined (TCC_TARGET_PE) ||  (defined(TCC_TARGET_MEOS)  && !defined(TCC_TARGET_KX))
6429 siemargl 1485
    ret = pe_load_file(s1, filename, fd);
9284 Coldy 1486
#elif defined(TCC_TARGET_KX)
1487
    ret = pe_load_def(s1, fd);
6429 siemargl 1488
#else
1489
    /* as GNU ld, consider it is an ld script if not recognized */
1490
    ret = tcc_load_ldscript(s1);
1491
#endif
1492
    if (ret < 0)
1493
        tcc_error_noabort("unrecognized file type");
1494
 
1495
the_end:
1496
    tcc_close();
1497
    return ret;
1498
}
1499
 
1500
LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename, int filetype)
1501
{
1502
    if (s->output_type == TCC_OUTPUT_PREPROCESS)
1503
        return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS, filetype);
1504
    else
1505
        return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR, filetype);
1506
}
1507
 
1508
LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1509
{
1510
    tcc_split_path(s, (void ***)&s->library_paths, &s->nb_library_paths, pathname);
1511
    return 0;
1512
}
1513
 
1514
static int tcc_add_library_internal(TCCState *s, const char *fmt,
1515
    const char *filename, int flags, char **paths, int nb_paths)
1516
{
1517
    char buf[1024];
1518
    int i;
1519
 
1520
    for(i = 0; i < nb_paths; i++) {
1521
        snprintf(buf, sizeof(buf), fmt, paths[i], filename);
7520 siemargl 1522
//printf("tcc_add_library_internal::added lib [%s]\n", buf);
6429 siemargl 1523
        if (tcc_add_file_internal(s, buf, flags, TCC_FILETYPE_BINARY) == 0)
1524
            return 0;
1525
    }
1526
    return -1;
1527
}
1528
 
1529
#if !defined(TCC_TARGET_PE) && !defined(TCC_TARGET_MEOS)
1530
/* find and load a dll. Return non zero if not found */
1531
/* XXX: add '-rpath' option support ? */
1532
ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1533
{
1534
    return tcc_add_library_internal(s, "%s/%s", filename, flags,
1535
        s->library_paths, s->nb_library_paths);
1536
}
1537
#endif
1538
 
1539
ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
1540
{
1541
    if (-1 == tcc_add_library_internal(s, "%s/%s",
1542
        filename, 0, s->crt_paths, s->nb_crt_paths))
1543
        tcc_error_noabort("file '%s' not found", filename);
1544
    return 0;
1545
}
1546
 
1547
/* the library name is the same as the argument of the '-l' option */
1548
LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1549
{
1550
#if defined(TCC_TARGET_PE) || defined(TCC_TARGET_MEOS)
1551
    const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1552
    const char **pp = s->static_link ? libs + 4 : libs;
1553
#else
1554
    const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1555
    const char **pp = s->static_link ? libs + 1 : libs;
1556
#endif
1557
    while (*pp) {
1558
        if (0 == tcc_add_library_internal(s, *pp,
1559
            libraryname, 0, s->library_paths, s->nb_library_paths))
1560
            return 0;
1561
        ++pp;
1562
    }
1563
    return -1;
1564
}
1565
 
1566
PUB_FUNC int tcc_add_library_err(TCCState *s, const char *libname)
1567
{
1568
    int ret = tcc_add_library(s, libname);
1569
    if (ret < 0)
1570
        tcc_error_noabort("cannot find library 'lib%s'", libname);
1571
    return ret;
1572
}
1573
 
1574
/* habdle #pragma comment(lib,) */
1575
ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1576
{
1577
    int i;
1578
    for (i = 0; i < s1->nb_pragma_libs; i++)
1579
        tcc_add_library_err(s1, s1->pragma_libs[i]);
1580
}
1581
 
1582
LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1583
{
1584
#if defined(TCC_TARGET_PE) || defined(TCC_TARGET_MEOS)
1585
    /* On x86_64 'val' might not be reachable with a 32bit offset.
1586
       So it is handled here as if it were in a DLL. */
1587
    pe_putimport(s, 0, name, (uintptr_t)val);
1588
#else
1589
    add_elf_sym(symtab_section, (uintptr_t)val, 0,
1590
        ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1591
        SHN_ABS, name);
1592
#endif
1593
    return 0;
1594
}
1595
 
1596
 
1597
/* Windows stat* ( https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx ):
1598
 * - st_gid, st_ino, st_uid: only valid on "unix" file systems (not FAT, NTFS, etc)
1599
 * - st_atime, st_ctime: not valid on FAT, valid on NTFS.
1600
 * - Other fields should be reasonably compatible (and S_ISDIR should work).
1601
 *
1602
 * BY_HANDLE_FILE_INFORMATION ( https://msdn.microsoft.com/en-us/library/windows/desktop/aa363788%28v=vs.85%29.aspx ):
1603
 * - File index (combined nFileIndexHigh and nFileIndexLow) _may_ change when the file is opened.
1604
 *   - But on NTFS: it's guaranteed to be the same value until the file is deleted.
1605
 * - On windows server 2012 there's a 128b file id, and the 64b one via
1606
 *   nFileIndex* is not guaranteed to be unique.
1607
 *
1608
 * - MS Docs suggest to that volume number with the file index could be used to
1609
 *   check if two handles refer to the same file.
1610
 */
1611
#ifndef _WIN32
1612
typedef struct stat                file_info_t;
1613
#else
1614
typedef BY_HANDLE_FILE_INFORMATION file_info_t;
1615
#endif
1616
 
1617
int get_file_info(const char *fname, file_info_t *out_info)
1618
{
1619
#ifndef _WIN32
1620
    return stat(fname, out_info);
1621
#else
1622
    int rv = 1;
1623
    HANDLE h = CreateFile(fname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1624
                          FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS, NULL);
1625
 
1626
    if (h != INVALID_HANDLE_VALUE) {
1627
        rv = !GetFileInformationByHandle(h, out_info);
1628
        CloseHandle(h);
1629
    }
1630
    return rv;
1631
#endif
1632
}
1633
 
1634
int is_dir(file_info_t *info)
1635
{
1636
#ifndef _WIN32
1637
    return S_ISDIR(info->st_mode);
1638
#else
1639
    return (info->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ==
1640
           FILE_ATTRIBUTE_DIRECTORY;
1641
#endif
1642
}
1643
 
1644
int is_same_file(const file_info_t *fi1, const file_info_t *fi2)
1645
{
1646
#ifndef _WIN32
1647
    return fi1->st_dev == fi2->st_dev &&
1648
           fi1->st_ino == fi2->st_ino;
1649
#else
1650
    return fi1->dwVolumeSerialNumber == fi2->dwVolumeSerialNumber &&
1651
           fi1->nFileIndexHigh       == fi2->nFileIndexHigh &&
1652
           fi1->nFileIndexLow        == fi2->nFileIndexLow;
1653
#endif
1654
}
1655
 
1656
static void
1657
tcc_normalize_inc_dirs_aux(file_info_t *stats, size_t *pnum, char **path)
1658
{
1659
    size_t i, num = *pnum;
1660
    if (get_file_info(*path, &stats[num]) || !is_dir(&stats[num]))
1661
        goto remove;
1662
    for (i = 0; i < num; i++)
1663
        if (is_same_file(&stats[i], &stats[num]))
1664
            goto remove;
1665
    *pnum = num + 1;
1666
    return;
1667
 remove:
1668
    tcc_free(*path);
1669
    *path = 0;
1670
}
1671
 
1672
/* Remove non-existent and duplicate directories from include paths. */
1673
ST_FUNC void tcc_normalize_inc_dirs(TCCState *s)
1674
{
1675
    file_info_t *stats =
1676
        tcc_malloc(((size_t)s->nb_sysinclude_paths + s->nb_include_paths) *
1677
                   sizeof(*stats));
1678
    size_t i, num = 0;
1679
    for (i = 0; i < s->nb_sysinclude_paths; i++)
1680
        tcc_normalize_inc_dirs_aux(stats, &num, &s->sysinclude_paths[i]);
1681
    for (i = 0; i < s->nb_include_paths; i++)
1682
        tcc_normalize_inc_dirs_aux(stats, &num, &s->include_paths[i]);
1683
    tcc_free(stats);
1684
}
1685
 
1686
LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
1687
{
1688
    s->output_type = output_type;
1689
 
1690
    if (s->output_type == TCC_OUTPUT_PREPROCESS) {
1691
        if (!s->outfile) {
1692
            s->ppfp = stdout;
1693
        } else {
1694
            s->ppfp = fopen(s->outfile, "w");
1695
            if (!s->ppfp)
1696
                tcc_error("could not write '%s'", s->outfile);
1697
        }
1698
        s->dffp = s->ppfp;
1699
        if (s->dflag == 'M')
1700
            s->ppfp = NULL;
1701
    }
1702
    if (s->option_C && !s->ppfp)
1703
        s->option_C = 0;
1704
 
1705
    if (!s->nostdinc) {
1706
        /* default include paths */
1707
        /* -isystem paths have already been handled */
1708
        tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
1709
    }
1710
 
1711
    /* if bound checking, then add corresponding sections */
1712
#ifdef CONFIG_TCC_BCHECK
1713
    if (s->do_bounds_check) {
1714
        /* define symbol */
1715
        tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1716
        /* create bounds sections */
1717
        bounds_section = new_section(s, ".bounds",
1718
                                     SHT_PROGBITS, SHF_ALLOC);
1719
        lbounds_section = new_section(s, ".lbounds",
1720
                                      SHT_PROGBITS, SHF_ALLOC);
1721
    }
1722
#endif
1723
 
1724
    if (s->char_is_unsigned) {
1725
        tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
1726
    }
1727
 
1728
    /* add debug sections */
1729
    if (s->do_debug) {
1730
        /* stab symbols */
1731
        stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
1732
        stab_section->sh_entsize = sizeof(Stab_Sym);
1733
        stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
1734
        put_elf_str(stabstr_section, "");
1735
        stab_section->link = stabstr_section;
1736
        /* put first entry */
1737
        put_stabs("", 0, 0, 0, 0);
1738
    }
1739
 
1740
    tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
1741
#ifdef TCC_TARGET_PE
1742
# ifdef _WIN32
1743
    tcc_add_systemdir(s);
1744
# endif
1745
#elif defined(TCC_TARGET_MEOS)
1746
    if (s->output_type != TCC_OUTPUT_OBJ && !s->nostdlib)
1747
    {
8799 turbocat 1748
        tcc_add_crt(s,"crt0.o");
9545 turbocat 1749
        tcc_add_library_err(s, "c");
1750
        tcc_add_library_err(s, "tcc1");
6429 siemargl 1751
    }
1752
#else
1753
    /* add libc crt1/crti objects */
1754
    if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1755
        !s->nostdlib) {
1756
        if (output_type != TCC_OUTPUT_DLL)
1757
            tcc_add_crt(s, "crt1.o");
1758
        tcc_add_crt(s, "crti.o");
1759
    }
1760
#endif
1761
 
1762
#ifdef CONFIG_TCC_BCHECK
1763
    if (s->do_bounds_check && (output_type == TCC_OUTPUT_EXE))
1764
    {
1765
        /* force a bcheck.o linking */
1766
        addr_t func = TOK___bound_init;
1767
        Sym *sym = external_global_sym(func, &func_old_type, 0);
1768
        if (!sym->c)
1769
            put_extern_sym(sym, NULL, 0, 0);
1770
    }
1771
#endif
1772
 
1773
    if (s->normalize_inc_dirs)
1774
        tcc_normalize_inc_dirs(s);
1775
    if (s->output_type == TCC_OUTPUT_PREPROCESS)
1776
        print_defines();
1777
 
1778
    return 0;
1779
}
1780
 
1781
LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1782
{
1783
    tcc_free(s->tcc_lib_path);
1784
    s->tcc_lib_path = tcc_strdup(path);
1785
}
1786
 
1787
#define WD_ALL    0x0001 /* warning is activated when using -Wall */
1788
#define FD_INVERT 0x0002 /* invert value before storing */
1789
 
1790
typedef struct FlagDef {
1791
    uint16_t offset;
1792
    uint16_t flags;
1793
    const char *name;
1794
} FlagDef;
1795
 
1796
static const FlagDef warning_defs[] = {
1797
    { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1798
    { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1799
    { offsetof(TCCState, warn_error), 0, "error" },
1800
    { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1801
      "implicit-function-declaration" },
1802
};
1803
 
1804
ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1805
                    const char *name, int value)
1806
{
1807
    int i;
1808
    const FlagDef *p;
1809
    const char *r;
1810
 
1811
    r = name;
1812
    if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
1813
        r += 3;
1814
        value = !value;
1815
    }
1816
    for(i = 0, p = flags; i < nb_flags; i++, p++) {
1817
        if (!strcmp(r, p->name))
1818
            goto found;
1819
    }
1820
    return -1;
1821
 found:
1822
    if (p->flags & FD_INVERT)
1823
        value = !value;
1824
    *(int *)((uint8_t *)s + p->offset) = value;
1825
    return 0;
1826
}
1827
 
1828
/* set/reset a warning */
1829
static int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1830
{
1831
    int i;
1832
    const FlagDef *p;
1833
 
1834
    if (!strcmp(warning_name, "all")) {
1835
        for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1836
            if (p->flags & WD_ALL)
1837
                *(int *)((uint8_t *)s + p->offset) = 1;
1838
        }
1839
		s->warn_unsupported = 1;  // siemargl. was unused flag about compiler features
1840
        return 0;
1841
    } else {
1842
        return set_flag(s, warning_defs, countof(warning_defs),
1843
                        warning_name, value);
1844
    }
1845
}
1846
 
1847
static const FlagDef flag_defs[] = {
1848
    { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1849
    { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1850
    { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1851
    { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1852
    { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1853
    { offsetof(TCCState, old_struct_init_code), 0, "old-struct-init-code" },
1854
    { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1855
    { offsetof(TCCState, normalize_inc_dirs), 0, "normalize-inc-dirs" },
1856
};
1857
 
1858
/* set/reset a flag */
1859
static int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1860
{
1861
    return set_flag(s, flag_defs, countof(flag_defs),
1862
                    flag_name, value);
1863
}
1864
 
1865
 
1866
static int strstart(const char *val, const char **str)
1867
{
1868
    const char *p, *q;
1869
    p = *str;
1870
    q = val;
1871
    while (*q) {
1872
        if (*p != *q)
1873
            return 0;
1874
        p++;
1875
        q++;
1876
    }
1877
    *str = p;
1878
    return 1;
1879
}
1880
 
1881
/* Like strstart, but automatically takes into account that ld options can
1882
 *
1883
 * - start with double or single dash (e.g. '--soname' or '-soname')
1884
 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1885
 *   or '-Wl,-soname=x.so')
1886
 *
1887
 * you provide `val` always in 'option[=]' form (no leading -)
1888
 */
1889
static int link_option(const char *str, const char *val, const char **ptr)
1890
{
1891
    const char *p, *q;
1892
 
1893
    /* there should be 1 or 2 dashes */
1894
    if (*str++ != '-')
1895
        return 0;
1896
    if (*str == '-')
1897
        str++;
1898
 
1899
    /* then str & val should match (potentialy up to '=') */
1900
    p = str;
1901
    q = val;
1902
 
1903
    while (*q != '\0' && *q != '=') {
1904
        if (*p != *q)
1905
            return 0;
1906
        p++;
1907
        q++;
1908
    }
1909
 
1910
    /* '=' near eos means ',' or '=' is ok */
1911
    if (*q == '=') {
1912
        if (*p != ',' && *p != '=')
1913
            return 0;
1914
        p++;
1915
        q++;
1916
    }
1917
 
1918
    if (ptr)
1919
        *ptr = p;
1920
    return 1;
1921
}
1922
 
1923
static const char *skip_linker_arg(const char **str)
1924
{
1925
    const char *s1 = *str;
1926
    const char *s2 = strchr(s1, ',');
1927
    *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1928
    return s2;
1929
}
1930
 
1931
static char *copy_linker_arg(const char *p)
1932
{
1933
    const char *q = p;
1934
    skip_linker_arg(&q);
1935
    return pstrncpy(tcc_malloc(q - p + 1), p, q - p);
1936
}
1937
 
1938
/* set linker options */
1939
static int tcc_set_linker(TCCState *s, const char *option)
8157 Boppan 1940
{
6429 siemargl 1941
    while (option && *option) {
1942
 
1943
        const char *p = option;
1944
        char *end = NULL;
1945
        int ignoring = 0;
1946
 
1947
        if (link_option(option, "Bsymbolic", &p)) {
1948
            s->symbolic = 1;
1949
        } else if (link_option(option, "nostdlib", &p)) {
1950
            s->nostdlib = 1;
1951
        } else if (link_option(option, "fini=", &p)) {
1952
            s->fini_symbol = copy_linker_arg(p);
1953
            ignoring = 1;
1954
        } else if (link_option(option, "image-base=", &p)
1955
                || link_option(option, "Ttext=", &p)) {
1956
            s->text_addr = strtoull(p, &end, 16);
1957
            s->has_text_addr = 1;
1958
        } else if (link_option(option, "init=", &p)) {
1959
            s->init_symbol = copy_linker_arg(p);
1960
            ignoring = 1;
1961
        } else if (link_option(option, "oformat=", &p)) {
1962
#if defined(TCC_TARGET_PE)
1963
            if (strstart("pe-", &p)) {
1964
#elif defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1965
            if (strstart("elf64-", &p)) {
1966
#else
1967
            if (strstart("elf32-", &p)) {
1968
#endif
1969
                s->output_format = TCC_OUTPUT_FORMAT_ELF;
1970
            } else if (!strcmp(p, "binary")) {
1971
                s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1972
#ifdef TCC_TARGET_COFF
1973
            } else if (!strcmp(p, "coff")) {
1974
                s->output_format = TCC_OUTPUT_FORMAT_COFF;
1975
#endif
1976
            } else
1977
                goto err;
1978
 
1979
        } else if (link_option(option, "as-needed", &p)) {
1980
            ignoring = 1;
1981
        } else if (link_option(option, "O", &p)) {
1982
            ignoring = 1;
1983
        } else if (link_option(option, "rpath=", &p)) {
1984
            s->rpath = copy_linker_arg(p);
1985
        } else if (link_option(option, "section-alignment=", &p)) {
1986
            s->section_align = strtoul(p, &end, 16);
1987
        } else if (link_option(option, "soname=", &p)) {
1988
            s->soname = copy_linker_arg(p);
1989
#ifdef TCC_TARGET_PE
1990
        } else if (link_option(option, "file-alignment=", &p)) {
1991
            s->pe_file_align = strtoul(p, &end, 16);
1992
        } else if (link_option(option, "stack=", &p)) {
1993
            s->pe_stack_size = strtoul(p, &end, 10);
1994
        } else if (link_option(option, "subsystem=", &p)) {
1995
#if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1996
            if (!strcmp(p, "native")) {
1997
                s->pe_subsystem = 1;
1998
            } else if (!strcmp(p, "console")) {
1999
                s->pe_subsystem = 3;
2000
            } else if (!strcmp(p, "gui")) {
2001
                s->pe_subsystem = 2;
2002
            } else if (!strcmp(p, "posix")) {
2003
                s->pe_subsystem = 7;
2004
            } else if (!strcmp(p, "efiapp")) {
2005
                s->pe_subsystem = 10;
2006
            } else if (!strcmp(p, "efiboot")) {
2007
                s->pe_subsystem = 11;
2008
            } else if (!strcmp(p, "efiruntime")) {
2009
                s->pe_subsystem = 12;
2010
            } else if (!strcmp(p, "efirom")) {
2011
                s->pe_subsystem = 13;
2012
#elif defined(TCC_TARGET_ARM)
2013
            if (!strcmp(p, "wince")) {
2014
                s->pe_subsystem = 9;
2015
#endif
2016
            } else
2017
                goto err;
2018
#endif
2019
        } else
2020
            goto err;
2021
 
2022
        if (ignoring && s->warn_unsupported) err: {
2023
            char buf[100], *e;
2024
            pstrcpy(buf, sizeof buf, e = copy_linker_arg(option)), tcc_free(e);
2025
            if (ignoring)
2026
                tcc_warning("unsupported linker option '%s'", buf);
2027
            else
2028
                tcc_error("unsupported linker option '%s'", buf);
2029
        }
2030
        option = skip_linker_arg(&p);
2031
    }
2032
    return 0;
2033
}
2034
 
2035
typedef struct TCCOption {
2036
    const char *name;
2037
    uint16_t index;
2038
    uint16_t flags;
2039
} TCCOption;
2040
 
2041
enum {
2042
    TCC_OPTION_HELP,
2043
    TCC_OPTION_I,
2044
    TCC_OPTION_D,
2045
    TCC_OPTION_U,
2046
    TCC_OPTION_P,
2047
    TCC_OPTION_L,
2048
    TCC_OPTION_B,
2049
    TCC_OPTION_l,
2050
    TCC_OPTION_bench,
2051
    TCC_OPTION_bt,
2052
    TCC_OPTION_b,
2053
    TCC_OPTION_g,
2054
    TCC_OPTION_c,
2055
    TCC_OPTION_C,
2056
    TCC_OPTION_dumpversion,
2057
    TCC_OPTION_d,
2058
    TCC_OPTION_float_abi,
2059
    TCC_OPTION_static,
2060
    TCC_OPTION_std,
2061
    TCC_OPTION_shared,
2062
    TCC_OPTION_soname,
2063
    TCC_OPTION_o,
2064
    TCC_OPTION_r,
2065
    TCC_OPTION_s,
2066
    TCC_OPTION_traditional,
2067
    TCC_OPTION_Wl,
2068
    TCC_OPTION_W,
2069
    TCC_OPTION_O,
2070
    TCC_OPTION_m,
2071
    TCC_OPTION_f,
2072
    TCC_OPTION_isystem,
2073
    TCC_OPTION_iwithprefix,
2074
    TCC_OPTION_nostdinc,
2075
    TCC_OPTION_nostdlib,
2076
    TCC_OPTION_print_search_dirs,
2077
    TCC_OPTION_rdynamic,
2078
    TCC_OPTION_pedantic,
2079
    TCC_OPTION_pthread,
2080
    TCC_OPTION_run,
2081
    TCC_OPTION_v,
2082
    TCC_OPTION_w,
2083
    TCC_OPTION_pipe,
2084
    TCC_OPTION_E,
2085
    TCC_OPTION_MD,
2086
    TCC_OPTION_MF,
6441 siemargl 2087
    TCC_OPTION_x,
8157 Boppan 2088
    TCC_OPTION_stack,
2089
    TCC_OPTION_nobss
6429 siemargl 2090
};
2091
 
2092
#define TCC_OPTION_HAS_ARG 0x0001
2093
#define TCC_OPTION_NOSEP   0x0002 /* cannot have space before option and arg */
2094
 
2095
static const TCCOption tcc_options[] = {
2096
    { "h", TCC_OPTION_HELP, 0 },
2097
    { "-help", TCC_OPTION_HELP, 0 },
2098
    { "?", TCC_OPTION_HELP, 0 },
2099
    { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
2100
    { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
2101
    { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
2102
    { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2103
    { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
2104
    { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
2105
    { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2106
    { "bench", TCC_OPTION_bench, 0 },
2107
#ifdef CONFIG_TCC_BACKTRACE
2108
    { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
2109
#endif
2110
#ifdef CONFIG_TCC_BCHECK
2111
    { "b", TCC_OPTION_b, 0 },
2112
#endif
2113
    { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2114
    { "c", TCC_OPTION_c, 0 },
2115
    { "C", TCC_OPTION_C, 0 },
2116
    { "dumpversion", TCC_OPTION_dumpversion, 0},
2117
    { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2118
#ifdef TCC_TARGET_ARM
2119
    { "mfloat-abi", TCC_OPTION_float_abi, TCC_OPTION_HAS_ARG },
2120
#endif
2121
    { "static", TCC_OPTION_static, 0 },
2122
    { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2123
    { "shared", TCC_OPTION_shared, 0 },
2124
    { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
2125
    { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
2126
    { "pedantic", TCC_OPTION_pedantic, 0},
2127
    { "pthread", TCC_OPTION_pthread, 0},
2128
    { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2129
    { "rdynamic", TCC_OPTION_rdynamic, 0 },
2130
    { "r", TCC_OPTION_r, 0 },
2131
    { "s", TCC_OPTION_s, 0 },
2132
    { "traditional", TCC_OPTION_traditional, 0 },
2133
    { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2134
    { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2135
    { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2136
    { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
2137
    { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2138
    { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
2139
    { "iwithprefix", TCC_OPTION_iwithprefix, TCC_OPTION_HAS_ARG },
2140
    { "nostdinc", TCC_OPTION_nostdinc, 0 },
2141
    { "nostdlib", TCC_OPTION_nostdlib, 0 },
2142
    { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
2143
    { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2144
    { "w", TCC_OPTION_w, 0 },
2145
    { "pipe", TCC_OPTION_pipe, 0},
2146
    { "E", TCC_OPTION_E, 0},
2147
    { "MD", TCC_OPTION_MD, 0},
2148
    { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
2149
    { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
6441 siemargl 2150
    { "stack", TCC_OPTION_stack, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP},
9284 Coldy 2151
#if defined(TCC_TARGET_MEOS) && !defined (TCC_TARGET_KX)
8157 Boppan 2152
    { "nobss", TCC_OPTION_nobss, 0 },
9284 Coldy 2153
#endif
6429 siemargl 2154
    { NULL, 0, 0 },
2155
};
2156
 
2157
static void parse_option_D(TCCState *s1, const char *optarg)
2158
{
2159
    char *sym = tcc_strdup(optarg);
2160
    char *value = strchr(sym, '=');
2161
    if (value)
2162
        *value++ = '\0';
2163
    tcc_define_symbol(s1, sym, value);
2164
    tcc_free(sym);
2165
}
2166
 
2167
static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
2168
{
2169
    int len = strlen(filename);
2170
    char *p = tcc_malloc(len + 2);
2171
    if (filetype) {
2172
        *p = filetype;
2173
    }
2174
    else {
2175
        /* use a file extension to detect a filetype */
2176
        const char *ext = tcc_fileextension(filename);
2177
        if (ext[0]) {
2178
            ext++;
2179
            if (!strcmp(ext, "S"))
2180
                *p = TCC_FILETYPE_ASM_PP;
2181
            else
2182
            if (!strcmp(ext, "s"))
2183
                *p = TCC_FILETYPE_ASM;
2184
            else
2185
            if (!PATHCMP(ext, "c") || !PATHCMP(ext, "i"))
2186
                *p = TCC_FILETYPE_C;
2187
            else
2188
                *p = TCC_FILETYPE_BINARY;
2189
        }
2190
        else {
2191
            *p = TCC_FILETYPE_C;
2192
        }
2193
    }
2194
    strcpy(p+1, filename);
2195
    dynarray_add((void ***)&s->files, &s->nb_files, p);
2196
}
2197
 
2198
ST_FUNC int tcc_parse_args1(TCCState *s, int argc, char **argv)
2199
{
2200
    const TCCOption *popt;
2201
    const char *optarg, *r;
2202
    int optind = 0;
2203
    ParseArgsState *pas = s->parse_args_state;
2204
 
6460 siemargl 2205
/*
2206
#ifdef TCC_TARGET_MEOS
2207
// siemargl testing
2208
	s->output_format = TCC_OUTPUT_FORMAT_COFF;
2209
#endif
2210
*/
6429 siemargl 2211
    while (optind < argc) {
2212
 
2213
        r = argv[optind++];
2214
        if (r[0] != '-' || r[1] == '\0') {
2215
            /* handle list files */
2216
            if (r[0] == '@' && r[1]) {
2217
                char buf[sizeof file->filename], *p;
2218
                char **argv = NULL;
2219
                int argc = 0;
2220
                FILE *fp;
2221
 
2222
                fp = fopen(r + 1, "rb");
2223
                if (fp == NULL)
2224
                    tcc_error("list file '%s' not found", r + 1);
2225
                while (fgets(buf, sizeof buf, fp)) {
2226
                    p = trimfront(trimback(buf, strchr(buf, 0)));
2227
                    if (0 == *p || ';' == *p)
2228
                        continue;
2229
                    dynarray_add((void ***)&argv, &argc, tcc_strdup(p));
2230
                }
2231
                fclose(fp);
2232
                tcc_parse_args1(s, argc, argv);
2233
                dynarray_reset(&argv, &argc);
2234
            } else {
2235
                args_parser_add_file(s, r, pas->filetype);
2236
                if (pas->run) {
2237
                    optind--;
2238
                    /* argv[0] will be this file */
2239
                    break;
2240
                }
2241
            }
2242
            continue;
2243
        }
2244
 
2245
        /* find option in table */
2246
        for(popt = tcc_options; ; ++popt) {
2247
            const char *p1 = popt->name;
2248
            const char *r1 = r + 1;
2249
            if (p1 == NULL)
2250
                tcc_error("invalid option -- '%s'", r);
2251
            if (!strstart(p1, &r1))
2252
                continue;
2253
            optarg = r1;
2254
            if (popt->flags & TCC_OPTION_HAS_ARG) {
2255
                if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
2256
                    if (optind >= argc)
2257
                        tcc_error("argument to '%s' is missing", r);
2258
                    optarg = argv[optind++];
2259
                }
2260
            } else if (*r1 != '\0')
2261
                continue;
2262
            break;
2263
        }
2264
 
2265
        switch(popt->index) {
2266
        case TCC_OPTION_HELP:
2267
            return 0;
2268
        case TCC_OPTION_I:
2269
            tcc_add_include_path(s, optarg);
2270
            break;
2271
        case TCC_OPTION_D:
2272
            parse_option_D(s, optarg);
2273
            break;
2274
        case TCC_OPTION_U:
2275
            tcc_undefine_symbol(s, optarg);
2276
            break;
2277
        case TCC_OPTION_L:
2278
            tcc_add_library_path(s, optarg);
2279
            break;
2280
        case TCC_OPTION_B:
2281
            /* set tcc utilities path (mainly for tcc development) */
2282
            tcc_set_lib_path(s, optarg);
2283
            break;
2284
        case TCC_OPTION_l:
2285
            args_parser_add_file(s, r, TCC_FILETYPE_BINARY);
2286
            s->nb_libraries++;
2287
            break;
2288
        case TCC_OPTION_pthread:
2289
            parse_option_D(s, "_REENTRANT");
2290
            pas->pthread = 1;
2291
            break;
2292
        case TCC_OPTION_bench:
2293
            s->do_bench = 1;
2294
            break;
2295
#ifdef CONFIG_TCC_BACKTRACE
2296
        case TCC_OPTION_bt:
2297
            tcc_set_num_callers(atoi(optarg));
2298
            break;
2299
#endif
2300
#ifdef CONFIG_TCC_BCHECK
2301
        case TCC_OPTION_b:
2302
            s->do_bounds_check = 1;
2303
            s->do_debug = 1;
2304
            break;
2305
#endif
2306
        case TCC_OPTION_g:
2307
            s->do_debug = 1;
2308
            break;
2309
        case TCC_OPTION_c:
2310
            if (s->output_type)
2311
                tcc_warning("-c: some compiler action already specified (%d)", s->output_type);
2312
            s->output_type = TCC_OUTPUT_OBJ;
2313
            break;
2314
        case TCC_OPTION_C:
2315
            s->option_C = 1;
2316
            break;
2317
        case TCC_OPTION_d:
2318
            if (*optarg == 'D' || *optarg == 'M')
2319
                s->dflag = *optarg;
2320
            else {
2321
                if (s->warn_unsupported)
2322
                    goto unsupported_option;
2323
                tcc_error("invalid option -- '%s'", r);
2324
            }
2325
            break;
2326
#ifdef TCC_TARGET_ARM
2327
        case TCC_OPTION_float_abi:
2328
            /* tcc doesn't support soft float yet */
2329
            if (!strcmp(optarg, "softfp")) {
2330
                s->float_abi = ARM_SOFTFP_FLOAT;
2331
                tcc_undefine_symbol(s, "__ARM_PCS_VFP");
2332
            } else if (!strcmp(optarg, "hard"))
2333
                s->float_abi = ARM_HARD_FLOAT;
2334
            else
2335
                tcc_error("unsupported float abi '%s'", optarg);
2336
            break;
2337
#endif
2338
        case TCC_OPTION_static:
2339
            s->static_link = 1;
2340
            break;
2341
        case TCC_OPTION_std:
2342
    	    /* silently ignore, a current purpose:
2343
    	       allow to use a tcc as a reference compiler for "make test" */
2344
            break;
2345
        case TCC_OPTION_shared:
2346
    	    if (s->output_type)
2347
                tcc_warning("-shared: some compiler action already specified (%d)", s->output_type);
2348
            s->output_type = TCC_OUTPUT_DLL;
2349
            break;
2350
        case TCC_OPTION_soname:
2351
            s->soname = tcc_strdup(optarg);
2352
            break;
2353
        case TCC_OPTION_m:
2354
            s->option_m = tcc_strdup(optarg);
2355
            break;
2356
        case TCC_OPTION_o:
2357
            if (s->outfile) {
2358
                tcc_warning("multiple -o option");
2359
                tcc_free(s->outfile);
2360
            }
2361
            s->outfile = tcc_strdup(optarg);
2362
            break;
2363
        case TCC_OPTION_r:
2364
            /* generate a .o merging several output files */
2365
    	    if (s->output_type)
2366
                tcc_warning("-r: some compiler action already specified (%d)", s->output_type);
2367
            s->option_r = 1;
2368
            s->output_type = TCC_OUTPUT_OBJ;
2369
            break;
2370
        case TCC_OPTION_isystem:
2371
            tcc_add_sysinclude_path(s, optarg);
2372
            break;
2373
        case TCC_OPTION_iwithprefix:
2374
            if (1) {
2375
                char buf[1024];
2376
                int buf_size = sizeof(buf)-1;
2377
                char *p = &buf[0];
2378
 
2379
                char *sysroot = "{B}/";
2380
                int len = strlen(sysroot);
2381
                if (len > buf_size)
2382
                    len = buf_size;
2383
                strncpy(p, sysroot, len);
2384
                p += len;
2385
                buf_size -= len;
2386
 
2387
                len = strlen(optarg);
2388
                if (len > buf_size)
2389
                    len = buf_size;
2390
                strncpy(p, optarg, len+1);
2391
                tcc_add_sysinclude_path(s, buf);
2392
            }
2393
            break;
2394
        case TCC_OPTION_nostdinc:
2395
            s->nostdinc = 1;
2396
            break;
2397
        case TCC_OPTION_nostdlib:
2398
            s->nostdlib = 1;
2399
            break;
2400
        case TCC_OPTION_print_search_dirs:
2401
            s->print_search_dirs = 1;
2402
            break;
2403
        case TCC_OPTION_run:
2404
    	    if (s->output_type)
2405
                tcc_warning("-run: some compiler action already specified (%d)", s->output_type);
2406
            s->output_type = TCC_OUTPUT_MEMORY;
2407
            tcc_set_options(s, optarg);
2408
            pas->run = 1;
2409
            break;
2410
        case TCC_OPTION_v:
2411
            do ++s->verbose; while (*optarg++ == 'v');
2412
            break;
2413
        case TCC_OPTION_f:
2414
            if (tcc_set_flag(s, optarg, 1) < 0 && s->warn_unsupported)
2415
                goto unsupported_option;
2416
            break;
2417
        case TCC_OPTION_W:
2418
            if (tcc_set_warning(s, optarg, 1) < 0 &&
2419
                s->warn_unsupported)
2420
                goto unsupported_option;
2421
            break;
2422
        case TCC_OPTION_w:
2423
            s->warn_none = 1;
2424
            break;
2425
        case TCC_OPTION_rdynamic:
2426
            s->rdynamic = 1;
2427
            break;
2428
        case TCC_OPTION_Wl:
2429
            if (pas->linker_arg.size)
2430
                --pas->linker_arg.size, cstr_ccat(&pas->linker_arg, ',');
2431
            cstr_cat(&pas->linker_arg, optarg, 0);
2432
            break;
2433
        case TCC_OPTION_E:
2434
    	    if (s->output_type)
2435
                tcc_warning("-E: some compiler action already specified (%d)", s->output_type);
2436
            s->output_type = TCC_OUTPUT_PREPROCESS;
2437
            break;
2438
        case TCC_OPTION_P:
2439
            s->Pflag = atoi(optarg) + 1;
2440
            break;
2441
        case TCC_OPTION_MD:
2442
            s->gen_deps = 1;
2443
            break;
2444
        case TCC_OPTION_MF:
2445
            s->deps_outfile = tcc_strdup(optarg);
2446
            break;
2447
        case TCC_OPTION_dumpversion:
2448
            printf ("%s\n", TCC_VERSION);
2449
            exit(0);
2450
        case TCC_OPTION_s:
2451
            s->do_strip = 1;
2452
            break;
2453
        case TCC_OPTION_traditional:
2454
            break;
2455
        case TCC_OPTION_x:
2456
            if (*optarg == 'c')
2457
                pas->filetype = TCC_FILETYPE_C;
2458
            else
2459
            if (*optarg == 'a')
2460
                pas->filetype = TCC_FILETYPE_ASM_PP;
2461
            else
2462
            if (*optarg == 'n')
2463
                pas->filetype = 0;
2464
            else
2465
                tcc_warning("unsupported language '%s'", optarg);
2466
            break;
2467
        case TCC_OPTION_O:
2468
            if (1) {
2469
                int opt = atoi(optarg);
2470
                char *sym = "__OPTIMIZE__";
2471
                if (opt)
2472
                    tcc_define_symbol(s, sym, 0);
2473
                else
2474
                    tcc_undefine_symbol(s, sym);
2475
            }
2476
            break;
2477
        case TCC_OPTION_pedantic:
2478
        case TCC_OPTION_pipe:
2479
            /* ignored */
2480
            break;
6441 siemargl 2481
        case TCC_OPTION_stack:
8157 Boppan 2482
#ifdef TCC_TARGET_MEOS
2483
            s->pe_stack_size = strtoul(optarg+1, NULL, 10);
2484
#endif
6441 siemargl 2485
            break;
9284 Coldy 2486
#if defined(TCC_TARGET_MEOS) && !defined (TCC_TARGET_KX)
8157 Boppan 2487
        case TCC_OPTION_nobss:
2488
            s->nobss = 1;
2489
            break;
9284 Coldy 2490
#endif
6429 siemargl 2491
        default:
2492
            if (s->warn_unsupported) {
2493
            unsupported_option:
2494
                tcc_warning("unsupported option '%s'", r);
2495
            }
2496
            break;
2497
        }
2498
    }
2499
    return optind;
2500
}
2501
 
2502
PUB_FUNC int tcc_parse_args(TCCState *s, int argc, char **argv)
2503
{
2504
    ParseArgsState *pas;
2505
    int ret, is_allocated = 0;
2506
 
2507
    if (!s->parse_args_state) {
2508
        s->parse_args_state = tcc_mallocz(sizeof(ParseArgsState));
2509
        cstr_new(&s->parse_args_state->linker_arg);
2510
        is_allocated = 1;
2511
    }
2512
    pas = s->parse_args_state;
2513
 
2514
    ret = tcc_parse_args1(s, argc, argv);
2515
 
2516
    if (s->output_type == 0)
2517
        s->output_type = TCC_OUTPUT_EXE;
2518
 
2519
    if (pas->pthread && s->output_type != TCC_OUTPUT_OBJ)
2520
        tcc_set_options(s, "-lpthread");
2521
 
2522
    if (s->output_type == TCC_OUTPUT_EXE)
2523
        tcc_set_linker(s, (const char *)pas->linker_arg.data);
2524
 
2525
    if (is_allocated) {
2526
        cstr_free(&pas->linker_arg);
2527
        tcc_free(pas);
2528
        s->parse_args_state = NULL;
2529
    }
2530
    return ret;
2531
}
2532
 
2533
LIBTCCAPI int tcc_set_options(TCCState *s, const char *str)
2534
{
2535
    const char *s1;
2536
    char **argv, *arg;
2537
    int argc, len;
2538
    int ret;
2539
 
2540
    argc = 0, argv = NULL;
2541
    for(;;) {
2542
        while (is_space(*str))
2543
            str++;
2544
        if (*str == '\0')
2545
            break;
2546
        s1 = str;
2547
        while (*str != '\0' && !is_space(*str))
2548
            str++;
2549
        len = str - s1;
2550
        arg = tcc_malloc(len + 1);
2551
        pstrncpy(arg, s1, len);
2552
        dynarray_add((void ***)&argv, &argc, arg);
2553
    }
2554
    ret = tcc_parse_args(s, argc, argv);
2555
    dynarray_reset(&argv, &argc);
2556
    return ret;
2557
}
2558
 
2559
PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time)
2560
{
2561
    double tt;
2562
    tt = (double)total_time / 1000000.0;
2563
    if (tt < 0.001)
2564
        tt = 0.001;
2565
    if (total_bytes < 1)
2566
        total_bytes = 1;
6574 siemargl 2567
    fprintf(stdout, "%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
6429 siemargl 2568
           tok_ident - TOK_IDENT, total_lines, total_bytes,
2569
           tt, (int)(total_lines / tt),
2570
           total_bytes / tt / 1000000.0);
2571
}
2572
 
2573
PUB_FUNC void tcc_set_environment(TCCState *s)
2574
{
2575
    char * path;
2576
 
2577
    path = getenv("C_INCLUDE_PATH");
2578
    if(path != NULL) {
2579
        tcc_add_include_path(s, path);
2580
    }
2581
    path = getenv("CPATH");
2582
    if(path != NULL) {
2583
        tcc_add_include_path(s, path);
2584
    }
2585
    path = getenv("LIBRARY_PATH");
2586
    if(path != NULL) {
2587
        tcc_add_library_path(s, path);
2588
    }
2589
}