├── .github
└── workflows
│ ├── build.yml
│ ├── clippy.yml
│ ├── rustfmt.yml
│ ├── tarpaulin.yml
│ └── tests.yml
├── .gitignore
├── CHANGELOG.md
├── Cargo.lock
├── Cargo.toml
├── LICENSE
├── Makefile
├── README.md
├── src
├── cli.rs
├── compilation_database
│ ├── compile_commands.rs
│ ├── file_list.rs
│ └── mod.rs
├── information_leak
│ ├── confirmed_leak.rs
│ ├── leak_location.rs
│ ├── mod.rs
│ └── potential_leak.rs
├── main.rs
├── reporting.rs
└── suppressions.rs
└── tests
└── data
├── compile_commands
├── db1.json
├── empty.json
├── file1.cc
├── file2.cc
└── invalid.json
├── main
└── file_list_proj
│ ├── a.exe
│ ├── a.out
│ ├── header.h
│ └── main.cc
└── suppressions
└── files_and_artifacts.yml
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: Build
2 |
3 | on:
4 | pull_request:
5 | push:
6 | branches:
7 | - main
8 |
9 | jobs:
10 | build-latest-windows:
11 | name: Build on Windows - Latest
12 | runs-on: windows-latest
13 | steps:
14 | - uses: actions/checkout@v2
15 | - uses: actions-rs/toolchain@v1
16 | with:
17 | toolchain: stable
18 | profile: minimal
19 | override: true
20 | - name: Build
21 | run: cargo build --release
22 | - name: Upload Build Artifacts
23 | uses: actions/upload-artifact@v3
24 | with:
25 | name: cpplumber-win64
26 | path: target/release/*.exe
27 | retention-days: 3
28 |
--------------------------------------------------------------------------------
/.github/workflows/clippy.yml:
--------------------------------------------------------------------------------
1 | name: Clippy
2 |
3 | on: [push]
4 |
5 | jobs:
6 | build:
7 | runs-on: ubuntu-20.04
8 |
9 | steps:
10 | - uses: actions/checkout@v1
11 | - uses: actions-rs/toolchain@v1
12 | with:
13 | toolchain: stable
14 | profile: minimal
15 | components: clippy, rustfmt
16 | override: true
17 | - name: Install libclang-dev
18 | run: sudo apt-get update; sudo apt-get install --no-install-recommends libclang-10-dev
19 | if: runner.os == 'linux'
20 | - name: Run clippy
21 | run: make lint
22 |
23 |
--------------------------------------------------------------------------------
/.github/workflows/rustfmt.yml:
--------------------------------------------------------------------------------
1 | name: Rustfmt
2 |
3 | on: [push]
4 |
5 | jobs:
6 | build:
7 | runs-on: ubuntu-latest
8 |
9 | steps:
10 | - uses: actions/checkout@v1
11 | - uses: actions-rs/toolchain@v1
12 | with:
13 | toolchain: stable
14 | profile: minimal
15 | components: clippy, rustfmt
16 | override: true
17 | - name: Run rustfmt
18 | run: make format-check
19 |
20 |
--------------------------------------------------------------------------------
/.github/workflows/tarpaulin.yml:
--------------------------------------------------------------------------------
1 | name: Tarpaulin
2 |
3 | on: [push]
4 |
5 | jobs:
6 | check:
7 | name: Tarpaulin on Linux - Latest
8 | runs-on: ubuntu-latest
9 | steps:
10 | - name: Checkout repository
11 | uses: actions/checkout@v2
12 |
13 | - name: Install stable toolchain
14 | uses: actions-rs/toolchain@v1
15 | with:
16 | toolchain: stable
17 | override: true
18 |
19 | - name: Install libclang-dev
20 | run: sudo apt-get update; sudo apt-get install --no-install-recommends libclang-10-dev
21 | if: runner.os == 'linux'
22 |
23 | - name: Run cargo-tarpaulin
24 | uses: actions-rs/tarpaulin@v0.1
25 | with:
26 | version: '0.15.0'
27 | args: '--ignore-tests --out Lcov -- --test-threads 1'
28 |
29 | - name: Upload to Coveralls
30 | uses: coverallsapp/github-action@master
31 | with:
32 | github-token: ${{ secrets.GITHUB_TOKEN }}
33 | path-to-lcov: './lcov.info'
34 |
--------------------------------------------------------------------------------
/.github/workflows/tests.yml:
--------------------------------------------------------------------------------
1 | name: Tests
2 |
3 | on: [push]
4 |
5 | jobs:
6 | test-latest:
7 | name: Test on Linux - Latest
8 | runs-on: ubuntu-20.04
9 |
10 | steps:
11 | - uses: actions/checkout@v2
12 | - uses: actions-rs/toolchain@v1
13 | with:
14 | toolchain: stable
15 | profile: minimal
16 | override: true
17 | - name: Install libclang-dev
18 | run: sudo apt-get update; sudo apt-get install --no-install-recommends libclang-10-dev
19 | if: runner.os == 'linux'
20 | - name: Test
21 | run: make test
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Generated by Cargo
2 | # will have compiled files and executables
3 | /target/
4 |
5 | # These are backup files generated by rustfmt
6 | **/*.rs.bk
7 |
8 |
9 | # Added by cargo
10 |
11 | /target
12 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## [Unreleased]
4 |
5 | ## [0.1.0] - 2022-09-24
6 |
7 | Initial release
8 |
--------------------------------------------------------------------------------
/Cargo.lock:
--------------------------------------------------------------------------------
1 | # This file is automatically @generated by Cargo.
2 | # It is not intended for manual editing.
3 | version = 3
4 |
5 | [[package]]
6 | name = "aho-corasick"
7 | version = "0.7.19"
8 | source = "registry+https://github.com/rust-lang/crates.io-index"
9 | checksum = "b4f55bd91a0978cbfd91c457a164bab8b4001c833b7f323132c0a4e1922dd44e"
10 | dependencies = [
11 | "memchr",
12 | ]
13 |
14 | [[package]]
15 | name = "ansi_term"
16 | version = "0.12.1"
17 | source = "registry+https://github.com/rust-lang/crates.io-index"
18 | checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2"
19 | dependencies = [
20 | "winapi",
21 | ]
22 |
23 | [[package]]
24 | name = "anyhow"
25 | version = "1.0.65"
26 | source = "registry+https://github.com/rust-lang/crates.io-index"
27 | checksum = "98161a4e3e2184da77bb14f02184cdd111e83bbbcc9979dfee3c44b9a85f5602"
28 |
29 | [[package]]
30 | name = "atty"
31 | version = "0.2.14"
32 | source = "registry+https://github.com/rust-lang/crates.io-index"
33 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
34 | dependencies = [
35 | "hermit-abi",
36 | "libc",
37 | "winapi",
38 | ]
39 |
40 | [[package]]
41 | name = "autocfg"
42 | version = "1.1.0"
43 | source = "registry+https://github.com/rust-lang/crates.io-index"
44 | checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
45 |
46 | [[package]]
47 | name = "bitflags"
48 | version = "1.3.2"
49 | source = "registry+https://github.com/rust-lang/crates.io-index"
50 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
51 |
52 | [[package]]
53 | name = "cfg-if"
54 | version = "1.0.0"
55 | source = "registry+https://github.com/rust-lang/crates.io-index"
56 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
57 |
58 | [[package]]
59 | name = "clang"
60 | version = "2.0.0"
61 | source = "registry+https://github.com/rust-lang/crates.io-index"
62 | checksum = "84c044c781163c001b913cd018fc95a628c50d0d2dfea8bca77dad71edb16e37"
63 | dependencies = [
64 | "clang-sys",
65 | "libc",
66 | ]
67 |
68 | [[package]]
69 | name = "clang-sys"
70 | version = "1.3.3"
71 | source = "registry+https://github.com/rust-lang/crates.io-index"
72 | checksum = "5a050e2153c5be08febd6734e29298e844fdb0fa21aeddd63b4eb7baa106c69b"
73 | dependencies = [
74 | "glob",
75 | "libc",
76 | ]
77 |
78 | [[package]]
79 | name = "clap"
80 | version = "2.34.0"
81 | source = "registry+https://github.com/rust-lang/crates.io-index"
82 | checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"
83 | dependencies = [
84 | "ansi_term",
85 | "atty",
86 | "bitflags",
87 | "strsim",
88 | "textwrap",
89 | "unicode-width",
90 | "vec_map",
91 | ]
92 |
93 | [[package]]
94 | name = "cpplumber"
95 | version = "0.1.0"
96 | dependencies = [
97 | "anyhow",
98 | "clang",
99 | "env_logger",
100 | "glob",
101 | "log",
102 | "rayon",
103 | "serde",
104 | "serde_json",
105 | "serde_yaml",
106 | "serial_test",
107 | "structopt",
108 | "tempfile",
109 | "widestring",
110 | ]
111 |
112 | [[package]]
113 | name = "crossbeam-channel"
114 | version = "0.5.6"
115 | source = "registry+https://github.com/rust-lang/crates.io-index"
116 | checksum = "c2dd04ddaf88237dc3b8d8f9a3c1004b506b54b3313403944054d23c0870c521"
117 | dependencies = [
118 | "cfg-if",
119 | "crossbeam-utils",
120 | ]
121 |
122 | [[package]]
123 | name = "crossbeam-deque"
124 | version = "0.8.2"
125 | source = "registry+https://github.com/rust-lang/crates.io-index"
126 | checksum = "715e8152b692bba2d374b53d4875445368fdf21a94751410af607a5ac677d1fc"
127 | dependencies = [
128 | "cfg-if",
129 | "crossbeam-epoch",
130 | "crossbeam-utils",
131 | ]
132 |
133 | [[package]]
134 | name = "crossbeam-epoch"
135 | version = "0.9.10"
136 | source = "registry+https://github.com/rust-lang/crates.io-index"
137 | checksum = "045ebe27666471bb549370b4b0b3e51b07f56325befa4284db65fc89c02511b1"
138 | dependencies = [
139 | "autocfg",
140 | "cfg-if",
141 | "crossbeam-utils",
142 | "memoffset",
143 | "once_cell",
144 | "scopeguard",
145 | ]
146 |
147 | [[package]]
148 | name = "crossbeam-utils"
149 | version = "0.8.11"
150 | source = "registry+https://github.com/rust-lang/crates.io-index"
151 | checksum = "51887d4adc7b564537b15adcfb307936f8075dfcd5f00dde9a9f1d29383682bc"
152 | dependencies = [
153 | "cfg-if",
154 | "once_cell",
155 | ]
156 |
157 | [[package]]
158 | name = "dashmap"
159 | version = "5.4.0"
160 | source = "registry+https://github.com/rust-lang/crates.io-index"
161 | checksum = "907076dfda823b0b36d2a1bb5f90c96660a5bbcd7729e10727f07858f22c4edc"
162 | dependencies = [
163 | "cfg-if",
164 | "hashbrown",
165 | "lock_api",
166 | "once_cell",
167 | "parking_lot_core",
168 | ]
169 |
170 | [[package]]
171 | name = "either"
172 | version = "1.8.0"
173 | source = "registry+https://github.com/rust-lang/crates.io-index"
174 | checksum = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797"
175 |
176 | [[package]]
177 | name = "env_logger"
178 | version = "0.9.1"
179 | source = "registry+https://github.com/rust-lang/crates.io-index"
180 | checksum = "c90bf5f19754d10198ccb95b70664fc925bd1fc090a0fd9a6ebc54acc8cd6272"
181 | dependencies = [
182 | "atty",
183 | "humantime",
184 | "log",
185 | "regex",
186 | "termcolor",
187 | ]
188 |
189 | [[package]]
190 | name = "fastrand"
191 | version = "1.8.0"
192 | source = "registry+https://github.com/rust-lang/crates.io-index"
193 | checksum = "a7a407cfaa3385c4ae6b23e84623d48c2798d06e3e6a1878f7f59f17b3f86499"
194 | dependencies = [
195 | "instant",
196 | ]
197 |
198 | [[package]]
199 | name = "futures"
200 | version = "0.3.24"
201 | source = "registry+https://github.com/rust-lang/crates.io-index"
202 | checksum = "7f21eda599937fba36daeb58a22e8f5cee2d14c4a17b5b7739c7c8e5e3b8230c"
203 | dependencies = [
204 | "futures-channel",
205 | "futures-core",
206 | "futures-executor",
207 | "futures-io",
208 | "futures-sink",
209 | "futures-task",
210 | "futures-util",
211 | ]
212 |
213 | [[package]]
214 | name = "futures-channel"
215 | version = "0.3.24"
216 | source = "registry+https://github.com/rust-lang/crates.io-index"
217 | checksum = "30bdd20c28fadd505d0fd6712cdfcb0d4b5648baf45faef7f852afb2399bb050"
218 | dependencies = [
219 | "futures-core",
220 | "futures-sink",
221 | ]
222 |
223 | [[package]]
224 | name = "futures-core"
225 | version = "0.3.24"
226 | source = "registry+https://github.com/rust-lang/crates.io-index"
227 | checksum = "4e5aa3de05362c3fb88de6531e6296e85cde7739cccad4b9dfeeb7f6ebce56bf"
228 |
229 | [[package]]
230 | name = "futures-executor"
231 | version = "0.3.24"
232 | source = "registry+https://github.com/rust-lang/crates.io-index"
233 | checksum = "9ff63c23854bee61b6e9cd331d523909f238fc7636290b96826e9cfa5faa00ab"
234 | dependencies = [
235 | "futures-core",
236 | "futures-task",
237 | "futures-util",
238 | ]
239 |
240 | [[package]]
241 | name = "futures-io"
242 | version = "0.3.24"
243 | source = "registry+https://github.com/rust-lang/crates.io-index"
244 | checksum = "bbf4d2a7a308fd4578637c0b17c7e1c7ba127b8f6ba00b29f717e9655d85eb68"
245 |
246 | [[package]]
247 | name = "futures-sink"
248 | version = "0.3.24"
249 | source = "registry+https://github.com/rust-lang/crates.io-index"
250 | checksum = "21b20ba5a92e727ba30e72834706623d94ac93a725410b6a6b6fbc1b07f7ba56"
251 |
252 | [[package]]
253 | name = "futures-task"
254 | version = "0.3.24"
255 | source = "registry+https://github.com/rust-lang/crates.io-index"
256 | checksum = "a6508c467c73851293f390476d4491cf4d227dbabcd4170f3bb6044959b294f1"
257 |
258 | [[package]]
259 | name = "futures-util"
260 | version = "0.3.24"
261 | source = "registry+https://github.com/rust-lang/crates.io-index"
262 | checksum = "44fb6cb1be61cc1d2e43b262516aafcf63b241cffdb1d3fa115f91d9c7b09c90"
263 | dependencies = [
264 | "futures-channel",
265 | "futures-core",
266 | "futures-io",
267 | "futures-sink",
268 | "futures-task",
269 | "memchr",
270 | "pin-project-lite",
271 | "pin-utils",
272 | "slab",
273 | ]
274 |
275 | [[package]]
276 | name = "glob"
277 | version = "0.3.0"
278 | source = "registry+https://github.com/rust-lang/crates.io-index"
279 | checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574"
280 |
281 | [[package]]
282 | name = "hashbrown"
283 | version = "0.12.3"
284 | source = "registry+https://github.com/rust-lang/crates.io-index"
285 | checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
286 |
287 | [[package]]
288 | name = "heck"
289 | version = "0.3.3"
290 | source = "registry+https://github.com/rust-lang/crates.io-index"
291 | checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c"
292 | dependencies = [
293 | "unicode-segmentation",
294 | ]
295 |
296 | [[package]]
297 | name = "hermit-abi"
298 | version = "0.1.19"
299 | source = "registry+https://github.com/rust-lang/crates.io-index"
300 | checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
301 | dependencies = [
302 | "libc",
303 | ]
304 |
305 | [[package]]
306 | name = "humantime"
307 | version = "2.1.0"
308 | source = "registry+https://github.com/rust-lang/crates.io-index"
309 | checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
310 |
311 | [[package]]
312 | name = "indexmap"
313 | version = "1.9.1"
314 | source = "registry+https://github.com/rust-lang/crates.io-index"
315 | checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e"
316 | dependencies = [
317 | "autocfg",
318 | "hashbrown",
319 | ]
320 |
321 | [[package]]
322 | name = "instant"
323 | version = "0.1.12"
324 | source = "registry+https://github.com/rust-lang/crates.io-index"
325 | checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
326 | dependencies = [
327 | "cfg-if",
328 | ]
329 |
330 | [[package]]
331 | name = "itoa"
332 | version = "1.0.3"
333 | source = "registry+https://github.com/rust-lang/crates.io-index"
334 | checksum = "6c8af84674fe1f223a982c933a0ee1086ac4d4052aa0fb8060c12c6ad838e754"
335 |
336 | [[package]]
337 | name = "lazy_static"
338 | version = "1.4.0"
339 | source = "registry+https://github.com/rust-lang/crates.io-index"
340 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
341 |
342 | [[package]]
343 | name = "libc"
344 | version = "0.2.132"
345 | source = "registry+https://github.com/rust-lang/crates.io-index"
346 | checksum = "8371e4e5341c3a96db127eb2465ac681ced4c433e01dd0e938adbef26ba93ba5"
347 |
348 | [[package]]
349 | name = "lock_api"
350 | version = "0.4.8"
351 | source = "registry+https://github.com/rust-lang/crates.io-index"
352 | checksum = "9f80bf5aacaf25cbfc8210d1cfb718f2bf3b11c4c54e5afe36c236853a8ec390"
353 | dependencies = [
354 | "autocfg",
355 | "scopeguard",
356 | ]
357 |
358 | [[package]]
359 | name = "log"
360 | version = "0.4.17"
361 | source = "registry+https://github.com/rust-lang/crates.io-index"
362 | checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"
363 | dependencies = [
364 | "cfg-if",
365 | ]
366 |
367 | [[package]]
368 | name = "memchr"
369 | version = "2.5.0"
370 | source = "registry+https://github.com/rust-lang/crates.io-index"
371 | checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
372 |
373 | [[package]]
374 | name = "memoffset"
375 | version = "0.6.5"
376 | source = "registry+https://github.com/rust-lang/crates.io-index"
377 | checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce"
378 | dependencies = [
379 | "autocfg",
380 | ]
381 |
382 | [[package]]
383 | name = "num_cpus"
384 | version = "1.13.1"
385 | source = "registry+https://github.com/rust-lang/crates.io-index"
386 | checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1"
387 | dependencies = [
388 | "hermit-abi",
389 | "libc",
390 | ]
391 |
392 | [[package]]
393 | name = "once_cell"
394 | version = "1.14.0"
395 | source = "registry+https://github.com/rust-lang/crates.io-index"
396 | checksum = "2f7254b99e31cad77da24b08ebf628882739a608578bb1bcdfc1f9c21260d7c0"
397 |
398 | [[package]]
399 | name = "parking_lot"
400 | version = "0.12.1"
401 | source = "registry+https://github.com/rust-lang/crates.io-index"
402 | checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
403 | dependencies = [
404 | "lock_api",
405 | "parking_lot_core",
406 | ]
407 |
408 | [[package]]
409 | name = "parking_lot_core"
410 | version = "0.9.3"
411 | source = "registry+https://github.com/rust-lang/crates.io-index"
412 | checksum = "09a279cbf25cb0757810394fbc1e359949b59e348145c643a939a525692e6929"
413 | dependencies = [
414 | "cfg-if",
415 | "libc",
416 | "redox_syscall",
417 | "smallvec",
418 | "windows-sys",
419 | ]
420 |
421 | [[package]]
422 | name = "pin-project-lite"
423 | version = "0.2.9"
424 | source = "registry+https://github.com/rust-lang/crates.io-index"
425 | checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116"
426 |
427 | [[package]]
428 | name = "pin-utils"
429 | version = "0.1.0"
430 | source = "registry+https://github.com/rust-lang/crates.io-index"
431 | checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
432 |
433 | [[package]]
434 | name = "proc-macro-error"
435 | version = "1.0.4"
436 | source = "registry+https://github.com/rust-lang/crates.io-index"
437 | checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
438 | dependencies = [
439 | "proc-macro-error-attr",
440 | "proc-macro2",
441 | "quote",
442 | "syn",
443 | "version_check",
444 | ]
445 |
446 | [[package]]
447 | name = "proc-macro-error-attr"
448 | version = "1.0.4"
449 | source = "registry+https://github.com/rust-lang/crates.io-index"
450 | checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
451 | dependencies = [
452 | "proc-macro2",
453 | "quote",
454 | "version_check",
455 | ]
456 |
457 | [[package]]
458 | name = "proc-macro2"
459 | version = "1.0.43"
460 | source = "registry+https://github.com/rust-lang/crates.io-index"
461 | checksum = "0a2ca2c61bc9f3d74d2886294ab7b9853abd9c1ad903a3ac7815c58989bb7bab"
462 | dependencies = [
463 | "unicode-ident",
464 | ]
465 |
466 | [[package]]
467 | name = "quote"
468 | version = "1.0.21"
469 | source = "registry+https://github.com/rust-lang/crates.io-index"
470 | checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179"
471 | dependencies = [
472 | "proc-macro2",
473 | ]
474 |
475 | [[package]]
476 | name = "rayon"
477 | version = "1.5.3"
478 | source = "registry+https://github.com/rust-lang/crates.io-index"
479 | checksum = "bd99e5772ead8baa5215278c9b15bf92087709e9c1b2d1f97cdb5a183c933a7d"
480 | dependencies = [
481 | "autocfg",
482 | "crossbeam-deque",
483 | "either",
484 | "rayon-core",
485 | ]
486 |
487 | [[package]]
488 | name = "rayon-core"
489 | version = "1.9.3"
490 | source = "registry+https://github.com/rust-lang/crates.io-index"
491 | checksum = "258bcdb5ac6dad48491bb2992db6b7cf74878b0384908af124823d118c99683f"
492 | dependencies = [
493 | "crossbeam-channel",
494 | "crossbeam-deque",
495 | "crossbeam-utils",
496 | "num_cpus",
497 | ]
498 |
499 | [[package]]
500 | name = "redox_syscall"
501 | version = "0.2.16"
502 | source = "registry+https://github.com/rust-lang/crates.io-index"
503 | checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"
504 | dependencies = [
505 | "bitflags",
506 | ]
507 |
508 | [[package]]
509 | name = "regex"
510 | version = "1.6.0"
511 | source = "registry+https://github.com/rust-lang/crates.io-index"
512 | checksum = "4c4eb3267174b8c6c2f654116623910a0fef09c4753f8dd83db29c48a0df988b"
513 | dependencies = [
514 | "aho-corasick",
515 | "memchr",
516 | "regex-syntax",
517 | ]
518 |
519 | [[package]]
520 | name = "regex-syntax"
521 | version = "0.6.27"
522 | source = "registry+https://github.com/rust-lang/crates.io-index"
523 | checksum = "a3f87b73ce11b1619a3c6332f45341e0047173771e8b8b73f87bfeefb7b56244"
524 |
525 | [[package]]
526 | name = "remove_dir_all"
527 | version = "0.5.3"
528 | source = "registry+https://github.com/rust-lang/crates.io-index"
529 | checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7"
530 | dependencies = [
531 | "winapi",
532 | ]
533 |
534 | [[package]]
535 | name = "ryu"
536 | version = "1.0.11"
537 | source = "registry+https://github.com/rust-lang/crates.io-index"
538 | checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09"
539 |
540 | [[package]]
541 | name = "scopeguard"
542 | version = "1.1.0"
543 | source = "registry+https://github.com/rust-lang/crates.io-index"
544 | checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
545 |
546 | [[package]]
547 | name = "serde"
548 | version = "1.0.144"
549 | source = "registry+https://github.com/rust-lang/crates.io-index"
550 | checksum = "0f747710de3dcd43b88c9168773254e809d8ddbdf9653b84e2554ab219f17860"
551 | dependencies = [
552 | "serde_derive",
553 | ]
554 |
555 | [[package]]
556 | name = "serde_derive"
557 | version = "1.0.144"
558 | source = "registry+https://github.com/rust-lang/crates.io-index"
559 | checksum = "94ed3a816fb1d101812f83e789f888322c34e291f894f19590dc310963e87a00"
560 | dependencies = [
561 | "proc-macro2",
562 | "quote",
563 | "syn",
564 | ]
565 |
566 | [[package]]
567 | name = "serde_json"
568 | version = "1.0.85"
569 | source = "registry+https://github.com/rust-lang/crates.io-index"
570 | checksum = "e55a28e3aaef9d5ce0506d0a14dbba8054ddc7e499ef522dd8b26859ec9d4a44"
571 | dependencies = [
572 | "itoa",
573 | "ryu",
574 | "serde",
575 | ]
576 |
577 | [[package]]
578 | name = "serde_yaml"
579 | version = "0.9.13"
580 | source = "registry+https://github.com/rust-lang/crates.io-index"
581 | checksum = "8613d593412a0deb7bbd8de9d908efff5a0cb9ccd8f62c641e7b2ed2f57291d1"
582 | dependencies = [
583 | "indexmap",
584 | "itoa",
585 | "ryu",
586 | "serde",
587 | "unsafe-libyaml",
588 | ]
589 |
590 | [[package]]
591 | name = "serial_test"
592 | version = "0.9.0"
593 | source = "registry+https://github.com/rust-lang/crates.io-index"
594 | checksum = "92761393ee4dc3ff8f4af487bd58f4307c9329bbedea02cac0089ad9c411e153"
595 | dependencies = [
596 | "dashmap",
597 | "futures",
598 | "lazy_static",
599 | "log",
600 | "parking_lot",
601 | "serial_test_derive",
602 | ]
603 |
604 | [[package]]
605 | name = "serial_test_derive"
606 | version = "0.9.0"
607 | source = "registry+https://github.com/rust-lang/crates.io-index"
608 | checksum = "4b6f5d1c3087fb119617cff2966fe3808a80e5eb59a8c1601d5994d66f4346a5"
609 | dependencies = [
610 | "proc-macro-error",
611 | "proc-macro2",
612 | "quote",
613 | "syn",
614 | ]
615 |
616 | [[package]]
617 | name = "slab"
618 | version = "0.4.7"
619 | source = "registry+https://github.com/rust-lang/crates.io-index"
620 | checksum = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef"
621 | dependencies = [
622 | "autocfg",
623 | ]
624 |
625 | [[package]]
626 | name = "smallvec"
627 | version = "1.9.0"
628 | source = "registry+https://github.com/rust-lang/crates.io-index"
629 | checksum = "2fd0db749597d91ff862fd1d55ea87f7855a744a8425a64695b6fca237d1dad1"
630 |
631 | [[package]]
632 | name = "strsim"
633 | version = "0.8.0"
634 | source = "registry+https://github.com/rust-lang/crates.io-index"
635 | checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
636 |
637 | [[package]]
638 | name = "structopt"
639 | version = "0.3.26"
640 | source = "registry+https://github.com/rust-lang/crates.io-index"
641 | checksum = "0c6b5c64445ba8094a6ab0c3cd2ad323e07171012d9c98b0b15651daf1787a10"
642 | dependencies = [
643 | "clap",
644 | "lazy_static",
645 | "structopt-derive",
646 | ]
647 |
648 | [[package]]
649 | name = "structopt-derive"
650 | version = "0.4.18"
651 | source = "registry+https://github.com/rust-lang/crates.io-index"
652 | checksum = "dcb5ae327f9cc13b68763b5749770cb9e048a99bd9dfdfa58d0cf05d5f64afe0"
653 | dependencies = [
654 | "heck",
655 | "proc-macro-error",
656 | "proc-macro2",
657 | "quote",
658 | "syn",
659 | ]
660 |
661 | [[package]]
662 | name = "syn"
663 | version = "1.0.99"
664 | source = "registry+https://github.com/rust-lang/crates.io-index"
665 | checksum = "58dbef6ec655055e20b86b15a8cc6d439cca19b667537ac6a1369572d151ab13"
666 | dependencies = [
667 | "proc-macro2",
668 | "quote",
669 | "unicode-ident",
670 | ]
671 |
672 | [[package]]
673 | name = "tempfile"
674 | version = "3.3.0"
675 | source = "registry+https://github.com/rust-lang/crates.io-index"
676 | checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4"
677 | dependencies = [
678 | "cfg-if",
679 | "fastrand",
680 | "libc",
681 | "redox_syscall",
682 | "remove_dir_all",
683 | "winapi",
684 | ]
685 |
686 | [[package]]
687 | name = "termcolor"
688 | version = "1.1.3"
689 | source = "registry+https://github.com/rust-lang/crates.io-index"
690 | checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755"
691 | dependencies = [
692 | "winapi-util",
693 | ]
694 |
695 | [[package]]
696 | name = "textwrap"
697 | version = "0.11.0"
698 | source = "registry+https://github.com/rust-lang/crates.io-index"
699 | checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"
700 | dependencies = [
701 | "unicode-width",
702 | ]
703 |
704 | [[package]]
705 | name = "unicode-ident"
706 | version = "1.0.4"
707 | source = "registry+https://github.com/rust-lang/crates.io-index"
708 | checksum = "dcc811dc4066ac62f84f11307873c4850cb653bfa9b1719cee2bd2204a4bc5dd"
709 |
710 | [[package]]
711 | name = "unicode-segmentation"
712 | version = "1.10.0"
713 | source = "registry+https://github.com/rust-lang/crates.io-index"
714 | checksum = "0fdbf052a0783de01e944a6ce7a8cb939e295b1e7be835a1112c3b9a7f047a5a"
715 |
716 | [[package]]
717 | name = "unicode-width"
718 | version = "0.1.10"
719 | source = "registry+https://github.com/rust-lang/crates.io-index"
720 | checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b"
721 |
722 | [[package]]
723 | name = "unsafe-libyaml"
724 | version = "0.2.4"
725 | source = "registry+https://github.com/rust-lang/crates.io-index"
726 | checksum = "c1e5fa573d8ac5f1a856f8d7be41d390ee973daf97c806b2c1a465e4e1406e68"
727 |
728 | [[package]]
729 | name = "vec_map"
730 | version = "0.8.2"
731 | source = "registry+https://github.com/rust-lang/crates.io-index"
732 | checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
733 |
734 | [[package]]
735 | name = "version_check"
736 | version = "0.9.4"
737 | source = "registry+https://github.com/rust-lang/crates.io-index"
738 | checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
739 |
740 | [[package]]
741 | name = "widestring"
742 | version = "1.0.2"
743 | source = "registry+https://github.com/rust-lang/crates.io-index"
744 | checksum = "653f141f39ec16bba3c5abe400a0c60da7468261cc2cbf36805022876bc721a8"
745 |
746 | [[package]]
747 | name = "winapi"
748 | version = "0.3.9"
749 | source = "registry+https://github.com/rust-lang/crates.io-index"
750 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
751 | dependencies = [
752 | "winapi-i686-pc-windows-gnu",
753 | "winapi-x86_64-pc-windows-gnu",
754 | ]
755 |
756 | [[package]]
757 | name = "winapi-i686-pc-windows-gnu"
758 | version = "0.4.0"
759 | source = "registry+https://github.com/rust-lang/crates.io-index"
760 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
761 |
762 | [[package]]
763 | name = "winapi-util"
764 | version = "0.1.5"
765 | source = "registry+https://github.com/rust-lang/crates.io-index"
766 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
767 | dependencies = [
768 | "winapi",
769 | ]
770 |
771 | [[package]]
772 | name = "winapi-x86_64-pc-windows-gnu"
773 | version = "0.4.0"
774 | source = "registry+https://github.com/rust-lang/crates.io-index"
775 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
776 |
777 | [[package]]
778 | name = "windows-sys"
779 | version = "0.36.1"
780 | source = "registry+https://github.com/rust-lang/crates.io-index"
781 | checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2"
782 | dependencies = [
783 | "windows_aarch64_msvc",
784 | "windows_i686_gnu",
785 | "windows_i686_msvc",
786 | "windows_x86_64_gnu",
787 | "windows_x86_64_msvc",
788 | ]
789 |
790 | [[package]]
791 | name = "windows_aarch64_msvc"
792 | version = "0.36.1"
793 | source = "registry+https://github.com/rust-lang/crates.io-index"
794 | checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47"
795 |
796 | [[package]]
797 | name = "windows_i686_gnu"
798 | version = "0.36.1"
799 | source = "registry+https://github.com/rust-lang/crates.io-index"
800 | checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6"
801 |
802 | [[package]]
803 | name = "windows_i686_msvc"
804 | version = "0.36.1"
805 | source = "registry+https://github.com/rust-lang/crates.io-index"
806 | checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024"
807 |
808 | [[package]]
809 | name = "windows_x86_64_gnu"
810 | version = "0.36.1"
811 | source = "registry+https://github.com/rust-lang/crates.io-index"
812 | checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1"
813 |
814 | [[package]]
815 | name = "windows_x86_64_msvc"
816 | version = "0.36.1"
817 | source = "registry+https://github.com/rust-lang/crates.io-index"
818 | checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680"
819 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "cpplumber"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | [profile.release]
7 | incremental = true
8 | debug = 0 # Set this to 1 or 2 to get more useful backtraces in debugger.
9 | lto = true
10 | codegen-units = 1
11 |
12 | [dependencies]
13 | clang = { version = "2.0", features = ["clang_10_0"] }
14 | anyhow = "1.0"
15 | structopt = "0.3"
16 | widestring = "1.0"
17 | log = "0.4"
18 | env_logger = "0.9"
19 | glob = "0.3.0"
20 | serde = { version = "1.0", features = ["derive", "rc"] }
21 | serde_json = "1.0"
22 | serde_yaml = "0.9"
23 | tempfile = "3.3"
24 | rayon = "1.5"
25 |
26 | [dev-dependencies]
27 | serial_test = "0.9"
28 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | Cpplumber
635 | Copyright (C) 2022 Erwan Grelet
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Cpplumber Copyright (C) 2022 Erwan Grelet
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | all: test
2 |
3 | build:
4 | @cargo build --all-features
5 |
6 | doc:
7 | @cargo doc --all-features
8 |
9 | test:
10 | @cargo test
11 | @cargo test --all-features
12 | @cargo test --no-default-features
13 |
14 | format:
15 | @rustup component add rustfmt 2> /dev/null
16 | @cargo fmt --all
17 |
18 | format-check:
19 | @rustup component add rustfmt 2> /dev/null
20 | @cargo fmt --all -- --check
21 |
22 | lint:
23 | @rustup component add clippy 2> /dev/null
24 | @cargo clippy -- -D warnings
25 |
26 | .PHONY: all doc test format format-check lint
27 |
28 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # cpplumber [](https://img.shields.io/badge/license-GPL--3.0-blue.svg) [](https://img.shields.io/badge/rust-1.63.0%2B-orange.svg) [](https://github.com/ergrelet/cpplumber/actions?query=workflow%3ATests) [](https://coveralls.io/github/ergrelet/cpplumber?branch=main)
2 |
3 | Cpplumber is a static analysis tool that helps detecting and keeping track of C
4 | and C++ source code information that leaks into compiled executable files.
5 |
6 | The project is written in Rust and depends on libclang, so it's cross-platform and
7 | can be used on projects that use the latest C and C++ standards.
8 |
9 | ## Key Features
10 |
11 | * Supports JSON compilation databases
12 | * Tracks leaks of string literals, struct names and class names
13 | * Allows filtering reported leaks through a YAML configuration file
14 | * Generates raw text and JSON reports
15 |
16 | ## Quick Example
17 |
18 | Imagine you have a source file `file1.c` that you compiled into `a.out` and
19 | you want to know if some string literal ended up in `a.out`, you can simply do:
20 | ```
21 | $ cpplumber --bin a.out file1.c
22 | [2022-09-24T19:57:14Z INFO cpplumber] Gathering source files...
23 | [2022-09-24T19:57:14Z INFO cpplumber] Filtering suppressed files...
24 | [2022-09-24T19:57:14Z INFO cpplumber] Extracting artifacts from source files...
25 | [2022-09-24T19:57:15Z INFO cpplumber] Filtering suppressed artifacts...
26 | [2022-09-24T19:57:15Z INFO cpplumber] Looking for leaks in 'a.out'...
27 | "My_Super_Secret_API_Key" (string literal) leaked at offset 0x14f20 in "/full/path/to/a.out" [declared at /full/path/to/file1.c:5]
28 | Error: Leaks detected!
29 | ```
30 |
31 | ## Documentation
32 |
33 | The full user documentation is available [here](https://ergrelet.github.io/cpplumber/)
34 | (and also [here](https://github.com/ergrelet/cpplumber/blob/gh-pages/index.md)
35 | as Markdown).
36 |
37 | ## How to Build
38 |
39 | Rust version 1.63.0 or greater is needed to build the project.
40 |
41 | ```
42 | git clone https://github.com/ergrelet/cpplumber.git
43 | cd cpplumber
44 | cargo build --release
45 | ```
46 |
47 | ## How to Install
48 |
49 | If you have Rust installed, you can easily install Cpplumber with `cargo`:
50 | ```
51 | cargo install --git https://github.com/ergrelet/cpplumber --tag 0.1.0
52 | ```
53 |
54 | After that, you can invoke `cpplumber` from anywhere through the command-line.
55 |
56 | Keep in mind that you need to have the required dependencies installed for
57 | `cpplumber` to run properly. Check out the user documentation for more details.
58 |
59 |
--------------------------------------------------------------------------------
/src/cli.rs:
--------------------------------------------------------------------------------
1 | use std::path::PathBuf;
2 |
3 | use structopt::StructOpt;
4 |
5 | const PKG_NAME: &str = env!("CARGO_PKG_NAME");
6 |
7 | #[derive(Debug, StructOpt)]
8 | #[structopt(name = PKG_NAME, about = "An information leak detector for C and C++ code bases")]
9 | pub struct CpplumberOptions {
10 | /// Path to the output binary to scan for leaked information.
11 | #[structopt(parse(from_os_str), short, long = "bin")]
12 | pub binary_file_path: PathBuf,
13 |
14 | /// Additional include directories.
15 | /// Only used when project files aren't used.
16 | #[structopt(short = "I")]
17 | pub include_directories: Vec,
18 |
19 | /// Additional preprocessor definitions.
20 | /// Only used when project files aren't used.
21 | #[structopt(short = "D")]
22 | pub compile_definitions: Vec,
23 |
24 | /// Compilation database.
25 | #[structopt(parse(from_os_str), short, long = "project")]
26 | pub project_file_path: Option,
27 |
28 | /// Path to a file containing rules to prevent certain errors from being
29 | /// generated.
30 | #[structopt(parse(from_os_str), short, long)]
31 | pub suppressions_list: Option,
32 |
33 | /// Report leaked values only once, even when found in multiple locations.
34 | #[structopt(long)]
35 | pub ignore_multiple_locations: bool,
36 |
37 | /// Report leaks for data declared in system headers
38 | #[structopt(long)]
39 | pub report_system_headers: bool,
40 |
41 | /// Minimum required size in bytes, for a leak to be reported. Defaults to 4.
42 | /// Warning: Setting this to a lower value might greatly increase resource
43 | /// consumption and reports' sizes.
44 | #[structopt(short, long)]
45 | pub minimum_leak_size: Option,
46 |
47 | /// Ignore leaks of string literals.
48 | #[structopt(long)]
49 | pub ignore_string_literals: bool,
50 |
51 | /// Ignore leaks of struct and class names.
52 | #[structopt(long)]
53 | pub ignore_struct_names: bool,
54 |
55 | /// Generate output as JSON.
56 | #[structopt(short, long = "json")]
57 | pub json_output: bool,
58 |
59 | /// List of source files to scan for (can be glob expressions).
60 | pub source_path_globs: Vec,
61 | }
62 |
--------------------------------------------------------------------------------
/src/compilation_database/compile_commands.rs:
--------------------------------------------------------------------------------
1 | use std::path::Path;
2 | use std::{fs, sync::Arc};
3 |
4 | use anyhow::{anyhow, Result};
5 | use tempfile::TempDir;
6 |
7 | use super::{CompilationDatabase, CompileCommand, CompileCommands};
8 |
9 | pub struct CompileCommandsDatabase {
10 | clang_db: clang::CompilationDatabase,
11 | }
12 |
13 | impl CompileCommandsDatabase {
14 | pub fn new>(db_file_path: P) -> Result {
15 | let fake_build_directory = move_database_file_into_tmp_dir(db_file_path)?;
16 | let clang_db = clang::CompilationDatabase::from_directory(fake_build_directory.path())
17 | .map_err(|_| anyhow!("Failed to parse compilation database"))?;
18 |
19 | Ok(Self { clang_db })
20 | }
21 | }
22 |
23 | impl CompilationDatabase for CompileCommandsDatabase {
24 | fn is_file_path_in_arguments(&self) -> bool {
25 | true
26 | }
27 |
28 | fn get_all_compile_commands(&self) -> Result {
29 | let clang_cmds = self.clang_db.get_all_compile_commands();
30 |
31 | convert_clang_compile_commands(clang_cmds)
32 | }
33 | }
34 |
35 | /// Converts `clang`'s CompileCommands to our own `CompileCommands` type
36 | fn convert_clang_compile_commands(clang_cmds: clang::CompileCommands) -> Result {
37 | clang_cmds
38 | .get_commands()
39 | .iter()
40 | .map(|cmd| {
41 | Ok(CompileCommand {
42 | // Some file paths may not be canonical, so we have to force them to be
43 | filename: cmd.get_filename().canonicalize()?,
44 | arguments: Arc::new(cmd.get_arguments()),
45 | })
46 | })
47 | .collect()
48 | }
49 |
50 | /// Move the database file with the name clang expects, into a temporary directory
51 | fn move_database_file_into_tmp_dir>(db_file_path: P) -> Result {
52 | let tmp_directory = tempfile::tempdir()?;
53 | let dest_path = tmp_directory.path().join("compile_commands.json");
54 | _ = fs::copy(db_file_path, dest_path)?;
55 |
56 | Ok(tmp_directory)
57 | }
58 |
59 | #[cfg(test)]
60 | mod tests {
61 | use std::path::PathBuf;
62 |
63 | use super::*;
64 |
65 | const COMPILE_COMMANDS_PATH: &str = "tests/data/compile_commands";
66 | const INVALID_DATABASE_PATH: &str = "tests/data/compile_commands/invalid.json";
67 | const EMPTY_DATABASE_PATH: &str = "tests/data/compile_commands/empty.json";
68 | const DATABASE1_PATH: &str = "tests/data/compile_commands/db1.json";
69 |
70 | #[test]
71 | fn is_file_path_in_arguments() {
72 | let db_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(DATABASE1_PATH);
73 | let database = CompileCommandsDatabase::new(db_path).expect("Failed to parse database");
74 |
75 | // Present in arguments
76 | assert!(database.is_file_path_in_arguments());
77 | }
78 |
79 | #[test]
80 | fn get_all_compile_commands_invalid() {
81 | let empty_db_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(INVALID_DATABASE_PATH);
82 | assert!(CompileCommandsDatabase::new(empty_db_path).is_err());
83 | }
84 |
85 | #[test]
86 | #[should_panic]
87 | fn get_all_compile_commands_empty() {
88 | let empty_db_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(EMPTY_DATABASE_PATH);
89 | // Unfortunately, the `clang` crate panics in `from_directory`
90 | // for empty databases.
91 | assert!(CompileCommandsDatabase::new(empty_db_path).is_err());
92 | }
93 |
94 | #[test]
95 | fn get_all_compile_commands() {
96 | let root_dir_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(COMPILE_COMMANDS_PATH);
97 | let db_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(DATABASE1_PATH);
98 | let database = CompileCommandsDatabase::new(db_path).expect("Failed to parse database");
99 |
100 | let compile_commands = database
101 | .get_all_compile_commands()
102 | .expect("get_all_compile_commands failed");
103 | // Result is not empty
104 | assert_eq!(compile_commands.len(), 2);
105 |
106 | // File #1
107 | // Check `filename` value
108 | assert_eq!(
109 | compile_commands[0].filename,
110 | root_dir_path.join("file1.cc").canonicalize().unwrap()
111 | );
112 | // Check `arguments` value
113 | assert_eq!(
114 | *compile_commands[0].arguments,
115 | vec![
116 | "/usr/bin/clang++".to_string(),
117 | "--driver-mode=g++".to_string(),
118 | "-Irelative".to_string(),
119 | "-DSOMEDEF=With spaces, quotes.".to_string(),
120 | "-c".to_string(),
121 | "-o".to_string(),
122 | "file1.o".to_string(),
123 | "tests/data/compile_commands/file1.cc".to_string(),
124 | ]
125 | );
126 |
127 | // File #2
128 | // Check `filename` value
129 | assert_eq!(
130 | compile_commands[1].filename,
131 | root_dir_path.join("file2.cc").canonicalize().unwrap()
132 | );
133 | // Check `arguments` value
134 | assert_eq!(
135 | *compile_commands[1].arguments,
136 | vec![
137 | "/usr/bin/clang++".to_string(),
138 | "--driver-mode=g++".to_string(),
139 | "-Irelative".to_string(),
140 | "-DSOMEDEF=With spaces, quotes.".to_string(),
141 | "-c".to_string(),
142 | "-o".to_string(),
143 | "file2.o".to_string(),
144 | "tests/data/compile_commands/file2.cc".to_string(),
145 | ]
146 | );
147 | }
148 | }
149 |
--------------------------------------------------------------------------------
/src/compilation_database/file_list.rs:
--------------------------------------------------------------------------------
1 | use std::path::PathBuf;
2 | use std::{collections::BTreeSet, sync::Arc};
3 |
4 | use anyhow::Result;
5 | use rayon::prelude::*;
6 |
7 | use super::{CompilationDatabase, CompileCommand, CompileCommands};
8 |
9 | pub struct FileListDatabase {
10 | /// Set of file paths
11 | file_paths: BTreeSet,
12 | /// Shared arguments for all files
13 | arguments: Arc>,
14 | }
15 |
16 | impl FileListDatabase {
17 | pub fn new(file_paths: &[PathBuf], arguments: Vec) -> Self {
18 | Self {
19 | file_paths: BTreeSet::from_iter(file_paths.iter().cloned()),
20 | arguments: Arc::new(arguments),
21 | }
22 | }
23 | }
24 |
25 | impl CompilationDatabase for FileListDatabase {
26 | fn is_file_path_in_arguments(&self) -> bool {
27 | false
28 | }
29 |
30 | fn get_all_compile_commands(&self) -> Result {
31 | self.file_paths
32 | .par_iter()
33 | .map(|file_path| {
34 | Ok(CompileCommand {
35 | filename: file_path.canonicalize()?,
36 | arguments: self.arguments.clone(),
37 | })
38 | })
39 | .collect()
40 | }
41 | }
42 |
43 | #[cfg(test)]
44 | mod tests {
45 | use super::*;
46 |
47 | const FILE_LIST_PROJ_PATH: &str = "tests/data/main/file_list_proj";
48 |
49 | #[test]
50 | fn is_file_path_in_arguments() {
51 | let database = FileListDatabase::new(&[], vec![]);
52 |
53 | // Not present in arguments
54 | assert!(!database.is_file_path_in_arguments());
55 | }
56 |
57 | #[test]
58 | fn get_all_compile_commands_empty() {
59 | let database = FileListDatabase::new(&[], vec![]);
60 | // Result is empty
61 | assert!(database
62 | .get_all_compile_commands()
63 | .expect("get_all_compile_commands failed")
64 | .is_empty());
65 | }
66 |
67 | #[test]
68 | fn get_all_compile_commands() {
69 | let root_dir_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(FILE_LIST_PROJ_PATH);
70 | let arguments = vec!["arg1".to_string(), "arg2".to_string()];
71 | let database = FileListDatabase::new(
72 | &[
73 | root_dir_path.join("main.cc"),
74 | root_dir_path.join("header.h"),
75 | ],
76 | arguments.clone(),
77 | );
78 |
79 | let compile_commands = database
80 | .get_all_compile_commands()
81 | .expect("get_all_compile_commands failed");
82 | // Result is not empty
83 | assert_eq!(compile_commands.len(), 2);
84 |
85 | // File #1
86 | // Check `filename` value
87 | assert_eq!(
88 | compile_commands[0].filename,
89 | root_dir_path.join("header.h").canonicalize().unwrap()
90 | );
91 | // Check `arguments` value
92 | assert_eq!(*compile_commands[0].arguments, arguments);
93 |
94 | // File #2
95 | // Check `filename` value
96 | assert_eq!(
97 | compile_commands[1].filename,
98 | root_dir_path.join("main.cc").canonicalize().unwrap()
99 | );
100 | // Check `arguments` value
101 | assert_eq!(*compile_commands[1].arguments, arguments);
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/src/compilation_database/mod.rs:
--------------------------------------------------------------------------------
1 | mod compile_commands;
2 | mod file_list;
3 |
4 | use glob::glob;
5 | use std::{
6 | path::{Path, PathBuf},
7 | sync::Arc,
8 | };
9 |
10 | use anyhow::Result;
11 | use rayon::prelude::*;
12 |
13 | pub use compile_commands::CompileCommandsDatabase;
14 | pub use file_list::FileListDatabase;
15 |
16 | pub enum ProjectConfiguration<'p> {
17 | CompilationDatabase {
18 | project_file_path: &'p Path,
19 | },
20 | Manual {
21 | source_path_globs: &'p [String],
22 | include_directories: &'p [String],
23 | compile_definitions: &'p [String],
24 | },
25 | }
26 |
27 | #[derive(Debug)]
28 | pub struct CompileCommand {
29 | pub filename: PathBuf,
30 | pub arguments: Arc>,
31 | }
32 |
33 | pub type CompileCommands = Vec;
34 |
35 | pub trait CompilationDatabase {
36 | /// Indicates if the file path can be found in the argument list.
37 | fn is_file_path_in_arguments(&self) -> bool;
38 | /// Returns all the compile commands stored in the database
39 | fn get_all_compile_commands(&self) -> Result;
40 | }
41 |
42 | pub fn generate_compilation_database(
43 | project_config: ProjectConfiguration,
44 | ) -> Result> {
45 | match project_config {
46 | ProjectConfiguration::CompilationDatabase { project_file_path } => {
47 | // Parse compile commands from the JSON database
48 | Ok(Box::new(CompileCommandsDatabase::new(project_file_path)?))
49 | }
50 |
51 | ProjectConfiguration::Manual {
52 | source_path_globs,
53 | include_directories,
54 | compile_definitions,
55 | } => {
56 | // Otherwise, process glob expressions
57 | let file_paths = source_path_globs
58 | .par_iter()
59 | .try_fold(
60 | Vec::new,
61 | |mut accum, glob_expression| -> Result> {
62 | if let Ok(paths) = glob(glob_expression) {
63 | for path in paths {
64 | accum.push(path?);
65 | }
66 | } else {
67 | log::warn!(
68 | "'{}' is not a valid path or glob expression, ignoring it",
69 | glob_expression
70 | );
71 | }
72 |
73 | Ok(accum)
74 | },
75 | )
76 | .try_reduce(Vec::new, |mut accum, mut other| {
77 | accum.append(&mut other);
78 | Ok(accum)
79 | })?;
80 |
81 | // Generate `arguments` from the CLI arguments
82 | let mut arguments = vec![];
83 |
84 | // Add include directories to the list of arguments
85 | for include_dir in include_directories.iter() {
86 | arguments.push(format!("-I{}", include_dir));
87 | }
88 | // Add preprocessor defitions to the list of arguments
89 | for compile_def in compile_definitions.iter() {
90 | arguments.push(format!("-D{}", compile_def));
91 | }
92 |
93 | log::debug!("Using arguments: {:?}", arguments);
94 | Ok(Box::new(FileListDatabase::new(&file_paths, arguments)))
95 | }
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/src/information_leak/confirmed_leak.rs:
--------------------------------------------------------------------------------
1 | use std::{ops::Deref, sync::Arc};
2 |
3 | use serde::Serialize;
4 |
5 | use super::{LeakLocation, LeakedDataType};
6 |
7 | /// Struct containing information on a piece of data that has leaked into a
8 | /// binary file.
9 | #[derive(Serialize)]
10 | pub struct ConfirmedLeak {
11 | /// Type of data leaked
12 | pub data_type: LeakedDataType,
13 | /// Leaked data, as represented in the source code
14 | pub data: Arc,
15 | /// Information on where the leaked data is declared in the source code as
16 | /// well as found in in the target binary
17 | pub location: LeakLocation,
18 | }
19 |
20 | impl From for ConfirmedLeak {
21 | fn from(leak: ConfirmedLeakWithUniqueLocation) -> Self {
22 | leak.0
23 | }
24 | }
25 |
26 | impl From for ConfirmedLeak {
27 | fn from(leak: ConfirmedLeakWithUniqueValue) -> Self {
28 | leak.0
29 | }
30 | }
31 |
32 | /// Wrapper struct used to deduplicate `ConfirmedLeak`s in `BTreeSet`s based on
33 | /// the value of the `location` field.
34 | #[derive(Serialize)]
35 | pub struct ConfirmedLeakWithUniqueLocation(ConfirmedLeak);
36 |
37 | impl From for ConfirmedLeakWithUniqueLocation {
38 | fn from(leak: ConfirmedLeak) -> Self {
39 | ConfirmedLeakWithUniqueLocation(leak)
40 | }
41 | }
42 |
43 | impl Deref for ConfirmedLeakWithUniqueLocation {
44 | type Target = ConfirmedLeak;
45 | fn deref(&self) -> &ConfirmedLeak {
46 | &self.0
47 | }
48 | }
49 |
50 | impl PartialEq for ConfirmedLeakWithUniqueLocation {
51 | fn eq(&self, other: &Self) -> bool {
52 | self.0.location == other.0.location
53 | }
54 | }
55 |
56 | impl Eq for ConfirmedLeakWithUniqueLocation {}
57 |
58 | impl PartialOrd for ConfirmedLeakWithUniqueLocation {
59 | fn partial_cmp(&self, other: &Self) -> Option {
60 | self.0.location.partial_cmp(&other.0.location)
61 | }
62 | }
63 |
64 | impl Ord for ConfirmedLeakWithUniqueLocation {
65 | fn cmp(&self, other: &Self) -> std::cmp::Ordering {
66 | self.0.location.cmp(&other.0.location)
67 | }
68 | }
69 |
70 | /// Wrapper struct used to deduplicate `ConfirmedLeak`s in `BTreeSet`s based on
71 | /// the value of the `leak_information` field.
72 | #[derive(Serialize)]
73 | pub struct ConfirmedLeakWithUniqueValue(ConfirmedLeak);
74 |
75 | impl From for ConfirmedLeakWithUniqueValue {
76 | fn from(leak: ConfirmedLeak) -> Self {
77 | ConfirmedLeakWithUniqueValue(leak)
78 | }
79 | }
80 |
81 | impl Deref for ConfirmedLeakWithUniqueValue {
82 | type Target = ConfirmedLeak;
83 | fn deref(&self) -> &ConfirmedLeak {
84 | &self.0
85 | }
86 | }
87 |
88 | impl PartialEq for ConfirmedLeakWithUniqueValue {
89 | fn eq(&self, other: &Self) -> bool {
90 | self.0.data == other.0.data
91 | }
92 | }
93 |
94 | impl Eq for ConfirmedLeakWithUniqueValue {}
95 |
96 | impl PartialOrd for ConfirmedLeakWithUniqueValue {
97 | fn partial_cmp(&self, other: &Self) -> Option {
98 | self.0.data.partial_cmp(&other.0.data)
99 | }
100 | }
101 |
102 | impl Ord for ConfirmedLeakWithUniqueValue {
103 | fn cmp(&self, other: &Self) -> std::cmp::Ordering {
104 | self.0.data.cmp(&other.0.data)
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/src/information_leak/leak_location.rs:
--------------------------------------------------------------------------------
1 | use std::{hash::Hash, path::PathBuf, sync::Arc};
2 |
3 | use serde::Serialize;
4 |
5 | /// Struct containing the source and binary locations of leaked data
6 | #[derive(Serialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
7 | pub struct LeakLocation {
8 | pub source: Arc,
9 | pub binary: BinaryLocation,
10 | }
11 |
12 | #[derive(Debug, Serialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
13 | pub struct SourceLocation {
14 | pub file: PathBuf,
15 | pub line: u64,
16 | }
17 |
18 | #[derive(Serialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
19 | pub struct BinaryLocation {
20 | pub file: Arc,
21 | pub offset: u64,
22 | }
23 |
--------------------------------------------------------------------------------
/src/information_leak/mod.rs:
--------------------------------------------------------------------------------
1 | mod confirmed_leak;
2 | mod leak_location;
3 | mod potential_leak;
4 |
5 | pub use confirmed_leak::*;
6 | pub use leak_location::*;
7 | pub use potential_leak::*;
8 |
9 | use serde::Serialize;
10 |
11 | /// Describes the kind of data that's leaked
12 | #[derive(Debug, Serialize, Clone, Copy)]
13 | pub enum LeakedDataType {
14 | /// Data comes from a string literal
15 | StringLiteral,
16 | /// Data represents the name of a C/C++ struct
17 | StructName,
18 | /// Data represents the name of a C++ class
19 | ClassName,
20 | }
21 |
--------------------------------------------------------------------------------
/src/information_leak/potential_leak.rs:
--------------------------------------------------------------------------------
1 | use std::{borrow::Cow, hash::Hash, sync::Arc};
2 |
3 | use anyhow::{anyhow, Result};
4 | use clang::{Entity, EntityKind};
5 | use widestring::{encode_utf16, encode_utf32};
6 |
7 | use super::{LeakedDataType, SourceLocation};
8 |
9 | /// Struct containing information on a piece of data from the source code, which
10 | /// may leak into a binary file.
11 | #[derive(Debug)]
12 | pub struct PotentialLeak {
13 | /// Type of data leaked
14 | pub data_type: LeakedDataType,
15 | /// Leaked data, as represented in the source code
16 | pub data: Arc,
17 | /// Byte pattern to match (i.e., leaked information, as represented in the
18 | /// binary file)
19 | pub bytes: Vec,
20 | /// Information on where the leaked data is declared in the source code
21 | pub declaration_metadata: Arc,
22 | }
23 |
24 | impl TryFrom> for PotentialLeak {
25 | type Error = anyhow::Error;
26 |
27 | fn try_from(entity: Entity) -> Result {
28 | let location = entity
29 | .get_location()
30 | .ok_or_else(|| anyhow!("Failed to get entity's location"))?
31 | .get_file_location();
32 | let file_location = location
33 | .file
34 | .ok_or_else(|| anyhow!("Failed to get entity's file location"))?
35 | .get_path();
36 |
37 | match entity.get_kind() {
38 | EntityKind::StringLiteral => {
39 | let leaked_information = entity
40 | .get_display_name()
41 | .ok_or_else(|| anyhow!("Failed to get entity's display name"))?;
42 | let (_, string_content) = parse_string_literal(&leaked_information)?;
43 |
44 | Ok(Self {
45 | data_type: LeakedDataType::StringLiteral,
46 | data: Arc::new(string_content.to_owned()),
47 | bytes: string_literal_to_bytes(&leaked_information, None)?,
48 | declaration_metadata: Arc::new(SourceLocation {
49 | file: file_location.canonicalize()?,
50 | line: location.line as u64,
51 | }),
52 | })
53 | }
54 | entity_kind @ (EntityKind::StructDecl | EntityKind::ClassDecl) => {
55 | // Convert `EntityKind` to `LeakedDataType`
56 | let data_type = match entity_kind {
57 | EntityKind::StructDecl => LeakedDataType::StructName,
58 | EntityKind::ClassDecl => LeakedDataType::ClassName,
59 | _ => unreachable!("This entity kind should not be matched"),
60 | };
61 | let leaked_information = entity.get_display_name().unwrap_or_default();
62 |
63 | Ok(Self {
64 | data_type,
65 | bytes: leaked_information.as_bytes().to_vec(),
66 | data: Arc::new(leaked_information),
67 | declaration_metadata: Arc::new(SourceLocation {
68 | file: file_location.canonicalize()?,
69 | line: location.line as u64,
70 | }),
71 | })
72 | }
73 | _ => Err(anyhow!("Unsupported entity kind")),
74 | }
75 | }
76 | }
77 |
78 | impl PartialEq for PotentialLeak {
79 | fn eq(&self, other: &Self) -> bool {
80 | self.data == other.data
81 | }
82 | }
83 |
84 | impl Eq for PotentialLeak {}
85 |
86 | impl Hash for PotentialLeak {
87 | fn hash(&self, state: &mut H) {
88 | self.data.hash(state);
89 | }
90 | }
91 |
92 | /// Kind of wide chars to use when encoding wide strings
93 | pub enum WideCharMode {
94 | /// Wide strings are encoded as UTF-16LE
95 | Windows,
96 | /// Wide strings are encoded as UTF-32LE
97 | Unix,
98 | }
99 |
100 | /// Describes the string encoding specified for a string literal
101 | enum StringLiteralEncoding {
102 | /// No encoding specified (i.e., typical "*" string)
103 | Unspecified,
104 | /// Wide string encoding specified (i.e., L"*" string)
105 | Wide,
106 | /// UTF-8 encoding (i.e., u8"*" string)
107 | Utf8,
108 | /// UTF-16LE encoding (i.e., u"*" string)
109 | Utf16,
110 | /// UTF-32LE encoding (i.e., U"*" string)
111 | Utf32,
112 | }
113 |
114 | /// We have to reimplement this ourselves since the `clang` crate doesn't
115 | /// provide an easy way to get byte representations of `StringLiteral` entities.
116 | fn string_literal_to_bytes(
117 | string_literal: &str,
118 | wide_char_mode: Option,
119 | ) -> Result> {
120 | let wide_char_mode = wide_char_mode.unwrap_or({
121 | // Pick the sensible default if not specified
122 | if cfg!(windows) {
123 | WideCharMode::Windows
124 | } else {
125 | WideCharMode::Unix
126 | }
127 | });
128 |
129 | let (string_encoding, string_content) = parse_string_literal(string_literal)?;
130 | match string_encoding {
131 | // Unspecified (ASCII assumed)
132 | StringLiteralEncoding::Unspecified => Ok(process_escape_sequences(string_content)
133 | .ok_or_else(|| anyhow!("Failed to process escape sequences"))?
134 | .as_bytes()
135 | .to_owned()),
136 |
137 | // Wide
138 | StringLiteralEncoding::Wide => {
139 | match wide_char_mode {
140 | WideCharMode::Windows => {
141 | // Encode as UTF-16LE on Windows
142 | Ok(encode_utf16(
143 | process_escape_sequences(string_content)
144 | .ok_or_else(|| anyhow!("Failed to process escape sequences"))?
145 | .chars(),
146 | )
147 | .map(u16::to_le_bytes)
148 | .fold(Vec::new(), |mut acc: Vec, e| {
149 | acc.extend(e);
150 | acc
151 | }))
152 | }
153 | WideCharMode::Unix => {
154 | // Encode as UTF-32LE on Unix platforms
155 | Ok(encode_utf32(
156 | process_escape_sequences(string_content)
157 | .ok_or_else(|| anyhow!("Failed to process escape sequences"))?
158 | .chars(),
159 | )
160 | .map(u32::to_le_bytes)
161 | .fold(Vec::new(), |mut acc: Vec, e| {
162 | acc.extend(e);
163 | acc
164 | }))
165 | }
166 | }
167 | }
168 |
169 | // UTF-8
170 | StringLiteralEncoding::Utf8 => Ok(process_escape_sequences(string_content)
171 | .ok_or_else(|| anyhow!("Failed to process escape sequences"))?
172 | .as_bytes()
173 | .to_owned()),
174 |
175 | // UTF-16LE
176 | StringLiteralEncoding::Utf16 => Ok(encode_utf16(
177 | process_escape_sequences(string_content)
178 | .ok_or_else(|| anyhow!("Failed to process escape sequences"))?
179 | .chars(),
180 | )
181 | .map(u16::to_le_bytes)
182 | .fold(Vec::new(), |mut acc: Vec, e| {
183 | acc.extend(e);
184 | acc
185 | })),
186 |
187 | // UTF-32LE
188 | StringLiteralEncoding::Utf32 => Ok(encode_utf32(
189 | process_escape_sequences(string_content)
190 | .ok_or_else(|| anyhow!("Failed to process escape sequences"))?
191 | .chars(),
192 | )
193 | .map(u32::to_le_bytes)
194 | .fold(Vec::new(), |mut acc: Vec, e| {
195 | acc.extend(e);
196 | acc
197 | })),
198 | }
199 | }
200 |
201 | /// Takes in a string literal (e.g., "str", L"str") and returns the specified
202 | /// encoding (extracted from the prefix) and the actual content of the string.
203 | fn parse_string_literal(string_literal: &str) -> Result<(StringLiteralEncoding, &str)> {
204 | let mut char_it = string_literal.chars();
205 | let first_char = char_it.next();
206 | match first_char {
207 | None => Err(anyhow!("Empty string literal")),
208 | Some(first_char) => match first_char {
209 | // Ordinary string (we assume it'll be encoded to ASCII)
210 | '"' => Ok((
211 | StringLiteralEncoding::Unspecified,
212 | &string_literal[1..string_literal.len() - 1],
213 | )),
214 |
215 | // Wide string
216 | 'L' => Ok((
217 | StringLiteralEncoding::Wide,
218 | &string_literal[2..string_literal.len() - 1],
219 | )),
220 |
221 | // UTF-32LE string
222 | 'U' => Ok((
223 | StringLiteralEncoding::Utf32,
224 | &string_literal[2..string_literal.len() - 1],
225 | )),
226 |
227 | // UTF-8 or UTF-16LE string
228 | 'u' => {
229 | let second_char = char_it
230 | .next()
231 | .ok_or_else(|| anyhow!("Invalid string literal"))?;
232 | let third_char = char_it
233 | .next()
234 | .ok_or_else(|| anyhow!("Invalid string literal"))?;
235 | if second_char == '8' && third_char == '"' {
236 | // UTF-8
237 | Ok((
238 | StringLiteralEncoding::Utf8,
239 | &string_literal[3..string_literal.len() - 1],
240 | ))
241 | } else {
242 | // UTF-16LE
243 | Ok((
244 | StringLiteralEncoding::Utf16,
245 | &string_literal[2..string_literal.len() - 1],
246 | ))
247 | }
248 | }
249 |
250 | _ => Err(anyhow!(
251 | "Invalid string literal or a new string literal prefix introduced in the standard."
252 | )),
253 | },
254 | }
255 | }
256 |
257 | fn process_escape_sequences(string: &str) -> Option> {
258 | let mut owned: Option = None;
259 | let mut skip_until: usize = 0;
260 | for (position, char) in string.chars().enumerate() {
261 | if position < skip_until {
262 | continue;
263 | }
264 |
265 | if char == '\\' {
266 | if owned.is_none() {
267 | owned = Some(string[..position].to_owned());
268 | }
269 | let b = owned.as_mut()?;
270 | let mut escape_char_it = string.chars();
271 | let first_char = escape_char_it.nth(position + 1);
272 | if let Some(first_char) = first_char {
273 | skip_until = position + 2;
274 | match first_char {
275 | // Simple escape sequences
276 | 'a' => b.push('\x07'),
277 | 'b' => b.push('\x08'),
278 | 't' => b.push('\t'),
279 | 'n' => b.push('\n'),
280 | 'v' => b.push('\x0b'),
281 | 'f' => b.push('\x0c'),
282 | 'r' => b.push('\r'),
283 | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' => {
284 | let start_position = position + 1;
285 | let mut end_position = start_position + 1;
286 | // Check following char
287 | if let Some(second_char) = escape_char_it.next() {
288 | if second_char.is_digit(8) {
289 | end_position += 1;
290 | // Check the next char
291 | if let Some(third_char) = escape_char_it.next() {
292 | if third_char.is_digit(8) {
293 | end_position += 1;
294 | }
295 | }
296 | }
297 | }
298 |
299 | // Octal escape sequence (\nnn)
300 | let octal_value =
301 | u8::from_str_radix(&string[start_position..end_position], 8).ok()?;
302 | b.push(octal_value as char);
303 | skip_until = end_position;
304 | }
305 | a => b.push(a),
306 | }
307 | } else {
308 | return None;
309 | }
310 | } else if let Some(o) = owned.as_mut() {
311 | o.push(char);
312 | }
313 | }
314 |
315 | if let Some(owned) = owned {
316 | Some(Cow::Owned(owned))
317 | } else {
318 | Some(Cow::Borrowed(string))
319 | }
320 | }
321 |
322 | #[cfg(test)]
323 | mod tests {
324 | use super::*;
325 |
326 | #[test]
327 | fn string_literal_to_bytes_empty_string() {
328 | // We consider empty string literals an error, as they should at least
329 | // contain two double-quotes.
330 | assert!(string_literal_to_bytes("", None).is_err());
331 | }
332 |
333 | #[test]
334 | fn string_literal_to_bytes_not_a_literal() {
335 | assert!(string_literal_to_bytes("not a literal", None).is_err());
336 | }
337 |
338 | #[test]
339 | fn string_literal_to_bytes_ascii_string_literal() {
340 | assert_eq!(
341 | string_literal_to_bytes("\"hello\"", None).expect("string_literal_to_bytes failed"),
342 | b"hello"
343 | );
344 | }
345 |
346 | #[test]
347 | fn string_literal_to_bytes_wide_string_literal_default() {
348 | // On Windows, wide chars are encoded as UTF-16LE
349 | #[cfg(windows)]
350 | assert_eq!(
351 | string_literal_to_bytes("L\"hello\"", None).expect("string_literal_to_bytes failed"),
352 | b"h\0e\0l\0l\0o\0"
353 | );
354 |
355 | // On Unix-like platforms, wide chars are encoded as UTF-32LE
356 | #[cfg(unix)]
357 | assert_eq!(
358 | string_literal_to_bytes("L\"hello\"", None).expect("string_literal_to_bytes failed"),
359 | b"h\0\0\0e\0\0\0l\0\0\0l\0\0\0o\0\0\0"
360 | );
361 | }
362 |
363 | #[test]
364 | fn string_literal_to_bytes_wide_string_literal_override() {
365 | // On Windows, wide chars are encoded as UTF-16LE
366 | assert_eq!(
367 | string_literal_to_bytes("L\"hello\"", Some(WideCharMode::Windows))
368 | .expect("string_literal_to_bytes failed"),
369 | b"h\0e\0l\0l\0o\0"
370 | );
371 |
372 | // On Unix-like platforms, wide chars are encoded as UTF-32LE
373 | assert_eq!(
374 | string_literal_to_bytes("L\"hello\"", Some(WideCharMode::Unix))
375 | .expect("string_literal_to_bytes failed"),
376 | b"h\0\0\0e\0\0\0l\0\0\0l\0\0\0o\0\0\0"
377 | );
378 | }
379 |
380 | #[test]
381 | fn string_literal_to_bytes_utf8_string_literal() {
382 | assert_eq!(
383 | string_literal_to_bytes("u8\"hello\"", None).expect("string_literal_to_bytes failed"),
384 | b"hello"
385 | );
386 | }
387 |
388 | #[test]
389 | fn string_literal_to_bytes_utf16_string_literal() {
390 | assert_eq!(
391 | string_literal_to_bytes("u\"hello\"", None).expect("string_literal_to_bytes failed"),
392 | b"h\0e\0l\0l\0o\0"
393 | );
394 | }
395 |
396 | #[test]
397 | fn string_literal_to_bytes_utf32_string_literal() {
398 | assert_eq!(
399 | string_literal_to_bytes("U\"hello\"", None).expect("string_literal_to_bytes failed"),
400 | b"h\0\0\0e\0\0\0l\0\0\0l\0\0\0o\0\0\0"
401 | );
402 | }
403 |
404 | #[test]
405 | fn process_escape_sequences_no_escape_sequence() {
406 | assert_eq!(
407 | process_escape_sequences("hello world!").expect("Failed to escape string"),
408 | "hello world!"
409 | );
410 | }
411 |
412 | #[test]
413 | fn process_escape_sequences_invalid_escape_sequence() {
414 | assert!(process_escape_sequences(r"invalid\").is_none());
415 | }
416 |
417 | #[test]
418 | fn process_escape_sequences_char_escape_sequences() {
419 | assert_eq!(
420 | process_escape_sequences(r"\a\b\t\n\v\f\r\ \\").expect("Failed to escape string"),
421 | "\x07\x08\t\n\x0B\x0C\r \\"
422 | );
423 | }
424 |
425 | #[test]
426 | fn process_escape_sequences_octal_escape_sequences() {
427 | assert_eq!(
428 | process_escape_sequences(r"\0\1\2\3\4\5\6\7\10\100").expect("Failed to escape string"),
429 | "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x40"
430 | );
431 | }
432 | }
433 |
--------------------------------------------------------------------------------
/src/main.rs:
--------------------------------------------------------------------------------
1 | mod cli;
2 | mod compilation_database;
3 | mod information_leak;
4 | mod reporting;
5 | mod suppressions;
6 |
7 | use std::{
8 | collections::{BTreeSet, HashMap},
9 | fs::File,
10 | io::Read,
11 | path::{Path, PathBuf},
12 | sync::Arc,
13 | vec,
14 | };
15 |
16 | use anyhow::{anyhow, Context, Result};
17 | use clang::{Clang, Entity, EntityKind, Index};
18 | use rayon::prelude::*;
19 | use structopt::StructOpt;
20 |
21 | use compilation_database::CompileCommands;
22 | use information_leak::{BinaryLocation, ConfirmedLeak};
23 | use reporting::dump_confirmed_leaks;
24 | use suppressions::Suppressions;
25 |
26 | use crate::{
27 | cli::CpplumberOptions,
28 | compilation_database::{generate_compilation_database, ProjectConfiguration},
29 | information_leak::{
30 | ConfirmedLeakWithUniqueLocation, ConfirmedLeakWithUniqueValue, PotentialLeak,
31 | },
32 | suppressions::parse_suppressions_file,
33 | };
34 |
35 | fn main() -> Result<()> {
36 | // Default to 'info' if 'RUST_LOG' is not set
37 | env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
38 |
39 | // Parse command-line options
40 | let options = CpplumberOptions::from_args();
41 | let minimum_leak_size = options.minimum_leak_size.unwrap_or(4);
42 |
43 | // Initial checks before starting work
44 | if !options.binary_file_path.is_file() {
45 | return Err(anyhow!(
46 | "'{}' is not a valid file path.",
47 | options.binary_file_path.display()
48 | ));
49 | }
50 |
51 | // Parse the suppression list if used
52 | let suppressions = if let Some(ref suppressions_list) = options.suppressions_list {
53 | log::info!("Parsing suppressions file...");
54 | Some(
55 | parse_suppressions_file(suppressions_list)
56 | .with_context(|| "Failed to parse suppressions list")?,
57 | )
58 | } else {
59 | None
60 | };
61 |
62 | log::info!("Gathering source files...");
63 | // Extract project configuration from the CLI
64 | let project_config = if let Some(ref project_file_path) = options.project_file_path {
65 | ProjectConfiguration::CompilationDatabase { project_file_path }
66 | } else {
67 | ProjectConfiguration::Manual {
68 | source_path_globs: &options.source_path_globs,
69 | include_directories: &options.include_directories,
70 | compile_definitions: &options.compile_definitions,
71 | }
72 | };
73 | // Parse project file or process glob expressions
74 | let compilation_db = generate_compilation_database(project_config)?;
75 |
76 | log::info!("Filtering suppressed files...");
77 | // Filter suppressed files from the list, to avoid parsing files we're not
78 | // interested in
79 | let compile_commands =
80 | filter_suppressed_files(compilation_db.get_all_compile_commands()?, &suppressions);
81 |
82 | log::info!("Extracting artifacts from source files...");
83 | // Parse source files and extract information that could leak
84 | let potential_leaks = extract_artifacts_from_source_files(
85 | compile_commands,
86 | compilation_db.is_file_path_in_arguments(),
87 | !options.report_system_headers,
88 | options.ignore_string_literals,
89 | options.ignore_struct_names,
90 | minimum_leak_size,
91 | )?;
92 |
93 | log::info!("Filtering suppressed artifacts...");
94 | // Filter suppressed artifacts by source location if needed
95 | // Note: We need to do this "again" because artifacts from suppressed
96 | // headers might have been included during the parsing of other files
97 | let potential_leaks = filter_suppressed_artifacts_by_origin(potential_leaks, &suppressions);
98 | // Filter suppressed artifacts by value if needed
99 | let potential_leaks = filter_suppressed_artifacts_by_value(potential_leaks, &suppressions);
100 |
101 | log::info!(
102 | "Looking for leaks in '{}'...",
103 | options.binary_file_path.display()
104 | );
105 | log::debug!("{:#?}", potential_leaks);
106 | if options.ignore_multiple_locations {
107 | // Find leaks and deduplicate based on their value
108 | let leaks: BTreeSet =
109 | find_leaks_in_binary_file(&options.binary_file_path, potential_leaks)?;
110 | log::debug!("Done!");
111 |
112 | if leaks.is_empty() {
113 | // Nothing leaked, alright!
114 | Ok(())
115 | } else {
116 | // Print the result to stdout
117 | dump_confirmed_leaks(std::io::stdout(), leaks, options.json_output)?;
118 |
119 | // Return an error to indicate that leaks were found (useful for automation)
120 | Err(anyhow!("Leaks detected!"))
121 | }
122 | } else {
123 | // Find leaks and deduplicate based on their location (source + binary)
124 | let leaks: BTreeSet =
125 | find_leaks_in_binary_file(&options.binary_file_path, potential_leaks)?;
126 | log::debug!("Done!");
127 |
128 | if leaks.is_empty() {
129 | // Nothing leaked, alright!
130 | Ok(())
131 | } else {
132 | // Print the result to stdout
133 | dump_confirmed_leaks(std::io::stdout(), leaks, options.json_output)?;
134 |
135 | // Return an error to indicate that leaks were found (useful for automation)
136 | Err(anyhow!("Leaks detected!"))
137 | }
138 | }
139 | }
140 |
141 | fn gather_entities_by_kind<'tu>(
142 | root_entity: Entity<'tu>,
143 | entity_kind_filter: &[EntityKind],
144 | ignore_system_headers: bool,
145 | ) -> Vec> {
146 | gather_entities_by_kind_rec(root_entity, entity_kind_filter, ignore_system_headers)
147 | }
148 |
149 | fn gather_entities_by_kind_rec<'tu>(
150 | root_entity: Entity<'tu>,
151 | entity_kind_filter: &[EntityKind],
152 | ignore_system_headers: bool,
153 | ) -> Vec> {
154 | let mut entities = vec![];
155 |
156 | let root_entity_kind = root_entity.get_kind();
157 | // Check the if entity's kind is one we're looking for
158 | if entity_kind_filter
159 | .iter()
160 | .any(|elem| elem == &root_entity_kind)
161 | {
162 | entities.push(root_entity);
163 | }
164 |
165 | for child in root_entity.get_children() {
166 | // Ignore entity if requested
167 | if ignore_system_headers && child.is_in_system_header() {
168 | continue;
169 | }
170 |
171 | let entities_sub =
172 | gather_entities_by_kind_rec(child, entity_kind_filter, ignore_system_headers);
173 | entities.extend(entities_sub);
174 | }
175 |
176 | entities
177 | }
178 |
179 | fn filter_suppressed_files(
180 | compile_cmds: CompileCommands,
181 | suppressions: &Option,
182 | ) -> CompileCommands {
183 | if let Some(suppressions) = suppressions {
184 | compile_cmds
185 | .into_par_iter()
186 | .filter(|compile_cmd| {
187 | if let Some(file_path) = compile_cmd.filename.to_str() {
188 | !suppressions
189 | .files
190 | .par_iter()
191 | .any(|pattern| pattern.matches(file_path))
192 | } else {
193 | true
194 | }
195 | })
196 | .collect()
197 | } else {
198 | compile_cmds
199 | }
200 | }
201 |
202 | fn extract_artifacts_from_source_files(
203 | compile_commands: CompileCommands,
204 | use_file_path_from_arguments: bool,
205 | ignore_system_headers: bool,
206 | ignore_string_literals: bool,
207 | ignore_struct_names: bool,
208 | minimum_leak_size: usize,
209 | ) -> Result> {
210 | // Prepare the clang index
211 | let clang = Clang::new().map_err(|e| anyhow!(e))?;
212 | let index = Index::new(&clang, false, false);
213 |
214 | compile_commands
215 | .into_iter()
216 | // Populate indexes by parsing source files in parallel
217 | .try_fold(
218 | Vec::new(),
219 | |mut accum, compile_cmd| -> Result> {
220 | // Note: For some reason, having the file path in `arguments` when
221 | // passing the file path explicitly to libclang make the parser fail.
222 | // So we explicitely avoid doing so.
223 | let file_path = if use_file_path_from_arguments {
224 | PathBuf::default()
225 | } else {
226 | compile_cmd.filename
227 | };
228 | let translation_unit = index
229 | .parser(&file_path)
230 | .arguments(&compile_cmd.arguments)
231 | .parse()
232 | .with_context(|| {
233 | format!("Failed to parse source file '{}'", file_path.display())
234 | })?;
235 |
236 | // Setup filter
237 | let mut entity_kind_filter = vec![];
238 | if !ignore_string_literals {
239 | entity_kind_filter.push(EntityKind::StringLiteral);
240 | }
241 | if !ignore_struct_names {
242 | entity_kind_filter.push(EntityKind::StructDecl);
243 | entity_kind_filter.push(EntityKind::ClassDecl);
244 | }
245 |
246 | // Gather entities
247 | let string_literals = gather_entities_by_kind(
248 | translation_unit.get_entity(),
249 | &entity_kind_filter,
250 | ignore_system_headers,
251 | );
252 |
253 | accum.extend(string_literals.into_iter().filter_map(|literal| {
254 | let leak_res: Result = literal.try_into();
255 | if let Ok(potential_leak) = leak_res {
256 | if potential_leak.bytes.len() >= minimum_leak_size {
257 | Some(potential_leak)
258 | } else {
259 | // Value is too small, ignore it
260 | None
261 | }
262 | } else {
263 | // Log failure and discard element
264 | log::warn!(
265 | "Failed to process entity '{:?}': {}",
266 | literal,
267 | leak_res.unwrap_err()
268 | );
269 | None
270 | }
271 | }));
272 |
273 | Ok(accum)
274 | },
275 | )
276 | }
277 |
278 | fn filter_suppressed_artifacts_by_origin(
279 | potential_leaks: Vec,
280 | suppressions: &Option,
281 | ) -> Vec {
282 | if let Some(suppressions) = suppressions {
283 | potential_leaks
284 | .into_par_iter()
285 | .filter(|leak| {
286 | let file_path = &leak.declaration_metadata.file;
287 | if let Some(file_path) = file_path.as_os_str().to_str() {
288 | !suppressions
289 | .files
290 | .par_iter()
291 | .any(|pattern| pattern.matches(file_path))
292 | } else {
293 | true
294 | }
295 | })
296 | .collect()
297 | } else {
298 | potential_leaks
299 | }
300 | }
301 |
302 | fn filter_suppressed_artifacts_by_value(
303 | potential_leaks: Vec,
304 | suppressions: &Option,
305 | ) -> Vec {
306 | if let Some(suppressions) = suppressions {
307 | potential_leaks
308 | .into_par_iter()
309 | .filter(|leak| !suppressions.artifacts.contains(&leak.data))
310 | .collect()
311 | } else {
312 | potential_leaks
313 | }
314 | }
315 |
316 | fn find_leaks_in_binary_file(
317 | binary_file_path: &Path,
318 | leak_desc: PotentialLeakCollection,
319 | ) -> Result>
320 | where
321 | PotentialLeakCollection: IntoParallelIterator- ,
322 | SortedConfirmedLeak: From + Ord + Eq + Send,
323 | {
324 | // Read binary file's content
325 | let mut bin_file = File::open(binary_file_path)?;
326 | let mut bin_data = vec![];
327 | bin_file.read_to_end(&mut bin_data)?;
328 |
329 | // Build a map that allows to lookup "leaks' first byte -> leaks"
330 | let byte_to_leaks = leak_desc
331 | .into_par_iter()
332 | .fold(
333 | HashMap::new,
334 | |mut accum: HashMap>, potential_leak| {
335 | if let Some(key) = potential_leak.bytes.first() {
336 | if let Some(value) = accum.get_mut(key) {
337 | value.push(potential_leak);
338 | } else {
339 | accum.insert(*key, vec![potential_leak]);
340 | }
341 | }
342 |
343 | accum
344 | },
345 | )
346 | // Reduce intermediate maps into one
347 | .reduce(HashMap::new, |mut accum, other| {
348 | for (other_key, mut other_value) in other {
349 | if let Some(value) = accum.get_mut(&other_key) {
350 | value.append(&mut other_value);
351 | } else {
352 | accum.insert(other_key, other_value);
353 | }
354 | }
355 | accum
356 | });
357 |
358 | // Go through the binary file byte by byte and try to match leaks that start
359 | // with each byte
360 | let shared_binary_file_path = Arc::new(binary_file_path.to_path_buf().canonicalize()?);
361 | let confirmed_leaks = bin_data
362 | .par_iter()
363 | .enumerate()
364 | // Find actual leaks
365 | .map(|(i, byte_value)| {
366 | let mut confirmed_leaks = BTreeSet::new();
367 | if let Some(potential_leaks) = byte_to_leaks.get(byte_value) {
368 | // Go through each candidate
369 | for leak in potential_leaks {
370 | // Check bounds
371 | if i + leak.bytes.len() <= bin_data.len() {
372 | let byte_slice = &bin_data[i..i + leak.bytes.len()];
373 | if byte_slice == leak.bytes {
374 | // Bytes match, the leak is confirmed
375 | confirmed_leaks.insert(SortedConfirmedLeak::from(ConfirmedLeak {
376 | data_type: leak.data_type,
377 | data: leak.data.clone(),
378 | location: information_leak::LeakLocation {
379 | source: leak.declaration_metadata.clone(),
380 | binary: BinaryLocation {
381 | file: shared_binary_file_path.clone(),
382 | offset: i as u64,
383 | },
384 | },
385 | }));
386 | }
387 | }
388 | }
389 | }
390 |
391 | confirmed_leaks
392 | })
393 | .reduce(BTreeSet::new, |mut accum, other| {
394 | accum.extend(other);
395 | accum
396 | });
397 |
398 | Ok(confirmed_leaks)
399 | }
400 |
401 | #[cfg(test)]
402 | mod tests {
403 | use crate::compilation_database::{CompilationDatabase, FileListDatabase};
404 |
405 | use super::*;
406 |
407 | use serial_test::serial;
408 |
409 | const FILE_LIST_PROJ_PATH: &str = "tests/data/main/file_list_proj";
410 |
411 | #[test]
412 | #[serial]
413 | fn extract_artifacts_from_source_files_file_list() {
414 | let root_dir_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(FILE_LIST_PROJ_PATH);
415 | let file_list_db = FileListDatabase::new(
416 | &[root_dir_path.join("main.cc")],
417 | vec![
418 | "-DDEF_TEST".to_string(),
419 | format!("-I{}", FILE_LIST_PROJ_PATH),
420 | ],
421 | );
422 | let potential_leaks = extract_artifacts_from_source_files(
423 | file_list_db
424 | .get_all_compile_commands()
425 | .expect("get_all_compile_commands failed"),
426 | file_list_db.is_file_path_in_arguments(),
427 | true,
428 | false,
429 | false,
430 | 0,
431 | )
432 | .expect("extract_artifacts_from_source_files failed");
433 |
434 | let expected_string_literals = vec![
435 | "included_string_literal",
436 | "c_string",
437 | "utf8_string",
438 | "wide_string",
439 | "utf16_string",
440 | "utf32_string",
441 | "raw_string",
442 | "raw_utf8_string",
443 | "wide_raw_string",
444 | "raw_utf16_string",
445 | "raw_utf32_string",
446 | "def_test",
447 | "concatenated_string",
448 | r#"multiline\nstring"#,
449 | r#"'\"\n\t\a\b|\220|\220|\351\246\231|\351\246\231|\360\237\230\202"#,
450 | "MyStruct",
451 | "",
452 | "MyClass",
453 | "",
454 | r#"%s\n"#,
455 | "preprocessor_string_literal",
456 | r#"%s\n"#,
457 | "preprocessor_string_literal",
458 | r#"%s\n"#,
459 | ];
460 |
461 | // Check extracted string literals
462 | assert!(potential_leaks.iter().enumerate().all(|(i, leak)| {
463 | println!("{:?}", leak.data);
464 | *leak.data == expected_string_literals[i]
465 | }));
466 | assert_eq!(expected_string_literals.len(), potential_leaks.len());
467 | }
468 |
469 | #[test]
470 | #[serial]
471 | fn extract_artifacts_with_minimum_leak_size() {
472 | let root_dir_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(FILE_LIST_PROJ_PATH);
473 | let file_list_db = FileListDatabase::new(
474 | &[root_dir_path.join("main.cc")],
475 | vec![
476 | "-DDEF_TEST".to_string(),
477 | format!("-I{}", FILE_LIST_PROJ_PATH),
478 | ],
479 | );
480 | let potential_leaks = extract_artifacts_from_source_files(
481 | file_list_db
482 | .get_all_compile_commands()
483 | .expect("get_all_compile_commands failed"),
484 | file_list_db.is_file_path_in_arguments(),
485 | true,
486 | false,
487 | false,
488 | 4,
489 | )
490 | .expect("extract_artifacts_from_source_files failed");
491 |
492 | // r#""%s\n""# should be removed
493 | let expected_string_literals = vec![
494 | // main.cc
495 | "included_string_literal",
496 | "c_string",
497 | "utf8_string",
498 | "wide_string",
499 | "utf16_string",
500 | "utf32_string",
501 | "raw_string",
502 | "raw_utf8_string",
503 | "wide_raw_string",
504 | "raw_utf16_string",
505 | "raw_utf32_string",
506 | "def_test",
507 | "concatenated_string",
508 | r#"multiline\nstring"#,
509 | r#"'\"\n\t\a\b|\220|\220|\351\246\231|\351\246\231|\360\237\230\202"#,
510 | "MyStruct",
511 | "MyClass",
512 | "preprocessor_string_literal",
513 | r#"%s\n"#,
514 | "preprocessor_string_literal",
515 | ];
516 |
517 | // Check extracted string literals
518 | assert!(potential_leaks.iter().enumerate().all(|(i, leak)| {
519 | println!("{:?}", leak.data);
520 | *leak.data == expected_string_literals[i]
521 | }));
522 | assert_eq!(expected_string_literals.len(), potential_leaks.len());
523 | }
524 |
525 | #[cfg(windows)]
526 | #[test]
527 | #[serial]
528 | fn find_leaks_in_binary_file_exe() {
529 | // Gather potential leaks
530 | let root_dir_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(FILE_LIST_PROJ_PATH);
531 | let file_list_db = FileListDatabase::new(
532 | &[root_dir_path.join("main.cc")],
533 | vec![
534 | "-DDEF_TEST".to_string(),
535 | format!("-I{}", FILE_LIST_PROJ_PATH),
536 | ],
537 | );
538 | let potential_leaks = extract_artifacts_from_source_files(
539 | file_list_db
540 | .get_all_compile_commands()
541 | .expect("get_all_compile_commands failed"),
542 | file_list_db.is_file_path_in_arguments(),
543 | true,
544 | false,
545 | false,
546 | 0,
547 | )
548 | .expect("extract_artifacts_from_source_files failed");
549 |
550 | // Look for leaks present in the compiled binary
551 | let bin_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
552 | .join(FILE_LIST_PROJ_PATH)
553 | .join("a.exe");
554 |
555 | let confirmed_leaks: BTreeSet =
556 | find_leaks_in_binary_file(&bin_path, potential_leaks)
557 | .expect("find_leaks_in_binary_file failed");
558 |
559 | let expected_string_literals = vec![
560 | // main.cc
561 | "included_string_literal",
562 | "MyStruct",
563 | "MyStruct",
564 | "MyStruct",
565 | "MyClass",
566 | "MyClass",
567 | "MyClass",
568 | "preprocessor_string_literal",
569 | "preprocessor_string_literal",
570 | r#"%s\n"#,
571 | ];
572 |
573 | // Check extracted string literals
574 | assert!(confirmed_leaks.iter().enumerate().all(|(i, leak)| {
575 | println!("{:?}", leak.data);
576 | *leak.data == expected_string_literals[i]
577 | }));
578 | assert_eq!(confirmed_leaks.len(), expected_string_literals.len());
579 | }
580 |
581 | #[cfg(unix)]
582 | #[test]
583 | #[serial]
584 | fn find_leaks_in_binary_file_elf() {
585 | // Gather potential leaks
586 | let root_dir_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(FILE_LIST_PROJ_PATH);
587 | let file_list_db = FileListDatabase::new(
588 | &[root_dir_path.join("main.cc")],
589 | vec!["-DDEF_TEST".to_string()],
590 | );
591 | let potential_leaks = extract_artifacts_from_source_files(
592 | file_list_db
593 | .get_all_compile_commands()
594 | .expect("get_all_compile_commands failed"),
595 | file_list_db.is_file_path_in_arguments(),
596 | true,
597 | false,
598 | false,
599 | 0,
600 | )
601 | .expect("extract_artifacts_from_source_files failed");
602 |
603 | // Look for leaks present in the compiled binary
604 | let bin_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
605 | .join(FILE_LIST_PROJ_PATH)
606 | .join("a.out");
607 |
608 | let confirmed_leaks: BTreeSet =
609 | find_leaks_in_binary_file(&bin_path, potential_leaks)
610 | .expect("find_leaks_in_binary_file failed");
611 |
612 | let expected_string_literals = vec![
613 | // main.cc
614 | "included_string_literal",
615 | "included_string_literal",
616 | "MyStruct",
617 | "MyStruct",
618 | "MyStruct",
619 | "MyStruct",
620 | "MyStruct",
621 | "MyStruct",
622 | "MyStruct",
623 | "MyStruct",
624 | "MyStruct",
625 | "MyStruct",
626 | "MyStruct",
627 | "MyStruct",
628 | "MyClass",
629 | "MyClass",
630 | "MyClass",
631 | "MyClass",
632 | "MyClass",
633 | "MyClass",
634 | "MyClass",
635 | "MyClass",
636 | "MyClass",
637 | "MyClass",
638 | "MyClass",
639 | "preprocessor_string_literal",
640 | r#"%s\n"#,
641 | "preprocessor_string_literal",
642 | ];
643 |
644 | // Check extracted string literals
645 | assert!(confirmed_leaks.iter().enumerate().all(|(i, leak)| {
646 | println!("{:?}", leak.data);
647 | *leak.data == expected_string_literals[i]
648 | }));
649 | assert_eq!(confirmed_leaks.len(), expected_string_literals.len());
650 | }
651 | }
652 |
--------------------------------------------------------------------------------
/src/reporting.rs:
--------------------------------------------------------------------------------
1 | use std::collections::BTreeSet;
2 |
3 | use anyhow::Result;
4 | use serde::Serialize;
5 |
6 | use crate::information_leak::{ConfirmedLeak, LeakedDataType};
7 |
8 | const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
9 | const REPORT_FORMAT_VERSION: u32 = 1;
10 |
11 | #[derive(Serialize)]
12 | struct JsonReport + Ord + Eq + Serialize> {
13 | version: ReportVersion,
14 | leaks: BTreeSet,
15 | }
16 |
17 | #[derive(Serialize)]
18 | struct ReportVersion {
19 | executable: String,
20 | format: u32,
21 | }
22 |
23 | pub fn dump_confirmed_leaks(
24 | writer: W,
25 | confirmed_leaks: BTreeSet,
26 | json: bool,
27 | ) -> Result<()>
28 | where
29 | W: std::io::Write,
30 | SortedConfirmedLeak: Into + Ord + Eq + Serialize,
31 | {
32 | if json {
33 | dump_confirmed_leaks_as_json(writer, confirmed_leaks)
34 | } else {
35 | dump_confirmed_leaks_as_text(writer, confirmed_leaks)
36 | }
37 | }
38 |
39 | fn dump_confirmed_leaks_as_json(
40 | writer: W,
41 | confirmed_leaks: BTreeSet,
42 | ) -> Result<()>
43 | where
44 | W: std::io::Write,
45 | SortedConfirmedLeak: Into + Ord + Eq + Serialize,
46 | {
47 | let report = JsonReport {
48 | version: ReportVersion {
49 | executable: PKG_VERSION.into(),
50 | format: REPORT_FORMAT_VERSION,
51 | },
52 | leaks: confirmed_leaks,
53 | };
54 |
55 | Ok(serde_json::to_writer(writer, &report)?)
56 | }
57 |
58 | fn dump_confirmed_leaks_as_text(
59 | mut writer: W,
60 | confirmed_leaks: BTreeSet,
61 | ) -> Result<()>
62 | where
63 | W: std::io::Write,
64 | SortedConfirmedLeak: Into + Ord + Eq + Serialize,
65 | {
66 | for leak in confirmed_leaks {
67 | let leak: ConfirmedLeak = leak.into();
68 | writeln!(
69 | &mut writer,
70 | "\"{}\" ({}) leaked at offset 0x{:x} in \"{}\" [declared at {}:{}]",
71 | leak.data,
72 | display_leaked_data_type(leak.data_type),
73 | leak.location.binary.offset,
74 | leak.location.binary.file.display(),
75 | leak.location.source.file.display(),
76 | leak.location.source.line,
77 | )?;
78 | }
79 |
80 | Ok(())
81 | }
82 |
83 | /// Returns a text representation of `LeakedDataType`
84 | fn display_leaked_data_type(data_type: LeakedDataType) -> String {
85 | match data_type {
86 | LeakedDataType::StringLiteral => "string literal".to_string(),
87 | LeakedDataType::StructName => "struct name".to_string(),
88 | LeakedDataType::ClassName => "class name".to_string(),
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/src/suppressions.rs:
--------------------------------------------------------------------------------
1 | use std::fs::File;
2 | use std::io::Read;
3 | use std::path::Path;
4 |
5 | use anyhow::Result;
6 | use glob::Pattern;
7 | use serde::Deserialize;
8 |
9 | pub struct Suppressions {
10 | pub files: Vec,
11 | pub artifacts: Vec,
12 | }
13 |
14 | #[derive(Deserialize)]
15 | struct SuppressionsListYaml {
16 | files: Option>,
17 | artifacts: Option>,
18 | }
19 |
20 | pub fn parse_suppressions_file(suppression_file_path: &Path) -> Result {
21 | // Read file
22 | let mut suppression_data = vec![];
23 | let mut suppression_file = File::open(suppression_file_path)?;
24 | suppression_file.read_to_end(&mut suppression_data)?;
25 |
26 | // Parse YAML content
27 | let suppressions_yaml: SuppressionsListYaml = serde_yaml::from_slice(&suppression_data)?;
28 |
29 | // Compile glob patterns
30 | let files = suppressions_yaml
31 | .files
32 | .unwrap_or_default()
33 | .iter()
34 | .map(|pattern| {
35 | if let Ok(pattern) = Pattern::new(pattern) {
36 | pattern
37 | } else {
38 | log::warn!("Failed to compile '{}', ignoring ...", &pattern);
39 | Pattern::default()
40 | }
41 | })
42 | .collect();
43 |
44 | Ok(Suppressions {
45 | files,
46 | artifacts: suppressions_yaml.artifacts.unwrap_or_default(),
47 | })
48 | }
49 |
50 | #[cfg(test)]
51 | mod tests {
52 | use std::path::PathBuf;
53 |
54 | use super::*;
55 |
56 | const FILE1_PATH: &str = "tests/data/suppressions/files_and_artifacts.yml";
57 |
58 | #[test]
59 | fn parse_suppressions_file_files_and_artifacts() {
60 | let file_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(FILE1_PATH);
61 | let suppressions =
62 | parse_suppressions_file(&file_path).expect("Failed parsing suppressions file");
63 |
64 | // Files
65 | assert_eq!(suppressions.files.len(), 1);
66 | assert_eq!(
67 | suppressions.files[0],
68 | glob::Pattern::new("*\\file2.cc").unwrap()
69 | );
70 |
71 | // Artifacts
72 | assert_eq!(suppressions.artifacts.len(), 2);
73 | assert_eq!(suppressions.artifacts[0], "c_string");
74 | assert_eq!(suppressions.artifacts[1], "utf32_string");
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/tests/data/compile_commands/db1.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "directory": "/home/user/cpplumber",
4 | "arguments": [
5 | "/usr/bin/clang++",
6 | "-Irelative",
7 | "-DSOMEDEF=With spaces, quotes.",
8 | "-c",
9 | "-o",
10 | "file1.o",
11 | "tests/data/compile_commands/file1.cc"
12 | ],
13 | "file": "tests/data/compile_commands/file1.cc"
14 | },
15 | {
16 | "directory": "/home/user/cpplumber",
17 | "command": "/usr/bin/clang++ -Irelative -DSOMEDEF=\"With spaces, quotes.\" -c -o file2.o tests/data/compile_commands/file2.cc",
18 | "file": "tests/data/compile_commands/file2.cc"
19 | }
20 | ]
--------------------------------------------------------------------------------
/tests/data/compile_commands/empty.json:
--------------------------------------------------------------------------------
1 | []
--------------------------------------------------------------------------------
/tests/data/compile_commands/file1.cc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ergrelet/cpplumber/68526a64c9bbdc929c286844e25cf6f8e73d0d59/tests/data/compile_commands/file1.cc
--------------------------------------------------------------------------------
/tests/data/compile_commands/file2.cc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ergrelet/cpplumber/68526a64c9bbdc929c286844e25cf6f8e73d0d59/tests/data/compile_commands/file2.cc
--------------------------------------------------------------------------------
/tests/data/compile_commands/invalid.json:
--------------------------------------------------------------------------------
1 | not a json file
--------------------------------------------------------------------------------
/tests/data/main/file_list_proj/a.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ergrelet/cpplumber/68526a64c9bbdc929c286844e25cf6f8e73d0d59/tests/data/main/file_list_proj/a.exe
--------------------------------------------------------------------------------
/tests/data/main/file_list_proj/a.out:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ergrelet/cpplumber/68526a64c9bbdc929c286844e25cf6f8e73d0d59/tests/data/main/file_list_proj/a.out
--------------------------------------------------------------------------------
/tests/data/main/file_list_proj/header.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | const char* included_string_literal = "included_string_literal";
4 |
--------------------------------------------------------------------------------
/tests/data/main/file_list_proj/main.cc:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include "header.h"
6 |
7 | #define PREPROCESSOR_STRING_LITERAL "preprocessor_string_literal"
8 | #define PREPROCESSOR_WIDE_STRING_LITERAL L"preprocessor_string_literal"
9 |
10 | static const char* my_c_string = "c_string";
11 | static const char* my_utf8_string = u8"utf8_string";
12 | static const wchar_t* my_wide_string = L"wide_string";
13 | static const char16_t* my_utf16_string = u"utf16_string";
14 | static const char32_t* my_utf32_string = U"utf32_string";
15 | // TODO: user-defined literals
16 |
17 | static const char* my_raw_string = R"(raw_string)";
18 | static const char* my_raw_utf8_string = u8R"(raw_utf8_string)";
19 | static const wchar_t* my_wide_raw_string = LR"(wide_raw_string)";
20 | static const char16_t* my_raw_utf16_string = uR"(raw_utf16_string)";
21 | static const char32_t* my_raw_utf32_string = UR"(raw_utf32_string)";
22 |
23 | #ifdef DEF_TEST
24 | static const char* def_test_string = "def_test";
25 | #endif
26 | static const char* my_concatenated_string = "concatenated" "_string";
27 | static const char* my_multiline_string = R"(multiline
28 | string)";
29 | static const char* my_escaped_string = "\'\"\n\t\a\b|\x90|\220|\u9999|\U00009999|😂";
30 | // static const char* my_commented_string = "commented_string";
31 |
32 | struct MyStruct {
33 | // Unnamed struct
34 | struct {
35 | int field1;
36 | };
37 | };
38 |
39 | class MyClass {
40 | public:
41 | // Unnamed class
42 | class {
43 | public:
44 | int field1;
45 | };
46 | };
47 |
48 | int main() {
49 | printf("%s\n", PREPROCESSOR_STRING_LITERAL);
50 | wprintf(L"%s\n", PREPROCESSOR_WIDE_STRING_LITERAL);
51 | printf("%s\n", included_string_literal);
52 |
53 | // Force the generation of some RTTI
54 | std::shared_ptr struct_ptr = std::make_unique();
55 | std::shared_ptr class_ptr = std::make_unique();
56 |
57 | return 0;
58 | }
59 |
--------------------------------------------------------------------------------
/tests/data/suppressions/files_and_artifacts.yml:
--------------------------------------------------------------------------------
1 | # Files to ignore (can include glob expressions)
2 | files:
3 | # Duplicated file
4 | - "*\\file2.cc"
5 |
6 | # Artifacts to ignore
7 | artifacts:
8 | # These leaks are not too bad
9 | - c_string
10 | - utf32_string
11 |
--------------------------------------------------------------------------------