1 /******************************************************************************
3 * Module Name: aslutils -- compiler utilities
5 *****************************************************************************/
8 * Copyright (C) 2000 - 2015, Intel Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions, and the following disclaimer,
16 * without modification.
17 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
18 * substantially similar to the "NO WARRANTY" disclaimer below
19 * ("Disclaimer") and any redistribution must be conditioned upon
20 * including a substantially similar Disclaimer requirement for further
21 * binary redistribution.
22 * 3. Neither the names of the above-listed copyright holders nor the names
23 * of any contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
26 * Alternatively, this software may be distributed under the terms of the
27 * GNU General Public License ("GPL") version 2 as published by the Free
28 * Software Foundation.
31 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
34 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
40 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
41 * POSSIBILITY OF SUCH DAMAGES.
44 #include <contrib/dev/acpica/compiler/aslcompiler.h>
45 #include "aslcompiler.y.h"
46 #include <contrib/dev/acpica/include/acdisasm.h>
47 #include <contrib/dev/acpica/include/acnamesp.h>
48 #include <contrib/dev/acpica/include/amlcode.h>
49 #include <contrib/dev/acpica/include/acapps.h>
51 #define _COMPONENT ACPI_COMPILER
52 ACPI_MODULE_NAME ("aslutils")
55 /* Local prototypes */
58 UtPadNameWithUnderscores (
64 ACPI_PARSE_OBJECT *Op,
68 /*******************************************************************************
70 * FUNCTION: UtDisplaySupportedTables
76 * DESCRIPTION: Print all supported ACPI table names.
78 ******************************************************************************/
81 UtDisplaySupportedTables (
84 const AH_TABLE *TableData;
88 printf ("\nACPI tables supported by iASL version %8.8X:\n"
89 " (Compiler, Disassembler, Template Generator)\n\n",
92 /* All ACPI tables with the common table header */
94 printf ("\n Supported ACPI tables:\n");
95 for (TableData = AcpiSupportedTables, i = 1;
96 TableData->Signature; TableData++, i++)
98 printf ("%8u) %s %s\n", i,
99 TableData->Signature, TableData->Description);
104 /*******************************************************************************
106 * FUNCTION: UtDisplayConstantOpcodes
112 * DESCRIPTION: Print AML opcodes that can be used in constant expressions.
114 ******************************************************************************/
117 UtDisplayConstantOpcodes (
123 printf ("Constant expression opcode information\n\n");
125 for (i = 0; i < sizeof (AcpiGbl_AmlOpInfo) / sizeof (ACPI_OPCODE_INFO); i++)
127 if (AcpiGbl_AmlOpInfo[i].Flags & AML_CONSTANT)
129 printf ("%s\n", AcpiGbl_AmlOpInfo[i].Name);
135 /*******************************************************************************
137 * FUNCTION: UtLocalCalloc
139 * PARAMETERS: Size - Bytes to be allocated
141 * RETURN: Pointer to the allocated memory. Guaranteed to be valid.
143 * DESCRIPTION: Allocate zero-initialized memory. Aborts the compile on an
144 * allocation failure, on the assumption that nothing more can be
147 ******************************************************************************/
156 Allocated = ACPI_ALLOCATE_ZEROED (Size);
159 AslCommonError (ASL_ERROR, ASL_MSG_MEMORY_ALLOCATION,
160 Gbl_CurrentLineNumber, Gbl_LogicalLineNumber,
161 Gbl_InputByteCount, Gbl_CurrentColumn,
162 Gbl_Files[ASL_FILE_INPUT].Filename, NULL);
169 TotalAllocated += Size;
174 /*******************************************************************************
176 * FUNCTION: UtBeginEvent
178 * PARAMETERS: Name - Ascii name of this event
180 * RETURN: Event number (integer index)
182 * DESCRIPTION: Saves the current time with this event
184 ******************************************************************************/
191 if (AslGbl_NextEvent >= ASL_NUM_EVENTS)
193 AcpiOsPrintf ("Ran out of compiler event structs!\n");
194 return (AslGbl_NextEvent);
197 /* Init event with current (start) time */
199 AslGbl_Events[AslGbl_NextEvent].StartTime = AcpiOsGetTimer ();
200 AslGbl_Events[AslGbl_NextEvent].EventName = Name;
201 AslGbl_Events[AslGbl_NextEvent].Valid = TRUE;
203 return (AslGbl_NextEvent++);
207 /*******************************************************************************
209 * FUNCTION: UtEndEvent
211 * PARAMETERS: Event - Event number (integer index)
215 * DESCRIPTION: Saves the current time (end time) with this event
217 ******************************************************************************/
224 if (Event >= ASL_NUM_EVENTS)
229 /* Insert end time for event */
231 AslGbl_Events[Event].EndTime = AcpiOsGetTimer ();
235 /*******************************************************************************
237 * FUNCTION: UtConvertByteToHex
239 * PARAMETERS: RawByte - Binary data
240 * Buffer - Pointer to where the hex bytes will be
243 * RETURN: Ascii hex byte is stored in Buffer.
245 * DESCRIPTION: Perform hex-to-ascii translation. The return data is prefixed
248 ******************************************************************************/
259 Buffer[2] = (UINT8) AcpiUtHexToAsciiChar (RawByte, 4);
260 Buffer[3] = (UINT8) AcpiUtHexToAsciiChar (RawByte, 0);
264 /*******************************************************************************
266 * FUNCTION: UtConvertByteToAsmHex
268 * PARAMETERS: RawByte - Binary data
269 * Buffer - Pointer to where the hex bytes will be
272 * RETURN: Ascii hex byte is stored in Buffer.
274 * DESCRIPTION: Perform hex-to-ascii translation. The return data is prefixed
275 * with '0', and a trailing 'h' is added.
277 ******************************************************************************/
280 UtConvertByteToAsmHex (
286 Buffer[1] = (UINT8) AcpiUtHexToAsciiChar (RawByte, 4);
287 Buffer[2] = (UINT8) AcpiUtHexToAsciiChar (RawByte, 0);
292 /*******************************************************************************
296 * PARAMETERS: Type - Type of output
297 * Fmt - Printf format string
298 * ... - variable printf list
302 * DESCRIPTION: Conditional print statement. Prints to stderr only if the
305 ******************************************************************************/
321 if ((Type == ASL_PARSE_OUTPUT) &&
322 (!(AslCompilerdebug)))
327 va_start (Args, Fmt);
328 (void) vfprintf (stderr, Fmt, Args);
334 /*******************************************************************************
336 * FUNCTION: UtPrintFormattedName
338 * PARAMETERS: ParseOpcode - Parser keyword ID
339 * Level - Indentation level
343 * DESCRIPTION: Print the ascii name of the parse opcode.
345 ******************************************************************************/
347 #define TEXT_OFFSET 10
350 UtPrintFormattedName (
357 DbgPrint (ASL_TREE_OUTPUT,
358 "%*s", (3 * Level), " ");
360 DbgPrint (ASL_TREE_OUTPUT,
361 " %-20.20s", UtGetOpName (ParseOpcode));
363 if (Level < TEXT_OFFSET)
365 DbgPrint (ASL_TREE_OUTPUT,
366 "%*s", (TEXT_OFFSET - Level) * 3, " ");
371 /*******************************************************************************
373 * FUNCTION: UtSetParseOpName
375 * PARAMETERS: Op - Parse op to be named.
379 * DESCRIPTION: Insert the ascii name of the parse opcode
381 ******************************************************************************/
385 ACPI_PARSE_OBJECT *Op)
388 strncpy (Op->Asl.ParseOpName, UtGetOpName (Op->Asl.ParseOpcode),
389 ACPI_MAX_PARSEOP_NAME);
393 /*******************************************************************************
395 * FUNCTION: UtDisplaySummary
397 * PARAMETERS: FileID - ID of outpout file
401 * DESCRIPTION: Display compilation statistics
403 ******************************************************************************/
412 if (FileId != ASL_FILE_STDOUT)
414 /* Compiler name and version number */
416 FlPrintFile (FileId, "%s version %X%s\n\n",
417 ASL_COMPILER_NAME, (UINT32) ACPI_CA_VERSION, ACPI_WIDTH);
420 /* Summary of main input and output files */
422 if (Gbl_FileType == ASL_INPUT_TYPE_ASCII_DATA)
425 "%-14s %s - %u lines, %u bytes, %u fields\n",
427 Gbl_Files[ASL_FILE_INPUT].Filename, Gbl_CurrentLineNumber,
428 Gbl_InputByteCount, Gbl_InputFieldCount);
430 if ((Gbl_ExceptionCount[ASL_ERROR] == 0) || (Gbl_IgnoreErrors))
433 "%-14s %s - %u bytes\n",
435 Gbl_Files[ASL_FILE_AML_OUTPUT].Filename, Gbl_TableLength);
441 "%-14s %s - %u lines, %u bytes, %u keywords\n",
443 Gbl_Files[ASL_FILE_INPUT].Filename, Gbl_CurrentLineNumber,
444 Gbl_InputByteCount, TotalKeywords);
448 if ((Gbl_ExceptionCount[ASL_ERROR] == 0) || (Gbl_IgnoreErrors))
451 "%-14s %s - %u bytes, %u named objects, %u executable opcodes\n",
453 Gbl_Files[ASL_FILE_AML_OUTPUT].Filename, Gbl_TableLength,
454 TotalNamedObjects, TotalExecutableOpcodes);
458 /* Display summary of any optional files */
460 for (i = ASL_FILE_SOURCE_OUTPUT; i <= ASL_MAX_FILE_TYPE; i++)
462 if (!Gbl_Files[i].Filename || !Gbl_Files[i].Handle)
467 /* .SRC is a temp file unless specifically requested */
469 if ((i == ASL_FILE_SOURCE_OUTPUT) && (!Gbl_SourceOutputFlag))
474 /* .I is a temp file unless specifically requested */
476 if ((i == ASL_FILE_PREPROCESSOR) && (!Gbl_PreprocessorOutputFlag))
481 FlPrintFile (FileId, "%14s %s - %u bytes\n",
482 Gbl_Files[i].ShortDescription,
483 Gbl_Files[i].Filename, FlGetFileSize (i));
489 "\nCompilation complete. %u Errors, %u Warnings, %u Remarks",
490 Gbl_ExceptionCount[ASL_ERROR],
491 Gbl_ExceptionCount[ASL_WARNING] +
492 Gbl_ExceptionCount[ASL_WARNING2] +
493 Gbl_ExceptionCount[ASL_WARNING3],
494 Gbl_ExceptionCount[ASL_REMARK]);
496 if (Gbl_FileType != ASL_INPUT_TYPE_ASCII_DATA)
498 FlPrintFile (FileId, ", %u Optimizations",
499 Gbl_ExceptionCount[ASL_OPTIMIZATION]);
503 FlPrintFile (FileId, ", %u Constants Folded", TotalFolds);
507 FlPrintFile (FileId, "\n");
511 /*******************************************************************************
513 * FUNCTION: UtCheckIntegerRange
515 * PARAMETERS: Op - Integer parse node
516 * LowValue - Smallest allowed value
517 * HighValue - Largest allowed value
519 * RETURN: Op if OK, otherwise NULL
521 * DESCRIPTION: Check integer for an allowable range
523 ******************************************************************************/
526 UtCheckIntegerRange (
527 ACPI_PARSE_OBJECT *Op,
537 if ((Op->Asl.Value.Integer < LowValue) ||
538 (Op->Asl.Value.Integer > HighValue))
540 sprintf (MsgBuffer, "0x%X, allowable: 0x%X-0x%X",
541 (UINT32) Op->Asl.Value.Integer, LowValue, HighValue);
543 AslError (ASL_ERROR, ASL_MSG_RANGE, Op, MsgBuffer);
551 /*******************************************************************************
553 * FUNCTION: UtStringCacheCalloc
555 * PARAMETERS: Length - Size of buffer requested
557 * RETURN: Pointer to the buffer. Aborts on allocation failure
559 * DESCRIPTION: Allocate a string buffer. Bypass the local
560 * dynamic memory manager for performance reasons (This has a
561 * major impact on the speed of the compiler.)
563 ******************************************************************************/
566 UtStringCacheCalloc (
570 ASL_CACHE_INFO *Cache;
571 UINT32 CacheSize = ASL_STRING_CACHE_SIZE;
574 if (Length > CacheSize)
578 if (Gbl_StringCacheList)
580 Cache = UtLocalCalloc (sizeof (Cache->Next) + CacheSize);
582 /* Link new cache buffer just following head of list */
584 Cache->Next = Gbl_StringCacheList->Next;
585 Gbl_StringCacheList->Next = Cache;
587 /* Leave cache management pointers alone as they pertain to head */
590 Gbl_StringSize += Length;
592 return (Cache->Buffer);
596 if ((Gbl_StringCacheNext + Length) >= Gbl_StringCacheLast)
598 /* Allocate a new buffer */
600 Cache = UtLocalCalloc (sizeof (Cache->Next) + CacheSize);
602 /* Link new cache buffer to head of list */
604 Cache->Next = Gbl_StringCacheList;
605 Gbl_StringCacheList = Cache;
607 /* Setup cache management pointers */
609 Gbl_StringCacheNext = Cache->Buffer;
610 Gbl_StringCacheLast = Gbl_StringCacheNext + CacheSize;
614 Gbl_StringSize += Length;
616 Buffer = Gbl_StringCacheNext;
617 Gbl_StringCacheNext += Length;
622 /******************************************************************************
624 * FUNCTION: UtExpandLineBuffers
626 * PARAMETERS: None. Updates global line buffer pointers.
628 * RETURN: None. Reallocates the global line buffers
630 * DESCRIPTION: Called if the current line buffer becomes filled. Reallocates
631 * all global line buffers and updates Gbl_LineBufferSize. NOTE:
632 * Also used for the initial allocation of the buffers, when
633 * all of the buffer pointers are NULL. Initial allocations are
634 * of size ASL_DEFAULT_LINE_BUFFER_SIZE
636 *****************************************************************************/
639 UtExpandLineBuffers (
645 /* Attempt to double the size of all line buffers */
647 NewSize = Gbl_LineBufferSize * 2;
648 if (Gbl_CurrentLineBuffer)
650 DbgPrint (ASL_DEBUG_OUTPUT,
651 "Increasing line buffer size from %u to %u\n",
652 Gbl_LineBufferSize, NewSize);
655 Gbl_CurrentLineBuffer = realloc (Gbl_CurrentLineBuffer, NewSize);
656 Gbl_LineBufPtr = Gbl_CurrentLineBuffer;
657 if (!Gbl_CurrentLineBuffer)
662 Gbl_MainTokenBuffer = realloc (Gbl_MainTokenBuffer, NewSize);
663 if (!Gbl_MainTokenBuffer)
668 Gbl_MacroTokenBuffer = realloc (Gbl_MacroTokenBuffer, NewSize);
669 if (!Gbl_MacroTokenBuffer)
674 Gbl_ExpressionTokenBuffer = realloc (Gbl_ExpressionTokenBuffer, NewSize);
675 if (!Gbl_ExpressionTokenBuffer)
680 Gbl_LineBufferSize = NewSize;
684 /* On error above, simply issue error messages and abort, cannot continue */
687 printf ("Could not increase line buffer size from %u to %u\n",
688 Gbl_LineBufferSize, Gbl_LineBufferSize * 2);
690 AslError (ASL_ERROR, ASL_MSG_BUFFER_ALLOCATION,
696 /******************************************************************************
698 * FUNCTION: UtFreeLineBuffers
704 * DESCRIPTION: Free all line buffers
706 *****************************************************************************/
713 free (Gbl_CurrentLineBuffer);
714 free (Gbl_MainTokenBuffer);
715 free (Gbl_MacroTokenBuffer);
716 free (Gbl_ExpressionTokenBuffer);
720 /*******************************************************************************
722 * FUNCTION: UtInternalizeName
724 * PARAMETERS: ExternalName - Name to convert
725 * ConvertedName - Where the converted name is returned
729 * DESCRIPTION: Convert an external (ASL) name to an internal (AML) name
731 ******************************************************************************/
736 char **ConvertedName)
738 ACPI_NAMESTRING_INFO Info;
747 /* Get the length of the new internal name */
749 Info.ExternalName = ExternalName;
750 AcpiNsGetInternalNameLength (&Info);
752 /* We need a segment to store the internal name */
754 Info.InternalName = UtStringCacheCalloc (Info.Length);
755 if (!Info.InternalName)
757 return (AE_NO_MEMORY);
762 Status = AcpiNsBuildInternalName (&Info);
763 if (ACPI_FAILURE (Status))
768 *ConvertedName = Info.InternalName;
773 /*******************************************************************************
775 * FUNCTION: UtPadNameWithUnderscores
777 * PARAMETERS: NameSeg - Input nameseg
778 * PaddedNameSeg - Output padded nameseg
780 * RETURN: Padded nameseg.
782 * DESCRIPTION: Pads a NameSeg with underscores if necessary to form a full
785 ******************************************************************************/
788 UtPadNameWithUnderscores (
795 for (i = 0; (i < ACPI_NAME_SIZE); i++)
799 *PaddedNameSeg = *NameSeg;
804 *PaddedNameSeg = '_';
811 /*******************************************************************************
813 * FUNCTION: UtAttachNameseg
815 * PARAMETERS: Op - Parent parse node
816 * Name - Full ExternalName
818 * RETURN: None; Sets the NameSeg field in parent node
820 * DESCRIPTION: Extract the last nameseg of the ExternalName and store it
821 * in the NameSeg field of the Op.
823 ******************************************************************************/
827 ACPI_PARSE_OBJECT *Op,
831 char PaddedNameSeg[4];
839 /* Look for the last dot in the namepath */
841 NameSeg = strrchr (Name, '.');
844 /* Found last dot, we have also found the final nameseg */
847 UtPadNameWithUnderscores (NameSeg, PaddedNameSeg);
851 /* No dots in the namepath, there is only a single nameseg. */
852 /* Handle prefixes */
854 while (ACPI_IS_ROOT_PREFIX (*Name) ||
855 ACPI_IS_PARENT_PREFIX (*Name))
860 /* Remaining string should be one single nameseg */
862 UtPadNameWithUnderscores (Name, PaddedNameSeg);
865 ACPI_MOVE_NAME (Op->Asl.NameSeg, PaddedNameSeg);
869 /*******************************************************************************
871 * FUNCTION: UtAttachNamepathToOwner
873 * PARAMETERS: Op - Parent parse node
874 * NameOp - Node that contains the name
876 * RETURN: Sets the ExternalName and Namepath in the parent node
878 * DESCRIPTION: Store the name in two forms in the parent node: The original
879 * (external) name, and the internalized name that is used within
880 * the ACPI namespace manager.
882 ******************************************************************************/
885 UtAttachNamepathToOwner (
886 ACPI_PARSE_OBJECT *Op,
887 ACPI_PARSE_OBJECT *NameOp)
892 /* Full external path */
894 Op->Asl.ExternalName = NameOp->Asl.Value.String;
896 /* Save the NameOp for possible error reporting later */
898 Op->Asl.ParentMethod = (void *) NameOp;
900 /* Last nameseg of the path */
902 UtAttachNameseg (Op, Op->Asl.ExternalName);
904 /* Create internalized path */
906 Status = UtInternalizeName (NameOp->Asl.Value.String, &Op->Asl.Namepath);
907 if (ACPI_FAILURE (Status))
909 /* TBD: abort on no memory */
914 /*******************************************************************************
916 * FUNCTION: UtDoConstant
918 * PARAMETERS: String - Hex, Octal, or Decimal string
920 * RETURN: Converted Integer
922 * DESCRIPTION: Convert a string to an integer, with error checking.
924 ******************************************************************************/
935 Status = UtStrtoul64 (String, 0, &Converted);
936 if (ACPI_FAILURE (Status))
938 sprintf (ErrBuf, "%s %s\n", "Conversion error:",
939 AcpiFormatException (Status));
940 AslCompilererror (ErrBuf);
947 /* TBD: use version in ACPICA main code base? */
949 /*******************************************************************************
951 * FUNCTION: UtStrtoul64
953 * PARAMETERS: String - Null terminated string
954 * Terminater - Where a pointer to the terminating byte
956 * Base - Radix of the string
958 * RETURN: Converted value
960 * DESCRIPTION: Convert a string into an unsigned value.
962 ******************************************************************************/
972 UINT64 ReturnValue = 0;
973 ACPI_STATUS Status = AE_OK;
989 * The specified Base parameter is not in the domain of
992 return (AE_BAD_PARAMETER);
995 /* Skip over any white space in the buffer: */
997 while (isspace ((int) *String) || *String == '\t')
1003 * The buffer may contain an optional plus or minus sign.
1004 * If it does, then skip over it but remember what is was:
1011 else if (*String == '+')
1022 * If the input parameter Base is zero, then we need to
1023 * determine if it is octal, decimal, or hexadecimal:
1029 if (tolower ((int) *(++String)) == 'x')
1046 * For octal and hexadecimal bases, skip over the leading
1047 * 0 or 0x, if they are present.
1049 if (Base == 8 && *String == '0')
1056 tolower ((int) *(++String)) == 'x')
1061 /* Main loop: convert the string to an unsigned long */
1065 if (isdigit ((int) *String))
1067 Index = ((UINT8) *String) - '0';
1071 Index = (UINT8) toupper ((int) *String);
1072 if (isupper ((int) Index))
1074 Index = Index - 'A' + 10;
1087 /* Check to see if value is out of range: */
1089 if (ReturnValue > ((ACPI_UINT64_MAX - (UINT64) Index) /
1096 ReturnValue *= Base;
1097 ReturnValue += Index;
1104 /* If a minus sign was present, then "the conversion is negated": */
1106 if (Sign == NEGATIVE)
1108 ReturnValue = (ACPI_UINT32_MAX - ReturnValue) + 1;
1111 *RetInteger = ReturnValue;
1120 Status = AE_BAD_OCTAL_CONSTANT;
1125 Status = AE_BAD_DECIMAL_CONSTANT;
1130 Status = AE_BAD_HEX_CONSTANT;
1135 /* Base validated above */