nasmlib: added string replace (strrep) utility function
[nasm/nasm.git] / nasmlib.c
blob538223f8128dfecdc5ad18e6a54b4ad846a01a11
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", logfp);
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
293 char *nasm_strrep(const char *str, const char *sub, char *lin, bool casesense)
295 char *outline = lin;
296 char *temp1 = NULL;
297 char *temp2 = NULL;
298 char *l, *lp, *lt, *ls;
299 int count = 0;
300 int str_len, sub_len, lin_len;
301 int i, c;
303 str_len = strlen(str);
304 sub_len = strlen(sub);
305 lin_len = strlen(lin);
307 if ((str_len > 0) && (lin_len > 0)) {
308 if (casesense == false) {
309 l = nasm_strdup(lin);
310 for (i = 0; i < lin_len; i++) {
311 l[i] = (char)nasm_tolower_tab[(int)l[i]];
313 ls = nasm_strdup(str);
314 for (i = 0; i < str_len; i++) {
315 ls[i] = (char)nasm_tolower_tab[(int)ls[i]];
317 temp1 = l;
318 temp2 = ls;
319 } else {
320 l = lin;
321 ls = (char *)str;
324 lt = l;
326 do {
327 l = strstr(l, ls);
328 if (l != NULL) {
329 count ++;
330 l += str_len;
332 } while (l != NULL);
334 if (count > 0) {
335 i = (lin_len - (count * str_len));
336 i += (count * sub_len);
337 outline = nasm_zalloc(i);
339 l = lt;
341 for (i = 0; i < count; i ++) {
342 lp = l;
343 l = strstr(l, ls);
344 c = (lp - l);
345 if (c > 0) {
346 strncat(outline, lt, c);
348 strncat(outline, sub, sub_len);
349 l += str_len;
350 lt += str_len;
353 c = (l - lin);
354 if (c < lin_len) {
355 strcat(outline, lt);
358 if (temp2 != NULL) {
359 nasm_free(temp2);
362 if (temp1 != NULL) {
363 nasm_free(temp1);
366 nasm_free(lin);
370 return outline;
374 #define lib_isnumchar(c) (nasm_isalnum(c) || (c) == '$' || (c) == '_')
375 #define numvalue(c) ((c)>='a' ? (c)-'a'+10 : (c)>='A' ? (c)-'A'+10 : (c)-'0')
377 static int radix_letter(char c)
379 switch (c) {
380 case 'b': case 'B':
381 case 'y': case 'Y':
382 return 2; /* Binary */
383 case 'o': case 'O':
384 case 'q': case 'Q':
385 return 8; /* Octal */
386 case 'h': case 'H':
387 case 'x': case 'X':
388 return 16; /* Hexadecimal */
389 case 'd': case 'D':
390 case 't': case 'T':
391 return 10; /* Decimal */
392 default:
393 return 0; /* Not a known radix letter */
397 int64_t readnum(char *str, bool *error)
399 char *r = str, *q;
400 int32_t pradix, sradix, radix;
401 int plen, slen, len;
402 uint64_t result, checklimit;
403 int digit, last;
404 bool warn = false;
405 int sign = 1;
407 *error = false;
409 while (nasm_isspace(*r))
410 r++; /* find start of number */
413 * If the number came from make_tok_num (as a result of an %assign), it
414 * might have a '-' built into it (rather than in a preceeding token).
416 if (*r == '-') {
417 r++;
418 sign = -1;
421 q = r;
423 while (lib_isnumchar(*q))
424 q++; /* find end of number */
426 len = q-r;
427 if (!len) {
428 /* Not numeric */
429 *error = true;
430 return 0;
434 * Handle radix formats:
436 * 0<radix-letter><string>
437 * $<string> (hexadecimal)
438 * <string><radix-letter>
440 pradix = sradix = 0;
441 plen = slen = 0;
443 if (len > 2 && *r == '0' && (pradix = radix_letter(r[1])) != 0)
444 plen = 2;
445 else if (len > 1 && *r == '$')
446 pradix = 16, plen = 1;
448 if (len > 1 && (sradix = radix_letter(q[-1])) != 0)
449 slen = 1;
451 if (pradix > sradix) {
452 radix = pradix;
453 r += plen;
454 } else if (sradix > pradix) {
455 radix = sradix;
456 q -= slen;
457 } else {
458 /* Either decimal, or invalid -- if invalid, we'll trip up
459 further down. */
460 radix = 10;
464 * `checklimit' must be 2**64 / radix. We can't do that in
465 * 64-bit arithmetic, which we're (probably) using, so we
466 * cheat: since we know that all radices we use are even, we
467 * can divide 2**63 by radix/2 instead.
469 checklimit = UINT64_C(0x8000000000000000) / (radix >> 1);
472 * Calculate the highest allowable value for the last digit of a
473 * 64-bit constant... in radix 10, it is 6, otherwise it is 0
475 last = (radix == 10 ? 6 : 0);
477 result = 0;
478 while (*r && r < q) {
479 if (*r != '_') {
480 if (*r < '0' || (*r > '9' && *r < 'A')
481 || (digit = numvalue(*r)) >= radix) {
482 *error = true;
483 return 0;
485 if (result > checklimit ||
486 (result == checklimit && digit >= last)) {
487 warn = true;
490 result = radix * result + digit;
492 r++;
495 if (warn)
496 nasm_error(ERR_WARNING | ERR_PASS1 | ERR_WARN_NOV,
497 "numeric constant %s does not fit in 64 bits",
498 str);
500 return result * sign;
503 int64_t readstrnum(char *str, int length, bool *warn)
505 int64_t charconst = 0;
506 int i;
508 *warn = false;
510 str += length;
511 if (globalbits == 64) {
512 for (i = 0; i < length; i++) {
513 if (charconst & UINT64_C(0xFF00000000000000))
514 *warn = true;
515 charconst = (charconst << 8) + (uint8_t)*--str;
517 } else {
518 for (i = 0; i < length; i++) {
519 if (charconst & 0xFF000000UL)
520 *warn = true;
521 charconst = (charconst << 8) + (uint8_t)*--str;
524 return charconst;
527 static int32_t next_seg;
529 void seg_init(void)
531 next_seg = 0;
534 int32_t seg_alloc(void)
536 return (next_seg += 2) - 2;
539 #ifdef WORDS_LITTLEENDIAN
541 void fwriteint16_t(uint16_t data, FILE * fp)
543 fwrite(&data, 1, 2, fp);
546 void fwriteint32_t(uint32_t data, FILE * fp)
548 fwrite(&data, 1, 4, fp);
551 void fwriteint64_t(uint64_t data, FILE * fp)
553 fwrite(&data, 1, 8, fp);
556 void fwriteaddr(uint64_t data, int size, FILE * fp)
558 fwrite(&data, 1, size, fp);
561 #else /* not WORDS_LITTLEENDIAN */
563 void fwriteint16_t(uint16_t data, FILE * fp)
565 char buffer[2], *p = buffer;
566 WRITESHORT(p, data);
567 fwrite(buffer, 1, 2, fp);
570 void fwriteint32_t(uint32_t data, FILE * fp)
572 char buffer[4], *p = buffer;
573 WRITELONG(p, data);
574 fwrite(buffer, 1, 4, fp);
577 void fwriteint64_t(uint64_t data, FILE * fp)
579 char buffer[8], *p = buffer;
580 WRITEDLONG(p, data);
581 fwrite(buffer, 1, 8, fp);
584 void fwriteaddr(uint64_t data, int size, FILE * fp)
586 char buffer[8], *p = buffer;
587 WRITEADDR(p, data, size);
588 fwrite(buffer, 1, size, fp);
591 #endif
593 size_t fwritezero(size_t bytes, FILE *fp)
595 size_t count = 0;
596 size_t blksize;
597 size_t rv;
599 while (bytes) {
600 blksize = (bytes < ZERO_BUF_SIZE) ? bytes : ZERO_BUF_SIZE;
602 rv = fwrite(zero_buffer, 1, blksize, fp);
603 if (!rv)
604 break;
606 count += rv;
607 bytes -= rv;
610 return count;
613 void standard_extension(char *inname, char *outname, char *extension)
615 char *p, *q;
617 if (*outname) /* file name already exists, */
618 return; /* so do nothing */
619 q = inname;
620 p = outname;
621 while (*q)
622 *p++ = *q++; /* copy, and find end of string */
623 *p = '\0'; /* terminate it */
624 while (p > outname && *--p != '.') ; /* find final period (or whatever) */
625 if (*p != '.')
626 while (*p)
627 p++; /* go back to end if none found */
628 if (!strcmp(p, extension)) { /* is the extension already there? */
629 if (*extension)
630 nasm_error(ERR_WARNING | ERR_NOFILE,
631 "file name already ends in `%s': "
632 "output will be in `nasm.out'", extension);
633 else
634 nasm_error(ERR_WARNING | ERR_NOFILE,
635 "file name already has no extension: "
636 "output will be in `nasm.out'");
637 strcpy(outname, "nasm.out");
638 } else
639 strcpy(p, extension);
643 * Common list of prefix names
645 static const char *prefix_names[] = {
646 "a16", "a32", "a64", "asp", "lock", "o16", "o32", "o64", "osp",
647 "rep", "repe", "repne", "repnz", "repz", "times", "wait"
650 const char *prefix_name(int token)
652 unsigned int prefix = token-PREFIX_ENUM_START;
653 if (prefix >= ARRAY_SIZE(prefix_names))
654 return NULL;
656 return prefix_names[prefix];
660 * Binary search.
662 int bsi(const char *string, const char **array, int size)
664 int i = -1, j = size; /* always, i < index < j */
665 while (j - i >= 2) {
666 int k = (i + j) / 2;
667 int l = strcmp(string, array[k]);
668 if (l < 0) /* it's in the first half */
669 j = k;
670 else if (l > 0) /* it's in the second half */
671 i = k;
672 else /* we've got it :) */
673 return k;
675 return -1; /* we haven't got it :( */
678 int bsii(const char *string, const char **array, int size)
680 int i = -1, j = size; /* always, i < index < j */
681 while (j - i >= 2) {
682 int k = (i + j) / 2;
683 int l = nasm_stricmp(string, array[k]);
684 if (l < 0) /* it's in the first half */
685 j = k;
686 else if (l > 0) /* it's in the second half */
687 i = k;
688 else /* we've got it :) */
689 return k;
691 return -1; /* we haven't got it :( */
694 static char *file_name = NULL;
695 static int32_t line_number = 0;
697 char *src_set_fname(char *newname)
699 char *oldname = file_name;
700 file_name = newname;
701 return oldname;
704 int32_t src_set_linnum(int32_t newline)
706 int32_t oldline = line_number;
707 line_number = newline;
708 return oldline;
711 int32_t src_get_linnum(void)
713 return line_number;
716 int src_get(int32_t *xline, char **xname)
718 if (!file_name || !*xname || strcmp(*xname, file_name)) {
719 nasm_free(*xname);
720 *xname = file_name ? nasm_strdup(file_name) : NULL;
721 *xline = line_number;
722 return -2;
724 if (*xline != line_number) {
725 int32_t tmp = line_number - *xline;
726 *xline = line_number;
727 return tmp;
729 return 0;
732 char *nasm_strcat(const char *one, const char *two)
734 char *rslt;
735 int l1 = strlen(one);
736 rslt = nasm_malloc(l1 + strlen(two) + 1);
737 strcpy(rslt, one);
738 strcpy(rslt + l1, two);
739 return rslt;
742 /* skip leading spaces */
743 char *nasm_skip_spaces(const char *p)
745 if (p)
746 while (*p && nasm_isspace(*p))
747 p++;
748 return (char *)p;
751 /* skip leading non-spaces */
752 char *nasm_skip_word(const char *p)
754 if (p)
755 while (*p && !nasm_isspace(*p))
756 p++;
757 return (char *)p;
760 /* zap leading spaces with zero */
761 char *nasm_zap_spaces_fwd(char *p)
763 if (p)
764 while (*p && nasm_isspace(*p))
765 *p++ = 0x0;
766 return p;
769 /* zap spaces with zero in reverse order */
770 char *nasm_zap_spaces_rev(char *p)
772 if (p)
773 while (*p && nasm_isspace(*p))
774 *p-- = 0x0;
775 return p;
778 /* zap leading and trailing spaces */
779 char *nasm_trim_spaces(char *p)
781 p = nasm_zap_spaces_fwd(p);
782 nasm_zap_spaces_fwd(nasm_skip_word(p));
784 return p;
788 * return the word extracted from a stream
789 * or NULL if nothing left
791 char *nasm_get_word(char *p, char **tail)
793 char *word = nasm_skip_spaces(p);
794 char *next = nasm_skip_word(word);
796 if (word && *word) {
797 if (*next)
798 *next++ = '\0';
799 } else
800 word = next = NULL;
802 /* NOTE: the tail may start with spaces */
803 *tail = next;
805 return word;
809 * Extract "opt=val" values from the stream and
810 * returns "opt"
812 * Exceptions:
813 * 1) If "=val" passed the NULL returned though
814 * you may continue handling the tail via "next"
815 * 2) If "=" passed the NULL is returned and "val"
816 * is set to NULL as well
818 char *nasm_opt_val(char *p, char **val, char **next)
820 char *q, *opt, *nxt;
822 opt = *val = *next = NULL;
824 p = nasm_get_word(p, &nxt);
825 if (!p)
826 return NULL;
828 q = strchr(p, '=');
829 if (q) {
830 if (q == p)
831 p = NULL;
832 *q++='\0';
833 if (*q) {
834 *val = q;
835 } else {
836 q = nasm_get_word(q + 1, &nxt);
837 if (q)
838 *val = q;
840 } else {
841 q = nasm_skip_spaces(nxt);
842 if (q && *q == '=') {
843 q = nasm_get_word(q + 1, &nxt);
844 if (q)
845 *val = q;
849 *next = nxt;
850 return p;
854 * initialized data bytes length from opcode
856 int idata_bytes(int opcode)
858 int ret;
859 switch (opcode) {
860 case I_DB:
861 ret = 1;
862 break;
863 case I_DW:
864 ret = 2;
865 break;
866 case I_DD:
867 ret = 4;
868 break;
869 case I_DQ:
870 ret = 8;
871 break;
872 case I_DT:
873 ret = 10;
874 break;
875 case I_DO:
876 ret = 16;
877 break;
878 case I_DY:
879 ret = 32;
880 break;
881 case I_none:
882 ret = -1;
883 break;
884 default:
885 ret = 0;
886 break;
888 return ret;