-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path2727-Proper-C-Parser-GhidraClangPoweredParse.patch
More file actions
5929 lines (5926 loc) · 226 KB
/
Copy path2727-Proper-C-Parser-GhidraClangPoweredParse.patch
File metadata and controls
5929 lines (5926 loc) · 226 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: PlayDay <18056374+playday3008@users.noreply.github.com>
Date: Thu, 26 Mar 2026 15:59:00 +0100
Subject: [PATCH] 2727: Proper C++ Parser (GhidraClangPoweredParse)
---
Ghidra/Features/Base/certification.manifest | 26 +
.../java/ghidra/app/util/gcpp/GCPPPlugin.java | 352 ++++++
.../util/gcpp/clang/CallingConvention.java | 53 +
.../ghidra/app/util/gcpp/clang/Cursor.java | 346 ++++++
.../app/util/gcpp/clang/CursorKind.java | 313 +++++
.../app/util/gcpp/clang/Diagnostic.java | 71 ++
.../ghidra/app/util/gcpp/clang/Index.java | 49 +
.../util/gcpp/clang/JavaVersionHelper.java | 47 +
.../ghidra/app/util/gcpp/clang/LibClang.java | 955 ++++++++++++++++
.../app/util/gcpp/clang/SourceLocation.java | 68 ++
.../app/util/gcpp/clang/TranslationUnit.java | 231 ++++
.../java/ghidra/app/util/gcpp/clang/Type.java | 199 ++++
.../ghidra/app/util/gcpp/clang/TypeKind.java | 115 ++
.../util/gcpp/clang/error/ParseErrorCode.java | 36 +
.../util/gcpp/clang/error/ParseException.java | 22 +
.../gcpp/processing/ArchitectureMapping.java | 260 +++++
.../app/util/gcpp/processing/ParsedEnum.java | 27 +
.../gcpp/processing/ParsedFunctionType.java | 71 ++
.../util/gcpp/processing/ParsedStructure.java | 81 ++
.../app/util/gcpp/processing/ParsedType.java | 20 +
.../util/gcpp/processing/ParsedTypedef.java | 27 +
.../app/util/gcpp/processing/ParsedUnion.java | 60 +
.../util/gcpp/processing/ParsedVtable.java | 93 ++
.../util/gcpp/processing/SourceParser.java | 625 ++++++++++
.../app/util/gcpp/processing/TypePool.java | 319 ++++++
.../app/util/gcpp/task/ClangParseTask.java | 212 ++++
.../app/util/gcpp/ui/ClangParseDialog.java | 1005 +++++++++++++++++
.../RuntimeScripts/support/launch.properties | 6 +
28 files changed, 5689 insertions(+)
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/GCPPPlugin.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/CallingConvention.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/Cursor.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/CursorKind.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/Diagnostic.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/Index.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/JavaVersionHelper.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/LibClang.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/SourceLocation.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/TranslationUnit.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/Type.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/TypeKind.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/error/ParseErrorCode.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/error/ParseException.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/processing/ArchitectureMapping.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/processing/ParsedEnum.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/processing/ParsedFunctionType.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/processing/ParsedStructure.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/processing/ParsedType.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/processing/ParsedTypedef.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/processing/ParsedUnion.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/processing/ParsedVtable.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/processing/SourceParser.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/processing/TypePool.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/task/ClangParseTask.java
create mode 100644 Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/ui/ClangParseDialog.java
diff --git a/Ghidra/Features/Base/certification.manifest b/Ghidra/Features/Base/certification.manifest
index 8fcedb9297..75c3cfa6e5 100644
--- a/Ghidra/Features/Base/certification.manifest
+++ b/Ghidra/Features/Base/certification.manifest
@@ -837,6 +837,32 @@ src/main/java/ghidra/app/util/bin/format/stabs/types/StabsTypeModifierTypeDescri
src/main/java/ghidra/app/util/bin/format/stabs/types/StabsTypeReferenceTypeDescriptor.java||GHIDRA||||END|
src/main/java/ghidra/app/util/bin/package.html||GHIDRA||||END|
src/main/java/ghidra/app/util/exporter/package.html||GHIDRA||||END|
+src/main/java/ghidra/app/util/gcpp/GCPPPlugin.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/clang/CallingConvention.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/clang/Cursor.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/clang/CursorKind.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/clang/Diagnostic.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/clang/Index.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/clang/LibClang.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/clang/JavaVersionHelper.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/clang/SourceLocation.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/clang/TranslationUnit.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/clang/Type.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/clang/TypeKind.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/clang/error/ParseErrorCode.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/clang/error/ParseException.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/processing/ArchitectureMapping.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/processing/ParsedEnum.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/processing/ParsedFunctionType.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/processing/ParsedStructure.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/processing/ParsedType.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/processing/ParsedTypedef.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/processing/ParsedUnion.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/processing/ParsedVtable.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/processing/SourceParser.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/processing/TypePool.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/task/ClangParseTask.java||Apache License 2.0||||END|
+src/main/java/ghidra/app/util/gcpp/ui/ClangParseDialog.java||Apache License 2.0||||END|
src/main/java/ghidra/app/util/importer/package.html||GHIDRA||||END|
src/main/java/ghidra/app/util/opinion/package.html||GHIDRA||||END|
src/main/java/ghidra/app/util/package.html||GHIDRA||||END|
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/GCPPPlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/GCPPPlugin.java
new file mode 100644
index 0000000000..26d4517dfe
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/GCPPPlugin.java
@@ -0,0 +1,352 @@
+/**
+ * Copyright 2024 playday3008
+ * Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
+ * provided that the above copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
+ * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+ * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+package ghidra.app.util.gcpp;
+
+import docking.ActionContext;
+import docking.action.DockingAction;
+import docking.action.MenuData;
+import docking.tool.ToolConstants;
+import docking.widgets.OptionDialog;
+import ghidra.app.CorePluginPackage;
+import ghidra.app.plugin.PluginCategoryNames;
+import ghidra.app.plugin.ProgramPlugin;
+import ghidra.app.services.DataTypeManagerService;
+import ghidra.app.util.gcpp.clang.error.ParseException;
+import ghidra.app.util.gcpp.processing.SourceParser;
+import ghidra.app.util.gcpp.processing.TypePool;
+import ghidra.app.util.gcpp.task.ClangParseTask;
+import ghidra.app.util.gcpp.ui.ClangParseDialog;
+import ghidra.framework.Application;
+import ghidra.framework.options.SaveState;
+import ghidra.framework.plugintool.PluginInfo;
+import ghidra.framework.plugintool.PluginTool;
+import ghidra.framework.plugintool.util.PluginStatus;
+import ghidra.program.database.data.ProgramDataTypeManager;
+import ghidra.program.model.data.BuiltInDataTypeManager;
+import ghidra.program.model.data.DataType;
+import ghidra.program.model.data.DataTypeConflictHandler;
+import ghidra.program.model.data.DataTypeManager;
+import ghidra.program.model.lang.LanguageCompilerSpecPair;
+import ghidra.program.model.listing.Program;
+import ghidra.util.*;
+import ghidra.util.exception.CancelledException;
+import ghidra.util.task.TaskMonitor;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+@PluginInfo(
+ status = PluginStatus.STABLE,
+ packageName = CorePluginPackage.NAME,
+ category = PluginCategoryNames.ANALYSIS,
+ shortDescription = "Clang C/C++ Parser",
+ description = GCPPPlugin.DESCRIPTION,
+ servicesRequired = { DataTypeManagerService.class }
+)
+public class GCPPPlugin extends ProgramPlugin
+{
+ private static final Logger LOGGER = LogManager.getLogger();
+
+ static final String DESCRIPTION =
+ "Parse C and C++ header files using libclang, extracting data type definitions.";
+
+ private ClangParseDialog parseDialog;
+ private File userProfileDir;
+
+ public GCPPPlugin(PluginTool plugintool)
+ {
+ super(plugintool);
+ createActions();
+ userProfileDir = new File(
+ Application.getUserSettingsDirectory().getAbsolutePath() +
+ File.separatorChar + "parserprofiles");
+ userProfileDir.mkdir();
+ }
+
+ public File getUserProfileDir()
+ {
+ return userProfileDir;
+ }
+
+ public Program getProgram()
+ {
+ return currentProgram;
+ }
+
+ public ClangParseDialog getDialog()
+ {
+ return parseDialog;
+ }
+
+ @Override
+ public void dispose()
+ {
+ if (parseDialog != null)
+ {
+ parseDialog.close();
+ parseDialog = null;
+ }
+ }
+
+ @Override
+ public void readDataState(SaveState saveState)
+ {
+ parseDialog = new ClangParseDialog(this);
+ parseDialog.readState(saveState);
+ }
+
+ @Override
+ public void writeDataState(SaveState saveState)
+ {
+ if (parseDialog != null)
+ parseDialog.writeState(saveState);
+ }
+
+ @Override
+ protected boolean canClose()
+ {
+ if (parseDialog != null)
+ parseDialog.closeProfile();
+ return true;
+ }
+
+ private void createActions()
+ {
+ DockingAction parseAction = new DockingAction("Parse C/C++ Source (Clang Powered)", getName())
+ {
+ @Override
+ public void actionPerformed(ActionContext context)
+ {
+ showParseDialog();
+ }
+ };
+ String[] menuPath = { ToolConstants.MENU_FILE, "Parse C/C++ Source (Clang Powered)..." };
+ MenuData menuData = new MenuData(menuPath, "Import/Export");
+ menuData.setMenuSubGroup("d");
+ parseAction.setMenuBarData(menuData);
+ parseAction.setDescription(DESCRIPTION);
+ parseAction.setEnabled(true);
+ tool.addAction(parseAction);
+ }
+
+ private void showParseDialog()
+ {
+ if (parseDialog == null)
+ parseDialog = new ClangParseDialog(this);
+ parseDialog.setupForDisplay();
+ tool.showDialog(parseDialog);
+ }
+
+ /**
+ * Parse to the current program's DataTypeManager.
+ */
+ public void parse(String[] filenames, String[] includePaths, String options)
+ {
+ if (currentProgram == null)
+ {
+ Msg.showInfo(getClass(), parseDialog.getComponent(), "No Open Program",
+ "A program must be open to \"Parse to Program\"");
+ return;
+ }
+
+ LanguageCompilerSpecPair lcsPair = currentProgram.getLanguageCompilerSpecPair();
+ String procID = lcsPair.languageID.getIdAsString();
+ String compilerID = lcsPair.compilerSpecID.getIdAsString();
+
+ int confirm = OptionDialog.showOptionDialog(parseDialog.getComponent(), "Confirm",
+ "Parse C/C++ source to \"" + currentProgram.getDomainFile().getName() + "\"?" + "\n\n" +
+ "Using program architecture: " + procID + " / " + compilerID, "Continue");
+
+ if (confirm == OptionDialog.CANCEL_OPTION)
+ return;
+
+ DataTypeManager[] openDTMgrs;
+ try
+ {
+ openDTMgrs = getOpenDTMgrs();
+ }
+ catch (CancelledException e)
+ {
+ return;
+ }
+
+ ClangParseTask task = new ClangParseTask(this, currentProgram.getDataTypeManager())
+ .setFileNames(filenames)
+ .setIncludePaths(includePaths)
+ .setOptions(options)
+ .setOpenArchives(openDTMgrs);
+
+ tool.execute(task);
+ }
+
+ /**
+ * Parse to a file (creates a new .gdt archive).
+ */
+ public void parse(String[] filenames, String[] includePaths, String options,
+ String languageIDString, String compilerSpecID, String dataFilename)
+ {
+ DataTypeManager[] openDTMgrs;
+ try
+ {
+ openDTMgrs = getOpenDTMgrs();
+ }
+ catch (CancelledException e)
+ {
+ return;
+ }
+
+ ClangParseTask task = new ClangParseTask(this, dataFilename)
+ .setFileNames(filenames)
+ .setIncludePaths(includePaths)
+ .setOptions(options)
+ .setLanguageID(languageIDString)
+ .setCompilerID(compilerSpecID)
+ .setOpenArchives(openDTMgrs);
+
+ tool.execute(task, 500);
+ }
+
+ /**
+ * Prompt the user whether to use currently open archives for type resolution.
+ * Matches the behavior of the built-in CParserPlugin.
+ *
+ * @return array of open DTMs to use, or null if user chose not to use them
+ * @throws CancelledException if user cancelled
+ */
+ private DataTypeManager[] getOpenDTMgrs() throws CancelledException
+ {
+ DataTypeManagerService dtService = tool.getService(DataTypeManagerService.class);
+ if (dtService == null)
+ return null;
+
+ DataTypeManager[] allDTMs = dtService.getDataTypeManagers();
+
+ ArrayList<DataTypeManager> list = new ArrayList<>();
+ StringBuilder htmlNamesList = new StringBuilder();
+ for (DataTypeManager dtm : allDTMs)
+ {
+ if (dtm instanceof ProgramDataTypeManager)
+ continue;
+ list.add(dtm);
+ if (!(dtm instanceof BuiltInDataTypeManager))
+ htmlNamesList.append("<li><b>").append(HTMLUtilities.escapeHTML(dtm.getName())).append("</b></li>");
+ }
+
+ DataTypeManager[] openDTMgrs = list.toArray(new DataTypeManager[0]);
+
+ if (openDTMgrs.length > 1)
+ {
+ int result = OptionDialog.showOptionDialog(
+ parseDialog.getComponent(), "Use Open Archives?",
+ "<html>The following archives are currently open: " +
+ "<ul>" + htmlNamesList + "</ul>" +
+ "<p><b>The new archive will become dependent on these archives<br>" +
+ "for any datatypes already defined in them </b>(only unique <br>" +
+ "data types will be added to the new archive).",
+ "Use Open Archives", "Don't Use Open Archives", OptionDialog.QUESTION_MESSAGE);
+
+ if (result == OptionDialog.CANCEL_OPTION)
+ throw new CancelledException("User Cancelled");
+ if (result == OptionDialog.OPTION_TWO)
+ return null;
+ }
+
+ return openDTMgrs;
+ }
+
+ /**
+ * Core parse method called by {@link ClangParseTask}.
+ * Parses source files via libclang, resolves types, and commits them to the DTM.
+ *
+ * @param filenames source files to parse
+ * @param includePaths include directories for header resolution
+ * @param options parse options (one per line, e.g. -D flags)
+ * @param dtMgr target DataTypeManager to commit types to
+ * @param languageId Ghidra LanguageID string (e.g. "x86:LE:64:default")
+ * @param compilerSpec Ghidra CompilerSpecID string (e.g. "gcc", "windows")
+ * @param openArchives additional DTMs to use for type resolution (may be null)
+ * @param monitor task monitor for progress reporting
+ * @return diagnostic messages from clang
+ * @throws ParseException if clang parsing fails
+ */
+ public String parseWithClang(String[] filenames, String[] includePaths, String options,
+ DataTypeManager dtMgr, String languageId, String compilerSpec,
+ DataTypeManager[] openArchives, TaskMonitor monitor)
+ throws ParseException
+ {
+ TypePool typePool = new TypePool(openArchives);
+ try
+ {
+ // Phase 1: Parse with clang
+ monitor.setMessage("Parsing " + filenames.length + " source file(s) with clang...");
+ SourceParser parser = new SourceParser();
+
+ List<String> diagnostics = parser.parseFiles(typePool, filenames, includePaths, options, languageId, compilerSpec);
+
+ // Phase 2: Resolve type dependencies
+ monitor.setMessage("Resolving type dependencies...");
+ TypePool.ResolutionResult result = typePool.resolve();
+
+ // Phase 3: Commit resolved types to the target DTM
+ List<DataType> dataTypes = result.getDataTypes();
+ monitor.setMessage("Committing " + dataTypes.size() + " data types...");
+ monitor.setMaximum(dataTypes.size());
+ monitor.setProgress(0);
+
+ int transaction = dtMgr.startTransaction("Add clang-parsed data types");
+ try
+ {
+ int count = 0;
+ for (DataType t : dataTypes)
+ {
+ monitor.setProgress(++count);
+ monitor.setMessage("Adding: " + t.getName());
+ try
+ {
+ dtMgr.addDataType(t, DataTypeConflictHandler.REPLACE_HANDLER);
+ }
+ catch (Exception e)
+ {
+ LOGGER.warn("Failed to add type: " + t.getName(), e);
+ }
+ }
+ }
+ finally
+ {
+ dtMgr.endTransaction(transaction, true);
+ }
+
+ // Build result message with diagnostics and any unresolved warnings
+ StringBuilder messages = new StringBuilder();
+ if (!diagnostics.isEmpty())
+ messages.append(String.join("\n", diagnostics));
+
+ var unresolved = result.getUnresolvedDependencies();
+ if (!unresolved.isEmpty())
+ {
+ LOGGER.warn("Unresolved type dependencies (skipped): " + unresolved);
+ if (!messages.isEmpty())
+ messages.append("\n");
+ messages.append(unresolved.size()).append(" types skipped due to unresolved dependencies.");
+ }
+
+ return messages.toString();
+ }
+ finally
+ {
+ typePool.close();
+ }
+ }
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/CallingConvention.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/CallingConvention.java
new file mode 100644
index 0000000000..62099166a9
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/CallingConvention.java
@@ -0,0 +1,53 @@
+package ghidra.app.util.gcpp.clang;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public enum CallingConvention {
+ DEFAULT(0, "__cdecl"),
+ C(1, "__cdecl"),
+ X86_STDCALL(2, "__stdcall"),
+ X86_FASTCALL(3, "__fastcall"),
+ X86_THISCALL(4, "__thiscall"),
+ X86_PASCAL(5, "__pascal"),
+ AAPCS(6, "__cdecl"),
+ AAPCS_VFP(7, "__cdecl"),
+ X86_REGCALL(8, "__regcall"),
+ INTEL_OCL_BICC(9, "__cdecl"),
+ WIN64(10, "__fastcall"),
+ X86_64_SYSV(11, "__cdecl"),
+ X86_VECTORCALL(12, "__vectorcall"),
+ SWIFT(13, "__cdecl"),
+ PRESERVE_MOST(14, "__cdecl"),
+ PRESERVE_ALL(15, "__cdecl"),
+ AARCH64_VECTORCALL(16, "__cdecl"),
+ SWIFT_ASYNC(17, "__cdecl"),
+ AARCH64_SVE_PCS(18, "__cdecl"),
+ INVALID(100, null),
+ UNEXPOSED(200, null);
+
+ private final int value;
+ private final String ghidraName;
+ private static final Map<Integer, CallingConvention> BY_VALUE = new HashMap<>();
+
+ static {
+ for (var v : values()) BY_VALUE.put(v.value, v);
+ }
+
+ CallingConvention(int value, String ghidraName) {
+ this.value = value;
+ this.ghidraName = ghidraName;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ public String getGhidraName() {
+ return ghidraName;
+ }
+
+ public static CallingConvention fromInteger(int value) {
+ return BY_VALUE.get(value);
+ }
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/Cursor.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/Cursor.java
new file mode 100644
index 0000000000..64b5d9ede7
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/Cursor.java
@@ -0,0 +1,346 @@
+package ghidra.app.util.gcpp.clang;
+
+import java.lang.foreign.Arena;
+import java.lang.foreign.MemorySegment;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import java.util.List;
+
+/**
+ * A cursor representing some element in the abstract syntax tree for
+ * a translation unit.
+ * <p>
+ * The cursor abstraction unifies the different kinds of entities in a
+ * program (declarations, statements, expressions, references to declarations,
+ * etc.) under a single "cursor" abstraction with a common set of operations.
+ * <p>
+ * Wraps a {@code CXCursor} struct (passed by value as a MemorySegment).
+ */
+public final class Cursor {
+
+ private final MemorySegment segment;
+ private final Arena arena;
+
+ // Thread-locals for visitor callback bridge
+ private static final ThreadLocal<CursorVisitor> CURRENT_VISITOR = new ThreadLocal<>();
+ private static final ThreadLocal<Arena> CURRENT_ARENA = new ThreadLocal<>();
+
+ /**
+ * Creates a Cursor wrapping the given CXCursor segment.
+ *
+ * @param segment the CXCursor memory segment (must be CX_CURSOR.byteSize() bytes)
+ * @param arena the arena used for allocating return-by-value structs
+ */
+ Cursor(MemorySegment segment, Arena arena) {
+ this.segment = segment;
+ this.arena = arena;
+ }
+
+ /**
+ * Returns the underlying CXCursor memory segment.
+ */
+ MemorySegment getSegment() {
+ return segment;
+ }
+
+ // ========================================================================
+ // Cursor properties
+ // ========================================================================
+
+ /**
+ * Return the kind of this cursor.
+ */
+ public CursorKind kind() {
+ int kindVal = LibClang.getCursorKind(segment);
+ return CursorKind.fromInteger(kindVal);
+ }
+
+ /**
+ * Return the spelling of the entity pointed at by the cursor.
+ */
+ public String spelling() {
+ MemorySegment cxStr = LibClang.getCursorSpelling(arena, segment);
+ return LibClang.extractString(arena, cxStr);
+ }
+
+ /**
+ * Return the display name for the entity referenced by this cursor.
+ * <p>
+ * The display name contains extra information that helps identify the
+ * cursor, such as the parameters of a function or template or the
+ * arguments of a class template specialization.
+ */
+ public String displayName() {
+ MemorySegment cxStr = LibClang.getCursorDisplayName(arena, segment);
+ return LibClang.extractString(arena, cxStr);
+ }
+
+ /**
+ * Retrieve the Type (if any) of the entity pointed at by the cursor.
+ */
+ public Type type() {
+ MemorySegment typeSeg = LibClang.getCursorType(arena, segment);
+ return new Type(typeSeg, arena);
+ }
+
+ /**
+ * Return the underlying type of a typedef declaration.
+ */
+ public Type underlyingTypedefType() {
+ MemorySegment typeSeg = LibClang.getTypedefDeclUnderlyingType(arena, segment);
+ return new Type(typeSeg, arena);
+ }
+
+ /**
+ * Return the integer type of an enum declaration.
+ */
+ public Type enumType() {
+ MemorySegment typeSeg = LibClang.getEnumDeclIntegerType(arena, segment);
+ return new Type(typeSeg, arena);
+ }
+
+ /**
+ * Return the value of an enum constant.
+ * <p>
+ * Automatically selects signed or unsigned retrieval based on the
+ * underlying enum integer type.
+ */
+ public long enumValue() {
+ Type underlyingType = this.type();
+
+ // If the type is ENUM, get the enum's integer type
+ if (underlyingType.kind() == TypeKind.ENUM) {
+ underlyingType = underlyingType.declaration().enumType();
+ }
+
+ // Check if the underlying type is unsigned
+ List<TypeKind> unsignedKinds = List.of(
+ TypeKind.CHAR_U, TypeKind.U_CHAR, TypeKind.CHAR16, TypeKind.CHAR32,
+ TypeKind.U_SHORT, TypeKind.U_INT, TypeKind.U_LONG, TypeKind.U_LONG_LONG,
+ TypeKind.U_INT128
+ );
+
+ if (unsignedKinds.contains(underlyingType.kind())) {
+ return LibClang.getEnumConstantDeclUnsignedValue(segment);
+ } else {
+ return LibClang.getEnumConstantDeclValue(segment);
+ }
+ }
+
+ /**
+ * Return the source location of this cursor.
+ */
+ public SourceLocation location() {
+ MemorySegment locSeg = LibClang.getCursorLocation(arena, segment);
+ return new SourceLocation(locSeg, arena);
+ }
+
+ /**
+ * Return the semantic parent of this cursor.
+ */
+ public Cursor semanticParent() {
+ MemorySegment parentSeg = LibClang.getCursorSemanticParent(arena, segment);
+ return new Cursor(parentSeg, arena);
+ }
+
+ /**
+ * Returns whether this cursor represents a bit-field declaration.
+ */
+ public boolean isBitField() {
+ return LibClang.cursorIsBitField(segment) != 0;
+ }
+
+ /**
+ * Returns the bit width of a bit-field declaration.
+ */
+ public int getBitFieldWidth() {
+ return LibClang.getFieldDeclBitWidth(segment);
+ }
+
+ /**
+ * Returns the offset of a field in bits.
+ */
+ public long getFieldOffset() {
+ return LibClang.cursorGetOffsetOfField(segment);
+ }
+
+ /**
+ * Returns whether this cursor represents an anonymous declaration.
+ */
+ public boolean isAnonymous() {
+ return LibClang.cursorIsAnonymous(segment) != 0;
+ }
+
+ /**
+ * Returns whether this cursor represents an anonymous record declaration.
+ */
+ public boolean isAnonymousRecordDecl() {
+ return LibClang.cursorIsAnonymousRecordDecl(segment) != 0;
+ }
+
+ /**
+ * Returns whether this C++ method is declared virtual.
+ */
+ public boolean isVirtualMethod() {
+ return LibClang.cxxMethodIsVirtual(segment) != 0;
+ }
+
+ /**
+ * Returns whether this C++ method is declared pure virtual (= 0).
+ */
+ public boolean isPureVirtualMethod() {
+ return LibClang.cxxMethodIsPureVirtual(segment) != 0;
+ }
+
+ /**
+ * Returns whether this C++ method is declared static.
+ */
+ public boolean isStaticMethod() {
+ return LibClang.cxxMethodIsStatic(segment) != 0;
+ }
+
+ /**
+ * Returns whether this base specifier represents a virtual base class.
+ */
+ public boolean isVirtualBase() {
+ return LibClang.isVirtualBase(segment) != 0;
+ }
+
+ // ========================================================================
+ // Visitor pattern
+ // ========================================================================
+
+ /**
+ * Functional interface for visiting child cursors.
+ */
+ @FunctionalInterface
+ public interface CursorVisitor {
+ ChildVisitResult visit(Cursor cursor, Cursor parent);
+ }
+
+ /**
+ * Result codes for cursor visitor callbacks.
+ */
+ public enum ChildVisitResult {
+ /** Terminates the cursor traversal. */
+ BREAK(0),
+ /** Continues with the next sibling, without visiting children. */
+ CONTINUE(1),
+ /** Recursively traverse the children of this cursor. */
+ RECURSE(2);
+
+ final int value;
+
+ ChildVisitResult(int v) {
+ this.value = v;
+ }
+ }
+
+ /**
+ * Visit the children of this cursor, invoking the visitor for each child.
+ *
+ * @param visitor the visitor callback to invoke for each child
+ */
+ public void visitChildren(CursorVisitor visitor) {
+ try (Arena upcallArena = Arena.ofConfined()) {
+ MethodHandle callback;
+ try {
+ callback = MethodHandles.lookup().findStatic(
+ Cursor.class,
+ "visitChildrenCallback",
+ MethodType.methodType(int.class,
+ MemorySegment.class, MemorySegment.class, MemorySegment.class)
+ );
+ } catch (NoSuchMethodException | IllegalAccessException e) {
+ throw new RuntimeException("Failed to find visitChildrenCallback", e);
+ }
+
+ MemorySegment stub = LibClang.linker().upcallStub(
+ callback,
+ LibClang.VISITOR_DESC,
+ upcallArena
+ );
+
+ // Save previous values for re-entrant (nested) visitChildren calls.
+ // SourceParser nests visitors: outer callback -> parseStruct -> inner visitChildren.
+ // Without save/restore, the inner finally block would remove() the ThreadLocal
+ // values that the outer callback still needs, causing a null dereference.
+ CursorVisitor previousVisitor = CURRENT_VISITOR.get();
+ Arena previousArena = CURRENT_ARENA.get();
+ CURRENT_VISITOR.set(visitor);
+ CURRENT_ARENA.set(this.arena);
+ try {
+ LibClang.visitChildren(this.segment, stub, MemorySegment.NULL);
+ } finally {
+ // Restore previous values (not remove!) so outer callbacks keep working
+ if (previousVisitor != null) {
+ CURRENT_VISITOR.set(previousVisitor);
+ } else {
+ CURRENT_VISITOR.remove();
+ }
+ if (previousArena != null) {
+ CURRENT_ARENA.set(previousArena);
+ } else {
+ CURRENT_ARENA.remove();
+ }
+ }
+ }
+ }
+
+ /**
+ * Native upcall target for clang_visitChildren. Receives raw MemorySegments
+ * representing CXCursor structs passed by value from libclang.
+ * <p>
+ * CRITICAL: Catches ALL Throwable to prevent JVM termination from uncaught
+ * exceptions in upcall stubs.
+ */
+ @SuppressWarnings("unused") // Invoked via MethodHandles.lookup().findStatic() in visitChildren()
+ private static int visitChildrenCallback(MemorySegment cursorSeg,
+ MemorySegment parentSeg,
+ MemorySegment clientData) {
+ try {
+ Arena arena = CURRENT_ARENA.get();
+ CursorVisitor visitor = CURRENT_VISITOR.get();
+
+ // Copy callback-scoped segments into the TU's persistent arena.
+ // The segments provided by Panama for struct-by-value upcall parameters
+ // are only valid for the duration of this callback invocation.
+ MemorySegment cursorCopy = arena.allocate(LibClang.CX_CURSOR);
+ cursorCopy.copyFrom(cursorSeg.reinterpret(LibClang.CX_CURSOR.byteSize()));
+ MemorySegment parentCopy = arena.allocate(LibClang.CX_CURSOR);
+ parentCopy.copyFrom(parentSeg.reinterpret(LibClang.CX_CURSOR.byteSize()));
+
+ Cursor cursor = new Cursor(cursorCopy, arena);
+ Cursor parent = new Cursor(parentCopy, arena);
+ return visitor.visit(cursor, parent).value;
+ } catch (Throwable t) {
+ // MUST catch everything -- uncaught exceptions in upcalls terminate the JVM
+ t.printStackTrace();
+ return ChildVisitResult.BREAK.value;
+ }
+ }
+
+ // ========================================================================
+ // Object methods
+ // ========================================================================
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) return true;
+ if (!(obj instanceof Cursor other)) return false;
+ return LibClang.equalCursors(this.segment, other.segment) != 0;
+ }
+
+ @Override
+ public int hashCode() {
+ return LibClang.hashCursor(segment);
+ }
+
+ @Override
+ public String toString() {
+ CursorKind k = kind();
+ String s = spelling();
+ return "Cursor{kind=" + k + ", spelling='" + s + "'}";
+ }
+}
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/CursorKind.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/CursorKind.java
new file mode 100644
index 0000000000..d9d49827d1
--- /dev/null
+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/gcpp/clang/CursorKind.java
@@ -0,0 +1,313 @@
+package ghidra.app.util.gcpp.clang;
+
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Map;
+
+public enum CursorKind {
+ UNEXPOSED_DECL(1),
+ STRUCT_DECL(2),
+ UNION_DECL(3),
+ CLASS_DECL(4),
+ ENUM_DECL(5),
+ FIELD_DECL(6),
+ ENUM_CONSTANT_DECL(7),
+ FUNCTION_DECL(8),
+ VAR_DECL(9),
+ PARM_DECL(10),
+ OBJ_C_INTERFACE_DECL(11),
+ OBJ_C_CATEGORY_DECL(12),
+ OBJ_C_PROTOCOL_DECL(13),
+ OBJ_C_PROPERTY_DECL(14),
+ OBJ_C_IVAR_DECL(15),
+ OBJ_C_INSTANCE_METHOD_DECL(16),
+ OBJ_C_CLASS_METHOD_DECL(17),
+ OBJ_C_IMPLEMENTATION_DECL(18),
+ OBJ_C_CATEGORY_IMPL_DECL(19),
+ TYPEDEF_DECL(20),
+ C_X_X_METHOD(21),
+ NAMESPACE(22),
+ LINKAGE_SPEC(23),
+ CONSTRUCTOR(24),
+ DESTRUCTOR(25),
+ CONVERSION_FUNCTION(26),
+ TEMPLATE_TYPE_PARAMETER(27),
+ NON_TYPE_TEMPLATE_PARAMETER(28),
+ TEMPLATE_TEMPLATE_PARAMETER(29),
+ FUNCTION_TEMPLATE(30),
+ CLASS_TEMPLATE(31),
+ CLASS_TEMPLATE_PARTIAL_SPECIALIZATION(32),
+ NAMESPACE_ALIAS(33),
+ USING_DIRECTIVE(34),
+ USING_DECLARATION(35),
+ TYPE_ALIAS_DECL(36),
+ OBJ_C_SYNTHESIZE_DECL(37),
+ OBJ_C_DYNAMIC_DECL(38),
+ C_X_X_ACCESS_SPECIFIER(39),
+ FIRST_REF(40),
+ OBJ_C_SUPER_CLASS_REF(40),
+ OBJ_C_PROTOCOL_REF(41),
+ OBJ_C_CLASS_REF(42),
+ TYPE_REF(43),
+ C_X_X_BASE_SPECIFIER(44),
+ TEMPLATE_REF(45),
+ NAMESPACE_REF(46),
+ MEMBER_REF(47),
+ LABEL_REF(48),
+ OVERLOADED_DECL_REF(49),
+ VARIABLE_REF(50),
+ FIRST_INVALID(70),
+ INVALID_FILE(70),
+ NO_DECL_FOUND(71),
+ NOT_IMPLEMENTED(72),
+ INVALID_CODE(73),
+ FIRST_EXPR(100),
+ UNEXPOSED_EXPR(100),
+ DECL_REF_EXPR(101),
+ MEMBER_REF_EXPR(102),
+ CALL_EXPR(103),
+ OBJ_C_MESSAGE_EXPR(104),
+ BLOCK_EXPR(105),
+ INTEGER_LITERAL(106),
+ FLOATING_LITERAL(107),
+ IMAGINARY_LITERAL(108),
+ STRING_LITERAL(109),
+ CHARACTER_LITERAL(110),
+ PAREN_EXPR(111),
+ UNARY_OPERATOR(112),
+ ARRAY_SUBSCRIPT_EXPR(113),
+ BINARY_OPERATOR(114),
+ COMPOUND_ASSIGN_OPERATOR(115),
+ CONDITIONAL_OPERATOR(116),
+ C_STYLE_CAST_EXPR(117),
+ COMPOUND_LITERAL_EXPR(118),
+ INIT_LIST_EXPR(119),
+ ADDR_LABEL_EXPR(120),
+ STMT_EXPR(121),
+ GENERIC_SELECTION_EXPR(122),
+ G_N_U_NULL_EXPR(123),
+ C_X_X_STATIC_CAST_EXPR(124),
+ C_X_X_DYNAMIC_CAST_EXPR(125),
+ C_X_X_REINTERPRET_CAST_EXPR(126),
+ C_X_X_CONST_CAST_EXPR(127),
+ C_X_X_FUNCTIONAL_CAST_EXPR(128),
+ C_X_X_TYPEID_EXPR(129),
+ C_X_X_BOOL_LITERAL_EXPR(130),
+ C_X_X_NULL_PTR_LITERAL_EXPR(131),
+ C_X_X_THIS_EXPR(132),
+ C_X_X_THROW_EXPR(133),
+ C_X_X_NEW_EXPR(134),
+ C_X_X_DELETE_EXPR(135),
+ UNARY_EXPR(136),
+ OBJ_C_STRING_LITERAL(137),
+ OBJ_C_ENCODE_EXPR(138),
+ OBJ_C_SELECTOR_EXPR(139),
+ OBJ_C_PROTOCOL_EXPR(140),
+ OBJ_C_BRIDGED_CAST_EXPR(141),
+ PACK_EXPANSION_EXPR(142),
+ SIZE_OF_PACK_EXPR(143),
+ LAMBDA_EXPR(144),
+ OBJ_C_BOOL_LITERAL_EXPR(145),
+ OBJ_C_SELF_EXPR(146),
+ O_M_P_ARRAY_SECTION_EXPR(147),
+ OBJ_C_AVAILABILITY_CHECK_EXPR(148),
+ FIXED_POINT_LITERAL(149),
+ O_M_P_ARRAY_SHAPING_EXPR(150),
+ O_M_P_ITERATOR_EXPR(151),
+ C_X_X_ADDRSPACE_CAST_EXPR(152),
+ CONCEPT_SPECIALIZATION_EXPR(153),
+ REQUIRES_EXPR(154),
+ C_X_X_PAREN_LIST_INIT_EXPR(155),
+ FIRST_STMT(200),
+ UNEXPOSED_STMT(200),
+ LABEL_STMT(201),
+ COMPOUND_STMT(202),
+ CASE_STMT(203),
+ DEFAULT_STMT(204),