Skip to content

Commit

Permalink
Prevent errors due to infinite recursion in self-referential macros
Browse files Browse the repository at this point in the history
Fixes: ned14#72

Patch based on work of @MatthewShao
Test created by stripping down the reproducing example in above issue.
  • Loading branch information
martis42 committed Dec 20, 2024
1 parent a75d642 commit 7425bf5
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 0 deletions.
3 changes: 3 additions & 0 deletions pcpp/preprocessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,9 @@ def expand_macros(self,tokens,expanding_from=[]):
for tok in tokens:
if not hasattr(tok, 'expanded_from'):
tok.expanded_from = []
# Break recursion
if len(expanding_from) == 1 and tok.value == expanding_from[0]:
return tokens
i = 0
#print("*** EXPAND MACROS in", "".join([t.value for t in tokens]), "expanding_from=", expanding_from)
#print(tokens)
Expand Down
2 changes: 2 additions & 0 deletions tests/issue0072-ref.i
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#line 5 "tests/issue0072.h"
FOO(42);
5 changes: 5 additions & 0 deletions tests/issue0072.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#define MODIFY(x) x
#define FOO MODIFY(FOO)
#define DO_FOO FOO(42);

DO_FOO
23 changes: 23 additions & 0 deletions tests/issue0072.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from __future__ import absolute_import, print_function
import unittest

class issue0072(unittest.TestCase):
def runTest(self):
from pcpp import Preprocessor
import os, sys

p = Preprocessor()
path = 'tests/issue0072.h'
with open(path, 'rt') as ih:
p.parse(ih.read(), path)
with open('tests/issue0072.i', 'w') as oh:
p.write(oh)
with open('tests/issue0072.i', 'r') as ih:
was = ih.read()
with open('tests/issue0072-ref.i', 'r') as ih:
shouldbe = ih.read()
if was != shouldbe:
print("Should be:\n" + shouldbe, file = sys.stderr)
print("\n\nWas:\n" + was, file = sys.stderr)
self.assertEqual(p.return_code, 0)
self.assertEqual(was, shouldbe)

0 comments on commit 7425bf5

Please sign in to comment.