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 * Condition codes. Note that we use c_ prefix not C_ because C_ is
331 * used in nasm.h for the "real" condition codes. At _this_ level,
332 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
333 * ones, so we need a different enum...
335 static const char * const conditions
[] = {
336 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
337 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
338 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
341 c_A
, c_AE
, c_B
, c_BE
, c_C
, c_CXZ
, c_E
, c_ECXZ
, c_G
, c_GE
, c_L
, c_LE
,
342 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, c_NE
, c_NG
, c_NGE
, c_NL
, c_NLE
, c_NO
,
343 c_NP
, c_NS
, c_NZ
, c_O
, c_P
, c_PE
, c_PO
, c_RCXZ
, c_S
, c_Z
,
346 static const enum pp_conds inverse_ccs
[] = {
347 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, -1, c_NE
, -1, c_NG
, c_NGE
, c_NL
, c_NLE
,
348 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
,
349 c_Z
, c_NO
, c_NP
, c_PO
, c_PE
, -1, c_NS
, c_NZ
355 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
356 static int is_condition(enum preproc_token arg
)
358 return PP_IS_COND(arg
) || (arg
== PP_ELSE
) || (arg
== PP_ENDIF
);
361 /* For TASM compatibility we need to be able to recognise TASM compatible
362 * conditional compilation directives. Using the NASM pre-processor does
363 * not work, so we look for them specifically from the following list and
364 * then jam in the equivalent NASM directive into the input stream.
368 TM_ARG
, TM_ELIF
, TM_ELSE
, TM_ENDIF
, TM_IF
, TM_IFDEF
, TM_IFDIFI
,
369 TM_IFNDEF
, TM_INCLUDE
, TM_LOCAL
372 static const char * const tasm_directives
[] = {
373 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
374 "ifndef", "include", "local"
377 static int StackSize
= 4;
378 static char *StackPointer
= "ebp";
379 static int ArgOffset
= 8;
380 static int LocalOffset
= 0;
382 static Context
*cstk
;
383 static Include
*istk
;
384 static IncPath
*ipath
= NULL
;
386 static int pass
; /* HACK: pass 0 = generate dependencies only */
387 static StrList
**dephead
, **deptail
; /* Dependency list */
389 static uint64_t unique
; /* unique identifier numbers */
391 static Line
*predef
= NULL
;
392 static bool do_predef
;
394 static ListGen
*list
;
397 * The current set of multi-line macros we have defined.
399 static struct hash_table mmacros
;
402 * The current set of single-line macros we have defined.
404 static struct hash_table smacros
;
407 * The multi-line macro we are currently defining, or the %rep
408 * block we are currently reading, if any.
410 static MMacro
*defining
;
412 static uint64_t nested_mac_count
;
413 static uint64_t nested_rep_count
;
416 * The number of macro parameters to allocate space for at a time.
418 #define PARAM_DELTA 16
421 * The standard macro set: defined in macros.c in the array nasm_stdmac.
422 * This gives our position in the macro set, when we're processing it.
424 static macros_t
*stdmacpos
;
427 * The extra standard macros that come from the object format, if
430 static macros_t
*extrastdmac
= NULL
;
431 static bool any_extrastdmac
;
434 * Tokens are allocated in blocks to improve speed
436 #define TOKEN_BLOCKSIZE 4096
437 static Token
*freeTokens
= NULL
;
443 static Blocks blocks
= { NULL
, NULL
};
446 * Forward declarations.
448 static Token
*expand_mmac_params(Token
* tline
);
449 static Token
*expand_smacro(Token
* tline
);
450 static Token
*expand_id(Token
* tline
);
451 static Context
*get_ctx(const char *name
, const char **namep
,
453 static void make_tok_num(Token
* tok
, int64_t val
);
454 static void error(int severity
, const char *fmt
, ...);
455 static void error_precond(int severity
, const char *fmt
, ...);
456 static void *new_Block(size_t size
);
457 static void delete_Blocks(void);
458 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
459 const char *text
, int txtlen
);
460 static Token
*delete_Token(Token
* t
);
463 * Macros for safe checking of token pointers, avoid *(NULL)
465 #define tok_type_(x,t) ((x) && (x)->type == (t))
466 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
467 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
468 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
471 * Handle TASM specific directives, which do not contain a % in
472 * front of them. We do it here because I could not find any other
473 * place to do it for the moment, and it is a hack (ideally it would
474 * be nice to be able to use the NASM pre-processor to do it).
476 static char *check_tasm_directive(char *line
)
478 int32_t i
, j
, k
, m
, len
;
479 char *p
, *q
, *oldline
, oldchar
;
481 p
= nasm_skip_spaces(line
);
483 /* Binary search for the directive name */
485 j
= ARRAY_SIZE(tasm_directives
);
486 q
= nasm_skip_word(p
);
493 m
= nasm_stricmp(p
, tasm_directives
[k
]);
495 /* We have found a directive, so jam a % in front of it
496 * so that NASM will then recognise it as one if it's own.
501 line
= nasm_malloc(len
+ 2);
503 if (k
== TM_IFDIFI
) {
505 * NASM does not recognise IFDIFI, so we convert
506 * it to %if 0. This is not used in NASM
507 * compatible code, but does need to parse for the
508 * TASM macro package.
510 strcpy(line
+ 1, "if 0");
512 memcpy(line
+ 1, p
, len
+ 1);
527 * The pre-preprocessing stage... This function translates line
528 * number indications as they emerge from GNU cpp (`# lineno "file"
529 * flags') into NASM preprocessor line number indications (`%line
532 static char *prepreproc(char *line
)
535 char *fname
, *oldline
;
537 if (line
[0] == '#' && line
[1] == ' ') {
540 lineno
= atoi(fname
);
541 fname
+= strspn(fname
, "0123456789 ");
544 fnlen
= strcspn(fname
, "\"");
545 line
= nasm_malloc(20 + fnlen
);
546 snprintf(line
, 20 + fnlen
, "%%line %d %.*s", lineno
, fnlen
, fname
);
549 if (tasm_compatible_mode
)
550 return check_tasm_directive(line
);
555 * Free a linked list of tokens.
557 static void free_tlist(Token
* list
)
560 list
= delete_Token(list
);
564 * Free a linked list of lines.
566 static void free_llist(Line
* list
)
569 list_for_each_safe(l
, tmp
, list
) {
570 free_tlist(l
->first
);
578 static void free_mmacro(MMacro
* m
)
581 free_tlist(m
->dlist
);
582 nasm_free(m
->defaults
);
583 free_llist(m
->expansion
);
588 * Free all currently defined macros, and free the hash tables
590 static void free_smacro_table(struct hash_table
*smt
)
594 struct hash_tbl_node
*it
= NULL
;
596 while ((s
= hash_iterate(smt
, &it
, &key
)) != NULL
) {
597 nasm_free((void *)key
);
598 list_for_each_safe(s
, tmp
, s
) {
600 free_tlist(s
->expansion
);
607 static void free_mmacro_table(struct hash_table
*mmt
)
611 struct hash_tbl_node
*it
= NULL
;
614 while ((m
= hash_iterate(mmt
, &it
, &key
)) != NULL
) {
615 nasm_free((void *)key
);
616 list_for_each_safe(m
,tmp
, m
)
622 static void free_macros(void)
624 free_smacro_table(&smacros
);
625 free_mmacro_table(&mmacros
);
629 * Initialize the hash tables
631 static void init_macros(void)
633 hash_init(&smacros
, HASH_LARGE
);
634 hash_init(&mmacros
, HASH_LARGE
);
638 * Pop the context stack.
640 static void ctx_pop(void)
645 free_smacro_table(&c
->localmac
);
651 * Search for a key in the hash index; adding it if necessary
652 * (in which case we initialize the data pointer to NULL.)
655 hash_findi_add(struct hash_table
*hash
, const char *str
)
657 struct hash_insert hi
;
661 r
= hash_findi(hash
, str
, &hi
);
665 strx
= nasm_strdup(str
); /* Use a more efficient allocator here? */
666 return hash_add(&hi
, strx
, NULL
);
670 * Like hash_findi, but returns the data element rather than a pointer
671 * to it. Used only when not adding a new element, hence no third
675 hash_findix(struct hash_table
*hash
, const char *str
)
679 p
= hash_findi(hash
, str
, NULL
);
680 return p
? *p
: NULL
;
684 * read line from standart macros set,
685 * if there no more left -- return NULL
687 static char *line_from_stdmac(void)
690 const unsigned char *p
= stdmacpos
;
699 len
+= pp_directives_len
[c
- 0x80] + 1;
704 line
= nasm_malloc(len
+ 1);
706 while ((c
= *stdmacpos
++)) {
708 memcpy(q
, pp_directives
[c
- 0x80], pp_directives_len
[c
- 0x80]);
709 q
+= pp_directives_len
[c
- 0x80];
719 /* This was the last of the standard macro chain... */
721 if (any_extrastdmac
) {
722 stdmacpos
= extrastdmac
;
723 any_extrastdmac
= false;
724 } else if (do_predef
) {
726 Token
*head
, **tail
, *t
;
729 * Nasty hack: here we push the contents of
730 * `predef' on to the top-level expansion stack,
731 * since this is the most convenient way to
732 * implement the pre-include and pre-define
735 list_for_each(pd
, predef
) {
738 list_for_each(t
, pd
->first
) {
739 *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
740 tail
= &(*tail
)->next
;
743 l
= nasm_malloc(sizeof(Line
));
744 l
->next
= istk
->expansion
;
757 #define BUF_DELTA 512
759 * Read a line from the top file in istk, handling multiple CR/LFs
760 * at the end of the line read, and handling spurious ^Zs. Will
761 * return lines from the standard macro set if this has not already
764 static char *read_line(void)
766 char *buffer
, *p
, *q
;
767 int bufsize
, continued_count
;
770 * standart macros set (predefined) goes first
772 p
= line_from_stdmac();
777 * regular read from a file
780 buffer
= nasm_malloc(BUF_DELTA
);
784 q
= fgets(p
, bufsize
- (p
- buffer
), istk
->fp
);
788 if (p
> buffer
&& p
[-1] == '\n') {
790 * Convert backslash-CRLF line continuation sequences into
791 * nothing at all (for DOS and Windows)
793 if (((p
- 2) > buffer
) && (p
[-3] == '\\') && (p
[-2] == '\r')) {
799 * Also convert backslash-LF line continuation sequences into
800 * nothing at all (for Unix)
802 else if (((p
- 1) > buffer
) && (p
[-2] == '\\')) {
810 if (p
- buffer
> bufsize
- 10) {
811 int32_t offset
= p
- buffer
;
812 bufsize
+= BUF_DELTA
;
813 buffer
= nasm_realloc(buffer
, bufsize
);
814 p
= buffer
+ offset
; /* prevent stale-pointer problems */
818 if (!q
&& p
== buffer
) {
823 src_set_linnum(src_get_linnum() + istk
->lineinc
+
824 (continued_count
* istk
->lineinc
));
827 * Play safe: remove CRs as well as LFs, if any of either are
828 * present at the end of the line.
830 while (--p
>= buffer
&& (*p
== '\n' || *p
== '\r'))
834 * Handle spurious ^Z, which may be inserted into source files
835 * by some file transfer utilities.
837 buffer
[strcspn(buffer
, "\032")] = '\0';
839 list
->line(LIST_READ
, buffer
);
845 * Tokenize a line of text. This is a very simple process since we
846 * don't need to parse the value out of e.g. numeric tokens: we
847 * simply split one string into many.
849 static Token
*tokenize(char *line
)
852 enum pp_token_type type
;
854 Token
*t
, **tail
= &list
;
860 if (*p
== '+' && !nasm_isdigit(p
[1])) {
863 } else if (nasm_isdigit(*p
) ||
864 ((*p
== '-' || *p
== '+') && nasm_isdigit(p
[1]))) {
868 while (nasm_isdigit(*p
));
869 type
= TOK_PREPROC_ID
;
870 } else if (*p
== '{') {
872 while (*p
&& *p
!= '}') {
879 type
= TOK_PREPROC_ID
;
880 } else if (*p
== '[') {
882 line
+= 2; /* Skip the leading %[ */
884 while (lvl
&& (c
= *p
++)) {
896 p
= nasm_skip_string(p
- 1) + 1;
906 error(ERR_NONFATAL
, "unterminated %[ construct");
908 } else if (*p
== '?') {
909 type
= TOK_PREPROC_Q
; /* %? */
912 type
= TOK_PREPROC_QQ
; /* %?? */
915 } else if (isidchar(*p
) ||
916 ((*p
== '!' || *p
== '%' || *p
== '$') &&
921 while (isidchar(*p
));
922 type
= TOK_PREPROC_ID
;
928 } else if (isidstart(*p
) || (*p
== '$' && isidstart(p
[1]))) {
931 while (*p
&& isidchar(*p
))
933 } else if (*p
== '\'' || *p
== '"' || *p
== '`') {
938 p
= nasm_skip_string(p
);
943 error(ERR_WARNING
|ERR_PASS1
, "unterminated string");
944 /* Handling unterminated strings by UNV */
947 } else if (p
[0] == '$' && p
[1] == '$') {
948 type
= TOK_OTHER
; /* TOKEN_BASE */
950 } else if (isnumstart(*p
)) {
952 bool is_float
= false;
968 if (!is_hex
&& (c
== 'e' || c
== 'E')) {
970 if (*p
== '+' || *p
== '-') {
972 * e can only be followed by +/- if it is either a
973 * prefixed hex number or a floating-point number
978 } else if (c
== 'H' || c
== 'h' || c
== 'X' || c
== 'x') {
980 } else if (c
== 'P' || c
== 'p') {
982 if (*p
== '+' || *p
== '-')
984 } else if (isnumchar(c
) || c
== '_')
988 * we need to deal with consequences of the legacy
989 * parser, like "1.nolist" being two tokens
990 * (TOK_NUMBER, TOK_ID) here; at least give it
991 * a shot for now. In the future, we probably need
992 * a flex-based scanner with proper pattern matching
993 * to do it as well as it can be done. Nothing in
994 * the world is going to help the person who wants
995 * 0x123.p16 interpreted as two tokens, though.
1001 if (nasm_isdigit(*r
) || (is_hex
&& nasm_isxdigit(*r
)) ||
1002 (!is_hex
&& (*r
== 'e' || *r
== 'E')) ||
1003 (*r
== 'p' || *r
== 'P')) {
1007 break; /* Terminate the token */
1011 p
--; /* Point to first character beyond number */
1013 if (p
== line
+1 && *line
== '$') {
1014 type
= TOK_OTHER
; /* TOKEN_HERE */
1016 if (has_e
&& !is_hex
) {
1017 /* 1e13 is floating-point, but 1e13h is not */
1021 type
= is_float
? TOK_FLOAT
: TOK_NUMBER
;
1023 } else if (nasm_isspace(*p
)) {
1024 type
= TOK_WHITESPACE
;
1025 p
= nasm_skip_spaces(p
);
1027 * Whitespace just before end-of-line is discarded by
1028 * pretending it's a comment; whitespace just before a
1029 * comment gets lumped into the comment.
1031 if (!*p
|| *p
== ';') {
1036 } else if (*p
== ';') {
1042 * Anything else is an operator of some kind. We check
1043 * for all the double-character operators (>>, <<, //,
1044 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1045 * else is a single-character operator.
1048 if ((p
[0] == '>' && p
[1] == '>') ||
1049 (p
[0] == '<' && p
[1] == '<') ||
1050 (p
[0] == '/' && p
[1] == '/') ||
1051 (p
[0] == '<' && p
[1] == '=') ||
1052 (p
[0] == '>' && p
[1] == '=') ||
1053 (p
[0] == '=' && p
[1] == '=') ||
1054 (p
[0] == '!' && p
[1] == '=') ||
1055 (p
[0] == '<' && p
[1] == '>') ||
1056 (p
[0] == '&' && p
[1] == '&') ||
1057 (p
[0] == '|' && p
[1] == '|') ||
1058 (p
[0] == '^' && p
[1] == '^')) {
1064 /* Handling unterminated string by UNV */
1067 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1068 t->text[p-line] = *line;
1072 if (type
!= TOK_COMMENT
) {
1073 *tail
= t
= new_Token(NULL
, type
, line
, p
- line
);
1082 * this function allocates a new managed block of memory and
1083 * returns a pointer to the block. The managed blocks are
1084 * deleted only all at once by the delete_Blocks function.
1086 static void *new_Block(size_t size
)
1088 Blocks
*b
= &blocks
;
1090 /* first, get to the end of the linked list */
1093 /* now allocate the requested chunk */
1094 b
->chunk
= nasm_malloc(size
);
1096 /* now allocate a new block for the next request */
1097 b
->next
= nasm_malloc(sizeof(Blocks
));
1098 /* and initialize the contents of the new block */
1099 b
->next
->next
= NULL
;
1100 b
->next
->chunk
= NULL
;
1105 * this function deletes all managed blocks of memory
1107 static void delete_Blocks(void)
1109 Blocks
*a
, *b
= &blocks
;
1112 * keep in mind that the first block, pointed to by blocks
1113 * is a static and not dynamically allocated, so we don't
1118 nasm_free(b
->chunk
);
1127 * this function creates a new Token and passes a pointer to it
1128 * back to the caller. It sets the type and text elements, and
1129 * also the a.mac and next elements to NULL.
1131 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
1132 const char *text
, int txtlen
)
1138 freeTokens
= (Token
*) new_Block(TOKEN_BLOCKSIZE
* sizeof(Token
));
1139 for (i
= 0; i
< TOKEN_BLOCKSIZE
- 1; i
++)
1140 freeTokens
[i
].next
= &freeTokens
[i
+ 1];
1141 freeTokens
[i
].next
= NULL
;
1144 freeTokens
= t
->next
;
1148 if (type
== TOK_WHITESPACE
|| !text
) {
1152 txtlen
= strlen(text
);
1153 t
->text
= nasm_malloc(txtlen
+1);
1154 memcpy(t
->text
, text
, txtlen
);
1155 t
->text
[txtlen
] = '\0';
1160 static Token
*delete_Token(Token
* t
)
1162 Token
*next
= t
->next
;
1164 t
->next
= freeTokens
;
1170 * Convert a line of tokens back into text.
1171 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1172 * will be transformed into ..@ctxnum.xxx
1174 static char *detoken(Token
* tlist
, bool expand_locals
)
1181 list_for_each(t
, tlist
) {
1182 if (t
->type
== TOK_PREPROC_ID
&& t
->text
[1] == '!') {
1183 char *p
= getenv(t
->text
+ 2);
1186 t
->text
= nasm_strdup(p
);
1188 t
->text
= nasm_strdup("");
1189 error(ERR_WARNING
| ERR_PASS1
, "`%s' is empty", q
+ 2);
1193 /* Expand local macros here and not during preprocessing */
1194 if (expand_locals
&&
1195 t
->type
== TOK_PREPROC_ID
&& t
->text
&&
1196 t
->text
[0] == '%' && t
->text
[1] == '$') {
1199 Context
*ctx
= get_ctx(t
->text
, &q
, false);
1202 snprintf(buffer
, sizeof(buffer
), "..@%"PRIu32
".", ctx
->number
);
1203 p
= nasm_strcat(buffer
, q
);
1208 if (t
->type
== TOK_WHITESPACE
)
1211 len
+= strlen(t
->text
);
1214 p
= line
= nasm_malloc(len
+ 1);
1216 list_for_each(t
, tlist
) {
1217 if (t
->type
== TOK_WHITESPACE
) {
1219 } else if (t
->text
) {
1231 * A scanner, suitable for use by the expression evaluator, which
1232 * operates on a line of Tokens. Expects a pointer to a pointer to
1233 * the first token in the line to be passed in as its private_data
1236 * FIX: This really needs to be unified with stdscan.
1238 static int ppscan(void *private_data
, struct tokenval
*tokval
)
1240 Token
**tlineptr
= private_data
;
1242 char ourcopy
[MAX_KEYWORD
+1], *p
, *r
, *s
;
1246 *tlineptr
= tline
? tline
->next
: NULL
;
1247 } while (tline
&& (tline
->type
== TOK_WHITESPACE
||
1248 tline
->type
== TOK_COMMENT
));
1251 return tokval
->t_type
= TOKEN_EOS
;
1253 tokval
->t_charptr
= tline
->text
;
1255 if (tline
->text
[0] == '$' && !tline
->text
[1])
1256 return tokval
->t_type
= TOKEN_HERE
;
1257 if (tline
->text
[0] == '$' && tline
->text
[1] == '$' && !tline
->text
[2])
1258 return tokval
->t_type
= TOKEN_BASE
;
1260 if (tline
->type
== TOK_ID
) {
1261 p
= tokval
->t_charptr
= tline
->text
;
1263 tokval
->t_charptr
++;
1264 return tokval
->t_type
= TOKEN_ID
;
1267 for (r
= p
, s
= ourcopy
; *r
; r
++) {
1268 if (r
>= p
+MAX_KEYWORD
)
1269 return tokval
->t_type
= TOKEN_ID
; /* Not a keyword */
1270 *s
++ = nasm_tolower(*r
);
1273 /* right, so we have an identifier sitting in temp storage. now,
1274 * is it actually a register or instruction name, or what? */
1275 return nasm_token_hash(ourcopy
, tokval
);
1278 if (tline
->type
== TOK_NUMBER
) {
1280 tokval
->t_integer
= readnum(tline
->text
, &rn_error
);
1281 tokval
->t_charptr
= tline
->text
;
1283 return tokval
->t_type
= TOKEN_ERRNUM
;
1285 return tokval
->t_type
= TOKEN_NUM
;
1288 if (tline
->type
== TOK_FLOAT
) {
1289 return tokval
->t_type
= TOKEN_FLOAT
;
1292 if (tline
->type
== TOK_STRING
) {
1295 bq
= tline
->text
[0];
1296 tokval
->t_charptr
= tline
->text
;
1297 tokval
->t_inttwo
= nasm_unquote(tline
->text
, &ep
);
1299 if (ep
[0] != bq
|| ep
[1] != '\0')
1300 return tokval
->t_type
= TOKEN_ERRSTR
;
1302 return tokval
->t_type
= TOKEN_STR
;
1305 if (tline
->type
== TOK_OTHER
) {
1306 if (!strcmp(tline
->text
, "<<"))
1307 return tokval
->t_type
= TOKEN_SHL
;
1308 if (!strcmp(tline
->text
, ">>"))
1309 return tokval
->t_type
= TOKEN_SHR
;
1310 if (!strcmp(tline
->text
, "//"))
1311 return tokval
->t_type
= TOKEN_SDIV
;
1312 if (!strcmp(tline
->text
, "%%"))
1313 return tokval
->t_type
= TOKEN_SMOD
;
1314 if (!strcmp(tline
->text
, "=="))
1315 return tokval
->t_type
= TOKEN_EQ
;
1316 if (!strcmp(tline
->text
, "<>"))
1317 return tokval
->t_type
= TOKEN_NE
;
1318 if (!strcmp(tline
->text
, "!="))
1319 return tokval
->t_type
= TOKEN_NE
;
1320 if (!strcmp(tline
->text
, "<="))
1321 return tokval
->t_type
= TOKEN_LE
;
1322 if (!strcmp(tline
->text
, ">="))
1323 return tokval
->t_type
= TOKEN_GE
;
1324 if (!strcmp(tline
->text
, "&&"))
1325 return tokval
->t_type
= TOKEN_DBL_AND
;
1326 if (!strcmp(tline
->text
, "^^"))
1327 return tokval
->t_type
= TOKEN_DBL_XOR
;
1328 if (!strcmp(tline
->text
, "||"))
1329 return tokval
->t_type
= TOKEN_DBL_OR
;
1333 * We have no other options: just return the first character of
1336 return tokval
->t_type
= tline
->text
[0];
1340 * Compare a string to the name of an existing macro; this is a
1341 * simple wrapper which calls either strcmp or nasm_stricmp
1342 * depending on the value of the `casesense' parameter.
1344 static int mstrcmp(const char *p
, const char *q
, bool casesense
)
1346 return casesense
? strcmp(p
, q
) : nasm_stricmp(p
, q
);
1350 * Compare a string to the name of an existing macro; this is a
1351 * simple wrapper which calls either strcmp or nasm_stricmp
1352 * depending on the value of the `casesense' parameter.
1354 static int mmemcmp(const char *p
, const char *q
, size_t l
, bool casesense
)
1356 return casesense
? memcmp(p
, q
, l
) : nasm_memicmp(p
, q
, l
);
1360 * Return the Context structure associated with a %$ token. Return
1361 * NULL, having _already_ reported an error condition, if the
1362 * context stack isn't deep enough for the supplied number of $
1364 * If all_contexts == true, contexts that enclose current are
1365 * also scanned for such smacro, until it is found; if not -
1366 * only the context that directly results from the number of $'s
1367 * in variable's name.
1369 * If "namep" is non-NULL, set it to the pointer to the macro name
1370 * tail, i.e. the part beyond %$...
1372 static Context
*get_ctx(const char *name
, const char **namep
,
1382 if (!name
|| name
[0] != '%' || name
[1] != '$')
1386 error(ERR_NONFATAL
, "`%s': context stack is empty", name
);
1393 while (ctx
&& *name
== '$') {
1399 error(ERR_NONFATAL
, "`%s': context stack is only"
1400 " %d level%s deep", name
, i
, (i
== 1 ? "" : "s"));
1411 /* Search for this smacro in found context */
1412 m
= hash_findix(&ctx
->localmac
, name
);
1414 if (!mstrcmp(m
->name
, name
, m
->casesense
))
1425 * Check to see if a file is already in a string list
1427 static bool in_list(const StrList
*list
, const char *str
)
1430 if (!strcmp(list
->str
, str
))
1438 * Open an include file. This routine must always return a valid
1439 * file pointer if it returns - it's responsible for throwing an
1440 * ERR_FATAL and bombing out completely if not. It should also try
1441 * the include path one by one until it finds the file or reaches
1442 * the end of the path.
1444 static FILE *inc_fopen(const char *file
, StrList
**dhead
, StrList
***dtail
,
1449 IncPath
*ip
= ipath
;
1450 int len
= strlen(file
);
1451 size_t prefix_len
= 0;
1455 sl
= nasm_malloc(prefix_len
+len
+1+sizeof sl
->next
);
1456 memcpy(sl
->str
, prefix
, prefix_len
);
1457 memcpy(sl
->str
+prefix_len
, file
, len
+1);
1458 fp
= fopen(sl
->str
, "r");
1459 if (fp
&& dhead
&& !in_list(*dhead
, sl
->str
)) {
1477 prefix_len
= strlen(prefix
);
1479 /* -MG given and file not found */
1480 if (dhead
&& !in_list(*dhead
, file
)) {
1481 sl
= nasm_malloc(len
+1+sizeof sl
->next
);
1483 strcpy(sl
->str
, file
);
1491 error(ERR_FATAL
, "unable to open include file `%s'", file
);
1496 * Determine if we should warn on defining a single-line macro of
1497 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1498 * return true if _any_ single-line macro of that name is defined.
1499 * Otherwise, will return true if a single-line macro with either
1500 * `nparam' or no parameters is defined.
1502 * If a macro with precisely the right number of parameters is
1503 * defined, or nparam is -1, the address of the definition structure
1504 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1505 * is NULL, no action will be taken regarding its contents, and no
1508 * Note that this is also called with nparam zero to resolve
1511 * If you already know which context macro belongs to, you can pass
1512 * the context pointer as first parameter; if you won't but name begins
1513 * with %$ the context will be automatically computed. If all_contexts
1514 * is true, macro will be searched in outer contexts as well.
1517 smacro_defined(Context
* ctx
, const char *name
, int nparam
, SMacro
** defn
,
1520 struct hash_table
*smtbl
;
1524 smtbl
= &ctx
->localmac
;
1525 } else if (name
[0] == '%' && name
[1] == '$') {
1527 ctx
= get_ctx(name
, &name
, false);
1529 return false; /* got to return _something_ */
1530 smtbl
= &ctx
->localmac
;
1534 m
= (SMacro
*) hash_findix(smtbl
, name
);
1537 if (!mstrcmp(m
->name
, name
, m
->casesense
&& nocase
) &&
1538 (nparam
<= 0 || m
->nparam
== 0 || nparam
== (int) m
->nparam
)) {
1540 if (nparam
== (int) m
->nparam
|| nparam
== -1)
1554 * Count and mark off the parameters in a multi-line macro call.
1555 * This is called both from within the multi-line macro expansion
1556 * code, and also to mark off the default parameters when provided
1557 * in a %macro definition line.
1559 static void count_mmac_params(Token
* t
, int *nparam
, Token
*** params
)
1561 int paramsize
, brace
;
1563 *nparam
= paramsize
= 0;
1566 /* +1: we need space for the final NULL */
1567 if (*nparam
+1 >= paramsize
) {
1568 paramsize
+= PARAM_DELTA
;
1569 *params
= nasm_realloc(*params
, sizeof(**params
) * paramsize
);
1573 if (tok_is_(t
, "{"))
1575 (*params
)[(*nparam
)++] = t
;
1576 while (tok_isnt_(t
, brace
? "}" : ","))
1578 if (t
) { /* got a comma/brace */
1582 * Now we've found the closing brace, look further
1586 if (tok_isnt_(t
, ",")) {
1588 "braces do not enclose all of macro parameter");
1589 while (tok_isnt_(t
, ","))
1593 t
= t
->next
; /* eat the comma */
1600 * Determine whether one of the various `if' conditions is true or
1603 * We must free the tline we get passed.
1605 static bool if_condition(Token
* tline
, enum preproc_token ct
)
1607 enum pp_conditional i
= PP_COND(ct
);
1609 Token
*t
, *tt
, **tptr
, *origline
;
1610 struct tokenval tokval
;
1612 enum pp_token_type needtype
;
1618 j
= false; /* have we matched yet? */
1623 if (tline
->type
!= TOK_ID
) {
1625 "`%s' expects context identifiers", pp_directives
[ct
]);
1626 free_tlist(origline
);
1629 if (cstk
&& cstk
->name
&& !nasm_stricmp(tline
->text
, cstk
->name
))
1631 tline
= tline
->next
;
1636 j
= false; /* have we matched yet? */
1639 if (!tline
|| (tline
->type
!= TOK_ID
&&
1640 (tline
->type
!= TOK_PREPROC_ID
||
1641 tline
->text
[1] != '$'))) {
1643 "`%s' expects macro identifiers", pp_directives
[ct
]);
1646 if (smacro_defined(NULL
, tline
->text
, 0, NULL
, true))
1648 tline
= tline
->next
;
1654 tline
= expand_smacro(tline
);
1656 while (tok_isnt_(tt
, ","))
1660 "`%s' expects two comma-separated arguments",
1665 j
= true; /* assume equality unless proved not */
1666 while ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) && tt
) {
1667 if (tt
->type
== TOK_OTHER
&& !strcmp(tt
->text
, ",")) {
1668 error(ERR_NONFATAL
, "`%s': more than one comma on line",
1672 if (t
->type
== TOK_WHITESPACE
) {
1676 if (tt
->type
== TOK_WHITESPACE
) {
1680 if (tt
->type
!= t
->type
) {
1681 j
= false; /* found mismatching tokens */
1684 /* When comparing strings, need to unquote them first */
1685 if (t
->type
== TOK_STRING
) {
1686 size_t l1
= nasm_unquote(t
->text
, NULL
);
1687 size_t l2
= nasm_unquote(tt
->text
, NULL
);
1693 if (mmemcmp(t
->text
, tt
->text
, l1
, i
== PPC_IFIDN
)) {
1697 } else if (mstrcmp(tt
->text
, t
->text
, i
== PPC_IFIDN
) != 0) {
1698 j
= false; /* found mismatching tokens */
1705 if ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) || tt
)
1706 j
= false; /* trailing gunk on one end or other */
1712 MMacro searching
, *mmac
;
1715 tline
= expand_id(tline
);
1716 if (!tok_type_(tline
, TOK_ID
)) {
1718 "`%s' expects a macro name", pp_directives
[ct
]);
1721 searching
.name
= nasm_strdup(tline
->text
);
1722 searching
.casesense
= true;
1723 searching
.plus
= false;
1724 searching
.nolist
= false;
1725 searching
.in_progress
= 0;
1726 searching
.max_depth
= 0;
1727 searching
.rep_nest
= NULL
;
1728 searching
.nparam_min
= 0;
1729 searching
.nparam_max
= INT_MAX
;
1730 tline
= expand_smacro(tline
->next
);
1733 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
1735 "`%s' expects a parameter count or nothing",
1738 searching
.nparam_min
= searching
.nparam_max
=
1739 readnum(tline
->text
, &j
);
1742 "unable to parse parameter count `%s'",
1745 if (tline
&& tok_is_(tline
->next
, "-")) {
1746 tline
= tline
->next
->next
;
1747 if (tok_is_(tline
, "*"))
1748 searching
.nparam_max
= INT_MAX
;
1749 else if (!tok_type_(tline
, TOK_NUMBER
))
1751 "`%s' expects a parameter count after `-'",
1754 searching
.nparam_max
= readnum(tline
->text
, &j
);
1757 "unable to parse parameter count `%s'",
1759 if (searching
.nparam_min
> searching
.nparam_max
)
1761 "minimum parameter count exceeds maximum");
1764 if (tline
&& tok_is_(tline
->next
, "+")) {
1765 tline
= tline
->next
;
1766 searching
.plus
= true;
1768 mmac
= (MMacro
*) hash_findix(&mmacros
, searching
.name
);
1770 if (!strcmp(mmac
->name
, searching
.name
) &&
1771 (mmac
->nparam_min
<= searching
.nparam_max
1773 && (searching
.nparam_min
<= mmac
->nparam_max
1780 if (tline
&& tline
->next
)
1781 error(ERR_WARNING
|ERR_PASS1
,
1782 "trailing garbage after %%ifmacro ignored");
1783 nasm_free(searching
.name
);
1792 needtype
= TOK_NUMBER
;
1795 needtype
= TOK_STRING
;
1799 t
= tline
= expand_smacro(tline
);
1801 while (tok_type_(t
, TOK_WHITESPACE
) ||
1802 (needtype
== TOK_NUMBER
&&
1803 tok_type_(t
, TOK_OTHER
) &&
1804 (t
->text
[0] == '-' || t
->text
[0] == '+') &&
1808 j
= tok_type_(t
, needtype
);
1812 t
= tline
= expand_smacro(tline
);
1813 while (tok_type_(t
, TOK_WHITESPACE
))
1818 t
= t
->next
; /* Skip the actual token */
1819 while (tok_type_(t
, TOK_WHITESPACE
))
1821 j
= !t
; /* Should be nothing left */
1826 t
= tline
= expand_smacro(tline
);
1827 while (tok_type_(t
, TOK_WHITESPACE
))
1830 j
= !t
; /* Should be empty */
1834 t
= tline
= expand_smacro(tline
);
1836 tokval
.t_type
= TOKEN_INVALID
;
1837 evalresult
= evaluate(ppscan
, tptr
, &tokval
,
1838 NULL
, pass
| CRITICAL
, error
, NULL
);
1842 error(ERR_WARNING
|ERR_PASS1
,
1843 "trailing garbage after expression ignored");
1844 if (!is_simple(evalresult
)) {
1846 "non-constant value given to `%s'", pp_directives
[ct
]);
1849 j
= reloc_value(evalresult
) != 0;
1854 "preprocessor directive `%s' not yet implemented",
1859 free_tlist(origline
);
1860 return j
^ PP_NEGATIVE(ct
);
1863 free_tlist(origline
);
1868 * Common code for defining an smacro
1870 static bool define_smacro(Context
*ctx
, const char *mname
, bool casesense
,
1871 int nparam
, Token
*expansion
)
1873 SMacro
*smac
, **smhead
;
1874 struct hash_table
*smtbl
;
1876 if (smacro_defined(ctx
, mname
, nparam
, &smac
, casesense
)) {
1878 error(ERR_WARNING
|ERR_PASS1
,
1879 "single-line macro `%s' defined both with and"
1880 " without parameters", mname
);
1882 * Some instances of the old code considered this a failure,
1883 * some others didn't. What is the right thing to do here?
1885 free_tlist(expansion
);
1886 return false; /* Failure */
1889 * We're redefining, so we have to take over an
1890 * existing SMacro structure. This means freeing
1891 * what was already in it.
1893 nasm_free(smac
->name
);
1894 free_tlist(smac
->expansion
);
1897 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
1898 smhead
= (SMacro
**) hash_findi_add(smtbl
, mname
);
1899 smac
= nasm_malloc(sizeof(SMacro
));
1900 smac
->next
= *smhead
;
1903 smac
->name
= nasm_strdup(mname
);
1904 smac
->casesense
= casesense
;
1905 smac
->nparam
= nparam
;
1906 smac
->expansion
= expansion
;
1907 smac
->in_progress
= false;
1908 return true; /* Success */
1912 * Undefine an smacro
1914 static void undef_smacro(Context
*ctx
, const char *mname
)
1916 SMacro
**smhead
, *s
, **sp
;
1917 struct hash_table
*smtbl
;
1919 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
1920 smhead
= (SMacro
**)hash_findi(smtbl
, mname
, NULL
);
1924 * We now have a macro name... go hunt for it.
1927 while ((s
= *sp
) != NULL
) {
1928 if (!mstrcmp(s
->name
, mname
, s
->casesense
)) {
1931 free_tlist(s
->expansion
);
1941 * Parse a mmacro specification.
1943 static bool parse_mmacro_spec(Token
*tline
, MMacro
*def
, const char *directive
)
1947 tline
= tline
->next
;
1949 tline
= expand_id(tline
);
1950 if (!tok_type_(tline
, TOK_ID
)) {
1951 error(ERR_NONFATAL
, "`%s' expects a macro name", directive
);
1956 def
->name
= nasm_strdup(tline
->text
);
1958 def
->nolist
= false;
1959 def
->in_progress
= 0;
1960 def
->rep_nest
= NULL
;
1961 def
->nparam_min
= 0;
1962 def
->nparam_max
= 0;
1964 tline
= expand_smacro(tline
->next
);
1966 if (!tok_type_(tline
, TOK_NUMBER
)) {
1967 error(ERR_NONFATAL
, "`%s' expects a parameter count", directive
);
1969 def
->nparam_min
= def
->nparam_max
=
1970 readnum(tline
->text
, &err
);
1973 "unable to parse parameter count `%s'", tline
->text
);
1975 if (tline
&& tok_is_(tline
->next
, "-")) {
1976 tline
= tline
->next
->next
;
1977 if (tok_is_(tline
, "*")) {
1978 def
->nparam_max
= INT_MAX
;
1979 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
1981 "`%s' expects a parameter count after `-'", directive
);
1983 def
->nparam_max
= readnum(tline
->text
, &err
);
1985 error(ERR_NONFATAL
, "unable to parse parameter count `%s'",
1988 if (def
->nparam_min
> def
->nparam_max
) {
1989 error(ERR_NONFATAL
, "minimum parameter count exceeds maximum");
1993 if (tline
&& tok_is_(tline
->next
, "+")) {
1994 tline
= tline
->next
;
1997 if (tline
&& tok_type_(tline
->next
, TOK_ID
) &&
1998 !nasm_stricmp(tline
->next
->text
, ".nolist")) {
1999 tline
= tline
->next
;
2004 * Handle default parameters.
2006 if (tline
&& tline
->next
) {
2007 def
->dlist
= tline
->next
;
2009 count_mmac_params(def
->dlist
, &def
->ndefs
, &def
->defaults
);
2012 def
->defaults
= NULL
;
2014 def
->expansion
= NULL
;
2016 if (def
->defaults
&& def
->ndefs
> def
->nparam_max
- def
->nparam_min
&&
2018 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MDP
,
2019 "too many default macro parameters");
2026 * Decode a size directive
2028 static int parse_size(const char *str
) {
2029 static const char *size_names
[] =
2030 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2031 static const int sizes
[] =
2032 { 0, 1, 4, 16, 8, 10, 2, 32 };
2034 return sizes
[bsii(str
, size_names
, ARRAY_SIZE(size_names
))+1];
2038 * nasm_unquote with error if the string contains NUL characters.
2039 * If the string contains NUL characters, issue an error and return
2040 * the C len, i.e. truncate at the NUL.
2042 static size_t nasm_unquote_cstr(char *qstr
, enum preproc_token directive
)
2044 size_t len
= nasm_unquote(qstr
, NULL
);
2045 size_t clen
= strlen(qstr
);
2048 error(ERR_NONFATAL
, "NUL character in `%s' directive",
2049 pp_directives
[directive
]);
2055 * find and process preprocessor directive in passed line
2056 * Find out if a line contains a preprocessor directive, and deal
2059 * If a directive _is_ found, it is the responsibility of this routine
2060 * (and not the caller) to free_tlist() the line.
2062 * @param tline a pointer to the current tokeninzed line linked list
2063 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2066 static int do_directive(Token
* tline
)
2068 enum preproc_token i
;
2081 MMacro
*mmac
, **mmhead
;
2082 Token
*t
, *tt
, *param_start
, *macro_start
, *last
, **tptr
, *origline
;
2084 struct tokenval tokval
;
2086 MMacro
*tmp_defining
; /* Used when manipulating rep_nest */
2094 if (!tline
|| !tok_type_(tline
, TOK_PREPROC_ID
) ||
2095 (tline
->text
[1] == '%' || tline
->text
[1] == '$'
2096 || tline
->text
[1] == '!'))
2097 return NO_DIRECTIVE_FOUND
;
2099 i
= pp_token_hash(tline
->text
);
2102 * FIXME: We zap execution of PP_RMACRO, PP_IRMACRO, PP_EXITMACRO
2103 * since they are known to be buggy at moment, we need to fix them
2104 * in future release (2.09-2.10)
2106 if (i
== PP_RMACRO
|| i
== PP_RMACRO
|| i
== PP_EXITMACRO
) {
2107 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2109 return NO_DIRECTIVE_FOUND
;
2113 * If we're in a non-emitting branch of a condition construct,
2114 * or walking to the end of an already terminated %rep block,
2115 * we should ignore all directives except for condition
2118 if (((istk
->conds
&& !emitting(istk
->conds
->state
)) ||
2119 (istk
->mstk
&& !istk
->mstk
->in_progress
)) && !is_condition(i
)) {
2120 return NO_DIRECTIVE_FOUND
;
2124 * If we're defining a macro or reading a %rep block, we should
2125 * ignore all directives except for %macro/%imacro (which nest),
2126 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2127 * If we're in a %rep block, another %rep nests, so should be let through.
2129 if (defining
&& i
!= PP_MACRO
&& i
!= PP_IMACRO
&&
2130 i
!= PP_RMACRO
&& i
!= PP_IRMACRO
&&
2131 i
!= PP_ENDMACRO
&& i
!= PP_ENDM
&&
2132 (defining
->name
|| (i
!= PP_ENDREP
&& i
!= PP_REP
))) {
2133 return NO_DIRECTIVE_FOUND
;
2137 if (i
== PP_MACRO
|| i
== PP_IMACRO
||
2138 i
== PP_RMACRO
|| i
== PP_IRMACRO
) {
2140 return NO_DIRECTIVE_FOUND
;
2141 } else if (nested_mac_count
> 0) {
2142 if (i
== PP_ENDMACRO
) {
2144 return NO_DIRECTIVE_FOUND
;
2147 if (!defining
->name
) {
2150 return NO_DIRECTIVE_FOUND
;
2151 } else if (nested_rep_count
> 0) {
2152 if (i
== PP_ENDREP
) {
2154 return NO_DIRECTIVE_FOUND
;
2162 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2164 return NO_DIRECTIVE_FOUND
; /* didn't get it */
2167 /* Directive to tell NASM what the default stack size is. The
2168 * default is for a 16-bit stack, and this can be overriden with
2171 tline
= tline
->next
;
2172 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2173 tline
= tline
->next
;
2174 if (!tline
|| tline
->type
!= TOK_ID
) {
2175 error(ERR_NONFATAL
, "`%%stacksize' missing size parameter");
2176 free_tlist(origline
);
2177 return DIRECTIVE_FOUND
;
2179 if (nasm_stricmp(tline
->text
, "flat") == 0) {
2180 /* All subsequent ARG directives are for a 32-bit stack */
2182 StackPointer
= "ebp";
2185 } else if (nasm_stricmp(tline
->text
, "flat64") == 0) {
2186 /* All subsequent ARG directives are for a 64-bit stack */
2188 StackPointer
= "rbp";
2191 } else if (nasm_stricmp(tline
->text
, "large") == 0) {
2192 /* All subsequent ARG directives are for a 16-bit stack,
2193 * far function call.
2196 StackPointer
= "bp";
2199 } else if (nasm_stricmp(tline
->text
, "small") == 0) {
2200 /* All subsequent ARG directives are for a 16-bit stack,
2201 * far function call. We don't support near functions.
2204 StackPointer
= "bp";
2208 error(ERR_NONFATAL
, "`%%stacksize' invalid size type");
2209 free_tlist(origline
);
2210 return DIRECTIVE_FOUND
;
2212 free_tlist(origline
);
2213 return DIRECTIVE_FOUND
;
2216 /* TASM like ARG directive to define arguments to functions, in
2217 * the following form:
2219 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2223 char *arg
, directive
[256];
2224 int size
= StackSize
;
2226 /* Find the argument name */
2227 tline
= tline
->next
;
2228 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2229 tline
= tline
->next
;
2230 if (!tline
|| tline
->type
!= TOK_ID
) {
2231 error(ERR_NONFATAL
, "`%%arg' missing argument parameter");
2232 free_tlist(origline
);
2233 return DIRECTIVE_FOUND
;
2237 /* Find the argument size type */
2238 tline
= tline
->next
;
2239 if (!tline
|| tline
->type
!= TOK_OTHER
2240 || tline
->text
[0] != ':') {
2242 "Syntax error processing `%%arg' directive");
2243 free_tlist(origline
);
2244 return DIRECTIVE_FOUND
;
2246 tline
= tline
->next
;
2247 if (!tline
|| tline
->type
!= TOK_ID
) {
2248 error(ERR_NONFATAL
, "`%%arg' missing size type parameter");
2249 free_tlist(origline
);
2250 return DIRECTIVE_FOUND
;
2253 /* Allow macro expansion of type parameter */
2254 tt
= tokenize(tline
->text
);
2255 tt
= expand_smacro(tt
);
2256 size
= parse_size(tt
->text
);
2259 "Invalid size type for `%%arg' missing directive");
2261 free_tlist(origline
);
2262 return DIRECTIVE_FOUND
;
2266 /* Round up to even stack slots */
2267 size
= ALIGN(size
, StackSize
);
2269 /* Now define the macro for the argument */
2270 snprintf(directive
, sizeof(directive
), "%%define %s (%s+%d)",
2271 arg
, StackPointer
, offset
);
2272 do_directive(tokenize(directive
));
2275 /* Move to the next argument in the list */
2276 tline
= tline
->next
;
2277 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2278 tline
= tline
->next
;
2279 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2281 free_tlist(origline
);
2282 return DIRECTIVE_FOUND
;
2285 /* TASM like LOCAL directive to define local variables for a
2286 * function, in the following form:
2288 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2290 * The '= LocalSize' at the end is ignored by NASM, but is
2291 * required by TASM to define the local parameter size (and used
2292 * by the TASM macro package).
2294 offset
= LocalOffset
;
2296 char *local
, directive
[256];
2297 int size
= StackSize
;
2299 /* Find the argument name */
2300 tline
= tline
->next
;
2301 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2302 tline
= tline
->next
;
2303 if (!tline
|| tline
->type
!= TOK_ID
) {
2305 "`%%local' missing argument parameter");
2306 free_tlist(origline
);
2307 return DIRECTIVE_FOUND
;
2309 local
= tline
->text
;
2311 /* Find the argument size type */
2312 tline
= tline
->next
;
2313 if (!tline
|| tline
->type
!= TOK_OTHER
2314 || tline
->text
[0] != ':') {
2316 "Syntax error processing `%%local' directive");
2317 free_tlist(origline
);
2318 return DIRECTIVE_FOUND
;
2320 tline
= tline
->next
;
2321 if (!tline
|| tline
->type
!= TOK_ID
) {
2323 "`%%local' missing size type parameter");
2324 free_tlist(origline
);
2325 return DIRECTIVE_FOUND
;
2328 /* Allow macro expansion of type parameter */
2329 tt
= tokenize(tline
->text
);
2330 tt
= expand_smacro(tt
);
2331 size
= parse_size(tt
->text
);
2334 "Invalid size type for `%%local' missing directive");
2336 free_tlist(origline
);
2337 return DIRECTIVE_FOUND
;
2341 /* Round up to even stack slots */
2342 size
= ALIGN(size
, StackSize
);
2344 offset
+= size
; /* Negative offset, increment before */
2346 /* Now define the macro for the argument */
2347 snprintf(directive
, sizeof(directive
), "%%define %s (%s-%d)",
2348 local
, StackPointer
, offset
);
2349 do_directive(tokenize(directive
));
2351 /* Now define the assign to setup the enter_c macro correctly */
2352 snprintf(directive
, sizeof(directive
),
2353 "%%assign %%$localsize %%$localsize+%d", size
);
2354 do_directive(tokenize(directive
));
2356 /* Move to the next argument in the list */
2357 tline
= tline
->next
;
2358 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2359 tline
= tline
->next
;
2360 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2361 LocalOffset
= offset
;
2362 free_tlist(origline
);
2363 return DIRECTIVE_FOUND
;
2367 error(ERR_WARNING
|ERR_PASS1
,
2368 "trailing garbage after `%%clear' ignored");
2371 free_tlist(origline
);
2372 return DIRECTIVE_FOUND
;
2375 t
= tline
->next
= expand_smacro(tline
->next
);
2377 if (!t
|| (t
->type
!= TOK_STRING
&&
2378 t
->type
!= TOK_INTERNAL_STRING
)) {
2379 error(ERR_NONFATAL
, "`%%depend' expects a file name");
2380 free_tlist(origline
);
2381 return DIRECTIVE_FOUND
; /* but we did _something_ */
2384 error(ERR_WARNING
|ERR_PASS1
,
2385 "trailing garbage after `%%depend' ignored");
2387 if (t
->type
!= TOK_INTERNAL_STRING
)
2388 nasm_unquote_cstr(p
, i
);
2389 if (dephead
&& !in_list(*dephead
, p
)) {
2390 StrList
*sl
= nasm_malloc(strlen(p
)+1+sizeof sl
->next
);
2394 deptail
= &sl
->next
;
2396 free_tlist(origline
);
2397 return DIRECTIVE_FOUND
;
2400 t
= tline
->next
= expand_smacro(tline
->next
);
2403 if (!t
|| (t
->type
!= TOK_STRING
&&
2404 t
->type
!= TOK_INTERNAL_STRING
)) {
2405 error(ERR_NONFATAL
, "`%%include' expects a file name");
2406 free_tlist(origline
);
2407 return DIRECTIVE_FOUND
; /* but we did _something_ */
2410 error(ERR_WARNING
|ERR_PASS1
,
2411 "trailing garbage after `%%include' ignored");
2413 if (t
->type
!= TOK_INTERNAL_STRING
)
2414 nasm_unquote_cstr(p
, i
);
2415 inc
= nasm_malloc(sizeof(Include
));
2418 inc
->fp
= inc_fopen(p
, dephead
, &deptail
, pass
== 0);
2420 /* -MG given but file not found */
2423 inc
->fname
= src_set_fname(nasm_strdup(p
));
2424 inc
->lineno
= src_set_linnum(0);
2426 inc
->expansion
= NULL
;
2429 list
->uplevel(LIST_INCLUDE
);
2431 free_tlist(origline
);
2432 return DIRECTIVE_FOUND
;
2436 static macros_t
*use_pkg
;
2437 const char *pkg_macro
= NULL
;
2439 tline
= tline
->next
;
2441 tline
= expand_id(tline
);
2443 if (!tline
|| (tline
->type
!= TOK_STRING
&&
2444 tline
->type
!= TOK_INTERNAL_STRING
&&
2445 tline
->type
!= TOK_ID
)) {
2446 error(ERR_NONFATAL
, "`%%use' expects a package name");
2447 free_tlist(origline
);
2448 return DIRECTIVE_FOUND
; /* but we did _something_ */
2451 error(ERR_WARNING
|ERR_PASS1
,
2452 "trailing garbage after `%%use' ignored");
2453 if (tline
->type
== TOK_STRING
)
2454 nasm_unquote_cstr(tline
->text
, i
);
2455 use_pkg
= nasm_stdmac_find_package(tline
->text
);
2457 error(ERR_NONFATAL
, "unknown `%%use' package: %s", tline
->text
);
2459 pkg_macro
= (char *)use_pkg
+ 1; /* The first string will be <%define>__USE_*__ */
2460 if (use_pkg
&& ! smacro_defined(NULL
, pkg_macro
, 0, NULL
, true)) {
2461 /* Not already included, go ahead and include it */
2462 stdmacpos
= use_pkg
;
2464 free_tlist(origline
);
2465 return DIRECTIVE_FOUND
;
2470 tline
= tline
->next
;
2472 tline
= expand_id(tline
);
2474 if (!tok_type_(tline
, TOK_ID
)) {
2475 error(ERR_NONFATAL
, "`%s' expects a context identifier",
2477 free_tlist(origline
);
2478 return DIRECTIVE_FOUND
; /* but we did _something_ */
2481 error(ERR_WARNING
|ERR_PASS1
,
2482 "trailing garbage after `%s' ignored",
2484 p
= nasm_strdup(tline
->text
);
2486 p
= NULL
; /* Anonymous */
2490 ctx
= nasm_malloc(sizeof(Context
));
2492 hash_init(&ctx
->localmac
, HASH_SMALL
);
2494 ctx
->number
= unique
++;
2499 error(ERR_NONFATAL
, "`%s': context stack is empty",
2501 } else if (i
== PP_POP
) {
2502 if (p
&& (!cstk
->name
|| nasm_stricmp(p
, cstk
->name
)))
2503 error(ERR_NONFATAL
, "`%%pop' in wrong context: %s, "
2505 cstk
->name
? cstk
->name
: "anonymous", p
);
2510 nasm_free(cstk
->name
);
2516 free_tlist(origline
);
2517 return DIRECTIVE_FOUND
;
2519 severity
= ERR_FATAL
;
2522 severity
= ERR_NONFATAL
;
2525 severity
= ERR_WARNING
|ERR_WARN_USER
;
2530 /* Only error out if this is the final pass */
2531 if (pass
!= 2 && i
!= PP_FATAL
)
2532 return DIRECTIVE_FOUND
;
2534 tline
->next
= expand_smacro(tline
->next
);
2535 tline
= tline
->next
;
2537 t
= tline
? tline
->next
: NULL
;
2539 if (tok_type_(tline
, TOK_STRING
) && !t
) {
2540 /* The line contains only a quoted string */
2542 nasm_unquote(p
, NULL
); /* Ignore NUL character truncation */
2543 error(severity
, "%s", p
);
2545 /* Not a quoted string, or more than a quoted string */
2546 p
= detoken(tline
, false);
2547 error(severity
, "%s", p
);
2550 free_tlist(origline
);
2551 return DIRECTIVE_FOUND
;
2555 if (istk
->conds
&& !emitting(istk
->conds
->state
))
2558 j
= if_condition(tline
->next
, i
);
2559 tline
->next
= NULL
; /* it got freed */
2560 j
= j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2562 cond
= nasm_malloc(sizeof(Cond
));
2563 cond
->next
= istk
->conds
;
2567 istk
->mstk
->condcnt
++;
2568 free_tlist(origline
);
2569 return DIRECTIVE_FOUND
;
2573 error(ERR_FATAL
, "`%s': no matching `%%if'", pp_directives
[i
]);
2574 switch(istk
->conds
->state
) {
2576 istk
->conds
->state
= COND_DONE
;
2583 case COND_ELSE_TRUE
:
2584 case COND_ELSE_FALSE
:
2585 error_precond(ERR_WARNING
|ERR_PASS1
,
2586 "`%%elif' after `%%else' ignored");
2587 istk
->conds
->state
= COND_NEVER
;
2592 * IMPORTANT: In the case of %if, we will already have
2593 * called expand_mmac_params(); however, if we're
2594 * processing an %elif we must have been in a
2595 * non-emitting mode, which would have inhibited
2596 * the normal invocation of expand_mmac_params().
2597 * Therefore, we have to do it explicitly here.
2599 j
= if_condition(expand_mmac_params(tline
->next
), i
);
2600 tline
->next
= NULL
; /* it got freed */
2601 istk
->conds
->state
=
2602 j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2605 free_tlist(origline
);
2606 return DIRECTIVE_FOUND
;
2610 error_precond(ERR_WARNING
|ERR_PASS1
,
2611 "trailing garbage after `%%else' ignored");
2613 error(ERR_FATAL
, "`%%else': no matching `%%if'");
2614 switch(istk
->conds
->state
) {
2617 istk
->conds
->state
= COND_ELSE_FALSE
;
2624 istk
->conds
->state
= COND_ELSE_TRUE
;
2627 case COND_ELSE_TRUE
:
2628 case COND_ELSE_FALSE
:
2629 error_precond(ERR_WARNING
|ERR_PASS1
,
2630 "`%%else' after `%%else' ignored.");
2631 istk
->conds
->state
= COND_NEVER
;
2634 free_tlist(origline
);
2635 return DIRECTIVE_FOUND
;
2639 error_precond(ERR_WARNING
|ERR_PASS1
,
2640 "trailing garbage after `%%endif' ignored");
2642 error(ERR_FATAL
, "`%%endif': no matching `%%if'");
2644 istk
->conds
= cond
->next
;
2647 istk
->mstk
->condcnt
--;
2648 free_tlist(origline
);
2649 return DIRECTIVE_FOUND
;
2656 error(ERR_FATAL
, "`%s': already defining a macro",
2658 return DIRECTIVE_FOUND
;
2660 defining
= nasm_malloc(sizeof(MMacro
));
2661 defining
->max_depth
=
2662 (i
== PP_RMACRO
) || (i
== PP_IRMACRO
) ? DEADMAN_LIMIT
: 0;
2663 defining
->casesense
= (i
== PP_MACRO
) || (i
== PP_RMACRO
);
2664 if (!parse_mmacro_spec(tline
, defining
, pp_directives
[i
])) {
2665 nasm_free(defining
);
2667 return DIRECTIVE_FOUND
;
2670 mmac
= (MMacro
*) hash_findix(&mmacros
, defining
->name
);
2672 if (!strcmp(mmac
->name
, defining
->name
) &&
2673 (mmac
->nparam_min
<= defining
->nparam_max
2675 && (defining
->nparam_min
<= mmac
->nparam_max
2677 error(ERR_WARNING
|ERR_PASS1
,
2678 "redefining multi-line macro `%s'", defining
->name
);
2679 return DIRECTIVE_FOUND
;
2683 free_tlist(origline
);
2684 return DIRECTIVE_FOUND
;
2688 if (! (defining
&& defining
->name
)) {
2689 error(ERR_NONFATAL
, "`%s': not defining a macro", tline
->text
);
2690 return DIRECTIVE_FOUND
;
2692 mmhead
= (MMacro
**) hash_findi_add(&mmacros
, defining
->name
);
2693 defining
->next
= *mmhead
;
2696 free_tlist(origline
);
2697 return DIRECTIVE_FOUND
;
2701 * We must search along istk->expansion until we hit a
2702 * macro-end marker for a macro with a name. Then we
2703 * bypass all lines between exitmacro and endmacro.
2705 list_for_each(l
, istk
->expansion
)
2706 if (l
->finishes
&& l
->finishes
->name
)
2711 * Remove all conditional entries relative to this
2712 * macro invocation. (safe to do in this context)
2714 for ( ; l
->finishes
->condcnt
> 0; l
->finishes
->condcnt
--) {
2716 istk
->conds
= cond
->next
;
2719 istk
->expansion
= l
;
2721 error(ERR_NONFATAL
, "`%%exitmacro' not within `%%macro' block");
2723 free_tlist(origline
);
2724 return DIRECTIVE_FOUND
;
2732 spec
.casesense
= (i
== PP_UNMACRO
);
2733 if (!parse_mmacro_spec(tline
, &spec
, pp_directives
[i
])) {
2734 return DIRECTIVE_FOUND
;
2736 mmac_p
= (MMacro
**) hash_findi(&mmacros
, spec
.name
, NULL
);
2737 while (mmac_p
&& *mmac_p
) {
2739 if (mmac
->casesense
== spec
.casesense
&&
2740 !mstrcmp(mmac
->name
, spec
.name
, spec
.casesense
) &&
2741 mmac
->nparam_min
== spec
.nparam_min
&&
2742 mmac
->nparam_max
== spec
.nparam_max
&&
2743 mmac
->plus
== spec
.plus
) {
2744 *mmac_p
= mmac
->next
;
2747 mmac_p
= &mmac
->next
;
2750 free_tlist(origline
);
2751 free_tlist(spec
.dlist
);
2752 return DIRECTIVE_FOUND
;
2756 if (tline
->next
&& tline
->next
->type
== TOK_WHITESPACE
)
2757 tline
= tline
->next
;
2759 free_tlist(origline
);
2760 error(ERR_NONFATAL
, "`%%rotate' missing rotate count");
2761 return DIRECTIVE_FOUND
;
2763 t
= expand_smacro(tline
->next
);
2765 free_tlist(origline
);
2768 tokval
.t_type
= TOKEN_INVALID
;
2770 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2773 return DIRECTIVE_FOUND
;
2775 error(ERR_WARNING
|ERR_PASS1
,
2776 "trailing garbage after expression ignored");
2777 if (!is_simple(evalresult
)) {
2778 error(ERR_NONFATAL
, "non-constant value given to `%%rotate'");
2779 return DIRECTIVE_FOUND
;
2782 while (mmac
&& !mmac
->name
) /* avoid mistaking %reps for macros */
2783 mmac
= mmac
->next_active
;
2785 error(ERR_NONFATAL
, "`%%rotate' invoked outside a macro call");
2786 } else if (mmac
->nparam
== 0) {
2788 "`%%rotate' invoked within macro without parameters");
2790 int rotate
= mmac
->rotate
+ reloc_value(evalresult
);
2792 rotate
%= (int)mmac
->nparam
;
2794 rotate
+= mmac
->nparam
;
2796 mmac
->rotate
= rotate
;
2798 return DIRECTIVE_FOUND
;
2803 tline
= tline
->next
;
2804 } while (tok_type_(tline
, TOK_WHITESPACE
));
2806 if (tok_type_(tline
, TOK_ID
) &&
2807 nasm_stricmp(tline
->text
, ".nolist") == 0) {
2810 tline
= tline
->next
;
2811 } while (tok_type_(tline
, TOK_WHITESPACE
));
2815 t
= expand_smacro(tline
);
2817 tokval
.t_type
= TOKEN_INVALID
;
2819 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2821 free_tlist(origline
);
2822 return DIRECTIVE_FOUND
;
2825 error(ERR_WARNING
|ERR_PASS1
,
2826 "trailing garbage after expression ignored");
2827 if (!is_simple(evalresult
)) {
2828 error(ERR_NONFATAL
, "non-constant value given to `%%rep'");
2829 return DIRECTIVE_FOUND
;
2831 count
= reloc_value(evalresult
) + 1;
2833 error(ERR_NONFATAL
, "`%%rep' expects a repeat count");
2836 free_tlist(origline
);
2838 tmp_defining
= defining
;
2839 defining
= nasm_malloc(sizeof(MMacro
));
2840 defining
->prev
= NULL
;
2841 defining
->name
= NULL
; /* flags this macro as a %rep block */
2842 defining
->casesense
= false;
2843 defining
->plus
= false;
2844 defining
->nolist
= nolist
;
2845 defining
->in_progress
= count
;
2846 defining
->max_depth
= 0;
2847 defining
->nparam_min
= defining
->nparam_max
= 0;
2848 defining
->defaults
= NULL
;
2849 defining
->dlist
= NULL
;
2850 defining
->expansion
= NULL
;
2851 defining
->next_active
= istk
->mstk
;
2852 defining
->rep_nest
= tmp_defining
;
2853 return DIRECTIVE_FOUND
;
2856 if (!defining
|| defining
->name
) {
2857 error(ERR_NONFATAL
, "`%%endrep': no matching `%%rep'");
2858 return DIRECTIVE_FOUND
;
2862 * Now we have a "macro" defined - although it has no name
2863 * and we won't be entering it in the hash tables - we must
2864 * push a macro-end marker for it on to istk->expansion.
2865 * After that, it will take care of propagating itself (a
2866 * macro-end marker line for a macro which is really a %rep
2867 * block will cause the macro to be re-expanded, complete
2868 * with another macro-end marker to ensure the process
2869 * continues) until the whole expansion is forcibly removed
2870 * from istk->expansion by a %exitrep.
2872 l
= nasm_malloc(sizeof(Line
));
2873 l
->next
= istk
->expansion
;
2874 l
->finishes
= defining
;
2876 istk
->expansion
= l
;
2878 istk
->mstk
= defining
;
2880 list
->uplevel(defining
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
2881 tmp_defining
= defining
;
2882 defining
= defining
->rep_nest
;
2883 free_tlist(origline
);
2884 return DIRECTIVE_FOUND
;
2888 * We must search along istk->expansion until we hit a
2889 * macro-end marker for a macro with no name. Then we set
2890 * its `in_progress' flag to 0.
2892 list_for_each(l
, istk
->expansion
)
2893 if (l
->finishes
&& !l
->finishes
->name
)
2897 l
->finishes
->in_progress
= 1;
2899 error(ERR_NONFATAL
, "`%%exitrep' not within `%%rep' block");
2900 free_tlist(origline
);
2901 return DIRECTIVE_FOUND
;
2907 casesense
= (i
== PP_DEFINE
|| i
== PP_XDEFINE
);
2909 tline
= tline
->next
;
2911 tline
= expand_id(tline
);
2912 if (!tline
|| (tline
->type
!= TOK_ID
&&
2913 (tline
->type
!= TOK_PREPROC_ID
||
2914 tline
->text
[1] != '$'))) {
2915 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
2917 free_tlist(origline
);
2918 return DIRECTIVE_FOUND
;
2921 ctx
= get_ctx(tline
->text
, &mname
, false);
2923 param_start
= tline
= tline
->next
;
2926 /* Expand the macro definition now for %xdefine and %ixdefine */
2927 if ((i
== PP_XDEFINE
) || (i
== PP_IXDEFINE
))
2928 tline
= expand_smacro(tline
);
2930 if (tok_is_(tline
, "(")) {
2932 * This macro has parameters.
2935 tline
= tline
->next
;
2939 error(ERR_NONFATAL
, "parameter identifier expected");
2940 free_tlist(origline
);
2941 return DIRECTIVE_FOUND
;
2943 if (tline
->type
!= TOK_ID
) {
2945 "`%s': parameter identifier expected",
2947 free_tlist(origline
);
2948 return DIRECTIVE_FOUND
;
2950 tline
->type
= TOK_SMAC_PARAM
+ nparam
++;
2951 tline
= tline
->next
;
2953 if (tok_is_(tline
, ",")) {
2954 tline
= tline
->next
;
2956 if (!tok_is_(tline
, ")")) {
2958 "`)' expected to terminate macro template");
2959 free_tlist(origline
);
2960 return DIRECTIVE_FOUND
;
2966 tline
= tline
->next
;
2968 if (tok_type_(tline
, TOK_WHITESPACE
))
2969 last
= tline
, tline
= tline
->next
;
2974 if (t
->type
== TOK_ID
) {
2975 list_for_each(tt
, param_start
)
2976 if (tt
->type
>= TOK_SMAC_PARAM
&&
2977 !strcmp(tt
->text
, t
->text
))
2981 t
->next
= macro_start
;
2986 * Good. We now have a macro name, a parameter count, and a
2987 * token list (in reverse order) for an expansion. We ought
2988 * to be OK just to create an SMacro, store it, and let
2989 * free_tlist have the rest of the line (which we have
2990 * carefully re-terminated after chopping off the expansion
2993 define_smacro(ctx
, mname
, casesense
, nparam
, macro_start
);
2994 free_tlist(origline
);
2995 return DIRECTIVE_FOUND
;
2998 tline
= tline
->next
;
3000 tline
= expand_id(tline
);
3001 if (!tline
|| (tline
->type
!= TOK_ID
&&
3002 (tline
->type
!= TOK_PREPROC_ID
||
3003 tline
->text
[1] != '$'))) {
3004 error(ERR_NONFATAL
, "`%%undef' expects a macro identifier");
3005 free_tlist(origline
);
3006 return DIRECTIVE_FOUND
;
3009 error(ERR_WARNING
|ERR_PASS1
,
3010 "trailing garbage after macro name ignored");
3013 /* Find the context that symbol belongs to */
3014 ctx
= get_ctx(tline
->text
, &mname
, false);
3015 undef_smacro(ctx
, mname
);
3016 free_tlist(origline
);
3017 return DIRECTIVE_FOUND
;
3021 casesense
= (i
== PP_DEFSTR
);
3023 tline
= tline
->next
;
3025 tline
= expand_id(tline
);
3026 if (!tline
|| (tline
->type
!= TOK_ID
&&
3027 (tline
->type
!= TOK_PREPROC_ID
||
3028 tline
->text
[1] != '$'))) {
3029 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3031 free_tlist(origline
);
3032 return DIRECTIVE_FOUND
;
3035 ctx
= get_ctx(tline
->text
, &mname
, false);
3037 tline
= expand_smacro(tline
->next
);
3040 while (tok_type_(tline
, TOK_WHITESPACE
))
3041 tline
= delete_Token(tline
);
3043 p
= detoken(tline
, false);
3044 macro_start
= nasm_malloc(sizeof(*macro_start
));
3045 macro_start
->next
= NULL
;
3046 macro_start
->text
= nasm_quote(p
, strlen(p
));
3047 macro_start
->type
= TOK_STRING
;
3048 macro_start
->a
.mac
= NULL
;
3052 * We now have a macro name, an implicit parameter count of
3053 * zero, and a string token to use as an expansion. Create
3054 * and store an SMacro.
3056 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3057 free_tlist(origline
);
3058 return DIRECTIVE_FOUND
;
3062 casesense
= (i
== PP_DEFTOK
);
3064 tline
= tline
->next
;
3066 tline
= expand_id(tline
);
3067 if (!tline
|| (tline
->type
!= TOK_ID
&&
3068 (tline
->type
!= TOK_PREPROC_ID
||
3069 tline
->text
[1] != '$'))) {
3071 "`%s' expects a macro identifier as first parameter",
3073 free_tlist(origline
);
3074 return DIRECTIVE_FOUND
;
3076 ctx
= get_ctx(tline
->text
, &mname
, false);
3078 tline
= expand_smacro(tline
->next
);
3082 while (tok_type_(t
, TOK_WHITESPACE
))
3084 /* t should now point to the string */
3085 if (t
->type
!= TOK_STRING
) {
3087 "`%s` requires string as second parameter",
3090 free_tlist(origline
);
3091 return DIRECTIVE_FOUND
;
3094 nasm_unquote_cstr(t
->text
, i
);
3095 macro_start
= tokenize(t
->text
);
3098 * We now have a macro name, an implicit parameter count of
3099 * zero, and a numeric token to use as an expansion. Create
3100 * and store an SMacro.
3102 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3104 free_tlist(origline
);
3105 return DIRECTIVE_FOUND
;
3110 StrList
*xsl
= NULL
;
3111 StrList
**xst
= &xsl
;
3115 tline
= tline
->next
;
3117 tline
= expand_id(tline
);
3118 if (!tline
|| (tline
->type
!= TOK_ID
&&
3119 (tline
->type
!= TOK_PREPROC_ID
||
3120 tline
->text
[1] != '$'))) {
3122 "`%%pathsearch' expects a macro identifier as first parameter");
3123 free_tlist(origline
);
3124 return DIRECTIVE_FOUND
;
3126 ctx
= get_ctx(tline
->text
, &mname
, false);
3128 tline
= expand_smacro(tline
->next
);
3132 while (tok_type_(t
, TOK_WHITESPACE
))
3135 if (!t
|| (t
->type
!= TOK_STRING
&&
3136 t
->type
!= TOK_INTERNAL_STRING
)) {
3137 error(ERR_NONFATAL
, "`%%pathsearch' expects a file name");
3139 free_tlist(origline
);
3140 return DIRECTIVE_FOUND
; /* but we did _something_ */
3143 error(ERR_WARNING
|ERR_PASS1
,
3144 "trailing garbage after `%%pathsearch' ignored");
3146 if (t
->type
!= TOK_INTERNAL_STRING
)
3147 nasm_unquote(p
, NULL
);
3149 fp
= inc_fopen(p
, &xsl
, &xst
, true);
3152 fclose(fp
); /* Don't actually care about the file */
3154 macro_start
= nasm_malloc(sizeof(*macro_start
));
3155 macro_start
->next
= NULL
;
3156 macro_start
->text
= nasm_quote(p
, strlen(p
));
3157 macro_start
->type
= TOK_STRING
;
3158 macro_start
->a
.mac
= NULL
;
3163 * We now have a macro name, an implicit parameter count of
3164 * zero, and a string token to use as an expansion. Create
3165 * and store an SMacro.
3167 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3169 free_tlist(origline
);
3170 return DIRECTIVE_FOUND
;
3176 tline
= tline
->next
;
3178 tline
= expand_id(tline
);
3179 if (!tline
|| (tline
->type
!= TOK_ID
&&
3180 (tline
->type
!= TOK_PREPROC_ID
||
3181 tline
->text
[1] != '$'))) {
3183 "`%%strlen' expects a macro identifier as first parameter");
3184 free_tlist(origline
);
3185 return DIRECTIVE_FOUND
;
3187 ctx
= get_ctx(tline
->text
, &mname
, false);
3189 tline
= expand_smacro(tline
->next
);
3193 while (tok_type_(t
, TOK_WHITESPACE
))
3195 /* t should now point to the string */
3196 if (t
->type
!= TOK_STRING
) {
3198 "`%%strlen` requires string as second parameter");
3200 free_tlist(origline
);
3201 return DIRECTIVE_FOUND
;
3204 macro_start
= nasm_malloc(sizeof(*macro_start
));
3205 macro_start
->next
= NULL
;
3206 make_tok_num(macro_start
, nasm_unquote(t
->text
, NULL
));
3207 macro_start
->a
.mac
= NULL
;
3210 * We now have a macro name, an implicit parameter count of
3211 * zero, and a numeric token to use as an expansion. Create
3212 * and store an SMacro.
3214 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3216 free_tlist(origline
);
3217 return DIRECTIVE_FOUND
;
3222 tline
= tline
->next
;
3224 tline
= expand_id(tline
);
3225 if (!tline
|| (tline
->type
!= TOK_ID
&&
3226 (tline
->type
!= TOK_PREPROC_ID
||
3227 tline
->text
[1] != '$'))) {
3229 "`%%strcat' expects a macro identifier as first parameter");
3230 free_tlist(origline
);
3231 return DIRECTIVE_FOUND
;
3233 ctx
= get_ctx(tline
->text
, &mname
, false);
3235 tline
= expand_smacro(tline
->next
);
3239 list_for_each(t
, tline
) {
3241 case TOK_WHITESPACE
:
3244 len
+= t
->a
.len
= nasm_unquote(t
->text
, NULL
);
3247 if (!strcmp(t
->text
, ",")) /* permit comma separators */
3249 /* else fall through */
3252 "non-string passed to `%%strcat' (%d)", t
->type
);
3254 free_tlist(origline
);
3255 return DIRECTIVE_FOUND
;
3259 p
= pp
= nasm_malloc(len
);
3260 list_for_each(t
, tline
) {
3261 if (t
->type
== TOK_STRING
) {
3262 memcpy(p
, t
->text
, t
->a
.len
);
3268 * We now have a macro name, an implicit parameter count of
3269 * zero, and a numeric token to use as an expansion. Create
3270 * and store an SMacro.
3272 macro_start
= new_Token(NULL
, TOK_STRING
, NULL
, 0);
3273 macro_start
->text
= nasm_quote(pp
, len
);
3275 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3277 free_tlist(origline
);
3278 return DIRECTIVE_FOUND
;
3287 tline
= tline
->next
;
3289 tline
= expand_id(tline
);
3290 if (!tline
|| (tline
->type
!= TOK_ID
&&
3291 (tline
->type
!= TOK_PREPROC_ID
||
3292 tline
->text
[1] != '$'))) {
3294 "`%%substr' expects a macro identifier as first parameter");
3295 free_tlist(origline
);
3296 return DIRECTIVE_FOUND
;
3298 ctx
= get_ctx(tline
->text
, &mname
, false);
3300 tline
= expand_smacro(tline
->next
);
3304 while (tok_type_(t
, TOK_WHITESPACE
))
3307 /* t should now point to the string */
3308 if (t
->type
!= TOK_STRING
) {
3310 "`%%substr` requires string as second parameter");
3312 free_tlist(origline
);
3313 return DIRECTIVE_FOUND
;
3318 tokval
.t_type
= TOKEN_INVALID
;
3319 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3323 free_tlist(origline
);
3324 return DIRECTIVE_FOUND
;
3325 } else if (!is_simple(evalresult
)) {
3326 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3328 free_tlist(origline
);
3329 return DIRECTIVE_FOUND
;
3331 a1
= evalresult
->value
-1;
3333 while (tok_type_(tt
, TOK_WHITESPACE
))
3336 a2
= 1; /* Backwards compatibility: one character */
3338 tokval
.t_type
= TOKEN_INVALID
;
3339 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3343 free_tlist(origline
);
3344 return DIRECTIVE_FOUND
;
3345 } else if (!is_simple(evalresult
)) {
3346 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3348 free_tlist(origline
);
3349 return DIRECTIVE_FOUND
;
3351 a2
= evalresult
->value
;
3354 len
= nasm_unquote(t
->text
, NULL
);
3357 if (a1
+a2
> (int64_t)len
)
3360 macro_start
= nasm_malloc(sizeof(*macro_start
));
3361 macro_start
->next
= NULL
;
3362 macro_start
->text
= nasm_quote((a1
< 0) ? "" : t
->text
+a1
, a2
);
3363 macro_start
->type
= TOK_STRING
;
3364 macro_start
->a
.mac
= NULL
;
3367 * We now have a macro name, an implicit parameter count of
3368 * zero, and a numeric token to use as an expansion. Create
3369 * and store an SMacro.
3371 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3373 free_tlist(origline
);
3374 return DIRECTIVE_FOUND
;
3379 casesense
= (i
== PP_ASSIGN
);
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 "`%%%sassign' expects a macro identifier",
3389 (i
== PP_IASSIGN
? "i" : ""));
3390 free_tlist(origline
);
3391 return DIRECTIVE_FOUND
;
3393 ctx
= get_ctx(tline
->text
, &mname
, false);
3395 tline
= expand_smacro(tline
->next
);
3400 tokval
.t_type
= TOKEN_INVALID
;
3402 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
3405 free_tlist(origline
);
3406 return DIRECTIVE_FOUND
;
3410 error(ERR_WARNING
|ERR_PASS1
,
3411 "trailing garbage after expression ignored");
3413 if (!is_simple(evalresult
)) {
3415 "non-constant value given to `%%%sassign'",
3416 (i
== PP_IASSIGN
? "i" : ""));
3417 free_tlist(origline
);
3418 return DIRECTIVE_FOUND
;
3421 macro_start
= nasm_malloc(sizeof(*macro_start
));
3422 macro_start
->next
= NULL
;
3423 make_tok_num(macro_start
, reloc_value(evalresult
));
3424 macro_start
->a
.mac
= NULL
;
3427 * We now have a macro name, an implicit parameter count of
3428 * zero, and a numeric token to use as an expansion. Create
3429 * and store an SMacro.
3431 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3432 free_tlist(origline
);
3433 return DIRECTIVE_FOUND
;
3437 * Syntax is `%line nnn[+mmm] [filename]'
3439 tline
= tline
->next
;
3441 if (!tok_type_(tline
, TOK_NUMBER
)) {
3442 error(ERR_NONFATAL
, "`%%line' expects line number");
3443 free_tlist(origline
);
3444 return DIRECTIVE_FOUND
;
3446 k
= readnum(tline
->text
, &err
);
3448 tline
= tline
->next
;
3449 if (tok_is_(tline
, "+")) {
3450 tline
= tline
->next
;
3451 if (!tok_type_(tline
, TOK_NUMBER
)) {
3452 error(ERR_NONFATAL
, "`%%line' expects line increment");
3453 free_tlist(origline
);
3454 return DIRECTIVE_FOUND
;
3456 m
= readnum(tline
->text
, &err
);
3457 tline
= tline
->next
;
3463 nasm_free(src_set_fname(detoken(tline
, false)));
3465 free_tlist(origline
);
3466 return DIRECTIVE_FOUND
;
3470 "preprocessor directive `%s' not yet implemented",
3472 return DIRECTIVE_FOUND
;
3477 * Ensure that a macro parameter contains a condition code and
3478 * nothing else. Return the condition code index if so, or -1
3481 static int find_cc(Token
* t
)
3487 return -1; /* Probably a %+ without a space */
3490 if (t
->type
!= TOK_ID
)
3494 if (tt
&& (tt
->type
!= TOK_OTHER
|| strcmp(tt
->text
, ",")))
3498 j
= ARRAY_SIZE(conditions
);
3501 m
= nasm_stricmp(t
->text
, conditions
[k
]);
3516 static bool paste_tokens(Token
**head
, bool handle_paste_tokens
)
3518 Token
**tail
, *t
, *tt
;
3520 bool did_paste
= false;
3523 /* Now handle token pasting... */
3526 while ((t
= *tail
) && (tt
= t
->next
)) {
3528 case TOK_WHITESPACE
:
3529 if (tt
->type
== TOK_WHITESPACE
) {
3530 /* Zap adjacent whitespace tokens */
3531 t
->next
= delete_Token(tt
);
3533 /* Do not advance paste_head here */
3544 while (tt
&& (tt
->type
== TOK_ID
|| tt
->type
== TOK_PREPROC_ID
||
3545 tt
->type
== TOK_NUMBER
|| tt
->type
== TOK_FLOAT
||
3546 tt
->type
== TOK_OTHER
)) {
3547 len
+= strlen(tt
->text
);
3552 * Now tt points to the first token after
3553 * the potential paste area...
3555 if (tt
!= t
->next
) {
3556 /* We have at least two tokens... */
3557 len
+= strlen(t
->text
);
3558 p
= tmp
= nasm_malloc(len
+1);
3562 p
= strchr(p
, '\0');
3563 t
= delete_Token(t
);
3566 t
= *tail
= tokenize(tmp
);
3573 t
->next
= tt
; /* Attach the remaining token chain */
3581 case TOK_PASTE
: /* %+ */
3582 if (handle_paste_tokens
) {
3583 /* Zap %+ and whitespace tokens to the right */
3584 while (t
&& (t
->type
== TOK_WHITESPACE
||
3585 t
->type
== TOK_PASTE
))
3586 t
= *tail
= delete_Token(t
);
3587 if (!paste_head
|| !t
)
3588 break; /* Nothing to paste with */
3592 while (tok_type_(tt
, TOK_WHITESPACE
))
3593 tt
= t
->next
= delete_Token(tt
);
3596 tmp
= nasm_strcat(t
->text
, tt
->text
);
3598 tt
= delete_Token(tt
);
3599 t
= *tail
= tokenize(tmp
);
3605 t
->next
= tt
; /* Attach the remaining token chain */
3612 /* else fall through */
3615 if (!tok_type_(t
->next
, TOK_WHITESPACE
))
3624 * expands to a list of tokens from %{x:y}
3626 static Token
*expand_mmac_params_range(MMacro
*mac
, Token
*tline
, Token
***last
)
3628 Token
*t
= tline
, **tt
, *tm
, *head
;
3632 pos
= strchr(tline
->text
, ':');
3635 lst
= atoi(pos
+ 1);
3636 fst
= atoi(tline
->text
+ 1);
3639 * only macros params are accounted so
3640 * if someone passes %0 -- we reject such
3643 if (lst
== 0 || fst
== 0)
3646 /* the values should be sane */
3647 if ((fst
> (int)mac
->nparam
|| fst
< (-(int)mac
->nparam
)) ||
3648 (lst
> (int)mac
->nparam
|| lst
< (-(int)mac
->nparam
)))
3651 fst
= fst
< 0 ? fst
+ (int)mac
->nparam
+ 1: fst
;
3652 lst
= lst
< 0 ? lst
+ (int)mac
->nparam
+ 1: lst
;
3654 /* counted from zero */
3658 * it will be at least one token
3660 tm
= mac
->params
[(fst
+ mac
->rotate
) % mac
->nparam
];
3661 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3662 head
= t
, tt
= &t
->next
;
3664 for (i
= fst
+ 1; i
<= lst
; i
++) {
3665 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3666 *tt
= t
, tt
= &t
->next
;
3667 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3668 tm
= mac
->params
[j
];
3669 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3670 *tt
= t
, tt
= &t
->next
;
3673 for (i
= fst
- 1; i
>= lst
; i
--) {
3674 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3675 *tt
= t
, tt
= &t
->next
;
3676 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3677 tm
= mac
->params
[j
];
3678 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3679 *tt
= t
, tt
= &t
->next
;
3687 error(ERR_NONFATAL
, "`%%{%s}': macro parameters out of range",
3693 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3694 * %-n) and MMacro-local identifiers (%%foo) as well as
3695 * macro indirection (%[...]) and range (%{..:..}).
3697 static Token
*expand_mmac_params(Token
* tline
)
3699 Token
*t
, *tt
, **tail
, *thead
;
3700 bool changed
= false;
3707 if (tline
->type
== TOK_PREPROC_ID
&&
3708 (((tline
->text
[1] == '+' || tline
->text
[1] == '-') && tline
->text
[2]) ||
3709 (tline
->text
[1] >= '0' && tline
->text
[1] <= '9') ||
3710 tline
->text
[1] == '%')) {
3712 int type
= 0, cc
; /* type = 0 to placate optimisers */
3719 tline
= tline
->next
;
3722 while (mac
&& !mac
->name
) /* avoid mistaking %reps for macros */
3723 mac
= mac
->next_active
;
3725 error(ERR_NONFATAL
, "`%s': not in a macro call", t
->text
);
3727 pos
= strchr(t
->text
, ':');
3729 switch (t
->text
[1]) {
3731 * We have to make a substitution of one of the
3732 * forms %1, %-1, %+1, %%foo, %0.
3736 snprintf(tmpbuf
, sizeof(tmpbuf
), "%d", mac
->nparam
);
3737 text
= nasm_strdup(tmpbuf
);
3741 snprintf(tmpbuf
, sizeof(tmpbuf
), "..@%"PRIu64
".",
3743 text
= nasm_strcat(tmpbuf
, t
->text
+ 2);
3746 n
= atoi(t
->text
+ 2) - 1;
3747 if (n
>= mac
->nparam
)
3750 if (mac
->nparam
> 1)
3751 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3752 tt
= mac
->params
[n
];
3757 "macro parameter %d is not a condition code",
3762 if (inverse_ccs
[cc
] == -1) {
3764 "condition code `%s' is not invertible",
3768 text
= nasm_strdup(conditions
[inverse_ccs
[cc
]]);
3772 n
= atoi(t
->text
+ 2) - 1;
3773 if (n
>= mac
->nparam
)
3776 if (mac
->nparam
> 1)
3777 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3778 tt
= mac
->params
[n
];
3783 "macro parameter %d is not a condition code",
3788 text
= nasm_strdup(conditions
[cc
]);
3792 n
= atoi(t
->text
+ 1) - 1;
3793 if (n
>= mac
->nparam
)
3796 if (mac
->nparam
> 1)
3797 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3798 tt
= mac
->params
[n
];
3801 for (i
= 0; i
< mac
->paramlen
[n
]; i
++) {
3802 *tail
= new_Token(NULL
, tt
->type
, tt
->text
, 0);
3803 tail
= &(*tail
)->next
;
3807 text
= NULL
; /* we've done it here */
3812 * seems we have a parameters range here
3814 Token
*head
, **last
;
3815 head
= expand_mmac_params_range(mac
, t
, &last
);
3836 } else if (tline
->type
== TOK_INDIRECT
) {
3838 tline
= tline
->next
;
3839 tt
= tokenize(t
->text
);
3840 tt
= expand_mmac_params(tt
);
3841 tt
= expand_smacro(tt
);
3844 tt
->a
.mac
= NULL
; /* Necessary? */
3852 tline
= tline
->next
;
3860 paste_tokens(&thead
, false);
3866 * Expand all single-line macro calls made in the given line.
3867 * Return the expanded version of the line. The original is deemed
3868 * to be destroyed in the process. (In reality we'll just move
3869 * Tokens from input to output a lot of the time, rather than
3870 * actually bothering to destroy and replicate.)
3873 static Token
*expand_smacro(Token
* tline
)
3875 Token
*t
, *tt
, *mstart
, **tail
, *thead
;
3876 SMacro
*head
= NULL
, *m
;
3879 unsigned int nparam
, sparam
;
3881 Token
*org_tline
= tline
;
3884 int deadman
= DEADMAN_LIMIT
;
3888 * Trick: we should avoid changing the start token pointer since it can
3889 * be contained in "next" field of other token. Because of this
3890 * we allocate a copy of first token and work with it; at the end of
3891 * routine we copy it back
3894 tline
= new_Token(org_tline
->next
, org_tline
->type
,
3895 org_tline
->text
, 0);
3896 tline
->a
.mac
= org_tline
->a
.mac
;
3897 nasm_free(org_tline
->text
);
3898 org_tline
->text
= NULL
;
3901 expanded
= true; /* Always expand %+ at least once */
3907 while (tline
) { /* main token loop */
3909 error(ERR_NONFATAL
, "interminable macro recursion");
3913 if ((mname
= tline
->text
)) {
3914 /* if this token is a local macro, look in local context */
3915 if (tline
->type
== TOK_ID
) {
3916 head
= (SMacro
*)hash_findix(&smacros
, mname
);
3917 } else if (tline
->type
== TOK_PREPROC_ID
) {
3918 ctx
= get_ctx(mname
, &mname
, true);
3919 head
= ctx
? (SMacro
*)hash_findix(&ctx
->localmac
, mname
) : NULL
;
3924 * We've hit an identifier. As in is_mmacro below, we first
3925 * check whether the identifier is a single-line macro at
3926 * all, then think about checking for parameters if
3929 list_for_each(m
, head
)
3930 if (!mstrcmp(m
->name
, mname
, m
->casesense
))
3936 if (m
->nparam
== 0) {
3938 * Simple case: the macro is parameterless. Discard the
3939 * one token that the macro call took, and push the
3940 * expansion back on the to-do stack.
3942 if (!m
->expansion
) {
3943 if (!strcmp("__FILE__", m
->name
)) {
3946 src_get(&num
, &file
);
3947 tline
->text
= nasm_quote(file
, strlen(file
));
3948 tline
->type
= TOK_STRING
;
3952 if (!strcmp("__LINE__", m
->name
)) {
3953 nasm_free(tline
->text
);
3954 make_tok_num(tline
, src_get_linnum());
3957 if (!strcmp("__BITS__", m
->name
)) {
3958 nasm_free(tline
->text
);
3959 make_tok_num(tline
, globalbits
);
3962 tline
= delete_Token(tline
);
3967 * Complicated case: at least one macro with this name
3968 * exists and takes parameters. We must find the
3969 * parameters in the call, count them, find the SMacro
3970 * that corresponds to that form of the macro call, and
3971 * substitute for the parameters when we expand. What a
3974 /*tline = tline->next;
3975 skip_white_(tline); */
3978 while (tok_type_(t
, TOK_SMAC_END
)) {
3979 t
->a
.mac
->in_progress
= false;
3981 t
= tline
->next
= delete_Token(t
);
3984 } while (tok_type_(tline
, TOK_WHITESPACE
));
3985 if (!tok_is_(tline
, "(")) {
3987 * This macro wasn't called with parameters: ignore
3988 * the call. (Behaviour borrowed from gnu cpp.)
3997 sparam
= PARAM_DELTA
;
3998 params
= nasm_malloc(sparam
* sizeof(Token
*));
3999 params
[0] = tline
->next
;
4000 paramsize
= nasm_malloc(sparam
* sizeof(int));
4002 while (true) { /* parameter loop */
4004 * For some unusual expansions
4005 * which concatenates function call
4008 while (tok_type_(t
, TOK_SMAC_END
)) {
4009 t
->a
.mac
->in_progress
= false;
4011 t
= tline
->next
= delete_Token(t
);
4017 "macro call expects terminating `)'");
4020 if (tline
->type
== TOK_WHITESPACE
4022 if (paramsize
[nparam
])
4025 params
[nparam
] = tline
->next
;
4026 continue; /* parameter loop */
4028 if (tline
->type
== TOK_OTHER
4029 && tline
->text
[1] == 0) {
4030 char ch
= tline
->text
[0];
4031 if (ch
== ',' && !paren
&& brackets
<= 0) {
4032 if (++nparam
>= sparam
) {
4033 sparam
+= PARAM_DELTA
;
4034 params
= nasm_realloc(params
,
4035 sparam
* sizeof(Token
*));
4036 paramsize
= nasm_realloc(paramsize
,
4037 sparam
* sizeof(int));
4039 params
[nparam
] = tline
->next
;
4040 paramsize
[nparam
] = 0;
4042 continue; /* parameter loop */
4045 (brackets
> 0 || (brackets
== 0 &&
4046 !paramsize
[nparam
])))
4048 if (!(brackets
++)) {
4049 params
[nparam
] = tline
->next
;
4050 continue; /* parameter loop */
4053 if (ch
== '}' && brackets
> 0)
4054 if (--brackets
== 0) {
4056 continue; /* parameter loop */
4058 if (ch
== '(' && !brackets
)
4060 if (ch
== ')' && brackets
<= 0)
4066 error(ERR_NONFATAL
, "braces do not "
4067 "enclose all of macro parameter");
4069 paramsize
[nparam
] += white
+ 1;
4071 } /* parameter loop */
4073 while (m
&& (m
->nparam
!= nparam
||
4074 mstrcmp(m
->name
, mname
,
4078 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4079 "macro `%s' exists, "
4080 "but not taking %d parameters",
4081 mstart
->text
, nparam
);
4084 if (m
&& m
->in_progress
)
4086 if (!m
) { /* in progess or didn't find '(' or wrong nparam */
4088 * Design question: should we handle !tline, which
4089 * indicates missing ')' here, or expand those
4090 * macros anyway, which requires the (t) test a few
4094 nasm_free(paramsize
);
4098 * Expand the macro: we are placed on the last token of the
4099 * call, so that we can easily split the call from the
4100 * following tokens. We also start by pushing an SMAC_END
4101 * token for the cycle removal.
4108 tt
= new_Token(tline
, TOK_SMAC_END
, NULL
, 0);
4110 m
->in_progress
= true;
4112 list_for_each(t
, m
->expansion
) {
4113 if (t
->type
>= TOK_SMAC_PARAM
) {
4114 Token
*pcopy
= tline
, **ptail
= &pcopy
;
4118 ttt
= params
[t
->type
- TOK_SMAC_PARAM
];
4119 i
= paramsize
[t
->type
- TOK_SMAC_PARAM
];
4121 pt
= *ptail
= new_Token(tline
, ttt
->type
,
4127 } else if (t
->type
== TOK_PREPROC_Q
) {
4128 tt
= new_Token(tline
, TOK_ID
, mname
, 0);
4130 } else if (t
->type
== TOK_PREPROC_QQ
) {
4131 tt
= new_Token(tline
, TOK_ID
, m
->name
, 0);
4134 tt
= new_Token(tline
, t
->type
, t
->text
, 0);
4140 * Having done that, get rid of the macro call, and clean
4141 * up the parameters.
4144 nasm_free(paramsize
);
4147 continue; /* main token loop */
4152 if (tline
->type
== TOK_SMAC_END
) {
4153 tline
->a
.mac
->in_progress
= false;
4154 tline
= delete_Token(tline
);
4157 tline
= tline
->next
;
4165 * Now scan the entire line and look for successive TOK_IDs that resulted
4166 * after expansion (they can't be produced by tokenize()). The successive
4167 * TOK_IDs should be concatenated.
4168 * Also we look for %+ tokens and concatenate the tokens before and after
4169 * them (without white spaces in between).
4171 if (expanded
&& paste_tokens(&thead
, true)) {
4173 * If we concatenated something, *and* we had previously expanded
4174 * an actual macro, scan the lines again for macros...
4184 *org_tline
= *thead
;
4185 /* since we just gave text to org_line, don't free it */
4187 delete_Token(thead
);
4189 /* the expression expanded to empty line;
4190 we can't return NULL for some reasons
4191 we just set the line to a single WHITESPACE token. */
4192 memset(org_tline
, 0, sizeof(*org_tline
));
4193 org_tline
->text
= NULL
;
4194 org_tline
->type
= TOK_WHITESPACE
;
4203 * Similar to expand_smacro but used exclusively with macro identifiers
4204 * right before they are fetched in. The reason is that there can be
4205 * identifiers consisting of several subparts. We consider that if there
4206 * are more than one element forming the name, user wants a expansion,
4207 * otherwise it will be left as-is. Example:
4211 * the identifier %$abc will be left as-is so that the handler for %define
4212 * will suck it and define the corresponding value. Other case:
4214 * %define _%$abc cde
4216 * In this case user wants name to be expanded *before* %define starts
4217 * working, so we'll expand %$abc into something (if it has a value;
4218 * otherwise it will be left as-is) then concatenate all successive
4221 static Token
*expand_id(Token
* tline
)
4223 Token
*cur
, *oldnext
= NULL
;
4225 if (!tline
|| !tline
->next
)
4230 (cur
->next
->type
== TOK_ID
||
4231 cur
->next
->type
== TOK_PREPROC_ID
4232 || cur
->next
->type
== TOK_NUMBER
))
4235 /* If identifier consists of just one token, don't expand */
4240 oldnext
= cur
->next
; /* Detach the tail past identifier */
4241 cur
->next
= NULL
; /* so that expand_smacro stops here */
4244 tline
= expand_smacro(tline
);
4247 /* expand_smacro possibly changhed tline; re-scan for EOL */
4249 while (cur
&& cur
->next
)
4252 cur
->next
= oldnext
;
4259 * Determine whether the given line constitutes a multi-line macro
4260 * call, and return the MMacro structure called if so. Doesn't have
4261 * to check for an initial label - that's taken care of in
4262 * expand_mmacro - but must check numbers of parameters. Guaranteed
4263 * to be called with tline->type == TOK_ID, so the putative macro
4264 * name is easy to find.
4266 static MMacro
*is_mmacro(Token
* tline
, Token
*** params_array
)
4272 head
= (MMacro
*) hash_findix(&mmacros
, tline
->text
);
4275 * Efficiency: first we see if any macro exists with the given
4276 * name. If not, we can return NULL immediately. _Then_ we
4277 * count the parameters, and then we look further along the
4278 * list if necessary to find the proper MMacro.
4280 list_for_each(m
, head
)
4281 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4287 * OK, we have a potential macro. Count and demarcate the
4290 count_mmac_params(tline
->next
, &nparam
, ¶ms
);
4293 * So we know how many parameters we've got. Find the MMacro
4294 * structure that handles this number.
4297 if (m
->nparam_min
<= nparam
4298 && (m
->plus
|| nparam
<= m
->nparam_max
)) {
4300 * This one is right. Just check if cycle removal
4301 * prohibits us using it before we actually celebrate...
4303 if (m
->in_progress
> m
->max_depth
) {
4304 if (m
->max_depth
> 0) {
4306 "reached maximum recursion depth of %i",
4313 * It's right, and we can use it. Add its default
4314 * parameters to the end of our list if necessary.
4316 if (m
->defaults
&& nparam
< m
->nparam_min
+ m
->ndefs
) {
4318 nasm_realloc(params
,
4319 ((m
->nparam_min
+ m
->ndefs
+
4320 1) * sizeof(*params
)));
4321 while (nparam
< m
->nparam_min
+ m
->ndefs
) {
4322 params
[nparam
] = m
->defaults
[nparam
- m
->nparam_min
];
4327 * If we've gone over the maximum parameter count (and
4328 * we're in Plus mode), ignore parameters beyond
4331 if (m
->plus
&& nparam
> m
->nparam_max
)
4332 nparam
= m
->nparam_max
;
4334 * Then terminate the parameter list, and leave.
4336 if (!params
) { /* need this special case */
4337 params
= nasm_malloc(sizeof(*params
));
4340 params
[nparam
] = NULL
;
4341 *params_array
= params
;
4345 * This one wasn't right: look for the next one with the
4348 list_for_each(m
, m
->next
)
4349 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4354 * After all that, we didn't find one with the right number of
4355 * parameters. Issue a warning, and fail to expand the macro.
4357 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4358 "macro `%s' exists, but not taking %d parameters",
4359 tline
->text
, nparam
);
4366 * Save MMacro invocation specific fields in
4367 * preparation for a recursive macro expansion
4369 static void push_mmacro(MMacro
*m
)
4371 MMacroInvocation
*i
;
4373 i
= nasm_malloc(sizeof(MMacroInvocation
));
4375 i
->params
= m
->params
;
4376 i
->iline
= m
->iline
;
4377 i
->nparam
= m
->nparam
;
4378 i
->rotate
= m
->rotate
;
4379 i
->paramlen
= m
->paramlen
;
4380 i
->unique
= m
->unique
;
4381 i
->condcnt
= m
->condcnt
;
4387 * Restore MMacro invocation specific fields that were
4388 * saved during a previous recursive macro expansion
4390 static void pop_mmacro(MMacro
*m
)
4392 MMacroInvocation
*i
;
4397 m
->params
= i
->params
;
4398 m
->iline
= i
->iline
;
4399 m
->nparam
= i
->nparam
;
4400 m
->rotate
= i
->rotate
;
4401 m
->paramlen
= i
->paramlen
;
4402 m
->unique
= i
->unique
;
4403 m
->condcnt
= i
->condcnt
;
4410 * Expand the multi-line macro call made by the given line, if
4411 * there is one to be expanded. If there is, push the expansion on
4412 * istk->expansion and return 1. Otherwise return 0.
4414 static int expand_mmacro(Token
* tline
)
4416 Token
*startline
= tline
;
4417 Token
*label
= NULL
;
4418 int dont_prepend
= 0;
4419 Token
**params
, *t
, *mtok
, *tt
;
4422 int i
, nparam
, *paramlen
;
4427 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4428 if (!tok_type_(t
, TOK_ID
) && !tok_type_(t
, TOK_PREPROC_ID
))
4431 m
= is_mmacro(t
, ¶ms
);
4437 * We have an id which isn't a macro call. We'll assume
4438 * it might be a label; we'll also check to see if a
4439 * colon follows it. Then, if there's another id after
4440 * that lot, we'll check it again for macro-hood.
4444 if (tok_type_(t
, TOK_WHITESPACE
))
4445 last
= t
, t
= t
->next
;
4446 if (tok_is_(t
, ":")) {
4448 last
= t
, t
= t
->next
;
4449 if (tok_type_(t
, TOK_WHITESPACE
))
4450 last
= t
, t
= t
->next
;
4452 if (!tok_type_(t
, TOK_ID
) || !(m
= is_mmacro(t
, ¶ms
)))
4460 * Fix up the parameters: this involves stripping leading and
4461 * trailing whitespace, then stripping braces if they are
4464 for (nparam
= 0; params
[nparam
]; nparam
++) ;
4465 paramlen
= nparam
? nasm_malloc(nparam
* sizeof(*paramlen
)) : NULL
;
4467 for (i
= 0; params
[i
]; i
++) {
4469 int comma
= (!m
->plus
|| i
< nparam
- 1);
4473 if (tok_is_(t
, "{"))
4474 t
= t
->next
, brace
= true, comma
= false;
4478 if (comma
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, ","))
4479 break; /* ... because we have hit a comma */
4480 if (comma
&& t
->type
== TOK_WHITESPACE
4481 && tok_is_(t
->next
, ","))
4482 break; /* ... or a space then a comma */
4483 if (brace
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, "}"))
4484 break; /* ... or a brace */
4491 * OK, we have a MMacro structure together with a set of
4492 * parameters. We must now go through the expansion and push
4493 * copies of each Line on to istk->expansion. Substitution of
4494 * parameter tokens and macro-local tokens doesn't get done
4495 * until the single-line macro substitution process; this is
4496 * because delaying them allows us to change the semantics
4497 * later through %rotate.
4499 * First, push an end marker on to istk->expansion, mark this
4500 * macro as in progress, and set up its invocation-specific
4503 ll
= nasm_malloc(sizeof(Line
));
4504 ll
->next
= istk
->expansion
;
4507 istk
->expansion
= ll
;
4510 * Save the previous MMacro expansion in the case of
4513 if (m
->max_depth
&& m
->in_progress
)
4521 m
->paramlen
= paramlen
;
4522 m
->unique
= unique
++;
4526 m
->next_active
= istk
->mstk
;
4529 list_for_each(l
, m
->expansion
) {
4532 ll
= nasm_malloc(sizeof(Line
));
4533 ll
->finishes
= NULL
;
4534 ll
->next
= istk
->expansion
;
4535 istk
->expansion
= ll
;
4538 list_for_each(t
, l
->first
) {
4542 tt
= *tail
= new_Token(NULL
, TOK_ID
, mname
, 0);
4544 case TOK_PREPROC_QQ
:
4545 tt
= *tail
= new_Token(NULL
, TOK_ID
, m
->name
, 0);
4547 case TOK_PREPROC_ID
:
4548 if (t
->text
[1] == '0' && t
->text
[2] == '0') {
4556 tt
= *tail
= new_Token(NULL
, x
->type
, x
->text
, 0);
4565 * If we had a label, push it on as the first line of
4566 * the macro expansion.
4569 if (dont_prepend
< 0)
4570 free_tlist(startline
);
4572 ll
= nasm_malloc(sizeof(Line
));
4573 ll
->finishes
= NULL
;
4574 ll
->next
= istk
->expansion
;
4575 istk
->expansion
= ll
;
4576 ll
->first
= startline
;
4577 if (!dont_prepend
) {
4579 label
= label
->next
;
4580 label
->next
= tt
= new_Token(NULL
, TOK_OTHER
, ":", 0);
4585 list
->uplevel(m
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
4590 /* The function that actually does the error reporting */
4591 static void verror(int severity
, const char *fmt
, va_list arg
)
4595 vsnprintf(buff
, sizeof(buff
), fmt
, arg
);
4597 if (istk
&& istk
->mstk
&& istk
->mstk
->name
)
4598 nasm_error(severity
, "(%s:%d) %s", istk
->mstk
->name
,
4599 istk
->mstk
->lineno
, buff
);
4601 nasm_error(severity
, "%s", buff
);
4605 * Since preprocessor always operate only on the line that didn't
4606 * arrived yet, we should always use ERR_OFFBY1.
4608 static void error(int severity
, const char *fmt
, ...)
4612 /* If we're in a dead branch of IF or something like it, ignore the error */
4613 if (istk
&& istk
->conds
&& !emitting(istk
->conds
->state
))
4617 verror(severity
, fmt
, arg
);
4622 * Because %else etc are evaluated in the state context
4623 * of the previous branch, errors might get lost with error():
4624 * %if 0 ... %else trailing garbage ... %endif
4625 * So %else etc should report errors with this function.
4627 static void error_precond(int severity
, const char *fmt
, ...)
4631 /* Only ignore the error if it's really in a dead branch */
4632 if (istk
&& istk
->conds
&& istk
->conds
->state
== COND_NEVER
)
4636 verror(severity
, fmt
, arg
);
4641 pp_reset(char *file
, int apass
, ListGen
* listgen
, StrList
**deplist
)
4646 istk
= nasm_malloc(sizeof(Include
));
4649 istk
->expansion
= NULL
;
4651 istk
->fp
= fopen(file
, "r");
4653 src_set_fname(nasm_strdup(file
));
4657 error(ERR_FATAL
|ERR_NOFILE
, "unable to open input file `%s'",
4660 nested_mac_count
= 0;
4661 nested_rep_count
= 0;
4664 if (tasm_compatible_mode
) {
4665 stdmacpos
= nasm_stdmac
;
4667 stdmacpos
= nasm_stdmac_after_tasm
;
4669 any_extrastdmac
= extrastdmac
&& *extrastdmac
;
4674 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4675 * The caller, however, will also pass in 3 for preprocess-only so
4676 * we can set __PASS__ accordingly.
4678 pass
= apass
> 2 ? 2 : apass
;
4680 dephead
= deptail
= deplist
;
4682 StrList
*sl
= nasm_malloc(strlen(file
)+1+sizeof sl
->next
);
4684 strcpy(sl
->str
, file
);
4686 deptail
= &sl
->next
;
4690 * Define the __PASS__ macro. This is defined here unlike
4691 * all the other builtins, because it is special -- it varies between
4694 t
= nasm_malloc(sizeof(*t
));
4696 make_tok_num(t
, apass
);
4698 define_smacro(NULL
, "__PASS__", true, 0, t
);
4701 static char *pp_getline(void)
4708 * Fetch a tokenized line, either from the macro-expansion
4709 * buffer or from the input file.
4712 while (istk
->expansion
&& istk
->expansion
->finishes
) {
4713 Line
*l
= istk
->expansion
;
4714 if (!l
->finishes
->name
&& l
->finishes
->in_progress
> 1) {
4718 * This is a macro-end marker for a macro with no
4719 * name, which means it's not really a macro at all
4720 * but a %rep block, and the `in_progress' field is
4721 * more than 1, meaning that we still need to
4722 * repeat. (1 means the natural last repetition; 0
4723 * means termination by %exitrep.) We have
4724 * therefore expanded up to the %endrep, and must
4725 * push the whole block on to the expansion buffer
4726 * again. We don't bother to remove the macro-end
4727 * marker: we'd only have to generate another one
4730 l
->finishes
->in_progress
--;
4731 list_for_each(l
, l
->finishes
->expansion
) {
4732 Token
*t
, *tt
, **tail
;
4734 ll
= nasm_malloc(sizeof(Line
));
4735 ll
->next
= istk
->expansion
;
4736 ll
->finishes
= NULL
;
4740 list_for_each(t
, l
->first
) {
4741 if (t
->text
|| t
->type
== TOK_WHITESPACE
) {
4742 tt
= *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
4747 istk
->expansion
= ll
;
4751 * Check whether a `%rep' was started and not ended
4752 * within this macro expansion. This can happen and
4753 * should be detected. It's a fatal error because
4754 * I'm too confused to work out how to recover
4760 "defining with name in expansion");
4761 else if (istk
->mstk
->name
)
4763 "`%%rep' without `%%endrep' within"
4764 " expansion of macro `%s'",
4769 * FIXME: investigate the relationship at this point between
4770 * istk->mstk and l->finishes
4773 MMacro
*m
= istk
->mstk
;
4774 istk
->mstk
= m
->next_active
;
4777 * This was a real macro call, not a %rep, and
4778 * therefore the parameter information needs to
4783 l
->finishes
->in_progress
--;
4785 nasm_free(m
->params
);
4786 free_tlist(m
->iline
);
4787 nasm_free(m
->paramlen
);
4788 l
->finishes
->in_progress
= 0;
4793 istk
->expansion
= l
->next
;
4795 list
->downlevel(LIST_MACRO
);
4798 while (1) { /* until we get a line we can use */
4800 if (istk
->expansion
) { /* from a macro expansion */
4802 Line
*l
= istk
->expansion
;
4804 istk
->mstk
->lineno
++;
4806 istk
->expansion
= l
->next
;
4808 p
= detoken(tline
, false);
4809 list
->line(LIST_MACRO
, p
);
4814 if (line
) { /* from the current input file */
4815 line
= prepreproc(line
);
4816 tline
= tokenize(line
);
4821 * The current file has ended; work down the istk
4828 "expected `%%endif' before end of file");
4829 /* only set line and file name if there's a next node */
4831 src_set_linnum(i
->lineno
);
4832 nasm_free(src_set_fname(i
->fname
));
4835 list
->downlevel(LIST_INCLUDE
);
4839 if (istk
->expansion
&& istk
->expansion
->finishes
)
4845 * We must expand MMacro parameters and MMacro-local labels
4846 * _before_ we plunge into directive processing, to cope
4847 * with things like `%define something %1' such as STRUC
4848 * uses. Unless we're _defining_ a MMacro, in which case
4849 * those tokens should be left alone to go into the
4850 * definition; and unless we're in a non-emitting
4851 * condition, in which case we don't want to meddle with
4854 if (!defining
&& !(istk
->conds
&& !emitting(istk
->conds
->state
))
4855 && !(istk
->mstk
&& !istk
->mstk
->in_progress
)) {
4856 tline
= expand_mmac_params(tline
);
4860 * Check the line to see if it's a preprocessor directive.
4862 if (do_directive(tline
) == DIRECTIVE_FOUND
) {
4864 } else if (defining
) {
4866 * We're defining a multi-line macro. We emit nothing
4868 * shove the tokenized line on to the macro definition.
4870 Line
*l
= nasm_malloc(sizeof(Line
));
4871 l
->next
= defining
->expansion
;
4874 defining
->expansion
= l
;
4876 } else if (istk
->conds
&& !emitting(istk
->conds
->state
)) {
4878 * We're in a non-emitting branch of a condition block.
4879 * Emit nothing at all, not even a blank line: when we
4880 * emerge from the condition we'll give a line-number
4881 * directive so we keep our place correctly.
4885 } else if (istk
->mstk
&& !istk
->mstk
->in_progress
) {
4887 * We're in a %rep block which has been terminated, so
4888 * we're walking through to the %endrep without
4889 * emitting anything. Emit nothing at all, not even a
4890 * blank line: when we emerge from the %rep block we'll
4891 * give a line-number directive so we keep our place
4897 tline
= expand_smacro(tline
);
4898 if (!expand_mmacro(tline
)) {
4900 * De-tokenize the line again, and emit it.
4902 line
= detoken(tline
, true);
4906 continue; /* expand_mmacro calls free_tlist */
4914 static void pp_cleanup(int pass
)
4917 if (defining
->name
) {
4919 "end of file while still defining macro `%s'",
4922 error(ERR_NONFATAL
, "end of file while still in %%rep");
4925 free_mmacro(defining
);
4935 nasm_free(i
->fname
);
4940 nasm_free(src_set_fname(NULL
));
4945 while ((i
= ipath
)) {
4954 void pp_include_path(char *path
)
4958 i
= nasm_malloc(sizeof(IncPath
));
4959 i
->path
= path
? nasm_strdup(path
) : NULL
;
4972 void pp_pre_include(char *fname
)
4974 Token
*inc
, *space
, *name
;
4977 name
= new_Token(NULL
, TOK_INTERNAL_STRING
, fname
, 0);
4978 space
= new_Token(name
, TOK_WHITESPACE
, NULL
, 0);
4979 inc
= new_Token(space
, TOK_PREPROC_ID
, "%include", 0);
4981 l
= nasm_malloc(sizeof(Line
));
4988 void pp_pre_define(char *definition
)
4994 equals
= strchr(definition
, '=');
4995 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
4996 def
= new_Token(space
, TOK_PREPROC_ID
, "%define", 0);
4999 space
->next
= tokenize(definition
);
5003 l
= nasm_malloc(sizeof(Line
));
5010 void pp_pre_undefine(char *definition
)
5015 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5016 def
= new_Token(space
, TOK_PREPROC_ID
, "%undef", 0);
5017 space
->next
= tokenize(definition
);
5019 l
= nasm_malloc(sizeof(Line
));
5027 * Added by Keith Kanios:
5029 * This function is used to assist with "runtime" preprocessor
5030 * directives. (e.g. pp_runtime("%define __BITS__ 64");)
5032 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
5033 * PASS A VALID STRING TO THIS FUNCTION!!!!!
5036 void pp_runtime(char *definition
)
5040 def
= tokenize(definition
);
5041 if (do_directive(def
) == NO_DIRECTIVE_FOUND
)
5046 void pp_extra_stdmac(macros_t
*macros
)
5048 extrastdmac
= macros
;
5051 static void make_tok_num(Token
* tok
, int64_t val
)
5054 snprintf(numbuf
, sizeof(numbuf
), "%"PRId64
"", val
);
5055 tok
->text
= nasm_strdup(numbuf
);
5056 tok
->type
= TOK_NUMBER
;