Add Makefile for OpenWatcom (DOS, OS/2 or Win32 output)
[nasm/autotest.git] / preproc.c
blob1ee07ad6bb711d432798a735ca7a35075feb9f03
1 /* -*- mode: c; c-file-style: "bsd" -*- */
2 /* preproc.c macro preprocessor for the Netwide Assembler
4 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
5 * Julian Hall. All rights reserved. The software is
6 * redistributable under the licence given in the file "Licence"
7 * distributed in the NASM archive.
9 * initial version 18/iii/97 by Simon Tatham
12 /* Typical flow of text through preproc
14 * pp_getline gets tokenized lines, either
16 * from a macro expansion
18 * or
19 * {
20 * read_line gets raw text from stdmacpos, or predef, or current input file
21 * tokenize converts to tokens
22 * }
24 * expand_mmac_params is used to expand %1 etc., unless a macro is being
25 * defined or a false conditional is being processed
26 * (%0, %1, %+1, %-1, %%foo
28 * do_directive checks for directives
30 * expand_smacro is used to expand single line macros
32 * expand_mmacro is used to expand multi-line macros
34 * detoken is used to convert the line back to text
37 #include <stdio.h>
38 #include <stdarg.h>
39 #include <stdlib.h>
40 #include <stddef.h>
41 #include <string.h>
42 #include <ctype.h>
43 #include <limits.h>
44 #include <inttypes.h>
46 #include "nasm.h"
47 #include "nasmlib.h"
48 #include "preproc.h"
49 #include "hashtbl.h"
51 typedef struct SMacro SMacro;
52 typedef struct MMacro MMacro;
53 typedef struct Context Context;
54 typedef struct Token Token;
55 typedef struct Blocks Blocks;
56 typedef struct Line Line;
57 typedef struct Include Include;
58 typedef struct Cond Cond;
59 typedef struct IncPath IncPath;
62 * Note on the storage of both SMacro and MMacros: the hash table
63 * indexes them case-insensitively, and we then have to go through a
64 * linked list of potential case aliases (and, for MMacros, parameter
65 * ranges); this is to preserve the matching semantics of the earlier
66 * code. If the number of case aliases for a specific macro is a
67 * performance issue, you may want to reconsider your coding style.
71 * Store the definition of a single-line macro.
73 struct SMacro {
74 SMacro *next;
75 char *name;
76 int casesense;
77 unsigned int nparam;
78 int in_progress;
79 Token *expansion;
83 * Store the definition of a multi-line macro. This is also used to
84 * store the interiors of `%rep...%endrep' blocks, which are
85 * effectively self-re-invoking multi-line macros which simply
86 * don't have a name or bother to appear in the hash tables. %rep
87 * blocks are signified by having a NULL `name' field.
89 * In a MMacro describing a `%rep' block, the `in_progress' field
90 * isn't merely boolean, but gives the number of repeats left to
91 * run.
93 * The `next' field is used for storing MMacros in hash tables; the
94 * `next_active' field is for stacking them on istk entries.
96 * When a MMacro is being expanded, `params', `iline', `nparam',
97 * `paramlen', `rotate' and `unique' are local to the invocation.
99 struct MMacro {
100 MMacro *next;
101 char *name;
102 int casesense;
103 int nparam_min, nparam_max;
104 int plus; /* is the last parameter greedy? */
105 int nolist; /* is this macro listing-inhibited? */
106 int in_progress;
107 Token *dlist; /* All defaults as one list */
108 Token **defaults; /* Parameter default pointers */
109 int ndefs; /* number of default parameters */
110 Line *expansion;
112 MMacro *next_active;
113 MMacro *rep_nest; /* used for nesting %rep */
114 Token **params; /* actual parameters */
115 Token *iline; /* invocation line */
116 unsigned int nparam, rotate;
117 int *paramlen;
118 uint32_t unique;
119 int lineno; /* Current line number on expansion */
123 * The context stack is composed of a linked list of these.
125 struct Context {
126 Context *next;
127 SMacro *localmac;
128 char *name;
129 uint32_t number;
133 * This is the internal form which we break input lines up into.
134 * Typically stored in linked lists.
136 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
137 * necessarily used as-is, but is intended to denote the number of
138 * the substituted parameter. So in the definition
140 * %define a(x,y) ( (x) & ~(y) )
142 * the token representing `x' will have its type changed to
143 * TOK_SMAC_PARAM, but the one representing `y' will be
144 * TOK_SMAC_PARAM+1.
146 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
147 * which doesn't need quotes around it. Used in the pre-include
148 * mechanism as an alternative to trying to find a sensible type of
149 * quote to use on the filename we were passed.
151 enum pp_token_type {
152 TOK_NONE = 0, TOK_WHITESPACE, TOK_COMMENT, TOK_ID,
153 TOK_PREPROC_ID, TOK_STRING,
154 TOK_NUMBER, TOK_SMAC_END, TOK_OTHER, TOK_SMAC_PARAM,
155 TOK_INTERNAL_STRING
158 struct Token {
159 Token *next;
160 char *text;
161 SMacro *mac; /* associated macro for TOK_SMAC_END */
162 enum pp_token_type type;
166 * Multi-line macro definitions are stored as a linked list of
167 * these, which is essentially a container to allow several linked
168 * lists of Tokens.
170 * Note that in this module, linked lists are treated as stacks
171 * wherever possible. For this reason, Lines are _pushed_ on to the
172 * `expansion' field in MMacro structures, so that the linked list,
173 * if walked, would give the macro lines in reverse order; this
174 * means that we can walk the list when expanding a macro, and thus
175 * push the lines on to the `expansion' field in _istk_ in reverse
176 * order (so that when popped back off they are in the right
177 * order). It may seem cockeyed, and it relies on my design having
178 * an even number of steps in, but it works...
180 * Some of these structures, rather than being actual lines, are
181 * markers delimiting the end of the expansion of a given macro.
182 * This is for use in the cycle-tracking and %rep-handling code.
183 * Such structures have `finishes' non-NULL, and `first' NULL. All
184 * others have `finishes' NULL, but `first' may still be NULL if
185 * the line is blank.
187 struct Line {
188 Line *next;
189 MMacro *finishes;
190 Token *first;
194 * To handle an arbitrary level of file inclusion, we maintain a
195 * stack (ie linked list) of these things.
197 struct Include {
198 Include *next;
199 FILE *fp;
200 Cond *conds;
201 Line *expansion;
202 char *fname;
203 int lineno, lineinc;
204 MMacro *mstk; /* stack of active macros/reps */
208 * Include search path. This is simply a list of strings which get
209 * prepended, in turn, to the name of an include file, in an
210 * attempt to find the file if it's not in the current directory.
212 struct IncPath {
213 IncPath *next;
214 char *path;
218 * Conditional assembly: we maintain a separate stack of these for
219 * each level of file inclusion. (The only reason we keep the
220 * stacks separate is to ensure that a stray `%endif' in a file
221 * included from within the true branch of a `%if' won't terminate
222 * it and cause confusion: instead, rightly, it'll cause an error.)
224 struct Cond {
225 Cond *next;
226 int state;
228 enum {
230 * These states are for use just after %if or %elif: IF_TRUE
231 * means the condition has evaluated to truth so we are
232 * currently emitting, whereas IF_FALSE means we are not
233 * currently emitting but will start doing so if a %else comes
234 * up. In these states, all directives are admissible: %elif,
235 * %else and %endif. (And of course %if.)
237 COND_IF_TRUE, COND_IF_FALSE,
239 * These states come up after a %else: ELSE_TRUE means we're
240 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
241 * any %elif or %else will cause an error.
243 COND_ELSE_TRUE, COND_ELSE_FALSE,
245 * This state means that we're not emitting now, and also that
246 * nothing until %endif will be emitted at all. It's for use in
247 * two circumstances: (i) when we've had our moment of emission
248 * and have now started seeing %elifs, and (ii) when the
249 * condition construct in question is contained within a
250 * non-emitting branch of a larger condition construct.
252 COND_NEVER
254 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
257 * These defines are used as the possible return values for do_directive
259 #define NO_DIRECTIVE_FOUND 0
260 #define DIRECTIVE_FOUND 1
263 * Condition codes. Note that we use c_ prefix not C_ because C_ is
264 * used in nasm.h for the "real" condition codes. At _this_ level,
265 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
266 * ones, so we need a different enum...
268 static const char *conditions[] = {
269 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
270 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
271 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
273 enum {
274 c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
275 c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
276 c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_RCXZ, c_S, c_Z
278 static int inverse_ccs[] = {
279 c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
280 c_A, c_AE, c_B, c_BE, c_C, c_E, c_G, c_GE, c_L, c_LE, c_O, c_P, c_S,
281 c_Z, c_NO, c_NP, c_PO, c_PE, -1, c_NS, c_NZ
285 * Directive names.
287 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
288 static int is_condition(enum preproc_token arg)
290 return PP_IS_COND(arg) || (arg == PP_ELSE) || (arg == PP_ENDIF);
293 /* For TASM compatibility we need to be able to recognise TASM compatible
294 * conditional compilation directives. Using the NASM pre-processor does
295 * not work, so we look for them specifically from the following list and
296 * then jam in the equivalent NASM directive into the input stream.
299 #ifndef MAX
300 # define MAX(a,b) ( ((a) > (b)) ? (a) : (b))
301 #endif
303 enum {
304 TM_ARG, TM_ELIF, TM_ELSE, TM_ENDIF, TM_IF, TM_IFDEF, TM_IFDIFI,
305 TM_IFNDEF, TM_INCLUDE, TM_LOCAL
308 static const char *tasm_directives[] = {
309 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
310 "ifndef", "include", "local"
313 static int StackSize = 4;
314 static char *StackPointer = "ebp";
315 static int ArgOffset = 8;
316 static int LocalOffset = 4;
318 static Context *cstk;
319 static Include *istk;
320 static IncPath *ipath = NULL;
322 static efunc _error; /* Pointer to client-provided error reporting function */
323 static evalfunc evaluate;
325 static int pass; /* HACK: pass 0 = generate dependencies only */
327 static uint32_t unique; /* unique identifier numbers */
329 static Line *predef = NULL;
331 static ListGen *list;
334 * The current set of multi-line macros we have defined.
336 static struct hash_table *mmacros;
339 * The current set of single-line macros we have defined.
341 static struct hash_table *smacros;
344 * The multi-line macro we are currently defining, or the %rep
345 * block we are currently reading, if any.
347 static MMacro *defining;
350 * The number of macro parameters to allocate space for at a time.
352 #define PARAM_DELTA 16
355 * The standard macro set: defined as `static char *stdmac[]'. Also
356 * gives our position in the macro set, when we're processing it.
358 #include "macros.c"
359 static const char **stdmacpos;
362 * The extra standard macros that come from the object format, if
363 * any.
365 static const char **extrastdmac = NULL;
366 int any_extrastdmac;
369 * Tokens are allocated in blocks to improve speed
371 #define TOKEN_BLOCKSIZE 4096
372 static Token *freeTokens = NULL;
373 struct Blocks {
374 Blocks *next;
375 void *chunk;
378 static Blocks blocks = { NULL, NULL };
381 * Forward declarations.
383 static Token *expand_mmac_params(Token * tline);
384 static Token *expand_smacro(Token * tline);
385 static Token *expand_id(Token * tline);
386 static Context *get_ctx(char *name, int all_contexts);
387 static void make_tok_num(Token * tok, int32_t val);
388 static void error(int severity, const char *fmt, ...);
389 static void *new_Block(size_t size);
390 static void delete_Blocks(void);
391 static Token *new_Token(Token * next, enum pp_token_type type, char *text, int txtlen);
392 static Token *delete_Token(Token * t);
395 * Macros for safe checking of token pointers, avoid *(NULL)
397 #define tok_type_(x,t) ((x) && (x)->type == (t))
398 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
399 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
400 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
402 /* Handle TASM specific directives, which do not contain a % in
403 * front of them. We do it here because I could not find any other
404 * place to do it for the moment, and it is a hack (ideally it would
405 * be nice to be able to use the NASM pre-processor to do it).
407 static char *check_tasm_directive(char *line)
409 int32_t i, j, k, m, len;
410 char *p = line, *oldline, oldchar;
412 /* Skip whitespace */
413 while (isspace(*p) && *p != 0)
414 p++;
416 /* Binary search for the directive name */
417 i = -1;
418 j = elements(tasm_directives);
419 len = 0;
420 while (!isspace(p[len]) && p[len] != 0)
421 len++;
422 if (len) {
423 oldchar = p[len];
424 p[len] = 0;
425 while (j - i > 1) {
426 k = (j + i) / 2;
427 m = nasm_stricmp(p, tasm_directives[k]);
428 if (m == 0) {
429 /* We have found a directive, so jam a % in front of it
430 * so that NASM will then recognise it as one if it's own.
432 p[len] = oldchar;
433 len = strlen(p);
434 oldline = line;
435 line = nasm_malloc(len + 2);
436 line[0] = '%';
437 if (k == TM_IFDIFI) {
438 /* NASM does not recognise IFDIFI, so we convert it to
439 * %ifdef BOGUS. This is not used in NASM comaptible
440 * code, but does need to parse for the TASM macro
441 * package.
443 strcpy(line + 1, "ifdef BOGUS");
444 } else {
445 memcpy(line + 1, p, len + 1);
447 nasm_free(oldline);
448 return line;
449 } else if (m < 0) {
450 j = k;
451 } else
452 i = k;
454 p[len] = oldchar;
456 return line;
460 * The pre-preprocessing stage... This function translates line
461 * number indications as they emerge from GNU cpp (`# lineno "file"
462 * flags') into NASM preprocessor line number indications (`%line
463 * lineno file').
465 static char *prepreproc(char *line)
467 int lineno, fnlen;
468 char *fname, *oldline;
470 if (line[0] == '#' && line[1] == ' ') {
471 oldline = line;
472 fname = oldline + 2;
473 lineno = atoi(fname);
474 fname += strspn(fname, "0123456789 ");
475 if (*fname == '"')
476 fname++;
477 fnlen = strcspn(fname, "\"");
478 line = nasm_malloc(20 + fnlen);
479 snprintf(line, 20 + fnlen, "%%line %d %.*s", lineno, fnlen, fname);
480 nasm_free(oldline);
482 if (tasm_compatible_mode)
483 return check_tasm_directive(line);
484 return line;
488 * Free a linked list of tokens.
490 static void free_tlist(Token * list)
492 while (list) {
493 list = delete_Token(list);
498 * Free a linked list of lines.
500 static void free_llist(Line * list)
502 Line *l;
503 while (list) {
504 l = list;
505 list = list->next;
506 free_tlist(l->first);
507 nasm_free(l);
512 * Free an MMacro
514 static void free_mmacro(MMacro * m)
516 nasm_free(m->name);
517 free_tlist(m->dlist);
518 nasm_free(m->defaults);
519 free_llist(m->expansion);
520 nasm_free(m);
524 * Free all currently defined macros, and free the hash tables
526 static void free_macros(void)
528 struct hash_tbl_node *it;
529 const char *key;
530 SMacro *s;
531 MMacro *m;
533 it = NULL;
534 while ((s = hash_iterate(smacros, &it, &key)) != NULL) {
535 nasm_free((void *)key);
536 while (s) {
537 SMacro *ns = s->next;
538 nasm_free(s->name);
539 free_tlist(s->expansion);
540 nasm_free(s);
541 s = ns;
544 hash_free(smacros);
546 it = NULL;
547 while ((m = hash_iterate(mmacros, &it, &key)) != NULL) {
548 nasm_free((void *)key);
549 while (m) {
550 MMacro *nm = m->next;
551 free_mmacro(m);
552 m = nm;
555 hash_free(mmacros);
559 * Initialize the hash tables
561 static void init_macros(void)
563 smacros = hash_init();
564 mmacros = hash_init();
568 * Pop the context stack.
570 static void ctx_pop(void)
572 Context *c = cstk;
573 SMacro *smac, *s;
575 cstk = cstk->next;
576 smac = c->localmac;
577 while (smac) {
578 s = smac;
579 smac = smac->next;
580 nasm_free(s->name);
581 free_tlist(s->expansion);
582 nasm_free(s);
584 nasm_free(c->name);
585 nasm_free(c);
588 #define BUF_DELTA 512
590 * Read a line from the top file in istk, handling multiple CR/LFs
591 * at the end of the line read, and handling spurious ^Zs. Will
592 * return lines from the standard macro set if this has not already
593 * been done.
595 static char *read_line(void)
597 char *buffer, *p, *q;
598 int bufsize, continued_count;
600 if (stdmacpos) {
601 if (*stdmacpos) {
602 char *ret = nasm_strdup(*stdmacpos++);
603 if (!*stdmacpos && any_extrastdmac) {
604 stdmacpos = extrastdmac;
605 any_extrastdmac = FALSE;
606 return ret;
609 * Nasty hack: here we push the contents of `predef' on
610 * to the top-level expansion stack, since this is the
611 * most convenient way to implement the pre-include and
612 * pre-define features.
614 if (!*stdmacpos) {
615 Line *pd, *l;
616 Token *head, **tail, *t;
618 for (pd = predef; pd; pd = pd->next) {
619 head = NULL;
620 tail = &head;
621 for (t = pd->first; t; t = t->next) {
622 *tail = new_Token(NULL, t->type, t->text, 0);
623 tail = &(*tail)->next;
625 l = nasm_malloc(sizeof(Line));
626 l->next = istk->expansion;
627 l->first = head;
628 l->finishes = FALSE;
629 istk->expansion = l;
632 return ret;
633 } else {
634 stdmacpos = NULL;
638 bufsize = BUF_DELTA;
639 buffer = nasm_malloc(BUF_DELTA);
640 p = buffer;
641 continued_count = 0;
642 while (1) {
643 q = fgets(p, bufsize - (p - buffer), istk->fp);
644 if (!q)
645 break;
646 p += strlen(p);
647 if (p > buffer && p[-1] == '\n') {
648 /* Convert backslash-CRLF line continuation sequences into
649 nothing at all (for DOS and Windows) */
650 if (((p - 2) > buffer) && (p[-3] == '\\') && (p[-2] == '\r')) {
651 p -= 3;
652 *p = 0;
653 continued_count++;
655 /* Also convert backslash-LF line continuation sequences into
656 nothing at all (for Unix) */
657 else if (((p - 1) > buffer) && (p[-2] == '\\')) {
658 p -= 2;
659 *p = 0;
660 continued_count++;
661 } else {
662 break;
665 if (p - buffer > bufsize - 10) {
666 int32_t offset = p - buffer;
667 bufsize += BUF_DELTA;
668 buffer = nasm_realloc(buffer, bufsize);
669 p = buffer + offset; /* prevent stale-pointer problems */
673 if (!q && p == buffer) {
674 nasm_free(buffer);
675 return NULL;
678 src_set_linnum(src_get_linnum() + istk->lineinc +
679 (continued_count * istk->lineinc));
682 * Play safe: remove CRs as well as LFs, if any of either are
683 * present at the end of the line.
685 while (--p >= buffer && (*p == '\n' || *p == '\r'))
686 *p = '\0';
689 * Handle spurious ^Z, which may be inserted into source files
690 * by some file transfer utilities.
692 buffer[strcspn(buffer, "\032")] = '\0';
694 list->line(LIST_READ, buffer);
696 return buffer;
700 * Tokenize a line of text. This is a very simple process since we
701 * don't need to parse the value out of e.g. numeric tokens: we
702 * simply split one string into many.
704 static Token *tokenize(char *line)
706 char *p = line;
707 enum pp_token_type type;
708 Token *list = NULL;
709 Token *t, **tail = &list;
711 while (*line) {
712 p = line;
713 if (*p == '%') {
714 p++;
715 if (isdigit(*p) ||
716 ((*p == '-' || *p == '+') && isdigit(p[1])) ||
717 ((*p == '+') && (isspace(p[1]) || !p[1]))) {
718 do {
719 p++;
721 while (isdigit(*p));
722 type = TOK_PREPROC_ID;
723 } else if (*p == '{') {
724 p++;
725 while (*p && *p != '}') {
726 p[-1] = *p;
727 p++;
729 p[-1] = '\0';
730 if (*p)
731 p++;
732 type = TOK_PREPROC_ID;
733 } else if (isidchar(*p) ||
734 ((*p == '!' || *p == '%' || *p == '$') &&
735 isidchar(p[1]))) {
736 do {
737 p++;
739 while (isidchar(*p));
740 type = TOK_PREPROC_ID;
741 } else {
742 type = TOK_OTHER;
743 if (*p == '%')
744 p++;
746 } else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
747 type = TOK_ID;
748 p++;
749 while (*p && isidchar(*p))
750 p++;
751 } else if (*p == '\'' || *p == '"') {
753 * A string token.
755 char c = *p;
756 p++;
757 type = TOK_STRING;
758 while (*p && *p != c)
759 p++;
761 if (*p) {
762 p++;
763 } else {
764 error(ERR_WARNING, "unterminated string");
765 /* Handling unterminated strings by UNV */
766 /* type = -1; */
768 } else if (isnumstart(*p)) {
770 * A number token.
772 type = TOK_NUMBER;
773 p++;
774 while (*p && isnumchar(*p))
775 p++;
776 } else if (isspace(*p)) {
777 type = TOK_WHITESPACE;
778 p++;
779 while (*p && isspace(*p))
780 p++;
782 * Whitespace just before end-of-line is discarded by
783 * pretending it's a comment; whitespace just before a
784 * comment gets lumped into the comment.
786 if (!*p || *p == ';') {
787 type = TOK_COMMENT;
788 while (*p)
789 p++;
791 } else if (*p == ';') {
792 type = TOK_COMMENT;
793 while (*p)
794 p++;
795 } else {
797 * Anything else is an operator of some kind. We check
798 * for all the double-character operators (>>, <<, //,
799 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
800 * else is a single-character operator.
802 type = TOK_OTHER;
803 if ((p[0] == '>' && p[1] == '>') ||
804 (p[0] == '<' && p[1] == '<') ||
805 (p[0] == '/' && p[1] == '/') ||
806 (p[0] == '<' && p[1] == '=') ||
807 (p[0] == '>' && p[1] == '=') ||
808 (p[0] == '=' && p[1] == '=') ||
809 (p[0] == '!' && p[1] == '=') ||
810 (p[0] == '<' && p[1] == '>') ||
811 (p[0] == '&' && p[1] == '&') ||
812 (p[0] == '|' && p[1] == '|') ||
813 (p[0] == '^' && p[1] == '^')) {
814 p++;
816 p++;
819 /* Handling unterminated string by UNV */
820 /*if (type == -1)
822 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
823 t->text[p-line] = *line;
824 tail = &t->next;
826 else */
827 if (type != TOK_COMMENT) {
828 *tail = t = new_Token(NULL, type, line, p - line);
829 tail = &t->next;
831 line = p;
833 return list;
837 * this function allocates a new managed block of memory and
838 * returns a pointer to the block. The managed blocks are
839 * deleted only all at once by the delete_Blocks function.
841 static void *new_Block(size_t size)
843 Blocks *b = &blocks;
845 /* first, get to the end of the linked list */
846 while (b->next)
847 b = b->next;
848 /* now allocate the requested chunk */
849 b->chunk = nasm_malloc(size);
851 /* now allocate a new block for the next request */
852 b->next = nasm_malloc(sizeof(Blocks));
853 /* and initialize the contents of the new block */
854 b->next->next = NULL;
855 b->next->chunk = NULL;
856 return b->chunk;
860 * this function deletes all managed blocks of memory
862 static void delete_Blocks(void)
864 Blocks *a, *b = &blocks;
867 * keep in mind that the first block, pointed to by blocks
868 * is a static and not dynamically allocated, so we don't
869 * free it.
871 while (b) {
872 if (b->chunk)
873 nasm_free(b->chunk);
874 a = b;
875 b = b->next;
876 if (a != &blocks)
877 nasm_free(a);
882 * this function creates a new Token and passes a pointer to it
883 * back to the caller. It sets the type and text elements, and
884 * also the mac and next elements to NULL.
886 static Token *new_Token(Token * next, enum pp_token_type type, char *text, int txtlen)
888 Token *t;
889 int i;
891 if (freeTokens == NULL) {
892 freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
893 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
894 freeTokens[i].next = &freeTokens[i + 1];
895 freeTokens[i].next = NULL;
897 t = freeTokens;
898 freeTokens = t->next;
899 t->next = next;
900 t->mac = NULL;
901 t->type = type;
902 if (type == TOK_WHITESPACE || text == NULL) {
903 t->text = NULL;
904 } else {
905 if (txtlen == 0)
906 txtlen = strlen(text);
907 t->text = nasm_malloc(1 + txtlen);
908 strncpy(t->text, text, txtlen);
909 t->text[txtlen] = '\0';
911 return t;
914 static Token *delete_Token(Token * t)
916 Token *next = t->next;
917 nasm_free(t->text);
918 t->next = freeTokens;
919 freeTokens = t;
920 return next;
924 * Convert a line of tokens back into text.
925 * If expand_locals is not zero, identifiers of the form "%$*xxx"
926 * will be transformed into ..@ctxnum.xxx
928 static char *detoken(Token * tlist, int expand_locals)
930 Token *t;
931 int len;
932 char *line, *p;
934 len = 0;
935 for (t = tlist; t; t = t->next) {
936 if (t->type == TOK_PREPROC_ID && t->text[1] == '!') {
937 char *p = getenv(t->text + 2);
938 nasm_free(t->text);
939 if (p)
940 t->text = nasm_strdup(p);
941 else
942 t->text = NULL;
944 /* Expand local macros here and not during preprocessing */
945 if (expand_locals &&
946 t->type == TOK_PREPROC_ID && t->text &&
947 t->text[0] == '%' && t->text[1] == '$') {
948 Context *ctx = get_ctx(t->text, FALSE);
949 if (ctx) {
950 char buffer[40];
951 char *p, *q = t->text + 2;
953 q += strspn(q, "$");
954 snprintf(buffer, sizeof(buffer), "..@%"PRIu32".", ctx->number);
955 p = nasm_strcat(buffer, q);
956 nasm_free(t->text);
957 t->text = p;
960 if (t->type == TOK_WHITESPACE) {
961 len++;
962 } else if (t->text) {
963 len += strlen(t->text);
966 p = line = nasm_malloc(len + 1);
967 for (t = tlist; t; t = t->next) {
968 if (t->type == TOK_WHITESPACE) {
969 *p = ' ';
970 p++;
971 *p = '\0';
972 } else if (t->text) {
973 strcpy(p, t->text);
974 p += strlen(p);
977 *p = '\0';
978 return line;
982 * A scanner, suitable for use by the expression evaluator, which
983 * operates on a line of Tokens. Expects a pointer to a pointer to
984 * the first token in the line to be passed in as its private_data
985 * field.
987 static int ppscan(void *private_data, struct tokenval *tokval)
989 Token **tlineptr = private_data;
990 Token *tline;
992 do {
993 tline = *tlineptr;
994 *tlineptr = tline ? tline->next : NULL;
996 while (tline && (tline->type == TOK_WHITESPACE ||
997 tline->type == TOK_COMMENT));
999 if (!tline)
1000 return tokval->t_type = TOKEN_EOS;
1002 if (tline->text[0] == '$' && !tline->text[1])
1003 return tokval->t_type = TOKEN_HERE;
1004 if (tline->text[0] == '$' && tline->text[1] == '$' && !tline->text[2])
1005 return tokval->t_type = TOKEN_BASE;
1007 if (tline->type == TOK_ID) {
1008 tokval->t_charptr = tline->text;
1009 if (tline->text[0] == '$') {
1010 tokval->t_charptr++;
1011 return tokval->t_type = TOKEN_ID;
1015 * This is the only special case we actually need to worry
1016 * about in this restricted context.
1018 if (!nasm_stricmp(tline->text, "seg"))
1019 return tokval->t_type = TOKEN_SEG;
1021 return tokval->t_type = TOKEN_ID;
1024 if (tline->type == TOK_NUMBER) {
1025 int rn_error;
1027 tokval->t_integer = readnum(tline->text, &rn_error);
1028 if (rn_error)
1029 return tokval->t_type = TOKEN_ERRNUM;
1030 tokval->t_charptr = NULL;
1031 return tokval->t_type = TOKEN_NUM;
1034 if (tline->type == TOK_STRING) {
1035 int rn_warn;
1036 char q, *r;
1037 int l;
1039 r = tline->text;
1040 q = *r++;
1041 l = strlen(r);
1043 if (l == 0 || r[l - 1] != q)
1044 return tokval->t_type = TOKEN_ERRNUM;
1045 tokval->t_integer = readstrnum(r, l - 1, &rn_warn);
1046 if (rn_warn)
1047 error(ERR_WARNING | ERR_PASS1, "character constant too long");
1048 tokval->t_charptr = NULL;
1049 return tokval->t_type = TOKEN_NUM;
1052 if (tline->type == TOK_OTHER) {
1053 if (!strcmp(tline->text, "<<"))
1054 return tokval->t_type = TOKEN_SHL;
1055 if (!strcmp(tline->text, ">>"))
1056 return tokval->t_type = TOKEN_SHR;
1057 if (!strcmp(tline->text, "//"))
1058 return tokval->t_type = TOKEN_SDIV;
1059 if (!strcmp(tline->text, "%%"))
1060 return tokval->t_type = TOKEN_SMOD;
1061 if (!strcmp(tline->text, "=="))
1062 return tokval->t_type = TOKEN_EQ;
1063 if (!strcmp(tline->text, "<>"))
1064 return tokval->t_type = TOKEN_NE;
1065 if (!strcmp(tline->text, "!="))
1066 return tokval->t_type = TOKEN_NE;
1067 if (!strcmp(tline->text, "<="))
1068 return tokval->t_type = TOKEN_LE;
1069 if (!strcmp(tline->text, ">="))
1070 return tokval->t_type = TOKEN_GE;
1071 if (!strcmp(tline->text, "&&"))
1072 return tokval->t_type = TOKEN_DBL_AND;
1073 if (!strcmp(tline->text, "^^"))
1074 return tokval->t_type = TOKEN_DBL_XOR;
1075 if (!strcmp(tline->text, "||"))
1076 return tokval->t_type = TOKEN_DBL_OR;
1080 * We have no other options: just return the first character of
1081 * the token text.
1083 return tokval->t_type = tline->text[0];
1087 * Compare a string to the name of an existing macro; this is a
1088 * simple wrapper which calls either strcmp or nasm_stricmp
1089 * depending on the value of the `casesense' parameter.
1091 static int mstrcmp(char *p, char *q, int casesense)
1093 return casesense ? strcmp(p, q) : nasm_stricmp(p, q);
1097 * Return the Context structure associated with a %$ token. Return
1098 * NULL, having _already_ reported an error condition, if the
1099 * context stack isn't deep enough for the supplied number of $
1100 * signs.
1101 * If all_contexts == TRUE, contexts that enclose current are
1102 * also scanned for such smacro, until it is found; if not -
1103 * only the context that directly results from the number of $'s
1104 * in variable's name.
1106 static Context *get_ctx(char *name, int all_contexts)
1108 Context *ctx;
1109 SMacro *m;
1110 int i;
1112 if (!name || name[0] != '%' || name[1] != '$')
1113 return NULL;
1115 if (!cstk) {
1116 error(ERR_NONFATAL, "`%s': context stack is empty", name);
1117 return NULL;
1120 for (i = strspn(name + 2, "$"), ctx = cstk; (i > 0) && ctx; i--) {
1121 ctx = ctx->next;
1122 /* i--; Lino - 02/25/02 */
1124 if (!ctx) {
1125 error(ERR_NONFATAL, "`%s': context stack is only"
1126 " %d level%s deep", name, i - 1, (i == 2 ? "" : "s"));
1127 return NULL;
1129 if (!all_contexts)
1130 return ctx;
1132 do {
1133 /* Search for this smacro in found context */
1134 m = ctx->localmac;
1135 while (m) {
1136 if (!mstrcmp(m->name, name, m->casesense))
1137 return ctx;
1138 m = m->next;
1140 ctx = ctx->next;
1142 while (ctx);
1143 return NULL;
1147 * Open an include file. This routine must always return a valid
1148 * file pointer if it returns - it's responsible for throwing an
1149 * ERR_FATAL and bombing out completely if not. It should also try
1150 * the include path one by one until it finds the file or reaches
1151 * the end of the path.
1153 static FILE *inc_fopen(char *file)
1155 FILE *fp;
1156 char *prefix = "", *combine;
1157 IncPath *ip = ipath;
1158 static int namelen = 0;
1159 int len = strlen(file);
1161 while (1) {
1162 combine = nasm_malloc(strlen(prefix) + len + 1);
1163 strcpy(combine, prefix);
1164 strcat(combine, file);
1165 fp = fopen(combine, "r");
1166 if (pass == 0 && fp) {
1167 namelen += strlen(combine) + 1;
1168 if (namelen > 62) {
1169 printf(" \\\n ");
1170 namelen = 2;
1172 printf(" %s", combine);
1174 nasm_free(combine);
1175 if (fp)
1176 return fp;
1177 if (!ip)
1178 break;
1179 prefix = ip->path;
1180 ip = ip->next;
1182 if (!prefix) {
1183 /* -MG given and file not found */
1184 if (pass == 0) {
1185 namelen += strlen(file) + 1;
1186 if (namelen > 62) {
1187 printf(" \\\n ");
1188 namelen = 2;
1190 printf(" %s", file);
1192 return NULL;
1196 error(ERR_FATAL, "unable to open include file `%s'", file);
1197 return NULL; /* never reached - placate compilers */
1201 * Search for a key in the hash index; adding it if necessary
1202 * (in which case we initialize the data pointer to NULL.)
1204 static void **
1205 hash_findi_add(struct hash_table *hash, const char *str)
1207 struct hash_insert hi;
1208 void **r;
1209 char *strx;
1211 r = hash_findi(hash, str, &hi);
1212 if (r)
1213 return r;
1215 strx = nasm_strdup(str); /* Use a more efficient allocator here? */
1216 return hash_add(&hi, strx, NULL);
1220 * Like hash_findi, but returns the data element rather than a pointer
1221 * to it. Used only when not adding a new element, hence no third
1222 * argument.
1224 static void *
1225 hash_findix(struct hash_table *hash, const char *str)
1227 void **p;
1229 p = hash_findi(hash, str, NULL);
1230 return p ? *p : NULL;
1234 * Determine if we should warn on defining a single-line macro of
1235 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1236 * return TRUE if _any_ single-line macro of that name is defined.
1237 * Otherwise, will return TRUE if a single-line macro with either
1238 * `nparam' or no parameters is defined.
1240 * If a macro with precisely the right number of parameters is
1241 * defined, or nparam is -1, the address of the definition structure
1242 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1243 * is NULL, no action will be taken regarding its contents, and no
1244 * error will occur.
1246 * Note that this is also called with nparam zero to resolve
1247 * `ifdef'.
1249 * If you already know which context macro belongs to, you can pass
1250 * the context pointer as first parameter; if you won't but name begins
1251 * with %$ the context will be automatically computed. If all_contexts
1252 * is true, macro will be searched in outer contexts as well.
1254 static int
1255 smacro_defined(Context * ctx, char *name, int nparam, SMacro ** defn,
1256 int nocase)
1258 SMacro *m;
1260 if (ctx) {
1261 m = ctx->localmac;
1262 } else if (name[0] == '%' && name[1] == '$') {
1263 if (cstk)
1264 ctx = get_ctx(name, FALSE);
1265 if (!ctx)
1266 return FALSE; /* got to return _something_ */
1267 m = ctx->localmac;
1268 } else {
1269 m = (SMacro *) hash_findix(smacros, name);
1272 while (m) {
1273 if (!mstrcmp(m->name, name, m->casesense && nocase) &&
1274 (nparam <= 0 || m->nparam == 0 || nparam == m->nparam)) {
1275 if (defn) {
1276 if (nparam == m->nparam || nparam == -1)
1277 *defn = m;
1278 else
1279 *defn = NULL;
1281 return TRUE;
1283 m = m->next;
1286 return FALSE;
1290 * Count and mark off the parameters in a multi-line macro call.
1291 * This is called both from within the multi-line macro expansion
1292 * code, and also to mark off the default parameters when provided
1293 * in a %macro definition line.
1295 static void count_mmac_params(Token * t, int *nparam, Token *** params)
1297 int paramsize, brace;
1299 *nparam = paramsize = 0;
1300 *params = NULL;
1301 while (t) {
1302 if (*nparam >= paramsize) {
1303 paramsize += PARAM_DELTA;
1304 *params = nasm_realloc(*params, sizeof(**params) * paramsize);
1306 skip_white_(t);
1307 brace = FALSE;
1308 if (tok_is_(t, "{"))
1309 brace = TRUE;
1310 (*params)[(*nparam)++] = t;
1311 while (tok_isnt_(t, brace ? "}" : ","))
1312 t = t->next;
1313 if (t) { /* got a comma/brace */
1314 t = t->next;
1315 if (brace) {
1317 * Now we've found the closing brace, look further
1318 * for the comma.
1320 skip_white_(t);
1321 if (tok_isnt_(t, ",")) {
1322 error(ERR_NONFATAL,
1323 "braces do not enclose all of macro parameter");
1324 while (tok_isnt_(t, ","))
1325 t = t->next;
1327 if (t)
1328 t = t->next; /* eat the comma */
1335 * Determine whether one of the various `if' conditions is true or
1336 * not.
1338 * We must free the tline we get passed.
1340 static int if_condition(Token * tline, enum preproc_token ct)
1342 enum pp_conditional i = PP_COND(ct);
1343 int j;
1344 Token *t, *tt, **tptr, *origline;
1345 struct tokenval tokval;
1346 expr *evalresult;
1347 enum pp_token_type needtype;
1349 origline = tline;
1351 switch (i) {
1352 case PPC_IFCTX:
1353 j = FALSE; /* have we matched yet? */
1354 while (cstk && tline) {
1355 skip_white_(tline);
1356 if (!tline || tline->type != TOK_ID) {
1357 error(ERR_NONFATAL,
1358 "`%s' expects context identifiers", pp_directives[ct]);
1359 free_tlist(origline);
1360 return -1;
1362 if (!nasm_stricmp(tline->text, cstk->name))
1363 j = TRUE;
1364 tline = tline->next;
1366 break;
1368 case PPC_IFDEF:
1369 j = FALSE; /* have we matched yet? */
1370 while (tline) {
1371 skip_white_(tline);
1372 if (!tline || (tline->type != TOK_ID &&
1373 (tline->type != TOK_PREPROC_ID ||
1374 tline->text[1] != '$'))) {
1375 error(ERR_NONFATAL,
1376 "`%s' expects macro identifiers", pp_directives[ct]);
1377 goto fail;
1379 if (smacro_defined(NULL, tline->text, 0, NULL, 1))
1380 j = TRUE;
1381 tline = tline->next;
1383 break;
1385 case PPC_IFIDN:
1386 case PPC_IFIDNI:
1387 tline = expand_smacro(tline);
1388 t = tt = tline;
1389 while (tok_isnt_(tt, ","))
1390 tt = tt->next;
1391 if (!tt) {
1392 error(ERR_NONFATAL,
1393 "`%s' expects two comma-separated arguments",
1394 pp_directives[ct]);
1395 goto fail;
1397 tt = tt->next;
1398 j = TRUE; /* assume equality unless proved not */
1399 while ((t->type != TOK_OTHER || strcmp(t->text, ",")) && tt) {
1400 if (tt->type == TOK_OTHER && !strcmp(tt->text, ",")) {
1401 error(ERR_NONFATAL, "`%s': more than one comma on line",
1402 pp_directives[ct]);
1403 goto fail;
1405 if (t->type == TOK_WHITESPACE) {
1406 t = t->next;
1407 continue;
1409 if (tt->type == TOK_WHITESPACE) {
1410 tt = tt->next;
1411 continue;
1413 if (tt->type != t->type) {
1414 j = FALSE; /* found mismatching tokens */
1415 break;
1417 /* Unify surrounding quotes for strings */
1418 if (t->type == TOK_STRING) {
1419 tt->text[0] = t->text[0];
1420 tt->text[strlen(tt->text) - 1] = t->text[0];
1422 if (mstrcmp(tt->text, t->text, i == PPC_IFIDN) != 0) {
1423 j = FALSE; /* found mismatching tokens */
1424 break;
1427 t = t->next;
1428 tt = tt->next;
1430 if ((t->type != TOK_OTHER || strcmp(t->text, ",")) || tt)
1431 j = FALSE; /* trailing gunk on one end or other */
1432 break;
1434 case PPC_IFMACRO:
1436 int found = 0;
1437 MMacro searching, *mmac;
1439 tline = tline->next;
1440 skip_white_(tline);
1441 tline = expand_id(tline);
1442 if (!tok_type_(tline, TOK_ID)) {
1443 error(ERR_NONFATAL,
1444 "`%s' expects a macro name", pp_directives[ct]);
1445 goto fail;
1447 searching.name = nasm_strdup(tline->text);
1448 searching.casesense = (i == PP_MACRO);
1449 searching.plus = FALSE;
1450 searching.nolist = FALSE;
1451 searching.in_progress = FALSE;
1452 searching.rep_nest = NULL;
1453 searching.nparam_min = 0;
1454 searching.nparam_max = INT_MAX;
1455 tline = expand_smacro(tline->next);
1456 skip_white_(tline);
1457 if (!tline) {
1458 } else if (!tok_type_(tline, TOK_NUMBER)) {
1459 error(ERR_NONFATAL,
1460 "`%s' expects a parameter count or nothing",
1461 pp_directives[ct]);
1462 } else {
1463 searching.nparam_min = searching.nparam_max =
1464 readnum(tline->text, &j);
1465 if (j)
1466 error(ERR_NONFATAL,
1467 "unable to parse parameter count `%s'",
1468 tline->text);
1470 if (tline && tok_is_(tline->next, "-")) {
1471 tline = tline->next->next;
1472 if (tok_is_(tline, "*"))
1473 searching.nparam_max = INT_MAX;
1474 else if (!tok_type_(tline, TOK_NUMBER))
1475 error(ERR_NONFATAL,
1476 "`%s' expects a parameter count after `-'",
1477 pp_directives[ct]);
1478 else {
1479 searching.nparam_max = readnum(tline->text, &j);
1480 if (j)
1481 error(ERR_NONFATAL,
1482 "unable to parse parameter count `%s'",
1483 tline->text);
1484 if (searching.nparam_min > searching.nparam_max)
1485 error(ERR_NONFATAL,
1486 "minimum parameter count exceeds maximum");
1489 if (tline && tok_is_(tline->next, "+")) {
1490 tline = tline->next;
1491 searching.plus = TRUE;
1493 mmac = (MMacro *) hash_findix(mmacros, searching.name);
1494 while (mmac) {
1495 if (!strcmp(mmac->name, searching.name) &&
1496 (mmac->nparam_min <= searching.nparam_max
1497 || searching.plus)
1498 && (searching.nparam_min <= mmac->nparam_max
1499 || mmac->plus)) {
1500 found = TRUE;
1501 break;
1503 mmac = mmac->next;
1505 nasm_free(searching.name);
1506 j = found;
1507 break;
1510 case PPC_IFID:
1511 needtype = TOK_ID;
1512 goto iftype;
1513 case PPC_IFNUM:
1514 needtype = TOK_NUMBER;
1515 goto iftype;
1516 case PPC_IFSTR:
1517 needtype = TOK_STRING;
1518 goto iftype;
1520 iftype:
1521 tline = expand_smacro(tline);
1522 t = tline;
1523 while (tok_type_(t, TOK_WHITESPACE))
1524 t = t->next;
1525 j = FALSE; /* placate optimiser */
1526 if (t)
1527 j = t->type == needtype;
1528 break;
1530 case PPC_IF:
1531 t = tline = expand_smacro(tline);
1532 tptr = &t;
1533 tokval.t_type = TOKEN_INVALID;
1534 evalresult = evaluate(ppscan, tptr, &tokval,
1535 NULL, pass | CRITICAL, error, NULL);
1536 if (!evalresult)
1537 return -1;
1538 if (tokval.t_type)
1539 error(ERR_WARNING,
1540 "trailing garbage after expression ignored");
1541 if (!is_simple(evalresult)) {
1542 error(ERR_NONFATAL,
1543 "non-constant value given to `%s'", pp_directives[ct]);
1544 goto fail;
1546 j = reloc_value(evalresult) != 0;
1547 return j;
1549 default:
1550 error(ERR_FATAL,
1551 "preprocessor directive `%s' not yet implemented",
1552 pp_directives[ct]);
1553 goto fail;
1556 free_tlist(origline);
1557 return j ^ PP_NEGATIVE(ct);
1559 fail:
1560 free_tlist(origline);
1561 return -1;
1565 * Expand macros in a string. Used in %error and %include directives.
1566 * First tokenize the string, apply "expand_smacro" and then de-tokenize back.
1567 * The returned variable should ALWAYS be freed after usage.
1569 void expand_macros_in_string(char **p)
1571 Token *line = tokenize(*p);
1572 line = expand_smacro(line);
1573 *p = detoken(line, FALSE);
1577 * find and process preprocessor directive in passed line
1578 * Find out if a line contains a preprocessor directive, and deal
1579 * with it if so.
1581 * If a directive _is_ found, it is the responsibility of this routine
1582 * (and not the caller) to free_tlist() the line.
1584 * @param tline a pointer to the current tokeninzed line linked list
1585 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
1588 static int do_directive(Token * tline)
1590 enum preproc_token i;
1591 int j;
1592 int nparam, nolist;
1593 int k, m;
1594 int offset;
1595 char *p, *mname;
1596 Include *inc;
1597 Context *ctx;
1598 Cond *cond;
1599 SMacro *smac, **smhead;
1600 MMacro *mmac, **mmhead;
1601 Token *t, *tt, *param_start, *macro_start, *last, **tptr, *origline;
1602 Line *l;
1603 struct tokenval tokval;
1604 expr *evalresult;
1605 MMacro *tmp_defining; /* Used when manipulating rep_nest */
1607 origline = tline;
1609 skip_white_(tline);
1610 if (!tok_type_(tline, TOK_PREPROC_ID) ||
1611 (tline->text[1] == '%' || tline->text[1] == '$'
1612 || tline->text[1] == '!'))
1613 return NO_DIRECTIVE_FOUND;
1615 i = pp_token_hash(tline->text);
1618 * If we're in a non-emitting branch of a condition construct,
1619 * or walking to the end of an already terminated %rep block,
1620 * we should ignore all directives except for condition
1621 * directives.
1623 if (((istk->conds && !emitting(istk->conds->state)) ||
1624 (istk->mstk && !istk->mstk->in_progress)) && !is_condition(i)) {
1625 return NO_DIRECTIVE_FOUND;
1629 * If we're defining a macro or reading a %rep block, we should
1630 * ignore all directives except for %macro/%imacro (which
1631 * generate an error), %endm/%endmacro, and (only if we're in a
1632 * %rep block) %endrep. If we're in a %rep block, another %rep
1633 * causes an error, so should be let through.
1635 if (defining && i != PP_MACRO && i != PP_IMACRO &&
1636 i != PP_ENDMACRO && i != PP_ENDM &&
1637 (defining->name || (i != PP_ENDREP && i != PP_REP))) {
1638 return NO_DIRECTIVE_FOUND;
1641 switch (i) {
1642 case PP_INVALID:
1643 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
1644 tline->text);
1645 return NO_DIRECTIVE_FOUND; /* didn't get it */
1647 case PP_STACKSIZE:
1648 /* Directive to tell NASM what the default stack size is. The
1649 * default is for a 16-bit stack, and this can be overriden with
1650 * %stacksize large.
1651 * the following form:
1653 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
1655 tline = tline->next;
1656 if (tline && tline->type == TOK_WHITESPACE)
1657 tline = tline->next;
1658 if (!tline || tline->type != TOK_ID) {
1659 error(ERR_NONFATAL, "`%%stacksize' missing size parameter");
1660 free_tlist(origline);
1661 return DIRECTIVE_FOUND;
1663 if (nasm_stricmp(tline->text, "flat") == 0) {
1664 /* All subsequent ARG directives are for a 32-bit stack */
1665 StackSize = 4;
1666 StackPointer = "ebp";
1667 ArgOffset = 8;
1668 LocalOffset = 4;
1669 } else if (nasm_stricmp(tline->text, "large") == 0) {
1670 /* All subsequent ARG directives are for a 16-bit stack,
1671 * far function call.
1673 StackSize = 2;
1674 StackPointer = "bp";
1675 ArgOffset = 4;
1676 LocalOffset = 2;
1677 } else if (nasm_stricmp(tline->text, "small") == 0) {
1678 /* All subsequent ARG directives are for a 16-bit stack,
1679 * far function call. We don't support near functions.
1681 StackSize = 2;
1682 StackPointer = "bp";
1683 ArgOffset = 6;
1684 LocalOffset = 2;
1685 } else {
1686 error(ERR_NONFATAL, "`%%stacksize' invalid size type");
1687 free_tlist(origline);
1688 return DIRECTIVE_FOUND;
1690 free_tlist(origline);
1691 return DIRECTIVE_FOUND;
1693 case PP_ARG:
1694 /* TASM like ARG directive to define arguments to functions, in
1695 * the following form:
1697 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
1699 offset = ArgOffset;
1700 do {
1701 char *arg, directive[256];
1702 int size = StackSize;
1704 /* Find the argument name */
1705 tline = tline->next;
1706 if (tline && tline->type == TOK_WHITESPACE)
1707 tline = tline->next;
1708 if (!tline || tline->type != TOK_ID) {
1709 error(ERR_NONFATAL, "`%%arg' missing argument parameter");
1710 free_tlist(origline);
1711 return DIRECTIVE_FOUND;
1713 arg = tline->text;
1715 /* Find the argument size type */
1716 tline = tline->next;
1717 if (!tline || tline->type != TOK_OTHER
1718 || tline->text[0] != ':') {
1719 error(ERR_NONFATAL,
1720 "Syntax error processing `%%arg' directive");
1721 free_tlist(origline);
1722 return DIRECTIVE_FOUND;
1724 tline = tline->next;
1725 if (!tline || tline->type != TOK_ID) {
1726 error(ERR_NONFATAL, "`%%arg' missing size type parameter");
1727 free_tlist(origline);
1728 return DIRECTIVE_FOUND;
1731 /* Allow macro expansion of type parameter */
1732 tt = tokenize(tline->text);
1733 tt = expand_smacro(tt);
1734 if (nasm_stricmp(tt->text, "byte") == 0) {
1735 size = MAX(StackSize, 1);
1736 } else if (nasm_stricmp(tt->text, "word") == 0) {
1737 size = MAX(StackSize, 2);
1738 } else if (nasm_stricmp(tt->text, "dword") == 0) {
1739 size = MAX(StackSize, 4);
1740 } else if (nasm_stricmp(tt->text, "qword") == 0) {
1741 size = MAX(StackSize, 8);
1742 } else if (nasm_stricmp(tt->text, "tword") == 0) {
1743 size = MAX(StackSize, 10);
1744 } else {
1745 error(ERR_NONFATAL,
1746 "Invalid size type for `%%arg' missing directive");
1747 free_tlist(tt);
1748 free_tlist(origline);
1749 return DIRECTIVE_FOUND;
1751 free_tlist(tt);
1753 /* Now define the macro for the argument */
1754 snprintf(directive, sizeof(directive), "%%define %s (%s+%d)",
1755 arg, StackPointer, offset);
1756 do_directive(tokenize(directive));
1757 offset += size;
1759 /* Move to the next argument in the list */
1760 tline = tline->next;
1761 if (tline && tline->type == TOK_WHITESPACE)
1762 tline = tline->next;
1764 while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
1765 free_tlist(origline);
1766 return DIRECTIVE_FOUND;
1768 case PP_LOCAL:
1769 /* TASM like LOCAL directive to define local variables for a
1770 * function, in the following form:
1772 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
1774 * The '= LocalSize' at the end is ignored by NASM, but is
1775 * required by TASM to define the local parameter size (and used
1776 * by the TASM macro package).
1778 offset = LocalOffset;
1779 do {
1780 char *local, directive[256];
1781 int size = StackSize;
1783 /* Find the argument name */
1784 tline = tline->next;
1785 if (tline && tline->type == TOK_WHITESPACE)
1786 tline = tline->next;
1787 if (!tline || tline->type != TOK_ID) {
1788 error(ERR_NONFATAL,
1789 "`%%local' missing argument parameter");
1790 free_tlist(origline);
1791 return DIRECTIVE_FOUND;
1793 local = tline->text;
1795 /* Find the argument size type */
1796 tline = tline->next;
1797 if (!tline || tline->type != TOK_OTHER
1798 || tline->text[0] != ':') {
1799 error(ERR_NONFATAL,
1800 "Syntax error processing `%%local' directive");
1801 free_tlist(origline);
1802 return DIRECTIVE_FOUND;
1804 tline = tline->next;
1805 if (!tline || tline->type != TOK_ID) {
1806 error(ERR_NONFATAL,
1807 "`%%local' missing size type parameter");
1808 free_tlist(origline);
1809 return DIRECTIVE_FOUND;
1812 /* Allow macro expansion of type parameter */
1813 tt = tokenize(tline->text);
1814 tt = expand_smacro(tt);
1815 if (nasm_stricmp(tt->text, "byte") == 0) {
1816 size = MAX(StackSize, 1);
1817 } else if (nasm_stricmp(tt->text, "word") == 0) {
1818 size = MAX(StackSize, 2);
1819 } else if (nasm_stricmp(tt->text, "dword") == 0) {
1820 size = MAX(StackSize, 4);
1821 } else if (nasm_stricmp(tt->text, "qword") == 0) {
1822 size = MAX(StackSize, 8);
1823 } else if (nasm_stricmp(tt->text, "tword") == 0) {
1824 size = MAX(StackSize, 10);
1825 } else {
1826 error(ERR_NONFATAL,
1827 "Invalid size type for `%%local' missing directive");
1828 free_tlist(tt);
1829 free_tlist(origline);
1830 return DIRECTIVE_FOUND;
1832 free_tlist(tt);
1834 /* Now define the macro for the argument */
1835 snprintf(directive, sizeof(directive), "%%define %s (%s-%d)",
1836 local, StackPointer, offset);
1837 do_directive(tokenize(directive));
1838 offset += size;
1840 /* Now define the assign to setup the enter_c macro correctly */
1841 snprintf(directive, sizeof(directive),
1842 "%%assign %%$localsize %%$localsize+%d", size);
1843 do_directive(tokenize(directive));
1845 /* Move to the next argument in the list */
1846 tline = tline->next;
1847 if (tline && tline->type == TOK_WHITESPACE)
1848 tline = tline->next;
1850 while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
1851 free_tlist(origline);
1852 return DIRECTIVE_FOUND;
1854 case PP_CLEAR:
1855 if (tline->next)
1856 error(ERR_WARNING, "trailing garbage after `%%clear' ignored");
1857 free_macros();
1858 init_macros();
1859 free_tlist(origline);
1860 return DIRECTIVE_FOUND;
1862 case PP_INCLUDE:
1863 tline = tline->next;
1864 skip_white_(tline);
1865 if (!tline || (tline->type != TOK_STRING &&
1866 tline->type != TOK_INTERNAL_STRING)) {
1867 error(ERR_NONFATAL, "`%%include' expects a file name");
1868 free_tlist(origline);
1869 return DIRECTIVE_FOUND; /* but we did _something_ */
1871 if (tline->next)
1872 error(ERR_WARNING,
1873 "trailing garbage after `%%include' ignored");
1874 if (tline->type != TOK_INTERNAL_STRING) {
1875 p = tline->text + 1; /* point past the quote to the name */
1876 p[strlen(p) - 1] = '\0'; /* remove the trailing quote */
1877 } else
1878 p = tline->text; /* internal_string is easier */
1879 expand_macros_in_string(&p);
1880 inc = nasm_malloc(sizeof(Include));
1881 inc->next = istk;
1882 inc->conds = NULL;
1883 inc->fp = inc_fopen(p);
1884 if (!inc->fp && pass == 0) {
1885 /* -MG given but file not found */
1886 nasm_free(inc);
1887 } else {
1888 inc->fname = src_set_fname(p);
1889 inc->lineno = src_set_linnum(0);
1890 inc->lineinc = 1;
1891 inc->expansion = NULL;
1892 inc->mstk = NULL;
1893 istk = inc;
1894 list->uplevel(LIST_INCLUDE);
1896 free_tlist(origline);
1897 return DIRECTIVE_FOUND;
1899 case PP_PUSH:
1900 tline = tline->next;
1901 skip_white_(tline);
1902 tline = expand_id(tline);
1903 if (!tok_type_(tline, TOK_ID)) {
1904 error(ERR_NONFATAL, "`%%push' expects a context identifier");
1905 free_tlist(origline);
1906 return DIRECTIVE_FOUND; /* but we did _something_ */
1908 if (tline->next)
1909 error(ERR_WARNING, "trailing garbage after `%%push' ignored");
1910 ctx = nasm_malloc(sizeof(Context));
1911 ctx->next = cstk;
1912 ctx->localmac = NULL;
1913 ctx->name = nasm_strdup(tline->text);
1914 ctx->number = unique++;
1915 cstk = ctx;
1916 free_tlist(origline);
1917 break;
1919 case PP_REPL:
1920 tline = tline->next;
1921 skip_white_(tline);
1922 tline = expand_id(tline);
1923 if (!tok_type_(tline, TOK_ID)) {
1924 error(ERR_NONFATAL, "`%%repl' expects a context identifier");
1925 free_tlist(origline);
1926 return DIRECTIVE_FOUND; /* but we did _something_ */
1928 if (tline->next)
1929 error(ERR_WARNING, "trailing garbage after `%%repl' ignored");
1930 if (!cstk)
1931 error(ERR_NONFATAL, "`%%repl': context stack is empty");
1932 else {
1933 nasm_free(cstk->name);
1934 cstk->name = nasm_strdup(tline->text);
1936 free_tlist(origline);
1937 break;
1939 case PP_POP:
1940 if (tline->next)
1941 error(ERR_WARNING, "trailing garbage after `%%pop' ignored");
1942 if (!cstk)
1943 error(ERR_NONFATAL, "`%%pop': context stack is already empty");
1944 else
1945 ctx_pop();
1946 free_tlist(origline);
1947 break;
1949 case PP_ERROR:
1950 tline->next = expand_smacro(tline->next);
1951 tline = tline->next;
1952 skip_white_(tline);
1953 if (tok_type_(tline, TOK_STRING)) {
1954 p = tline->text + 1; /* point past the quote to the name */
1955 p[strlen(p) - 1] = '\0'; /* remove the trailing quote */
1956 expand_macros_in_string(&p);
1957 error(ERR_NONFATAL, "%s", p);
1958 nasm_free(p);
1959 } else {
1960 p = detoken(tline, FALSE);
1961 error(ERR_WARNING, "%s", p);
1962 nasm_free(p);
1964 free_tlist(origline);
1965 break;
1967 CASE_PP_IF:
1968 if (istk->conds && !emitting(istk->conds->state))
1969 j = COND_NEVER;
1970 else {
1971 j = if_condition(tline->next, i);
1972 tline->next = NULL; /* it got freed */
1973 free_tlist(origline);
1974 j = j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
1976 cond = nasm_malloc(sizeof(Cond));
1977 cond->next = istk->conds;
1978 cond->state = j;
1979 istk->conds = cond;
1980 return DIRECTIVE_FOUND;
1982 CASE_PP_ELIF:
1983 if (!istk->conds)
1984 error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
1985 if (emitting(istk->conds->state)
1986 || istk->conds->state == COND_NEVER)
1987 istk->conds->state = COND_NEVER;
1988 else {
1990 * IMPORTANT: In the case of %if, we will already have
1991 * called expand_mmac_params(); however, if we're
1992 * processing an %elif we must have been in a
1993 * non-emitting mode, which would have inhibited
1994 * the normal invocation of expand_mmac_params(). Therefore,
1995 * we have to do it explicitly here.
1997 j = if_condition(expand_mmac_params(tline->next), i);
1998 tline->next = NULL; /* it got freed */
1999 free_tlist(origline);
2000 istk->conds->state =
2001 j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2003 return DIRECTIVE_FOUND;
2005 case PP_ELSE:
2006 if (tline->next)
2007 error(ERR_WARNING, "trailing garbage after `%%else' ignored");
2008 if (!istk->conds)
2009 error(ERR_FATAL, "`%%else': no matching `%%if'");
2010 if (emitting(istk->conds->state)
2011 || istk->conds->state == COND_NEVER)
2012 istk->conds->state = COND_ELSE_FALSE;
2013 else
2014 istk->conds->state = COND_ELSE_TRUE;
2015 free_tlist(origline);
2016 return DIRECTIVE_FOUND;
2018 case PP_ENDIF:
2019 if (tline->next)
2020 error(ERR_WARNING, "trailing garbage after `%%endif' ignored");
2021 if (!istk->conds)
2022 error(ERR_FATAL, "`%%endif': no matching `%%if'");
2023 cond = istk->conds;
2024 istk->conds = cond->next;
2025 nasm_free(cond);
2026 free_tlist(origline);
2027 return DIRECTIVE_FOUND;
2029 case PP_MACRO:
2030 case PP_IMACRO:
2031 if (defining)
2032 error(ERR_FATAL,
2033 "`%%%smacro': already defining a macro",
2034 (i == PP_IMACRO ? "i" : ""));
2035 tline = tline->next;
2036 skip_white_(tline);
2037 tline = expand_id(tline);
2038 if (!tok_type_(tline, TOK_ID)) {
2039 error(ERR_NONFATAL,
2040 "`%%%smacro' expects a macro name",
2041 (i == PP_IMACRO ? "i" : ""));
2042 return DIRECTIVE_FOUND;
2044 defining = nasm_malloc(sizeof(MMacro));
2045 defining->name = nasm_strdup(tline->text);
2046 defining->casesense = (i == PP_MACRO);
2047 defining->plus = FALSE;
2048 defining->nolist = FALSE;
2049 defining->in_progress = FALSE;
2050 defining->rep_nest = NULL;
2051 tline = expand_smacro(tline->next);
2052 skip_white_(tline);
2053 if (!tok_type_(tline, TOK_NUMBER)) {
2054 error(ERR_NONFATAL,
2055 "`%%%smacro' expects a parameter count",
2056 (i == PP_IMACRO ? "i" : ""));
2057 defining->nparam_min = defining->nparam_max = 0;
2058 } else {
2059 defining->nparam_min = defining->nparam_max =
2060 readnum(tline->text, &j);
2061 if (j)
2062 error(ERR_NONFATAL,
2063 "unable to parse parameter count `%s'", tline->text);
2065 if (tline && tok_is_(tline->next, "-")) {
2066 tline = tline->next->next;
2067 if (tok_is_(tline, "*"))
2068 defining->nparam_max = INT_MAX;
2069 else if (!tok_type_(tline, TOK_NUMBER))
2070 error(ERR_NONFATAL,
2071 "`%%%smacro' expects a parameter count after `-'",
2072 (i == PP_IMACRO ? "i" : ""));
2073 else {
2074 defining->nparam_max = readnum(tline->text, &j);
2075 if (j)
2076 error(ERR_NONFATAL,
2077 "unable to parse parameter count `%s'",
2078 tline->text);
2079 if (defining->nparam_min > defining->nparam_max)
2080 error(ERR_NONFATAL,
2081 "minimum parameter count exceeds maximum");
2084 if (tline && tok_is_(tline->next, "+")) {
2085 tline = tline->next;
2086 defining->plus = TRUE;
2088 if (tline && tok_type_(tline->next, TOK_ID) &&
2089 !nasm_stricmp(tline->next->text, ".nolist")) {
2090 tline = tline->next;
2091 defining->nolist = TRUE;
2093 mmac = (MMacro *) hash_findix(mmacros, defining->name);
2094 while (mmac) {
2095 if (!strcmp(mmac->name, defining->name) &&
2096 (mmac->nparam_min <= defining->nparam_max
2097 || defining->plus)
2098 && (defining->nparam_min <= mmac->nparam_max
2099 || mmac->plus)) {
2100 error(ERR_WARNING,
2101 "redefining multi-line macro `%s'", defining->name);
2102 break;
2104 mmac = mmac->next;
2107 * Handle default parameters.
2109 if (tline && tline->next) {
2110 defining->dlist = tline->next;
2111 tline->next = NULL;
2112 count_mmac_params(defining->dlist, &defining->ndefs,
2113 &defining->defaults);
2114 } else {
2115 defining->dlist = NULL;
2116 defining->defaults = NULL;
2118 defining->expansion = NULL;
2119 free_tlist(origline);
2120 return DIRECTIVE_FOUND;
2122 case PP_ENDM:
2123 case PP_ENDMACRO:
2124 if (!defining) {
2125 error(ERR_NONFATAL, "`%s': not defining a macro", tline->text);
2126 return DIRECTIVE_FOUND;
2128 mmhead = (MMacro **) hash_findi_add(mmacros, defining->name);
2129 defining->next = *mmhead;
2130 *mmhead = defining;
2131 defining = NULL;
2132 free_tlist(origline);
2133 return DIRECTIVE_FOUND;
2135 case PP_ROTATE:
2136 if (tline->next && tline->next->type == TOK_WHITESPACE)
2137 tline = tline->next;
2138 if (tline->next == NULL) {
2139 free_tlist(origline);
2140 error(ERR_NONFATAL, "`%%rotate' missing rotate count");
2141 return DIRECTIVE_FOUND;
2143 t = expand_smacro(tline->next);
2144 tline->next = NULL;
2145 free_tlist(origline);
2146 tline = t;
2147 tptr = &t;
2148 tokval.t_type = TOKEN_INVALID;
2149 evalresult =
2150 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2151 free_tlist(tline);
2152 if (!evalresult)
2153 return DIRECTIVE_FOUND;
2154 if (tokval.t_type)
2155 error(ERR_WARNING,
2156 "trailing garbage after expression ignored");
2157 if (!is_simple(evalresult)) {
2158 error(ERR_NONFATAL, "non-constant value given to `%%rotate'");
2159 return DIRECTIVE_FOUND;
2161 mmac = istk->mstk;
2162 while (mmac && !mmac->name) /* avoid mistaking %reps for macros */
2163 mmac = mmac->next_active;
2164 if (!mmac) {
2165 error(ERR_NONFATAL, "`%%rotate' invoked outside a macro call");
2166 } else if (mmac->nparam == 0) {
2167 error(ERR_NONFATAL,
2168 "`%%rotate' invoked within macro without parameters");
2169 } else {
2170 int rotate = mmac->rotate + reloc_value(evalresult);
2172 rotate %= (int)mmac->nparam;
2173 if (rotate < 0)
2174 rotate += mmac->nparam;
2176 mmac->rotate = rotate;
2178 return DIRECTIVE_FOUND;
2180 case PP_REP:
2181 nolist = FALSE;
2182 do {
2183 tline = tline->next;
2184 } while (tok_type_(tline, TOK_WHITESPACE));
2186 if (tok_type_(tline, TOK_ID) &&
2187 nasm_stricmp(tline->text, ".nolist") == 0) {
2188 nolist = TRUE;
2189 do {
2190 tline = tline->next;
2191 } while (tok_type_(tline, TOK_WHITESPACE));
2194 if (tline) {
2195 t = expand_smacro(tline);
2196 tptr = &t;
2197 tokval.t_type = TOKEN_INVALID;
2198 evalresult =
2199 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2200 if (!evalresult) {
2201 free_tlist(origline);
2202 return DIRECTIVE_FOUND;
2204 if (tokval.t_type)
2205 error(ERR_WARNING,
2206 "trailing garbage after expression ignored");
2207 if (!is_simple(evalresult)) {
2208 error(ERR_NONFATAL, "non-constant value given to `%%rep'");
2209 return DIRECTIVE_FOUND;
2211 i = (int)reloc_value(evalresult) + 1;
2212 } else {
2213 error(ERR_NONFATAL, "`%%rep' expects a repeat count");
2214 i = 0;
2216 free_tlist(origline);
2218 tmp_defining = defining;
2219 defining = nasm_malloc(sizeof(MMacro));
2220 defining->name = NULL; /* flags this macro as a %rep block */
2221 defining->casesense = 0;
2222 defining->plus = FALSE;
2223 defining->nolist = nolist;
2224 defining->in_progress = i;
2225 defining->nparam_min = defining->nparam_max = 0;
2226 defining->defaults = NULL;
2227 defining->dlist = NULL;
2228 defining->expansion = NULL;
2229 defining->next_active = istk->mstk;
2230 defining->rep_nest = tmp_defining;
2231 return DIRECTIVE_FOUND;
2233 case PP_ENDREP:
2234 if (!defining || defining->name) {
2235 error(ERR_NONFATAL, "`%%endrep': no matching `%%rep'");
2236 return DIRECTIVE_FOUND;
2240 * Now we have a "macro" defined - although it has no name
2241 * and we won't be entering it in the hash tables - we must
2242 * push a macro-end marker for it on to istk->expansion.
2243 * After that, it will take care of propagating itself (a
2244 * macro-end marker line for a macro which is really a %rep
2245 * block will cause the macro to be re-expanded, complete
2246 * with another macro-end marker to ensure the process
2247 * continues) until the whole expansion is forcibly removed
2248 * from istk->expansion by a %exitrep.
2250 l = nasm_malloc(sizeof(Line));
2251 l->next = istk->expansion;
2252 l->finishes = defining;
2253 l->first = NULL;
2254 istk->expansion = l;
2256 istk->mstk = defining;
2258 list->uplevel(defining->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
2259 tmp_defining = defining;
2260 defining = defining->rep_nest;
2261 free_tlist(origline);
2262 return DIRECTIVE_FOUND;
2264 case PP_EXITREP:
2266 * We must search along istk->expansion until we hit a
2267 * macro-end marker for a macro with no name. Then we set
2268 * its `in_progress' flag to 0.
2270 for (l = istk->expansion; l; l = l->next)
2271 if (l->finishes && !l->finishes->name)
2272 break;
2274 if (l)
2275 l->finishes->in_progress = 0;
2276 else
2277 error(ERR_NONFATAL, "`%%exitrep' not within `%%rep' block");
2278 free_tlist(origline);
2279 return DIRECTIVE_FOUND;
2281 case PP_XDEFINE:
2282 case PP_IXDEFINE:
2283 case PP_DEFINE:
2284 case PP_IDEFINE:
2285 tline = tline->next;
2286 skip_white_(tline);
2287 tline = expand_id(tline);
2288 if (!tline || (tline->type != TOK_ID &&
2289 (tline->type != TOK_PREPROC_ID ||
2290 tline->text[1] != '$'))) {
2291 error(ERR_NONFATAL,
2292 "`%%%s%sdefine' expects a macro identifier",
2293 ((i == PP_IDEFINE || i == PP_IXDEFINE) ? "i" : ""),
2294 ((i == PP_XDEFINE || i == PP_IXDEFINE) ? "x" : ""));
2295 free_tlist(origline);
2296 return DIRECTIVE_FOUND;
2299 ctx = get_ctx(tline->text, FALSE);
2301 mname = tline->text;
2302 last = tline;
2303 param_start = tline = tline->next;
2304 nparam = 0;
2306 /* Expand the macro definition now for %xdefine and %ixdefine */
2307 if ((i == PP_XDEFINE) || (i == PP_IXDEFINE))
2308 tline = expand_smacro(tline);
2310 if (tok_is_(tline, "(")) {
2312 * This macro has parameters.
2315 tline = tline->next;
2316 while (1) {
2317 skip_white_(tline);
2318 if (!tline) {
2319 error(ERR_NONFATAL, "parameter identifier expected");
2320 free_tlist(origline);
2321 return DIRECTIVE_FOUND;
2323 if (tline->type != TOK_ID) {
2324 error(ERR_NONFATAL,
2325 "`%s': parameter identifier expected",
2326 tline->text);
2327 free_tlist(origline);
2328 return DIRECTIVE_FOUND;
2330 tline->type = TOK_SMAC_PARAM + nparam++;
2331 tline = tline->next;
2332 skip_white_(tline);
2333 if (tok_is_(tline, ",")) {
2334 tline = tline->next;
2335 continue;
2337 if (!tok_is_(tline, ")")) {
2338 error(ERR_NONFATAL,
2339 "`)' expected to terminate macro template");
2340 free_tlist(origline);
2341 return DIRECTIVE_FOUND;
2343 break;
2345 last = tline;
2346 tline = tline->next;
2348 if (tok_type_(tline, TOK_WHITESPACE))
2349 last = tline, tline = tline->next;
2350 macro_start = NULL;
2351 last->next = NULL;
2352 t = tline;
2353 while (t) {
2354 if (t->type == TOK_ID) {
2355 for (tt = param_start; tt; tt = tt->next)
2356 if (tt->type >= TOK_SMAC_PARAM &&
2357 !strcmp(tt->text, t->text))
2358 t->type = tt->type;
2360 tt = t->next;
2361 t->next = macro_start;
2362 macro_start = t;
2363 t = tt;
2366 * Good. We now have a macro name, a parameter count, and a
2367 * token list (in reverse order) for an expansion. We ought
2368 * to be OK just to create an SMacro, store it, and let
2369 * free_tlist have the rest of the line (which we have
2370 * carefully re-terminated after chopping off the expansion
2371 * from the end).
2373 if (smacro_defined(ctx, mname, nparam, &smac, i == PP_DEFINE)) {
2374 if (!smac) {
2375 error(ERR_WARNING,
2376 "single-line macro `%s' defined both with and"
2377 " without parameters", mname);
2378 free_tlist(origline);
2379 free_tlist(macro_start);
2380 return DIRECTIVE_FOUND;
2381 } else {
2383 * We're redefining, so we have to take over an
2384 * existing SMacro structure. This means freeing
2385 * what was already in it.
2387 nasm_free(smac->name);
2388 free_tlist(smac->expansion);
2390 } else {
2391 if (!ctx)
2392 smhead = (SMacro **) hash_findi_add(smacros, mname);
2393 else
2394 smhead = &ctx->localmac;
2396 smac = nasm_malloc(sizeof(SMacro));
2397 smac->next = *smhead;
2398 *smhead = smac;
2400 smac->name = nasm_strdup(mname);
2401 smac->casesense = ((i == PP_DEFINE) || (i == PP_XDEFINE));
2402 smac->nparam = nparam;
2403 smac->expansion = macro_start;
2404 smac->in_progress = FALSE;
2405 free_tlist(origline);
2406 return DIRECTIVE_FOUND;
2408 case PP_UNDEF:
2409 tline = tline->next;
2410 skip_white_(tline);
2411 tline = expand_id(tline);
2412 if (!tline || (tline->type != TOK_ID &&
2413 (tline->type != TOK_PREPROC_ID ||
2414 tline->text[1] != '$'))) {
2415 error(ERR_NONFATAL, "`%%undef' expects a macro identifier");
2416 free_tlist(origline);
2417 return DIRECTIVE_FOUND;
2419 if (tline->next) {
2420 error(ERR_WARNING,
2421 "trailing garbage after macro name ignored");
2424 /* Find the context that symbol belongs to */
2425 ctx = get_ctx(tline->text, FALSE);
2426 if (!ctx)
2427 smhead = (SMacro **) hash_findi(smacros, tline->text, NULL);
2428 else
2429 smhead = &ctx->localmac;
2431 if (smhead) {
2432 SMacro *s, **sp;
2434 mname = tline->text;
2435 last = tline;
2436 last->next = NULL;
2439 * We now have a macro name... go hunt for it.
2441 sp = smhead;
2442 while ((s = *sp) != NULL) {
2443 if (!mstrcmp(s->name, tline->text, s->casesense)) {
2444 *sp = s->next;
2445 nasm_free(s->name);
2446 free_tlist(s->expansion);
2447 nasm_free(s);
2448 } else {
2449 sp = &s->next;
2452 free_tlist(origline);
2454 return DIRECTIVE_FOUND;
2456 case PP_STRLEN:
2457 tline = tline->next;
2458 skip_white_(tline);
2459 tline = expand_id(tline);
2460 if (!tline || (tline->type != TOK_ID &&
2461 (tline->type != TOK_PREPROC_ID ||
2462 tline->text[1] != '$'))) {
2463 error(ERR_NONFATAL,
2464 "`%%strlen' expects a macro identifier as first parameter");
2465 free_tlist(origline);
2466 return DIRECTIVE_FOUND;
2468 ctx = get_ctx(tline->text, FALSE);
2470 mname = tline->text;
2471 last = tline;
2472 tline = expand_smacro(tline->next);
2473 last->next = NULL;
2475 t = tline;
2476 while (tok_type_(t, TOK_WHITESPACE))
2477 t = t->next;
2478 /* t should now point to the string */
2479 if (t->type != TOK_STRING) {
2480 error(ERR_NONFATAL,
2481 "`%%strlen` requires string as second parameter");
2482 free_tlist(tline);
2483 free_tlist(origline);
2484 return DIRECTIVE_FOUND;
2487 macro_start = nasm_malloc(sizeof(*macro_start));
2488 macro_start->next = NULL;
2489 make_tok_num(macro_start, strlen(t->text) - 2);
2490 macro_start->mac = NULL;
2493 * We now have a macro name, an implicit parameter count of
2494 * zero, and a numeric token to use as an expansion. Create
2495 * and store an SMacro.
2497 if (smacro_defined(ctx, mname, 0, &smac, i == PP_STRLEN)) {
2498 if (!smac)
2499 error(ERR_WARNING,
2500 "single-line macro `%s' defined both with and"
2501 " without parameters", mname);
2502 else {
2504 * We're redefining, so we have to take over an
2505 * existing SMacro structure. This means freeing
2506 * what was already in it.
2508 nasm_free(smac->name);
2509 free_tlist(smac->expansion);
2511 } else {
2512 if (!ctx)
2513 smhead = (SMacro **) hash_findi_add(smacros, mname);
2514 else
2515 smhead = &ctx->localmac;
2517 smac = nasm_malloc(sizeof(SMacro));
2518 smac->next = *smhead;
2519 *smhead = smac;
2521 smac->name = nasm_strdup(mname);
2522 smac->casesense = (i == PP_STRLEN);
2523 smac->nparam = 0;
2524 smac->expansion = macro_start;
2525 smac->in_progress = FALSE;
2526 free_tlist(tline);
2527 free_tlist(origline);
2528 return DIRECTIVE_FOUND;
2530 case PP_SUBSTR:
2531 tline = tline->next;
2532 skip_white_(tline);
2533 tline = expand_id(tline);
2534 if (!tline || (tline->type != TOK_ID &&
2535 (tline->type != TOK_PREPROC_ID ||
2536 tline->text[1] != '$'))) {
2537 error(ERR_NONFATAL,
2538 "`%%substr' expects a macro identifier as first parameter");
2539 free_tlist(origline);
2540 return DIRECTIVE_FOUND;
2542 ctx = get_ctx(tline->text, FALSE);
2544 mname = tline->text;
2545 last = tline;
2546 tline = expand_smacro(tline->next);
2547 last->next = NULL;
2549 t = tline->next;
2550 while (tok_type_(t, TOK_WHITESPACE))
2551 t = t->next;
2553 /* t should now point to the string */
2554 if (t->type != TOK_STRING) {
2555 error(ERR_NONFATAL,
2556 "`%%substr` requires string as second parameter");
2557 free_tlist(tline);
2558 free_tlist(origline);
2559 return DIRECTIVE_FOUND;
2562 tt = t->next;
2563 tptr = &tt;
2564 tokval.t_type = TOKEN_INVALID;
2565 evalresult =
2566 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2567 if (!evalresult) {
2568 free_tlist(tline);
2569 free_tlist(origline);
2570 return DIRECTIVE_FOUND;
2572 if (!is_simple(evalresult)) {
2573 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
2574 free_tlist(tline);
2575 free_tlist(origline);
2576 return DIRECTIVE_FOUND;
2579 macro_start = nasm_malloc(sizeof(*macro_start));
2580 macro_start->next = NULL;
2581 macro_start->text = nasm_strdup("'''");
2582 if (evalresult->value > 0
2583 && evalresult->value < strlen(t->text) - 1) {
2584 macro_start->text[1] = t->text[evalresult->value];
2585 } else {
2586 macro_start->text[2] = '\0';
2588 macro_start->type = TOK_STRING;
2589 macro_start->mac = NULL;
2592 * We now have a macro name, an implicit parameter count of
2593 * zero, and a numeric token to use as an expansion. Create
2594 * and store an SMacro.
2596 if (smacro_defined(ctx, mname, 0, &smac, i == PP_SUBSTR)) {
2597 if (!smac)
2598 error(ERR_WARNING,
2599 "single-line macro `%s' defined both with and"
2600 " without parameters", mname);
2601 else {
2603 * We're redefining, so we have to take over an
2604 * existing SMacro structure. This means freeing
2605 * what was already in it.
2607 nasm_free(smac->name);
2608 free_tlist(smac->expansion);
2610 } else {
2611 if (!ctx)
2612 smhead = (SMacro **) hash_findi_add(smacros, tline->text);
2613 else
2614 smhead = &ctx->localmac;
2616 smac = nasm_malloc(sizeof(SMacro));
2617 smac->next = *smhead;
2618 *smhead = smac;
2620 smac->name = nasm_strdup(mname);
2621 smac->casesense = (i == PP_SUBSTR);
2622 smac->nparam = 0;
2623 smac->expansion = macro_start;
2624 smac->in_progress = FALSE;
2625 free_tlist(tline);
2626 free_tlist(origline);
2627 return DIRECTIVE_FOUND;
2629 case PP_ASSIGN:
2630 case PP_IASSIGN:
2631 tline = tline->next;
2632 skip_white_(tline);
2633 tline = expand_id(tline);
2634 if (!tline || (tline->type != TOK_ID &&
2635 (tline->type != TOK_PREPROC_ID ||
2636 tline->text[1] != '$'))) {
2637 error(ERR_NONFATAL,
2638 "`%%%sassign' expects a macro identifier",
2639 (i == PP_IASSIGN ? "i" : ""));
2640 free_tlist(origline);
2641 return DIRECTIVE_FOUND;
2643 ctx = get_ctx(tline->text, FALSE);
2645 mname = tline->text;
2646 last = tline;
2647 tline = expand_smacro(tline->next);
2648 last->next = NULL;
2650 t = tline;
2651 tptr = &t;
2652 tokval.t_type = TOKEN_INVALID;
2653 evalresult =
2654 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2655 free_tlist(tline);
2656 if (!evalresult) {
2657 free_tlist(origline);
2658 return DIRECTIVE_FOUND;
2661 if (tokval.t_type)
2662 error(ERR_WARNING,
2663 "trailing garbage after expression ignored");
2665 if (!is_simple(evalresult)) {
2666 error(ERR_NONFATAL,
2667 "non-constant value given to `%%%sassign'",
2668 (i == PP_IASSIGN ? "i" : ""));
2669 free_tlist(origline);
2670 return DIRECTIVE_FOUND;
2673 macro_start = nasm_malloc(sizeof(*macro_start));
2674 macro_start->next = NULL;
2675 make_tok_num(macro_start, reloc_value(evalresult));
2676 macro_start->mac = NULL;
2679 * We now have a macro name, an implicit parameter count of
2680 * zero, and a numeric token to use as an expansion. Create
2681 * and store an SMacro.
2683 if (smacro_defined(ctx, mname, 0, &smac, i == PP_ASSIGN)) {
2684 if (!smac)
2685 error(ERR_WARNING,
2686 "single-line macro `%s' defined both with and"
2687 " without parameters", mname);
2688 else {
2690 * We're redefining, so we have to take over an
2691 * existing SMacro structure. This means freeing
2692 * what was already in it.
2694 nasm_free(smac->name);
2695 free_tlist(smac->expansion);
2697 } else {
2698 if (!ctx)
2699 smhead = (SMacro **) hash_findi_add(smacros, mname);
2700 else
2701 smhead = &ctx->localmac;
2703 smac = nasm_malloc(sizeof(SMacro));
2704 smac->next = *smhead;
2705 *smhead = smac;
2707 smac->name = nasm_strdup(mname);
2708 smac->casesense = (i == PP_ASSIGN);
2709 smac->nparam = 0;
2710 smac->expansion = macro_start;
2711 smac->in_progress = FALSE;
2712 free_tlist(origline);
2713 return DIRECTIVE_FOUND;
2715 case PP_LINE:
2717 * Syntax is `%line nnn[+mmm] [filename]'
2719 tline = tline->next;
2720 skip_white_(tline);
2721 if (!tok_type_(tline, TOK_NUMBER)) {
2722 error(ERR_NONFATAL, "`%%line' expects line number");
2723 free_tlist(origline);
2724 return DIRECTIVE_FOUND;
2726 k = readnum(tline->text, &j);
2727 m = 1;
2728 tline = tline->next;
2729 if (tok_is_(tline, "+")) {
2730 tline = tline->next;
2731 if (!tok_type_(tline, TOK_NUMBER)) {
2732 error(ERR_NONFATAL, "`%%line' expects line increment");
2733 free_tlist(origline);
2734 return DIRECTIVE_FOUND;
2736 m = readnum(tline->text, &j);
2737 tline = tline->next;
2739 skip_white_(tline);
2740 src_set_linnum(k);
2741 istk->lineinc = m;
2742 if (tline) {
2743 nasm_free(src_set_fname(detoken(tline, FALSE)));
2745 free_tlist(origline);
2746 return DIRECTIVE_FOUND;
2748 default:
2749 error(ERR_FATAL,
2750 "preprocessor directive `%s' not yet implemented",
2751 pp_directives[i]);
2752 break;
2754 return DIRECTIVE_FOUND;
2758 * Ensure that a macro parameter contains a condition code and
2759 * nothing else. Return the condition code index if so, or -1
2760 * otherwise.
2762 static int find_cc(Token * t)
2764 Token *tt;
2765 int i, j, k, m;
2767 if (!t)
2768 return -1; /* Probably a %+ without a space */
2770 skip_white_(t);
2771 if (t->type != TOK_ID)
2772 return -1;
2773 tt = t->next;
2774 skip_white_(tt);
2775 if (tt && (tt->type != TOK_OTHER || strcmp(tt->text, ",")))
2776 return -1;
2778 i = -1;
2779 j = elements(conditions);
2780 while (j - i > 1) {
2781 k = (j + i) / 2;
2782 m = nasm_stricmp(t->text, conditions[k]);
2783 if (m == 0) {
2784 i = k;
2785 j = -2;
2786 break;
2787 } else if (m < 0) {
2788 j = k;
2789 } else
2790 i = k;
2792 if (j != -2)
2793 return -1;
2794 return i;
2798 * Expand MMacro-local things: parameter references (%0, %n, %+n,
2799 * %-n) and MMacro-local identifiers (%%foo).
2801 static Token *expand_mmac_params(Token * tline)
2803 Token *t, *tt, **tail, *thead;
2805 tail = &thead;
2806 thead = NULL;
2808 while (tline) {
2809 if (tline->type == TOK_PREPROC_ID &&
2810 (((tline->text[1] == '+' || tline->text[1] == '-')
2811 && tline->text[2]) || tline->text[1] == '%'
2812 || (tline->text[1] >= '0' && tline->text[1] <= '9'))) {
2813 char *text = NULL;
2814 int type = 0, cc; /* type = 0 to placate optimisers */
2815 char tmpbuf[30];
2816 unsigned int n;
2817 int i;
2818 MMacro *mac;
2820 t = tline;
2821 tline = tline->next;
2823 mac = istk->mstk;
2824 while (mac && !mac->name) /* avoid mistaking %reps for macros */
2825 mac = mac->next_active;
2826 if (!mac)
2827 error(ERR_NONFATAL, "`%s': not in a macro call", t->text);
2828 else
2829 switch (t->text[1]) {
2831 * We have to make a substitution of one of the
2832 * forms %1, %-1, %+1, %%foo, %0.
2834 case '0':
2835 type = TOK_NUMBER;
2836 snprintf(tmpbuf, sizeof(tmpbuf), "%d", mac->nparam);
2837 text = nasm_strdup(tmpbuf);
2838 break;
2839 case '%':
2840 type = TOK_ID;
2841 snprintf(tmpbuf, sizeof(tmpbuf), "..@%"PRIu32".",
2842 mac->unique);
2843 text = nasm_strcat(tmpbuf, t->text + 2);
2844 break;
2845 case '-':
2846 n = atoi(t->text + 2) - 1;
2847 if (n >= mac->nparam)
2848 tt = NULL;
2849 else {
2850 if (mac->nparam > 1)
2851 n = (n + mac->rotate) % mac->nparam;
2852 tt = mac->params[n];
2854 cc = find_cc(tt);
2855 if (cc == -1) {
2856 error(ERR_NONFATAL,
2857 "macro parameter %d is not a condition code",
2858 n + 1);
2859 text = NULL;
2860 } else {
2861 type = TOK_ID;
2862 if (inverse_ccs[cc] == -1) {
2863 error(ERR_NONFATAL,
2864 "condition code `%s' is not invertible",
2865 conditions[cc]);
2866 text = NULL;
2867 } else
2868 text =
2869 nasm_strdup(conditions[inverse_ccs[cc]]);
2871 break;
2872 case '+':
2873 n = atoi(t->text + 2) - 1;
2874 if (n >= mac->nparam)
2875 tt = NULL;
2876 else {
2877 if (mac->nparam > 1)
2878 n = (n + mac->rotate) % mac->nparam;
2879 tt = mac->params[n];
2881 cc = find_cc(tt);
2882 if (cc == -1) {
2883 error(ERR_NONFATAL,
2884 "macro parameter %d is not a condition code",
2885 n + 1);
2886 text = NULL;
2887 } else {
2888 type = TOK_ID;
2889 text = nasm_strdup(conditions[cc]);
2891 break;
2892 default:
2893 n = atoi(t->text + 1) - 1;
2894 if (n >= mac->nparam)
2895 tt = NULL;
2896 else {
2897 if (mac->nparam > 1)
2898 n = (n + mac->rotate) % mac->nparam;
2899 tt = mac->params[n];
2901 if (tt) {
2902 for (i = 0; i < mac->paramlen[n]; i++) {
2903 *tail = new_Token(NULL, tt->type, tt->text, 0);
2904 tail = &(*tail)->next;
2905 tt = tt->next;
2908 text = NULL; /* we've done it here */
2909 break;
2911 if (!text) {
2912 delete_Token(t);
2913 } else {
2914 *tail = t;
2915 tail = &t->next;
2916 t->type = type;
2917 nasm_free(t->text);
2918 t->text = text;
2919 t->mac = NULL;
2921 continue;
2922 } else {
2923 t = *tail = tline;
2924 tline = tline->next;
2925 t->mac = NULL;
2926 tail = &t->next;
2929 *tail = NULL;
2930 t = thead;
2931 for (; t && (tt = t->next) != NULL; t = t->next)
2932 switch (t->type) {
2933 case TOK_WHITESPACE:
2934 if (tt->type == TOK_WHITESPACE) {
2935 t->next = delete_Token(tt);
2937 break;
2938 case TOK_ID:
2939 if (tt->type == TOK_ID || tt->type == TOK_NUMBER) {
2940 char *tmp = nasm_strcat(t->text, tt->text);
2941 nasm_free(t->text);
2942 t->text = tmp;
2943 t->next = delete_Token(tt);
2945 break;
2946 case TOK_NUMBER:
2947 if (tt->type == TOK_NUMBER) {
2948 char *tmp = nasm_strcat(t->text, tt->text);
2949 nasm_free(t->text);
2950 t->text = tmp;
2951 t->next = delete_Token(tt);
2953 break;
2954 default:
2955 break;
2958 return thead;
2962 * Expand all single-line macro calls made in the given line.
2963 * Return the expanded version of the line. The original is deemed
2964 * to be destroyed in the process. (In reality we'll just move
2965 * Tokens from input to output a lot of the time, rather than
2966 * actually bothering to destroy and replicate.)
2968 static Token *expand_smacro(Token * tline)
2970 Token *t, *tt, *mstart, **tail, *thead;
2971 SMacro *head = NULL, *m;
2972 Token **params;
2973 int *paramsize;
2974 unsigned int nparam, sparam;
2975 int brackets, rescan;
2976 Token *org_tline = tline;
2977 Context *ctx;
2978 char *mname;
2981 * Trick: we should avoid changing the start token pointer since it can
2982 * be contained in "next" field of other token. Because of this
2983 * we allocate a copy of first token and work with it; at the end of
2984 * routine we copy it back
2986 if (org_tline) {
2987 tline =
2988 new_Token(org_tline->next, org_tline->type, org_tline->text,
2990 tline->mac = org_tline->mac;
2991 nasm_free(org_tline->text);
2992 org_tline->text = NULL;
2995 again:
2996 tail = &thead;
2997 thead = NULL;
2999 while (tline) { /* main token loop */
3000 if ((mname = tline->text)) {
3001 /* if this token is a local macro, look in local context */
3002 if (tline->type == TOK_ID || tline->type == TOK_PREPROC_ID)
3003 ctx = get_ctx(mname, TRUE);
3004 else
3005 ctx = NULL;
3006 if (!ctx) {
3007 head = (SMacro *) hash_findix(smacros, mname);
3008 } else {
3009 head = ctx->localmac;
3012 * We've hit an identifier. As in is_mmacro below, we first
3013 * check whether the identifier is a single-line macro at
3014 * all, then think about checking for parameters if
3015 * necessary.
3017 for (m = head; m; m = m->next)
3018 if (!mstrcmp(m->name, mname, m->casesense))
3019 break;
3020 if (m) {
3021 mstart = tline;
3022 params = NULL;
3023 paramsize = NULL;
3024 if (m->nparam == 0) {
3026 * Simple case: the macro is parameterless. Discard the
3027 * one token that the macro call took, and push the
3028 * expansion back on the to-do stack.
3030 if (!m->expansion) {
3031 if (!strcmp("__FILE__", m->name)) {
3032 int32_t num = 0;
3033 src_get(&num, &(tline->text));
3034 nasm_quote(&(tline->text));
3035 tline->type = TOK_STRING;
3036 continue;
3038 if (!strcmp("__LINE__", m->name)) {
3039 nasm_free(tline->text);
3040 make_tok_num(tline, src_get_linnum());
3041 continue;
3043 if (!strcmp("__BITS__", m->name)) {
3044 nasm_free(tline->text);
3045 make_tok_num(tline, globalbits);
3046 continue;
3048 tline = delete_Token(tline);
3049 continue;
3051 } else {
3053 * Complicated case: at least one macro with this name
3054 * exists and takes parameters. We must find the
3055 * parameters in the call, count them, find the SMacro
3056 * that corresponds to that form of the macro call, and
3057 * substitute for the parameters when we expand. What a
3058 * pain.
3060 /*tline = tline->next;
3061 skip_white_(tline); */
3062 do {
3063 t = tline->next;
3064 while (tok_type_(t, TOK_SMAC_END)) {
3065 t->mac->in_progress = FALSE;
3066 t->text = NULL;
3067 t = tline->next = delete_Token(t);
3069 tline = t;
3070 } while (tok_type_(tline, TOK_WHITESPACE));
3071 if (!tok_is_(tline, "(")) {
3073 * This macro wasn't called with parameters: ignore
3074 * the call. (Behaviour borrowed from gnu cpp.)
3076 tline = mstart;
3077 m = NULL;
3078 } else {
3079 int paren = 0;
3080 int white = 0;
3081 brackets = 0;
3082 nparam = 0;
3083 sparam = PARAM_DELTA;
3084 params = nasm_malloc(sparam * sizeof(Token *));
3085 params[0] = tline->next;
3086 paramsize = nasm_malloc(sparam * sizeof(int));
3087 paramsize[0] = 0;
3088 while (TRUE) { /* parameter loop */
3090 * For some unusual expansions
3091 * which concatenates function call
3093 t = tline->next;
3094 while (tok_type_(t, TOK_SMAC_END)) {
3095 t->mac->in_progress = FALSE;
3096 t->text = NULL;
3097 t = tline->next = delete_Token(t);
3099 tline = t;
3101 if (!tline) {
3102 error(ERR_NONFATAL,
3103 "macro call expects terminating `)'");
3104 break;
3106 if (tline->type == TOK_WHITESPACE
3107 && brackets <= 0) {
3108 if (paramsize[nparam])
3109 white++;
3110 else
3111 params[nparam] = tline->next;
3112 continue; /* parameter loop */
3114 if (tline->type == TOK_OTHER
3115 && tline->text[1] == 0) {
3116 char ch = tline->text[0];
3117 if (ch == ',' && !paren && brackets <= 0) {
3118 if (++nparam >= sparam) {
3119 sparam += PARAM_DELTA;
3120 params = nasm_realloc(params,
3121 sparam *
3122 sizeof(Token
3123 *));
3124 paramsize =
3125 nasm_realloc(paramsize,
3126 sparam *
3127 sizeof(int));
3129 params[nparam] = tline->next;
3130 paramsize[nparam] = 0;
3131 white = 0;
3132 continue; /* parameter loop */
3134 if (ch == '{' &&
3135 (brackets > 0 || (brackets == 0 &&
3136 !paramsize[nparam])))
3138 if (!(brackets++)) {
3139 params[nparam] = tline->next;
3140 continue; /* parameter loop */
3143 if (ch == '}' && brackets > 0)
3144 if (--brackets == 0) {
3145 brackets = -1;
3146 continue; /* parameter loop */
3148 if (ch == '(' && !brackets)
3149 paren++;
3150 if (ch == ')' && brackets <= 0)
3151 if (--paren < 0)
3152 break;
3154 if (brackets < 0) {
3155 brackets = 0;
3156 error(ERR_NONFATAL, "braces do not "
3157 "enclose all of macro parameter");
3159 paramsize[nparam] += white + 1;
3160 white = 0;
3161 } /* parameter loop */
3162 nparam++;
3163 while (m && (m->nparam != nparam ||
3164 mstrcmp(m->name, mname,
3165 m->casesense)))
3166 m = m->next;
3167 if (!m)
3168 error(ERR_WARNING | ERR_WARN_MNP,
3169 "macro `%s' exists, "
3170 "but not taking %d parameters",
3171 mstart->text, nparam);
3174 if (m && m->in_progress)
3175 m = NULL;
3176 if (!m) { /* in progess or didn't find '(' or wrong nparam */
3178 * Design question: should we handle !tline, which
3179 * indicates missing ')' here, or expand those
3180 * macros anyway, which requires the (t) test a few
3181 * lines down?
3183 nasm_free(params);
3184 nasm_free(paramsize);
3185 tline = mstart;
3186 } else {
3188 * Expand the macro: we are placed on the last token of the
3189 * call, so that we can easily split the call from the
3190 * following tokens. We also start by pushing an SMAC_END
3191 * token for the cycle removal.
3193 t = tline;
3194 if (t) {
3195 tline = t->next;
3196 t->next = NULL;
3198 tt = new_Token(tline, TOK_SMAC_END, NULL, 0);
3199 tt->mac = m;
3200 m->in_progress = TRUE;
3201 tline = tt;
3202 for (t = m->expansion; t; t = t->next) {
3203 if (t->type >= TOK_SMAC_PARAM) {
3204 Token *pcopy = tline, **ptail = &pcopy;
3205 Token *ttt, *pt;
3206 int i;
3208 ttt = params[t->type - TOK_SMAC_PARAM];
3209 for (i = paramsize[t->type - TOK_SMAC_PARAM];
3210 --i >= 0;) {
3211 pt = *ptail =
3212 new_Token(tline, ttt->type, ttt->text,
3214 ptail = &pt->next;
3215 ttt = ttt->next;
3217 tline = pcopy;
3218 } else {
3219 tt = new_Token(tline, t->type, t->text, 0);
3220 tline = tt;
3225 * Having done that, get rid of the macro call, and clean
3226 * up the parameters.
3228 nasm_free(params);
3229 nasm_free(paramsize);
3230 free_tlist(mstart);
3231 continue; /* main token loop */
3236 if (tline->type == TOK_SMAC_END) {
3237 tline->mac->in_progress = FALSE;
3238 tline = delete_Token(tline);
3239 } else {
3240 t = *tail = tline;
3241 tline = tline->next;
3242 t->mac = NULL;
3243 t->next = NULL;
3244 tail = &t->next;
3249 * Now scan the entire line and look for successive TOK_IDs that resulted
3250 * after expansion (they can't be produced by tokenize()). The successive
3251 * TOK_IDs should be concatenated.
3252 * Also we look for %+ tokens and concatenate the tokens before and after
3253 * them (without white spaces in between).
3255 t = thead;
3256 rescan = 0;
3257 while (t) {
3258 while (t && t->type != TOK_ID && t->type != TOK_PREPROC_ID)
3259 t = t->next;
3260 if (!t || !t->next)
3261 break;
3262 if (t->next->type == TOK_ID ||
3263 t->next->type == TOK_PREPROC_ID ||
3264 t->next->type == TOK_NUMBER) {
3265 char *p = nasm_strcat(t->text, t->next->text);
3266 nasm_free(t->text);
3267 t->next = delete_Token(t->next);
3268 t->text = p;
3269 rescan = 1;
3270 } else if (t->next->type == TOK_WHITESPACE && t->next->next &&
3271 t->next->next->type == TOK_PREPROC_ID &&
3272 strcmp(t->next->next->text, "%+") == 0) {
3273 /* free the next whitespace, the %+ token and next whitespace */
3274 int i;
3275 for (i = 1; i <= 3; i++) {
3276 if (!t->next
3277 || (i != 2 && t->next->type != TOK_WHITESPACE))
3278 break;
3279 t->next = delete_Token(t->next);
3280 } /* endfor */
3281 } else
3282 t = t->next;
3284 /* If we concatenaded something, re-scan the line for macros */
3285 if (rescan) {
3286 tline = thead;
3287 goto again;
3290 if (org_tline) {
3291 if (thead) {
3292 *org_tline = *thead;
3293 /* since we just gave text to org_line, don't free it */
3294 thead->text = NULL;
3295 delete_Token(thead);
3296 } else {
3297 /* the expression expanded to empty line;
3298 we can't return NULL for some reasons
3299 we just set the line to a single WHITESPACE token. */
3300 memset(org_tline, 0, sizeof(*org_tline));
3301 org_tline->text = NULL;
3302 org_tline->type = TOK_WHITESPACE;
3304 thead = org_tline;
3307 return thead;
3311 * Similar to expand_smacro but used exclusively with macro identifiers
3312 * right before they are fetched in. The reason is that there can be
3313 * identifiers consisting of several subparts. We consider that if there
3314 * are more than one element forming the name, user wants a expansion,
3315 * otherwise it will be left as-is. Example:
3317 * %define %$abc cde
3319 * the identifier %$abc will be left as-is so that the handler for %define
3320 * will suck it and define the corresponding value. Other case:
3322 * %define _%$abc cde
3324 * In this case user wants name to be expanded *before* %define starts
3325 * working, so we'll expand %$abc into something (if it has a value;
3326 * otherwise it will be left as-is) then concatenate all successive
3327 * PP_IDs into one.
3329 static Token *expand_id(Token * tline)
3331 Token *cur, *oldnext = NULL;
3333 if (!tline || !tline->next)
3334 return tline;
3336 cur = tline;
3337 while (cur->next &&
3338 (cur->next->type == TOK_ID ||
3339 cur->next->type == TOK_PREPROC_ID
3340 || cur->next->type == TOK_NUMBER))
3341 cur = cur->next;
3343 /* If identifier consists of just one token, don't expand */
3344 if (cur == tline)
3345 return tline;
3347 if (cur) {
3348 oldnext = cur->next; /* Detach the tail past identifier */
3349 cur->next = NULL; /* so that expand_smacro stops here */
3352 tline = expand_smacro(tline);
3354 if (cur) {
3355 /* expand_smacro possibly changhed tline; re-scan for EOL */
3356 cur = tline;
3357 while (cur && cur->next)
3358 cur = cur->next;
3359 if (cur)
3360 cur->next = oldnext;
3363 return tline;
3367 * Determine whether the given line constitutes a multi-line macro
3368 * call, and return the MMacro structure called if so. Doesn't have
3369 * to check for an initial label - that's taken care of in
3370 * expand_mmacro - but must check numbers of parameters. Guaranteed
3371 * to be called with tline->type == TOK_ID, so the putative macro
3372 * name is easy to find.
3374 static MMacro *is_mmacro(Token * tline, Token *** params_array)
3376 MMacro *head, *m;
3377 Token **params;
3378 int nparam;
3380 head = (MMacro *) hash_findix(mmacros, tline->text);
3383 * Efficiency: first we see if any macro exists with the given
3384 * name. If not, we can return NULL immediately. _Then_ we
3385 * count the parameters, and then we look further along the
3386 * list if necessary to find the proper MMacro.
3388 for (m = head; m; m = m->next)
3389 if (!mstrcmp(m->name, tline->text, m->casesense))
3390 break;
3391 if (!m)
3392 return NULL;
3395 * OK, we have a potential macro. Count and demarcate the
3396 * parameters.
3398 count_mmac_params(tline->next, &nparam, &params);
3401 * So we know how many parameters we've got. Find the MMacro
3402 * structure that handles this number.
3404 while (m) {
3405 if (m->nparam_min <= nparam
3406 && (m->plus || nparam <= m->nparam_max)) {
3408 * This one is right. Just check if cycle removal
3409 * prohibits us using it before we actually celebrate...
3411 if (m->in_progress) {
3412 #if 0
3413 error(ERR_NONFATAL,
3414 "self-reference in multi-line macro `%s'", m->name);
3415 #endif
3416 nasm_free(params);
3417 return NULL;
3420 * It's right, and we can use it. Add its default
3421 * parameters to the end of our list if necessary.
3423 if (m->defaults && nparam < m->nparam_min + m->ndefs) {
3424 params =
3425 nasm_realloc(params,
3426 ((m->nparam_min + m->ndefs +
3427 1) * sizeof(*params)));
3428 while (nparam < m->nparam_min + m->ndefs) {
3429 params[nparam] = m->defaults[nparam - m->nparam_min];
3430 nparam++;
3434 * If we've gone over the maximum parameter count (and
3435 * we're in Plus mode), ignore parameters beyond
3436 * nparam_max.
3438 if (m->plus && nparam > m->nparam_max)
3439 nparam = m->nparam_max;
3441 * Then terminate the parameter list, and leave.
3443 if (!params) { /* need this special case */
3444 params = nasm_malloc(sizeof(*params));
3445 nparam = 0;
3447 params[nparam] = NULL;
3448 *params_array = params;
3449 return m;
3452 * This one wasn't right: look for the next one with the
3453 * same name.
3455 for (m = m->next; m; m = m->next)
3456 if (!mstrcmp(m->name, tline->text, m->casesense))
3457 break;
3461 * After all that, we didn't find one with the right number of
3462 * parameters. Issue a warning, and fail to expand the macro.
3464 error(ERR_WARNING | ERR_WARN_MNP,
3465 "macro `%s' exists, but not taking %d parameters",
3466 tline->text, nparam);
3467 nasm_free(params);
3468 return NULL;
3472 * Expand the multi-line macro call made by the given line, if
3473 * there is one to be expanded. If there is, push the expansion on
3474 * istk->expansion and return 1. Otherwise return 0.
3476 static int expand_mmacro(Token * tline)
3478 Token *startline = tline;
3479 Token *label = NULL;
3480 int dont_prepend = 0;
3481 Token **params, *t, *tt;
3482 MMacro *m;
3483 Line *l, *ll;
3484 int i, nparam, *paramlen;
3486 t = tline;
3487 skip_white_(t);
3488 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
3489 if (!tok_type_(t, TOK_ID) && !tok_type_(t, TOK_PREPROC_ID))
3490 return 0;
3491 m = is_mmacro(t, &params);
3492 if (!m) {
3493 Token *last;
3495 * We have an id which isn't a macro call. We'll assume
3496 * it might be a label; we'll also check to see if a
3497 * colon follows it. Then, if there's another id after
3498 * that lot, we'll check it again for macro-hood.
3500 label = last = t;
3501 t = t->next;
3502 if (tok_type_(t, TOK_WHITESPACE))
3503 last = t, t = t->next;
3504 if (tok_is_(t, ":")) {
3505 dont_prepend = 1;
3506 last = t, t = t->next;
3507 if (tok_type_(t, TOK_WHITESPACE))
3508 last = t, t = t->next;
3510 if (!tok_type_(t, TOK_ID) || (m = is_mmacro(t, &params)) == NULL)
3511 return 0;
3512 last->next = NULL;
3513 tline = t;
3517 * Fix up the parameters: this involves stripping leading and
3518 * trailing whitespace, then stripping braces if they are
3519 * present.
3521 for (nparam = 0; params[nparam]; nparam++) ;
3522 paramlen = nparam ? nasm_malloc(nparam * sizeof(*paramlen)) : NULL;
3524 for (i = 0; params[i]; i++) {
3525 int brace = FALSE;
3526 int comma = (!m->plus || i < nparam - 1);
3528 t = params[i];
3529 skip_white_(t);
3530 if (tok_is_(t, "{"))
3531 t = t->next, brace = TRUE, comma = FALSE;
3532 params[i] = t;
3533 paramlen[i] = 0;
3534 while (t) {
3535 if (comma && t->type == TOK_OTHER && !strcmp(t->text, ","))
3536 break; /* ... because we have hit a comma */
3537 if (comma && t->type == TOK_WHITESPACE
3538 && tok_is_(t->next, ","))
3539 break; /* ... or a space then a comma */
3540 if (brace && t->type == TOK_OTHER && !strcmp(t->text, "}"))
3541 break; /* ... or a brace */
3542 t = t->next;
3543 paramlen[i]++;
3548 * OK, we have a MMacro structure together with a set of
3549 * parameters. We must now go through the expansion and push
3550 * copies of each Line on to istk->expansion. Substitution of
3551 * parameter tokens and macro-local tokens doesn't get done
3552 * until the single-line macro substitution process; this is
3553 * because delaying them allows us to change the semantics
3554 * later through %rotate.
3556 * First, push an end marker on to istk->expansion, mark this
3557 * macro as in progress, and set up its invocation-specific
3558 * variables.
3560 ll = nasm_malloc(sizeof(Line));
3561 ll->next = istk->expansion;
3562 ll->finishes = m;
3563 ll->first = NULL;
3564 istk->expansion = ll;
3566 m->in_progress = TRUE;
3567 m->params = params;
3568 m->iline = tline;
3569 m->nparam = nparam;
3570 m->rotate = 0;
3571 m->paramlen = paramlen;
3572 m->unique = unique++;
3573 m->lineno = 0;
3575 m->next_active = istk->mstk;
3576 istk->mstk = m;
3578 for (l = m->expansion; l; l = l->next) {
3579 Token **tail;
3581 ll = nasm_malloc(sizeof(Line));
3582 ll->finishes = NULL;
3583 ll->next = istk->expansion;
3584 istk->expansion = ll;
3585 tail = &ll->first;
3587 for (t = l->first; t; t = t->next) {
3588 Token *x = t;
3589 if (t->type == TOK_PREPROC_ID &&
3590 t->text[1] == '0' && t->text[2] == '0') {
3591 dont_prepend = -1;
3592 x = label;
3593 if (!x)
3594 continue;
3596 tt = *tail = new_Token(NULL, x->type, x->text, 0);
3597 tail = &tt->next;
3599 *tail = NULL;
3603 * If we had a label, push it on as the first line of
3604 * the macro expansion.
3606 if (label) {
3607 if (dont_prepend < 0)
3608 free_tlist(startline);
3609 else {
3610 ll = nasm_malloc(sizeof(Line));
3611 ll->finishes = NULL;
3612 ll->next = istk->expansion;
3613 istk->expansion = ll;
3614 ll->first = startline;
3615 if (!dont_prepend) {
3616 while (label->next)
3617 label = label->next;
3618 label->next = tt = new_Token(NULL, TOK_OTHER, ":", 0);
3623 list->uplevel(m->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
3625 return 1;
3629 * Since preprocessor always operate only on the line that didn't
3630 * arrived yet, we should always use ERR_OFFBY1. Also since user
3631 * won't want to see same error twice (preprocessing is done once
3632 * per pass) we will want to show errors only during pass one.
3634 static void error(int severity, const char *fmt, ...)
3636 va_list arg;
3637 char buff[1024];
3639 /* If we're in a dead branch of IF or something like it, ignore the error */
3640 if (istk && istk->conds && !emitting(istk->conds->state))
3641 return;
3643 va_start(arg, fmt);
3644 vsnprintf(buff, sizeof(buff), fmt, arg);
3645 va_end(arg);
3647 if (istk && istk->mstk && istk->mstk->name)
3648 _error(severity | ERR_PASS1, "(%s:%d) %s", istk->mstk->name,
3649 istk->mstk->lineno, buff);
3650 else
3651 _error(severity | ERR_PASS1, "%s", buff);
3654 static void
3655 pp_reset(char *file, int apass, efunc errfunc, evalfunc eval,
3656 ListGen * listgen)
3658 _error = errfunc;
3659 cstk = NULL;
3660 istk = nasm_malloc(sizeof(Include));
3661 istk->next = NULL;
3662 istk->conds = NULL;
3663 istk->expansion = NULL;
3664 istk->mstk = NULL;
3665 istk->fp = fopen(file, "r");
3666 istk->fname = NULL;
3667 src_set_fname(nasm_strdup(file));
3668 src_set_linnum(0);
3669 istk->lineinc = 1;
3670 if (!istk->fp)
3671 error(ERR_FATAL | ERR_NOFILE, "unable to open input file `%s'",
3672 file);
3673 defining = NULL;
3674 init_macros();
3675 unique = 0;
3676 if (tasm_compatible_mode) {
3677 stdmacpos = stdmac;
3678 } else {
3679 stdmacpos = &stdmac[TASM_MACRO_COUNT];
3681 any_extrastdmac = (extrastdmac != NULL);
3682 list = listgen;
3683 evaluate = eval;
3684 pass = apass;
3687 static char *pp_getline(void)
3689 char *line;
3690 Token *tline;
3692 while (1) {
3694 * Fetch a tokenized line, either from the macro-expansion
3695 * buffer or from the input file.
3697 tline = NULL;
3698 while (istk->expansion && istk->expansion->finishes) {
3699 Line *l = istk->expansion;
3700 if (!l->finishes->name && l->finishes->in_progress > 1) {
3701 Line *ll;
3704 * This is a macro-end marker for a macro with no
3705 * name, which means it's not really a macro at all
3706 * but a %rep block, and the `in_progress' field is
3707 * more than 1, meaning that we still need to
3708 * repeat. (1 means the natural last repetition; 0
3709 * means termination by %exitrep.) We have
3710 * therefore expanded up to the %endrep, and must
3711 * push the whole block on to the expansion buffer
3712 * again. We don't bother to remove the macro-end
3713 * marker: we'd only have to generate another one
3714 * if we did.
3716 l->finishes->in_progress--;
3717 for (l = l->finishes->expansion; l; l = l->next) {
3718 Token *t, *tt, **tail;
3720 ll = nasm_malloc(sizeof(Line));
3721 ll->next = istk->expansion;
3722 ll->finishes = NULL;
3723 ll->first = NULL;
3724 tail = &ll->first;
3726 for (t = l->first; t; t = t->next) {
3727 if (t->text || t->type == TOK_WHITESPACE) {
3728 tt = *tail =
3729 new_Token(NULL, t->type, t->text, 0);
3730 tail = &tt->next;
3734 istk->expansion = ll;
3736 } else {
3738 * Check whether a `%rep' was started and not ended
3739 * within this macro expansion. This can happen and
3740 * should be detected. It's a fatal error because
3741 * I'm too confused to work out how to recover
3742 * sensibly from it.
3744 if (defining) {
3745 if (defining->name)
3746 error(ERR_PANIC,
3747 "defining with name in expansion");
3748 else if (istk->mstk->name)
3749 error(ERR_FATAL,
3750 "`%%rep' without `%%endrep' within"
3751 " expansion of macro `%s'",
3752 istk->mstk->name);
3756 * FIXME: investigate the relationship at this point between
3757 * istk->mstk and l->finishes
3760 MMacro *m = istk->mstk;
3761 istk->mstk = m->next_active;
3762 if (m->name) {
3764 * This was a real macro call, not a %rep, and
3765 * therefore the parameter information needs to
3766 * be freed.
3768 nasm_free(m->params);
3769 free_tlist(m->iline);
3770 nasm_free(m->paramlen);
3771 l->finishes->in_progress = FALSE;
3772 } else
3773 free_mmacro(m);
3775 istk->expansion = l->next;
3776 nasm_free(l);
3777 list->downlevel(LIST_MACRO);
3780 while (1) { /* until we get a line we can use */
3782 if (istk->expansion) { /* from a macro expansion */
3783 char *p;
3784 Line *l = istk->expansion;
3785 if (istk->mstk)
3786 istk->mstk->lineno++;
3787 tline = l->first;
3788 istk->expansion = l->next;
3789 nasm_free(l);
3790 p = detoken(tline, FALSE);
3791 list->line(LIST_MACRO, p);
3792 nasm_free(p);
3793 break;
3795 line = read_line();
3796 if (line) { /* from the current input file */
3797 line = prepreproc(line);
3798 tline = tokenize(line);
3799 nasm_free(line);
3800 break;
3803 * The current file has ended; work down the istk
3806 Include *i = istk;
3807 fclose(i->fp);
3808 if (i->conds)
3809 error(ERR_FATAL,
3810 "expected `%%endif' before end of file");
3811 /* only set line and file name if there's a next node */
3812 if (i->next) {
3813 src_set_linnum(i->lineno);
3814 nasm_free(src_set_fname(i->fname));
3816 istk = i->next;
3817 list->downlevel(LIST_INCLUDE);
3818 nasm_free(i);
3819 if (!istk)
3820 return NULL;
3825 * We must expand MMacro parameters and MMacro-local labels
3826 * _before_ we plunge into directive processing, to cope
3827 * with things like `%define something %1' such as STRUC
3828 * uses. Unless we're _defining_ a MMacro, in which case
3829 * those tokens should be left alone to go into the
3830 * definition; and unless we're in a non-emitting
3831 * condition, in which case we don't want to meddle with
3832 * anything.
3834 if (!defining && !(istk->conds && !emitting(istk->conds->state)))
3835 tline = expand_mmac_params(tline);
3838 * Check the line to see if it's a preprocessor directive.
3840 if (do_directive(tline) == DIRECTIVE_FOUND) {
3841 continue;
3842 } else if (defining) {
3844 * We're defining a multi-line macro. We emit nothing
3845 * at all, and just
3846 * shove the tokenized line on to the macro definition.
3848 Line *l = nasm_malloc(sizeof(Line));
3849 l->next = defining->expansion;
3850 l->first = tline;
3851 l->finishes = FALSE;
3852 defining->expansion = l;
3853 continue;
3854 } else if (istk->conds && !emitting(istk->conds->state)) {
3856 * We're in a non-emitting branch of a condition block.
3857 * Emit nothing at all, not even a blank line: when we
3858 * emerge from the condition we'll give a line-number
3859 * directive so we keep our place correctly.
3861 free_tlist(tline);
3862 continue;
3863 } else if (istk->mstk && !istk->mstk->in_progress) {
3865 * We're in a %rep block which has been terminated, so
3866 * we're walking through to the %endrep without
3867 * emitting anything. Emit nothing at all, not even a
3868 * blank line: when we emerge from the %rep block we'll
3869 * give a line-number directive so we keep our place
3870 * correctly.
3872 free_tlist(tline);
3873 continue;
3874 } else {
3875 tline = expand_smacro(tline);
3876 if (!expand_mmacro(tline)) {
3878 * De-tokenize the line again, and emit it.
3880 line = detoken(tline, TRUE);
3881 free_tlist(tline);
3882 break;
3883 } else {
3884 continue; /* expand_mmacro calls free_tlist */
3889 return line;
3892 static void pp_cleanup(int pass)
3894 if (defining) {
3895 error(ERR_NONFATAL, "end of file while still defining macro `%s'",
3896 defining->name);
3897 free_mmacro(defining);
3899 while (cstk)
3900 ctx_pop();
3901 free_macros();
3902 while (istk) {
3903 Include *i = istk;
3904 istk = istk->next;
3905 fclose(i->fp);
3906 nasm_free(i->fname);
3907 nasm_free(i);
3909 while (cstk)
3910 ctx_pop();
3911 if (pass == 0) {
3912 free_llist(predef);
3913 delete_Blocks();
3917 void pp_include_path(char *path)
3919 IncPath *i;
3921 i = nasm_malloc(sizeof(IncPath));
3922 i->path = path ? nasm_strdup(path) : NULL;
3923 i->next = NULL;
3925 if (ipath != NULL) {
3926 IncPath *j = ipath;
3927 while (j->next != NULL)
3928 j = j->next;
3929 j->next = i;
3930 } else {
3931 ipath = i;
3936 * added by alexfru:
3938 * This function is used to "export" the include paths, e.g.
3939 * the paths specified in the '-I' command switch.
3940 * The need for such exporting is due to the 'incbin' directive,
3941 * which includes raw binary files (unlike '%include', which
3942 * includes text source files). It would be real nice to be
3943 * able to specify paths to search for incbin'ned files also.
3944 * So, this is a simple workaround.
3946 * The function use is simple:
3948 * The 1st call (with NULL argument) returns a pointer to the 1st path
3949 * (char** type) or NULL if none include paths available.
3951 * All subsequent calls take as argument the value returned by this
3952 * function last. The return value is either the next path
3953 * (char** type) or NULL if the end of the paths list is reached.
3955 * It is maybe not the best way to do things, but I didn't want
3956 * to export too much, just one or two functions and no types or
3957 * variables exported.
3959 * Can't say I like the current situation with e.g. this path list either,
3960 * it seems to be never deallocated after creation...
3962 char **pp_get_include_path_ptr(char **pPrevPath)
3964 /* This macro returns offset of a member of a structure */
3965 #define GetMemberOffset(StructType,MemberName)\
3966 ((size_t)&((StructType*)0)->MemberName)
3967 IncPath *i;
3969 if (pPrevPath == NULL) {
3970 if (ipath != NULL)
3971 return &ipath->path;
3972 else
3973 return NULL;
3975 i = (IncPath *) ((char *)pPrevPath - GetMemberOffset(IncPath, path));
3976 i = i->next;
3977 if (i != NULL)
3978 return &i->path;
3979 else
3980 return NULL;
3981 #undef GetMemberOffset
3984 void pp_pre_include(char *fname)
3986 Token *inc, *space, *name;
3987 Line *l;
3989 name = new_Token(NULL, TOK_INTERNAL_STRING, fname, 0);
3990 space = new_Token(name, TOK_WHITESPACE, NULL, 0);
3991 inc = new_Token(space, TOK_PREPROC_ID, "%include", 0);
3993 l = nasm_malloc(sizeof(Line));
3994 l->next = predef;
3995 l->first = inc;
3996 l->finishes = FALSE;
3997 predef = l;
4000 void pp_pre_define(char *definition)
4002 Token *def, *space;
4003 Line *l;
4004 char *equals;
4006 equals = strchr(definition, '=');
4007 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4008 def = new_Token(space, TOK_PREPROC_ID, "%define", 0);
4009 if (equals)
4010 *equals = ' ';
4011 space->next = tokenize(definition);
4012 if (equals)
4013 *equals = '=';
4015 l = nasm_malloc(sizeof(Line));
4016 l->next = predef;
4017 l->first = def;
4018 l->finishes = FALSE;
4019 predef = l;
4022 void pp_pre_undefine(char *definition)
4024 Token *def, *space;
4025 Line *l;
4027 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4028 def = new_Token(space, TOK_PREPROC_ID, "%undef", 0);
4029 space->next = tokenize(definition);
4031 l = nasm_malloc(sizeof(Line));
4032 l->next = predef;
4033 l->first = def;
4034 l->finishes = FALSE;
4035 predef = l;
4039 * Added by Keith Kanios:
4041 * This function is used to assist with "runtime" preprocessor
4042 * directives. (e.g. pp_runtime("%define __BITS__ 64");)
4044 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
4045 * PASS A VALID STRING TO THIS FUNCTION!!!!!
4048 void pp_runtime(char *definition)
4050 Token *def;
4052 def = tokenize(definition);
4053 if(do_directive(def) == NO_DIRECTIVE_FOUND)
4054 free_tlist(def);
4058 void pp_extra_stdmac(const char **macros)
4060 extrastdmac = macros;
4063 static void make_tok_num(Token * tok, int32_t val)
4065 char numbuf[20];
4066 snprintf(numbuf, sizeof(numbuf), "%"PRId32"", val);
4067 tok->text = nasm_strdup(numbuf);
4068 tok->type = TOK_NUMBER;
4071 Preproc nasmpp = {
4072 pp_reset,
4073 pp_getline,
4074 pp_cleanup