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_OriginalInputFileSize, TotalKeywords);
448 if ((Gbl_ExceptionCount[ASL_ERROR] == 0) || (Gbl_IgnoreErrors))
450 if (Gbl_Files[ASL_FILE_AML_OUTPUT].Handle)
453 "%-14s %s - %u bytes, %u named objects, %u executable opcodes\n",
455 Gbl_Files[ASL_FILE_AML_OUTPUT].Filename, Gbl_TableLength,
456 TotalNamedObjects, TotalExecutableOpcodes);
461 /* Display summary of any optional files */
463 for (i = ASL_FILE_SOURCE_OUTPUT; i <= ASL_MAX_FILE_TYPE; i++)
465 if (!Gbl_Files[i].Filename || !Gbl_Files[i].Handle)
470 /* .SRC is a temp file unless specifically requested */
472 if ((i == ASL_FILE_SOURCE_OUTPUT) && (!Gbl_SourceOutputFlag))
477 /* .PRE is the preprocessor intermediate file */
479 if ((i == ASL_FILE_PREPROCESSOR) && (!Gbl_KeepPreprocessorTempFile))
484 FlPrintFile (FileId, "%14s %s - %u bytes\n",
485 Gbl_Files[i].ShortDescription,
486 Gbl_Files[i].Filename, FlGetFileSize (i));
492 "\nCompilation complete. %u Errors, %u Warnings, %u Remarks",
493 Gbl_ExceptionCount[ASL_ERROR],
494 Gbl_ExceptionCount[ASL_WARNING] +
495 Gbl_ExceptionCount[ASL_WARNING2] +
496 Gbl_ExceptionCount[ASL_WARNING3],
497 Gbl_ExceptionCount[ASL_REMARK]);
499 if (Gbl_FileType != ASL_INPUT_TYPE_ASCII_DATA)
501 FlPrintFile (FileId, ", %u Optimizations",
502 Gbl_ExceptionCount[ASL_OPTIMIZATION]);
506 FlPrintFile (FileId, ", %u Constants Folded", TotalFolds);
510 FlPrintFile (FileId, "\n");
514 /*******************************************************************************
516 * FUNCTION: UtCheckIntegerRange
518 * PARAMETERS: Op - Integer parse node
519 * LowValue - Smallest allowed value
520 * HighValue - Largest allowed value
522 * RETURN: Op if OK, otherwise NULL
524 * DESCRIPTION: Check integer for an allowable range
526 ******************************************************************************/
529 UtCheckIntegerRange (
530 ACPI_PARSE_OBJECT *Op,
540 if ((Op->Asl.Value.Integer < LowValue) ||
541 (Op->Asl.Value.Integer > HighValue))
543 sprintf (MsgBuffer, "0x%X, allowable: 0x%X-0x%X",
544 (UINT32) Op->Asl.Value.Integer, LowValue, HighValue);
546 AslError (ASL_ERROR, ASL_MSG_RANGE, Op, MsgBuffer);
554 /*******************************************************************************
556 * FUNCTION: UtStringCacheCalloc
558 * PARAMETERS: Length - Size of buffer requested
560 * RETURN: Pointer to the buffer. Aborts on allocation failure
562 * DESCRIPTION: Allocate a string buffer. Bypass the local
563 * dynamic memory manager for performance reasons (This has a
564 * major impact on the speed of the compiler.)
566 ******************************************************************************/
569 UtStringCacheCalloc (
573 ASL_CACHE_INFO *Cache;
574 UINT32 CacheSize = ASL_STRING_CACHE_SIZE;
577 if (Length > CacheSize)
581 if (Gbl_StringCacheList)
583 Cache = UtLocalCalloc (sizeof (Cache->Next) + CacheSize);
585 /* Link new cache buffer just following head of list */
587 Cache->Next = Gbl_StringCacheList->Next;
588 Gbl_StringCacheList->Next = Cache;
590 /* Leave cache management pointers alone as they pertain to head */
593 Gbl_StringSize += Length;
595 return (Cache->Buffer);
599 if ((Gbl_StringCacheNext + Length) >= Gbl_StringCacheLast)
601 /* Allocate a new buffer */
603 Cache = UtLocalCalloc (sizeof (Cache->Next) + CacheSize);
605 /* Link new cache buffer to head of list */
607 Cache->Next = Gbl_StringCacheList;
608 Gbl_StringCacheList = Cache;
610 /* Setup cache management pointers */
612 Gbl_StringCacheNext = Cache->Buffer;
613 Gbl_StringCacheLast = Gbl_StringCacheNext + CacheSize;
617 Gbl_StringSize += Length;
619 Buffer = Gbl_StringCacheNext;
620 Gbl_StringCacheNext += Length;
625 /******************************************************************************
627 * FUNCTION: UtExpandLineBuffers
629 * PARAMETERS: None. Updates global line buffer pointers.
631 * RETURN: None. Reallocates the global line buffers
633 * DESCRIPTION: Called if the current line buffer becomes filled. Reallocates
634 * all global line buffers and updates Gbl_LineBufferSize. NOTE:
635 * Also used for the initial allocation of the buffers, when
636 * all of the buffer pointers are NULL. Initial allocations are
637 * of size ASL_DEFAULT_LINE_BUFFER_SIZE
639 *****************************************************************************/
642 UtExpandLineBuffers (
648 /* Attempt to double the size of all line buffers */
650 NewSize = Gbl_LineBufferSize * 2;
651 if (Gbl_CurrentLineBuffer)
653 DbgPrint (ASL_DEBUG_OUTPUT,
654 "Increasing line buffer size from %u to %u\n",
655 Gbl_LineBufferSize, NewSize);
658 Gbl_CurrentLineBuffer = realloc (Gbl_CurrentLineBuffer, NewSize);
659 Gbl_LineBufPtr = Gbl_CurrentLineBuffer;
660 if (!Gbl_CurrentLineBuffer)
665 Gbl_MainTokenBuffer = realloc (Gbl_MainTokenBuffer, NewSize);
666 if (!Gbl_MainTokenBuffer)
671 Gbl_MacroTokenBuffer = realloc (Gbl_MacroTokenBuffer, NewSize);
672 if (!Gbl_MacroTokenBuffer)
677 Gbl_ExpressionTokenBuffer = realloc (Gbl_ExpressionTokenBuffer, NewSize);
678 if (!Gbl_ExpressionTokenBuffer)
683 Gbl_LineBufferSize = NewSize;
687 /* On error above, simply issue error messages and abort, cannot continue */
690 printf ("Could not increase line buffer size from %u to %u\n",
691 Gbl_LineBufferSize, Gbl_LineBufferSize * 2);
693 AslError (ASL_ERROR, ASL_MSG_BUFFER_ALLOCATION,
699 /******************************************************************************
701 * FUNCTION: UtFreeLineBuffers
707 * DESCRIPTION: Free all line buffers
709 *****************************************************************************/
716 free (Gbl_CurrentLineBuffer);
717 free (Gbl_MainTokenBuffer);
718 free (Gbl_MacroTokenBuffer);
719 free (Gbl_ExpressionTokenBuffer);
723 /*******************************************************************************
725 * FUNCTION: UtInternalizeName
727 * PARAMETERS: ExternalName - Name to convert
728 * ConvertedName - Where the converted name is returned
732 * DESCRIPTION: Convert an external (ASL) name to an internal (AML) name
734 ******************************************************************************/
739 char **ConvertedName)
741 ACPI_NAMESTRING_INFO Info;
750 /* Get the length of the new internal name */
752 Info.ExternalName = ExternalName;
753 AcpiNsGetInternalNameLength (&Info);
755 /* We need a segment to store the internal name */
757 Info.InternalName = UtStringCacheCalloc (Info.Length);
758 if (!Info.InternalName)
760 return (AE_NO_MEMORY);
765 Status = AcpiNsBuildInternalName (&Info);
766 if (ACPI_FAILURE (Status))
771 *ConvertedName = Info.InternalName;
776 /*******************************************************************************
778 * FUNCTION: UtPadNameWithUnderscores
780 * PARAMETERS: NameSeg - Input nameseg
781 * PaddedNameSeg - Output padded nameseg
783 * RETURN: Padded nameseg.
785 * DESCRIPTION: Pads a NameSeg with underscores if necessary to form a full
788 ******************************************************************************/
791 UtPadNameWithUnderscores (
798 for (i = 0; (i < ACPI_NAME_SIZE); i++)
802 *PaddedNameSeg = *NameSeg;
807 *PaddedNameSeg = '_';
814 /*******************************************************************************
816 * FUNCTION: UtAttachNameseg
818 * PARAMETERS: Op - Parent parse node
819 * Name - Full ExternalName
821 * RETURN: None; Sets the NameSeg field in parent node
823 * DESCRIPTION: Extract the last nameseg of the ExternalName and store it
824 * in the NameSeg field of the Op.
826 ******************************************************************************/
830 ACPI_PARSE_OBJECT *Op,
834 char PaddedNameSeg[4];
842 /* Look for the last dot in the namepath */
844 NameSeg = strrchr (Name, '.');
847 /* Found last dot, we have also found the final nameseg */
850 UtPadNameWithUnderscores (NameSeg, PaddedNameSeg);
854 /* No dots in the namepath, there is only a single nameseg. */
855 /* Handle prefixes */
857 while (ACPI_IS_ROOT_PREFIX (*Name) ||
858 ACPI_IS_PARENT_PREFIX (*Name))
863 /* Remaining string should be one single nameseg */
865 UtPadNameWithUnderscores (Name, PaddedNameSeg);
868 ACPI_MOVE_NAME (Op->Asl.NameSeg, PaddedNameSeg);
872 /*******************************************************************************
874 * FUNCTION: UtAttachNamepathToOwner
876 * PARAMETERS: Op - Parent parse node
877 * NameOp - Node that contains the name
879 * RETURN: Sets the ExternalName and Namepath in the parent node
881 * DESCRIPTION: Store the name in two forms in the parent node: The original
882 * (external) name, and the internalized name that is used within
883 * the ACPI namespace manager.
885 ******************************************************************************/
888 UtAttachNamepathToOwner (
889 ACPI_PARSE_OBJECT *Op,
890 ACPI_PARSE_OBJECT *NameOp)
895 /* Full external path */
897 Op->Asl.ExternalName = NameOp->Asl.Value.String;
899 /* Save the NameOp for possible error reporting later */
901 Op->Asl.ParentMethod = (void *) NameOp;
903 /* Last nameseg of the path */
905 UtAttachNameseg (Op, Op->Asl.ExternalName);
907 /* Create internalized path */
909 Status = UtInternalizeName (NameOp->Asl.Value.String, &Op->Asl.Namepath);
910 if (ACPI_FAILURE (Status))
912 /* TBD: abort on no memory */
917 /*******************************************************************************
919 * FUNCTION: UtDoConstant
921 * PARAMETERS: String - Hex, Octal, or Decimal string
923 * RETURN: Converted Integer
925 * DESCRIPTION: Convert a string to an integer, with error checking.
927 ******************************************************************************/
938 Status = stroul64 (String, 0, &Converted);
939 if (ACPI_FAILURE (Status))
941 sprintf (ErrBuf, "%s %s\n", "Conversion error:",
942 AcpiFormatException (Status));
943 AslCompilererror (ErrBuf);
950 /* TBD: use version in ACPICA main code base? */
952 /*******************************************************************************
956 * PARAMETERS: String - Null terminated string
957 * Terminater - Where a pointer to the terminating byte
959 * Base - Radix of the string
961 * RETURN: Converted value
963 * DESCRIPTION: Convert a string into an unsigned value.
965 ******************************************************************************/
975 UINT64 ReturnValue = 0;
976 ACPI_STATUS Status = AE_OK;
992 * The specified Base parameter is not in the domain of
995 return (AE_BAD_PARAMETER);
998 /* Skip over any white space in the buffer: */
1000 while (isspace ((int) *String) || *String == '\t')
1006 * The buffer may contain an optional plus or minus sign.
1007 * If it does, then skip over it but remember what is was:
1014 else if (*String == '+')
1025 * If the input parameter Base is zero, then we need to
1026 * determine if it is octal, decimal, or hexadecimal:
1032 if (tolower ((int) *(++String)) == 'x')
1049 * For octal and hexadecimal bases, skip over the leading
1050 * 0 or 0x, if they are present.
1052 if (Base == 8 && *String == '0')
1059 tolower ((int) *(++String)) == 'x')
1064 /* Main loop: convert the string to an unsigned long */
1068 if (isdigit ((int) *String))
1070 Index = ((UINT8) *String) - '0';
1074 Index = (UINT8) toupper ((int) *String);
1075 if (isupper ((int) Index))
1077 Index = Index - 'A' + 10;
1090 /* Check to see if value is out of range: */
1092 if (ReturnValue > ((ACPI_UINT64_MAX - (UINT64) Index) /
1099 ReturnValue *= Base;
1100 ReturnValue += Index;
1107 /* If a minus sign was present, then "the conversion is negated": */
1109 if (Sign == NEGATIVE)
1111 ReturnValue = (ACPI_UINT32_MAX - ReturnValue) + 1;
1114 *RetInteger = ReturnValue;
1123 Status = AE_BAD_OCTAL_CONSTANT;
1128 Status = AE_BAD_DECIMAL_CONSTANT;
1133 Status = AE_BAD_HEX_CONSTANT;
1138 /* Base validated above */