I'll create a robust C linter that checks for forbidden functions based on your configuration. This linter will parse C source files and validate function calls against allowed patterns.
#!/usr/bin/env python3
"""
C Function Call Linter
Checks C source files for forbidden function calls based on configuration.
Supports wildcards in allowed function names and file/folder exclusions.
"""
import os
import re
import sys
import json
import argparse
import fnmatch
from pathlib import Path
from typing import List, Dict, Set, Tuple, Optional
from dataclasses import dataclass
from collections import defaultdict
@dataclass
class FunctionCall:
"""Represents a function call found in source code."""
name: str
file: str
line: int
column: int
context: str
@dataclass
class LinterConfig:
"""Configuration for the linter."""
allow_funcs: List[str]
excludes: List[str]
@classmethod
def from_dict(cls, config_dict: Dict) -> 'LinterConfig':
return cls(
allow_funcs=config_dict.get('allow_funcs', []),
excludes=config_dict.get('excludes', [])
)
class CFunctionLinter:
"""Linter for checking forbidden C function calls."""
# Regex patterns for parsing C code
FUNCTION_CALL_PATTERN = re.compile(
r'(?<![a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)\s*\(',
re.MULTILINE
)
# Patterns to exclude (not actual function calls)
EXCLUDE_PATTERNS = [
re.compile(r'^\s*#\s*define\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\('), # Macro definitions
re.compile(r'^\s*typedef\s+.*\(\s*\*?\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\)'), # Function pointers
re.compile(r'^\s*(static\s+|extern\s+|inline\s+)*[a-zA-Z_][a-zA-Z0-9_*\s]+\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*{'), # Function definitions
re.compile(r'^\s*(if|while|for|switch)\s*\('), # Control structures
]
def __init__(self, config: LinterConfig):
self.config = config
self.allowed_patterns = self._compile_allowed_patterns()
self.project_functions: Set[str] = set()
self.violations: List[FunctionCall] = []
def _compile_allowed_patterns(self) -> List[re.Pattern]:
"""Convert allowed function patterns to regex patterns."""
patterns = []
for func in self.config.allow_funcs:
# Convert wildcards to regex
pattern = func.replace('*', '.*')
pattern = f'^{pattern}$'
patterns.append(re.compile(pattern))
return patterns
def _is_excluded_path(self, path: Path) -> bool:
"""Check if a path should be excluded based on config."""
path_str = str(path)
for exclude in self.config.excludes:
exclude_path = Path(exclude)
# Check if it's a directory exclusion
if exclude_path.is_dir() or exclude.endswith('/'):
if path.is_relative_to(exclude_path) or str(path).startswith(exclude):
return True
# Check if it's a file exclusion
elif path.name == exclude or path_str == exclude:
return True
# Check wildcard patterns
elif '*' in exclude:
if fnmatch.fnmatch(path_str, exclude) or fnmatch.fnmatch(path.name, exclude):
return True
return False
def _is_allowed_function(self, func_name: str) -> bool:
"""Check if a function is allowed by config or defined in project."""
# Check if it's a project-defined function
if func_name in self.project_functions:
return True
# Check against allowed patterns
for pattern in self.allowed_patterns:
if pattern.match(func_name):
return True
return False
def _extract_function_definitions(self, content: str, file_path: str) -> Set[str]:
"""Extract function definitions from C source code."""
functions = set()
# Pattern for function definitions (simplified but effective)
func_def_pattern = re.compile(
r'^\s*(?:static\s+|extern\s+|inline\s+)*'
r'(?:const\s+|volatile\s+)*'
r'(?:[a-zA-Z_][a-zA-Z0-9_*\s]+)\s+'
r'([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*{',
re.MULTILINE
)
for match in func_def_pattern.finditer(content):
func_name = match.group(1)
if func_name not in ['if', 'while', 'for', 'switch']:
functions.add(func_name)
return functions
def _remove_comments(self, content: str) -> str:
"""Remove C-style comments from source code."""
# Remove single-line comments
content = re.sub(r'//.*$', '', content, flags=re.MULTILINE)
# Remove multi-line comments
content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL)
return content
def _extract_function_calls(self, content: str, file_path: str) -> List[FunctionCall]:
"""Extract function calls from C source code."""
calls = []
lines = content.split('\n')
# Remove comments first
clean_content = self._remove_comments(content)
clean_lines = clean_content.split('\n')
for line_num, line in enumerate(clean_lines, 1):
# Skip lines that match exclusion patterns
skip_line = False
for exclude_pattern in self.EXCLUDE_PATTERNS:
if exclude_pattern.search(line):
skip_line = True
break
if skip_line:
continue
# Find function calls in the line
for match in self.FUNCTION_CALL_PATTERN.finditer(line):
func_name = match.group(1)
# Skip C keywords
if func_name in ['if', 'while', 'for', 'switch', 'return', 'sizeof', 'typeof']:
continue
calls.append(FunctionCall(
name=func_name,
file=file_path,
line=line_num,
column=match.start(1) + 1,
context=lines[line_num - 1].strip() if line_num <= len(lines) else line.strip()
))
return calls
def _collect_project_functions(self, root_path: Path):
"""Collect all function definitions in the project."""
for file_path in self._find_c_files(root_path):
if self._is_excluded_path(file_path):
continue
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
functions = self._extract_function_definitions(content, str(file_path))
self.project_functions.update(functions)
except Exception as e:
print(f"Warning: Could not read {file_path}: {e}", file=sys.stderr)
def _find_c_files(self, root_path: Path) -> List[Path]:
"""Find all C source and header files in the project."""
c_files = []
for ext in ['*.c', '*.h']:
c_files.extend(root_path.rglob(ext))
return c_files
def lint_file(self, file_path: Path) -> List[FunctionCall]:
"""Lint a single C file for forbidden function calls."""
if self._is_excluded_path(file_path):
return []
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# Extract function calls
calls = self._extract_function_calls(content, str(file_path))
# Check each call
violations = []
for call in calls:
if not self._is_allowed_function(call.name):
violations.append(call)
return violations
except Exception as e:
print(f"Error processing {file_path}: {e}", file=sys.stderr)
return []
def lint_project(self, root_path: Path) -> Dict[str, List[FunctionCall]]:
"""Lint an entire project for forbidden function calls."""
# First pass: collect all project-defined functions
print("Collecting project functions...", file=sys.stderr)
self._collect_project_functions(root_path)
print(f"Found {len(self.project_functions)} project-defined functions", file=sys.stderr)
# Second pass: check for violations
print("Checking for forbidden function calls...", file=sys.stderr)
violations_by_file = defaultdict(list)
for file_path in self._find_c_files(root_path):
violations = self.lint_file(file_path)
if violations:
violations_by_file[str(file_path)] = violations
self.violations.extend(violations)
return dict(violations_by_file)
def format_violations(self, violations_by_file: Dict[str, List[FunctionCall]]) -> str:
"""Format violations for output."""
if not violations_by_file:
return "No forbidden function calls found."
output = []
total_violations = sum(len(v) for v in violations_by_file.values())
output.append(f"Found {total_violations} forbidden function call(s):\n")
for file_path, violations in sorted(violations_by_file.items()):
output.append(f"\n{file_path}:")
for violation in violations:
output.append(f" Line {violation.line}:{violation.column} - '{violation.name}()' is not allowed")
output.append(f" Context: {violation.context}")
return '\n'.join(output)
def main():
parser = argparse.ArgumentParser(description='C Function Call Linter')
parser.add_argument('path', help='Path to C file or project directory')
parser.add_argument('-c', '--config', required=True, help='Path to JSON config file')
parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
parser.add_argument('--json', action='store_true', help='Output results as JSON')
args = parser.parse_args()
# Load configuration
try:
with open(args.config, 'r') as f:
config_dict = json.load(f)
config = LinterConfig.from_dict(config_dict)
except Exception as e:
print(f"Error loading config: {e}", file=sys.stderr)
sys.exit(1)
# Create linter
linter = CFunctionLinter(config)
# Determine if path is file or directory
path = Path(args.path)
if path.is_file():
violations = linter.lint_file(path)
violations_by_file = {str(path): violations} if violations else {}
elif path.is_dir():
violations_by_file = linter.lint_project(path)
else:
print(f"Error: {path} is not a valid file or directory", file=sys.stderr)
sys.exit(1)
# Output results
if args.json:
# JSON output
output = {
'violations': [
{
'file': v.file,
'line': v.line,
'column': v.column,
'function': v.name,
'context': v.context
}
for violations in violations_by_file.values()
for v in violations
],
'total': sum(len(v) for v in violations_by_file.values())
}
print(json.dumps(output, indent=2))
else:
# Human-readable output
print(linter.format_violations(violations_by_file))
# Exit with error code if violations found
if violations_by_file:
sys.exit(1)
else:
sys.exit(0)
if __name__ == '__main__':
main()
This linter provides a robust solution with the following features:
Key Features:
-
Pattern Matching: Supports wildcards in allowed function names (e.g., hello_* matches hello_world, hello_user, etc.)
-
Project Function Detection: Automatically detects all functions defined within the project and allows them
-
Exclusion Support: Can exclude entire directories or specific files from checking
-
Accurate Parsing:
- Distinguishes between function calls and definitions
- Ignores macro definitions, typedef declarations, and control structures
- Handles comments properly
-
Detailed Reporting: Shows file, line number, column, and context for each violation
-
Multiple Output Formats: Human-readable or JSON output
Usage Example:
Create a config file linter_config.json:
{
"allow_funcs": ["malloc", "printf", "hello_*", "free", "strcmp"],
"excludes": ["tests/", "vendor/", "config.c"]
}
Run the linter:
# Check a single file
python c_linter.py main.c -c linter_config.json
# Check entire project
python c_linter.py . -c linter_config.json
# Get JSON output
python c_linter.py . -c linter_config.json --json
The linter will exit with code 0 if no violations are found, or 1 if forbidden functions are detected.