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