1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2010 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * preproc.c macro preprocessor for the Netwide Assembler
38 /* Typical flow of text through preproc
40 * pp_getline gets tokenized lines, either
42 * from a macro expansion
46 * read_line gets raw text from stdmacpos, or predef, or current input file
47 * tokenize converts to tokens
50 * expand_mmac_params is used to expand %1 etc., unless a macro is being
51 * defined or a false conditional is being processed
52 * (%0, %1, %+1, %-1, %%foo
54 * do_directive checks for directives
56 * expand_smacro is used to expand single line macros
58 * expand_mmacro is used to expand multi-line macros
60 * detoken is used to convert the line back to text
84 typedef struct SMacro SMacro
;
85 typedef struct MMacro MMacro
;
86 typedef struct MMacroInvocation MMacroInvocation
;
87 typedef struct Context Context
;
88 typedef struct Token Token
;
89 typedef struct Blocks Blocks
;
90 typedef struct Line Line
;
91 typedef struct Include Include
;
92 typedef struct Cond Cond
;
93 typedef struct IncPath IncPath
;
96 * Note on the storage of both SMacro and MMacros: the hash table
97 * indexes them case-insensitively, and we then have to go through a
98 * linked list of potential case aliases (and, for MMacros, parameter
99 * ranges); this is to preserve the matching semantics of the earlier
100 * code. If the number of case aliases for a specific macro is a
101 * performance issue, you may want to reconsider your coding style.
105 * Store the definition of a single-line macro.
117 * Store the definition of a multi-line macro. This is also used to
118 * store the interiors of `%rep...%endrep' blocks, which are
119 * effectively self-re-invoking multi-line macros which simply
120 * don't have a name or bother to appear in the hash tables. %rep
121 * blocks are signified by having a NULL `name' field.
123 * In a MMacro describing a `%rep' block, the `in_progress' field
124 * isn't merely boolean, but gives the number of repeats left to
127 * The `next' field is used for storing MMacros in hash tables; the
128 * `next_active' field is for stacking them on istk entries.
130 * When a MMacro is being expanded, `params', `iline', `nparam',
131 * `paramlen', `rotate' and `unique' are local to the invocation.
135 MMacroInvocation
*prev
; /* previous invocation */
137 int nparam_min
, nparam_max
;
139 bool plus
; /* is the last parameter greedy? */
140 bool nolist
; /* is this macro listing-inhibited? */
141 int64_t in_progress
; /* is this macro currently being expanded? */
142 int32_t max_depth
; /* maximum number of recursive expansions allowed */
143 Token
*dlist
; /* All defaults as one list */
144 Token
**defaults
; /* Parameter default pointers */
145 int ndefs
; /* number of default parameters */
149 MMacro
*rep_nest
; /* used for nesting %rep */
150 Token
**params
; /* actual parameters */
151 Token
*iline
; /* invocation line */
152 unsigned int nparam
, rotate
;
155 int lineno
; /* Current line number on expansion */
156 uint64_t condcnt
; /* number of if blocks... */
160 /* Store the definition of a multi-line macro, as defined in a
161 * previous recursive macro expansion.
163 struct MMacroInvocation
{
164 MMacroInvocation
*prev
; /* previous invocation */
165 Token
**params
; /* actual parameters */
166 Token
*iline
; /* invocation line */
167 unsigned int nparam
, rotate
;
175 * The context stack is composed of a linked list of these.
180 struct hash_table localmac
;
185 * This is the internal form which we break input lines up into.
186 * Typically stored in linked lists.
188 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
189 * necessarily used as-is, but is intended to denote the number of
190 * the substituted parameter. So in the definition
192 * %define a(x,y) ( (x) & ~(y) )
194 * the token representing `x' will have its type changed to
195 * TOK_SMAC_PARAM, but the one representing `y' will be
198 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
199 * which doesn't need quotes around it. Used in the pre-include
200 * mechanism as an alternative to trying to find a sensible type of
201 * quote to use on the filename we were passed.
204 TOK_NONE
= 0, TOK_WHITESPACE
, TOK_COMMENT
, TOK_ID
,
205 TOK_PREPROC_ID
, TOK_STRING
,
206 TOK_NUMBER
, TOK_FLOAT
, TOK_SMAC_END
, TOK_OTHER
,
208 TOK_PREPROC_Q
, TOK_PREPROC_QQ
,
210 TOK_INDIRECT
, /* %[...] */
211 TOK_SMAC_PARAM
, /* MUST BE LAST IN THE LIST!!! */
212 TOK_MAX
= INT_MAX
/* Keep compiler from reducing the range */
219 SMacro
*mac
; /* associated macro for TOK_SMAC_END */
220 size_t len
; /* scratch length field */
221 } a
; /* Auxiliary data */
222 enum pp_token_type type
;
226 * Multi-line macro definitions are stored as a linked list of
227 * these, which is essentially a container to allow several linked
230 * Note that in this module, linked lists are treated as stacks
231 * wherever possible. For this reason, Lines are _pushed_ on to the
232 * `expansion' field in MMacro structures, so that the linked list,
233 * if walked, would give the macro lines in reverse order; this
234 * means that we can walk the list when expanding a macro, and thus
235 * push the lines on to the `expansion' field in _istk_ in reverse
236 * order (so that when popped back off they are in the right
237 * order). It may seem cockeyed, and it relies on my design having
238 * an even number of steps in, but it works...
240 * Some of these structures, rather than being actual lines, are
241 * markers delimiting the end of the expansion of a given macro.
242 * This is for use in the cycle-tracking and %rep-handling code.
243 * Such structures have `finishes' non-NULL, and `first' NULL. All
244 * others have `finishes' NULL, but `first' may still be NULL if
254 * To handle an arbitrary level of file inclusion, we maintain a
255 * stack (ie linked list) of these things.
264 MMacro
*mstk
; /* stack of active macros/reps */
268 * Include search path. This is simply a list of strings which get
269 * prepended, in turn, to the name of an include file, in an
270 * attempt to find the file if it's not in the current directory.
278 * Conditional assembly: we maintain a separate stack of these for
279 * each level of file inclusion. (The only reason we keep the
280 * stacks separate is to ensure that a stray `%endif' in a file
281 * included from within the true branch of a `%if' won't terminate
282 * it and cause confusion: instead, rightly, it'll cause an error.)
290 * These states are for use just after %if or %elif: IF_TRUE
291 * means the condition has evaluated to truth so we are
292 * currently emitting, whereas IF_FALSE means we are not
293 * currently emitting but will start doing so if a %else comes
294 * up. In these states, all directives are admissible: %elif,
295 * %else and %endif. (And of course %if.)
297 COND_IF_TRUE
, COND_IF_FALSE
,
299 * These states come up after a %else: ELSE_TRUE means we're
300 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
301 * any %elif or %else will cause an error.
303 COND_ELSE_TRUE
, COND_ELSE_FALSE
,
305 * These states mean that we're not emitting now, and also that
306 * nothing until %endif will be emitted at all. COND_DONE is
307 * used when we've had our moment of emission
308 * and have now started seeing %elifs. COND_NEVER is used when
309 * the condition construct in question is contained within a
310 * non-emitting branch of a larger condition construct,
311 * or if there is an error.
313 COND_DONE
, COND_NEVER
315 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
318 * These defines are used as the possible return values for do_directive
320 #define NO_DIRECTIVE_FOUND 0
321 #define DIRECTIVE_FOUND 1
324 * This define sets the upper limit for smacro and recursive mmacro
327 #define DEADMAN_LIMIT (1 << 20)
330 #define REP_LIMIT ((INT64_C(1) << 62))
333 * Condition codes. Note that we use c_ prefix not C_ because C_ is
334 * used in nasm.h for the "real" condition codes. At _this_ level,
335 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
336 * ones, so we need a different enum...
338 static const char * const conditions
[] = {
339 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
340 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
341 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
344 c_A
, c_AE
, c_B
, c_BE
, c_C
, c_CXZ
, c_E
, c_ECXZ
, c_G
, c_GE
, c_L
, c_LE
,
345 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, c_NE
, c_NG
, c_NGE
, c_NL
, c_NLE
, c_NO
,
346 c_NP
, c_NS
, c_NZ
, c_O
, c_P
, c_PE
, c_PO
, c_RCXZ
, c_S
, c_Z
,
349 static const enum pp_conds inverse_ccs
[] = {
350 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, -1, c_NE
, -1, c_NG
, c_NGE
, c_NL
, c_NLE
,
351 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
,
352 c_Z
, c_NO
, c_NP
, c_PO
, c_PE
, -1, c_NS
, c_NZ
358 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
359 static int is_condition(enum preproc_token arg
)
361 return PP_IS_COND(arg
) || (arg
== PP_ELSE
) || (arg
== PP_ENDIF
);
364 /* For TASM compatibility we need to be able to recognise TASM compatible
365 * conditional compilation directives. Using the NASM pre-processor does
366 * not work, so we look for them specifically from the following list and
367 * then jam in the equivalent NASM directive into the input stream.
371 TM_ARG
, TM_ELIF
, TM_ELSE
, TM_ENDIF
, TM_IF
, TM_IFDEF
, TM_IFDIFI
,
372 TM_IFNDEF
, TM_INCLUDE
, TM_LOCAL
375 static const char * const tasm_directives
[] = {
376 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
377 "ifndef", "include", "local"
380 static int StackSize
= 4;
381 static char *StackPointer
= "ebp";
382 static int ArgOffset
= 8;
383 static int LocalOffset
= 0;
385 static Context
*cstk
;
386 static Include
*istk
;
387 static IncPath
*ipath
= NULL
;
389 static int pass
; /* HACK: pass 0 = generate dependencies only */
390 static StrList
**dephead
, **deptail
; /* Dependency list */
392 static uint64_t unique
; /* unique identifier numbers */
394 static Line
*predef
= NULL
;
395 static bool do_predef
;
397 static ListGen
*list
;
400 * The current set of multi-line macros we have defined.
402 static struct hash_table mmacros
;
405 * The current set of single-line macros we have defined.
407 static struct hash_table smacros
;
410 * The multi-line macro we are currently defining, or the %rep
411 * block we are currently reading, if any.
413 static MMacro
*defining
;
415 static uint64_t nested_mac_count
;
416 static uint64_t nested_rep_count
;
419 * The number of macro parameters to allocate space for at a time.
421 #define PARAM_DELTA 16
424 * The standard macro set: defined in macros.c in the array nasm_stdmac.
425 * This gives our position in the macro set, when we're processing it.
427 static macros_t
*stdmacpos
;
430 * The extra standard macros that come from the object format, if
433 static macros_t
*extrastdmac
= NULL
;
434 static bool any_extrastdmac
;
437 * Tokens are allocated in blocks to improve speed
439 #define TOKEN_BLOCKSIZE 4096
440 static Token
*freeTokens
= NULL
;
446 static Blocks blocks
= { NULL
, NULL
};
449 * Forward declarations.
451 static Token
*expand_mmac_params(Token
* tline
);
452 static Token
*expand_smacro(Token
* tline
);
453 static Token
*expand_id(Token
* tline
);
454 static Context
*get_ctx(const char *name
, const char **namep
,
456 static void make_tok_num(Token
* tok
, int64_t val
);
457 static void error(int severity
, const char *fmt
, ...);
458 static void error_precond(int severity
, const char *fmt
, ...);
459 static void *new_Block(size_t size
);
460 static void delete_Blocks(void);
461 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
462 const char *text
, int txtlen
);
463 static Token
*delete_Token(Token
* t
);
466 * Macros for safe checking of token pointers, avoid *(NULL)
468 #define tok_type_(x,t) ((x) && (x)->type == (t))
469 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
470 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
471 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
474 * nasm_unquote with error if the string contains NUL characters.
475 * If the string contains NUL characters, issue an error and return
476 * the C len, i.e. truncate at the NUL.
478 static size_t nasm_unquote_cstr(char *qstr
, enum preproc_token directive
)
480 size_t len
= nasm_unquote(qstr
, NULL
);
481 size_t clen
= strlen(qstr
);
484 error(ERR_NONFATAL
, "NUL character in `%s' directive",
485 pp_directives
[directive
]);
491 * Handle TASM specific directives, which do not contain a % in
492 * front of them. We do it here because I could not find any other
493 * place to do it for the moment, and it is a hack (ideally it would
494 * be nice to be able to use the NASM pre-processor to do it).
496 static char *check_tasm_directive(char *line
)
498 int32_t i
, j
, k
, m
, len
;
499 char *p
, *q
, *oldline
, oldchar
;
501 p
= nasm_skip_spaces(line
);
503 /* Binary search for the directive name */
505 j
= ARRAY_SIZE(tasm_directives
);
506 q
= nasm_skip_word(p
);
513 m
= nasm_stricmp(p
, tasm_directives
[k
]);
515 /* We have found a directive, so jam a % in front of it
516 * so that NASM will then recognise it as one if it's own.
521 line
= nasm_malloc(len
+ 2);
523 if (k
== TM_IFDIFI
) {
525 * NASM does not recognise IFDIFI, so we convert
526 * it to %if 0. This is not used in NASM
527 * compatible code, but does need to parse for the
528 * TASM macro package.
530 strcpy(line
+ 1, "if 0");
532 memcpy(line
+ 1, p
, len
+ 1);
547 * The pre-preprocessing stage... This function translates line
548 * number indications as they emerge from GNU cpp (`# lineno "file"
549 * flags') into NASM preprocessor line number indications (`%line
552 static char *prepreproc(char *line
)
555 char *fname
, *oldline
;
557 if (line
[0] == '#' && line
[1] == ' ') {
560 lineno
= atoi(fname
);
561 fname
+= strspn(fname
, "0123456789 ");
564 fnlen
= strcspn(fname
, "\"");
565 line
= nasm_malloc(20 + fnlen
);
566 snprintf(line
, 20 + fnlen
, "%%line %d %.*s", lineno
, fnlen
, fname
);
569 if (tasm_compatible_mode
)
570 return check_tasm_directive(line
);
575 * Free a linked list of tokens.
577 static void free_tlist(Token
* list
)
580 list
= delete_Token(list
);
584 * Free a linked list of lines.
586 static void free_llist(Line
* list
)
589 list_for_each_safe(l
, tmp
, list
) {
590 free_tlist(l
->first
);
598 static void free_mmacro(MMacro
* m
)
601 free_tlist(m
->dlist
);
602 nasm_free(m
->defaults
);
603 free_llist(m
->expansion
);
608 * Free all currently defined macros, and free the hash tables
610 static void free_smacro_table(struct hash_table
*smt
)
614 struct hash_tbl_node
*it
= NULL
;
616 while ((s
= hash_iterate(smt
, &it
, &key
)) != NULL
) {
617 nasm_free((void *)key
);
618 list_for_each_safe(s
, tmp
, s
) {
620 free_tlist(s
->expansion
);
627 static void free_mmacro_table(struct hash_table
*mmt
)
631 struct hash_tbl_node
*it
= NULL
;
634 while ((m
= hash_iterate(mmt
, &it
, &key
)) != NULL
) {
635 nasm_free((void *)key
);
636 list_for_each_safe(m
,tmp
, m
)
642 static void free_macros(void)
644 free_smacro_table(&smacros
);
645 free_mmacro_table(&mmacros
);
649 * Initialize the hash tables
651 static void init_macros(void)
653 hash_init(&smacros
, HASH_LARGE
);
654 hash_init(&mmacros
, HASH_LARGE
);
658 * Pop the context stack.
660 static void ctx_pop(void)
665 free_smacro_table(&c
->localmac
);
671 * Search for a key in the hash index; adding it if necessary
672 * (in which case we initialize the data pointer to NULL.)
675 hash_findi_add(struct hash_table
*hash
, const char *str
)
677 struct hash_insert hi
;
681 r
= hash_findi(hash
, str
, &hi
);
685 strx
= nasm_strdup(str
); /* Use a more efficient allocator here? */
686 return hash_add(&hi
, strx
, NULL
);
690 * Like hash_findi, but returns the data element rather than a pointer
691 * to it. Used only when not adding a new element, hence no third
695 hash_findix(struct hash_table
*hash
, const char *str
)
699 p
= hash_findi(hash
, str
, NULL
);
700 return p
? *p
: NULL
;
704 * read line from standart macros set,
705 * if there no more left -- return NULL
707 static char *line_from_stdmac(void)
710 const unsigned char *p
= stdmacpos
;
719 len
+= pp_directives_len
[c
- 0x80] + 1;
724 line
= nasm_malloc(len
+ 1);
726 while ((c
= *stdmacpos
++)) {
728 memcpy(q
, pp_directives
[c
- 0x80], pp_directives_len
[c
- 0x80]);
729 q
+= pp_directives_len
[c
- 0x80];
739 /* This was the last of the standard macro chain... */
741 if (any_extrastdmac
) {
742 stdmacpos
= extrastdmac
;
743 any_extrastdmac
= false;
744 } else if (do_predef
) {
746 Token
*head
, **tail
, *t
;
749 * Nasty hack: here we push the contents of
750 * `predef' on to the top-level expansion stack,
751 * since this is the most convenient way to
752 * implement the pre-include and pre-define
755 list_for_each(pd
, predef
) {
758 list_for_each(t
, pd
->first
) {
759 *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
760 tail
= &(*tail
)->next
;
763 l
= nasm_malloc(sizeof(Line
));
764 l
->next
= istk
->expansion
;
777 #define BUF_DELTA 512
779 * Read a line from the top file in istk, handling multiple CR/LFs
780 * at the end of the line read, and handling spurious ^Zs. Will
781 * return lines from the standard macro set if this has not already
784 static char *read_line(void)
786 char *buffer
, *p
, *q
;
787 int bufsize
, continued_count
;
790 * standart macros set (predefined) goes first
792 p
= line_from_stdmac();
797 * regular read from a file
800 buffer
= nasm_malloc(BUF_DELTA
);
804 q
= fgets(p
, bufsize
- (p
- buffer
), istk
->fp
);
808 if (p
> buffer
&& p
[-1] == '\n') {
810 * Convert backslash-CRLF line continuation sequences into
811 * nothing at all (for DOS and Windows)
813 if (((p
- 2) > buffer
) && (p
[-3] == '\\') && (p
[-2] == '\r')) {
819 * Also convert backslash-LF line continuation sequences into
820 * nothing at all (for Unix)
822 else if (((p
- 1) > buffer
) && (p
[-2] == '\\')) {
830 if (p
- buffer
> bufsize
- 10) {
831 int32_t offset
= p
- buffer
;
832 bufsize
+= BUF_DELTA
;
833 buffer
= nasm_realloc(buffer
, bufsize
);
834 p
= buffer
+ offset
; /* prevent stale-pointer problems */
838 if (!q
&& p
== buffer
) {
843 src_set_linnum(src_get_linnum() + istk
->lineinc
+
844 (continued_count
* istk
->lineinc
));
847 * Play safe: remove CRs as well as LFs, if any of either are
848 * present at the end of the line.
850 while (--p
>= buffer
&& (*p
== '\n' || *p
== '\r'))
854 * Handle spurious ^Z, which may be inserted into source files
855 * by some file transfer utilities.
857 buffer
[strcspn(buffer
, "\032")] = '\0';
859 list
->line(LIST_READ
, buffer
);
865 * Tokenize a line of text. This is a very simple process since we
866 * don't need to parse the value out of e.g. numeric tokens: we
867 * simply split one string into many.
869 static Token
*tokenize(char *line
)
872 enum pp_token_type type
;
874 Token
*t
, **tail
= &list
;
880 if (*p
== '+' && !nasm_isdigit(p
[1])) {
883 } else if (nasm_isdigit(*p
) ||
884 ((*p
== '-' || *p
== '+') && nasm_isdigit(p
[1]))) {
888 while (nasm_isdigit(*p
));
889 type
= TOK_PREPROC_ID
;
890 } else if (*p
== '{') {
892 while (*p
&& *p
!= '}') {
899 type
= TOK_PREPROC_ID
;
900 } else if (*p
== '[') {
902 line
+= 2; /* Skip the leading %[ */
904 while (lvl
&& (c
= *p
++)) {
916 p
= nasm_skip_string(p
- 1) + 1;
926 error(ERR_NONFATAL
, "unterminated %[ construct");
928 } else if (*p
== '?') {
929 type
= TOK_PREPROC_Q
; /* %? */
932 type
= TOK_PREPROC_QQ
; /* %?? */
935 } else if (*p
== '!') {
936 type
= TOK_PREPROC_ID
;
941 } while (isidchar(*p
));
942 } else if (*p
== '\'' || *p
== '\"' || *p
== '`') {
943 p
= nasm_skip_string(p
);
947 error(ERR_NONFATAL
|ERR_PASS1
, "unterminated %! string");
949 /* %! without string or identifier */
950 type
= TOK_OTHER
; /* Legacy behavior... */
952 } else if (isidchar(*p
) ||
953 ((*p
== '!' || *p
== '%' || *p
== '$') &&
958 while (isidchar(*p
));
959 type
= TOK_PREPROC_ID
;
965 } else if (isidstart(*p
) || (*p
== '$' && isidstart(p
[1]))) {
968 while (*p
&& isidchar(*p
))
970 } else if (*p
== '\'' || *p
== '"' || *p
== '`') {
975 p
= nasm_skip_string(p
);
980 error(ERR_WARNING
|ERR_PASS1
, "unterminated string");
981 /* Handling unterminated strings by UNV */
984 } else if (p
[0] == '$' && p
[1] == '$') {
985 type
= TOK_OTHER
; /* TOKEN_BASE */
987 } else if (isnumstart(*p
)) {
989 bool is_float
= false;
1005 if (!is_hex
&& (c
== 'e' || c
== 'E')) {
1007 if (*p
== '+' || *p
== '-') {
1009 * e can only be followed by +/- if it is either a
1010 * prefixed hex number or a floating-point number
1015 } else if (c
== 'H' || c
== 'h' || c
== 'X' || c
== 'x') {
1017 } else if (c
== 'P' || c
== 'p') {
1019 if (*p
== '+' || *p
== '-')
1021 } else if (isnumchar(c
) || c
== '_')
1022 ; /* just advance */
1023 else if (c
== '.') {
1025 * we need to deal with consequences of the legacy
1026 * parser, like "1.nolist" being two tokens
1027 * (TOK_NUMBER, TOK_ID) here; at least give it
1028 * a shot for now. In the future, we probably need
1029 * a flex-based scanner with proper pattern matching
1030 * to do it as well as it can be done. Nothing in
1031 * the world is going to help the person who wants
1032 * 0x123.p16 interpreted as two tokens, though.
1038 if (nasm_isdigit(*r
) || (is_hex
&& nasm_isxdigit(*r
)) ||
1039 (!is_hex
&& (*r
== 'e' || *r
== 'E')) ||
1040 (*r
== 'p' || *r
== 'P')) {
1044 break; /* Terminate the token */
1048 p
--; /* Point to first character beyond number */
1050 if (p
== line
+1 && *line
== '$') {
1051 type
= TOK_OTHER
; /* TOKEN_HERE */
1053 if (has_e
&& !is_hex
) {
1054 /* 1e13 is floating-point, but 1e13h is not */
1058 type
= is_float
? TOK_FLOAT
: TOK_NUMBER
;
1060 } else if (nasm_isspace(*p
)) {
1061 type
= TOK_WHITESPACE
;
1062 p
= nasm_skip_spaces(p
);
1064 * Whitespace just before end-of-line is discarded by
1065 * pretending it's a comment; whitespace just before a
1066 * comment gets lumped into the comment.
1068 if (!*p
|| *p
== ';') {
1073 } else if (*p
== ';') {
1079 * Anything else is an operator of some kind. We check
1080 * for all the double-character operators (>>, <<, //,
1081 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1082 * else is a single-character operator.
1085 if ((p
[0] == '>' && p
[1] == '>') ||
1086 (p
[0] == '<' && p
[1] == '<') ||
1087 (p
[0] == '/' && p
[1] == '/') ||
1088 (p
[0] == '<' && p
[1] == '=') ||
1089 (p
[0] == '>' && p
[1] == '=') ||
1090 (p
[0] == '=' && p
[1] == '=') ||
1091 (p
[0] == '!' && p
[1] == '=') ||
1092 (p
[0] == '<' && p
[1] == '>') ||
1093 (p
[0] == '&' && p
[1] == '&') ||
1094 (p
[0] == '|' && p
[1] == '|') ||
1095 (p
[0] == '^' && p
[1] == '^')) {
1101 /* Handling unterminated string by UNV */
1104 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1105 t->text[p-line] = *line;
1109 if (type
!= TOK_COMMENT
) {
1110 *tail
= t
= new_Token(NULL
, type
, line
, p
- line
);
1119 * this function allocates a new managed block of memory and
1120 * returns a pointer to the block. The managed blocks are
1121 * deleted only all at once by the delete_Blocks function.
1123 static void *new_Block(size_t size
)
1125 Blocks
*b
= &blocks
;
1127 /* first, get to the end of the linked list */
1130 /* now allocate the requested chunk */
1131 b
->chunk
= nasm_malloc(size
);
1133 /* now allocate a new block for the next request */
1134 b
->next
= nasm_malloc(sizeof(Blocks
));
1135 /* and initialize the contents of the new block */
1136 b
->next
->next
= NULL
;
1137 b
->next
->chunk
= NULL
;
1142 * this function deletes all managed blocks of memory
1144 static void delete_Blocks(void)
1146 Blocks
*a
, *b
= &blocks
;
1149 * keep in mind that the first block, pointed to by blocks
1150 * is a static and not dynamically allocated, so we don't
1155 nasm_free(b
->chunk
);
1164 * this function creates a new Token and passes a pointer to it
1165 * back to the caller. It sets the type and text elements, and
1166 * also the a.mac and next elements to NULL.
1168 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
1169 const char *text
, int txtlen
)
1175 freeTokens
= (Token
*) new_Block(TOKEN_BLOCKSIZE
* sizeof(Token
));
1176 for (i
= 0; i
< TOKEN_BLOCKSIZE
- 1; i
++)
1177 freeTokens
[i
].next
= &freeTokens
[i
+ 1];
1178 freeTokens
[i
].next
= NULL
;
1181 freeTokens
= t
->next
;
1185 if (type
== TOK_WHITESPACE
|| !text
) {
1189 txtlen
= strlen(text
);
1190 t
->text
= nasm_malloc(txtlen
+1);
1191 memcpy(t
->text
, text
, txtlen
);
1192 t
->text
[txtlen
] = '\0';
1197 static Token
*delete_Token(Token
* t
)
1199 Token
*next
= t
->next
;
1201 t
->next
= freeTokens
;
1207 * Convert a line of tokens back into text.
1208 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1209 * will be transformed into ..@ctxnum.xxx
1211 static char *detoken(Token
* tlist
, bool expand_locals
)
1218 list_for_each(t
, tlist
) {
1219 if (t
->type
== TOK_PREPROC_ID
&& t
->text
[1] == '!') {
1224 if (*v
== '\'' || *v
== '\"' || *v
== '`') {
1225 size_t len
= nasm_unquote(v
, NULL
);
1226 size_t clen
= strlen(v
);
1229 error(ERR_NONFATAL
| ERR_PASS1
,
1230 "NUL character in %! string");
1236 char *p
= getenv(v
);
1238 error(ERR_NONFATAL
| ERR_PASS1
,
1239 "nonexistent environment variable `%s'", v
);
1242 t
->text
= nasm_strdup(p
);
1247 /* Expand local macros here and not during preprocessing */
1248 if (expand_locals
&&
1249 t
->type
== TOK_PREPROC_ID
&& t
->text
&&
1250 t
->text
[0] == '%' && t
->text
[1] == '$') {
1253 Context
*ctx
= get_ctx(t
->text
, &q
, false);
1256 snprintf(buffer
, sizeof(buffer
), "..@%"PRIu32
".", ctx
->number
);
1257 p
= nasm_strcat(buffer
, q
);
1262 if (t
->type
== TOK_WHITESPACE
)
1265 len
+= strlen(t
->text
);
1268 p
= line
= nasm_malloc(len
+ 1);
1270 list_for_each(t
, tlist
) {
1271 if (t
->type
== TOK_WHITESPACE
) {
1273 } else if (t
->text
) {
1285 * A scanner, suitable for use by the expression evaluator, which
1286 * operates on a line of Tokens. Expects a pointer to a pointer to
1287 * the first token in the line to be passed in as its private_data
1290 * FIX: This really needs to be unified with stdscan.
1292 static int ppscan(void *private_data
, struct tokenval
*tokval
)
1294 Token
**tlineptr
= private_data
;
1296 char ourcopy
[MAX_KEYWORD
+1], *p
, *r
, *s
;
1300 *tlineptr
= tline
? tline
->next
: NULL
;
1301 } while (tline
&& (tline
->type
== TOK_WHITESPACE
||
1302 tline
->type
== TOK_COMMENT
));
1305 return tokval
->t_type
= TOKEN_EOS
;
1307 tokval
->t_charptr
= tline
->text
;
1309 if (tline
->text
[0] == '$' && !tline
->text
[1])
1310 return tokval
->t_type
= TOKEN_HERE
;
1311 if (tline
->text
[0] == '$' && tline
->text
[1] == '$' && !tline
->text
[2])
1312 return tokval
->t_type
= TOKEN_BASE
;
1314 if (tline
->type
== TOK_ID
) {
1315 p
= tokval
->t_charptr
= tline
->text
;
1317 tokval
->t_charptr
++;
1318 return tokval
->t_type
= TOKEN_ID
;
1321 for (r
= p
, s
= ourcopy
; *r
; r
++) {
1322 if (r
>= p
+MAX_KEYWORD
)
1323 return tokval
->t_type
= TOKEN_ID
; /* Not a keyword */
1324 *s
++ = nasm_tolower(*r
);
1327 /* right, so we have an identifier sitting in temp storage. now,
1328 * is it actually a register or instruction name, or what? */
1329 return nasm_token_hash(ourcopy
, tokval
);
1332 if (tline
->type
== TOK_NUMBER
) {
1334 tokval
->t_integer
= readnum(tline
->text
, &rn_error
);
1335 tokval
->t_charptr
= tline
->text
;
1337 return tokval
->t_type
= TOKEN_ERRNUM
;
1339 return tokval
->t_type
= TOKEN_NUM
;
1342 if (tline
->type
== TOK_FLOAT
) {
1343 return tokval
->t_type
= TOKEN_FLOAT
;
1346 if (tline
->type
== TOK_STRING
) {
1349 bq
= tline
->text
[0];
1350 tokval
->t_charptr
= tline
->text
;
1351 tokval
->t_inttwo
= nasm_unquote(tline
->text
, &ep
);
1353 if (ep
[0] != bq
|| ep
[1] != '\0')
1354 return tokval
->t_type
= TOKEN_ERRSTR
;
1356 return tokval
->t_type
= TOKEN_STR
;
1359 if (tline
->type
== TOK_OTHER
) {
1360 if (!strcmp(tline
->text
, "<<"))
1361 return tokval
->t_type
= TOKEN_SHL
;
1362 if (!strcmp(tline
->text
, ">>"))
1363 return tokval
->t_type
= TOKEN_SHR
;
1364 if (!strcmp(tline
->text
, "//"))
1365 return tokval
->t_type
= TOKEN_SDIV
;
1366 if (!strcmp(tline
->text
, "%%"))
1367 return tokval
->t_type
= TOKEN_SMOD
;
1368 if (!strcmp(tline
->text
, "=="))
1369 return tokval
->t_type
= TOKEN_EQ
;
1370 if (!strcmp(tline
->text
, "<>"))
1371 return tokval
->t_type
= TOKEN_NE
;
1372 if (!strcmp(tline
->text
, "!="))
1373 return tokval
->t_type
= TOKEN_NE
;
1374 if (!strcmp(tline
->text
, "<="))
1375 return tokval
->t_type
= TOKEN_LE
;
1376 if (!strcmp(tline
->text
, ">="))
1377 return tokval
->t_type
= TOKEN_GE
;
1378 if (!strcmp(tline
->text
, "&&"))
1379 return tokval
->t_type
= TOKEN_DBL_AND
;
1380 if (!strcmp(tline
->text
, "^^"))
1381 return tokval
->t_type
= TOKEN_DBL_XOR
;
1382 if (!strcmp(tline
->text
, "||"))
1383 return tokval
->t_type
= TOKEN_DBL_OR
;
1387 * We have no other options: just return the first character of
1390 return tokval
->t_type
= tline
->text
[0];
1394 * Compare a string to the name of an existing macro; this is a
1395 * simple wrapper which calls either strcmp or nasm_stricmp
1396 * depending on the value of the `casesense' parameter.
1398 static int mstrcmp(const char *p
, const char *q
, bool casesense
)
1400 return casesense
? strcmp(p
, q
) : nasm_stricmp(p
, q
);
1404 * Compare a string to the name of an existing macro; this is a
1405 * simple wrapper which calls either strcmp or nasm_stricmp
1406 * depending on the value of the `casesense' parameter.
1408 static int mmemcmp(const char *p
, const char *q
, size_t l
, bool casesense
)
1410 return casesense
? memcmp(p
, q
, l
) : nasm_memicmp(p
, q
, l
);
1414 * Return the Context structure associated with a %$ token. Return
1415 * NULL, having _already_ reported an error condition, if the
1416 * context stack isn't deep enough for the supplied number of $
1418 * If all_contexts == true, contexts that enclose current are
1419 * also scanned for such smacro, until it is found; if not -
1420 * only the context that directly results from the number of $'s
1421 * in variable's name.
1423 * If "namep" is non-NULL, set it to the pointer to the macro name
1424 * tail, i.e. the part beyond %$...
1426 static Context
*get_ctx(const char *name
, const char **namep
,
1436 if (!name
|| name
[0] != '%' || name
[1] != '$')
1440 error(ERR_NONFATAL
, "`%s': context stack is empty", name
);
1447 while (ctx
&& *name
== '$') {
1453 error(ERR_NONFATAL
, "`%s': context stack is only"
1454 " %d level%s deep", name
, i
, (i
== 1 ? "" : "s"));
1465 * NOTE: In 2.10 we will not need lookup in extarnal
1466 * contexts, so this is a gentle way to inform users
1467 * about their source code need to be updated
1470 /* first round -- check the current context */
1471 m
= hash_findix(&ctx
->localmac
, name
);
1473 if (!mstrcmp(m
->name
, name
, m
->casesense
))
1478 /* second round - external contexts */
1479 while ((ctx
= ctx
->next
)) {
1480 /* Search for this smacro in found context */
1481 m
= hash_findix(&ctx
->localmac
, name
);
1483 if (!mstrcmp(m
->name
, name
, m
->casesense
)) {
1484 /* NOTE: deprecated as of 2.10 */
1485 static int once
= 0;
1487 error(ERR_WARNING
, "context-local macro expansion"
1488 " fall-through (automatic searching of outer"
1489 " contexts) will be deprecated starting in"
1490 " NASM 2.10, please see the NASM Manual for"
1491 " more information");
1494 error(ERR_WARNING
, "`%s': context-local macro expansion fall-through", name
);
1505 * Check to see if a file is already in a string list
1507 static bool in_list(const StrList
*list
, const char *str
)
1510 if (!strcmp(list
->str
, str
))
1518 * Open an include file. This routine must always return a valid
1519 * file pointer if it returns - it's responsible for throwing an
1520 * ERR_FATAL and bombing out completely if not. It should also try
1521 * the include path one by one until it finds the file or reaches
1522 * the end of the path.
1524 static FILE *inc_fopen(const char *file
, StrList
**dhead
, StrList
***dtail
,
1529 IncPath
*ip
= ipath
;
1530 int len
= strlen(file
);
1531 size_t prefix_len
= 0;
1535 sl
= nasm_malloc(prefix_len
+len
+1+sizeof sl
->next
);
1536 memcpy(sl
->str
, prefix
, prefix_len
);
1537 memcpy(sl
->str
+prefix_len
, file
, len
+1);
1538 fp
= fopen(sl
->str
, "r");
1539 if (fp
&& dhead
&& !in_list(*dhead
, sl
->str
)) {
1557 prefix_len
= strlen(prefix
);
1559 /* -MG given and file not found */
1560 if (dhead
&& !in_list(*dhead
, file
)) {
1561 sl
= nasm_malloc(len
+1+sizeof sl
->next
);
1563 strcpy(sl
->str
, file
);
1571 error(ERR_FATAL
, "unable to open include file `%s'", file
);
1576 * Determine if we should warn on defining a single-line macro of
1577 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1578 * return true if _any_ single-line macro of that name is defined.
1579 * Otherwise, will return true if a single-line macro with either
1580 * `nparam' or no parameters is defined.
1582 * If a macro with precisely the right number of parameters is
1583 * defined, or nparam is -1, the address of the definition structure
1584 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1585 * is NULL, no action will be taken regarding its contents, and no
1588 * Note that this is also called with nparam zero to resolve
1591 * If you already know which context macro belongs to, you can pass
1592 * the context pointer as first parameter; if you won't but name begins
1593 * with %$ the context will be automatically computed. If all_contexts
1594 * is true, macro will be searched in outer contexts as well.
1597 smacro_defined(Context
* ctx
, const char *name
, int nparam
, SMacro
** defn
,
1600 struct hash_table
*smtbl
;
1604 smtbl
= &ctx
->localmac
;
1605 } else if (name
[0] == '%' && name
[1] == '$') {
1607 ctx
= get_ctx(name
, &name
, false);
1609 return false; /* got to return _something_ */
1610 smtbl
= &ctx
->localmac
;
1614 m
= (SMacro
*) hash_findix(smtbl
, name
);
1617 if (!mstrcmp(m
->name
, name
, m
->casesense
&& nocase
) &&
1618 (nparam
<= 0 || m
->nparam
== 0 || nparam
== (int) m
->nparam
)) {
1620 if (nparam
== (int) m
->nparam
|| nparam
== -1)
1634 * Count and mark off the parameters in a multi-line macro call.
1635 * This is called both from within the multi-line macro expansion
1636 * code, and also to mark off the default parameters when provided
1637 * in a %macro definition line.
1639 static void count_mmac_params(Token
* t
, int *nparam
, Token
*** params
)
1641 int paramsize
, brace
;
1643 *nparam
= paramsize
= 0;
1646 /* +1: we need space for the final NULL */
1647 if (*nparam
+1 >= paramsize
) {
1648 paramsize
+= PARAM_DELTA
;
1649 *params
= nasm_realloc(*params
, sizeof(**params
) * paramsize
);
1653 if (tok_is_(t
, "{"))
1655 (*params
)[(*nparam
)++] = t
;
1656 while (tok_isnt_(t
, brace
? "}" : ","))
1658 if (t
) { /* got a comma/brace */
1662 * Now we've found the closing brace, look further
1666 if (tok_isnt_(t
, ",")) {
1668 "braces do not enclose all of macro parameter");
1669 while (tok_isnt_(t
, ","))
1673 t
= t
->next
; /* eat the comma */
1680 * Determine whether one of the various `if' conditions is true or
1683 * We must free the tline we get passed.
1685 static bool if_condition(Token
* tline
, enum preproc_token ct
)
1687 enum pp_conditional i
= PP_COND(ct
);
1689 Token
*t
, *tt
, **tptr
, *origline
;
1690 struct tokenval tokval
;
1692 enum pp_token_type needtype
;
1699 j
= false; /* have we matched yet? */
1704 if (tline
->type
!= TOK_ID
) {
1706 "`%s' expects context identifiers", pp_directives
[ct
]);
1707 free_tlist(origline
);
1710 if (cstk
&& cstk
->name
&& !nasm_stricmp(tline
->text
, cstk
->name
))
1712 tline
= tline
->next
;
1717 j
= false; /* have we matched yet? */
1720 if (!tline
|| (tline
->type
!= TOK_ID
&&
1721 (tline
->type
!= TOK_PREPROC_ID
||
1722 tline
->text
[1] != '$'))) {
1724 "`%s' expects macro identifiers", pp_directives
[ct
]);
1727 if (smacro_defined(NULL
, tline
->text
, 0, NULL
, true))
1729 tline
= tline
->next
;
1734 tline
= expand_smacro(tline
);
1735 j
= false; /* have we matched yet? */
1738 if (!tline
|| (tline
->type
!= TOK_ID
&&
1739 tline
->type
!= TOK_STRING
&&
1740 (tline
->type
!= TOK_PREPROC_ID
||
1741 tline
->text
[1] != '!'))) {
1743 "`%s' expects environment variable names",
1748 if (tline
->type
== TOK_PREPROC_ID
)
1749 p
+= 2; /* Skip leading %! */
1750 if (*p
== '\'' || *p
== '\"' || *p
== '`')
1751 nasm_unquote_cstr(p
, ct
);
1754 tline
= tline
->next
;
1760 tline
= expand_smacro(tline
);
1762 while (tok_isnt_(tt
, ","))
1766 "`%s' expects two comma-separated arguments",
1771 j
= true; /* assume equality unless proved not */
1772 while ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) && tt
) {
1773 if (tt
->type
== TOK_OTHER
&& !strcmp(tt
->text
, ",")) {
1774 error(ERR_NONFATAL
, "`%s': more than one comma on line",
1778 if (t
->type
== TOK_WHITESPACE
) {
1782 if (tt
->type
== TOK_WHITESPACE
) {
1786 if (tt
->type
!= t
->type
) {
1787 j
= false; /* found mismatching tokens */
1790 /* When comparing strings, need to unquote them first */
1791 if (t
->type
== TOK_STRING
) {
1792 size_t l1
= nasm_unquote(t
->text
, NULL
);
1793 size_t l2
= nasm_unquote(tt
->text
, NULL
);
1799 if (mmemcmp(t
->text
, tt
->text
, l1
, i
== PPC_IFIDN
)) {
1803 } else if (mstrcmp(tt
->text
, t
->text
, i
== PPC_IFIDN
) != 0) {
1804 j
= false; /* found mismatching tokens */
1811 if ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) || tt
)
1812 j
= false; /* trailing gunk on one end or other */
1818 MMacro searching
, *mmac
;
1821 tline
= expand_id(tline
);
1822 if (!tok_type_(tline
, TOK_ID
)) {
1824 "`%s' expects a macro name", pp_directives
[ct
]);
1827 searching
.name
= nasm_strdup(tline
->text
);
1828 searching
.casesense
= true;
1829 searching
.plus
= false;
1830 searching
.nolist
= false;
1831 searching
.in_progress
= 0;
1832 searching
.max_depth
= 0;
1833 searching
.rep_nest
= NULL
;
1834 searching
.nparam_min
= 0;
1835 searching
.nparam_max
= INT_MAX
;
1836 tline
= expand_smacro(tline
->next
);
1839 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
1841 "`%s' expects a parameter count or nothing",
1844 searching
.nparam_min
= searching
.nparam_max
=
1845 readnum(tline
->text
, &j
);
1848 "unable to parse parameter count `%s'",
1851 if (tline
&& tok_is_(tline
->next
, "-")) {
1852 tline
= tline
->next
->next
;
1853 if (tok_is_(tline
, "*"))
1854 searching
.nparam_max
= INT_MAX
;
1855 else if (!tok_type_(tline
, TOK_NUMBER
))
1857 "`%s' expects a parameter count after `-'",
1860 searching
.nparam_max
= readnum(tline
->text
, &j
);
1863 "unable to parse parameter count `%s'",
1865 if (searching
.nparam_min
> searching
.nparam_max
)
1867 "minimum parameter count exceeds maximum");
1870 if (tline
&& tok_is_(tline
->next
, "+")) {
1871 tline
= tline
->next
;
1872 searching
.plus
= true;
1874 mmac
= (MMacro
*) hash_findix(&mmacros
, searching
.name
);
1876 if (!strcmp(mmac
->name
, searching
.name
) &&
1877 (mmac
->nparam_min
<= searching
.nparam_max
1879 && (searching
.nparam_min
<= mmac
->nparam_max
1886 if (tline
&& tline
->next
)
1887 error(ERR_WARNING
|ERR_PASS1
,
1888 "trailing garbage after %%ifmacro ignored");
1889 nasm_free(searching
.name
);
1898 needtype
= TOK_NUMBER
;
1901 needtype
= TOK_STRING
;
1905 t
= tline
= expand_smacro(tline
);
1907 while (tok_type_(t
, TOK_WHITESPACE
) ||
1908 (needtype
== TOK_NUMBER
&&
1909 tok_type_(t
, TOK_OTHER
) &&
1910 (t
->text
[0] == '-' || t
->text
[0] == '+') &&
1914 j
= tok_type_(t
, needtype
);
1918 t
= tline
= expand_smacro(tline
);
1919 while (tok_type_(t
, TOK_WHITESPACE
))
1924 t
= t
->next
; /* Skip the actual token */
1925 while (tok_type_(t
, TOK_WHITESPACE
))
1927 j
= !t
; /* Should be nothing left */
1932 t
= tline
= expand_smacro(tline
);
1933 while (tok_type_(t
, TOK_WHITESPACE
))
1936 j
= !t
; /* Should be empty */
1940 t
= tline
= expand_smacro(tline
);
1942 tokval
.t_type
= TOKEN_INVALID
;
1943 evalresult
= evaluate(ppscan
, tptr
, &tokval
,
1944 NULL
, pass
| CRITICAL
, error
, NULL
);
1948 error(ERR_WARNING
|ERR_PASS1
,
1949 "trailing garbage after expression ignored");
1950 if (!is_simple(evalresult
)) {
1952 "non-constant value given to `%s'", pp_directives
[ct
]);
1955 j
= reloc_value(evalresult
) != 0;
1960 "preprocessor directive `%s' not yet implemented",
1965 free_tlist(origline
);
1966 return j
^ PP_NEGATIVE(ct
);
1969 free_tlist(origline
);
1974 * Common code for defining an smacro
1976 static bool define_smacro(Context
*ctx
, const char *mname
, bool casesense
,
1977 int nparam
, Token
*expansion
)
1979 SMacro
*smac
, **smhead
;
1980 struct hash_table
*smtbl
;
1982 if (smacro_defined(ctx
, mname
, nparam
, &smac
, casesense
)) {
1984 error(ERR_WARNING
|ERR_PASS1
,
1985 "single-line macro `%s' defined both with and"
1986 " without parameters", mname
);
1988 * Some instances of the old code considered this a failure,
1989 * some others didn't. What is the right thing to do here?
1991 free_tlist(expansion
);
1992 return false; /* Failure */
1995 * We're redefining, so we have to take over an
1996 * existing SMacro structure. This means freeing
1997 * what was already in it.
1999 nasm_free(smac
->name
);
2000 free_tlist(smac
->expansion
);
2003 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
2004 smhead
= (SMacro
**) hash_findi_add(smtbl
, mname
);
2005 smac
= nasm_malloc(sizeof(SMacro
));
2006 smac
->next
= *smhead
;
2009 smac
->name
= nasm_strdup(mname
);
2010 smac
->casesense
= casesense
;
2011 smac
->nparam
= nparam
;
2012 smac
->expansion
= expansion
;
2013 smac
->in_progress
= false;
2014 return true; /* Success */
2018 * Undefine an smacro
2020 static void undef_smacro(Context
*ctx
, const char *mname
)
2022 SMacro
**smhead
, *s
, **sp
;
2023 struct hash_table
*smtbl
;
2025 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
2026 smhead
= (SMacro
**)hash_findi(smtbl
, mname
, NULL
);
2030 * We now have a macro name... go hunt for it.
2033 while ((s
= *sp
) != NULL
) {
2034 if (!mstrcmp(s
->name
, mname
, s
->casesense
)) {
2037 free_tlist(s
->expansion
);
2047 * Parse a mmacro specification.
2049 static bool parse_mmacro_spec(Token
*tline
, MMacro
*def
, const char *directive
)
2053 tline
= tline
->next
;
2055 tline
= expand_id(tline
);
2056 if (!tok_type_(tline
, TOK_ID
)) {
2057 error(ERR_NONFATAL
, "`%s' expects a macro name", directive
);
2062 def
->name
= nasm_strdup(tline
->text
);
2064 def
->nolist
= false;
2065 def
->in_progress
= 0;
2066 def
->rep_nest
= NULL
;
2067 def
->nparam_min
= 0;
2068 def
->nparam_max
= 0;
2070 tline
= expand_smacro(tline
->next
);
2072 if (!tok_type_(tline
, TOK_NUMBER
)) {
2073 error(ERR_NONFATAL
, "`%s' expects a parameter count", directive
);
2075 def
->nparam_min
= def
->nparam_max
=
2076 readnum(tline
->text
, &err
);
2079 "unable to parse parameter count `%s'", tline
->text
);
2081 if (tline
&& tok_is_(tline
->next
, "-")) {
2082 tline
= tline
->next
->next
;
2083 if (tok_is_(tline
, "*")) {
2084 def
->nparam_max
= INT_MAX
;
2085 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
2087 "`%s' expects a parameter count after `-'", directive
);
2089 def
->nparam_max
= readnum(tline
->text
, &err
);
2091 error(ERR_NONFATAL
, "unable to parse parameter count `%s'",
2094 if (def
->nparam_min
> def
->nparam_max
) {
2095 error(ERR_NONFATAL
, "minimum parameter count exceeds maximum");
2099 if (tline
&& tok_is_(tline
->next
, "+")) {
2100 tline
= tline
->next
;
2103 if (tline
&& tok_type_(tline
->next
, TOK_ID
) &&
2104 !nasm_stricmp(tline
->next
->text
, ".nolist")) {
2105 tline
= tline
->next
;
2110 * Handle default parameters.
2112 if (tline
&& tline
->next
) {
2113 def
->dlist
= tline
->next
;
2115 count_mmac_params(def
->dlist
, &def
->ndefs
, &def
->defaults
);
2118 def
->defaults
= NULL
;
2120 def
->expansion
= NULL
;
2122 if (def
->defaults
&& def
->ndefs
> def
->nparam_max
- def
->nparam_min
&&
2124 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MDP
,
2125 "too many default macro parameters");
2132 * Decode a size directive
2134 static int parse_size(const char *str
) {
2135 static const char *size_names
[] =
2136 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2137 static const int sizes
[] =
2138 { 0, 1, 4, 16, 8, 10, 2, 32 };
2140 return sizes
[bsii(str
, size_names
, ARRAY_SIZE(size_names
))+1];
2144 * find and process preprocessor directive in passed line
2145 * Find out if a line contains a preprocessor directive, and deal
2148 * If a directive _is_ found, it is the responsibility of this routine
2149 * (and not the caller) to free_tlist() the line.
2151 * @param tline a pointer to the current tokeninzed line linked list
2152 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2155 static int do_directive(Token
* tline
)
2157 enum preproc_token i
;
2170 MMacro
*mmac
, **mmhead
;
2171 Token
*t
, *tt
, *param_start
, *macro_start
, *last
, **tptr
, *origline
;
2173 struct tokenval tokval
;
2175 MMacro
*tmp_defining
; /* Used when manipulating rep_nest */
2183 if (!tline
|| !tok_type_(tline
, TOK_PREPROC_ID
) ||
2184 (tline
->text
[1] == '%' || tline
->text
[1] == '$'
2185 || tline
->text
[1] == '!'))
2186 return NO_DIRECTIVE_FOUND
;
2188 i
= pp_token_hash(tline
->text
);
2191 * FIXME: We zap execution of PP_RMACRO, PP_IRMACRO, PP_EXITMACRO
2192 * since they are known to be buggy at moment, we need to fix them
2193 * in future release (2.09-2.10)
2195 if (i
== PP_RMACRO
|| i
== PP_RMACRO
|| i
== PP_EXITMACRO
) {
2196 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2198 return NO_DIRECTIVE_FOUND
;
2202 * If we're in a non-emitting branch of a condition construct,
2203 * or walking to the end of an already terminated %rep block,
2204 * we should ignore all directives except for condition
2207 if (((istk
->conds
&& !emitting(istk
->conds
->state
)) ||
2208 (istk
->mstk
&& !istk
->mstk
->in_progress
)) && !is_condition(i
)) {
2209 return NO_DIRECTIVE_FOUND
;
2213 * If we're defining a macro or reading a %rep block, we should
2214 * ignore all directives except for %macro/%imacro (which nest),
2215 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2216 * If we're in a %rep block, another %rep nests, so should be let through.
2218 if (defining
&& i
!= PP_MACRO
&& i
!= PP_IMACRO
&&
2219 i
!= PP_RMACRO
&& i
!= PP_IRMACRO
&&
2220 i
!= PP_ENDMACRO
&& i
!= PP_ENDM
&&
2221 (defining
->name
|| (i
!= PP_ENDREP
&& i
!= PP_REP
))) {
2222 return NO_DIRECTIVE_FOUND
;
2226 if (i
== PP_MACRO
|| i
== PP_IMACRO
||
2227 i
== PP_RMACRO
|| i
== PP_IRMACRO
) {
2229 return NO_DIRECTIVE_FOUND
;
2230 } else if (nested_mac_count
> 0) {
2231 if (i
== PP_ENDMACRO
) {
2233 return NO_DIRECTIVE_FOUND
;
2236 if (!defining
->name
) {
2239 return NO_DIRECTIVE_FOUND
;
2240 } else if (nested_rep_count
> 0) {
2241 if (i
== PP_ENDREP
) {
2243 return NO_DIRECTIVE_FOUND
;
2251 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2253 return NO_DIRECTIVE_FOUND
; /* didn't get it */
2256 /* Directive to tell NASM what the default stack size is. The
2257 * default is for a 16-bit stack, and this can be overriden with
2260 tline
= tline
->next
;
2261 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2262 tline
= tline
->next
;
2263 if (!tline
|| tline
->type
!= TOK_ID
) {
2264 error(ERR_NONFATAL
, "`%%stacksize' missing size parameter");
2265 free_tlist(origline
);
2266 return DIRECTIVE_FOUND
;
2268 if (nasm_stricmp(tline
->text
, "flat") == 0) {
2269 /* All subsequent ARG directives are for a 32-bit stack */
2271 StackPointer
= "ebp";
2274 } else if (nasm_stricmp(tline
->text
, "flat64") == 0) {
2275 /* All subsequent ARG directives are for a 64-bit stack */
2277 StackPointer
= "rbp";
2280 } else if (nasm_stricmp(tline
->text
, "large") == 0) {
2281 /* All subsequent ARG directives are for a 16-bit stack,
2282 * far function call.
2285 StackPointer
= "bp";
2288 } else if (nasm_stricmp(tline
->text
, "small") == 0) {
2289 /* All subsequent ARG directives are for a 16-bit stack,
2290 * far function call. We don't support near functions.
2293 StackPointer
= "bp";
2297 error(ERR_NONFATAL
, "`%%stacksize' invalid size type");
2298 free_tlist(origline
);
2299 return DIRECTIVE_FOUND
;
2301 free_tlist(origline
);
2302 return DIRECTIVE_FOUND
;
2305 /* TASM like ARG directive to define arguments to functions, in
2306 * the following form:
2308 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2312 char *arg
, directive
[256];
2313 int size
= StackSize
;
2315 /* Find the argument name */
2316 tline
= tline
->next
;
2317 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2318 tline
= tline
->next
;
2319 if (!tline
|| tline
->type
!= TOK_ID
) {
2320 error(ERR_NONFATAL
, "`%%arg' missing argument parameter");
2321 free_tlist(origline
);
2322 return DIRECTIVE_FOUND
;
2326 /* Find the argument size type */
2327 tline
= tline
->next
;
2328 if (!tline
|| tline
->type
!= TOK_OTHER
2329 || tline
->text
[0] != ':') {
2331 "Syntax error processing `%%arg' directive");
2332 free_tlist(origline
);
2333 return DIRECTIVE_FOUND
;
2335 tline
= tline
->next
;
2336 if (!tline
|| tline
->type
!= TOK_ID
) {
2337 error(ERR_NONFATAL
, "`%%arg' missing size type parameter");
2338 free_tlist(origline
);
2339 return DIRECTIVE_FOUND
;
2342 /* Allow macro expansion of type parameter */
2343 tt
= tokenize(tline
->text
);
2344 tt
= expand_smacro(tt
);
2345 size
= parse_size(tt
->text
);
2348 "Invalid size type for `%%arg' missing directive");
2350 free_tlist(origline
);
2351 return DIRECTIVE_FOUND
;
2355 /* Round up to even stack slots */
2356 size
= ALIGN(size
, StackSize
);
2358 /* Now define the macro for the argument */
2359 snprintf(directive
, sizeof(directive
), "%%define %s (%s+%d)",
2360 arg
, StackPointer
, offset
);
2361 do_directive(tokenize(directive
));
2364 /* Move to the next argument in the list */
2365 tline
= tline
->next
;
2366 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2367 tline
= tline
->next
;
2368 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2370 free_tlist(origline
);
2371 return DIRECTIVE_FOUND
;
2374 /* TASM like LOCAL directive to define local variables for a
2375 * function, in the following form:
2377 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2379 * The '= LocalSize' at the end is ignored by NASM, but is
2380 * required by TASM to define the local parameter size (and used
2381 * by the TASM macro package).
2383 offset
= LocalOffset
;
2385 char *local
, directive
[256];
2386 int size
= StackSize
;
2388 /* Find the argument name */
2389 tline
= tline
->next
;
2390 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2391 tline
= tline
->next
;
2392 if (!tline
|| tline
->type
!= TOK_ID
) {
2394 "`%%local' missing argument parameter");
2395 free_tlist(origline
);
2396 return DIRECTIVE_FOUND
;
2398 local
= tline
->text
;
2400 /* Find the argument size type */
2401 tline
= tline
->next
;
2402 if (!tline
|| tline
->type
!= TOK_OTHER
2403 || tline
->text
[0] != ':') {
2405 "Syntax error processing `%%local' directive");
2406 free_tlist(origline
);
2407 return DIRECTIVE_FOUND
;
2409 tline
= tline
->next
;
2410 if (!tline
|| tline
->type
!= TOK_ID
) {
2412 "`%%local' missing size type parameter");
2413 free_tlist(origline
);
2414 return DIRECTIVE_FOUND
;
2417 /* Allow macro expansion of type parameter */
2418 tt
= tokenize(tline
->text
);
2419 tt
= expand_smacro(tt
);
2420 size
= parse_size(tt
->text
);
2423 "Invalid size type for `%%local' missing directive");
2425 free_tlist(origline
);
2426 return DIRECTIVE_FOUND
;
2430 /* Round up to even stack slots */
2431 size
= ALIGN(size
, StackSize
);
2433 offset
+= size
; /* Negative offset, increment before */
2435 /* Now define the macro for the argument */
2436 snprintf(directive
, sizeof(directive
), "%%define %s (%s-%d)",
2437 local
, StackPointer
, offset
);
2438 do_directive(tokenize(directive
));
2440 /* Now define the assign to setup the enter_c macro correctly */
2441 snprintf(directive
, sizeof(directive
),
2442 "%%assign %%$localsize %%$localsize+%d", size
);
2443 do_directive(tokenize(directive
));
2445 /* Move to the next argument in the list */
2446 tline
= tline
->next
;
2447 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2448 tline
= tline
->next
;
2449 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2450 LocalOffset
= offset
;
2451 free_tlist(origline
);
2452 return DIRECTIVE_FOUND
;
2456 error(ERR_WARNING
|ERR_PASS1
,
2457 "trailing garbage after `%%clear' ignored");
2460 free_tlist(origline
);
2461 return DIRECTIVE_FOUND
;
2464 t
= tline
->next
= expand_smacro(tline
->next
);
2466 if (!t
|| (t
->type
!= TOK_STRING
&&
2467 t
->type
!= TOK_INTERNAL_STRING
)) {
2468 error(ERR_NONFATAL
, "`%%depend' expects a file name");
2469 free_tlist(origline
);
2470 return DIRECTIVE_FOUND
; /* but we did _something_ */
2473 error(ERR_WARNING
|ERR_PASS1
,
2474 "trailing garbage after `%%depend' ignored");
2476 if (t
->type
!= TOK_INTERNAL_STRING
)
2477 nasm_unquote_cstr(p
, i
);
2478 if (dephead
&& !in_list(*dephead
, p
)) {
2479 StrList
*sl
= nasm_malloc(strlen(p
)+1+sizeof sl
->next
);
2483 deptail
= &sl
->next
;
2485 free_tlist(origline
);
2486 return DIRECTIVE_FOUND
;
2489 t
= tline
->next
= expand_smacro(tline
->next
);
2492 if (!t
|| (t
->type
!= TOK_STRING
&&
2493 t
->type
!= TOK_INTERNAL_STRING
)) {
2494 error(ERR_NONFATAL
, "`%%include' expects a file name");
2495 free_tlist(origline
);
2496 return DIRECTIVE_FOUND
; /* but we did _something_ */
2499 error(ERR_WARNING
|ERR_PASS1
,
2500 "trailing garbage after `%%include' ignored");
2502 if (t
->type
!= TOK_INTERNAL_STRING
)
2503 nasm_unquote_cstr(p
, i
);
2504 inc
= nasm_malloc(sizeof(Include
));
2507 inc
->fp
= inc_fopen(p
, dephead
, &deptail
, pass
== 0);
2509 /* -MG given but file not found */
2512 inc
->fname
= src_set_fname(nasm_strdup(p
));
2513 inc
->lineno
= src_set_linnum(0);
2515 inc
->expansion
= NULL
;
2518 list
->uplevel(LIST_INCLUDE
);
2520 free_tlist(origline
);
2521 return DIRECTIVE_FOUND
;
2525 static macros_t
*use_pkg
;
2526 const char *pkg_macro
= NULL
;
2528 tline
= tline
->next
;
2530 tline
= expand_id(tline
);
2532 if (!tline
|| (tline
->type
!= TOK_STRING
&&
2533 tline
->type
!= TOK_INTERNAL_STRING
&&
2534 tline
->type
!= TOK_ID
)) {
2535 error(ERR_NONFATAL
, "`%%use' expects a package name");
2536 free_tlist(origline
);
2537 return DIRECTIVE_FOUND
; /* but we did _something_ */
2540 error(ERR_WARNING
|ERR_PASS1
,
2541 "trailing garbage after `%%use' ignored");
2542 if (tline
->type
== TOK_STRING
)
2543 nasm_unquote_cstr(tline
->text
, i
);
2544 use_pkg
= nasm_stdmac_find_package(tline
->text
);
2546 error(ERR_NONFATAL
, "unknown `%%use' package: %s", tline
->text
);
2548 pkg_macro
= (char *)use_pkg
+ 1; /* The first string will be <%define>__USE_*__ */
2549 if (use_pkg
&& ! smacro_defined(NULL
, pkg_macro
, 0, NULL
, true)) {
2550 /* Not already included, go ahead and include it */
2551 stdmacpos
= use_pkg
;
2553 free_tlist(origline
);
2554 return DIRECTIVE_FOUND
;
2559 tline
= tline
->next
;
2561 tline
= expand_id(tline
);
2563 if (!tok_type_(tline
, TOK_ID
)) {
2564 error(ERR_NONFATAL
, "`%s' expects a context identifier",
2566 free_tlist(origline
);
2567 return DIRECTIVE_FOUND
; /* but we did _something_ */
2570 error(ERR_WARNING
|ERR_PASS1
,
2571 "trailing garbage after `%s' ignored",
2573 p
= nasm_strdup(tline
->text
);
2575 p
= NULL
; /* Anonymous */
2579 ctx
= nasm_malloc(sizeof(Context
));
2581 hash_init(&ctx
->localmac
, HASH_SMALL
);
2583 ctx
->number
= unique
++;
2588 error(ERR_NONFATAL
, "`%s': context stack is empty",
2590 } else if (i
== PP_POP
) {
2591 if (p
&& (!cstk
->name
|| nasm_stricmp(p
, cstk
->name
)))
2592 error(ERR_NONFATAL
, "`%%pop' in wrong context: %s, "
2594 cstk
->name
? cstk
->name
: "anonymous", p
);
2599 nasm_free(cstk
->name
);
2605 free_tlist(origline
);
2606 return DIRECTIVE_FOUND
;
2608 severity
= ERR_FATAL
;
2611 severity
= ERR_NONFATAL
;
2614 severity
= ERR_WARNING
|ERR_WARN_USER
;
2619 /* Only error out if this is the final pass */
2620 if (pass
!= 2 && i
!= PP_FATAL
)
2621 return DIRECTIVE_FOUND
;
2623 tline
->next
= expand_smacro(tline
->next
);
2624 tline
= tline
->next
;
2626 t
= tline
? tline
->next
: NULL
;
2628 if (tok_type_(tline
, TOK_STRING
) && !t
) {
2629 /* The line contains only a quoted string */
2631 nasm_unquote(p
, NULL
); /* Ignore NUL character truncation */
2632 error(severity
, "%s", p
);
2634 /* Not a quoted string, or more than a quoted string */
2635 p
= detoken(tline
, false);
2636 error(severity
, "%s", p
);
2639 free_tlist(origline
);
2640 return DIRECTIVE_FOUND
;
2644 if (istk
->conds
&& !emitting(istk
->conds
->state
))
2647 j
= if_condition(tline
->next
, i
);
2648 tline
->next
= NULL
; /* it got freed */
2649 j
= j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2651 cond
= nasm_malloc(sizeof(Cond
));
2652 cond
->next
= istk
->conds
;
2656 istk
->mstk
->condcnt
++;
2657 free_tlist(origline
);
2658 return DIRECTIVE_FOUND
;
2662 error(ERR_FATAL
, "`%s': no matching `%%if'", pp_directives
[i
]);
2663 switch(istk
->conds
->state
) {
2665 istk
->conds
->state
= COND_DONE
;
2672 case COND_ELSE_TRUE
:
2673 case COND_ELSE_FALSE
:
2674 error_precond(ERR_WARNING
|ERR_PASS1
,
2675 "`%%elif' after `%%else' ignored");
2676 istk
->conds
->state
= COND_NEVER
;
2681 * IMPORTANT: In the case of %if, we will already have
2682 * called expand_mmac_params(); however, if we're
2683 * processing an %elif we must have been in a
2684 * non-emitting mode, which would have inhibited
2685 * the normal invocation of expand_mmac_params().
2686 * Therefore, we have to do it explicitly here.
2688 j
= if_condition(expand_mmac_params(tline
->next
), i
);
2689 tline
->next
= NULL
; /* it got freed */
2690 istk
->conds
->state
=
2691 j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2694 free_tlist(origline
);
2695 return DIRECTIVE_FOUND
;
2699 error_precond(ERR_WARNING
|ERR_PASS1
,
2700 "trailing garbage after `%%else' ignored");
2702 error(ERR_FATAL
, "`%%else': no matching `%%if'");
2703 switch(istk
->conds
->state
) {
2706 istk
->conds
->state
= COND_ELSE_FALSE
;
2713 istk
->conds
->state
= COND_ELSE_TRUE
;
2716 case COND_ELSE_TRUE
:
2717 case COND_ELSE_FALSE
:
2718 error_precond(ERR_WARNING
|ERR_PASS1
,
2719 "`%%else' after `%%else' ignored.");
2720 istk
->conds
->state
= COND_NEVER
;
2723 free_tlist(origline
);
2724 return DIRECTIVE_FOUND
;
2728 error_precond(ERR_WARNING
|ERR_PASS1
,
2729 "trailing garbage after `%%endif' ignored");
2731 error(ERR_FATAL
, "`%%endif': no matching `%%if'");
2733 istk
->conds
= cond
->next
;
2736 istk
->mstk
->condcnt
--;
2737 free_tlist(origline
);
2738 return DIRECTIVE_FOUND
;
2745 error(ERR_FATAL
, "`%s': already defining a macro",
2747 return DIRECTIVE_FOUND
;
2749 defining
= nasm_malloc(sizeof(MMacro
));
2750 defining
->max_depth
=
2751 (i
== PP_RMACRO
) || (i
== PP_IRMACRO
) ? DEADMAN_LIMIT
: 0;
2752 defining
->casesense
= (i
== PP_MACRO
) || (i
== PP_RMACRO
);
2753 if (!parse_mmacro_spec(tline
, defining
, pp_directives
[i
])) {
2754 nasm_free(defining
);
2756 return DIRECTIVE_FOUND
;
2759 mmac
= (MMacro
*) hash_findix(&mmacros
, defining
->name
);
2761 if (!strcmp(mmac
->name
, defining
->name
) &&
2762 (mmac
->nparam_min
<= defining
->nparam_max
2764 && (defining
->nparam_min
<= mmac
->nparam_max
2766 error(ERR_WARNING
|ERR_PASS1
,
2767 "redefining multi-line macro `%s'", defining
->name
);
2768 return DIRECTIVE_FOUND
;
2772 free_tlist(origline
);
2773 return DIRECTIVE_FOUND
;
2777 if (! (defining
&& defining
->name
)) {
2778 error(ERR_NONFATAL
, "`%s': not defining a macro", tline
->text
);
2779 return DIRECTIVE_FOUND
;
2781 mmhead
= (MMacro
**) hash_findi_add(&mmacros
, defining
->name
);
2782 defining
->next
= *mmhead
;
2785 free_tlist(origline
);
2786 return DIRECTIVE_FOUND
;
2790 * We must search along istk->expansion until we hit a
2791 * macro-end marker for a macro with a name. Then we
2792 * bypass all lines between exitmacro and endmacro.
2794 list_for_each(l
, istk
->expansion
)
2795 if (l
->finishes
&& l
->finishes
->name
)
2800 * Remove all conditional entries relative to this
2801 * macro invocation. (safe to do in this context)
2803 for ( ; l
->finishes
->condcnt
> 0; l
->finishes
->condcnt
--) {
2805 istk
->conds
= cond
->next
;
2808 istk
->expansion
= l
;
2810 error(ERR_NONFATAL
, "`%%exitmacro' not within `%%macro' block");
2812 free_tlist(origline
);
2813 return DIRECTIVE_FOUND
;
2821 spec
.casesense
= (i
== PP_UNMACRO
);
2822 if (!parse_mmacro_spec(tline
, &spec
, pp_directives
[i
])) {
2823 return DIRECTIVE_FOUND
;
2825 mmac_p
= (MMacro
**) hash_findi(&mmacros
, spec
.name
, NULL
);
2826 while (mmac_p
&& *mmac_p
) {
2828 if (mmac
->casesense
== spec
.casesense
&&
2829 !mstrcmp(mmac
->name
, spec
.name
, spec
.casesense
) &&
2830 mmac
->nparam_min
== spec
.nparam_min
&&
2831 mmac
->nparam_max
== spec
.nparam_max
&&
2832 mmac
->plus
== spec
.plus
) {
2833 *mmac_p
= mmac
->next
;
2836 mmac_p
= &mmac
->next
;
2839 free_tlist(origline
);
2840 free_tlist(spec
.dlist
);
2841 return DIRECTIVE_FOUND
;
2845 if (tline
->next
&& tline
->next
->type
== TOK_WHITESPACE
)
2846 tline
= tline
->next
;
2848 free_tlist(origline
);
2849 error(ERR_NONFATAL
, "`%%rotate' missing rotate count");
2850 return DIRECTIVE_FOUND
;
2852 t
= expand_smacro(tline
->next
);
2854 free_tlist(origline
);
2857 tokval
.t_type
= TOKEN_INVALID
;
2859 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2862 return DIRECTIVE_FOUND
;
2864 error(ERR_WARNING
|ERR_PASS1
,
2865 "trailing garbage after expression ignored");
2866 if (!is_simple(evalresult
)) {
2867 error(ERR_NONFATAL
, "non-constant value given to `%%rotate'");
2868 return DIRECTIVE_FOUND
;
2871 while (mmac
&& !mmac
->name
) /* avoid mistaking %reps for macros */
2872 mmac
= mmac
->next_active
;
2874 error(ERR_NONFATAL
, "`%%rotate' invoked outside a macro call");
2875 } else if (mmac
->nparam
== 0) {
2877 "`%%rotate' invoked within macro without parameters");
2879 int rotate
= mmac
->rotate
+ reloc_value(evalresult
);
2881 rotate
%= (int)mmac
->nparam
;
2883 rotate
+= mmac
->nparam
;
2885 mmac
->rotate
= rotate
;
2887 return DIRECTIVE_FOUND
;
2892 tline
= tline
->next
;
2893 } while (tok_type_(tline
, TOK_WHITESPACE
));
2895 if (tok_type_(tline
, TOK_ID
) &&
2896 nasm_stricmp(tline
->text
, ".nolist") == 0) {
2899 tline
= tline
->next
;
2900 } while (tok_type_(tline
, TOK_WHITESPACE
));
2904 t
= expand_smacro(tline
);
2906 tokval
.t_type
= TOKEN_INVALID
;
2908 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2910 free_tlist(origline
);
2911 return DIRECTIVE_FOUND
;
2914 error(ERR_WARNING
|ERR_PASS1
,
2915 "trailing garbage after expression ignored");
2916 if (!is_simple(evalresult
)) {
2917 error(ERR_NONFATAL
, "non-constant value given to `%%rep'");
2918 return DIRECTIVE_FOUND
;
2920 count
= reloc_value(evalresult
);
2921 if (count
>= REP_LIMIT
) {
2922 error(ERR_NONFATAL
, "`%%rep' value exceeds limit");
2927 error(ERR_NONFATAL
, "`%%rep' expects a repeat count");
2930 free_tlist(origline
);
2932 tmp_defining
= defining
;
2933 defining
= nasm_malloc(sizeof(MMacro
));
2934 defining
->prev
= NULL
;
2935 defining
->name
= NULL
; /* flags this macro as a %rep block */
2936 defining
->casesense
= false;
2937 defining
->plus
= false;
2938 defining
->nolist
= nolist
;
2939 defining
->in_progress
= count
;
2940 defining
->max_depth
= 0;
2941 defining
->nparam_min
= defining
->nparam_max
= 0;
2942 defining
->defaults
= NULL
;
2943 defining
->dlist
= NULL
;
2944 defining
->expansion
= NULL
;
2945 defining
->next_active
= istk
->mstk
;
2946 defining
->rep_nest
= tmp_defining
;
2947 return DIRECTIVE_FOUND
;
2950 if (!defining
|| defining
->name
) {
2951 error(ERR_NONFATAL
, "`%%endrep': no matching `%%rep'");
2952 return DIRECTIVE_FOUND
;
2956 * Now we have a "macro" defined - although it has no name
2957 * and we won't be entering it in the hash tables - we must
2958 * push a macro-end marker for it on to istk->expansion.
2959 * After that, it will take care of propagating itself (a
2960 * macro-end marker line for a macro which is really a %rep
2961 * block will cause the macro to be re-expanded, complete
2962 * with another macro-end marker to ensure the process
2963 * continues) until the whole expansion is forcibly removed
2964 * from istk->expansion by a %exitrep.
2966 l
= nasm_malloc(sizeof(Line
));
2967 l
->next
= istk
->expansion
;
2968 l
->finishes
= defining
;
2970 istk
->expansion
= l
;
2972 istk
->mstk
= defining
;
2974 list
->uplevel(defining
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
2975 tmp_defining
= defining
;
2976 defining
= defining
->rep_nest
;
2977 free_tlist(origline
);
2978 return DIRECTIVE_FOUND
;
2982 * We must search along istk->expansion until we hit a
2983 * macro-end marker for a macro with no name. Then we set
2984 * its `in_progress' flag to 0.
2986 list_for_each(l
, istk
->expansion
)
2987 if (l
->finishes
&& !l
->finishes
->name
)
2991 l
->finishes
->in_progress
= 1;
2993 error(ERR_NONFATAL
, "`%%exitrep' not within `%%rep' block");
2994 free_tlist(origline
);
2995 return DIRECTIVE_FOUND
;
3001 casesense
= (i
== PP_DEFINE
|| i
== PP_XDEFINE
);
3003 tline
= tline
->next
;
3005 tline
= expand_id(tline
);
3006 if (!tline
|| (tline
->type
!= TOK_ID
&&
3007 (tline
->type
!= TOK_PREPROC_ID
||
3008 tline
->text
[1] != '$'))) {
3009 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3011 free_tlist(origline
);
3012 return DIRECTIVE_FOUND
;
3015 ctx
= get_ctx(tline
->text
, &mname
, false);
3017 param_start
= tline
= tline
->next
;
3020 /* Expand the macro definition now for %xdefine and %ixdefine */
3021 if ((i
== PP_XDEFINE
) || (i
== PP_IXDEFINE
))
3022 tline
= expand_smacro(tline
);
3024 if (tok_is_(tline
, "(")) {
3026 * This macro has parameters.
3029 tline
= tline
->next
;
3033 error(ERR_NONFATAL
, "parameter identifier expected");
3034 free_tlist(origline
);
3035 return DIRECTIVE_FOUND
;
3037 if (tline
->type
!= TOK_ID
) {
3039 "`%s': parameter identifier expected",
3041 free_tlist(origline
);
3042 return DIRECTIVE_FOUND
;
3044 tline
->type
= TOK_SMAC_PARAM
+ nparam
++;
3045 tline
= tline
->next
;
3047 if (tok_is_(tline
, ",")) {
3048 tline
= tline
->next
;
3050 if (!tok_is_(tline
, ")")) {
3052 "`)' expected to terminate macro template");
3053 free_tlist(origline
);
3054 return DIRECTIVE_FOUND
;
3060 tline
= tline
->next
;
3062 if (tok_type_(tline
, TOK_WHITESPACE
))
3063 last
= tline
, tline
= tline
->next
;
3068 if (t
->type
== TOK_ID
) {
3069 list_for_each(tt
, param_start
)
3070 if (tt
->type
>= TOK_SMAC_PARAM
&&
3071 !strcmp(tt
->text
, t
->text
))
3075 t
->next
= macro_start
;
3080 * Good. We now have a macro name, a parameter count, and a
3081 * token list (in reverse order) for an expansion. We ought
3082 * to be OK just to create an SMacro, store it, and let
3083 * free_tlist have the rest of the line (which we have
3084 * carefully re-terminated after chopping off the expansion
3087 define_smacro(ctx
, mname
, casesense
, nparam
, macro_start
);
3088 free_tlist(origline
);
3089 return DIRECTIVE_FOUND
;
3092 tline
= tline
->next
;
3094 tline
= expand_id(tline
);
3095 if (!tline
|| (tline
->type
!= TOK_ID
&&
3096 (tline
->type
!= TOK_PREPROC_ID
||
3097 tline
->text
[1] != '$'))) {
3098 error(ERR_NONFATAL
, "`%%undef' expects a macro identifier");
3099 free_tlist(origline
);
3100 return DIRECTIVE_FOUND
;
3103 error(ERR_WARNING
|ERR_PASS1
,
3104 "trailing garbage after macro name ignored");
3107 /* Find the context that symbol belongs to */
3108 ctx
= get_ctx(tline
->text
, &mname
, false);
3109 undef_smacro(ctx
, mname
);
3110 free_tlist(origline
);
3111 return DIRECTIVE_FOUND
;
3115 casesense
= (i
== PP_DEFSTR
);
3117 tline
= tline
->next
;
3119 tline
= expand_id(tline
);
3120 if (!tline
|| (tline
->type
!= TOK_ID
&&
3121 (tline
->type
!= TOK_PREPROC_ID
||
3122 tline
->text
[1] != '$'))) {
3123 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3125 free_tlist(origline
);
3126 return DIRECTIVE_FOUND
;
3129 ctx
= get_ctx(tline
->text
, &mname
, false);
3131 tline
= expand_smacro(tline
->next
);
3134 while (tok_type_(tline
, TOK_WHITESPACE
))
3135 tline
= delete_Token(tline
);
3137 p
= detoken(tline
, false);
3138 macro_start
= nasm_malloc(sizeof(*macro_start
));
3139 macro_start
->next
= NULL
;
3140 macro_start
->text
= nasm_quote(p
, strlen(p
));
3141 macro_start
->type
= TOK_STRING
;
3142 macro_start
->a
.mac
= NULL
;
3146 * We now have a macro name, an implicit parameter count of
3147 * zero, and a string token to use as an expansion. Create
3148 * and store an SMacro.
3150 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3151 free_tlist(origline
);
3152 return DIRECTIVE_FOUND
;
3156 casesense
= (i
== PP_DEFTOK
);
3158 tline
= tline
->next
;
3160 tline
= expand_id(tline
);
3161 if (!tline
|| (tline
->type
!= TOK_ID
&&
3162 (tline
->type
!= TOK_PREPROC_ID
||
3163 tline
->text
[1] != '$'))) {
3165 "`%s' expects a macro identifier as first parameter",
3167 free_tlist(origline
);
3168 return DIRECTIVE_FOUND
;
3170 ctx
= get_ctx(tline
->text
, &mname
, false);
3172 tline
= expand_smacro(tline
->next
);
3176 while (tok_type_(t
, TOK_WHITESPACE
))
3178 /* t should now point to the string */
3179 if (!tok_type_(t
, TOK_STRING
)) {
3181 "`%s` requires string as second parameter",
3184 free_tlist(origline
);
3185 return DIRECTIVE_FOUND
;
3188 nasm_unquote_cstr(t
->text
, i
);
3189 macro_start
= tokenize(t
->text
);
3192 * We now have a macro name, an implicit parameter count of
3193 * zero, and a numeric token to use as an expansion. Create
3194 * and store an SMacro.
3196 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3198 free_tlist(origline
);
3199 return DIRECTIVE_FOUND
;
3204 StrList
*xsl
= NULL
;
3205 StrList
**xst
= &xsl
;
3209 tline
= tline
->next
;
3211 tline
= expand_id(tline
);
3212 if (!tline
|| (tline
->type
!= TOK_ID
&&
3213 (tline
->type
!= TOK_PREPROC_ID
||
3214 tline
->text
[1] != '$'))) {
3216 "`%%pathsearch' expects a macro identifier as first parameter");
3217 free_tlist(origline
);
3218 return DIRECTIVE_FOUND
;
3220 ctx
= get_ctx(tline
->text
, &mname
, false);
3222 tline
= expand_smacro(tline
->next
);
3226 while (tok_type_(t
, TOK_WHITESPACE
))
3229 if (!t
|| (t
->type
!= TOK_STRING
&&
3230 t
->type
!= TOK_INTERNAL_STRING
)) {
3231 error(ERR_NONFATAL
, "`%%pathsearch' expects a file name");
3233 free_tlist(origline
);
3234 return DIRECTIVE_FOUND
; /* but we did _something_ */
3237 error(ERR_WARNING
|ERR_PASS1
,
3238 "trailing garbage after `%%pathsearch' ignored");
3240 if (t
->type
!= TOK_INTERNAL_STRING
)
3241 nasm_unquote(p
, NULL
);
3243 fp
= inc_fopen(p
, &xsl
, &xst
, true);
3246 fclose(fp
); /* Don't actually care about the file */
3248 macro_start
= nasm_malloc(sizeof(*macro_start
));
3249 macro_start
->next
= NULL
;
3250 macro_start
->text
= nasm_quote(p
, strlen(p
));
3251 macro_start
->type
= TOK_STRING
;
3252 macro_start
->a
.mac
= NULL
;
3257 * We now have a macro name, an implicit parameter count of
3258 * zero, and a string token to use as an expansion. Create
3259 * and store an SMacro.
3261 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3263 free_tlist(origline
);
3264 return DIRECTIVE_FOUND
;
3270 tline
= tline
->next
;
3272 tline
= expand_id(tline
);
3273 if (!tline
|| (tline
->type
!= TOK_ID
&&
3274 (tline
->type
!= TOK_PREPROC_ID
||
3275 tline
->text
[1] != '$'))) {
3277 "`%%strlen' expects a macro identifier as first parameter");
3278 free_tlist(origline
);
3279 return DIRECTIVE_FOUND
;
3281 ctx
= get_ctx(tline
->text
, &mname
, false);
3283 tline
= expand_smacro(tline
->next
);
3287 while (tok_type_(t
, TOK_WHITESPACE
))
3289 /* t should now point to the string */
3290 if (!tok_type_(t
, TOK_STRING
)) {
3292 "`%%strlen` requires string as second parameter");
3294 free_tlist(origline
);
3295 return DIRECTIVE_FOUND
;
3298 macro_start
= nasm_malloc(sizeof(*macro_start
));
3299 macro_start
->next
= NULL
;
3300 make_tok_num(macro_start
, nasm_unquote(t
->text
, NULL
));
3301 macro_start
->a
.mac
= NULL
;
3304 * We now have a macro name, an implicit parameter count of
3305 * zero, and a numeric token to use as an expansion. Create
3306 * and store an SMacro.
3308 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3310 free_tlist(origline
);
3311 return DIRECTIVE_FOUND
;
3316 tline
= tline
->next
;
3318 tline
= expand_id(tline
);
3319 if (!tline
|| (tline
->type
!= TOK_ID
&&
3320 (tline
->type
!= TOK_PREPROC_ID
||
3321 tline
->text
[1] != '$'))) {
3323 "`%%strcat' expects a macro identifier as first parameter");
3324 free_tlist(origline
);
3325 return DIRECTIVE_FOUND
;
3327 ctx
= get_ctx(tline
->text
, &mname
, false);
3329 tline
= expand_smacro(tline
->next
);
3333 list_for_each(t
, tline
) {
3335 case TOK_WHITESPACE
:
3338 len
+= t
->a
.len
= nasm_unquote(t
->text
, NULL
);
3341 if (!strcmp(t
->text
, ",")) /* permit comma separators */
3343 /* else fall through */
3346 "non-string passed to `%%strcat' (%d)", t
->type
);
3348 free_tlist(origline
);
3349 return DIRECTIVE_FOUND
;
3353 p
= pp
= nasm_malloc(len
);
3354 list_for_each(t
, tline
) {
3355 if (t
->type
== TOK_STRING
) {
3356 memcpy(p
, t
->text
, t
->a
.len
);
3362 * We now have a macro name, an implicit parameter count of
3363 * zero, and a numeric token to use as an expansion. Create
3364 * and store an SMacro.
3366 macro_start
= new_Token(NULL
, TOK_STRING
, NULL
, 0);
3367 macro_start
->text
= nasm_quote(pp
, len
);
3369 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3371 free_tlist(origline
);
3372 return DIRECTIVE_FOUND
;
3376 int64_t start
, count
;
3381 tline
= tline
->next
;
3383 tline
= expand_id(tline
);
3384 if (!tline
|| (tline
->type
!= TOK_ID
&&
3385 (tline
->type
!= TOK_PREPROC_ID
||
3386 tline
->text
[1] != '$'))) {
3388 "`%%substr' expects a macro identifier as first parameter");
3389 free_tlist(origline
);
3390 return DIRECTIVE_FOUND
;
3392 ctx
= get_ctx(tline
->text
, &mname
, false);
3394 tline
= expand_smacro(tline
->next
);
3397 if (tline
) /* skip expanded id */
3399 while (tok_type_(t
, TOK_WHITESPACE
))
3402 /* t should now point to the string */
3403 if (!tok_type_(t
, TOK_STRING
)) {
3405 "`%%substr` requires string as second parameter");
3407 free_tlist(origline
);
3408 return DIRECTIVE_FOUND
;
3413 tokval
.t_type
= TOKEN_INVALID
;
3414 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3418 free_tlist(origline
);
3419 return DIRECTIVE_FOUND
;
3420 } else if (!is_simple(evalresult
)) {
3421 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3423 free_tlist(origline
);
3424 return DIRECTIVE_FOUND
;
3426 start
= evalresult
->value
- 1;
3428 while (tok_type_(tt
, TOK_WHITESPACE
))
3431 count
= 1; /* Backwards compatibility: one character */
3433 tokval
.t_type
= TOKEN_INVALID
;
3434 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3438 free_tlist(origline
);
3439 return DIRECTIVE_FOUND
;
3440 } else if (!is_simple(evalresult
)) {
3441 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3443 free_tlist(origline
);
3444 return DIRECTIVE_FOUND
;
3446 count
= evalresult
->value
;
3449 len
= nasm_unquote(t
->text
, NULL
);
3451 /* make start and count being in range */
3455 count
= len
+ count
+ 1 - start
;
3456 if (start
+ count
> (int64_t)len
)
3457 count
= len
- start
;
3458 if (!len
|| count
< 0 || start
>=(int64_t)len
)
3459 start
= -1, count
= 0; /* empty string */
3461 macro_start
= nasm_malloc(sizeof(*macro_start
));
3462 macro_start
->next
= NULL
;
3463 macro_start
->text
= nasm_quote((start
< 0) ? "" : t
->text
+ start
, count
);
3464 macro_start
->type
= TOK_STRING
;
3465 macro_start
->a
.mac
= NULL
;
3468 * We now have a macro name, an implicit parameter count of
3469 * zero, and a numeric token to use as an expansion. Create
3470 * and store an SMacro.
3472 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3474 free_tlist(origline
);
3475 return DIRECTIVE_FOUND
;
3480 casesense
= (i
== PP_ASSIGN
);
3482 tline
= tline
->next
;
3484 tline
= expand_id(tline
);
3485 if (!tline
|| (tline
->type
!= TOK_ID
&&
3486 (tline
->type
!= TOK_PREPROC_ID
||
3487 tline
->text
[1] != '$'))) {
3489 "`%%%sassign' expects a macro identifier",
3490 (i
== PP_IASSIGN
? "i" : ""));
3491 free_tlist(origline
);
3492 return DIRECTIVE_FOUND
;
3494 ctx
= get_ctx(tline
->text
, &mname
, false);
3496 tline
= expand_smacro(tline
->next
);
3501 tokval
.t_type
= TOKEN_INVALID
;
3503 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
3506 free_tlist(origline
);
3507 return DIRECTIVE_FOUND
;
3511 error(ERR_WARNING
|ERR_PASS1
,
3512 "trailing garbage after expression ignored");
3514 if (!is_simple(evalresult
)) {
3516 "non-constant value given to `%%%sassign'",
3517 (i
== PP_IASSIGN
? "i" : ""));
3518 free_tlist(origline
);
3519 return DIRECTIVE_FOUND
;
3522 macro_start
= nasm_malloc(sizeof(*macro_start
));
3523 macro_start
->next
= NULL
;
3524 make_tok_num(macro_start
, reloc_value(evalresult
));
3525 macro_start
->a
.mac
= NULL
;
3528 * We now have a macro name, an implicit parameter count of
3529 * zero, and a numeric token to use as an expansion. Create
3530 * and store an SMacro.
3532 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3533 free_tlist(origline
);
3534 return DIRECTIVE_FOUND
;
3538 * Syntax is `%line nnn[+mmm] [filename]'
3540 tline
= tline
->next
;
3542 if (!tok_type_(tline
, TOK_NUMBER
)) {
3543 error(ERR_NONFATAL
, "`%%line' expects line number");
3544 free_tlist(origline
);
3545 return DIRECTIVE_FOUND
;
3547 k
= readnum(tline
->text
, &err
);
3549 tline
= tline
->next
;
3550 if (tok_is_(tline
, "+")) {
3551 tline
= tline
->next
;
3552 if (!tok_type_(tline
, TOK_NUMBER
)) {
3553 error(ERR_NONFATAL
, "`%%line' expects line increment");
3554 free_tlist(origline
);
3555 return DIRECTIVE_FOUND
;
3557 m
= readnum(tline
->text
, &err
);
3558 tline
= tline
->next
;
3564 nasm_free(src_set_fname(detoken(tline
, false)));
3566 free_tlist(origline
);
3567 return DIRECTIVE_FOUND
;
3571 "preprocessor directive `%s' not yet implemented",
3573 return DIRECTIVE_FOUND
;
3578 * Ensure that a macro parameter contains a condition code and
3579 * nothing else. Return the condition code index if so, or -1
3582 static int find_cc(Token
* t
)
3588 return -1; /* Probably a %+ without a space */
3591 if (t
->type
!= TOK_ID
)
3595 if (tt
&& (tt
->type
!= TOK_OTHER
|| strcmp(tt
->text
, ",")))
3599 j
= ARRAY_SIZE(conditions
);
3602 m
= nasm_stricmp(t
->text
, conditions
[k
]);
3617 static bool paste_tokens(Token
**head
, bool handle_paste_tokens
)
3619 Token
**tail
, *t
, *tt
;
3621 bool did_paste
= false;
3624 /* Now handle token pasting... */
3627 while ((t
= *tail
) && (tt
= t
->next
)) {
3629 case TOK_WHITESPACE
:
3630 if (tt
->type
== TOK_WHITESPACE
) {
3631 /* Zap adjacent whitespace tokens */
3632 t
->next
= delete_Token(tt
);
3634 /* Do not advance paste_head here */
3645 while (tt
&& (tt
->type
== TOK_ID
|| tt
->type
== TOK_PREPROC_ID
||
3646 tt
->type
== TOK_NUMBER
|| tt
->type
== TOK_FLOAT
||
3647 tt
->type
== TOK_OTHER
)) {
3648 len
+= strlen(tt
->text
);
3653 * Now tt points to the first token after
3654 * the potential paste area...
3656 if (tt
!= t
->next
) {
3657 /* We have at least two tokens... */
3658 len
+= strlen(t
->text
);
3659 p
= tmp
= nasm_malloc(len
+1);
3663 p
= strchr(p
, '\0');
3664 t
= delete_Token(t
);
3667 t
= *tail
= tokenize(tmp
);
3674 t
->next
= tt
; /* Attach the remaining token chain */
3682 case TOK_PASTE
: /* %+ */
3683 if (handle_paste_tokens
) {
3684 /* Zap %+ and whitespace tokens to the right */
3685 while (t
&& (t
->type
== TOK_WHITESPACE
||
3686 t
->type
== TOK_PASTE
))
3687 t
= *tail
= delete_Token(t
);
3688 if (!paste_head
|| !t
)
3689 break; /* Nothing to paste with */
3693 while (tok_type_(tt
, TOK_WHITESPACE
))
3694 tt
= t
->next
= delete_Token(tt
);
3697 tmp
= nasm_strcat(t
->text
, tt
->text
);
3699 tt
= delete_Token(tt
);
3700 t
= *tail
= tokenize(tmp
);
3706 t
->next
= tt
; /* Attach the remaining token chain */
3713 /* else fall through */
3716 if (!tok_type_(t
->next
, TOK_WHITESPACE
))
3725 * expands to a list of tokens from %{x:y}
3727 static Token
*expand_mmac_params_range(MMacro
*mac
, Token
*tline
, Token
***last
)
3729 Token
*t
= tline
, **tt
, *tm
, *head
;
3733 pos
= strchr(tline
->text
, ':');
3736 lst
= atoi(pos
+ 1);
3737 fst
= atoi(tline
->text
+ 1);
3740 * only macros params are accounted so
3741 * if someone passes %0 -- we reject such
3744 if (lst
== 0 || fst
== 0)
3747 /* the values should be sane */
3748 if ((fst
> (int)mac
->nparam
|| fst
< (-(int)mac
->nparam
)) ||
3749 (lst
> (int)mac
->nparam
|| lst
< (-(int)mac
->nparam
)))
3752 fst
= fst
< 0 ? fst
+ (int)mac
->nparam
+ 1: fst
;
3753 lst
= lst
< 0 ? lst
+ (int)mac
->nparam
+ 1: lst
;
3755 /* counted from zero */
3759 * it will be at least one token
3761 tm
= mac
->params
[(fst
+ mac
->rotate
) % mac
->nparam
];
3762 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3763 head
= t
, tt
= &t
->next
;
3765 for (i
= fst
+ 1; i
<= lst
; i
++) {
3766 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3767 *tt
= t
, tt
= &t
->next
;
3768 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3769 tm
= mac
->params
[j
];
3770 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3771 *tt
= t
, tt
= &t
->next
;
3774 for (i
= fst
- 1; i
>= lst
; i
--) {
3775 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3776 *tt
= t
, tt
= &t
->next
;
3777 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3778 tm
= mac
->params
[j
];
3779 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3780 *tt
= t
, tt
= &t
->next
;
3788 error(ERR_NONFATAL
, "`%%{%s}': macro parameters out of range",
3794 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3795 * %-n) and MMacro-local identifiers (%%foo) as well as
3796 * macro indirection (%[...]) and range (%{..:..}).
3798 static Token
*expand_mmac_params(Token
* tline
)
3800 Token
*t
, *tt
, **tail
, *thead
;
3801 bool changed
= false;
3808 if (tline
->type
== TOK_PREPROC_ID
&&
3809 (((tline
->text
[1] == '+' || tline
->text
[1] == '-') && tline
->text
[2]) ||
3810 (tline
->text
[1] >= '0' && tline
->text
[1] <= '9') ||
3811 tline
->text
[1] == '%')) {
3813 int type
= 0, cc
; /* type = 0 to placate optimisers */
3820 tline
= tline
->next
;
3823 while (mac
&& !mac
->name
) /* avoid mistaking %reps for macros */
3824 mac
= mac
->next_active
;
3826 error(ERR_NONFATAL
, "`%s': not in a macro call", t
->text
);
3828 pos
= strchr(t
->text
, ':');
3830 switch (t
->text
[1]) {
3832 * We have to make a substitution of one of the
3833 * forms %1, %-1, %+1, %%foo, %0.
3837 snprintf(tmpbuf
, sizeof(tmpbuf
), "%d", mac
->nparam
);
3838 text
= nasm_strdup(tmpbuf
);
3842 snprintf(tmpbuf
, sizeof(tmpbuf
), "..@%"PRIu64
".",
3844 text
= nasm_strcat(tmpbuf
, t
->text
+ 2);
3847 n
= atoi(t
->text
+ 2) - 1;
3848 if (n
>= mac
->nparam
)
3851 if (mac
->nparam
> 1)
3852 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3853 tt
= mac
->params
[n
];
3858 "macro parameter %d is not a condition code",
3863 if (inverse_ccs
[cc
] == -1) {
3865 "condition code `%s' is not invertible",
3869 text
= nasm_strdup(conditions
[inverse_ccs
[cc
]]);
3873 n
= atoi(t
->text
+ 2) - 1;
3874 if (n
>= mac
->nparam
)
3877 if (mac
->nparam
> 1)
3878 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3879 tt
= mac
->params
[n
];
3884 "macro parameter %d is not a condition code",
3889 text
= nasm_strdup(conditions
[cc
]);
3893 n
= atoi(t
->text
+ 1) - 1;
3894 if (n
>= mac
->nparam
)
3897 if (mac
->nparam
> 1)
3898 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3899 tt
= mac
->params
[n
];
3902 for (i
= 0; i
< mac
->paramlen
[n
]; i
++) {
3903 *tail
= new_Token(NULL
, tt
->type
, tt
->text
, 0);
3904 tail
= &(*tail
)->next
;
3908 text
= NULL
; /* we've done it here */
3913 * seems we have a parameters range here
3915 Token
*head
, **last
;
3916 head
= expand_mmac_params_range(mac
, t
, &last
);
3937 } else if (tline
->type
== TOK_INDIRECT
) {
3939 tline
= tline
->next
;
3940 tt
= tokenize(t
->text
);
3941 tt
= expand_mmac_params(tt
);
3942 tt
= expand_smacro(tt
);
3945 tt
->a
.mac
= NULL
; /* Necessary? */
3953 tline
= tline
->next
;
3961 paste_tokens(&thead
, false);
3967 * Expand all single-line macro calls made in the given line.
3968 * Return the expanded version of the line. The original is deemed
3969 * to be destroyed in the process. (In reality we'll just move
3970 * Tokens from input to output a lot of the time, rather than
3971 * actually bothering to destroy and replicate.)
3974 static Token
*expand_smacro(Token
* tline
)
3976 Token
*t
, *tt
, *mstart
, **tail
, *thead
;
3977 SMacro
*head
= NULL
, *m
;
3980 unsigned int nparam
, sparam
;
3982 Token
*org_tline
= tline
;
3985 int deadman
= DEADMAN_LIMIT
;
3989 * Trick: we should avoid changing the start token pointer since it can
3990 * be contained in "next" field of other token. Because of this
3991 * we allocate a copy of first token and work with it; at the end of
3992 * routine we copy it back
3995 tline
= new_Token(org_tline
->next
, org_tline
->type
,
3996 org_tline
->text
, 0);
3997 tline
->a
.mac
= org_tline
->a
.mac
;
3998 nasm_free(org_tline
->text
);
3999 org_tline
->text
= NULL
;
4002 expanded
= true; /* Always expand %+ at least once */
4008 while (tline
) { /* main token loop */
4010 error(ERR_NONFATAL
, "interminable macro recursion");
4014 if ((mname
= tline
->text
)) {
4015 /* if this token is a local macro, look in local context */
4016 if (tline
->type
== TOK_ID
) {
4017 head
= (SMacro
*)hash_findix(&smacros
, mname
);
4018 } else if (tline
->type
== TOK_PREPROC_ID
) {
4019 ctx
= get_ctx(mname
, &mname
, true);
4020 head
= ctx
? (SMacro
*)hash_findix(&ctx
->localmac
, mname
) : NULL
;
4025 * We've hit an identifier. As in is_mmacro below, we first
4026 * check whether the identifier is a single-line macro at
4027 * all, then think about checking for parameters if
4030 list_for_each(m
, head
)
4031 if (!mstrcmp(m
->name
, mname
, m
->casesense
))
4037 if (m
->nparam
== 0) {
4039 * Simple case: the macro is parameterless. Discard the
4040 * one token that the macro call took, and push the
4041 * expansion back on the to-do stack.
4043 if (!m
->expansion
) {
4044 if (!strcmp("__FILE__", m
->name
)) {
4047 src_get(&num
, &file
);
4048 tline
->text
= nasm_quote(file
, strlen(file
));
4049 tline
->type
= TOK_STRING
;
4053 if (!strcmp("__LINE__", m
->name
)) {
4054 nasm_free(tline
->text
);
4055 make_tok_num(tline
, src_get_linnum());
4058 if (!strcmp("__BITS__", m
->name
)) {
4059 nasm_free(tline
->text
);
4060 make_tok_num(tline
, globalbits
);
4063 tline
= delete_Token(tline
);
4068 * Complicated case: at least one macro with this name
4069 * exists and takes parameters. We must find the
4070 * parameters in the call, count them, find the SMacro
4071 * that corresponds to that form of the macro call, and
4072 * substitute for the parameters when we expand. What a
4075 /*tline = tline->next;
4076 skip_white_(tline); */
4079 while (tok_type_(t
, TOK_SMAC_END
)) {
4080 t
->a
.mac
->in_progress
= false;
4082 t
= tline
->next
= delete_Token(t
);
4085 } while (tok_type_(tline
, TOK_WHITESPACE
));
4086 if (!tok_is_(tline
, "(")) {
4088 * This macro wasn't called with parameters: ignore
4089 * the call. (Behaviour borrowed from gnu cpp.)
4098 sparam
= PARAM_DELTA
;
4099 params
= nasm_malloc(sparam
* sizeof(Token
*));
4100 params
[0] = tline
->next
;
4101 paramsize
= nasm_malloc(sparam
* sizeof(int));
4103 while (true) { /* parameter loop */
4105 * For some unusual expansions
4106 * which concatenates function call
4109 while (tok_type_(t
, TOK_SMAC_END
)) {
4110 t
->a
.mac
->in_progress
= false;
4112 t
= tline
->next
= delete_Token(t
);
4118 "macro call expects terminating `)'");
4121 if (tline
->type
== TOK_WHITESPACE
4123 if (paramsize
[nparam
])
4126 params
[nparam
] = tline
->next
;
4127 continue; /* parameter loop */
4129 if (tline
->type
== TOK_OTHER
4130 && tline
->text
[1] == 0) {
4131 char ch
= tline
->text
[0];
4132 if (ch
== ',' && !paren
&& brackets
<= 0) {
4133 if (++nparam
>= sparam
) {
4134 sparam
+= PARAM_DELTA
;
4135 params
= nasm_realloc(params
,
4136 sparam
* sizeof(Token
*));
4137 paramsize
= nasm_realloc(paramsize
,
4138 sparam
* sizeof(int));
4140 params
[nparam
] = tline
->next
;
4141 paramsize
[nparam
] = 0;
4143 continue; /* parameter loop */
4146 (brackets
> 0 || (brackets
== 0 &&
4147 !paramsize
[nparam
])))
4149 if (!(brackets
++)) {
4150 params
[nparam
] = tline
->next
;
4151 continue; /* parameter loop */
4154 if (ch
== '}' && brackets
> 0)
4155 if (--brackets
== 0) {
4157 continue; /* parameter loop */
4159 if (ch
== '(' && !brackets
)
4161 if (ch
== ')' && brackets
<= 0)
4167 error(ERR_NONFATAL
, "braces do not "
4168 "enclose all of macro parameter");
4170 paramsize
[nparam
] += white
+ 1;
4172 } /* parameter loop */
4174 while (m
&& (m
->nparam
!= nparam
||
4175 mstrcmp(m
->name
, mname
,
4179 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4180 "macro `%s' exists, "
4181 "but not taking %d parameters",
4182 mstart
->text
, nparam
);
4185 if (m
&& m
->in_progress
)
4187 if (!m
) { /* in progess or didn't find '(' or wrong nparam */
4189 * Design question: should we handle !tline, which
4190 * indicates missing ')' here, or expand those
4191 * macros anyway, which requires the (t) test a few
4195 nasm_free(paramsize
);
4199 * Expand the macro: we are placed on the last token of the
4200 * call, so that we can easily split the call from the
4201 * following tokens. We also start by pushing an SMAC_END
4202 * token for the cycle removal.
4209 tt
= new_Token(tline
, TOK_SMAC_END
, NULL
, 0);
4211 m
->in_progress
= true;
4213 list_for_each(t
, m
->expansion
) {
4214 if (t
->type
>= TOK_SMAC_PARAM
) {
4215 Token
*pcopy
= tline
, **ptail
= &pcopy
;
4219 ttt
= params
[t
->type
- TOK_SMAC_PARAM
];
4220 i
= paramsize
[t
->type
- TOK_SMAC_PARAM
];
4222 pt
= *ptail
= new_Token(tline
, ttt
->type
,
4228 } else if (t
->type
== TOK_PREPROC_Q
) {
4229 tt
= new_Token(tline
, TOK_ID
, mname
, 0);
4231 } else if (t
->type
== TOK_PREPROC_QQ
) {
4232 tt
= new_Token(tline
, TOK_ID
, m
->name
, 0);
4235 tt
= new_Token(tline
, t
->type
, t
->text
, 0);
4241 * Having done that, get rid of the macro call, and clean
4242 * up the parameters.
4245 nasm_free(paramsize
);
4248 continue; /* main token loop */
4253 if (tline
->type
== TOK_SMAC_END
) {
4254 tline
->a
.mac
->in_progress
= false;
4255 tline
= delete_Token(tline
);
4258 tline
= tline
->next
;
4266 * Now scan the entire line and look for successive TOK_IDs that resulted
4267 * after expansion (they can't be produced by tokenize()). The successive
4268 * TOK_IDs should be concatenated.
4269 * Also we look for %+ tokens and concatenate the tokens before and after
4270 * them (without white spaces in between).
4272 if (expanded
&& paste_tokens(&thead
, true)) {
4274 * If we concatenated something, *and* we had previously expanded
4275 * an actual macro, scan the lines again for macros...
4285 *org_tline
= *thead
;
4286 /* since we just gave text to org_line, don't free it */
4288 delete_Token(thead
);
4290 /* the expression expanded to empty line;
4291 we can't return NULL for some reasons
4292 we just set the line to a single WHITESPACE token. */
4293 memset(org_tline
, 0, sizeof(*org_tline
));
4294 org_tline
->text
= NULL
;
4295 org_tline
->type
= TOK_WHITESPACE
;
4304 * Similar to expand_smacro but used exclusively with macro identifiers
4305 * right before they are fetched in. The reason is that there can be
4306 * identifiers consisting of several subparts. We consider that if there
4307 * are more than one element forming the name, user wants a expansion,
4308 * otherwise it will be left as-is. Example:
4312 * the identifier %$abc will be left as-is so that the handler for %define
4313 * will suck it and define the corresponding value. Other case:
4315 * %define _%$abc cde
4317 * In this case user wants name to be expanded *before* %define starts
4318 * working, so we'll expand %$abc into something (if it has a value;
4319 * otherwise it will be left as-is) then concatenate all successive
4322 static Token
*expand_id(Token
* tline
)
4324 Token
*cur
, *oldnext
= NULL
;
4326 if (!tline
|| !tline
->next
)
4331 (cur
->next
->type
== TOK_ID
||
4332 cur
->next
->type
== TOK_PREPROC_ID
4333 || cur
->next
->type
== TOK_NUMBER
))
4336 /* If identifier consists of just one token, don't expand */
4341 oldnext
= cur
->next
; /* Detach the tail past identifier */
4342 cur
->next
= NULL
; /* so that expand_smacro stops here */
4345 tline
= expand_smacro(tline
);
4348 /* expand_smacro possibly changhed tline; re-scan for EOL */
4350 while (cur
&& cur
->next
)
4353 cur
->next
= oldnext
;
4360 * Determine whether the given line constitutes a multi-line macro
4361 * call, and return the MMacro structure called if so. Doesn't have
4362 * to check for an initial label - that's taken care of in
4363 * expand_mmacro - but must check numbers of parameters. Guaranteed
4364 * to be called with tline->type == TOK_ID, so the putative macro
4365 * name is easy to find.
4367 static MMacro
*is_mmacro(Token
* tline
, Token
*** params_array
)
4373 head
= (MMacro
*) hash_findix(&mmacros
, tline
->text
);
4376 * Efficiency: first we see if any macro exists with the given
4377 * name. If not, we can return NULL immediately. _Then_ we
4378 * count the parameters, and then we look further along the
4379 * list if necessary to find the proper MMacro.
4381 list_for_each(m
, head
)
4382 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4388 * OK, we have a potential macro. Count and demarcate the
4391 count_mmac_params(tline
->next
, &nparam
, ¶ms
);
4394 * So we know how many parameters we've got. Find the MMacro
4395 * structure that handles this number.
4398 if (m
->nparam_min
<= nparam
4399 && (m
->plus
|| nparam
<= m
->nparam_max
)) {
4401 * This one is right. Just check if cycle removal
4402 * prohibits us using it before we actually celebrate...
4404 if (m
->in_progress
> m
->max_depth
) {
4405 if (m
->max_depth
> 0) {
4407 "reached maximum recursion depth of %i",
4414 * It's right, and we can use it. Add its default
4415 * parameters to the end of our list if necessary.
4417 if (m
->defaults
&& nparam
< m
->nparam_min
+ m
->ndefs
) {
4419 nasm_realloc(params
,
4420 ((m
->nparam_min
+ m
->ndefs
+
4421 1) * sizeof(*params
)));
4422 while (nparam
< m
->nparam_min
+ m
->ndefs
) {
4423 params
[nparam
] = m
->defaults
[nparam
- m
->nparam_min
];
4428 * If we've gone over the maximum parameter count (and
4429 * we're in Plus mode), ignore parameters beyond
4432 if (m
->plus
&& nparam
> m
->nparam_max
)
4433 nparam
= m
->nparam_max
;
4435 * Then terminate the parameter list, and leave.
4437 if (!params
) { /* need this special case */
4438 params
= nasm_malloc(sizeof(*params
));
4441 params
[nparam
] = NULL
;
4442 *params_array
= params
;
4446 * This one wasn't right: look for the next one with the
4449 list_for_each(m
, m
->next
)
4450 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4455 * After all that, we didn't find one with the right number of
4456 * parameters. Issue a warning, and fail to expand the macro.
4458 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4459 "macro `%s' exists, but not taking %d parameters",
4460 tline
->text
, nparam
);
4467 * Save MMacro invocation specific fields in
4468 * preparation for a recursive macro expansion
4470 static void push_mmacro(MMacro
*m
)
4472 MMacroInvocation
*i
;
4474 i
= nasm_malloc(sizeof(MMacroInvocation
));
4476 i
->params
= m
->params
;
4477 i
->iline
= m
->iline
;
4478 i
->nparam
= m
->nparam
;
4479 i
->rotate
= m
->rotate
;
4480 i
->paramlen
= m
->paramlen
;
4481 i
->unique
= m
->unique
;
4482 i
->condcnt
= m
->condcnt
;
4488 * Restore MMacro invocation specific fields that were
4489 * saved during a previous recursive macro expansion
4491 static void pop_mmacro(MMacro
*m
)
4493 MMacroInvocation
*i
;
4498 m
->params
= i
->params
;
4499 m
->iline
= i
->iline
;
4500 m
->nparam
= i
->nparam
;
4501 m
->rotate
= i
->rotate
;
4502 m
->paramlen
= i
->paramlen
;
4503 m
->unique
= i
->unique
;
4504 m
->condcnt
= i
->condcnt
;
4511 * Expand the multi-line macro call made by the given line, if
4512 * there is one to be expanded. If there is, push the expansion on
4513 * istk->expansion and return 1. Otherwise return 0.
4515 static int expand_mmacro(Token
* tline
)
4517 Token
*startline
= tline
;
4518 Token
*label
= NULL
;
4519 int dont_prepend
= 0;
4520 Token
**params
, *t
, *mtok
, *tt
;
4523 int i
, nparam
, *paramlen
;
4528 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4529 if (!tok_type_(t
, TOK_ID
) && !tok_type_(t
, TOK_PREPROC_ID
))
4532 m
= is_mmacro(t
, ¶ms
);
4538 * We have an id which isn't a macro call. We'll assume
4539 * it might be a label; we'll also check to see if a
4540 * colon follows it. Then, if there's another id after
4541 * that lot, we'll check it again for macro-hood.
4545 if (tok_type_(t
, TOK_WHITESPACE
))
4546 last
= t
, t
= t
->next
;
4547 if (tok_is_(t
, ":")) {
4549 last
= t
, t
= t
->next
;
4550 if (tok_type_(t
, TOK_WHITESPACE
))
4551 last
= t
, t
= t
->next
;
4553 if (!tok_type_(t
, TOK_ID
) || !(m
= is_mmacro(t
, ¶ms
)))
4561 * Fix up the parameters: this involves stripping leading and
4562 * trailing whitespace, then stripping braces if they are
4565 for (nparam
= 0; params
[nparam
]; nparam
++) ;
4566 paramlen
= nparam
? nasm_malloc(nparam
* sizeof(*paramlen
)) : NULL
;
4568 for (i
= 0; params
[i
]; i
++) {
4570 int comma
= (!m
->plus
|| i
< nparam
- 1);
4574 if (tok_is_(t
, "{"))
4575 t
= t
->next
, brace
= true, comma
= false;
4579 if (comma
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, ","))
4580 break; /* ... because we have hit a comma */
4581 if (comma
&& t
->type
== TOK_WHITESPACE
4582 && tok_is_(t
->next
, ","))
4583 break; /* ... or a space then a comma */
4584 if (brace
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, "}"))
4585 break; /* ... or a brace */
4592 * OK, we have a MMacro structure together with a set of
4593 * parameters. We must now go through the expansion and push
4594 * copies of each Line on to istk->expansion. Substitution of
4595 * parameter tokens and macro-local tokens doesn't get done
4596 * until the single-line macro substitution process; this is
4597 * because delaying them allows us to change the semantics
4598 * later through %rotate.
4600 * First, push an end marker on to istk->expansion, mark this
4601 * macro as in progress, and set up its invocation-specific
4604 ll
= nasm_malloc(sizeof(Line
));
4605 ll
->next
= istk
->expansion
;
4608 istk
->expansion
= ll
;
4611 * Save the previous MMacro expansion in the case of
4614 if (m
->max_depth
&& m
->in_progress
)
4622 m
->paramlen
= paramlen
;
4623 m
->unique
= unique
++;
4627 m
->next_active
= istk
->mstk
;
4630 list_for_each(l
, m
->expansion
) {
4633 ll
= nasm_malloc(sizeof(Line
));
4634 ll
->finishes
= NULL
;
4635 ll
->next
= istk
->expansion
;
4636 istk
->expansion
= ll
;
4639 list_for_each(t
, l
->first
) {
4643 tt
= *tail
= new_Token(NULL
, TOK_ID
, mname
, 0);
4645 case TOK_PREPROC_QQ
:
4646 tt
= *tail
= new_Token(NULL
, TOK_ID
, m
->name
, 0);
4648 case TOK_PREPROC_ID
:
4649 if (t
->text
[1] == '0' && t
->text
[2] == '0') {
4657 tt
= *tail
= new_Token(NULL
, x
->type
, x
->text
, 0);
4666 * If we had a label, push it on as the first line of
4667 * the macro expansion.
4670 if (dont_prepend
< 0)
4671 free_tlist(startline
);
4673 ll
= nasm_malloc(sizeof(Line
));
4674 ll
->finishes
= NULL
;
4675 ll
->next
= istk
->expansion
;
4676 istk
->expansion
= ll
;
4677 ll
->first
= startline
;
4678 if (!dont_prepend
) {
4680 label
= label
->next
;
4681 label
->next
= tt
= new_Token(NULL
, TOK_OTHER
, ":", 0);
4686 list
->uplevel(m
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
4691 /* The function that actually does the error reporting */
4692 static void verror(int severity
, const char *fmt
, va_list arg
)
4696 vsnprintf(buff
, sizeof(buff
), fmt
, arg
);
4698 if (istk
&& istk
->mstk
&& istk
->mstk
->name
)
4699 nasm_error(severity
, "(%s:%d) %s", istk
->mstk
->name
,
4700 istk
->mstk
->lineno
, buff
);
4702 nasm_error(severity
, "%s", buff
);
4706 * Since preprocessor always operate only on the line that didn't
4707 * arrived yet, we should always use ERR_OFFBY1.
4709 static void error(int severity
, const char *fmt
, ...)
4713 /* If we're in a dead branch of IF or something like it, ignore the error */
4714 if (istk
&& istk
->conds
&& !emitting(istk
->conds
->state
))
4718 verror(severity
, fmt
, arg
);
4723 * Because %else etc are evaluated in the state context
4724 * of the previous branch, errors might get lost with error():
4725 * %if 0 ... %else trailing garbage ... %endif
4726 * So %else etc should report errors with this function.
4728 static void error_precond(int severity
, const char *fmt
, ...)
4732 /* Only ignore the error if it's really in a dead branch */
4733 if (istk
&& istk
->conds
&& istk
->conds
->state
== COND_NEVER
)
4737 verror(severity
, fmt
, arg
);
4742 pp_reset(char *file
, int apass
, ListGen
* listgen
, StrList
**deplist
)
4747 istk
= nasm_malloc(sizeof(Include
));
4750 istk
->expansion
= NULL
;
4752 istk
->fp
= fopen(file
, "r");
4754 src_set_fname(nasm_strdup(file
));
4758 error(ERR_FATAL
|ERR_NOFILE
, "unable to open input file `%s'",
4761 nested_mac_count
= 0;
4762 nested_rep_count
= 0;
4765 if (tasm_compatible_mode
) {
4766 stdmacpos
= nasm_stdmac
;
4768 stdmacpos
= nasm_stdmac_after_tasm
;
4770 any_extrastdmac
= extrastdmac
&& *extrastdmac
;
4775 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4776 * The caller, however, will also pass in 3 for preprocess-only so
4777 * we can set __PASS__ accordingly.
4779 pass
= apass
> 2 ? 2 : apass
;
4781 dephead
= deptail
= deplist
;
4783 StrList
*sl
= nasm_malloc(strlen(file
)+1+sizeof sl
->next
);
4785 strcpy(sl
->str
, file
);
4787 deptail
= &sl
->next
;
4791 * Define the __PASS__ macro. This is defined here unlike
4792 * all the other builtins, because it is special -- it varies between
4795 t
= nasm_malloc(sizeof(*t
));
4797 make_tok_num(t
, apass
);
4799 define_smacro(NULL
, "__PASS__", true, 0, t
);
4802 static char *pp_getline(void)
4809 * Fetch a tokenized line, either from the macro-expansion
4810 * buffer or from the input file.
4813 while (istk
->expansion
&& istk
->expansion
->finishes
) {
4814 Line
*l
= istk
->expansion
;
4815 if (!l
->finishes
->name
&& l
->finishes
->in_progress
> 1) {
4819 * This is a macro-end marker for a macro with no
4820 * name, which means it's not really a macro at all
4821 * but a %rep block, and the `in_progress' field is
4822 * more than 1, meaning that we still need to
4823 * repeat. (1 means the natural last repetition; 0
4824 * means termination by %exitrep.) We have
4825 * therefore expanded up to the %endrep, and must
4826 * push the whole block on to the expansion buffer
4827 * again. We don't bother to remove the macro-end
4828 * marker: we'd only have to generate another one
4831 l
->finishes
->in_progress
--;
4832 list_for_each(l
, l
->finishes
->expansion
) {
4833 Token
*t
, *tt
, **tail
;
4835 ll
= nasm_malloc(sizeof(Line
));
4836 ll
->next
= istk
->expansion
;
4837 ll
->finishes
= NULL
;
4841 list_for_each(t
, l
->first
) {
4842 if (t
->text
|| t
->type
== TOK_WHITESPACE
) {
4843 tt
= *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
4848 istk
->expansion
= ll
;
4852 * Check whether a `%rep' was started and not ended
4853 * within this macro expansion. This can happen and
4854 * should be detected. It's a fatal error because
4855 * I'm too confused to work out how to recover
4861 "defining with name in expansion");
4862 else if (istk
->mstk
->name
)
4864 "`%%rep' without `%%endrep' within"
4865 " expansion of macro `%s'",
4870 * FIXME: investigate the relationship at this point between
4871 * istk->mstk and l->finishes
4874 MMacro
*m
= istk
->mstk
;
4875 istk
->mstk
= m
->next_active
;
4878 * This was a real macro call, not a %rep, and
4879 * therefore the parameter information needs to
4884 l
->finishes
->in_progress
--;
4886 nasm_free(m
->params
);
4887 free_tlist(m
->iline
);
4888 nasm_free(m
->paramlen
);
4889 l
->finishes
->in_progress
= 0;
4894 istk
->expansion
= l
->next
;
4896 list
->downlevel(LIST_MACRO
);
4899 while (1) { /* until we get a line we can use */
4901 if (istk
->expansion
) { /* from a macro expansion */
4903 Line
*l
= istk
->expansion
;
4905 istk
->mstk
->lineno
++;
4907 istk
->expansion
= l
->next
;
4909 p
= detoken(tline
, false);
4910 list
->line(LIST_MACRO
, p
);
4915 if (line
) { /* from the current input file */
4916 line
= prepreproc(line
);
4917 tline
= tokenize(line
);
4922 * The current file has ended; work down the istk
4928 /* nasm_error can't be conditionally suppressed */
4929 nasm_error(ERR_FATAL
,
4930 "expected `%%endif' before end of file");
4932 /* only set line and file name if there's a next node */
4934 src_set_linnum(i
->lineno
);
4935 nasm_free(src_set_fname(i
->fname
));
4938 list
->downlevel(LIST_INCLUDE
);
4942 if (istk
->expansion
&& istk
->expansion
->finishes
)
4948 * We must expand MMacro parameters and MMacro-local labels
4949 * _before_ we plunge into directive processing, to cope
4950 * with things like `%define something %1' such as STRUC
4951 * uses. Unless we're _defining_ a MMacro, in which case
4952 * those tokens should be left alone to go into the
4953 * definition; and unless we're in a non-emitting
4954 * condition, in which case we don't want to meddle with
4957 if (!defining
&& !(istk
->conds
&& !emitting(istk
->conds
->state
))
4958 && !(istk
->mstk
&& !istk
->mstk
->in_progress
)) {
4959 tline
= expand_mmac_params(tline
);
4963 * Check the line to see if it's a preprocessor directive.
4965 if (do_directive(tline
) == DIRECTIVE_FOUND
) {
4967 } else if (defining
) {
4969 * We're defining a multi-line macro. We emit nothing
4971 * shove the tokenized line on to the macro definition.
4973 Line
*l
= nasm_malloc(sizeof(Line
));
4974 l
->next
= defining
->expansion
;
4977 defining
->expansion
= l
;
4979 } else if (istk
->conds
&& !emitting(istk
->conds
->state
)) {
4981 * We're in a non-emitting branch of a condition block.
4982 * Emit nothing at all, not even a blank line: when we
4983 * emerge from the condition we'll give a line-number
4984 * directive so we keep our place correctly.
4988 } else if (istk
->mstk
&& !istk
->mstk
->in_progress
) {
4990 * We're in a %rep block which has been terminated, so
4991 * we're walking through to the %endrep without
4992 * emitting anything. Emit nothing at all, not even a
4993 * blank line: when we emerge from the %rep block we'll
4994 * give a line-number directive so we keep our place
5000 tline
= expand_smacro(tline
);
5001 if (!expand_mmacro(tline
)) {
5003 * De-tokenize the line again, and emit it.
5005 line
= detoken(tline
, true);
5009 continue; /* expand_mmacro calls free_tlist */
5017 static void pp_cleanup(int pass
)
5020 if (defining
->name
) {
5022 "end of file while still defining macro `%s'",
5025 error(ERR_NONFATAL
, "end of file while still in %%rep");
5028 free_mmacro(defining
);
5038 nasm_free(i
->fname
);
5043 nasm_free(src_set_fname(NULL
));
5048 while ((i
= ipath
)) {
5057 void pp_include_path(char *path
)
5061 i
= nasm_malloc(sizeof(IncPath
));
5062 i
->path
= path
? nasm_strdup(path
) : NULL
;
5075 void pp_pre_include(char *fname
)
5077 Token
*inc
, *space
, *name
;
5080 name
= new_Token(NULL
, TOK_INTERNAL_STRING
, fname
, 0);
5081 space
= new_Token(name
, TOK_WHITESPACE
, NULL
, 0);
5082 inc
= new_Token(space
, TOK_PREPROC_ID
, "%include", 0);
5084 l
= nasm_malloc(sizeof(Line
));
5091 void pp_pre_define(char *definition
)
5097 equals
= strchr(definition
, '=');
5098 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5099 def
= new_Token(space
, TOK_PREPROC_ID
, "%define", 0);
5102 space
->next
= tokenize(definition
);
5106 l
= nasm_malloc(sizeof(Line
));
5113 void pp_pre_undefine(char *definition
)
5118 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5119 def
= new_Token(space
, TOK_PREPROC_ID
, "%undef", 0);
5120 space
->next
= tokenize(definition
);
5122 l
= nasm_malloc(sizeof(Line
));
5130 * Added by Keith Kanios:
5132 * This function is used to assist with "runtime" preprocessor
5133 * directives. (e.g. pp_runtime("%define __BITS__ 64");)
5135 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
5136 * PASS A VALID STRING TO THIS FUNCTION!!!!!
5139 void pp_runtime(char *definition
)
5143 def
= tokenize(definition
);
5144 if (do_directive(def
) == NO_DIRECTIVE_FOUND
)
5149 void pp_extra_stdmac(macros_t
*macros
)
5151 extrastdmac
= macros
;
5154 static void make_tok_num(Token
* tok
, int64_t val
)
5157 snprintf(numbuf
, sizeof(numbuf
), "%"PRId64
"", val
);
5158 tok
->text
= nasm_strdup(numbuf
);
5159 tok
->type
= TOK_NUMBER
;