Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-1335_emteere Fixes for #line in structures and function bodies, ternary expression evaluation, near/far keywords changed to __near __far, allow '*' in asm blocks

emteere7455e74a9d94
diff --git a/Ghidra/Features/Base/src/main/javacc/ghidra/app/util/cparser/C/C.jj b/Ghidra/Features/Base/src/main/javacc/ghidra/app/util/cparser/C/C.jj
index eff774718e..cc13fa4724 100644
--- a/Ghidra/Features/Base/src/main/javacc/ghidra/app/util/cparser/C/C.jj
+++ b/Ghidra/Features/Base/src/main/javacc/ghidra/app/util/cparser/C/C.jj
@@ -587,6 +587,16 @@ public class CParser {
return null;
}
+ Object computeTernaryValue(Object objTest, Object objTrue, Object objFalse) {
+ if (!(objTest instanceof Long)) {
+ return null;
+ }
+
+ Long testValue = (Long) objTest;
+ return (testValue != 0 ? objTrue : objFalse);
+ }
+
+
/**
* Get the data type manager
*
@@ -984,9 +994,9 @@ TOKEN :
|
<GOTO : "goto">
|
- <NEAR : "near">
+ <NEAR : "__near">
|
- <FAR : "far">
+ <FAR : "__far">
|
<FOR : "for">
|
@@ -2002,7 +2012,7 @@ Declaration DirectDeclarator(Declaration dt, DataType container) : {
{
(
(
- t= <IDENTIFIER> { dec= new Declaration(dt, t.image); }
+ t= <IDENTIFIER> { dec= new Declaration(dt, t.image); }
//****** working here Looks like should define a function here.
// if the data type in dec is a pointer, it should be a pointer.
// The function should be set locally so the param list can be applied.
@@ -2364,7 +2374,8 @@ void CompoundStatement() : {}
void StatementList() : {}
{
- ( Statement() )+
+ ( LineDef() |
+ Statement() )+
}
@@ -2376,10 +2387,6 @@ void AsmStatement() :
(
<ASM> [TypeQualifier(dec)]
(
-// ("(" AsmLine() ")" )
-// |
-// ("{" AsmLine() "}" )
-// |
( AsmLine() )
)
)
@@ -2390,31 +2397,10 @@ void AsmLine() :
Declaration dec = new Declaration();
}
{
- (<IDENTIFIER> | <STRING_LITERAL> | <INTEGER_LITERAL> | <ATTRIBUTE> | BuiltInTypeSpecifier(dec) | "#" | "+" | "-" | "," | ":" | ("[" AsmLine() "]") | ( "(" AsmLine() ")" ) | ( "{" AsmLine() "}" ) )+
+ (<IDENTIFIER> | <STRING_LITERAL> | <INTEGER_LITERAL> | <ATTRIBUTE> | BuiltInTypeSpecifier(dec) | "#" | "+" | "-" | "," | ":" | "*" | ("[" AsmLine() "]") | ( "(" AsmLine() ")" ) | ( "{" AsmLine() "}" ) )+
}
-//void AsmStatement() : {}
-//{
-// ( <ASM> (
-// ( "{" SubAsm() "}" )
-// |
-// ( "(" SubAsm() ")" )
-// |
-// ( <IDENTIFIER> | "," | "[" | "]" | "(" | ")" | "%" | <INTEGER_LITERAL> | <CHARACTER_LITERAL> )+ ("\r" | "\n)+
-// )
-// )
-//}
-
-//void SubAsm() : {}
-//{
-// ( "(" SubAsm() ")" ) |
-// ( <IDENTIFIER> | "," | "[" | "]" | "%" | <INTEGER_LITERAL> | <CHARACTER_LITERAL> )+
-// ( [ "(" SubAsm() ")" ] [ SubAsm() ] )
-// )
-//}
-
-
void SelectionStatement() : {}
{
(
@@ -2476,9 +2462,10 @@ void AssignmentOperator() : {}
Object ConditionalExpression() : {
Object obj = null;
+ Object objTrue = null, objFalse = null;
}
{
- obj = LogicalORExpression() [ "?" Expression() ":" ConditionalExpression() { obj=null; } ]
+ obj = LogicalORExpression() [ "?" objTrue=Expression() ":" objFalse=ConditionalExpression() { obj = computeTernaryValue(obj, objTrue, objFalse); } ]
{
return obj;
}
diff --git a/Ghidra/Features/Base/src/test/java/ghidra/app/util/cparser/CParserTest.java b/Ghidra/Features/Base/src/test/java/ghidra/app/util/cparser/CParserTest.java
new file mode 100644
index 0000000000..7a72bf570d
--- /dev/null
+++ b/Ghidra/Features/Base/src/test/java/ghidra/app/util/cparser/CParserTest.java
@@ -0,0 +1,418 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.cparser;
+
+import static org.junit.Assert.*;
+
+import java.io.InputStream;
+import java.util.ArrayList;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import generic.test.AbstractGenericTest;
+import ghidra.app.util.cparser.C.CParser;
+import ghidra.app.util.cparser.C.ParseException;
+import ghidra.program.model.data.*;
+import ghidra.program.model.data.Enum;
+
+public class CParserTest extends AbstractGenericTest {
+
+ public CParserTest() {
+ super();
+ }
+
+ /**
+ * This method just tries to parse a bunch o'
+ * data types just checking for stack traces.
+ */
+ @Test
+ public void testSimple() throws Exception {
+ CParser parser = new CParser();
+
+ DataType pdt = parser.parse("typedef long int32_t;");
+ assertTrue(pdt != null);
+ assertTrue(pdt instanceof TypeDef);
+ assertTrue(pdt.getName().equals("int32_t"));
+ DataType dt = parser.getDataTypeManager().getDataType("/int32_t");
+ assertTrue(dt != null);
+ assertTrue(dt instanceof TypeDef);
+ }
+
+ /**
+ * This method just tries to parse a bunch o'
+ * data types just checking for stack traces.
+ */
+ @Test
+ public void testLongLong() throws Exception {
+ CParser parser;
+
+ parser = new CParser();
+ DataType pdt64 = parser.parse("typedef unsigned long int uint64_t;");
+
+ assertTrue(pdt64 != null);
+ assertTrue(pdt64 instanceof TypeDef);
+ assertTrue(pdt64.getName().equals("uint64_t"));
+ assertEquals(4, pdt64.getLength());
+
+ DataType dt = parser.getDataTypeManager().getDataType("/uint64_t");
+ assertTrue(dt != null);
+ assertTrue(dt instanceof TypeDef);
+
+ parser = new CParser();
+ DataType pdt32 = parser.parse("typedef unsigned long long int uint64_t;");
+ assertTrue(pdt32 != null);
+ assertTrue(pdt32 instanceof TypeDef);
+ assertTrue(pdt32.getName().equals("uint64_t"));
+ assertEquals(8, pdt32.getLength());
+ }
+
+ @Test
+ public void testParseDataType_NoSubArchive() throws Exception {
+
+ DataTypeManager primary = new StandAloneDataTypeManager("primary");
+
+ DataTypeManager[] subs = new DataTypeManager[] {};
+
+ CParser parser = new CParser(primary, false, subs);
+ try {
+ parser.parse("void foo(bar *);");
+ Assert.fail("Expected an exception when the parser was missing a data type definition");
+ }
+ catch (ParseException e) {
+ // good!
+ }
+ }
+
+ @Test
+ public void testParseDataType_WithSubArchive() throws Exception {
+
+ DataTypeManager primary = new StandAloneDataTypeManager("primary");
+
+ DataTypeManager[] subs = new DataTypeManager[] { createDataTypeManagerWithABar() };
+
+ CParser parser = new CParser(primary, false, subs);
+ DataType result = parser.parse("void foo(bar *);");
+ assertNotNull(result);
+ }
+
+ private DataTypeManager createDataTypeManagerWithABar() {
+ DataTypeManager dtm = new StandAloneDataTypeManager("sub 0");
+
+ int txID = dtm.startTransaction("Add DataType");
+ try {
+ DataType dt = new StructureDataType("bar", 1);
+ dtm.addDataType(dt, DataTypeConflictHandler.REPLACE_HANDLER);
+ }
+ finally {
+ dtm.endTransaction(txID, true);
+ }
+
+ return dtm;
+ }
+
+ @Test
+ public void testPreProcessor() throws Exception {
+ // TODO: parse a header file with lots of CPP defines, etc
+ // TODO: Do a simple parse to make sure the data came out correctly
+ }
+
+ @Test
+ public void testHeaderParsing() throws Exception {
+// Uncomment to save the parse results to a GDT file to check out
+//
+// File fgdt = new File("/tmp/CParserTest.gdt");
+// fgdt.delete();
+// FileDataTypeManager fdt = FileDataTypeManager.createFileArchive(fgdt);
+// CParser parser = new CParser(fdt, true, null);
+// DataTypeManager dtMgr = fdt;
+
+ CParser parser = new CParser();
+
+ String resourceName;
+ resourceName = "CParserTest.h";
+ InputStream is = CParserTest.class.getResourceAsStream(resourceName);
+ // resourceName = "/home/mjtiern/CParserPlugin.out.sav";
+ // is = new FileInputStream(new File(resourceName));
+
+ parser.parse(is);
+ DataTypeManager dtMgr = parser.getDataTypeManager();
+
+ DataType dt;
+ String str;
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "fnptr"); // typedef int (*fnptr)(struct fstruct);
+ // "fnptr" named typedef of pointer to "int fnptr(fstruct )" --- should an anonymous function name be used?
+
+ dt = dtMgr.getDataType(new CategoryPath("/functions"), "_Once"); // void __cdecl _Once(_Once_t *, void (__cdecl *)(void));
+ // void _Once(_Once_t * , void * ) ---- 2nd param should be an anonymouse function * --> void (__cdecl *)(void)
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "UShortInt");
+ assertTrue(dt instanceof TypeDef);
+ assertTrue("signature not correct",
+ ((TypeDef) dt).getBaseDataType() instanceof UnsignedShortDataType);
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "ULongLong");
+ assertTrue(dt instanceof TypeDef);
+ assertTrue("signature not correct",
+ ((TypeDef) dt).getBaseDataType() instanceof UnsignedLongLongDataType);
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "SLongLong");
+ assertTrue(dt instanceof TypeDef);
+ assertTrue("signature not correct",
+ ((TypeDef) dt).getBaseDataType() instanceof LongLongDataType);
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "LongLong");
+ assertTrue(dt instanceof TypeDef);
+ assertTrue("signature not correct",
+ ((TypeDef) dt).getBaseDataType() instanceof LongLongDataType);
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "SShortInt");
+ assertTrue(dt instanceof TypeDef);
+ assertTrue("signature not correct",
+ ((TypeDef) dt).getBaseDataType() instanceof ShortDataType);
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "ShortInt");
+ assertTrue(dt instanceof TypeDef);
+ assertTrue("signature not correct",
+ ((TypeDef) dt).getBaseDataType() instanceof ShortDataType);
+
+ dt = dtMgr.getDataType(new CategoryPath("/functions"), "bob");
+ assertTrue("not a function", dt instanceof FunctionDefinition);
+ str = ((FunctionDefinition) dt).getPrototypeString();
+ assertTrue("signature not correct", str.equals("int bob(int b)"));
+
+ dt = dtMgr.getDataType(new CategoryPath("/functions"), "bobCRef");
+ assertTrue("not a function", dt instanceof FunctionDefinition);
+ str = ((FunctionDefinition) dt).getPrototypeString();
+ assertTrue("signature not correct",
+ str.equals("int bobCRef(int a, fstruct * fs, fstruct * fp)"));
+
+ dt = dtMgr.getDataType(new CategoryPath("/functions"), "stdcall_func");
+ assertTrue("not a function", dt instanceof FunctionDefinition);
+ str = ((FunctionDefinition) dt).getPrototypeString();
+ assertTrue("Callee should not purge", ((FunctionDefinition) dt)
+ .getGenericCallingConvention() == GenericCallingConvention.stdcall);
+ assertTrue("signature not correct", str.equals("int stdcall_func(int b)"));
+
+ dt = dtMgr.getDataType(new CategoryPath("/functions"), "cdecl_func");
+ assertTrue("not a function", dt instanceof FunctionDefinition);
+ str = ((FunctionDefinition) dt).getPrototypeString();
+ assertTrue("Caller should purge", ((FunctionDefinition) dt)
+ .getGenericCallingConvention() != GenericCallingConvention.stdcall);
+ assertTrue("signature not correct", str.equals("int cdecl_func(int a)"));
+
+ dt = dtMgr.getDataType(new CategoryPath("/functions"), "cdecl_func_after");
+ assertTrue("not a function", dt instanceof FunctionDefinition);
+ assertTrue("Caller should purge", ((FunctionDefinition) dt)
+ .getGenericCallingConvention() != GenericCallingConvention.stdcall);
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "UINT2");
+ assertTrue(dt instanceof TypeDef);
+ assertEquals("ushort", ((TypeDef) dt).getBaseDataType().getName());
+
+ dt = dtMgr.getDataType("/int32_t");
+ assertTrue(dt != null);
+ assertTrue(dt instanceof TypeDef);
+
+ // typedef long unsigned int LUI_size_t;
+ dt = dtMgr.getDataType("/LUI_size_t");
+ assertEquals("ulong", ((TypeDef) dt).getBaseDataType().getName());
+
+ // typedef unsigned long int ULI_size_t;
+ dt = dtMgr.getDataType("/ULI_size_t");
+ assertEquals("ulong", ((TypeDef) dt).getBaseDataType().getName());
+
+ // typedef long signed int LSI_size_t;
+ dt = dtMgr.getDataType("/LSI_size_t");
+ assertEquals("long", ((TypeDef) dt).getBaseDataType().getName());
+
+ // typedef long int LI_size_t;
+ dt = dtMgr.getDataType("/LI_size_t");
+ assertEquals("long", ((TypeDef) dt).getBaseDataType().getName());
+
+ // typedef long long int LLI_size_t;
+ dt = dtMgr.getDataType("/LLI_size_t");
+ assertEquals("longlong", ((TypeDef) dt).getBaseDataType().getName());
+
+ // typedef long unsigned long int LULI_size_t;
+ dt = dtMgr.getDataType("/LULI_size_t");
+ assertEquals("ulonglong", ((TypeDef) dt).getBaseDataType().getName());
+
+ // typedef unsigned long long int ULLI_size_t;
+ dt = dtMgr.getDataType("/ULLI_size_t");
+ assertEquals("ulonglong", ((TypeDef) dt).getBaseDataType().getName());
+
+ // typedef long long unsigned int LLUI_size_t;
+ dt = dtMgr.getDataType("/LLUI_size_t");
+ assertEquals("ulonglong", ((TypeDef) dt).getBaseDataType().getName());
+
+ // typedef unsigned int UI_size_t;
+ dt = dtMgr.getDataType("/UI_size_t");
+ assertEquals("uint", ((TypeDef) dt).getBaseDataType().getName());
+
+ dt = dtMgr.getDataType("/baz");
+ assertTrue(dt != null);
+ assertTrue(dt instanceof TypeDef);
+ assertTrue(((TypeDef) dt).getBaseDataType() instanceof Array);
+ Array adt = (Array) ((TypeDef) dt).getBaseDataType();
+ assertEquals(8, adt.getNumElements());
+ assertTrue(adt.getDataType() instanceof Array);
+ adt = (Array) adt.getDataType();
+ assertEquals(6, adt.getNumElements());
+
+ dt = dtMgr.getDataType("/outer");
+ assertTrue(dt != null);
+ assertTrue(dt instanceof Structure);
+ Structure sdt = (Structure) dt;
+ DataTypeComponent comp = sdt.getComponentAt(2);
+ assertEquals("sa", comp.getFieldName());
+ assertEquals(2, comp.getOffset());
+ comp = sdt.getComponentAt(4);
+ assertEquals("ia", comp.getFieldName());
+ assertEquals(4, comp.getOffset());
+ comp = sdt.getComponentAt(8);
+ assertEquals("cb", comp.getFieldName());
+ assertEquals(8, comp.getOffset());
+ comp = sdt.getComponentAt(10);
+ assertEquals("ib", comp.getFieldName());
+ assertEquals(10, comp.getOffset());
+ comp = sdt.getComponentAt(16);
+ assertEquals("cc", comp.getFieldName());
+ assertEquals(16, comp.getOffset());
+ // fdt.save();
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "options_enum");
+ assertTrue(dt instanceof Enum);
+ assertEquals("enum options_enum not correct", 0x4, ((Enum) dt).getValue("SUPPORTED"));
+ assertEquals("enum options_enum not correct", 0x5, ((Enum) dt).getValue("ONE_UP"));
+ assertEquals("enum options_enum not correct", 4 + 12, ((Enum) dt).getValue("PLUS_SET"));
+ assertEquals("enum options_enum not correct", 12 - 1, ((Enum) dt).getValue("MINUS_SET"));
+ assertEquals("enum options_enum not correct", 1 - 1 + 1, ((Enum) dt).getValue("ISONE"));
+ assertEquals("enum options_enum not correct", -5 - 1, ((Enum) dt).getValue("ISNEGATIVE"));
+ assertEquals("enum options_enum not correct", 64 * 16 + 16, ((Enum) dt).getValue("BIGNUM"));
+ assertEquals("enum options_enum not correct", 11, ((Enum) dt).getValue("TRINARY"));
+ assertEquals("enum options_enum not correct", 1 << 1 >> 1,
+ ((Enum) dt).getValue("SHIFTED1"));
+ assertEquals("enum options_enum not correct", 7 >> 3 << 3,
+ ((Enum) dt).getValue("SHIFTED3"));
+ assertEquals("enum options_enum not correct", 15 >> 3 << 3,
+ ((Enum) dt).getValue("SHIFTED4"));
+
+ dt = dtMgr.getDataType(new CategoryPath("/functions"), "__checkint");
+ assertTrue("not a function", dt instanceof FunctionDefinition);
+ str = ((FunctionDefinition) dt).getPrototypeString();
+ assertEquals("signature not correct", "int __checkint(int val, int * err)", str);
+
+ dt = dtMgr.getDataType(new CategoryPath("/functions"), "fputs");
+ assertTrue("not a function", dt instanceof FunctionDefinition);
+ str = ((FunctionDefinition) dt).getPrototypeString();
+ assertEquals("signature not correct", "int fputs(char * , void * )", str);
+
+ // ensure that temporary anonymous function definition names did not get retained
+ ArrayList<DataType> list = new ArrayList<>();
+ dtMgr.findDataTypes("_func_", list);
+ assertTrue(list.isEmpty());
+ dtMgr.findDataTypes("_func_1", list);
+ assertTrue(list.isEmpty());
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "EmptyBuffer");
+ assertTrue(dt instanceof Structure);
+ sdt = (Structure) dt;
+
+ assertTrue(sdt.hasFlexibleArrayComponent());
+
+ DataTypeComponent component = sdt.getFlexibleArrayComponent();
+ assertTrue(component.isFlexibleArrayComponent());
+
+ assertTrue(component.getDataType() instanceof CharDataType);
+ assertEquals("Size of the component is zero", 0, component.getLength());
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "BitFields1");
+ assertEquals("char size bitfield", 1, dt.getLength());
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "BitFields2");
+ assertEquals("char size overflow bitfield", 2, dt.getLength());
+
+ // bitfield is aligned
+ dt = dtMgr.getDataType(new CategoryPath("/"), "BitFields3");
+ assertEquals("char to int to char bitfield split", 4, dt.getLength());
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "BitFields4");
+ assertEquals("char to int to char bitfield split", 8, dt.getLength());
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "wait");
+ assertEquals("union of bitfields in structures with empty names", 8, dt.getLength());
+
+ dt = dtMgr.getDataType("/packed2");
+ assertTrue(dt instanceof Structure);
+ sdt = (Structure) dt;
+ assertEquals("Explicit packing", true, sdt.hasExplicitPackingValue());
+ assertEquals("Packing of packed2", 2, sdt.getExplicitPackingValue());
+ comp = sdt.getComponentAt(4); // int should be covering offset 4
+ assertEquals("d", comp.getFieldName());
+ assertEquals(2, comp.getOffset());
+
+ dt = dtMgr.getDataType("/packed4");
+ assertTrue(dt instanceof Structure);
+ sdt = (Structure) dt;
+ assertEquals("Explicit packing", true, sdt.hasExplicitPackingValue());
+ assertEquals("Packing of packed4", 4, sdt.getExplicitPackingValue());
+ comp = sdt.getComponentAt(4); // int should be covering offset 4
+ assertEquals("d", comp.getFieldName());
+ assertEquals(4, comp.getOffset());
+
+ // pack setting with no push/pop
+ dt = dtMgr.getDataType("/packed1");
+ assertTrue(dt instanceof Structure);
+ sdt = (Structure) dt;
+ assertEquals("Explicit packing", true, sdt.hasExplicitPackingValue());
+ assertEquals("Packing of packed1", 1, sdt.getExplicitPackingValue());
+
+ // pack setting with no push/pop
+ dt = dtMgr.getDataType("/packed_none");
+ assertTrue(dt instanceof Structure);
+ sdt = (Structure) dt;
+ assertEquals("Default packing", false, sdt.hasExplicitPackingValue());
+ assertEquals("Default packing", true, sdt.hasDefaultPacking());
+
+ // data type after #pragma got parsed
+ dt = dtMgr.getDataType("/functions/dtAfterPragma"); // typedef int (*fnptr)(struct fstruct);
+ assertNotNull("parsed datatype after #pragma", dt);
+ assertTrue(dt instanceof FunctionDefinition);
+ DataType returnType = ((FunctionDefinition) dt).getReturnType();
+ assertEquals("return type", "packed4 *", returnType.getName());
+
+ // test function definition typedef
+ dt = dtMgr.getDataType(new CategoryPath("/functions"), "range_t");
+ assertTrue("not a function", dt instanceof FunctionDefinition);
+
+ dt = dtMgr.getDataType(new CategoryPath("/functions"), "WNDPROC");
+
+ dt = dtMgr.getDataType(new CategoryPath("/functions"), "enumerator");
+ assertFalse("structure member anonymous function", dt instanceof FunctionDefinition);
+
+ dt = dtMgr.getDataType(new CategoryPath("/"), "ArraysInStruct");
+ sdt = (Structure) ((TypeDef) dt).getBaseDataType();
+ DataTypeComponent data8 = sdt.getComponent(4);
+ assertEquals("Computed Array correct", data8.getLength(), 32);
+ DataTypeComponent data16 = sdt.getComponent(5);
+ assertEquals("Computed Array correct", data16.getLength(), 64);
+ DataTypeComponent flex = sdt.getFlexibleArrayComponent();
+ assertEquals("Computed Array correct", 0, flex.getLength());
+
+ }
+}
diff --git a/Ghidra/Features/Base/src/test/java/ghidra/app/util/cparser/PreProcessorTest.java b/Ghidra/Features/Base/src/test/java/ghidra/app/util/cparser/PreProcessorTest.java
new file mode 100644
index 0000000000..118ee3088c
--- /dev/null
+++ b/Ghidra/Features/Base/src/test/java/ghidra/app/util/cparser/PreProcessorTest.java
@@ -0,0 +1,152 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.app.util.cparser;
+
+import static org.junit.Assert.*;
+
+import java.io.ByteArrayOutputStream;
+import java.net.URL;
+
+import org.junit.Test;
+
+import generic.test.AbstractGenericTest;
+import ghidra.app.util.cparser.CPP.PreProcessor;
+import ghidra.program.model.data.*;
+import ghidra.program.model.data.Enum;
+
+public class PreProcessorTest extends AbstractGenericTest {
+
+ public PreProcessorTest() {
+ super();
+ }
+
+ @Test
+ public void testHeaderParsing() throws Exception {
+ PreProcessor parser = new PreProcessor();
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ parser.setOutputStream(baos);
+
+//// String[] args = new String[] {"-I/local/VisualStudio/Windows/v7.0a/Include", "-I/local/VisualStudio/VS12/include", "-D_WIN32", "-D_CRT_SECURE_NO_WARNINGS"};
+// String[] args = new String[] {"-I/local/Mac/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include",
+// "-I/local/Mac/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/System/Library/Frameworks/Kernel.framework/Versions/A/Headers/",
+// "-D_LARGEFILE64_SOURCE=0","-D__GNUCC__=4.1","-D_DARWIN_C_SOURCE","-DBSD","-D__APPLE__","-D__x86_64__=1"};
+// parser.setArgs(args);
+// String fullName;
+// fullName = "mach/memory_object_types.h";
+// parser.parse(fullName);
+// fullName = "ctype.h";
+// parser.parse(fullName);
+//// fullName = "adoguids.h";
+//// parser.parse(fullName);
+
+ String resourceName = "PreProcessorTest.h";
+ URL url = PreProcessorTest.class.getResource(resourceName);
+
+ parser.parse(url.getFile());
+
+ // Uncomment to print out parse results
+ System.err.println(baos.toString());
+
+ String results = baos.toString("ASCII");
+ int end = results.lastIndexOf(";") + 1;
+ String endStr = results.substring(end - 9, end);
+ assertEquals("theEnd();", endStr);
+
+ assertTrue("macro expansion _fpl(bob) failed ", results
+ .indexOf("extern int __declspec(\"fp(\\\"l\\\", \" #bob \")\") __ifplbob;") != -1);
+
+ StandAloneDataTypeManager dtMgr = new StandAloneDataTypeManager("parsed");
+ parser.getDefinitions().populateDefineEquates(dtMgr);
+
+ CategoryPath path = new CategoryPath("/PreProcessorTest.h");
+ path = new CategoryPath(path, "defines");
+
+ long value = 32516;
+ String defname = "DefVal1";
+ checkDefine(dtMgr, path, value, defname);
+
+ value = 0x06010000 + 0xf1;
+ defname = "DefVal2";
+ checkDefine(dtMgr, path, value, defname);
+
+ value = 0x60010001 & 0x21234 | 1;
+ defname = "DefVal3";
+ checkDefine(dtMgr, path, value, defname);
+
+ value = 0x1 << (1 + 2 | 4);
+ defname = "DefVal4";
+ checkDefine(dtMgr, path, value, defname);
+
+ value = (0xFF000000L & (~(0x01000000L | 0x02000000L | 0x04000000L)));
+ defname = "DefVal5";
+ checkDefine(dtMgr, path, value, defname);
+
+ value = ((0x000F0000L) | (0x00100000L) | 0x3);
+ defname = "DefVal6";
+ checkDefine(dtMgr, path, value, defname);
+
+ value = 0x40000000L;
+ defname = "DefVal7";
+ checkDefine(dtMgr, path, value, defname);
+
+ value = ((3 << 13) | (3 << 9) | 4);
+ defname = "DefVal8";
+ checkDefine(dtMgr, path, value, defname);
+
+ value = ((0x7fff & ~(((1 << 4) - 1))));
+ defname = "DefVal9";
+ checkDefine(dtMgr, path, value, defname);
+
+ value = ((0x7fff) * 900L / 1000);
+ defname = "DefVal10";
+ checkDefine(dtMgr, path, value, defname);
+
+ value = 0;
+ defname = "TOO_MANY_FISH";
+ checkDefine(dtMgr, path, value, defname);
+
+ value = 0x53977;
+ defname = "ImOctal";
+ checkDefine(dtMgr, path, value, defname);
+
+ defname = "TEST_FAILED";
+ checkNotDefine(dtMgr, path, defname);
+
+ defname = "isDefineOnValue";
+ value = 1;
+ checkDefine(dtMgr, path, value, defname);
+
+ defname = "BIGNUM";
+ value = 64 * 16 + 16;
+ checkDefine(dtMgr, path, value, defname);
+ }
+
+ private void checkDefine(StandAloneDataTypeManager dtMgr, CategoryPath path, long value,
+ String defname) {
+ DataType dataType = dtMgr.getDataType(path, "define_" + defname);
+ String msg = "Define Enum " + defname;
+ assertNotNull(msg, dataType);
+ assertTrue(msg, dataType instanceof Enum);
+ assertEquals(msg, value, ((Enum) dataType).getValue(defname));
+ }
+
+ private void checkNotDefine(StandAloneDataTypeManager dtMgr, CategoryPath path,
+ String defname) {
+ DataType dataType = dtMgr.getDataType(path, "define_" + defname);
+ assertNull(dataType);
+ }
+}
diff --git a/Ghidra/Features/Base/src/test/resources/ghidra/app/util/cparser/CParserTest.h b/Ghidra/Features/Base/src/test/resources/ghidra/app/util/cparser/CParserTest.h
new file mode 100644
index 0000000000..79ef0a1c60
--- /dev/null
+++ b/Ghidra/Features/Base/src/test/resources/ghidra/app/util/cparser/CParserTest.h
@@ -0,0 +1,853 @@
+/* ###
+ * IP: Copyright
+ * EXCLUDE: YES
+ * NOTE:
+ */
+
+/** Test parsing header file for CParser. Most of the file is just checked to make sure it gets through parsing.
+ ** Some data types are checked. More checking of the parsed information would be beneficial at some point.
+ **/
+
+/**
+ ** use of long as an attribute
+ **/
+typedef long unsigned int LUI_size_t;
+typedef unsigned long int ULI_size_t;
+typedef long signed int LSI_size_t;
+typedef long int LI_size_t;
+typedef long long int LLI_size_t;
+typedef long unsigned long int LULI_size_t;
+typedef unsigned long long int ULLI_size_t;
+typedef long long unsigned int LLUI_size_t;
+typedef unsigned int UI_size_t;
+
+/**
+ ** pragma usage
+ **/
+int (__stdcall * GetSectionBlock) (
+ int section,
+ long len,
+ long align=1,
+ void **ppBytes=0) ;
+
+ #pragma region Input compatibility macros
+
+ #pragma warning(disable)
+
+ #pragma warning(disable:4035 4793) // re-enable below
+
+ #pragma section(".CRTMP$XCA",long,read)
+
+
+/**
+ ** Packing tests
+ **/
+ #pragma pack(push,2)
+
+ #pragma pack(push, PlaceHolder)
+
+ #pragma pack(push, 4)
+
+ __pragma(pack(push, MyName, 8))
+struct packed8 {
+ char a;
+ short b;
+ int c;
+ long d;
+ long long e;
+};
+__pragma(pack(pop, MyName))
+
+struct packed4 {
+ char a;
+ char b;
+ char c;
+ int d;
+};
+
+#pragma pack(pop, PlaceHolder)
+
+
+struct packed2 {
+ char a;
+ int d;
+};
+#pragma pack(pop)
+
+#pragma pack(1)
+
+struct packed1 {
+ char a;
+};
+
+#pragma pack(); // reset to none
+
+struct packed_none {
+ char a;
+};
+
+
+/**
+ ** Bitfield tests
+ **/
+struct BitFields1 {
+ char a:1;
+ char b:2;
+ char c:3;
+ char d:1;
+};
+
+struct BitFields2 {
+ char a:1;
+ char b:2;
+ char c:3;
+ char d:4;
+};
+
+struct BitFields3 {
+ char a:1;
+ char b:2;
+ char c:3;
+ int i:11;
+ char d:1;
+ char e:8;
+};
+
+struct BitFields4 {
+ unsigned long n0:4;
+ unsigned long n1:4;
+ unsigned long n2:4;
+ unsigned long n3:4;
+ unsigned long n4:4;
+ unsigned long n5:4;
+ unsigned long n6:4;
+ unsigned long n7:4;
+ unsigned long n8:4;
+ unsigned long n9:4;
+ unsigned long n10:4;
+ unsigned long n11:4;
+ unsigned long n12:4;
+ unsigned long n13:4;
+ unsigned long n14:4;
+ unsigned long n15:4;
+};
+
+union BitFields5 {
+ char a:1;
+ char b:2;
+ char c:3;
+ short i:11;
+ char d:1;
+ short s;
+ char e:8;
+ int f:23;
+};
+
+union wait
+{
+ int w_status;
+ struct
+ {
+ unsigned int t:7;
+ unsigned int c:1;
+ unsigned int r:8;
+ unsigned int:16;
+ } __wait_terminated;
+ struct
+ {
+ unsigned int v:8;
+ unsigned int s:8;
+ unsigned int:0;
+ unsigned int:8;
+ unsigned int:8;
+ } __wait_stopped;
+};
+
+
+ #pragma once
+
+packed4 *
+__stdcall
+ dtAfterPragma(int);
+
+/**
+ ** unnamed function decl in param
+ **/
+typedef long _Once_t;
+void __cdecl _Once(_Once_t *, void (__cdecl *)(void));
+
+
+/**
+ ** typdef data type definition and usage
+ **/
+typedef int *memory_object_info_t;
+typedef int memory_object_flavor_t;
+typedef int memory_object_info_data_t[(1024)];
+
+typedef void range_t(int, void *, unsigned type, void *, unsigned);
+
+typedef struct introspect_t {
+ void (*enumerator)(int task, void *, unsigned type_mask, int zone_address, int reader, range_t recorder);
+} introspect_t;
+
+
+typedef void (event_fun) (unsigned int type, void *arg,
+ unsigned int arg_size, void *user_data);
+
+extern int select_events (unsigned int mask,
+ event_fun *callback,
+ void *callback_data);
+
+int testForUseOfTypedef(int a, int b, int c) {
+ callOther(a, xp_event_fun, b);
+}
+
+int fputs( char * , void * ) __asm("_" "fputs" "$FPOOTS");
+
+void _exit(int) __attribute__((noreturn));
+
+int abs(int) __attribute__((bob));
+
+typedef int (__cdecl * _onexit_t)(void);
+
+typedef int int32_t;
+typedef long int64_t;
+
+static __inline __attribute__((always_inline)) int
+__checkint(int val, int* err) {
+ if (val < (-2147483647-1) || val > 2147483647) {
+ *err |= OVR_ERR;
+ }
+
+ return (int32_t) val;
+}
+
+typedef enum {} EmptyEnum;
+
+
+typedef struct fstruct;
+
+typedef int (*fnptr)(struct fstruct);
+
+
+
+/**
+ ** function declarations in a structure
+ **/
+struct {
+int ( __stdcall *Initialize )(
+ void * This,
+int *pUnkAD,
+int ( __stdcall __DHelper0000 )(
+ void *pv),
+void *pPool);
+
+int ( __stdcall *DoCallback )(
+ void * This,
+int *pUnkAD,
+int ( __stdcall __DHelper0001 )(
+ void *pv),
+void *pPool);
+
+} IDHelperVtbl;
+
+
+
+struct fowstruct {
+ fstruct *next;
+};
+
+@protocol Bubba
+bob
+marley
+@end
+
+typedef struct __attribute__ ((packed))
+{
+ int test1;
+ int test2;
+}testStruct;
+
+
+int bob(int b);
+
+
+typedef unsigned long long int ULONGLONG;
+typedef long long int LONGLONG;
+typedef int DWORD;
+
+
+typedef void (__stdcall COOLBACK)(int hdrvr, int uMsg, int * dwUser, int * dw1, int * dw2);
+
+typedef COOLBACK *LPCOOLBACK;
+
+typedef COOLBACK *PCOOLBACK;
+
+ typedef int size_t;
+ typedef int pid_t;
+
+/* struct cbs */
+struct cbs
+{
+ int (*init) (void);
+ int (*m_init) (void **p);
+ int (*m_destroy) (void **p);
+ int (*m_lock) (void **p);
+ int (*m_unlock) (void **p);
+ size_t (*read) (int fd, void *buf, size_t nbytes);
+ size_t (*write) (int fd, const void *buf, size_t nbytes);
+};
+
+/**
+ ** Union tests
+ **/
+ typedef union sigval
+ {
+ int sival_int;
+ void *sival_ptr;
+ } sigval_t;
+
+typedef struct sigevent
+ {
+ sigval_t sigev_value;
+ int sigev_signo;
+ int sigev_notify;
+
+ union {
+ int _pad[((64 / sizeof (int)) - 3)];
+
+
+ int _tid;
+
+ struct
+ {
+ void (*_function) (sigval_t);
+ void *_attribute;
+ } _sigev_thread;
+ } _sigev_un;
+ } sigevent_t;
+
+
+
+
+ void __mem_func (void *, char **, int ***, long (*) (size_t),
+ short *(*) (size_t),
+ void *(*) (void *, size_t));
+
+typedef unsigned short int UShortInt;
+typedef unsigned long long ULongLong;
+typedef signed long long SLongLong;
+typedef long long LongLong;
+typedef signed short int SShortInt;
+typedef short int ShortInt;
+
+typedef union { unsigned char __c[8]; double __d; } __huge_val_t;
+
+static __huge_val_t __huge_val = { { 0, 0, 0, 0, 0, 0, 0xf0, 0x7f } };
+
+typedef unsigned int error_t;
+
+static inline error_t
+make_error (error_t source, error_t code)
+{
+ char x = L'x';
+
+ return 1;
+}
+
+extern unsigned char AsciiTable[][8];
+
+unsigned short int __bswap_16 (unsigned short int __bsx)
+{
+ return ((((__bsx) >> 8) & 0xff) | (((__bsx) & 0xff) << 8));
+}
+
+struct bob {
+ int a;
+ int b;
+};
+
+
+/**
+ ** struct allocation with sizeof
+ **/
+struct sockaddr_in
+ {
+ int sin_family;
+ int sin_port;
+ struct in_addr sin_addr;
+
+
+ unsigned char sin_zero[sizeof (struct bob) -
+ (sizeof (unsigned short int)) -
+ sizeof (int) -
+ sizeof (struct bob)];
+ };
+
+struct __step;
+struct __step_data;
+struct __load_object;
+struct __trans_data;
+typedef int size_t;
+
+
+typedef int (*__gconv_fct) (struct __step *, struct __step_data *,
+ const unsigned char **, const unsigned char *,
+ unsigned char **, size_t *, int, int);
+
+
+typedef union __declspec(intrin_type) __declspec(align(8)) __m64
+{
+ unsigned __int64 m64_u64;
+ float m64_f32[2];
+ __int8 m64_i8[8];
+ __int16 m64_i16[4];
+ __int32 m64_i32[2];
+ __int64 m64_i64;
+ unsigned __int8 m64_u8[8];
+ unsigned __int16 m64_u16[4];
+ unsigned __int32 m64_u32[2];
+} __m64;
+
+extern __m64 _mm_loadh_pi1(__m64, const __m64 *);
+extern __m64 _mm_loadh_pi2(__m64, __m64 const *);
+
+__cdecl int cdecl_func(const int a);
+
+int __cdecl cdecl_func_after(const int a);
+
+int __stdcall stdcall_func(int b);
+
+// test default structure alignment
+struct inner {
+ char ca;
+ short sa;
+};
+
+struct outer {
+ char ca;
+ short sa; // @2
+ struct inner ia; // @4
+ char cb; // @8
+ struct inner ib; // @10
+ int cc; // @16
+};
+
+ typedef char wctype_t;
+
+ const wctype_t * __cdecl __pwctype_func(void);
+
+ const unsigned short * __cdecl __pctype_func(void);
+
+ extern const unsigned short *_pctype;
+
+ extern const unsigned short _wctype[];
+
+
+ extern const wctype_t *_pwctype;
+
+
+typedef long int32_t;
+
+extern int bob(int a);
+
+typedef int baz[8][6];
+
+void * IOPRepLoss(void *, void *, void *);
+
+typedef unsigned short int UINT2;
+
+typedef unsigned long POINTER_64_INT;
+
+
+typedef unsigned int DWORD;
+
+typedef struct _IFEntry {
+ DWORD BeginAddr;
+ DWORD EndAddr;
+ DWORD UnwindInfoAddr;
+} _IFEntry, *_pIFENtry;
+
+
+typedef signed char INT8, *PINT8;
+typedef signed short INT16, *PINT16;
+typedef signed int INT32, *PINT32;
+typedef signed __int64 INT64, *PINT64;
+typedef unsigned char UINT8, *PUINT8;
+typedef unsigned short UINT16, *PUINT16;
+typedef unsigned int UINT32, *PUINT32;
+typedef unsigned __int64 UINT64, *PUINT64;
+
+
+typedef signed int LONG32, *PLONG32;
+
+typedef unsigned int ULONG32, *PULONG32;
+typedef unsigned int DWORD32, *PDWORD32;
+
+
+typedef __w64 int INT_PTR, *PINT_PTR;
+typedef __w64 unsigned int UINT_PTR, *PUINT_PTR;
+
+typedef __w64 long LONG_PTR, *PLONG_PTR;
+typedef __w64 unsigned long ULONG_PTR, *PULONG_PTR;
+
+typedef unsigned short UHALF_PTR, *PUHALF_PTR;
+typedef short HALF_PTR, *PHALF_PTR;
+typedef __w64 long SHANDLE_PTR;
+typedef __w64 unsigned long HANDLE_PTR;
+
+
+__inline
+void * __ptr64
+PtrToPtr64(
+ const void *p
+ )
+{
+ return((void * __ptr64) (unsigned __int64) (ULONG_PTR)p );
+}
+
+__inline
+void *
+Ptr64ToPtr(
+ const void * __ptr64 p
+ )
+{
+ return((void *) (ULONG_PTR) (unsigned __int64) p);
+}
+
+__inline
+void * __ptr64
+HandleToHandle64(
+ const void *h
+ )
+{
+ return((void * __ptr64) h );
+}
+
+
+/**
+ ** pragma usage
+ **/
+__pragma(warning(push))
+__pragma(warning(disable: 6014))
+__declspec(noalias) __inline void __cdecl _freea( void * _mem)
+{
+ unsigned int _mark;
+ if (_mem)
+ {
+ __pragma(warning(push));
+ _mem = (char*)_mem - 8;
+ _mark = *(unsigned int *)_mem;
+
+ if (_mark == 0xDDDD)
+ {
+ free(_mem);
+ }
+ else if (_mark != 0xCCCC)
+ {
+ ((void)0);
+ }
+ __pragma(warning(pop));
+ }
+}
+
+__pragma(warning(pop))
+
+__inline void _set_daylight(int day) { __pragma(warning(push)) __pragma(warning(disable:4996)) (*__nightTime()) = day; __pragma(warning(pop)) }
+
+
+
+int __cdecl atexit(void (*)(void));
+
+/**
+ ** Array sizes with flex array
+ **/
+typedef struct _arraysInStruct
+ {
+ unsigned long A,B,C,D;
+ unsigned long data4[64>>3];
+ unsigned long flexOne[0];
+ unsigned long data16[(64/(4))];
+ unsigned int num;
+ unsigned long flexTwo[0];
+} ArraysInStruct;
+
+struct EmptyBuffer {
+ int x;
+ char buf[];
+};
+
+
+/**
+ ** Array Size allocation with expression
+ **/
+struct ivd {
+ char type[(1-1+1)];
+ char id[(6-2+1)];
+ char version[(7-7+1)];
+ char data[(2048-8+1)];
+};
+
+
+struct precedence {
+ char oneA[1-1+1];
+ char oneB[(1 << 1 >> 1)];
+ char version[1 - (1 >> 1 << 1)];
+ char data[(2048-8+1)];
+};
+
+/**
+ ** Calculated Enum values
+ **/
+enum options_enum {
+ DOBACKGROUND = 1 << 0,
+
+ DONEBACKROUND = 1 << 1,
+
+ SUPPORTED = 1 << 2,
+
+ /* one up value */
+
+ ONE_UP,
+
+ PLUS_SET = 4 + 12,
+
+ MINUS_SET = 12 - 1,
+
+ SHIFTED1 = 1 << 1 >> 1,
+
+ SHIFTED3 = 7 >> 3 << 3,
+
+ SHIFTED4 = 15 >> 3 << 3,
+
+ ISONE = 1 - 1 + 1,
+
+ ISNEGATIVE = -5-1,
+
+ BIGNUM = 64 * 16 + 16,
+
+ TRINARY = (0 ? 10 : 11),
+};
+
+
+/**
+ ** Casting
+ **/
+char * retInitedStorage(int i)
+{
+ char foo[3] = { 'a', 'b', 'c'};
+
+ return (char *) (void) { 'a', 'b', 'c'};
+}
+
+typedef float __m128 __attribute__ ((__vector_size__ (16), __may_alias__));
+
+
+typedef float __v4sf __attribute__ ((__vector_size__ (16)));
+
+extern __inline __m128 __attribute__((__gnu_inline__, __always_inline__, __artificial__))
+_mm_set1_ps (float __F)
+{
+ return (__m128) {0, 1, 2, 3};
+}
+
+
+/**
+ ** Structure Initializers / casting
+ **/
+struct { int a[3], b; } w[] =
+{
+ { { 1, 0, 0 }, 0 },
+ { { 2, 0, 0 }, 0 }
+};
+
+int *ptr = (int *){ 10, 20, 30, 40 };
+
+struct s {
+ int x;
+ float y;
+ char *z;
+};
+
+struct s pi = (struct s){ 3, 3.1415, "Pi" };
+
+struct s fs_pi = (struct s){ .z = "Pi", .x = 3, .y = 3.1415 };
+
+struct { int a[3], b; } w[] = { [0].a = {1}, [1].a[0] = 2 };
+
+
+
+typedef long long LRESULT;
+
+typedef LRESULT (__stdcall* WNDPROC)(HWND, UINT, WPARAM, LPARAM);
+
+
+/**
+ ** declspec directive
+ **/
+__declspec(deprecated("abc" "def"))
+void old_function(void);
+
+__declspec(deprecated("The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: " #_inpw ".")) unsigned short __cdecl inpw(unsigned short);
+
+__declspec(deprecated("The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: " #_getch() ".")) int __cdecl getch(void);
+
+
+__declspec(deprecated("This function || variable has been superceded by newer library || functionality. Consider using " #Bat " instead. See online help for details.")) int __cdecl _BatBall( char * name);
+__declspec(deprecated("This function || variable has been superceded by newer library || functionality. Consider using " #LA " instead. See online help for details.")) int __cdecl _LARun( int a);
+__declspec(deprecated("This function || variable has been superceded by newer library || functionality. Consider using " #GetA " instead. See online help for details.")) int (__cdecl * __cdecl _DoGood( int a, char * name, int oort))(void);
+
+
+extern "C" __declspec(dllexport) int __cdecl bobCRef(int a, const fstruct &fs, struct fstruct *fp);
+
+
+typedef unsigned int __uint32_t;
+
+/**
+ ** far pointer keyword use
+ **/
+struct arm_exception_state
+{
+ __uint32_t exception;
+ __uint32_t fsr;
+ __uint32_t far;
+};
+
+
+/**
+ ** Assembly Parsing
+ **/
+__forceinline
+long
+readInLine (
+ int count
+ )
+{
+ int i = 1;
+ int b = 0;
+ int c = 50;
+
+ __asm _volatile_ {
+ mov ecx, count
+ ret
+ };
+}
+
+
+__inline void * doIt( void ) { __asm {
+ mov eax, fs:[0x500]
+ mov eax,[eax]
+ };
+ }
+
+__inline long
+__stdcall
+iMod (
+ int v,
+ int sc
+ )
+{
+ __asm {
+ mov ecx, sc
+ mov eax, dword ptr [v]
+ mov edx, dword ptr [v+20]
+ pop edx, ebx
+ }
+}
+
+__inline int * accessT( void ) { __asm mov eax, fs:[0x8] }
+
+
+__forceinline
+long
+getOut (
+ void
+ )
+{
+ __asm rdtsc
+}
+
+__forceinline
+void
+assertFail (
+ void
+ )
+{
+ __asm int 0x2e
+}
+
+
+/**
+ ** More assembly block parsing (ignoring)
+ **/
+typedef int size_t;
+
+void simple_gnu_asm()
+{
+ asm(".intel_syntax noprefix");
+ asm ("call .L1 \n\t"
+ ".L1: \n\t"
+ "addw [esp],6 \n\t"
+ "ret \n\t"
+ );
+ asm("ret":::);
+ asm(".att_syntax noprefix");
+}
+
+unsigned long __readfsdword(unsigned long Offset)
+{
+ unsigned long ret;
+ __asm__ (
+ "mov{" "l" " %%" "fs" ":%[offset], %[ret] | %[ret], %%" "fs" ":%[offset]}"
+ : [ret] "=r" (ret)
+ : [offset] "m" ((int)Offset)
+ );
+ return ret;
+}
+
+typedef int size_t;
+
+unsigned long __readfsdword2(unsigned long Offset) { unsigned long ret; __asm__ ("mov{" "l" " %%" "fs" ":%[offset], %[ret] | %[ret], %%" "fs" ":%[offset]}" : [ret] "=r" (ret) : [offset] "m" ((*(unsigned long *) (size_t) Offset)) ); return ret; }
+
+unsigned char _interlockedbittestandset(long *Base, long Offset)
+{
+ unsigned char old;
+ __asm__ (
+ "lock bts{l %[Offset],%[Base] | %[Base],%[Offset]} ; setc %[old]"
+ : [old] "=qm" (old), [Base] "+m" (*Base)
+ : [Offset] "I" "r" "w" (Offset)
+ : "memory", "cc"
+ );
+ return old;
+}
+
+unsigned char _interlockedbittestandset2(long *Base, long Offset) { unsigned char old; __asm__ __volatile__ ("lock bts{l %[Offset],%[Base] | %[Base],%[Offset]} ; setc %[old]" : [old] "=qm" (old), [Base] "+m" (*Base) : [Offset] "I" "r" (Offset) : "memory", "cc"); return old; }
+/**/
+
+
+/**
+ ** #line in structure/function body
+ **/
+
+#line 1 "C:source/repos/ghidra_preprocess/structif.h"
+
+typedef struct mystruct {
+
+#line 8 "C:source/repos/ghidra_preprocess/structif.h"
+
+ int a;
+
+#line 8 "C:source/repos/ghidra_preprocess/structif.h"
+};
+#line 9 ""
+
+
+char lineInFunc(int i) {
+ #line 1 "first/line.h"
+ int j;
+
+ #line 2 "second/line.h"
+ return 'a';
+ #line 3 "third/line.h"
+ }
+
\ No newline at end of file
diff --git a/Ghidra/Features/Base/src/test/resources/ghidra/app/util/cparser/PreProcessorTest.h b/Ghidra/Features/Base/src/test/resources/ghidra/app/util/cparser/PreProcessorTest.h
new file mode 100644
index 0000000000..ceecb60cfc
--- /dev/null
+++ b/Ghidra/Features/Base/src/test/resources/ghidra/app/util/cparser/PreProcessorTest.h
@@ -0,0 +1,280 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+
+#ifndef _CRTIMP
+ #define _VCRT_DEFINED_CRTIMP
+ #if defined CRTDLL && defined _CRTBLD
+ #define _CRTIMP __declspec(dllexport)
+ #else
+ #ifdef _DLL
+ #define _CRTIMP __declspec(dllimport)
+ #else /* this is an else comment that goes to the next line
+ #define and this should be ignored */
+ #define _CRTIMP
+ #endif /* this is a endif comment that goes to the next line
+ #define and this should be ignored */
+ #endif
+#endif /* this is a comment that goes to the next line
+ #endif and this should be ignored */
+
+#define ONEFISH 1
+#define TWOFISH 2
+
+#if (ONEFISH + TWOFISH + REDFISH + BLUEFISH) > 2
+#error "Too many fish"
+#define TOO_MANY_FISH 0
+int TooManyFish;
+#endif
+
+#define TEST1 one
+
+#if defined(TEST1) + \
+ defined(TEST2) + \
+ defined(TEST3) > 1
+#error "Two or more defined, only one allowed of TEST1, TEST2, TEST3
+#define TEST_FAILED 1
+int TEST_FAILED;
+#endif
+
+#if !defined(__GNUC__) || __GNUC__ < 4
+#warning "Unsupported compiler detected"
+#endif
+
+#if defined(else) // end comment
+#error Cannot redefine C keywords
+#else STUPIDCOMMENT IS IGNORED
+#define ElseNotDefined TRUE
+#endif /* !_SYS_UNISTD_H_ */
+
+#define O_M 0xffff0000 // test commment
+#define N_V 0x60010001 // test comment
+
+#define K 0x06010000
+
+/**
+ ** Test Various define value simplification to Enum
+ **/
+#define DefVal1 (((ULONG_PTR)((WORD)(32516))))
+
+#define DefVal2 (((long) K + 0xf1))
+#define DefVal3 ((long ) ((long) N_V & 0x21234) | (( ULONG ) 1))
+
+#define DefVal4 ((long ) (0x1 << (1 + 2 | 4)))
+
+#define DefVal5 (0xFF000000 & (~(0x01000000 | 0x02000000 | 0x04000000)))
+
+#define DefVal6 ((0x000F0000L)|(0x00100000L)|0x3)
+
+#define DefVal7 0x40000000UL
+
+#define DefVal8 ((3 << 13)|(3 << 9)|4)
+
+#define DefVal9 ((0x7fff & ~(((1 << 4) - 1))))
+
+#define DefVal10 ((0x7fff) * 900L / 1000)
+
+#define BIGNUM 64 * 16 + 16
+
+#define ImOctal 01234567
+
+/**
+ ** Test for recursive definitions, Should not cause an infinite loop
+ **/
+#define AVERSION enum AVERSION
+AVERSION
+{
+ AVERSION_5 = 1,
+ AVERSION_6,
+ AVERSION_7,
+ AVERSION_8,
+};
+
+#define Group(a,b)
+
+#define _In Group(_In,a)
+
+int doit(_In int a);
+
+
+
+/**
+ ** test concat operator
+ **/
+
+#if (N_V >= K) // [
+int ntver_gt_nt2k(int a, int b);
+#endif
+
+#if ((O_M & N_V) == K)
+#error VM setting conflicts with N_V setting
+#endif
+
+// make a symbol
+#define $$doit(x, y) x ## y
+#define $doit(x, y) $$doit(x, y)
+#define $dosym(x) $doit(x, __cnt__)
+
+
+#define __mode(x) \
+ __declspec("marker(\"" #x "\")") \
+ __inline void $dosym(__dud_)(void){}
+
+__mode(Why);
+
+#define _fpf(t) __declspec("fp("f", " #t ")")
+#define _fpc(t) __declspec("fp(\"c\", " #t ")")
+#define _fpl(typ) extern int __declspec("fp(\"l\", " #typ ")") __ifpl##typ;
+
+_fpl(bob)
+
+#define BUILD_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
+ EXTERN_C const GUID DECLSPEC_SELECTANY name \
+ = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
+
+BUILD_GUID(LIBID_ADO20,0x##00000200,0x##0000,0x##0010,0x##80,0x##00,0x##00,0x##AA,0x##00,0x##6D,0x##2E,0x##A4)
+
+
+#define ___POSIX_C_DEPRECATED_STARTING_199506L
+
+#define __POSIX_C_DEPRECATED(ver) ___POSIX_C_DEPRECATED_STARTING_##ver
+
+int chroot(const char *) __POSIX_C_DEPRECATED(199506L);
+
+
+/**
+ ** Test for correct macro expansion truth evaluation in #if constructs
+ **/
+#define A 0x2
+#define B 0x1
+
+#define FAMILY_APP (B | A)
+
+#define FAMILY FAMILY_APP
+
+#define FUNC(v) ((FAMILY & v) == v)
+
+#if FUNC(A)
+#define isDefineOnValue 1
+#endif
+
+
+
+
+#define MEMORY_OBJECT_INFO_MAX (1024)
+typedef int *mem_info_t;
+typedef int mem_flavor_t;
+typedef int mem_info_data_t[MEMORY_OBJECT_INFO_MAX];
+
+
+#define PERF_INFO 11
+#define ATTR_INFO 14
+#define BEHAVE_INFO 15
+
+
+#define MEMORY_OBJECT_BEHAVE_INFO_COUNT ((mach_msg_type_number_t) \
+ (sizeof(memory_object_behave_info_data_t)/sizeof(int)))
+
+#define invalid_memory_object_flavor(f) \
+ (f != ATTR_INFO && \
+ f != PERF_INFO && \
+ f != OLD_BEHAVE_INFO && \
+ f != BEHAVE_INFO && \
+ f != OLD_ATTR_INFO)
+
+
+#define GET_IT(flags) \
+ ((((unsigned int)(flags)) >> 24) & 0xFF)
+
+#define SET_MEM(ca, flags) \
+ ((flags) = ((((unsigned int)(ca)) << 24) \
+ & 0xFF000000) | ((flags) & 0xFFFFFF));
+
+
+struct p_info {
+ unsigned int dummy[2]; /* dummy funcs */
+};
+
+
+typedef struct p_info p_info_t;
+typedef p_info_t *p_info_array_t;
+typedef p_info_array_t p_list_ptr_t;
+
+typedef uint32_t p_offset_t; /* offset */
+typedef uint32_t p_size_t; /* size */
+
+
+# define LDP(protos) protos
+
+#define LDP_CONST /* no const */
+
+ldp LDP((
+ LDP *ld,
+ LDP_CONST char *dn, /* usually NULL */
+ LDP_CONST char *saslMechanism,
+ LDPControl **sCont,
+
+ /* controls */
+ ungiend flag,
+ LDP_UNDEP *proc,
+ void *defaults,
+
+ /* result */
+ LDPValue *result,
+
+ /* installed */
+ const char **rm,
+ int *id ));
+
+#define SPECHSZ 64
+#if ((SPECHSZ&(SPECHSZ-1)) == 0)
+#define SPECHASH(d) (((d>>21)+(d))&(SPECHSZ-1))
+#else
+#define SPECHASH(d) (((unsigned)((d>>21)+(d)))%SPECHSZ)
+#endif
+
+
+
+#if -_LARGEFILE64_SOURCE - -1 == 1
+# undef _LARGEFILE64_SOURCE
+#endif
+
+/**
+ ** Multi line define
+ **/
+#define __MISMATCH_TAGS_PUSH \
+ _Pragma("clang diagnostic push") \
+ _Pragma("clang diagnostic ignored \"-Wmismatched-tags\"")
+
+
+#if defined(__has_include)
+#if __has_include(<gethostuuid_private.h>)
+int does_has_include_found();
+#else
+int does_has_include_not_found();
+#endif
+#else
+int does_not_has_include();
+#endif
+
+#if (defined(__MINGW32__) || defined(_MSC_VER)) && \
+ defined(__has_include_next) && __has_include_next(<float.h>)
+# include_next <float.h>
+#endif
+
+
+theEnd();