Subversion Repositories Kolibri OS

Rev

Rev 9615 | 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);
9615 turbocat 116
#ifdef TCC_TARGET_KX
9558 turbocat 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;
9558 turbocat 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)
9615 turbocat 158
{
7520 siemargl 159
	char** argv0 = (char**)0x20; // path in kolibri header
9615 turbocat 160
    char path[1024], *p;
7520 siemargl 161
	strncpy(path, *argv0, sizeof path);
9615 turbocat 162
#ifdef TCC_TARGET_KX
9558 turbocat 163
	kx_fix_root_directory(path, sizeof path);
9615 turbocat 164
#else
7520 siemargl 165
	p = tcc_basename(path);
166
    if (p > path) p--;
167
    *p = 0;
9558 turbocat 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);
9615 turbocat 177
#ifdef TCC_TARGET_KX
178
	kx_fix_root_directory(buff, sizeof buff);
9558 turbocat 179
	const char *path = buff;
180
#else
8272 superturbo 181
    const char *path = dirname(buff);
9558 turbocat 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
 
9782 Coldy 663
    if (((sym->type.t & VT_BTYPE) == VT_FUNC
664
#ifdef TCC_TARGET_KX
665
		) && ((vtop->type.t & VT_IMPORT) == 0
666
#endif
667
		)) {
6429 siemargl 668
        sym_type = STT_FUNC;
669
    } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
670
        sym_type = STT_NOTYPE;
671
    } else {
672
        sym_type = STT_OBJECT;
673
    }
674
 
675
    if (sym->type.t & VT_STATIC)
676
        sym_bind = STB_LOCAL;
677
    else {
678
        if (sym->type.t & VT_WEAK)
679
            sym_bind = STB_WEAK;
680
        else
681
            sym_bind = STB_GLOBAL;
682
    }
683
 
684
    if (!sym->c) {
685
        name = get_tok_str(sym->v, NULL);
686
#ifdef CONFIG_TCC_BCHECK
687
        if (tcc_state->do_bounds_check) {
688
            /* XXX: avoid doing that for statics ? */
689
            /* if bound checking is activated, we change some function
690
               names by adding the "__bound" prefix */
691
            switch(sym->v) {
692
#ifdef TCC_TARGET_PE
693
            /* XXX: we rely only on malloc hooks */
694
            case TOK_malloc:
695
            case TOK_free:
696
            case TOK_realloc:
697
            case TOK_memalign:
698
            case TOK_calloc:
699
#endif
700
            case TOK_memcpy:
701
            case TOK_memmove:
702
            case TOK_memset:
703
            case TOK_strlen:
704
            case TOK_strcpy:
705
            case TOK_alloca:
706
                strcpy(buf, "__bound_");
707
                strcat(buf, name);
708
                name = buf;
709
                break;
710
            }
711
        }
712
#endif
713
        other = 0;
714
 
715
#ifdef TCC_TARGET_PE
716
        if (sym->type.t & VT_EXPORT)
717
            other |= ST_PE_EXPORT;
718
        if (sym_type == STT_FUNC && sym->type.ref) {
719
            Sym *ref = sym->type.ref;
720
            if (ref->a.func_export)
721
                other |= ST_PE_EXPORT;
722
            if (ref->a.func_call == FUNC_STDCALL && can_add_underscore) {
723
                sprintf(buf1, "_%s@%d", name, ref->a.func_args * PTR_SIZE);
724
                name = buf1;
725
                other |= ST_PE_STDCALL;
726
                can_add_underscore = 0;
727
            }
728
        } else {
729
            if (find_elf_sym(tcc_state->dynsymtab_section, name))
730
                other |= ST_PE_IMPORT;
731
            if (sym->type.t & VT_IMPORT)
732
                other |= ST_PE_IMPORT;
733
        }
734
#else
735
        if (! (sym->type.t & VT_STATIC))
736
	    other = (sym->type.t & VT_VIS_MASK) >> VT_VIS_SHIFT;
737
#endif
738
        if (tcc_state->leading_underscore && can_add_underscore) {
739
            buf1[0] = '_';
740
            pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
741
            name = buf1;
742
        }
743
        if (sym->asm_label) {
744
            name = get_tok_str(sym->asm_label, NULL);
745
        }
746
        info = ELFW(ST_INFO)(sym_bind, sym_type);
747
        sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
748
    } else {
749
        esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
750
        esym->st_value = value;
751
        esym->st_size = size;
752
        esym->st_shndx = sh_num;
753
    }
754
}
755
 
756
ST_FUNC void put_extern_sym(Sym *sym, Section *section,
757
                           addr_t value, unsigned long size)
758
{
759
    put_extern_sym2(sym, section, value, size, 1);
760
}
761
 
762
/* add a new relocation entry to symbol 'sym' in section 's' */
763
ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type,
764
                     addr_t addend)
765
{
766
    int c = 0;
767
    if (sym) {
768
        if (0 == sym->c)
769
            put_extern_sym(sym, NULL, 0, 0);
770
        c = sym->c;
771
    }
772
    /* now we can add ELF relocation info */
773
    put_elf_reloca(symtab_section, s, offset, type, c, addend);
774
}
775
 
776
ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
777
{
778
    greloca(s, sym, offset, type, 0);
779
}
780
 
781
/********************************************************/
782
 
783
static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
784
{
785
    int len;
786
    len = strlen(buf);
787
    vsnprintf(buf + len, buf_size - len, fmt, ap);
788
}
789
 
790
static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
791
{
792
    va_list ap;
793
    va_start(ap, fmt);
794
    strcat_vprintf(buf, buf_size, fmt, ap);
795
    va_end(ap);
796
}
797
 
798
static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
799
{
800
    char buf[2048];
801
    BufferedFile **pf, *f;
802
 
803
    buf[0] = '\0';
804
    /* use upper file if inline ":asm:" or token ":paste:" */
805
    for (f = file; f && f->filename[0] == ':'; f = f->prev)
806
     ;
807
    if (f) {
808
        for(pf = s1->include_stack; pf < s1->include_stack_ptr; pf++)
809
            strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
810
                (*pf)->filename, (*pf)->line_num);
811
        if (f->line_num > 0) {
812
            strcat_printf(buf, sizeof(buf), "%s:%d: ",
813
                f->filename, f->line_num);
814
        } else {
815
            strcat_printf(buf, sizeof(buf), "%s: ",
816
                f->filename);
817
        }
818
    } else {
819
        strcat_printf(buf, sizeof(buf), "tcc: ");
820
    }
821
    if (is_warning)
822
        strcat_printf(buf, sizeof(buf), "warning: ");
823
    else
824
        strcat_printf(buf, sizeof(buf), "error: ");
825
    strcat_vprintf(buf, sizeof(buf), fmt, ap);
826
 
827
    if (!s1->error_func) {
828
        /* default case: stderr */
829
        if (s1->ppfp) /* print a newline during tcc -E */
830
            fprintf(s1->ppfp, "\n"), fflush(s1->ppfp);
6574 siemargl 831
#ifndef TCC_TARGET_MEOS
6429 siemargl 832
        fprintf(stderr, "%s\n", buf);
833
        fflush(stderr); /* print error/warning now (win32) */
6574 siemargl 834
#else
835
        fprintf(stdout, "%s\n", buf);
836
        fflush(stdout); /* print error/warning now (win32) */
837
#endif
6429 siemargl 838
    } else {
839
        s1->error_func(s1->error_opaque, buf);
840
    }
841
    if (!is_warning || s1->warn_error)
842
        s1->nb_errors++;
843
}
844
 
845
LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
846
                        void (*error_func)(void *opaque, const char *msg))
847
{
848
    s->error_opaque = error_opaque;
849
    s->error_func = error_func;
850
}
851
 
852
/* error without aborting current compilation */
853
PUB_FUNC void tcc_error_noabort(const char *fmt, ...)
854
{
855
    TCCState *s1 = tcc_state;
856
    va_list ap;
857
 
858
    va_start(ap, fmt);
859
    error1(s1, 0, fmt, ap);
860
    va_end(ap);
861
}
862
 
863
PUB_FUNC void tcc_error(const char *fmt, ...)
864
{
865
    TCCState *s1 = tcc_state;
9782 Coldy 866
	// { Edit by Coldy
867
	if (fmt) {
6429 siemargl 868
    va_list ap;
869
 
870
    va_start(ap, fmt);
871
    error1(s1, 0, fmt, ap);
872
    va_end(ap);
9782 Coldy 873
	} // }
6429 siemargl 874
    /* better than nothing: in some cases, we accept to handle errors */
875
    if (s1->error_set_jmp_enabled) {
876
        longjmp(s1->error_jmp_buf, 1);
877
    } else {
878
        /* XXX: eliminate this someday */
879
        exit(1);
880
    }
881
}
882
 
883
PUB_FUNC void tcc_warning(const char *fmt, ...)
884
{
885
    TCCState *s1 = tcc_state;
886
    va_list ap;
887
 
888
    if (s1->warn_none)
889
        return;
890
 
891
    va_start(ap, fmt);
892
    error1(s1, 1, fmt, ap);
893
    va_end(ap);
894
}
895
 
896
/********************************************************/
897
/* I/O layer */
898
 
899
ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
900
{
901
    BufferedFile *bf;
902
    int buflen = initlen ? initlen : IO_BUF_SIZE;
903
 
904
    bf = tcc_mallocz(sizeof(BufferedFile) + buflen);
905
    bf->buf_ptr = bf->buffer;
906
    bf->buf_end = bf->buffer + initlen;
907
    bf->buf_end[0] = CH_EOB; /* put eob symbol */
908
    pstrcpy(bf->filename, sizeof(bf->filename), filename);
909
#ifdef _WIN32
910
    normalize_slashes(bf->filename);
911
#endif
912
    bf->line_num = 1;
913
    bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
914
    bf->fd = -1;
915
    bf->prev = file;
916
    file = bf;
917
}
918
 
919
ST_FUNC void tcc_close(void)
920
{
921
    BufferedFile *bf = file;
922
    if (bf->fd > 0) {
923
        close(bf->fd);
924
        total_lines += bf->line_num;
925
    }
926
    file = bf->prev;
927
    tcc_free(bf);
928
}
929
 
930
ST_FUNC int tcc_open(TCCState *s1, const char *filename)
931
{
932
    int fd;
933
    if (strcmp(filename, "-") == 0)
934
        fd = 0, filename = "";
935
    else
936
        fd = open(filename, O_RDONLY | O_BINARY);
937
    if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
938
        printf("%s %*s%s\n", fd < 0 ? "nf":"->",
939
               (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
940
    if (fd < 0)
941
        return -1;
942
 
943
    tcc_open_bf(s1, filename, 0);
944
    file->fd = fd;
945
    return fd;
946
}
947
 
948
/* compile the C file opened in 'file'. Return non zero if errors. */
949
static int tcc_compile(TCCState *s1)
950
{
951
    Sym *define_start;
952
    char buf[512];
953
    volatile int section_sym;
954
 
955
#ifdef INC_DEBUG
956
    printf("%s: **** new file\n", file->filename);
957
#endif
958
    preprocess_init(s1);
959
 
960
    cur_text_section = NULL;
961
    funcname = "";
962
    anon_sym = SYM_FIRST_ANOM;
963
 
964
    /* file info: full path + filename */
965
    section_sym = 0; /* avoid warning */
966
    if (s1->do_debug) {
967
        section_sym = put_elf_sym(symtab_section, 0, 0,
968
                                  ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
969
                                  text_section->sh_num, NULL);
970
        getcwd(buf, sizeof(buf));
971
#ifdef _WIN32
972
        normalize_slashes(buf);
973
#endif
974
        pstrcat(buf, sizeof(buf), "/");
975
        put_stabs_r(buf, N_SO, 0, 0,
976
                    text_section->data_offset, text_section, section_sym);
977
        put_stabs_r(file->filename, N_SO, 0, 0,
978
                    text_section->data_offset, text_section, section_sym);
979
    }
980
    /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
981
       symbols can be safely used */
982
    put_elf_sym(symtab_section, 0, 0,
983
                ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
984
                SHN_ABS, file->filename);
985
 
986
    /* define some often used types */
987
    int_type.t = VT_INT;
988
 
989
    char_pointer_type.t = VT_BYTE;
990
    mk_pointer(&char_pointer_type);
991
 
992
#if PTR_SIZE == 4
993
    size_type.t = VT_INT;
994
#else
995
    size_type.t = VT_LLONG;
996
#endif
997
 
998
    func_old_type.t = VT_FUNC;
999
    func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
1000
#ifdef TCC_TARGET_ARM
1001
    arm_init(s1);
1002
#endif
1003
 
1004
#if 0
1005
    /* define 'void *alloca(unsigned int)' builtin function */
1006
    {
1007
        Sym *s1;
1008
 
1009
        p = anon_sym++;
1010
        sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
1011
        s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
1012
        s1->next = NULL;
1013
        sym->next = s1;
1014
        sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
1015
    }
1016
#endif
1017
 
1018
    define_start = define_stack;
1019
    nocode_wanted = 1;
1020
 
1021
    if (setjmp(s1->error_jmp_buf) == 0) {
1022
        s1->nb_errors = 0;
1023
        s1->error_set_jmp_enabled = 1;
1024
 
1025
        ch = file->buf_ptr[0];
1026
        tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
1027
        parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | PARSE_FLAG_TOK_STR;
1028
        next();
1029
        decl(VT_CONST);
1030
        if (tok != TOK_EOF)
1031
            expect("declaration");
1032
        check_vstack();
1033
 
1034
        /* end of translation unit info */
1035
        if (s1->do_debug) {
1036
            put_stabs_r(NULL, N_SO, 0, 0,
1037
                        text_section->data_offset, text_section, section_sym);
1038
        }
1039
    }
1040
 
1041
    s1->error_set_jmp_enabled = 0;
1042
 
1043
    /* reset define stack, but leave -Dsymbols (may be incorrect if
1044
       they are undefined) */
1045
    free_defines(define_start);
1046
 
1047
    gen_inline_functions();
1048
 
1049
    sym_pop(&global_stack, NULL);
1050
    sym_pop(&local_stack, NULL);
1051
 
1052
    return s1->nb_errors != 0 ? -1 : 0;
1053
}
1054
 
1055
LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
1056
{
1057
    int len, ret;
1058
 
1059
    len = strlen(str);
1060
    tcc_open_bf(s, "", len);
1061
    memcpy(file->buffer, str, len);
1062
    ret = tcc_compile(s);
1063
    tcc_close();
1064
    return ret;
1065
}
1066
 
1067
/* define a preprocessor symbol. A value can also be provided with the '=' operator */
1068
LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
1069
{
1070
    int len1, len2;
1071
    /* default value */
1072
    if (!value)
1073
        value = "1";
1074
    len1 = strlen(sym);
1075
    len2 = strlen(value);
1076
 
1077
    /* init file structure */
1078
    tcc_open_bf(s1, "", len1 + len2 + 1);
1079
    memcpy(file->buffer, sym, len1);
1080
    file->buffer[len1] = ' ';
1081
    memcpy(file->buffer + len1 + 1, value, len2);
1082
 
1083
    /* parse with define parser */
1084
    ch = file->buf_ptr[0];
1085
    next_nomacro();
1086
    parse_define();
1087
 
1088
    tcc_close();
1089
}
1090
 
1091
/* undefine a preprocessor symbol */
1092
LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
1093
{
1094
    TokenSym *ts;
1095
    Sym *s;
1096
    ts = tok_alloc(sym, strlen(sym));
1097
    s = define_find(ts->tok);
1098
    /* undefine symbol by putting an invalid name */
1099
    if (s)
1100
        define_undef(s);
1101
}
1102
 
1103
/* cleanup all static data used during compilation */
1104
static void tcc_cleanup(void)
1105
{
1106
    if (NULL == tcc_state)
1107
        return;
1108
    tcc_state = NULL;
1109
 
1110
    preprocess_delete();
1111
 
1112
    /* free sym_pools */
1113
    dynarray_reset(&sym_pools, &nb_sym_pools);
1114
    /* reset symbol stack */
1115
    sym_free_first = NULL;
1116
}
1117
 
1118
LIBTCCAPI TCCState *tcc_new(void)
1119
{
1120
    TCCState *s;
1121
    char buffer[100];
1122
    int a,b,c;
1123
 
1124
    tcc_cleanup();
1125
 
1126
    s = tcc_mallocz(sizeof(TCCState));
1127
    if (!s)
1128
        return NULL;
1129
    tcc_state = s;
1130
#ifdef _WIN32
1131
    tcc_set_lib_path_w32(s);
1132
#else
8272 superturbo 1133
 
8250 superturbo 1134
#if defined TCC_TARGET_MEOS && ! TCC_TARGET_MEOS_LINUX
7520 siemargl 1135
    tcc_set_lib_path_kos(s);
1136
#else
8272 superturbo 1137
 
1138
#ifdef TCC_TARGET_MEOS_LINUX
1139
    tcc_set_lib_path_linux(s);
1140
#else
6429 siemargl 1141
    tcc_set_lib_path(s, CONFIG_TCCDIR);
1142
#endif
7520 siemargl 1143
#endif
8272 superturbo 1144
#endif
6429 siemargl 1145
    s->output_type = 0;
1146
    preprocess_new();
1147
    s->include_stack_ptr = s->include_stack;
1148
 
1149
    /* we add dummy defines for some special macros to speed up tests
1150
       and to have working defined() */
1151
    define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
1152
    define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
1153
    define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
1154
    define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
1155
 
1156
    /* define __TINYC__ 92X  */
1157
    sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
1158
    sprintf(buffer, "%d", a*10000 + b*100 + c);
1159
    tcc_define_symbol(s, "__TINYC__", buffer);
1160
 
1161
    /* standard defines */
1162
    tcc_define_symbol(s, "__STDC__", NULL);
1163
    tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
1164
    tcc_define_symbol(s, "__STDC_HOSTED__", NULL);
1165
 
1166
    /* target defines */
1167
#if defined(TCC_TARGET_I386)
1168
    tcc_define_symbol(s, "__i386__", NULL);
1169
    tcc_define_symbol(s, "__i386", NULL);
1170
    tcc_define_symbol(s, "i386", NULL);
1171
#elif defined(TCC_TARGET_X86_64)
1172
    tcc_define_symbol(s, "__x86_64__", NULL);
1173
#elif defined(TCC_TARGET_ARM)
1174
    tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
1175
    tcc_define_symbol(s, "__arm_elf__", NULL);
1176
    tcc_define_symbol(s, "__arm_elf", NULL);
1177
    tcc_define_symbol(s, "arm_elf", NULL);
1178
    tcc_define_symbol(s, "__arm__", NULL);
1179
    tcc_define_symbol(s, "__arm", NULL);
1180
    tcc_define_symbol(s, "arm", NULL);
1181
    tcc_define_symbol(s, "__APCS_32__", NULL);
1182
    tcc_define_symbol(s, "__ARMEL__", NULL);
1183
#if defined(TCC_ARM_EABI)
1184
    tcc_define_symbol(s, "__ARM_EABI__", NULL);
1185
#endif
1186
#if defined(TCC_ARM_HARDFLOAT)
1187
    s->float_abi = ARM_HARD_FLOAT;
1188
    tcc_define_symbol(s, "__ARM_PCS_VFP", NULL);
1189
#else
1190
    s->float_abi = ARM_SOFTFP_FLOAT;
1191
#endif
1192
#elif defined(TCC_TARGET_ARM64)
1193
    tcc_define_symbol(s, "__aarch64__", NULL);
1194
#endif
1195
 
1196
#ifdef TCC_TARGET_PE
1197
    tcc_define_symbol(s, "_WIN32", NULL);
1198
# ifdef TCC_TARGET_X86_64
1199
    tcc_define_symbol(s, "_WIN64", NULL);
1200
# endif
9153 turbocat 1201
#elif defined(TCC_TARGET_MEOS) || defined(TCC_TARGET_MEOS_LINUX)
1202
    tcc_define_symbol(s, "KOLIBRI",  NULL);
1203
    tcc_define_symbol(s, "_KOLIBRI", NULL);
1204
    tcc_define_symbol(s, "_KOLIBRI_",NULL);
9305 Coldy 1205
#ifdef TCC_TARGET_KX
1206
	tcc_define_symbol(s, "__KX__", NULL);
1207
#endif
6429 siemargl 1208
#else
1209
    tcc_define_symbol(s, "__unix__", NULL);
1210
    tcc_define_symbol(s, "__unix", NULL);
1211
    tcc_define_symbol(s, "unix", NULL);
1212
# if defined(__linux__)
1213
    tcc_define_symbol(s, "__linux__", NULL);
1214
    tcc_define_symbol(s, "__linux", NULL);
1215
# endif
1216
# if defined(__FreeBSD__)
1217
#  define str(s) #s
1218
    tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
1219
#  undef str
1220
# endif
1221
# if defined(__FreeBSD_kernel__)
1222
    tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
1223
# endif
1224
#endif
1225
# if defined(__NetBSD__)
1226
#  define str(s) #s
1227
    tcc_define_symbol(s, "__NetBSD__", str( __NetBSD__));
1228
#  undef str
1229
# endif
9153 turbocat 1230
 
6429 siemargl 1231
    /* TinyCC & gcc defines */
1232
#if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
1233
    tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
1234
    tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
1235
#else
1236
    tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
1237
    tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
1238
#endif
1239
 
1240
#ifdef TCC_TARGET_PE
1241
    tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
1242
    tcc_define_symbol(s, "__WINT_TYPE__", "unsigned short");
1243
#else
1244
    tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
1245
    /* wint_t is unsigned int by default, but (signed) int on BSDs
1246
       and unsigned short on windows.  Other OSes might have still
1247
       other conventions, sigh.  */
1248
#if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__NetBSD__)
1249
    tcc_define_symbol(s, "__WINT_TYPE__", "int");
1250
#else
1251
    tcc_define_symbol(s, "__WINT_TYPE__", "unsigned int");
1252
#endif
1253
#endif
1254
 
1255
#ifndef TCC_TARGET_PE
1256
    /* glibc defines */
1257
    tcc_define_symbol(s, "__REDIRECT(name, proto, alias)", "name proto __asm__ (#alias)");
1258
    tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)", "name proto __asm__ (#alias) __THROW");
1259
    /* paths for crt objects */
1260
    tcc_split_path(s, (void ***)&s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
1261
#endif
1262
 
1263
    /* no section zero */
1264
    dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
1265
 
1266
    /* create standard sections */
1267
    text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
1268
    data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
1269
    bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1270
 
1271
    /* symbols are always generated for linking stage */
1272
    symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
1273
                                ".strtab",
1274
                                ".hashtab", SHF_PRIVATE);
1275
    strtab_section = symtab_section->link;
1276
    s->symtab = symtab_section;
1277
 
1278
    /* private symbol table for dynamic symbols */
1279
    s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
1280
                                      ".dynstrtab",
1281
                                      ".dynhashtab", SHF_PRIVATE);
1282
    s->alacarte_link = 1;
1283
    s->nocommon = 1;
1284
    s->warn_implicit_function_declaration = 1;
1285
 
1286
#ifdef CHAR_IS_UNSIGNED
1287
    s->char_is_unsigned = 1;
1288
#endif
1289
    /* enable this if you want symbols with leading underscore on windows: */
1290
#if 0 /* def TCC_TARGET_PE */
1291
    s->leading_underscore = 1;
1292
#endif
1293
#if 0 /* TCC_TARGET_MEOS */
1294
    s->leading_underscore = 1;
1295
#endif
1296
#ifdef TCC_TARGET_I386
1297
    s->seg_size = 32;
1298
#endif
1299
#ifdef TCC_IS_NATIVE
1300
    s->runtime_main = "main";
1301
#endif
1302
    return s;
1303
}
1304
 
1305
LIBTCCAPI void tcc_delete(TCCState *s1)
1306
{
1307
    int i;
1308
    int bench = s1->do_bench;
1309
 
1310
    tcc_cleanup();
1311
 
1312
    /* close a preprocessor output */
1313
    if (s1->ppfp && s1->ppfp != stdout)
1314
        fclose(s1->ppfp);
1315
    if (s1->dffp && s1->dffp != s1->ppfp)
1316
        fclose(s1->dffp);
1317
 
1318
    /* free all sections */
1319
    for(i = 1; i < s1->nb_sections; i++)
1320
        free_section(s1->sections[i]);
1321
    dynarray_reset(&s1->sections, &s1->nb_sections);
1322
 
1323
    for(i = 0; i < s1->nb_priv_sections; i++)
1324
        free_section(s1->priv_sections[i]);
1325
    dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
1326
 
1327
    /* free any loaded DLLs */
1328
#ifdef TCC_IS_NATIVE
1329
    for ( i = 0; i < s1->nb_loaded_dlls; i++) {
1330
        DLLReference *ref = s1->loaded_dlls[i];
1331
        if ( ref->handle )
1332
            dlclose(ref->handle);
1333
    }
1334
#endif
1335
 
1336
    /* free loaded dlls array */
1337
    dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
1338
 
1339
    /* free library paths */
1340
    dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
1341
    dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
1342
 
1343
    /* free include paths */
1344
    dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
1345
    dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
1346
    dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
1347
 
1348
    tcc_free(s1->tcc_lib_path);
1349
    tcc_free(s1->soname);
1350
    tcc_free(s1->rpath);
1351
    tcc_free(s1->init_symbol);
1352
    tcc_free(s1->fini_symbol);
1353
    tcc_free(s1->outfile);
1354
    tcc_free(s1->deps_outfile);
1355
    dynarray_reset(&s1->files, &s1->nb_files);
1356
    dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
1357
    dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
1358
 
1359
#ifdef TCC_IS_NATIVE
1360
# ifdef HAVE_SELINUX
1361
    munmap (s1->write_mem, s1->mem_size);
1362
    munmap (s1->runtime_mem, s1->mem_size);
1363
# else
1364
    tcc_free(s1->runtime_mem);
1365
# endif
1366
#endif
1367
 
1368
    tcc_free(s1->sym_attrs);
1369
    tcc_free(s1);
1370
    tcc_memstats(bench);
1371
}
1372
 
1373
LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
1374
{
1375
    tcc_split_path(s, (void ***)&s->include_paths, &s->nb_include_paths, pathname);
1376
    return 0;
1377
}
1378
 
1379
LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
1380
{
1381
    tcc_split_path(s, (void ***)&s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
1382
    return 0;
1383
}
1384
 
1385
ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags, int filetype)
1386
{
1387
    ElfW(Ehdr) ehdr;
1388
    int fd, ret, size;
1389
 
1390
    parse_flags = 0;
1391
#ifdef CONFIG_TCC_ASM
1392
    /* if .S file, define __ASSEMBLER__ like gcc does */
1393
    if ((filetype == TCC_FILETYPE_ASM) || (filetype == TCC_FILETYPE_ASM_PP)) {
1394
        tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
1395
        parse_flags = PARSE_FLAG_ASM_FILE;
1396
    }
1397
#endif
1398
 
1399
    /* open the file */
1400
    ret = tcc_open(s1, filename);
1401
    if (ret < 0) {
1402
        if (flags & AFF_PRINT_ERROR)
1403
            tcc_error_noabort("file '%s' not found", filename);
1404
        return ret;
1405
    }
1406
 
1407
    /* update target deps */
1408
    dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
1409
            tcc_strdup(filename));
1410
 
1411
    if (flags & AFF_PREPROCESS) {
1412
        ret = tcc_preprocess(s1);
1413
        goto the_end;
1414
    }
1415
 
1416
    if (filetype == TCC_FILETYPE_C) {
1417
        /* C file assumed */
1418
        ret = tcc_compile(s1);
1419
        goto the_end;
1420
    }
1421
 
1422
#ifdef CONFIG_TCC_ASM
1423
    if (filetype == TCC_FILETYPE_ASM_PP) {
1424
        /* non preprocessed assembler */
1425
        ret = tcc_assemble(s1, 1);
1426
        goto the_end;
1427
    }
1428
 
1429
    if (filetype == TCC_FILETYPE_ASM) {
1430
        /* preprocessed assembler */
1431
        ret = tcc_assemble(s1, 0);
1432
        goto the_end;
1433
    }
1434
#endif
1435
 
1436
    fd = file->fd;
1437
    /* assume executable format: auto guess file type */
1438
    size = read(fd, &ehdr, sizeof(ehdr));
1439
    lseek(fd, 0, SEEK_SET);
1440
    if (size <= 0) {
1441
        tcc_error_noabort("could not read header");
1442
        goto the_end;
1443
    }
1444
 
1445
    if (size == sizeof(ehdr) &&
1446
        ehdr.e_ident[0] == ELFMAG0 &&
1447
        ehdr.e_ident[1] == ELFMAG1 &&
1448
        ehdr.e_ident[2] == ELFMAG2 &&
1449
        ehdr.e_ident[3] == ELFMAG3) {
1450
 
1451
        /* do not display line number if error */
1452
        file->line_num = 0;
1453
        if (ehdr.e_type == ET_REL) {
1454
            ret = tcc_load_object_file(s1, fd, 0);
1455
            goto the_end;
1456
 
1457
        }
1458
#if !defined(TCC_TARGET_PE) && !defined(TCC_TARGET_MEOS)
1459
        if (ehdr.e_type == ET_DYN) {
1460
            if (s1->output_type == TCC_OUTPUT_MEMORY) {
1461
#ifdef TCC_IS_NATIVE
1462
                void *h;
1463
                h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
1464
                if (h)
1465
#endif
1466
                    ret = 0;
1467
            } else {
1468
                ret = tcc_load_dll(s1, fd, filename,
1469
                                   (flags & AFF_REFERENCED_DLL) != 0);
1470
            }
1471
            goto the_end;
1472
        }
1473
#endif
1474
        tcc_error_noabort("unrecognized ELF file");
1475
        goto the_end;
1476
    }
1477
 
1478
    if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
1479
        file->line_num = 0; /* do not display line number if error */
1480
        ret = tcc_load_archive(s1, fd);
1481
        goto the_end;
1482
    }
1483
 
1484
#ifdef TCC_TARGET_COFF
1485
    if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
1486
        ret = tcc_load_coff(s1, fd);
1487
        goto the_end;
1488
    }
1489
#endif
1490
 
9284 Coldy 1491
#if defined (TCC_TARGET_PE) ||  (defined(TCC_TARGET_MEOS)  && !defined(TCC_TARGET_KX))
6429 siemargl 1492
    ret = pe_load_file(s1, filename, fd);
9284 Coldy 1493
#elif defined(TCC_TARGET_KX)
1494
    ret = pe_load_def(s1, fd);
6429 siemargl 1495
#else
1496
    /* as GNU ld, consider it is an ld script if not recognized */
1497
    ret = tcc_load_ldscript(s1);
1498
#endif
1499
    if (ret < 0)
1500
        tcc_error_noabort("unrecognized file type");
1501
 
1502
the_end:
1503
    tcc_close();
1504
    return ret;
1505
}
1506
 
1507
LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename, int filetype)
1508
{
1509
    if (s->output_type == TCC_OUTPUT_PREPROCESS)
1510
        return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS, filetype);
1511
    else
1512
        return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR, filetype);
1513
}
1514
 
1515
LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
1516
{
1517
    tcc_split_path(s, (void ***)&s->library_paths, &s->nb_library_paths, pathname);
1518
    return 0;
1519
}
1520
 
1521
static int tcc_add_library_internal(TCCState *s, const char *fmt,
1522
    const char *filename, int flags, char **paths, int nb_paths)
1523
{
1524
    char buf[1024];
1525
    int i;
1526
 
1527
    for(i = 0; i < nb_paths; i++) {
1528
        snprintf(buf, sizeof(buf), fmt, paths[i], filename);
7520 siemargl 1529
//printf("tcc_add_library_internal::added lib [%s]\n", buf);
6429 siemargl 1530
        if (tcc_add_file_internal(s, buf, flags, TCC_FILETYPE_BINARY) == 0)
1531
            return 0;
1532
    }
1533
    return -1;
1534
}
1535
 
1536
#if !defined(TCC_TARGET_PE) && !defined(TCC_TARGET_MEOS)
1537
/* find and load a dll. Return non zero if not found */
1538
/* XXX: add '-rpath' option support ? */
1539
ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
1540
{
1541
    return tcc_add_library_internal(s, "%s/%s", filename, flags,
1542
        s->library_paths, s->nb_library_paths);
1543
}
1544
#endif
1545
 
1546
ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
1547
{
1548
    if (-1 == tcc_add_library_internal(s, "%s/%s",
1549
        filename, 0, s->crt_paths, s->nb_crt_paths))
9558 turbocat 1550
        tcc_error_noabort("file '%s' not found", filename);
6429 siemargl 1551
    return 0;
1552
}
1553
 
1554
/* the library name is the same as the argument of the '-l' option */
1555
LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
1556
{
1557
#if defined(TCC_TARGET_PE) || defined(TCC_TARGET_MEOS)
1558
    const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
1559
    const char **pp = s->static_link ? libs + 4 : libs;
1560
#else
1561
    const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
1562
    const char **pp = s->static_link ? libs + 1 : libs;
1563
#endif
1564
    while (*pp) {
1565
        if (0 == tcc_add_library_internal(s, *pp,
1566
            libraryname, 0, s->library_paths, s->nb_library_paths))
1567
            return 0;
1568
        ++pp;
1569
    }
1570
    return -1;
1571
}
1572
 
1573
PUB_FUNC int tcc_add_library_err(TCCState *s, const char *libname)
1574
{
1575
    int ret = tcc_add_library(s, libname);
1576
    if (ret < 0)
1577
        tcc_error_noabort("cannot find library 'lib%s'", libname);
1578
    return ret;
1579
}
1580
 
1581
/* habdle #pragma comment(lib,) */
1582
ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
1583
{
1584
    int i;
1585
    for (i = 0; i < s1->nb_pragma_libs; i++)
1586
        tcc_add_library_err(s1, s1->pragma_libs[i]);
1587
}
1588
 
1589
LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
1590
{
1591
#if defined(TCC_TARGET_PE) || defined(TCC_TARGET_MEOS)
1592
    /* On x86_64 'val' might not be reachable with a 32bit offset.
1593
       So it is handled here as if it were in a DLL. */
1594
    pe_putimport(s, 0, name, (uintptr_t)val);
1595
#else
1596
    add_elf_sym(symtab_section, (uintptr_t)val, 0,
1597
        ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
1598
        SHN_ABS, name);
1599
#endif
1600
    return 0;
1601
}
1602
 
1603
 
1604
/* Windows stat* ( https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx ):
1605
 * - st_gid, st_ino, st_uid: only valid on "unix" file systems (not FAT, NTFS, etc)
1606
 * - st_atime, st_ctime: not valid on FAT, valid on NTFS.
1607
 * - Other fields should be reasonably compatible (and S_ISDIR should work).
1608
 *
1609
 * BY_HANDLE_FILE_INFORMATION ( https://msdn.microsoft.com/en-us/library/windows/desktop/aa363788%28v=vs.85%29.aspx ):
1610
 * - File index (combined nFileIndexHigh and nFileIndexLow) _may_ change when the file is opened.
1611
 *   - But on NTFS: it's guaranteed to be the same value until the file is deleted.
1612
 * - On windows server 2012 there's a 128b file id, and the 64b one via
1613
 *   nFileIndex* is not guaranteed to be unique.
1614
 *
1615
 * - MS Docs suggest to that volume number with the file index could be used to
1616
 *   check if two handles refer to the same file.
1617
 */
1618
#ifndef _WIN32
1619
typedef struct stat                file_info_t;
1620
#else
1621
typedef BY_HANDLE_FILE_INFORMATION file_info_t;
1622
#endif
1623
 
1624
int get_file_info(const char *fname, file_info_t *out_info)
1625
{
1626
#ifndef _WIN32
1627
    return stat(fname, out_info);
1628
#else
1629
    int rv = 1;
1630
    HANDLE h = CreateFile(fname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
1631
                          FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS, NULL);
1632
 
1633
    if (h != INVALID_HANDLE_VALUE) {
1634
        rv = !GetFileInformationByHandle(h, out_info);
1635
        CloseHandle(h);
1636
    }
1637
    return rv;
1638
#endif
1639
}
1640
 
1641
int is_dir(file_info_t *info)
1642
{
1643
#ifndef _WIN32
1644
    return S_ISDIR(info->st_mode);
1645
#else
1646
    return (info->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ==
1647
           FILE_ATTRIBUTE_DIRECTORY;
1648
#endif
1649
}
1650
 
1651
int is_same_file(const file_info_t *fi1, const file_info_t *fi2)
1652
{
1653
#ifndef _WIN32
1654
    return fi1->st_dev == fi2->st_dev &&
1655
           fi1->st_ino == fi2->st_ino;
1656
#else
1657
    return fi1->dwVolumeSerialNumber == fi2->dwVolumeSerialNumber &&
1658
           fi1->nFileIndexHigh       == fi2->nFileIndexHigh &&
1659
           fi1->nFileIndexLow        == fi2->nFileIndexLow;
1660
#endif
1661
}
1662
 
1663
static void
1664
tcc_normalize_inc_dirs_aux(file_info_t *stats, size_t *pnum, char **path)
1665
{
1666
    size_t i, num = *pnum;
1667
    if (get_file_info(*path, &stats[num]) || !is_dir(&stats[num]))
1668
        goto remove;
1669
    for (i = 0; i < num; i++)
1670
        if (is_same_file(&stats[i], &stats[num]))
1671
            goto remove;
1672
    *pnum = num + 1;
1673
    return;
1674
 remove:
1675
    tcc_free(*path);
1676
    *path = 0;
1677
}
1678
 
1679
/* Remove non-existent and duplicate directories from include paths. */
1680
ST_FUNC void tcc_normalize_inc_dirs(TCCState *s)
1681
{
1682
    file_info_t *stats =
1683
        tcc_malloc(((size_t)s->nb_sysinclude_paths + s->nb_include_paths) *
1684
                   sizeof(*stats));
1685
    size_t i, num = 0;
1686
    for (i = 0; i < s->nb_sysinclude_paths; i++)
1687
        tcc_normalize_inc_dirs_aux(stats, &num, &s->sysinclude_paths[i]);
1688
    for (i = 0; i < s->nb_include_paths; i++)
1689
        tcc_normalize_inc_dirs_aux(stats, &num, &s->include_paths[i]);
1690
    tcc_free(stats);
1691
}
1692
 
1693
LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
1694
{
1695
    s->output_type = output_type;
1696
 
1697
    if (s->output_type == TCC_OUTPUT_PREPROCESS) {
1698
        if (!s->outfile) {
1699
            s->ppfp = stdout;
1700
        } else {
1701
            s->ppfp = fopen(s->outfile, "w");
1702
            if (!s->ppfp)
1703
                tcc_error("could not write '%s'", s->outfile);
1704
        }
1705
        s->dffp = s->ppfp;
1706
        if (s->dflag == 'M')
1707
            s->ppfp = NULL;
1708
    }
1709
    if (s->option_C && !s->ppfp)
1710
        s->option_C = 0;
1711
 
1712
    if (!s->nostdinc) {
1713
        /* default include paths */
1714
        /* -isystem paths have already been handled */
1715
        tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
1716
    }
1717
 
1718
    /* if bound checking, then add corresponding sections */
1719
#ifdef CONFIG_TCC_BCHECK
1720
    if (s->do_bounds_check) {
1721
        /* define symbol */
1722
        tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
1723
        /* create bounds sections */
1724
        bounds_section = new_section(s, ".bounds",
1725
                                     SHT_PROGBITS, SHF_ALLOC);
1726
        lbounds_section = new_section(s, ".lbounds",
1727
                                      SHT_PROGBITS, SHF_ALLOC);
1728
    }
1729
#endif
1730
 
1731
    if (s->char_is_unsigned) {
1732
        tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
1733
    }
1734
 
1735
    /* add debug sections */
1736
    if (s->do_debug) {
1737
        /* stab symbols */
1738
        stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
1739
        stab_section->sh_entsize = sizeof(Stab_Sym);
1740
        stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
1741
        put_elf_str(stabstr_section, "");
1742
        stab_section->link = stabstr_section;
1743
        /* put first entry */
1744
        put_stabs("", 0, 0, 0, 0);
1745
    }
1746
 
1747
    tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
1748
#ifdef TCC_TARGET_PE
1749
# ifdef _WIN32
1750
    tcc_add_systemdir(s);
1751
# endif
1752
#elif defined(TCC_TARGET_MEOS)
1753
    if (s->output_type != TCC_OUTPUT_OBJ && !s->nostdlib)
1754
    {
9558 turbocat 1755
        tcc_add_crt(s,"crt0.o");
1756
        //tcc_add_library(s,"lc.obj"); // adding libck.a dont work, because need to be added last
6429 siemargl 1757
    }
1758
#else
1759
    /* add libc crt1/crti objects */
1760
    if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
1761
        !s->nostdlib) {
1762
        if (output_type != TCC_OUTPUT_DLL)
1763
            tcc_add_crt(s, "crt1.o");
1764
        tcc_add_crt(s, "crti.o");
1765
    }
1766
#endif
1767
 
1768
#ifdef CONFIG_TCC_BCHECK
1769
    if (s->do_bounds_check && (output_type == TCC_OUTPUT_EXE))
1770
    {
1771
        /* force a bcheck.o linking */
1772
        addr_t func = TOK___bound_init;
1773
        Sym *sym = external_global_sym(func, &func_old_type, 0);
1774
        if (!sym->c)
1775
            put_extern_sym(sym, NULL, 0, 0);
1776
    }
1777
#endif
1778
 
1779
    if (s->normalize_inc_dirs)
1780
        tcc_normalize_inc_dirs(s);
1781
    if (s->output_type == TCC_OUTPUT_PREPROCESS)
1782
        print_defines();
1783
 
1784
    return 0;
1785
}
1786
 
1787
LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
1788
{
1789
    tcc_free(s->tcc_lib_path);
1790
    s->tcc_lib_path = tcc_strdup(path);
1791
}
1792
 
1793
#define WD_ALL    0x0001 /* warning is activated when using -Wall */
1794
#define FD_INVERT 0x0002 /* invert value before storing */
1795
 
1796
typedef struct FlagDef {
1797
    uint16_t offset;
1798
    uint16_t flags;
1799
    const char *name;
1800
} FlagDef;
1801
 
1802
static const FlagDef warning_defs[] = {
1803
    { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
1804
    { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
1805
    { offsetof(TCCState, warn_error), 0, "error" },
1806
    { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
1807
      "implicit-function-declaration" },
1808
};
1809
 
1810
ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
1811
                    const char *name, int value)
1812
{
1813
    int i;
1814
    const FlagDef *p;
1815
    const char *r;
1816
 
1817
    r = name;
1818
    if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
1819
        r += 3;
1820
        value = !value;
1821
    }
1822
    for(i = 0, p = flags; i < nb_flags; i++, p++) {
1823
        if (!strcmp(r, p->name))
1824
            goto found;
1825
    }
1826
    return -1;
1827
 found:
1828
    if (p->flags & FD_INVERT)
1829
        value = !value;
1830
    *(int *)((uint8_t *)s + p->offset) = value;
1831
    return 0;
1832
}
1833
 
1834
/* set/reset a warning */
1835
static int tcc_set_warning(TCCState *s, const char *warning_name, int value)
1836
{
1837
    int i;
1838
    const FlagDef *p;
1839
 
1840
    if (!strcmp(warning_name, "all")) {
1841
        for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
1842
            if (p->flags & WD_ALL)
1843
                *(int *)((uint8_t *)s + p->offset) = 1;
1844
        }
1845
		s->warn_unsupported = 1;  // siemargl. was unused flag about compiler features
1846
        return 0;
1847
    } else {
1848
        return set_flag(s, warning_defs, countof(warning_defs),
1849
                        warning_name, value);
1850
    }
1851
}
1852
 
1853
static const FlagDef flag_defs[] = {
1854
    { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
1855
    { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
1856
    { offsetof(TCCState, nocommon), FD_INVERT, "common" },
1857
    { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
1858
    { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
1859
    { offsetof(TCCState, old_struct_init_code), 0, "old-struct-init-code" },
1860
    { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
1861
    { offsetof(TCCState, normalize_inc_dirs), 0, "normalize-inc-dirs" },
1862
};
1863
 
1864
/* set/reset a flag */
1865
static int tcc_set_flag(TCCState *s, const char *flag_name, int value)
1866
{
1867
    return set_flag(s, flag_defs, countof(flag_defs),
1868
                    flag_name, value);
1869
}
1870
 
1871
 
1872
static int strstart(const char *val, const char **str)
1873
{
1874
    const char *p, *q;
1875
    p = *str;
1876
    q = val;
1877
    while (*q) {
1878
        if (*p != *q)
1879
            return 0;
1880
        p++;
1881
        q++;
1882
    }
1883
    *str = p;
1884
    return 1;
1885
}
1886
 
1887
/* Like strstart, but automatically takes into account that ld options can
1888
 *
1889
 * - start with double or single dash (e.g. '--soname' or '-soname')
1890
 * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
1891
 *   or '-Wl,-soname=x.so')
1892
 *
1893
 * you provide `val` always in 'option[=]' form (no leading -)
1894
 */
1895
static int link_option(const char *str, const char *val, const char **ptr)
1896
{
1897
    const char *p, *q;
1898
 
1899
    /* there should be 1 or 2 dashes */
1900
    if (*str++ != '-')
1901
        return 0;
1902
    if (*str == '-')
1903
        str++;
1904
 
1905
    /* then str & val should match (potentialy up to '=') */
1906
    p = str;
1907
    q = val;
1908
 
1909
    while (*q != '\0' && *q != '=') {
1910
        if (*p != *q)
1911
            return 0;
1912
        p++;
1913
        q++;
1914
    }
1915
 
1916
    /* '=' near eos means ',' or '=' is ok */
1917
    if (*q == '=') {
1918
        if (*p != ',' && *p != '=')
1919
            return 0;
1920
        p++;
1921
        q++;
1922
    }
1923
 
1924
    if (ptr)
1925
        *ptr = p;
1926
    return 1;
1927
}
1928
 
1929
static const char *skip_linker_arg(const char **str)
1930
{
1931
    const char *s1 = *str;
1932
    const char *s2 = strchr(s1, ',');
1933
    *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
1934
    return s2;
1935
}
1936
 
1937
static char *copy_linker_arg(const char *p)
1938
{
1939
    const char *q = p;
1940
    skip_linker_arg(&q);
1941
    return pstrncpy(tcc_malloc(q - p + 1), p, q - p);
1942
}
1943
 
1944
/* set linker options */
1945
static int tcc_set_linker(TCCState *s, const char *option)
8157 Boppan 1946
{
6429 siemargl 1947
    while (option && *option) {
1948
 
1949
        const char *p = option;
1950
        char *end = NULL;
1951
        int ignoring = 0;
1952
 
1953
        if (link_option(option, "Bsymbolic", &p)) {
1954
            s->symbolic = 1;
1955
        } else if (link_option(option, "nostdlib", &p)) {
1956
            s->nostdlib = 1;
1957
        } else if (link_option(option, "fini=", &p)) {
1958
            s->fini_symbol = copy_linker_arg(p);
1959
            ignoring = 1;
1960
        } else if (link_option(option, "image-base=", &p)
1961
                || link_option(option, "Ttext=", &p)) {
1962
            s->text_addr = strtoull(p, &end, 16);
1963
            s->has_text_addr = 1;
1964
        } else if (link_option(option, "init=", &p)) {
1965
            s->init_symbol = copy_linker_arg(p);
1966
            ignoring = 1;
1967
        } else if (link_option(option, "oformat=", &p)) {
1968
#if defined(TCC_TARGET_PE)
1969
            if (strstart("pe-", &p)) {
1970
#elif defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1971
            if (strstart("elf64-", &p)) {
1972
#else
1973
            if (strstart("elf32-", &p)) {
1974
#endif
1975
                s->output_format = TCC_OUTPUT_FORMAT_ELF;
1976
            } else if (!strcmp(p, "binary")) {
1977
                s->output_format = TCC_OUTPUT_FORMAT_BINARY;
1978
#ifdef TCC_TARGET_COFF
1979
            } else if (!strcmp(p, "coff")) {
1980
                s->output_format = TCC_OUTPUT_FORMAT_COFF;
1981
#endif
1982
            } else
1983
                goto err;
1984
 
1985
        } else if (link_option(option, "as-needed", &p)) {
1986
            ignoring = 1;
1987
        } else if (link_option(option, "O", &p)) {
1988
            ignoring = 1;
1989
        } else if (link_option(option, "rpath=", &p)) {
1990
            s->rpath = copy_linker_arg(p);
1991
        } else if (link_option(option, "section-alignment=", &p)) {
1992
            s->section_align = strtoul(p, &end, 16);
1993
        } else if (link_option(option, "soname=", &p)) {
1994
            s->soname = copy_linker_arg(p);
1995
#ifdef TCC_TARGET_PE
1996
        } else if (link_option(option, "file-alignment=", &p)) {
1997
            s->pe_file_align = strtoul(p, &end, 16);
1998
        } else if (link_option(option, "stack=", &p)) {
1999
            s->pe_stack_size = strtoul(p, &end, 10);
2000
        } else if (link_option(option, "subsystem=", &p)) {
2001
#if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
2002
            if (!strcmp(p, "native")) {
2003
                s->pe_subsystem = 1;
2004
            } else if (!strcmp(p, "console")) {
2005
                s->pe_subsystem = 3;
2006
            } else if (!strcmp(p, "gui")) {
2007
                s->pe_subsystem = 2;
2008
            } else if (!strcmp(p, "posix")) {
2009
                s->pe_subsystem = 7;
2010
            } else if (!strcmp(p, "efiapp")) {
2011
                s->pe_subsystem = 10;
2012
            } else if (!strcmp(p, "efiboot")) {
2013
                s->pe_subsystem = 11;
2014
            } else if (!strcmp(p, "efiruntime")) {
2015
                s->pe_subsystem = 12;
2016
            } else if (!strcmp(p, "efirom")) {
2017
                s->pe_subsystem = 13;
2018
#elif defined(TCC_TARGET_ARM)
2019
            if (!strcmp(p, "wince")) {
2020
                s->pe_subsystem = 9;
2021
#endif
2022
            } else
2023
                goto err;
2024
#endif
2025
        } else
2026
            goto err;
2027
 
2028
        if (ignoring && s->warn_unsupported) err: {
2029
            char buf[100], *e;
2030
            pstrcpy(buf, sizeof buf, e = copy_linker_arg(option)), tcc_free(e);
2031
            if (ignoring)
2032
                tcc_warning("unsupported linker option '%s'", buf);
2033
            else
2034
                tcc_error("unsupported linker option '%s'", buf);
2035
        }
2036
        option = skip_linker_arg(&p);
2037
    }
2038
    return 0;
2039
}
2040
 
2041
typedef struct TCCOption {
2042
    const char *name;
2043
    uint16_t index;
2044
    uint16_t flags;
2045
} TCCOption;
2046
 
2047
enum {
2048
    TCC_OPTION_HELP,
2049
    TCC_OPTION_I,
2050
    TCC_OPTION_D,
2051
    TCC_OPTION_U,
2052
    TCC_OPTION_P,
2053
    TCC_OPTION_L,
2054
    TCC_OPTION_B,
2055
    TCC_OPTION_l,
2056
    TCC_OPTION_bench,
2057
    TCC_OPTION_bt,
2058
    TCC_OPTION_b,
2059
    TCC_OPTION_g,
2060
    TCC_OPTION_c,
2061
    TCC_OPTION_C,
2062
    TCC_OPTION_dumpversion,
2063
    TCC_OPTION_d,
2064
    TCC_OPTION_float_abi,
2065
    TCC_OPTION_static,
2066
    TCC_OPTION_std,
2067
    TCC_OPTION_shared,
2068
    TCC_OPTION_soname,
2069
    TCC_OPTION_o,
2070
    TCC_OPTION_r,
2071
    TCC_OPTION_s,
2072
    TCC_OPTION_traditional,
2073
    TCC_OPTION_Wl,
2074
    TCC_OPTION_W,
2075
    TCC_OPTION_O,
2076
    TCC_OPTION_m,
2077
    TCC_OPTION_f,
2078
    TCC_OPTION_isystem,
2079
    TCC_OPTION_iwithprefix,
2080
    TCC_OPTION_nostdinc,
2081
    TCC_OPTION_nostdlib,
2082
    TCC_OPTION_print_search_dirs,
2083
    TCC_OPTION_rdynamic,
2084
    TCC_OPTION_pedantic,
2085
    TCC_OPTION_pthread,
2086
    TCC_OPTION_run,
2087
    TCC_OPTION_v,
2088
    TCC_OPTION_w,
2089
    TCC_OPTION_pipe,
2090
    TCC_OPTION_E,
2091
    TCC_OPTION_MD,
2092
    TCC_OPTION_MF,
6441 siemargl 2093
    TCC_OPTION_x,
8157 Boppan 2094
    TCC_OPTION_stack,
2095
    TCC_OPTION_nobss
6429 siemargl 2096
};
2097
 
2098
#define TCC_OPTION_HAS_ARG 0x0001
2099
#define TCC_OPTION_NOSEP   0x0002 /* cannot have space before option and arg */
2100
 
2101
static const TCCOption tcc_options[] = {
2102
    { "h", TCC_OPTION_HELP, 0 },
2103
    { "-help", TCC_OPTION_HELP, 0 },
2104
    { "?", TCC_OPTION_HELP, 0 },
2105
    { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
2106
    { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
2107
    { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
2108
    { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2109
    { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
2110
    { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
2111
    { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2112
    { "bench", TCC_OPTION_bench, 0 },
2113
#ifdef CONFIG_TCC_BACKTRACE
2114
    { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
2115
#endif
2116
#ifdef CONFIG_TCC_BCHECK
2117
    { "b", TCC_OPTION_b, 0 },
2118
#endif
2119
    { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2120
    { "c", TCC_OPTION_c, 0 },
2121
    { "C", TCC_OPTION_C, 0 },
2122
    { "dumpversion", TCC_OPTION_dumpversion, 0},
2123
    { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2124
#ifdef TCC_TARGET_ARM
2125
    { "mfloat-abi", TCC_OPTION_float_abi, TCC_OPTION_HAS_ARG },
2126
#endif
2127
    { "static", TCC_OPTION_static, 0 },
2128
    { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2129
    { "shared", TCC_OPTION_shared, 0 },
2130
    { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
2131
    { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
2132
    { "pedantic", TCC_OPTION_pedantic, 0},
2133
    { "pthread", TCC_OPTION_pthread, 0},
2134
    { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2135
    { "rdynamic", TCC_OPTION_rdynamic, 0 },
2136
    { "r", TCC_OPTION_r, 0 },
2137
    { "s", TCC_OPTION_s, 0 },
2138
    { "traditional", TCC_OPTION_traditional, 0 },
2139
    { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2140
    { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2141
    { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2142
    { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
2143
    { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2144
    { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
2145
    { "iwithprefix", TCC_OPTION_iwithprefix, TCC_OPTION_HAS_ARG },
2146
    { "nostdinc", TCC_OPTION_nostdinc, 0 },
2147
    { "nostdlib", TCC_OPTION_nostdlib, 0 },
2148
    { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
2149
    { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
2150
    { "w", TCC_OPTION_w, 0 },
2151
    { "pipe", TCC_OPTION_pipe, 0},
2152
    { "E", TCC_OPTION_E, 0},
2153
    { "MD", TCC_OPTION_MD, 0},
2154
    { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
2155
    { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
6441 siemargl 2156
    { "stack", TCC_OPTION_stack, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP},
9284 Coldy 2157
#if defined(TCC_TARGET_MEOS) && !defined (TCC_TARGET_KX)
8157 Boppan 2158
    { "nobss", TCC_OPTION_nobss, 0 },
9284 Coldy 2159
#endif
6429 siemargl 2160
    { NULL, 0, 0 },
2161
};
2162
 
2163
static void parse_option_D(TCCState *s1, const char *optarg)
2164
{
2165
    char *sym = tcc_strdup(optarg);
2166
    char *value = strchr(sym, '=');
2167
    if (value)
2168
        *value++ = '\0';
2169
    tcc_define_symbol(s1, sym, value);
2170
    tcc_free(sym);
2171
}
2172
 
2173
static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
2174
{
2175
    int len = strlen(filename);
2176
    char *p = tcc_malloc(len + 2);
2177
    if (filetype) {
2178
        *p = filetype;
2179
    }
2180
    else {
2181
        /* use a file extension to detect a filetype */
2182
        const char *ext = tcc_fileextension(filename);
2183
        if (ext[0]) {
2184
            ext++;
2185
            if (!strcmp(ext, "S"))
2186
                *p = TCC_FILETYPE_ASM_PP;
2187
            else
2188
            if (!strcmp(ext, "s"))
2189
                *p = TCC_FILETYPE_ASM;
2190
            else
2191
            if (!PATHCMP(ext, "c") || !PATHCMP(ext, "i"))
2192
                *p = TCC_FILETYPE_C;
2193
            else
2194
                *p = TCC_FILETYPE_BINARY;
2195
        }
2196
        else {
2197
            *p = TCC_FILETYPE_C;
2198
        }
2199
    }
2200
    strcpy(p+1, filename);
2201
    dynarray_add((void ***)&s->files, &s->nb_files, p);
2202
}
2203
 
2204
ST_FUNC int tcc_parse_args1(TCCState *s, int argc, char **argv)
2205
{
2206
    const TCCOption *popt;
2207
    const char *optarg, *r;
2208
    int optind = 0;
2209
    ParseArgsState *pas = s->parse_args_state;
2210
 
6460 siemargl 2211
/*
2212
#ifdef TCC_TARGET_MEOS
2213
// siemargl testing
2214
	s->output_format = TCC_OUTPUT_FORMAT_COFF;
2215
#endif
2216
*/
6429 siemargl 2217
    while (optind < argc) {
2218
 
2219
        r = argv[optind++];
2220
        if (r[0] != '-' || r[1] == '\0') {
2221
            /* handle list files */
2222
            if (r[0] == '@' && r[1]) {
2223
                char buf[sizeof file->filename], *p;
2224
                char **argv = NULL;
2225
                int argc = 0;
2226
                FILE *fp;
2227
 
2228
                fp = fopen(r + 1, "rb");
2229
                if (fp == NULL)
2230
                    tcc_error("list file '%s' not found", r + 1);
2231
                while (fgets(buf, sizeof buf, fp)) {
2232
                    p = trimfront(trimback(buf, strchr(buf, 0)));
2233
                    if (0 == *p || ';' == *p)
2234
                        continue;
2235
                    dynarray_add((void ***)&argv, &argc, tcc_strdup(p));
2236
                }
2237
                fclose(fp);
2238
                tcc_parse_args1(s, argc, argv);
2239
                dynarray_reset(&argv, &argc);
2240
            } else {
2241
                args_parser_add_file(s, r, pas->filetype);
2242
                if (pas->run) {
2243
                    optind--;
2244
                    /* argv[0] will be this file */
2245
                    break;
2246
                }
2247
            }
2248
            continue;
2249
        }
2250
 
2251
        /* find option in table */
2252
        for(popt = tcc_options; ; ++popt) {
2253
            const char *p1 = popt->name;
2254
            const char *r1 = r + 1;
2255
            if (p1 == NULL)
2256
                tcc_error("invalid option -- '%s'", r);
2257
            if (!strstart(p1, &r1))
2258
                continue;
2259
            optarg = r1;
2260
            if (popt->flags & TCC_OPTION_HAS_ARG) {
2261
                if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
2262
                    if (optind >= argc)
2263
                        tcc_error("argument to '%s' is missing", r);
2264
                    optarg = argv[optind++];
2265
                }
2266
            } else if (*r1 != '\0')
2267
                continue;
2268
            break;
2269
        }
2270
 
2271
        switch(popt->index) {
2272
        case TCC_OPTION_HELP:
2273
            return 0;
2274
        case TCC_OPTION_I:
2275
            tcc_add_include_path(s, optarg);
2276
            break;
2277
        case TCC_OPTION_D:
2278
            parse_option_D(s, optarg);
2279
            break;
2280
        case TCC_OPTION_U:
2281
            tcc_undefine_symbol(s, optarg);
2282
            break;
2283
        case TCC_OPTION_L:
2284
            tcc_add_library_path(s, optarg);
2285
            break;
2286
        case TCC_OPTION_B:
2287
            /* set tcc utilities path (mainly for tcc development) */
2288
            tcc_set_lib_path(s, optarg);
9615 turbocat 2289
#ifdef TCC_TARGET_MEOS
2290
            tcc_split_path(s, (void ***)&s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
2291
#endif
6429 siemargl 2292
            break;
2293
        case TCC_OPTION_l:
2294
            args_parser_add_file(s, r, TCC_FILETYPE_BINARY);
2295
            s->nb_libraries++;
2296
            break;
2297
        case TCC_OPTION_pthread:
2298
            parse_option_D(s, "_REENTRANT");
2299
            pas->pthread = 1;
2300
            break;
2301
        case TCC_OPTION_bench:
2302
            s->do_bench = 1;
2303
            break;
2304
#ifdef CONFIG_TCC_BACKTRACE
2305
        case TCC_OPTION_bt:
2306
            tcc_set_num_callers(atoi(optarg));
2307
            break;
2308
#endif
2309
#ifdef CONFIG_TCC_BCHECK
2310
        case TCC_OPTION_b:
2311
            s->do_bounds_check = 1;
2312
            s->do_debug = 1;
2313
            break;
2314
#endif
2315
        case TCC_OPTION_g:
2316
            s->do_debug = 1;
2317
            break;
2318
        case TCC_OPTION_c:
2319
            if (s->output_type)
2320
                tcc_warning("-c: some compiler action already specified (%d)", s->output_type);
2321
            s->output_type = TCC_OUTPUT_OBJ;
2322
            break;
2323
        case TCC_OPTION_C:
2324
            s->option_C = 1;
2325
            break;
2326
        case TCC_OPTION_d:
2327
            if (*optarg == 'D' || *optarg == 'M')
2328
                s->dflag = *optarg;
2329
            else {
2330
                if (s->warn_unsupported)
2331
                    goto unsupported_option;
2332
                tcc_error("invalid option -- '%s'", r);
2333
            }
2334
            break;
2335
#ifdef TCC_TARGET_ARM
2336
        case TCC_OPTION_float_abi:
2337
            /* tcc doesn't support soft float yet */
2338
            if (!strcmp(optarg, "softfp")) {
2339
                s->float_abi = ARM_SOFTFP_FLOAT;
2340
                tcc_undefine_symbol(s, "__ARM_PCS_VFP");
2341
            } else if (!strcmp(optarg, "hard"))
2342
                s->float_abi = ARM_HARD_FLOAT;
2343
            else
2344
                tcc_error("unsupported float abi '%s'", optarg);
2345
            break;
2346
#endif
2347
        case TCC_OPTION_static:
2348
            s->static_link = 1;
2349
            break;
2350
        case TCC_OPTION_std:
2351
    	    /* silently ignore, a current purpose:
2352
    	       allow to use a tcc as a reference compiler for "make test" */
2353
            break;
2354
        case TCC_OPTION_shared:
2355
    	    if (s->output_type)
2356
                tcc_warning("-shared: some compiler action already specified (%d)", s->output_type);
2357
            s->output_type = TCC_OUTPUT_DLL;
2358
            break;
2359
        case TCC_OPTION_soname:
2360
            s->soname = tcc_strdup(optarg);
2361
            break;
2362
        case TCC_OPTION_m:
2363
            s->option_m = tcc_strdup(optarg);
2364
            break;
2365
        case TCC_OPTION_o:
2366
            if (s->outfile) {
2367
                tcc_warning("multiple -o option");
2368
                tcc_free(s->outfile);
2369
            }
2370
            s->outfile = tcc_strdup(optarg);
2371
            break;
2372
        case TCC_OPTION_r:
2373
            /* generate a .o merging several output files */
2374
    	    if (s->output_type)
2375
                tcc_warning("-r: some compiler action already specified (%d)", s->output_type);
2376
            s->option_r = 1;
2377
            s->output_type = TCC_OUTPUT_OBJ;
2378
            break;
2379
        case TCC_OPTION_isystem:
2380
            tcc_add_sysinclude_path(s, optarg);
2381
            break;
2382
        case TCC_OPTION_iwithprefix:
2383
            if (1) {
2384
                char buf[1024];
2385
                int buf_size = sizeof(buf)-1;
2386
                char *p = &buf[0];
2387
 
2388
                char *sysroot = "{B}/";
2389
                int len = strlen(sysroot);
2390
                if (len > buf_size)
2391
                    len = buf_size;
2392
                strncpy(p, sysroot, len);
2393
                p += len;
2394
                buf_size -= len;
2395
 
2396
                len = strlen(optarg);
2397
                if (len > buf_size)
2398
                    len = buf_size;
2399
                strncpy(p, optarg, len+1);
2400
                tcc_add_sysinclude_path(s, buf);
2401
            }
2402
            break;
2403
        case TCC_OPTION_nostdinc:
2404
            s->nostdinc = 1;
2405
            break;
2406
        case TCC_OPTION_nostdlib:
2407
            s->nostdlib = 1;
2408
            break;
2409
        case TCC_OPTION_print_search_dirs:
2410
            s->print_search_dirs = 1;
2411
            break;
2412
        case TCC_OPTION_run:
2413
    	    if (s->output_type)
2414
                tcc_warning("-run: some compiler action already specified (%d)", s->output_type);
2415
            s->output_type = TCC_OUTPUT_MEMORY;
2416
            tcc_set_options(s, optarg);
2417
            pas->run = 1;
2418
            break;
2419
        case TCC_OPTION_v:
2420
            do ++s->verbose; while (*optarg++ == 'v');
2421
            break;
2422
        case TCC_OPTION_f:
2423
            if (tcc_set_flag(s, optarg, 1) < 0 && s->warn_unsupported)
2424
                goto unsupported_option;
2425
            break;
2426
        case TCC_OPTION_W:
2427
            if (tcc_set_warning(s, optarg, 1) < 0 &&
2428
                s->warn_unsupported)
2429
                goto unsupported_option;
2430
            break;
2431
        case TCC_OPTION_w:
2432
            s->warn_none = 1;
2433
            break;
2434
        case TCC_OPTION_rdynamic:
2435
            s->rdynamic = 1;
2436
            break;
2437
        case TCC_OPTION_Wl:
2438
            if (pas->linker_arg.size)
2439
                --pas->linker_arg.size, cstr_ccat(&pas->linker_arg, ',');
2440
            cstr_cat(&pas->linker_arg, optarg, 0);
2441
            break;
2442
        case TCC_OPTION_E:
2443
    	    if (s->output_type)
2444
                tcc_warning("-E: some compiler action already specified (%d)", s->output_type);
2445
            s->output_type = TCC_OUTPUT_PREPROCESS;
2446
            break;
2447
        case TCC_OPTION_P:
2448
            s->Pflag = atoi(optarg) + 1;
2449
            break;
2450
        case TCC_OPTION_MD:
2451
            s->gen_deps = 1;
2452
            break;
2453
        case TCC_OPTION_MF:
2454
            s->deps_outfile = tcc_strdup(optarg);
2455
            break;
2456
        case TCC_OPTION_dumpversion:
2457
            printf ("%s\n", TCC_VERSION);
2458
            exit(0);
2459
        case TCC_OPTION_s:
2460
            s->do_strip = 1;
2461
            break;
2462
        case TCC_OPTION_traditional:
2463
            break;
2464
        case TCC_OPTION_x:
2465
            if (*optarg == 'c')
2466
                pas->filetype = TCC_FILETYPE_C;
2467
            else
2468
            if (*optarg == 'a')
2469
                pas->filetype = TCC_FILETYPE_ASM_PP;
2470
            else
2471
            if (*optarg == 'n')
2472
                pas->filetype = 0;
2473
            else
2474
                tcc_warning("unsupported language '%s'", optarg);
2475
            break;
2476
        case TCC_OPTION_O:
2477
            if (1) {
2478
                int opt = atoi(optarg);
2479
                char *sym = "__OPTIMIZE__";
2480
                if (opt)
2481
                    tcc_define_symbol(s, sym, 0);
2482
                else
2483
                    tcc_undefine_symbol(s, sym);
2484
            }
2485
            break;
2486
        case TCC_OPTION_pedantic:
2487
        case TCC_OPTION_pipe:
2488
            /* ignored */
2489
            break;
6441 siemargl 2490
        case TCC_OPTION_stack:
8157 Boppan 2491
#ifdef TCC_TARGET_MEOS
2492
            s->pe_stack_size = strtoul(optarg+1, NULL, 10);
2493
#endif
6441 siemargl 2494
            break;
9284 Coldy 2495
#if defined(TCC_TARGET_MEOS) && !defined (TCC_TARGET_KX)
8157 Boppan 2496
        case TCC_OPTION_nobss:
2497
            s->nobss = 1;
2498
            break;
9284 Coldy 2499
#endif
6429 siemargl 2500
        default:
2501
            if (s->warn_unsupported) {
2502
            unsupported_option:
2503
                tcc_warning("unsupported option '%s'", r);
2504
            }
2505
            break;
2506
        }
2507
    }
2508
    return optind;
2509
}
2510
 
2511
PUB_FUNC int tcc_parse_args(TCCState *s, int argc, char **argv)
2512
{
2513
    ParseArgsState *pas;
2514
    int ret, is_allocated = 0;
2515
 
2516
    if (!s->parse_args_state) {
2517
        s->parse_args_state = tcc_mallocz(sizeof(ParseArgsState));
2518
        cstr_new(&s->parse_args_state->linker_arg);
2519
        is_allocated = 1;
2520
    }
2521
    pas = s->parse_args_state;
2522
 
2523
    ret = tcc_parse_args1(s, argc, argv);
2524
 
2525
    if (s->output_type == 0)
2526
        s->output_type = TCC_OUTPUT_EXE;
2527
 
2528
    if (pas->pthread && s->output_type != TCC_OUTPUT_OBJ)
2529
        tcc_set_options(s, "-lpthread");
2530
 
2531
    if (s->output_type == TCC_OUTPUT_EXE)
2532
        tcc_set_linker(s, (const char *)pas->linker_arg.data);
2533
 
2534
    if (is_allocated) {
2535
        cstr_free(&pas->linker_arg);
2536
        tcc_free(pas);
2537
        s->parse_args_state = NULL;
2538
    }
2539
    return ret;
2540
}
2541
 
2542
LIBTCCAPI int tcc_set_options(TCCState *s, const char *str)
2543
{
2544
    const char *s1;
2545
    char **argv, *arg;
2546
    int argc, len;
2547
    int ret;
2548
 
2549
    argc = 0, argv = NULL;
2550
    for(;;) {
2551
        while (is_space(*str))
2552
            str++;
2553
        if (*str == '\0')
2554
            break;
2555
        s1 = str;
2556
        while (*str != '\0' && !is_space(*str))
2557
            str++;
2558
        len = str - s1;
2559
        arg = tcc_malloc(len + 1);
2560
        pstrncpy(arg, s1, len);
2561
        dynarray_add((void ***)&argv, &argc, arg);
2562
    }
2563
    ret = tcc_parse_args(s, argc, argv);
2564
    dynarray_reset(&argv, &argc);
2565
    return ret;
2566
}
2567
 
2568
PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time)
2569
{
2570
    double tt;
2571
    tt = (double)total_time / 1000000.0;
2572
    if (tt < 0.001)
2573
        tt = 0.001;
2574
    if (total_bytes < 1)
2575
        total_bytes = 1;
6574 siemargl 2576
    fprintf(stdout, "%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
6429 siemargl 2577
           tok_ident - TOK_IDENT, total_lines, total_bytes,
2578
           tt, (int)(total_lines / tt),
2579
           total_bytes / tt / 1000000.0);
2580
}
2581
 
2582
PUB_FUNC void tcc_set_environment(TCCState *s)
2583
{
2584
    char * path;
2585
 
2586
    path = getenv("C_INCLUDE_PATH");
2587
    if(path != NULL) {
2588
        tcc_add_include_path(s, path);
2589
    }
2590
    path = getenv("CPATH");
2591
    if(path != NULL) {
2592
        tcc_add_include_path(s, path);
2593
    }
2594
    path = getenv("LIBRARY_PATH");
2595
    if(path != NULL) {
2596
        tcc_add_library_path(s, path);
2597
    }
2598
}