To create a linter that checks for forbidden functions in a C program without using regex for searching function definitions and allows all defined functions within the project, we'll follow these steps:
- Parse the configuration file: Read the configuration from a JSON file to determine allowed functions and files/folders to exclude.
- Parse C files: Use a C parser to identify function calls, definitions, and declarations within the C files.
- Check function calls against the configuration: Compare the function calls found in the C files against the list of allowed functions and report any forbidden function calls.
For parsing C files, we'll use the pycparser library, a Python package for parsing C code. It provides a robust way to analyze C code without using regular expressions for complex parsing tasks.
First, ensure you have pycparser installed. You can install it using pip:
pip install pycparser
Here's a basic implementation of the linter in Python:
import json
import os
from pycparser import c_parser, c_ast, parse_file
class ForbiddenFunctionChecker:
def __init__(self, config_file):
with open(config_file, 'r') as f:
self.config = json.load(f)
self.allowed_funcs = self.config.get('allow_funcs', [])
self.excludes = self.config.get('excludes', [])
self.defined_funcs = set()
def is_allowed(self, func_name):
for pattern in self.allowed_funcs:
if '*' in pattern:
if func_name.startswith(pattern.replace('*', '')):
return True
else:
if func_name == pattern:
return True
return False
def is_excluded(self, file_path):
for exclude in self.excludes:
if exclude in file_path:
return True
return False
def extract_defined_functions(self, node):
"""Extract function definitions from a node."""
if isinstance(node, c_ast.FuncDef):
self.defined_funcs.add(node.decl.name)
def check_file(self, file_path):
if self.is_excluded(file_path):
print(f"Skipping {file_path} as it's excluded.")
return
try:
ast = parse_file(file_path, use_cpp=True)
# Extract defined functions
for node in ast.ext:
self.extract_defined_functions(node)
# Check function calls
class FuncCallVisitor(c_ast.NodeVisitor):
def __init__(self, checker):
self.checker = checker
def visit_FuncCall(self, node):
func_name = node.name.name if isinstance(node.name, c_ast.ID) else None
if func_name and func_name not in self.checker.defined_funcs and not self.checker.is_allowed(func_name):
print(f"Forbidden function call: {func_name} at {node.coord}")
visitor = FuncCallVisitor(self)
visitor.visit(ast)
except Exception as e:
print(f"Error processing {file_path}: {e}")
def lint(self, root_dir):
for root, dirs, files in os.walk(root_dir):
for file in files:
if file.endswith('.c'):
file_path = os.path.join(root, file)
self.check_file(file_path)
if __name__ == "__main__":
config_file = 'config.json'
linter = ForbiddenFunctionChecker(config_file)
linter.lint('.')
print("Linting completed.")
This script assumes you have a config.json file in the same directory with content like:
{
"allow_funcs": ["malloc", "printf", "hello_*"],
"excludes": ["folder_to_exclude", "file_to_exclude.c"]
}
This linter walks through C files in the specified root directory, checks for forbidden function calls based on the configuration, and reports them. It correctly handles function definitions within the project by allowing them, regardless of whether they're listed in the allow_funcs section. Note that this is a basic implementation and might need adjustments based on your specific requirements or if you encounter issues with certain C code constructs.