6314dc6461f64bc10f16320353ef7f327610158f
[platform/upstream/nasm.git] / nasmlib.c
1 /* ----------------------------------------------------------------------- *
2  *   
3  *   Copyright 1996-2009 The NASM Authors - All Rights Reserved
4  *   See the file AUTHORS included with the NASM distribution for
5  *   the specific copyright holders.
6  *
7  *   This program is free software; you can redistribute it and/or modify
8  *   it under the terms of the GNU Lesser General Public License as
9  *   published by the Free Software Foundation, Inc.,
10  *   51 Franklin St, Fifth Floor, Boston MA 02110-1301, USA; version 2.1,
11  *   or, at your option, any later version, incorporated herein by
12  *   reference.
13  *
14  *   Patches submitted to this file are required to be dual licensed
15  *   under the LGPL 2.1+ and the 2-clause BSD license:
16  *
17  *   Copyright 1996-2009 the NASM Authors - All rights reserved.
18  *
19  *   Redistribution and use in source and binary forms, with or without
20  *   modification, are permitted provided that the following
21  *   conditions are met:
22  *
23  *   * Redistributions of source code must retain the above copyright
24  *     notice, this list of conditions and the following disclaimer.
25  *   * Redistributions in binary form must reproduce the above
26  *     copyright notice, this list of conditions and the following
27  *     disclaimer in the documentation and/or other materials provided
28  *     with the distribution.
29  *     
30  *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
31  *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
32  *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
33  *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
34  *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
35  *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36  *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37  *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
38  *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39  *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
40  *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
41  *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
42  *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43  *
44  * ----------------------------------------------------------------------- */
45
46 /*
47  * nasmlib.c    library routines for the Netwide Assembler
48  */
49
50 #include "compiler.h"
51
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <ctype.h>
56 #include <inttypes.h>
57
58 #include "nasm.h"
59 #include "nasmlib.h"
60 #include "insns.h"
61
62 int globalbits = 0;    /* defined in nasm.h, works better here for ASM+DISASM */
63 efunc nasm_malloc_error;        /* Exported for the benefit of vsnprintf.c */
64
65 #ifdef LOGALLOC
66 static FILE *logfp;
67 #endif
68
69 /* Uninitialized -> all zero by C spec */
70 const uint8_t zero_buffer[ZERO_BUF_SIZE];
71
72 /*
73  * Prepare a table of tolower() results.  This avoids function calls
74  * on some platforms.
75  */
76
77 unsigned char nasm_tolower_tab[256];
78
79 void tolower_init(void)
80 {
81     int i;
82
83     for (i = 0; i < 256; i++)
84         nasm_tolower_tab[i] = tolower(i);
85 }
86
87 void nasm_set_malloc_error(efunc error)
88 {
89     nasm_malloc_error = error;
90 #ifdef LOGALLOC
91     logfp = fopen("malloc.log", "w");
92     setvbuf(logfp, NULL, _IOLBF, BUFSIZ);
93     fprintf(logfp, "null pointer is %p\n", NULL);
94 #endif
95 }
96
97 #ifdef LOGALLOC
98 void *nasm_malloc_log(const char *file, int line, size_t size)
99 #else
100 void *nasm_malloc(size_t size)
101 #endif
102 {
103     void *p = malloc(size);
104     if (!p)
105         nasm_malloc_error(ERR_FATAL | ERR_NOFILE, "out of memory");
106 #ifdef LOGALLOC
107     else
108         fprintf(logfp, "%s %d malloc(%ld) returns %p\n",
109                 file, line, (long)size, p);
110 #endif
111     return p;
112 }
113
114 #ifdef LOGALLOC
115 void *nasm_zalloc_log(const char *file, int line, size_t size)
116 #else
117 void *nasm_zalloc(size_t size)
118 #endif
119 {
120     void *p = calloc(size, 1);
121     if (!p)
122         nasm_malloc_error(ERR_FATAL | ERR_NOFILE, "out of memory");
123 #ifdef LOGALLOC
124     else
125         fprintf(logfp, "%s %d calloc(%ld, 1) returns %p\n",
126                 file, line, (long)size, p);
127 #endif
128     return p;
129 }
130
131 #ifdef LOGALLOC
132 void *nasm_realloc_log(const char *file, int line, void *q, size_t size)
133 #else
134 void *nasm_realloc(void *q, size_t size)
135 #endif
136 {
137     void *p = q ? realloc(q, size) : malloc(size);
138     if (!p)
139         nasm_malloc_error(ERR_FATAL | ERR_NOFILE, "out of memory");
140 #ifdef LOGALLOC
141     else if (q)
142         fprintf(logfp, "%s %d realloc(%p,%ld) returns %p\n",
143                 file, line, q, (long)size, p);
144     else
145         fprintf(logfp, "%s %d malloc(%ld) returns %p\n",
146                 file, line, (long)size, p);
147 #endif
148     return p;
149 }
150
151 #ifdef LOGALLOC
152 void nasm_free_log(const char *file, int line, void *q)
153 #else
154 void nasm_free(void *q)
155 #endif
156 {
157     if (q) {
158 #ifdef LOGALLOC
159         fprintf(logfp, "%s %d free(%p)\n", file, line, q);
160 #endif
161         free(q);
162     }
163 }
164
165 #ifdef LOGALLOC
166 char *nasm_strdup_log(const char *file, int line, const char *s)
167 #else
168 char *nasm_strdup(const char *s)
169 #endif
170 {
171     char *p;
172     int size = strlen(s) + 1;
173
174     p = malloc(size);
175     if (!p)
176         nasm_malloc_error(ERR_FATAL | ERR_NOFILE, "out of memory");
177 #ifdef LOGALLOC
178     else
179         fprintf(logfp, "%s %d strdup(%ld) returns %p\n",
180                 file, line, (long)size, p);
181 #endif
182     strcpy(p, s);
183     return p;
184 }
185
186 #ifdef LOGALLOC
187 char *nasm_strndup_log(const char *file, int line, const char *s, size_t len)
188 #else
189 char *nasm_strndup(const char *s, size_t len)
190 #endif
191 {
192     char *p;
193     int size = len + 1;
194
195     p = malloc(size);
196     if (!p)
197         nasm_malloc_error(ERR_FATAL | ERR_NOFILE, "out of memory");
198 #ifdef LOGALLOC
199     else
200         fprintf(logfp, "%s %d strndup(%ld) returns %p\n",
201                 file, line, (long)size, p);
202 #endif
203     strncpy(p, s, len);
204     p[len] = '\0';
205     return p;
206 }
207
208 no_return nasm_assert_failed(const char *file, int line, const char *msg)
209 {
210     nasm_malloc_error(ERR_FATAL, "assertion %s failed at %s:%d",
211                       msg, file, line);
212     exit(1);
213 }
214
215 #ifndef nasm_stricmp
216 int nasm_stricmp(const char *s1, const char *s2)
217 {
218     unsigned char c1, c2;
219     int d;
220
221     while (1) {
222         c1 = nasm_tolower(*s1++);
223         c2 = nasm_tolower(*s2++);
224         d = c1-c2;
225
226         if (d)
227             return d;
228         if (!c1)
229             break;
230     }
231     return 0;
232 }
233 #endif
234
235 #ifndef nasm_strnicmp
236 int nasm_strnicmp(const char *s1, const char *s2, size_t n)
237 {
238     unsigned char c1, c2;
239     int d;
240
241     while (n--) {
242         c1 = nasm_tolower(*s1++);
243         c2 = nasm_tolower(*s2++);
244         d = c1-c2;
245
246         if (d)
247             return d;
248         if (!c1)
249             break;
250     }
251     return 0;
252 }
253 #endif
254
255 int nasm_memicmp(const char *s1, const char *s2, size_t n)
256 {
257     unsigned char c1, c2;
258     int d;
259
260     while (n--) {
261         c1 = nasm_tolower(*s1++);
262         c2 = nasm_tolower(*s2++);
263         d = c1-c2;
264         if (d)
265             return d;
266     }
267     return 0;
268 }
269
270 #ifndef nasm_strsep
271 char *nasm_strsep(char **stringp, const char *delim)
272 {
273         char *s = *stringp;
274         char *e;
275
276         if (!s)
277                 return NULL;
278
279         e = strpbrk(s, delim);
280         if (e)
281                 *e++ = '\0';
282
283         *stringp = e;
284         return s;
285 }
286 #endif
287
288
289 #define lib_isnumchar(c)   (nasm_isalnum(c) || (c) == '$' || (c) == '_')
290 #define numvalue(c)  ((c)>='a' ? (c)-'a'+10 : (c)>='A' ? (c)-'A'+10 : (c)-'0')
291
292 static int radix_letter(char c)
293 {
294     switch (c) {
295     case 'b': case 'B':
296     case 'y': case 'Y':
297         return 2;               /* Binary */
298     case 'o': case 'O':
299     case 'q': case 'Q':
300         return 8;               /* Octal */
301     case 'h': case 'H':
302     case 'x': case 'X':
303         return 16;              /* Hexadecimal */
304     case 'd': case 'D':
305     case 't': case 'T':
306         return 10;              /* Decimal */
307     default:
308         return 0;               /* Not a known radix letter */
309     }
310 }
311
312 int64_t readnum(char *str, bool *error)
313 {
314     char *r = str, *q;
315     int32_t pradix, sradix, radix;
316     int plen, slen, len;
317     uint64_t result, checklimit;
318     int digit, last;
319     bool warn = false;
320     int sign = 1;
321
322     *error = false;
323
324     while (nasm_isspace(*r))
325         r++;                    /* find start of number */
326
327     /*
328      * If the number came from make_tok_num (as a result of an %assign), it
329      * might have a '-' built into it (rather than in a preceeding token).
330      */
331     if (*r == '-') {
332         r++;
333         sign = -1;
334     }
335
336     q = r;
337
338     while (lib_isnumchar(*q))
339         q++;                    /* find end of number */
340
341     len = q-r;
342     if (!len) {
343         /* Not numeric */
344         *error = true;
345         return 0;
346     }
347
348     /*
349      * Handle radix formats:
350      *
351      * 0<radix-letter><string>
352      * $<string>                (hexadecimal)
353      * <string><radix-letter>
354      */
355     pradix = sradix = 0;
356     plen = slen = 0;
357
358     if (len > 2 && *r == '0' && (pradix = radix_letter(r[1])) != 0)
359         plen = 2;
360     else if (len > 1 && *r == '$')
361         pradix = 16, plen = 1;
362
363     if (len > 1 && (sradix = radix_letter(q[-1])) != 0)
364         slen = 1;
365
366     if (pradix > sradix) {
367         radix = pradix;
368         r += plen;
369     } else if (sradix > pradix) {
370         radix = sradix;
371         q -= slen;
372     } else {
373         /* Either decimal, or invalid -- if invalid, we'll trip up
374            further down. */
375         radix = 10;
376     }
377
378     /*
379      * `checklimit' must be 2**64 / radix. We can't do that in
380      * 64-bit arithmetic, which we're (probably) using, so we
381      * cheat: since we know that all radices we use are even, we
382      * can divide 2**63 by radix/2 instead.
383      */
384     checklimit = 0x8000000000000000ULL / (radix >> 1);
385
386     /*
387      * Calculate the highest allowable value for the last digit of a
388      * 64-bit constant... in radix 10, it is 6, otherwise it is 0
389      */
390     last = (radix == 10 ? 6 : 0);
391
392     result = 0;
393     while (*r && r < q) {
394         if (*r != '_') {
395             if (*r < '0' || (*r > '9' && *r < 'A')
396                 || (digit = numvalue(*r)) >= radix) {
397                 *error = true;
398                 return 0;
399             }
400             if (result > checklimit ||
401                 (result == checklimit && digit >= last)) {
402                 warn = true;
403             }
404
405             result = radix * result + digit;
406         }
407         r++;
408     }
409
410     if (warn)
411         nasm_malloc_error(ERR_WARNING | ERR_PASS1 | ERR_WARN_NOV,
412                           "numeric constant %s does not fit in 64 bits",
413                           str);
414
415     return result * sign;
416 }
417
418 int64_t readstrnum(char *str, int length, bool *warn)
419 {
420     int64_t charconst = 0;
421     int i;
422
423     *warn = false;
424
425     str += length;
426     if (globalbits == 64) {
427         for (i = 0; i < length; i++) {
428             if (charconst & 0xFF00000000000000ULL)
429                 *warn = true;
430             charconst = (charconst << 8) + (uint8_t)*--str;
431         }
432     } else {
433         for (i = 0; i < length; i++) {
434             if (charconst & 0xFF000000UL)
435                 *warn = true;
436             charconst = (charconst << 8) + (uint8_t)*--str;
437         }
438     }
439     return charconst;
440 }
441
442 static int32_t next_seg;
443
444 void seg_init(void)
445 {
446     next_seg = 0;
447 }
448
449 int32_t seg_alloc(void)
450 {
451     return (next_seg += 2) - 2;
452 }
453
454 #ifdef WORDS_LITTLEENDIAN
455
456 void fwriteint16_t(uint16_t data, FILE * fp)
457 {
458     fwrite(&data, 1, 2, fp);
459 }
460
461 void fwriteint32_t(uint32_t data, FILE * fp)
462 {
463     fwrite(&data, 1, 4, fp);
464 }
465
466 void fwriteint64_t(uint64_t data, FILE * fp)
467 {
468     fwrite(&data, 1, 8, fp);
469 }
470
471 void fwriteaddr(uint64_t data, int size, FILE * fp)
472 {
473     fwrite(&data, 1, size, fp);
474 }
475
476 #else /* not WORDS_LITTLEENDIAN */
477
478 void fwriteint16_t(uint16_t data, FILE * fp)
479 {
480     char buffer[2], *p = buffer;
481     WRITESHORT(p, data);
482     fwrite(buffer, 1, 2, fp);
483 }
484
485 void fwriteint32_t(uint32_t data, FILE * fp)
486 {
487     char buffer[4], *p = buffer;
488     WRITELONG(p, data);
489     fwrite(buffer, 1, 4, fp);
490 }
491
492 void fwriteint64_t(uint64_t data, FILE * fp)
493 {
494     char buffer[8], *p = buffer;
495     WRITEDLONG(p, data);
496     fwrite(buffer, 1, 8, fp);
497 }
498
499 void fwriteaddr(uint64_t data, int size, FILE * fp)
500 {
501     char buffer[8], *p = buffer;
502     WRITEADDR(p, data, size);
503     fwrite(buffer, 1, size, fp);
504 }
505
506 #endif
507
508 size_t fwritezero(size_t bytes, FILE *fp)
509 {
510     size_t count = 0;
511     size_t blksize;
512     size_t rv;
513
514     while (bytes) {
515         blksize = (bytes < ZERO_BUF_SIZE) ? bytes : ZERO_BUF_SIZE;
516
517         rv = fwrite(zero_buffer, 1, blksize, fp);
518         if (!rv)
519             break;
520
521         count += rv;
522         bytes -= rv;
523     }
524
525     return count;
526 }
527
528 void standard_extension(char *inname, char *outname, char *extension,
529                         efunc error)
530 {
531     char *p, *q;
532
533     if (*outname)               /* file name already exists, */
534         return;                 /* so do nothing */
535     q = inname;
536     p = outname;
537     while (*q)
538         *p++ = *q++;            /* copy, and find end of string */
539     *p = '\0';                  /* terminate it */
540     while (p > outname && *--p != '.') ;        /* find final period (or whatever) */
541     if (*p != '.')
542         while (*p)
543             p++;                /* go back to end if none found */
544     if (!strcmp(p, extension)) {        /* is the extension already there? */
545         if (*extension)
546             error(ERR_WARNING | ERR_NOFILE,
547                   "file name already ends in `%s': "
548                   "output will be in `nasm.out'", extension);
549         else
550             error(ERR_WARNING | ERR_NOFILE,
551                   "file name already has no extension: "
552                   "output will be in `nasm.out'");
553         strcpy(outname, "nasm.out");
554     } else
555         strcpy(p, extension);
556 }
557
558 /*
559  * Common list of prefix names
560  */
561 static const char *prefix_names[] = {
562     "a16", "a32", "a64", "asp", "lock", "o16", "o32", "o64", "osp",
563     "rep", "repe", "repne", "repnz", "repz", "times", "wait"
564 };
565
566 const char *prefix_name(int token)
567 {
568     unsigned int prefix = token-PREFIX_ENUM_START;
569     if (prefix > elements(prefix_names))
570         return NULL;
571
572     return prefix_names[prefix];
573 }
574
575 /*
576  * Binary search.
577  */
578 int bsi(const char *string, const char **array, int size)
579 {
580     int i = -1, j = size;       /* always, i < index < j */
581     while (j - i >= 2) {
582         int k = (i + j) / 2;
583         int l = strcmp(string, array[k]);
584         if (l < 0)              /* it's in the first half */
585             j = k;
586         else if (l > 0)         /* it's in the second half */
587             i = k;
588         else                    /* we've got it :) */
589             return k;
590     }
591     return -1;                  /* we haven't got it :( */
592 }
593
594 int bsii(const char *string, const char **array, int size)
595 {
596     int i = -1, j = size;       /* always, i < index < j */
597     while (j - i >= 2) {
598         int k = (i + j) / 2;
599         int l = nasm_stricmp(string, array[k]);
600         if (l < 0)              /* it's in the first half */
601             j = k;
602         else if (l > 0)         /* it's in the second half */
603             i = k;
604         else                    /* we've got it :) */
605             return k;
606     }
607     return -1;                  /* we haven't got it :( */
608 }
609
610 static char *file_name = NULL;
611 static int32_t line_number = 0;
612
613 char *src_set_fname(char *newname)
614 {
615     char *oldname = file_name;
616     file_name = newname;
617     return oldname;
618 }
619
620 int32_t src_set_linnum(int32_t newline)
621 {
622     int32_t oldline = line_number;
623     line_number = newline;
624     return oldline;
625 }
626
627 int32_t src_get_linnum(void)
628 {
629     return line_number;
630 }
631
632 int src_get(int32_t *xline, char **xname)
633 {
634     if (!file_name || !*xname || strcmp(*xname, file_name)) {
635         nasm_free(*xname);
636         *xname = file_name ? nasm_strdup(file_name) : NULL;
637         *xline = line_number;
638         return -2;
639     }
640     if (*xline != line_number) {
641         int32_t tmp = line_number - *xline;
642         *xline = line_number;
643         return tmp;
644     }
645     return 0;
646 }
647
648 char *nasm_strcat(const char *one, const char *two)
649 {
650     char *rslt;
651     int l1 = strlen(one);
652     rslt = nasm_malloc(l1 + strlen(two) + 1);
653     strcpy(rslt, one);
654     strcpy(rslt + l1, two);
655     return rslt;
656 }