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
) {
456 /* NASM does not recognise IFDIFI, so we convert it to
457 * %ifdef BOGUS. This is not used in NASM comaptible
458 * code, but does need to parse for the TASM macro
461 strcpy(line
+ 1, "ifdef BOGUS");
463 memcpy(line
+ 1, p
, len
+ 1);
478 * The pre-preprocessing stage... This function translates line
479 * number indications as they emerge from GNU cpp (`# lineno "file"
480 * flags') into NASM preprocessor line number indications (`%line
483 static char *prepreproc(char *line
)
486 char *fname
, *oldline
;
488 if (line
[0] == '#' && line
[1] == ' ') {
491 lineno
= atoi(fname
);
492 fname
+= strspn(fname
, "0123456789 ");
495 fnlen
= strcspn(fname
, "\"");
496 line
= nasm_malloc(20 + fnlen
);
497 snprintf(line
, 20 + fnlen
, "%%line %d %.*s", lineno
, fnlen
, fname
);
500 if (tasm_compatible_mode
)
501 return check_tasm_directive(line
);
506 * Free a linked list of tokens.
508 static void free_tlist(Token
* list
)
511 list
= delete_Token(list
);
516 * Free a linked list of lines.
518 static void free_llist(Line
* list
)
524 free_tlist(l
->first
);
532 static void free_mmacro(MMacro
* m
)
535 free_tlist(m
->dlist
);
536 nasm_free(m
->defaults
);
537 free_llist(m
->expansion
);
542 * Free all currently defined macros, and free the hash tables
544 static void free_smacro_table(struct hash_table
*smt
)
548 struct hash_tbl_node
*it
= NULL
;
550 while ((s
= hash_iterate(smt
, &it
, &key
)) != NULL
) {
551 nasm_free((void *)key
);
553 SMacro
*ns
= s
->next
;
555 free_tlist(s
->expansion
);
563 static void free_mmacro_table(struct hash_table
*mmt
)
567 struct hash_tbl_node
*it
= NULL
;
570 while ((m
= hash_iterate(mmt
, &it
, &key
)) != NULL
) {
571 nasm_free((void *)key
);
573 MMacro
*nm
= m
->next
;
581 static void free_macros(void)
583 free_smacro_table(&smacros
);
584 free_mmacro_table(&mmacros
);
588 * Initialize the hash tables
590 static void init_macros(void)
592 hash_init(&smacros
, HASH_LARGE
);
593 hash_init(&mmacros
, HASH_LARGE
);
597 * Pop the context stack.
599 static void ctx_pop(void)
604 free_smacro_table(&c
->localmac
);
610 * Search for a key in the hash index; adding it if necessary
611 * (in which case we initialize the data pointer to NULL.)
614 hash_findi_add(struct hash_table
*hash
, const char *str
)
616 struct hash_insert hi
;
620 r
= hash_findi(hash
, str
, &hi
);
624 strx
= nasm_strdup(str
); /* Use a more efficient allocator here? */
625 return hash_add(&hi
, strx
, NULL
);
629 * Like hash_findi, but returns the data element rather than a pointer
630 * to it. Used only when not adding a new element, hence no third
634 hash_findix(struct hash_table
*hash
, const char *str
)
638 p
= hash_findi(hash
, str
, NULL
);
639 return p
? *p
: NULL
;
642 #define BUF_DELTA 512
644 * Read a line from the top file in istk, handling multiple CR/LFs
645 * at the end of the line read, and handling spurious ^Zs. Will
646 * return lines from the standard macro set if this has not already
649 static char *read_line(void)
651 char *buffer
, *p
, *q
;
652 int bufsize
, continued_count
;
656 const unsigned char *p
= stdmacpos
;
661 len
+= pp_directives_len
[c
-0x80]+1;
665 ret
= nasm_malloc(len
+1);
667 while ((c
= *stdmacpos
++)) {
669 memcpy(q
, pp_directives
[c
-0x80], pp_directives_len
[c
-0x80]);
670 q
+= pp_directives_len
[c
-0x80];
680 /* This was the last of the standard macro chain... */
682 if (any_extrastdmac
) {
683 stdmacpos
= extrastdmac
;
684 any_extrastdmac
= false;
685 } else if (do_predef
) {
687 Token
*head
, **tail
, *t
;
690 * Nasty hack: here we push the contents of
691 * `predef' on to the top-level expansion stack,
692 * since this is the most convenient way to
693 * implement the pre-include and pre-define
696 for (pd
= predef
; pd
; pd
= pd
->next
) {
699 for (t
= pd
->first
; t
; t
= t
->next
) {
700 *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
701 tail
= &(*tail
)->next
;
703 l
= nasm_malloc(sizeof(Line
));
704 l
->next
= istk
->expansion
;
716 buffer
= nasm_malloc(BUF_DELTA
);
720 q
= fgets(p
, bufsize
- (p
- buffer
), istk
->fp
);
724 if (p
> buffer
&& p
[-1] == '\n') {
725 /* Convert backslash-CRLF line continuation sequences into
726 nothing at all (for DOS and Windows) */
727 if (((p
- 2) > buffer
) && (p
[-3] == '\\') && (p
[-2] == '\r')) {
732 /* Also convert backslash-LF line continuation sequences into
733 nothing at all (for Unix) */
734 else if (((p
- 1) > buffer
) && (p
[-2] == '\\')) {
742 if (p
- buffer
> bufsize
- 10) {
743 int32_t offset
= p
- buffer
;
744 bufsize
+= BUF_DELTA
;
745 buffer
= nasm_realloc(buffer
, bufsize
);
746 p
= buffer
+ offset
; /* prevent stale-pointer problems */
750 if (!q
&& p
== buffer
) {
755 src_set_linnum(src_get_linnum() + istk
->lineinc
+
756 (continued_count
* istk
->lineinc
));
759 * Play safe: remove CRs as well as LFs, if any of either are
760 * present at the end of the line.
762 while (--p
>= buffer
&& (*p
== '\n' || *p
== '\r'))
766 * Handle spurious ^Z, which may be inserted into source files
767 * by some file transfer utilities.
769 buffer
[strcspn(buffer
, "\032")] = '\0';
771 list
->line(LIST_READ
, buffer
);
777 * Tokenize a line of text. This is a very simple process since we
778 * don't need to parse the value out of e.g. numeric tokens: we
779 * simply split one string into many.
781 static Token
*tokenize(char *line
)
784 enum pp_token_type type
;
786 Token
*t
, **tail
= &list
;
792 if (*p
== '+' && !nasm_isdigit(p
[1])) {
795 } else if (nasm_isdigit(*p
) ||
796 ((*p
== '-' || *p
== '+') && nasm_isdigit(p
[1]))) {
800 while (nasm_isdigit(*p
));
801 type
= TOK_PREPROC_ID
;
802 } else if (*p
== '{') {
804 while (*p
&& *p
!= '}') {
811 type
= TOK_PREPROC_ID
;
812 } else if (*p
== '[') {
814 line
+= 2; /* Skip the leading %[ */
816 while (lvl
&& (c
= *p
++)) {
828 p
= nasm_skip_string(p
)+1;
838 error(ERR_NONFATAL
, "unterminated %[ construct");
840 } else if (*p
== '?') {
841 type
= TOK_PREPROC_Q
; /* %? */
844 type
= TOK_PREPROC_QQ
; /* %?? */
847 } else if (isidchar(*p
) ||
848 ((*p
== '!' || *p
== '%' || *p
== '$') &&
853 while (isidchar(*p
));
854 type
= TOK_PREPROC_ID
;
860 } else if (isidstart(*p
) || (*p
== '$' && isidstart(p
[1]))) {
863 while (*p
&& isidchar(*p
))
865 } else if (*p
== '\'' || *p
== '"' || *p
== '`') {
870 p
= nasm_skip_string(p
);
875 error(ERR_WARNING
|ERR_PASS1
, "unterminated string");
876 /* Handling unterminated strings by UNV */
879 } else if (p
[0] == '$' && p
[1] == '$') {
880 type
= TOK_OTHER
; /* TOKEN_BASE */
882 } else if (isnumstart(*p
)) {
884 bool is_float
= false;
900 if (!is_hex
&& (c
== 'e' || c
== 'E')) {
902 if (*p
== '+' || *p
== '-') {
903 /* e can only be followed by +/- if it is either a
904 prefixed hex number or a floating-point number */
908 } else if (c
== 'H' || c
== 'h' || c
== 'X' || c
== 'x') {
910 } else if (c
== 'P' || c
== 'p') {
912 if (*p
== '+' || *p
== '-')
914 } else if (isnumchar(c
) || c
== '_')
917 /* we need to deal with consequences of the legacy
918 parser, like "1.nolist" being two tokens
919 (TOK_NUMBER, TOK_ID) here; at least give it
920 a shot for now. In the future, we probably need
921 a flex-based scanner with proper pattern matching
922 to do it as well as it can be done. Nothing in
923 the world is going to help the person who wants
924 0x123.p16 interpreted as two tokens, though. */
929 if (nasm_isdigit(*r
) || (is_hex
&& nasm_isxdigit(*r
)) ||
930 (!is_hex
&& (*r
== 'e' || *r
== 'E')) ||
931 (*r
== 'p' || *r
== 'P')) {
935 break; /* Terminate the token */
939 p
--; /* Point to first character beyond number */
941 if (p
== line
+1 && *line
== '$') {
942 type
= TOK_OTHER
; /* TOKEN_HERE */
944 if (has_e
&& !is_hex
) {
945 /* 1e13 is floating-point, but 1e13h is not */
949 type
= is_float
? TOK_FLOAT
: TOK_NUMBER
;
951 } else if (nasm_isspace(*p
)) {
952 type
= TOK_WHITESPACE
;
954 while (*p
&& nasm_isspace(*p
))
957 * Whitespace just before end-of-line is discarded by
958 * pretending it's a comment; whitespace just before a
959 * comment gets lumped into the comment.
961 if (!*p
|| *p
== ';') {
966 } else if (*p
== ';') {
972 * Anything else is an operator of some kind. We check
973 * for all the double-character operators (>>, <<, //,
974 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
975 * else is a single-character operator.
978 if ((p
[0] == '>' && p
[1] == '>') ||
979 (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] == '^')) {
994 /* Handling unterminated string by UNV */
997 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
998 t->text[p-line] = *line;
1002 if (type
!= TOK_COMMENT
) {
1003 *tail
= t
= new_Token(NULL
, type
, line
, p
- line
);
1012 * this function allocates a new managed block of memory and
1013 * returns a pointer to the block. The managed blocks are
1014 * deleted only all at once by the delete_Blocks function.
1016 static void *new_Block(size_t size
)
1018 Blocks
*b
= &blocks
;
1020 /* first, get to the end of the linked list */
1023 /* now allocate the requested chunk */
1024 b
->chunk
= nasm_malloc(size
);
1026 /* now allocate a new block for the next request */
1027 b
->next
= nasm_malloc(sizeof(Blocks
));
1028 /* and initialize the contents of the new block */
1029 b
->next
->next
= NULL
;
1030 b
->next
->chunk
= NULL
;
1035 * this function deletes all managed blocks of memory
1037 static void delete_Blocks(void)
1039 Blocks
*a
, *b
= &blocks
;
1042 * keep in mind that the first block, pointed to by blocks
1043 * is a static and not dynamically allocated, so we don't
1048 nasm_free(b
->chunk
);
1057 * this function creates a new Token and passes a pointer to it
1058 * back to the caller. It sets the type and text elements, and
1059 * also the a.mac and next elements to NULL.
1061 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
1062 const char *text
, int txtlen
)
1067 if (freeTokens
== NULL
) {
1068 freeTokens
= (Token
*) new_Block(TOKEN_BLOCKSIZE
* sizeof(Token
));
1069 for (i
= 0; i
< TOKEN_BLOCKSIZE
- 1; i
++)
1070 freeTokens
[i
].next
= &freeTokens
[i
+ 1];
1071 freeTokens
[i
].next
= NULL
;
1074 freeTokens
= t
->next
;
1078 if (type
== TOK_WHITESPACE
|| text
== NULL
) {
1082 txtlen
= strlen(text
);
1083 t
->text
= nasm_malloc(txtlen
+1);
1084 memcpy(t
->text
, text
, txtlen
);
1085 t
->text
[txtlen
] = '\0';
1090 static Token
*delete_Token(Token
* t
)
1092 Token
*next
= t
->next
;
1094 t
->next
= freeTokens
;
1100 * Convert a line of tokens back into text.
1101 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1102 * will be transformed into ..@ctxnum.xxx
1104 static char *detoken(Token
* tlist
, bool expand_locals
)
1112 for (t
= tlist
; t
; t
= t
->next
) {
1113 if (t
->type
== TOK_PREPROC_ID
&& t
->text
[1] == '!') {
1114 char *p
= getenv(t
->text
+ 2);
1117 t
->text
= nasm_strdup(p
);
1121 /* Expand local macros here and not during preprocessing */
1122 if (expand_locals
&&
1123 t
->type
== TOK_PREPROC_ID
&& t
->text
&&
1124 t
->text
[0] == '%' && t
->text
[1] == '$') {
1127 Context
*ctx
= get_ctx(t
->text
, &q
, false);
1130 snprintf(buffer
, sizeof(buffer
), "..@%"PRIu32
".", ctx
->number
);
1131 p
= nasm_strcat(buffer
, q
);
1136 if (t
->type
== TOK_WHITESPACE
) {
1138 } else if (t
->text
) {
1139 len
+= strlen(t
->text
);
1142 p
= line
= nasm_malloc(len
+ 1);
1143 for (t
= tlist
; t
; t
= t
->next
) {
1144 if (t
->type
== TOK_WHITESPACE
) {
1146 } else if (t
->text
) {
1157 * A scanner, suitable for use by the expression evaluator, which
1158 * operates on a line of Tokens. Expects a pointer to a pointer to
1159 * the first token in the line to be passed in as its private_data
1162 * FIX: This really needs to be unified with stdscan.
1164 static int ppscan(void *private_data
, struct tokenval
*tokval
)
1166 Token
**tlineptr
= private_data
;
1168 char ourcopy
[MAX_KEYWORD
+1], *p
, *r
, *s
;
1172 *tlineptr
= tline
? tline
->next
: NULL
;
1174 while (tline
&& (tline
->type
== TOK_WHITESPACE
||
1175 tline
->type
== TOK_COMMENT
));
1178 return tokval
->t_type
= TOKEN_EOS
;
1180 tokval
->t_charptr
= tline
->text
;
1182 if (tline
->text
[0] == '$' && !tline
->text
[1])
1183 return tokval
->t_type
= TOKEN_HERE
;
1184 if (tline
->text
[0] == '$' && tline
->text
[1] == '$' && !tline
->text
[2])
1185 return tokval
->t_type
= TOKEN_BASE
;
1187 if (tline
->type
== TOK_ID
) {
1188 p
= tokval
->t_charptr
= tline
->text
;
1190 tokval
->t_charptr
++;
1191 return tokval
->t_type
= TOKEN_ID
;
1194 for (r
= p
, s
= ourcopy
; *r
; r
++) {
1195 if (r
>= p
+MAX_KEYWORD
)
1196 return tokval
->t_type
= TOKEN_ID
; /* Not a keyword */
1197 *s
++ = nasm_tolower(*r
);
1200 /* right, so we have an identifier sitting in temp storage. now,
1201 * is it actually a register or instruction name, or what? */
1202 return nasm_token_hash(ourcopy
, tokval
);
1205 if (tline
->type
== TOK_NUMBER
) {
1207 tokval
->t_integer
= readnum(tline
->text
, &rn_error
);
1208 tokval
->t_charptr
= tline
->text
;
1210 return tokval
->t_type
= TOKEN_ERRNUM
;
1212 return tokval
->t_type
= TOKEN_NUM
;
1215 if (tline
->type
== TOK_FLOAT
) {
1216 return tokval
->t_type
= TOKEN_FLOAT
;
1219 if (tline
->type
== TOK_STRING
) {
1222 bq
= tline
->text
[0];
1223 tokval
->t_charptr
= tline
->text
;
1224 tokval
->t_inttwo
= nasm_unquote(tline
->text
, &ep
);
1226 if (ep
[0] != bq
|| ep
[1] != '\0')
1227 return tokval
->t_type
= TOKEN_ERRSTR
;
1229 return tokval
->t_type
= TOKEN_STR
;
1232 if (tline
->type
== TOK_OTHER
) {
1233 if (!strcmp(tline
->text
, "<<"))
1234 return tokval
->t_type
= TOKEN_SHL
;
1235 if (!strcmp(tline
->text
, ">>"))
1236 return tokval
->t_type
= TOKEN_SHR
;
1237 if (!strcmp(tline
->text
, "//"))
1238 return tokval
->t_type
= TOKEN_SDIV
;
1239 if (!strcmp(tline
->text
, "%%"))
1240 return tokval
->t_type
= TOKEN_SMOD
;
1241 if (!strcmp(tline
->text
, "=="))
1242 return tokval
->t_type
= TOKEN_EQ
;
1243 if (!strcmp(tline
->text
, "<>"))
1244 return tokval
->t_type
= TOKEN_NE
;
1245 if (!strcmp(tline
->text
, "!="))
1246 return tokval
->t_type
= TOKEN_NE
;
1247 if (!strcmp(tline
->text
, "<="))
1248 return tokval
->t_type
= TOKEN_LE
;
1249 if (!strcmp(tline
->text
, ">="))
1250 return tokval
->t_type
= TOKEN_GE
;
1251 if (!strcmp(tline
->text
, "&&"))
1252 return tokval
->t_type
= TOKEN_DBL_AND
;
1253 if (!strcmp(tline
->text
, "^^"))
1254 return tokval
->t_type
= TOKEN_DBL_XOR
;
1255 if (!strcmp(tline
->text
, "||"))
1256 return tokval
->t_type
= TOKEN_DBL_OR
;
1260 * We have no other options: just return the first character of
1263 return tokval
->t_type
= tline
->text
[0];
1267 * Compare a string to the name of an existing macro; this is a
1268 * simple wrapper which calls either strcmp or nasm_stricmp
1269 * depending on the value of the `casesense' parameter.
1271 static int mstrcmp(const char *p
, const char *q
, bool casesense
)
1273 return casesense
? strcmp(p
, q
) : nasm_stricmp(p
, q
);
1277 * Compare a string to the name of an existing macro; this is a
1278 * simple wrapper which calls either strcmp or nasm_stricmp
1279 * depending on the value of the `casesense' parameter.
1281 static int mmemcmp(const char *p
, const char *q
, size_t l
, bool casesense
)
1283 return casesense
? memcmp(p
, q
, l
) : nasm_memicmp(p
, q
, l
);
1287 * Return the Context structure associated with a %$ token. Return
1288 * NULL, having _already_ reported an error condition, if the
1289 * context stack isn't deep enough for the supplied number of $
1291 * If all_contexts == true, contexts that enclose current are
1292 * also scanned for such smacro, until it is found; if not -
1293 * only the context that directly results from the number of $'s
1294 * in variable's name.
1296 * If "namep" is non-NULL, set it to the pointer to the macro name
1297 * tail, i.e. the part beyond %$...
1299 static Context
*get_ctx(const char *name
, const char **namep
,
1309 if (!name
|| name
[0] != '%' || name
[1] != '$')
1313 error(ERR_NONFATAL
, "`%s': context stack is empty", name
);
1320 while (ctx
&& *name
== '$') {
1326 error(ERR_NONFATAL
, "`%s': context stack is only"
1327 " %d level%s deep", name
, i
, (i
== 1 ? "" : "s"));
1338 /* Search for this smacro in found context */
1339 m
= hash_findix(&ctx
->localmac
, name
);
1341 if (!mstrcmp(m
->name
, name
, m
->casesense
))
1352 * Check to see if a file is already in a string list
1354 static bool in_list(const StrList
*list
, const char *str
)
1357 if (!strcmp(list
->str
, str
))
1365 * Open an include file. This routine must always return a valid
1366 * file pointer if it returns - it's responsible for throwing an
1367 * ERR_FATAL and bombing out completely if not. It should also try
1368 * the include path one by one until it finds the file or reaches
1369 * the end of the path.
1371 static FILE *inc_fopen(const char *file
, StrList
**dhead
, StrList
***dtail
,
1376 IncPath
*ip
= ipath
;
1377 int len
= strlen(file
);
1378 size_t prefix_len
= 0;
1382 sl
= nasm_malloc(prefix_len
+len
+1+sizeof sl
->next
);
1383 memcpy(sl
->str
, prefix
, prefix_len
);
1384 memcpy(sl
->str
+prefix_len
, file
, len
+1);
1385 fp
= fopen(sl
->str
, "r");
1386 if (fp
&& dhead
&& !in_list(*dhead
, sl
->str
)) {
1404 prefix_len
= strlen(prefix
);
1406 /* -MG given and file not found */
1407 if (dhead
&& !in_list(*dhead
, file
)) {
1408 sl
= nasm_malloc(len
+1+sizeof sl
->next
);
1410 strcpy(sl
->str
, file
);
1418 error(ERR_FATAL
, "unable to open include file `%s'", file
);
1419 return NULL
; /* never reached - placate compilers */
1423 * Determine if we should warn on defining a single-line macro of
1424 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1425 * return true if _any_ single-line macro of that name is defined.
1426 * Otherwise, will return true if a single-line macro with either
1427 * `nparam' or no parameters is defined.
1429 * If a macro with precisely the right number of parameters is
1430 * defined, or nparam is -1, the address of the definition structure
1431 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1432 * is NULL, no action will be taken regarding its contents, and no
1435 * Note that this is also called with nparam zero to resolve
1438 * If you already know which context macro belongs to, you can pass
1439 * the context pointer as first parameter; if you won't but name begins
1440 * with %$ the context will be automatically computed. If all_contexts
1441 * is true, macro will be searched in outer contexts as well.
1444 smacro_defined(Context
* ctx
, const char *name
, int nparam
, SMacro
** defn
,
1447 struct hash_table
*smtbl
;
1451 smtbl
= &ctx
->localmac
;
1452 } else if (name
[0] == '%' && name
[1] == '$') {
1454 ctx
= get_ctx(name
, &name
, false);
1456 return false; /* got to return _something_ */
1457 smtbl
= &ctx
->localmac
;
1461 m
= (SMacro
*) hash_findix(smtbl
, name
);
1464 if (!mstrcmp(m
->name
, name
, m
->casesense
&& nocase
) &&
1465 (nparam
<= 0 || m
->nparam
== 0 || nparam
== (int) m
->nparam
)) {
1467 if (nparam
== (int) m
->nparam
|| nparam
== -1)
1481 * Count and mark off the parameters in a multi-line macro call.
1482 * This is called both from within the multi-line macro expansion
1483 * code, and also to mark off the default parameters when provided
1484 * in a %macro definition line.
1486 static void count_mmac_params(Token
* t
, int *nparam
, Token
*** params
)
1488 int paramsize
, brace
;
1490 *nparam
= paramsize
= 0;
1493 /* +1: we need space for the final NULL */
1494 if (*nparam
+1 >= paramsize
) {
1495 paramsize
+= PARAM_DELTA
;
1496 *params
= nasm_realloc(*params
, sizeof(**params
) * paramsize
);
1500 if (tok_is_(t
, "{"))
1502 (*params
)[(*nparam
)++] = t
;
1503 while (tok_isnt_(t
, brace
? "}" : ","))
1505 if (t
) { /* got a comma/brace */
1509 * Now we've found the closing brace, look further
1513 if (tok_isnt_(t
, ",")) {
1515 "braces do not enclose all of macro parameter");
1516 while (tok_isnt_(t
, ","))
1520 t
= t
->next
; /* eat the comma */
1527 * Determine whether one of the various `if' conditions is true or
1530 * We must free the tline we get passed.
1532 static bool if_condition(Token
* tline
, enum preproc_token ct
)
1534 enum pp_conditional i
= PP_COND(ct
);
1536 Token
*t
, *tt
, **tptr
, *origline
;
1537 struct tokenval tokval
;
1539 enum pp_token_type needtype
;
1545 j
= false; /* have we matched yet? */
1550 if (tline
->type
!= TOK_ID
) {
1552 "`%s' expects context identifiers", pp_directives
[ct
]);
1553 free_tlist(origline
);
1556 if (cstk
&& cstk
->name
&& !nasm_stricmp(tline
->text
, cstk
->name
))
1558 tline
= tline
->next
;
1563 j
= false; /* have we matched yet? */
1566 if (!tline
|| (tline
->type
!= TOK_ID
&&
1567 (tline
->type
!= TOK_PREPROC_ID
||
1568 tline
->text
[1] != '$'))) {
1570 "`%s' expects macro identifiers", pp_directives
[ct
]);
1573 if (smacro_defined(NULL
, tline
->text
, 0, NULL
, true))
1575 tline
= tline
->next
;
1581 tline
= expand_smacro(tline
);
1583 while (tok_isnt_(tt
, ","))
1587 "`%s' expects two comma-separated arguments",
1592 j
= true; /* assume equality unless proved not */
1593 while ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) && tt
) {
1594 if (tt
->type
== TOK_OTHER
&& !strcmp(tt
->text
, ",")) {
1595 error(ERR_NONFATAL
, "`%s': more than one comma on line",
1599 if (t
->type
== TOK_WHITESPACE
) {
1603 if (tt
->type
== TOK_WHITESPACE
) {
1607 if (tt
->type
!= t
->type
) {
1608 j
= false; /* found mismatching tokens */
1611 /* When comparing strings, need to unquote them first */
1612 if (t
->type
== TOK_STRING
) {
1613 size_t l1
= nasm_unquote(t
->text
, NULL
);
1614 size_t l2
= nasm_unquote(tt
->text
, NULL
);
1620 if (mmemcmp(t
->text
, tt
->text
, l1
, i
== PPC_IFIDN
)) {
1624 } else if (mstrcmp(tt
->text
, t
->text
, i
== PPC_IFIDN
) != 0) {
1625 j
= false; /* found mismatching tokens */
1632 if ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) || tt
)
1633 j
= false; /* trailing gunk on one end or other */
1639 MMacro searching
, *mmac
;
1642 tline
= expand_id(tline
);
1643 if (!tok_type_(tline
, TOK_ID
)) {
1645 "`%s' expects a macro name", pp_directives
[ct
]);
1648 searching
.name
= nasm_strdup(tline
->text
);
1649 searching
.casesense
= true;
1650 searching
.plus
= false;
1651 searching
.nolist
= false;
1652 searching
.in_progress
= 0;
1653 searching
.rep_nest
= NULL
;
1654 searching
.nparam_min
= 0;
1655 searching
.nparam_max
= INT_MAX
;
1656 tline
= expand_smacro(tline
->next
);
1659 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
1661 "`%s' expects a parameter count or nothing",
1664 searching
.nparam_min
= searching
.nparam_max
=
1665 readnum(tline
->text
, &j
);
1668 "unable to parse parameter count `%s'",
1671 if (tline
&& tok_is_(tline
->next
, "-")) {
1672 tline
= tline
->next
->next
;
1673 if (tok_is_(tline
, "*"))
1674 searching
.nparam_max
= INT_MAX
;
1675 else if (!tok_type_(tline
, TOK_NUMBER
))
1677 "`%s' expects a parameter count after `-'",
1680 searching
.nparam_max
= readnum(tline
->text
, &j
);
1683 "unable to parse parameter count `%s'",
1685 if (searching
.nparam_min
> searching
.nparam_max
)
1687 "minimum parameter count exceeds maximum");
1690 if (tline
&& tok_is_(tline
->next
, "+")) {
1691 tline
= tline
->next
;
1692 searching
.plus
= true;
1694 mmac
= (MMacro
*) hash_findix(&mmacros
, searching
.name
);
1696 if (!strcmp(mmac
->name
, searching
.name
) &&
1697 (mmac
->nparam_min
<= searching
.nparam_max
1699 && (searching
.nparam_min
<= mmac
->nparam_max
1706 if(tline
&& tline
->next
)
1707 error(ERR_WARNING
|ERR_PASS1
,
1708 "trailing garbage after %%ifmacro ignored");
1709 nasm_free(searching
.name
);
1718 needtype
= TOK_NUMBER
;
1721 needtype
= TOK_STRING
;
1725 t
= tline
= expand_smacro(tline
);
1727 while (tok_type_(t
, TOK_WHITESPACE
) ||
1728 (needtype
== TOK_NUMBER
&&
1729 tok_type_(t
, TOK_OTHER
) &&
1730 (t
->text
[0] == '-' || t
->text
[0] == '+') &&
1734 j
= tok_type_(t
, needtype
);
1738 t
= tline
= expand_smacro(tline
);
1739 while (tok_type_(t
, TOK_WHITESPACE
))
1744 t
= t
->next
; /* Skip the actual token */
1745 while (tok_type_(t
, TOK_WHITESPACE
))
1747 j
= !t
; /* Should be nothing left */
1752 t
= tline
= expand_smacro(tline
);
1753 while (tok_type_(t
, TOK_WHITESPACE
))
1756 j
= !t
; /* Should be empty */
1760 t
= tline
= expand_smacro(tline
);
1762 tokval
.t_type
= TOKEN_INVALID
;
1763 evalresult
= evaluate(ppscan
, tptr
, &tokval
,
1764 NULL
, pass
| CRITICAL
, error
, NULL
);
1768 error(ERR_WARNING
|ERR_PASS1
,
1769 "trailing garbage after expression ignored");
1770 if (!is_simple(evalresult
)) {
1772 "non-constant value given to `%s'", pp_directives
[ct
]);
1775 j
= reloc_value(evalresult
) != 0;
1780 "preprocessor directive `%s' not yet implemented",
1785 free_tlist(origline
);
1786 return j
^ PP_NEGATIVE(ct
);
1789 free_tlist(origline
);
1794 * Common code for defining an smacro
1796 static bool define_smacro(Context
*ctx
, const char *mname
, bool casesense
,
1797 int nparam
, Token
*expansion
)
1799 SMacro
*smac
, **smhead
;
1800 struct hash_table
*smtbl
;
1802 if (smacro_defined(ctx
, mname
, nparam
, &smac
, casesense
)) {
1804 error(ERR_WARNING
|ERR_PASS1
,
1805 "single-line macro `%s' defined both with and"
1806 " without parameters", mname
);
1808 /* Some instances of the old code considered this a failure,
1809 some others didn't. What is the right thing to do here? */
1810 free_tlist(expansion
);
1811 return false; /* Failure */
1814 * We're redefining, so we have to take over an
1815 * existing SMacro structure. This means freeing
1816 * what was already in it.
1818 nasm_free(smac
->name
);
1819 free_tlist(smac
->expansion
);
1822 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
1823 smhead
= (SMacro
**) hash_findi_add(smtbl
, mname
);
1824 smac
= nasm_malloc(sizeof(SMacro
));
1825 smac
->next
= *smhead
;
1828 smac
->name
= nasm_strdup(mname
);
1829 smac
->casesense
= casesense
;
1830 smac
->nparam
= nparam
;
1831 smac
->expansion
= expansion
;
1832 smac
->in_progress
= false;
1833 return true; /* Success */
1837 * Undefine an smacro
1839 static void undef_smacro(Context
*ctx
, const char *mname
)
1841 SMacro
**smhead
, *s
, **sp
;
1842 struct hash_table
*smtbl
;
1844 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
1845 smhead
= (SMacro
**)hash_findi(smtbl
, mname
, NULL
);
1849 * We now have a macro name... go hunt for it.
1852 while ((s
= *sp
) != NULL
) {
1853 if (!mstrcmp(s
->name
, mname
, s
->casesense
)) {
1856 free_tlist(s
->expansion
);
1866 * Parse a mmacro specification.
1868 static bool parse_mmacro_spec(Token
*tline
, MMacro
*def
, const char *directive
)
1872 tline
= tline
->next
;
1874 tline
= expand_id(tline
);
1875 if (!tok_type_(tline
, TOK_ID
)) {
1876 error(ERR_NONFATAL
, "`%s' expects a macro name", directive
);
1880 def
->name
= nasm_strdup(tline
->text
);
1882 def
->nolist
= false;
1883 def
->in_progress
= 0;
1884 def
->rep_nest
= NULL
;
1885 def
->nparam_min
= 0;
1886 def
->nparam_max
= 0;
1888 tline
= expand_smacro(tline
->next
);
1890 if (!tok_type_(tline
, TOK_NUMBER
)) {
1891 error(ERR_NONFATAL
, "`%s' expects a parameter count", directive
);
1893 def
->nparam_min
= def
->nparam_max
=
1894 readnum(tline
->text
, &err
);
1897 "unable to parse parameter count `%s'", tline
->text
);
1899 if (tline
&& tok_is_(tline
->next
, "-")) {
1900 tline
= tline
->next
->next
;
1901 if (tok_is_(tline
, "*")) {
1902 def
->nparam_max
= INT_MAX
;
1903 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
1905 "`%s' expects a parameter count after `-'", directive
);
1907 def
->nparam_max
= readnum(tline
->text
, &err
);
1909 error(ERR_NONFATAL
, "unable to parse parameter count `%s'",
1912 if (def
->nparam_min
> def
->nparam_max
) {
1913 error(ERR_NONFATAL
, "minimum parameter count exceeds maximum");
1917 if (tline
&& tok_is_(tline
->next
, "+")) {
1918 tline
= tline
->next
;
1921 if (tline
&& tok_type_(tline
->next
, TOK_ID
) &&
1922 !nasm_stricmp(tline
->next
->text
, ".nolist")) {
1923 tline
= tline
->next
;
1928 * Handle default parameters.
1930 if (tline
&& tline
->next
) {
1931 def
->dlist
= tline
->next
;
1933 count_mmac_params(def
->dlist
, &def
->ndefs
, &def
->defaults
);
1936 def
->defaults
= NULL
;
1938 def
->expansion
= NULL
;
1941 def
->ndefs
> def
->nparam_max
- def
->nparam_min
&&
1943 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MDP
,
1944 "too many default macro parameters");
1951 * Decode a size directive
1953 static int parse_size(const char *str
) {
1954 static const char *size_names
[] =
1955 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
1956 static const int sizes
[] =
1957 { 0, 1, 4, 16, 8, 10, 2, 32 };
1959 return sizes
[bsii(str
, size_names
, elements(size_names
))+1];
1963 * find and process preprocessor directive in passed line
1964 * Find out if a line contains a preprocessor directive, and deal
1967 * If a directive _is_ found, it is the responsibility of this routine
1968 * (and not the caller) to free_tlist() the line.
1970 * @param tline a pointer to the current tokeninzed line linked list
1971 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
1974 static int do_directive(Token
* tline
)
1976 enum preproc_token i
;
1989 MMacro
*mmac
, **mmhead
;
1990 Token
*t
, *tt
, *param_start
, *macro_start
, *last
, **tptr
, *origline
;
1992 struct tokenval tokval
;
1994 MMacro
*tmp_defining
; /* Used when manipulating rep_nest */
2002 if (!tline
|| !tok_type_(tline
, TOK_PREPROC_ID
) ||
2003 (tline
->text
[1] == '%' || tline
->text
[1] == '$'
2004 || tline
->text
[1] == '!'))
2005 return NO_DIRECTIVE_FOUND
;
2007 i
= pp_token_hash(tline
->text
);
2010 * If we're in a non-emitting branch of a condition construct,
2011 * or walking to the end of an already terminated %rep block,
2012 * we should ignore all directives except for condition
2015 if (((istk
->conds
&& !emitting(istk
->conds
->state
)) ||
2016 (istk
->mstk
&& !istk
->mstk
->in_progress
)) && !is_condition(i
)) {
2017 return NO_DIRECTIVE_FOUND
;
2021 * If we're defining a macro or reading a %rep block, we should
2022 * ignore all directives except for %macro/%imacro (which nest),
2023 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2024 * If we're in a %rep block, another %rep nests, so should be let through.
2026 if (defining
&& i
!= PP_MACRO
&& i
!= PP_IMACRO
&&
2027 i
!= PP_ENDMACRO
&& i
!= PP_ENDM
&&
2028 (defining
->name
|| (i
!= PP_ENDREP
&& i
!= PP_REP
))) {
2029 return NO_DIRECTIVE_FOUND
;
2033 if (i
== PP_MACRO
|| i
== PP_IMACRO
) {
2035 return NO_DIRECTIVE_FOUND
;
2036 } else if (nested_mac_count
> 0) {
2037 if (i
== PP_ENDMACRO
) {
2039 return NO_DIRECTIVE_FOUND
;
2042 if (!defining
->name
) {
2045 return NO_DIRECTIVE_FOUND
;
2046 } else if (nested_rep_count
> 0) {
2047 if (i
== PP_ENDREP
) {
2049 return NO_DIRECTIVE_FOUND
;
2057 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2059 return NO_DIRECTIVE_FOUND
; /* didn't get it */
2062 /* Directive to tell NASM what the default stack size is. The
2063 * default is for a 16-bit stack, and this can be overriden with
2065 * the following form:
2067 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2069 tline
= tline
->next
;
2070 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2071 tline
= tline
->next
;
2072 if (!tline
|| tline
->type
!= TOK_ID
) {
2073 error(ERR_NONFATAL
, "`%%stacksize' missing size parameter");
2074 free_tlist(origline
);
2075 return DIRECTIVE_FOUND
;
2077 if (nasm_stricmp(tline
->text
, "flat") == 0) {
2078 /* All subsequent ARG directives are for a 32-bit stack */
2080 StackPointer
= "ebp";
2083 } else if (nasm_stricmp(tline
->text
, "flat64") == 0) {
2084 /* All subsequent ARG directives are for a 64-bit stack */
2086 StackPointer
= "rbp";
2089 } else if (nasm_stricmp(tline
->text
, "large") == 0) {
2090 /* All subsequent ARG directives are for a 16-bit stack,
2091 * far function call.
2094 StackPointer
= "bp";
2097 } else if (nasm_stricmp(tline
->text
, "small") == 0) {
2098 /* All subsequent ARG directives are for a 16-bit stack,
2099 * far function call. We don't support near functions.
2102 StackPointer
= "bp";
2106 error(ERR_NONFATAL
, "`%%stacksize' invalid size type");
2107 free_tlist(origline
);
2108 return DIRECTIVE_FOUND
;
2110 free_tlist(origline
);
2111 return DIRECTIVE_FOUND
;
2114 /* TASM like ARG directive to define arguments to functions, in
2115 * the following form:
2117 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2121 char *arg
, directive
[256];
2122 int size
= StackSize
;
2124 /* Find the argument name */
2125 tline
= tline
->next
;
2126 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2127 tline
= tline
->next
;
2128 if (!tline
|| tline
->type
!= TOK_ID
) {
2129 error(ERR_NONFATAL
, "`%%arg' missing argument parameter");
2130 free_tlist(origline
);
2131 return DIRECTIVE_FOUND
;
2135 /* Find the argument size type */
2136 tline
= tline
->next
;
2137 if (!tline
|| tline
->type
!= TOK_OTHER
2138 || tline
->text
[0] != ':') {
2140 "Syntax error processing `%%arg' directive");
2141 free_tlist(origline
);
2142 return DIRECTIVE_FOUND
;
2144 tline
= tline
->next
;
2145 if (!tline
|| tline
->type
!= TOK_ID
) {
2146 error(ERR_NONFATAL
, "`%%arg' missing size type parameter");
2147 free_tlist(origline
);
2148 return DIRECTIVE_FOUND
;
2151 /* Allow macro expansion of type parameter */
2152 tt
= tokenize(tline
->text
);
2153 tt
= expand_smacro(tt
);
2154 size
= parse_size(tt
->text
);
2157 "Invalid size type for `%%arg' missing directive");
2159 free_tlist(origline
);
2160 return DIRECTIVE_FOUND
;
2164 /* Round up to even stack slots */
2165 size
= (size
+StackSize
-1) & ~(StackSize
-1);
2167 /* Now define the macro for the argument */
2168 snprintf(directive
, sizeof(directive
), "%%define %s (%s+%d)",
2169 arg
, StackPointer
, offset
);
2170 do_directive(tokenize(directive
));
2173 /* Move to the next argument in the list */
2174 tline
= tline
->next
;
2175 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2176 tline
= tline
->next
;
2177 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2179 free_tlist(origline
);
2180 return DIRECTIVE_FOUND
;
2183 /* TASM like LOCAL directive to define local variables for a
2184 * function, in the following form:
2186 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2188 * The '= LocalSize' at the end is ignored by NASM, but is
2189 * required by TASM to define the local parameter size (and used
2190 * by the TASM macro package).
2192 offset
= LocalOffset
;
2194 char *local
, directive
[256];
2195 int size
= StackSize
;
2197 /* Find the argument name */
2198 tline
= tline
->next
;
2199 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2200 tline
= tline
->next
;
2201 if (!tline
|| tline
->type
!= TOK_ID
) {
2203 "`%%local' missing argument parameter");
2204 free_tlist(origline
);
2205 return DIRECTIVE_FOUND
;
2207 local
= tline
->text
;
2209 /* Find the argument size type */
2210 tline
= tline
->next
;
2211 if (!tline
|| tline
->type
!= TOK_OTHER
2212 || tline
->text
[0] != ':') {
2214 "Syntax error processing `%%local' directive");
2215 free_tlist(origline
);
2216 return DIRECTIVE_FOUND
;
2218 tline
= tline
->next
;
2219 if (!tline
|| tline
->type
!= TOK_ID
) {
2221 "`%%local' missing size type parameter");
2222 free_tlist(origline
);
2223 return DIRECTIVE_FOUND
;
2226 /* Allow macro expansion of type parameter */
2227 tt
= tokenize(tline
->text
);
2228 tt
= expand_smacro(tt
);
2229 size
= parse_size(tt
->text
);
2232 "Invalid size type for `%%local' missing directive");
2234 free_tlist(origline
);
2235 return DIRECTIVE_FOUND
;
2239 /* Round up to even stack slots */
2240 size
= (size
+StackSize
-1) & ~(StackSize
-1);
2242 offset
+= size
; /* Negative offset, increment before */
2244 /* Now define the macro for the argument */
2245 snprintf(directive
, sizeof(directive
), "%%define %s (%s-%d)",
2246 local
, StackPointer
, offset
);
2247 do_directive(tokenize(directive
));
2249 /* Now define the assign to setup the enter_c macro correctly */
2250 snprintf(directive
, sizeof(directive
),
2251 "%%assign %%$localsize %%$localsize+%d", size
);
2252 do_directive(tokenize(directive
));
2254 /* Move to the next argument in the list */
2255 tline
= tline
->next
;
2256 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2257 tline
= tline
->next
;
2258 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2259 LocalOffset
= offset
;
2260 free_tlist(origline
);
2261 return DIRECTIVE_FOUND
;
2265 error(ERR_WARNING
|ERR_PASS1
,
2266 "trailing garbage after `%%clear' ignored");
2269 free_tlist(origline
);
2270 return DIRECTIVE_FOUND
;
2273 t
= tline
->next
= expand_smacro(tline
->next
);
2275 if (!t
|| (t
->type
!= TOK_STRING
&&
2276 t
->type
!= TOK_INTERNAL_STRING
)) {
2277 error(ERR_NONFATAL
, "`%%depend' expects a file name");
2278 free_tlist(origline
);
2279 return DIRECTIVE_FOUND
; /* but we did _something_ */
2282 error(ERR_WARNING
|ERR_PASS1
,
2283 "trailing garbage after `%%depend' ignored");
2285 if (t
->type
!= TOK_INTERNAL_STRING
)
2286 nasm_unquote(p
, NULL
);
2287 if (dephead
&& !in_list(*dephead
, p
)) {
2288 StrList
*sl
= nasm_malloc(strlen(p
)+1+sizeof sl
->next
);
2292 deptail
= &sl
->next
;
2294 free_tlist(origline
);
2295 return DIRECTIVE_FOUND
;
2298 t
= tline
->next
= expand_smacro(tline
->next
);
2301 if (!t
|| (t
->type
!= TOK_STRING
&&
2302 t
->type
!= TOK_INTERNAL_STRING
)) {
2303 error(ERR_NONFATAL
, "`%%include' expects a file name");
2304 free_tlist(origline
);
2305 return DIRECTIVE_FOUND
; /* but we did _something_ */
2308 error(ERR_WARNING
|ERR_PASS1
,
2309 "trailing garbage after `%%include' ignored");
2311 if (t
->type
!= TOK_INTERNAL_STRING
)
2312 nasm_unquote(p
, NULL
);
2313 inc
= nasm_malloc(sizeof(Include
));
2316 inc
->fp
= inc_fopen(p
, dephead
, &deptail
, pass
== 0);
2318 /* -MG given but file not found */
2321 inc
->fname
= src_set_fname(nasm_strdup(p
));
2322 inc
->lineno
= src_set_linnum(0);
2324 inc
->expansion
= NULL
;
2327 list
->uplevel(LIST_INCLUDE
);
2329 free_tlist(origline
);
2330 return DIRECTIVE_FOUND
;
2334 static macros_t
*use_pkg
;
2335 const char *pkg_macro
;
2337 tline
= tline
->next
;
2339 tline
= expand_id(tline
);
2341 if (!tline
|| (tline
->type
!= TOK_STRING
&&
2342 tline
->type
!= TOK_INTERNAL_STRING
&&
2343 tline
->type
!= TOK_ID
)) {
2344 error(ERR_NONFATAL
, "`%%use' expects a package name");
2345 free_tlist(origline
);
2346 return DIRECTIVE_FOUND
; /* but we did _something_ */
2349 error(ERR_WARNING
|ERR_PASS1
,
2350 "trailing garbage after `%%use' ignored");
2351 if (tline
->type
== TOK_STRING
)
2352 nasm_unquote(tline
->text
, NULL
);
2353 use_pkg
= nasm_stdmac_find_package(tline
->text
);
2355 error(ERR_NONFATAL
, "unknown `%%use' package: %s", tline
->text
);
2356 /* The first string will be <%define>__USE_*__ */
2357 pkg_macro
= (char *)use_pkg
+ 1;
2358 if (!smacro_defined(NULL
, pkg_macro
, 0, NULL
, true)) {
2359 /* Not already included, go ahead and include it */
2360 stdmacpos
= use_pkg
;
2362 free_tlist(origline
);
2363 return DIRECTIVE_FOUND
;
2368 tline
= tline
->next
;
2370 tline
= expand_id(tline
);
2372 if (!tok_type_(tline
, TOK_ID
)) {
2373 error(ERR_NONFATAL
, "`%s' expects a context identifier",
2375 free_tlist(origline
);
2376 return DIRECTIVE_FOUND
; /* but we did _something_ */
2379 error(ERR_WARNING
|ERR_PASS1
,
2380 "trailing garbage after `%s' ignored",
2382 p
= nasm_strdup(tline
->text
);
2384 p
= NULL
; /* Anonymous */
2388 ctx
= nasm_malloc(sizeof(Context
));
2390 hash_init(&ctx
->localmac
, HASH_SMALL
);
2392 ctx
->number
= unique
++;
2397 error(ERR_NONFATAL
, "`%s': context stack is empty",
2399 } else if (i
== PP_POP
) {
2400 if (p
&& (!cstk
->name
|| nasm_stricmp(p
, cstk
->name
)))
2401 error(ERR_NONFATAL
, "`%%pop' in wrong context: %s, "
2403 cstk
->name
? cstk
->name
: "anonymous", p
);
2408 nasm_free(cstk
->name
);
2414 free_tlist(origline
);
2415 return DIRECTIVE_FOUND
;
2417 severity
= ERR_FATAL
|ERR_NO_SEVERITY
;
2420 severity
= ERR_NONFATAL
|ERR_NO_SEVERITY
;
2423 severity
= ERR_WARNING
|ERR_NO_SEVERITY
|ERR_WARN_USER
;
2428 /* Only error out if this is the final pass */
2429 if (pass
!= 2 && i
!= PP_FATAL
)
2430 return DIRECTIVE_FOUND
;
2432 tline
->next
= expand_smacro(tline
->next
);
2433 tline
= tline
->next
;
2435 t
= tline
? tline
->next
: NULL
;
2437 if (tok_type_(tline
, TOK_STRING
) && !t
) {
2438 /* The line contains only a quoted string */
2440 nasm_unquote(p
, NULL
);
2441 error(severity
, "%s: %s", pp_directives
[i
], p
);
2443 /* Not a quoted string, or more than a quoted string */
2444 p
= detoken(tline
, false);
2445 error(severity
, "%s: %s", pp_directives
[i
], p
);
2448 free_tlist(origline
);
2449 return DIRECTIVE_FOUND
;
2453 if (istk
->conds
&& !emitting(istk
->conds
->state
))
2456 j
= if_condition(tline
->next
, i
);
2457 tline
->next
= NULL
; /* it got freed */
2458 j
= j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2460 cond
= nasm_malloc(sizeof(Cond
));
2461 cond
->next
= istk
->conds
;
2464 free_tlist(origline
);
2465 return DIRECTIVE_FOUND
;
2469 error(ERR_FATAL
, "`%s': no matching `%%if'", pp_directives
[i
]);
2470 switch(istk
->conds
->state
) {
2472 istk
->conds
->state
= COND_DONE
;
2479 case COND_ELSE_TRUE
:
2480 case COND_ELSE_FALSE
:
2481 error_precond(ERR_WARNING
|ERR_PASS1
,
2482 "`%%elif' after `%%else' ignored");
2483 istk
->conds
->state
= COND_NEVER
;
2488 * IMPORTANT: In the case of %if, we will already have
2489 * called expand_mmac_params(); however, if we're
2490 * processing an %elif we must have been in a
2491 * non-emitting mode, which would have inhibited
2492 * the normal invocation of expand_mmac_params().
2493 * Therefore, we have to do it explicitly here.
2495 j
= if_condition(expand_mmac_params(tline
->next
), i
);
2496 tline
->next
= NULL
; /* it got freed */
2497 istk
->conds
->state
=
2498 j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2501 free_tlist(origline
);
2502 return DIRECTIVE_FOUND
;
2506 error_precond(ERR_WARNING
|ERR_PASS1
,
2507 "trailing garbage after `%%else' ignored");
2509 error(ERR_FATAL
, "`%%else': no matching `%%if'");
2510 switch(istk
->conds
->state
) {
2513 istk
->conds
->state
= COND_ELSE_FALSE
;
2520 istk
->conds
->state
= COND_ELSE_TRUE
;
2523 case COND_ELSE_TRUE
:
2524 case COND_ELSE_FALSE
:
2525 error_precond(ERR_WARNING
|ERR_PASS1
,
2526 "`%%else' after `%%else' ignored.");
2527 istk
->conds
->state
= COND_NEVER
;
2530 free_tlist(origline
);
2531 return DIRECTIVE_FOUND
;
2535 error_precond(ERR_WARNING
|ERR_PASS1
,
2536 "trailing garbage after `%%endif' ignored");
2538 error(ERR_FATAL
, "`%%endif': no matching `%%if'");
2540 istk
->conds
= cond
->next
;
2542 free_tlist(origline
);
2543 return DIRECTIVE_FOUND
;
2549 "`%%%smacro': already defining a macro",
2550 (i
== PP_IMACRO
? "i" : ""));
2551 return DIRECTIVE_FOUND
;
2553 defining
= nasm_malloc(sizeof(MMacro
));
2554 defining
->casesense
= (i
== PP_MACRO
);
2555 if (!parse_mmacro_spec(tline
, defining
, pp_directives
[i
])) {
2556 nasm_free(defining
);
2558 return DIRECTIVE_FOUND
;
2561 mmac
= (MMacro
*) hash_findix(&mmacros
, defining
->name
);
2563 if (!strcmp(mmac
->name
, defining
->name
) &&
2564 (mmac
->nparam_min
<= defining
->nparam_max
2566 && (defining
->nparam_min
<= mmac
->nparam_max
2568 error(ERR_WARNING
|ERR_PASS1
,
2569 "redefining multi-line macro `%s'", defining
->name
);
2570 return DIRECTIVE_FOUND
;
2574 free_tlist(origline
);
2575 return DIRECTIVE_FOUND
;
2579 if (! (defining
&& defining
->name
)) {
2580 error(ERR_NONFATAL
, "`%s': not defining a macro", tline
->text
);
2581 return DIRECTIVE_FOUND
;
2583 mmhead
= (MMacro
**) hash_findi_add(&mmacros
, defining
->name
);
2584 defining
->next
= *mmhead
;
2587 free_tlist(origline
);
2588 return DIRECTIVE_FOUND
;
2596 spec
.casesense
= (i
== PP_UNMACRO
);
2597 if (!parse_mmacro_spec(tline
, &spec
, pp_directives
[i
])) {
2598 return DIRECTIVE_FOUND
;
2600 mmac_p
= (MMacro
**) hash_findi(&mmacros
, spec
.name
, NULL
);
2601 while (mmac_p
&& *mmac_p
) {
2603 if (mmac
->casesense
== spec
.casesense
&&
2604 !mstrcmp(mmac
->name
, spec
.name
, spec
.casesense
) &&
2605 mmac
->nparam_min
== spec
.nparam_min
&&
2606 mmac
->nparam_max
== spec
.nparam_max
&&
2607 mmac
->plus
== spec
.plus
) {
2608 *mmac_p
= mmac
->next
;
2611 mmac_p
= &mmac
->next
;
2614 free_tlist(origline
);
2615 free_tlist(spec
.dlist
);
2616 return DIRECTIVE_FOUND
;
2620 if (tline
->next
&& tline
->next
->type
== TOK_WHITESPACE
)
2621 tline
= tline
->next
;
2622 if (tline
->next
== NULL
) {
2623 free_tlist(origline
);
2624 error(ERR_NONFATAL
, "`%%rotate' missing rotate count");
2625 return DIRECTIVE_FOUND
;
2627 t
= expand_smacro(tline
->next
);
2629 free_tlist(origline
);
2632 tokval
.t_type
= TOKEN_INVALID
;
2634 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2637 return DIRECTIVE_FOUND
;
2639 error(ERR_WARNING
|ERR_PASS1
,
2640 "trailing garbage after expression ignored");
2641 if (!is_simple(evalresult
)) {
2642 error(ERR_NONFATAL
, "non-constant value given to `%%rotate'");
2643 return DIRECTIVE_FOUND
;
2646 while (mmac
&& !mmac
->name
) /* avoid mistaking %reps for macros */
2647 mmac
= mmac
->next_active
;
2649 error(ERR_NONFATAL
, "`%%rotate' invoked outside a macro call");
2650 } else if (mmac
->nparam
== 0) {
2652 "`%%rotate' invoked within macro without parameters");
2654 int rotate
= mmac
->rotate
+ reloc_value(evalresult
);
2656 rotate
%= (int)mmac
->nparam
;
2658 rotate
+= mmac
->nparam
;
2660 mmac
->rotate
= rotate
;
2662 return DIRECTIVE_FOUND
;
2667 tline
= tline
->next
;
2668 } while (tok_type_(tline
, TOK_WHITESPACE
));
2670 if (tok_type_(tline
, TOK_ID
) &&
2671 nasm_stricmp(tline
->text
, ".nolist") == 0) {
2674 tline
= tline
->next
;
2675 } while (tok_type_(tline
, TOK_WHITESPACE
));
2679 t
= expand_smacro(tline
);
2681 tokval
.t_type
= TOKEN_INVALID
;
2683 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2685 free_tlist(origline
);
2686 return DIRECTIVE_FOUND
;
2689 error(ERR_WARNING
|ERR_PASS1
,
2690 "trailing garbage after expression ignored");
2691 if (!is_simple(evalresult
)) {
2692 error(ERR_NONFATAL
, "non-constant value given to `%%rep'");
2693 return DIRECTIVE_FOUND
;
2695 count
= reloc_value(evalresult
) + 1;
2697 error(ERR_NONFATAL
, "`%%rep' expects a repeat count");
2700 free_tlist(origline
);
2702 tmp_defining
= defining
;
2703 defining
= nasm_malloc(sizeof(MMacro
));
2704 defining
->name
= NULL
; /* flags this macro as a %rep block */
2705 defining
->casesense
= false;
2706 defining
->plus
= false;
2707 defining
->nolist
= nolist
;
2708 defining
->in_progress
= count
;
2709 defining
->nparam_min
= defining
->nparam_max
= 0;
2710 defining
->defaults
= NULL
;
2711 defining
->dlist
= NULL
;
2712 defining
->expansion
= NULL
;
2713 defining
->next_active
= istk
->mstk
;
2714 defining
->rep_nest
= tmp_defining
;
2715 return DIRECTIVE_FOUND
;
2718 if (!defining
|| defining
->name
) {
2719 error(ERR_NONFATAL
, "`%%endrep': no matching `%%rep'");
2720 return DIRECTIVE_FOUND
;
2724 * Now we have a "macro" defined - although it has no name
2725 * and we won't be entering it in the hash tables - we must
2726 * push a macro-end marker for it on to istk->expansion.
2727 * After that, it will take care of propagating itself (a
2728 * macro-end marker line for a macro which is really a %rep
2729 * block will cause the macro to be re-expanded, complete
2730 * with another macro-end marker to ensure the process
2731 * continues) until the whole expansion is forcibly removed
2732 * from istk->expansion by a %exitrep.
2734 l
= nasm_malloc(sizeof(Line
));
2735 l
->next
= istk
->expansion
;
2736 l
->finishes
= defining
;
2738 istk
->expansion
= l
;
2740 istk
->mstk
= defining
;
2742 list
->uplevel(defining
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
2743 tmp_defining
= defining
;
2744 defining
= defining
->rep_nest
;
2745 free_tlist(origline
);
2746 return DIRECTIVE_FOUND
;
2750 * We must search along istk->expansion until we hit a
2751 * macro-end marker for a macro with no name. Then we set
2752 * its `in_progress' flag to 0.
2754 for (l
= istk
->expansion
; l
; l
= l
->next
)
2755 if (l
->finishes
&& !l
->finishes
->name
)
2759 l
->finishes
->in_progress
= 1;
2761 error(ERR_NONFATAL
, "`%%exitrep' not within `%%rep' block");
2762 free_tlist(origline
);
2763 return DIRECTIVE_FOUND
;
2769 casesense
= (i
== PP_DEFINE
|| i
== PP_XDEFINE
);
2771 tline
= tline
->next
;
2773 tline
= expand_id(tline
);
2774 if (!tline
|| (tline
->type
!= TOK_ID
&&
2775 (tline
->type
!= TOK_PREPROC_ID
||
2776 tline
->text
[1] != '$'))) {
2777 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
2779 free_tlist(origline
);
2780 return DIRECTIVE_FOUND
;
2783 ctx
= get_ctx(tline
->text
, &mname
, false);
2785 param_start
= tline
= tline
->next
;
2788 /* Expand the macro definition now for %xdefine and %ixdefine */
2789 if ((i
== PP_XDEFINE
) || (i
== PP_IXDEFINE
))
2790 tline
= expand_smacro(tline
);
2792 if (tok_is_(tline
, "(")) {
2794 * This macro has parameters.
2797 tline
= tline
->next
;
2801 error(ERR_NONFATAL
, "parameter identifier expected");
2802 free_tlist(origline
);
2803 return DIRECTIVE_FOUND
;
2805 if (tline
->type
!= TOK_ID
) {
2807 "`%s': parameter identifier expected",
2809 free_tlist(origline
);
2810 return DIRECTIVE_FOUND
;
2812 tline
->type
= TOK_SMAC_PARAM
+ nparam
++;
2813 tline
= tline
->next
;
2815 if (tok_is_(tline
, ",")) {
2816 tline
= tline
->next
;
2818 if (!tok_is_(tline
, ")")) {
2820 "`)' expected to terminate macro template");
2821 free_tlist(origline
);
2822 return DIRECTIVE_FOUND
;
2828 tline
= tline
->next
;
2830 if (tok_type_(tline
, TOK_WHITESPACE
))
2831 last
= tline
, tline
= tline
->next
;
2836 if (t
->type
== TOK_ID
) {
2837 for (tt
= param_start
; tt
; tt
= tt
->next
)
2838 if (tt
->type
>= TOK_SMAC_PARAM
&&
2839 !strcmp(tt
->text
, t
->text
))
2843 t
->next
= macro_start
;
2848 * Good. We now have a macro name, a parameter count, and a
2849 * token list (in reverse order) for an expansion. We ought
2850 * to be OK just to create an SMacro, store it, and let
2851 * free_tlist have the rest of the line (which we have
2852 * carefully re-terminated after chopping off the expansion
2855 define_smacro(ctx
, mname
, casesense
, nparam
, macro_start
);
2856 free_tlist(origline
);
2857 return DIRECTIVE_FOUND
;
2860 tline
= tline
->next
;
2862 tline
= expand_id(tline
);
2863 if (!tline
|| (tline
->type
!= TOK_ID
&&
2864 (tline
->type
!= TOK_PREPROC_ID
||
2865 tline
->text
[1] != '$'))) {
2866 error(ERR_NONFATAL
, "`%%undef' expects a macro identifier");
2867 free_tlist(origline
);
2868 return DIRECTIVE_FOUND
;
2871 error(ERR_WARNING
|ERR_PASS1
,
2872 "trailing garbage after macro name ignored");
2875 /* Find the context that symbol belongs to */
2876 ctx
= get_ctx(tline
->text
, &mname
, false);
2877 undef_smacro(ctx
, mname
);
2878 free_tlist(origline
);
2879 return DIRECTIVE_FOUND
;
2883 casesense
= (i
== PP_DEFSTR
);
2885 tline
= tline
->next
;
2887 tline
= expand_id(tline
);
2888 if (!tline
|| (tline
->type
!= TOK_ID
&&
2889 (tline
->type
!= TOK_PREPROC_ID
||
2890 tline
->text
[1] != '$'))) {
2891 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
2893 free_tlist(origline
);
2894 return DIRECTIVE_FOUND
;
2897 ctx
= get_ctx(tline
->text
, &mname
, false);
2899 tline
= expand_smacro(tline
->next
);
2902 while (tok_type_(tline
, TOK_WHITESPACE
))
2903 tline
= delete_Token(tline
);
2905 p
= detoken(tline
, false);
2906 macro_start
= nasm_malloc(sizeof(*macro_start
));
2907 macro_start
->next
= NULL
;
2908 macro_start
->text
= nasm_quote(p
, strlen(p
));
2909 macro_start
->type
= TOK_STRING
;
2910 macro_start
->a
.mac
= NULL
;
2914 * We now have a macro name, an implicit parameter count of
2915 * zero, and a string token to use as an expansion. Create
2916 * and store an SMacro.
2918 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
2919 free_tlist(origline
);
2920 return DIRECTIVE_FOUND
;
2925 StrList
*xsl
= NULL
;
2926 StrList
**xst
= &xsl
;
2930 tline
= tline
->next
;
2932 tline
= expand_id(tline
);
2933 if (!tline
|| (tline
->type
!= TOK_ID
&&
2934 (tline
->type
!= TOK_PREPROC_ID
||
2935 tline
->text
[1] != '$'))) {
2937 "`%%pathsearch' expects a macro identifier as first parameter");
2938 free_tlist(origline
);
2939 return DIRECTIVE_FOUND
;
2941 ctx
= get_ctx(tline
->text
, &mname
, false);
2943 tline
= expand_smacro(tline
->next
);
2947 while (tok_type_(t
, TOK_WHITESPACE
))
2950 if (!t
|| (t
->type
!= TOK_STRING
&&
2951 t
->type
!= TOK_INTERNAL_STRING
)) {
2952 error(ERR_NONFATAL
, "`%%pathsearch' expects a file name");
2954 free_tlist(origline
);
2955 return DIRECTIVE_FOUND
; /* but we did _something_ */
2958 error(ERR_WARNING
|ERR_PASS1
,
2959 "trailing garbage after `%%pathsearch' ignored");
2961 if (t
->type
!= TOK_INTERNAL_STRING
)
2962 nasm_unquote(p
, NULL
);
2964 fp
= inc_fopen(p
, &xsl
, &xst
, true);
2967 fclose(fp
); /* Don't actually care about the file */
2969 macro_start
= nasm_malloc(sizeof(*macro_start
));
2970 macro_start
->next
= NULL
;
2971 macro_start
->text
= nasm_quote(p
, strlen(p
));
2972 macro_start
->type
= TOK_STRING
;
2973 macro_start
->a
.mac
= NULL
;
2978 * We now have a macro name, an implicit parameter count of
2979 * zero, and a string token to use as an expansion. Create
2980 * and store an SMacro.
2982 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
2984 free_tlist(origline
);
2985 return DIRECTIVE_FOUND
;
2991 tline
= tline
->next
;
2993 tline
= expand_id(tline
);
2994 if (!tline
|| (tline
->type
!= TOK_ID
&&
2995 (tline
->type
!= TOK_PREPROC_ID
||
2996 tline
->text
[1] != '$'))) {
2998 "`%%strlen' expects a macro identifier as first parameter");
2999 free_tlist(origline
);
3000 return DIRECTIVE_FOUND
;
3002 ctx
= get_ctx(tline
->text
, &mname
, false);
3004 tline
= expand_smacro(tline
->next
);
3008 while (tok_type_(t
, TOK_WHITESPACE
))
3010 /* t should now point to the string */
3011 if (t
->type
!= TOK_STRING
) {
3013 "`%%strlen` requires string as second parameter");
3015 free_tlist(origline
);
3016 return DIRECTIVE_FOUND
;
3019 macro_start
= nasm_malloc(sizeof(*macro_start
));
3020 macro_start
->next
= NULL
;
3021 make_tok_num(macro_start
, nasm_unquote(t
->text
, NULL
));
3022 macro_start
->a
.mac
= NULL
;
3025 * We now have a macro name, an implicit parameter count of
3026 * zero, and a numeric token to use as an expansion. Create
3027 * and store an SMacro.
3029 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3031 free_tlist(origline
);
3032 return DIRECTIVE_FOUND
;
3037 tline
= tline
->next
;
3039 tline
= expand_id(tline
);
3040 if (!tline
|| (tline
->type
!= TOK_ID
&&
3041 (tline
->type
!= TOK_PREPROC_ID
||
3042 tline
->text
[1] != '$'))) {
3044 "`%%strcat' expects a macro identifier as first parameter");
3045 free_tlist(origline
);
3046 return DIRECTIVE_FOUND
;
3048 ctx
= get_ctx(tline
->text
, &mname
, false);
3050 tline
= expand_smacro(tline
->next
);
3054 for (t
= tline
; t
; t
= t
->next
) {
3056 case TOK_WHITESPACE
:
3059 len
+= t
->a
.len
= nasm_unquote(t
->text
, NULL
);
3062 if (!strcmp(t
->text
, ",")) /* permit comma separators */
3064 /* else fall through */
3067 "non-string passed to `%%strcat' (%d)", t
->type
);
3069 free_tlist(origline
);
3070 return DIRECTIVE_FOUND
;
3074 p
= pp
= nasm_malloc(len
);
3076 for (t
= tline
; t
; t
= t
->next
) {
3077 if (t
->type
== TOK_STRING
) {
3078 memcpy(p
, t
->text
, t
->a
.len
);
3084 * We now have a macro name, an implicit parameter count of
3085 * zero, and a numeric token to use as an expansion. Create
3086 * and store an SMacro.
3088 macro_start
= new_Token(NULL
, TOK_STRING
, NULL
, 0);
3089 macro_start
->text
= nasm_quote(pp
, len
);
3091 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3093 free_tlist(origline
);
3094 return DIRECTIVE_FOUND
;
3103 tline
= tline
->next
;
3105 tline
= expand_id(tline
);
3106 if (!tline
|| (tline
->type
!= TOK_ID
&&
3107 (tline
->type
!= TOK_PREPROC_ID
||
3108 tline
->text
[1] != '$'))) {
3110 "`%%substr' expects a macro identifier as first parameter");
3111 free_tlist(origline
);
3112 return DIRECTIVE_FOUND
;
3114 ctx
= get_ctx(tline
->text
, &mname
, false);
3116 tline
= expand_smacro(tline
->next
);
3120 while (tok_type_(t
, TOK_WHITESPACE
))
3123 /* t should now point to the string */
3124 if (t
->type
!= TOK_STRING
) {
3126 "`%%substr` requires string as second parameter");
3128 free_tlist(origline
);
3129 return DIRECTIVE_FOUND
;
3134 tokval
.t_type
= TOKEN_INVALID
;
3135 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3139 free_tlist(origline
);
3140 return DIRECTIVE_FOUND
;
3141 } else if (!is_simple(evalresult
)) {
3142 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3144 free_tlist(origline
);
3145 return DIRECTIVE_FOUND
;
3147 a1
= evalresult
->value
-1;
3149 while (tok_type_(tt
, TOK_WHITESPACE
))
3152 a2
= 1; /* Backwards compatibility: one character */
3154 tokval
.t_type
= TOKEN_INVALID
;
3155 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3159 free_tlist(origline
);
3160 return DIRECTIVE_FOUND
;
3161 } else if (!is_simple(evalresult
)) {
3162 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3164 free_tlist(origline
);
3165 return DIRECTIVE_FOUND
;
3167 a2
= evalresult
->value
;
3170 len
= nasm_unquote(t
->text
, NULL
);
3173 if (a1
+a2
> (int64_t)len
)
3176 macro_start
= nasm_malloc(sizeof(*macro_start
));
3177 macro_start
->next
= NULL
;
3178 macro_start
->text
= nasm_quote((a1
< 0) ? "" : t
->text
+a1
, a2
);
3179 macro_start
->type
= TOK_STRING
;
3180 macro_start
->a
.mac
= NULL
;
3183 * We now have a macro name, an implicit parameter count of
3184 * zero, and a numeric token to use as an expansion. Create
3185 * and store an SMacro.
3187 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3189 free_tlist(origline
);
3190 return DIRECTIVE_FOUND
;
3195 casesense
= (i
== PP_ASSIGN
);
3197 tline
= tline
->next
;
3199 tline
= expand_id(tline
);
3200 if (!tline
|| (tline
->type
!= TOK_ID
&&
3201 (tline
->type
!= TOK_PREPROC_ID
||
3202 tline
->text
[1] != '$'))) {
3204 "`%%%sassign' expects a macro identifier",
3205 (i
== PP_IASSIGN
? "i" : ""));
3206 free_tlist(origline
);
3207 return DIRECTIVE_FOUND
;
3209 ctx
= get_ctx(tline
->text
, &mname
, false);
3211 tline
= expand_smacro(tline
->next
);
3216 tokval
.t_type
= TOKEN_INVALID
;
3218 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
3221 free_tlist(origline
);
3222 return DIRECTIVE_FOUND
;
3226 error(ERR_WARNING
|ERR_PASS1
,
3227 "trailing garbage after expression ignored");
3229 if (!is_simple(evalresult
)) {
3231 "non-constant value given to `%%%sassign'",
3232 (i
== PP_IASSIGN
? "i" : ""));
3233 free_tlist(origline
);
3234 return DIRECTIVE_FOUND
;
3237 macro_start
= nasm_malloc(sizeof(*macro_start
));
3238 macro_start
->next
= NULL
;
3239 make_tok_num(macro_start
, reloc_value(evalresult
));
3240 macro_start
->a
.mac
= NULL
;
3243 * We now have a macro name, an implicit parameter count of
3244 * zero, and a numeric token to use as an expansion. Create
3245 * and store an SMacro.
3247 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3248 free_tlist(origline
);
3249 return DIRECTIVE_FOUND
;
3253 * Syntax is `%line nnn[+mmm] [filename]'
3255 tline
= tline
->next
;
3257 if (!tok_type_(tline
, TOK_NUMBER
)) {
3258 error(ERR_NONFATAL
, "`%%line' expects line number");
3259 free_tlist(origline
);
3260 return DIRECTIVE_FOUND
;
3262 k
= readnum(tline
->text
, &err
);
3264 tline
= tline
->next
;
3265 if (tok_is_(tline
, "+")) {
3266 tline
= tline
->next
;
3267 if (!tok_type_(tline
, TOK_NUMBER
)) {
3268 error(ERR_NONFATAL
, "`%%line' expects line increment");
3269 free_tlist(origline
);
3270 return DIRECTIVE_FOUND
;
3272 m
= readnum(tline
->text
, &err
);
3273 tline
= tline
->next
;
3279 nasm_free(src_set_fname(detoken(tline
, false)));
3281 free_tlist(origline
);
3282 return DIRECTIVE_FOUND
;
3286 "preprocessor directive `%s' not yet implemented",
3288 return DIRECTIVE_FOUND
;
3293 * Ensure that a macro parameter contains a condition code and
3294 * nothing else. Return the condition code index if so, or -1
3297 static int find_cc(Token
* t
)
3303 return -1; /* Probably a %+ without a space */
3306 if (t
->type
!= TOK_ID
)
3310 if (tt
&& (tt
->type
!= TOK_OTHER
|| strcmp(tt
->text
, ",")))
3314 j
= elements(conditions
);
3317 m
= nasm_stricmp(t
->text
, conditions
[k
]);
3332 static bool paste_tokens(Token
**head
, bool handle_paste_tokens
)
3334 Token
**tail
, *t
, *tt
;
3336 bool did_paste
= false;
3339 /* Now handle token pasting... */
3342 while ((t
= *tail
) && (tt
= t
->next
)) {
3344 case TOK_WHITESPACE
:
3345 if (tt
->type
== TOK_WHITESPACE
) {
3346 /* Zap adjacent whitespace tokens */
3347 t
->next
= delete_Token(tt
);
3349 /* Do not advance paste_head here */
3354 case TOK_PREPROC_ID
:
3361 while (tt
&& (tt
->type
== TOK_ID
|| tt
->type
== TOK_PREPROC_ID
||
3362 tt
->type
== TOK_NUMBER
|| tt
->type
== TOK_FLOAT
||
3363 tt
->type
== TOK_OTHER
)) {
3364 len
+= strlen(tt
->text
);
3368 /* Now tt points to the first token after the potential
3370 if (tt
!= t
->next
) {
3371 /* We have at least two tokens... */
3372 len
+= strlen(t
->text
);
3373 p
= tmp
= nasm_malloc(len
+1);
3377 p
= strchr(p
, '\0');
3378 t
= delete_Token(t
);
3381 t
= *tail
= tokenize(tmp
);
3388 t
->next
= tt
; /* Attach the remaining token chain */
3396 case TOK_PASTE
: /* %+ */
3397 if (handle_paste_tokens
) {
3398 /* Zap %+ and whitespace tokens to the right */
3399 while (t
&& (t
->type
== TOK_WHITESPACE
||
3400 t
->type
== TOK_PASTE
))
3401 t
= *tail
= delete_Token(t
);
3402 if (!paste_head
|| !t
)
3403 break; /* Nothing to paste with */
3407 while (tok_type_(tt
, TOK_WHITESPACE
))
3408 tt
= t
->next
= delete_Token(tt
);
3411 tmp
= nasm_strcat(t
->text
, tt
->text
);
3413 tt
= delete_Token(tt
);
3414 t
= *tail
= tokenize(tmp
);
3420 t
->next
= tt
; /* Attach the remaining token chain */
3427 /* else fall through */
3429 tail
= paste_head
= &t
->next
;
3436 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3437 * %-n) and MMacro-local identifiers (%%foo) as well as
3438 * macro indirection (%[...]).
3440 static Token
*expand_mmac_params(Token
* tline
)
3442 Token
*t
, *tt
, **tail
, *thead
;
3443 bool changed
= false;
3449 if (tline
->type
== TOK_PREPROC_ID
&&
3450 (((tline
->text
[1] == '+' || tline
->text
[1] == '-')
3451 && tline
->text
[2]) || tline
->text
[1] == '%'
3452 || (tline
->text
[1] >= '0' && tline
->text
[1] <= '9'))) {
3454 int type
= 0, cc
; /* type = 0 to placate optimisers */
3461 tline
= tline
->next
;
3464 while (mac
&& !mac
->name
) /* avoid mistaking %reps for macros */
3465 mac
= mac
->next_active
;
3467 error(ERR_NONFATAL
, "`%s': not in a macro call", t
->text
);
3469 switch (t
->text
[1]) {
3471 * We have to make a substitution of one of the
3472 * forms %1, %-1, %+1, %%foo, %0.
3476 snprintf(tmpbuf
, sizeof(tmpbuf
), "%d", mac
->nparam
);
3477 text
= nasm_strdup(tmpbuf
);
3481 snprintf(tmpbuf
, sizeof(tmpbuf
), "..@%"PRIu64
".",
3483 text
= nasm_strcat(tmpbuf
, t
->text
+ 2);
3486 n
= atoi(t
->text
+ 2) - 1;
3487 if (n
>= mac
->nparam
)
3490 if (mac
->nparam
> 1)
3491 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3492 tt
= mac
->params
[n
];
3497 "macro parameter %d is not a condition code",
3502 if (inverse_ccs
[cc
] == -1) {
3504 "condition code `%s' is not invertible",
3508 text
= nasm_strdup(conditions
[inverse_ccs
[cc
]]);
3512 n
= atoi(t
->text
+ 2) - 1;
3513 if (n
>= mac
->nparam
)
3516 if (mac
->nparam
> 1)
3517 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3518 tt
= mac
->params
[n
];
3523 "macro parameter %d is not a condition code",
3528 text
= nasm_strdup(conditions
[cc
]);
3532 n
= atoi(t
->text
+ 1) - 1;
3533 if (n
>= mac
->nparam
)
3536 if (mac
->nparam
> 1)
3537 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3538 tt
= mac
->params
[n
];
3541 for (i
= 0; i
< mac
->paramlen
[n
]; i
++) {
3542 *tail
= new_Token(NULL
, tt
->type
, tt
->text
, 0);
3543 tail
= &(*tail
)->next
;
3547 text
= NULL
; /* we've done it here */
3562 } else if (tline
->type
== TOK_INDIRECT
) {
3564 tline
= tline
->next
;
3565 tt
= tokenize(t
->text
);
3566 tt
= expand_mmac_params(tt
);
3567 tt
= expand_smacro(tt
);
3570 tt
->a
.mac
= NULL
; /* Necessary? */
3578 tline
= tline
->next
;
3586 paste_tokens(&thead
, false);
3592 * Expand all single-line macro calls made in the given line.
3593 * Return the expanded version of the line. The original is deemed
3594 * to be destroyed in the process. (In reality we'll just move
3595 * Tokens from input to output a lot of the time, rather than
3596 * actually bothering to destroy and replicate.)
3598 #define DEADMAN_LIMIT (1 << 20)
3600 static Token
*expand_smacro(Token
* tline
)
3602 Token
*t
, *tt
, *mstart
, **tail
, *thead
;
3603 struct hash_table
*smtbl
;
3604 SMacro
*head
= NULL
, *m
;
3607 unsigned int nparam
, sparam
;
3609 Token
*org_tline
= tline
;
3612 int deadman
= DEADMAN_LIMIT
;
3616 * Trick: we should avoid changing the start token pointer since it can
3617 * be contained in "next" field of other token. Because of this
3618 * we allocate a copy of first token and work with it; at the end of
3619 * routine we copy it back
3623 new_Token(org_tline
->next
, org_tline
->type
, org_tline
->text
,
3625 tline
->a
.mac
= org_tline
->a
.mac
;
3626 nasm_free(org_tline
->text
);
3627 org_tline
->text
= NULL
;
3635 while (tline
) { /* main token loop */
3637 error(ERR_NONFATAL
, "interminable macro recursion");
3641 if ((mname
= tline
->text
)) {
3642 /* if this token is a local macro, look in local context */
3643 if (tline
->type
== TOK_ID
|| tline
->type
== TOK_PREPROC_ID
)
3644 ctx
= get_ctx(mname
, &mname
, true);
3647 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
3648 head
= (SMacro
*) hash_findix(smtbl
, mname
);
3651 * We've hit an identifier. As in is_mmacro below, we first
3652 * check whether the identifier is a single-line macro at
3653 * all, then think about checking for parameters if
3656 for (m
= head
; m
; m
= m
->next
)
3657 if (!mstrcmp(m
->name
, mname
, m
->casesense
))
3663 if (m
->nparam
== 0) {
3665 * Simple case: the macro is parameterless. Discard the
3666 * one token that the macro call took, and push the
3667 * expansion back on the to-do stack.
3669 if (!m
->expansion
) {
3670 if (!strcmp("__FILE__", m
->name
)) {
3673 src_get(&num
, &file
);
3674 tline
->text
= nasm_quote(file
, strlen(file
));
3675 tline
->type
= TOK_STRING
;
3679 if (!strcmp("__LINE__", m
->name
)) {
3680 nasm_free(tline
->text
);
3681 make_tok_num(tline
, src_get_linnum());
3684 if (!strcmp("__BITS__", m
->name
)) {
3685 nasm_free(tline
->text
);
3686 make_tok_num(tline
, globalbits
);
3689 tline
= delete_Token(tline
);
3694 * Complicated case: at least one macro with this name
3695 * exists and takes parameters. We must find the
3696 * parameters in the call, count them, find the SMacro
3697 * that corresponds to that form of the macro call, and
3698 * substitute for the parameters when we expand. What a
3701 /*tline = tline->next;
3702 skip_white_(tline); */
3705 while (tok_type_(t
, TOK_SMAC_END
)) {
3706 t
->a
.mac
->in_progress
= false;
3708 t
= tline
->next
= delete_Token(t
);
3711 } while (tok_type_(tline
, TOK_WHITESPACE
));
3712 if (!tok_is_(tline
, "(")) {
3714 * This macro wasn't called with parameters: ignore
3715 * the call. (Behaviour borrowed from gnu cpp.)
3724 sparam
= PARAM_DELTA
;
3725 params
= nasm_malloc(sparam
* sizeof(Token
*));
3726 params
[0] = tline
->next
;
3727 paramsize
= nasm_malloc(sparam
* sizeof(int));
3729 while (true) { /* parameter loop */
3731 * For some unusual expansions
3732 * which concatenates function call
3735 while (tok_type_(t
, TOK_SMAC_END
)) {
3736 t
->a
.mac
->in_progress
= false;
3738 t
= tline
->next
= delete_Token(t
);
3744 "macro call expects terminating `)'");
3747 if (tline
->type
== TOK_WHITESPACE
3749 if (paramsize
[nparam
])
3752 params
[nparam
] = tline
->next
;
3753 continue; /* parameter loop */
3755 if (tline
->type
== TOK_OTHER
3756 && tline
->text
[1] == 0) {
3757 char ch
= tline
->text
[0];
3758 if (ch
== ',' && !paren
&& brackets
<= 0) {
3759 if (++nparam
>= sparam
) {
3760 sparam
+= PARAM_DELTA
;
3761 params
= nasm_realloc(params
,
3766 nasm_realloc(paramsize
,
3770 params
[nparam
] = tline
->next
;
3771 paramsize
[nparam
] = 0;
3773 continue; /* parameter loop */
3776 (brackets
> 0 || (brackets
== 0 &&
3777 !paramsize
[nparam
])))
3779 if (!(brackets
++)) {
3780 params
[nparam
] = tline
->next
;
3781 continue; /* parameter loop */
3784 if (ch
== '}' && brackets
> 0)
3785 if (--brackets
== 0) {
3787 continue; /* parameter loop */
3789 if (ch
== '(' && !brackets
)
3791 if (ch
== ')' && brackets
<= 0)
3797 error(ERR_NONFATAL
, "braces do not "
3798 "enclose all of macro parameter");
3800 paramsize
[nparam
] += white
+ 1;
3802 } /* parameter loop */
3804 while (m
&& (m
->nparam
!= nparam
||
3805 mstrcmp(m
->name
, mname
,
3809 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
3810 "macro `%s' exists, "
3811 "but not taking %d parameters",
3812 mstart
->text
, nparam
);
3815 if (m
&& m
->in_progress
)
3817 if (!m
) { /* in progess or didn't find '(' or wrong nparam */
3819 * Design question: should we handle !tline, which
3820 * indicates missing ')' here, or expand those
3821 * macros anyway, which requires the (t) test a few
3825 nasm_free(paramsize
);
3829 * Expand the macro: we are placed on the last token of the
3830 * call, so that we can easily split the call from the
3831 * following tokens. We also start by pushing an SMAC_END
3832 * token for the cycle removal.
3839 tt
= new_Token(tline
, TOK_SMAC_END
, NULL
, 0);
3841 m
->in_progress
= true;
3843 for (t
= m
->expansion
; t
; t
= t
->next
) {
3844 if (t
->type
>= TOK_SMAC_PARAM
) {
3845 Token
*pcopy
= tline
, **ptail
= &pcopy
;
3849 ttt
= params
[t
->type
- TOK_SMAC_PARAM
];
3850 for (i
= paramsize
[t
->type
- TOK_SMAC_PARAM
];
3853 new_Token(tline
, ttt
->type
, ttt
->text
,
3859 } else if (t
->type
== TOK_PREPROC_Q
) {
3860 tt
= new_Token(tline
, TOK_ID
, mname
, 0);
3862 } else if (t
->type
== TOK_PREPROC_QQ
) {
3863 tt
= new_Token(tline
, TOK_ID
, m
->name
, 0);
3866 tt
= new_Token(tline
, t
->type
, t
->text
, 0);
3872 * Having done that, get rid of the macro call, and clean
3873 * up the parameters.
3876 nasm_free(paramsize
);
3879 continue; /* main token loop */
3884 if (tline
->type
== TOK_SMAC_END
) {
3885 tline
->a
.mac
->in_progress
= false;
3886 tline
= delete_Token(tline
);
3889 tline
= tline
->next
;
3897 * Now scan the entire line and look for successive TOK_IDs that resulted
3898 * after expansion (they can't be produced by tokenize()). The successive
3899 * TOK_IDs should be concatenated.
3900 * Also we look for %+ tokens and concatenate the tokens before and after
3901 * them (without white spaces in between).
3903 if (expanded
&& paste_tokens(&thead
, true)) {
3904 /* If we concatenated something, re-scan the line for macros */
3911 *org_tline
= *thead
;
3912 /* since we just gave text to org_line, don't free it */
3914 delete_Token(thead
);
3916 /* the expression expanded to empty line;
3917 we can't return NULL for some reasons
3918 we just set the line to a single WHITESPACE token. */
3919 memset(org_tline
, 0, sizeof(*org_tline
));
3920 org_tline
->text
= NULL
;
3921 org_tline
->type
= TOK_WHITESPACE
;
3930 * Similar to expand_smacro but used exclusively with macro identifiers
3931 * right before they are fetched in. The reason is that there can be
3932 * identifiers consisting of several subparts. We consider that if there
3933 * are more than one element forming the name, user wants a expansion,
3934 * otherwise it will be left as-is. Example:
3938 * the identifier %$abc will be left as-is so that the handler for %define
3939 * will suck it and define the corresponding value. Other case:
3941 * %define _%$abc cde
3943 * In this case user wants name to be expanded *before* %define starts
3944 * working, so we'll expand %$abc into something (if it has a value;
3945 * otherwise it will be left as-is) then concatenate all successive
3948 static Token
*expand_id(Token
* tline
)
3950 Token
*cur
, *oldnext
= NULL
;
3952 if (!tline
|| !tline
->next
)
3957 (cur
->next
->type
== TOK_ID
||
3958 cur
->next
->type
== TOK_PREPROC_ID
3959 || cur
->next
->type
== TOK_NUMBER
))
3962 /* If identifier consists of just one token, don't expand */
3967 oldnext
= cur
->next
; /* Detach the tail past identifier */
3968 cur
->next
= NULL
; /* so that expand_smacro stops here */
3971 tline
= expand_smacro(tline
);
3974 /* expand_smacro possibly changhed tline; re-scan for EOL */
3976 while (cur
&& cur
->next
)
3979 cur
->next
= oldnext
;
3986 * Determine whether the given line constitutes a multi-line macro
3987 * call, and return the MMacro structure called if so. Doesn't have
3988 * to check for an initial label - that's taken care of in
3989 * expand_mmacro - but must check numbers of parameters. Guaranteed
3990 * to be called with tline->type == TOK_ID, so the putative macro
3991 * name is easy to find.
3993 static MMacro
*is_mmacro(Token
* tline
, Token
*** params_array
)
3999 head
= (MMacro
*) hash_findix(&mmacros
, tline
->text
);
4002 * Efficiency: first we see if any macro exists with the given
4003 * name. If not, we can return NULL immediately. _Then_ we
4004 * count the parameters, and then we look further along the
4005 * list if necessary to find the proper MMacro.
4007 for (m
= head
; m
; m
= m
->next
)
4008 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4014 * OK, we have a potential macro. Count and demarcate the
4017 count_mmac_params(tline
->next
, &nparam
, ¶ms
);
4020 * So we know how many parameters we've got. Find the MMacro
4021 * structure that handles this number.
4024 if (m
->nparam_min
<= nparam
4025 && (m
->plus
|| nparam
<= m
->nparam_max
)) {
4027 * This one is right. Just check if cycle removal
4028 * prohibits us using it before we actually celebrate...
4030 if (m
->in_progress
) {
4033 "self-reference in multi-line macro `%s'", m
->name
);
4039 * It's right, and we can use it. Add its default
4040 * parameters to the end of our list if necessary.
4042 if (m
->defaults
&& nparam
< m
->nparam_min
+ m
->ndefs
) {
4044 nasm_realloc(params
,
4045 ((m
->nparam_min
+ m
->ndefs
+
4046 1) * sizeof(*params
)));
4047 while (nparam
< m
->nparam_min
+ m
->ndefs
) {
4048 params
[nparam
] = m
->defaults
[nparam
- m
->nparam_min
];
4053 * If we've gone over the maximum parameter count (and
4054 * we're in Plus mode), ignore parameters beyond
4057 if (m
->plus
&& nparam
> m
->nparam_max
)
4058 nparam
= m
->nparam_max
;
4060 * Then terminate the parameter list, and leave.
4062 if (!params
) { /* need this special case */
4063 params
= nasm_malloc(sizeof(*params
));
4066 params
[nparam
] = NULL
;
4067 *params_array
= params
;
4071 * This one wasn't right: look for the next one with the
4074 for (m
= m
->next
; m
; m
= m
->next
)
4075 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4080 * After all that, we didn't find one with the right number of
4081 * parameters. Issue a warning, and fail to expand the macro.
4083 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4084 "macro `%s' exists, but not taking %d parameters",
4085 tline
->text
, nparam
);
4091 * Expand the multi-line macro call made by the given line, if
4092 * there is one to be expanded. If there is, push the expansion on
4093 * istk->expansion and return 1. Otherwise return 0.
4095 static int expand_mmacro(Token
* tline
)
4097 Token
*startline
= tline
;
4098 Token
*label
= NULL
;
4099 int dont_prepend
= 0;
4100 Token
**params
, *t
, *mtok
, *tt
;
4103 int i
, nparam
, *paramlen
;
4108 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4109 if (!tok_type_(t
, TOK_ID
) && !tok_type_(t
, TOK_PREPROC_ID
))
4112 m
= is_mmacro(t
, ¶ms
);
4118 * We have an id which isn't a macro call. We'll assume
4119 * it might be a label; we'll also check to see if a
4120 * colon follows it. Then, if there's another id after
4121 * that lot, we'll check it again for macro-hood.
4125 if (tok_type_(t
, TOK_WHITESPACE
))
4126 last
= t
, t
= t
->next
;
4127 if (tok_is_(t
, ":")) {
4129 last
= t
, t
= t
->next
;
4130 if (tok_type_(t
, TOK_WHITESPACE
))
4131 last
= t
, t
= t
->next
;
4133 if (!tok_type_(t
, TOK_ID
) || (m
= is_mmacro(t
, ¶ms
)) == NULL
)
4141 * Fix up the parameters: this involves stripping leading and
4142 * trailing whitespace, then stripping braces if they are
4145 for (nparam
= 0; params
[nparam
]; nparam
++) ;
4146 paramlen
= nparam
? nasm_malloc(nparam
* sizeof(*paramlen
)) : NULL
;
4148 for (i
= 0; params
[i
]; i
++) {
4150 int comma
= (!m
->plus
|| i
< nparam
- 1);
4154 if (tok_is_(t
, "{"))
4155 t
= t
->next
, brace
= true, comma
= false;
4159 if (comma
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, ","))
4160 break; /* ... because we have hit a comma */
4161 if (comma
&& t
->type
== TOK_WHITESPACE
4162 && tok_is_(t
->next
, ","))
4163 break; /* ... or a space then a comma */
4164 if (brace
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, "}"))
4165 break; /* ... or a brace */
4172 * OK, we have a MMacro structure together with a set of
4173 * parameters. We must now go through the expansion and push
4174 * copies of each Line on to istk->expansion. Substitution of
4175 * parameter tokens and macro-local tokens doesn't get done
4176 * until the single-line macro substitution process; this is
4177 * because delaying them allows us to change the semantics
4178 * later through %rotate.
4180 * First, push an end marker on to istk->expansion, mark this
4181 * macro as in progress, and set up its invocation-specific
4184 ll
= nasm_malloc(sizeof(Line
));
4185 ll
->next
= istk
->expansion
;
4188 istk
->expansion
= ll
;
4190 m
->in_progress
= true;
4195 m
->paramlen
= paramlen
;
4196 m
->unique
= unique
++;
4199 m
->next_active
= istk
->mstk
;
4202 for (l
= m
->expansion
; l
; l
= l
->next
) {
4205 ll
= nasm_malloc(sizeof(Line
));
4206 ll
->finishes
= NULL
;
4207 ll
->next
= istk
->expansion
;
4208 istk
->expansion
= ll
;
4211 for (t
= l
->first
; t
; t
= t
->next
) {
4215 tt
= *tail
= new_Token(NULL
, TOK_ID
, mname
, 0);
4217 case TOK_PREPROC_QQ
:
4218 tt
= *tail
= new_Token(NULL
, TOK_ID
, m
->name
, 0);
4220 case TOK_PREPROC_ID
:
4221 if (t
->text
[1] == '0' && t
->text
[2] == '0') {
4229 tt
= *tail
= new_Token(NULL
, x
->type
, x
->text
, 0);
4238 * If we had a label, push it on as the first line of
4239 * the macro expansion.
4242 if (dont_prepend
< 0)
4243 free_tlist(startline
);
4245 ll
= nasm_malloc(sizeof(Line
));
4246 ll
->finishes
= NULL
;
4247 ll
->next
= istk
->expansion
;
4248 istk
->expansion
= ll
;
4249 ll
->first
= startline
;
4250 if (!dont_prepend
) {
4252 label
= label
->next
;
4253 label
->next
= tt
= new_Token(NULL
, TOK_OTHER
, ":", 0);
4258 list
->uplevel(m
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
4263 /* The function that actually does the error reporting */
4264 static void verror(int severity
, const char *fmt
, va_list arg
)
4268 vsnprintf(buff
, sizeof(buff
), fmt
, arg
);
4270 if (istk
&& istk
->mstk
&& istk
->mstk
->name
)
4271 _error(severity
, "(%s:%d) %s", istk
->mstk
->name
,
4272 istk
->mstk
->lineno
, buff
);
4274 _error(severity
, "%s", buff
);
4278 * Since preprocessor always operate only on the line that didn't
4279 * arrived yet, we should always use ERR_OFFBY1.
4281 static void error(int severity
, const char *fmt
, ...)
4285 /* If we're in a dead branch of IF or something like it, ignore the error */
4286 if (istk
&& istk
->conds
&& !emitting(istk
->conds
->state
))
4290 verror(severity
, fmt
, arg
);
4295 * Because %else etc are evaluated in the state context
4296 * of the previous branch, errors might get lost with error():
4297 * %if 0 ... %else trailing garbage ... %endif
4298 * So %else etc should report errors with this function.
4300 static void error_precond(int severity
, const char *fmt
, ...)
4304 /* Only ignore the error if it's really in a dead branch */
4305 if (istk
&& istk
->conds
&& istk
->conds
->state
== COND_NEVER
)
4309 verror(severity
, fmt
, arg
);
4314 pp_reset(char *file
, int apass
, efunc errfunc
, evalfunc eval
,
4315 ListGen
* listgen
, StrList
**deplist
)
4321 istk
= nasm_malloc(sizeof(Include
));
4324 istk
->expansion
= NULL
;
4326 istk
->fp
= fopen(file
, "r");
4328 src_set_fname(nasm_strdup(file
));
4332 error(ERR_FATAL
|ERR_NOFILE
, "unable to open input file `%s'",
4335 nested_mac_count
= 0;
4336 nested_rep_count
= 0;
4339 if (tasm_compatible_mode
) {
4340 stdmacpos
= nasm_stdmac
;
4342 stdmacpos
= nasm_stdmac_after_tasm
;
4344 any_extrastdmac
= extrastdmac
&& *extrastdmac
;
4350 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4351 * The caller, however, will also pass in 3 for preprocess-only so
4352 * we can set __PASS__ accordingly.
4354 pass
= apass
> 2 ? 2 : apass
;
4356 dephead
= deptail
= deplist
;
4358 StrList
*sl
= nasm_malloc(strlen(file
)+1+sizeof sl
->next
);
4360 strcpy(sl
->str
, file
);
4362 deptail
= &sl
->next
;
4366 * Define the __PASS__ macro. This is defined here unlike
4367 * all the other builtins, because it is special -- it varies between
4370 t
= nasm_malloc(sizeof(*t
));
4372 make_tok_num(t
, apass
);
4374 define_smacro(NULL
, "__PASS__", true, 0, t
);
4377 static char *pp_getline(void)
4384 * Fetch a tokenized line, either from the macro-expansion
4385 * buffer or from the input file.
4388 while (istk
->expansion
&& istk
->expansion
->finishes
) {
4389 Line
*l
= istk
->expansion
;
4390 if (!l
->finishes
->name
&& l
->finishes
->in_progress
> 1) {
4394 * This is a macro-end marker for a macro with no
4395 * name, which means it's not really a macro at all
4396 * but a %rep block, and the `in_progress' field is
4397 * more than 1, meaning that we still need to
4398 * repeat. (1 means the natural last repetition; 0
4399 * means termination by %exitrep.) We have
4400 * therefore expanded up to the %endrep, and must
4401 * push the whole block on to the expansion buffer
4402 * again. We don't bother to remove the macro-end
4403 * marker: we'd only have to generate another one
4406 l
->finishes
->in_progress
--;
4407 for (l
= l
->finishes
->expansion
; l
; l
= l
->next
) {
4408 Token
*t
, *tt
, **tail
;
4410 ll
= nasm_malloc(sizeof(Line
));
4411 ll
->next
= istk
->expansion
;
4412 ll
->finishes
= NULL
;
4416 for (t
= l
->first
; t
; t
= t
->next
) {
4417 if (t
->text
|| t
->type
== TOK_WHITESPACE
) {
4419 new_Token(NULL
, t
->type
, t
->text
, 0);
4424 istk
->expansion
= ll
;
4428 * Check whether a `%rep' was started and not ended
4429 * within this macro expansion. This can happen and
4430 * should be detected. It's a fatal error because
4431 * I'm too confused to work out how to recover
4437 "defining with name in expansion");
4438 else if (istk
->mstk
->name
)
4440 "`%%rep' without `%%endrep' within"
4441 " expansion of macro `%s'",
4446 * FIXME: investigate the relationship at this point between
4447 * istk->mstk and l->finishes
4450 MMacro
*m
= istk
->mstk
;
4451 istk
->mstk
= m
->next_active
;
4454 * This was a real macro call, not a %rep, and
4455 * therefore the parameter information needs to
4458 nasm_free(m
->params
);
4459 free_tlist(m
->iline
);
4460 nasm_free(m
->paramlen
);
4461 l
->finishes
->in_progress
= false;
4465 istk
->expansion
= l
->next
;
4467 list
->downlevel(LIST_MACRO
);
4470 while (1) { /* until we get a line we can use */
4472 if (istk
->expansion
) { /* from a macro expansion */
4474 Line
*l
= istk
->expansion
;
4476 istk
->mstk
->lineno
++;
4478 istk
->expansion
= l
->next
;
4480 p
= detoken(tline
, false);
4481 list
->line(LIST_MACRO
, p
);
4486 if (line
) { /* from the current input file */
4487 line
= prepreproc(line
);
4488 tline
= tokenize(line
);
4493 * The current file has ended; work down the istk
4500 "expected `%%endif' before end of file");
4501 /* only set line and file name if there's a next node */
4503 src_set_linnum(i
->lineno
);
4504 nasm_free(src_set_fname(i
->fname
));
4507 list
->downlevel(LIST_INCLUDE
);
4511 if (istk
->expansion
&& istk
->expansion
->finishes
)
4517 * We must expand MMacro parameters and MMacro-local labels
4518 * _before_ we plunge into directive processing, to cope
4519 * with things like `%define something %1' such as STRUC
4520 * uses. Unless we're _defining_ a MMacro, in which case
4521 * those tokens should be left alone to go into the
4522 * definition; and unless we're in a non-emitting
4523 * condition, in which case we don't want to meddle with
4526 if (!defining
&& !(istk
->conds
&& !emitting(istk
->conds
->state
))
4527 && !(istk
->mstk
&& !istk
->mstk
->in_progress
)) {
4528 tline
= expand_mmac_params(tline
);
4532 * Check the line to see if it's a preprocessor directive.
4534 if (do_directive(tline
) == DIRECTIVE_FOUND
) {
4536 } else if (defining
) {
4538 * We're defining a multi-line macro. We emit nothing
4540 * shove the tokenized line on to the macro definition.
4542 Line
*l
= nasm_malloc(sizeof(Line
));
4543 l
->next
= defining
->expansion
;
4546 defining
->expansion
= l
;
4548 } else if (istk
->conds
&& !emitting(istk
->conds
->state
)) {
4550 * We're in a non-emitting branch of a condition block.
4551 * Emit nothing at all, not even a blank line: when we
4552 * emerge from the condition we'll give a line-number
4553 * directive so we keep our place correctly.
4557 } else if (istk
->mstk
&& !istk
->mstk
->in_progress
) {
4559 * We're in a %rep block which has been terminated, so
4560 * we're walking through to the %endrep without
4561 * emitting anything. Emit nothing at all, not even a
4562 * blank line: when we emerge from the %rep block we'll
4563 * give a line-number directive so we keep our place
4569 tline
= expand_smacro(tline
);
4570 if (!expand_mmacro(tline
)) {
4572 * De-tokenize the line again, and emit it.
4574 line
= detoken(tline
, true);
4578 continue; /* expand_mmacro calls free_tlist */
4586 static void pp_cleanup(int pass
)
4589 if(defining
->name
) {
4591 "end of file while still defining macro `%s'",
4594 error(ERR_NONFATAL
, "end of file while still in %%rep");
4597 free_mmacro(defining
);
4606 nasm_free(i
->fname
);
4611 nasm_free(src_set_fname(NULL
));
4616 while ((i
= ipath
)) {
4625 void pp_include_path(char *path
)
4629 i
= nasm_malloc(sizeof(IncPath
));
4630 i
->path
= path
? nasm_strdup(path
) : NULL
;
4633 if (ipath
!= NULL
) {
4635 while (j
->next
!= NULL
)
4643 void pp_pre_include(char *fname
)
4645 Token
*inc
, *space
, *name
;
4648 name
= new_Token(NULL
, TOK_INTERNAL_STRING
, fname
, 0);
4649 space
= new_Token(name
, TOK_WHITESPACE
, NULL
, 0);
4650 inc
= new_Token(space
, TOK_PREPROC_ID
, "%include", 0);
4652 l
= nasm_malloc(sizeof(Line
));
4659 void pp_pre_define(char *definition
)
4665 equals
= strchr(definition
, '=');
4666 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
4667 def
= new_Token(space
, TOK_PREPROC_ID
, "%define", 0);
4670 space
->next
= tokenize(definition
);
4674 l
= nasm_malloc(sizeof(Line
));
4681 void pp_pre_undefine(char *definition
)
4686 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
4687 def
= new_Token(space
, TOK_PREPROC_ID
, "%undef", 0);
4688 space
->next
= tokenize(definition
);
4690 l
= nasm_malloc(sizeof(Line
));
4698 * Added by Keith Kanios:
4700 * This function is used to assist with "runtime" preprocessor
4701 * directives. (e.g. pp_runtime("%define __BITS__ 64");)
4703 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
4704 * PASS A VALID STRING TO THIS FUNCTION!!!!!
4707 void pp_runtime(char *definition
)
4711 def
= tokenize(definition
);
4712 if(do_directive(def
) == NO_DIRECTIVE_FOUND
)
4717 void pp_extra_stdmac(macros_t
*macros
)
4719 extrastdmac
= macros
;
4722 static void make_tok_num(Token
* tok
, int64_t val
)
4725 snprintf(numbuf
, sizeof(numbuf
), "%"PRId64
"", val
);
4726 tok
->text
= nasm_strdup(numbuf
);
4727 tok
->type
= TOK_NUMBER
;