Make strings a first-class token type; defer evaluation
[platform/upstream/nasm.git] / nasmlib.c
1 /* nasmlib.c    library routines for the Netwide Assembler
2  *
3  * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
4  * Julian Hall. All rights reserved. The software is
5  * redistributable under the license given in the file "LICENSE"
6  * distributed in the NASM archive.
7  */
8
9 #include "compiler.h"
10
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <ctype.h>
15 #include <inttypes.h>
16
17 #include "nasm.h"
18 #include "nasmlib.h"
19 #include "insns.h"
20
21 int globalbits = 0;    /* defined in nasm.h, works better here for ASM+DISASM */
22 efunc nasm_malloc_error;        /* Exported for the benefit of vsnprintf.c */
23
24 #ifdef LOGALLOC
25 static FILE *logfp;
26 #endif
27
28 void nasm_set_malloc_error(efunc error)
29 {
30     nasm_malloc_error = error;
31 #ifdef LOGALLOC
32     logfp = fopen("malloc.log", "w");
33     setvbuf(logfp, NULL, _IOLBF, BUFSIZ);
34     fprintf(logfp, "null pointer is %p\n", NULL);
35 #endif
36 }
37
38 #ifdef LOGALLOC
39 void *nasm_malloc_log(char *file, int line, size_t size)
40 #else
41 void *nasm_malloc(size_t size)
42 #endif
43 {
44     void *p = malloc(size);
45     if (!p)
46         nasm_malloc_error(ERR_FATAL | ERR_NOFILE, "out of memory");
47 #ifdef LOGALLOC
48     else
49         fprintf(logfp, "%s %d malloc(%ld) returns %p\n",
50                 file, line, (long)size, p);
51 #endif
52     return p;
53 }
54
55 #ifdef LOGALLOC
56 void *nasm_zalloc_log(char *file, int line, size_t size)
57 #else
58 void *nasm_zalloc(size_t size)
59 #endif
60 {
61     void *p = calloc(size, 1);
62     if (!p)
63         nasm_malloc_error(ERR_FATAL | ERR_NOFILE, "out of memory");
64 #ifdef LOGALLOC
65     else
66         fprintf(logfp, "%s %d calloc(%ld, 1) returns %p\n",
67                 file, line, (long)size, p);
68 #endif
69     return p;
70 }
71
72 #ifdef LOGALLOC
73 void *nasm_realloc_log(char *file, int line, void *q, size_t size)
74 #else
75 void *nasm_realloc(void *q, size_t size)
76 #endif
77 {
78     void *p = q ? realloc(q, size) : malloc(size);
79     if (!p)
80         nasm_malloc_error(ERR_FATAL | ERR_NOFILE, "out of memory");
81 #ifdef LOGALLOC
82     else if (q)
83         fprintf(logfp, "%s %d realloc(%p,%ld) returns %p\n",
84                 file, line, q, (long)size, p);
85     else
86         fprintf(logfp, "%s %d malloc(%ld) returns %p\n",
87                 file, line, (long)size, p);
88 #endif
89     return p;
90 }
91
92 #ifdef LOGALLOC
93 void nasm_free_log(char *file, int line, void *q)
94 #else
95 void nasm_free(void *q)
96 #endif
97 {
98     if (q) {
99 #ifdef LOGALLOC
100         fprintf(logfp, "%s %d free(%p)\n", file, line, q);
101 #endif
102         free(q);
103     }
104 }
105
106 #ifdef LOGALLOC
107 char *nasm_strdup_log(char *file, int line, const char *s)
108 #else
109 char *nasm_strdup(const char *s)
110 #endif
111 {
112     char *p;
113     int size = strlen(s) + 1;
114
115     p = malloc(size);
116     if (!p)
117         nasm_malloc_error(ERR_FATAL | ERR_NOFILE, "out of memory");
118 #ifdef LOGALLOC
119     else
120         fprintf(logfp, "%s %d strdup(%ld) returns %p\n",
121                 file, line, (long)size, p);
122 #endif
123     strcpy(p, s);
124     return p;
125 }
126
127 #ifdef LOGALLOC
128 char *nasm_strndup_log(char *file, int line, char *s, size_t len)
129 #else
130 char *nasm_strndup(char *s, size_t len)
131 #endif
132 {
133     char *p;
134     int size = len + 1;
135
136     p = malloc(size);
137     if (!p)
138         nasm_malloc_error(ERR_FATAL | ERR_NOFILE, "out of memory");
139 #ifdef LOGALLOC
140     else
141         fprintf(logfp, "%s %d strndup(%ld) returns %p\n",
142                 file, line, (long)size, p);
143 #endif
144     strncpy(p, s, len);
145     p[len] = '\0';
146     return p;
147 }
148
149 #ifndef nasm_stricmp
150 int nasm_stricmp(const char *s1, const char *s2)
151 {
152     unsigned char c1, c2;
153     int d;
154
155     while (1) {
156         c1 = *s1++;
157         c2 = *s2++;
158         d = c1-c2;
159
160         if (d)
161             return d;
162         if (!c1)
163             break;
164     }
165     return 0;
166 }
167 #endif
168
169 #ifndef nasm_strnicmp
170 int nasm_strnicmp(const char *s1, const char *s2, size_t n)
171 {
172     unsigned char c1, c2;
173     int d;
174
175     while (n--) {
176         c1 = *s1++;
177         c2 = *s2++;
178         d = c1-c2;
179
180         if (d)
181             return d;
182         if (!c1)
183             break;
184     }
185     return 0;
186 }
187 #endif
188
189 int nasm_memicmp(const char *s1, const char *s2, size_t n)
190 {
191     unsigned char c1, c2;
192     int d;
193
194     while (n--) {
195         c1 = tolower(*s1++);
196         c2 = tolower(*s2++);
197         d = c1-c2;
198         if (d)
199             return d;
200     }
201     return 0;
202 }
203
204 #ifndef nasm_strsep
205 char *nasm_strsep(char **stringp, const char *delim)
206 {
207         char *s = *stringp;
208         char *e;
209
210         if (!s)
211                 return NULL;
212
213         e = strpbrk(s, delim);
214         if (e)
215                 *e++ = '\0';
216
217         *stringp = e;
218         return s;
219 }
220 #endif
221
222
223 #define lib_isnumchar(c)   (isalnum(c) || (c) == '$' || (c) == '_')
224 #define numvalue(c)  ((c)>='a' ? (c)-'a'+10 : (c)>='A' ? (c)-'A'+10 : (c)-'0')
225
226 static int radix_letter(char c)
227 {
228     switch (c) {
229     case 'b': case 'B':
230     case 'y': case 'Y':
231         return 2;               /* Binary */
232     case 'o': case 'O':
233     case 'q': case 'Q':
234         return 8;               /* Octal */
235     case 'h': case 'H':
236     case 'x': case 'X':
237         return 16;              /* Hexadecimal */
238     case 'd': case 'D':
239     case 't': case 'T':
240         return 10;              /* Decimal */
241     default:
242         return 0;               /* Not a known radix letter */
243     }
244 }
245
246 int64_t readnum(char *str, bool *error)
247 {
248     char *r = str, *q;
249     int32_t pradix, sradix, radix;
250     int plen, slen, len;
251     uint64_t result, checklimit;
252     int digit, last;
253     bool warn = false;
254     int sign = 1;
255
256     *error = false;
257
258     while (isspace(*r))
259         r++;                    /* find start of number */
260
261     /*
262      * If the number came from make_tok_num (as a result of an %assign), it
263      * might have a '-' built into it (rather than in a preceeding token).
264      */
265     if (*r == '-') {
266         r++;
267         sign = -1;
268     }
269
270     q = r;
271
272     while (lib_isnumchar(*q))
273         q++;                    /* find end of number */
274
275     len = q-r;
276     if (!len) {
277         /* Not numeric */
278         *error = true;
279         return 0;
280     }
281
282     /*
283      * Handle radix formats:
284      *
285      * 0<radix-letter><string>
286      * $<string>                (hexadecimal)
287      * <string><radix-letter>
288      */
289     pradix = sradix = 0;
290     plen = slen = 0;
291
292     if (len > 2 && *r == '0' && (pradix = radix_letter(r[1])) != 0)
293         plen = 2;
294     else if (len > 1 && *r == '$')
295         pradix = 16, plen = 1;
296
297     if (len > 1 && (sradix = radix_letter(q[-1])) != 0)
298         slen = 1;
299
300     if (pradix > sradix) {
301         radix = pradix;
302         r += plen;
303     } else if (sradix > pradix) {
304         radix = sradix;
305         q -= slen;
306     } else {
307         /* Either decimal, or invalid -- if invalid, we'll trip up
308            further down. */
309         radix = 10;
310     }
311
312     /*
313      * `checklimit' must be 2**64 / radix. We can't do that in
314      * 64-bit arithmetic, which we're (probably) using, so we
315      * cheat: since we know that all radices we use are even, we
316      * can divide 2**63 by radix/2 instead.
317      */
318     checklimit = 0x8000000000000000ULL / (radix >> 1);
319
320     /*
321      * Calculate the highest allowable value for the last digit of a
322      * 64-bit constant... in radix 10, it is 6, otherwise it is 0
323      */
324     last = (radix == 10 ? 6 : 0);
325
326     result = 0;
327     while (*r && r < q) {
328         if (*r != '_') {
329             if (*r < '0' || (*r > '9' && *r < 'A')
330                 || (digit = numvalue(*r)) >= radix) {
331                 *error = true;
332                 return 0;
333             }
334             if (result > checklimit ||
335                 (result == checklimit && digit >= last)) {
336                 warn = true;
337             }
338
339             result = radix * result + digit;
340         }
341         r++;
342     }
343
344     if (warn)
345         nasm_malloc_error(ERR_WARNING | ERR_PASS1 | ERR_WARN_NOV,
346                           "numeric constant %s does not fit in 64 bits",
347                           str);
348
349     return result * sign;
350 }
351
352 int64_t readstrnum(char *str, int length, bool *warn)
353 {
354     int64_t charconst = 0;
355     int i;
356
357     *warn = false;
358
359     str += length;
360     if (globalbits == 64) {
361         for (i = 0; i < length; i++) {
362             if (charconst & 0xFF00000000000000ULL)
363                 *warn = true;
364             charconst = (charconst << 8) + (uint8_t)*--str;
365         }
366     } else {
367         for (i = 0; i < length; i++) {
368             if (charconst & 0xFF000000UL)
369                 *warn = true;
370             charconst = (charconst << 8) + (uint8_t)*--str;
371         }
372     }
373     return charconst;
374 }
375
376 static int32_t next_seg;
377
378 void seg_init(void)
379 {
380     next_seg = 0;
381 }
382
383 int32_t seg_alloc(void)
384 {
385     return (next_seg += 2) - 2;
386 }
387
388 #if X86_MEMORY
389
390 void fwriteint16_t(uint16_t data, FILE * fp)
391 {
392     fwrite(&data, 1, 2, fp);
393 }
394
395 void fwriteint32_t(uint32_t data, FILE * fp)
396 {
397     fwrite(&data, 1, 4, fp);
398 }
399
400 void fwriteint64_t(uint64_t data, FILE * fp)
401 {
402     fwrite(&data, 1, 8, fp);
403 }
404
405 void fwriteaddr(uint64_t data, int size, FILE * fp)
406 {
407     fwrite(&data, 1, size, fp);
408 }
409
410 #else /* !X86_MEMORY */
411
412 void fwriteint16_t(uint16_t data, FILE * fp)
413 {
414     char buffer[2], *p = buffer;
415     WRITESHORT(p, data);
416     fwrite(buffer, 1, 2, fp);
417 }
418
419 void fwriteint32_t(uint32_t data, FILE * fp)
420 {
421     char buffer[4], *p = buffer;
422     WRITELONG(p, data);
423     fwrite(buffer, 1, 4, fp);
424 }
425
426 void fwriteint64_t(uint64_t data, FILE * fp)
427 {
428     char buffer[8], *p = buffer;
429     WRITEDLONG(p, data);
430     fwrite(buffer, 1, 8, fp);
431 }
432
433 void fwriteaddr(uint64_t data, int size, FILE * fp)
434 {
435     char buffer[8], *p = buffer;
436     WRITEADDR(p, data, size);
437     fwrite(buffer, 1, size, fp);
438 }
439
440 #endif
441
442 void standard_extension(char *inname, char *outname, char *extension,
443                         efunc error)
444 {
445     char *p, *q;
446
447     if (*outname)               /* file name already exists, */
448         return;                 /* so do nothing */
449     q = inname;
450     p = outname;
451     while (*q)
452         *p++ = *q++;            /* copy, and find end of string */
453     *p = '\0';                  /* terminate it */
454     while (p > outname && *--p != '.') ;        /* find final period (or whatever) */
455     if (*p != '.')
456         while (*p)
457             p++;                /* go back to end if none found */
458     if (!strcmp(p, extension)) {        /* is the extension already there? */
459         if (*extension)
460             error(ERR_WARNING | ERR_NOFILE,
461                   "file name already ends in `%s': "
462                   "output will be in `nasm.out'", extension);
463         else
464             error(ERR_WARNING | ERR_NOFILE,
465                   "file name already has no extension: "
466                   "output will be in `nasm.out'");
467         strcpy(outname, "nasm.out");
468     } else
469         strcpy(p, extension);
470 }
471
472 /*
473  * Common list of prefix names
474  */
475 static const char *prefix_names[] = {
476     "a16", "a32", "lock", "o16", "o32", "rep", "repe", "repne",
477     "repnz", "repz", "times"
478 };
479
480 const char *prefix_name(int token)
481 {
482     unsigned int prefix = token-PREFIX_ENUM_START;
483     if (prefix > elements(prefix_names))
484         return NULL;
485
486     return prefix_names[prefix];
487 }
488
489 /*
490  * Binary search.
491  */
492 int bsi(const char *string, const char **array, int size)
493 {
494     int i = -1, j = size;       /* always, i < index < j */
495     while (j - i >= 2) {
496         int k = (i + j) / 2;
497         int l = strcmp(string, array[k]);
498         if (l < 0)              /* it's in the first half */
499             j = k;
500         else if (l > 0)         /* it's in the second half */
501             i = k;
502         else                    /* we've got it :) */
503             return k;
504     }
505     return -1;                  /* we haven't got it :( */
506 }
507
508 int bsii(const char *string, const char **array, int size)
509 {
510     int i = -1, j = size;       /* always, i < index < j */
511     while (j - i >= 2) {
512         int k = (i + j) / 2;
513         int l = nasm_stricmp(string, array[k]);
514         if (l < 0)              /* it's in the first half */
515             j = k;
516         else if (l > 0)         /* it's in the second half */
517             i = k;
518         else                    /* we've got it :) */
519             return k;
520     }
521     return -1;                  /* we haven't got it :( */
522 }
523
524 static char *file_name = NULL;
525 static int32_t line_number = 0;
526
527 char *src_set_fname(char *newname)
528 {
529     char *oldname = file_name;
530     file_name = newname;
531     return oldname;
532 }
533
534 int32_t src_set_linnum(int32_t newline)
535 {
536     int32_t oldline = line_number;
537     line_number = newline;
538     return oldline;
539 }
540
541 int32_t src_get_linnum(void)
542 {
543     return line_number;
544 }
545
546 int src_get(int32_t *xline, char **xname)
547 {
548     if (!file_name || !*xname || strcmp(*xname, file_name)) {
549         nasm_free(*xname);
550         *xname = file_name ? nasm_strdup(file_name) : NULL;
551         *xline = line_number;
552         return -2;
553     }
554     if (*xline != line_number) {
555         int32_t tmp = line_number - *xline;
556         *xline = line_number;
557         return tmp;
558     }
559     return 0;
560 }
561
562 char *nasm_strcat(char *one, char *two)
563 {
564     char *rslt;
565     int l1 = strlen(one);
566     rslt = nasm_malloc(l1 + strlen(two) + 1);
567     strcpy(rslt, one);
568     strcpy(rslt + l1, two);
569     return rslt;
570 }
571
572 void null_debug_init(struct ofmt *of, void *id, FILE * fp, efunc error)
573 {
574         (void)of;
575         (void)id;
576         (void)fp;
577         (void)error;
578 }
579 void null_debug_linenum(const char *filename, int32_t linenumber, int32_t segto)
580 {
581         (void)filename;
582         (void)linenumber;
583         (void)segto;
584 }
585 void null_debug_deflabel(char *name, int32_t segment, int64_t offset,
586                          int is_global, char *special)
587 {
588         (void)name;
589         (void)segment;
590         (void)offset;
591         (void)is_global;
592         (void)special;
593 }
594 void null_debug_routine(const char *directive, const char *params)
595 {
596         (void)directive;
597         (void)params;
598 }
599 void null_debug_typevalue(int32_t type)
600 {
601         (void)type;
602 }
603 void null_debug_output(int type, void *param)
604 {
605         (void)type;
606         (void)param;
607 }
608 void null_debug_cleanup(void)
609 {
610 }
611
612 struct dfmt null_debug_form = {
613     "Null debug format",
614     "null",
615     null_debug_init,
616     null_debug_linenum,
617     null_debug_deflabel,
618     null_debug_routine,
619     null_debug_typevalue,
620     null_debug_output,
621     null_debug_cleanup
622 };
623
624 struct dfmt *null_debug_arr[2] = { &null_debug_form, NULL };