1 /* preproc.c macro preprocessor for the Netwide Assembler
3 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
4 * Julian Hall. All rights reserved. The software is
5 * redistributable under the license given in the file "LICENSE"
6 * distributed in the NASM archive.
8 * initial version 18/iii/97 by Simon Tatham
11 /* Typical flow of text through preproc
13 * pp_getline gets tokenized lines, either
15 * from a macro expansion
19 * read_line gets raw text from stdmacpos, or predef, or current input file
20 * tokenize converts to tokens
23 * expand_mmac_params is used to expand %1 etc., unless a macro is being
24 * defined or a false conditional is being processed
25 * (%0, %1, %+1, %-1, %%foo
27 * do_directive checks for directives
29 * expand_smacro is used to expand single line macros
31 * expand_mmacro is used to expand multi-line macros
33 * detoken is used to convert the line back to text
56 typedef struct SMacro SMacro
;
57 typedef struct MMacro MMacro
;
58 typedef struct Context Context
;
59 typedef struct Token Token
;
60 typedef struct Blocks Blocks
;
61 typedef struct Line Line
;
62 typedef struct Include Include
;
63 typedef struct Cond Cond
;
64 typedef struct IncPath IncPath
;
67 * Note on the storage of both SMacro and MMacros: the hash table
68 * indexes them case-insensitively, and we then have to go through a
69 * linked list of potential case aliases (and, for MMacros, parameter
70 * ranges); this is to preserve the matching semantics of the earlier
71 * code. If the number of case aliases for a specific macro is a
72 * performance issue, you may want to reconsider your coding style.
76 * Store the definition of a single-line macro.
88 * Store the definition of a multi-line macro. This is also used to
89 * store the interiors of `%rep...%endrep' blocks, which are
90 * effectively self-re-invoking multi-line macros which simply
91 * don't have a name or bother to appear in the hash tables. %rep
92 * blocks are signified by having a NULL `name' field.
94 * In a MMacro describing a `%rep' block, the `in_progress' field
95 * isn't merely boolean, but gives the number of repeats left to
98 * The `next' field is used for storing MMacros in hash tables; the
99 * `next_active' field is for stacking them on istk entries.
101 * When a MMacro is being expanded, `params', `iline', `nparam',
102 * `paramlen', `rotate' and `unique' are local to the invocation.
107 int nparam_min
, nparam_max
;
109 bool plus
; /* is the last parameter greedy? */
110 bool nolist
; /* is this macro listing-inhibited? */
112 Token
*dlist
; /* All defaults as one list */
113 Token
**defaults
; /* Parameter default pointers */
114 int ndefs
; /* number of default parameters */
118 MMacro
*rep_nest
; /* used for nesting %rep */
119 Token
**params
; /* actual parameters */
120 Token
*iline
; /* invocation line */
121 unsigned int nparam
, rotate
;
124 int lineno
; /* Current line number on expansion */
128 * The context stack is composed of a linked list of these.
133 struct hash_table localmac
;
138 * This is the internal form which we break input lines up into.
139 * Typically stored in linked lists.
141 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
142 * necessarily used as-is, but is intended to denote the number of
143 * the substituted parameter. So in the definition
145 * %define a(x,y) ( (x) & ~(y) )
147 * the token representing `x' will have its type changed to
148 * TOK_SMAC_PARAM, but the one representing `y' will be
151 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
152 * which doesn't need quotes around it. Used in the pre-include
153 * mechanism as an alternative to trying to find a sensible type of
154 * quote to use on the filename we were passed.
157 TOK_NONE
= 0, TOK_WHITESPACE
, TOK_COMMENT
, TOK_ID
,
158 TOK_PREPROC_ID
, TOK_STRING
,
159 TOK_NUMBER
, TOK_FLOAT
, TOK_SMAC_END
, TOK_OTHER
,
161 TOK_PREPROC_Q
, TOK_PREPROC_QQ
,
163 TOK_INDIRECT
, /* %[...] */
164 TOK_SMAC_PARAM
, /* MUST BE LAST IN THE LIST!!! */
165 TOK_MAX
= INT_MAX
/* Keep compiler from reducing the range */
172 SMacro
*mac
; /* associated macro for TOK_SMAC_END */
173 size_t len
; /* scratch length field */
174 } a
; /* Auxiliary data */
175 enum pp_token_type type
;
179 * Multi-line macro definitions are stored as a linked list of
180 * these, which is essentially a container to allow several linked
183 * Note that in this module, linked lists are treated as stacks
184 * wherever possible. For this reason, Lines are _pushed_ on to the
185 * `expansion' field in MMacro structures, so that the linked list,
186 * if walked, would give the macro lines in reverse order; this
187 * means that we can walk the list when expanding a macro, and thus
188 * push the lines on to the `expansion' field in _istk_ in reverse
189 * order (so that when popped back off they are in the right
190 * order). It may seem cockeyed, and it relies on my design having
191 * an even number of steps in, but it works...
193 * Some of these structures, rather than being actual lines, are
194 * markers delimiting the end of the expansion of a given macro.
195 * This is for use in the cycle-tracking and %rep-handling code.
196 * Such structures have `finishes' non-NULL, and `first' NULL. All
197 * others have `finishes' NULL, but `first' may still be NULL if
207 * To handle an arbitrary level of file inclusion, we maintain a
208 * stack (ie linked list) of these things.
217 MMacro
*mstk
; /* stack of active macros/reps */
221 * Include search path. This is simply a list of strings which get
222 * prepended, in turn, to the name of an include file, in an
223 * attempt to find the file if it's not in the current directory.
231 * Conditional assembly: we maintain a separate stack of these for
232 * each level of file inclusion. (The only reason we keep the
233 * stacks separate is to ensure that a stray `%endif' in a file
234 * included from within the true branch of a `%if' won't terminate
235 * it and cause confusion: instead, rightly, it'll cause an error.)
243 * These states are for use just after %if or %elif: IF_TRUE
244 * means the condition has evaluated to truth so we are
245 * currently emitting, whereas IF_FALSE means we are not
246 * currently emitting but will start doing so if a %else comes
247 * up. In these states, all directives are admissible: %elif,
248 * %else and %endif. (And of course %if.)
250 COND_IF_TRUE
, COND_IF_FALSE
,
252 * These states come up after a %else: ELSE_TRUE means we're
253 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
254 * any %elif or %else will cause an error.
256 COND_ELSE_TRUE
, COND_ELSE_FALSE
,
258 * These states mean that we're not emitting now, and also that
259 * nothing until %endif will be emitted at all. COND_DONE is
260 * used when we've had our moment of emission
261 * and have now started seeing %elifs. COND_NEVER is used when
262 * the condition construct in question is contained within a
263 * non-emitting branch of a larger condition construct,
264 * or if there is an error.
266 COND_DONE
, COND_NEVER
268 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
271 * These defines are used as the possible return values for do_directive
273 #define NO_DIRECTIVE_FOUND 0
274 #define DIRECTIVE_FOUND 1
277 * Condition codes. Note that we use c_ prefix not C_ because C_ is
278 * used in nasm.h for the "real" condition codes. At _this_ level,
279 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
280 * ones, so we need a different enum...
282 static const char * const conditions
[] = {
283 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
284 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
285 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
288 c_A
, c_AE
, c_B
, c_BE
, c_C
, c_CXZ
, c_E
, c_ECXZ
, c_G
, c_GE
, c_L
, c_LE
,
289 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, c_NE
, c_NG
, c_NGE
, c_NL
, c_NLE
, c_NO
,
290 c_NP
, c_NS
, c_NZ
, c_O
, c_P
, c_PE
, c_PO
, c_RCXZ
, c_S
, c_Z
,
293 static const enum pp_conds inverse_ccs
[] = {
294 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, -1, c_NE
, -1, c_NG
, c_NGE
, c_NL
, c_NLE
,
295 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
,
296 c_Z
, c_NO
, c_NP
, c_PO
, c_PE
, -1, c_NS
, c_NZ
302 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
303 static int is_condition(enum preproc_token arg
)
305 return PP_IS_COND(arg
) || (arg
== PP_ELSE
) || (arg
== PP_ENDIF
);
308 /* For TASM compatibility we need to be able to recognise TASM compatible
309 * conditional compilation directives. Using the NASM pre-processor does
310 * not work, so we look for them specifically from the following list and
311 * then jam in the equivalent NASM directive into the input stream.
315 TM_ARG
, TM_ELIF
, TM_ELSE
, TM_ENDIF
, TM_IF
, TM_IFDEF
, TM_IFDIFI
,
316 TM_IFNDEF
, TM_INCLUDE
, TM_LOCAL
319 static const char * const tasm_directives
[] = {
320 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
321 "ifndef", "include", "local"
324 static int StackSize
= 4;
325 static char *StackPointer
= "ebp";
326 static int ArgOffset
= 8;
327 static int LocalOffset
= 0;
329 static Context
*cstk
;
330 static Include
*istk
;
331 static IncPath
*ipath
= NULL
;
333 static efunc _error
; /* Pointer to client-provided error reporting function */
334 static evalfunc evaluate
;
336 static int pass
; /* HACK: pass 0 = generate dependencies only */
337 static StrList
**dephead
, **deptail
; /* Dependency list */
339 static uint64_t unique
; /* unique identifier numbers */
341 static Line
*predef
= NULL
;
342 static bool do_predef
;
344 static ListGen
*list
;
347 * The current set of multi-line macros we have defined.
349 static struct hash_table mmacros
;
352 * The current set of single-line macros we have defined.
354 static struct hash_table smacros
;
357 * The multi-line macro we are currently defining, or the %rep
358 * block we are currently reading, if any.
360 static MMacro
*defining
;
362 static uint64_t nested_mac_count
;
363 static uint64_t nested_rep_count
;
366 * The number of macro parameters to allocate space for at a time.
368 #define PARAM_DELTA 16
371 * The standard macro set: defined in macros.c in the array nasm_stdmac.
372 * This gives our position in the macro set, when we're processing it.
374 static macros_t
*stdmacpos
;
377 * The extra standard macros that come from the object format, if
380 static macros_t
*extrastdmac
= NULL
;
381 static bool any_extrastdmac
;
384 * Tokens are allocated in blocks to improve speed
386 #define TOKEN_BLOCKSIZE 4096
387 static Token
*freeTokens
= NULL
;
393 static Blocks blocks
= { NULL
, NULL
};
396 * Forward declarations.
398 static Token
*expand_mmac_params(Token
* tline
);
399 static Token
*expand_smacro(Token
* tline
);
400 static Token
*expand_id(Token
* tline
);
401 static Context
*get_ctx(const char *name
, const char **namep
,
403 static void make_tok_num(Token
* tok
, int64_t val
);
404 static void error(int severity
, const char *fmt
, ...);
405 static void error_precond(int severity
, const char *fmt
, ...);
406 static void *new_Block(size_t size
);
407 static void delete_Blocks(void);
408 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
409 const char *text
, int txtlen
);
410 static Token
*delete_Token(Token
* t
);
413 * Macros for safe checking of token pointers, avoid *(NULL)
415 #define tok_type_(x,t) ((x) && (x)->type == (t))
416 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
417 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
418 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
420 /* Handle TASM specific directives, which do not contain a % in
421 * front of them. We do it here because I could not find any other
422 * place to do it for the moment, and it is a hack (ideally it would
423 * be nice to be able to use the NASM pre-processor to do it).
425 static char *check_tasm_directive(char *line
)
427 int32_t i
, j
, k
, m
, len
;
428 char *p
= line
, *oldline
, oldchar
;
430 /* Skip whitespace */
431 while (nasm_isspace(*p
) && *p
!= 0)
434 /* Binary search for the directive name */
436 j
= elements(tasm_directives
);
438 while (!nasm_isspace(p
[len
]) && p
[len
] != 0)
445 m
= nasm_stricmp(p
, tasm_directives
[k
]);
447 /* We have found a directive, so jam a % in front of it
448 * so that NASM will then recognise it as one if it's own.
453 line
= nasm_malloc(len
+ 2);
455 if (k
== TM_IFDIFI
) {
457 * NASM does not recognise IFDIFI, so we convert
458 * it to %if 0. This is not used in NASM
459 * compatible code, but does need to parse for the
460 * TASM macro package.
462 strcpy(line
+ 1, "if 0");
464 memcpy(line
+ 1, p
, len
+ 1);
479 * The pre-preprocessing stage... This function translates line
480 * number indications as they emerge from GNU cpp (`# lineno "file"
481 * flags') into NASM preprocessor line number indications (`%line
484 static char *prepreproc(char *line
)
487 char *fname
, *oldline
;
489 if (line
[0] == '#' && line
[1] == ' ') {
492 lineno
= atoi(fname
);
493 fname
+= strspn(fname
, "0123456789 ");
496 fnlen
= strcspn(fname
, "\"");
497 line
= nasm_malloc(20 + fnlen
);
498 snprintf(line
, 20 + fnlen
, "%%line %d %.*s", lineno
, fnlen
, fname
);
501 if (tasm_compatible_mode
)
502 return check_tasm_directive(line
);
507 * Free a linked list of tokens.
509 static void free_tlist(Token
* list
)
512 list
= delete_Token(list
);
517 * Free a linked list of lines.
519 static void free_llist(Line
* list
)
525 free_tlist(l
->first
);
533 static void free_mmacro(MMacro
* m
)
536 free_tlist(m
->dlist
);
537 nasm_free(m
->defaults
);
538 free_llist(m
->expansion
);
543 * Free all currently defined macros, and free the hash tables
545 static void free_smacro_table(struct hash_table
*smt
)
549 struct hash_tbl_node
*it
= NULL
;
551 while ((s
= hash_iterate(smt
, &it
, &key
)) != NULL
) {
552 nasm_free((void *)key
);
554 SMacro
*ns
= s
->next
;
556 free_tlist(s
->expansion
);
564 static void free_mmacro_table(struct hash_table
*mmt
)
568 struct hash_tbl_node
*it
= NULL
;
571 while ((m
= hash_iterate(mmt
, &it
, &key
)) != NULL
) {
572 nasm_free((void *)key
);
574 MMacro
*nm
= m
->next
;
582 static void free_macros(void)
584 free_smacro_table(&smacros
);
585 free_mmacro_table(&mmacros
);
589 * Initialize the hash tables
591 static void init_macros(void)
593 hash_init(&smacros
, HASH_LARGE
);
594 hash_init(&mmacros
, HASH_LARGE
);
598 * Pop the context stack.
600 static void ctx_pop(void)
605 free_smacro_table(&c
->localmac
);
611 * Search for a key in the hash index; adding it if necessary
612 * (in which case we initialize the data pointer to NULL.)
615 hash_findi_add(struct hash_table
*hash
, const char *str
)
617 struct hash_insert hi
;
621 r
= hash_findi(hash
, str
, &hi
);
625 strx
= nasm_strdup(str
); /* Use a more efficient allocator here? */
626 return hash_add(&hi
, strx
, NULL
);
630 * Like hash_findi, but returns the data element rather than a pointer
631 * to it. Used only when not adding a new element, hence no third
635 hash_findix(struct hash_table
*hash
, const char *str
)
639 p
= hash_findi(hash
, str
, NULL
);
640 return p
? *p
: NULL
;
643 #define BUF_DELTA 512
645 * Read a line from the top file in istk, handling multiple CR/LFs
646 * at the end of the line read, and handling spurious ^Zs. Will
647 * return lines from the standard macro set if this has not already
650 static char *read_line(void)
652 char *buffer
, *p
, *q
;
653 int bufsize
, continued_count
;
657 const unsigned char *p
= stdmacpos
;
662 len
+= pp_directives_len
[c
-0x80]+1;
666 ret
= nasm_malloc(len
+1);
668 while ((c
= *stdmacpos
++)) {
670 memcpy(q
, pp_directives
[c
-0x80], pp_directives_len
[c
-0x80]);
671 q
+= pp_directives_len
[c
-0x80];
681 /* This was the last of the standard macro chain... */
683 if (any_extrastdmac
) {
684 stdmacpos
= extrastdmac
;
685 any_extrastdmac
= false;
686 } else if (do_predef
) {
688 Token
*head
, **tail
, *t
;
691 * Nasty hack: here we push the contents of
692 * `predef' on to the top-level expansion stack,
693 * since this is the most convenient way to
694 * implement the pre-include and pre-define
697 for (pd
= predef
; pd
; pd
= pd
->next
) {
700 for (t
= pd
->first
; t
; t
= t
->next
) {
701 *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
702 tail
= &(*tail
)->next
;
704 l
= nasm_malloc(sizeof(Line
));
705 l
->next
= istk
->expansion
;
717 buffer
= nasm_malloc(BUF_DELTA
);
721 q
= fgets(p
, bufsize
- (p
- buffer
), istk
->fp
);
725 if (p
> buffer
&& p
[-1] == '\n') {
726 /* Convert backslash-CRLF line continuation sequences into
727 nothing at all (for DOS and Windows) */
728 if (((p
- 2) > buffer
) && (p
[-3] == '\\') && (p
[-2] == '\r')) {
733 /* Also convert backslash-LF line continuation sequences into
734 nothing at all (for Unix) */
735 else if (((p
- 1) > buffer
) && (p
[-2] == '\\')) {
743 if (p
- buffer
> bufsize
- 10) {
744 int32_t offset
= p
- buffer
;
745 bufsize
+= BUF_DELTA
;
746 buffer
= nasm_realloc(buffer
, bufsize
);
747 p
= buffer
+ offset
; /* prevent stale-pointer problems */
751 if (!q
&& p
== buffer
) {
756 src_set_linnum(src_get_linnum() + istk
->lineinc
+
757 (continued_count
* istk
->lineinc
));
760 * Play safe: remove CRs as well as LFs, if any of either are
761 * present at the end of the line.
763 while (--p
>= buffer
&& (*p
== '\n' || *p
== '\r'))
767 * Handle spurious ^Z, which may be inserted into source files
768 * by some file transfer utilities.
770 buffer
[strcspn(buffer
, "\032")] = '\0';
772 list
->line(LIST_READ
, buffer
);
778 * Tokenize a line of text. This is a very simple process since we
779 * don't need to parse the value out of e.g. numeric tokens: we
780 * simply split one string into many.
782 static Token
*tokenize(char *line
)
785 enum pp_token_type type
;
787 Token
*t
, **tail
= &list
;
793 if (*p
== '+' && !nasm_isdigit(p
[1])) {
796 } else if (nasm_isdigit(*p
) ||
797 ((*p
== '-' || *p
== '+') && nasm_isdigit(p
[1]))) {
801 while (nasm_isdigit(*p
));
802 type
= TOK_PREPROC_ID
;
803 } else if (*p
== '{') {
805 while (*p
&& *p
!= '}') {
812 type
= TOK_PREPROC_ID
;
813 } else if (*p
== '[') {
815 line
+= 2; /* Skip the leading %[ */
817 while (lvl
&& (c
= *p
++)) {
829 p
= nasm_skip_string(p
)+1;
839 error(ERR_NONFATAL
, "unterminated %[ construct");
841 } else if (*p
== '?') {
842 type
= TOK_PREPROC_Q
; /* %? */
845 type
= TOK_PREPROC_QQ
; /* %?? */
848 } else if (isidchar(*p
) ||
849 ((*p
== '!' || *p
== '%' || *p
== '$') &&
854 while (isidchar(*p
));
855 type
= TOK_PREPROC_ID
;
861 } else if (isidstart(*p
) || (*p
== '$' && isidstart(p
[1]))) {
864 while (*p
&& isidchar(*p
))
866 } else if (*p
== '\'' || *p
== '"' || *p
== '`') {
871 p
= nasm_skip_string(p
);
876 error(ERR_WARNING
|ERR_PASS1
, "unterminated string");
877 /* Handling unterminated strings by UNV */
880 } else if (p
[0] == '$' && p
[1] == '$') {
881 type
= TOK_OTHER
; /* TOKEN_BASE */
883 } else if (isnumstart(*p
)) {
885 bool is_float
= false;
901 if (!is_hex
&& (c
== 'e' || c
== 'E')) {
903 if (*p
== '+' || *p
== '-') {
904 /* e can only be followed by +/- if it is either a
905 prefixed hex number or a floating-point number */
909 } else if (c
== 'H' || c
== 'h' || c
== 'X' || c
== 'x') {
911 } else if (c
== 'P' || c
== 'p') {
913 if (*p
== '+' || *p
== '-')
915 } else if (isnumchar(c
) || c
== '_')
918 /* we need to deal with consequences of the legacy
919 parser, like "1.nolist" being two tokens
920 (TOK_NUMBER, TOK_ID) here; at least give it
921 a shot for now. In the future, we probably need
922 a flex-based scanner with proper pattern matching
923 to do it as well as it can be done. Nothing in
924 the world is going to help the person who wants
925 0x123.p16 interpreted as two tokens, though. */
930 if (nasm_isdigit(*r
) || (is_hex
&& nasm_isxdigit(*r
)) ||
931 (!is_hex
&& (*r
== 'e' || *r
== 'E')) ||
932 (*r
== 'p' || *r
== 'P')) {
936 break; /* Terminate the token */
940 p
--; /* Point to first character beyond number */
942 if (p
== line
+1 && *line
== '$') {
943 type
= TOK_OTHER
; /* TOKEN_HERE */
945 if (has_e
&& !is_hex
) {
946 /* 1e13 is floating-point, but 1e13h is not */
950 type
= is_float
? TOK_FLOAT
: TOK_NUMBER
;
952 } else if (nasm_isspace(*p
)) {
953 type
= TOK_WHITESPACE
;
955 while (*p
&& nasm_isspace(*p
))
958 * Whitespace just before end-of-line is discarded by
959 * pretending it's a comment; whitespace just before a
960 * comment gets lumped into the comment.
962 if (!*p
|| *p
== ';') {
967 } else if (*p
== ';') {
973 * Anything else is an operator of some kind. We check
974 * for all the double-character operators (>>, <<, //,
975 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
976 * else is a single-character operator.
979 if ((p
[0] == '>' && p
[1] == '>') ||
980 (p
[0] == '<' && p
[1] == '<') ||
981 (p
[0] == '/' && p
[1] == '/') ||
982 (p
[0] == '<' && p
[1] == '=') ||
983 (p
[0] == '>' && p
[1] == '=') ||
984 (p
[0] == '=' && p
[1] == '=') ||
985 (p
[0] == '!' && p
[1] == '=') ||
986 (p
[0] == '<' && p
[1] == '>') ||
987 (p
[0] == '&' && p
[1] == '&') ||
988 (p
[0] == '|' && p
[1] == '|') ||
989 (p
[0] == '^' && p
[1] == '^')) {
995 /* Handling unterminated string by UNV */
998 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
999 t->text[p-line] = *line;
1003 if (type
!= TOK_COMMENT
) {
1004 *tail
= t
= new_Token(NULL
, type
, line
, p
- line
);
1013 * this function allocates a new managed block of memory and
1014 * returns a pointer to the block. The managed blocks are
1015 * deleted only all at once by the delete_Blocks function.
1017 static void *new_Block(size_t size
)
1019 Blocks
*b
= &blocks
;
1021 /* first, get to the end of the linked list */
1024 /* now allocate the requested chunk */
1025 b
->chunk
= nasm_malloc(size
);
1027 /* now allocate a new block for the next request */
1028 b
->next
= nasm_malloc(sizeof(Blocks
));
1029 /* and initialize the contents of the new block */
1030 b
->next
->next
= NULL
;
1031 b
->next
->chunk
= NULL
;
1036 * this function deletes all managed blocks of memory
1038 static void delete_Blocks(void)
1040 Blocks
*a
, *b
= &blocks
;
1043 * keep in mind that the first block, pointed to by blocks
1044 * is a static and not dynamically allocated, so we don't
1049 nasm_free(b
->chunk
);
1058 * this function creates a new Token and passes a pointer to it
1059 * back to the caller. It sets the type and text elements, and
1060 * also the a.mac and next elements to NULL.
1062 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
1063 const char *text
, int txtlen
)
1068 if (freeTokens
== NULL
) {
1069 freeTokens
= (Token
*) new_Block(TOKEN_BLOCKSIZE
* sizeof(Token
));
1070 for (i
= 0; i
< TOKEN_BLOCKSIZE
- 1; i
++)
1071 freeTokens
[i
].next
= &freeTokens
[i
+ 1];
1072 freeTokens
[i
].next
= NULL
;
1075 freeTokens
= t
->next
;
1079 if (type
== TOK_WHITESPACE
|| text
== NULL
) {
1083 txtlen
= strlen(text
);
1084 t
->text
= nasm_malloc(txtlen
+1);
1085 memcpy(t
->text
, text
, txtlen
);
1086 t
->text
[txtlen
] = '\0';
1091 static Token
*delete_Token(Token
* t
)
1093 Token
*next
= t
->next
;
1095 t
->next
= freeTokens
;
1101 * Convert a line of tokens back into text.
1102 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1103 * will be transformed into ..@ctxnum.xxx
1105 static char *detoken(Token
* tlist
, bool expand_locals
)
1113 for (t
= tlist
; t
; t
= t
->next
) {
1114 if (t
->type
== TOK_PREPROC_ID
&& t
->text
[1] == '!') {
1115 char *p
= getenv(t
->text
+ 2);
1118 t
->text
= nasm_strdup(p
);
1122 /* Expand local macros here and not during preprocessing */
1123 if (expand_locals
&&
1124 t
->type
== TOK_PREPROC_ID
&& t
->text
&&
1125 t
->text
[0] == '%' && t
->text
[1] == '$') {
1128 Context
*ctx
= get_ctx(t
->text
, &q
, false);
1131 snprintf(buffer
, sizeof(buffer
), "..@%"PRIu32
".", ctx
->number
);
1132 p
= nasm_strcat(buffer
, q
);
1137 if (t
->type
== TOK_WHITESPACE
) {
1139 } else if (t
->text
) {
1140 len
+= strlen(t
->text
);
1143 p
= line
= nasm_malloc(len
+ 1);
1144 for (t
= tlist
; t
; t
= t
->next
) {
1145 if (t
->type
== TOK_WHITESPACE
) {
1147 } else if (t
->text
) {
1158 * A scanner, suitable for use by the expression evaluator, which
1159 * operates on a line of Tokens. Expects a pointer to a pointer to
1160 * the first token in the line to be passed in as its private_data
1163 * FIX: This really needs to be unified with stdscan.
1165 static int ppscan(void *private_data
, struct tokenval
*tokval
)
1167 Token
**tlineptr
= private_data
;
1169 char ourcopy
[MAX_KEYWORD
+1], *p
, *r
, *s
;
1173 *tlineptr
= tline
? tline
->next
: NULL
;
1175 while (tline
&& (tline
->type
== TOK_WHITESPACE
||
1176 tline
->type
== TOK_COMMENT
));
1179 return tokval
->t_type
= TOKEN_EOS
;
1181 tokval
->t_charptr
= tline
->text
;
1183 if (tline
->text
[0] == '$' && !tline
->text
[1])
1184 return tokval
->t_type
= TOKEN_HERE
;
1185 if (tline
->text
[0] == '$' && tline
->text
[1] == '$' && !tline
->text
[2])
1186 return tokval
->t_type
= TOKEN_BASE
;
1188 if (tline
->type
== TOK_ID
) {
1189 p
= tokval
->t_charptr
= tline
->text
;
1191 tokval
->t_charptr
++;
1192 return tokval
->t_type
= TOKEN_ID
;
1195 for (r
= p
, s
= ourcopy
; *r
; r
++) {
1196 if (r
>= p
+MAX_KEYWORD
)
1197 return tokval
->t_type
= TOKEN_ID
; /* Not a keyword */
1198 *s
++ = nasm_tolower(*r
);
1201 /* right, so we have an identifier sitting in temp storage. now,
1202 * is it actually a register or instruction name, or what? */
1203 return nasm_token_hash(ourcopy
, tokval
);
1206 if (tline
->type
== TOK_NUMBER
) {
1208 tokval
->t_integer
= readnum(tline
->text
, &rn_error
);
1209 tokval
->t_charptr
= tline
->text
;
1211 return tokval
->t_type
= TOKEN_ERRNUM
;
1213 return tokval
->t_type
= TOKEN_NUM
;
1216 if (tline
->type
== TOK_FLOAT
) {
1217 return tokval
->t_type
= TOKEN_FLOAT
;
1220 if (tline
->type
== TOK_STRING
) {
1223 bq
= tline
->text
[0];
1224 tokval
->t_charptr
= tline
->text
;
1225 tokval
->t_inttwo
= nasm_unquote(tline
->text
, &ep
);
1227 if (ep
[0] != bq
|| ep
[1] != '\0')
1228 return tokval
->t_type
= TOKEN_ERRSTR
;
1230 return tokval
->t_type
= TOKEN_STR
;
1233 if (tline
->type
== TOK_OTHER
) {
1234 if (!strcmp(tline
->text
, "<<"))
1235 return tokval
->t_type
= TOKEN_SHL
;
1236 if (!strcmp(tline
->text
, ">>"))
1237 return tokval
->t_type
= TOKEN_SHR
;
1238 if (!strcmp(tline
->text
, "//"))
1239 return tokval
->t_type
= TOKEN_SDIV
;
1240 if (!strcmp(tline
->text
, "%%"))
1241 return tokval
->t_type
= TOKEN_SMOD
;
1242 if (!strcmp(tline
->text
, "=="))
1243 return tokval
->t_type
= TOKEN_EQ
;
1244 if (!strcmp(tline
->text
, "<>"))
1245 return tokval
->t_type
= TOKEN_NE
;
1246 if (!strcmp(tline
->text
, "!="))
1247 return tokval
->t_type
= TOKEN_NE
;
1248 if (!strcmp(tline
->text
, "<="))
1249 return tokval
->t_type
= TOKEN_LE
;
1250 if (!strcmp(tline
->text
, ">="))
1251 return tokval
->t_type
= TOKEN_GE
;
1252 if (!strcmp(tline
->text
, "&&"))
1253 return tokval
->t_type
= TOKEN_DBL_AND
;
1254 if (!strcmp(tline
->text
, "^^"))
1255 return tokval
->t_type
= TOKEN_DBL_XOR
;
1256 if (!strcmp(tline
->text
, "||"))
1257 return tokval
->t_type
= TOKEN_DBL_OR
;
1261 * We have no other options: just return the first character of
1264 return tokval
->t_type
= tline
->text
[0];
1268 * Compare a string to the name of an existing macro; this is a
1269 * simple wrapper which calls either strcmp or nasm_stricmp
1270 * depending on the value of the `casesense' parameter.
1272 static int mstrcmp(const char *p
, const char *q
, bool casesense
)
1274 return casesense
? strcmp(p
, q
) : nasm_stricmp(p
, q
);
1278 * Compare a string to the name of an existing macro; this is a
1279 * simple wrapper which calls either strcmp or nasm_stricmp
1280 * depending on the value of the `casesense' parameter.
1282 static int mmemcmp(const char *p
, const char *q
, size_t l
, bool casesense
)
1284 return casesense
? memcmp(p
, q
, l
) : nasm_memicmp(p
, q
, l
);
1288 * Return the Context structure associated with a %$ token. Return
1289 * NULL, having _already_ reported an error condition, if the
1290 * context stack isn't deep enough for the supplied number of $
1292 * If all_contexts == true, contexts that enclose current are
1293 * also scanned for such smacro, until it is found; if not -
1294 * only the context that directly results from the number of $'s
1295 * in variable's name.
1297 * If "namep" is non-NULL, set it to the pointer to the macro name
1298 * tail, i.e. the part beyond %$...
1300 static Context
*get_ctx(const char *name
, const char **namep
,
1310 if (!name
|| name
[0] != '%' || name
[1] != '$')
1314 error(ERR_NONFATAL
, "`%s': context stack is empty", name
);
1321 while (ctx
&& *name
== '$') {
1327 error(ERR_NONFATAL
, "`%s': context stack is only"
1328 " %d level%s deep", name
, i
, (i
== 1 ? "" : "s"));
1339 /* Search for this smacro in found context */
1340 m
= hash_findix(&ctx
->localmac
, name
);
1342 if (!mstrcmp(m
->name
, name
, m
->casesense
))
1353 * Check to see if a file is already in a string list
1355 static bool in_list(const StrList
*list
, const char *str
)
1358 if (!strcmp(list
->str
, str
))
1366 * Open an include file. This routine must always return a valid
1367 * file pointer if it returns - it's responsible for throwing an
1368 * ERR_FATAL and bombing out completely if not. It should also try
1369 * the include path one by one until it finds the file or reaches
1370 * the end of the path.
1372 static FILE *inc_fopen(const char *file
, StrList
**dhead
, StrList
***dtail
,
1377 IncPath
*ip
= ipath
;
1378 int len
= strlen(file
);
1379 size_t prefix_len
= 0;
1383 sl
= nasm_malloc(prefix_len
+len
+1+sizeof sl
->next
);
1384 memcpy(sl
->str
, prefix
, prefix_len
);
1385 memcpy(sl
->str
+prefix_len
, file
, len
+1);
1386 fp
= fopen(sl
->str
, "r");
1387 if (fp
&& dhead
&& !in_list(*dhead
, sl
->str
)) {
1405 prefix_len
= strlen(prefix
);
1407 /* -MG given and file not found */
1408 if (dhead
&& !in_list(*dhead
, file
)) {
1409 sl
= nasm_malloc(len
+1+sizeof sl
->next
);
1411 strcpy(sl
->str
, file
);
1419 error(ERR_FATAL
, "unable to open include file `%s'", file
);
1420 return NULL
; /* never reached - placate compilers */
1424 * Determine if we should warn on defining a single-line macro of
1425 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1426 * return true if _any_ single-line macro of that name is defined.
1427 * Otherwise, will return true if a single-line macro with either
1428 * `nparam' or no parameters is defined.
1430 * If a macro with precisely the right number of parameters is
1431 * defined, or nparam is -1, the address of the definition structure
1432 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1433 * is NULL, no action will be taken regarding its contents, and no
1436 * Note that this is also called with nparam zero to resolve
1439 * If you already know which context macro belongs to, you can pass
1440 * the context pointer as first parameter; if you won't but name begins
1441 * with %$ the context will be automatically computed. If all_contexts
1442 * is true, macro will be searched in outer contexts as well.
1445 smacro_defined(Context
* ctx
, const char *name
, int nparam
, SMacro
** defn
,
1448 struct hash_table
*smtbl
;
1452 smtbl
= &ctx
->localmac
;
1453 } else if (name
[0] == '%' && name
[1] == '$') {
1455 ctx
= get_ctx(name
, &name
, false);
1457 return false; /* got to return _something_ */
1458 smtbl
= &ctx
->localmac
;
1462 m
= (SMacro
*) hash_findix(smtbl
, name
);
1465 if (!mstrcmp(m
->name
, name
, m
->casesense
&& nocase
) &&
1466 (nparam
<= 0 || m
->nparam
== 0 || nparam
== (int) m
->nparam
)) {
1468 if (nparam
== (int) m
->nparam
|| nparam
== -1)
1482 * Count and mark off the parameters in a multi-line macro call.
1483 * This is called both from within the multi-line macro expansion
1484 * code, and also to mark off the default parameters when provided
1485 * in a %macro definition line.
1487 static void count_mmac_params(Token
* t
, int *nparam
, Token
*** params
)
1489 int paramsize
, brace
;
1491 *nparam
= paramsize
= 0;
1494 /* +1: we need space for the final NULL */
1495 if (*nparam
+1 >= paramsize
) {
1496 paramsize
+= PARAM_DELTA
;
1497 *params
= nasm_realloc(*params
, sizeof(**params
) * paramsize
);
1501 if (tok_is_(t
, "{"))
1503 (*params
)[(*nparam
)++] = t
;
1504 while (tok_isnt_(t
, brace
? "}" : ","))
1506 if (t
) { /* got a comma/brace */
1510 * Now we've found the closing brace, look further
1514 if (tok_isnt_(t
, ",")) {
1516 "braces do not enclose all of macro parameter");
1517 while (tok_isnt_(t
, ","))
1521 t
= t
->next
; /* eat the comma */
1528 * Determine whether one of the various `if' conditions is true or
1531 * We must free the tline we get passed.
1533 static bool if_condition(Token
* tline
, enum preproc_token ct
)
1535 enum pp_conditional i
= PP_COND(ct
);
1537 Token
*t
, *tt
, **tptr
, *origline
;
1538 struct tokenval tokval
;
1540 enum pp_token_type needtype
;
1546 j
= false; /* have we matched yet? */
1551 if (tline
->type
!= TOK_ID
) {
1553 "`%s' expects context identifiers", pp_directives
[ct
]);
1554 free_tlist(origline
);
1557 if (cstk
&& cstk
->name
&& !nasm_stricmp(tline
->text
, cstk
->name
))
1559 tline
= tline
->next
;
1564 j
= false; /* have we matched yet? */
1567 if (!tline
|| (tline
->type
!= TOK_ID
&&
1568 (tline
->type
!= TOK_PREPROC_ID
||
1569 tline
->text
[1] != '$'))) {
1571 "`%s' expects macro identifiers", pp_directives
[ct
]);
1574 if (smacro_defined(NULL
, tline
->text
, 0, NULL
, true))
1576 tline
= tline
->next
;
1582 tline
= expand_smacro(tline
);
1584 while (tok_isnt_(tt
, ","))
1588 "`%s' expects two comma-separated arguments",
1593 j
= true; /* assume equality unless proved not */
1594 while ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) && tt
) {
1595 if (tt
->type
== TOK_OTHER
&& !strcmp(tt
->text
, ",")) {
1596 error(ERR_NONFATAL
, "`%s': more than one comma on line",
1600 if (t
->type
== TOK_WHITESPACE
) {
1604 if (tt
->type
== TOK_WHITESPACE
) {
1608 if (tt
->type
!= t
->type
) {
1609 j
= false; /* found mismatching tokens */
1612 /* When comparing strings, need to unquote them first */
1613 if (t
->type
== TOK_STRING
) {
1614 size_t l1
= nasm_unquote(t
->text
, NULL
);
1615 size_t l2
= nasm_unquote(tt
->text
, NULL
);
1621 if (mmemcmp(t
->text
, tt
->text
, l1
, i
== PPC_IFIDN
)) {
1625 } else if (mstrcmp(tt
->text
, t
->text
, i
== PPC_IFIDN
) != 0) {
1626 j
= false; /* found mismatching tokens */
1633 if ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) || tt
)
1634 j
= false; /* trailing gunk on one end or other */
1640 MMacro searching
, *mmac
;
1643 tline
= expand_id(tline
);
1644 if (!tok_type_(tline
, TOK_ID
)) {
1646 "`%s' expects a macro name", pp_directives
[ct
]);
1649 searching
.name
= nasm_strdup(tline
->text
);
1650 searching
.casesense
= true;
1651 searching
.plus
= false;
1652 searching
.nolist
= false;
1653 searching
.in_progress
= 0;
1654 searching
.rep_nest
= NULL
;
1655 searching
.nparam_min
= 0;
1656 searching
.nparam_max
= INT_MAX
;
1657 tline
= expand_smacro(tline
->next
);
1660 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
1662 "`%s' expects a parameter count or nothing",
1665 searching
.nparam_min
= searching
.nparam_max
=
1666 readnum(tline
->text
, &j
);
1669 "unable to parse parameter count `%s'",
1672 if (tline
&& tok_is_(tline
->next
, "-")) {
1673 tline
= tline
->next
->next
;
1674 if (tok_is_(tline
, "*"))
1675 searching
.nparam_max
= INT_MAX
;
1676 else if (!tok_type_(tline
, TOK_NUMBER
))
1678 "`%s' expects a parameter count after `-'",
1681 searching
.nparam_max
= readnum(tline
->text
, &j
);
1684 "unable to parse parameter count `%s'",
1686 if (searching
.nparam_min
> searching
.nparam_max
)
1688 "minimum parameter count exceeds maximum");
1691 if (tline
&& tok_is_(tline
->next
, "+")) {
1692 tline
= tline
->next
;
1693 searching
.plus
= true;
1695 mmac
= (MMacro
*) hash_findix(&mmacros
, searching
.name
);
1697 if (!strcmp(mmac
->name
, searching
.name
) &&
1698 (mmac
->nparam_min
<= searching
.nparam_max
1700 && (searching
.nparam_min
<= mmac
->nparam_max
1707 if(tline
&& tline
->next
)
1708 error(ERR_WARNING
|ERR_PASS1
,
1709 "trailing garbage after %%ifmacro ignored");
1710 nasm_free(searching
.name
);
1719 needtype
= TOK_NUMBER
;
1722 needtype
= TOK_STRING
;
1726 t
= tline
= expand_smacro(tline
);
1728 while (tok_type_(t
, TOK_WHITESPACE
) ||
1729 (needtype
== TOK_NUMBER
&&
1730 tok_type_(t
, TOK_OTHER
) &&
1731 (t
->text
[0] == '-' || t
->text
[0] == '+') &&
1735 j
= tok_type_(t
, needtype
);
1739 t
= tline
= expand_smacro(tline
);
1740 while (tok_type_(t
, TOK_WHITESPACE
))
1745 t
= t
->next
; /* Skip the actual token */
1746 while (tok_type_(t
, TOK_WHITESPACE
))
1748 j
= !t
; /* Should be nothing left */
1753 t
= tline
= expand_smacro(tline
);
1754 while (tok_type_(t
, TOK_WHITESPACE
))
1757 j
= !t
; /* Should be empty */
1761 t
= tline
= expand_smacro(tline
);
1763 tokval
.t_type
= TOKEN_INVALID
;
1764 evalresult
= evaluate(ppscan
, tptr
, &tokval
,
1765 NULL
, pass
| CRITICAL
, error
, NULL
);
1769 error(ERR_WARNING
|ERR_PASS1
,
1770 "trailing garbage after expression ignored");
1771 if (!is_simple(evalresult
)) {
1773 "non-constant value given to `%s'", pp_directives
[ct
]);
1776 j
= reloc_value(evalresult
) != 0;
1781 "preprocessor directive `%s' not yet implemented",
1786 free_tlist(origline
);
1787 return j
^ PP_NEGATIVE(ct
);
1790 free_tlist(origline
);
1795 * Common code for defining an smacro
1797 static bool define_smacro(Context
*ctx
, const char *mname
, bool casesense
,
1798 int nparam
, Token
*expansion
)
1800 SMacro
*smac
, **smhead
;
1801 struct hash_table
*smtbl
;
1803 if (smacro_defined(ctx
, mname
, nparam
, &smac
, casesense
)) {
1805 error(ERR_WARNING
|ERR_PASS1
,
1806 "single-line macro `%s' defined both with and"
1807 " without parameters", mname
);
1809 /* Some instances of the old code considered this a failure,
1810 some others didn't. What is the right thing to do here? */
1811 free_tlist(expansion
);
1812 return false; /* Failure */
1815 * We're redefining, so we have to take over an
1816 * existing SMacro structure. This means freeing
1817 * what was already in it.
1819 nasm_free(smac
->name
);
1820 free_tlist(smac
->expansion
);
1823 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
1824 smhead
= (SMacro
**) hash_findi_add(smtbl
, mname
);
1825 smac
= nasm_malloc(sizeof(SMacro
));
1826 smac
->next
= *smhead
;
1829 smac
->name
= nasm_strdup(mname
);
1830 smac
->casesense
= casesense
;
1831 smac
->nparam
= nparam
;
1832 smac
->expansion
= expansion
;
1833 smac
->in_progress
= false;
1834 return true; /* Success */
1838 * Undefine an smacro
1840 static void undef_smacro(Context
*ctx
, const char *mname
)
1842 SMacro
**smhead
, *s
, **sp
;
1843 struct hash_table
*smtbl
;
1845 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
1846 smhead
= (SMacro
**)hash_findi(smtbl
, mname
, NULL
);
1850 * We now have a macro name... go hunt for it.
1853 while ((s
= *sp
) != NULL
) {
1854 if (!mstrcmp(s
->name
, mname
, s
->casesense
)) {
1857 free_tlist(s
->expansion
);
1867 * Parse a mmacro specification.
1869 static bool parse_mmacro_spec(Token
*tline
, MMacro
*def
, const char *directive
)
1873 tline
= tline
->next
;
1875 tline
= expand_id(tline
);
1876 if (!tok_type_(tline
, TOK_ID
)) {
1877 error(ERR_NONFATAL
, "`%s' expects a macro name", directive
);
1881 def
->name
= nasm_strdup(tline
->text
);
1883 def
->nolist
= false;
1884 def
->in_progress
= 0;
1885 def
->rep_nest
= NULL
;
1886 def
->nparam_min
= 0;
1887 def
->nparam_max
= 0;
1889 tline
= expand_smacro(tline
->next
);
1891 if (!tok_type_(tline
, TOK_NUMBER
)) {
1892 error(ERR_NONFATAL
, "`%s' expects a parameter count", directive
);
1894 def
->nparam_min
= def
->nparam_max
=
1895 readnum(tline
->text
, &err
);
1898 "unable to parse parameter count `%s'", tline
->text
);
1900 if (tline
&& tok_is_(tline
->next
, "-")) {
1901 tline
= tline
->next
->next
;
1902 if (tok_is_(tline
, "*")) {
1903 def
->nparam_max
= INT_MAX
;
1904 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
1906 "`%s' expects a parameter count after `-'", directive
);
1908 def
->nparam_max
= readnum(tline
->text
, &err
);
1910 error(ERR_NONFATAL
, "unable to parse parameter count `%s'",
1913 if (def
->nparam_min
> def
->nparam_max
) {
1914 error(ERR_NONFATAL
, "minimum parameter count exceeds maximum");
1918 if (tline
&& tok_is_(tline
->next
, "+")) {
1919 tline
= tline
->next
;
1922 if (tline
&& tok_type_(tline
->next
, TOK_ID
) &&
1923 !nasm_stricmp(tline
->next
->text
, ".nolist")) {
1924 tline
= tline
->next
;
1929 * Handle default parameters.
1931 if (tline
&& tline
->next
) {
1932 def
->dlist
= tline
->next
;
1934 count_mmac_params(def
->dlist
, &def
->ndefs
, &def
->defaults
);
1937 def
->defaults
= NULL
;
1939 def
->expansion
= NULL
;
1942 def
->ndefs
> def
->nparam_max
- def
->nparam_min
&&
1944 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MDP
,
1945 "too many default macro parameters");
1952 * Decode a size directive
1954 static int parse_size(const char *str
) {
1955 static const char *size_names
[] =
1956 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
1957 static const int sizes
[] =
1958 { 0, 1, 4, 16, 8, 10, 2, 32 };
1960 return sizes
[bsii(str
, size_names
, elements(size_names
))+1];
1964 * find and process preprocessor directive in passed line
1965 * Find out if a line contains a preprocessor directive, and deal
1968 * If a directive _is_ found, it is the responsibility of this routine
1969 * (and not the caller) to free_tlist() the line.
1971 * @param tline a pointer to the current tokeninzed line linked list
1972 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
1975 static int do_directive(Token
* tline
)
1977 enum preproc_token i
;
1990 MMacro
*mmac
, **mmhead
;
1991 Token
*t
, *tt
, *param_start
, *macro_start
, *last
, **tptr
, *origline
;
1993 struct tokenval tokval
;
1995 MMacro
*tmp_defining
; /* Used when manipulating rep_nest */
2003 if (!tline
|| !tok_type_(tline
, TOK_PREPROC_ID
) ||
2004 (tline
->text
[1] == '%' || tline
->text
[1] == '$'
2005 || tline
->text
[1] == '!'))
2006 return NO_DIRECTIVE_FOUND
;
2008 i
= pp_token_hash(tline
->text
);
2011 * If we're in a non-emitting branch of a condition construct,
2012 * or walking to the end of an already terminated %rep block,
2013 * we should ignore all directives except for condition
2016 if (((istk
->conds
&& !emitting(istk
->conds
->state
)) ||
2017 (istk
->mstk
&& !istk
->mstk
->in_progress
)) && !is_condition(i
)) {
2018 return NO_DIRECTIVE_FOUND
;
2022 * If we're defining a macro or reading a %rep block, we should
2023 * ignore all directives except for %macro/%imacro (which nest),
2024 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2025 * If we're in a %rep block, another %rep nests, so should be let through.
2027 if (defining
&& i
!= PP_MACRO
&& i
!= PP_IMACRO
&&
2028 i
!= PP_ENDMACRO
&& i
!= PP_ENDM
&&
2029 (defining
->name
|| (i
!= PP_ENDREP
&& i
!= PP_REP
))) {
2030 return NO_DIRECTIVE_FOUND
;
2034 if (i
== PP_MACRO
|| i
== PP_IMACRO
) {
2036 return NO_DIRECTIVE_FOUND
;
2037 } else if (nested_mac_count
> 0) {
2038 if (i
== PP_ENDMACRO
) {
2040 return NO_DIRECTIVE_FOUND
;
2043 if (!defining
->name
) {
2046 return NO_DIRECTIVE_FOUND
;
2047 } else if (nested_rep_count
> 0) {
2048 if (i
== PP_ENDREP
) {
2050 return NO_DIRECTIVE_FOUND
;
2058 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2060 return NO_DIRECTIVE_FOUND
; /* didn't get it */
2063 /* Directive to tell NASM what the default stack size is. The
2064 * default is for a 16-bit stack, and this can be overriden with
2066 * the following form:
2068 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2070 tline
= tline
->next
;
2071 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2072 tline
= tline
->next
;
2073 if (!tline
|| tline
->type
!= TOK_ID
) {
2074 error(ERR_NONFATAL
, "`%%stacksize' missing size parameter");
2075 free_tlist(origline
);
2076 return DIRECTIVE_FOUND
;
2078 if (nasm_stricmp(tline
->text
, "flat") == 0) {
2079 /* All subsequent ARG directives are for a 32-bit stack */
2081 StackPointer
= "ebp";
2084 } else if (nasm_stricmp(tline
->text
, "flat64") == 0) {
2085 /* All subsequent ARG directives are for a 64-bit stack */
2087 StackPointer
= "rbp";
2090 } else if (nasm_stricmp(tline
->text
, "large") == 0) {
2091 /* All subsequent ARG directives are for a 16-bit stack,
2092 * far function call.
2095 StackPointer
= "bp";
2098 } else if (nasm_stricmp(tline
->text
, "small") == 0) {
2099 /* All subsequent ARG directives are for a 16-bit stack,
2100 * far function call. We don't support near functions.
2103 StackPointer
= "bp";
2107 error(ERR_NONFATAL
, "`%%stacksize' invalid size type");
2108 free_tlist(origline
);
2109 return DIRECTIVE_FOUND
;
2111 free_tlist(origline
);
2112 return DIRECTIVE_FOUND
;
2115 /* TASM like ARG directive to define arguments to functions, in
2116 * the following form:
2118 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2122 char *arg
, directive
[256];
2123 int size
= StackSize
;
2125 /* Find the argument name */
2126 tline
= tline
->next
;
2127 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2128 tline
= tline
->next
;
2129 if (!tline
|| tline
->type
!= TOK_ID
) {
2130 error(ERR_NONFATAL
, "`%%arg' missing argument parameter");
2131 free_tlist(origline
);
2132 return DIRECTIVE_FOUND
;
2136 /* Find the argument size type */
2137 tline
= tline
->next
;
2138 if (!tline
|| tline
->type
!= TOK_OTHER
2139 || tline
->text
[0] != ':') {
2141 "Syntax error processing `%%arg' directive");
2142 free_tlist(origline
);
2143 return DIRECTIVE_FOUND
;
2145 tline
= tline
->next
;
2146 if (!tline
|| tline
->type
!= TOK_ID
) {
2147 error(ERR_NONFATAL
, "`%%arg' missing size type parameter");
2148 free_tlist(origline
);
2149 return DIRECTIVE_FOUND
;
2152 /* Allow macro expansion of type parameter */
2153 tt
= tokenize(tline
->text
);
2154 tt
= expand_smacro(tt
);
2155 size
= parse_size(tt
->text
);
2158 "Invalid size type for `%%arg' missing directive");
2160 free_tlist(origline
);
2161 return DIRECTIVE_FOUND
;
2165 /* Round up to even stack slots */
2166 size
= (size
+StackSize
-1) & ~(StackSize
-1);
2168 /* Now define the macro for the argument */
2169 snprintf(directive
, sizeof(directive
), "%%define %s (%s+%d)",
2170 arg
, StackPointer
, offset
);
2171 do_directive(tokenize(directive
));
2174 /* Move to the next argument in the list */
2175 tline
= tline
->next
;
2176 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2177 tline
= tline
->next
;
2178 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2180 free_tlist(origline
);
2181 return DIRECTIVE_FOUND
;
2184 /* TASM like LOCAL directive to define local variables for a
2185 * function, in the following form:
2187 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2189 * The '= LocalSize' at the end is ignored by NASM, but is
2190 * required by TASM to define the local parameter size (and used
2191 * by the TASM macro package).
2193 offset
= LocalOffset
;
2195 char *local
, directive
[256];
2196 int size
= StackSize
;
2198 /* Find the argument name */
2199 tline
= tline
->next
;
2200 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2201 tline
= tline
->next
;
2202 if (!tline
|| tline
->type
!= TOK_ID
) {
2204 "`%%local' missing argument parameter");
2205 free_tlist(origline
);
2206 return DIRECTIVE_FOUND
;
2208 local
= tline
->text
;
2210 /* Find the argument size type */
2211 tline
= tline
->next
;
2212 if (!tline
|| tline
->type
!= TOK_OTHER
2213 || tline
->text
[0] != ':') {
2215 "Syntax error processing `%%local' directive");
2216 free_tlist(origline
);
2217 return DIRECTIVE_FOUND
;
2219 tline
= tline
->next
;
2220 if (!tline
|| tline
->type
!= TOK_ID
) {
2222 "`%%local' missing size type parameter");
2223 free_tlist(origline
);
2224 return DIRECTIVE_FOUND
;
2227 /* Allow macro expansion of type parameter */
2228 tt
= tokenize(tline
->text
);
2229 tt
= expand_smacro(tt
);
2230 size
= parse_size(tt
->text
);
2233 "Invalid size type for `%%local' missing directive");
2235 free_tlist(origline
);
2236 return DIRECTIVE_FOUND
;
2240 /* Round up to even stack slots */
2241 size
= (size
+StackSize
-1) & ~(StackSize
-1);
2243 offset
+= size
; /* Negative offset, increment before */
2245 /* Now define the macro for the argument */
2246 snprintf(directive
, sizeof(directive
), "%%define %s (%s-%d)",
2247 local
, StackPointer
, offset
);
2248 do_directive(tokenize(directive
));
2250 /* Now define the assign to setup the enter_c macro correctly */
2251 snprintf(directive
, sizeof(directive
),
2252 "%%assign %%$localsize %%$localsize+%d", size
);
2253 do_directive(tokenize(directive
));
2255 /* Move to the next argument in the list */
2256 tline
= tline
->next
;
2257 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2258 tline
= tline
->next
;
2259 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2260 LocalOffset
= offset
;
2261 free_tlist(origline
);
2262 return DIRECTIVE_FOUND
;
2266 error(ERR_WARNING
|ERR_PASS1
,
2267 "trailing garbage after `%%clear' ignored");
2270 free_tlist(origline
);
2271 return DIRECTIVE_FOUND
;
2274 t
= tline
->next
= expand_smacro(tline
->next
);
2276 if (!t
|| (t
->type
!= TOK_STRING
&&
2277 t
->type
!= TOK_INTERNAL_STRING
)) {
2278 error(ERR_NONFATAL
, "`%%depend' expects a file name");
2279 free_tlist(origline
);
2280 return DIRECTIVE_FOUND
; /* but we did _something_ */
2283 error(ERR_WARNING
|ERR_PASS1
,
2284 "trailing garbage after `%%depend' ignored");
2286 if (t
->type
!= TOK_INTERNAL_STRING
)
2287 nasm_unquote(p
, NULL
);
2288 if (dephead
&& !in_list(*dephead
, p
)) {
2289 StrList
*sl
= nasm_malloc(strlen(p
)+1+sizeof sl
->next
);
2293 deptail
= &sl
->next
;
2295 free_tlist(origline
);
2296 return DIRECTIVE_FOUND
;
2299 t
= tline
->next
= expand_smacro(tline
->next
);
2302 if (!t
|| (t
->type
!= TOK_STRING
&&
2303 t
->type
!= TOK_INTERNAL_STRING
)) {
2304 error(ERR_NONFATAL
, "`%%include' expects a file name");
2305 free_tlist(origline
);
2306 return DIRECTIVE_FOUND
; /* but we did _something_ */
2309 error(ERR_WARNING
|ERR_PASS1
,
2310 "trailing garbage after `%%include' ignored");
2312 if (t
->type
!= TOK_INTERNAL_STRING
)
2313 nasm_unquote(p
, NULL
);
2314 inc
= nasm_malloc(sizeof(Include
));
2317 inc
->fp
= inc_fopen(p
, dephead
, &deptail
, pass
== 0);
2319 /* -MG given but file not found */
2322 inc
->fname
= src_set_fname(nasm_strdup(p
));
2323 inc
->lineno
= src_set_linnum(0);
2325 inc
->expansion
= NULL
;
2328 list
->uplevel(LIST_INCLUDE
);
2330 free_tlist(origline
);
2331 return DIRECTIVE_FOUND
;
2335 static macros_t
*use_pkg
;
2336 const char *pkg_macro
;
2338 tline
= tline
->next
;
2340 tline
= expand_id(tline
);
2342 if (!tline
|| (tline
->type
!= TOK_STRING
&&
2343 tline
->type
!= TOK_INTERNAL_STRING
&&
2344 tline
->type
!= TOK_ID
)) {
2345 error(ERR_NONFATAL
, "`%%use' expects a package name");
2346 free_tlist(origline
);
2347 return DIRECTIVE_FOUND
; /* but we did _something_ */
2350 error(ERR_WARNING
|ERR_PASS1
,
2351 "trailing garbage after `%%use' ignored");
2352 if (tline
->type
== TOK_STRING
)
2353 nasm_unquote(tline
->text
, NULL
);
2354 use_pkg
= nasm_stdmac_find_package(tline
->text
);
2356 error(ERR_NONFATAL
, "unknown `%%use' package: %s", tline
->text
);
2357 /* The first string will be <%define>__USE_*__ */
2358 pkg_macro
= (char *)use_pkg
+ 1;
2359 if (!smacro_defined(NULL
, pkg_macro
, 0, NULL
, true)) {
2360 /* Not already included, go ahead and include it */
2361 stdmacpos
= use_pkg
;
2363 free_tlist(origline
);
2364 return DIRECTIVE_FOUND
;
2369 tline
= tline
->next
;
2371 tline
= expand_id(tline
);
2373 if (!tok_type_(tline
, TOK_ID
)) {
2374 error(ERR_NONFATAL
, "`%s' expects a context identifier",
2376 free_tlist(origline
);
2377 return DIRECTIVE_FOUND
; /* but we did _something_ */
2380 error(ERR_WARNING
|ERR_PASS1
,
2381 "trailing garbage after `%s' ignored",
2383 p
= nasm_strdup(tline
->text
);
2385 p
= NULL
; /* Anonymous */
2389 ctx
= nasm_malloc(sizeof(Context
));
2391 hash_init(&ctx
->localmac
, HASH_SMALL
);
2393 ctx
->number
= unique
++;
2398 error(ERR_NONFATAL
, "`%s': context stack is empty",
2400 } else if (i
== PP_POP
) {
2401 if (p
&& (!cstk
->name
|| nasm_stricmp(p
, cstk
->name
)))
2402 error(ERR_NONFATAL
, "`%%pop' in wrong context: %s, "
2404 cstk
->name
? cstk
->name
: "anonymous", p
);
2409 nasm_free(cstk
->name
);
2415 free_tlist(origline
);
2416 return DIRECTIVE_FOUND
;
2418 severity
= ERR_FATAL
|ERR_NO_SEVERITY
;
2421 severity
= ERR_NONFATAL
|ERR_NO_SEVERITY
;
2424 severity
= ERR_WARNING
|ERR_NO_SEVERITY
|ERR_WARN_USER
;
2429 /* Only error out if this is the final pass */
2430 if (pass
!= 2 && i
!= PP_FATAL
)
2431 return DIRECTIVE_FOUND
;
2433 tline
->next
= expand_smacro(tline
->next
);
2434 tline
= tline
->next
;
2436 t
= tline
? tline
->next
: NULL
;
2438 if (tok_type_(tline
, TOK_STRING
) && !t
) {
2439 /* The line contains only a quoted string */
2441 nasm_unquote(p
, NULL
);
2442 error(severity
, "%s: %s", pp_directives
[i
], p
);
2444 /* Not a quoted string, or more than a quoted string */
2445 p
= detoken(tline
, false);
2446 error(severity
, "%s: %s", pp_directives
[i
], p
);
2449 free_tlist(origline
);
2450 return DIRECTIVE_FOUND
;
2454 if (istk
->conds
&& !emitting(istk
->conds
->state
))
2457 j
= if_condition(tline
->next
, i
);
2458 tline
->next
= NULL
; /* it got freed */
2459 j
= j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2461 cond
= nasm_malloc(sizeof(Cond
));
2462 cond
->next
= istk
->conds
;
2465 free_tlist(origline
);
2466 return DIRECTIVE_FOUND
;
2470 error(ERR_FATAL
, "`%s': no matching `%%if'", pp_directives
[i
]);
2471 switch(istk
->conds
->state
) {
2473 istk
->conds
->state
= COND_DONE
;
2480 case COND_ELSE_TRUE
:
2481 case COND_ELSE_FALSE
:
2482 error_precond(ERR_WARNING
|ERR_PASS1
,
2483 "`%%elif' after `%%else' ignored");
2484 istk
->conds
->state
= COND_NEVER
;
2489 * IMPORTANT: In the case of %if, we will already have
2490 * called expand_mmac_params(); however, if we're
2491 * processing an %elif we must have been in a
2492 * non-emitting mode, which would have inhibited
2493 * the normal invocation of expand_mmac_params().
2494 * Therefore, we have to do it explicitly here.
2496 j
= if_condition(expand_mmac_params(tline
->next
), i
);
2497 tline
->next
= NULL
; /* it got freed */
2498 istk
->conds
->state
=
2499 j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2502 free_tlist(origline
);
2503 return DIRECTIVE_FOUND
;
2507 error_precond(ERR_WARNING
|ERR_PASS1
,
2508 "trailing garbage after `%%else' ignored");
2510 error(ERR_FATAL
, "`%%else': no matching `%%if'");
2511 switch(istk
->conds
->state
) {
2514 istk
->conds
->state
= COND_ELSE_FALSE
;
2521 istk
->conds
->state
= COND_ELSE_TRUE
;
2524 case COND_ELSE_TRUE
:
2525 case COND_ELSE_FALSE
:
2526 error_precond(ERR_WARNING
|ERR_PASS1
,
2527 "`%%else' after `%%else' ignored.");
2528 istk
->conds
->state
= COND_NEVER
;
2531 free_tlist(origline
);
2532 return DIRECTIVE_FOUND
;
2536 error_precond(ERR_WARNING
|ERR_PASS1
,
2537 "trailing garbage after `%%endif' ignored");
2539 error(ERR_FATAL
, "`%%endif': no matching `%%if'");
2541 istk
->conds
= cond
->next
;
2543 free_tlist(origline
);
2544 return DIRECTIVE_FOUND
;
2550 "`%%%smacro': already defining a macro",
2551 (i
== PP_IMACRO
? "i" : ""));
2552 return DIRECTIVE_FOUND
;
2554 defining
= nasm_malloc(sizeof(MMacro
));
2555 defining
->casesense
= (i
== PP_MACRO
);
2556 if (!parse_mmacro_spec(tline
, defining
, pp_directives
[i
])) {
2557 nasm_free(defining
);
2559 return DIRECTIVE_FOUND
;
2562 mmac
= (MMacro
*) hash_findix(&mmacros
, defining
->name
);
2564 if (!strcmp(mmac
->name
, defining
->name
) &&
2565 (mmac
->nparam_min
<= defining
->nparam_max
2567 && (defining
->nparam_min
<= mmac
->nparam_max
2569 error(ERR_WARNING
|ERR_PASS1
,
2570 "redefining multi-line macro `%s'", defining
->name
);
2571 return DIRECTIVE_FOUND
;
2575 free_tlist(origline
);
2576 return DIRECTIVE_FOUND
;
2580 if (! (defining
&& defining
->name
)) {
2581 error(ERR_NONFATAL
, "`%s': not defining a macro", tline
->text
);
2582 return DIRECTIVE_FOUND
;
2584 mmhead
= (MMacro
**) hash_findi_add(&mmacros
, defining
->name
);
2585 defining
->next
= *mmhead
;
2588 free_tlist(origline
);
2589 return DIRECTIVE_FOUND
;
2597 spec
.casesense
= (i
== PP_UNMACRO
);
2598 if (!parse_mmacro_spec(tline
, &spec
, pp_directives
[i
])) {
2599 return DIRECTIVE_FOUND
;
2601 mmac_p
= (MMacro
**) hash_findi(&mmacros
, spec
.name
, NULL
);
2602 while (mmac_p
&& *mmac_p
) {
2604 if (mmac
->casesense
== spec
.casesense
&&
2605 !mstrcmp(mmac
->name
, spec
.name
, spec
.casesense
) &&
2606 mmac
->nparam_min
== spec
.nparam_min
&&
2607 mmac
->nparam_max
== spec
.nparam_max
&&
2608 mmac
->plus
== spec
.plus
) {
2609 *mmac_p
= mmac
->next
;
2612 mmac_p
= &mmac
->next
;
2615 free_tlist(origline
);
2616 free_tlist(spec
.dlist
);
2617 return DIRECTIVE_FOUND
;
2621 if (tline
->next
&& tline
->next
->type
== TOK_WHITESPACE
)
2622 tline
= tline
->next
;
2623 if (tline
->next
== NULL
) {
2624 free_tlist(origline
);
2625 error(ERR_NONFATAL
, "`%%rotate' missing rotate count");
2626 return DIRECTIVE_FOUND
;
2628 t
= expand_smacro(tline
->next
);
2630 free_tlist(origline
);
2633 tokval
.t_type
= TOKEN_INVALID
;
2635 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2638 return DIRECTIVE_FOUND
;
2640 error(ERR_WARNING
|ERR_PASS1
,
2641 "trailing garbage after expression ignored");
2642 if (!is_simple(evalresult
)) {
2643 error(ERR_NONFATAL
, "non-constant value given to `%%rotate'");
2644 return DIRECTIVE_FOUND
;
2647 while (mmac
&& !mmac
->name
) /* avoid mistaking %reps for macros */
2648 mmac
= mmac
->next_active
;
2650 error(ERR_NONFATAL
, "`%%rotate' invoked outside a macro call");
2651 } else if (mmac
->nparam
== 0) {
2653 "`%%rotate' invoked within macro without parameters");
2655 int rotate
= mmac
->rotate
+ reloc_value(evalresult
);
2657 rotate
%= (int)mmac
->nparam
;
2659 rotate
+= mmac
->nparam
;
2661 mmac
->rotate
= rotate
;
2663 return DIRECTIVE_FOUND
;
2668 tline
= tline
->next
;
2669 } while (tok_type_(tline
, TOK_WHITESPACE
));
2671 if (tok_type_(tline
, TOK_ID
) &&
2672 nasm_stricmp(tline
->text
, ".nolist") == 0) {
2675 tline
= tline
->next
;
2676 } while (tok_type_(tline
, TOK_WHITESPACE
));
2680 t
= expand_smacro(tline
);
2682 tokval
.t_type
= TOKEN_INVALID
;
2684 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2686 free_tlist(origline
);
2687 return DIRECTIVE_FOUND
;
2690 error(ERR_WARNING
|ERR_PASS1
,
2691 "trailing garbage after expression ignored");
2692 if (!is_simple(evalresult
)) {
2693 error(ERR_NONFATAL
, "non-constant value given to `%%rep'");
2694 return DIRECTIVE_FOUND
;
2696 count
= reloc_value(evalresult
) + 1;
2698 error(ERR_NONFATAL
, "`%%rep' expects a repeat count");
2701 free_tlist(origline
);
2703 tmp_defining
= defining
;
2704 defining
= nasm_malloc(sizeof(MMacro
));
2705 defining
->name
= NULL
; /* flags this macro as a %rep block */
2706 defining
->casesense
= false;
2707 defining
->plus
= false;
2708 defining
->nolist
= nolist
;
2709 defining
->in_progress
= count
;
2710 defining
->nparam_min
= defining
->nparam_max
= 0;
2711 defining
->defaults
= NULL
;
2712 defining
->dlist
= NULL
;
2713 defining
->expansion
= NULL
;
2714 defining
->next_active
= istk
->mstk
;
2715 defining
->rep_nest
= tmp_defining
;
2716 return DIRECTIVE_FOUND
;
2719 if (!defining
|| defining
->name
) {
2720 error(ERR_NONFATAL
, "`%%endrep': no matching `%%rep'");
2721 return DIRECTIVE_FOUND
;
2725 * Now we have a "macro" defined - although it has no name
2726 * and we won't be entering it in the hash tables - we must
2727 * push a macro-end marker for it on to istk->expansion.
2728 * After that, it will take care of propagating itself (a
2729 * macro-end marker line for a macro which is really a %rep
2730 * block will cause the macro to be re-expanded, complete
2731 * with another macro-end marker to ensure the process
2732 * continues) until the whole expansion is forcibly removed
2733 * from istk->expansion by a %exitrep.
2735 l
= nasm_malloc(sizeof(Line
));
2736 l
->next
= istk
->expansion
;
2737 l
->finishes
= defining
;
2739 istk
->expansion
= l
;
2741 istk
->mstk
= defining
;
2743 list
->uplevel(defining
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
2744 tmp_defining
= defining
;
2745 defining
= defining
->rep_nest
;
2746 free_tlist(origline
);
2747 return DIRECTIVE_FOUND
;
2751 * We must search along istk->expansion until we hit a
2752 * macro-end marker for a macro with no name. Then we set
2753 * its `in_progress' flag to 0.
2755 for (l
= istk
->expansion
; l
; l
= l
->next
)
2756 if (l
->finishes
&& !l
->finishes
->name
)
2760 l
->finishes
->in_progress
= 1;
2762 error(ERR_NONFATAL
, "`%%exitrep' not within `%%rep' block");
2763 free_tlist(origline
);
2764 return DIRECTIVE_FOUND
;
2770 casesense
= (i
== PP_DEFINE
|| i
== PP_XDEFINE
);
2772 tline
= tline
->next
;
2774 tline
= expand_id(tline
);
2775 if (!tline
|| (tline
->type
!= TOK_ID
&&
2776 (tline
->type
!= TOK_PREPROC_ID
||
2777 tline
->text
[1] != '$'))) {
2778 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
2780 free_tlist(origline
);
2781 return DIRECTIVE_FOUND
;
2784 ctx
= get_ctx(tline
->text
, &mname
, false);
2786 param_start
= tline
= tline
->next
;
2789 /* Expand the macro definition now for %xdefine and %ixdefine */
2790 if ((i
== PP_XDEFINE
) || (i
== PP_IXDEFINE
))
2791 tline
= expand_smacro(tline
);
2793 if (tok_is_(tline
, "(")) {
2795 * This macro has parameters.
2798 tline
= tline
->next
;
2802 error(ERR_NONFATAL
, "parameter identifier expected");
2803 free_tlist(origline
);
2804 return DIRECTIVE_FOUND
;
2806 if (tline
->type
!= TOK_ID
) {
2808 "`%s': parameter identifier expected",
2810 free_tlist(origline
);
2811 return DIRECTIVE_FOUND
;
2813 tline
->type
= TOK_SMAC_PARAM
+ nparam
++;
2814 tline
= tline
->next
;
2816 if (tok_is_(tline
, ",")) {
2817 tline
= tline
->next
;
2819 if (!tok_is_(tline
, ")")) {
2821 "`)' expected to terminate macro template");
2822 free_tlist(origline
);
2823 return DIRECTIVE_FOUND
;
2829 tline
= tline
->next
;
2831 if (tok_type_(tline
, TOK_WHITESPACE
))
2832 last
= tline
, tline
= tline
->next
;
2837 if (t
->type
== TOK_ID
) {
2838 for (tt
= param_start
; tt
; tt
= tt
->next
)
2839 if (tt
->type
>= TOK_SMAC_PARAM
&&
2840 !strcmp(tt
->text
, t
->text
))
2844 t
->next
= macro_start
;
2849 * Good. We now have a macro name, a parameter count, and a
2850 * token list (in reverse order) for an expansion. We ought
2851 * to be OK just to create an SMacro, store it, and let
2852 * free_tlist have the rest of the line (which we have
2853 * carefully re-terminated after chopping off the expansion
2856 define_smacro(ctx
, mname
, casesense
, nparam
, macro_start
);
2857 free_tlist(origline
);
2858 return DIRECTIVE_FOUND
;
2861 tline
= tline
->next
;
2863 tline
= expand_id(tline
);
2864 if (!tline
|| (tline
->type
!= TOK_ID
&&
2865 (tline
->type
!= TOK_PREPROC_ID
||
2866 tline
->text
[1] != '$'))) {
2867 error(ERR_NONFATAL
, "`%%undef' expects a macro identifier");
2868 free_tlist(origline
);
2869 return DIRECTIVE_FOUND
;
2872 error(ERR_WARNING
|ERR_PASS1
,
2873 "trailing garbage after macro name ignored");
2876 /* Find the context that symbol belongs to */
2877 ctx
= get_ctx(tline
->text
, &mname
, false);
2878 undef_smacro(ctx
, mname
);
2879 free_tlist(origline
);
2880 return DIRECTIVE_FOUND
;
2884 casesense
= (i
== PP_DEFSTR
);
2886 tline
= tline
->next
;
2888 tline
= expand_id(tline
);
2889 if (!tline
|| (tline
->type
!= TOK_ID
&&
2890 (tline
->type
!= TOK_PREPROC_ID
||
2891 tline
->text
[1] != '$'))) {
2892 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
2894 free_tlist(origline
);
2895 return DIRECTIVE_FOUND
;
2898 ctx
= get_ctx(tline
->text
, &mname
, false);
2900 tline
= expand_smacro(tline
->next
);
2903 while (tok_type_(tline
, TOK_WHITESPACE
))
2904 tline
= delete_Token(tline
);
2906 p
= detoken(tline
, false);
2907 macro_start
= nasm_malloc(sizeof(*macro_start
));
2908 macro_start
->next
= NULL
;
2909 macro_start
->text
= nasm_quote(p
, strlen(p
));
2910 macro_start
->type
= TOK_STRING
;
2911 macro_start
->a
.mac
= NULL
;
2915 * We now have a macro name, an implicit parameter count of
2916 * zero, and a string token to use as an expansion. Create
2917 * and store an SMacro.
2919 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
2920 free_tlist(origline
);
2921 return DIRECTIVE_FOUND
;
2926 StrList
*xsl
= NULL
;
2927 StrList
**xst
= &xsl
;
2931 tline
= tline
->next
;
2933 tline
= expand_id(tline
);
2934 if (!tline
|| (tline
->type
!= TOK_ID
&&
2935 (tline
->type
!= TOK_PREPROC_ID
||
2936 tline
->text
[1] != '$'))) {
2938 "`%%pathsearch' expects a macro identifier as first parameter");
2939 free_tlist(origline
);
2940 return DIRECTIVE_FOUND
;
2942 ctx
= get_ctx(tline
->text
, &mname
, false);
2944 tline
= expand_smacro(tline
->next
);
2948 while (tok_type_(t
, TOK_WHITESPACE
))
2951 if (!t
|| (t
->type
!= TOK_STRING
&&
2952 t
->type
!= TOK_INTERNAL_STRING
)) {
2953 error(ERR_NONFATAL
, "`%%pathsearch' expects a file name");
2955 free_tlist(origline
);
2956 return DIRECTIVE_FOUND
; /* but we did _something_ */
2959 error(ERR_WARNING
|ERR_PASS1
,
2960 "trailing garbage after `%%pathsearch' ignored");
2962 if (t
->type
!= TOK_INTERNAL_STRING
)
2963 nasm_unquote(p
, NULL
);
2965 fp
= inc_fopen(p
, &xsl
, &xst
, true);
2968 fclose(fp
); /* Don't actually care about the file */
2970 macro_start
= nasm_malloc(sizeof(*macro_start
));
2971 macro_start
->next
= NULL
;
2972 macro_start
->text
= nasm_quote(p
, strlen(p
));
2973 macro_start
->type
= TOK_STRING
;
2974 macro_start
->a
.mac
= NULL
;
2979 * We now have a macro name, an implicit parameter count of
2980 * zero, and a string token to use as an expansion. Create
2981 * and store an SMacro.
2983 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
2985 free_tlist(origline
);
2986 return DIRECTIVE_FOUND
;
2992 tline
= tline
->next
;
2994 tline
= expand_id(tline
);
2995 if (!tline
|| (tline
->type
!= TOK_ID
&&
2996 (tline
->type
!= TOK_PREPROC_ID
||
2997 tline
->text
[1] != '$'))) {
2999 "`%%strlen' expects a macro identifier as first parameter");
3000 free_tlist(origline
);
3001 return DIRECTIVE_FOUND
;
3003 ctx
= get_ctx(tline
->text
, &mname
, false);
3005 tline
= expand_smacro(tline
->next
);
3009 while (tok_type_(t
, TOK_WHITESPACE
))
3011 /* t should now point to the string */
3012 if (t
->type
!= TOK_STRING
) {
3014 "`%%strlen` requires string as second parameter");
3016 free_tlist(origline
);
3017 return DIRECTIVE_FOUND
;
3020 macro_start
= nasm_malloc(sizeof(*macro_start
));
3021 macro_start
->next
= NULL
;
3022 make_tok_num(macro_start
, nasm_unquote(t
->text
, NULL
));
3023 macro_start
->a
.mac
= NULL
;
3026 * We now have a macro name, an implicit parameter count of
3027 * zero, and a numeric token to use as an expansion. Create
3028 * and store an SMacro.
3030 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3032 free_tlist(origline
);
3033 return DIRECTIVE_FOUND
;
3038 tline
= tline
->next
;
3040 tline
= expand_id(tline
);
3041 if (!tline
|| (tline
->type
!= TOK_ID
&&
3042 (tline
->type
!= TOK_PREPROC_ID
||
3043 tline
->text
[1] != '$'))) {
3045 "`%%strcat' expects a macro identifier as first parameter");
3046 free_tlist(origline
);
3047 return DIRECTIVE_FOUND
;
3049 ctx
= get_ctx(tline
->text
, &mname
, false);
3051 tline
= expand_smacro(tline
->next
);
3055 for (t
= tline
; t
; t
= t
->next
) {
3057 case TOK_WHITESPACE
:
3060 len
+= t
->a
.len
= nasm_unquote(t
->text
, NULL
);
3063 if (!strcmp(t
->text
, ",")) /* permit comma separators */
3065 /* else fall through */
3068 "non-string passed to `%%strcat' (%d)", t
->type
);
3070 free_tlist(origline
);
3071 return DIRECTIVE_FOUND
;
3075 p
= pp
= nasm_malloc(len
);
3077 for (t
= tline
; t
; t
= t
->next
) {
3078 if (t
->type
== TOK_STRING
) {
3079 memcpy(p
, t
->text
, t
->a
.len
);
3085 * We now have a macro name, an implicit parameter count of
3086 * zero, and a numeric token to use as an expansion. Create
3087 * and store an SMacro.
3089 macro_start
= new_Token(NULL
, TOK_STRING
, NULL
, 0);
3090 macro_start
->text
= nasm_quote(pp
, len
);
3092 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3094 free_tlist(origline
);
3095 return DIRECTIVE_FOUND
;
3104 tline
= tline
->next
;
3106 tline
= expand_id(tline
);
3107 if (!tline
|| (tline
->type
!= TOK_ID
&&
3108 (tline
->type
!= TOK_PREPROC_ID
||
3109 tline
->text
[1] != '$'))) {
3111 "`%%substr' expects a macro identifier as first parameter");
3112 free_tlist(origline
);
3113 return DIRECTIVE_FOUND
;
3115 ctx
= get_ctx(tline
->text
, &mname
, false);
3117 tline
= expand_smacro(tline
->next
);
3121 while (tok_type_(t
, TOK_WHITESPACE
))
3124 /* t should now point to the string */
3125 if (t
->type
!= TOK_STRING
) {
3127 "`%%substr` requires string as second parameter");
3129 free_tlist(origline
);
3130 return DIRECTIVE_FOUND
;
3135 tokval
.t_type
= TOKEN_INVALID
;
3136 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3140 free_tlist(origline
);
3141 return DIRECTIVE_FOUND
;
3142 } else if (!is_simple(evalresult
)) {
3143 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3145 free_tlist(origline
);
3146 return DIRECTIVE_FOUND
;
3148 a1
= evalresult
->value
-1;
3150 while (tok_type_(tt
, TOK_WHITESPACE
))
3153 a2
= 1; /* Backwards compatibility: one character */
3155 tokval
.t_type
= TOKEN_INVALID
;
3156 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3160 free_tlist(origline
);
3161 return DIRECTIVE_FOUND
;
3162 } else if (!is_simple(evalresult
)) {
3163 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3165 free_tlist(origline
);
3166 return DIRECTIVE_FOUND
;
3168 a2
= evalresult
->value
;
3171 len
= nasm_unquote(t
->text
, NULL
);
3174 if (a1
+a2
> (int64_t)len
)
3177 macro_start
= nasm_malloc(sizeof(*macro_start
));
3178 macro_start
->next
= NULL
;
3179 macro_start
->text
= nasm_quote((a1
< 0) ? "" : t
->text
+a1
, a2
);
3180 macro_start
->type
= TOK_STRING
;
3181 macro_start
->a
.mac
= NULL
;
3184 * We now have a macro name, an implicit parameter count of
3185 * zero, and a numeric token to use as an expansion. Create
3186 * and store an SMacro.
3188 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3190 free_tlist(origline
);
3191 return DIRECTIVE_FOUND
;
3196 casesense
= (i
== PP_ASSIGN
);
3198 tline
= tline
->next
;
3200 tline
= expand_id(tline
);
3201 if (!tline
|| (tline
->type
!= TOK_ID
&&
3202 (tline
->type
!= TOK_PREPROC_ID
||
3203 tline
->text
[1] != '$'))) {
3205 "`%%%sassign' expects a macro identifier",
3206 (i
== PP_IASSIGN
? "i" : ""));
3207 free_tlist(origline
);
3208 return DIRECTIVE_FOUND
;
3210 ctx
= get_ctx(tline
->text
, &mname
, false);
3212 tline
= expand_smacro(tline
->next
);
3217 tokval
.t_type
= TOKEN_INVALID
;
3219 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
3222 free_tlist(origline
);
3223 return DIRECTIVE_FOUND
;
3227 error(ERR_WARNING
|ERR_PASS1
,
3228 "trailing garbage after expression ignored");
3230 if (!is_simple(evalresult
)) {
3232 "non-constant value given to `%%%sassign'",
3233 (i
== PP_IASSIGN
? "i" : ""));
3234 free_tlist(origline
);
3235 return DIRECTIVE_FOUND
;
3238 macro_start
= nasm_malloc(sizeof(*macro_start
));
3239 macro_start
->next
= NULL
;
3240 make_tok_num(macro_start
, reloc_value(evalresult
));
3241 macro_start
->a
.mac
= NULL
;
3244 * We now have a macro name, an implicit parameter count of
3245 * zero, and a numeric token to use as an expansion. Create
3246 * and store an SMacro.
3248 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3249 free_tlist(origline
);
3250 return DIRECTIVE_FOUND
;
3254 * Syntax is `%line nnn[+mmm] [filename]'
3256 tline
= tline
->next
;
3258 if (!tok_type_(tline
, TOK_NUMBER
)) {
3259 error(ERR_NONFATAL
, "`%%line' expects line number");
3260 free_tlist(origline
);
3261 return DIRECTIVE_FOUND
;
3263 k
= readnum(tline
->text
, &err
);
3265 tline
= tline
->next
;
3266 if (tok_is_(tline
, "+")) {
3267 tline
= tline
->next
;
3268 if (!tok_type_(tline
, TOK_NUMBER
)) {
3269 error(ERR_NONFATAL
, "`%%line' expects line increment");
3270 free_tlist(origline
);
3271 return DIRECTIVE_FOUND
;
3273 m
= readnum(tline
->text
, &err
);
3274 tline
= tline
->next
;
3280 nasm_free(src_set_fname(detoken(tline
, false)));
3282 free_tlist(origline
);
3283 return DIRECTIVE_FOUND
;
3287 "preprocessor directive `%s' not yet implemented",
3289 return DIRECTIVE_FOUND
;
3294 * Ensure that a macro parameter contains a condition code and
3295 * nothing else. Return the condition code index if so, or -1
3298 static int find_cc(Token
* t
)
3304 return -1; /* Probably a %+ without a space */
3307 if (t
->type
!= TOK_ID
)
3311 if (tt
&& (tt
->type
!= TOK_OTHER
|| strcmp(tt
->text
, ",")))
3315 j
= elements(conditions
);
3318 m
= nasm_stricmp(t
->text
, conditions
[k
]);
3333 static bool paste_tokens(Token
**head
, bool handle_paste_tokens
)
3335 Token
**tail
, *t
, *tt
;
3337 bool did_paste
= false;
3340 /* Now handle token pasting... */
3343 while ((t
= *tail
) && (tt
= t
->next
)) {
3345 case TOK_WHITESPACE
:
3346 if (tt
->type
== TOK_WHITESPACE
) {
3347 /* Zap adjacent whitespace tokens */
3348 t
->next
= delete_Token(tt
);
3350 /* Do not advance paste_head here */
3355 case TOK_PREPROC_ID
:
3362 while (tt
&& (tt
->type
== TOK_ID
|| tt
->type
== TOK_PREPROC_ID
||
3363 tt
->type
== TOK_NUMBER
|| tt
->type
== TOK_FLOAT
||
3364 tt
->type
== TOK_OTHER
)) {
3365 len
+= strlen(tt
->text
);
3369 /* Now tt points to the first token after the potential
3371 if (tt
!= t
->next
) {
3372 /* We have at least two tokens... */
3373 len
+= strlen(t
->text
);
3374 p
= tmp
= nasm_malloc(len
+1);
3378 p
= strchr(p
, '\0');
3379 t
= delete_Token(t
);
3382 t
= *tail
= tokenize(tmp
);
3389 t
->next
= tt
; /* Attach the remaining token chain */
3397 case TOK_PASTE
: /* %+ */
3398 if (handle_paste_tokens
) {
3399 /* Zap %+ and whitespace tokens to the right */
3400 while (t
&& (t
->type
== TOK_WHITESPACE
||
3401 t
->type
== TOK_PASTE
))
3402 t
= *tail
= delete_Token(t
);
3403 if (!paste_head
|| !t
)
3404 break; /* Nothing to paste with */
3408 while (tok_type_(tt
, TOK_WHITESPACE
))
3409 tt
= t
->next
= delete_Token(tt
);
3412 tmp
= nasm_strcat(t
->text
, tt
->text
);
3414 tt
= delete_Token(tt
);
3415 t
= *tail
= tokenize(tmp
);
3421 t
->next
= tt
; /* Attach the remaining token chain */
3428 /* else fall through */
3430 tail
= paste_head
= &t
->next
;
3437 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3438 * %-n) and MMacro-local identifiers (%%foo) as well as
3439 * macro indirection (%[...]).
3441 static Token
*expand_mmac_params(Token
* tline
)
3443 Token
*t
, *tt
, **tail
, *thead
;
3444 bool changed
= false;
3450 if (tline
->type
== TOK_PREPROC_ID
&&
3451 (((tline
->text
[1] == '+' || tline
->text
[1] == '-')
3452 && tline
->text
[2]) || tline
->text
[1] == '%'
3453 || (tline
->text
[1] >= '0' && tline
->text
[1] <= '9'))) {
3455 int type
= 0, cc
; /* type = 0 to placate optimisers */
3462 tline
= tline
->next
;
3465 while (mac
&& !mac
->name
) /* avoid mistaking %reps for macros */
3466 mac
= mac
->next_active
;
3468 error(ERR_NONFATAL
, "`%s': not in a macro call", t
->text
);
3470 switch (t
->text
[1]) {
3472 * We have to make a substitution of one of the
3473 * forms %1, %-1, %+1, %%foo, %0.
3477 snprintf(tmpbuf
, sizeof(tmpbuf
), "%d", mac
->nparam
);
3478 text
= nasm_strdup(tmpbuf
);
3482 snprintf(tmpbuf
, sizeof(tmpbuf
), "..@%"PRIu64
".",
3484 text
= nasm_strcat(tmpbuf
, t
->text
+ 2);
3487 n
= atoi(t
->text
+ 2) - 1;
3488 if (n
>= mac
->nparam
)
3491 if (mac
->nparam
> 1)
3492 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3493 tt
= mac
->params
[n
];
3498 "macro parameter %d is not a condition code",
3503 if (inverse_ccs
[cc
] == -1) {
3505 "condition code `%s' is not invertible",
3509 text
= nasm_strdup(conditions
[inverse_ccs
[cc
]]);
3513 n
= atoi(t
->text
+ 2) - 1;
3514 if (n
>= mac
->nparam
)
3517 if (mac
->nparam
> 1)
3518 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3519 tt
= mac
->params
[n
];
3524 "macro parameter %d is not a condition code",
3529 text
= nasm_strdup(conditions
[cc
]);
3533 n
= atoi(t
->text
+ 1) - 1;
3534 if (n
>= mac
->nparam
)
3537 if (mac
->nparam
> 1)
3538 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3539 tt
= mac
->params
[n
];
3542 for (i
= 0; i
< mac
->paramlen
[n
]; i
++) {
3543 *tail
= new_Token(NULL
, tt
->type
, tt
->text
, 0);
3544 tail
= &(*tail
)->next
;
3548 text
= NULL
; /* we've done it here */
3563 } else if (tline
->type
== TOK_INDIRECT
) {
3565 tline
= tline
->next
;
3566 tt
= tokenize(t
->text
);
3567 tt
= expand_mmac_params(tt
);
3568 tt
= expand_smacro(tt
);
3571 tt
->a
.mac
= NULL
; /* Necessary? */
3579 tline
= tline
->next
;
3587 paste_tokens(&thead
, true);
3593 * Expand all single-line macro calls made in the given line.
3594 * Return the expanded version of the line. The original is deemed
3595 * to be destroyed in the process. (In reality we'll just move
3596 * Tokens from input to output a lot of the time, rather than
3597 * actually bothering to destroy and replicate.)
3599 #define DEADMAN_LIMIT (1 << 20)
3601 static Token
*expand_smacro(Token
* tline
)
3603 Token
*t
, *tt
, *mstart
, **tail
, *thead
;
3604 struct hash_table
*smtbl
;
3605 SMacro
*head
= NULL
, *m
;
3608 unsigned int nparam
, sparam
;
3610 Token
*org_tline
= tline
;
3613 int deadman
= DEADMAN_LIMIT
;
3617 * Trick: we should avoid changing the start token pointer since it can
3618 * be contained in "next" field of other token. Because of this
3619 * we allocate a copy of first token and work with it; at the end of
3620 * routine we copy it back
3624 new_Token(org_tline
->next
, org_tline
->type
, org_tline
->text
,
3626 tline
->a
.mac
= org_tline
->a
.mac
;
3627 nasm_free(org_tline
->text
);
3628 org_tline
->text
= NULL
;
3636 while (tline
) { /* main token loop */
3638 error(ERR_NONFATAL
, "interminable macro recursion");
3642 if ((mname
= tline
->text
)) {
3643 /* if this token is a local macro, look in local context */
3644 if (tline
->type
== TOK_ID
|| tline
->type
== TOK_PREPROC_ID
)
3645 ctx
= get_ctx(mname
, &mname
, true);
3648 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
3649 head
= (SMacro
*) hash_findix(smtbl
, mname
);
3652 * We've hit an identifier. As in is_mmacro below, we first
3653 * check whether the identifier is a single-line macro at
3654 * all, then think about checking for parameters if
3657 for (m
= head
; m
; m
= m
->next
)
3658 if (!mstrcmp(m
->name
, mname
, m
->casesense
))
3664 if (m
->nparam
== 0) {
3666 * Simple case: the macro is parameterless. Discard the
3667 * one token that the macro call took, and push the
3668 * expansion back on the to-do stack.
3670 if (!m
->expansion
) {
3671 if (!strcmp("__FILE__", m
->name
)) {
3674 src_get(&num
, &file
);
3675 tline
->text
= nasm_quote(file
, strlen(file
));
3676 tline
->type
= TOK_STRING
;
3680 if (!strcmp("__LINE__", m
->name
)) {
3681 nasm_free(tline
->text
);
3682 make_tok_num(tline
, src_get_linnum());
3685 if (!strcmp("__BITS__", m
->name
)) {
3686 nasm_free(tline
->text
);
3687 make_tok_num(tline
, globalbits
);
3690 tline
= delete_Token(tline
);
3695 * Complicated case: at least one macro with this name
3696 * exists and takes parameters. We must find the
3697 * parameters in the call, count them, find the SMacro
3698 * that corresponds to that form of the macro call, and
3699 * substitute for the parameters when we expand. What a
3702 /*tline = tline->next;
3703 skip_white_(tline); */
3706 while (tok_type_(t
, TOK_SMAC_END
)) {
3707 t
->a
.mac
->in_progress
= false;
3709 t
= tline
->next
= delete_Token(t
);
3712 } while (tok_type_(tline
, TOK_WHITESPACE
));
3713 if (!tok_is_(tline
, "(")) {
3715 * This macro wasn't called with parameters: ignore
3716 * the call. (Behaviour borrowed from gnu cpp.)
3725 sparam
= PARAM_DELTA
;
3726 params
= nasm_malloc(sparam
* sizeof(Token
*));
3727 params
[0] = tline
->next
;
3728 paramsize
= nasm_malloc(sparam
* sizeof(int));
3730 while (true) { /* parameter loop */
3732 * For some unusual expansions
3733 * which concatenates function call
3736 while (tok_type_(t
, TOK_SMAC_END
)) {
3737 t
->a
.mac
->in_progress
= false;
3739 t
= tline
->next
= delete_Token(t
);
3745 "macro call expects terminating `)'");
3748 if (tline
->type
== TOK_WHITESPACE
3750 if (paramsize
[nparam
])
3753 params
[nparam
] = tline
->next
;
3754 continue; /* parameter loop */
3756 if (tline
->type
== TOK_OTHER
3757 && tline
->text
[1] == 0) {
3758 char ch
= tline
->text
[0];
3759 if (ch
== ',' && !paren
&& brackets
<= 0) {
3760 if (++nparam
>= sparam
) {
3761 sparam
+= PARAM_DELTA
;
3762 params
= nasm_realloc(params
,
3767 nasm_realloc(paramsize
,
3771 params
[nparam
] = tline
->next
;
3772 paramsize
[nparam
] = 0;
3774 continue; /* parameter loop */
3777 (brackets
> 0 || (brackets
== 0 &&
3778 !paramsize
[nparam
])))
3780 if (!(brackets
++)) {
3781 params
[nparam
] = tline
->next
;
3782 continue; /* parameter loop */
3785 if (ch
== '}' && brackets
> 0)
3786 if (--brackets
== 0) {
3788 continue; /* parameter loop */
3790 if (ch
== '(' && !brackets
)
3792 if (ch
== ')' && brackets
<= 0)
3798 error(ERR_NONFATAL
, "braces do not "
3799 "enclose all of macro parameter");
3801 paramsize
[nparam
] += white
+ 1;
3803 } /* parameter loop */
3805 while (m
&& (m
->nparam
!= nparam
||
3806 mstrcmp(m
->name
, mname
,
3810 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
3811 "macro `%s' exists, "
3812 "but not taking %d parameters",
3813 mstart
->text
, nparam
);
3816 if (m
&& m
->in_progress
)
3818 if (!m
) { /* in progess or didn't find '(' or wrong nparam */
3820 * Design question: should we handle !tline, which
3821 * indicates missing ')' here, or expand those
3822 * macros anyway, which requires the (t) test a few
3826 nasm_free(paramsize
);
3830 * Expand the macro: we are placed on the last token of the
3831 * call, so that we can easily split the call from the
3832 * following tokens. We also start by pushing an SMAC_END
3833 * token for the cycle removal.
3840 tt
= new_Token(tline
, TOK_SMAC_END
, NULL
, 0);
3842 m
->in_progress
= true;
3844 for (t
= m
->expansion
; t
; t
= t
->next
) {
3845 if (t
->type
>= TOK_SMAC_PARAM
) {
3846 Token
*pcopy
= tline
, **ptail
= &pcopy
;
3850 ttt
= params
[t
->type
- TOK_SMAC_PARAM
];
3851 for (i
= paramsize
[t
->type
- TOK_SMAC_PARAM
];
3854 new_Token(tline
, ttt
->type
, ttt
->text
,
3860 } else if (t
->type
== TOK_PREPROC_Q
) {
3861 tt
= new_Token(tline
, TOK_ID
, mname
, 0);
3863 } else if (t
->type
== TOK_PREPROC_QQ
) {
3864 tt
= new_Token(tline
, TOK_ID
, m
->name
, 0);
3867 tt
= new_Token(tline
, t
->type
, t
->text
, 0);
3873 * Having done that, get rid of the macro call, and clean
3874 * up the parameters.
3877 nasm_free(paramsize
);
3880 continue; /* main token loop */
3885 if (tline
->type
== TOK_SMAC_END
) {
3886 tline
->a
.mac
->in_progress
= false;
3887 tline
= delete_Token(tline
);
3890 tline
= tline
->next
;
3898 * Now scan the entire line and look for successive TOK_IDs that resulted
3899 * after expansion (they can't be produced by tokenize()). The successive
3900 * TOK_IDs should be concatenated.
3901 * Also we look for %+ tokens and concatenate the tokens before and after
3902 * them (without white spaces in between).
3904 if (expanded
&& paste_tokens(&thead
, true)) {
3905 /* If we concatenated something, re-scan the line for macros */
3912 *org_tline
= *thead
;
3913 /* since we just gave text to org_line, don't free it */
3915 delete_Token(thead
);
3917 /* the expression expanded to empty line;
3918 we can't return NULL for some reasons
3919 we just set the line to a single WHITESPACE token. */
3920 memset(org_tline
, 0, sizeof(*org_tline
));
3921 org_tline
->text
= NULL
;
3922 org_tline
->type
= TOK_WHITESPACE
;
3931 * Similar to expand_smacro but used exclusively with macro identifiers
3932 * right before they are fetched in. The reason is that there can be
3933 * identifiers consisting of several subparts. We consider that if there
3934 * are more than one element forming the name, user wants a expansion,
3935 * otherwise it will be left as-is. Example:
3939 * the identifier %$abc will be left as-is so that the handler for %define
3940 * will suck it and define the corresponding value. Other case:
3942 * %define _%$abc cde
3944 * In this case user wants name to be expanded *before* %define starts
3945 * working, so we'll expand %$abc into something (if it has a value;
3946 * otherwise it will be left as-is) then concatenate all successive
3949 static Token
*expand_id(Token
* tline
)
3951 Token
*cur
, *oldnext
= NULL
;
3953 if (!tline
|| !tline
->next
)
3958 (cur
->next
->type
== TOK_ID
||
3959 cur
->next
->type
== TOK_PREPROC_ID
3960 || cur
->next
->type
== TOK_NUMBER
))
3963 /* If identifier consists of just one token, don't expand */
3968 oldnext
= cur
->next
; /* Detach the tail past identifier */
3969 cur
->next
= NULL
; /* so that expand_smacro stops here */
3972 tline
= expand_smacro(tline
);
3975 /* expand_smacro possibly changhed tline; re-scan for EOL */
3977 while (cur
&& cur
->next
)
3980 cur
->next
= oldnext
;
3987 * Determine whether the given line constitutes a multi-line macro
3988 * call, and return the MMacro structure called if so. Doesn't have
3989 * to check for an initial label - that's taken care of in
3990 * expand_mmacro - but must check numbers of parameters. Guaranteed
3991 * to be called with tline->type == TOK_ID, so the putative macro
3992 * name is easy to find.
3994 static MMacro
*is_mmacro(Token
* tline
, Token
*** params_array
)
4000 head
= (MMacro
*) hash_findix(&mmacros
, tline
->text
);
4003 * Efficiency: first we see if any macro exists with the given
4004 * name. If not, we can return NULL immediately. _Then_ we
4005 * count the parameters, and then we look further along the
4006 * list if necessary to find the proper MMacro.
4008 for (m
= head
; m
; m
= m
->next
)
4009 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4015 * OK, we have a potential macro. Count and demarcate the
4018 count_mmac_params(tline
->next
, &nparam
, ¶ms
);
4021 * So we know how many parameters we've got. Find the MMacro
4022 * structure that handles this number.
4025 if (m
->nparam_min
<= nparam
4026 && (m
->plus
|| nparam
<= m
->nparam_max
)) {
4028 * This one is right. Just check if cycle removal
4029 * prohibits us using it before we actually celebrate...
4031 if (m
->in_progress
) {
4034 "self-reference in multi-line macro `%s'", m
->name
);
4040 * It's right, and we can use it. Add its default
4041 * parameters to the end of our list if necessary.
4043 if (m
->defaults
&& nparam
< m
->nparam_min
+ m
->ndefs
) {
4045 nasm_realloc(params
,
4046 ((m
->nparam_min
+ m
->ndefs
+
4047 1) * sizeof(*params
)));
4048 while (nparam
< m
->nparam_min
+ m
->ndefs
) {
4049 params
[nparam
] = m
->defaults
[nparam
- m
->nparam_min
];
4054 * If we've gone over the maximum parameter count (and
4055 * we're in Plus mode), ignore parameters beyond
4058 if (m
->plus
&& nparam
> m
->nparam_max
)
4059 nparam
= m
->nparam_max
;
4061 * Then terminate the parameter list, and leave.
4063 if (!params
) { /* need this special case */
4064 params
= nasm_malloc(sizeof(*params
));
4067 params
[nparam
] = NULL
;
4068 *params_array
= params
;
4072 * This one wasn't right: look for the next one with the
4075 for (m
= m
->next
; m
; m
= m
->next
)
4076 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4081 * After all that, we didn't find one with the right number of
4082 * parameters. Issue a warning, and fail to expand the macro.
4084 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4085 "macro `%s' exists, but not taking %d parameters",
4086 tline
->text
, nparam
);
4092 * Expand the multi-line macro call made by the given line, if
4093 * there is one to be expanded. If there is, push the expansion on
4094 * istk->expansion and return 1. Otherwise return 0.
4096 static int expand_mmacro(Token
* tline
)
4098 Token
*startline
= tline
;
4099 Token
*label
= NULL
;
4100 int dont_prepend
= 0;
4101 Token
**params
, *t
, *mtok
, *tt
;
4104 int i
, nparam
, *paramlen
;
4109 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4110 if (!tok_type_(t
, TOK_ID
) && !tok_type_(t
, TOK_PREPROC_ID
))
4113 m
= is_mmacro(t
, ¶ms
);
4119 * We have an id which isn't a macro call. We'll assume
4120 * it might be a label; we'll also check to see if a
4121 * colon follows it. Then, if there's another id after
4122 * that lot, we'll check it again for macro-hood.
4126 if (tok_type_(t
, TOK_WHITESPACE
))
4127 last
= t
, t
= t
->next
;
4128 if (tok_is_(t
, ":")) {
4130 last
= t
, t
= t
->next
;
4131 if (tok_type_(t
, TOK_WHITESPACE
))
4132 last
= t
, t
= t
->next
;
4134 if (!tok_type_(t
, TOK_ID
) || (m
= is_mmacro(t
, ¶ms
)) == NULL
)
4142 * Fix up the parameters: this involves stripping leading and
4143 * trailing whitespace, then stripping braces if they are
4146 for (nparam
= 0; params
[nparam
]; nparam
++) ;
4147 paramlen
= nparam
? nasm_malloc(nparam
* sizeof(*paramlen
)) : NULL
;
4149 for (i
= 0; params
[i
]; i
++) {
4151 int comma
= (!m
->plus
|| i
< nparam
- 1);
4155 if (tok_is_(t
, "{"))
4156 t
= t
->next
, brace
= true, comma
= false;
4160 if (comma
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, ","))
4161 break; /* ... because we have hit a comma */
4162 if (comma
&& t
->type
== TOK_WHITESPACE
4163 && tok_is_(t
->next
, ","))
4164 break; /* ... or a space then a comma */
4165 if (brace
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, "}"))
4166 break; /* ... or a brace */
4173 * OK, we have a MMacro structure together with a set of
4174 * parameters. We must now go through the expansion and push
4175 * copies of each Line on to istk->expansion. Substitution of
4176 * parameter tokens and macro-local tokens doesn't get done
4177 * until the single-line macro substitution process; this is
4178 * because delaying them allows us to change the semantics
4179 * later through %rotate.
4181 * First, push an end marker on to istk->expansion, mark this
4182 * macro as in progress, and set up its invocation-specific
4185 ll
= nasm_malloc(sizeof(Line
));
4186 ll
->next
= istk
->expansion
;
4189 istk
->expansion
= ll
;
4191 m
->in_progress
= true;
4196 m
->paramlen
= paramlen
;
4197 m
->unique
= unique
++;
4200 m
->next_active
= istk
->mstk
;
4203 for (l
= m
->expansion
; l
; l
= l
->next
) {
4206 ll
= nasm_malloc(sizeof(Line
));
4207 ll
->finishes
= NULL
;
4208 ll
->next
= istk
->expansion
;
4209 istk
->expansion
= ll
;
4212 for (t
= l
->first
; t
; t
= t
->next
) {
4216 tt
= *tail
= new_Token(NULL
, TOK_ID
, mname
, 0);
4218 case TOK_PREPROC_QQ
:
4219 tt
= *tail
= new_Token(NULL
, TOK_ID
, m
->name
, 0);
4221 case TOK_PREPROC_ID
:
4222 if (t
->text
[1] == '0' && t
->text
[2] == '0') {
4230 tt
= *tail
= new_Token(NULL
, x
->type
, x
->text
, 0);
4239 * If we had a label, push it on as the first line of
4240 * the macro expansion.
4243 if (dont_prepend
< 0)
4244 free_tlist(startline
);
4246 ll
= nasm_malloc(sizeof(Line
));
4247 ll
->finishes
= NULL
;
4248 ll
->next
= istk
->expansion
;
4249 istk
->expansion
= ll
;
4250 ll
->first
= startline
;
4251 if (!dont_prepend
) {
4253 label
= label
->next
;
4254 label
->next
= tt
= new_Token(NULL
, TOK_OTHER
, ":", 0);
4259 list
->uplevel(m
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
4264 /* The function that actually does the error reporting */
4265 static void verror(int severity
, const char *fmt
, va_list arg
)
4269 vsnprintf(buff
, sizeof(buff
), fmt
, arg
);
4271 if (istk
&& istk
->mstk
&& istk
->mstk
->name
)
4272 _error(severity
, "(%s:%d) %s", istk
->mstk
->name
,
4273 istk
->mstk
->lineno
, buff
);
4275 _error(severity
, "%s", buff
);
4279 * Since preprocessor always operate only on the line that didn't
4280 * arrived yet, we should always use ERR_OFFBY1.
4282 static void error(int severity
, const char *fmt
, ...)
4286 /* If we're in a dead branch of IF or something like it, ignore the error */
4287 if (istk
&& istk
->conds
&& !emitting(istk
->conds
->state
))
4291 verror(severity
, fmt
, arg
);
4296 * Because %else etc are evaluated in the state context
4297 * of the previous branch, errors might get lost with error():
4298 * %if 0 ... %else trailing garbage ... %endif
4299 * So %else etc should report errors with this function.
4301 static void error_precond(int severity
, const char *fmt
, ...)
4305 /* Only ignore the error if it's really in a dead branch */
4306 if (istk
&& istk
->conds
&& istk
->conds
->state
== COND_NEVER
)
4310 verror(severity
, fmt
, arg
);
4315 pp_reset(char *file
, int apass
, efunc errfunc
, evalfunc eval
,
4316 ListGen
* listgen
, StrList
**deplist
)
4322 istk
= nasm_malloc(sizeof(Include
));
4325 istk
->expansion
= NULL
;
4327 istk
->fp
= fopen(file
, "r");
4329 src_set_fname(nasm_strdup(file
));
4333 error(ERR_FATAL
|ERR_NOFILE
, "unable to open input file `%s'",
4336 nested_mac_count
= 0;
4337 nested_rep_count
= 0;
4340 if (tasm_compatible_mode
) {
4341 stdmacpos
= nasm_stdmac
;
4343 stdmacpos
= nasm_stdmac_after_tasm
;
4345 any_extrastdmac
= extrastdmac
&& *extrastdmac
;
4351 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4352 * The caller, however, will also pass in 3 for preprocess-only so
4353 * we can set __PASS__ accordingly.
4355 pass
= apass
> 2 ? 2 : apass
;
4357 dephead
= deptail
= deplist
;
4359 StrList
*sl
= nasm_malloc(strlen(file
)+1+sizeof sl
->next
);
4361 strcpy(sl
->str
, file
);
4363 deptail
= &sl
->next
;
4367 * Define the __PASS__ macro. This is defined here unlike
4368 * all the other builtins, because it is special -- it varies between
4371 t
= nasm_malloc(sizeof(*t
));
4373 make_tok_num(t
, apass
);
4375 define_smacro(NULL
, "__PASS__", true, 0, t
);
4378 static char *pp_getline(void)
4385 * Fetch a tokenized line, either from the macro-expansion
4386 * buffer or from the input file.
4389 while (istk
->expansion
&& istk
->expansion
->finishes
) {
4390 Line
*l
= istk
->expansion
;
4391 if (!l
->finishes
->name
&& l
->finishes
->in_progress
> 1) {
4395 * This is a macro-end marker for a macro with no
4396 * name, which means it's not really a macro at all
4397 * but a %rep block, and the `in_progress' field is
4398 * more than 1, meaning that we still need to
4399 * repeat. (1 means the natural last repetition; 0
4400 * means termination by %exitrep.) We have
4401 * therefore expanded up to the %endrep, and must
4402 * push the whole block on to the expansion buffer
4403 * again. We don't bother to remove the macro-end
4404 * marker: we'd only have to generate another one
4407 l
->finishes
->in_progress
--;
4408 for (l
= l
->finishes
->expansion
; l
; l
= l
->next
) {
4409 Token
*t
, *tt
, **tail
;
4411 ll
= nasm_malloc(sizeof(Line
));
4412 ll
->next
= istk
->expansion
;
4413 ll
->finishes
= NULL
;
4417 for (t
= l
->first
; t
; t
= t
->next
) {
4418 if (t
->text
|| t
->type
== TOK_WHITESPACE
) {
4420 new_Token(NULL
, t
->type
, t
->text
, 0);
4425 istk
->expansion
= ll
;
4429 * Check whether a `%rep' was started and not ended
4430 * within this macro expansion. This can happen and
4431 * should be detected. It's a fatal error because
4432 * I'm too confused to work out how to recover
4438 "defining with name in expansion");
4439 else if (istk
->mstk
->name
)
4441 "`%%rep' without `%%endrep' within"
4442 " expansion of macro `%s'",
4447 * FIXME: investigate the relationship at this point between
4448 * istk->mstk and l->finishes
4451 MMacro
*m
= istk
->mstk
;
4452 istk
->mstk
= m
->next_active
;
4455 * This was a real macro call, not a %rep, and
4456 * therefore the parameter information needs to
4459 nasm_free(m
->params
);
4460 free_tlist(m
->iline
);
4461 nasm_free(m
->paramlen
);
4462 l
->finishes
->in_progress
= false;
4466 istk
->expansion
= l
->next
;
4468 list
->downlevel(LIST_MACRO
);
4471 while (1) { /* until we get a line we can use */
4473 if (istk
->expansion
) { /* from a macro expansion */
4475 Line
*l
= istk
->expansion
;
4477 istk
->mstk
->lineno
++;
4479 istk
->expansion
= l
->next
;
4481 p
= detoken(tline
, false);
4482 list
->line(LIST_MACRO
, p
);
4487 if (line
) { /* from the current input file */
4488 line
= prepreproc(line
);
4489 tline
= tokenize(line
);
4494 * The current file has ended; work down the istk
4501 "expected `%%endif' before end of file");
4502 /* only set line and file name if there's a next node */
4504 src_set_linnum(i
->lineno
);
4505 nasm_free(src_set_fname(i
->fname
));
4508 list
->downlevel(LIST_INCLUDE
);
4512 if (istk
->expansion
&& istk
->expansion
->finishes
)
4518 * We must expand MMacro parameters and MMacro-local labels
4519 * _before_ we plunge into directive processing, to cope
4520 * with things like `%define something %1' such as STRUC
4521 * uses. Unless we're _defining_ a MMacro, in which case
4522 * those tokens should be left alone to go into the
4523 * definition; and unless we're in a non-emitting
4524 * condition, in which case we don't want to meddle with
4527 if (!defining
&& !(istk
->conds
&& !emitting(istk
->conds
->state
))
4528 && !(istk
->mstk
&& !istk
->mstk
->in_progress
)) {
4529 tline
= expand_mmac_params(tline
);
4533 * Check the line to see if it's a preprocessor directive.
4535 if (do_directive(tline
) == DIRECTIVE_FOUND
) {
4537 } else if (defining
) {
4539 * We're defining a multi-line macro. We emit nothing
4541 * shove the tokenized line on to the macro definition.
4543 Line
*l
= nasm_malloc(sizeof(Line
));
4544 l
->next
= defining
->expansion
;
4547 defining
->expansion
= l
;
4549 } else if (istk
->conds
&& !emitting(istk
->conds
->state
)) {
4551 * We're in a non-emitting branch of a condition block.
4552 * Emit nothing at all, not even a blank line: when we
4553 * emerge from the condition we'll give a line-number
4554 * directive so we keep our place correctly.
4558 } else if (istk
->mstk
&& !istk
->mstk
->in_progress
) {
4560 * We're in a %rep block which has been terminated, so
4561 * we're walking through to the %endrep without
4562 * emitting anything. Emit nothing at all, not even a
4563 * blank line: when we emerge from the %rep block we'll
4564 * give a line-number directive so we keep our place
4570 tline
= expand_smacro(tline
);
4571 if (!expand_mmacro(tline
)) {
4573 * De-tokenize the line again, and emit it.
4575 line
= detoken(tline
, true);
4579 continue; /* expand_mmacro calls free_tlist */
4587 static void pp_cleanup(int pass
)
4590 if(defining
->name
) {
4592 "end of file while still defining macro `%s'",
4595 error(ERR_NONFATAL
, "end of file while still in %%rep");
4598 free_mmacro(defining
);
4607 nasm_free(i
->fname
);
4612 nasm_free(src_set_fname(NULL
));
4617 while ((i
= ipath
)) {
4626 void pp_include_path(char *path
)
4630 i
= nasm_malloc(sizeof(IncPath
));
4631 i
->path
= path
? nasm_strdup(path
) : NULL
;
4634 if (ipath
!= NULL
) {
4636 while (j
->next
!= NULL
)
4644 void pp_pre_include(char *fname
)
4646 Token
*inc
, *space
, *name
;
4649 name
= new_Token(NULL
, TOK_INTERNAL_STRING
, fname
, 0);
4650 space
= new_Token(name
, TOK_WHITESPACE
, NULL
, 0);
4651 inc
= new_Token(space
, TOK_PREPROC_ID
, "%include", 0);
4653 l
= nasm_malloc(sizeof(Line
));
4660 void pp_pre_define(char *definition
)
4666 equals
= strchr(definition
, '=');
4667 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
4668 def
= new_Token(space
, TOK_PREPROC_ID
, "%define", 0);
4671 space
->next
= tokenize(definition
);
4675 l
= nasm_malloc(sizeof(Line
));
4682 void pp_pre_undefine(char *definition
)
4687 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
4688 def
= new_Token(space
, TOK_PREPROC_ID
, "%undef", 0);
4689 space
->next
= tokenize(definition
);
4691 l
= nasm_malloc(sizeof(Line
));
4699 * Added by Keith Kanios:
4701 * This function is used to assist with "runtime" preprocessor
4702 * directives. (e.g. pp_runtime("%define __BITS__ 64");)
4704 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
4705 * PASS A VALID STRING TO THIS FUNCTION!!!!!
4708 void pp_runtime(char *definition
)
4712 def
= tokenize(definition
);
4713 if(do_directive(def
) == NO_DIRECTIVE_FOUND
)
4718 void pp_extra_stdmac(macros_t
*macros
)
4720 extrastdmac
= macros
;
4723 static void make_tok_num(Token
* tok
, int64_t val
)
4726 snprintf(numbuf
, sizeof(numbuf
), "%"PRId64
"", val
);
4727 tok
->text
= nasm_strdup(numbuf
);
4728 tok
->type
= TOK_NUMBER
;