Add copyright headers to macro files
[nasm.git] / nasmlib.c
blobfda0c7a5ff9afad101ae35872f7744a69b84944b
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.
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.
14 * Patches submitted to this file are required to be dual licensed
15 * under the LGPL 2.1+ and the 2-clause BSD license:
17 * Copyright 1996-2009 the NASM Authors - All rights reserved.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following
21 * conditions are met:
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.
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.
44 * ----------------------------------------------------------------------- */
47 * nasmlib.c library routines for the Netwide Assembler
50 #include "compiler.h"
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <ctype.h>
56 #include <inttypes.h>
58 #include "nasm.h"
59 #include "nasmlib.h"
60 #include "insns.h"
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 */
65 #ifdef LOGALLOC
66 static FILE *logfp;
67 #endif
69 /* Uninitialized -> all zero by C spec */
70 const uint8_t zero_buffer[ZERO_BUF_SIZE];
73 * Prepare a table of tolower() results. This avoids function calls
74 * on some platforms.
77 unsigned char nasm_tolower_tab[256];
79 void tolower_init(void)
81 int i;
83 for (i = 0; i < 256; i++)
84 nasm_tolower_tab[i] = tolower(i);
87 void nasm_set_malloc_error(efunc error)
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
97 #ifdef LOGALLOC
98 void *nasm_malloc_log(char *file, int line, size_t size)
99 #else
100 void *nasm_malloc(size_t size)
101 #endif
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;
114 #ifdef LOGALLOC
115 void *nasm_zalloc_log(char *file, int line, size_t size)
116 #else
117 void *nasm_zalloc(size_t size)
118 #endif
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;
131 #ifdef LOGALLOC
132 void *nasm_realloc_log(char *file, int line, void *q, size_t size)
133 #else
134 void *nasm_realloc(void *q, size_t size)
135 #endif
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;
151 #ifdef LOGALLOC
152 void nasm_free_log(char *file, int line, void *q)
153 #else
154 void nasm_free(void *q)
155 #endif
157 if (q) {
158 #ifdef LOGALLOC
159 fprintf(logfp, "%s %d free(%p)\n", file, line, q);
160 #endif
161 free(q);
165 #ifdef LOGALLOC
166 char *nasm_strdup_log(char *file, int line, const char *s)
167 #else
168 char *nasm_strdup(const char *s)
169 #endif
171 char *p;
172 int size = strlen(s) + 1;
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;
186 #ifdef LOGALLOC
187 char *nasm_strndup_log(char *file, int line, char *s, size_t len)
188 #else
189 char *nasm_strndup(char *s, size_t len)
190 #endif
192 char *p;
193 int size = len + 1;
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;
208 #ifndef nasm_stricmp
209 int nasm_stricmp(const char *s1, const char *s2)
211 unsigned char c1, c2;
212 int d;
214 while (1) {
215 c1 = nasm_tolower(*s1++);
216 c2 = nasm_tolower(*s2++);
217 d = c1-c2;
219 if (d)
220 return d;
221 if (!c1)
222 break;
224 return 0;
226 #endif
228 #ifndef nasm_strnicmp
229 int nasm_strnicmp(const char *s1, const char *s2, size_t n)
231 unsigned char c1, c2;
232 int d;
234 while (n--) {
235 c1 = nasm_tolower(*s1++);
236 c2 = nasm_tolower(*s2++);
237 d = c1-c2;
239 if (d)
240 return d;
241 if (!c1)
242 break;
244 return 0;
246 #endif
248 int nasm_memicmp(const char *s1, const char *s2, size_t n)
250 unsigned char c1, c2;
251 int d;
253 while (n--) {
254 c1 = nasm_tolower(*s1++);
255 c2 = nasm_tolower(*s2++);
256 d = c1-c2;
257 if (d)
258 return d;
260 return 0;
263 #ifndef nasm_strsep
264 char *nasm_strsep(char **stringp, const char *delim)
266 char *s = *stringp;
267 char *e;
269 if (!s)
270 return NULL;
272 e = strpbrk(s, delim);
273 if (e)
274 *e++ = '\0';
276 *stringp = e;
277 return s;
279 #endif
282 #define lib_isnumchar(c) (nasm_isalnum(c) || (c) == '$' || (c) == '_')
283 #define numvalue(c) ((c)>='a' ? (c)-'a'+10 : (c)>='A' ? (c)-'A'+10 : (c)-'0')
285 static int radix_letter(char c)
287 switch (c) {
288 case 'b': case 'B':
289 case 'y': case 'Y':
290 return 2; /* Binary */
291 case 'o': case 'O':
292 case 'q': case 'Q':
293 return 8; /* Octal */
294 case 'h': case 'H':
295 case 'x': case 'X':
296 return 16; /* Hexadecimal */
297 case 'd': case 'D':
298 case 't': case 'T':
299 return 10; /* Decimal */
300 default:
301 return 0; /* Not a known radix letter */
305 int64_t readnum(char *str, bool *error)
307 char *r = str, *q;
308 int32_t pradix, sradix, radix;
309 int plen, slen, len;
310 uint64_t result, checklimit;
311 int digit, last;
312 bool warn = false;
313 int sign = 1;
315 *error = false;
317 while (nasm_isspace(*r))
318 r++; /* find start of number */
321 * If the number came from make_tok_num (as a result of an %assign), it
322 * might have a '-' built into it (rather than in a preceeding token).
324 if (*r == '-') {
325 r++;
326 sign = -1;
329 q = r;
331 while (lib_isnumchar(*q))
332 q++; /* find end of number */
334 len = q-r;
335 if (!len) {
336 /* Not numeric */
337 *error = true;
338 return 0;
342 * Handle radix formats:
344 * 0<radix-letter><string>
345 * $<string> (hexadecimal)
346 * <string><radix-letter>
348 pradix = sradix = 0;
349 plen = slen = 0;
351 if (len > 2 && *r == '0' && (pradix = radix_letter(r[1])) != 0)
352 plen = 2;
353 else if (len > 1 && *r == '$')
354 pradix = 16, plen = 1;
356 if (len > 1 && (sradix = radix_letter(q[-1])) != 0)
357 slen = 1;
359 if (pradix > sradix) {
360 radix = pradix;
361 r += plen;
362 } else if (sradix > pradix) {
363 radix = sradix;
364 q -= slen;
365 } else {
366 /* Either decimal, or invalid -- if invalid, we'll trip up
367 further down. */
368 radix = 10;
372 * `checklimit' must be 2**64 / radix. We can't do that in
373 * 64-bit arithmetic, which we're (probably) using, so we
374 * cheat: since we know that all radices we use are even, we
375 * can divide 2**63 by radix/2 instead.
377 checklimit = 0x8000000000000000ULL / (radix >> 1);
380 * Calculate the highest allowable value for the last digit of a
381 * 64-bit constant... in radix 10, it is 6, otherwise it is 0
383 last = (radix == 10 ? 6 : 0);
385 result = 0;
386 while (*r && r < q) {
387 if (*r != '_') {
388 if (*r < '0' || (*r > '9' && *r < 'A')
389 || (digit = numvalue(*r)) >= radix) {
390 *error = true;
391 return 0;
393 if (result > checklimit ||
394 (result == checklimit && digit >= last)) {
395 warn = true;
398 result = radix * result + digit;
400 r++;
403 if (warn)
404 nasm_malloc_error(ERR_WARNING | ERR_PASS1 | ERR_WARN_NOV,
405 "numeric constant %s does not fit in 64 bits",
406 str);
408 return result * sign;
411 int64_t readstrnum(char *str, int length, bool *warn)
413 int64_t charconst = 0;
414 int i;
416 *warn = false;
418 str += length;
419 if (globalbits == 64) {
420 for (i = 0; i < length; i++) {
421 if (charconst & 0xFF00000000000000ULL)
422 *warn = true;
423 charconst = (charconst << 8) + (uint8_t)*--str;
425 } else {
426 for (i = 0; i < length; i++) {
427 if (charconst & 0xFF000000UL)
428 *warn = true;
429 charconst = (charconst << 8) + (uint8_t)*--str;
432 return charconst;
435 static int32_t next_seg;
437 void seg_init(void)
439 next_seg = 0;
442 int32_t seg_alloc(void)
444 return (next_seg += 2) - 2;
447 #ifdef WORDS_LITTLEENDIAN
449 void fwriteint16_t(uint16_t data, FILE * fp)
451 fwrite(&data, 1, 2, fp);
454 void fwriteint32_t(uint32_t data, FILE * fp)
456 fwrite(&data, 1, 4, fp);
459 void fwriteint64_t(uint64_t data, FILE * fp)
461 fwrite(&data, 1, 8, fp);
464 void fwriteaddr(uint64_t data, int size, FILE * fp)
466 fwrite(&data, 1, size, fp);
469 #else /* not WORDS_LITTLEENDIAN */
471 void fwriteint16_t(uint16_t data, FILE * fp)
473 char buffer[2], *p = buffer;
474 WRITESHORT(p, data);
475 fwrite(buffer, 1, 2, fp);
478 void fwriteint32_t(uint32_t data, FILE * fp)
480 char buffer[4], *p = buffer;
481 WRITELONG(p, data);
482 fwrite(buffer, 1, 4, fp);
485 void fwriteint64_t(uint64_t data, FILE * fp)
487 char buffer[8], *p = buffer;
488 WRITEDLONG(p, data);
489 fwrite(buffer, 1, 8, fp);
492 void fwriteaddr(uint64_t data, int size, FILE * fp)
494 char buffer[8], *p = buffer;
495 WRITEADDR(p, data, size);
496 fwrite(buffer, 1, size, fp);
499 #endif
501 size_t fwritezero(size_t bytes, FILE *fp)
503 size_t count = 0;
504 size_t blksize;
505 size_t rv;
507 while (bytes) {
508 blksize = (bytes < ZERO_BUF_SIZE) ? bytes : ZERO_BUF_SIZE;
510 rv = fwrite(zero_buffer, 1, blksize, fp);
511 if (!rv)
512 break;
514 count += rv;
515 bytes -= rv;
518 return count;
521 void standard_extension(char *inname, char *outname, char *extension,
522 efunc error)
524 char *p, *q;
526 if (*outname) /* file name already exists, */
527 return; /* so do nothing */
528 q = inname;
529 p = outname;
530 while (*q)
531 *p++ = *q++; /* copy, and find end of string */
532 *p = '\0'; /* terminate it */
533 while (p > outname && *--p != '.') ; /* find final period (or whatever) */
534 if (*p != '.')
535 while (*p)
536 p++; /* go back to end if none found */
537 if (!strcmp(p, extension)) { /* is the extension already there? */
538 if (*extension)
539 error(ERR_WARNING | ERR_NOFILE,
540 "file name already ends in `%s': "
541 "output will be in `nasm.out'", extension);
542 else
543 error(ERR_WARNING | ERR_NOFILE,
544 "file name already has no extension: "
545 "output will be in `nasm.out'");
546 strcpy(outname, "nasm.out");
547 } else
548 strcpy(p, extension);
552 * Common list of prefix names
554 static const char *prefix_names[] = {
555 "a16", "a32", "a64", "asp", "lock", "o16", "o32", "o64", "osp",
556 "rep", "repe", "repne", "repnz", "repz", "times", "wait"
559 const char *prefix_name(int token)
561 unsigned int prefix = token-PREFIX_ENUM_START;
562 if (prefix > elements(prefix_names))
563 return NULL;
565 return prefix_names[prefix];
569 * Binary search.
571 int bsi(const char *string, const char **array, int size)
573 int i = -1, j = size; /* always, i < index < j */
574 while (j - i >= 2) {
575 int k = (i + j) / 2;
576 int l = strcmp(string, array[k]);
577 if (l < 0) /* it's in the first half */
578 j = k;
579 else if (l > 0) /* it's in the second half */
580 i = k;
581 else /* we've got it :) */
582 return k;
584 return -1; /* we haven't got it :( */
587 int bsii(const char *string, const char **array, int size)
589 int i = -1, j = size; /* always, i < index < j */
590 while (j - i >= 2) {
591 int k = (i + j) / 2;
592 int l = nasm_stricmp(string, array[k]);
593 if (l < 0) /* it's in the first half */
594 j = k;
595 else if (l > 0) /* it's in the second half */
596 i = k;
597 else /* we've got it :) */
598 return k;
600 return -1; /* we haven't got it :( */
603 static char *file_name = NULL;
604 static int32_t line_number = 0;
606 char *src_set_fname(char *newname)
608 char *oldname = file_name;
609 file_name = newname;
610 return oldname;
613 int32_t src_set_linnum(int32_t newline)
615 int32_t oldline = line_number;
616 line_number = newline;
617 return oldline;
620 int32_t src_get_linnum(void)
622 return line_number;
625 int src_get(int32_t *xline, char **xname)
627 if (!file_name || !*xname || strcmp(*xname, file_name)) {
628 nasm_free(*xname);
629 *xname = file_name ? nasm_strdup(file_name) : NULL;
630 *xline = line_number;
631 return -2;
633 if (*xline != line_number) {
634 int32_t tmp = line_number - *xline;
635 *xline = line_number;
636 return tmp;
638 return 0;
641 char *nasm_strcat(const char *one, const char *two)
643 char *rslt;
644 int l1 = strlen(one);
645 rslt = nasm_malloc(l1 + strlen(two) + 1);
646 strcpy(rslt, one);
647 strcpy(rslt + l1, two);
648 return rslt;