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