outmac64.c: Fix memory clobber bug, clean up memory free
[nasm.git] / nasmlib.c
blob3c26546a970b561c4816941aa2b2afa56d679928
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_panic(int flags, const char *fmt, ...)
88 va_list ap;
90 va_start(ap, fmt);
91 nasm_verror(flags | ERR_PANIC, fmt, ap);
92 abort(); /* We should never get here */
95 void *nasm_malloc(size_t size)
97 void *p = malloc(size);
98 if (!p)
99 nasm_error(ERR_FATAL | ERR_NOFILE, "out of memory");
100 return p;
103 void *nasm_zalloc(size_t size)
105 void *p = calloc(size, 1);
106 if (!p)
107 nasm_error(ERR_FATAL | ERR_NOFILE, "out of memory");
108 return p;
111 void *nasm_realloc(void *q, size_t size)
113 void *p = q ? realloc(q, size) : malloc(size);
114 if (!p)
115 nasm_error(ERR_FATAL | ERR_NOFILE, "out of memory");
116 return p;
119 void nasm_free(void *q)
121 if (q)
122 free(q);
125 char *nasm_strdup(const char *s)
127 char *p;
128 int size = strlen(s) + 1;
130 p = malloc(size);
131 if (!p)
132 nasm_error(ERR_FATAL | ERR_NOFILE, "out of memory");
133 strcpy(p, s);
134 return p;
137 char *nasm_strndup(const char *s, size_t len)
139 char *p;
140 int size = len + 1;
142 p = malloc(size);
143 if (!p)
144 nasm_error(ERR_FATAL | ERR_NOFILE, "out of memory");
145 strncpy(p, s, len);
146 p[len] = '\0';
147 return p;
150 no_return nasm_assert_failed(const char *file, int line, const char *msg)
152 nasm_error(ERR_FATAL, "assertion %s failed at %s:%d", msg, file, line);
153 exit(1);
156 void nasm_write(const void *ptr, size_t size, FILE *f)
158 size_t n = fwrite(ptr, 1, size, f);
159 if (n != size)
160 nasm_error(ERR_FATAL, "unable to write output: %s", strerror(errno));
163 #ifndef nasm_stricmp
164 int nasm_stricmp(const char *s1, const char *s2)
166 unsigned char c1, c2;
167 int d;
169 while (1) {
170 c1 = nasm_tolower(*s1++);
171 c2 = nasm_tolower(*s2++);
172 d = c1-c2;
174 if (d)
175 return d;
176 if (!c1)
177 break;
179 return 0;
181 #endif
183 #ifndef nasm_strnicmp
184 int nasm_strnicmp(const char *s1, const char *s2, size_t n)
186 unsigned char c1, c2;
187 int d;
189 while (n--) {
190 c1 = nasm_tolower(*s1++);
191 c2 = nasm_tolower(*s2++);
192 d = c1-c2;
194 if (d)
195 return d;
196 if (!c1)
197 break;
199 return 0;
201 #endif
203 int nasm_memicmp(const char *s1, const char *s2, size_t n)
205 unsigned char c1, c2;
206 int d;
208 while (n--) {
209 c1 = nasm_tolower(*s1++);
210 c2 = nasm_tolower(*s2++);
211 d = c1-c2;
212 if (d)
213 return d;
215 return 0;
218 #ifndef nasm_strsep
219 char *nasm_strsep(char **stringp, const char *delim)
221 char *s = *stringp;
222 char *e;
224 if (!s)
225 return NULL;
227 e = strpbrk(s, delim);
228 if (e)
229 *e++ = '\0';
231 *stringp = e;
232 return s;
234 #endif
237 #define lib_isnumchar(c) (nasm_isalnum(c) || (c) == '$' || (c) == '_')
239 static int radix_letter(char c)
241 switch (c) {
242 case 'b': case 'B':
243 case 'y': case 'Y':
244 return 2; /* Binary */
245 case 'o': case 'O':
246 case 'q': case 'Q':
247 return 8; /* Octal */
248 case 'h': case 'H':
249 case 'x': case 'X':
250 return 16; /* Hexadecimal */
251 case 'd': case 'D':
252 case 't': case 'T':
253 return 10; /* Decimal */
254 default:
255 return 0; /* Not a known radix letter */
259 int64_t readnum(char *str, bool *error)
261 char *r = str, *q;
262 int32_t pradix, sradix, radix;
263 int plen, slen, len;
264 uint64_t result, checklimit;
265 int digit, last;
266 bool warn = false;
267 int sign = 1;
269 *error = false;
271 while (nasm_isspace(*r))
272 r++; /* find start of number */
275 * If the number came from make_tok_num (as a result of an %assign), it
276 * might have a '-' built into it (rather than in a preceeding token).
278 if (*r == '-') {
279 r++;
280 sign = -1;
283 q = r;
285 while (lib_isnumchar(*q))
286 q++; /* find end of number */
288 len = q-r;
289 if (!len) {
290 /* Not numeric */
291 *error = true;
292 return 0;
296 * Handle radix formats:
298 * 0<radix-letter><string>
299 * $<string> (hexadecimal)
300 * <string><radix-letter>
302 pradix = sradix = 0;
303 plen = slen = 0;
305 if (len > 2 && *r == '0' && (pradix = radix_letter(r[1])) != 0)
306 plen = 2;
307 else if (len > 1 && *r == '$')
308 pradix = 16, plen = 1;
310 if (len > 1 && (sradix = radix_letter(q[-1])) != 0)
311 slen = 1;
313 if (pradix > sradix) {
314 radix = pradix;
315 r += plen;
316 } else if (sradix > pradix) {
317 radix = sradix;
318 q -= slen;
319 } else {
320 /* Either decimal, or invalid -- if invalid, we'll trip up
321 further down. */
322 radix = 10;
326 * `checklimit' must be 2**64 / radix. We can't do that in
327 * 64-bit arithmetic, which we're (probably) using, so we
328 * cheat: since we know that all radices we use are even, we
329 * can divide 2**63 by radix/2 instead.
331 checklimit = UINT64_C(0x8000000000000000) / (radix >> 1);
334 * Calculate the highest allowable value for the last digit of a
335 * 64-bit constant... in radix 10, it is 6, otherwise it is 0
337 last = (radix == 10 ? 6 : 0);
339 result = 0;
340 while (*r && r < q) {
341 if (*r != '_') {
342 if (*r < '0' || (*r > '9' && *r < 'A')
343 || (digit = numvalue(*r)) >= radix) {
344 *error = true;
345 return 0;
347 if (result > checklimit ||
348 (result == checklimit && digit >= last)) {
349 warn = true;
352 result = radix * result + digit;
354 r++;
357 if (warn)
358 nasm_error(ERR_WARNING | ERR_PASS1 | ERR_WARN_NOV,
359 "numeric constant %s does not fit in 64 bits",
360 str);
362 return result * sign;
365 int64_t readstrnum(char *str, int length, bool *warn)
367 int64_t charconst = 0;
368 int i;
370 *warn = false;
372 str += length;
373 if (globalbits == 64) {
374 for (i = 0; i < length; i++) {
375 if (charconst & UINT64_C(0xFF00000000000000))
376 *warn = true;
377 charconst = (charconst << 8) + (uint8_t)*--str;
379 } else {
380 for (i = 0; i < length; i++) {
381 if (charconst & 0xFF000000UL)
382 *warn = true;
383 charconst = (charconst << 8) + (uint8_t)*--str;
386 return charconst;
389 static int32_t next_seg;
391 void seg_init(void)
393 next_seg = 0;
396 int32_t seg_alloc(void)
398 return (next_seg += 2) - 2;
401 #ifdef WORDS_LITTLEENDIAN
403 void fwriteint16_t(uint16_t data, FILE * fp)
405 nasm_write(&data, 2, fp);
408 void fwriteint32_t(uint32_t data, FILE * fp)
410 nasm_write(&data, 4, fp);
413 void fwriteint64_t(uint64_t data, FILE * fp)
415 nasm_write(&data, 8, fp);
418 void fwriteaddr(uint64_t data, int size, FILE * fp)
420 nasm_write(&data, size, fp);
423 #else /* not WORDS_LITTLEENDIAN */
425 void fwriteint16_t(uint16_t data, FILE * fp)
427 char buffer[2], *p = buffer;
428 WRITESHORT(p, data);
429 nasm_write(buffer, 2, fp);
432 void fwriteint32_t(uint32_t data, FILE * fp)
434 char buffer[4], *p = buffer;
435 WRITELONG(p, data);
436 nasm_write(buffer, 4, fp);
439 void fwriteint64_t(uint64_t data, FILE * fp)
441 char buffer[8], *p = buffer;
442 WRITEDLONG(p, data);
443 nasm_write(buffer, 8, fp);
446 void fwriteaddr(uint64_t data, int size, FILE * fp)
448 char buffer[8], *p = buffer;
449 WRITEADDR(p, data, size);
450 nasm_write(buffer, size, fp);
453 #endif
455 void fwritezero(size_t bytes, FILE *fp)
457 size_t blksize;
459 while (bytes) {
460 blksize = (bytes < ZERO_BUF_SIZE) ? bytes : ZERO_BUF_SIZE;
462 nasm_write(zero_buffer, blksize, fp);
463 bytes -= blksize;
467 void standard_extension(char *inname, char *outname, char *extension)
469 char *p, *q;
471 if (*outname) /* file name already exists, */
472 return; /* so do nothing */
473 q = inname;
474 p = outname;
475 while (*q)
476 *p++ = *q++; /* copy, and find end of string */
477 *p = '\0'; /* terminate it */
478 while (p > outname && *--p != '.') ; /* find final period (or whatever) */
479 if (*p != '.')
480 while (*p)
481 p++; /* go back to end if none found */
482 if (!strcmp(p, extension)) { /* is the extension already there? */
483 if (*extension)
484 nasm_error(ERR_WARNING | ERR_NOFILE,
485 "file name already ends in `%s': "
486 "output will be in `nasm.out'", extension);
487 else
488 nasm_error(ERR_WARNING | ERR_NOFILE,
489 "file name already has no extension: "
490 "output will be in `nasm.out'");
491 strcpy(outname, "nasm.out");
492 } else
493 strcpy(p, extension);
497 * Common list of prefix names
499 static const char *prefix_names[] = {
500 "a16", "a32", "a64", "asp", "lock", "o16", "o32", "o64", "osp",
501 "rep", "repe", "repne", "repnz", "repz", "times", "wait",
502 "xacquire", "xrelease", "bnd"
505 const char *prefix_name(int token)
507 unsigned int prefix = token-PREFIX_ENUM_START;
508 if (prefix >= ARRAY_SIZE(prefix_names))
509 return NULL;
511 return prefix_names[prefix];
515 * Binary search.
517 int bsi(const char *string, const char **array, int size)
519 int i = -1, j = size; /* always, i < index < j */
520 while (j - i >= 2) {
521 int k = (i + j) / 2;
522 int l = strcmp(string, array[k]);
523 if (l < 0) /* it's in the first half */
524 j = k;
525 else if (l > 0) /* it's in the second half */
526 i = k;
527 else /* we've got it :) */
528 return k;
530 return -1; /* we haven't got it :( */
533 int bsii(const char *string, const char **array, int size)
535 int i = -1, j = size; /* always, i < index < j */
536 while (j - i >= 2) {
537 int k = (i + j) / 2;
538 int l = nasm_stricmp(string, array[k]);
539 if (l < 0) /* it's in the first half */
540 j = k;
541 else if (l > 0) /* it's in the second half */
542 i = k;
543 else /* we've got it :) */
544 return k;
546 return -1; /* we haven't got it :( */
549 static char *file_name = NULL;
550 static int32_t line_number = 0;
552 char *src_set_fname(char *newname)
554 char *oldname = file_name;
555 file_name = newname;
556 return oldname;
559 int32_t src_set_linnum(int32_t newline)
561 int32_t oldline = line_number;
562 line_number = newline;
563 return oldline;
566 int32_t src_get_linnum(void)
568 return line_number;
571 int src_get(int32_t *xline, char **xname)
573 if (!file_name || !*xname || strcmp(*xname, file_name)) {
574 nasm_free(*xname);
575 *xname = file_name ? nasm_strdup(file_name) : NULL;
576 *xline = line_number;
577 return -2;
579 if (*xline != line_number) {
580 int32_t tmp = line_number - *xline;
581 *xline = line_number;
582 return tmp;
584 return 0;
587 char *nasm_strcat(const char *one, const char *two)
589 char *rslt;
590 int l1 = strlen(one);
591 rslt = nasm_malloc(l1 + strlen(two) + 1);
592 strcpy(rslt, one);
593 strcpy(rslt + l1, two);
594 return rslt;
597 /* skip leading spaces */
598 char *nasm_skip_spaces(const char *p)
600 if (p)
601 while (*p && nasm_isspace(*p))
602 p++;
603 return (char *)p;
606 /* skip leading non-spaces */
607 char *nasm_skip_word(const char *p)
609 if (p)
610 while (*p && !nasm_isspace(*p))
611 p++;
612 return (char *)p;
615 /* zap leading spaces with zero */
616 char *nasm_zap_spaces_fwd(char *p)
618 if (p)
619 while (*p && nasm_isspace(*p))
620 *p++ = 0x0;
621 return p;
624 /* zap spaces with zero in reverse order */
625 char *nasm_zap_spaces_rev(char *p)
627 if (p)
628 while (*p && nasm_isspace(*p))
629 *p-- = 0x0;
630 return p;
633 /* zap leading and trailing spaces */
634 char *nasm_trim_spaces(char *p)
636 p = nasm_zap_spaces_fwd(p);
637 nasm_zap_spaces_fwd(nasm_skip_word(p));
639 return p;
643 * return the word extracted from a stream
644 * or NULL if nothing left
646 char *nasm_get_word(char *p, char **tail)
648 char *word = nasm_skip_spaces(p);
649 char *next = nasm_skip_word(word);
651 if (word && *word) {
652 if (*next)
653 *next++ = '\0';
654 } else
655 word = next = NULL;
657 /* NOTE: the tail may start with spaces */
658 *tail = next;
660 return word;
664 * Extract "opt=val" values from the stream and
665 * returns "opt"
667 * Exceptions:
668 * 1) If "=val" passed the NULL returned though
669 * you may continue handling the tail via "next"
670 * 2) If "=" passed the NULL is returned and "val"
671 * is set to NULL as well
673 char *nasm_opt_val(char *p, char **val, char **next)
675 char *q, *nxt;
677 *val = *next = NULL;
679 p = nasm_get_word(p, &nxt);
680 if (!p)
681 return NULL;
683 q = strchr(p, '=');
684 if (q) {
685 if (q == p)
686 p = NULL;
687 *q++='\0';
688 if (*q) {
689 *val = q;
690 } else {
691 q = nasm_get_word(q + 1, &nxt);
692 if (q)
693 *val = q;
695 } else {
696 q = nasm_skip_spaces(nxt);
697 if (q && *q == '=') {
698 q = nasm_get_word(q + 1, &nxt);
699 if (q)
700 *val = q;
704 *next = nxt;
705 return p;
709 * initialized data bytes length from opcode
711 int idata_bytes(int opcode)
713 switch (opcode) {
714 case I_DB:
715 return 1;
716 case I_DW:
717 return 2;
718 case I_DD:
719 return 4;
720 case I_DQ:
721 return 8;
722 case I_DT:
723 return 10;
724 case I_DO:
725 return 16;
726 case I_DY:
727 return 32;
728 case I_DZ:
729 return 64;
730 case I_none:
731 return -1;
732 default:
733 return 0;