1/******************************************************************************
2 *
3 * Module Name: prutils - Preprocessor utilities
4 *
5 *****************************************************************************/
6
7/******************************************************************************
8 *
9 * 1. Copyright Notice
10 *
11 * Some or all of this work - Copyright (c) 1999 - 2016, 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#include "aslcompiler.h"
117#include "dtcompiler.h"
118
119
120#define _COMPONENT          ASL_PREPROCESSOR
121        ACPI_MODULE_NAME    ("prutils")
122
123
124/******************************************************************************
125 *
126 * FUNCTION:    PrGetNextToken
127 *
128 * PARAMETERS:  Buffer              - Current line buffer
129 *              MatchString         - String with valid token delimiters
130 *              Next                - Set to next possible token in buffer
131 *
132 * RETURN:      Next token (null-terminated). Modifies the input line.
133 *              Remainder of line is stored in *Next.
134 *
135 * DESCRIPTION: Local implementation of strtok() with local storage for the
136 *              next pointer. Not only thread-safe, but allows multiple
137 *              parsing of substrings such as expressions.
138 *
139 *****************************************************************************/
140
141char *
142PrGetNextToken (
143    char                    *Buffer,
144    char                    *MatchString,
145    char                    **Next)
146{
147    char                    *TokenStart;
148
149
150    if (!Buffer)
151    {
152        /* Use Next if it is valid */
153
154        Buffer = *Next;
155        if (!(*Next))
156        {
157            return (NULL);
158        }
159    }
160
161    /* Skip any leading delimiters */
162
163    while (*Buffer)
164    {
165        if (strchr (MatchString, *Buffer))
166        {
167            Buffer++;
168        }
169        else
170        {
171            break;
172        }
173    }
174
175    /* Anything left on the line? */
176
177    if (!(*Buffer))
178    {
179        *Next = NULL;
180        return (NULL);
181    }
182
183    TokenStart = Buffer;
184
185    /* Find the end of this token */
186
187    while (*Buffer)
188    {
189        if (strchr (MatchString, *Buffer))
190        {
191            *Buffer = 0;
192            *Next = Buffer+1;
193            if (!**Next)
194            {
195                *Next = NULL;
196            }
197
198            return (TokenStart);
199        }
200
201        Buffer++;
202    }
203
204    *Next = NULL;
205    return (TokenStart);
206}
207
208
209/*******************************************************************************
210 *
211 * FUNCTION:    PrError
212 *
213 * PARAMETERS:  Level               - Seriousness (Warning/error, etc.)
214 *              MessageId           - Index into global message buffer
215 *              Column              - Column in current line
216 *
217 * RETURN:      None
218 *
219 * DESCRIPTION: Preprocessor error reporting. Front end to AslCommonError2
220 *
221 ******************************************************************************/
222
223void
224PrError (
225    UINT8                   Level,
226    UINT16                  MessageId,
227    UINT32                  Column)
228{
229#if 0
230    AcpiOsPrintf ("%s (%u) : %s", Gbl_Files[ASL_FILE_INPUT].Filename,
231        Gbl_CurrentLineNumber, Gbl_CurrentLineBuffer);
232#endif
233
234
235    if (Column > 120)
236    {
237        Column = 0;
238    }
239
240    /* TBD: Need Logical line number? */
241
242    AslCommonError2 (Level, MessageId,
243        Gbl_CurrentLineNumber, Column,
244        Gbl_CurrentLineBuffer,
245        Gbl_Files[ASL_FILE_INPUT].Filename, "Preprocessor");
246
247    Gbl_PreprocessorError = TRUE;
248}
249
250
251/*******************************************************************************
252 *
253 * FUNCTION:    PrReplaceData
254 *
255 * PARAMETERS:  Buffer              - Original(target) buffer pointer
256 *              LengthToRemove      - Length to be removed from target buffer
257 *              BufferToAdd         - Data to be inserted into target buffer
258 *              LengthToAdd         - Length of BufferToAdd
259 *
260 * RETURN:      None
261 *
262 * DESCRIPTION: Generic buffer data replacement.
263 *
264 ******************************************************************************/
265
266void
267PrReplaceData (
268    char                    *Buffer,
269    UINT32                  LengthToRemove,
270    char                    *BufferToAdd,
271    UINT32                  LengthToAdd)
272{
273    UINT32                  BufferLength;
274
275
276    /* Buffer is a string, so the length must include the terminating zero */
277
278    BufferLength = strlen (Buffer) + 1;
279
280    if (LengthToRemove != LengthToAdd)
281    {
282        /*
283         * Move some of the existing data
284         * 1) If adding more bytes than removing, make room for the new data
285         * 2) if removing more bytes than adding, delete the extra space
286         */
287        if (LengthToRemove > 0)
288        {
289            memmove ((Buffer + LengthToAdd), (Buffer + LengthToRemove),
290                (BufferLength - LengthToRemove));
291        }
292    }
293
294    /* Now we can move in the new data */
295
296    if (LengthToAdd > 0)
297    {
298        memmove (Buffer, BufferToAdd, LengthToAdd);
299    }
300}
301
302
303/*******************************************************************************
304 *
305 * FUNCTION:    PrOpenIncludeFile
306 *
307 * PARAMETERS:  Filename            - Filename or pathname for include file
308 *
309 * RETURN:      None.
310 *
311 * DESCRIPTION: Open an include file and push it on the input file stack.
312 *
313 ******************************************************************************/
314
315FILE *
316PrOpenIncludeFile (
317    char                    *Filename,
318    char                    *OpenMode,
319    char                    **FullPathname)
320{
321    FILE                    *IncludeFile;
322    ASL_INCLUDE_DIR         *NextDir;
323
324
325    /* Start the actual include file on the next line */
326
327    Gbl_CurrentLineOffset++;
328
329    /* Attempt to open the include file */
330    /* If the file specifies an absolute path, just open it */
331
332    if ((Filename[0] == '/')  ||
333        (Filename[0] == '\\') ||
334        (Filename[1] == ':'))
335    {
336        IncludeFile = PrOpenIncludeWithPrefix (
337            "", Filename, OpenMode, FullPathname);
338        if (!IncludeFile)
339        {
340            goto ErrorExit;
341        }
342        return (IncludeFile);
343    }
344
345    /*
346     * The include filename is not an absolute path.
347     *
348     * First, search for the file within the "local" directory -- meaning
349     * the same directory that contains the source file.
350     *
351     * Construct the file pathname from the global directory name.
352     */
353    IncludeFile = PrOpenIncludeWithPrefix (
354        Gbl_DirectoryPath, Filename, OpenMode, FullPathname);
355    if (IncludeFile)
356    {
357        return (IncludeFile);
358    }
359
360    /*
361     * Second, search for the file within the (possibly multiple)
362     * directories specified by the -I option on the command line.
363     */
364    NextDir = Gbl_IncludeDirList;
365    while (NextDir)
366    {
367        IncludeFile = PrOpenIncludeWithPrefix (
368            NextDir->Dir, Filename, OpenMode, FullPathname);
369        if (IncludeFile)
370        {
371            return (IncludeFile);
372        }
373
374        NextDir = NextDir->Next;
375    }
376
377    /* We could not open the include file after trying very hard */
378
379ErrorExit:
380    sprintf (Gbl_MainTokenBuffer, "%s, %s", Filename, strerror (errno));
381    PrError (ASL_ERROR, ASL_MSG_INCLUDE_FILE_OPEN, 0);
382    return (NULL);
383}
384
385
386/*******************************************************************************
387 *
388 * FUNCTION:    FlOpenIncludeWithPrefix
389 *
390 * PARAMETERS:  PrefixDir       - Prefix directory pathname. Can be a zero
391 *                                length string.
392 *              Filename        - The include filename from the source ASL.
393 *
394 * RETURN:      Valid file descriptor if successful. Null otherwise.
395 *
396 * DESCRIPTION: Open an include file and push it on the input file stack.
397 *
398 ******************************************************************************/
399
400FILE *
401PrOpenIncludeWithPrefix (
402    char                    *PrefixDir,
403    char                    *Filename,
404    char                    *OpenMode,
405    char                    **FullPathname)
406{
407    FILE                    *IncludeFile;
408    char                    *Pathname;
409
410
411    /* Build the full pathname to the file */
412
413    Pathname = FlMergePathnames (PrefixDir, Filename);
414
415    DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
416        "Include: Opening file - \"%s\"\n",
417        Gbl_CurrentLineNumber, Pathname);
418
419    /* Attempt to open the file, push if successful */
420
421    IncludeFile = fopen (Pathname, OpenMode);
422    if (!IncludeFile)
423    {
424        fprintf (stderr, "Could not open include file %s\n", Pathname);
425        return (NULL);
426    }
427
428    /* Push the include file on the open input file stack */
429
430    PrPushInputFileStack (IncludeFile, Pathname);
431    *FullPathname = Pathname;
432    return (IncludeFile);
433}
434
435
436/*******************************************************************************
437 *
438 * FUNCTION:    AslPushInputFileStack
439 *
440 * PARAMETERS:  InputFile           - Open file pointer
441 *              Filename            - Name of the file
442 *
443 * RETURN:      None
444 *
445 * DESCRIPTION: Push the InputFile onto the file stack, and point the parser
446 *              to this file. Called when an include file is successfully
447 *              opened.
448 *
449 ******************************************************************************/
450
451void
452PrPushInputFileStack (
453    FILE                    *InputFile,
454    char                    *Filename)
455{
456    PR_FILE_NODE            *Fnode;
457
458
459    Gbl_HasIncludeFiles = TRUE;
460
461    /* Save the current state in an Fnode */
462
463    Fnode = UtLocalCalloc (sizeof (PR_FILE_NODE));
464
465    Fnode->File = Gbl_Files[ASL_FILE_INPUT].Handle;
466    Fnode->Next = Gbl_InputFileList;
467    Fnode->Filename = Gbl_Files[ASL_FILE_INPUT].Filename;
468    Fnode->CurrentLineNumber = Gbl_CurrentLineNumber;
469
470    /* Push it on the stack */
471
472    Gbl_InputFileList = Fnode;
473
474    DbgPrint (ASL_PARSE_OUTPUT, PR_PREFIX_ID
475        "Push InputFile Stack: handle %p\n\n",
476        Gbl_CurrentLineNumber, InputFile);
477
478    /* Reset the global line count and filename */
479
480    Gbl_Files[ASL_FILE_INPUT].Filename =
481        UtStringCacheCalloc (strlen (Filename) + 1);
482    strcpy (Gbl_Files[ASL_FILE_INPUT].Filename, Filename);
483
484    Gbl_Files[ASL_FILE_INPUT].Handle = InputFile;
485    Gbl_CurrentLineNumber = 1;
486
487    /* Emit a new #line directive for the include file */
488
489    FlPrintFile (ASL_FILE_PREPROCESSOR, "#line %u \"%s\"\n", 1, Filename);
490}
491
492
493/*******************************************************************************
494 *
495 * FUNCTION:    AslPopInputFileStack
496 *
497 * PARAMETERS:  None
498 *
499 * RETURN:      0 if a node was popped, -1 otherwise
500 *
501 * DESCRIPTION: Pop the top of the input file stack and point the parser to
502 *              the saved parse buffer contained in the fnode. Also, set the
503 *              global line counters to the saved values. This function is
504 *              called when an include file reaches EOF.
505 *
506 ******************************************************************************/
507
508BOOLEAN
509PrPopInputFileStack (
510    void)
511{
512    PR_FILE_NODE            *Fnode;
513
514
515    Fnode = Gbl_InputFileList;
516    DbgPrint (ASL_PARSE_OUTPUT, "\n" PR_PREFIX_ID
517        "Pop InputFile Stack, Fnode %p\n\n",
518        Gbl_CurrentLineNumber, Fnode);
519
520    if (!Fnode)
521    {
522        return (FALSE);
523    }
524
525    /* Close the current include file */
526
527    fclose (Gbl_Files[ASL_FILE_INPUT].Handle);
528
529    /* Update the top-of-stack */
530
531    Gbl_InputFileList = Fnode->Next;
532
533    /* Reset global line counter and filename */
534
535    Gbl_Files[ASL_FILE_INPUT].Filename = Fnode->Filename;
536    Gbl_Files[ASL_FILE_INPUT].Handle = Fnode->File;
537    Gbl_CurrentLineNumber = Fnode->CurrentLineNumber;
538
539    /* Emit a new #line directive after the include file */
540
541    FlPrintFile (ASL_FILE_PREPROCESSOR, "#line %u \"%s\"\n",
542        Gbl_CurrentLineNumber, Fnode->Filename);
543
544    /* All done with this node */
545
546    ACPI_FREE (Fnode);
547    return (TRUE);
548}
549