write me a linter to check forbidden function for c program in robust way, all define function in project is allowed { "allow_funcs": ["malloc", "printf", "hello_*"] "excludes": ["folder", "file.c"] }
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a robust Python script that checks C programs for forbidden functions while allowing specified functions and excluding certain files/directories. The script uses pycparser for parsing C code and implements pattern matching for wildcard function names.
python
#!/usr/bin/env python3
import os
import sys
import json
import fnmatch
from pycparser import c_parser, c_ast, parse_file
class ForbiddenFunctionVisitor(c_ast.NodeVisitor):
def __init__(self, allowed_funcs, forbidden_funcs):
self.allowed_funcs = allowed_funcs
self.forbidden_funcs = forbidden_funcs
self.violations = []
def visit_FuncCall(self, node):
if isinstance(node.name, c_ast.ID):
func_name = node.name.name
self._check_function(func_name, node)
elif isinstance(node.name, c_ast.UnaryOp) and isinstance(node.name.expr, c_ast.ID):
# Handle pointer-to-function calls like (*func)()
func_name = node.name.expr.name
self._check_function(func_name, node)
def _check_function(self, func_name, node):
# Check if function is allowed
allowed = False
for pattern in self.allowed_funcs:
if fnmatch.fnmatch(func_name, pattern):
allowed = True
break
# Check if function is explicitly forbidden
forbidden = False
for pattern in self.forbidden_funcs:
if fnmatch.fnmatch(func_name, pattern):
forbidden = True
break
if not allowed and not forbidden:
self.violations.append({
'file': node.coord.file if node.coord else 'unknown',
'line': node.coord.line if node.coord else -1,
'function': func_name
})
def parse_config(config_path):
with open(config_path) as f:
config = json.load(f)
# Process allowed functions
allowed_funcs = config.get("allow_funcs", [])
# Process excludes
excludes = config.get("excludes", [])
exclude_patterns = []
for pattern in excludes:
if pattern.endswith('/') or pattern.endswith('\\'):
# Directory pattern
exclude_patterns.append(os.path.normpath(pattern) + os.sep + '*')
else:
# File pattern
exclude_patterns.append(os.path.normpath(pattern))
return allowed_funcs, exclude_patterns
def should_exclude(file_path, exclude_patterns):
for pattern in exclude_patterns:
if fnmatch.fnmatch(file_path, pattern):
return True
return False
def find_c_files(directory):
c_files = []
for root, _, files in os.walk(directory):
for file in files:
if file.endswith('.c'):
c_files.append(os.path.join(root, file))
return c_files
def lint_project(project_dir, allowed_funcs, exclude_patterns):
c_files = find_c_files(project_dir)
violations = []
for c_file in c_files:
if should_exclude(c_file, exclude_patterns):
continue
try:
# Parse the C file
ast = parse_file(c_file, use_cpp=True)
# Get all function definitions in the file to allow them
defined_funcs = set()
class FuncDefVisitor(c_ast.NodeVisitor):
def visit_FuncDef(self, node):
if isinstance(node.decl.name, str):
defined_funcs.add(node.decl.name)
func_def_visitor = FuncDefVisitor()
func_def_visitor.visit(ast)
# Combine allowed functions with defined functions
all_allowed = allowed_funcs + list(defined_funcs)
# Check for forbidden function calls
visitor = ForbiddenFunctionVisitor(all_allowed, [])
visitor.visit(ast)
for violation in visitor.violations:
violations.append({
'file': c_file,
'line': violation['line'],
'function': violation['function']
})
except Exception as e:
print(f"Error processing {c_file}: {str(e)}", file=sys.stderr)
return violations
def main():
if len(sys.argv) != 3:
print("Usage: python linter.py <project_directory> <config_file>", file=sys.stderr)
sys.exit(1)
project_dir = sys.argv[1]
config_file = sys.argv[2]
if not os.path.isdir(project_dir):
print(f"Error: {project_dir} is not a valid directory", file=sys.stderr)
sys.exit(1)
if not os.path.isfile(config_file):
print(f"Error: {config_file} is not a valid file", file=sys.stderr)
sys.exit(1)
allowed_funcs, exclude_patterns = parse_config(config_file)
violations = lint_project(project_dir, allowed_funcs, exclude_patterns)
if violations:
print("Forbidden function violations found:")
for violation in violations:
print(f"{violation['file']}:{violation['line']}: Forbidden function call: {violation['function']}")
sys.exit(1)
else:
print("No forbidden function violations found.")
sys.exit(0)
if __name__ == "__main__":
main()