Below is a robust implementation of a C linter that checks for forbidden function calls in a C program. This linter uses the libclang library (part of the Clang/LLVM project) to parse C code and analyze the Abstract Syntax Tree (AST) instead of relying on regex. This approach ensures accurate detection of function calls and definitions, even in complex codebases with macros, comments, or tricky formatting.
Features of the Linter
- AST-based Parsing: Uses
libclang to parse C code and analyze function calls and definitions.
- Configuration File: Reads a JSON configuration file to specify allowed functions (with wildcard support) and excluded files/folders.
- Robust Function Detection: Distinguishes between function declarations and definitions, allowing all defined functions in the project.
- Exclusions: Skips files or folders specified in the
excludes list.
- Error Reporting: Reports forbidden function calls with file, line, and column information.
Prerequisites
- Install
libclang and its Python bindings:
pip install libclang
- Ensure you have Clang/LLVM installed on your system (e.g.,
sudo apt install clang on Ubuntu).
- Python 3.x is required to run the script.
Linter Implementation
Here is the Python script for the linter:
import os
import sys
import json
import fnmatch
from clang.cindex import Index, CursorKind, Config
class CLinter:
def __init__(self, config_path):
"""Initialize the linter with a configuration file."""
self.config = self._load_config(config_path)
self.allowed_funcs = set(self.config.get("allow_funcs", []))
self.excludes = set(self.config.get("excludes", []))
self.defined_funcs = set() # Store functions defined in the project
self.errors = [] # Store linting errors
def _load_config(self, config_path):
"""Load and parse the JSON configuration file."""
try:
with open(config_path, 'r') as f:
return json.load(f)
except FileNotFoundError:
print(f"Error: Configuration file '{config_path}' not found.")
sys.exit(1)
except json.JSONDecodeError:
print(f"Error: Invalid JSON in configuration file '{config_path}'.")
sys.exit(1)
def _is_allowed_func(self, func_name):
"""Check if a function is allowed based on the config (supports wildcards)."""
for pattern in self.allowed_funcs:
if fnmatch.fnmatch(func_name, pattern):
return True
return False
def _is_excluded(self, filepath):
"""Check if a file or its parent folder is in the excludes list."""
filepath = os.path.normpath(filepath)
for exclude in self.excludes:
exclude = os.path.normpath(exclude)
if exclude in filepath or fnmatch.fnmatch(os.path.basename(filepath), exclude):
return True
return False
def _collect_defined_functions(self, node, filepath):
"""Traverse the AST to collect all function definitions in the project."""
if self._is_excluded(filepath):
return
if node.kind == CursorKind.FUNCTION_DECL and node.is_definition():
self.defined_funcs.add(node.spelling)
for child in node.get_children():
self._collect_defined_functions(child, filepath)
def _check_forbidden_calls(self, node, filepath):
"""Traverse the AST to check for forbidden function calls."""
if self._is_excluded(filepath):
return
if node.kind == CursorKind.CALL_EXPR:
func_name = node.spelling
if func_name and func_name not in self.defined_funcs and not self._is_allowed_func(func_name):
location = node.location
error_msg = (
f"Forbidden function call '{func_name}' detected at "
f"{location.file}:{location.line}:{location.column}"
)
self.errors.append(error_msg)
for child in node.get_children():
self._check_forbidden_calls(child, filepath)
def lint_file(self, filepath):
"""Lint a single C file."""
if self._is_excluded(filepath):
print(f"Skipping excluded file: {filepath}")
return
try:
index = Index.create()
tu = index.parse(filepath, args=['-std=c11']) # Adjust C standard if needed
if not tu:
print(f"Error: Failed to parse file '{filepath}'.")
return
# Step 1: Collect defined functions
self._collect_defined_functions(tu.cursor, filepath)
# Step 2: Check for forbidden function calls
self._check_forbidden_calls(tu.cursor, filepath)
except Exception as e:
print(f"Error processing file '{filepath}': {e}")
def lint_project(self, project_dir):
"""Lint all C files in a project directory."""
for root, _, files in os.walk(project_dir):
for filename in files:
if filename.endswith(('.c', '.h')): # Process C source and header files
filepath = os.path.join(root, filename)
self.lint_file(filepath)
# Report errors
if self.errors:
print("\nLinting Errors:")
for error in self.errors:
print(error)
sys.exit(1)
else:
print("\nNo linting errors found.")
def main():
if len(sys.argv) != 3:
print("Usage: python linter.py <config.json> <project_dir>")
sys.exit(1)
config_path = sys.argv[1]
project_dir = sys.argv[2]
if not os.path.exists(config_path):
print(f"Error: Configuration file '{config_path}' does not exist.")
sys.exit(1)
if not os.path.isdir(project_dir):
print(f"Error: Project directory '{project_dir}' does not exist.")
sys.exit(1)
# Set the path to libclang if needed (e.g., on Windows or custom installations)
# Config.set_library_path('/path/to/llvm/lib')
linter = CLinter(config_path)
linter.lint_project(project_dir)
if __name__ == "__main__":
main()
Example Configuration File (config.json)
{
"allow_funcs": ["malloc", "printf", "hello_*"],
"excludes": ["folder", "file.c"]
}
How to Use the Linter
- Save the script as
linter.py.
- Create a
config.json file with the desired configuration (as shown above).
- Run the linter on your project:
python linter.py config.json /path/to/your/project
Example Project Structure
Assume the following project structure:
/project
├── config.json
├── main.c
├── utils.c
├── folder
│ └── excluded.c
└── file.c
main.c
#include <stdio.h>
#include <stdlib.h>
void my_function() {
printf("Hello, world!\n");
malloc(10); // Allowed
hello_world(); // Allowed (matches hello_*)
forbidden_function(); // Forbidden
}
int main() {
my_function();
return 0;
}
utils.c
#include <stdio.h>
void hello_world() {
printf("Hello from utils!\n");
}
void forbidden_function() {
printf("This is forbidden!\n");
}
folder/excluded.c
#include <stdio.h>
void some_function() {
forbidden_function(); // Ignored because this file is excluded
}
file.c
#include <stdio.h>
void another_function() {
forbidden_function(); // Ignored because this file is excluded
}
Running the Linter
Run the linter:
python linter.py config.json /project
Expected Output
The linter will:
- Skip
folder/excluded.c and file.c due to the excludes configuration.
- Allow
printf, malloc, and hello_world due to the allow_funcs configuration.
- Allow
my_function because it is defined in the project.
- Report an error for the call to
forbidden_function in main.c.
Example output:
Skipping excluded file: /project/folder/excluded.c
Skipping excluded file: /project/file.c
Linting Errors:
Forbidden function call 'forbidden_function' detected at /project/main.c:8:5
Notes
- libclang Path: If
libclang is not found, you may need to set the path to the library explicitly in the script (see the commented line in main()).
- C Standard: The script uses
-std=c11 for parsing. Adjust this if your project uses a different C standard (e.g., -std=c99).
- Wildcards: The
allow_funcs list supports wildcards (e.g., hello_*) using fnmatch.
- Error Handling: The script includes basic error handling for file parsing and configuration loading. You can extend this further as needed.
- Performance: For large projects, consider parallelizing the file processing using Python's
multiprocessing module.
This linter is robust, extensible, and avoids the pitfalls of regex-based approaches, making it suitable for real-world C projects.