Skip to content

Commit 512a0d6

Browse files
committed
Rust: Add MaD bulk generation script
1 parent 51229a6 commit 512a0d6

File tree

2 files changed

+337
-0
lines changed

2 files changed

+337
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ node_modules/
6262

6363
# Temporary folders for working with generated models
6464
.model-temp
65+
/mad-generation-build
6566

6667
# bazel-built in-tree extractor packs
6768
/*/extractor-pack
Lines changed: 336 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,336 @@
1+
"""
2+
Experimental script for bulk generation of MaD models based on a list of projects.
3+
4+
Currently the script only targets Rust.
5+
"""
6+
7+
import os.path
8+
import subprocess
9+
import sys
10+
from typing import TypedDict, List, Optional
11+
from concurrent.futures import ThreadPoolExecutor, as_completed
12+
import time
13+
14+
import generate_mad as mad
15+
16+
gitroot = (
17+
subprocess.check_output(["git", "rev-parse", "--show-toplevel"])
18+
.decode("utf-8")
19+
.strip()
20+
)
21+
build_dir = os.path.join(gitroot, "mad-generation-build")
22+
23+
24+
def path_to_mad_directory(language: str, name: str) -> str:
25+
return os.path.join(gitroot, f"{language}/ql/lib/ext/generated/{name}")
26+
27+
28+
# A project to generate models for
29+
class Project(TypedDict):
30+
"""
31+
Type definition for Rust projects to model.
32+
33+
Attributes:
34+
name: The name of the project
35+
git_repo: URL to the git repository
36+
git_tag: Optional Git tag to check out
37+
"""
38+
39+
name: str
40+
git_repo: str
41+
git_tag: Optional[str]
42+
43+
44+
# List of Rust projects to generate models for.
45+
projects: List[Project] = [
46+
{
47+
"name": "libc",
48+
"git_repo": "https://github.com/rust-lang/libc",
49+
"git_tag": "0.2.172",
50+
},
51+
{
52+
"name": "log",
53+
"git_repo": "https://github.com/rust-lang/log",
54+
"git_tag": "0.4.27",
55+
},
56+
{
57+
"name": "memchr",
58+
"git_repo": "https://github.com/BurntSushi/memchr",
59+
"git_tag": "2.7.4",
60+
},
61+
{
62+
"name": "once_cell",
63+
"git_repo": "https://github.com/matklad/once_cell",
64+
"git_tag": "v1.21.3",
65+
},
66+
{
67+
"name": "rand",
68+
"git_repo": "https://github.com/rust-random/rand",
69+
"git_tag": "0.9.1",
70+
},
71+
{
72+
"name": "smallvec",
73+
"git_repo": "https://github.com/servo/rust-smallvec",
74+
"git_tag": "v1.15.0",
75+
},
76+
{
77+
"name": "serde",
78+
"git_repo": "https://github.com/serde-rs/serde",
79+
"git_tag": "v1.0.219",
80+
},
81+
{
82+
"name": "tokio",
83+
"git_repo": "https://github.com/tokio-rs/tokio",
84+
"git_tag": "tokio-1.45.0",
85+
},
86+
# NOTE: We want to include `reqwest` but as of now the only effect of that
87+
# is that the previously generated models are deleted. Once that issue is
88+
# solved we should include it here.
89+
# {
90+
# "name": "reqwest",
91+
# "git_repo": "https://github.com/seanmonstar/reqwest",
92+
# "git_tag": "v0.12.15",
93+
# },
94+
{
95+
"name": "rocket",
96+
"git_repo": "https://github.com/SergioBenitez/Rocket",
97+
"git_tag": "v0.5.1",
98+
},
99+
{
100+
"name": "actix-web",
101+
"git_repo": "https://github.com/actix/actix-web",
102+
"git_tag": "web-v4.11.0",
103+
},
104+
{
105+
"name": "hyper",
106+
"git_repo": "https://github.com/hyperium/hyper",
107+
"git_tag": "v1.6.0",
108+
},
109+
{
110+
"name": "clap",
111+
"git_repo": "https://github.com/clap-rs/clap",
112+
"git_tag": "v4.5.38",
113+
},
114+
]
115+
116+
117+
def clone_project(project: Project) -> str:
118+
"""
119+
Shallow clone a project into the build directory.
120+
121+
Args:
122+
project: A dictionary containing project information with 'name', 'git_repo', and optional 'git_tag' keys.
123+
124+
Returns:
125+
The path to the cloned project directory.
126+
"""
127+
name = project["name"]
128+
repo_url = project["git_repo"]
129+
git_tag = project.get("git_tag")
130+
131+
# Determine target directory
132+
target_dir = os.path.join(build_dir, name)
133+
134+
# Clone only if directory doesn't already exist
135+
if not os.path.exists(target_dir):
136+
if git_tag:
137+
print(f"Cloning {name} from {repo_url} at tag {git_tag}")
138+
else:
139+
print(f"Cloning {name} from {repo_url}")
140+
141+
subprocess.check_call(
142+
[
143+
"git",
144+
"clone",
145+
"--quiet",
146+
"--depth",
147+
"1", # Shallow clone
148+
*(
149+
["--branch", git_tag] if git_tag else []
150+
), # Add branch if tag is provided
151+
repo_url,
152+
target_dir,
153+
]
154+
)
155+
print(f"Completed cloning {name}")
156+
else:
157+
print(f"Skipping cloning {name} as it already exists at {target_dir}")
158+
159+
return target_dir
160+
161+
162+
def clone_projects(projects: List[Project]) -> List[tuple[Project, str]]:
163+
"""
164+
Clone all projects in parallel.
165+
166+
Args:
167+
projects: List of projects to clone
168+
169+
Returns:
170+
List of (project, project_dir) pairs in the same order as the input projects
171+
"""
172+
start_time = time.time()
173+
max_workers = min(8, len(projects)) # Use at most 8 threads
174+
project_dirs_map = {} # Map to store results by project name
175+
176+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
177+
# Start cloning tasks and keep track of them
178+
future_to_project = {
179+
executor.submit(clone_project, project): project for project in projects
180+
}
181+
182+
# Process results as they complete
183+
for future in as_completed(future_to_project):
184+
project = future_to_project[future]
185+
try:
186+
project_dir = future.result()
187+
project_dirs_map[project["name"]] = (project, project_dir)
188+
except Exception as e:
189+
print(f"ERROR: Failed to clone {project['name']}: {e}")
190+
191+
if len(project_dirs_map) != len(projects):
192+
failed_projects = [
193+
project["name"]
194+
for project in projects
195+
if project["name"] not in project_dirs_map
196+
]
197+
print(
198+
f"ERROR: Only {len(project_dirs_map)} out of {len(projects)} projects were cloned successfully. Failed projects: {', '.join(failed_projects)}"
199+
)
200+
sys.exit(1)
201+
202+
project_dirs = [project_dirs_map[project["name"]] for project in projects]
203+
204+
clone_time = time.time() - start_time
205+
print(f"Cloning completed in {clone_time:.2f} seconds")
206+
return project_dirs
207+
208+
209+
def build_database(project: Project, project_dir: str) -> str | None:
210+
"""
211+
Build a CodeQL database for a project.
212+
213+
Args:
214+
project: A dictionary containing project information with 'name' and 'git_repo' keys.
215+
project_dir: The directory containing the project source code.
216+
217+
Returns:
218+
The path to the created database directory.
219+
"""
220+
name = project["name"]
221+
222+
# Create database directory path
223+
database_dir = os.path.join(build_dir, f"{name}-db")
224+
225+
# Only build the database if it doesn't already exist
226+
if not os.path.exists(database_dir):
227+
print(f"Building CodeQL database for {name}...")
228+
try:
229+
subprocess.check_call(
230+
[
231+
"codeql",
232+
"database",
233+
"create",
234+
"--language=rust",
235+
"--source-root=" + project_dir,
236+
"--overwrite",
237+
"--",
238+
database_dir,
239+
]
240+
)
241+
print(f"Successfully created database at {database_dir}")
242+
except subprocess.CalledProcessError as e:
243+
print(f"Failed to create database for {name}: {e}")
244+
return None
245+
else:
246+
print(
247+
f"Skipping database creation for {name} as it already exists at {database_dir}"
248+
)
249+
250+
return database_dir
251+
252+
253+
def generate_models(project: Project, database_dir: str) -> None:
254+
"""
255+
Generate models for a project.
256+
257+
Args:
258+
project: A dictionary containing project information with 'name' and 'git_repo' keys.
259+
project_dir: The directory containing the project source code.
260+
"""
261+
name = project["name"]
262+
263+
generator = mad.Generator("rust")
264+
generator.generateSinks = True
265+
generator.generateSources = True
266+
generator.generateSummaries = True
267+
generator.setenvironment(database=database_dir, folder=name)
268+
generator.run()
269+
270+
271+
def main() -> None:
272+
"""
273+
Process all projects in three distinct phases:
274+
1. Clone projects (in parallel)
275+
2. Build databases for projects
276+
3. Generate models for successful database builds
277+
"""
278+
279+
# Create build directory if it doesn't exist
280+
if not os.path.exists(build_dir):
281+
os.makedirs(build_dir)
282+
283+
# Check if any of the MaD directories contain working directory changes in git
284+
for project in projects:
285+
mad_dir = path_to_mad_directory("rust", project["name"])
286+
if os.path.exists(mad_dir):
287+
git_status_output = subprocess.check_output(
288+
["git", "status", "-s", mad_dir], text=True
289+
).strip()
290+
if git_status_output:
291+
print(
292+
f"""ERROR: Working directory changes detected in {mad_dir}.
293+
294+
Before generating new models, the existing models are deleted.
295+
296+
To avoid loss of data, please commit your changes."""
297+
)
298+
sys.exit(1)
299+
300+
# Phase 1: Clone projects in parallel
301+
print("=== Phase 1: Cloning projects ===")
302+
project_dirs = clone_projects(projects)
303+
304+
# Phase 2: Build databases for all projects
305+
print("\n=== Phase 2: Building databases ===")
306+
database_results = [
307+
(project, build_database(project, project_dir))
308+
for project, project_dir in project_dirs
309+
]
310+
311+
# Phase 3: Generate models for all projects
312+
print("\n=== Phase 3: Generating models ===")
313+
314+
failed_builds = [
315+
project["name"] for project, db_dir in database_results if db_dir is None
316+
]
317+
if failed_builds:
318+
print(
319+
f"ERROR: {len(failed_builds)} database builds failed: {', '.join(failed_builds)}"
320+
)
321+
sys.exit(1)
322+
323+
# Delete the MaD directory for each project
324+
for project, database_dir in database_results:
325+
mad_dir = path_to_mad_directory("rust", project["name"])
326+
if os.path.exists(mad_dir):
327+
print(f"Deleting existing MaD directory at {mad_dir}")
328+
subprocess.check_call(["rm", "-rf", mad_dir])
329+
330+
for project, database_dir in database_results:
331+
if database_dir is not None:
332+
generate_models(project, database_dir)
333+
334+
335+
if __name__ == "__main__":
336+
main()

0 commit comments

Comments
 (0)