xref: /illumos-gate/usr/src/cmd/acpi/iasl/prscan.c (revision 35786f6866ae52207d0f1a25fe7ca5f652f32ce0)
1 /******************************************************************************
2  *
3  * Module Name: prscan - Preprocessor start-up and file scan module
4  *
5  *****************************************************************************/
6 
7 /******************************************************************************
8  *
9  * 1. Copyright Notice
10  *
11  * Some or all of this work - Copyright (c) 1999 - 2018, Intel Corp.
12  * All rights reserved.
13  *
14  * 2. License
15  *
16  * 2.1. This is your license from Intel Corp. under its intellectual property
17  * rights. You may have additional license terms from the party that provided
18  * you this software, covering your right to use that party's intellectual
19  * property rights.
20  *
21  * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
22  * copy of the source code appearing in this file ("Covered Code") an
23  * irrevocable, perpetual, worldwide license under Intel's copyrights in the
24  * base code distributed originally by Intel ("Original Intel Code") to copy,
25  * make derivatives, distribute, use and display any portion of the Covered
26  * Code in any form, with the right to sublicense such rights; and
27  *
28  * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
29  * license (with the right to sublicense), under only those claims of Intel
30  * patents that are infringed by the Original Intel Code, to make, use, sell,
31  * offer to sell, and import the Covered Code and derivative works thereof
32  * solely to the minimum extent necessary to exercise the above copyright
33  * license, and in no event shall the patent license extend to any additions
34  * to or modifications of the Original Intel Code. No other license or right
35  * is granted directly or by implication, estoppel or otherwise;
36  *
37  * The above copyright and patent license is granted only if the following
38  * conditions are met:
39  *
40  * 3. Conditions
41  *
42  * 3.1. Redistribution of Source with Rights to Further Distribute Source.
43  * Redistribution of source code of any substantial portion of the Covered
44  * Code or modification with rights to further distribute source must include
45  * the above Copyright Notice, the above License, this list of Conditions,
46  * and the following Disclaimer and Export Compliance provision. In addition,
47  * Licensee must cause all Covered Code to which Licensee contributes to
48  * contain a file documenting the changes Licensee made to create that Covered
49  * Code and the date of any change. Licensee must include in that file the
50  * documentation of any changes made by any predecessor Licensee. Licensee
51  * must include a prominent statement that the modification is derived,
52  * directly or indirectly, from Original Intel Code.
53  *
54  * 3.2. Redistribution of Source with no Rights to Further Distribute Source.
55  * Redistribution of source code of any substantial portion of the Covered
56  * Code or modification without rights to further distribute source must
57  * include the following Disclaimer and Export Compliance provision in the
58  * documentation and/or other materials provided with distribution. In
59  * addition, Licensee may not authorize further sublicense of source of any
60  * portion of the Covered Code, and must include terms to the effect that the
61  * license from Licensee to its licensee is limited to the intellectual
62  * property embodied in the software Licensee provides to its licensee, and
63  * not to intellectual property embodied in modifications its licensee may
64  * make.
65  *
66  * 3.3. Redistribution of Executable. Redistribution in executable form of any
67  * substantial portion of the Covered Code or modification must reproduce the
68  * above Copyright Notice, and the following Disclaimer and Export Compliance
69  * provision in the documentation and/or other materials provided with the
70  * distribution.
71  *
72  * 3.4. Intel retains all right, title, and interest in and to the Original
73  * Intel Code.
74  *
75  * 3.5. Neither the name Intel nor any other trademark owned or controlled by
76  * Intel shall be used in advertising or otherwise to promote the sale, use or
77  * other dealings in products derived from or relating to the Covered Code
78  * without prior written authorization from Intel.
79  *
80  * 4. Disclaimer and Export Compliance
81  *
82  * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
83  * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
84  * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
85  * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
86  * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
87  * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
88  * PARTICULAR PURPOSE.
89  *
90  * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
91  * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
92  * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
93  * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
94  * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
95  * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
96  * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
97  * LIMITED REMEDY.
98  *
99  * 4.3. Licensee shall not export, either directly or indirectly, any of this
100  * software or system incorporating such software without first obtaining any
101  * required license or other approval from the U. S. Department of Commerce or
102  * any other agency or department of the United States Government. In the
103  * event Licensee exports any such software from the United States or
104  * re-exports any such software from a foreign destination, Licensee shall
105  * ensure that the distribution and export/re-export of the software is in
106  * compliance with all laws, regulations, orders, or other restrictions of the
107  * U.S. Export Administration Regulations. Licensee agrees that neither it nor
108  * any of its subsidiaries will export/re-export any technical data, process,
109  * software, or service, directly or indirectly, to any country for which the
110  * United States government or any agency thereof requires an export license,
111  * other governmental approval, or letter of assurance, without first obtaining
112  * such license, approval or letter.
113  *
114  *****************************************************************************
115  *
116  * Alternatively, you may choose to be licensed under the terms of the
117  * following license:
118  *
119  * Redistribution and use in source and binary forms, with or without
120  * modification, are permitted provided that the following conditions
121  * are met:
122  * 1. Redistributions of source code must retain the above copyright
123  *    notice, this list of conditions, and the following disclaimer,
124  *    without modification.
125  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
126  *    substantially similar to the "NO WARRANTY" disclaimer below
127  *    ("Disclaimer") and any redistribution must be conditioned upon
128  *    including a substantially similar Disclaimer requirement for further
129  *    binary redistribution.
130  * 3. Neither the names of the above-listed copyright holders nor the names
131  *    of any contributors may be used to endorse or promote products derived
132  *    from this software without specific prior written permission.
133  *
134  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
135  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
136  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
137  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
138  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
139  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
140  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
141  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
142  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
143  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
144  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
145  *
146  * Alternatively, you may choose to be licensed under the terms of the
147  * GNU General Public License ("GPL") version 2 as published by the Free
148  * Software Foundation.
149  *
150  *****************************************************************************/
151 
152 #define _DECLARE_PR_GLOBALS
153 
154 #include "aslcompiler.h"
155 
156 /*
157  * TBDs:
158  *
159  * No nested macros, maybe never
160  * Implement ASL "Include" as well as "#include" here?
161  */
162 #define _COMPONENT          ASL_PREPROCESSOR
163         ACPI_MODULE_NAME    ("prscan")
164 
165 
166 /* Local prototypes */
167 
168 static void
169 PrPreprocessInputFile (
170     void);
171 
172 static void
173 PrDoDirective (
174     char                    *DirectiveToken,
175     char                    **Next);
176 
177 static void
178 PrGetNextLineInit (
179     void);
180 
181 static UINT32
182 PrGetNextLine (
183     FILE                    *Handle);
184 
185 static int
186 PrMatchDirective (
187     char                    *Directive);
188 
189 static void
190 PrPushDirective (
191     int                     Directive,
192     char                    *Argument);
193 
194 static ACPI_STATUS
195 PrPopDirective (
196     void);
197 
198 static void
199 PrDbgPrint (
200     char                    *Action,
201     char                    *DirectiveName);
202 
203 static void
204 PrDoIncludeBuffer (
205     char                    *Pathname,
206     char                    *BufferName);
207 
208 static void
209 PrDoIncludeFile (
210     char                    *Pathname);
211 
212 
213 /*
214  * Supported preprocessor directives
215  * Each entry is of the form "Name, ArgumentCount"
216  */
217 static const PR_DIRECTIVE_INFO      Gbl_DirectiveInfo[] =
218 {
219     {"define",          1},
220     {"elif",            0}, /* Converted to #else..#if internally */
221     {"else",            0},
222     {"endif",           0},
223     {"error",           1},
224     {"if",              1},
225     {"ifdef",           1},
226     {"ifndef",          1},
227     {"include",         0}, /* Argument is not standard format, so just use 0 here */
228     {"includebuffer",   0}, /* Argument is not standard format, so just use 0 here */
229     {"line",            1},
230     {"pragma",          1},
231     {"undef",           1},
232     {"warning",         1},
233     {NULL,              0}
234 };
235 
236 /* This table must match ordering of above table exactly */
237 
238 enum Gbl_DirectiveIndexes
239 {
240     PR_DIRECTIVE_DEFINE = 0,
241     PR_DIRECTIVE_ELIF,
242     PR_DIRECTIVE_ELSE,
243     PR_DIRECTIVE_ENDIF,
244     PR_DIRECTIVE_ERROR,
245     PR_DIRECTIVE_IF,
246     PR_DIRECTIVE_IFDEF,
247     PR_DIRECTIVE_IFNDEF,
248     PR_DIRECTIVE_INCLUDE,
249     PR_DIRECTIVE_INCLUDEBUFFER,
250     PR_DIRECTIVE_LINE,
251     PR_DIRECTIVE_PRAGMA,
252     PR_DIRECTIVE_UNDEF,
253     PR_DIRECTIVE_WARNING
254 };
255 
256 #define ASL_DIRECTIVE_NOT_FOUND     -1
257 
258 
259 /*******************************************************************************
260  *
261  * FUNCTION:    PrInitializePreprocessor
262  *
263  * PARAMETERS:  None
264  *
265  * RETURN:      None
266  *
267  * DESCRIPTION: Startup initialization for the Preprocessor.
268  *
269  ******************************************************************************/
270 
271 void
PrInitializePreprocessor(void)272 PrInitializePreprocessor (
273     void)
274 {
275     /* Init globals and the list of #defines */
276 
277     PrInitializeGlobals ();
278     Gbl_DefineList = NULL;
279 }
280 
281 
282 /*******************************************************************************
283  *
284  * FUNCTION:    PrInitializeGlobals
285  *
286  * PARAMETERS:  None
287  *
288  * RETURN:      None
289  *
290  * DESCRIPTION: Initialize globals for the Preprocessor. Used for startuup
291  *              initialization and re-initialization between compiles during
292  *              a multiple source file compile.
293  *
294  ******************************************************************************/
295 
296 void
PrInitializeGlobals(void)297 PrInitializeGlobals (
298     void)
299 {
300     /* Init globals */
301 
302     Gbl_InputFileList = NULL;
303     Gbl_CurrentLineNumber = 1;
304     Gbl_PreprocessorLineNumber = 1;
305     Gbl_PreprocessorError = FALSE;
306 
307     /* These are used to track #if/#else blocks (possibly nested) */
308 
309     Gbl_IfDepth = 0;
310     Gbl_IgnoringThisCodeBlock = FALSE;
311     Gbl_DirectiveStack = NULL;
312 }
313 
314 
315 /*******************************************************************************
316  *
317  * FUNCTION:    PrTerminatePreprocessor
318  *
319  * PARAMETERS:  None
320  *
321  * RETURN:      None
322  *
323  * DESCRIPTION: Termination of the preprocessor. Delete lists. Keep any
324  *              defines that were specified on the command line, in order to
325  *              support multiple compiles with a single compiler invocation.
326  *
327  ******************************************************************************/
328 
329 void
PrTerminatePreprocessor(void)330 PrTerminatePreprocessor (
331     void)
332 {
333     PR_DEFINE_INFO          *DefineInfo;
334 
335 
336     /*
337      * The persistent defines (created on the command line) are always at the
338      * end of the list. We save them.
339      */
340     while ((Gbl_DefineList) && (!Gbl_DefineList->Persist))
341     {
342         DefineInfo = Gbl_DefineList;
343         Gbl_DefineList = DefineInfo->Next;
344 
345         ACPI_FREE (DefineInfo->Replacement);
346         ACPI_FREE (DefineInfo->Identifier);
347         ACPI_FREE (DefineInfo);
348     }
349 }
350 
351 
352 /*******************************************************************************
353  *
354  * FUNCTION:    PrDoPreprocess
355  *
356  * PARAMETERS:  None
357  *
358  * RETURN:      None
359  *
360  * DESCRIPTION: Main entry point for the iASL Preprocessor. Input file must
361  *              be already open. Handles multiple input files via the
362  *              #include directive.
363  *
364  ******************************************************************************/
365 
366 void
PrDoPreprocess(void)367 PrDoPreprocess (
368     void)
369 {
370     BOOLEAN                 MoreInputFiles;
371 
372 
373     DbgPrint (ASL_DEBUG_OUTPUT, "Starting preprocessing phase\n\n");
374 
375 
376     FlSeekFile (ASL_FILE_INPUT, 0);
377     PrDumpPredefinedNames ();
378 
379     /* Main preprocessor loop, handles include files */
380 
381     do
382     {
383         PrPreprocessInputFile ();
384         MoreInputFiles = PrPopInputFileStack ();
385 
386     } while (MoreInputFiles);
387 
388     /* Point compiler input to the new preprocessor output file (.pre) */
389 
390     FlCloseFile (ASL_FILE_INPUT);
391     Gbl_Files[ASL_FILE_INPUT].Handle = Gbl_Files[ASL_FILE_PREPROCESSOR].Handle;
392     AslCompilerin = Gbl_Files[ASL_FILE_INPUT].Handle;
393 
394     /* Reset globals to allow compiler to run */
395 
396     FlSeekFile (ASL_FILE_INPUT, 0);
397     if (!Gbl_PreprocessOnly)
398     {
399         Gbl_CurrentLineNumber = 0;
400     }
401 
402     DbgPrint (ASL_DEBUG_OUTPUT, "Preprocessing phase complete \n\n");
403 }
404 
405 
406 /*******************************************************************************
407  *
408  * FUNCTION:    PrPreprocessInputFile
409  *
410  * PARAMETERS:  None
411  *
412  * RETURN:      None
413  *
414  * DESCRIPTION: Preprocess one entire file, line-by-line.
415  *
416  * Input:  Raw user ASL from ASL_FILE_INPUT
417  * Output: Preprocessed file written to ASL_FILE_PREPROCESSOR and
418  *         (optionally) ASL_FILE_PREPROCESSOR_USER
419  *
420  ******************************************************************************/
421 
422 static void
PrPreprocessInputFile(void)423 PrPreprocessInputFile (
424     void)
425 {
426     UINT32                  Status;
427     char                    *Token;
428     char                    *ReplaceString;
429     PR_DEFINE_INFO          *DefineInfo;
430     ACPI_SIZE               TokenOffset;
431     char                    *Next;
432     int                     OffsetAdjust;
433 
434 
435     PrGetNextLineInit ();
436 
437     /* Scan source line-by-line and process directives. Then write the .i file */
438 
439     while ((Status = PrGetNextLine (Gbl_Files[ASL_FILE_INPUT].Handle)) != ASL_EOF)
440     {
441         Gbl_CurrentLineNumber++;
442         Gbl_LogicalLineNumber++;
443 
444         if (Status == ASL_IGNORE_LINE)
445         {
446             goto WriteEntireLine;
447         }
448 
449         /* Need a copy of the input line for strok() */
450 
451         strcpy (Gbl_MainTokenBuffer, Gbl_CurrentLineBuffer);
452         Token = PrGetNextToken (Gbl_MainTokenBuffer, PR_TOKEN_SEPARATORS, &Next);
453         OffsetAdjust = 0;
454 
455         /* All preprocessor directives must begin with '#' */
456 
457         if (Token && (*Token == '#'))
458         {
459             if (strlen (Token) == 1)
460             {
461                 Token = PrGetNextToken (NULL, PR_TOKEN_SEPARATORS, &Next);
462             }
463             else
464             {
465                 Token++;    /* Skip leading # */
466             }
467 
468             /* Execute the directive, do not write line to output file */
469 
470             PrDoDirective (Token, &Next);
471             continue;
472         }
473 
474         /*
475          * If we are currently within the part of an IF/ELSE block that is
476          * FALSE, ignore the line and do not write it to the output file.
477          * This continues until an #else or #endif is encountered.
478          */
479         if (Gbl_IgnoringThisCodeBlock)
480         {
481             continue;
482         }
483 
484         /* Match and replace all #defined names within this source line */
485 
486         while (Token)
487         {
488             DefineInfo = PrMatchDefine (Token);
489             if (DefineInfo)
490             {
491                 if (DefineInfo->Body)
492                 {
493                     /* This is a macro */
494 
495                     DbgPrint (ASL_DEBUG_OUTPUT, PR_PREFIX_ID
496                         "Matched Macro: %s->%s\n",
497                         Gbl_CurrentLineNumber, DefineInfo->Identifier,
498                         DefineInfo->Replacement);
499 
500                     PrDoMacroInvocation (Gbl_MainTokenBuffer, Token,
501                         DefineInfo, &Next);
502                 }
503                 else
504                 {
505                     ReplaceString = DefineInfo->Replacement;
506 
507                     /* Replace the name in the original line buffer */
508 
509                     TokenOffset = Token - Gbl_MainTokenBuffer + OffsetAdjust;
510                     PrReplaceData (
511                         &Gbl_CurrentLineBuffer[TokenOffset], strlen (Token),
512                         ReplaceString, strlen (ReplaceString));
513 
514                     /* Adjust for length difference between old and new name length */
515 
516                     OffsetAdjust += strlen (ReplaceString) - strlen (Token);
517 
518                     DbgPrint (ASL_DEBUG_OUTPUT, PR_PREFIX_ID
519                         "Matched #define: %s->%s\n",
520                         Gbl_CurrentLineNumber, Token,
521                         *ReplaceString ? ReplaceString : "(NULL STRING)");
522                 }
523             }
524 
525             Token = PrGetNextToken (NULL, PR_TOKEN_SEPARATORS, &Next);
526         }
527 
528         Gbl_PreprocessorLineNumber++;
529 
530 
531 WriteEntireLine:
532         /*
533          * Now we can write the possibly modified source line to the
534          * preprocessor file(s).
535          */
536         FlWriteFile (ASL_FILE_PREPROCESSOR, Gbl_CurrentLineBuffer,
537             strlen (Gbl_CurrentLineBuffer));
538     }
539 }
540 
541 
542 /*******************************************************************************
543  *
544  * FUNCTION:    PrDoDirective
545  *
546  * PARAMETERS:  Directive               - Pointer to directive name token
547  *              Next                    - "Next" buffer from GetNextToken
548  *
549  * RETURN:      None.
550  *
551  * DESCRIPTION: Main processing for all preprocessor directives
552  *
553  ******************************************************************************/
554 
555 static void
PrDoDirective(char * DirectiveToken,char ** Next)556 PrDoDirective (
557     char                    *DirectiveToken,
558     char                    **Next)
559 {
560     char                    *Token = Gbl_MainTokenBuffer;
561     char                    *Token2 = NULL;
562     char                    *End;
563     UINT64                  Value;
564     ACPI_SIZE               TokenOffset;
565     int                     Directive;
566     ACPI_STATUS             Status;
567 
568 
569     if (!DirectiveToken)
570     {
571         goto SyntaxError;
572     }
573 
574     Directive = PrMatchDirective (DirectiveToken);
575     if (Directive == ASL_DIRECTIVE_NOT_FOUND)
576     {
577         PrError (ASL_ERROR, ASL_MSG_UNKNOWN_DIRECTIVE,
578             THIS_TOKEN_OFFSET (DirectiveToken));
579 
580         DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
581             "#%s: Unknown directive\n",
582             Gbl_CurrentLineNumber, DirectiveToken);
583         return;
584     }
585 
586     /*
587      * Emit a line directive into the preprocessor file (.pre) after
588      * every matched directive. This is passed through to the compiler
589      * so that error/warning messages are kept in sync with the
590      * original source file.
591      */
592     FlPrintFile (ASL_FILE_PREPROCESSOR, "#line %u \"%s\" // #%s\n",
593         Gbl_CurrentLineNumber, Gbl_Files[ASL_FILE_INPUT].Filename,
594         Gbl_DirectiveInfo[Directive].Name);
595 
596     /*
597      * If we are currently ignoring this block and we encounter a #else or
598      * #elif, we must ignore their blocks also if the parent block is also
599      * being ignored.
600      */
601     if (Gbl_IgnoringThisCodeBlock)
602     {
603         switch (Directive)
604         {
605         case PR_DIRECTIVE_ELSE:
606         case PR_DIRECTIVE_ELIF:
607 
608             if (Gbl_DirectiveStack &&
609                 Gbl_DirectiveStack->IgnoringThisCodeBlock)
610             {
611                 PrDbgPrint ("Ignoring", Gbl_DirectiveInfo[Directive].Name);
612                 return;
613             }
614             break;
615 
616         default:
617             break;
618         }
619     }
620 
621     /*
622      * Need to always check for #else, #elif, #endif regardless of
623      * whether we are ignoring the current code block, since these
624      * are conditional code block terminators.
625      */
626     switch (Directive)
627     {
628     case PR_DIRECTIVE_ELSE:
629 
630         Gbl_IgnoringThisCodeBlock = !(Gbl_IgnoringThisCodeBlock);
631         PrDbgPrint ("Executing", "else block");
632         return;
633 
634     case PR_DIRECTIVE_ELIF:
635 
636         Gbl_IgnoringThisCodeBlock = !(Gbl_IgnoringThisCodeBlock);
637         Directive = PR_DIRECTIVE_IF;
638 
639         if (Gbl_IgnoringThisCodeBlock == TRUE)
640         {
641             /* Not executing the ELSE part -- all done here */
642             PrDbgPrint ("Ignoring", "elif block");
643             return;
644         }
645 
646         /*
647          * After this, we will execute the IF part further below.
648          * First, however, pop off the original #if directive.
649          */
650         if (ACPI_FAILURE (PrPopDirective ()))
651         {
652             PrError (ASL_ERROR, ASL_MSG_COMPILER_INTERNAL,
653                 THIS_TOKEN_OFFSET (DirectiveToken));
654         }
655 
656         PrDbgPrint ("Executing", "elif block");
657         break;
658 
659     case PR_DIRECTIVE_ENDIF:
660 
661         PrDbgPrint ("Executing", "endif");
662 
663         /* Pop the owning #if/#ifdef/#ifndef */
664 
665         if (ACPI_FAILURE (PrPopDirective ()))
666         {
667             PrError (ASL_ERROR, ASL_MSG_ENDIF_MISMATCH,
668                 THIS_TOKEN_OFFSET (DirectiveToken));
669         }
670         return;
671 
672     default:
673         break;
674     }
675 
676     /* Most directives have at least one argument */
677 
678     if (Gbl_DirectiveInfo[Directive].ArgCount >= 1)
679     {
680         Token = PrGetNextToken (NULL, PR_TOKEN_SEPARATORS, Next);
681         if (!Token)
682         {
683             goto SyntaxError;
684         }
685     }
686 
687     if (Gbl_DirectiveInfo[Directive].ArgCount >= 2)
688     {
689         Token2 = PrGetNextToken (NULL, PR_TOKEN_SEPARATORS, Next);
690         if (!Token2)
691         {
692             goto SyntaxError;
693         }
694     }
695 
696     /*
697      * At this point, if we are ignoring the current code block,
698      * do not process any more directives (i.e., ignore them also.)
699      * For "if" style directives, open/push a new block anyway. We
700      * must do this to keep track of #endif directives
701      */
702     if (Gbl_IgnoringThisCodeBlock)
703     {
704         switch (Directive)
705         {
706         case PR_DIRECTIVE_IF:
707         case PR_DIRECTIVE_IFDEF:
708         case PR_DIRECTIVE_IFNDEF:
709 
710             PrPushDirective (Directive, Token);
711             PrDbgPrint ("Ignoring", Gbl_DirectiveInfo[Directive].Name);
712             break;
713 
714         default:
715             break;
716         }
717 
718         return;
719     }
720 
721     /*
722      * Execute the directive
723      */
724     PrDbgPrint ("Begin execution", Gbl_DirectiveInfo[Directive].Name);
725 
726     switch (Directive)
727     {
728     case PR_DIRECTIVE_IF:
729 
730         TokenOffset = Token - Gbl_MainTokenBuffer;
731 
732         /* Need to expand #define macros in the expression string first */
733 
734         Status = PrResolveIntegerExpression (
735             &Gbl_CurrentLineBuffer[TokenOffset-1], &Value);
736         if (ACPI_FAILURE (Status))
737         {
738             return;
739         }
740 
741         PrPushDirective (Directive, Token);
742         if (!Value)
743         {
744             Gbl_IgnoringThisCodeBlock = TRUE;
745         }
746 
747         DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
748             "Resolved #if: %8.8X%8.8X %s\n",
749             Gbl_CurrentLineNumber, ACPI_FORMAT_UINT64 (Value),
750             Gbl_IgnoringThisCodeBlock ? "<Skipping Block>" : "<Executing Block>");
751         break;
752 
753     case PR_DIRECTIVE_IFDEF:
754 
755         PrPushDirective (Directive, Token);
756         if (!PrMatchDefine (Token))
757         {
758             Gbl_IgnoringThisCodeBlock = TRUE;
759         }
760 
761         PrDbgPrint ("Evaluated", "ifdef");
762         break;
763 
764     case PR_DIRECTIVE_IFNDEF:
765 
766         PrPushDirective (Directive, Token);
767         if (PrMatchDefine (Token))
768         {
769             Gbl_IgnoringThisCodeBlock = TRUE;
770         }
771 
772         PrDbgPrint ("Evaluated", "ifndef");
773         break;
774 
775     case PR_DIRECTIVE_DEFINE:
776         /*
777          * By definition, if first char after the name is a paren,
778          * this is a function macro.
779          */
780         TokenOffset = Token - Gbl_MainTokenBuffer + strlen (Token);
781         if (*(&Gbl_CurrentLineBuffer[TokenOffset]) == '(')
782         {
783 #ifndef MACROS_SUPPORTED
784             AcpiOsPrintf (
785                 "%s ERROR - line %u: #define macros are not supported yet\n",
786                 Gbl_CurrentLineBuffer, Gbl_LogicalLineNumber);
787             exit(1);
788 #else
789             PrAddMacro (Token, Next);
790 #endif
791         }
792         else
793         {
794             /* Use the remainder of the line for the #define */
795 
796             Token2 = *Next;
797             if (Token2)
798             {
799                 while ((*Token2 == ' ') || (*Token2 == '\t'))
800                 {
801                     Token2++;
802                 }
803 
804                 End = Token2;
805                 while (*End != '\n')
806                 {
807                     End++;
808                 }
809 
810                 *End = 0;
811             }
812             else
813             {
814                 Token2 = "";
815             }
816 #if 0
817             Token2 = PrGetNextToken (NULL, "\n", /*PR_TOKEN_SEPARATORS,*/ Next);
818             if (!Token2)
819             {
820                 Token2 = "";
821             }
822 #endif
823             DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
824                 "New #define: %s->%s\n",
825                 Gbl_LogicalLineNumber, Token, Token2);
826 
827             PrAddDefine (Token, Token2, FALSE);
828         }
829         break;
830 
831     case PR_DIRECTIVE_ERROR:
832 
833         /* Note: No macro expansion */
834 
835         PrError (ASL_ERROR, ASL_MSG_ERROR_DIRECTIVE,
836             THIS_TOKEN_OFFSET (Token));
837 
838         Gbl_SourceLine = 0;
839         Gbl_NextError = Gbl_ErrorLog;
840         CmCleanupAndExit ();
841         exit(1);
842 
843     case PR_DIRECTIVE_INCLUDE:
844 
845         Token = PrGetNextToken (NULL, " \"<>", Next);
846         if (!Token)
847         {
848             goto SyntaxError;
849         }
850 
851         DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
852             "Start #include file \"%s\"\n", Gbl_CurrentLineNumber,
853             Token, Gbl_CurrentLineNumber);
854 
855         PrDoIncludeFile (Token);
856         break;
857 
858     case PR_DIRECTIVE_INCLUDEBUFFER:
859 
860         Token = PrGetNextToken (NULL, " \"<>", Next);
861         if (!Token)
862         {
863             goto SyntaxError;
864         }
865 
866         Token2 = PrGetNextToken (NULL, PR_TOKEN_SEPARATORS, Next);
867         if (!Token2)
868         {
869             goto SyntaxError;
870         }
871 
872         DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
873             "Start #includebuffer input from file \"%s\", buffer name %s\n",
874             Gbl_CurrentLineNumber, Token, Token2);
875 
876         PrDoIncludeBuffer (Token, Token2);
877         break;
878 
879     case PR_DIRECTIVE_LINE:
880 
881         TokenOffset = Token - Gbl_MainTokenBuffer;
882 
883         Status = PrResolveIntegerExpression (
884             &Gbl_CurrentLineBuffer[TokenOffset-1], &Value);
885         if (ACPI_FAILURE (Status))
886         {
887             return;
888         }
889 
890         DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
891             "User #line invocation %s\n", Gbl_CurrentLineNumber,
892             Token);
893 
894         Gbl_CurrentLineNumber = (UINT32) Value;
895 
896         /* Emit #line into the preprocessor file */
897 
898         FlPrintFile (ASL_FILE_PREPROCESSOR, "#line %u \"%s\"\n",
899             Gbl_CurrentLineNumber, Gbl_Files[ASL_FILE_INPUT].Filename);
900         break;
901 
902     case PR_DIRECTIVE_PRAGMA:
903 
904         if (!strcmp (Token, "disable"))
905         {
906             Token = PrGetNextToken (NULL, PR_TOKEN_SEPARATORS, Next);
907             if (!Token)
908             {
909                 goto SyntaxError;
910             }
911 
912             TokenOffset = Token - Gbl_MainTokenBuffer;
913             AslDisableException (&Gbl_CurrentLineBuffer[TokenOffset]);
914         }
915         else if (!strcmp (Token, "message"))
916         {
917             Token = PrGetNextToken (NULL, PR_TOKEN_SEPARATORS, Next);
918             if (!Token)
919             {
920                 goto SyntaxError;
921             }
922 
923             TokenOffset = Token - Gbl_MainTokenBuffer;
924             AcpiOsPrintf ("%s\n", &Gbl_CurrentLineBuffer[TokenOffset]);
925         }
926         else
927         {
928             PrError (ASL_ERROR, ASL_MSG_UNKNOWN_PRAGMA,
929                 THIS_TOKEN_OFFSET (Token));
930             return;
931         }
932 
933         break;
934 
935     case PR_DIRECTIVE_UNDEF:
936 
937         DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
938             "#undef: %s\n", Gbl_CurrentLineNumber, Token);
939 
940         PrRemoveDefine (Token);
941         break;
942 
943     case PR_DIRECTIVE_WARNING:
944 
945         PrError (ASL_WARNING, ASL_MSG_WARNING_DIRECTIVE,
946             THIS_TOKEN_OFFSET (Token));
947 
948         Gbl_SourceLine = 0;
949         Gbl_NextError = Gbl_ErrorLog;
950         break;
951 
952     default:
953 
954         /* Should never get here */
955         DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
956             "Unrecognized directive: %u\n",
957             Gbl_CurrentLineNumber, Directive);
958         break;
959     }
960 
961     return;
962 
963 SyntaxError:
964 
965     PrError (ASL_ERROR, ASL_MSG_DIRECTIVE_SYNTAX,
966         THIS_TOKEN_OFFSET (DirectiveToken));
967     return;
968 }
969 
970 
971 /*******************************************************************************
972  *
973  * FUNCTION:    PrGetNextLine, PrGetNextLineInit
974  *
975  * PARAMETERS:  Handle              - Open file handle for the source file
976  *
977  * RETURN:      Status of the GetLine operation:
978  *              AE_OK               - Normal line, OK status
979  *              ASL_IGNORE_LINE     - Line is blank or part of a multi-line
980  *                                      comment
981  *              ASL_EOF             - End-of-file reached
982  *
983  * DESCRIPTION: Get the next text line from the input file. Does not strip
984  *              comments.
985  *
986  ******************************************************************************/
987 
988 #define PR_NORMAL_TEXT          0
989 #define PR_MULTI_LINE_COMMENT   1
990 #define PR_SINGLE_LINE_COMMENT  2
991 #define PR_QUOTED_STRING        3
992 
993 static UINT8                    AcpiGbl_LineScanState = PR_NORMAL_TEXT;
994 
995 static void
PrGetNextLineInit(void)996 PrGetNextLineInit (
997     void)
998 {
999     AcpiGbl_LineScanState = 0;
1000 }
1001 
1002 static UINT32
PrGetNextLine(FILE * Handle)1003 PrGetNextLine (
1004     FILE                    *Handle)
1005 {
1006     UINT32                  i;
1007     int                     c = 0;
1008     int                     PreviousChar;
1009 
1010 
1011     /* Always clear the global line buffer */
1012 
1013     memset (Gbl_CurrentLineBuffer, 0, Gbl_LineBufferSize);
1014     for (i = 0; ;)
1015     {
1016         /*
1017          * If line is too long, expand the line buffers. Also increases
1018          * Gbl_LineBufferSize.
1019          */
1020         if (i >= Gbl_LineBufferSize)
1021         {
1022             UtExpandLineBuffers ();
1023         }
1024 
1025         PreviousChar = c;
1026         c = getc (Handle);
1027         if (c == EOF)
1028         {
1029             /*
1030              * On EOF: If there is anything in the line buffer, terminate
1031              * it with a newline, and catch the EOF on the next call
1032              * to this function.
1033              */
1034             if (i > 0)
1035             {
1036                 Gbl_CurrentLineBuffer[i] = '\n';
1037                 return (AE_OK);
1038             }
1039 
1040             return (ASL_EOF);
1041         }
1042 
1043         /* Update state machine as necessary */
1044 
1045         switch (AcpiGbl_LineScanState)
1046         {
1047         case PR_NORMAL_TEXT:
1048 
1049             /* Check for multi-line comment start */
1050 
1051             if ((PreviousChar == '/') && (c == '*'))
1052             {
1053                 AcpiGbl_LineScanState = PR_MULTI_LINE_COMMENT;
1054             }
1055 
1056             /* Check for single-line comment start */
1057 
1058             else if ((PreviousChar == '/') && (c == '/'))
1059             {
1060                 AcpiGbl_LineScanState = PR_SINGLE_LINE_COMMENT;
1061             }
1062 
1063             /* Check for quoted string start */
1064 
1065             else if (PreviousChar == '"')
1066             {
1067                 AcpiGbl_LineScanState = PR_QUOTED_STRING;
1068             }
1069             break;
1070 
1071         case PR_QUOTED_STRING:
1072 
1073             if (PreviousChar == '"')
1074             {
1075                 AcpiGbl_LineScanState = PR_NORMAL_TEXT;
1076             }
1077             break;
1078 
1079         case PR_MULTI_LINE_COMMENT:
1080 
1081             /* Check for multi-line comment end */
1082 
1083             if ((PreviousChar == '*') && (c == '/'))
1084             {
1085                 AcpiGbl_LineScanState = PR_NORMAL_TEXT;
1086             }
1087             break;
1088 
1089         case PR_SINGLE_LINE_COMMENT: /* Just ignore text until EOL */
1090         default:
1091             break;
1092         }
1093 
1094         /* Always copy the character into line buffer */
1095 
1096         Gbl_CurrentLineBuffer[i] = (char) c;
1097         i++;
1098 
1099         /* Always exit on end-of-line */
1100 
1101         if (c == '\n')
1102         {
1103             /* Handle multi-line comments */
1104 
1105             if (AcpiGbl_LineScanState == PR_MULTI_LINE_COMMENT)
1106             {
1107                 return (ASL_IGNORE_LINE);
1108             }
1109 
1110             /* End of single-line comment */
1111 
1112             if (AcpiGbl_LineScanState == PR_SINGLE_LINE_COMMENT)
1113             {
1114                 AcpiGbl_LineScanState = PR_NORMAL_TEXT;
1115                 return (AE_OK);
1116             }
1117 
1118             /* Blank line */
1119 
1120             if (i == 1)
1121             {
1122                 return (ASL_IGNORE_LINE);
1123             }
1124 
1125             return (AE_OK);
1126         }
1127     }
1128 }
1129 
1130 
1131 /*******************************************************************************
1132  *
1133  * FUNCTION:    PrMatchDirective
1134  *
1135  * PARAMETERS:  Directive           - Pointer to directive name token
1136  *
1137  * RETURN:      Index into command array, -1 if not found
1138  *
1139  * DESCRIPTION: Lookup the incoming directive in the known directives table.
1140  *
1141  ******************************************************************************/
1142 
1143 static int
PrMatchDirective(char * Directive)1144 PrMatchDirective (
1145     char                    *Directive)
1146 {
1147     int                     i;
1148 
1149 
1150     if (!Directive || Directive[0] == 0)
1151     {
1152         return (ASL_DIRECTIVE_NOT_FOUND);
1153     }
1154 
1155     for (i = 0; Gbl_DirectiveInfo[i].Name; i++)
1156     {
1157         if (!strcmp (Gbl_DirectiveInfo[i].Name, Directive))
1158         {
1159             return (i);
1160         }
1161     }
1162 
1163     return (ASL_DIRECTIVE_NOT_FOUND);    /* Command not recognized */
1164 }
1165 
1166 
1167 /*******************************************************************************
1168  *
1169  * FUNCTION:    PrPushDirective
1170  *
1171  * PARAMETERS:  Directive           - Encoded directive ID
1172  *              Argument            - String containing argument to the
1173  *                                    directive
1174  *
1175  * RETURN:      None
1176  *
1177  * DESCRIPTION: Push an item onto the directive stack. Used for processing
1178  *              nested #if/#else type conditional compilation directives.
1179  *              Specifically: Used on detection of #if/#ifdef/#ifndef to open
1180  *              a block.
1181  *
1182  ******************************************************************************/
1183 
1184 static void
PrPushDirective(int Directive,char * Argument)1185 PrPushDirective (
1186     int                     Directive,
1187     char                    *Argument)
1188 {
1189     DIRECTIVE_INFO          *Info;
1190 
1191 
1192     /* Allocate and populate a stack info item */
1193 
1194     Info = ACPI_ALLOCATE (sizeof (DIRECTIVE_INFO));
1195 
1196     Info->Next = Gbl_DirectiveStack;
1197     Info->Directive = Directive;
1198     Info->IgnoringThisCodeBlock = Gbl_IgnoringThisCodeBlock;
1199     AcpiUtSafeStrncpy (Info->Argument, Argument, MAX_ARGUMENT_LENGTH);
1200 
1201     DbgPrint (ASL_DEBUG_OUTPUT,
1202         "Pr(%.4u) - [%u %s] %*s Pushed [#%s %s]: IgnoreFlag = %s\n",
1203         Gbl_CurrentLineNumber, Gbl_IfDepth,
1204         Gbl_IgnoringThisCodeBlock ? "I" : "E",
1205         Gbl_IfDepth * 4, " ",
1206         Gbl_DirectiveInfo[Directive].Name,
1207         Argument, Gbl_IgnoringThisCodeBlock ? "TRUE" : "FALSE");
1208 
1209     /* Push new item */
1210 
1211     Gbl_DirectiveStack = Info;
1212     Gbl_IfDepth++;
1213 }
1214 
1215 
1216 /*******************************************************************************
1217  *
1218  * FUNCTION:    PrPopDirective
1219  *
1220  * PARAMETERS:  None
1221  *
1222  * RETURN:      Status. Error if the stack is empty.
1223  *
1224  * DESCRIPTION: Pop an item off the directive stack. Used for processing
1225  *              nested #if/#else type conditional compilation directives.
1226  *              Specifically: Used on detection of #elif and #endif to remove
1227  *              the original #if/#ifdef/#ifndef from the stack and close
1228  *              the block.
1229  *
1230  ******************************************************************************/
1231 
1232 static ACPI_STATUS
PrPopDirective(void)1233 PrPopDirective (
1234     void)
1235 {
1236     DIRECTIVE_INFO          *Info;
1237 
1238 
1239     /* Check for empty stack */
1240 
1241     Info = Gbl_DirectiveStack;
1242     if (!Info)
1243     {
1244         return (AE_ERROR);
1245     }
1246 
1247     /* Pop one item, keep globals up-to-date */
1248 
1249     Gbl_IfDepth--;
1250     Gbl_IgnoringThisCodeBlock = Info->IgnoringThisCodeBlock;
1251     Gbl_DirectiveStack = Info->Next;
1252 
1253     DbgPrint (ASL_DEBUG_OUTPUT,
1254         "Pr(%.4u) - [%u %s] %*s Popped [#%s %s]: IgnoreFlag now = %s\n",
1255         Gbl_CurrentLineNumber, Gbl_IfDepth,
1256         Gbl_IgnoringThisCodeBlock ? "I" : "E",
1257         Gbl_IfDepth * 4, " ",
1258         Gbl_DirectiveInfo[Info->Directive].Name,
1259         Info->Argument, Gbl_IgnoringThisCodeBlock ? "TRUE" : "FALSE");
1260 
1261     ACPI_FREE (Info);
1262     return (AE_OK);
1263 }
1264 
1265 
1266 /*******************************************************************************
1267  *
1268  * FUNCTION:    PrDbgPrint
1269  *
1270  * PARAMETERS:  Action              - Action being performed
1271  *              DirectiveName       - Directive being processed
1272  *
1273  * RETURN:      None
1274  *
1275  * DESCRIPTION: Special debug print for directive processing.
1276  *
1277  ******************************************************************************/
1278 
1279 static void
PrDbgPrint(char * Action,char * DirectiveName)1280 PrDbgPrint (
1281     char                    *Action,
1282     char                    *DirectiveName)
1283 {
1284 
1285     DbgPrint (ASL_DEBUG_OUTPUT, "Pr(%.4u) - [%u %s] "
1286         "%*s %s #%s, IfDepth %u\n",
1287         Gbl_CurrentLineNumber, Gbl_IfDepth,
1288         Gbl_IgnoringThisCodeBlock ? "I" : "E",
1289         Gbl_IfDepth * 4, " ",
1290         Action, DirectiveName, Gbl_IfDepth);
1291 }
1292 
1293 
1294 /*******************************************************************************
1295  *
1296  * FUNCTION:    PrDoIncludeFile
1297  *
1298  * PARAMETERS:  Pathname                - Name of the input file
1299  *
1300  * RETURN:      None.
1301  *
1302  * DESCRIPTION: Open an include file, from #include.
1303  *
1304  ******************************************************************************/
1305 
1306 static void
PrDoIncludeFile(char * Pathname)1307 PrDoIncludeFile (
1308     char                    *Pathname)
1309 {
1310     char                    *FullPathname;
1311 
1312 
1313     (void) PrOpenIncludeFile (Pathname, "r", &FullPathname);
1314 }
1315 
1316 
1317 /*******************************************************************************
1318  *
1319  * FUNCTION:    PrDoIncludeBuffer
1320  *
1321  * PARAMETERS:  Pathname                - Name of the input binary file
1322  *              BufferName              - ACPI namepath of the buffer
1323  *
1324  * RETURN:      None.
1325  *
1326  * DESCRIPTION: Create an ACPI buffer object from a binary file. The contents
1327  *              of the file are emitted into the buffer object as ascii
1328  *              hex data. From #includebuffer.
1329  *
1330  ******************************************************************************/
1331 
1332 static void
PrDoIncludeBuffer(char * Pathname,char * BufferName)1333 PrDoIncludeBuffer (
1334     char                    *Pathname,
1335     char                    *BufferName)
1336 {
1337     char                    *FullPathname;
1338     FILE                    *BinaryBufferFile;
1339     UINT32                  i = 0;
1340     UINT8                   c;
1341 
1342 
1343     BinaryBufferFile = PrOpenIncludeFile (Pathname, "rb", &FullPathname);
1344     if (!BinaryBufferFile)
1345     {
1346         return;
1347     }
1348 
1349     /* Emit "Name (XXXX, Buffer() {" header */
1350 
1351     FlPrintFile (ASL_FILE_PREPROCESSOR, "Name (%s, Buffer()\n{", BufferName);
1352 
1353     /* Dump the entire file in ascii hex format */
1354 
1355     while (fread (&c, 1, 1, BinaryBufferFile))
1356     {
1357         if (!(i % 8))
1358         {
1359             FlPrintFile (ASL_FILE_PREPROCESSOR, "\n   ", c);
1360         }
1361 
1362         FlPrintFile (ASL_FILE_PREPROCESSOR, " 0x%2.2X,", c);
1363         i++;
1364     }
1365 
1366     DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
1367         "#includebuffer: read %u bytes from %s\n",
1368         Gbl_CurrentLineNumber, i, FullPathname);
1369 
1370     /* Close the Name() operator */
1371 
1372     FlPrintFile (ASL_FILE_PREPROCESSOR, "\n})\n", BufferName);
1373     fclose (BinaryBufferFile);
1374 }
1375