write me a linter to check forbidden function for c program in robust way (dont use regex), all defined 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.
I'll create a robust C linter that checks for forbidden functions without using regex. This linter will parse C code properly and handle various edge cases.
python
#!/usr/bin/env python3
import os
import sys
import json
import argparse
from typing import Set, List, Dict, Tuple
from dataclasses import dataclass
from pathlib import Path
@dataclass
class Token:
"""Represents a token in C code"""
type: str
value: str
line: int
column: int
file: str
@dataclass
class FunctionCall:
"""Represents a function call in the code"""
name: str
line: int
column: int
file: str
class CLexer:
"""Simple C lexer for tokenizing C code"""
def __init__(self, code: str, filename: str):
self.code = code
self.filename = filename
self.pos = 0
self.line = 1
self.column = 1
self.tokens = []
def peek(self, offset=0):
"""Peek at character without consuming"""
pos = self.pos + offset
if pos < len(self.code):
return self.code[pos]
return None
def advance(self):
"""Consume and return next character"""
if self.pos < len(self.code):
char = self.code[self.pos]
self.pos += 1
if char == '\n':
self.line += 1
self.column = 1
else:
self.column += 1
return char
return None
def skip_whitespace(self):
"""Skip whitespace characters"""
while self.peek() and self.peek().isspace():
self.advance()
def skip_single_line_comment(self):
"""Skip // comments"""
while self.peek() and self.peek() != '\n':
self.advance()
def skip_multi_line_comment(self):
"""Skip /* */ comments"""
while True:
if self.peek() == '*' and self.peek(1) == '/':
self.advance() # *
self.advance() # /
break
if self.peek() is None:
break
self.advance()
def read_string_literal(self):
"""Read string literal"""
quote_char = self.advance() # " or '
value = quote_char
while True:
char = self.peek()
if char is None:
break
if char == '\\':
value += self.advance() # \
if self.peek():
value += self.advance() # escaped char
elif char == quote_char:
value += self.advance()
break
else:
value += self.advance()
return Token('STRING', value, self.line, self.column - len(value), self.filename)
def read_identifier(self):
"""Read identifier or keyword"""
start_col = self.column
value = ''
while self.peek() and (self.peek().isalnum() or self.peek() == '_'):
value += self.advance()
return Token('IDENTIFIER', value, self.line, start_col, self.filename)
def read_number(self):
"""Read number literal"""
start_col = self.column
value = ''
# Handle hex numbers
if self.peek() == '0' and self.peek(1) in 'xX':
value += self.advance() # 0
value += self.advance() # x
while self.peek() and self.peek() in '0123456789abcdefABCDEF':
value += self.advance()
else:
# Regular numbers
while self.peek() and (self.peek().isdigit() or self.peek() in '.eE+-'):
value += self.advance()
# Handle suffixes like L, U, F
while self.peek() and self.peek() in 'lLuUfF':
value += self.advance()
return Token('NUMBER', value, self.line, start_col, self.filename)
def tokenize(self):
"""Tokenize the entire code"""
while self.pos < len(self.code):
self.skip_whitespace()
if self.pos >= len(self.code):
break
# Handle comments
if self.peek() == '/' and self.peek(1) == '/':
self.skip_single_line_comment()
continue
if self.peek() == '/' and self.peek(1) == '*':
self.advance() # /
self.advance() # *
self.skip_multi_line_comment()
continue
# Handle preprocessor directives
if self.peek() == '#':
start_col = self.column
value = ''
while self.peek() and self.peek() != '\n':
if self.peek() == '\\' and self.peek(1) == '\n':
self.advance() # \
self.advance() # \n
else:
value += self.advance()
self.tokens.append(Token('PREPROCESSOR', value, self.line, start_col, self.filename))
continue
# Handle string literals
if self.peek() in '"\'':
self.tokens.append(self.read_string_literal())
continue
# Handle identifiers
if self.peek().isalpha() or self.peek() == '_':
self.tokens.append(self.read_identifier())
continue
# Handle numbers
if self.peek().isdigit():
self.tokens.append(self.read_number())
continue
# Handle operators and punctuation
char = self.advance()
self.tokens.append(Token('PUNCT', char, self.line, self.column - 1, self.filename))
return self.tokens
class CFunctionExtractor:
"""Extract function definitions and calls from C code"""
def __init__(self, tokens: List[Token]):
self.tokens = tokens
self.pos = 0
self.defined_functions = set()
self.function_calls = []
def peek_token(self, offset=0):
"""Peek at token without consuming"""
pos = self.pos + offset
if pos < len(self.tokens):
return self.tokens[pos]
return None
def advance_token(self):
"""Consume and return next token"""
if self.pos < len(self.tokens):
token = self.tokens[self.pos]
self.pos += 1
return token
return None
def is_function_call(self, idx):
"""Check if identifier at idx is a function call"""
if idx >= len(self.tokens) - 1:
return False
token = self.tokens[idx]
next_token = self.tokens[idx + 1]
# Check for function call pattern: identifier(
return (token.type == 'IDENTIFIER' and
next_token.type == 'PUNCT' and
next_token.value == '(')
def is_function_definition(self, idx):
"""Check if this might be a function definition"""
# Look for patterns like: type name(...) {
# This is simplified - real C parsing is complex
if idx >= len(self.tokens) - 2:
return False
# Find opening parenthesis
paren_idx = idx + 1
while paren_idx < len(self.tokens) and self.tokens[paren_idx].value != '(':
paren_idx += 1
if paren_idx >= len(self.tokens):
return False
# Find matching closing parenthesis
paren_count = 1
close_paren_idx = paren_idx + 1
while close_paren_idx < len(self.tokens) and paren_count > 0:
if self.tokens[close_paren_idx].value == '(':
paren_count += 1
elif self.tokens[close_paren_idx].value == ')':
paren_count -= 1
close_paren_idx += 1
if paren_count != 0:
return False
# Look for { after )
brace_idx = close_paren_idx
while brace_idx < len(self.tokens) and self.tokens[brace_idx].type in ['PUNCT', 'IDENTIFIER']:
if self.tokens[brace_idx].value == '{':
return True
if self.tokens[brace_idx].value == ';':
return False # Function declaration, not definition
brace_idx += 1
return False
def extract(self):
"""Extract function definitions and calls"""
i = 0
while i < len(self.tokens):
token = self.tokens[i]
if token.type == 'IDENTIFIER':
# Check for function definition
if self.is_function_definition(i):
self.defined_functions.add(token.value)
# Check for function call
elif self.is_function_call(i):
# Skip certain patterns that look like calls but aren't
# e.g., sizeof(x), if(x), while(x), for(x)
if token.value not in ['sizeof', 'if', 'while', 'for', 'switch', 'return']:
self.function_calls.append(FunctionCall(
token.value, token.line, token.column, token.file
))
i += 1
return self.defined_functions, self.function_calls
class CFunctionLinter:
"""Main linter class"""
def __init__(self, config: Dict):
self.allowed_funcs = set(config.get('allow_funcs', []))
self.excludes = set(config.get('excludes', []))
self.all_defined_functions = set()
self.violations = []
# Extract patterns and exact matches
self.allowed_patterns = []
self.allowed_exact = set()
for func in self.allowed_funcs:
if '*' in func:
# Convert pattern to prefix
prefix = func.replace('*', '')
self.allowed_patterns.append(prefix)
else:
self.allowed_exact.add(func)
def should_exclude(self, filepath: Path) -> bool:
"""Check if file or directory should be excluded"""
for exclude in self.excludes:
exclude_path = Path(exclude)
# Check if it's a file
if exclude_path.suffix:
if filepath.name == exclude_path.name:
return True
else:
# It's a directory
if exclude in filepath.parts:
return True
return False
def is_allowed_function(self, func_name: str) -> bool:
"""Check if function is allowed"""
# Check exact matches
if func_name in self.allowed_exact:
return True
# Check patterns
for pattern in self.allowed_patterns:
if func_name.startswith(pattern):
return True
# Check if it's defined in the project
if func_name in self.all_defined_functions:
return True
return False
def process_file(self, filepath: Path):
"""Process a single C file"""
try:
with open(filepath, 'r', encoding='utf-8') as f:
code = f.read()
except Exception as e:
print(f"Error reading {filepath}: {e}", file=sys.stderr)
return
# Tokenize
lexer = CLexer(code, str(filepath))
tokens = lexer.tokenize()
# Extract functions
extractor = CFunctionExtractor(tokens)
defined_funcs, function_calls = extractor.extract()
# Add to global defined functions
self.all_defined_functions.update(defined_funcs)
# Store for second pass
return function_calls
def find_c_files(self, path: Path) -> List[Path]:
"""Find all C files in directory"""
c_files = []
if path.is_file():
if path.suffix in ['.c', '.h'] and not self.should_exclude(path):
c_files.append(path)
else:
for item in path.rglob('*'):
if item.is_file() and item.suffix in ['.c', '.h']:
if not self.should_exclude(item):
c_files.append(item)
return c_files
def lint(self, paths: List[str]):
"""Run the linter on given paths"""
all_files = []
file_calls = {}
# Collect all C files
for path_str in paths:
path = Path(path_str)
all_files.extend(self.find_c_files(path))
# First pass: collect all defined functions
print(f"Analyzing {len(all_files)} files...")
for filepath in all_files:
calls = self.process_file(filepath)
if calls:
file_calls[filepath] = calls
# Second pass: check function calls
for filepath, calls in file_calls.items():
for call in calls:
if not self.is_allowed_function(call.name):
self.violations.append({
'file': str(filepath),
'line': call.line,
'column': call.column,
'function': call.name
})
return self.violations
def main():
parser = argparse.ArgumentParser(description='C Function Linter')
parser.add_argument('paths', nargs='+', help='Files or directories to lint')
parser.add_argument('-c', '--config', required=True, help='Config file (JSON)')
parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
args = parser.parse_args()
# Load config
try:
with open(args.config, 'r') as f:
config = json.load(f)
except Exception as e:
print(f"Error loading config: {e}", file=sys.stderr)
sys.exit(1)
# Run linter
linter = CFunctionLinter(config)
violations = linter.lint(args.paths)
# Report results
if violations:
print(f"\nFound {len(violations)} forbidden function calls:\n")
for v in violations:
print(f"{v['file']}:{v['line']}:{v['column']}: "
f"forbidden function '{v['function']}'")
sys.exit(1)
else:
print("No forbidden functions found.")
sys.exit(0)
if __name__ == '__main__':
main()
This linter provides a robust solution for checking forbidden functions in C code:
Key Features:
Proper C Tokenization: Instead of regex, it uses a lexer that understands C syntax including:
Comments (single and multi-line)
String literals (with escape sequences)
Preprocessor directives
Various number formats (hex, floating point, suffixes)
Function Detection:
Identifies function definitions in the project
Detects function calls accurately
Distinguishes between function calls and other constructs (like if, while)
Pattern Matching:
Supports wildcards in allowed functions (e.g., hello_*)
Exact matching for specific functions
Automatically allows all functions defined within the project