Replace nasm_error(ERR_FATAL/ERR_PANIC) with nasm_fatal/nasm_panic
[nasm.git] / nasmlib.c
blob265091c70956c3cc97d7684d469929c77227ad95
1 /* ----------------------------------------------------------------------- *
2 *
3 * Copyright 1996-2016 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
9 * conditions are met:
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.
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.
32 * ----------------------------------------------------------------------- */
35 * nasmlib.c library routines for the Netwide Assembler
38 #include "compiler.h"
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <ctype.h>
44 #include <errno.h>
45 #include <inttypes.h>
47 #include "nasm.h"
48 #include "nasmlib.h"
49 #include "insns.h"
51 int globalbits = 0; /* defined in nasm.h, works better here for ASM+DISASM */
52 static vefunc nasm_verror; /* Global error handling function */
54 /* Uninitialized -> all zero by C spec */
55 const uint8_t zero_buffer[ZERO_BUF_SIZE];
58 * Prepare a table of tolower() results. This avoids function calls
59 * on some platforms.
62 unsigned char nasm_tolower_tab[256];
64 void tolower_init(void)
66 int i;
68 for (i = 0; i < 256; i++)
69 nasm_tolower_tab[i] = tolower(i);
72 void nasm_set_verror(vefunc ve)
74 nasm_verror = ve;
77 void nasm_error(int severity, const char *fmt, ...)
79 va_list ap;
81 va_start(ap, fmt);
82 nasm_verror(severity, fmt, ap);
83 va_end(ap);
86 no_return nasm_fatal(int flags, const char *fmt, ...)
88 va_list ap;
90 va_start(ap, fmt);
91 nasm_verror(flags | ERR_FATAL, fmt, ap);
92 abort(); /* We should never get here */
95 no_return nasm_panic(int flags, const char *fmt, ...)
97 va_list ap;
99 va_start(ap, fmt);
100 nasm_verror(flags | ERR_PANIC, fmt, ap);
101 abort(); /* We should never get here */
104 no_return nasm_panic_from_macro(const char *file, int line)
106 nasm_panic(ERR_NOFILE, "Internal error at %s:%d\n", file, line);
109 void *nasm_malloc(size_t size)
111 void *p = malloc(size);
112 if (!p)
113 nasm_fatal(ERR_NOFILE, "out of memory");
114 return p;
117 void *nasm_zalloc(size_t size)
119 void *p = calloc(size, 1);
120 if (!p)
121 nasm_fatal(ERR_NOFILE, "out of memory");
122 return p;
125 void *nasm_realloc(void *q, size_t size)
127 void *p = q ? realloc(q, size) : malloc(size);
128 if (!p)
129 nasm_fatal(ERR_NOFILE, "out of memory");
130 return p;
133 void nasm_free(void *q)
135 if (q)
136 free(q);
139 char *nasm_strdup(const char *s)
141 char *p;
142 int size = strlen(s) + 1;
144 p = malloc(size);
145 if (!p)
146 nasm_fatal(ERR_NOFILE, "out of memory");
147 strcpy(p, s);
148 return p;
151 char *nasm_strndup(const char *s, size_t len)
153 char *p;
154 int size = len + 1;
156 p = malloc(size);
157 if (!p)
158 nasm_fatal(ERR_NOFILE, "out of memory");
159 strncpy(p, s, len);
160 p[len] = '\0';
161 return p;
164 no_return nasm_assert_failed(const char *file, int line, const char *msg)
166 nasm_fatal(0, "assertion %s failed at %s:%d", msg, file, line);
167 exit(1);
170 void nasm_write(const void *ptr, size_t size, FILE *f)
172 size_t n = fwrite(ptr, 1, size, f);
173 if (n != size)
174 nasm_fatal(0, "unable to write output: %s", strerror(errno));
177 #ifndef nasm_stricmp
178 int nasm_stricmp(const char *s1, const char *s2)
180 unsigned char c1, c2;
181 int d;
183 while (1) {
184 c1 = nasm_tolower(*s1++);
185 c2 = nasm_tolower(*s2++);
186 d = c1-c2;
188 if (d)
189 return d;
190 if (!c1)
191 break;
193 return 0;
195 #endif
197 #ifndef nasm_strnicmp
198 int nasm_strnicmp(const char *s1, const char *s2, size_t n)
200 unsigned char c1, c2;
201 int d;
203 while (n--) {
204 c1 = nasm_tolower(*s1++);
205 c2 = nasm_tolower(*s2++);
206 d = c1-c2;
208 if (d)
209 return d;
210 if (!c1)
211 break;
213 return 0;
215 #endif
217 int nasm_memicmp(const char *s1, const char *s2, size_t n)
219 unsigned char c1, c2;
220 int d;
222 while (n--) {
223 c1 = nasm_tolower(*s1++);
224 c2 = nasm_tolower(*s2++);
225 d = c1-c2;
226 if (d)
227 return d;
229 return 0;
232 #ifndef nasm_strsep
233 char *nasm_strsep(char **stringp, const char *delim)
235 char *s = *stringp;
236 char *e;
238 if (!s)
239 return NULL;
241 e = strpbrk(s, delim);
242 if (e)
243 *e++ = '\0';
245 *stringp = e;
246 return s;
248 #endif
251 #define lib_isnumchar(c) (nasm_isalnum(c) || (c) == '$' || (c) == '_')
253 static int radix_letter(char c)
255 switch (c) {
256 case 'b': case 'B':
257 case 'y': case 'Y':
258 return 2; /* Binary */
259 case 'o': case 'O':
260 case 'q': case 'Q':
261 return 8; /* Octal */
262 case 'h': case 'H':
263 case 'x': case 'X':
264 return 16; /* Hexadecimal */
265 case 'd': case 'D':
266 case 't': case 'T':
267 return 10; /* Decimal */
268 default:
269 return 0; /* Not a known radix letter */
273 int64_t readnum(char *str, bool *error)
275 char *r = str, *q;
276 int32_t pradix, sradix, radix;
277 int plen, slen, len;
278 uint64_t result, checklimit;
279 int digit, last;
280 bool warn = false;
281 int sign = 1;
283 *error = false;
285 while (nasm_isspace(*r))
286 r++; /* find start of number */
289 * If the number came from make_tok_num (as a result of an %assign), it
290 * might have a '-' built into it (rather than in a preceeding token).
292 if (*r == '-') {
293 r++;
294 sign = -1;
297 q = r;
299 while (lib_isnumchar(*q))
300 q++; /* find end of number */
302 len = q-r;
303 if (!len) {
304 /* Not numeric */
305 *error = true;
306 return 0;
310 * Handle radix formats:
312 * 0<radix-letter><string>
313 * $<string> (hexadecimal)
314 * <string><radix-letter>
316 pradix = sradix = 0;
317 plen = slen = 0;
319 if (len > 2 && *r == '0' && (pradix = radix_letter(r[1])) != 0)
320 plen = 2;
321 else if (len > 1 && *r == '$')
322 pradix = 16, plen = 1;
324 if (len > 1 && (sradix = radix_letter(q[-1])) != 0)
325 slen = 1;
327 if (pradix > sradix) {
328 radix = pradix;
329 r += plen;
330 } else if (sradix > pradix) {
331 radix = sradix;
332 q -= slen;
333 } else {
334 /* Either decimal, or invalid -- if invalid, we'll trip up
335 further down. */
336 radix = 10;
340 * `checklimit' must be 2**64 / radix. We can't do that in
341 * 64-bit arithmetic, which we're (probably) using, so we
342 * cheat: since we know that all radices we use are even, we
343 * can divide 2**63 by radix/2 instead.
345 checklimit = UINT64_C(0x8000000000000000) / (radix >> 1);
348 * Calculate the highest allowable value for the last digit of a
349 * 64-bit constant... in radix 10, it is 6, otherwise it is 0
351 last = (radix == 10 ? 6 : 0);
353 result = 0;
354 while (*r && r < q) {
355 if (*r != '_') {
356 if (*r < '0' || (*r > '9' && *r < 'A')
357 || (digit = numvalue(*r)) >= radix) {
358 *error = true;
359 return 0;
361 if (result > checklimit ||
362 (result == checklimit && digit >= last)) {
363 warn = true;
366 result = radix * result + digit;
368 r++;
371 if (warn)
372 nasm_error(ERR_WARNING | ERR_PASS1 | ERR_WARN_NOV,
373 "numeric constant %s does not fit in 64 bits",
374 str);
376 return result * sign;
379 int64_t readstrnum(char *str, int length, bool *warn)
381 int64_t charconst = 0;
382 int i;
384 *warn = false;
386 str += length;
387 if (globalbits == 64) {
388 for (i = 0; i < length; i++) {
389 if (charconst & UINT64_C(0xFF00000000000000))
390 *warn = true;
391 charconst = (charconst << 8) + (uint8_t)*--str;
393 } else {
394 for (i = 0; i < length; i++) {
395 if (charconst & 0xFF000000UL)
396 *warn = true;
397 charconst = (charconst << 8) + (uint8_t)*--str;
400 return charconst;
403 int32_t seg_alloc(void)
405 static int32_t next_seg = 0;
406 int32_t this_seg = next_seg;
408 next_seg += 2;
410 return this_seg;
413 #ifdef WORDS_LITTLEENDIAN
415 void fwriteint16_t(uint16_t data, FILE * fp)
417 nasm_write(&data, 2, fp);
420 void fwriteint32_t(uint32_t data, FILE * fp)
422 nasm_write(&data, 4, fp);
425 void fwriteint64_t(uint64_t data, FILE * fp)
427 nasm_write(&data, 8, fp);
430 void fwriteaddr(uint64_t data, int size, FILE * fp)
432 nasm_write(&data, size, fp);
435 #else /* not WORDS_LITTLEENDIAN */
437 void fwriteint16_t(uint16_t data, FILE * fp)
439 char buffer[2], *p = buffer;
440 WRITESHORT(p, data);
441 nasm_write(buffer, 2, fp);
444 void fwriteint32_t(uint32_t data, FILE * fp)
446 char buffer[4], *p = buffer;
447 WRITELONG(p, data);
448 nasm_write(buffer, 4, fp);
451 void fwriteint64_t(uint64_t data, FILE * fp)
453 char buffer[8], *p = buffer;
454 WRITEDLONG(p, data);
455 nasm_write(buffer, 8, fp);
458 void fwriteaddr(uint64_t data, int size, FILE * fp)
460 char buffer[8], *p = buffer;
461 WRITEADDR(p, data, size);
462 nasm_write(buffer, size, fp);
465 #endif
467 void fwritezero(size_t bytes, FILE *fp)
469 size_t blksize;
471 while (bytes) {
472 blksize = (bytes < ZERO_BUF_SIZE) ? bytes : ZERO_BUF_SIZE;
474 nasm_write(zero_buffer, blksize, fp);
475 bytes -= blksize;
479 void standard_extension(char *inname, char *outname, char *extension)
481 char *p, *q;
483 if (*outname) /* file name already exists, */
484 return; /* so do nothing */
485 q = inname;
486 p = outname;
487 while (*q)
488 *p++ = *q++; /* copy, and find end of string */
489 *p = '\0'; /* terminate it */
490 while (p > outname && *--p != '.') ; /* find final period (or whatever) */
491 if (*p != '.')
492 while (*p)
493 p++; /* go back to end if none found */
494 if (!strcmp(p, extension)) { /* is the extension already there? */
495 if (*extension)
496 nasm_error(ERR_WARNING | ERR_NOFILE,
497 "file name already ends in `%s': "
498 "output will be in `nasm.out'", extension);
499 else
500 nasm_error(ERR_WARNING | ERR_NOFILE,
501 "file name already has no extension: "
502 "output will be in `nasm.out'");
503 strcpy(outname, "nasm.out");
504 } else
505 strcpy(p, extension);
509 * Common list of prefix names
511 static const char *prefix_names[] = {
512 "a16", "a32", "a64", "asp", "lock", "o16", "o32", "o64", "osp",
513 "rep", "repe", "repne", "repnz", "repz", "times", "wait",
514 "xacquire", "xrelease", "bnd"
517 const char *prefix_name(int token)
519 unsigned int prefix = token-PREFIX_ENUM_START;
520 if (prefix >= ARRAY_SIZE(prefix_names))
521 return NULL;
523 return prefix_names[prefix];
527 * Binary search.
529 int bsi(const char *string, const char **array, int size)
531 int i = -1, j = size; /* always, i < index < j */
532 while (j - i >= 2) {
533 int k = (i + j) / 2;
534 int l = strcmp(string, array[k]);
535 if (l < 0) /* it's in the first half */
536 j = k;
537 else if (l > 0) /* it's in the second half */
538 i = k;
539 else /* we've got it :) */
540 return k;
542 return -1; /* we haven't got it :( */
545 int bsii(const char *string, const char **array, int size)
547 int i = -1, j = size; /* always, i < index < j */
548 while (j - i >= 2) {
549 int k = (i + j) / 2;
550 int l = nasm_stricmp(string, array[k]);
551 if (l < 0) /* it's in the first half */
552 j = k;
553 else if (l > 0) /* it's in the second half */
554 i = k;
555 else /* we've got it :) */
556 return k;
558 return -1; /* we haven't got it :( */
561 static char *file_name = NULL;
562 static int32_t line_number = 0;
564 char *src_set_fname(char *newname)
566 char *oldname = file_name;
567 file_name = newname;
568 return oldname;
571 int32_t src_set_linnum(int32_t newline)
573 int32_t oldline = line_number;
574 line_number = newline;
575 return oldline;
578 int32_t src_get_linnum(void)
580 return line_number;
583 int src_get(int32_t *xline, char **xname)
585 if (!file_name || !*xname || strcmp(*xname, file_name)) {
586 nasm_free(*xname);
587 *xname = file_name ? nasm_strdup(file_name) : NULL;
588 *xline = line_number;
589 return -2;
591 if (*xline != line_number) {
592 int32_t tmp = line_number - *xline;
593 *xline = line_number;
594 return tmp;
596 return 0;
599 char *nasm_strcat(const char *one, const char *two)
601 char *rslt;
602 int l1 = strlen(one);
603 rslt = nasm_malloc(l1 + strlen(two) + 1);
604 strcpy(rslt, one);
605 strcpy(rslt + l1, two);
606 return rslt;
609 /* skip leading spaces */
610 char *nasm_skip_spaces(const char *p)
612 if (p)
613 while (*p && nasm_isspace(*p))
614 p++;
615 return (char *)p;
618 /* skip leading non-spaces */
619 char *nasm_skip_word(const char *p)
621 if (p)
622 while (*p && !nasm_isspace(*p))
623 p++;
624 return (char *)p;
627 /* zap leading spaces with zero */
628 char *nasm_zap_spaces_fwd(char *p)
630 if (p)
631 while (*p && nasm_isspace(*p))
632 *p++ = 0x0;
633 return p;
636 /* zap spaces with zero in reverse order */
637 char *nasm_zap_spaces_rev(char *p)
639 if (p)
640 while (*p && nasm_isspace(*p))
641 *p-- = 0x0;
642 return p;
645 /* zap leading and trailing spaces */
646 char *nasm_trim_spaces(char *p)
648 p = nasm_zap_spaces_fwd(p);
649 nasm_zap_spaces_fwd(nasm_skip_word(p));
651 return p;
655 * return the word extracted from a stream
656 * or NULL if nothing left
658 char *nasm_get_word(char *p, char **tail)
660 char *word = nasm_skip_spaces(p);
661 char *next = nasm_skip_word(word);
663 if (word && *word) {
664 if (*next)
665 *next++ = '\0';
666 } else
667 word = next = NULL;
669 /* NOTE: the tail may start with spaces */
670 *tail = next;
672 return word;
676 * Extract "opt=val" values from the stream and
677 * returns "opt"
679 * Exceptions:
680 * 1) If "=val" passed the NULL returned though
681 * you may continue handling the tail via "next"
682 * 2) If "=" passed the NULL is returned and "val"
683 * is set to NULL as well
685 char *nasm_opt_val(char *p, char **val, char **next)
687 char *q, *nxt;
689 *val = *next = NULL;
691 p = nasm_get_word(p, &nxt);
692 if (!p)
693 return NULL;
695 q = strchr(p, '=');
696 if (q) {
697 if (q == p)
698 p = NULL;
699 *q++='\0';
700 if (*q) {
701 *val = q;
702 } else {
703 q = nasm_get_word(q + 1, &nxt);
704 if (q)
705 *val = q;
707 } else {
708 q = nasm_skip_spaces(nxt);
709 if (q && *q == '=') {
710 q = nasm_get_word(q + 1, &nxt);
711 if (q)
712 *val = q;
716 *next = nxt;
717 return p;
721 * initialized data bytes length from opcode
723 int idata_bytes(int opcode)
725 switch (opcode) {
726 case I_DB:
727 return 1;
728 case I_DW:
729 return 2;
730 case I_DD:
731 return 4;
732 case I_DQ:
733 return 8;
734 case I_DT:
735 return 10;
736 case I_DO:
737 return 16;
738 case I_DY:
739 return 32;
740 case I_DZ:
741 return 64;
742 case I_none:
743 return -1;
744 default:
745 return 0;