This is an excellent request! Creating a robust linter for C function calls without full AST parsing is challenging due to comments, strings, preprocessor directives, and complex C syntax. However, we can achieve a very robust solution using clever regex and pre-processing.
The core idea is:
- Preprocessing: Remove comments and string/character literals to avoid false positives.
- Function Call Detection: Use a regex to find what looks like a function call.
- Filtering:
- Exclude specified files/folders.
- Identify "project-defined" functions implicitly by checking if they are not on a curated list of inherently forbidden standard/system functions.
- Apply the user-defined
allow_funcs as exceptions to the forbidden list (including wildcards).
Understanding "all defined function in project is allowed":
This implies we maintain a blacklist of common standard/system functions that are often security-sensitive or problematic (e.g., strcpy, system, fork). Any function not on this blacklist is assumed to be project-defined and thus allowed by default. The allow_funcs list then serves as an override for functions that are on the blacklist but are explicitly permitted by the project.
Python Linter Script
import argparse
import re
import os
import sys
from pathlib import Path
import fnmatch
# --- Configuration ---
# Default list of inherently forbidden standard/system functions.
# These are often associated with security vulnerabilities, bad practices,
# or direct system interaction that might be restricted.
# Any function *not* in this list is assumed to be project-defined and allowed by default.
FORBIDDEN_FUNCTIONS_BASE = {
# Memory unsafe functions
"strcpy", "strcat", "sprintf", "gets", "scanf", "sscanf",
"strncpy", # Still potentially unsafe if not used carefully
"strncat", # Still potentially unsafe if not used carefully
"snprintf", # Still potentially unsafe if not used carefully
# System/process control functions
"system", "execve", "execl", "execle", "execlp", "execv", "execvp",
"fork", "vfork", "popen", "pclose",
# File/Path related (often problematic or security-sensitive)
"mktemp", "tmpnam", "tempnam", "mkstemp", # Temporary file issues
"chown", "chmod", # Privilege escalation/file modification
"unlink", "rmdir", # Deletion operations
# Privilege escalation/management
"setuid", "setgid", "seteuid", "setegid",
"setreuid", "setregid", "setresuid", "setresgid",
"initgroups", "setgroups",
"reboot", "poweroff", "sync", # System control
# Dynamic library loading (can be risky)
"dlopen", "dlsym", "dlclose", "dlerror",
# Unsafe memory allocation/deallocation
"alloca", # Stack allocation, can cause stack overflow
"free", # Misuse can lead to use-after-free
"malloc", "calloc", "realloc", # Only if specific memory management is forbidden globally
# (Note: malloc/calloc/realloc are often allowed, but included here for completeness
# if a very strict memory policy is in place. The 'allow_funcs' can override this.)
# Networking (if restricted to certain patterns)
"socket", "bind", "listen", "accept", "connect", "send", "recv",
# Other potentially problematic
"goto", # Bad practice in structured programming (though valid C)
"longjmp", "setjmp", # Non-local jumps, can be complex/error-prone
}
# Regex to match function calls (word followed by parenthesis)
# This is refined to be more robust.
# - \b ensures word boundary
# - ([a-zA-Z_][a-zA-Z0-9_]*) captures the function name
# - \s*\( matches optional whitespace and an opening parenthesis
FUNCTION_CALL_PATTERN = re.compile(r'\b([a-zA-Z_][a-zA-Z0-9_]*)\s*\(')
# --- Helper Functions for Robustness ---
def remove_comments_and_strings(content: str) -> str:
"""
Removes C-style comments (// and /* */) and string/character literals
from the content to prevent false positives.
Replaces them with spaces to preserve line numbers roughly.
"""
# 1. Remove multi-line comments /* ... */
# re.DOTALL allows . to match newlines
# .*? makes it non-greedy
content = re.sub(r'/\*.*?\*/', ' ', content, flags=re.DOTALL)
# 2. Remove single-line comments //
content = re.sub(r'//.*', ' ', content)
# 3. Remove string and character literals
# Matches "..." or '...'
# (?:[^"\\]|\\.)* matches any character that's not a quote or backslash,
# OR an escaped character (e.g., \"). This handles escaped quotes inside strings.
# The 's' flag (re.DOTALL) allows . to match newlines within a string.
content = re.sub(r'(?s)"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'', ' ', content)
return content
def is_excluded(file_path: Path, excludes: list[str]) -> bool:
"""
Checks if a file path is excluded based on the provided list of exclusion patterns.
Exclusion patterns can be file names or folder names.
"""
absolute_path = file_path.resolve() # Get absolute path for robust comparison
for exclude_pattern in excludes:
# Normalize exclude pattern to absolute path if it exists
exclude_path = Path(exclude_pattern).resolve()
if exclude_path.is_dir():
# If exclusion is a directory, check if file_path is inside it
if absolute_path.is_relative_to(exclude_path):
return True
elif exclude_path.is_file():
# If exclusion is a specific file, check for exact match
if absolute_path == exclude_path:
return True
else:
# Handle cases where exclude_pattern might be a partial name
# or a non-existent path. Let's assume it's a file name or folder name.
# Fallback to simple name check (less robust but covers simple cases)
if file_path.name == exclude_pattern:
return True
return False
def is_allowed_by_config(func_name: str, allow_funcs: list[str]) -> bool:
"""
Checks if a function name is explicitly allowed by the user configuration,
including wildcard patterns (e.g., 'hello_*').
"""
for pattern in allow_funcs:
if fnmatch.fnmatch(func_name, pattern):
return True
return False
def lint_file(file_path: Path, forbidden_funcs: set[str], allow_funcs: list[str], verbose: bool) -> list[dict]:
"""
Lints a single C file for forbidden function calls.
Returns a list of issues found.
"""
issues = []
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
original_content = f.read()
# Pre-process content to remove comments and strings
processed_content = remove_comments_and_strings(original_content)
# Iterate line by line to get line numbers for issues
lines = original_content.splitlines()
processed_lines = processed_content.splitlines()
for line_num, (original_line, processed_line) in enumerate(zip(lines, processed_lines), 1):
for match in FUNCTION_CALL_PATTERN.finditer(processed_line):
func_name = match.group(1)
col_num = match.start(1) + 1 # +1 for 1-based column
# Check if the function is on our base forbidden list
if func_name in forbidden_funcs:
# If it is, check if it's explicitly allowed by the user's config
if not is_allowed_by_config(func_name, allow_funcs):
issues.append({
"file": str(file_path),
"line": line_num,
"column": col_num,
"function": func_name,
"message": f"Forbidden function '{func_name}' found."
})
elif verbose:
# In verbose mode, show all found functions that are allowed by default
# (i.e., not in the forbidden_funcs_base)
print(f"DEBUG: Found allowed function '{func_name}' in {file_path}:{line_num}:{col_num}")
except Exception as e:
print(f"Error processing {file_path}: {e}", file=sys.stderr)
return issues
def main():
parser = argparse.ArgumentParser(
description="C Linter for checking forbidden function calls.",
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument('paths', nargs='+',
help="Paths to C source files or directories to lint.")
parser.add_argument('--allow-funcs', nargs='*', default=[],
help="Space-separated list of functions allowed to override "
"the default forbidden list. Wildcards like 'hello_*' are supported.\n"
"Example: --allow-funcs malloc printf hello_world\n"
"Note: 'hello_*' will allow functions like 'hello_world', 'hello_init', etc.")
parser.add_argument('--excludes', nargs='*', default=[],
help="Space-separated list of files or folders to exclude from linting.\n"
"Example: --excludes folder/ file.c another_folder/")
parser.add_argument('--verbose', action='store_true',
help="Enable verbose output (e.g., showing allowed functions found).")
parser.add_argument('--forbidden-list', nargs='*',
help="Override the default hardcoded forbidden function list. "
"Use 'none' to clear it entirely. Otherwise, provide a space-separated list.\n"
"Example: --forbidden-list strcpy system fork\n"
"Example: --forbidden-list none")
args = parser.parse_args()
# Determine the actual forbidden functions list
if args.forbidden_list is not None:
if 'none' in args.forbidden_list:
final_forbidden_funcs = set()
else:
final_forbidden_funcs = set(args.forbidden_list)
else:
final_forbidden_funcs = FORBIDDEN_FUNCTIONS_BASE
all_issues = []
linted_files_count = 0
for path_str in args.paths:
path = Path(path_str)
if not path.exists():
print(f"Warning: Path '{path_str}' does not exist. Skipping.", file=sys.stderr)
continue
if path.is_file():
if path.suffix in ['.c', '.h', '.cpp', '.hpp']: # Lint C/C++ files
if not is_excluded(path, args.excludes):
linted_files_count += 1
issues = lint_file(path, final_forbidden_funcs, args.allow_funcs, args.verbose)
all_issues.extend(issues)
elif args.verbose:
print(f"Skipping excluded file: {path}")
elif args.verbose:
print(f"Skipping non C/C++ file: {path}")
elif path.is_dir():
if not is_excluded(path, args.excludes):
for root, _, files in os.walk(path):
for file_name in files:
file_path = Path(root) / file_name
if file_path.suffix in ['.c', '.h', '.cpp', '.hpp']:
if not is_excluded(file_path, args.excludes):
linted_files_count += 1
issues = lint_file(file_path, final_forbidden_funcs, args.allow_funcs, args.verbose)
all_issues.extend(issues)
elif args.verbose:
print(f"Skipping excluded file: {file_path}")
elif args.verbose:
print(f"Skipping non C/C++ file: {file_path}")
elif args.verbose:
print(f"Skipping excluded directory: {path}")
if all_issues:
print("\n--- Linter Report ---")
for issue in all_issues:
print(f"{issue['file']}:{issue['line']}:{issue['column']}: {issue['message']}")
print(f"\nFound {len(all_issues)} forbidden function calls in {linted_files_count} files.")
sys.exit(1) # Indicate failure
else:
print(f"\nNo forbidden function calls found in {linted_files_count} files. Good job!")
sys.exit(0) # Indicate success
if __name__ == "__main__":
main()
How to Use
-
Save: Save the code above as c_linter.py.
-
Make Executable (Optional): chmod +x c_linter.py
-
Run:
python c_linter.py <path_to_c_file_or_dir> [options]
Examples:
Let's create a test C file: test_code.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // For malloc
// This is a comment containing strcpy()
/* Another comment with system("ls") */
void my_project_func() {
printf("Hello from project func!\n");
// Some logic
}
void process_data(char* buffer) {
// Forbidden by default, but allowed by config
char temp[100];
strcpy(temp, buffer); // This is risky!
// Forbidden by default
system("echo 'hello'"); // Dangerous!
}
int main(int argc, char **argv) {
// Allowed by config
char* my_mem = malloc(100);
if (my_mem == NULL) {
return 1;
}
printf("Memory allocated.\n");
my_project_func();
// Not in our default forbidden list, so allowed
hello_world_func(); // Assumed project-defined
process_data(argv[0]);
free(my_mem); // free is in the default forbidden list, but often allowed.
// If not explicitly allowed, it would be flagged.
return 0;
}
Scenario 1: Default Scan
python c_linter.py test_code.c
Expected Output:
--- Linter Report ---
test_code.c:19:5: Forbidden function 'strcpy' found.
test_code.c:23:5: Forbidden function 'system' found.
test_code.c:40:5: Forbidden function 'free' found.
Found 3 forbidden function calls in 1 files.
Scenario 2: Allow malloc, printf, hello_*
python c_linter.py test_code.c --allow-funcs malloc printf hello_* free
Expected Output:
(Now malloc, printf, hello_world_func, free are allowed)
--- Linter Report ---
test_code.c:19:5: Forbidden function 'strcpy' found.
test_code.c:23:5: Forbidden function 'system' found.
Found 2 forbidden function calls in 1 files.
Notice free is now allowed because it was added to allow_funcs.
Scenario 3: Exclude a file
python c_linter.py . --excludes test_code.c
Expected Output:
Skipping excluded file: test_code.c
No forbidden function calls found in 0 files. Good job!
Scenario 4: Using a custom forbidden list
Let's say you only want to forbid system and strcpy.
python c_linter.py test_code.c --forbidden-list system strcpy --allow-funcs printf
Expected Output:
--- Linter Report ---
test_code.c:19:5: Forbidden function 'strcpy' found.
test_code.c:23:5: Forbidden function 'system' found.
Found 2 forbidden function calls in 1 files.
In this case, malloc, free, hello_world_func are implicitly allowed because they are not on the custom forbidden-list.
Scenario 5: Clear the forbidden list (only check what's explicitly added)
python c_linter.py test_code.c --forbidden-list none
Expected Output:
No forbidden function calls found in 1 files. Good job!
Since the forbidden list is empty, nothing is flagged. This is useful if you want to build your forbidden list from scratch.
Robustness Considerations & Limitations
- Preprocessing for Comments and Strings: The
remove_comments_and_strings function is crucial. It uses regular expressions that handle multi-line comments (/* */), single-line comments (//), and string/character literals ("...", '...') including escaped quotes within them. This significantly reduces false positives.
\b in Regex: The \b (word boundary) in FUNCTION_CALL_PATTERN prevents matching substrings (e.g., printf in my_printf_wrapper).
pathlib and os.walk: Using pathlib for path manipulation and os.walk for directory traversal ensures cross-platform compatibility and proper handling of file paths.
fnmatch for Wildcards: fnmatch.fnmatch is used for allow_funcs wildcard matching, which is robust for shell-style wildcards.
- Exclusions: The
is_excluded function intelligently checks if an exclusion is a file or a directory, using Path.is_relative_to for directory containment.
- Line and Column Numbers: The linter attempts to provide accurate line and column numbers by processing line by line and using
match.start().
Limitations (inherent without a full C parser/AST):
- Macros: If a macro expands to a forbidden function (e.g.,
#define MY_STRCPY strcpy), this linter will not detect MY_STRCPY(...). A full preprocessor run or AST parser would be needed.
- Function Pointers: Calls through function pointers (
(*func_ptr)(args)) or func_ptr(args) (if func_ptr is a function pointer) will not be detected by the current regex, as it looks for an identifier directly followed by (.
- Complex Syntax: Highly unusual C syntax might bypass the regex (e.g.,
(void)(func_name)(args)).
- Context: It doesn't understand the context of the call (e.g., if
strcpy is called within a well-audited, safe wrapper function). A real static analysis tool would use data flow analysis.
- Function Definitions: The regex might occasionally match a function definition if it doesn't look ahead for
{. However, the current regex targets NAME( which is usually a call. A more sophisticated regex would explicitly try to exclude TYPE NAME( or NAME (ARGS) {. For a quick linter, this is usually acceptable, as definitions are unlikely to be on the forbidden list.
Despite these limitations, this linter is quite robust for its class (regex-based) and handles the common pitfalls effectively. For true, compiler-level robustness, you would need to integrate with clang (via libclang bindings in Python) or use a dedicated C parsing library like pycparser to build an Abstract Syntax Tree (AST) and traverse it.