expand_mmacro: Use list helpers
[nasm/sigaren-mirror.git] / nasmlib.c
blob2351101f190db954092e30a547ca0e1e0cbb21ce
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.
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 <inttypes.h>
46 #include "nasm.h"
47 #include "nasmlib.h"
48 #include "insns.h"
50 int globalbits = 0; /* defined in nasm.h, works better here for ASM+DISASM */
51 static vefunc nasm_verror; /* Global error handling function */
53 #ifdef LOGALLOC
54 static FILE *logfp;
55 #endif
57 /* Uninitialized -> all zero by C spec */
58 const uint8_t zero_buffer[ZERO_BUF_SIZE];
61 * Prepare a table of tolower() results. This avoids function calls
62 * on some platforms.
65 unsigned char nasm_tolower_tab[256];
67 void tolower_init(void)
69 int i;
71 for (i = 0; i < 256; i++)
72 nasm_tolower_tab[i] = tolower(i);
75 void nasm_set_verror(vefunc ve)
77 nasm_verror = ve;
80 void nasm_error(int severity, const char *fmt, ...)
82 va_list ap;
84 va_start(ap, fmt);
85 nasm_verror(severity, fmt, ap);
86 va_end(ap);
89 void nasm_init_malloc_error(void)
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", file);
97 logfp = stderr;
99 fprintf(logfp, "null pointer is %p\n", NULL);
100 #endif
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
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;
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
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;
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
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;
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
163 if (q) {
164 #ifdef LOGALLOC
165 fprintf(logfp, "%s %d free(%p)\n", file, line, q);
166 #endif
167 free(q);
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
177 char *p;
178 int size = strlen(s) + 1;
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;
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
198 char *p;
199 int size = len + 1;
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;
214 no_return nasm_assert_failed(const char *file, int line, const char *msg)
216 nasm_error(ERR_FATAL, "assertion %s failed at %s:%d", msg, file, line);
217 exit(1);
220 #ifndef nasm_stricmp
221 int nasm_stricmp(const char *s1, const char *s2)
223 unsigned char c1, c2;
224 int d;
226 while (1) {
227 c1 = nasm_tolower(*s1++);
228 c2 = nasm_tolower(*s2++);
229 d = c1-c2;
231 if (d)
232 return d;
233 if (!c1)
234 break;
236 return 0;
238 #endif
240 #ifndef nasm_strnicmp
241 int nasm_strnicmp(const char *s1, const char *s2, size_t n)
243 unsigned char c1, c2;
244 int d;
246 while (n--) {
247 c1 = nasm_tolower(*s1++);
248 c2 = nasm_tolower(*s2++);
249 d = c1-c2;
251 if (d)
252 return d;
253 if (!c1)
254 break;
256 return 0;
258 #endif
260 int nasm_memicmp(const char *s1, const char *s2, size_t n)
262 unsigned char c1, c2;
263 int d;
265 while (n--) {
266 c1 = nasm_tolower(*s1++);
267 c2 = nasm_tolower(*s2++);
268 d = c1-c2;
269 if (d)
270 return d;
272 return 0;
275 #ifndef nasm_strsep
276 char *nasm_strsep(char **stringp, const char *delim)
278 char *s = *stringp;
279 char *e;
281 if (!s)
282 return NULL;
284 e = strpbrk(s, delim);
285 if (e)
286 *e++ = '\0';
288 *stringp = e;
289 return s;
291 #endif
294 #define lib_isnumchar(c) (nasm_isalnum(c) || (c) == '$' || (c) == '_')
295 #define numvalue(c) ((c)>='a' ? (c)-'a'+10 : (c)>='A' ? (c)-'A'+10 : (c)-'0')
297 static int radix_letter(char c)
299 switch (c) {
300 case 'b': case 'B':
301 case 'y': case 'Y':
302 return 2; /* Binary */
303 case 'o': case 'O':
304 case 'q': case 'Q':
305 return 8; /* Octal */
306 case 'h': case 'H':
307 case 'x': case 'X':
308 return 16; /* Hexadecimal */
309 case 'd': case 'D':
310 case 't': case 'T':
311 return 10; /* Decimal */
312 default:
313 return 0; /* Not a known radix letter */
317 int64_t readnum(char *str, bool *error)
319 char *r = str, *q;
320 int32_t pradix, sradix, radix;
321 int plen, slen, len;
322 uint64_t result, checklimit;
323 int digit, last;
324 bool warn = false;
325 int sign = 1;
327 *error = false;
329 while (nasm_isspace(*r))
330 r++; /* find start of number */
333 * If the number came from make_tok_num (as a result of an %assign), it
334 * might have a '-' built into it (rather than in a preceeding token).
336 if (*r == '-') {
337 r++;
338 sign = -1;
341 q = r;
343 while (lib_isnumchar(*q))
344 q++; /* find end of number */
346 len = q-r;
347 if (!len) {
348 /* Not numeric */
349 *error = true;
350 return 0;
354 * Handle radix formats:
356 * 0<radix-letter><string>
357 * $<string> (hexadecimal)
358 * <string><radix-letter>
360 pradix = sradix = 0;
361 plen = slen = 0;
363 if (len > 2 && *r == '0' && (pradix = radix_letter(r[1])) != 0)
364 plen = 2;
365 else if (len > 1 && *r == '$')
366 pradix = 16, plen = 1;
368 if (len > 1 && (sradix = radix_letter(q[-1])) != 0)
369 slen = 1;
371 if (pradix > sradix) {
372 radix = pradix;
373 r += plen;
374 } else if (sradix > pradix) {
375 radix = sradix;
376 q -= slen;
377 } else {
378 /* Either decimal, or invalid -- if invalid, we'll trip up
379 further down. */
380 radix = 10;
384 * `checklimit' must be 2**64 / radix. We can't do that in
385 * 64-bit arithmetic, which we're (probably) using, so we
386 * cheat: since we know that all radices we use are even, we
387 * can divide 2**63 by radix/2 instead.
389 checklimit = UINT64_C(0x8000000000000000) / (radix >> 1);
392 * Calculate the highest allowable value for the last digit of a
393 * 64-bit constant... in radix 10, it is 6, otherwise it is 0
395 last = (radix == 10 ? 6 : 0);
397 result = 0;
398 while (*r && r < q) {
399 if (*r != '_') {
400 if (*r < '0' || (*r > '9' && *r < 'A')
401 || (digit = numvalue(*r)) >= radix) {
402 *error = true;
403 return 0;
405 if (result > checklimit ||
406 (result == checklimit && digit >= last)) {
407 warn = true;
410 result = radix * result + digit;
412 r++;
415 if (warn)
416 nasm_error(ERR_WARNING | ERR_PASS1 | ERR_WARN_NOV,
417 "numeric constant %s does not fit in 64 bits",
418 str);
420 return result * sign;
423 int64_t readstrnum(char *str, int length, bool *warn)
425 int64_t charconst = 0;
426 int i;
428 *warn = false;
430 str += length;
431 if (globalbits == 64) {
432 for (i = 0; i < length; i++) {
433 if (charconst & UINT64_C(0xFF00000000000000))
434 *warn = true;
435 charconst = (charconst << 8) + (uint8_t)*--str;
437 } else {
438 for (i = 0; i < length; i++) {
439 if (charconst & 0xFF000000UL)
440 *warn = true;
441 charconst = (charconst << 8) + (uint8_t)*--str;
444 return charconst;
447 static int32_t next_seg;
449 void seg_init(void)
451 next_seg = 0;
454 int32_t seg_alloc(void)
456 return (next_seg += 2) - 2;
459 #ifdef WORDS_LITTLEENDIAN
461 void fwriteint16_t(uint16_t data, FILE * fp)
463 fwrite(&data, 1, 2, fp);
466 void fwriteint32_t(uint32_t data, FILE * fp)
468 fwrite(&data, 1, 4, fp);
471 void fwriteint64_t(uint64_t data, FILE * fp)
473 fwrite(&data, 1, 8, fp);
476 void fwriteaddr(uint64_t data, int size, FILE * fp)
478 fwrite(&data, 1, size, fp);
481 #else /* not WORDS_LITTLEENDIAN */
483 void fwriteint16_t(uint16_t data, FILE * fp)
485 char buffer[2], *p = buffer;
486 WRITESHORT(p, data);
487 fwrite(buffer, 1, 2, fp);
490 void fwriteint32_t(uint32_t data, FILE * fp)
492 char buffer[4], *p = buffer;
493 WRITELONG(p, data);
494 fwrite(buffer, 1, 4, fp);
497 void fwriteint64_t(uint64_t data, FILE * fp)
499 char buffer[8], *p = buffer;
500 WRITEDLONG(p, data);
501 fwrite(buffer, 1, 8, fp);
504 void fwriteaddr(uint64_t data, int size, FILE * fp)
506 char buffer[8], *p = buffer;
507 WRITEADDR(p, data, size);
508 fwrite(buffer, 1, size, fp);
511 #endif
513 size_t fwritezero(size_t bytes, FILE *fp)
515 size_t count = 0;
516 size_t blksize;
517 size_t rv;
519 while (bytes) {
520 blksize = (bytes < ZERO_BUF_SIZE) ? bytes : ZERO_BUF_SIZE;
522 rv = fwrite(zero_buffer, 1, blksize, fp);
523 if (!rv)
524 break;
526 count += rv;
527 bytes -= rv;
530 return count;
533 void standard_extension(char *inname, char *outname, char *extension)
535 char *p, *q;
537 if (*outname) /* file name already exists, */
538 return; /* so do nothing */
539 q = inname;
540 p = outname;
541 while (*q)
542 *p++ = *q++; /* copy, and find end of string */
543 *p = '\0'; /* terminate it */
544 while (p > outname && *--p != '.') ; /* find final period (or whatever) */
545 if (*p != '.')
546 while (*p)
547 p++; /* go back to end if none found */
548 if (!strcmp(p, extension)) { /* is the extension already there? */
549 if (*extension)
550 nasm_error(ERR_WARNING | ERR_NOFILE,
551 "file name already ends in `%s': "
552 "output will be in `nasm.out'", extension);
553 else
554 nasm_error(ERR_WARNING | ERR_NOFILE,
555 "file name already has no extension: "
556 "output will be in `nasm.out'");
557 strcpy(outname, "nasm.out");
558 } else
559 strcpy(p, extension);
563 * Common list of prefix names
565 static const char *prefix_names[] = {
566 "a16", "a32", "a64", "asp", "lock", "o16", "o32", "o64", "osp",
567 "rep", "repe", "repne", "repnz", "repz", "times", "wait"
570 const char *prefix_name(int token)
572 unsigned int prefix = token-PREFIX_ENUM_START;
573 if (prefix > elements(prefix_names))
574 return NULL;
576 return prefix_names[prefix];
580 * Binary search.
582 int bsi(const char *string, const char **array, int size)
584 int i = -1, j = size; /* always, i < index < j */
585 while (j - i >= 2) {
586 int k = (i + j) / 2;
587 int l = strcmp(string, array[k]);
588 if (l < 0) /* it's in the first half */
589 j = k;
590 else if (l > 0) /* it's in the second half */
591 i = k;
592 else /* we've got it :) */
593 return k;
595 return -1; /* we haven't got it :( */
598 int bsii(const char *string, const char **array, int size)
600 int i = -1, j = size; /* always, i < index < j */
601 while (j - i >= 2) {
602 int k = (i + j) / 2;
603 int l = nasm_stricmp(string, array[k]);
604 if (l < 0) /* it's in the first half */
605 j = k;
606 else if (l > 0) /* it's in the second half */
607 i = k;
608 else /* we've got it :) */
609 return k;
611 return -1; /* we haven't got it :( */
614 static char *file_name = NULL;
615 static int32_t line_number = 0;
617 char *src_set_fname(char *newname)
619 char *oldname = file_name;
620 file_name = newname;
621 return oldname;
624 int32_t src_set_linnum(int32_t newline)
626 int32_t oldline = line_number;
627 line_number = newline;
628 return oldline;
631 int32_t src_get_linnum(void)
633 return line_number;
636 int src_get(int32_t *xline, char **xname)
638 if (!file_name || !*xname || strcmp(*xname, file_name)) {
639 nasm_free(*xname);
640 *xname = file_name ? nasm_strdup(file_name) : NULL;
641 *xline = line_number;
642 return -2;
644 if (*xline != line_number) {
645 int32_t tmp = line_number - *xline;
646 *xline = line_number;
647 return tmp;
649 return 0;
652 char *nasm_strcat(const char *one, const char *two)
654 char *rslt;
655 int l1 = strlen(one);
656 rslt = nasm_malloc(l1 + strlen(two) + 1);
657 strcpy(rslt, one);
658 strcpy(rslt + l1, two);
659 return rslt;
662 /* skip leading spaces */
663 char *nasm_skip_spaces(const char *p)
665 if (p)
666 while (*p && nasm_isspace(*p))
667 p++;
668 return (char *)p;
671 /* skip leading non-spaces */
672 char *nasm_skip_word(const char *p)
674 if (p)
675 while (*p && !nasm_isspace(*p))
676 p++;
677 return (char *)p;
680 /* zap leading spaces with zero */
681 char *nasm_zap_spaces_fwd(char *p)
683 if (p)
684 while (*p && nasm_isspace(*p))
685 *p++ = 0x0;
686 return p;
689 /* zap spaces with zero in reverse order */
690 char *nasm_zap_spaces_rev(char *p)
692 if (p)
693 while (*p && nasm_isspace(*p))
694 *p-- = 0x0;
695 return p;
698 /* zap leading and trailing spaces */
699 char *nasm_trim_spaces(char *p)
701 p = nasm_zap_spaces_fwd(p);
702 nasm_zap_spaces_fwd(nasm_skip_word(p));
704 return p;
708 * extract option and value from a string formatted as "opt = val"
709 * and return pointer to the next string or NULL on empty string
710 * passed or if nothing left for handling
712 char *nasm_opt_val(char *p, char **opt, char **val)
714 char *q, *next;
716 p = nasm_skip_spaces(p);
717 if (!p || (p && !*p))
718 return NULL;
720 q = strchr(p, '=');
721 if (q) {
722 *q++ = '\0';
723 next = nasm_skip_spaces(nasm_skip_word(nasm_skip_spaces(q)));
724 } else
725 next = nasm_skip_spaces(nasm_skip_word(nasm_skip_spaces(p)));
727 *opt = nasm_trim_spaces(p);
728 *val = nasm_trim_spaces(q);
730 return next;
734 * initialized data bytes length from opcode
736 int idata_bytes(int opcode)
738 int ret;
739 switch (opcode) {
740 case I_DB:
741 ret = 1;
742 break;
743 case I_DW:
744 ret = 2;
745 break;
746 case I_DD:
747 ret = 4;
748 break;
749 case I_DQ:
750 ret = 8;
751 break;
752 case I_DT:
753 ret = 10;
754 break;
755 case I_DO:
756 ret = 16;
757 break;
758 case I_DY:
759 ret = 32;
760 break;
761 case I_none:
762 ret = -1;
763 break;
764 default:
765 ret = 0;
766 break;
768 return ret;