Benchanything commited on
Commit
4eaabb5
·
verified ·
1 Parent(s): 8247f19

Add 300 CheckerBench tasks, dataset card, and restoration tools (part 4)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/csa159/pair_135405/post_functions.txt +144 -0
  2. tasks/csa159/pair_135405/pre_functions.txt +123 -0
  3. tasks/csa159/pair_135405/task_prompt.md +383 -0
  4. tasks/csa159/pair_135446/checker_template.cpp +98 -0
  5. tasks/csa159/pair_135446/config.json +19 -0
  6. tasks/csa159/pair_135446/patch.diff +46 -0
  7. tasks/csa159/pair_135446/post_functions.txt +313 -0
  8. tasks/csa159/pair_135446/pre_functions.txt +315 -0
  9. tasks/csa159/pair_135446/task_prompt.md +374 -0
  10. tasks/csa159/pair_135624/checker_template.cpp +98 -0
  11. tasks/csa159/pair_135624/config.json +19 -0
  12. tasks/csa159/pair_135624/patch.diff +13 -0
  13. tasks/csa159/pair_135624/post_functions.txt +67 -0
  14. tasks/csa159/pair_135624/pre_functions.txt +67 -0
  15. tasks/csa159/pair_135624/task_prompt.md +380 -0
  16. tasks/csa159/pair_135745/checker_template.cpp +98 -0
  17. tasks/csa159/pair_135745/config.json +20 -0
  18. tasks/csa159/pair_135745/patch.diff +68 -0
  19. tasks/csa159/pair_135745/post_functions.txt +220 -0
  20. tasks/csa159/pair_135745/pre_functions.txt +216 -0
  21. tasks/csa159/pair_135745/task_prompt.md +318 -0
  22. tasks/csa159/pair_135749/checker_template.cpp +98 -0
  23. tasks/csa159/pair_135749/config.json +20 -0
  24. tasks/csa159/pair_135749/patch.diff +71 -0
  25. tasks/csa159/pair_135749/post_functions.txt +226 -0
  26. tasks/csa159/pair_135749/pre_functions.txt +284 -0
  27. tasks/csa159/pair_135749/task_prompt.md +370 -0
  28. tasks/csa159/pair_136251/checker_template.cpp +98 -0
  29. tasks/csa159/pair_136251/config.json +36 -0
  30. tasks/csa159/pair_136251/patch.diff +1071 -0
  31. tasks/csa159/pair_136251/post_functions.txt +0 -0
  32. tasks/csa159/pair_136251/pre_functions.txt +2527 -0
  33. tasks/csa159/pair_136251/task_prompt.md +374 -0
  34. tasks/csa159/pair_136252/checker_template.cpp +98 -0
  35. tasks/csa159/pair_136252/config.json +19 -0
  36. tasks/csa159/pair_136252/patch.diff +13 -0
  37. tasks/csa159/pair_136252/post_functions.txt +333 -0
  38. tasks/csa159/pair_136252/pre_functions.txt +333 -0
  39. tasks/csa159/pair_136252/task_prompt.md +384 -0
  40. tasks/csa159/pair_136342/checker_template.cpp +98 -0
  41. tasks/csa159/pair_136342/config.json +20 -0
  42. tasks/csa159/pair_136342/patch.diff +41 -0
  43. tasks/csa159/pair_136342/post_functions.txt +567 -0
  44. tasks/csa159/pair_136342/pre_functions.txt +570 -0
  45. tasks/csa159/pair_136342/task_prompt.md +318 -0
  46. tasks/csa159/pair_136864/checker_template.cpp +98 -0
  47. tasks/csa159/pair_136864/config.json +19 -0
  48. tasks/csa159/pair_136864/patch.diff +23 -0
  49. tasks/csa159/pair_136864/post_functions.txt +282 -0
  50. tasks/csa159/pair_136864/pre_functions.txt +282 -0
tasks/csa159/pair_135405/post_functions.txt ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: src/ext-cmd.c
2
+ ```c
3
+ static int select_read(int sockfd, char buffer[], int bufsize, struct timeval *tv)
4
+ {
5
+ fd_set rfds;
6
+ int retval;
7
+
8
+ FD_ZERO(&rfds);
9
+ FD_SET(sockfd, &rfds);
10
+
11
+ retval = select(sockfd + 1, &rfds, NULL, NULL, tv);
12
+
13
+ if (retval == -1) {
14
+ // Error
15
+ return -1;
16
+ } else if (retval) {
17
+ // Data available
18
+ return read(sockfd, buffer, bufsize);
19
+ } else {
20
+ // Timeout reached
21
+ return 0;
22
+ }
23
+ }
24
+
25
+ static int append_strings(char buf[], size_t bufsize, int argc, char *argv[])
26
+ {
27
+ int i;
28
+ int len;
29
+
30
+ // Check input length
31
+ len = 0;
32
+ for (i = 0; i < argc; ++i) {
33
+ len += 1 + strlen(argv[i]);
34
+ if(len >= bufsize) {
35
+ return EXIT_FAILURE;
36
+ }
37
+ }
38
+
39
+ // Concatenate strings
40
+ buf[0] = '\0';
41
+ for (i = 0; i < argc; ++i) {
42
+ if (i) {
43
+ strcat(buf, " ");
44
+ }
45
+ strcat(buf, argv[i]);
46
+ }
47
+ strcat(buf, "\n");
48
+
49
+ return EXIT_SUCCESS;
50
+ }
51
+
52
+ int cmd_client(int argc, char *argv[])
53
+ {
54
+ char buffer[256];
55
+ const char *path;
56
+ struct sockaddr_un addr;
57
+ struct timeval tv;
58
+ ssize_t size;
59
+ int sock;
60
+
61
+ // Default unix socket path
62
+ path = CMD_PATH;
63
+
64
+ // Skip program name
65
+ argc -= 1;
66
+ argv += 1;
67
+
68
+ if (argc >= 1) {
69
+ if (strcmp(argv[0], "-h") == 0) {
70
+ fprintf(stdout, "%s", g_client_usage);
71
+ return 0;
72
+ } else if (strcmp(argv[0], "-p") == 0) {
73
+ if (argc >= 2) {
74
+ path = argv[1];
75
+ // Skip option and path
76
+ argc -= 2;
77
+ argv += 2;
78
+ } else {
79
+ fprintf(stderr, "Path is missing!\n");
80
+ return 1;
81
+ }
82
+ }
83
+ }
84
+
85
+ if (EXIT_FAILURE == append_strings(buffer, sizeof(buffer), argc, argv)) {
86
+ fprintf(stderr, "Input to long\n");
87
+ return EXIT_FAILURE;
88
+ }
89
+
90
+ sock = socket(AF_LOCAL, SOCK_STREAM, 0);
91
+ if (sock < 0) {
92
+ fprintf(stderr, "socket(): %s\n", strerror(errno));
93
+ return EXIT_FAILURE;
94
+ }
95
+
96
+ addr.sun_family = AF_LOCAL;
97
+ strcpy(addr.sun_path, path);
98
+
99
+ if (connect(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
100
+ fprintf(stderr, "Failed to connect to '%s': %s\n", path, strerror(errno));
101
+ goto error;
102
+ }
103
+
104
+ /* Set receive timeout: 200ms */
105
+ tv.tv_sec = 0;
106
+ tv.tv_usec = 200000;
107
+
108
+ #ifndef __CYGWIN__
109
+ if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) < 0) {
110
+ fprintf(stderr, "setsockopt(): %s\n", strerror(errno));
111
+ goto error;
112
+ }
113
+ #endif
114
+
115
+ // Send request
116
+ send(sock, buffer, strlen(buffer), 0);
117
+
118
+ while (1) {
119
+ // Receive replies
120
+ #ifdef __CYGWIN__
121
+ size = select_read(sock, buffer, strlen(buffer), &tv);
122
+ #else
123
+ size = read(sock, buffer, strlen(buffer));
124
+ #endif
125
+ if (size <= 0) {
126
+ break;
127
+ }
128
+
129
+ buffer[size] = '\0';
130
+ printf("%s", buffer);
131
+ }
132
+
133
+ close(sock);
134
+
135
+ return EXIT_SUCCESS;
136
+
137
+ error:
138
+ if (sock > 0) {
139
+ close(sock);
140
+ }
141
+
142
+ return EXIT_FAILURE;
143
+ }
144
+ ```
tasks/csa159/pair_135405/pre_functions.txt ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: src/ext-cmd.c
2
+ ```c
3
+ static int select_read(int sockfd, char buffer[], int bufsize, struct timeval *tv)
4
+ {
5
+ fd_set rfds;
6
+ int retval;
7
+
8
+ FD_ZERO(&rfds);
9
+ FD_SET(sockfd, &rfds);
10
+
11
+ retval = select(sockfd + 1, &rfds, NULL, NULL, tv);
12
+
13
+ if (retval == -1) {
14
+ // Error
15
+ return -1;
16
+ } else if (retval) {
17
+ // Data available
18
+ return read(sockfd, buffer, bufsize);
19
+ } else {
20
+ // Timeout reached
21
+ return 0;
22
+ }
23
+ }
24
+
25
+ int cmd_client(int argc, char *argv[])
26
+ {
27
+ char buffer[256];
28
+ const char *path;
29
+ struct sockaddr_un addr;
30
+ struct timeval tv;
31
+ ssize_t size;
32
+ int sock;
33
+ size_t i;
34
+
35
+ // Default unix socket path
36
+ path = CMD_PATH;
37
+
38
+ // Skip program name
39
+ argc -= 1;
40
+ argv += 1;
41
+
42
+ if (argc >= 1) {
43
+ if (strcmp(argv[0], "-h") == 0) {
44
+ fprintf(stdout, "%s", g_client_usage);
45
+ return 0;
46
+ } else if (strcmp(argv[0], "-p") == 0) {
47
+ if (argc >= 2) {
48
+ path = argv[1];
49
+ // Skip option and path
50
+ argc -= 2;
51
+ argv += 2;
52
+ } else {
53
+ fprintf(stderr, "Path is missing!\n");
54
+ return 1;
55
+ }
56
+ }
57
+ }
58
+
59
+ // Construct request string from args
60
+ buffer[0] = '\0';
61
+ for (i = 0; i < argc; ++i) {
62
+ if (i) {
63
+ strcat(buffer, " ");
64
+ }
65
+ strcat(buffer, argv[i]);
66
+ }
67
+ strcat(buffer, "\n");
68
+
69
+ sock = socket(AF_LOCAL, SOCK_STREAM, 0);
70
+ if (sock < 0) {
71
+ fprintf(stderr, "socket(): %s\n", strerror(errno));
72
+ return EXIT_FAILURE;
73
+ }
74
+
75
+ addr.sun_family = AF_LOCAL;
76
+ strcpy(addr.sun_path, path);
77
+
78
+ if (connect(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
79
+ fprintf(stderr, "Failed to connect to '%s': %s\n", path, strerror(errno));
80
+ goto error;
81
+ }
82
+
83
+ /* Set receive timeout: 200ms */
84
+ tv.tv_sec = 0;
85
+ tv.tv_usec = 200000;
86
+
87
+ #ifndef __CYGWIN__
88
+ if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) < 0) {
89
+ fprintf(stderr, "setsockopt(): %s\n", strerror(errno));
90
+ goto error;
91
+ }
92
+ #endif
93
+
94
+ // Send request
95
+ send(sock, buffer, strlen(buffer), 0);
96
+
97
+ while (1) {
98
+ // Receive replies
99
+ #ifdef __CYGWIN__
100
+ size = select_read(sock, buffer, strlen(buffer), &tv);
101
+ #else
102
+ size = read(sock, buffer, strlen(buffer));
103
+ #endif
104
+ if (size <= 0) {
105
+ break;
106
+ }
107
+
108
+ buffer[size] = '\0';
109
+ printf("%s", buffer);
110
+ }
111
+
112
+ close(sock);
113
+
114
+ return EXIT_SUCCESS;
115
+
116
+ error:
117
+ if (sock > 0) {
118
+ close(sock);
119
+ }
120
+
121
+ return EXIT_FAILURE;
122
+ }
123
+ ```
tasks/csa159/pair_135405/task_prompt.md ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Task: Synthesize a CSA Checker from a CVE Patch
2
+
3
+ ## Your Role
4
+
5
+ You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker
6
+ that detects the bug pattern fixed by the CVE patch in this working directory.
7
+
8
+ You have full filesystem and bash access — use them.
9
+
10
+ ### Skills
11
+
12
+ Many skills are available under `.claude/skills/` — covering vulnerability analysis,
13
+ checker design, debugging, code audit, security patterns, and more. Each skill
14
+ encodes reusable expertise: take time to explore them, read their SKILL.md files,
15
+ and invoke those that look useful via the Skill tool. Let the task guide which
16
+ ones you reach for.
17
+
18
+ ## File Layout
19
+
20
+ ```
21
+ /work/
22
+ ├── compile.sh ← RUN ME: compile checker.cpp → checker.so
23
+ ├── checker_template.cpp ← skeleton, start here
24
+ ├── patch.diff ← the CVE fix
25
+ ├── pre_functions.txt ← buggy source (before_commit)
26
+ ├── post_functions.txt ← patched source (after_commit)
27
+ ├── config.json ← paths, commit_message, commit hashes, flags
28
+ ├── scan/
29
+ │ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy
30
+ │ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched
31
+ │ └── flags_*.txt ← pre-extracted compile flags (-I, -D)
32
+ ├── references/
33
+ │ ├── repo_knowledge.md ← project-specific API/convention reference
34
+ │ ├── patterns_summary.md ← (optional) historical bug pattern summary
35
+ │ ├── cwe_cards/ ← CWE knowledge library (all categories)
36
+ │ │ ├── index.json ← lookup index — use to find relevant cards
37
+ │ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns
38
+ │ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped)
39
+ │ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers)
40
+ │ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.)
41
+ │ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.)
42
+ │ └── examples/
43
+ │ └── llvm-official/ ← 5 official checker sources (with comments)
44
+ │ ├── 01_div_zero.cpp
45
+ │ ├── 02_simple_stream.cpp
46
+ │ ├── 03_undef_result.cpp
47
+ │ ├── 04_nullability.cpp
48
+ │ └── 05_malloc.cpp
49
+ │
50
+ ├── checker.cpp ← YOUR OUTPUT: synthesized checker
51
+ ├── checker.so ← YOUR OUTPUT: compiled checker
52
+ ├── state.json ← YOUR OUTPUT: structured task state
53
+ ├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3)
54
+ └── summary.json ← YOUR OUTPUT: final report
55
+ ```
56
+
57
+ ## Resources
58
+
59
+ **Read these before writing any code:**
60
+
61
+ 1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from
62
+ LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types,
63
+ MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.**
64
+
65
+ 2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested
66
+ patterns from official LLVM checkers: resource tracking, null checking, undefined
67
+ value detection, division-by-zero, and malloc/free. Each pattern includes skeleton
68
+ code, state traits, and key API usage.
69
+
70
+ 3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations
71
+ with explanatory comments:
72
+ - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback)
73
+ - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose)
74
+ - `03_undef_result.cpp` — PostStmt pattern (160 lines)
75
+ - `04_nullability.cpp` — multi-callback checker (1247 lines)
76
+ - `05_malloc.cpp` — comprehensive malloc/free (1511 lines)
77
+
78
+ 4. **`checker_template.cpp`** — Skeleton with placeholders. Start here.
79
+
80
+ 5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this
81
+ repository's memory allocation API, key data types, source layout, and typical
82
+ CVE patterns. **Read this before writing the checker** — knowing the project's
83
+ alloc/free conventions and common bug patterns saves many grep rounds.
84
+
85
+ 5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis
86
+ patterns for this project. If present, it contains a concise summary of the
87
+ most common bug patterns, frequent CWE categories, and reusable checker
88
+ architectures observed in previous synthesis runs. Read after repo_knowledge.md.
89
+
90
+ 6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all
91
+ vulnerability categories. **The framework provides the full library —
92
+ you must identify the vulnerability type yourself.** Workflow:
93
+
94
+ 1. Analyse the patch diff and commit message to determine the vulnerability
95
+ type (buffer overflow, UAF, null deref, integer overflow, race condition,
96
+ etc.). Do NOT rely on the CWE label — treat it as a hint at most.
97
+ 2. Open ``index.json`` to discover available cards and their tiers.
98
+ 3. Read the relevant card(s) for **detection strategies**, **checker
99
+ architecture suggestions**, and **known false-positive patterns**.
100
+
101
+ Card tiers:
102
+ - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel /
103
+ userspace variants when the detection strategy differs substantially.
104
+ - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by
105
+ category (input validation, resource management, etc.).
106
+
107
+ 7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for
108
+ checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`),
109
+ expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string
110
+ size extraction, MemRegion helpers, and `ExprHasName()` for robust function
111
+ matching. All verified against LLVM 18. **Read before implementing detection
112
+ logic** — these save writing boilerplate that's easy to get wrong.
113
+
114
+ ## Environment
115
+
116
+ Key paths are in ``config.json``.
117
+
118
+ ### Pre-built scripts
119
+
120
+ | Script | What it does |
121
+ |--------|-------------|
122
+ | `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) |
123
+ | `CHECKER_NAME=<name> bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy |
124
+ | `CHECKER_NAME=<name> bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched |
125
+
126
+ ```bash
127
+ # Compile (run from workdir root)
128
+ bash compile.sh
129
+
130
+ # Scan — set CHECKER_NAME to the string passed to addChecker<>()
131
+ CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy
132
+ CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched
133
+ ```
134
+
135
+ - ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags.
136
+ - ``scan/scan_*.sh`` count only warnings tagged with your checker name.
137
+ - Scan environments (source files + compile flags) are pre-built in ``scan/``.
138
+
139
+ ### Scan Script Integrity (CRITICAL)
140
+
141
+ The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only
142
+ valid measurement** of N_buggy and N_patched. They are the ground truth that the
143
+ Python-side validator will also use. You MUST obey these rules:
144
+
145
+ **1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly
146
+ to measure warning counts. The Python validator runs the same scan scripts
147
+ — if you measured with a different command, your numbers will not reproduce
148
+ and the synthesis will be rejected.
149
+
150
+ **2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared
151
+ identifiers, etc.), the scan environment needs repair. You MUST fix it:
152
+ - Add missing ``-I`` include paths to the flags files in ``scan/``
153
+ - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot
154
+ - If the file fundamentally cannot be compiled by clang, stop and write
155
+ ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason``
156
+
157
+ **3. Only trust scan script output.** The ``Total <name> warnings: N`` line
158
+ printed by the scan script is the number that goes into ``summary.json``.
159
+ If the scan script says 0, write 0. Fabricating numbers that the scan
160
+ script did not produce will cause the Python validator to reject the
161
+ synthesis.
162
+
163
+ - If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles).
164
+ - If validation fails: revise checker logic, re-compile, re-scan.
165
+
166
+ ## MCP Tools
167
+
168
+ You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`).
169
+ Each returns **source context embedded in the result** — no need to follow up with Read.
170
+
171
+ | Tool | What it does | Key advantage |
172
+ |------|-------------|---------------|
173
+ | `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call |
174
+ | `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file |
175
+ | `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed |
176
+
177
+ ### When to use each
178
+
179
+ - **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure.
180
+ - **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines.
181
+ - **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action.
182
+
183
+ ## Semantic Design Contract — before writing checker.cpp
184
+
185
+ Create the analysis portions of `state.json` and `scope_statement.md` **before**
186
+ writing checker.cpp. They are a design contract, not a retrospective summary.
187
+ After compilation, update only implementation facts such as `build_attempts`.
188
+
189
+ In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the
190
+ semantic fact introduced by the patch that makes it safe. In `detection_plan`,
191
+ make `report_condition`, `safe_condition`, and `source_level_signal` concrete
192
+ CSA-observable facts. In `api_choice`, record the mechanism level and explain
193
+ why the selected callback can observe and prove those facts.
194
+
195
+ In `scope_statement.md`, include this mapping table and check it again after
196
+ implementation:
197
+
198
+ | Semantic condition | CSA evidence | checker.cpp implementation |
199
+ | --- | --- | --- |
200
+ | report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports |
201
+ | safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report |
202
+
203
+ Every condition in the plan must have an implementation entry. Do not claim a
204
+ condition that checker.cpp does not implement, and do not silently add a code
205
+ condition absent from the plan.
206
+
207
+ ## Mechanism Selection — diagnose before coding
208
+
209
+ Choose the weakest CSA mechanism that can prove the vulnerability property:
210
+
211
+ 1. **syntax-only AST**: only when local AST shape itself is the defect;
212
+ 2. **control flow / dominance**: when guard placement relative to a sink matters;
213
+ 3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use;
214
+ 4. **cross-procedure/dataflow**: when the required fact crosses function boundaries.
215
+
216
+ For a guard-based patch, prove both that the guard rejects the unsafe value and
217
+ that it dominates the vulnerable use. For path-sensitive or cross-procedure
218
+ defects, do not replace the required state or flow proof with local AST matching
219
+ or source-text substring matching merely because it passes the differential scan.
220
+ Record the selected level as `api_choice.mechanism_level`.
221
+
222
+ ## Semantic identity, locality, and final validation
223
+
224
+ Before accepting the checker, verify that its primary matching logic does not
225
+ depend on patch-local variable names, labels, line numbers, commit IDs, or unique
226
+ literals. Project APIs, types, and stable semantic call relationships are valid
227
+ scope anchors when they define the vulnerability class. Attach the report to the
228
+ actual vulnerable operation, and implement every suppression as a real safe
229
+ condition rather than the mere presence of a nearby guard-shaped statement.
230
+
231
+ The required final sequence is: **compile → before scan → after scan → inspect
232
+ the final checker name, artifacts, and report locations → write summary.json**.
233
+ Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only
234
+ additional redesign cycles after a failed validation; if it is zero, preserve the
235
+ real validation evidence and report failure honestly rather than fabricating counts.
236
+
237
+ ## Validation Criteria
238
+
239
+ ```
240
+ VALID : N_buggy > N_patched AND N_patched < 50
241
+ INVALID : otherwise → revise and re-validate (max 1 attempts)
242
+ ```
243
+
244
+ ## Refinement
245
+
246
+ Do NOT self-refine the checker repeatedly. Your goal is to produce the first
247
+ checker that passes the Validation Criteria above — fix compile errors and
248
+ validation failures only. False positives are triaged and repaired by the
249
+ framework's refinement stage: you will receive a concrete FP list via
250
+ session resume (if needed) and fix only those. Reserve budget for that stage.
251
+
252
+ ## Output
253
+
254
+ Produce all of the following **only when completely done**:
255
+
256
+ | File | Content |
257
+ |------|---------|
258
+ | ``checker.cpp`` | Synthesized checker source code |
259
+ | ``checker.so`` | Compiled checker plugin |
260
+ | ``state.json`` | Structured task state (see schema below) |
261
+ | ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) |
262
+ | ``summary.json`` | Final report (see schema below) |
263
+
264
+ Writing ``summary.json`` signals completion. Do NOT write it early.
265
+
266
+ ### ``state.json``
267
+
268
+ Create this before writing checker.cpp to capture the design contract. After the
269
+ checker compiles, update only implementation facts and retain the original
270
+ semantic plan.
271
+
272
+ ```json
273
+ {
274
+ "patch_analysis": {
275
+ "summary": "One sentence describing the vulnerability this patch fixes",
276
+ "changed_files": ["file1.c", "file2.h"],
277
+ "changed_functions": ["func_a", "func_b"],
278
+ "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other",
279
+ "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other",
280
+ "affected_types": ["GF_BitStream", "custom_struct_t"],
281
+ "critical_calls": ["gf_strdup", "memcpy"]
282
+ },
283
+ "detection_plan": {
284
+ "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')",
285
+ "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')",
286
+ "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')",
287
+ "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')"
288
+ },
289
+ "api_choice": {
290
+ "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow",
291
+ "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...",
292
+ "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions",
293
+ "alternatives_considered": ["check::PostCall"]
294
+ },
295
+ "implementation": {
296
+ "scope_level": "patch_specific | project_general | cross_project",
297
+ "checker_name": "project.CheckerName",
298
+ "build_attempts": 1
299
+ }
300
+ }
301
+ ```
302
+
303
+ ### ``summary.json``
304
+
305
+ ```json
306
+ {
307
+ "status": "plausible | failed",
308
+ "bug_pattern": "One sentence describing the bug pattern",
309
+ "scope_level": "patch_specific | project_general | cross_project",
310
+ "checker_cpp": "checker.cpp",
311
+ "checker_so": "checker.so",
312
+ "n_buggy": 0,
313
+ "n_patched": 0,
314
+ "total_reports": 0,
315
+ "fp_rate_estimate": 0.0,
316
+ "failure_reason": null
317
+ }
318
+ ```
319
+
320
+ ## Feedback-derived requirements for this fresh synthesis
321
+
322
+ A prior independent rollout exposed the risks below. Start again from the patch
323
+ in this new session. Do not reconstruct, edit, or assume the prior checker.
324
+
325
+ Required mechanism level: `control_flow`
326
+
327
+ ### Current failure diagnosis
328
+
329
+ - The prior rollout did not prove that a candidate condition constrains the accumulated output length; it accepted any relational comparison with an operand at least as large as the capacity.
330
+ - Source-order precedence was substituted for reachability and dominance, so a guard on another branch or a bypassable guard could incorrectly suppress a real overflow.
331
+ - Termination was recognized without proving comparison orientation or which successor reaches the writes; accepting arbitrary return, goto, break, or continue constructs made the safe condition unsound.
332
+ - Treating every nonliteral source as unbounded ignored the cumulative semantics of repeated concatenation, including argument lengths, separators, newline, and the terminating null byte.
333
+ - Process quality remained below threshold because validation included working-directory mistakes, an avoidable CSA API type error, unreliable scans with compile errors, and some weakly evidenced recovery steps.
334
+
335
+ ### Preserve from prior rollouts
336
+
337
+ - The new synthesis must compile successfully and pass before/after validation and code verification.
338
+ - Preserve objective eligibility gate G6.
339
+ - Preserve an accepted or clean refinement outcome.
340
+ - Maintain the semantic score at or above the configured threshold while correcting the semantic mechanism.
341
+ - Remain independent of patch anchors such as changed line numbers or exact diff locations.
342
+ - Remain free of patch-local hardcoding, including project-specific function, variable, file, or macro names.
343
+
344
+ ### Required semantic proof
345
+
346
+ - Report only when repeated unbounded string writes can reach a fixed-capacity destination without a proven bound on the total required bytes.
347
+ - Relate the checked quantity to the same accumulated length consumed by the writes, accounting for each source length, inserted separators, the final newline, and null termination.
348
+ - A suppressing guard must compare that accumulated requirement against the destination capacity with the correct operator and operand orientation.
349
+ - Prove through the CFG that the rejecting successor exits before every relevant write and that every path reaching those writes passed through the safe successor.
350
+ - For the patched structure, establish that completion of the length-accumulation loop and the condition len >= capacity imply len < capacity on all paths entering the later concatenation loop.
351
+ - Do not infer safety merely from a nonliteral source being preceded by some capacity-like comparison; absence or presence of the precise length-to-capacity relation controls the diagnostic.
352
+
353
+ ### Implementation constraints
354
+
355
+ - Use check::PreCall, or an equivalently local pre-write callback, for strcat/strcpy so destination and source arguments are available and the diagnostic is emitted at the unsafe call.
356
+ - Recover the destination extent from CSA region and type information, including an inlined caller's fixed array when observable, rather than from spelling or a literal capacity value.
357
+ - Use the enclosing AnalysisDeclContext CFG and dominance or equivalent all-path reachability reasoning; SourceManager ordering alone is insufficient.
358
+ - Identify the length accumulator by its data dependencies on strlen-derived source lengths and added delimiter costs, not by its identifier.
359
+ - Accept a guard only when its safe CFG edge dominates the relevant writes and its rejecting edge cannot rejoin before them.
360
+ - Resolve a size parameter to a concrete destination capacity only through semantic argument/type relationships such as sizeof of the same destination; do not guess from parameter position or value alone.
361
+ - Keep scope project-general around fixed-capacity destinations and standard unbounded string-copy or concatenation sinks, with no special treatment of ext-cmd.c, cmd_client, append_strings, buffer, len, bufsize, argv, or 256.
362
+ - Avoid persistent ProgramState traits or cross-function fact propagation unless CFG and call-context facts demonstrably cannot establish the required relation.
363
+
364
+ ### Validation checklist
365
+
366
+ - Build the new checker against the supplied LLVM/Clang API with no diagnostics and verify registration and loading before scanning.
367
+ - Run scans from verified working directories with the supplied include flags; reject any result in which either source version has a compile error or skipped file.
368
+ - Confirm exactly the relevant vulnerable-version diagnostic is produced and the patched version is clean, preserving N_buggy=1 and N_patched=0.
369
+ - Confirm the vulnerable diagnostic is located on the length-unknown strcat in cmd_client, at zero or comparably minimal distance from the changed vulnerable operation.
370
+ - Add focused negative tests showing that an unrelated large-constant comparison, reversed or permissive comparison, terminating wrong branch, source-ordered but bypassable guard, or nondominating guard does not establish safety.
371
+ - Add a positive safety test matching the patch semantics: accumulated strlen plus delimiter costs is rejected at or above the same buffer capacity before all concatenations.
372
+ - Run code verification and ensure no warnings disappear only in non-patched functions and no unrelated strcpy to a struct field is newly diagnosed outside the declared scope.
373
+ - Complete refinement with an accepted or clean outcome and retain objective gate G6 and the configured semantic-score threshold.
374
+
375
+ ### Avoid and forbidden regressions
376
+
377
+ - Do not reuse the failed heuristic of collecting arbitrary preceding IfStmt nodes and accepting any capacity-sized operand plus any syntactically nested terminator.
378
+ - Do not equate lexical source order with dominance, path reachability, or enforcement of a guard.
379
+ - Do not suppress on a comparison unless the checker proves accumulator identity, comparison direction, rejecting successor, and the path relationship to every sink.
380
+ - Do not use a pure strcat/strcpy syntax match or fixed-array plus nonliteral-source match; those patterns cannot distinguish the patched helper from the vulnerability.
381
+ - Do not introduce unnecessary caller-to-callee dataflow or symbolic-state machinery merely to recover a literal value when semantic CFG and argument relationships suffice.
382
+ - Do not rely on file paths, source lines, patch anchors, project identifiers, exact variable names, or the literal capacity 256.
383
+ - Do not count scans with parse failures, missing headers, invalid flags, or unverified recovery commands as validation evidence.
tasks/csa159/pair_135446/checker_template.cpp ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ============================================================================
2
+ // CSA Checker Template
3
+ // ============================================================================
4
+ // Fill in the sections marked with TODO to implement your checker.
5
+ // The checker is compiled with -fno-rtti to match the LLVM 18 build config.
6
+ // It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName
7
+ //
8
+ // Compilation:
9
+ // clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \
10
+ // -I${LLVM_BUILD_DIR}/include \
11
+ // checker.cpp -o checker.so \
12
+ // -Wl,--allow-shlib-undefined
13
+ //
14
+ // Usage:
15
+ // clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze <file>
16
+ // ============================================================================
17
+
18
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20
+ #include "clang/StaticAnalyzer/Core/Checker.h"
21
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23
+ #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
24
+
25
+ using namespace clang;
26
+ using namespace ento;
27
+
28
+ namespace {
29
+
30
+ // ────────────────────────────────────────────────────────────────
31
+ // TODO: Rename this class to describe your checker's purpose.
32
+ // ────────────────────────────────────────────────────────────────
33
+ class {{CHECKER_CLASS_NAME}}
34
+ : public Checker<check::PreCall, // for checking before function calls
35
+ check::PostCall> // for checking after function calls
36
+ {
37
+ // TODO: Customize the bug type name and category.
38
+ mutable std::unique_ptr<BugType> BT;
39
+
40
+ public:
41
+ {{CHECKER_CLASS_NAME}}()
42
+ : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {}
43
+
44
+ // ── PreCall callback (fires before every function call) ──────
45
+ void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
46
+ // TODO: Implement your pre-call analysis logic here.
47
+ //
48
+ // Common patterns:
49
+ //
50
+ // 1. Check if the called function matches a specific name:
51
+ // if (Call.getCalleeIdentifier()) {
52
+ // StringRef name = Call.getCalleeIdentifier()->getName();
53
+ // if (name == "target_function") { ... }
54
+ // }
55
+ //
56
+ // 2. Get the program state:
57
+ // ProgramStateRef State = C.getState();
58
+ //
59
+ // 3. Get arguments:
60
+ // SVal Arg = Call.getArgSVal(0);
61
+ //
62
+ // 4. Generate a bug report:
63
+ // ExplodedNode *ErrNode = C.generateErrorNode();
64
+ // if (ErrNode) {
65
+ // auto R = std::make_unique<PathSensitiveBugReport>(
66
+ // *BT, "Description of the bug", ErrNode);
67
+ // C.emitReport(std::move(R));
68
+ // }
69
+ }
70
+
71
+ // ── PostCall callback (fires after every function call) ─────
72
+ void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
73
+ // TODO: Implement your post-call analysis logic here.
74
+ //
75
+ // Common pattern — check the return value:
76
+ // SVal RetVal = Call.getReturnValue();
77
+ // if (RetVal.isUnknownOrUndef()) return;
78
+ //
79
+ // ProgramStateRef State = C.getState();
80
+ // // Modify state based on post-call conditions...
81
+ }
82
+ };
83
+
84
+ } // anonymous namespace
85
+
86
+ // ────────────────────────────────────────────────────────────────
87
+ // Registration — DO NOT modify the function signatures.
88
+ // ────────────────────────────────────────────────────────────────
89
+
90
+ extern "C" void clang_registerCheckers(CheckerRegistry &registry) {
91
+ registry.addChecker<{{CHECKER_CLASS_NAME}}>(
92
+ "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker"
93
+ "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference"
94
+ "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs"
95
+ }
96
+
97
+ extern "C" const char clang_analyzerAPIVersionString[] =
98
+ CLANG_ANALYZER_API_VERSION_STRING;
tasks/csa159/pair_135446/config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "project_id": "openSUSE_libsolv",
3
+ "before_commit": "926244b99d3261b3f60bd974612999a9c781a7ab",
4
+ "after_commit": "0077ef29eb46d2e1df2f230fc95a1d9748d49dec",
5
+ "repo_path": "/workspace/repo/openSUSE/libsolv",
6
+ "llvm_build_dir": "/opt/llvm",
7
+ "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/openSUSE_libsolv/7046fb004987c7f1b3722628d9a4ca1c67577188/compile_commands.json",
8
+ "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/openSUSE_libsolv/7046fb004987c7f1b3722628d9a4ca1c67577188/compile_commands.json",
9
+ "changed_files": [
10
+ "ext/testcase.c"
11
+ ],
12
+ "commit_message": "testcase_read: error out if repos are added or the system is changed too late\n\nWe must not add new solvables after the considered map was created, the solver\nwas created, or jobs were added. We may not changed the system after jobs have\nbeen added.\n\n(Jobs may point inside the whatproviedes array, so we must not invalidate this\narea.)",
13
+ "t_valid": 50,
14
+ "t_plausible": 20,
15
+ "triage_sample_size": 10,
16
+ "max_synthesis_retry": 0,
17
+ "max_in_session_redesigns": 1,
18
+ "max_refinement_iter": 3
19
+ }
tasks/csa159/pair_135446/patch.diff ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/ext/testcase.c b/ext/testcase.c
2
+ index 0be7a213..8fb6d793 100644
3
+ --- a/ext/testcase.c
4
+ +++ b/ext/testcase.c
5
+ @@ -1991,6 +1991,7 @@ testcase_read(Pool *pool, FILE *fp, const char *testcase, Queue *job, char **res
6
+ Id *genid = 0;
7
+ int ngenid = 0;
8
+ Queue autoinstq;
9
+ + int oldjobsize = job ? job->count : 0;
10
+
11
+ if (resultp)
12
+ *resultp = 0;
13
+ @@ -2065,6 +2066,21 @@ testcase_read(Pool *pool, FILE *fp, const char *testcase, Queue *job, char **res
14
+ int prio, subprio;
15
+ const char *rdata;
16
+
17
+ + if (pool->considered)
18
+ + {
19
+ + pool_error(pool, 0, "testcase_read: cannot add repos after packages were disabled");
20
+ + continue;
21
+ + }
22
+ + if (solv)
23
+ + {
24
+ + pool_error(pool, 0, "testcase_read: cannot add repos after the solver was created");
25
+ + continue;
26
+ + }
27
+ + if (job && job->count != oldjobsize)
28
+ + {
29
+ + pool_error(pool, 0, "testcase_read: cannot add repos after jobs have been created");
30
+ + continue;
31
+ + }
32
+ prepared = 0;
33
+ if (!poolflagsreset)
34
+ {
35
+ @@ -2125,6 +2141,11 @@ testcase_read(Pool *pool, FILE *fp, const char *testcase, Queue *job, char **res
36
+ int i;
37
+
38
+ /* must set the disttype before the arch */
39
+ + if (job && job->count != oldjobsize)
40
+ + {
41
+ + pool_error(pool, 0, "testcase_read: cannot change the system after jobs have been created");
42
+ + continue;
43
+ + }
44
+ prepared = 0;
45
+ if (strcmp(pieces[2], "*") != 0)
46
+ {
tasks/csa159/pair_135446/post_functions.txt ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: ext/testcase.c
2
+ ```c
3
+ Solver *
4
+ testcase_read(Pool *pool, FILE *fp, const char *testcase, Queue *job, char **resultp, int *resultflagsp)
5
+ {
6
+ Solver *solv;
7
+ char *buf, *bufp;
8
+ int bufl;
9
+ char *testcasedir, *s;
10
+ int l;
11
+ char **pieces = 0;
12
+ int npieces = 0;
13
+ int prepared = 0;
14
+ int closefp = !fp;
15
+ int poolflagsreset = 0;
16
+ int missing_features = 0;
17
+ Id *genid = 0;
18
+ int ngenid = 0;
19
+ Queue autoinstq;
20
+ int oldjobsize = job ? job->count : 0;
21
+
22
+ if (resultp)
23
+ *resultp = 0;
24
+ if (resultflagsp)
25
+ *resultflagsp = 0;
26
+ if (!fp && !(fp = fopen(testcase, "r")))
27
+ {
28
+ pool_error(pool, 0, "testcase_read: could not open '%s'", testcase);
29
+ return 0;
30
+ }
31
+ testcasedir = solv_strdup(testcase);
32
+ s = strrchr(testcasedir, '/');
33
+ #ifdef _WIN32
34
+ buf = strrchr(testcasedir, '\\');
35
+ if (!s || (buf && buf > s))
36
+ s = buf;
37
+ #endif
38
+ if (s)
39
+ s[1] = 0;
40
+ else
41
+ *testcasedir = 0;
42
+ bufl = 1024;
43
+ buf = solv_malloc(bufl);
44
+ bufp = buf;
45
+ solv = 0;
46
+ queue_init(&autoinstq);
47
+ for (;;)
48
+ {
49
+ if (bufp - buf + 16 > bufl)
50
+ {
51
+ bufl = bufp - buf;
52
+ buf = solv_realloc(buf, bufl + 512);
53
+ bufp = buf + bufl;
54
+ bufl += 512;
55
+ }
56
+ if (!fgets(bufp, bufl - (bufp - buf), fp))
57
+ break;
58
+ bufp = buf;
59
+ l = strlen(buf);
60
+ if (!l || buf[l - 1] != '\n')
61
+ {
62
+ bufp += l;
63
+ continue;
64
+ }
65
+ buf[--l] = 0;
66
+ s = buf;
67
+ while (*s && (*s == ' ' || *s == '\t'))
68
+ s++;
69
+ if (!*s || *s == '#')
70
+ continue;
71
+ npieces = 0;
72
+ /* split it in pieces */
73
+ for (;;)
74
+ {
75
+ while (*s == ' ' || *s == '\t')
76
+ s++;
77
+ if (!*s)
78
+ break;
79
+ pieces = solv_extend(pieces, npieces, 1, sizeof(*pieces), 7);
80
+ pieces[npieces++] = s;
81
+ while (*s && *s != ' ' && *s != '\t')
82
+ s++;
83
+ if (*s)
84
+ *s++ = 0;
85
+ }
86
+ pieces = solv_extend(pieces, npieces, 1, sizeof(*pieces), 7);
87
+ pieces[npieces] = 0;
88
+ if (!strcmp(pieces[0], "repo") && npieces >= 4)
89
+ {
90
+ Repo *repo = repo_create(pool, pieces[1]);
91
+ FILE *rfp;
92
+ int prio, subprio;
93
+ const char *rdata;
94
+
95
+ if (pool->considered)
96
+ {
97
+ pool_error(pool, 0, "testcase_read: cannot add repos after packages were disabled");
98
+ continue;
99
+ }
100
+ if (solv)
101
+ {
102
+ pool_error(pool, 0, "testcase_read: cannot add repos after the solver was created");
103
+ continue;
104
+ }
105
+ if (job && job->count != oldjobsize)
106
+ {
107
+ pool_error(pool, 0, "testcase_read: cannot add repos after jobs have been created");
108
+ continue;
109
+ }
110
+ prepared = 0;
111
+ if (!poolflagsreset)
112
+ {
113
+ poolflagsreset = 1;
114
+ testcase_resetpoolflags(pool); /* hmm */
115
+ }
116
+ if (sscanf(pieces[2], "%d.%d", &prio, &subprio) != 2)
117
+ {
118
+ subprio = 0;
119
+ prio = atoi(pieces[2]);
120
+ }
121
+ repo->priority = prio;
122
+ repo->subpriority = subprio;
123
+ if (strcmp(pieces[3], "empty") != 0)
124
+ {
125
+ const char *repotype = pool_tmpjoin(pool, pieces[3], 0, 0); /* gets overwritten in <inline> case */
126
+ if (!strcmp(pieces[4], "<inline>"))
127
+ {
128
+ char *idata = read_inline_file(fp, &buf, &bufp, &bufl);
129
+ rdata = "<inline>";
130
+ rfp = solv_fmemopen(idata, strlen(idata), "rf");
131
+ }
132
+ else
133
+ {
134
+ rdata = pool_tmpjoin(pool, testcasedir, pieces[4], 0);
135
+ rfp = solv_xfopen(rdata, "r");
136
+ }
137
+ if (!rfp)
138
+ {
139
+ pool_error(pool, 0, "testcase_read: could not open '%s'", rdata);
140
+ }
141
+ else if (!strcmp(repotype, "testtags"))
142
+ {
143
+ testcase_add_testtags(repo, rfp, 0);
144
+ fclose(rfp);
145
+ }
146
+ else if (!strcmp(repotype, "solv"))
147
+ {
148
+ repo_add_solv(repo, rfp, 0);
149
+ fclose(rfp);
150
+ }
151
+ #if ENABLE_TESTCASE_HELIXREPO
152
+ else if (!strcmp(repotype, "helix"))
153
+ {
154
+ repo_add_helix(repo, rfp, 0);
155
+ fclose(rfp);
156
+ }
157
+ #endif
158
+ else
159
+ {
160
+ fclose(rfp);
161
+ pool_error(pool, 0, "testcase_read: unknown repo type for repo '%s'", repo->name);
162
+ }
163
+ }
164
+ }
165
+ else if (!strcmp(pieces[0], "system") && npieces >= 3)
166
+ {
167
+ int i;
168
+
169
+ /* must set the disttype before the arch */
170
+ if (job && job->count != oldjobsize)
171
+ {
172
+ pool_error(pool, 0, "testcase_read: cannot change the system after jobs have been created");
173
+ continue;
174
+ }
175
+ prepared = 0;
176
+ if (strcmp(pieces[2], "*") != 0)
177
+ {
178
+ char *dp = pieces[2];
179
+ while (dp && *dp)
180
+ {
181
+ char *dpe = strchr(dp, ',');
182
+ if (dpe)
183
+ *dpe = 0;
184
+ for (i = 0; disttype2str[i].str != 0; i++)
185
+ if (!strcmp(disttype2str[i].str, dp))
186
+ break;
187
+ if (dpe)
188
+ *dpe++ = ',';
189
+ if (disttype2str[i].str)
190
+ {
191
+ #ifdef MULTI_SEMANTICS
192
+ if (pool->disttype != disttype2str[i].type)
193
+ pool_setdisttype(pool, disttype2str[i].type);
194
+ #endif
195
+ if (pool->disttype == disttype2str[i].type)
196
+ break;
197
+ }
198
+ dp = dpe;
199
+ }
200
+ if (!(dp && *dp))
201
+ {
202
+ pool_error(pool, 0, "testcase_read: system: could not change disttype to '%s'", pieces[2]);
203
+ missing_features = 1;
204
+ }
205
+ }
206
+ if (strcmp(pieces[1], "unset") == 0 || strcmp(pieces[1], "-") == 0)
207
+ pool_setarch(pool, 0);
208
+ else if (pieces[1][0] == ':')
209
+ pool_setarchpolicy(pool, pieces[1] + 1);
210
+ else
211
+ pool_setarch(pool, pieces[1]);
212
+ if (npieces > 3)
213
+ {
214
+ Repo *repo = testcase_str2repo(pool, pieces[3]);
215
+ if (!repo)
216
+ pool_error(pool, 0, "testcase_read: system: unknown repo '%s'", pieces[3]);
217
+ else
218
+ pool_set_installed(pool, repo);
219
+ }
220
+ }
221
+ else if (!strcmp(pieces[0], "job") && npieces > 1)
222
+ {
223
+ char *sp;
224
+ Id how, what;
225
+ if (prepared <= 0)
226
+ {
227
+ pool_addfileprovides(pool);
228
+ pool_createwhatprovides(pool);
229
+ prepared = 1;
230
+ }
231
+ if (npieces >= 3 && !strcmp(pieces[2], "selection"))
232
+ {
233
+ addselectionjob(pool, pieces + 1, npieces - 1, job, 0, 0);
234
+ continue;
235
+ }
236
+ if (npieces >= 4 && !strcmp(pieces[2], "selection_matchdeps"))
237
+ {
238
+ pieces[2] = pieces[1];
239
+ addselectionjob(pool, pieces + 2, npieces - 2, job, SELECTIONJOB_MATCHDEPS, pool_str2id(pool, pieces[3], 1));
240
+ continue;
241
+ }
242
+ if (npieces >= 4 && !strcmp(pieces[2], "selection_matchdepid"))
243
+ {
244
+ pieces[2] = pieces[1];
245
+ addselectionjob(pool, pieces + 2, npieces - 2, job, SELECTIONJOB_MATCHDEPID, pool_str2id(pool, pieces[3], 1));
246
+ continue;
247
+ }
248
+ if (npieces >= 4 && !strcmp(pieces[2], "selection_matchsolvable"))
249
+ {
250
+ pieces[2] = pieces[1];
251
+ addselectionjob(pool, pieces + 2, npieces - 2, job, SELECTIONJOB_MATCHSOLVABLE, pool_str2id(pool, pieces[3], 1));
252
+ continue;
253
+ }
254
+ /* rejoin */
255
+ for (sp = pieces[1]; sp < pieces[npieces - 1]; sp++)
256
+ if (*sp == 0)
257
+ *sp = ' ';
258
+ how = testcase_str2job(pool, pieces[1], &what);
259
+ if (how >= 0 && job)
260
+ queue_push2(job, how, what);
261
+ }
262
+ else if (!strcmp(pieces[0], "vendorclass") && npieces > 1)
263
+ {
264
+ pool_addvendorclass(pool, (const char **)(pieces + 1));
265
+ }
266
+ else if (!strcmp(pieces[0], "namespace") && npieces > 1)
267
+ {
268
+ int i = strlen(pieces[1]);
269
+ s = strchr(pieces[1], '(');
270
+ if (!s || pieces[1][i - 1] != ')')
271
+ {
272
+ pool_error(pool, 0, "testcase_read: bad namespace '%s'", pieces[1]);
273
+ }
274
+ else
275
+ {
276
+ Id name, evr, id;
277
+ Queue q;
278
+ queue_init(&q);
279
+ *s = 0;
280
+ pieces[1][i - 1] = 0;
281
+ name = pool_str2id(pool, pieces[1], 1);
282
+ evr = pool_str2id(pool, s + 1, 1);
283
+ *s = '(';
284
+ pieces[1][i - 1] = ')';
285
+ id = pool_rel2id(pool, name, evr, REL_NAMESPACE, 1);
286
+ for (i = 2; i < npieces; i++)
287
+ queue_push(&q, testcase_str2solvid(pool, pieces[i]));
288
+ /* now do the callback */
289
+ if (prepared <= 0)
290
+ {
291
+ pool_addfileprovides(pool);
292
+ pool_createwhatprovides(pool);
293
+ prepared = 1;
294
+ }
295
+ pool->whatprovides_rel[GETRELID(id)] = pool_queuetowhatprovides(pool, &q);
296
+ queue_free(&q);
297
+ }
298
+ }
299
+ else if (!strcmp(pieces[0], "poolflags"))
300
+ {
301
+ int i;
302
+ if (!poolflagsreset)
303
+ {
304
+ poolflagsreset = 1;
305
+ testcase_resetpoolflags(pool); /* hmm */
306
+ }
307
+ for (i = 1; i < npieces; i++)
308
+ testcase_setpoolflags(pool, pieces[i]);
309
+ }
310
+ else if
311
+
312
+ // ... (5039 more chars)
313
+ ```
tasks/csa159/pair_135446/pre_functions.txt ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: ext/testcase.c
2
+ ```c
3
+ Solver *
4
+ testcase_read(Pool *pool, FILE *fp, const char *testcase, Queue *job, char **resultp, int *resultflagsp)
5
+ {
6
+ Solver *solv;
7
+ char *buf, *bufp;
8
+ int bufl;
9
+ char *testcasedir, *s;
10
+ int l;
11
+ char **pieces = 0;
12
+ int npieces = 0;
13
+ int prepared = 0;
14
+ int closefp = !fp;
15
+ int poolflagsreset = 0;
16
+ int missing_features = 0;
17
+ Id *genid = 0;
18
+ int ngenid = 0;
19
+ Queue autoinstq;
20
+
21
+ if (resultp)
22
+ *resultp = 0;
23
+ if (resultflagsp)
24
+ *resultflagsp = 0;
25
+ if (!fp && !(fp = fopen(testcase, "r")))
26
+ {
27
+ pool_error(pool, 0, "testcase_read: could not open '%s'", testcase);
28
+ return 0;
29
+ }
30
+ testcasedir = solv_strdup(testcase);
31
+ s = strrchr(testcasedir, '/');
32
+ #ifdef _WIN32
33
+ buf = strrchr(testcasedir, '\\');
34
+ if (!s || (buf && buf > s))
35
+ s = buf;
36
+ #endif
37
+ if (s)
38
+ s[1] = 0;
39
+ else
40
+ *testcasedir = 0;
41
+ bufl = 1024;
42
+ buf = solv_malloc(bufl);
43
+ bufp = buf;
44
+ solv = 0;
45
+ queue_init(&autoinstq);
46
+ for (;;)
47
+ {
48
+ if (bufp - buf + 16 > bufl)
49
+ {
50
+ bufl = bufp - buf;
51
+ buf = solv_realloc(buf, bufl + 512);
52
+ bufp = buf + bufl;
53
+ bufl += 512;
54
+ }
55
+ if (!fgets(bufp, bufl - (bufp - buf), fp))
56
+ break;
57
+ bufp = buf;
58
+ l = strlen(buf);
59
+ if (!l || buf[l - 1] != '\n')
60
+ {
61
+ bufp += l;
62
+ continue;
63
+ }
64
+ buf[--l] = 0;
65
+ s = buf;
66
+ while (*s && (*s == ' ' || *s == '\t'))
67
+ s++;
68
+ if (!*s || *s == '#')
69
+ continue;
70
+ npieces = 0;
71
+ /* split it in pieces */
72
+ for (;;)
73
+ {
74
+ while (*s == ' ' || *s == '\t')
75
+ s++;
76
+ if (!*s)
77
+ break;
78
+ pieces = solv_extend(pieces, npieces, 1, sizeof(*pieces), 7);
79
+ pieces[npieces++] = s;
80
+ while (*s && *s != ' ' && *s != '\t')
81
+ s++;
82
+ if (*s)
83
+ *s++ = 0;
84
+ }
85
+ pieces = solv_extend(pieces, npieces, 1, sizeof(*pieces), 7);
86
+ pieces[npieces] = 0;
87
+ if (!strcmp(pieces[0], "repo") && npieces >= 4)
88
+ {
89
+ Repo *repo = repo_create(pool, pieces[1]);
90
+ FILE *rfp;
91
+ int prio, subprio;
92
+ const char *rdata;
93
+
94
+ prepared = 0;
95
+ if (!poolflagsreset)
96
+ {
97
+ poolflagsreset = 1;
98
+ testcase_resetpoolflags(pool); /* hmm */
99
+ }
100
+ if (sscanf(pieces[2], "%d.%d", &prio, &subprio) != 2)
101
+ {
102
+ subprio = 0;
103
+ prio = atoi(pieces[2]);
104
+ }
105
+ repo->priority = prio;
106
+ repo->subpriority = subprio;
107
+ if (strcmp(pieces[3], "empty") != 0)
108
+ {
109
+ const char *repotype = pool_tmpjoin(pool, pieces[3], 0, 0); /* gets overwritten in <inline> case */
110
+ if (!strcmp(pieces[4], "<inline>"))
111
+ {
112
+ char *idata = read_inline_file(fp, &buf, &bufp, &bufl);
113
+ rdata = "<inline>";
114
+ rfp = solv_fmemopen(idata, strlen(idata), "rf");
115
+ }
116
+ else
117
+ {
118
+ rdata = pool_tmpjoin(pool, testcasedir, pieces[4], 0);
119
+ rfp = solv_xfopen(rdata, "r");
120
+ }
121
+ if (!rfp)
122
+ {
123
+ pool_error(pool, 0, "testcase_read: could not open '%s'", rdata);
124
+ }
125
+ else if (!strcmp(repotype, "testtags"))
126
+ {
127
+ testcase_add_testtags(repo, rfp, 0);
128
+ fclose(rfp);
129
+ }
130
+ else if (!strcmp(repotype, "solv"))
131
+ {
132
+ repo_add_solv(repo, rfp, 0);
133
+ fclose(rfp);
134
+ }
135
+ #if ENABLE_TESTCASE_HELIXREPO
136
+ else if (!strcmp(repotype, "helix"))
137
+ {
138
+ repo_add_helix(repo, rfp, 0);
139
+ fclose(rfp);
140
+ }
141
+ #endif
142
+ else
143
+ {
144
+ fclose(rfp);
145
+ pool_error(pool, 0, "testcase_read: unknown repo type for repo '%s'", repo->name);
146
+ }
147
+ }
148
+ }
149
+ else if (!strcmp(pieces[0], "system") && npieces >= 3)
150
+ {
151
+ int i;
152
+
153
+ /* must set the disttype before the arch */
154
+ prepared = 0;
155
+ if (strcmp(pieces[2], "*") != 0)
156
+ {
157
+ char *dp = pieces[2];
158
+ while (dp && *dp)
159
+ {
160
+ char *dpe = strchr(dp, ',');
161
+ if (dpe)
162
+ *dpe = 0;
163
+ for (i = 0; disttype2str[i].str != 0; i++)
164
+ if (!strcmp(disttype2str[i].str, dp))
165
+ break;
166
+ if (dpe)
167
+ *dpe++ = ',';
168
+ if (disttype2str[i].str)
169
+ {
170
+ #ifdef MULTI_SEMANTICS
171
+ if (pool->disttype != disttype2str[i].type)
172
+ pool_setdisttype(pool, disttype2str[i].type);
173
+ #endif
174
+ if (pool->disttype == disttype2str[i].type)
175
+ break;
176
+ }
177
+ dp = dpe;
178
+ }
179
+ if (!(dp && *dp))
180
+ {
181
+ pool_error(pool, 0, "testcase_read: system: could not change disttype to '%s'", pieces[2]);
182
+ missing_features = 1;
183
+ }
184
+ }
185
+ if (strcmp(pieces[1], "unset") == 0 || strcmp(pieces[1], "-") == 0)
186
+ pool_setarch(pool, 0);
187
+ else if (pieces[1][0] == ':')
188
+ pool_setarchpolicy(pool, pieces[1] + 1);
189
+ else
190
+ pool_setarch(pool, pieces[1]);
191
+ if (npieces > 3)
192
+ {
193
+ Repo *repo = testcase_str2repo(pool, pieces[3]);
194
+ if (!repo)
195
+ pool_error(pool, 0, "testcase_read: system: unknown repo '%s'", pieces[3]);
196
+ else
197
+ pool_set_installed(pool, repo);
198
+ }
199
+ }
200
+ else if (!strcmp(pieces[0], "job") && npieces > 1)
201
+ {
202
+ char *sp;
203
+ Id how, what;
204
+ if (prepared <= 0)
205
+ {
206
+ pool_addfileprovides(pool);
207
+ pool_createwhatprovides(pool);
208
+ prepared = 1;
209
+ }
210
+ if (npieces >= 3 && !strcmp(pieces[2], "selection"))
211
+ {
212
+ addselectionjob(pool, pieces + 1, npieces - 1, job, 0, 0);
213
+ continue;
214
+ }
215
+ if (npieces >= 4 && !strcmp(pieces[2], "selection_matchdeps"))
216
+ {
217
+ pieces[2] = pieces[1];
218
+ addselectionjob(pool, pieces + 2, npieces - 2, job, SELECTIONJOB_MATCHDEPS, pool_str2id(pool, pieces[3], 1));
219
+ continue;
220
+ }
221
+ if (npieces >= 4 && !strcmp(pieces[2], "selection_matchdepid"))
222
+ {
223
+ pieces[2] = pieces[1];
224
+ addselectionjob(pool, pieces + 2, npieces - 2, job, SELECTIONJOB_MATCHDEPID, pool_str2id(pool, pieces[3], 1));
225
+ continue;
226
+ }
227
+ if (npieces >= 4 && !strcmp(pieces[2], "selection_matchsolvable"))
228
+ {
229
+ pieces[2] = pieces[1];
230
+ addselectionjob(pool, pieces + 2, npieces - 2, job, SELECTIONJOB_MATCHSOLVABLE, pool_str2id(pool, pieces[3], 1));
231
+ continue;
232
+ }
233
+ /* rejoin */
234
+ for (sp = pieces[1]; sp < pieces[npieces - 1]; sp++)
235
+ if (*sp == 0)
236
+ *sp = ' ';
237
+ how = testcase_str2job(pool, pieces[1], &what);
238
+ if (how >= 0 && job)
239
+ queue_push2(job, how, what);
240
+ }
241
+ else if (!strcmp(pieces[0], "vendorclass") && npieces > 1)
242
+ {
243
+ pool_addvendorclass(pool, (const char **)(pieces + 1));
244
+ }
245
+ else if (!strcmp(pieces[0], "namespace") && npieces > 1)
246
+ {
247
+ int i = strlen(pieces[1]);
248
+ s = strchr(pieces[1], '(');
249
+ if (!s || pieces[1][i - 1] != ')')
250
+ {
251
+ pool_error(pool, 0, "testcase_read: bad namespace '%s'", pieces[1]);
252
+ }
253
+ else
254
+ {
255
+ Id name, evr, id;
256
+ Queue q;
257
+ queue_init(&q);
258
+ *s = 0;
259
+ pieces[1][i - 1] = 0;
260
+ name = pool_str2id(pool, pieces[1], 1);
261
+ evr = pool_str2id(pool, s + 1, 1);
262
+ *s = '(';
263
+ pieces[1][i - 1] = ')';
264
+ id = pool_rel2id(pool, name, evr, REL_NAMESPACE, 1);
265
+ for (i = 2; i < npieces; i++)
266
+ queue_push(&q, testcase_str2solvid(pool, pieces[i]));
267
+ /* now do the callback */
268
+ if (prepared <= 0)
269
+ {
270
+ pool_addfileprovides(pool);
271
+ pool_createwhatprovides(pool);
272
+ prepared = 1;
273
+ }
274
+ pool->whatprovides_rel[GETRELID(id)] = pool_queuetowhatprovides(pool, &q);
275
+ queue_free(&q);
276
+ }
277
+ }
278
+ else if (!strcmp(pieces[0], "poolflags"))
279
+ {
280
+ int i;
281
+ if (!poolflagsreset)
282
+ {
283
+ poolflagsreset = 1;
284
+ testcase_resetpoolflags(pool); /* hmm */
285
+ }
286
+ for (i = 1; i < npieces; i++)
287
+ testcase_setpoolflags(pool, pieces[i]);
288
+ }
289
+ else if (!strcmp(pieces[0], "solverflags") && npieces > 1)
290
+ {
291
+ int i;
292
+ if (!solv)
293
+ {
294
+ solv = solver_create(pool);
295
+ testcase_resetsolverflags(solv);
296
+ }
297
+ for (i = 1; i < npieces; i++)
298
+ testcase_setsolverflags(solv, pieces[i]);
299
+ }
300
+ else if (!strcmp(pieces[0], "result") && npieces > 1)
301
+ {
302
+ char *result = 0;
303
+ int resultflags = str2resultflags(pool, pieces[1]);
304
+ const char *rdata;
305
+ if (npieces > 2)
306
+ {
307
+ rdata = pool_tmpjoin(pool, testcasedir, pieces[2], 0);
308
+ if (!strcmp(pieces[2], "<inline>"))
309
+ result = read_inline_file(fp, &buf, &bufp, &bufl);
310
+ else
311
+ {
312
+ FILE *rfp = fopen(rdata, "r")
313
+
314
+ // ... (4380 more chars)
315
+ ```
tasks/csa159/pair_135446/task_prompt.md ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Task: Synthesize a CSA Checker from a CVE Patch
2
+
3
+ ## Your Role
4
+
5
+ You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker
6
+ that detects the bug pattern fixed by the CVE patch in this working directory.
7
+
8
+ You have full filesystem and bash access — use them.
9
+
10
+ ### Skills
11
+
12
+ Many skills are available under `.claude/skills/` — covering vulnerability analysis,
13
+ checker design, debugging, code audit, security patterns, and more. Each skill
14
+ encodes reusable expertise: take time to explore them, read their SKILL.md files,
15
+ and invoke those that look useful via the Skill tool. Let the task guide which
16
+ ones you reach for.
17
+
18
+ ## File Layout
19
+
20
+ ```
21
+ /work/
22
+ ├── compile.sh ← RUN ME: compile checker.cpp → checker.so
23
+ ├── checker_template.cpp ← skeleton, start here
24
+ ├── patch.diff ← the CVE fix
25
+ ├── pre_functions.txt ← buggy source (before_commit)
26
+ ├── post_functions.txt ← patched source (after_commit)
27
+ ├── config.json ← paths, commit_message, commit hashes, flags
28
+ ├── scan/
29
+ │ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy
30
+ │ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched
31
+ │ └── flags_*.txt ← pre-extracted compile flags (-I, -D)
32
+ ├── references/
33
+ │ ├── repo_knowledge.md ← project-specific API/convention reference
34
+ │ ├── patterns_summary.md ← (optional) historical bug pattern summary
35
+ │ ├── cwe_cards/ ← CWE knowledge library (all categories)
36
+ │ │ ├── index.json ← lookup index — use to find relevant cards
37
+ │ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns
38
+ │ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped)
39
+ │ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers)
40
+ │ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.)
41
+ │ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.)
42
+ │ └── examples/
43
+ │ └── llvm-official/ ← 5 official checker sources (with comments)
44
+ │ ├── 01_div_zero.cpp
45
+ │ ├── 02_simple_stream.cpp
46
+ │ ├── 03_undef_result.cpp
47
+ │ ├── 04_nullability.cpp
48
+ │ └── 05_malloc.cpp
49
+ │
50
+ ├── checker.cpp ← YOUR OUTPUT: synthesized checker
51
+ ├── checker.so ← YOUR OUTPUT: compiled checker
52
+ ├── state.json ← YOUR OUTPUT: structured task state
53
+ ├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3)
54
+ └── summary.json ← YOUR OUTPUT: final report
55
+ ```
56
+
57
+ ## Resources
58
+
59
+ **Read these before writing any code:**
60
+
61
+ 1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from
62
+ LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types,
63
+ MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.**
64
+
65
+ 2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested
66
+ patterns from official LLVM checkers: resource tracking, null checking, undefined
67
+ value detection, division-by-zero, and malloc/free. Each pattern includes skeleton
68
+ code, state traits, and key API usage.
69
+
70
+ 3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations
71
+ with explanatory comments:
72
+ - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback)
73
+ - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose)
74
+ - `03_undef_result.cpp` — PostStmt pattern (160 lines)
75
+ - `04_nullability.cpp` — multi-callback checker (1247 lines)
76
+ - `05_malloc.cpp` — comprehensive malloc/free (1511 lines)
77
+
78
+ 4. **`checker_template.cpp`** — Skeleton with placeholders. Start here.
79
+
80
+ 5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this
81
+ repository's memory allocation API, key data types, source layout, and typical
82
+ CVE patterns. **Read this before writing the checker** — knowing the project's
83
+ alloc/free conventions and common bug patterns saves many grep rounds.
84
+
85
+ 5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis
86
+ patterns for this project. If present, it contains a concise summary of the
87
+ most common bug patterns, frequent CWE categories, and reusable checker
88
+ architectures observed in previous synthesis runs. Read after repo_knowledge.md.
89
+
90
+ 6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all
91
+ vulnerability categories. **The framework provides the full library —
92
+ you must identify the vulnerability type yourself.** Workflow:
93
+
94
+ 1. Analyse the patch diff and commit message to determine the vulnerability
95
+ type (buffer overflow, UAF, null deref, integer overflow, race condition,
96
+ etc.). Do NOT rely on the CWE label — treat it as a hint at most.
97
+ 2. Open ``index.json`` to discover available cards and their tiers.
98
+ 3. Read the relevant card(s) for **detection strategies**, **checker
99
+ architecture suggestions**, and **known false-positive patterns**.
100
+
101
+ Card tiers:
102
+ - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel /
103
+ userspace variants when the detection strategy differs substantially.
104
+ - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by
105
+ category (input validation, resource management, etc.).
106
+
107
+ 7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for
108
+ checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`),
109
+ expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string
110
+ size extraction, MemRegion helpers, and `ExprHasName()` for robust function
111
+ matching. All verified against LLVM 18. **Read before implementing detection
112
+ logic** — these save writing boilerplate that's easy to get wrong.
113
+
114
+ ## Environment
115
+
116
+ Key paths are in ``config.json``.
117
+
118
+ ### Pre-built scripts
119
+
120
+ | Script | What it does |
121
+ |--------|-------------|
122
+ | `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) |
123
+ | `CHECKER_NAME=<name> bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy |
124
+ | `CHECKER_NAME=<name> bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched |
125
+
126
+ ```bash
127
+ # Compile (run from workdir root)
128
+ bash compile.sh
129
+
130
+ # Scan — set CHECKER_NAME to the string passed to addChecker<>()
131
+ CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy
132
+ CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched
133
+ ```
134
+
135
+ - ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags.
136
+ - ``scan/scan_*.sh`` count only warnings tagged with your checker name.
137
+ - Scan environments (source files + compile flags) are pre-built in ``scan/``.
138
+
139
+ ### Scan Script Integrity (CRITICAL)
140
+
141
+ The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only
142
+ valid measurement** of N_buggy and N_patched. They are the ground truth that the
143
+ Python-side validator will also use. You MUST obey these rules:
144
+
145
+ **1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly
146
+ to measure warning counts. The Python validator runs the same scan scripts
147
+ — if you measured with a different command, your numbers will not reproduce
148
+ and the synthesis will be rejected.
149
+
150
+ **2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared
151
+ identifiers, etc.), the scan environment needs repair. You MUST fix it:
152
+ - Add missing ``-I`` include paths to the flags files in ``scan/``
153
+ - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot
154
+ - If the file fundamentally cannot be compiled by clang, stop and write
155
+ ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason``
156
+
157
+ **3. Only trust scan script output.** The ``Total <name> warnings: N`` line
158
+ printed by the scan script is the number that goes into ``summary.json``.
159
+ If the scan script says 0, write 0. Fabricating numbers that the scan
160
+ script did not produce will cause the Python validator to reject the
161
+ synthesis.
162
+
163
+ - If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles).
164
+ - If validation fails: revise checker logic, re-compile, re-scan.
165
+
166
+ ## MCP Tools
167
+
168
+ You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`).
169
+ Each returns **source context embedded in the result** — no need to follow up with Read.
170
+
171
+ | Tool | What it does | Key advantage |
172
+ |------|-------------|---------------|
173
+ | `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call |
174
+ | `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file |
175
+ | `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed |
176
+
177
+ ### When to use each
178
+
179
+ - **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure.
180
+ - **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines.
181
+ - **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action.
182
+
183
+ ## Semantic Design Contract — before writing checker.cpp
184
+
185
+ Create the analysis portions of `state.json` and `scope_statement.md` **before**
186
+ writing checker.cpp. They are a design contract, not a retrospective summary.
187
+ After compilation, update only implementation facts such as `build_attempts`.
188
+
189
+ In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the
190
+ semantic fact introduced by the patch that makes it safe. In `detection_plan`,
191
+ make `report_condition`, `safe_condition`, and `source_level_signal` concrete
192
+ CSA-observable facts. In `api_choice`, record the mechanism level and explain
193
+ why the selected callback can observe and prove those facts.
194
+
195
+ In `scope_statement.md`, include this mapping table and check it again after
196
+ implementation:
197
+
198
+ | Semantic condition | CSA evidence | checker.cpp implementation |
199
+ | --- | --- | --- |
200
+ | report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports |
201
+ | safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report |
202
+
203
+ Every condition in the plan must have an implementation entry. Do not claim a
204
+ condition that checker.cpp does not implement, and do not silently add a code
205
+ condition absent from the plan.
206
+
207
+ ## Mechanism Selection — diagnose before coding
208
+
209
+ Choose the weakest CSA mechanism that can prove the vulnerability property:
210
+
211
+ 1. **syntax-only AST**: only when local AST shape itself is the defect;
212
+ 2. **control flow / dominance**: when guard placement relative to a sink matters;
213
+ 3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use;
214
+ 4. **cross-procedure/dataflow**: when the required fact crosses function boundaries.
215
+
216
+ For a guard-based patch, prove both that the guard rejects the unsafe value and
217
+ that it dominates the vulnerable use. For path-sensitive or cross-procedure
218
+ defects, do not replace the required state or flow proof with local AST matching
219
+ or source-text substring matching merely because it passes the differential scan.
220
+ Record the selected level as `api_choice.mechanism_level`.
221
+
222
+ ## Semantic identity, locality, and final validation
223
+
224
+ Before accepting the checker, verify that its primary matching logic does not
225
+ depend on patch-local variable names, labels, line numbers, commit IDs, or unique
226
+ literals. Project APIs, types, and stable semantic call relationships are valid
227
+ scope anchors when they define the vulnerability class. Attach the report to the
228
+ actual vulnerable operation, and implement every suppression as a real safe
229
+ condition rather than the mere presence of a nearby guard-shaped statement.
230
+
231
+ The required final sequence is: **compile → before scan → after scan → inspect
232
+ the final checker name, artifacts, and report locations → write summary.json**.
233
+ Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only
234
+ additional redesign cycles after a failed validation; if it is zero, preserve the
235
+ real validation evidence and report failure honestly rather than fabricating counts.
236
+
237
+ ## Validation Criteria
238
+
239
+ ```
240
+ VALID : N_buggy > N_patched AND N_patched < 50
241
+ INVALID : otherwise → revise and re-validate (max 1 attempts)
242
+ ```
243
+
244
+ ## Refinement
245
+
246
+ Do NOT self-refine the checker repeatedly. Your goal is to produce the first
247
+ checker that passes the Validation Criteria above — fix compile errors and
248
+ validation failures only. False positives are triaged and repaired by the
249
+ framework's refinement stage: you will receive a concrete FP list via
250
+ session resume (if needed) and fix only those. Reserve budget for that stage.
251
+
252
+ ## Output
253
+
254
+ Produce all of the following **only when completely done**:
255
+
256
+ | File | Content |
257
+ |------|---------|
258
+ | ``checker.cpp`` | Synthesized checker source code |
259
+ | ``checker.so`` | Compiled checker plugin |
260
+ | ``state.json`` | Structured task state (see schema below) |
261
+ | ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) |
262
+ | ``summary.json`` | Final report (see schema below) |
263
+
264
+ Writing ``summary.json`` signals completion. Do NOT write it early.
265
+
266
+ ### ``state.json``
267
+
268
+ Create this before writing checker.cpp to capture the design contract. After the
269
+ checker compiles, update only implementation facts and retain the original
270
+ semantic plan.
271
+
272
+ ```json
273
+ {
274
+ "patch_analysis": {
275
+ "summary": "One sentence describing the vulnerability this patch fixes",
276
+ "changed_files": ["file1.c", "file2.h"],
277
+ "changed_functions": ["func_a", "func_b"],
278
+ "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other",
279
+ "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other",
280
+ "affected_types": ["GF_BitStream", "custom_struct_t"],
281
+ "critical_calls": ["gf_strdup", "memcpy"]
282
+ },
283
+ "detection_plan": {
284
+ "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')",
285
+ "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')",
286
+ "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')",
287
+ "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')"
288
+ },
289
+ "api_choice": {
290
+ "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow",
291
+ "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...",
292
+ "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions",
293
+ "alternatives_considered": ["check::PostCall"]
294
+ },
295
+ "implementation": {
296
+ "scope_level": "patch_specific | project_general | cross_project",
297
+ "checker_name": "project.CheckerName",
298
+ "build_attempts": 1
299
+ }
300
+ }
301
+ ```
302
+
303
+ ### ``summary.json``
304
+
305
+ ```json
306
+ {
307
+ "status": "plausible | failed",
308
+ "bug_pattern": "One sentence describing the bug pattern",
309
+ "scope_level": "patch_specific | project_general | cross_project",
310
+ "checker_cpp": "checker.cpp",
311
+ "checker_so": "checker.so",
312
+ "n_buggy": 0,
313
+ "n_patched": 0,
314
+ "total_reports": 0,
315
+ "fp_rate_estimate": 0.0,
316
+ "failure_reason": null
317
+ }
318
+ ```
319
+
320
+ ## Feedback-derived requirements for this fresh synthesis
321
+
322
+ A prior independent rollout exposed the risks below. Start again from the patch
323
+ in this new session. Do not reconstruct, edit, or assume the prior checker.
324
+
325
+ Required mechanism level: `control_flow`
326
+
327
+ ### Current failure diagnosis
328
+
329
+ - Path-sensitive ProgramState traits never became true: testcase_read dispatches on opaque fgets/strcmp of FILE input, so CSA never explores one exploded path that both enqueues jobs (or creates the solver / stores pool->considered) and later reaches a repo/system sink.
330
+ - scan_before produced n_buggy=0 on the buggy tree, so hard_validation, objective_gate (G3), semantic_mechanism, semantic_score, process_score, and refinement_accepted all failed; refinement was not run.
331
+ - JobsAdded/SolverSym/ConsideredSym could not survive the parse-loop back-edge, so PreCall sink predicates stayed false even though the sources and sinks are present in the same function.
332
+ - repo_create was treated as a repo sink even though the patch still calls it before the new continue-guards, so that sink choice cannot separate buggy from patched even if state tracking had worked.
333
+
334
+ ### Preserve from prior rollouts
335
+
336
+ - Do not introduce patch-anchor dependence.
337
+ - Do not introduce patch-local hardcoding.
338
+
339
+ ### Required semantic proof
340
+
341
+ - In testcase_read's parse loop, a job-queue write (addselectionjob or queue_push2 on the caller Queue*), solver_create, or a store to pool->considered can CFG-reach a later repo-content or system-change sink via the loop back-edge.
342
+ - Repo-content sinks are testcase_add_testtags, repo_add_solv, and repo_add_helix (the operations after the patch continue-guards), not repo_create which still executes before those guards.
343
+ - System-change sinks are pool_setarch, pool_setarchpolicy, and pool_set_installed.
344
+ - A finding requires that the sink is not dominated by a continue-guard on pool->considered, a non-null solv, or a job-queue count that differs from its function-entry value.
345
+ - Patched code is safe because those continue-guards dominate the sinks; buggy code has the same sinks with no such dominating guards.
346
+
347
+ ### Implementation constraints
348
+
349
+ - Walk the CFG/AST of functions that both mutate a Queue* job parameter and call repo-add or system-change APIs (checkASTCodeBody or equivalent); do not rely on ProgramState facts surviving I/O-driven loops.
350
+ - Prove source-to-sink reachability through the parse-loop back-edge and test whether considered/solv/job-count continue-guards dominate each sink.
351
+ - Report at the unguarded sink call inside testcase_read using the sink source range; do not key diagnostics on repo_create.
352
+ - Identify sources and sinks by stable libsolv API and type names (s_Queue, s_Pool::considered, solver_create, repo_add_*, pool_setarch*) rather than patch locals, line numbers, or commit IDs.
353
+ - Keep reports inside the function that owns both the job-queue parameter and the parse loop; do not require interprocedural value tracking into addselectionjob.
354
+ - Silence on the patched TU must come from the new if-continue guards dominating the sinks, not from proving a symbolic job->count inequality.
355
+
356
+ ### Validation checklist
357
+
358
+ - Checker compiles and registers as a CSA plugin.
359
+ - scan_before on the buggy tree yields n_buggy>0 with at least one warning in ext/testcase.c::testcase_read.
360
+ - Warning locations are at testcase_add_testtags/repo_add_solv/repo_add_helix and/or pool_setarch/pool_setarchpolicy/pool_set_installed, near the pre-patch repo (~2068) and system (~2128) handler spans.
361
+ - scan_after on the patched tree yields n_patched=0 for those sinks because the new guards dominate them, and the buggy reports disappear only in the patched function.
362
+ - No diagnostic is emitted solely at repo_create, which remains reachable after the patch.
363
+ - Cross-validation records N_buggy>0 and N_patched=0; refinement is executed and accepted.
364
+ - Reports must remain valid without matching the identifier oldjobsize.
365
+
366
+ ### Avoid and forbidden regressions
367
+
368
+ - Do not track JobsAdded, SolverSym, ConsideredSym, or JobCountAtEntry in ProgramState across the fgets loop.
369
+ - Do not treat repo_create as a repo-invalidation sink.
370
+ - Do not match oldjobsize, patch line numbers, or commit hashes.
371
+ - Do not require a single exploded path to execute both a job/solver/disable command and a later repo/system command.
372
+ - Do not dump llvm::errs debug traces.
373
+ - Do not treat co-occurrence of source and sink call names in one function as sufficient without CFG reachability and guard-dominance (that does not distinguish patched from buggy).
374
+ - Do not demand interprocedural dataflow through addselectionjob or queue_push2 to prove that Queue::count changed.
tasks/csa159/pair_135624/checker_template.cpp ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ============================================================================
2
+ // CSA Checker Template
3
+ // ============================================================================
4
+ // Fill in the sections marked with TODO to implement your checker.
5
+ // The checker is compiled with -fno-rtti to match the LLVM 18 build config.
6
+ // It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName
7
+ //
8
+ // Compilation:
9
+ // clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \
10
+ // -I${LLVM_BUILD_DIR}/include \
11
+ // checker.cpp -o checker.so \
12
+ // -Wl,--allow-shlib-undefined
13
+ //
14
+ // Usage:
15
+ // clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze <file>
16
+ // ============================================================================
17
+
18
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20
+ #include "clang/StaticAnalyzer/Core/Checker.h"
21
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23
+ #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
24
+
25
+ using namespace clang;
26
+ using namespace ento;
27
+
28
+ namespace {
29
+
30
+ // ────────────────────────────────────────────────────────────────
31
+ // TODO: Rename this class to describe your checker's purpose.
32
+ // ────────────────────────────────────────────────────────────────
33
+ class {{CHECKER_CLASS_NAME}}
34
+ : public Checker<check::PreCall, // for checking before function calls
35
+ check::PostCall> // for checking after function calls
36
+ {
37
+ // TODO: Customize the bug type name and category.
38
+ mutable std::unique_ptr<BugType> BT;
39
+
40
+ public:
41
+ {{CHECKER_CLASS_NAME}}()
42
+ : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {}
43
+
44
+ // ── PreCall callback (fires before every function call) ──────
45
+ void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
46
+ // TODO: Implement your pre-call analysis logic here.
47
+ //
48
+ // Common patterns:
49
+ //
50
+ // 1. Check if the called function matches a specific name:
51
+ // if (Call.getCalleeIdentifier()) {
52
+ // StringRef name = Call.getCalleeIdentifier()->getName();
53
+ // if (name == "target_function") { ... }
54
+ // }
55
+ //
56
+ // 2. Get the program state:
57
+ // ProgramStateRef State = C.getState();
58
+ //
59
+ // 3. Get arguments:
60
+ // SVal Arg = Call.getArgSVal(0);
61
+ //
62
+ // 4. Generate a bug report:
63
+ // ExplodedNode *ErrNode = C.generateErrorNode();
64
+ // if (ErrNode) {
65
+ // auto R = std::make_unique<PathSensitiveBugReport>(
66
+ // *BT, "Description of the bug", ErrNode);
67
+ // C.emitReport(std::move(R));
68
+ // }
69
+ }
70
+
71
+ // ── PostCall callback (fires after every function call) ─────
72
+ void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
73
+ // TODO: Implement your post-call analysis logic here.
74
+ //
75
+ // Common pattern — check the return value:
76
+ // SVal RetVal = Call.getReturnValue();
77
+ // if (RetVal.isUnknownOrUndef()) return;
78
+ //
79
+ // ProgramStateRef State = C.getState();
80
+ // // Modify state based on post-call conditions...
81
+ }
82
+ };
83
+
84
+ } // anonymous namespace
85
+
86
+ // ────────────────────────────────────────────────────────────────
87
+ // Registration — DO NOT modify the function signatures.
88
+ // ────────────────────────────────────────────────────────────────
89
+
90
+ extern "C" void clang_registerCheckers(CheckerRegistry &registry) {
91
+ registry.addChecker<{{CHECKER_CLASS_NAME}}>(
92
+ "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker"
93
+ "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference"
94
+ "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs"
95
+ }
96
+
97
+ extern "C" const char clang_analyzerAPIVersionString[] =
98
+ CLANG_ANALYZER_API_VERSION_STRING;
tasks/csa159/pair_135624/config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "project_id": "sass_libsass",
3
+ "before_commit": "c93f0581c6b7794d8c1d5637c5c4dabd591b1d57",
4
+ "after_commit": "eb15533b07773c30dc03c9d742865604f47120ef",
5
+ "repo_path": "/workspace/repo/sass/libsass",
6
+ "llvm_build_dir": "/opt/llvm",
7
+ "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/sass_libsass/5c2501eaa115aafafb254fa4f3522efa0ee14edb/compile_commands.json",
8
+ "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/sass_libsass/5c2501eaa115aafafb254fa4f3522efa0ee14edb/compile_commands.json",
9
+ "changed_files": [
10
+ "src/parser.cpp"
11
+ ],
12
+ "commit_message": "Fix memory leak in `parse_ie_keyword_arg`\n\n`kwd_arg` would never get freed when there was a parse error in\n`parse_ie_keyword_arg`.\n\nCloses #2656",
13
+ "t_valid": 50,
14
+ "t_plausible": 20,
15
+ "triage_sample_size": 10,
16
+ "max_synthesis_retry": 0,
17
+ "max_in_session_redesigns": 1,
18
+ "max_refinement_iter": 3
19
+ }
tasks/csa159/pair_135624/patch.diff ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/parser.cpp b/src/parser.cpp
2
+ index 374ffa13..516d593d 100644
3
+ --- a/src/parser.cpp
4
+ +++ b/src/parser.cpp
5
+ @@ -1918,7 +1918,7 @@ namespace Sass {
6
+
7
+ String_Obj Parser::parse_ie_keyword_arg()
8
+ {
9
+ - String_Schema_Ptr kwd_arg = SASS_MEMORY_NEW(String_Schema, pstate, 3);
10
+ + String_Schema_Obj kwd_arg = SASS_MEMORY_NEW(String_Schema, pstate, 3);
11
+ if (lex< variable >()) {
12
+ kwd_arg->append(SASS_MEMORY_NEW(Variable, pstate, Util::normalize_underscores(lexed)));
13
+ } else {
tasks/csa159/pair_135624/post_functions.txt ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: src/parser.cpp
2
+ ```c
3
+ String_Obj Parser::parse_ie_property()
4
+ {
5
+ lex< ie_property >();
6
+ Token str(lexed);
7
+ const char* i = str.begin;
8
+ // see if there any interpolants
9
+ const char* p = find_first_in_interval< exactly<hash_lbrace>, block_comment >(str.begin, str.end);
10
+ if (!p) {
11
+ return SASS_MEMORY_NEW(String_Quoted, pstate, std::string(str.begin, str.end));
12
+ }
13
+
14
+ String_Schema_Ptr schema = SASS_MEMORY_NEW(String_Schema, pstate);
15
+ while (i < str.end) {
16
+ p = find_first_in_interval< exactly<hash_lbrace>, block_comment >(i, str.end);
17
+ if (p) {
18
+ if (i < p) {
19
+ schema->append(SASS_MEMORY_NEW(String_Constant, pstate, std::string(i, p))); // accumulate the preceding segment if it's nonempty
20
+ }
21
+ if (peek < sequence < optional_spaces, exactly<rbrace> > >(p+2)) { position = p+2;
22
+ css_error("Invalid CSS", " after ", ": expected expression (e.g. 1px, bold), was ");
23
+ }
24
+ const char* j = skip_over_scopes< exactly<hash_lbrace>, exactly<rbrace> >(p+2, str.end); // find the closing brace
25
+ if (j) {
26
+ // parse the interpolant and accumulate it
27
+ Expression_Obj interp_node = Parser::from_token(Token(p+2, j), ctx, traces, pstate, source).parse_list();
28
+ interp_node->is_interpolant(true);
29
+ schema->append(interp_node);
30
+ i = j;
31
+ }
32
+ else {
33
+ // throw an error if the interpolant is unterminated
34
+ error("unterminated interpolant inside IE function " + str.to_string());
35
+ }
36
+ }
37
+ else { // no interpolants left; add the last segment if nonempty
38
+ if (i < str.end) {
39
+ schema->append(SASS_MEMORY_NEW(String_Constant, pstate, std::string(i, str.end)));
40
+ }
41
+ break;
42
+ }
43
+ }
44
+ return schema;
45
+ }
46
+
47
+ String_Obj Parser::parse_ie_keyword_arg()
48
+ {
49
+ String_Schema_Obj kwd_arg = SASS_MEMORY_NEW(String_Schema, pstate, 3);
50
+ if (lex< variable >()) {
51
+ kwd_arg->append(SASS_MEMORY_NEW(Variable, pstate, Util::normalize_underscores(lexed)));
52
+ } else {
53
+ lex< alternatives< identifier_schema, identifier > >();
54
+ kwd_arg->append(SASS_MEMORY_NEW(String_Constant, pstate, lexed));
55
+ }
56
+ lex< exactly<'='> >();
57
+ kwd_arg->append(SASS_MEMORY_NEW(String_Constant, pstate, lexed));
58
+ if (peek< variable >()) kwd_arg->append(parse_list());
59
+ else if (lex< number >()) {
60
+ std::string parsed(lexed);
61
+ Util::normalize_decimals(parsed);
62
+ kwd_arg->append(lexed_number(parsed));
63
+ }
64
+ else if (peek < ie_keyword_arg_value >()) { kwd_arg->append(parse_list()); }
65
+ return kwd_arg;
66
+ }
67
+ ```
tasks/csa159/pair_135624/pre_functions.txt ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: src/parser.cpp
2
+ ```c
3
+ String_Obj Parser::parse_ie_property()
4
+ {
5
+ lex< ie_property >();
6
+ Token str(lexed);
7
+ const char* i = str.begin;
8
+ // see if there any interpolants
9
+ const char* p = find_first_in_interval< exactly<hash_lbrace>, block_comment >(str.begin, str.end);
10
+ if (!p) {
11
+ return SASS_MEMORY_NEW(String_Quoted, pstate, std::string(str.begin, str.end));
12
+ }
13
+
14
+ String_Schema_Ptr schema = SASS_MEMORY_NEW(String_Schema, pstate);
15
+ while (i < str.end) {
16
+ p = find_first_in_interval< exactly<hash_lbrace>, block_comment >(i, str.end);
17
+ if (p) {
18
+ if (i < p) {
19
+ schema->append(SASS_MEMORY_NEW(String_Constant, pstate, std::string(i, p))); // accumulate the preceding segment if it's nonempty
20
+ }
21
+ if (peek < sequence < optional_spaces, exactly<rbrace> > >(p+2)) { position = p+2;
22
+ css_error("Invalid CSS", " after ", ": expected expression (e.g. 1px, bold), was ");
23
+ }
24
+ const char* j = skip_over_scopes< exactly<hash_lbrace>, exactly<rbrace> >(p+2, str.end); // find the closing brace
25
+ if (j) {
26
+ // parse the interpolant and accumulate it
27
+ Expression_Obj interp_node = Parser::from_token(Token(p+2, j), ctx, traces, pstate, source).parse_list();
28
+ interp_node->is_interpolant(true);
29
+ schema->append(interp_node);
30
+ i = j;
31
+ }
32
+ else {
33
+ // throw an error if the interpolant is unterminated
34
+ error("unterminated interpolant inside IE function " + str.to_string());
35
+ }
36
+ }
37
+ else { // no interpolants left; add the last segment if nonempty
38
+ if (i < str.end) {
39
+ schema->append(SASS_MEMORY_NEW(String_Constant, pstate, std::string(i, str.end)));
40
+ }
41
+ break;
42
+ }
43
+ }
44
+ return schema;
45
+ }
46
+
47
+ String_Obj Parser::parse_ie_keyword_arg()
48
+ {
49
+ String_Schema_Ptr kwd_arg = SASS_MEMORY_NEW(String_Schema, pstate, 3);
50
+ if (lex< variable >()) {
51
+ kwd_arg->append(SASS_MEMORY_NEW(Variable, pstate, Util::normalize_underscores(lexed)));
52
+ } else {
53
+ lex< alternatives< identifier_schema, identifier > >();
54
+ kwd_arg->append(SASS_MEMORY_NEW(String_Constant, pstate, lexed));
55
+ }
56
+ lex< exactly<'='> >();
57
+ kwd_arg->append(SASS_MEMORY_NEW(String_Constant, pstate, lexed));
58
+ if (peek< variable >()) kwd_arg->append(parse_list());
59
+ else if (lex< number >()) {
60
+ std::string parsed(lexed);
61
+ Util::normalize_decimals(parsed);
62
+ kwd_arg->append(lexed_number(parsed));
63
+ }
64
+ else if (peek < ie_keyword_arg_value >()) { kwd_arg->append(parse_list()); }
65
+ return kwd_arg;
66
+ }
67
+ ```
tasks/csa159/pair_135624/task_prompt.md ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Task: Synthesize a CSA Checker from a CVE Patch
2
+
3
+ ## Your Role
4
+
5
+ You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker
6
+ that detects the bug pattern fixed by the CVE patch in this working directory.
7
+
8
+ You have full filesystem and bash access — use them.
9
+
10
+ ### Skills
11
+
12
+ Many skills are available under `.claude/skills/` — covering vulnerability analysis,
13
+ checker design, debugging, code audit, security patterns, and more. Each skill
14
+ encodes reusable expertise: take time to explore them, read their SKILL.md files,
15
+ and invoke those that look useful via the Skill tool. Let the task guide which
16
+ ones you reach for.
17
+
18
+ ## File Layout
19
+
20
+ ```
21
+ /work/
22
+ ├── compile.sh ← RUN ME: compile checker.cpp → checker.so
23
+ ├── checker_template.cpp ← skeleton, start here
24
+ ├── patch.diff ← the CVE fix
25
+ ├── pre_functions.txt ← buggy source (before_commit)
26
+ ├── post_functions.txt ← patched source (after_commit)
27
+ ├── config.json ← paths, commit_message, commit hashes, flags
28
+ ├── scan/
29
+ │ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy
30
+ │ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched
31
+ │ └── flags_*.txt ← pre-extracted compile flags (-I, -D)
32
+ ├── references/
33
+ │ ├── repo_knowledge.md ← project-specific API/convention reference
34
+ │ ├── patterns_summary.md ← (optional) historical bug pattern summary
35
+ │ ├── cwe_cards/ ← CWE knowledge library (all categories)
36
+ │ │ ├── index.json ← lookup index — use to find relevant cards
37
+ │ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns
38
+ │ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped)
39
+ │ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers)
40
+ │ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.)
41
+ │ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.)
42
+ │ └── examples/
43
+ │ └── llvm-official/ ← 5 official checker sources (with comments)
44
+ │ ├── 01_div_zero.cpp
45
+ │ ├── 02_simple_stream.cpp
46
+ │ ├── 03_undef_result.cpp
47
+ │ ├── 04_nullability.cpp
48
+ │ └── 05_malloc.cpp
49
+ │
50
+ ├── checker.cpp ← YOUR OUTPUT: synthesized checker
51
+ ├── checker.so ← YOUR OUTPUT: compiled checker
52
+ ├── state.json ← YOUR OUTPUT: structured task state
53
+ ├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3)
54
+ └── summary.json ← YOUR OUTPUT: final report
55
+ ```
56
+
57
+ ## Resources
58
+
59
+ **Read these before writing any code:**
60
+
61
+ 1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from
62
+ LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types,
63
+ MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.**
64
+
65
+ 2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested
66
+ patterns from official LLVM checkers: resource tracking, null checking, undefined
67
+ value detection, division-by-zero, and malloc/free. Each pattern includes skeleton
68
+ code, state traits, and key API usage.
69
+
70
+ 3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations
71
+ with explanatory comments:
72
+ - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback)
73
+ - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose)
74
+ - `03_undef_result.cpp` — PostStmt pattern (160 lines)
75
+ - `04_nullability.cpp` — multi-callback checker (1247 lines)
76
+ - `05_malloc.cpp` — comprehensive malloc/free (1511 lines)
77
+
78
+ 4. **`checker_template.cpp`** — Skeleton with placeholders. Start here.
79
+
80
+ 5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this
81
+ repository's memory allocation API, key data types, source layout, and typical
82
+ CVE patterns. **Read this before writing the checker** — knowing the project's
83
+ alloc/free conventions and common bug patterns saves many grep rounds.
84
+
85
+ 5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis
86
+ patterns for this project. If present, it contains a concise summary of the
87
+ most common bug patterns, frequent CWE categories, and reusable checker
88
+ architectures observed in previous synthesis runs. Read after repo_knowledge.md.
89
+
90
+ 6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all
91
+ vulnerability categories. **The framework provides the full library —
92
+ you must identify the vulnerability type yourself.** Workflow:
93
+
94
+ 1. Analyse the patch diff and commit message to determine the vulnerability
95
+ type (buffer overflow, UAF, null deref, integer overflow, race condition,
96
+ etc.). Do NOT rely on the CWE label — treat it as a hint at most.
97
+ 2. Open ``index.json`` to discover available cards and their tiers.
98
+ 3. Read the relevant card(s) for **detection strategies**, **checker
99
+ architecture suggestions**, and **known false-positive patterns**.
100
+
101
+ Card tiers:
102
+ - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel /
103
+ userspace variants when the detection strategy differs substantially.
104
+ - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by
105
+ category (input validation, resource management, etc.).
106
+
107
+ 7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for
108
+ checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`),
109
+ expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string
110
+ size extraction, MemRegion helpers, and `ExprHasName()` for robust function
111
+ matching. All verified against LLVM 18. **Read before implementing detection
112
+ logic** — these save writing boilerplate that's easy to get wrong.
113
+
114
+ ## Environment
115
+
116
+ Key paths are in ``config.json``.
117
+
118
+ ### Pre-built scripts
119
+
120
+ | Script | What it does |
121
+ |--------|-------------|
122
+ | `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) |
123
+ | `CHECKER_NAME=<name> bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy |
124
+ | `CHECKER_NAME=<name> bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched |
125
+
126
+ ```bash
127
+ # Compile (run from workdir root)
128
+ bash compile.sh
129
+
130
+ # Scan — set CHECKER_NAME to the string passed to addChecker<>()
131
+ CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy
132
+ CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched
133
+ ```
134
+
135
+ - ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags.
136
+ - ``scan/scan_*.sh`` count only warnings tagged with your checker name.
137
+ - Scan environments (source files + compile flags) are pre-built in ``scan/``.
138
+
139
+ ### Scan Script Integrity (CRITICAL)
140
+
141
+ The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only
142
+ valid measurement** of N_buggy and N_patched. They are the ground truth that the
143
+ Python-side validator will also use. You MUST obey these rules:
144
+
145
+ **1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly
146
+ to measure warning counts. The Python validator runs the same scan scripts
147
+ — if you measured with a different command, your numbers will not reproduce
148
+ and the synthesis will be rejected.
149
+
150
+ **2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared
151
+ identifiers, etc.), the scan environment needs repair. You MUST fix it:
152
+ - Add missing ``-I`` include paths to the flags files in ``scan/``
153
+ - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot
154
+ - If the file fundamentally cannot be compiled by clang, stop and write
155
+ ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason``
156
+
157
+ **3. Only trust scan script output.** The ``Total <name> warnings: N`` line
158
+ printed by the scan script is the number that goes into ``summary.json``.
159
+ If the scan script says 0, write 0. Fabricating numbers that the scan
160
+ script did not produce will cause the Python validator to reject the
161
+ synthesis.
162
+
163
+ - If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles).
164
+ - If validation fails: revise checker logic, re-compile, re-scan.
165
+
166
+ ## MCP Tools
167
+
168
+ You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`).
169
+ Each returns **source context embedded in the result** — no need to follow up with Read.
170
+
171
+ | Tool | What it does | Key advantage |
172
+ |------|-------------|---------------|
173
+ | `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call |
174
+ | `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file |
175
+ | `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed |
176
+
177
+ ### When to use each
178
+
179
+ - **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure.
180
+ - **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines.
181
+ - **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action.
182
+
183
+ ## Semantic Design Contract — before writing checker.cpp
184
+
185
+ Create the analysis portions of `state.json` and `scope_statement.md` **before**
186
+ writing checker.cpp. They are a design contract, not a retrospective summary.
187
+ After compilation, update only implementation facts such as `build_attempts`.
188
+
189
+ In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the
190
+ semantic fact introduced by the patch that makes it safe. In `detection_plan`,
191
+ make `report_condition`, `safe_condition`, and `source_level_signal` concrete
192
+ CSA-observable facts. In `api_choice`, record the mechanism level and explain
193
+ why the selected callback can observe and prove those facts.
194
+
195
+ In `scope_statement.md`, include this mapping table and check it again after
196
+ implementation:
197
+
198
+ | Semantic condition | CSA evidence | checker.cpp implementation |
199
+ | --- | --- | --- |
200
+ | report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports |
201
+ | safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report |
202
+
203
+ Every condition in the plan must have an implementation entry. Do not claim a
204
+ condition that checker.cpp does not implement, and do not silently add a code
205
+ condition absent from the plan.
206
+
207
+ ## Mechanism Selection — diagnose before coding
208
+
209
+ Choose the weakest CSA mechanism that can prove the vulnerability property:
210
+
211
+ 1. **syntax-only AST**: only when local AST shape itself is the defect;
212
+ 2. **control flow / dominance**: when guard placement relative to a sink matters;
213
+ 3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use;
214
+ 4. **cross-procedure/dataflow**: when the required fact crosses function boundaries.
215
+
216
+ For a guard-based patch, prove both that the guard rejects the unsafe value and
217
+ that it dominates the vulnerable use. For path-sensitive or cross-procedure
218
+ defects, do not replace the required state or flow proof with local AST matching
219
+ or source-text substring matching merely because it passes the differential scan.
220
+ Record the selected level as `api_choice.mechanism_level`.
221
+
222
+ ## Semantic identity, locality, and final validation
223
+
224
+ Before accepting the checker, verify that its primary matching logic does not
225
+ depend on patch-local variable names, labels, line numbers, commit IDs, or unique
226
+ literals. Project APIs, types, and stable semantic call relationships are valid
227
+ scope anchors when they define the vulnerability class. Attach the report to the
228
+ actual vulnerable operation, and implement every suppression as a real safe
229
+ condition rather than the mere presence of a nearby guard-shaped statement.
230
+
231
+ The required final sequence is: **compile → before scan → after scan → inspect
232
+ the final checker name, artifacts, and report locations → write summary.json**.
233
+ Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only
234
+ additional redesign cycles after a failed validation; if it is zero, preserve the
235
+ real validation evidence and report failure honestly rather than fabricating counts.
236
+
237
+ ## Validation Criteria
238
+
239
+ ```
240
+ VALID : N_buggy > N_patched AND N_patched < 50
241
+ INVALID : otherwise → revise and re-validate (max 1 attempts)
242
+ ```
243
+
244
+ ## Refinement
245
+
246
+ Do NOT self-refine the checker repeatedly. Your goal is to produce the first
247
+ checker that passes the Validation Criteria above — fix compile errors and
248
+ validation failures only. False positives are triaged and repaired by the
249
+ framework's refinement stage: you will receive a concrete FP list via
250
+ session resume (if needed) and fix only those. Reserve budget for that stage.
251
+
252
+ ## Output
253
+
254
+ Produce all of the following **only when completely done**:
255
+
256
+ | File | Content |
257
+ |------|---------|
258
+ | ``checker.cpp`` | Synthesized checker source code |
259
+ | ``checker.so`` | Compiled checker plugin |
260
+ | ``state.json`` | Structured task state (see schema below) |
261
+ | ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) |
262
+ | ``summary.json`` | Final report (see schema below) |
263
+
264
+ Writing ``summary.json`` signals completion. Do NOT write it early.
265
+
266
+ ### ``state.json``
267
+
268
+ Create this before writing checker.cpp to capture the design contract. After the
269
+ checker compiles, update only implementation facts and retain the original
270
+ semantic plan.
271
+
272
+ ```json
273
+ {
274
+ "patch_analysis": {
275
+ "summary": "One sentence describing the vulnerability this patch fixes",
276
+ "changed_files": ["file1.c", "file2.h"],
277
+ "changed_functions": ["func_a", "func_b"],
278
+ "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other",
279
+ "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other",
280
+ "affected_types": ["GF_BitStream", "custom_struct_t"],
281
+ "critical_calls": ["gf_strdup", "memcpy"]
282
+ },
283
+ "detection_plan": {
284
+ "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')",
285
+ "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')",
286
+ "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')",
287
+ "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')"
288
+ },
289
+ "api_choice": {
290
+ "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow",
291
+ "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...",
292
+ "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions",
293
+ "alternatives_considered": ["check::PostCall"]
294
+ },
295
+ "implementation": {
296
+ "scope_level": "patch_specific | project_general | cross_project",
297
+ "checker_name": "project.CheckerName",
298
+ "build_attempts": 1
299
+ }
300
+ }
301
+ ```
302
+
303
+ ### ``summary.json``
304
+
305
+ ```json
306
+ {
307
+ "status": "plausible | failed",
308
+ "bug_pattern": "One sentence describing the bug pattern",
309
+ "scope_level": "patch_specific | project_general | cross_project",
310
+ "checker_cpp": "checker.cpp",
311
+ "checker_so": "checker.so",
312
+ "n_buggy": 0,
313
+ "n_patched": 0,
314
+ "total_reports": 0,
315
+ "fp_rate_estimate": 0.0,
316
+ "failure_reason": null
317
+ }
318
+ ```
319
+
320
+ ## Feedback-derived requirements for this fresh synthesis
321
+
322
+ A prior independent rollout exposed the risks below. Start again from the patch
323
+ in this new session. Do not reconstruct, edit, or assume the prior checker.
324
+
325
+ Required mechanism level: `path_sensitive`
326
+
327
+ ### Current failure diagnosis
328
+
329
+ - The rollout did not establish hard validation, leaving the objective gate at G5 rather than the required G6 and the process score below threshold.
330
+ - Refinement ended with feedback_required rather than an accepted or clean outcome.
331
+ - The exception oracle treated a throw lexically present in a callee or transitive callee as propagating, without proving that it escapes intervening catch scopes.
332
+ - The claimed safe cases exceeded the demonstrated ownership model: direct SharedImpl assignment and all stated transfer forms were not fully recognized.
333
+ - Differential sharpness was low: 12 buggy-tree reports and 11 patched-tree reports produced only one patch-relevant disappearance, although no unrelated warning disappeared.
334
+
335
+ ### Preserve from prior rollouts
336
+
337
+ - Retain the accepted path-sensitive mechanism level and a semantic score at or above the configured threshold.
338
+ - Retain an accepted or clean refinement outcome.
339
+ - Remain independent of changed lines, patch text, commit identity, source locations, and the names parse_ie_keyword_arg and kwd_arg.
340
+ - Remain free of patch-local hardcoding while using stable project ownership semantics.
341
+ - Preserve detection of the relevant buggy allocation and suppression after immediate owning String_Schema_Obj initialization.
342
+
343
+ ### Required semantic proof
344
+
345
+ - Prove that a feasible path creates a MemRegion for a SharedObj-derived allocation and reaches an exception-propagating operation while that same region remains unadopted.
346
+ - Prove that SharedImpl ownership has not been established before the sink on the reporting path; adoption on a sibling path must not discharge the region.
347
+ - Treat a sink as relevant only when an exception can escape the called operation and unwind across the lifetime of the raw local, accounting for visible catches rather than merely finding a nested throw.
348
+ - Suppress the report when every feasible path to an escaping-exception sink first transfers the allocation into an owning SharedImpl.
349
+ - Distinguish raw, non-owning pointer storage from ownership-producing construction, assignment, parameter transfer, or return conversion according to the evidenced SharedImpl contract.
350
+
351
+ ### Implementation constraints
352
+
353
+ - Use ProgramState keyed by allocation identity, with check::PostStmt<CXXNewExpr> to introduce unadopted SharedObj-derived regions and path-local transitions to update ownership.
354
+ - Observe ownership-producing SharedImpl operations with callbacks appropriate to construction and any supported assignment or transfer forms; each discharge must resolve to the tracked MemRegion.
355
+ - Use check::PreCall for the throwing sink because exception-unwind exits are not represented adequately by check::EndFunction.
356
+ - Derive ordering and reachability from the ExplodedGraph and current ProgramState, not lexical source order; keep the ownership proof intraprocedural.
357
+ - Any auxiliary callee analysis must be structural, bounded, cycle-safe, restricted to available evidence, and distinguish escaping throws from throws caught before return.
358
+ - Emit one diagnostic per proven allocation-path condition, with the primary location at the allocation and a secondary note at the exception-capable call.
359
+ - Scope matching to stable SharedObj inheritance and SharedImpl ownership behavior rather than parser function names, variable names, filenames, line numbers, or changed literals.
360
+
361
+ ### Validation checklist
362
+
363
+ - Compile and load the checker against the target Clang Static Analyzer API with no diagnostics or registration failures.
364
+ - Scan both source revisions and confirm a diagnostic in buggy Parser::parse_ie_keyword_arg that disappears after String_Schema_Ptr becomes String_Schema_Obj.
365
+ - Confirm the primary diagnostic location is the vulnerable String_Schema allocation and the path note identifies the proven escaping-exception sink.
366
+ - Exercise branch cases where adoption occurs on all paths, one path, or no path, verifying that ProgramState does not discharge sibling paths.
367
+ - Exercise immediate construction and each supported later ownership-transfer form, especially direct SharedImpl assignment, and require clean results after adoption.
368
+ - Exercise direct throws, transitively escaping throws, locally caught throws, indirect or unavailable callees, loops, early returns, and non-SharedObj allocations.
369
+ - Review the 11 warnings that remain in the patched tree against the full ownership and exception-propagation proof; suppress unsupported cases semantically rather than by location.
370
+ - Require hard validation, objective eligibility of at least G6, accepted or clean refinement, and a process score above threshold before rollout.
371
+
372
+ ### Avoid and forbidden regressions
373
+
374
+ - Do not reduce the design to syntax-only or control-flow-only matching; local declaration shape and CFG order cannot represent path-specific ownership.
375
+ - Do not use check::Bind as the sole adoption signal because raw binding and SharedImpl ownership are not reliably distinguished there.
376
+ - Do not defer detection to check::EndFunction or assume CSA models exception-unwind exits as ordinary analyzed paths.
377
+ - Do not classify a call as propagating solely because a visible body or transitive callee contains CXXThrowExpr.
378
+ - Do not claim ownership-transfer safe cases that the selected callbacks and region resolution cannot demonstrate.
379
+ - Do not suppress remaining reports to improve sharpness through patch anchors, function allowlists, line proximity, source-text matching, or changed identifiers.
380
+ - Do not report non-SharedObj allocations or paths on which an owning SharedImpl has already adopted the tracked region.
tasks/csa159/pair_135745/checker_template.cpp ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ============================================================================
2
+ // CSA Checker Template
3
+ // ============================================================================
4
+ // Fill in the sections marked with TODO to implement your checker.
5
+ // The checker is compiled with -fno-rtti to match the LLVM 18 build config.
6
+ // It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName
7
+ //
8
+ // Compilation:
9
+ // clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \
10
+ // -I${LLVM_BUILD_DIR}/include \
11
+ // checker.cpp -o checker.so \
12
+ // -Wl,--allow-shlib-undefined
13
+ //
14
+ // Usage:
15
+ // clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze <file>
16
+ // ============================================================================
17
+
18
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20
+ #include "clang/StaticAnalyzer/Core/Checker.h"
21
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23
+ #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
24
+
25
+ using namespace clang;
26
+ using namespace ento;
27
+
28
+ namespace {
29
+
30
+ // ────────────────────────────────────────────────────────────────
31
+ // TODO: Rename this class to describe your checker's purpose.
32
+ // ────────────────────────────────────────────────────────────────
33
+ class {{CHECKER_CLASS_NAME}}
34
+ : public Checker<check::PreCall, // for checking before function calls
35
+ check::PostCall> // for checking after function calls
36
+ {
37
+ // TODO: Customize the bug type name and category.
38
+ mutable std::unique_ptr<BugType> BT;
39
+
40
+ public:
41
+ {{CHECKER_CLASS_NAME}}()
42
+ : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {}
43
+
44
+ // ── PreCall callback (fires before every function call) ──────
45
+ void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
46
+ // TODO: Implement your pre-call analysis logic here.
47
+ //
48
+ // Common patterns:
49
+ //
50
+ // 1. Check if the called function matches a specific name:
51
+ // if (Call.getCalleeIdentifier()) {
52
+ // StringRef name = Call.getCalleeIdentifier()->getName();
53
+ // if (name == "target_function") { ... }
54
+ // }
55
+ //
56
+ // 2. Get the program state:
57
+ // ProgramStateRef State = C.getState();
58
+ //
59
+ // 3. Get arguments:
60
+ // SVal Arg = Call.getArgSVal(0);
61
+ //
62
+ // 4. Generate a bug report:
63
+ // ExplodedNode *ErrNode = C.generateErrorNode();
64
+ // if (ErrNode) {
65
+ // auto R = std::make_unique<PathSensitiveBugReport>(
66
+ // *BT, "Description of the bug", ErrNode);
67
+ // C.emitReport(std::move(R));
68
+ // }
69
+ }
70
+
71
+ // ── PostCall callback (fires after every function call) ─────
72
+ void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
73
+ // TODO: Implement your post-call analysis logic here.
74
+ //
75
+ // Common pattern — check the return value:
76
+ // SVal RetVal = Call.getReturnValue();
77
+ // if (RetVal.isUnknownOrUndef()) return;
78
+ //
79
+ // ProgramStateRef State = C.getState();
80
+ // // Modify state based on post-call conditions...
81
+ }
82
+ };
83
+
84
+ } // anonymous namespace
85
+
86
+ // ────────────────────────────────────────────────────────────────
87
+ // Registration — DO NOT modify the function signatures.
88
+ // ────────────────────────────────────────────────────────────────
89
+
90
+ extern "C" void clang_registerCheckers(CheckerRegistry &registry) {
91
+ registry.addChecker<{{CHECKER_CLASS_NAME}}>(
92
+ "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker"
93
+ "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference"
94
+ "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs"
95
+ }
96
+
97
+ extern "C" const char clang_analyzerAPIVersionString[] =
98
+ CLANG_ANALYZER_API_VERSION_STRING;
tasks/csa159/pair_135745/config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "project_id": "verdammelt_tnef",
3
+ "before_commit": "5af0791db67d50ce5ebc16252626c679bb4079fb",
4
+ "after_commit": "cfdd80f52b31215bb4cf59ffb6e1bf5be93ead7c",
5
+ "repo_path": "/workspace/repo/verdammelt/tnef",
6
+ "llvm_build_dir": "/opt/llvm",
7
+ "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/verdammelt_tnef/5af0791db67d50ce5ebc16252626c679bb4079fb/compile_commands.json",
8
+ "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/verdammelt_tnef/5af0791db67d50ce5ebc16252626c679bb4079fb/compile_commands.json",
9
+ "changed_files": [
10
+ "src/mapi_attr.c",
11
+ "src/util.c"
12
+ ],
13
+ "commit_message": "Handle overflow problem reported in #23\n\n1. Assert that names must be non-zero length.\n2. Keep unicode_to_utf8 from underflowing.",
14
+ "t_valid": 50,
15
+ "t_plausible": 20,
16
+ "triage_sample_size": 10,
17
+ "max_synthesis_retry": 0,
18
+ "max_in_session_redesigns": 1,
19
+ "max_refinement_iter": 3
20
+ }
tasks/csa159/pair_135745/patch.diff ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/mapi_attr.c b/src/mapi_attr.c
2
+ index 3f3250b..455cc67 100644
3
+ --- a/src/mapi_attr.c
4
+ +++ b/src/mapi_attr.c
5
+ @@ -211,6 +211,8 @@ mapi_attr_read (size_t len, unsigned char *buf)
6
+ CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4;
7
+
8
+ /* read the data into a buffer */
9
+ + /* read the data into a buffer */
10
+ + assert(a->names[i].len != 0);
11
+ assert(idx+a->names[i].len <= len);
12
+ a->names[i].data = unicode_to_utf8(a->names[i].len, buf+idx);
13
+
14
+ diff --git a/src/util.c b/src/util.c
15
+ index 9a56e0e..db9e714 100644
16
+ --- a/src/util.c
17
+ +++ b/src/util.c
18
+ @@ -85,28 +85,29 @@ unicode_to_utf8 (size_t len, unsigned char* buf)
19
+ int j = 0;
20
+ unsigned char *utf8 = malloc (3 * len/2 + 1); /* won't get any longer than this */
21
+
22
+ - for (i = 0; i < len - 1; i += 2)
23
+ - {
24
+ - uint32 c = GETINT16(buf + i);
25
+ - if (c <= 0x007f)
26
+ - {
27
+ - utf8[j++] = 0x00 | ((c & 0x007f) >> 0);
28
+ - }
29
+ - else if (c < 0x07ff)
30
+ - {
31
+ - utf8[j++] = 0xc0 | ((c & 0x07c0) >> 6);
32
+ - utf8[j++] = 0x80 | ((c & 0x003f) >> 0);
33
+ - }
34
+ - else
35
+ - {
36
+ - utf8[j++] = 0xe0 | ((c & 0xf000) >> 12);
37
+ - utf8[j++] = 0x80 | ((c & 0x0fc0) >> 6);
38
+ - utf8[j++] = 0x80 | ((c & 0x003f) >> 0);
39
+ - }
40
+ + if (len > 0) {
41
+ + for (i = 0; i < len - 1; i += 2)
42
+ + {
43
+ + uint32 c = GETINT16(buf + i);
44
+ + if (c <= 0x007f)
45
+ + {
46
+ + utf8[j++] = 0x00 | ((c & 0x007f) >> 0);
47
+ + }
48
+ + else if (c < 0x07ff)
49
+ + {
50
+ + utf8[j++] = 0xc0 | ((c & 0x07c0) >> 6);
51
+ + utf8[j++] = 0x80 | ((c & 0x003f) >> 0);
52
+ + }
53
+ + else
54
+ + {
55
+ + utf8[j++] = 0xe0 | ((c & 0xf000) >> 12);
56
+ + utf8[j++] = 0x80 | ((c & 0x0fc0) >> 6);
57
+ + utf8[j++] = 0x80 | ((c & 0x003f) >> 0);
58
+ + }
59
+ + }
60
+ }
61
+ -
62
+ +
63
+ utf8[j] = '\0';
64
+ -
65
+ +
66
+ return utf8;
67
+ }
68
+ -
tasks/csa159/pair_135745/post_functions.txt ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: src/mapi_attr.c
2
+ ```c
3
+ MAPI_Attr**
4
+ mapi_attr_read (size_t len, unsigned char *buf)
5
+ {
6
+ size_t idx = 0;
7
+ uint32 i,j;
8
+ assert(len > 4);
9
+ uint32 num_properties = GETINT32(buf+idx);
10
+ assert((num_properties+1) != 0);
11
+ MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1));
12
+
13
+ idx += 4;
14
+
15
+ if (!attrs) return NULL;
16
+ for (i = 0; i < num_properties; i++)
17
+ {
18
+ MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1);
19
+ MAPI_Value* v = NULL;
20
+
21
+ CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2;
22
+ CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2;
23
+
24
+ /* handle special case of GUID prefixed properties */
25
+ if (a->name & GUID_EXISTS_FLAG)
26
+ {
27
+ /* copy GUID */
28
+ a->guid = CHECKED_XMALLOC(GUID, 1);
29
+ copy_guid_from_buf(a->guid, buf+idx, len-idx);
30
+ idx += sizeof (GUID);
31
+
32
+ CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4;
33
+ if (a->num_names > 0)
34
+ {
35
+ size_t i;
36
+
37
+ a->names = CHECKED_XCALLOC(VarLenData, a->num_names);
38
+ assert(a->names);
39
+ for (i = 0; i < a->num_names; i++)
40
+ {
41
+ size_t j;
42
+
43
+ CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4;
44
+
45
+ /* read the data into a buffer */
46
+ /* read the data into a buffer */
47
+ assert(a->names[i].len != 0);
48
+ assert(idx+a->names[i].len <= len);
49
+ a->names[i].data = unicode_to_utf8(a->names[i].len, buf+idx);
50
+
51
+ idx += pad_to_4byte(a->names[i].len);
52
+ }
53
+ }
54
+ else
55
+ {
56
+ /* get the 'real' name */
57
+ CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4;
58
+ }
59
+ }
60
+
61
+ /*
62
+ * Multi-value types and string/object/binary types have
63
+ * multiple values
64
+ */
65
+ if (a->type & MULTI_VALUE_FLAG ||
66
+ a->type == szMAPI_STRING ||
67
+ a->type == szMAPI_UNICODE_STRING ||
68
+ a->type == szMAPI_OBJECT ||
69
+ a->type == szMAPI_BINARY)
70
+ {
71
+ CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx);
72
+ idx += 4;
73
+ }
74
+ else
75
+ {
76
+ a->num_values = 1;
77
+ }
78
+
79
+ /* Amend the type in case of multi-value type */
80
+ if (a->type & MULTI_VALUE_FLAG)
81
+ {
82
+ a->type -= MULTI_VALUE_FLAG;
83
+ }
84
+
85
+
86
+ v = alloc_mapi_values (a);
87
+ assert(v);
88
+ for (j = 0; j < a->num_values; j++)
89
+ {
90
+ switch (a->type)
91
+ {
92
+ case szMAPI_SHORT: /* 2 bytes */
93
+ v->len = 2;
94
+ CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx);
95
+ idx += 4; /* assume padding of 2, advance by 4! */
96
+ break;
97
+
98
+ case szMAPI_INT: /* 4 bytes */
99
+ v->len = 4;
100
+ CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx);
101
+ idx += 4;
102
+ v++;
103
+ break;
104
+
105
+ case szMAPI_FLOAT: /* 4 bytes */
106
+ case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */
107
+ v->len = 4;
108
+ CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx);
109
+ idx += v->len;
110
+ break;
111
+
112
+ case szMAPI_SYSTIME: /* 8 bytes */
113
+ v->len = 8;
114
+ CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx);
115
+ CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4);
116
+ idx += 8;
117
+ v++;
118
+ break;
119
+
120
+ case szMAPI_DOUBLE: /* 8 bytes */
121
+ case szMAPI_APPTIME:
122
+ case szMAPI_CURRENCY:
123
+ case szMAPI_INT8BYTE:
124
+ v->len = 8;
125
+ CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx);
126
+ CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4);
127
+ idx += v->len;
128
+ break;
129
+
130
+ case szMAPI_CLSID:
131
+ v->len = sizeof (GUID);
132
+ copy_guid_from_buf(&v->data.guid, buf+idx, len-idx);
133
+ idx += v->len;
134
+ break;
135
+
136
+ case szMAPI_STRING:
137
+ case szMAPI_UNICODE_STRING:
138
+ case szMAPI_OBJECT:
139
+ case szMAPI_BINARY:
140
+ CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4;
141
+
142
+ assert(v->len + idx <= len);
143
+
144
+ if (a->type == szMAPI_UNICODE_STRING)
145
+ {
146
+ assert(v->len != 0);
147
+ v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx);
148
+ }
149
+ else
150
+ {
151
+ v->data.buf = CHECKED_XMALLOC(unsigned char, v->len);
152
+ memmove (v->data.buf, buf+idx, v->len);
153
+ }
154
+
155
+ idx += pad_to_4byte(v->len);
156
+ v++;
157
+ break;
158
+
159
+ case szMAPI_NULL: /* illegal in input tnef streams */
160
+ case szMAPI_ERROR:
161
+ case szMAPI_UNSPECIFIED:
162
+ fprintf (stderr,
163
+ "Invalid attribute, input file may be corrupted\n");
164
+ if (!ENCODE_SKIP) exit (1);
165
+
166
+ return NULL;
167
+
168
+ default: /* should never get here */
169
+ fprintf (stderr,
170
+ "Undefined attribute, input file may be corrupted\n");
171
+ if (!ENCODE_SKIP) exit (1);
172
+
173
+ return NULL;
174
+
175
+ }
176
+ if (DEBUG_ON) mapi_attr_dump (attrs[i]);
177
+ }
178
+ }
179
+ attrs[i] = NULL;
180
+
181
+ return attrs;
182
+ }
183
+ ```
184
+
185
+ ### File: src/util.c
186
+ ```c
187
+ unsigned char*
188
+ unicode_to_utf8 (size_t len, unsigned char* buf)
189
+ {
190
+ int i = 0;
191
+ int j = 0;
192
+ unsigned char *utf8 = malloc (3 * len/2 + 1); /* won't get any longer than this */
193
+
194
+ if (len > 0) {
195
+ for (i = 0; i < len - 1; i += 2)
196
+ {
197
+ uint32 c = GETINT16(buf + i);
198
+ if (c <= 0x007f)
199
+ {
200
+ utf8[j++] = 0x00 | ((c & 0x007f) >> 0);
201
+ }
202
+ else if (c < 0x07ff)
203
+ {
204
+ utf8[j++] = 0xc0 | ((c & 0x07c0) >> 6);
205
+ utf8[j++] = 0x80 | ((c & 0x003f) >> 0);
206
+ }
207
+ else
208
+ {
209
+ utf8[j++] = 0xe0 | ((c & 0xf000) >> 12);
210
+ utf8[j++] = 0x80 | ((c & 0x0fc0) >> 6);
211
+ utf8[j++] = 0x80 | ((c & 0x003f) >> 0);
212
+ }
213
+ }
214
+ }
215
+
216
+ utf8[j] = '\0';
217
+
218
+ return utf8;
219
+ }
220
+ ```
tasks/csa159/pair_135745/pre_functions.txt ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: src/mapi_attr.c
2
+ ```c
3
+ MAPI_Attr**
4
+ mapi_attr_read (size_t len, unsigned char *buf)
5
+ {
6
+ size_t idx = 0;
7
+ uint32 i,j;
8
+ assert(len > 4);
9
+ uint32 num_properties = GETINT32(buf+idx);
10
+ assert((num_properties+1) != 0);
11
+ MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1));
12
+
13
+ idx += 4;
14
+
15
+ if (!attrs) return NULL;
16
+ for (i = 0; i < num_properties; i++)
17
+ {
18
+ MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1);
19
+ MAPI_Value* v = NULL;
20
+
21
+ CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2;
22
+ CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2;
23
+
24
+ /* handle special case of GUID prefixed properties */
25
+ if (a->name & GUID_EXISTS_FLAG)
26
+ {
27
+ /* copy GUID */
28
+ a->guid = CHECKED_XMALLOC(GUID, 1);
29
+ copy_guid_from_buf(a->guid, buf+idx, len-idx);
30
+ idx += sizeof (GUID);
31
+
32
+ CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4;
33
+ if (a->num_names > 0)
34
+ {
35
+ size_t i;
36
+
37
+ a->names = CHECKED_XCALLOC(VarLenData, a->num_names);
38
+ assert(a->names);
39
+ for (i = 0; i < a->num_names; i++)
40
+ {
41
+ size_t j;
42
+
43
+ CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4;
44
+
45
+ /* read the data into a buffer */
46
+ assert(idx+a->names[i].len <= len);
47
+ a->names[i].data = unicode_to_utf8(a->names[i].len, buf+idx);
48
+
49
+ idx += pad_to_4byte(a->names[i].len);
50
+ }
51
+ }
52
+ else
53
+ {
54
+ /* get the 'real' name */
55
+ CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4;
56
+ }
57
+ }
58
+
59
+ /*
60
+ * Multi-value types and string/object/binary types have
61
+ * multiple values
62
+ */
63
+ if (a->type & MULTI_VALUE_FLAG ||
64
+ a->type == szMAPI_STRING ||
65
+ a->type == szMAPI_UNICODE_STRING ||
66
+ a->type == szMAPI_OBJECT ||
67
+ a->type == szMAPI_BINARY)
68
+ {
69
+ CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx);
70
+ idx += 4;
71
+ }
72
+ else
73
+ {
74
+ a->num_values = 1;
75
+ }
76
+
77
+ /* Amend the type in case of multi-value type */
78
+ if (a->type & MULTI_VALUE_FLAG)
79
+ {
80
+ a->type -= MULTI_VALUE_FLAG;
81
+ }
82
+
83
+
84
+ v = alloc_mapi_values (a);
85
+ assert(v);
86
+ for (j = 0; j < a->num_values; j++)
87
+ {
88
+ switch (a->type)
89
+ {
90
+ case szMAPI_SHORT: /* 2 bytes */
91
+ v->len = 2;
92
+ CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx);
93
+ idx += 4; /* assume padding of 2, advance by 4! */
94
+ break;
95
+
96
+ case szMAPI_INT: /* 4 bytes */
97
+ v->len = 4;
98
+ CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx);
99
+ idx += 4;
100
+ v++;
101
+ break;
102
+
103
+ case szMAPI_FLOAT: /* 4 bytes */
104
+ case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */
105
+ v->len = 4;
106
+ CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx);
107
+ idx += v->len;
108
+ break;
109
+
110
+ case szMAPI_SYSTIME: /* 8 bytes */
111
+ v->len = 8;
112
+ CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx);
113
+ CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4);
114
+ idx += 8;
115
+ v++;
116
+ break;
117
+
118
+ case szMAPI_DOUBLE: /* 8 bytes */
119
+ case szMAPI_APPTIME:
120
+ case szMAPI_CURRENCY:
121
+ case szMAPI_INT8BYTE:
122
+ v->len = 8;
123
+ CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx);
124
+ CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4);
125
+ idx += v->len;
126
+ break;
127
+
128
+ case szMAPI_CLSID:
129
+ v->len = sizeof (GUID);
130
+ copy_guid_from_buf(&v->data.guid, buf+idx, len-idx);
131
+ idx += v->len;
132
+ break;
133
+
134
+ case szMAPI_STRING:
135
+ case szMAPI_UNICODE_STRING:
136
+ case szMAPI_OBJECT:
137
+ case szMAPI_BINARY:
138
+ CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4;
139
+
140
+ assert(v->len + idx <= len);
141
+
142
+ if (a->type == szMAPI_UNICODE_STRING)
143
+ {
144
+ assert(v->len != 0);
145
+ v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx);
146
+ }
147
+ else
148
+ {
149
+ v->data.buf = CHECKED_XMALLOC(unsigned char, v->len);
150
+ memmove (v->data.buf, buf+idx, v->len);
151
+ }
152
+
153
+ idx += pad_to_4byte(v->len);
154
+ v++;
155
+ break;
156
+
157
+ case szMAPI_NULL: /* illegal in input tnef streams */
158
+ case szMAPI_ERROR:
159
+ case szMAPI_UNSPECIFIED:
160
+ fprintf (stderr,
161
+ "Invalid attribute, input file may be corrupted\n");
162
+ if (!ENCODE_SKIP) exit (1);
163
+
164
+ return NULL;
165
+
166
+ default: /* should never get here */
167
+ fprintf (stderr,
168
+ "Undefined attribute, input file may be corrupted\n");
169
+ if (!ENCODE_SKIP) exit (1);
170
+
171
+ return NULL;
172
+
173
+ }
174
+ if (DEBUG_ON) mapi_attr_dump (attrs[i]);
175
+ }
176
+ }
177
+ attrs[i] = NULL;
178
+
179
+ return attrs;
180
+ }
181
+ ```
182
+
183
+ ### File: src/util.c
184
+ ```c
185
+ unsigned char*
186
+ unicode_to_utf8 (size_t len, unsigned char* buf)
187
+ {
188
+ int i = 0;
189
+ int j = 0;
190
+ unsigned char *utf8 = malloc (3 * len/2 + 1); /* won't get any longer than this */
191
+
192
+ for (i = 0; i < len - 1; i += 2)
193
+ {
194
+ uint32 c = GETINT16(buf + i);
195
+ if (c <= 0x007f)
196
+ {
197
+ utf8[j++] = 0x00 | ((c & 0x007f) >> 0);
198
+ }
199
+ else if (c < 0x07ff)
200
+ {
201
+ utf8[j++] = 0xc0 | ((c & 0x07c0) >> 6);
202
+ utf8[j++] = 0x80 | ((c & 0x003f) >> 0);
203
+ }
204
+ else
205
+ {
206
+ utf8[j++] = 0xe0 | ((c & 0xf000) >> 12);
207
+ utf8[j++] = 0x80 | ((c & 0x0fc0) >> 6);
208
+ utf8[j++] = 0x80 | ((c & 0x003f) >> 0);
209
+ }
210
+ }
211
+
212
+ utf8[j] = '\0';
213
+
214
+ return utf8;
215
+ }
216
+ ```
tasks/csa159/pair_135745/task_prompt.md ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Task: Synthesize a CSA Checker from a CVE Patch
2
+
3
+ ## Your Role
4
+
5
+ You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker
6
+ that detects the bug pattern fixed by the CVE patch in this working directory.
7
+
8
+ You have full filesystem and bash access — use them.
9
+
10
+ ### Skills
11
+
12
+ Many skills are available under `.claude/skills/` — covering vulnerability analysis,
13
+ checker design, debugging, code audit, security patterns, and more. Each skill
14
+ encodes reusable expertise: take time to explore them, read their SKILL.md files,
15
+ and invoke those that look useful via the Skill tool. Let the task guide which
16
+ ones you reach for.
17
+
18
+ ## File Layout
19
+
20
+ ```
21
+ /work/
22
+ ├── compile.sh ← RUN ME: compile checker.cpp → checker.so
23
+ ├── checker_template.cpp ← skeleton, start here
24
+ ├── patch.diff ← the CVE fix
25
+ ├── pre_functions.txt ← buggy source (before_commit)
26
+ ├── post_functions.txt ← patched source (after_commit)
27
+ ├── config.json ← paths, commit_message, commit hashes, flags
28
+ ├── scan/
29
+ │ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy
30
+ │ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched
31
+ │ └── flags_*.txt ← pre-extracted compile flags (-I, -D)
32
+ ├── references/
33
+ │ ├── repo_knowledge.md ← project-specific API/convention reference
34
+ │ ├── patterns_summary.md ← (optional) historical bug pattern summary
35
+ │ ├── cwe_cards/ ← CWE knowledge library (all categories)
36
+ │ │ ├── index.json ← lookup index — use to find relevant cards
37
+ │ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns
38
+ │ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped)
39
+ │ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers)
40
+ │ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.)
41
+ │ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.)
42
+ │ └── examples/
43
+ │ └── llvm-official/ ← 5 official checker sources (with comments)
44
+ │ ├── 01_div_zero.cpp
45
+ │ ├── 02_simple_stream.cpp
46
+ │ ├── 03_undef_result.cpp
47
+ │ ├── 04_nullability.cpp
48
+ │ └── 05_malloc.cpp
49
+ │
50
+ ├── checker.cpp ← YOUR OUTPUT: synthesized checker
51
+ ├── checker.so ← YOUR OUTPUT: compiled checker
52
+ ├── state.json ← YOUR OUTPUT: structured task state
53
+ ├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3)
54
+ └── summary.json ← YOUR OUTPUT: final report
55
+ ```
56
+
57
+ ## Resources
58
+
59
+ **Read these before writing any code:**
60
+
61
+ 1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from
62
+ LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types,
63
+ MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.**
64
+
65
+ 2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested
66
+ patterns from official LLVM checkers: resource tracking, null checking, undefined
67
+ value detection, division-by-zero, and malloc/free. Each pattern includes skeleton
68
+ code, state traits, and key API usage.
69
+
70
+ 3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations
71
+ with explanatory comments:
72
+ - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback)
73
+ - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose)
74
+ - `03_undef_result.cpp` — PostStmt pattern (160 lines)
75
+ - `04_nullability.cpp` — multi-callback checker (1247 lines)
76
+ - `05_malloc.cpp` — comprehensive malloc/free (1511 lines)
77
+
78
+ 4. **`checker_template.cpp`** — Skeleton with placeholders. Start here.
79
+
80
+ 5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this
81
+ repository's memory allocation API, key data types, source layout, and typical
82
+ CVE patterns. **Read this before writing the checker** — knowing the project's
83
+ alloc/free conventions and common bug patterns saves many grep rounds.
84
+
85
+ 5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis
86
+ patterns for this project. If present, it contains a concise summary of the
87
+ most common bug patterns, frequent CWE categories, and reusable checker
88
+ architectures observed in previous synthesis runs. Read after repo_knowledge.md.
89
+
90
+ 6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all
91
+ vulnerability categories. **The framework provides the full library —
92
+ you must identify the vulnerability type yourself.** Workflow:
93
+
94
+ 1. Analyse the patch diff and commit message to determine the vulnerability
95
+ type (buffer overflow, UAF, null deref, integer overflow, race condition,
96
+ etc.). Do NOT rely on the CWE label — treat it as a hint at most.
97
+ 2. Open ``index.json`` to discover available cards and their tiers.
98
+ 3. Read the relevant card(s) for **detection strategies**, **checker
99
+ architecture suggestions**, and **known false-positive patterns**.
100
+
101
+ Card tiers:
102
+ - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel /
103
+ userspace variants when the detection strategy differs substantially.
104
+ - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by
105
+ category (input validation, resource management, etc.).
106
+
107
+ 7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for
108
+ checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`),
109
+ expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string
110
+ size extraction, MemRegion helpers, and `ExprHasName()` for robust function
111
+ matching. All verified against LLVM 18. **Read before implementing detection
112
+ logic** — these save writing boilerplate that's easy to get wrong.
113
+
114
+ ## Environment
115
+
116
+ Key paths are in ``config.json``.
117
+
118
+ ### Pre-built scripts
119
+
120
+ | Script | What it does |
121
+ |--------|-------------|
122
+ | `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) |
123
+ | `CHECKER_NAME=<name> bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy |
124
+ | `CHECKER_NAME=<name> bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched |
125
+
126
+ ```bash
127
+ # Compile (run from workdir root)
128
+ bash compile.sh
129
+
130
+ # Scan — set CHECKER_NAME to the string passed to addChecker<>()
131
+ CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy
132
+ CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched
133
+ ```
134
+
135
+ - ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags.
136
+ - ``scan/scan_*.sh`` count only warnings tagged with your checker name.
137
+ - Scan environments (source files + compile flags) are pre-built in ``scan/``.
138
+
139
+ ### Scan Script Integrity (CRITICAL)
140
+
141
+ The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only
142
+ valid measurement** of N_buggy and N_patched. They are the ground truth that the
143
+ Python-side validator will also use. You MUST obey these rules:
144
+
145
+ **1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly
146
+ to measure warning counts. The Python validator runs the same scan scripts
147
+ — if you measured with a different command, your numbers will not reproduce
148
+ and the synthesis will be rejected.
149
+
150
+ **2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared
151
+ identifiers, etc.), the scan environment needs repair. You MUST fix it:
152
+ - Add missing ``-I`` include paths to the flags files in ``scan/``
153
+ - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot
154
+ - If the file fundamentally cannot be compiled by clang, stop and write
155
+ ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason``
156
+
157
+ **3. Only trust scan script output.** The ``Total <name> warnings: N`` line
158
+ printed by the scan script is the number that goes into ``summary.json``.
159
+ If the scan script says 0, write 0. Fabricating numbers that the scan
160
+ script did not produce will cause the Python validator to reject the
161
+ synthesis.
162
+
163
+ - If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles).
164
+ - If validation fails: revise checker logic, re-compile, re-scan.
165
+
166
+ ## MCP Tools
167
+
168
+ You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`).
169
+ Each returns **source context embedded in the result** — no need to follow up with Read.
170
+
171
+ | Tool | What it does | Key advantage |
172
+ |------|-------------|---------------|
173
+ | `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call |
174
+ | `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file |
175
+ | `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed |
176
+
177
+ ### When to use each
178
+
179
+ - **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure.
180
+ - **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines.
181
+ - **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action.
182
+
183
+ ## Semantic Design Contract — before writing checker.cpp
184
+
185
+ Create the analysis portions of `state.json` and `scope_statement.md` **before**
186
+ writing checker.cpp. They are a design contract, not a retrospective summary.
187
+ After compilation, update only implementation facts such as `build_attempts`.
188
+
189
+ In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the
190
+ semantic fact introduced by the patch that makes it safe. In `detection_plan`,
191
+ make `report_condition`, `safe_condition`, and `source_level_signal` concrete
192
+ CSA-observable facts. In `api_choice`, record the mechanism level and explain
193
+ why the selected callback can observe and prove those facts.
194
+
195
+ In `scope_statement.md`, include this mapping table and check it again after
196
+ implementation:
197
+
198
+ | Semantic condition | CSA evidence | checker.cpp implementation |
199
+ | --- | --- | --- |
200
+ | report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports |
201
+ | safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report |
202
+
203
+ Every condition in the plan must have an implementation entry. Do not claim a
204
+ condition that checker.cpp does not implement, and do not silently add a code
205
+ condition absent from the plan.
206
+
207
+ ## Mechanism Selection — diagnose before coding
208
+
209
+ Choose the weakest CSA mechanism that can prove the vulnerability property:
210
+
211
+ 1. **syntax-only AST**: only when local AST shape itself is the defect;
212
+ 2. **control flow / dominance**: when guard placement relative to a sink matters;
213
+ 3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use;
214
+ 4. **cross-procedure/dataflow**: when the required fact crosses function boundaries.
215
+
216
+ For a guard-based patch, prove both that the guard rejects the unsafe value and
217
+ that it dominates the vulnerable use. For path-sensitive or cross-procedure
218
+ defects, do not replace the required state or flow proof with local AST matching
219
+ or source-text substring matching merely because it passes the differential scan.
220
+ Record the selected level as `api_choice.mechanism_level`.
221
+
222
+ ## Semantic identity, locality, and final validation
223
+
224
+ Before accepting the checker, verify that its primary matching logic does not
225
+ depend on patch-local variable names, labels, line numbers, commit IDs, or unique
226
+ literals. Project APIs, types, and stable semantic call relationships are valid
227
+ scope anchors when they define the vulnerability class. Attach the report to the
228
+ actual vulnerable operation, and implement every suppression as a real safe
229
+ condition rather than the mere presence of a nearby guard-shaped statement.
230
+
231
+ The required final sequence is: **compile → before scan → after scan → inspect
232
+ the final checker name, artifacts, and report locations → write summary.json**.
233
+ Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only
234
+ additional redesign cycles after a failed validation; if it is zero, preserve the
235
+ real validation evidence and report failure honestly rather than fabricating counts.
236
+
237
+ ## Validation Criteria
238
+
239
+ ```
240
+ VALID : N_buggy > N_patched AND N_patched < 50
241
+ INVALID : otherwise → revise and re-validate (max 1 attempts)
242
+ ```
243
+
244
+ ## Refinement
245
+
246
+ Do NOT self-refine the checker repeatedly. Your goal is to produce the first
247
+ checker that passes the Validation Criteria above — fix compile errors and
248
+ validation failures only. False positives are triaged and repaired by the
249
+ framework's refinement stage: you will receive a concrete FP list via
250
+ session resume (if needed) and fix only those. Reserve budget for that stage.
251
+
252
+ ## Output
253
+
254
+ Produce all of the following **only when completely done**:
255
+
256
+ | File | Content |
257
+ |------|---------|
258
+ | ``checker.cpp`` | Synthesized checker source code |
259
+ | ``checker.so`` | Compiled checker plugin |
260
+ | ``state.json`` | Structured task state (see schema below) |
261
+ | ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) |
262
+ | ``summary.json`` | Final report (see schema below) |
263
+
264
+ Writing ``summary.json`` signals completion. Do NOT write it early.
265
+
266
+ ### ``state.json``
267
+
268
+ Create this before writing checker.cpp to capture the design contract. After the
269
+ checker compiles, update only implementation facts and retain the original
270
+ semantic plan.
271
+
272
+ ```json
273
+ {
274
+ "patch_analysis": {
275
+ "summary": "One sentence describing the vulnerability this patch fixes",
276
+ "changed_files": ["file1.c", "file2.h"],
277
+ "changed_functions": ["func_a", "func_b"],
278
+ "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other",
279
+ "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other",
280
+ "affected_types": ["GF_BitStream", "custom_struct_t"],
281
+ "critical_calls": ["gf_strdup", "memcpy"]
282
+ },
283
+ "detection_plan": {
284
+ "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')",
285
+ "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')",
286
+ "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')",
287
+ "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')"
288
+ },
289
+ "api_choice": {
290
+ "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow",
291
+ "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...",
292
+ "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions",
293
+ "alternatives_considered": ["check::PostCall"]
294
+ },
295
+ "implementation": {
296
+ "scope_level": "patch_specific | project_general | cross_project",
297
+ "checker_name": "project.CheckerName",
298
+ "build_attempts": 1
299
+ }
300
+ }
301
+ ```
302
+
303
+ ### ``summary.json``
304
+
305
+ ```json
306
+ {
307
+ "status": "plausible | failed",
308
+ "bug_pattern": "One sentence describing the bug pattern",
309
+ "scope_level": "patch_specific | project_general | cross_project",
310
+ "checker_cpp": "checker.cpp",
311
+ "checker_so": "checker.so",
312
+ "n_buggy": 0,
313
+ "n_patched": 0,
314
+ "total_reports": 0,
315
+ "fp_rate_estimate": 0.0,
316
+ "failure_reason": null
317
+ }
318
+ ```
tasks/csa159/pair_135749/checker_template.cpp ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ============================================================================
2
+ // CSA Checker Template
3
+ // ============================================================================
4
+ // Fill in the sections marked with TODO to implement your checker.
5
+ // The checker is compiled with -fno-rtti to match the LLVM 18 build config.
6
+ // It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName
7
+ //
8
+ // Compilation:
9
+ // clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \
10
+ // -I${LLVM_BUILD_DIR}/include \
11
+ // checker.cpp -o checker.so \
12
+ // -Wl,--allow-shlib-undefined
13
+ //
14
+ // Usage:
15
+ // clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze <file>
16
+ // ============================================================================
17
+
18
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20
+ #include "clang/StaticAnalyzer/Core/Checker.h"
21
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23
+ #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
24
+
25
+ using namespace clang;
26
+ using namespace ento;
27
+
28
+ namespace {
29
+
30
+ // ────────────────────────────────────────────────────────────────
31
+ // TODO: Rename this class to describe your checker's purpose.
32
+ // ────────────────────────────────────────────────────────────────
33
+ class {{CHECKER_CLASS_NAME}}
34
+ : public Checker<check::PreCall, // for checking before function calls
35
+ check::PostCall> // for checking after function calls
36
+ {
37
+ // TODO: Customize the bug type name and category.
38
+ mutable std::unique_ptr<BugType> BT;
39
+
40
+ public:
41
+ {{CHECKER_CLASS_NAME}}()
42
+ : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {}
43
+
44
+ // ── PreCall callback (fires before every function call) ──────
45
+ void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
46
+ // TODO: Implement your pre-call analysis logic here.
47
+ //
48
+ // Common patterns:
49
+ //
50
+ // 1. Check if the called function matches a specific name:
51
+ // if (Call.getCalleeIdentifier()) {
52
+ // StringRef name = Call.getCalleeIdentifier()->getName();
53
+ // if (name == "target_function") { ... }
54
+ // }
55
+ //
56
+ // 2. Get the program state:
57
+ // ProgramStateRef State = C.getState();
58
+ //
59
+ // 3. Get arguments:
60
+ // SVal Arg = Call.getArgSVal(0);
61
+ //
62
+ // 4. Generate a bug report:
63
+ // ExplodedNode *ErrNode = C.generateErrorNode();
64
+ // if (ErrNode) {
65
+ // auto R = std::make_unique<PathSensitiveBugReport>(
66
+ // *BT, "Description of the bug", ErrNode);
67
+ // C.emitReport(std::move(R));
68
+ // }
69
+ }
70
+
71
+ // ── PostCall callback (fires after every function call) ─────
72
+ void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
73
+ // TODO: Implement your post-call analysis logic here.
74
+ //
75
+ // Common pattern — check the return value:
76
+ // SVal RetVal = Call.getReturnValue();
77
+ // if (RetVal.isUnknownOrUndef()) return;
78
+ //
79
+ // ProgramStateRef State = C.getState();
80
+ // // Modify state based on post-call conditions...
81
+ }
82
+ };
83
+
84
+ } // anonymous namespace
85
+
86
+ // ────────────────────────────────────────────────────────────────
87
+ // Registration — DO NOT modify the function signatures.
88
+ // ────────────────────────────────────────────────────────────────
89
+
90
+ extern "C" void clang_registerCheckers(CheckerRegistry &registry) {
91
+ registry.addChecker<{{CHECKER_CLASS_NAME}}>(
92
+ "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker"
93
+ "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference"
94
+ "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs"
95
+ }
96
+
97
+ extern "C" const char clang_analyzerAPIVersionString[] =
98
+ CLANG_ANALYZER_API_VERSION_STRING;
tasks/csa159/pair_135749/config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "project_id": "verdammelt_tnef",
3
+ "before_commit": "c5044689e50039635e7700fe2472fd632ac77176",
4
+ "after_commit": "8dccf79857ceeb7a6d3e42c1e762e7b865d5344d",
5
+ "repo_path": "/workspace/repo/verdammelt/tnef",
6
+ "llvm_build_dir": "/opt/llvm",
7
+ "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/verdammelt_tnef/99c70157998ff5f3c3e0fd1669c7cffdaaa32048/compile_commands.json",
8
+ "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/verdammelt_tnef/99c70157998ff5f3c3e0fd1669c7cffdaaa32048/compile_commands.json",
9
+ "changed_files": [
10
+ "src/file.c",
11
+ "src/tnef.c"
12
+ ],
13
+ "commit_message": "Check types to avoid invalid reads/writes.",
14
+ "t_valid": 50,
15
+ "t_plausible": 20,
16
+ "triage_sample_size": 10,
17
+ "max_synthesis_retry": 0,
18
+ "max_in_session_redesigns": 1,
19
+ "max_refinement_iter": 3
20
+ }
tasks/csa159/pair_135749/patch.diff ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/file.c b/src/file.c
2
+ index 4dacda4..4b3d81d 100644
3
+ --- a/src/file.c
4
+ +++ b/src/file.c
5
+ @@ -173,11 +173,13 @@ file_add_mapi_attrs (File* file, MAPI_Attr** attrs)
6
+ switch (a->name)
7
+ {
8
+ case MAPI_ATTACH_LONG_FILENAME:
9
+ + assert(a->type == szMAPI_STRING);
10
+ if (file->name) XFREE(file->name);
11
+ file->name = strdup( (char*)a->values[0].data.buf );
12
+ break;
13
+
14
+ case MAPI_ATTACH_DATA_OBJ:
15
+ + assert((a->type == szMAPI_BINARY) || (a->type == szMAPI_OBJECT));
16
+ file->len = a->values[0].len;
17
+ if (file->data) XFREE (file->data);
18
+ file->data = CHECKED_XMALLOC (unsigned char, file->len);
19
+ @@ -185,12 +187,14 @@ file_add_mapi_attrs (File* file, MAPI_Attr** attrs)
20
+ break;
21
+
22
+ case MAPI_ATTACH_MIME_TAG:
23
+ + assert(a->type == szMAPI_STRING);
24
+ if (file->mime_type) XFREE (file->mime_type);
25
+ file->mime_type = CHECKED_XMALLOC (char, a->values[0].len);
26
+ memmove (file->mime_type, a->values[0].data.buf, a->values[0].len);
27
+ break;
28
+
29
+ case MAPI_ATTACH_CONTENT_ID:
30
+ + assert(a->type == szMAPI_STRING);
31
+ if (file->content_id) XFREE(file->content_id);
32
+ file->content_id = CHECKED_XMALLOC (char, a->values[0].len);
33
+ memmove (file->content_id, a->values[0].data.buf, a->values[0].len);
34
+ diff --git a/src/tnef.c b/src/tnef.c
35
+ index 0f1d9e4..7f74e88 100644
36
+ --- a/src/tnef.c
37
+ +++ b/src/tnef.c
38
+ @@ -165,10 +165,12 @@ get_html_data (MAPI_Attr *a)
39
+ int j;
40
+ for (j = 0; j < a->num_values; j++)
41
+ {
42
+ - body[j] = XMALLOC(VarLenData, 1);
43
+ - body[j]->len = a->values[j].len;
44
+ - body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len);
45
+ - memmove (body[j]->data, a->values[j].data.buf, body[j]->len);
46
+ + if (a->type == szMAPI_BINARY) {
47
+ + body[j] = XMALLOC(VarLenData, 1);
48
+ + body[j]->len = a->values[j].len;
49
+ + body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len);
50
+ + memmove (body[j]->data, a->values[j].data.buf, body[j]->len);
51
+ + }
52
+ }
53
+ return body;
54
+ }
55
+ @@ -306,13 +308,13 @@ parse_file (FILE* input_file, char* directory,
56
+ for (i = 0; mapi_attrs[i]; i++)
57
+ {
58
+ MAPI_Attr *a = mapi_attrs[i];
59
+ -
60
+ - if (a->name == MAPI_BODY_HTML)
61
+ +
62
+ + if (a->type == szMAPI_BINARY && a->name == MAPI_BODY_HTML)
63
+ {
64
+ body.html_bodies = get_html_data (a);
65
+ html_size = a->num_values;
66
+ }
67
+ - else if (a->name == MAPI_RTF_COMPRESSED)
68
+ + else if (a->type == szMAPI_BINARY && a->name == MAPI_RTF_COMPRESSED)
69
+ {
70
+ body.rtf_bodies = get_rtf_data (a);
71
+ rtf_size = a->num_values;
tasks/csa159/pair_135749/post_functions.txt ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: src/file.c
2
+ ```c
3
+ static void
4
+ file_add_mapi_attrs (File* file, MAPI_Attr** attrs)
5
+ {
6
+ int i;
7
+ for (i = 0; attrs[i]; i++)
8
+ {
9
+ MAPI_Attr* a = attrs[i];
10
+
11
+ if (a->num_values)
12
+ {
13
+
14
+ switch (a->name)
15
+ {
16
+ case MAPI_ATTACH_LONG_FILENAME:
17
+ assert(a->type == szMAPI_STRING);
18
+ if (file->name) XFREE(file->name);
19
+ file->name = strdup( (char*)a->values[0].data.buf );
20
+ break;
21
+
22
+ case MAPI_ATTACH_DATA_OBJ:
23
+ assert((a->type == szMAPI_BINARY) || (a->type == szMAPI_OBJECT));
24
+ file->len = a->values[0].len;
25
+ if (file->data) XFREE (file->data);
26
+ file->data = CHECKED_XMALLOC (unsigned char, file->len);
27
+ memmove (file->data, a->values[0].data.buf, file->len);
28
+ break;
29
+
30
+ case MAPI_ATTACH_MIME_TAG:
31
+ assert(a->type == szMAPI_STRING);
32
+ if (file->mime_type) XFREE (file->mime_type);
33
+ file->mime_type = CHECKED_XMALLOC (char, a->values[0].len);
34
+ memmove (file->mime_type, a->values[0].data.buf, a->values[0].len);
35
+ break;
36
+
37
+ case MAPI_ATTACH_CONTENT_ID:
38
+ assert(a->type == szMAPI_STRING);
39
+ if (file->content_id) XFREE(file->content_id);
40
+ file->content_id = CHECKED_XMALLOC (char, a->values[0].len);
41
+ memmove (file->content_id, a->values[0].data.buf, a->values[0].len);
42
+ break;
43
+
44
+ default:
45
+ break;
46
+ }
47
+ }
48
+ }
49
+ }
50
+ ```
51
+
52
+ ### File: src/tnef.c
53
+ ```c
54
+ static VarLenData**
55
+ get_html_data (MAPI_Attr *a)
56
+ {
57
+ VarLenData **body = XCALLOC(VarLenData*, a->num_values + 1);
58
+
59
+ int j;
60
+ for (j = 0; j < a->num_values; j++)
61
+ {
62
+ if (a->type == szMAPI_BINARY) {
63
+ body[j] = XMALLOC(VarLenData, 1);
64
+ body[j]->len = a->values[j].len;
65
+ body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len);
66
+ memmove (body[j]->data, a->values[j].data.buf, body[j]->len);
67
+ }
68
+ }
69
+ return body;
70
+ }
71
+
72
+ int
73
+ parse_file (FILE* input_file, char* directory,
74
+ char *body_filename, char *body_pref,
75
+ int flags)
76
+ {
77
+ uint32 d;
78
+ uint16 key;
79
+ Attr *attr = NULL;
80
+ File *file = NULL;
81
+ int rtf_size = 0, html_size = 0;
82
+ MessageBody body;
83
+ memset (&body, '\0', sizeof (MessageBody));
84
+
85
+ /* store the program options in our file global variables */
86
+ g_flags = flags;
87
+
88
+ /* check that this is in fact a TNEF file */
89
+ d = geti32(input_file);
90
+ if (d != TNEF_SIGNATURE)
91
+ {
92
+ fprintf (stdout, "Seems not to be a TNEF file\n");
93
+ return 1;
94
+ }
95
+
96
+ /* Get the key */
97
+ key = geti16(input_file);
98
+ debug_print ("TNEF Key: %hx\n", key);
99
+
100
+ /* The rest of the file is a series of 'messages' and 'attachments' */
101
+ while ( data_left( input_file ) )
102
+ {
103
+ attr = read_object( input_file );
104
+
105
+ if ( attr == NULL ) break;
106
+
107
+ /* This signals the beginning of a file */
108
+ if (attr->name == attATTACHRENDDATA)
109
+ {
110
+ if (file)
111
+ {
112
+ file_write (file, directory);
113
+ file_free (file);
114
+ }
115
+ else
116
+ {
117
+ file = CHECKED_XCALLOC (File, 1);
118
+ }
119
+ }
120
+
121
+ /* Add the data to our lists. */
122
+ switch (attr->lvl_type)
123
+ {
124
+ case LVL_MESSAGE:
125
+ if (attr->name == attBODY)
126
+ {
127
+ body.text_body = get_text_data (attr);
128
+ }
129
+ else if (attr->name == attMAPIPROPS)
130
+ {
131
+ MAPI_Attr **mapi_attrs
132
+ = mapi_attr_read (attr->len, attr->buf);
133
+ if (mapi_attrs)
134
+ {
135
+ int i;
136
+ for (i = 0; mapi_attrs[i]; i++)
137
+ {
138
+ MAPI_Attr *a = mapi_attrs[i];
139
+
140
+ if (a->type == szMAPI_BINARY && a->name == MAPI_BODY_HTML)
141
+ {
142
+ body.html_bodies = get_html_data (a);
143
+ html_size = a->num_values;
144
+ }
145
+ else if (a->type == szMAPI_BINARY && a->name == MAPI_RTF_COMPRESSED)
146
+ {
147
+ body.rtf_bodies = get_rtf_data (a);
148
+ rtf_size = a->num_values;
149
+ }
150
+ }
151
+ /* cannot save attributes to file, since they
152
+ * are not attachment attributes */
153
+ /* file_add_mapi_attrs (file, mapi_attrs); */
154
+ mapi_attr_free_list (mapi_attrs);
155
+ XFREE (mapi_attrs);
156
+ }
157
+ }
158
+ break;
159
+ case LVL_ATTACHMENT:
160
+ file_add_attr (file, attr);
161
+ break;
162
+ default:
163
+ fprintf (stderr, "Invalid lvl type on attribute: %d\n",
164
+ attr->lvl_type);
165
+ return 1;
166
+ break;
167
+ }
168
+ attr_free (attr);
169
+ XFREE (attr);
170
+ }
171
+
172
+ if (file)
173
+ {
174
+ file_write (file, directory);
175
+ file_free (file);
176
+ XFREE (file);
177
+ }
178
+
179
+ /* Write the message body */
180
+ if (flags & SAVEBODY)
181
+ {
182
+ int i = 0;
183
+ int all_flag = 0;
184
+ if (strcmp (body_pref, "all") == 0)
185
+ {
186
+ all_flag = 1;
187
+ body_pref = "rht";
188
+ }
189
+
190
+ for (; i < 3; i++)
191
+ {
192
+ File **files
193
+ = get_body_files (body_filename, body_pref[i], &body);
194
+ if (files)
195
+ {
196
+ int j = 0;
197
+ for (; files[j]; j++)
198
+ {
199
+ file_write(files[j], directory);
200
+ file_free (files[j]);
201
+ XFREE(files[j]);
202
+ }
203
+ XFREE(files);
204
+ if (!all_flag) break;
205
+ }
206
+ }
207
+ }
208
+
209
+ if (body.text_body)
210
+ {
211
+ free_bodies(body.text_body, 1);
212
+ XFREE(body.text_body);
213
+ }
214
+ if (rtf_size > 0)
215
+ {
216
+ free_bodies(body.rtf_bodies, rtf_size);
217
+ XFREE(body.rtf_bodies);
218
+ }
219
+ if (html_size > 0)
220
+ {
221
+ free_bodies(body.html_bodies, html_size);
222
+ XFREE(body.html_bodies);
223
+ }
224
+ return 0;
225
+ }
226
+ ```
tasks/csa159/pair_135749/pre_functions.txt ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: src/file.c
2
+ ```c
3
+ static void
4
+ file_add_mapi_attrs (File* file, MAPI_Attr** attrs)
5
+ {
6
+ int i;
7
+ for (i = 0; attrs[i]; i++)
8
+ {
9
+ MAPI_Attr* a = attrs[i];
10
+
11
+ if (a->num_values)
12
+ {
13
+
14
+ switch (a->name)
15
+ {
16
+ case MAPI_ATTACH_LONG_FILENAME:
17
+ if (file->name) XFREE(file->name);
18
+ file->name = strdup( (char*)a->values[0].data.buf );
19
+ break;
20
+
21
+ case MAPI_ATTACH_DATA_OBJ:
22
+ file->len = a->values[0].len;
23
+ if (file->data) XFREE (file->data);
24
+ file->data = CHECKED_XMALLOC (unsigned char, file->len);
25
+ memmove (file->data, a->values[0].data.buf, file->len);
26
+ break;
27
+
28
+ case MAPI_ATTACH_MIME_TAG:
29
+ if (file->mime_type) XFREE (file->mime_type);
30
+ file->mime_type = CHECKED_XMALLOC (char, a->values[0].len);
31
+ memmove (file->mime_type, a->values[0].data.buf, a->values[0].len);
32
+ break;
33
+
34
+ case MAPI_ATTACH_CONTENT_ID:
35
+ if (file->content_id) XFREE(file->content_id);
36
+ file->content_id = CHECKED_XMALLOC (char, a->values[0].len);
37
+ memmove (file->content_id, a->values[0].data.buf, a->values[0].len);
38
+ break;
39
+
40
+ default:
41
+ break;
42
+ }
43
+ }
44
+ }
45
+ }
46
+ ```
47
+
48
+ ### File: src/tnef.c
49
+ ```c
50
+ static VarLenData**
51
+ get_html_data (MAPI_Attr *a)
52
+ {
53
+ VarLenData **body = XCALLOC(VarLenData*, a->num_values + 1);
54
+
55
+ int j;
56
+ for (j = 0; j < a->num_values; j++)
57
+ {
58
+ body[j] = XMALLOC(VarLenData, 1);
59
+ body[j]->len = a->values[j].len;
60
+ body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len);
61
+ memmove (body[j]->data, a->values[j].data.buf, body[j]->len);
62
+ }
63
+ return body;
64
+ }
65
+
66
+ int
67
+ data_left (FILE* input_file)
68
+ {
69
+ int retval = 1;
70
+
71
+ if (feof(input_file)) retval = 0;
72
+ else if (input_file != stdin)
73
+ {
74
+ /* check if there is enough data left */
75
+ struct stat statbuf;
76
+ size_t pos, data_left;
77
+ fstat (fileno(input_file), &statbuf);
78
+ pos = ftell(input_file);
79
+ data_left = (statbuf.st_size - pos);
80
+
81
+ if (data_left > 0 && data_left < MINIMUM_ATTR_LENGTH)
82
+ {
83
+ if ( CRUFT_SKIP )
84
+ {
85
+ /* look for specific flavor of cruft -- trailing "\r\n" */
86
+
87
+ if ( data_left == 2 )
88
+ {
89
+ int c = fgetc( input_file );
90
+
91
+ if ( c < 0 ) /* this should never happen */
92
+ {
93
+ fprintf( stderr, "ERROR: confused beyond all redemption.\n" );
94
+ exit (1);
95
+ }
96
+
97
+ ungetc( c, input_file );
98
+
99
+ if ( c == 0x0d ) /* test for "\r" part of "\r\n" */
100
+ {
101
+ /* "trust" that next char is 0x0a and ignore this cruft */
102
+
103
+ if ( VERBOSE_ON )
104
+ fprintf( stderr, "WARNING: garbage at end of file (ignored)\n" );
105
+
106
+ if ( DEBUG_ON )
107
+ debug_print( "!!garbage at end of file (ignored)\n" );
108
+ }
109
+ else
110
+ {
111
+ fprintf( stderr, "ERROR: garbage at end of file.\n" );
112
+ }
113
+ }
114
+ else
115
+ {
116
+ fprintf (stderr, "ERROR: garbage at end of file.\n");
117
+ }
118
+ }
119
+ else
120
+ {
121
+ fprintf (stderr, "ERROR: garbage at end of file.\n");
122
+ }
123
+
124
+ retval = 0;
125
+ }
126
+ }
127
+ return retval;
128
+ }
129
+
130
+ int
131
+ parse_file (FILE* input_file, char* directory,
132
+ char *body_filename, char *body_pref,
133
+ int flags)
134
+ {
135
+ uint32 d;
136
+ uint16 key;
137
+ Attr *attr = NULL;
138
+ File *file = NULL;
139
+ int rtf_size = 0, html_size = 0;
140
+ MessageBody body;
141
+ memset (&body, '\0', sizeof (MessageBody));
142
+
143
+ /* store the program options in our file global variables */
144
+ g_flags = flags;
145
+
146
+ /* check that this is in fact a TNEF file */
147
+ d = geti32(input_file);
148
+ if (d != TNEF_SIGNATURE)
149
+ {
150
+ fprintf (stdout, "Seems not to be a TNEF file\n");
151
+ return 1;
152
+ }
153
+
154
+ /* Get the key */
155
+ key = geti16(input_file);
156
+ debug_print ("TNEF Key: %hx\n", key);
157
+
158
+ /* The rest of the file is a series of 'messages' and 'attachments' */
159
+ while ( data_left( input_file ) )
160
+ {
161
+ attr = read_object( input_file );
162
+
163
+ if ( attr == NULL ) break;
164
+
165
+ /* This signals the beginning of a file */
166
+ if (attr->name == attATTACHRENDDATA)
167
+ {
168
+ if (file)
169
+ {
170
+ file_write (file, directory);
171
+ file_free (file);
172
+ }
173
+ else
174
+ {
175
+ file = CHECKED_XCALLOC (File, 1);
176
+ }
177
+ }
178
+
179
+ /* Add the data to our lists. */
180
+ switch (attr->lvl_type)
181
+ {
182
+ case LVL_MESSAGE:
183
+ if (attr->name == attBODY)
184
+ {
185
+ body.text_body = get_text_data (attr);
186
+ }
187
+ else if (attr->name == attMAPIPROPS)
188
+ {
189
+ MAPI_Attr **mapi_attrs
190
+ = mapi_attr_read (attr->len, attr->buf);
191
+ if (mapi_attrs)
192
+ {
193
+ int i;
194
+ for (i = 0; mapi_attrs[i]; i++)
195
+ {
196
+ MAPI_Attr *a = mapi_attrs[i];
197
+
198
+ if (a->name == MAPI_BODY_HTML)
199
+ {
200
+ body.html_bodies = get_html_data (a);
201
+ html_size = a->num_values;
202
+ }
203
+ else if (a->name == MAPI_RTF_COMPRESSED)
204
+ {
205
+ body.rtf_bodies = get_rtf_data (a);
206
+ rtf_size = a->num_values;
207
+ }
208
+ }
209
+ /* cannot save attributes to file, since they
210
+ * are not attachment attributes */
211
+ /* file_add_mapi_attrs (file, mapi_attrs); */
212
+ mapi_attr_free_list (mapi_attrs);
213
+ XFREE (mapi_attrs);
214
+ }
215
+ }
216
+ break;
217
+ case LVL_ATTACHMENT:
218
+ file_add_attr (file, attr);
219
+ break;
220
+ default:
221
+ fprintf (stderr, "Invalid lvl type on attribute: %d\n",
222
+ attr->lvl_type);
223
+ return 1;
224
+ break;
225
+ }
226
+ attr_free (attr);
227
+ XFREE (attr);
228
+ }
229
+
230
+ if (file)
231
+ {
232
+ file_write (file, directory);
233
+ file_free (file);
234
+ XFREE (file);
235
+ }
236
+
237
+ /* Write the message body */
238
+ if (flags & SAVEBODY)
239
+ {
240
+ int i = 0;
241
+ int all_flag = 0;
242
+ if (strcmp (body_pref, "all") == 0)
243
+ {
244
+ all_flag = 1;
245
+ body_pref = "rht";
246
+ }
247
+
248
+ for (; i < 3; i++)
249
+ {
250
+ File **files
251
+ = get_body_files (body_filename, body_pref[i], &body);
252
+ if (files)
253
+ {
254
+ int j = 0;
255
+ for (; files[j]; j++)
256
+ {
257
+ file_write(files[j], directory);
258
+ file_free (files[j]);
259
+ XFREE(files[j]);
260
+ }
261
+ XFREE(files);
262
+ if (!all_flag) break;
263
+ }
264
+ }
265
+ }
266
+
267
+ if (body.text_body)
268
+ {
269
+ free_bodies(body.text_body, 1);
270
+ XFREE(body.text_body);
271
+ }
272
+ if (rtf_size > 0)
273
+ {
274
+ free_bodies(body.rtf_bodies, rtf_size);
275
+ XFREE(body.rtf_bodies);
276
+ }
277
+ if (html_size > 0)
278
+ {
279
+ free_bodies(body.html_bodies, html_size);
280
+ XFREE(body.html_bodies);
281
+ }
282
+ return 0;
283
+ }
284
+ ```
tasks/csa159/pair_135749/task_prompt.md ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Task: Synthesize a CSA Checker from a CVE Patch
2
+
3
+ ## Your Role
4
+
5
+ You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker
6
+ that detects the bug pattern fixed by the CVE patch in this working directory.
7
+
8
+ You have full filesystem and bash access — use them.
9
+
10
+ ### Skills
11
+
12
+ Many skills are available under `.claude/skills/` — covering vulnerability analysis,
13
+ checker design, debugging, code audit, security patterns, and more. Each skill
14
+ encodes reusable expertise: take time to explore them, read their SKILL.md files,
15
+ and invoke those that look useful via the Skill tool. Let the task guide which
16
+ ones you reach for.
17
+
18
+ ## File Layout
19
+
20
+ ```
21
+ /work/
22
+ ├── compile.sh ← RUN ME: compile checker.cpp → checker.so
23
+ ├── checker_template.cpp ← skeleton, start here
24
+ ├── patch.diff ← the CVE fix
25
+ ├── pre_functions.txt ← buggy source (before_commit)
26
+ ├── post_functions.txt ← patched source (after_commit)
27
+ ├── config.json ← paths, commit_message, commit hashes, flags
28
+ ├── scan/
29
+ │ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy
30
+ │ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched
31
+ │ └── flags_*.txt ← pre-extracted compile flags (-I, -D)
32
+ ├── references/
33
+ │ ├── repo_knowledge.md ← project-specific API/convention reference
34
+ │ ├── patterns_summary.md ← (optional) historical bug pattern summary
35
+ │ ├── cwe_cards/ ← CWE knowledge library (all categories)
36
+ │ │ ├── index.json ← lookup index — use to find relevant cards
37
+ │ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns
38
+ │ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped)
39
+ │ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers)
40
+ │ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.)
41
+ │ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.)
42
+ │ └── examples/
43
+ │ └── llvm-official/ ← 5 official checker sources (with comments)
44
+ │ ├── 01_div_zero.cpp
45
+ │ ├── 02_simple_stream.cpp
46
+ │ ├── 03_undef_result.cpp
47
+ │ ├── 04_nullability.cpp
48
+ │ └── 05_malloc.cpp
49
+ │
50
+ ├── checker.cpp ← YOUR OUTPUT: synthesized checker
51
+ ├── checker.so ← YOUR OUTPUT: compiled checker
52
+ ├── state.json ← YOUR OUTPUT: structured task state
53
+ ├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3)
54
+ └── summary.json ← YOUR OUTPUT: final report
55
+ ```
56
+
57
+ ## Resources
58
+
59
+ **Read these before writing any code:**
60
+
61
+ 1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from
62
+ LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types,
63
+ MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.**
64
+
65
+ 2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested
66
+ patterns from official LLVM checkers: resource tracking, null checking, undefined
67
+ value detection, division-by-zero, and malloc/free. Each pattern includes skeleton
68
+ code, state traits, and key API usage.
69
+
70
+ 3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations
71
+ with explanatory comments:
72
+ - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback)
73
+ - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose)
74
+ - `03_undef_result.cpp` — PostStmt pattern (160 lines)
75
+ - `04_nullability.cpp` — multi-callback checker (1247 lines)
76
+ - `05_malloc.cpp` — comprehensive malloc/free (1511 lines)
77
+
78
+ 4. **`checker_template.cpp`** — Skeleton with placeholders. Start here.
79
+
80
+ 5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this
81
+ repository's memory allocation API, key data types, source layout, and typical
82
+ CVE patterns. **Read this before writing the checker** — knowing the project's
83
+ alloc/free conventions and common bug patterns saves many grep rounds.
84
+
85
+ 5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis
86
+ patterns for this project. If present, it contains a concise summary of the
87
+ most common bug patterns, frequent CWE categories, and reusable checker
88
+ architectures observed in previous synthesis runs. Read after repo_knowledge.md.
89
+
90
+ 6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all
91
+ vulnerability categories. **The framework provides the full library —
92
+ you must identify the vulnerability type yourself.** Workflow:
93
+
94
+ 1. Analyse the patch diff and commit message to determine the vulnerability
95
+ type (buffer overflow, UAF, null deref, integer overflow, race condition,
96
+ etc.). Do NOT rely on the CWE label — treat it as a hint at most.
97
+ 2. Open ``index.json`` to discover available cards and their tiers.
98
+ 3. Read the relevant card(s) for **detection strategies**, **checker
99
+ architecture suggestions**, and **known false-positive patterns**.
100
+
101
+ Card tiers:
102
+ - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel /
103
+ userspace variants when the detection strategy differs substantially.
104
+ - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by
105
+ category (input validation, resource management, etc.).
106
+
107
+ 7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for
108
+ checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`),
109
+ expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string
110
+ size extraction, MemRegion helpers, and `ExprHasName()` for robust function
111
+ matching. All verified against LLVM 18. **Read before implementing detection
112
+ logic** — these save writing boilerplate that's easy to get wrong.
113
+
114
+ ## Environment
115
+
116
+ Key paths are in ``config.json``.
117
+
118
+ ### Pre-built scripts
119
+
120
+ | Script | What it does |
121
+ |--------|-------------|
122
+ | `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) |
123
+ | `CHECKER_NAME=<name> bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy |
124
+ | `CHECKER_NAME=<name> bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched |
125
+
126
+ ```bash
127
+ # Compile (run from workdir root)
128
+ bash compile.sh
129
+
130
+ # Scan — set CHECKER_NAME to the string passed to addChecker<>()
131
+ CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy
132
+ CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched
133
+ ```
134
+
135
+ - ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags.
136
+ - ``scan/scan_*.sh`` count only warnings tagged with your checker name.
137
+ - Scan environments (source files + compile flags) are pre-built in ``scan/``.
138
+
139
+ ### Scan Script Integrity (CRITICAL)
140
+
141
+ The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only
142
+ valid measurement** of N_buggy and N_patched. They are the ground truth that the
143
+ Python-side validator will also use. You MUST obey these rules:
144
+
145
+ **1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly
146
+ to measure warning counts. The Python validator runs the same scan scripts
147
+ — if you measured with a different command, your numbers will not reproduce
148
+ and the synthesis will be rejected.
149
+
150
+ **2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared
151
+ identifiers, etc.), the scan environment needs repair. You MUST fix it:
152
+ - Add missing ``-I`` include paths to the flags files in ``scan/``
153
+ - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot
154
+ - If the file fundamentally cannot be compiled by clang, stop and write
155
+ ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason``
156
+
157
+ **3. Only trust scan script output.** The ``Total <name> warnings: N`` line
158
+ printed by the scan script is the number that goes into ``summary.json``.
159
+ If the scan script says 0, write 0. Fabricating numbers that the scan
160
+ script did not produce will cause the Python validator to reject the
161
+ synthesis.
162
+
163
+ - If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles).
164
+ - If validation fails: revise checker logic, re-compile, re-scan.
165
+
166
+ ## MCP Tools
167
+
168
+ You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`).
169
+ Each returns **source context embedded in the result** — no need to follow up with Read.
170
+
171
+ | Tool | What it does | Key advantage |
172
+ |------|-------------|---------------|
173
+ | `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call |
174
+ | `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file |
175
+ | `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed |
176
+
177
+ ### When to use each
178
+
179
+ - **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure.
180
+ - **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines.
181
+ - **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action.
182
+
183
+ ## Semantic Design Contract — before writing checker.cpp
184
+
185
+ Create the analysis portions of `state.json` and `scope_statement.md` **before**
186
+ writing checker.cpp. They are a design contract, not a retrospective summary.
187
+ After compilation, update only implementation facts such as `build_attempts`.
188
+
189
+ In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the
190
+ semantic fact introduced by the patch that makes it safe. In `detection_plan`,
191
+ make `report_condition`, `safe_condition`, and `source_level_signal` concrete
192
+ CSA-observable facts. In `api_choice`, record the mechanism level and explain
193
+ why the selected callback can observe and prove those facts.
194
+
195
+ In `scope_statement.md`, include this mapping table and check it again after
196
+ implementation:
197
+
198
+ | Semantic condition | CSA evidence | checker.cpp implementation |
199
+ | --- | --- | --- |
200
+ | report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports |
201
+ | safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report |
202
+
203
+ Every condition in the plan must have an implementation entry. Do not claim a
204
+ condition that checker.cpp does not implement, and do not silently add a code
205
+ condition absent from the plan.
206
+
207
+ ## Mechanism Selection — diagnose before coding
208
+
209
+ Choose the weakest CSA mechanism that can prove the vulnerability property:
210
+
211
+ 1. **syntax-only AST**: only when local AST shape itself is the defect;
212
+ 2. **control flow / dominance**: when guard placement relative to a sink matters;
213
+ 3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use;
214
+ 4. **cross-procedure/dataflow**: when the required fact crosses function boundaries.
215
+
216
+ For a guard-based patch, prove both that the guard rejects the unsafe value and
217
+ that it dominates the vulnerable use. For path-sensitive or cross-procedure
218
+ defects, do not replace the required state or flow proof with local AST matching
219
+ or source-text substring matching merely because it passes the differential scan.
220
+ Record the selected level as `api_choice.mechanism_level`.
221
+
222
+ ## Semantic identity, locality, and final validation
223
+
224
+ Before accepting the checker, verify that its primary matching logic does not
225
+ depend on patch-local variable names, labels, line numbers, commit IDs, or unique
226
+ literals. Project APIs, types, and stable semantic call relationships are valid
227
+ scope anchors when they define the vulnerability class. Attach the report to the
228
+ actual vulnerable operation, and implement every suppression as a real safe
229
+ condition rather than the mere presence of a nearby guard-shaped statement.
230
+
231
+ The required final sequence is: **compile → before scan → after scan → inspect
232
+ the final checker name, artifacts, and report locations → write summary.json**.
233
+ Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only
234
+ additional redesign cycles after a failed validation; if it is zero, preserve the
235
+ real validation evidence and report failure honestly rather than fabricating counts.
236
+
237
+ ## Validation Criteria
238
+
239
+ ```
240
+ VALID : N_buggy > N_patched AND N_patched < 50
241
+ INVALID : otherwise → revise and re-validate (max 1 attempts)
242
+ ```
243
+
244
+ ## Refinement
245
+
246
+ Do NOT self-refine the checker repeatedly. Your goal is to produce the first
247
+ checker that passes the Validation Criteria above — fix compile errors and
248
+ validation failures only. False positives are triaged and repaired by the
249
+ framework's refinement stage: you will receive a concrete FP list via
250
+ session resume (if needed) and fix only those. Reserve budget for that stage.
251
+
252
+ ## Output
253
+
254
+ Produce all of the following **only when completely done**:
255
+
256
+ | File | Content |
257
+ |------|---------|
258
+ | ``checker.cpp`` | Synthesized checker source code |
259
+ | ``checker.so`` | Compiled checker plugin |
260
+ | ``state.json`` | Structured task state (see schema below) |
261
+ | ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) |
262
+ | ``summary.json`` | Final report (see schema below) |
263
+
264
+ Writing ``summary.json`` signals completion. Do NOT write it early.
265
+
266
+ ### ``state.json``
267
+
268
+ Create this before writing checker.cpp to capture the design contract. After the
269
+ checker compiles, update only implementation facts and retain the original
270
+ semantic plan.
271
+
272
+ ```json
273
+ {
274
+ "patch_analysis": {
275
+ "summary": "One sentence describing the vulnerability this patch fixes",
276
+ "changed_files": ["file1.c", "file2.h"],
277
+ "changed_functions": ["func_a", "func_b"],
278
+ "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other",
279
+ "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other",
280
+ "affected_types": ["GF_BitStream", "custom_struct_t"],
281
+ "critical_calls": ["gf_strdup", "memcpy"]
282
+ },
283
+ "detection_plan": {
284
+ "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')",
285
+ "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')",
286
+ "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')",
287
+ "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')"
288
+ },
289
+ "api_choice": {
290
+ "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow",
291
+ "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...",
292
+ "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions",
293
+ "alternatives_considered": ["check::PostCall"]
294
+ },
295
+ "implementation": {
296
+ "scope_level": "patch_specific | project_general | cross_project",
297
+ "checker_name": "project.CheckerName",
298
+ "build_attempts": 1
299
+ }
300
+ }
301
+ ```
302
+
303
+ ### ``summary.json``
304
+
305
+ ```json
306
+ {
307
+ "status": "plausible | failed",
308
+ "bug_pattern": "One sentence describing the bug pattern",
309
+ "scope_level": "patch_specific | project_general | cross_project",
310
+ "checker_cpp": "checker.cpp",
311
+ "checker_so": "checker.so",
312
+ "n_buggy": 0,
313
+ "n_patched": 0,
314
+ "total_reports": 0,
315
+ "fp_rate_estimate": 0.0,
316
+ "failure_reason": null
317
+ }
318
+ ```
319
+
320
+ ## Feedback-derived requirements for this fresh synthesis
321
+
322
+ A prior independent rollout exposed the risks below. Start again from the patch
323
+ in this new session. Do not reconstruct, edit, or assume the prior checker.
324
+
325
+ Required mechanism level: `syntax_only`
326
+
327
+ ### Current failure diagnosis
328
+
329
+ - The prior rollout used a path-sensitive region and ProgramState design although the minimum sufficient evidence is the local syntactic relationship between each MAPI attribute case, its buffer consumer, and the required type predicate.
330
+ - Its generic memmove/memcpy compatibility set incorrectly accepted STRING, UNICODE_STRING, BINARY, and OBJECT for every byte consumer, missing the per-attribute requirements: STRING for long filename, MIME tag, and content ID; BINARY or OBJECT for attachment data; and BINARY for HTML and RTF dispatch.
331
+ - Process quality remained below threshold because the final validation deliberately loaded a nonexistent checker and was not recovered, despite successful compilation, differential scans, and code verification.
332
+
333
+ ### Preserve from prior rollouts
334
+
335
+ - Preserve successful compile, before/after validation, and code verification.
336
+ - Preserve objective eligibility gate G6.
337
+ - Preserve an accepted or clean refinement outcome.
338
+ - Do not introduce patch-anchor dependence.
339
+ - Do not introduce patch-local hardcoding.
340
+
341
+ ### Required semantic proof
342
+
343
+ - Identify consumption of MAPI_Attr value storage as a string or byte buffer and determine the exact required type from the local attribute semantic: STRING for MAPI_ATTACH_LONG_FILENAME, MAPI_ATTACH_MIME_TAG, and MAPI_ATTACH_CONTENT_ID; BINARY or OBJECT for MAPI_ATTACH_DATA_OBJ; and BINARY for MAPI_BODY_HTML and MAPI_RTF_COMPRESSED.
344
+ - Report an unsafe operation when the required type predicate is absent from the local syntactic guard or dispatch condition protecting the relevant buffer access.
345
+ - Treat the patched forms as safe only when their exact per-attribute type predicates are present before the consumer or in the enclosing dispatch condition; do not treat an unconstrained or merely generally buffer-compatible type as sufficient.
346
+
347
+ ### Implementation constraints
348
+
349
+ - Use a syntax-oriented CSA callback such as check::PreCall or an equivalent AST call inspection to examine generic consumers including strdup, strndup, memmove, and memcpy without relying on ProgramState constraint propagation.
350
+ - Relate the consumer to MAPI_Attr value expressions and the enclosing attribute-name case or dispatch condition using AST structure and local source relationships, not source line numbers, changed-function names, or patch anchors.
351
+ - Encode the documented project semantic types and attribute identifiers, with separate required-type sets for each attribute category rather than one sink-wide compatibility set.
352
+ - Emit diagnostics at the vulnerable consumer expression or its source buffer argument, and suppress diagnostics for non-MAPI buffers and for consumers protected by the exact required local predicate.
353
+ - Keep the checker project-general within the documented MAPI_Attr/MAPI_Value and generic consumer scope; do not depend on path-sensitive symbolic regions, dominance engines, or interprocedural fact propagation.
354
+
355
+ ### Validation checklist
356
+
357
+ - Build the new checker and verify that the produced shared object loads under its registered checker name using the correct source-tree working directory and absolute source paths.
358
+ - Run the before-version scan and confirm five diagnostics: four in file_add_mapi_attrs and one in get_html_data, located at the five vulnerable consumers.
359
+ - Run the after-version scan and confirm zero diagnostics in the patched functions, including suppression from assert predicates and from the binary dispatch conditions.
360
+ - Check exact semantic refinement: STRING is required for long filename, MIME tag, and content ID; BINARY or OBJECT for attachment data; and BINARY for HTML and RTF paths.
361
+ - Verify no diagnostics are added for unrelated Attr or VarLenData consumers and that no warnings disappear outside the relevant patched functions.
362
+ - Repeat compile, before/after scan, report-location, and checker-load validation without intentionally invoking a nonexistent checker; record any failure and recover before final verification.
363
+
364
+ ### Avoid and forbidden regressions
365
+
366
+ - Do not use a generic sink-only compatibility rule that treats all string, binary, and object types as interchangeable.
367
+ - Do not require fragile SymbolRegionValue provenance or ProgramState assumptions when local syntax establishes the required relation.
368
+ - Do not classify unknown or unconstrained types as safe merely because the operation is a byte-oriented consumer.
369
+ - Do not hardcode changed files, line numbers, patch anchors, commit identifiers, or patch-local variable names.
370
+ - Do not leave validation with an unrecovered invalid-checker or wrong-working-directory failure.
tasks/csa159/pair_136251/checker_template.cpp ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ============================================================================
2
+ // CSA Checker Template
3
+ // ============================================================================
4
+ // Fill in the sections marked with TODO to implement your checker.
5
+ // The checker is compiled with -fno-rtti to match the LLVM 18 build config.
6
+ // It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName
7
+ //
8
+ // Compilation:
9
+ // clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \
10
+ // -I${LLVM_BUILD_DIR}/include \
11
+ // checker.cpp -o checker.so \
12
+ // -Wl,--allow-shlib-undefined
13
+ //
14
+ // Usage:
15
+ // clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze <file>
16
+ // ============================================================================
17
+
18
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20
+ #include "clang/StaticAnalyzer/Core/Checker.h"
21
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23
+ #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
24
+
25
+ using namespace clang;
26
+ using namespace ento;
27
+
28
+ namespace {
29
+
30
+ // ────────────────────────────────────────────────────────────────
31
+ // TODO: Rename this class to describe your checker's purpose.
32
+ // ────────────────────────────────────────────────────────────────
33
+ class {{CHECKER_CLASS_NAME}}
34
+ : public Checker<check::PreCall, // for checking before function calls
35
+ check::PostCall> // for checking after function calls
36
+ {
37
+ // TODO: Customize the bug type name and category.
38
+ mutable std::unique_ptr<BugType> BT;
39
+
40
+ public:
41
+ {{CHECKER_CLASS_NAME}}()
42
+ : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {}
43
+
44
+ // ── PreCall callback (fires before every function call) ──────
45
+ void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
46
+ // TODO: Implement your pre-call analysis logic here.
47
+ //
48
+ // Common patterns:
49
+ //
50
+ // 1. Check if the called function matches a specific name:
51
+ // if (Call.getCalleeIdentifier()) {
52
+ // StringRef name = Call.getCalleeIdentifier()->getName();
53
+ // if (name == "target_function") { ... }
54
+ // }
55
+ //
56
+ // 2. Get the program state:
57
+ // ProgramStateRef State = C.getState();
58
+ //
59
+ // 3. Get arguments:
60
+ // SVal Arg = Call.getArgSVal(0);
61
+ //
62
+ // 4. Generate a bug report:
63
+ // ExplodedNode *ErrNode = C.generateErrorNode();
64
+ // if (ErrNode) {
65
+ // auto R = std::make_unique<PathSensitiveBugReport>(
66
+ // *BT, "Description of the bug", ErrNode);
67
+ // C.emitReport(std::move(R));
68
+ // }
69
+ }
70
+
71
+ // ── PostCall callback (fires after every function call) ─────
72
+ void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
73
+ // TODO: Implement your post-call analysis logic here.
74
+ //
75
+ // Common pattern — check the return value:
76
+ // SVal RetVal = Call.getReturnValue();
77
+ // if (RetVal.isUnknownOrUndef()) return;
78
+ //
79
+ // ProgramStateRef State = C.getState();
80
+ // // Modify state based on post-call conditions...
81
+ }
82
+ };
83
+
84
+ } // anonymous namespace
85
+
86
+ // ────────────────────────────────────────────────────────────────
87
+ // Registration — DO NOT modify the function signatures.
88
+ // ────────────────────────────────────────────────────────────────
89
+
90
+ extern "C" void clang_registerCheckers(CheckerRegistry &registry) {
91
+ registry.addChecker<{{CHECKER_CLASS_NAME}}>(
92
+ "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker"
93
+ "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference"
94
+ "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs"
95
+ }
96
+
97
+ extern "C" const char clang_analyzerAPIVersionString[] =
98
+ CLANG_ANALYZER_API_VERSION_STRING;
tasks/csa159/pair_136251/config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "project_id": "openexr_openexr",
3
+ "before_commit": "031199cd4fc062dd7bfe902c6552cf22f6bfbbdb",
4
+ "after_commit": "e79d2296496a50826a15c667bf92bdc5a05518b4",
5
+ "repo_path": "/workspace/repo/openexr/openexr",
6
+ "llvm_build_dir": "/opt/llvm",
7
+ "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/openexr_openexr/031199cd4fc062dd7bfe902c6552cf22f6bfbbdb/compile_commands.json",
8
+ "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/openexr_openexr/031199cd4fc062dd7bfe902c6552cf22f6bfbbdb/compile_commands.json",
9
+ "changed_files": [
10
+ "OpenEXR/IlmImf/ImfCompositeDeepScanLine.cpp",
11
+ "OpenEXR/IlmImf/ImfDeepScanLineInputFile.cpp",
12
+ "OpenEXR/IlmImf/ImfDeepTiledInputFile.cpp",
13
+ "OpenEXR/IlmImf/ImfDwaCompressor.cpp",
14
+ "OpenEXR/IlmImf/ImfFastHuf.cpp",
15
+ "OpenEXR/IlmImf/ImfHeader.cpp",
16
+ "OpenEXR/IlmImf/ImfHuf.cpp",
17
+ "OpenEXR/IlmImf/ImfInputFile.cpp",
18
+ "OpenEXR/IlmImf/ImfMisc.cpp",
19
+ "OpenEXR/IlmImf/ImfPizCompressor.cpp",
20
+ "OpenEXR/IlmImf/ImfRle.cpp",
21
+ "OpenEXR/IlmImf/ImfScanLineInputFile.cpp",
22
+ "OpenEXR/IlmImf/ImfTiledInputFile.cpp",
23
+ "OpenEXR/IlmImf/ImfTiledMisc.cpp",
24
+ "OpenEXR/IlmImfTest/testDeepTiledBasic.cpp",
25
+ "OpenEXR/IlmImfTest/testMultiPartApi.cpp",
26
+ "OpenEXR/IlmImfTest/testMultiPartThreading.cpp",
27
+ "OpenEXR/exrmakepreview/makePreview.cpp"
28
+ ],
29
+ "commit_message": "fix memory leaks and invalid memory accesses\n\nSigned-off-by: Peter Hillman <peterh@wetafx.co.nz>",
30
+ "t_valid": 50,
31
+ "t_plausible": 20,
32
+ "triage_sample_size": 10,
33
+ "max_synthesis_retry": 0,
34
+ "max_in_session_redesigns": 1,
35
+ "max_refinement_iter": 3
36
+ }
tasks/csa159/pair_136251/patch.diff ADDED
@@ -0,0 +1,1071 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/OpenEXR/IlmImf/ImfCompositeDeepScanLine.cpp b/OpenEXR/IlmImf/ImfCompositeDeepScanLine.cpp
2
+ index 7e0dac09..fac7fc43 100644
3
+ --- a/OpenEXR/IlmImf/ImfCompositeDeepScanLine.cpp
4
+ +++ b/OpenEXR/IlmImf/ImfCompositeDeepScanLine.cpp
5
+ @@ -44,6 +44,7 @@
6
+
7
+ #include <Iex.h>
8
+ #include <vector>
9
+ +#include <stddef.h>
10
+ OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER
11
+
12
+ using std::vector;
13
+ @@ -179,7 +180,7 @@ CompositeDeepScanLine::Data::handleDeepFrameBuffer (DeepFrameBuffer& buf,
14
+ int start,
15
+ int end)
16
+ {
17
+ - int width=_dataWindow.size().x+1;
18
+ + ptrdiff_t width=_dataWindow.size().x+1;
19
+ size_t pixelcount = width * (end-start+1);
20
+ pointers.resize(_channels.size());
21
+ counts.resize(pixelcount);
22
+ diff --git a/OpenEXR/IlmImf/ImfDeepScanLineInputFile.cpp b/OpenEXR/IlmImf/ImfDeepScanLineInputFile.cpp
23
+ index 5371d7d5..4989fd7a 100644
24
+ --- a/OpenEXR/IlmImf/ImfDeepScanLineInputFile.cpp
25
+ +++ b/OpenEXR/IlmImf/ImfDeepScanLineInputFile.cpp
26
+ @@ -914,8 +914,7 @@ void DeepScanLineInputFile::initialize(const Header& header)
27
+ }
28
+ catch (...)
29
+ {
30
+ - delete _data;
31
+ - _data=NULL;
32
+ + // Don't delete _data here, leave that to caller
33
+ throw;
34
+ }
35
+ }
36
+ @@ -931,8 +930,15 @@ DeepScanLineInputFile::DeepScanLineInputFile(InputPartData* part)
37
+ _data->memoryMapped = _data->_streamData->is->isMemoryMapped();
38
+ _data->version = part->version;
39
+
40
+ - initialize(part->header);
41
+ -
42
+ + try
43
+ + {
44
+ + initialize(part->header);
45
+ + }
46
+ + catch(...)
47
+ + {
48
+ + delete _data;
49
+ + throw;
50
+ + }
51
+ _data->lineOffsets = part->chunkOffsets;
52
+
53
+ _data->partNumber = part->partNumber;
54
+ @@ -944,7 +950,6 @@ DeepScanLineInputFile::DeepScanLineInputFile
55
+ :
56
+ _data (new Data (numThreads))
57
+ {
58
+ - _data->_streamData = new InputStreamMutex();
59
+ _data->_deleteStream = true;
60
+ OPENEXR_IMF_INTERNAL_NAMESPACE::IStream* is = 0;
61
+
62
+ @@ -954,12 +959,29 @@ DeepScanLineInputFile::DeepScanLineInputFile
63
+ readMagicNumberAndVersionField(*is, _data->version);
64
+ //
65
+ // Backward compatibility to read multpart file.
66
+ - //
67
+ + // multiPartInitialize will create _streamData
68
+ if (isMultiPart(_data->version))
69
+ {
70
+ compatibilityInitialize(*is);
71
+ return;
72
+ }
73
+ + }
74
+ + catch (IEX_NAMESPACE::BaseExc &e)
75
+ + {
76
+ + if (is) delete is;
77
+ + if (_data) delete _data;
78
+ +
79
+ + REPLACE_EXC (e, "Cannot read image file "
80
+ + "\"" << fileName << "\". " << e.what());
81
+ + throw;
82
+ + }
83
+ +
84
+ + //
85
+ + // not multiPart - allocate stream data and intialise as normal
86
+ + //
87
+ + try
88
+ + {
89
+ + _data->_streamData = new InputStreamMutex();
90
+ _data->_streamData->is = is;
91
+ _data->memoryMapped = is->isMemoryMapped();
92
+ _data->header.readFrom (*_data->_streamData->is, _data->version);
93
+ @@ -975,7 +997,10 @@ DeepScanLineInputFile::DeepScanLineInputFile
94
+ catch (IEX_NAMESPACE::BaseExc &e)
95
+ {
96
+ if (is) delete is;
97
+ - if (_data && _data->_streamData) delete _data->_streamData;
98
+ + if (_data && _data->_streamData)
99
+ + {
100
+ + delete _data->_streamData;
101
+ + }
102
+ if (_data) delete _data;
103
+
104
+ REPLACE_EXC (e, "Cannot read image file "
105
+ @@ -985,7 +1010,10 @@ DeepScanLineInputFile::DeepScanLineInputFile
106
+ catch (...)
107
+ {
108
+ if (is) delete is;
109
+ - if (_data && _data->_streamData) delete _data->_streamData;
110
+ + if (_data && _data->_streamData)
111
+ + {
112
+ + delete _data->_streamData;
113
+ + }
114
+ if (_data) delete _data;
115
+
116
+ throw;
117
+ @@ -1009,7 +1037,18 @@ DeepScanLineInputFile::DeepScanLineInputFile
118
+
119
+ _data->version =version;
120
+
121
+ - initialize (header);
122
+ + try
123
+ + {
124
+ + initialize (header);
125
+ + }
126
+ + catch (...)
127
+ + {
128
+ + if (_data && _data->_streamData)
129
+ + {
130
+ + delete _data->_streamData;
131
+ + }
132
+ + if (_data) delete _data;
133
+ + }
134
+
135
+ readLineOffsets (*_data->_streamData->is,
136
+ _data->lineOrder,
137
+ @@ -1041,8 +1080,9 @@ DeepScanLineInputFile::~DeepScanLineInputFile ()
138
+ //
139
+
140
+ if (_data->partNumber == -1 && _data->_streamData)
141
+ + {
142
+ delete _data->_streamData;
143
+ -
144
+ + }
145
+ delete _data;
146
+ }
147
+ }
148
+ diff --git a/OpenEXR/IlmImf/ImfDeepTiledInputFile.cpp b/OpenEXR/IlmImf/ImfDeepTiledInputFile.cpp
149
+ index 916717f7..38ea33cd 100644
150
+ --- a/OpenEXR/IlmImf/ImfDeepTiledInputFile.cpp
151
+ +++ b/OpenEXR/IlmImf/ImfDeepTiledInputFile.cpp
152
+ @@ -283,7 +283,8 @@ DeepTiledInputFile::Data::Data (int numThreads):
153
+ multiPartBackwardSupport(false),
154
+ numThreads(numThreads),
155
+ memoryMapped(false),
156
+ - _streamData(NULL),
157
+ + sampleCountTableComp(nullptr),
158
+ + _streamData(nullptr),
159
+ _deleteStream(false)
160
+ {
161
+ //
162
+ @@ -308,6 +309,8 @@ DeepTiledInputFile::Data::~Data ()
163
+
164
+ for (size_t i = 0; i < slices.size(); i++)
165
+ delete slices[i];
166
+ +
167
+ + delete sampleCountTableComp;
168
+ }
169
+
170
+
171
+ @@ -878,7 +881,15 @@ DeepTiledInputFile::DeepTiledInputFile (InputPartData* part) :
172
+ _data (new Data (part->numThreads))
173
+ {
174
+ _data->_deleteStream=false;
175
+ - multiPartInitialize(part);
176
+ + try
177
+ + {
178
+ + multiPartInitialize(part);
179
+ + }
180
+ + catch(...)
181
+ + {
182
+ + delete _data;
183
+ + throw;
184
+ + }
185
+ }
186
+
187
+
188
+ diff --git a/OpenEXR/IlmImf/ImfDwaCompressor.cpp b/OpenEXR/IlmImf/ImfDwaCompressor.cpp
189
+ index d029121d..872c8c7d 100644
190
+ --- a/OpenEXR/IlmImf/ImfDwaCompressor.cpp
191
+ +++ b/OpenEXR/IlmImf/ImfDwaCompressor.cpp
192
+ @@ -266,8 +266,9 @@ struct DwaCompressor::Classifier
193
+ " (truncated rule).");
194
+
195
+ {
196
+ - char suffix[Name::SIZE];
197
+ - memset (suffix, 0, Name::SIZE);
198
+ + // maximum length of string plus one byte for terminating NULL
199
+ + char suffix[Name::SIZE+1];
200
+ + memset (suffix, 0, Name::SIZE+1);
201
+ Xdr::read<CharPtrIO> (ptr, std::min(size, Name::SIZE-1), suffix);
202
+ _suffix = std::string(suffix);
203
+ }
204
+ @@ -2419,7 +2420,7 @@ DwaCompressor::uncompress
205
+ unsigned short ruleSize = 0;
206
+ Xdr::read<CharPtrIO>(dataPtr, ruleSize);
207
+
208
+ - if (ruleSize < 0)
209
+ + if (ruleSize < Xdr::size<unsigned short>() )
210
+ throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data"
211
+ " (corrupt header file).");
212
+
213
+ @@ -2814,6 +2815,14 @@ DwaCompressor::uncompress
214
+ if (IMATH_NAMESPACE::modp (y, cd->ySampling) != 0)
215
+ continue;
216
+
217
+ + //
218
+ + // sanity check for buffer data lying within range
219
+ + //
220
+ + if (cd->planarUncBufferEnd + dstScanlineSize - _planarUncBuffer[UNKNOWN] > _planarUncBufferSize[UNKNOWN] )
221
+ + {
222
+ + throw Iex::InputExc("DWA data corrupt");
223
+ + }
224
+ +
225
+ memcpy (rowPtrs[chan][row],
226
+ cd->planarUncBufferEnd,
227
+ dstScanlineSize);
228
+ diff --git a/OpenEXR/IlmImf/ImfFastHuf.cpp b/OpenEXR/IlmImf/ImfFastHuf.cpp
229
+ index 3e00bdd7..9ccf2e15 100644
230
+ --- a/OpenEXR/IlmImf/ImfFastHuf.cpp
231
+ +++ b/OpenEXR/IlmImf/ImfFastHuf.cpp
232
+ @@ -256,14 +256,29 @@ FastHufDecoder::FastHufDecoder
233
+ int symbol = *i >> 6;
234
+
235
+ if (mapping[codeLen] >= static_cast<Int64>(_numSymbols))
236
+ + {
237
+ + delete[] _idToSymbol;
238
+ + _idToSymbol = NULL;
239
+ throw IEX_NAMESPACE::InputExc ("Huffman decode error "
240
+ "(Invalid symbol in header).");
241
+ -
242
+ + }
243
+ _idToSymbol[mapping[codeLen]] = symbol;
244
+ mapping[codeLen]++;
245
+ }
246
+
247
+ - buildTables(base, offset);
248
+ + //
249
+ + // exceptions can be thrown whilst building tables. Delete
250
+ + // _idToSynmbol before re-throwing to prevent memory leak
251
+ + //
252
+ + try
253
+ + {
254
+ + buildTables(base, offset);
255
+ + }catch(...)
256
+ + {
257
+ + delete[] _idToSymbol;
258
+ + _idToSymbol = NULL;
259
+ + throw;
260
+ + }
261
+ }
262
+
263
+
264
+ diff --git a/OpenEXR/IlmImf/ImfHeader.cpp b/OpenEXR/IlmImf/ImfHeader.cpp
265
+ index e29ec421..6d63cd2e 100644
266
+ --- a/OpenEXR/IlmImf/ImfHeader.cpp
267
+ +++ b/OpenEXR/IlmImf/ImfHeader.cpp
268
+ @@ -873,6 +873,7 @@ Header::sanityCheck (bool isTiled, bool isMultipartFile) const
269
+ }
270
+
271
+ const std::string & part_type=hasType() ? type() : "";
272
+ +
273
+
274
+ if(part_type!="" && !isSupportedType(part_type))
275
+ {
276
+ @@ -882,6 +883,7 @@ Header::sanityCheck (bool isTiled, bool isMultipartFile) const
277
+ return;
278
+ }
279
+
280
+ + bool isDeep = isDeepData(part_type);
281
+
282
+ //
283
+ // If the file is tiled, verify that the tile description has reasonable
284
+ @@ -902,7 +904,7 @@ Header::sanityCheck (bool isTiled, bool isMultipartFile) const
285
+
286
+ const TileDescription &tileDesc = tileDescription();
287
+
288
+ - if (tileDesc.xSize <= 0 || tileDesc.ySize <= 0)
289
+ + if (tileDesc.xSize <= 0 || tileDesc.ySize <= 0 || tileDesc.xSize > INT_MAX || tileDesc.ySize > INT_MAX )
290
+ throw IEX_NAMESPACE::ArgExc ("Invalid tile size in image header.");
291
+
292
+ if (maxTileWidth > 0 &&
293
+ @@ -953,7 +955,8 @@ Header::sanityCheck (bool isTiled, bool isMultipartFile) const
294
+ if (!isValidCompression (this->compression()))
295
+ throw IEX_NAMESPACE::ArgExc ("Unknown compression type in image header.");
296
+
297
+ - if(isDeepData(part_type))
298
+ +
299
+ + if( isDeep )
300
+ {
301
+ if (!isValidDeepCompression (this->compression()))
302
+ throw IEX_NAMESPACE::ArgExc ("Compression type in header not valid for deep data");
303
+ @@ -965,6 +968,8 @@ Header::sanityCheck (bool isTiled, bool isMultipartFile) const
304
+ // If the file is tiled then for each channel, the type must be one of the
305
+ // predefined values, and the x and y sampling must both be 1.
306
+ //
307
+ + // x and y sampling must currently also be 1 for deep scanline images
308
+ + //
309
+ // If the file is not tiled then for each channel, the type must be one
310
+ // of the predefined values, the x and y coordinates of the data window's
311
+ // upper left corner must be divisible by the x and y subsampling factors,
312
+ @@ -974,7 +979,7 @@ Header::sanityCheck (bool isTiled, bool isMultipartFile) const
313
+
314
+ const ChannelList &channels = this->channels();
315
+
316
+ - if (isTiled)
317
+ + if (isTiled || isDeep)
318
+ {
319
+ for (ChannelList::ConstIterator i = channels.begin();
320
+ i != channels.end();
321
+ diff --git a/OpenEXR/IlmImf/ImfHuf.cpp b/OpenEXR/IlmImf/ImfHuf.cpp
322
+ index 97909a5b..fabb5faa 100644
323
+ --- a/OpenEXR/IlmImf/ImfHuf.cpp
324
+ +++ b/OpenEXR/IlmImf/ImfHuf.cpp
325
+ @@ -1052,7 +1052,10 @@ hufUncompress (const char compressed[],
326
+ unsigned short raw[],
327
+ int nRaw)
328
+ {
329
+ - if (nCompressed == 0)
330
+ + //
331
+ + // need at least 20 bytes for header
332
+ + //
333
+ + if (nCompressed < 20 )
334
+ {
335
+ if (nRaw != 0)
336
+ notEnoughData();
337
+ @@ -1070,6 +1073,12 @@ hufUncompress (const char compressed[],
338
+
339
+ const char *ptr = compressed + 20;
340
+
341
+ + if ( ptr + (nBits+7 )/8 > compressed+nCompressed)
342
+ + {
343
+ + notEnoughData();
344
+ + return;
345
+ + }
346
+ +
347
+ //
348
+ // Fast decoder needs at least 2x64-bits of compressed data, and
349
+ // needs to be run-able on this platform. Otherwise, fall back
350
+ diff --git a/OpenEXR/IlmImf/ImfInputFile.cpp b/OpenEXR/IlmImf/ImfInputFile.cpp
351
+ index 8661c104..74c1a353 100644
352
+ --- a/OpenEXR/IlmImf/ImfInputFile.cpp
353
+ +++ b/OpenEXR/IlmImf/ImfInputFile.cpp
354
+ @@ -475,7 +475,15 @@ InputFile::InputFile (InputPartData* part) :
355
+ _data (new Data (part->numThreads))
356
+ {
357
+ _data->_deleteStream=false;
358
+ - multiPartInitialize (part);
359
+ + try
360
+ + {
361
+ + multiPartInitialize (part);
362
+ + }
363
+ + catch(...)
364
+ + {
365
+ + delete _data;
366
+ + throw;
367
+ + }
368
+ }
369
+
370
+
371
+ diff --git a/OpenEXR/IlmImf/ImfMisc.cpp b/OpenEXR/IlmImf/ImfMisc.cpp
372
+ index 27755432..d0b6fb26 100644
373
+ --- a/OpenEXR/IlmImf/ImfMisc.cpp
374
+ +++ b/OpenEXR/IlmImf/ImfMisc.cpp
375
+ @@ -114,9 +114,9 @@ bytesPerLineTable (const Header &header,
376
+ c != channels.end();
377
+ ++c)
378
+ {
379
+ - int nBytes = pixelTypeSize (c.channel().type) *
380
+ - (dataWindow.max.x - dataWindow.min.x + 1) /
381
+ - c.channel().xSampling;
382
+ + size_t nBytes = size_t(pixelTypeSize (c.channel().type)) *
383
+ + size_t(dataWindow.max.x - dataWindow.min.x + 1) /
384
+ + size_t(c.channel().xSampling);
385
+
386
+ for (int y = dataWindow.min.y, i = 0; y <= dataWindow.max.y; ++y, ++i)
387
+ if (modp (y, c.channel().ySampling) == 0)
388
+ @@ -269,6 +269,7 @@ defaultFormat (Compressor * compressor)
389
+ }
390
+
391
+
392
+ +//obsolete
393
+ int
394
+ numLinesInBuffer (Compressor * compressor)
395
+ {
396
+ @@ -1842,6 +1843,39 @@ usesLongNames (const Header &header)
397
+ return false;
398
+ }
399
+
400
+ +namespace
401
+ +{
402
+ +// for a given compression type, return the number of scanlines
403
+ +// compressed into a single chunk
404
+ +// TODO add to API and move to ImfCompressor.cpp
405
+ +int
406
+ +numLinesInBuffer(Compression comp)
407
+ +{
408
+ + switch(comp)
409
+ + {
410
+ + case NO_COMPRESSION :
411
+ + case RLE_COMPRESSION:
412
+ + case ZIPS_COMPRESSION:
413
+ + return 1;
414
+ + case ZIP_COMPRESSION:
415
+ + return 16;
416
+ + case PIZ_COMPRESSION:
417
+ + return 32;
418
+ + case PXR24_COMPRESSION:
419
+ + return 16;
420
+ + case B44_COMPRESSION:
421
+ + case B44A_COMPRESSION:
422
+ + case DWAA_COMPRESSION:
423
+ + return 32;
424
+ + case DWAB_COMPRESSION:
425
+ + return 256;
426
+ +
427
+ + default:
428
+ + throw IEX_NAMESPACE::ArgExc ("Unknown compression type");
429
+ + }
430
+ +}
431
+ +}
432
+ +
433
+ int
434
+ getScanlineChunkOffsetTableSize(const Header& header)
435
+ {
436
+ @@ -1851,17 +1885,11 @@ getScanlineChunkOffsetTableSize(const Header& header)
437
+ size_t maxBytesPerLine = bytesPerLineTable (header,
438
+ bytesPerLine);
439
+
440
+ - Compressor* compressor = newCompressor(header.compression(),
441
+ - maxBytesPerLine,
442
+ - header);
443
+ -
444
+ - int linesInBuffer = numLinesInBuffer (compressor);
445
+ + int linesInBuffer = numLinesInBuffer ( header.compression() );
446
+
447
+ int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y +
448
+ linesInBuffer) / linesInBuffer;
449
+
450
+ - delete compressor;
451
+ -
452
+ return lineOffsetSize;
453
+ }
454
+
455
+ diff --git a/OpenEXR/IlmImf/ImfPizCompressor.cpp b/OpenEXR/IlmImf/ImfPizCompressor.cpp
456
+ index 7a49d42d..edc141ad 100644
457
+ --- a/OpenEXR/IlmImf/ImfPizCompressor.cpp
458
+ +++ b/OpenEXR/IlmImf/ImfPizCompressor.cpp
459
+ @@ -492,7 +492,9 @@ PizCompressor::uncompress (const char *inPtr,
460
+ // This is the cunompress function which is used by both the tiled and
461
+ // scanline decompression routines.
462
+ //
463
+ -
464
+ +
465
+ + const char* inputEnd=inPtr+inSize;
466
+ +
467
+ //
468
+ // Special case - empty input buffer
469
+ //
470
+ @@ -503,6 +505,7 @@ PizCompressor::uncompress (const char *inPtr,
471
+ return 0;
472
+ }
473
+
474
+ +
475
+ //
476
+ // Determine the layout of the compressed pixel data
477
+ //
478
+ @@ -549,6 +552,12 @@ PizCompressor::uncompress (const char *inPtr,
479
+ AutoArray <unsigned char, BITMAP_SIZE> bitmap;
480
+ memset (bitmap, 0, sizeof (unsigned char) * BITMAP_SIZE);
481
+
482
+ +
483
+ + if(inPtr + sizeof(unsigned short)*2 > inputEnd)
484
+ + {
485
+ + throw InputExc ("PIZ compressed data too short");
486
+ + }
487
+ +
488
+ Xdr::read <CharPtrIO> (inPtr, minNonZero);
489
+ Xdr::read <CharPtrIO> (inPtr, maxNonZero);
490
+
491
+ @@ -560,8 +569,14 @@ PizCompressor::uncompress (const char *inPtr,
492
+
493
+ if (minNonZero <= maxNonZero)
494
+ {
495
+ - Xdr::read <CharPtrIO> (inPtr, (char *) &bitmap[0] + minNonZero,
496
+ - maxNonZero - minNonZero + 1);
497
+ + size_t bytesToRead = maxNonZero - minNonZero + 1;
498
+ + if(inPtr + bytesToRead > inputEnd)
499
+ + {
500
+ + throw InputExc ("PIZ compressed data too short");
501
+ + }
502
+ +
503
+ +Xdr::read <CharPtrIO> (inPtr, (char *) &bitmap[0] + minNonZero,
504
+ + bytesToRead);
505
+ }
506
+
507
+ AutoArray <unsigned short, USHORT_RANGE> lut;
508
+ @@ -570,6 +585,11 @@ PizCompressor::uncompress (const char *inPtr,
509
+ //
510
+ // Huffman decoding
511
+ //
512
+ + if(inPtr + sizeof(int)> inputEnd)
513
+ + {
514
+ + throw InputExc ("PIZ compressed data too short");
515
+ + }
516
+ +
517
+
518
+ int length;
519
+ Xdr::read <CharPtrIO> (inPtr, length);
520
+ diff --git a/OpenEXR/IlmImf/ImfRle.cpp b/OpenEXR/IlmImf/ImfRle.cpp
521
+ index 7be6ac44..f6992fa5 100644
522
+ --- a/OpenEXR/IlmImf/ImfRle.cpp
523
+ +++ b/OpenEXR/IlmImf/ImfRle.cpp
524
+ @@ -129,6 +129,11 @@ rleUncompress (int inLength, int maxLength, const signed char in[], char out[])
525
+ if (0 > (maxLength -= count))
526
+ return 0;
527
+
528
+ + // check the input buffer is big enough to contain
529
+ + // 'count' bytes of remaining data
530
+ + if (inLength < 0)
531
+ + return 0;
532
+ +
533
+ memcpy(out, in, count);
534
+ out += count;
535
+ in += count;
536
+ diff --git a/OpenEXR/IlmImf/ImfScanLineInputFile.cpp b/OpenEXR/IlmImf/ImfScanLineInputFile.cpp
537
+ index 9d7404f3..2a559654 100644
538
+ --- a/OpenEXR/IlmImf/ImfScanLineInputFile.cpp
539
+ +++ b/OpenEXR/IlmImf/ImfScanLineInputFile.cpp
540
+ @@ -1097,8 +1097,6 @@ newLineBufferTask (TaskGroup *group,
541
+
542
+ void ScanLineInputFile::initialize(const Header& header)
543
+ {
544
+ - try
545
+ - {
546
+ _data->header = header;
547
+
548
+ _data->lineOrder = _data->header.lineOrder();
549
+ @@ -1112,6 +1110,12 @@ void ScanLineInputFile::initialize(const Header& header)
550
+
551
+ size_t maxBytesPerLine = bytesPerLineTable (_data->header,
552
+ _data->bytesPerLine);
553
+ +
554
+ + if(maxBytesPerLine > INT_MAX)
555
+ + {
556
+ + throw IEX_NAMESPACE::InputExc("maximum bytes per scanline exceeds maximum permissible size");
557
+ + }
558
+ +
559
+
560
+ for (size_t i = 0; i < _data->lineBuffers.size(); i++)
561
+ {
562
+ @@ -1143,13 +1147,6 @@ void ScanLineInputFile::initialize(const Header& header)
563
+ _data->linesInBuffer) / _data->linesInBuffer;
564
+
565
+ _data->lineOffsets.resize (lineOffsetSize);
566
+ - }
567
+ - catch (...)
568
+ - {
569
+ - delete _data;
570
+ - _data=NULL;
571
+ - throw;
572
+ - }
573
+ }
574
+
575
+
576
+ @@ -1164,8 +1161,27 @@ ScanLineInputFile::ScanLineInputFile(InputPartData* part)
577
+
578
+ _data->version = part->version;
579
+
580
+ - initialize(part->header);
581
+ -
582
+ + try
583
+ + {
584
+ + initialize(part->header);
585
+ + }
586
+ + catch(...)
587
+ + {
588
+ + if (!_data->memoryMapped)
589
+ + {
590
+ + for (size_t i = 0; i < _data->lineBuffers.size(); i++)
591
+ + {
592
+ + if( _data->lineBuffers[i] )
593
+ + {
594
+ + EXRFreeAligned(_data->lineBuffers[i]->buffer);
595
+ + _data->lineBuffers[i]->buffer=nullptr;
596
+ + }
597
+ + }
598
+ + }
599
+ +
600
+ + delete _data;
601
+ + throw;
602
+ + }
603
+ _data->lineOffsets = part->chunkOffsets;
604
+
605
+ _data->partNumber = part->partNumber;
606
+ @@ -1188,19 +1204,43 @@ ScanLineInputFile::ScanLineInputFile
607
+ _streamData->is = is;
608
+ _data->memoryMapped = is->isMemoryMapped();
609
+
610
+ - initialize(header);
611
+ -
612
+ - //
613
+ - // (TODO) this is nasty - we need a better way of working out what type of file has been used.
614
+ - // in any case I believe this constructor only gets used with single part files
615
+ - // and 'version' currently only tracks multipart state, so setting to 0 (not multipart) works for us
616
+ - //
617
+ -
618
+ - _data->version=0;
619
+ - readLineOffsets (*_streamData->is,
620
+ - _data->lineOrder,
621
+ - _data->lineOffsets,
622
+ - _data->fileIsComplete);
623
+ + try
624
+ + {
625
+ +
626
+ + initialize(header);
627
+ +
628
+ + //
629
+ + // (TODO) this is nasty - we need a better way of working out what type of file has been used.
630
+ + // in any case I believe this constructor only gets used with single part files
631
+ + // and 'version' currently only tracks multipart state, so setting to 0 (not multipart) works for us
632
+ + //
633
+ +
634
+ + _data->version=0;
635
+ + readLineOffsets (*_streamData->is,
636
+ + _data->lineOrder,
637
+ + _data->lineOffsets,
638
+ + _data->fileIsComplete);
639
+ + }
640
+ + catch(...)
641
+ + {
642
+ + if(_data)
643
+ + {
644
+ + if (!_data->memoryMapped)
645
+ + {
646
+ + for (size_t i = 0; i < _data->lineBuffers.size(); i++)
647
+ + {
648
+ + if( _data->lineBuffers[i] )
649
+ + {
650
+ + EXRFreeAligned(_data->lineBuffers[i]->buffer);
651
+ + _data->lineBuffers[i]->buffer=nullptr;
652
+ + }
653
+ + }
654
+ + }
655
+ + }
656
+ + delete _streamData;
657
+ + delete _data;
658
+ + throw;
659
+ + }
660
+ }
661
+
662
+
663
+ @@ -1422,6 +1462,14 @@ ScanLineInputFile::setFrameBuffer (const FrameBuffer &frameBuffer)
664
+ // not possible.
665
+ break;
666
+ }
667
+ +
668
+ + //
669
+ + // optimization mode cannot currently skip subsampled channels
670
+ + //
671
+ + if (i.channel().xSampling!=1 || i.channel().ySampling!=1)
672
+ + {
673
+ + optimizationPossible = false;
674
+ + }
675
+ ++i;
676
+ }
677
+
678
+ diff --git a/OpenEXR/IlmImf/ImfTiledInputFile.cpp b/OpenEXR/IlmImf/ImfTiledInputFile.cpp
679
+ index bda7bad5..e6936d53 100644
680
+ --- a/OpenEXR/IlmImf/ImfTiledInputFile.cpp
681
+ +++ b/OpenEXR/IlmImf/ImfTiledInputFile.cpp
682
+ @@ -703,61 +703,56 @@ TiledInputFile::TiledInputFile (const char fileName[], int numThreads):
683
+ IStream* is = 0;
684
+ try
685
+ {
686
+ - is = new StdIFStream (fileName);
687
+ - readMagicNumberAndVersionField(*is, _data->version);
688
+ -
689
+ - //
690
+ - // Backward compatibility to read multpart file.
691
+ - //
692
+ - if (isMultiPart(_data->version))
693
+ - {
694
+ - compatibilityInitialize(*is);
695
+ - return;
696
+ - }
697
+ -
698
+ - _data->_streamData = new InputStreamMutex();
699
+ - _data->_streamData->is = is;
700
+ - _data->header.readFrom (*_data->_streamData->is, _data->version);
701
+ - initialize();
702
+ - //read tile offsets - we are not multipart or deep
703
+ - _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false);
704
+ - _data->_streamData->currentPosition = _data->_streamData->is->tellg();
705
+ - }
706
+ - catch (IEX_NAMESPACE::BaseExc &e)
707
+ - {
708
+ - if (_data->_streamData != 0)
709
+ + try
710
+ {
711
+ - if (_data->_streamData->is != 0)
712
+ + is = new StdIFStream (fileName);
713
+ + readMagicNumberAndVersionField(*is, _data->version);
714
+ +
715
+ + //
716
+ + // Backward compatibility to read multpart file.
717
+ + //
718
+ + if (isMultiPart(_data->version))
719
+ {
720
+ - delete _data->_streamData->is;
721
+ - _data->_streamData->is = is = 0;
722
+ + compatibilityInitialize(*is);
723
+ + return;
724
+ }
725
+
726
+ - delete _data->_streamData;
727
+ + _data->_streamData = new InputStreamMutex();
728
+ + _data->_streamData->is = is;
729
+ + _data->header.readFrom (*_data->_streamData->is, _data->version);
730
+ + initialize();
731
+ + //read tile offsets - we are not multipart or deep
732
+ + _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false);
733
+ + _data->_streamData->currentPosition = _data->_streamData->is->tellg();
734
+ + }
735
+ + catch (IEX_NAMESPACE::BaseExc &e)
736
+ + {
737
+ + REPLACE_EXC (e, "Cannot open image file "
738
+ + "\"" << fileName << "\". " << e.what());
739
+ + throw;
740
+ }
741
+ -
742
+ - if (is != 0)
743
+ - delete is;
744
+ -
745
+ - REPLACE_EXC (e, "Cannot open image file "
746
+ - "\"" << fileName << "\". " << e.what());
747
+ - throw;
748
+ }
749
+ catch (...)
750
+ {
751
+ - if ( _data->_streamData != 0)
752
+ + if (!_data->memoryMapped)
753
+ {
754
+ - if ( _data->_streamData->is != 0)
755
+ + for (size_t i = 0; i < _data->tileBuffers.size(); i++)
756
+ {
757
+ - delete _data->_streamData->is;
758
+ - _data->_streamData->is = is = 0;
759
+ + if(_data->tileBuffers[i])
760
+ + {
761
+ + delete [] _data->tileBuffers[i]->buffer;
762
+ + }
763
+ }
764
+ -
765
+ + }
766
+ + if ( _data->_streamData != 0)
767
+ + {
768
+ + delete _data->_streamData->is;
769
+ + _data->_streamData->is = is = 0;
770
+ delete _data->_streamData;
771
+ }
772
+
773
+ - if (is != 0)
774
+ - delete is;
775
+ + delete is;
776
+ + delete _data;
777
+ throw;
778
+ }
779
+ }
780
+ @@ -776,38 +771,45 @@ TiledInputFile::TiledInputFile (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream &is, int
781
+
782
+ try
783
+ {
784
+ - readMagicNumberAndVersionField(is, _data->version);
785
+ -
786
+ - //
787
+ - // Backward compatibility to read multpart file.
788
+ - //
789
+ - if (isMultiPart(_data->version))
790
+ + try
791
+ {
792
+ - compatibilityInitialize(is);
793
+ - return;
794
+ - }
795
+ + readMagicNumberAndVersionField(is, _data->version);
796
+
797
+ - streamDataCreated = true;
798
+ - _data->_streamData = new InputStreamMutex();
799
+ - _data->_streamData->is = &is;
800
+ - _data->header.readFrom (*_data->_streamData->is, _data->version);
801
+ - initialize();
802
+ - // file is guaranteed to be single part, regular image
803
+ - _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false);
804
+ - _data->memoryMapped = _data->_streamData->is->isMemoryMapped();
805
+ - _data->_streamData->currentPosition = _data->_streamData->is->tellg();
806
+ - }
807
+ - catch (IEX_NAMESPACE::BaseExc &e)
808
+ - {
809
+ - if (streamDataCreated) delete _data->_streamData;
810
+ - delete _data;
811
+ + //
812
+ + // Backward compatibility to read multpart file.
813
+ + //
814
+ + if (isMultiPart(_data->version))
815
+ + {
816
+ + compatibilityInitialize(is);
817
+ + return;
818
+ + }
819
+
820
+ - REPLACE_EXC (e, "Cannot open image file "
821
+ - "\"" << is.fileName() << "\". " << e.what());
822
+ - throw;
823
+ + streamDataCreated = true;
824
+ + _data->_streamData = new InputStreamMutex();
825
+ + _data->_streamData->is = &is;
826
+ + _data->header.readFrom (*_data->_streamData->is, _data->version);
827
+ + initialize();
828
+ + // file is guaranteed to be single part, regular image
829
+ + _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false);
830
+ + _data->memoryMapped = _data->_streamData->is->isMemoryMapped();
831
+ + _data->_streamData->currentPosition = _data->_streamData->is->tellg();
832
+ + }
833
+ + catch (IEX_NAMESPACE::BaseExc &e)
834
+ + {
835
+ + REPLACE_EXC (e, "Cannot open image file "
836
+ + "\"" << is.fileName() << "\". " << e.what());
837
+ + throw;
838
+ + }
839
+ }
840
+ catch (...)
841
+ {
842
+ + if (!_data->memoryMapped)
843
+ + {
844
+ + for (size_t i = 0; i < _data->tileBuffers.size(); i++)
845
+ + {
846
+ + delete [] _data->tileBuffers[i]->buffer;
847
+ + }
848
+ + }
849
+ if (streamDataCreated) delete _data->_streamData;
850
+ delete _data;
851
+ throw;
852
+ @@ -831,13 +833,29 @@ TiledInputFile::TiledInputFile (const Header &header,
853
+ // we have somehow got the header.
854
+ //
855
+
856
+ - _data->_streamData->is = is;
857
+ - _data->header = header;
858
+ - _data->version = version;
859
+ - initialize();
860
+ - _data->tileOffsets.readFrom (*(_data->_streamData->is),_data->fileIsComplete,false,false);
861
+ - _data->memoryMapped = is->isMemoryMapped();
862
+ - _data->_streamData->currentPosition = _data->_streamData->is->tellg();
863
+ + try
864
+ + {
865
+ + _data->_streamData->is = is;
866
+ + _data->header = header;
867
+ + _data->version = version;
868
+ + initialize();
869
+ + _data->tileOffsets.readFrom (*(_data->_streamData->is),_data->fileIsComplete,false,false);
870
+ + _data->memoryMapped = is->isMemoryMapped();
871
+ + _data->_streamData->currentPosition = _data->_streamData->is->tellg();
872
+ + }
873
+ + catch(...)
874
+ + {
875
+ + if (!_data->memoryMapped)
876
+ + {
877
+ + for (size_t i = 0; i < _data->tileBuffers.size(); i++)
878
+ + {
879
+ + delete [] _data->tileBuffers[i]->buffer;
880
+ + }
881
+ + }
882
+ + delete _data->_streamData;
883
+ + delete _data;
884
+ + throw;
885
+ + }
886
+ }
887
+
888
+
889
+ @@ -845,7 +863,15 @@ TiledInputFile::TiledInputFile (InputPartData* part)
890
+ {
891
+ _data = new Data (part->numThreads);
892
+ _data->_deleteStream=false;
893
+ - multiPartInitialize(part);
894
+ + try
895
+ + {
896
+ + multiPartInitialize(part);
897
+ + }
898
+ + catch(...)
899
+ + {
900
+ + if (_data) delete _data;
901
+ + throw;
902
+ + }
903
+ }
904
+
905
+
906
+ diff --git a/OpenEXR/IlmImf/ImfTiledMisc.cpp b/OpenEXR/IlmImf/ImfTiledMisc.cpp
907
+ index d262f734..8552ada2 100644
908
+ --- a/OpenEXR/IlmImf/ImfTiledMisc.cpp
909
+ +++ b/OpenEXR/IlmImf/ImfTiledMisc.cpp
910
+ @@ -363,40 +363,51 @@ getTiledChunkOffsetTableSize(const Header& header)
911
+ //
912
+ Int64 lineOffsetSize = 0;
913
+ const TileDescription &desc = header.tileDescription();
914
+ - switch (desc.mode)
915
+ + try
916
+ {
917
+ - case ONE_LEVEL:
918
+ - case MIPMAP_LEVELS:
919
+ - for (int i = 0; i < numXLevels; i++)
920
+ - {
921
+ - lineOffsetSize += static_cast<Int64>(numXTiles[i]) * static_cast<Int64>(numYTiles[i]);
922
+ - if ( lineOffsetSize > static_cast<Int64>(std::numeric_limits<int>::max()) )
923
+ + switch (desc.mode)
924
+ + {
925
+ + case ONE_LEVEL:
926
+ + case MIPMAP_LEVELS:
927
+ + for (int i = 0; i < numXLevels; i++)
928
+ {
929
+ - throw IEX_NAMESPACE::LogicExc("Maximum number of tiles exceeded");
930
+ + lineOffsetSize += static_cast<Int64>(numXTiles[i]) * static_cast<Int64>(numYTiles[i]);
931
+ + if ( lineOffsetSize > static_cast<Int64>(std::numeric_limits<int>::max()) )
932
+ + {
933
+ + throw IEX_NAMESPACE::LogicExc("Maximum number of tiles exceeded");
934
+ + }
935
+ }
936
+ - }
937
+ - break;
938
+ - case RIPMAP_LEVELS:
939
+ - for (int i = 0; i < numXLevels; i++)
940
+ - {
941
+ - for (int j = 0; j < numYLevels; j++)
942
+ + break;
943
+ + case RIPMAP_LEVELS:
944
+ + for (int i = 0; i < numXLevels; i++)
945
+ {
946
+ - lineOffsetSize += static_cast<Int64>(numXTiles[i]) * static_cast<Int64>(numYTiles[j]);
947
+ - if ( lineOffsetSize > static_cast<Int64>(std::numeric_limits<int>::max()) )
948
+ - {
949
+ - throw IEX_NAMESPACE::LogicExc("Maximum number of tiles exceeded");
950
+ - }
951
+ + for (int j = 0; j < numYLevels; j++)
952
+ + {
953
+ + lineOffsetSize += static_cast<Int64>(numXTiles[i]) * static_cast<Int64>(numYTiles[j]);
954
+ + if ( lineOffsetSize > static_cast<Int64>(std::numeric_limits<int>::max()) )
955
+ + {
956
+ + throw IEX_NAMESPACE::LogicExc("Maximum number of tiles exceeded");
957
+ + }
958
+ + }
959
+ }
960
+ - }
961
+ - break;
962
+ - case NUM_LEVELMODES :
963
+ - throw IEX_NAMESPACE::LogicExc("Bad level mode getting chunk offset table size");
964
+ + break;
965
+ + case NUM_LEVELMODES :
966
+ + throw IEX_NAMESPACE::LogicExc("Bad level mode getting chunk offset table size");
967
+ + }
968
+ + delete[] numXTiles;
969
+ + delete[] numYTiles;
970
+ +
971
+ + return static_cast<int>(lineOffsetSize);
972
+ +
973
+ }
974
+ + catch(...)
975
+ + {
976
+ + delete[] numXTiles;
977
+ + delete[] numYTiles;
978
+
979
+ - delete[] numXTiles;
980
+ - delete[] numYTiles;
981
+ + throw;
982
+ + }
983
+
984
+ - return static_cast<int>(lineOffsetSize);
985
+ }
986
+
987
+
988
+ diff --git a/OpenEXR/IlmImfTest/testDeepTiledBasic.cpp b/OpenEXR/IlmImfTest/testDeepTiledBasic.cpp
989
+ index e81b56a7..9fab3553 100644
990
+ --- a/OpenEXR/IlmImfTest/testDeepTiledBasic.cpp
991
+ +++ b/OpenEXR/IlmImfTest/testDeepTiledBasic.cpp
992
+ @@ -754,15 +754,12 @@ void readFile (int channelCount,
993
+ {
994
+ for (int k = 0; k < channelCount; k++)
995
+ {
996
+ - if( !randomChannels || read_channel[k]==1)
997
+ - {
998
+ if (channelTypes[k] == 0)
999
+ delete[] (unsigned int*) data[k][i][j];
1000
+ if (channelTypes[k] == 1)
1001
+ delete[] (half*) data[k][i][j];
1002
+ if (channelTypes[k] == 2)
1003
+ delete[] (float*) data[k][i][j];
1004
+ - }
1005
+ }
1006
+ for( int f = 0 ; f < fillChannels ; ++f )
1007
+ {
1008
+ diff --git a/OpenEXR/IlmImfTest/testMultiPartApi.cpp b/OpenEXR/IlmImfTest/testMultiPartApi.cpp
1009
+ index c6265b88..c0bfb688 100644
1010
+ --- a/OpenEXR/IlmImfTest/testMultiPartApi.cpp
1011
+ +++ b/OpenEXR/IlmImfTest/testMultiPartApi.cpp
1012
+ @@ -463,6 +463,21 @@ generateRandomFile (int partCount, const std::string & fn)
1013
+ }
1014
+ }
1015
+
1016
+ + for (size_t i = 0 ; i < parts.size() ; ++i )
1017
+ + {
1018
+ + int partType = partTypes[i];
1019
+ +
1020
+ + if (partType == 0)
1021
+ + {
1022
+ + delete (OutputPart*) parts[i];
1023
+ + }
1024
+ + else
1025
+ + {
1026
+ + delete (TiledOutputPart*) parts[i];
1027
+ + }
1028
+ +
1029
+ + }
1030
+ +
1031
+ delete[] tiledHalfData;
1032
+ delete[] tiledUintData;
1033
+ delete[] tiledFloatData;
1034
+ diff --git a/OpenEXR/IlmImfTest/testMultiPartThreading.cpp b/OpenEXR/IlmImfTest/testMultiPartThreading.cpp
1035
+ index 68eb8fa9..c4e05704 100644
1036
+ --- a/OpenEXR/IlmImfTest/testMultiPartThreading.cpp
1037
+ +++ b/OpenEXR/IlmImfTest/testMultiPartThreading.cpp
1038
+ @@ -625,6 +625,18 @@ generateRandomFile (int partCount, const std::string & fn)
1039
+ }
1040
+ }
1041
+
1042
+ + for (int i = 0; i < partCount; i++)
1043
+ + {
1044
+ + if (partTypes[i] == 0)
1045
+ + {
1046
+ + delete (OutputPart*) parts[i];
1047
+ + }
1048
+ + else
1049
+ + {
1050
+ + delete (TiledOutputPart*) parts[i];
1051
+ + }
1052
+ + }
1053
+ +
1054
+ delete threadPool;
1055
+
1056
+ delete[] tiledHalfData;
1057
+ diff --git a/OpenEXR/exrmakepreview/makePreview.cpp b/OpenEXR/exrmakepreview/makePreview.cpp
1058
+ index e2d08798..28205aa0 100644
1059
+ --- a/OpenEXR/exrmakepreview/makePreview.cpp
1060
+ +++ b/OpenEXR/exrmakepreview/makePreview.cpp
1061
+ @@ -120,8 +120,8 @@ generatePreview (const char inFileName[],
1062
+ previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1);
1063
+ previewPixels.resizeErase (previewHeight, previewWidth);
1064
+
1065
+ - float fx = (previewWidth > 1)? (float (w - 1) / (previewWidth - 1)): 1;
1066
+ - float fy = (previewHeight > 1)? (float (h - 1) / (previewHeight - 1)): 1;
1067
+ + double fx = (previewWidth > 1)? (double (w - 1) / (previewWidth - 1)): 1;
1068
+ + double fy = (previewHeight > 1)? (double (h - 1) / (previewHeight - 1)): 1;
1069
+ float m = Math<float>::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f));
1070
+
1071
+ for (int y = 0; y < previewHeight; ++y)
tasks/csa159/pair_136251/post_functions.txt ADDED
The diff for this file is too large to render. See raw diff
 
tasks/csa159/pair_136251/pre_functions.txt ADDED
@@ -0,0 +1,2527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: OpenEXR/IlmImf/ImfCompositeDeepScanLine.cpp
2
+ ```c
3
+ void
4
+ CompositeDeepScanLine::Data::handleDeepFrameBuffer (DeepFrameBuffer& buf,
5
+ std::vector< unsigned int > & counts,
6
+ vector< std::vector< float* > > & pointers,
7
+ const Header& header,
8
+ int start,
9
+ int end)
10
+ {
11
+ int width=_dataWindow.size().x+1;
12
+ size_t pixelcount = width * (end-start+1);
13
+ pointers.resize(_channels.size());
14
+ counts.resize(pixelcount);
15
+ buf.insertSampleCountSlice (Slice (OPENEXR_IMF_INTERNAL_NAMESPACE::UINT,
16
+ (char *) (&counts[0]-_dataWindow.min.x-start*width),
17
+ sizeof(unsigned int),
18
+ sizeof(unsigned int)*width));
19
+
20
+ pointers[0].resize(pixelcount);
21
+ buf.insert ("Z", DeepSlice (OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT,
22
+ (char *)(&pointers[0][0]-_dataWindow.min.x-start*width),
23
+ sizeof(float *),
24
+ sizeof(float *)*width,
25
+ sizeof(float) ));
26
+
27
+ if(_zback)
28
+ {
29
+ pointers[1].resize(pixelcount);
30
+ buf.insert ("ZBack", DeepSlice (OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT,
31
+ (char *)(&pointers[1][0]-_dataWindow.min.x-start*width),
32
+ sizeof(float *),
33
+ sizeof(float *)*width,
34
+ sizeof(float) ));
35
+ }
36
+
37
+ pointers[2].resize(pixelcount);
38
+ buf.insert ("A", DeepSlice (OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT,
39
+ (char *)(&pointers[2][0]-_dataWindow.min.x-start*width),
40
+ sizeof(float *),
41
+ sizeof(float *)*width,
42
+ sizeof(float) ));
43
+
44
+
45
+ size_t i =0;
46
+ for(FrameBuffer::ConstIterator qt = _outputFrameBuffer.begin();
47
+ qt != _outputFrameBuffer.end();
48
+ qt++)
49
+ {
50
+ int channel_in_source = _bufferMap[i];
51
+ if(channel_in_source>2)
52
+ {
53
+ // not dealt with yet (0,1,2 previously inserted)
54
+ pointers[channel_in_source].resize(pixelcount);
55
+ buf.insert (qt.name(),
56
+ DeepSlice (OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT,
57
+ (char *)(&pointers[channel_in_source][0]-_dataWindow.min.x-start*width),
58
+ sizeof(float *),
59
+ sizeof(float *)*width,
60
+ sizeof(float) ));
61
+ }
62
+
63
+ i++;
64
+ }
65
+
66
+ }
67
+ ```
68
+
69
+ ### File: OpenEXR/IlmImf/ImfDeepScanLineInputFile.cpp
70
+ ```c
71
+ void DeepScanLineInputFile::initialize(const Header& header)
72
+ {
73
+ try
74
+ {
75
+ if (header.type() != DEEPSCANLINE)
76
+ throw IEX_NAMESPACE::ArgExc("Can't build a DeepScanLineInputFile from "
77
+ "a type-mismatched part.");
78
+
79
+ if(header.version()!=1)
80
+ {
81
+ THROW(IEX_NAMESPACE::ArgExc, "Version " << header.version() << " not supported for deepscanline images in this version of the library");
82
+ }
83
+
84
+ _data->header = header;
85
+
86
+ _data->lineOrder = _data->header.lineOrder();
87
+
88
+ const Box2i &dataWindow = _data->header.dataWindow();
89
+
90
+ _data->minX = dataWindow.min.x;
91
+ _data->maxX = dataWindow.max.x;
92
+ _data->minY = dataWindow.min.y;
93
+ _data->maxY = dataWindow.max.y;
94
+
95
+ _data->sampleCount.resizeErase(_data->maxY - _data->minY + 1,
96
+ _data->maxX - _data->minX + 1);
97
+ _data->lineSampleCount.resizeErase(_data->maxY - _data->minY + 1);
98
+
99
+ Compressor* compressor = newCompressor(_data->header.compression(),
100
+ 0,
101
+ _data->header);
102
+
103
+ _data->linesInBuffer = numLinesInBuffer (compressor);
104
+
105
+ delete compressor;
106
+
107
+ _data->nextLineBufferMinY = _data->minY - 1;
108
+
109
+ int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y +
110
+ _data->linesInBuffer) / _data->linesInBuffer;
111
+
112
+ _data->lineOffsets.resize (lineOffsetSize);
113
+
114
+ for (size_t i = 0; i < _data->lineBuffers.size(); i++)
115
+ _data->lineBuffers[i] = new LineBuffer ();
116
+
117
+ _data->gotSampleCount.resizeErase(_data->maxY - _data->minY + 1);
118
+ for (int i = 0; i < _data->maxY - _data->minY + 1; i++)
119
+ _data->gotSampleCount[i] = false;
120
+
121
+ _data->maxSampleCountTableSize = min(_data->linesInBuffer, _data->maxY - _data->minY + 1) *
122
+ (_data->maxX - _data->minX + 1) *
123
+ sizeof(unsigned int);
124
+
125
+ _data->sampleCountTableBuffer.resizeErase(_data->maxSampleCountTableSize);
126
+
127
+ _data->sampleCountTableComp = newCompressor(_data->header.compression(),
128
+ _data->maxSampleCountTableSize,
129
+ _data->header);
130
+
131
+ _data->bytesPerLine.resize (_data->maxY - _data->minY + 1);
132
+
133
+ const ChannelList & c=header.channels();
134
+
135
+ _data->combinedSampleSize=0;
136
+ for(ChannelList::ConstIterator i=c.begin();i!=c.end();i++)
137
+ {
138
+ switch(i.channel().type)
139
+ {
140
+ case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF :
141
+ _data->combinedSampleSize+=Xdr::size<half>();
142
+ break;
143
+ case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT :
144
+ _data->combinedSampleSize+=Xdr::size<float>();
145
+ break;
146
+ case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT :
147
+ _data->combinedSampleSize+=Xdr::size<unsigned int>();
148
+ break;
149
+ default :
150
+ THROW(IEX_NAMESPACE::ArgExc, "Bad type for channel " << i.name() << " initializing deepscanline reader");
151
+
152
+ }
153
+ }
154
+
155
+ }
156
+ catch (...)
157
+ {
158
+ delete _data;
159
+ _data=NULL;
160
+ throw;
161
+ }
162
+ }
163
+
164
+ void
165
+ DeepScanLineInputFile::compatibilityInitialize(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is)
166
+ {
167
+ is.seekg(0);
168
+ //
169
+ // Construct a MultiPartInputFile, initialize TiledInputFile
170
+ // with the part 0 data.
171
+ // (TODO) maybe change the third parameter of the constructor of MultiPartInputFile later.
172
+ //
173
+ _data->multiPartBackwardSupport = true;
174
+ _data->multiPartFile = new MultiPartInputFile(is, _data->numThreads);
175
+ InputPartData* part = _data->multiPartFile->getPart(0);
176
+
177
+ multiPartInitialize(part);
178
+ }
179
+ ```
180
+
181
+ ### File: OpenEXR/IlmImf/ImfDeepTiledInputFile.cpp
182
+ ```c
183
+ void
184
+ DeepTiledInputFile::compatibilityInitialize(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is)
185
+ {
186
+ is.seekg(0);
187
+ //
188
+ // Construct a MultiPartInputFile, initialize TiledInputFile
189
+ // with the part 0 data.
190
+ // (TODO) maybe change the third parameter of the constructor of MultiPartInputFile later.
191
+ //
192
+ _data->multiPartFile = new MultiPartInputFile(is, _data->numThreads);
193
+ _data->multiPartBackwardSupport = true;
194
+ InputPartData* part = _data->multiPartFile->getPart(0);
195
+
196
+ multiPartInitialize(part);
197
+ }
198
+ ```
199
+
200
+ ### File: OpenEXR/IlmImf/ImfDwaCompressor.cpp
201
+ ```c
202
+ struct DwaCompressor::Classifier
203
+ {
204
+ Classifier (std::string suffix,
205
+ CompressorScheme scheme,
206
+ PixelType type,
207
+ int cscIdx,
208
+ bool caseInsensitive):
209
+ _suffix(suffix),
210
+ _scheme(scheme),
211
+ _type(type),
212
+ _cscIdx(cscIdx),
213
+ _caseInsensitive(caseInsensitive)
214
+ {
215
+ if (caseInsensitive)
216
+ std::transform(_suffix.begin(), _suffix.end(), _suffix.begin(), tolower);
217
+ }
218
+
219
+ Classifier (const char *&ptr, int size)
220
+ {
221
+ if (size <= 0)
222
+ throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data"
223
+ " (truncated rule).");
224
+
225
+ {
226
+ char suffix[Name::SIZE];
227
+ memset (suffix, 0, Name::SIZE);
228
+ Xdr::read<CharPtrIO> (ptr, std::min(size, Name::SIZE-1), suffix);
229
+ _suffix = std::string(suffix);
230
+ }
231
+
232
+ if (static_cast<size_t>(size) < _suffix.length() + 1 + 2*Xdr::size<char>())
233
+ throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data"
234
+ " (truncated rule).");
235
+
236
+ char value;
237
+ Xdr::read<CharPtrIO> (ptr, value);
238
+
239
+ _cscIdx = (int)(value >> 4) - 1;
240
+ if (_cscIdx < -1 || _cscIdx >= 3)
241
+ throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data"
242
+ " (corrupt cscIdx rule).");
243
+
244
+ _scheme = (CompressorScheme)((value >> 2) & 3);
245
+ if (_scheme < 0 || _scheme >= NUM_COMPRESSOR_SCHEMES)
246
+ throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data"
247
+ " (corrupt scheme rule).");
248
+
249
+ _caseInsensitive = (value & 1 ? true : false);
250
+
251
+ Xdr::read<CharPtrIO> (ptr, value);
252
+ if (value < 0 || value >= NUM_PIXELTYPES)
253
+ throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data"
254
+ " (corrupt rule).");
255
+ _type = (PixelType)value;
256
+ }
257
+ ```
258
+
259
+ ### File: OpenEXR/IlmImf/ImfFastHuf.cpp
260
+ ```c
261
+ ///////////////////////////////////////////////////////////////////////////
262
+ //
263
+ // Copyright (c) 2009-2014 DreamWorks Animation LLC.
264
+ //
265
+ // All rights reserved.
266
+ //
267
+ // Redistribution and use in source and binary forms, with or without
268
+ // modification, are permitted provided that the following conditions are
269
+ // met:
270
+ // * Redistributions of source code must retain the above copyright
271
+ // notice, this list of conditions and the following disclaimer.
272
+ // * Redistributions in binary form must reproduce the above
273
+ // copyright notice, this list of conditions and the following disclaimer
274
+ // in the documentation and/or other materials provided with the
275
+ // distribution.
276
+ // * Neither the name of DreamWorks Animation nor the names of
277
+ // its contributors may be used to endorse or promote products derived
278
+ // from this software without specific prior written permission.
279
+ //
280
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
281
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
282
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
283
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
284
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
285
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
286
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
287
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
288
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
289
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
290
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
291
+ //
292
+ ///////////////////////////////////////////////////////////////////////////
293
+
294
+ #include "ImfFastHuf.h"
295
+ #include <Iex.h>
296
+
297
+ #include <string.h>
298
+ #include <assert.h>
299
+ #include <math.h>
300
+ #include <vector>
301
+
302
+ OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER
303
+
304
+ //
305
+ // Adapted from hufUnpackEncTable -
306
+ // We don't need to reconstruct the code book, just the encoded
307
+ // lengths for each symbol. From the lengths, we can build the
308
+ // base + offset tables. This should be a bit more efficient
309
+ // for sparse code books.
310
+ //
311
+ // table - ptr to the start of the code length data. Will be
312
+ // updated as we decode data
313
+ //
314
+ // numBytes - size of the encoded table (I think)?
315
+ //
316
+ // minSymbol - smallest symbol in the code book
317
+ //
318
+ // maxSymbol - largest symbol in the code book.
319
+ //
320
+ // rleSymbol - the symbol to trigger RLE in the encoded bitstream
321
+ //
322
+
323
+ FastHufDecoder::FastHufDecoder
324
+ (const char *&table,
325
+ int numBytes,
326
+ int minSymbol,
327
+ int maxSymbol,
328
+ int rleSymbol)
329
+ :
330
+ _rleSymbol (rleSymbol),
331
+ _numSymbols (0),
332
+ _minCodeLength (255),
333
+ _maxCodeLength (0),
334
+ _idToSymbol (0)
335
+ {
336
+ //
337
+ // List of symbols that we find with non-zero code lengths
338
+ // (listed in the order we find them). Store these in the
339
+ // same format as the code book stores codes + lengths -
340
+ // low 6 bits are the length, everything above that is
341
+ // the symbol.
342
+ //
343
+
344
+ std::vector<Int64> symbols;
345
+
346
+ //
347
+ // The 'base' table is the minimum code at each code length. base[i]
348
+ // is the smallest code (numerically) of length i.
349
+ //
350
+
351
+ Int64 base[MAX_CODE_LEN + 1];
352
+
353
+ //
354
+ // The 'offset' table is the position (in sorted order) of the first id
355
+ // of a given code lenght. Array is indexed by code length, like base.
356
+ //
357
+
358
+ Int64 offset[MAX_CODE_LEN + 1];
359
+
360
+ //
361
+ // Count of how many codes at each length there are. Array is
362
+ // indexed by code length, like base and offset.
363
+ //
364
+
365
+ size_t codeCount[MAX_CODE_LEN + 1];
366
+
367
+ for (int i = 0; i <= MAX_CODE_LEN; ++i)
368
+ {
369
+ codeCount[i] = 0;
370
+ base[i] = 0xffffffffffffffffULL;
371
+ offset[i] = 0;
372
+ }
373
+
374
+ //
375
+ // Count the number of codes, the min/max code lengths, the number of
376
+ // codes with each length, and record symbols with non-zero code
377
+ // length as we find them.
378
+ //
379
+
380
+ const char *currByte = table;
381
+ Int64 currBits = 0;
382
+ int currBitCount = 0;
383
+
384
+ const int SHORT_ZEROCODE_RUN = 59;
385
+ const int LONG_ZEROCODE_RUN = 63;
386
+ const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
387
+
388
+ for (Int64 symbol = static_cast<Int64>(minSymbol); symbol <= static_cast<Int64>(maxSymbol); symbol++)
389
+ {
390
+ if (currByte - table > numBytes)
391
+ {
392
+ throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table "
393
+ "(Truncated table data).");
394
+ }
395
+
396
+ //
397
+ // Next code length - either:
398
+ // 0-58 (literal code length)
399
+ // 59-62 (various lengths runs of 0)
400
+ // 63 (run of n 0's, with n is the next 8 bits)
401
+ //
402
+
403
+ Int64 codeLen = readBits (6, currBits, currBitCount, currByte);
404
+
405
+ if (codeLen == (Int64) LONG_ZEROCODE_RUN)
406
+ {
407
+ if (currByte - table > numBytes)
408
+ {
409
+ throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table "
410
+ "(Truncated table data).");
411
+ }
412
+
413
+ int runLen = readBits (8, currBits, currBitCount, currByte) +
414
+ SHORTEST_LONG_RUN;
415
+
416
+ if (symbol + runLen > static_cast<Int64>(maxSymbol + 1))
417
+ {
418
+ throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table "
419
+ "(Run beyond end of table).");
420
+ }
421
+
422
+ symbol += runLen - 1;
423
+
424
+ }
425
+ else if (codeLen >= static_cast<Int64>(SHORT_ZEROCODE_RUN))
426
+ {
427
+ int runLen = codeLen - SHORT_ZEROCODE_RUN + 2;
428
+
429
+ if (symbol + runLen > static_cast<Int64>(maxSymbol + 1))
430
+ {
431
+ throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table "
432
+ "(Run beyond end of table).");
433
+ }
434
+
435
+ symbol += runLen - 1;
436
+
437
+ }
438
+ else if (codeLen != 0)
439
+ {
440
+ symbols.push_back ((symbol << 6) | (codeLen & 63));
441
+
442
+ if (codeLen < _minCodeLength)
443
+ _minCodeLength = codeLen;
444
+
445
+ if (codeLen > _maxCodeLength)
446
+ _maxCodeLength = codeLen;
447
+
448
+ codeCount[codeLen]++;
449
+ }
450
+ }
451
+
452
+ for (int i = 0; i < MAX_CODE_LEN; ++i)
453
+ _numSymbols += codeCount[i];
454
+
455
+ table = currByte;
456
+
457
+ //
458
+ // Compute base - once we have the code length counts, there
459
+ // is a closed form solution for this
460
+ //
461
+
462
+ {
463
+ double* countTmp = new double[_maxCodeLength+1];
464
+
465
+ for (int l = _minCodeLength; l <= _maxCodeLength; ++l)
466
+ {
467
+ countTmp[l] = (double)codeCount[l] *
468
+ (double)(2 << (_maxCodeLength-l));
469
+ }
470
+
471
+ for (int l = _minCodeLength; l <= _maxCodeLength; ++l)
472
+ {
473
+ double tmp = 0;
474
+
475
+ for (int k =l + 1; k <= _maxCodeLength; ++k)
476
+ tmp += countTmp[k];
477
+
478
+ tmp /= (double)(2 << (_maxCodeLength - l));
479
+
480
+ base[l] = (Int64)ceil (tmp);
481
+ }
482
+
483
+ delete [] countTmp;
484
+ }
485
+
486
+ //
487
+ // Compute offset - these are the positions of the first
488
+ // id (not symbol) that has length [i]
489
+ //
490
+
491
+ offset[_maxCodeLength] = 0;
492
+
493
+ for (int i= _maxCodeLength - 1; i >= _minCodeLength; i--)
494
+ offset[i] = offset[i + 1] + codeCount[i + 1];
495
+
496
+ //
497
+ // Allocate and fill the symbol-to-id mapping. Smaller Ids should be
498
+ // mapped to less-frequent symbols (which have longer codes). Use
499
+ // the offset table to tell us where the id's for a given code
500
+ // length start off.
501
+ //
502
+
503
+ _idToSymbol = new int[_numSymbols];
504
+
505
+ Int64 mapping[MAX_CODE_LEN + 1];
506
+ for (int i = 0; i < MAX_CODE_LEN + 1; ++i)
507
+ mapping[i] = -1;
508
+ for (int i = _minCodeLength; i <= _maxCodeLength; ++i)
509
+ mapping[i] =
510
+
511
+ // ... (14845 more chars)
512
+ ```
513
+
514
+ ### File: OpenEXR/IlmImf/ImfHeader.cpp
515
+ ```c
516
+ ///////////////////////////////////////////////////////////////////////////
517
+ //
518
+ // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
519
+ // Digital Ltd. LLC
520
+ //
521
+ // All rights reserved.
522
+ //
523
+ // Redistribution and use in source and binary forms, with or without
524
+ // modification, are permitted provided that the following conditions are
525
+ // met:
526
+ // * Redistributions of source code must retain the above copyright
527
+ // notice, this list of conditions and the following disclaimer.
528
+ // * Redistributions in binary form must reproduce the above
529
+ // copyright notice, this list of conditions and the following disclaimer
530
+ // in the documentation and/or other materials provided with the
531
+ // distribution.
532
+ // * Neither the name of Industrial Light & Magic nor the names of
533
+ // its contributors may be used to endorse or promote products derived
534
+ // from this software without specific prior written permission.
535
+ //
536
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
537
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
538
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
539
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
540
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
541
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
542
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
543
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
544
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
545
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
546
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
547
+ //
548
+ ///////////////////////////////////////////////////////////////////////////
549
+
550
+
551
+
552
+ //-----------------------------------------------------------------------------
553
+ //
554
+ // class Header
555
+ //
556
+ //-----------------------------------------------------------------------------
557
+
558
+ #include <ImfHeader.h>
559
+ #include <ImfStdIO.h>
560
+ #include <ImfVersion.h>
561
+ #include <ImfCompressor.h>
562
+ #include <ImfMisc.h>
563
+ #include <ImfBoxAttribute.h>
564
+ #include <ImfChannelListAttribute.h>
565
+ #include <ImfChromaticitiesAttribute.h>
566
+ #include <ImfCompressionAttribute.h>
567
+ #include <ImfDeepImageStateAttribute.h>
568
+ #include <ImfDoubleAttribute.h>
569
+ #include <ImfDwaCompressor.h>
570
+ #include <ImfEnvmapAttribute.h>
571
+ #include <ImfFloatAttribute.h>
572
+ #include <ImfFloatVectorAttribute.h>
573
+ #include <ImfIntAttribute.h>
574
+ #include <ImfKeyCodeAttribute.h>
575
+ #include <ImfLineOrderAttribute.h>
576
+ #include <ImfMatrixAttribute.h>
577
+ #include <ImfOpaqueAttribute.h>
578
+ #include <ImfPreviewImageAttribute.h>
579
+ #include <ImfRationalAttribute.h>
580
+ #include <ImfStringAttribute.h>
581
+ #include <ImfStringVectorAttribute.h>
582
+ #include <ImfTileDescriptionAttribute.h>
583
+ #include <ImfTimeCodeAttribute.h>
584
+ #include <ImfVecAttribute.h>
585
+ #include <ImfPartType.h>
586
+ #include "IlmThreadMutex.h"
587
+ #include "Iex.h"
588
+ #include <sstream>
589
+ #include <stdlib.h>
590
+ #include <time.h>
591
+ #include <cmath>
592
+ #include "ImfTiledMisc.h"
593
+ #include "ImfNamespace.h"
594
+
595
+ OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER
596
+
597
+ using namespace std;
598
+ using IMATH_NAMESPACE::Box2i;
599
+ using IMATH_NAMESPACE::V2i;
600
+ using IMATH_NAMESPACE::V2f;
601
+ using ILMTHREAD_NAMESPACE::Mutex;
602
+ using ILMTHREAD_NAMESPACE::Lock;
603
+
604
+
605
+ namespace {
606
+
607
+ int maxImageWidth = 0;
608
+ int maxImageHeight = 0;
609
+ int maxTileWidth = 0;
610
+ int maxTileHeight = 0;
611
+
612
+
613
+ void
614
+ initialize (Header &header,
615
+ const Box2i &displayWindow,
616
+ const Box2i &dataWindow,
617
+ float pixelAspectRatio,
618
+ const V2f &screenWindowCenter,
619
+ float screenWindowWidth,
620
+ LineOrder lineOrder,
621
+ Compression compression)
622
+ {
623
+ header.insert ("displayWindow", Box2iAttribute (displayWindow));
624
+ header.insert ("dataWindow", Box2iAttribute (dataWindow));
625
+ if ( !std::isnormal (pixelAspectRatio) || pixelAspectRatio < 0.f)
626
+ THROW (IEX_NAMESPACE::ArgExc, "Invalid pixel aspect ratio");
627
+ header.insert ("pixelAspectRatio", FloatAttribute (pixelAspectRatio));
628
+ header.insert ("screenWindowCenter", V2fAttribute (screenWindowCenter));
629
+ header.insert ("screenWindowWidth", FloatAttribute (screenWindowWidth));
630
+ header.insert ("lineOrder", LineOrderAttribute (lineOrder));
631
+ header.insert ("compression", CompressionAttribute (compression));
632
+ header.insert ("channels", ChannelListAttribute ());
633
+ }
634
+
635
+ template <size_t N>
636
+ void checkIsNullTerminated (const char (&str)[N], const char *what)
637
+ {
638
+ for (size_t i = 0; i < N; ++i) {
639
+ if (str[i] == '\0')
640
+ return;
641
+ }
642
+ std::stringstream s;
643
+ s << "Invalid " << what << ": it is more than " << (N - 1)
644
+ << " characters long.";
645
+ throw IEX_NAMESPACE::InputExc(s);
646
+ }
647
+
648
+ } // namespace
649
+
650
+
651
+ Header::Header (int width,
652
+ int height,
653
+ float pixelAspectRatio,
654
+ const V2f &screenWindowCenter,
655
+ float screenWindowWidth,
656
+ LineOrder lineOrder,
657
+ Compression compression)
658
+ :
659
+ _map()
660
+ {
661
+ staticInitialize();
662
+
663
+ Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1));
664
+
665
+ initialize (*this,
666
+ displayWindow,
667
+ displayWindow,
668
+ pixelAspectRatio,
669
+ screenWindowCenter,
670
+ screenWindowWidth,
671
+ lineOrder,
672
+ compression);
673
+ }
674
+
675
+
676
+ Header::Header (int width,
677
+ int height,
678
+ const Box2i &dataWindow,
679
+ float pixelAspectRatio,
680
+ const V2f &screenWindowCenter,
681
+ float screenWindowWidth,
682
+ LineOrder lineOrder,
683
+ Compression compression)
684
+ :
685
+ _map()
686
+ {
687
+ staticInitialize();
688
+
689
+ Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1));
690
+
691
+ initialize (*this,
692
+ displayWindow,
693
+ dataWindow,
694
+ pixelAspectRatio,
695
+ screenWindowCenter,
696
+ screenWindowWidth,
697
+ lineOrder,
698
+ compression);
699
+ }
700
+
701
+
702
+ Header::Header (const Box2i &displayWindow,
703
+ const Box2i &dataWindow,
704
+ float pixelAspectRatio,
705
+ const V2f &screenWindowCenter,
706
+ float screenWindowWidth,
707
+ LineOrder lineOrder,
708
+ Compression compression)
709
+ :
710
+ _map()
711
+ {
712
+ staticInitialize();
713
+
714
+ initialize (*this,
715
+ displayWindow,
716
+ dataWindow,
717
+ pixelAspectRatio,
718
+ screenWindowCenter,
719
+ screenWindowWidth,
720
+ lineOrder,
721
+ compression);
722
+ }
723
+
724
+
725
+ Header::Header (const Header &other): _map()
726
+ {
727
+ for (AttributeMap::const_iterator i = other._map.begin();
728
+ i != other._map.end();
729
+ ++i)
730
+ {
731
+ insert (*i->first, *i->second);
732
+ }
733
+ }
734
+
735
+
736
+ Header::~Header ()
737
+ {
738
+ for (AttributeMap::iterator i = _map.begin();
739
+ i != _map.end();
740
+ ++i)
741
+ {
742
+ delete i->second;
743
+ }
744
+ }
745
+
746
+
747
+ Header &
748
+ Header::operator = (const Header &other)
749
+ {
750
+ if (this != &other)
751
+ {
752
+ for (AttributeMap::iterator i = _map.begin();
753
+ i != _map.end();
754
+ ++i)
755
+ {
756
+ delete i->second;
757
+ }
758
+
759
+ _map.erase (_map.begin(), _map.end());
760
+
761
+ for (AttributeMap::const_iterator i = other._map.begin();
762
+ i != other._map.end();
763
+ ++i)
764
+ {
765
+ insert (*i->first, *i->second);
766
+ }
767
+ }
768
+
769
+ return *this;
770
+ }
771
+
772
+
773
+ void
774
+ Header::erase (const char name[])
775
+ {
776
+ if (name[0] == 0)
777
+ THROW (IEX_NAMESPACE::ArgExc, "Image attribute name cannot be an empty string.");
778
+
779
+
780
+ AttributeMap::iterator i = _map.find (name);
781
+ if (i != _map.end())
782
+ _map.erase (i);
783
+
784
+ }
785
+
786
+
787
+ void
788
+ Header::erase (const string &name)
789
+ {
790
+ erase (name.c_str());
791
+ }
792
+
793
+
794
+ void
795
+ Header::insert (const char name[], const Attribute &attribute)
796
+ {
797
+ if (name[0] == 0)
798
+ THROW (IEX_NAMESPACE::ArgExc, "Image attribute name cannot be an empty string.");
799
+
800
+ AttributeMap::iterator i = _map.find (name);
801
+
802
+ if (i == _map.end())
803
+ {
804
+ Attribute *tmp = attribute.copy();
805
+
806
+ try
807
+ {
808
+ _map[name] = tmp;
809
+ }
810
+ catch (...)
811
+ {
812
+ delete tmp;
813
+ throw;
814
+ }
815
+ }
816
+ else
817
+ {
818
+ if (strcmp (i->second->typeName(), attribute.typeName()))
819
+ THROW (IEX_NAMESPACE::TypeExc, "Cannot assign a value of "
820
+ "type \"" << attribute.typeName() << "\" "
821
+ "to image attribute \"" << name << "\" of "
822
+ "type \"" << i->second->typeName() << "\".");
823
+
824
+ Attribute *tmp = attribute.copy();
825
+ delete i->second;
826
+ i->second = tmp;
827
+ }
828
+ }
829
+
830
+
831
+ void
832
+ Header::insert (const string &name, const Attribute &attribute)
833
+ {
834
+ insert (name.c_str(), attribute);
835
+ }
836
+
837
+
838
+ Attribute &
839
+ Header::operator [] (const char name[])
840
+ {
841
+ AttributeMap::iterator i = _map.find (name);
842
+
843
+ if (i =
844
+
845
+ // ... (22549 more chars)
846
+ ```
847
+
848
+ ### File: OpenEXR/IlmImf/ImfHuf.cpp
849
+ ```c
850
+ void
851
+ hufUncompress (const char compressed[],
852
+ int nCompressed,
853
+ unsigned short raw[],
854
+ int nRaw)
855
+ {
856
+ if (nCompressed == 0)
857
+ {
858
+ if (nRaw != 0)
859
+ notEnoughData();
860
+
861
+ return;
862
+ }
863
+
864
+ int im = readUInt (compressed);
865
+ int iM = readUInt (compressed + 4);
866
+ // int tableLength = readUInt (compressed + 8);
867
+ int nBits = readUInt (compressed + 12);
868
+
869
+ if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE)
870
+ invalidTableSize();
871
+
872
+ const char *ptr = compressed + 20;
873
+
874
+ //
875
+ // Fast decoder needs at least 2x64-bits of compressed data, and
876
+ // needs to be run-able on this platform. Otherwise, fall back
877
+ // to the original decoder
878
+ //
879
+
880
+ if (FastHufDecoder::enabled() && nBits > 128)
881
+ {
882
+ FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM);
883
+ fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw);
884
+ }
885
+ else
886
+ {
887
+ AutoArray <Int64, HUF_ENCSIZE> freq;
888
+ AutoArray <HufDec, HUF_DECSIZE> hdec;
889
+
890
+ hufClearDecTable (hdec);
891
+
892
+ hufUnpackEncTable (&ptr,
893
+ nCompressed - (ptr - compressed),
894
+ im,
895
+ iM,
896
+ freq);
897
+
898
+ try
899
+ {
900
+ if (nBits > 8 * (nCompressed - (ptr - compressed)))
901
+ invalidNBits();
902
+
903
+ hufBuildDecTable (freq, im, iM, hdec);
904
+ hufDecode (freq, hdec, ptr, nBits, iM, nRaw, raw);
905
+ }
906
+ catch (...)
907
+ {
908
+ hufFreeDecTable (hdec);
909
+ throw;
910
+ }
911
+
912
+ hufFreeDecTable (hdec);
913
+ }
914
+ }
915
+ ```
916
+
917
+ ### File: OpenEXR/IlmImf/ImfInputFile.cpp
918
+ ```c
919
+ void
920
+ InputFile::compatibilityInitialize (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is)
921
+ {
922
+ is.seekg(0);
923
+
924
+ //
925
+ // Construct a MultiPartInputFile, initialize InputFile
926
+ // with the part 0 data.
927
+ // (TODO) may want to have a way to set the reconstruction flag.
928
+ //
929
+ _data->multiPartBackwardSupport = true;
930
+ _data->multiPartFile = new MultiPartInputFile(is, _data->numThreads);
931
+ InputPartData* part = _data->multiPartFile->getPart(0);
932
+
933
+ multiPartInitialize (part);
934
+ }
935
+ ```
936
+
937
+ ### File: OpenEXR/IlmImf/ImfMisc.cpp
938
+ ```c
939
+ size_t
940
+ bytesPerLineTable (const Header &header,
941
+ vector<size_t> &bytesPerLine)
942
+ {
943
+ const Box2i &dataWindow = header.dataWindow();
944
+ const ChannelList &channels = header.channels();
945
+
946
+ bytesPerLine.resize (dataWindow.max.y - dataWindow.min.y + 1);
947
+
948
+ for (ChannelList::ConstIterator c = channels.begin();
949
+ c != channels.end();
950
+ ++c)
951
+ {
952
+ int nBytes = pixelTypeSize (c.channel().type) *
953
+ (dataWindow.max.x - dataWindow.min.x + 1) /
954
+ c.channel().xSampling;
955
+
956
+ for (int y = dataWindow.min.y, i = 0; y <= dataWindow.max.y; ++y, ++i)
957
+ if (modp (y, c.channel().ySampling) == 0)
958
+ bytesPerLine[i] += nBytes;
959
+ }
960
+
961
+ size_t maxBytesPerLine = 0;
962
+
963
+ for (int y = dataWindow.min.y, i = 0; y <= dataWindow.max.y; ++y, ++i)
964
+ if (maxBytesPerLine < bytesPerLine[i])
965
+ maxBytesPerLine = bytesPerLine[i];
966
+
967
+ return maxBytesPerLine;
968
+ }
969
+
970
+ int
971
+ numLinesInBuffer (Compressor * compressor)
972
+ {
973
+ return compressor? compressor->numScanLines(): 1;
974
+ }
975
+
976
+ bool
977
+ usesLongNames (const Header &header)
978
+ {
979
+ //
980
+ // If an OpenEXR file contains any attribute names, attribute type names
981
+ // or channel names longer than 31 characters, then the file cannot be
982
+ // read by older versions of the IlmImf library (up to OpenEXR 1.6.1).
983
+ // Before writing the file header, we check if the header contains
984
+ // any names longer than 31 characters; if it does, then we set the
985
+ // LONG_NAMES_FLAG in the file version number. Older versions of the
986
+ // IlmImf library will refuse to read files that have the LONG_NAMES_FLAG
987
+ // set. Without the flag, older versions of the library would mis-
988
+ // interpret the file as broken.
989
+ //
990
+
991
+ for (Header::ConstIterator i = header.begin();
992
+ i != header.end();
993
+ ++i)
994
+ {
995
+ if (strlen (i.name()) >= 32 || strlen (i.attribute().typeName()) >= 32)
996
+ return true;
997
+ }
998
+
999
+ const ChannelList &channels = header.channels();
1000
+
1001
+ for (ChannelList::ConstIterator i = channels.begin();
1002
+ i != channels.end();
1003
+ ++i)
1004
+ {
1005
+ if (strlen (i.name()) >= 32)
1006
+ return true;
1007
+ }
1008
+
1009
+ return false;
1010
+ }
1011
+
1012
+ int
1013
+ getScanlineChunkOffsetTableSize(const Header& header)
1014
+ {
1015
+ const Box2i &dataWindow = header.dataWindow();
1016
+
1017
+ vector<size_t> bytesPerLine;
1018
+ size_t maxBytesPerLine = bytesPerLineTable (header,
1019
+ bytesPerLine);
1020
+
1021
+ Compressor* compressor = newCompressor(header.compression(),
1022
+ maxBytesPerLine,
1023
+ header);
1024
+
1025
+ int linesInBuffer = numLinesInBuffer (compressor);
1026
+
1027
+ int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y +
1028
+ linesInBuffer) / linesInBuffer;
1029
+
1030
+ delete compressor;
1031
+
1032
+ return lineOffsetSize;
1033
+ }
1034
+ ```
1035
+
1036
+ ### File: OpenEXR/IlmImf/ImfPizCompressor.cpp
1037
+ ```c
1038
+ ///////////////////////////////////////////////////////////////////////////
1039
+ //
1040
+ // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
1041
+ // Digital Ltd. LLC
1042
+ //
1043
+ // All rights reserved.
1044
+ //
1045
+ // Redistribution and use in source and binary forms, with or without
1046
+ // modification, are permitted provided that the following conditions are
1047
+ // met:
1048
+ // * Redistributions of source code must retain the above copyright
1049
+ // notice, this list of conditions and the following disclaimer.
1050
+ // * Redistributions in binary form must reproduce the above
1051
+ // copyright notice, this list of conditions and the following disclaimer
1052
+ // in the documentation and/or other materials provided with the
1053
+ // distribution.
1054
+ // * Neither the name of Industrial Light & Magic nor the names of
1055
+ // its contributors may be used to endorse or promote products derived
1056
+ // from this software without specific prior written permission.
1057
+ //
1058
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1059
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1060
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1061
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1062
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1063
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1064
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1065
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1066
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1067
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1068
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1069
+ //
1070
+ ///////////////////////////////////////////////////////////////////////////
1071
+
1072
+
1073
+ //-----------------------------------------------------------------------------
1074
+ //
1075
+ // class PizCompressor
1076
+ //
1077
+ //-----------------------------------------------------------------------------
1078
+
1079
+ #include "ImfPizCompressor.h"
1080
+ #include "ImfHeader.h"
1081
+ #include "ImfChannelList.h"
1082
+ #include "ImfHuf.h"
1083
+ #include "ImfWav.h"
1084
+ #include "ImfMisc.h"
1085
+ #include "ImfCheckedArithmetic.h"
1086
+ #include <ImathFun.h>
1087
+ #include <ImathBox.h>
1088
+ #include <Iex.h>
1089
+ #include "ImfIO.h"
1090
+ #include "ImfXdr.h"
1091
+ #include "ImfAutoArray.h"
1092
+ #include <string.h>
1093
+ #include <assert.h>
1094
+ #include "ImfNamespace.h"
1095
+
1096
+ OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER
1097
+
1098
+ using IMATH_NAMESPACE::divp;
1099
+ using IMATH_NAMESPACE::modp;
1100
+ using IMATH_NAMESPACE::Box2i;
1101
+ using IMATH_NAMESPACE::V2i;
1102
+ using IEX_NAMESPACE::InputExc;
1103
+
1104
+ namespace {
1105
+
1106
+ //
1107
+ // Functions to compress the range of values in the pixel data
1108
+ //
1109
+
1110
+ const int USHORT_RANGE = (1 << 16);
1111
+ const int BITMAP_SIZE = (USHORT_RANGE >> 3);
1112
+
1113
+ void
1114
+ bitmapFromData (const unsigned short data[/*nData*/],
1115
+ int nData,
1116
+ unsigned char bitmap[BITMAP_SIZE],
1117
+ unsigned short &minNonZero,
1118
+ unsigned short &maxNonZero)
1119
+ {
1120
+ for (int i = 0; i < BITMAP_SIZE; ++i)
1121
+ bitmap[i] = 0;
1122
+
1123
+ for (int i = 0; i < nData; ++i)
1124
+ bitmap[data[i] >> 3] |= (1 << (data[i] & 7));
1125
+
1126
+ bitmap[0] &= ~1; // zero is not explicitly stored in
1127
+ // the bitmap; we assume that the
1128
+ // data always contain zeroes
1129
+ minNonZero = BITMAP_SIZE - 1;
1130
+ maxNonZero = 0;
1131
+
1132
+ for (int i = 0; i < BITMAP_SIZE; ++i)
1133
+ {
1134
+ if (bitmap[i])
1135
+ {
1136
+ if (minNonZero > i)
1137
+ minNonZero = i;
1138
+ if (maxNonZero < i)
1139
+ maxNonZero = i;
1140
+ }
1141
+ }
1142
+ }
1143
+
1144
+
1145
+ unsigned short
1146
+ forwardLutFromBitmap (const unsigned char bitmap[BITMAP_SIZE],
1147
+ unsigned short lut[USHORT_RANGE])
1148
+ {
1149
+ int k = 0;
1150
+
1151
+ for (int i = 0; i < USHORT_RANGE; ++i)
1152
+ {
1153
+ if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
1154
+ lut[i] = k++;
1155
+ else
1156
+ lut[i] = 0;
1157
+ }
1158
+
1159
+ return k - 1; // maximum value stored in lut[],
1160
+ } // i.e. number of ones in bitmap minus 1
1161
+
1162
+
1163
+ unsigned short
1164
+ reverseLutFromBitmap (const unsigned char bitmap[BITMAP_SIZE],
1165
+ unsigned short lut[USHORT_RANGE])
1166
+ {
1167
+ int k = 0;
1168
+
1169
+ for (int i = 0; i < USHORT_RANGE; ++i)
1170
+ {
1171
+ if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
1172
+ lut[k++] = i;
1173
+ }
1174
+
1175
+ int n = k - 1;
1176
+
1177
+ while (k < USHORT_RANGE)
1178
+ lut[k++] = 0;
1179
+
1180
+ return n; // maximum k where lut[k] is non-zero,
1181
+ } // i.e. number of ones in bitmap minus 1
1182
+
1183
+
1184
+ void
1185
+ applyLut (const unsigned short lut[USHORT_RANGE],
1186
+ unsigned short data[/*nData*/],
1187
+ int nData)
1188
+ {
1189
+ for (int i = 0; i < nData; ++i)
1190
+ data[i] = lut[data[i]];
1191
+ }
1192
+
1193
+
1194
+ } // namespace
1195
+
1196
+
1197
+ struct PizCompressor::ChannelData
1198
+ {
1199
+ unsigned short * start;
1200
+ unsigned short * end;
1201
+ int nx;
1202
+ int ny;
1203
+ int ys;
1204
+ int size;
1205
+ };
1206
+
1207
+
1208
+ PizCompressor::PizCompressor
1209
+ (const Header &hdr,
1210
+ size_t maxScanLineSize,
1211
+ size_t numScanLines)
1212
+ :
1213
+ Compressor (hdr),
1214
+ _maxScanLineSize (maxScanLineSize),
1215
+ _format (XDR),
1216
+ _numScanLines (numScanLines),
1217
+ _tmpBuffer (0),
1218
+ _outBuffer (0),
1219
+ _numChans (0),
1220
+ _channels (hdr.channels()),
1221
+ _channelData (0)
1222
+ {
1223
+ // TODO: Remove this when we can change the ABI
1224
+ (void) _maxScanLineSize;
1225
+ size_t tmpBufferSize = uiMult (maxScanLineSize, numScanLines) / 2;
1226
+
1227
+ size_t outBufferSize =
1228
+ uiAdd (uiMult (maxScanLineSize, numScanLines),
1229
+ size_t (65536 + 8192));
1230
+
1231
+ _tmpBuffer = new unsigned short
1232
+ [checkArraySize (tmpBufferSize, sizeof (unsigned short))];
1233
+
1234
+ _outBuffer = new char [outBufferSize];
1235
+
1236
+ const ChannelList &channels = header().channels();
1237
+ bool onlyHalfChannels = true;
1238
+
1239
+ for (ChannelList::ConstIterator c = channels.begin();
1240
+ c != channels.end();
1241
+ ++c)
1242
+ {
1243
+ _numChans++;
1244
+
1245
+ assert (pixelTypeSize (c.channel().type) % pixelTypeSize (HALF) == 0);
1246
+
1247
+ if (c.channel().type != HALF)
1248
+ onlyHalfChannels = false;
1249
+ }
1250
+
1251
+ _channelData = new ChannelData[_numChans];
1252
+
1253
+ const Box2i &dataWindow = hdr.dataWindow();
1254
+
1255
+ _minX = dataWindow.min.x;
1256
+ _maxX = dataWindow.max.x;
1257
+ _maxY = dataWindow.max.y;
1258
+
1259
+ //
1260
+ // We can support uncompressed data in the machine's native format
1261
+ // if all image channels are of type HALF, and if the Xdr and the
1262
+ // native represenations of a half have the same size.
1263
+ //
1264
+
1265
+ if (onlyHalfChannels && (sizeof (half) == pixelTypeSize (HALF)))
1266
+ _format = NATIVE;
1267
+ }
1268
+
1269
+
1270
+ PizCompressor::~PizCompressor ()
1271
+ {
1272
+ delete [] _tmpBuffer;
1273
+ delete [] _outBuffer;
1274
+ delete [] _channelData;
1275
+ }
1276
+
1277
+
1278
+ int
1279
+ PizCompressor::numScanLines () const
1280
+ {
1281
+ return _numScanLines;
1282
+ }
1283
+
1284
+
1285
+ Compressor::Format
1286
+ PizCompressor::format () const
1287
+ {
1288
+ return _format;
1289
+ }
1290
+
1291
+
1292
+ int
1293
+ PizCompressor::compress (const char *inPtr,
1294
+ int inSize,
1295
+ int minY,
1296
+ const char *&outPtr)
1297
+ {
1298
+ return compress (inPtr,
1299
+ inSize,
1300
+ Box2i (V2i (_minX, minY),
1301
+ V2i (_maxX, minY + numScanLines() - 1)),
1302
+ outPtr);
1303
+ }
1304
+
1305
+
1306
+ int
1307
+ PizCompressor::compressTile (const char *inPtr,
1308
+ int inSize,
1309
+ IMATH_NAMESPACE::Box2i range,
1310
+ const char *&outPtr)
1311
+ {
1312
+ return compress (inPtr, inSize, range, outPtr);
1313
+ }
1314
+
1315
+
1316
+ int
1317
+ PizCompressor::uncompress (const char *inPtr,
1318
+ int inSize,
1319
+ int minY,
1320
+ const char *&outPtr)
1321
+ {
1322
+ return uncompress (inPtr,
1323
+ inSize,
1324
+ Box2i (V2i (_minX, minY),
1325
+ V2i (_maxX, minY + numScanLines() - 1)),
1326
+ outPtr);
1327
+ }
1328
+
1329
+
1330
+ int
1331
+ PizCompressor::uncompressTile (const char *inPtr,
1332
+ int inSize,
1333
+ IMATH_NAMESPACE::Box2i range,
1334
+ const char *&outPtr)
1335
+ {
1336
+ return uncompress (inPtr, inSize, range, outPtr);
1337
+ }
1338
+
1339
+
1340
+ int
1341
+ PizCompressor::compress (const char *inPtr,
1342
+ int inSize,
1343
+ IMATH_NAMESPACE::Box2i range,
1344
+ const char *&outPtr)
1345
+ {
1346
+ //
1347
+ // This is the compress function which is used by both the tiled and
1348
+ // scanline compression routines.
1349
+ //
1350
+
1351
+ //
1352
+ // Special case �- empty input buffer
1353
+ //
1354
+
1355
+ if (inSize == 0)
1356
+ {
1357
+ outPtr = _outBuffer;
1358
+ return 0;
1359
+ }
1360
+
1361
+ //
1362
+ // Rearrange the pixel data so that the wavelet
1363
+ // and Huffman encoders can process them easily.
1364
+ //
1365
+ // The wavelet and Huffman encoders both handle only
1366
+ // 16-bit data, so 32-bit data must be split into smaller
1367
+ // pieces. We treat each 32-bit ch
1368
+
1369
+ // ... (6963 more chars)
1370
+ ```
1371
+
1372
+ ### File: OpenEXR/IlmImf/ImfRle.cpp
1373
+ ```c
1374
+ int
1375
+ rleUncompress (int inLength, int maxLength, const signed char in[], char out[])
1376
+ {
1377
+ char *outStart = out;
1378
+
1379
+ while (inLength > 0)
1380
+ {
1381
+ if (*in < 0)
1382
+ {
1383
+ int count = -((int)*in++);
1384
+ inLength -= count + 1;
1385
+
1386
+ if (0 > (maxLength -= count))
1387
+ return 0;
1388
+
1389
+ memcpy(out, in, count);
1390
+ out += count;
1391
+ in += count;
1392
+ }
1393
+ else
1394
+ {
1395
+ int count = *in++;
1396
+ inLength -= 2;
1397
+
1398
+ if (0 > (maxLength -= count + 1))
1399
+ return 0;
1400
+
1401
+ memset(out, *(char*)in, count+1);
1402
+ out += count+1;
1403
+
1404
+ in++;
1405
+ }
1406
+ }
1407
+
1408
+ return out - outStart;
1409
+ }
1410
+ ```
1411
+
1412
+ ### File: OpenEXR/IlmImf/ImfScanLineInputFile.cpp
1413
+ ```c
1414
+ void ScanLineInputFile::initialize(const Header& header)
1415
+ {
1416
+ try
1417
+ {
1418
+ _data->header = header;
1419
+
1420
+ _data->lineOrder = _data->header.lineOrder();
1421
+
1422
+ const Box2i &dataWindow = _data->header.dataWindow();
1423
+
1424
+ _data->minX = dataWindow.min.x;
1425
+ _data->maxX = dataWindow.max.x;
1426
+ _data->minY = dataWindow.min.y;
1427
+ _data->maxY = dataWindow.max.y;
1428
+
1429
+ size_t maxBytesPerLine = bytesPerLineTable (_data->header,
1430
+ _data->bytesPerLine);
1431
+
1432
+ for (size_t i = 0; i < _data->lineBuffers.size(); i++)
1433
+ {
1434
+ _data->lineBuffers[i] = new LineBuffer (newCompressor
1435
+ (_data->header.compression(),
1436
+ maxBytesPerLine,
1437
+ _data->header));
1438
+ }
1439
+
1440
+ _data->linesInBuffer =
1441
+ numLinesInBuffer (_data->lineBuffers[0]->compressor);
1442
+
1443
+ _data->lineBufferSize = maxBytesPerLine * _data->linesInBuffer;
1444
+
1445
+ if (!_streamData->is->isMemoryMapped())
1446
+ {
1447
+ for (size_t i = 0; i < _data->lineBuffers.size(); i++)
1448
+ {
1449
+ _data->lineBuffers[i]->buffer = (char *) EXRAllocAligned(_data->lineBufferSize*sizeof(char),16);
1450
+ }
1451
+ }
1452
+ _data->nextLineBufferMinY = _data->minY - 1;
1453
+
1454
+ offsetInLineBufferTable (_data->bytesPerLine,
1455
+ _data->linesInBuffer,
1456
+ _data->offsetInLineBuffer);
1457
+
1458
+ int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y +
1459
+ _data->linesInBuffer) / _data->linesInBuffer;
1460
+
1461
+ _data->lineOffsets.resize (lineOffsetSize);
1462
+ }
1463
+ catch (...)
1464
+ {
1465
+ delete _data;
1466
+ _data=NULL;
1467
+ throw;
1468
+ }
1469
+ }
1470
+
1471
+ void
1472
+ ScanLineInputFile::setFrameBuffer (const FrameBuffer &frameBuffer)
1473
+ {
1474
+ Lock lock (*_streamData);
1475
+
1476
+
1477
+
1478
+ const ChannelList &channels = _data->header.channels();
1479
+ for (FrameBuffer::ConstIterator j = frameBuffer.begin();
1480
+ j != frameBuffer.end();
1481
+ ++j)
1482
+ {
1483
+ ChannelList::ConstIterator i = channels.find (j.name());
1484
+
1485
+ if (i == channels.end())
1486
+ continue;
1487
+
1488
+ if (i.channel().xSampling != j.slice().xSampling ||
1489
+ i.channel().ySampling != j.slice().ySampling)
1490
+ THROW (IEX_NAMESPACE::ArgExc, "X and/or y subsampling factors "
1491
+ "of \"" << i.name() << "\" channel "
1492
+ "of input file \"" << fileName() << "\" are "
1493
+ "not compatible with the frame buffer's "
1494
+ "subsampling factors.");
1495
+ }
1496
+
1497
+ // optimization is possible if this is a little endian system
1498
+ // and both inputs and outputs are half floats
1499
+ //
1500
+ bool optimizationPossible = true;
1501
+
1502
+ if (!GLOBAL_SYSTEM_LITTLE_ENDIAN)
1503
+ {
1504
+ optimizationPossible =false;
1505
+ }
1506
+
1507
+ vector<sliceOptimizationData> optData;
1508
+
1509
+
1510
+ //
1511
+ // Initialize the slice table for readPixels().
1512
+ //
1513
+
1514
+ vector<InSliceInfo> slices;
1515
+ ChannelList::ConstIterator i = channels.begin();
1516
+
1517
+ // current offset of channel: pixel data starts at offset*width into the
1518
+ // decompressed scanline buffer
1519
+ size_t offset = 0;
1520
+
1521
+ for (FrameBuffer::ConstIterator j = frameBuffer.begin();
1522
+ j != frameBuffer.end();
1523
+ ++j)
1524
+ {
1525
+ while (i != channels.end() && strcmp (i.name(), j.name()) < 0)
1526
+ {
1527
+ //
1528
+ // Channel i is present in the file but not
1529
+ // in the frame buffer; data for channel i
1530
+ // will be skipped during readPixels().
1531
+ //
1532
+
1533
+ slices.push_back (InSliceInfo (i.channel().type,
1534
+ i.channel().type,
1535
+ 0, // base
1536
+ 0, // xStride
1537
+ 0, // yStride
1538
+ i.channel().xSampling,
1539
+ i.channel().ySampling,
1540
+ false, // fill
1541
+ true, // skip
1542
+ 0.0)); // fillValue
1543
+
1544
+ switch(i.channel().type)
1545
+ {
1546
+ case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF :
1547
+ offset++;
1548
+ break;
1549
+ case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT :
1550
+ offset+=2;
1551
+ break;
1552
+ case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT :
1553
+ offset+=2;
1554
+ break;
1555
+ case OPENEXR_IMF_INTERNAL_NAMESPACE::NUM_PIXELTYPES:
1556
+ default:
1557
+ // not possible.
1558
+ break;
1559
+ }
1560
+ ++i;
1561
+ }
1562
+
1563
+ bool fill = false;
1564
+
1565
+ if (i == channels.end() || strcmp (i.name(), j.name()) > 0)
1566
+ {
1567
+ //
1568
+ // Channel i is present in the frame buffer, but not in the file.
1569
+ // In the frame buffer, slice j will be filled with a default value.
1570
+ //
1571
+
1572
+ fill = true;
1573
+ }
1574
+
1575
+ slices.push_back (InSliceInfo (j.slice().type,
1576
+ fill? j.slice().type:
1577
+ i.channel().type,
1578
+ j.slice().base,
1579
+ j.slice().xStride,
1580
+ j.slice().yStride,
1581
+ j.slice().xSampling,
1582
+ j.slice().ySampling,
1583
+ fill,
1584
+ false, // skip
1585
+ j.slice().fillValue));
1586
+
1587
+ if(!fill && i.channel().type!=OPENEXR_IMF_INTERNAL_NAMESPACE::HALF)
1588
+ {
1589
+ optimizationPossible = false;
1590
+ }
1591
+
1592
+ if(j.slice().type != OPENEXR_IMF_INTERNAL_NAMESPACE::HALF)
1593
+ {
1594
+ optimizationPossible = false;
1595
+ }
1596
+ if(j.slice().xSampling!=1 || j.slice().ySampling!=1)
1597
+ {
1598
+ optimizationPossible = false;
1599
+ }
1600
+
1601
+
1602
+ if(optimizationPossible)
1603
+ {
1604
+ sliceOptimizationData dat;
1605
+ dat.base = j.slice().base;
1606
+ dat.fill = fill;
1607
+ dat.fillValue = j.slice().fillValue;
1608
+ dat.offset = offset;
1609
+ dat.xStride = j.slice().xStride;
1610
+ dat.yStride = j.slice().yStride;
1611
+ dat.xSampling = j.slice().xSampling;
1612
+ dat.ySampling = j.slice().ySampling;
1613
+ optData.push_back(dat);
1614
+ }
1615
+
1616
+ if(!fill)
1617
+ {
1618
+ switch(i.channel().type)
1619
+ {
1620
+ case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF :
1621
+ offset++;
1622
+ break;
1623
+ case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT :
1624
+ offset+=2;
1625
+ break;
1626
+ case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT :
1627
+ offset+=2;
1628
+ break;
1629
+ case OPENEXR_IMF_INTERNAL_NAMESPACE::NUM_PIXELTYPES:
1630
+ default:
1631
+ // not possible.
1632
+ break;
1633
+ }
1634
+ }
1635
+
1636
+
1637
+
1638
+ if (i != channels.end() && !fill)
1639
+ ++i;
1640
+ }
1641
+
1642
+
1643
+ if(optimizationPossible)
1644
+ {
1645
+ //
1646
+ // check optimisibility
1647
+ // based on channel ordering and fill channel positions
1648
+ //
1649
+ sort(optData.begin(),optData.end());
1650
+ _data->optimizationMode = detectOptimizationMode(optData);
1651
+ }
1652
+
1653
+ if(!optimizationPossible || _data->optimizationMode._optimizable==false)
1654
+ {
1655
+ optData = vector<sliceOptimizationData>();
1656
+ _data->optimizationMode._optimizable=false;
1657
+ }
1658
+
1659
+ //
1660
+ // Store the new frame buffer.
1661
+ //
1662
+
1663
+ _data->frameBuffer = frameBuffer;
1664
+ _data->slices = slices;
1665
+ _data->optimizationData = optData;
1666
+ }
1667
+ ```
1668
+
1669
+ ### File: OpenEXR/IlmImf/ImfTiledInputFile.cpp
1670
+ ```c
1671
+ void
1672
+ TiledInputFile::compatibilityInitialize(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is)
1673
+ {
1674
+ is.seekg(0);
1675
+ //
1676
+ // Construct a MultiPartInputFile, initialize TiledInputFile
1677
+ // with the part 0 data.
1678
+ // (TODO) maybe change the third parameter of the constructor of MultiPartInputFile later.
1679
+ //
1680
+ _data->multiPartBackwardSupport = true;
1681
+ _data->multiPartFile = new MultiPartInputFile(is, _data->numThreads);
1682
+ InputPartData* part = _data->multiPartFile->getPart(0);
1683
+
1684
+ multiPartInitialize(part);
1685
+ }
1686
+ ```
1687
+
1688
+ ### File: OpenEXR/IlmImf/ImfTiledMisc.cpp
1689
+ ```c
1690
+ int
1691
+ getTiledChunkOffsetTableSize(const Header& header)
1692
+ {
1693
+ //
1694
+ // Save the dataWindow information
1695
+ //
1696
+
1697
+ const Box2i &dataWindow = header.dataWindow();
1698
+
1699
+ //
1700
+ // Precompute level and tile information.
1701
+ //
1702
+
1703
+ int* numXTiles;
1704
+ int* numYTiles;
1705
+ int numXLevels;
1706
+ int numYLevels;
1707
+ precalculateTileInfo (header.tileDescription(),
1708
+ dataWindow.min.x, dataWindow.max.x,
1709
+ dataWindow.min.y, dataWindow.max.y,
1710
+ numXTiles, numYTiles,
1711
+ numXLevels, numYLevels);
1712
+
1713
+ //
1714
+ // Calculate lineOffsetSize.
1715
+ //
1716
+ Int64 lineOffsetSize = 0;
1717
+ const TileDescription &desc = header.tileDescription();
1718
+ switch (desc.mode)
1719
+ {
1720
+ case ONE_LEVEL:
1721
+ case MIPMAP_LEVELS:
1722
+ for (int i = 0; i < numXLevels; i++)
1723
+ {
1724
+ lineOffsetSize += static_cast<Int64>(numXTiles[i]) * static_cast<Int64>(numYTiles[i]);
1725
+ if ( lineOffsetSize > static_cast<Int64>(std::numeric_limits<int>::max()) )
1726
+ {
1727
+ throw IEX_NAMESPACE::LogicExc("Maximum number of tiles exceeded");
1728
+ }
1729
+ }
1730
+ break;
1731
+ case RIPMAP_LEVELS:
1732
+ for (int i = 0; i < numXLevels; i++)
1733
+ {
1734
+ for (int j = 0; j < numYLevels; j++)
1735
+ {
1736
+ lineOffsetSize += static_cast<Int64>(numXTiles[i]) * static_cast<Int64>(numYTiles[j]);
1737
+ if ( lineOffsetSize > static_cast<Int64>(std::numeric_limits<int>::max()) )
1738
+ {
1739
+ throw IEX_NAMESPACE::LogicExc("Maximum number of tiles exceeded");
1740
+ }
1741
+ }
1742
+ }
1743
+ break;
1744
+ case NUM_LEVELMODES :
1745
+ throw IEX_NAMESPACE::LogicExc("Bad level mode getting chunk offset table size");
1746
+ }
1747
+
1748
+ delete[] numXTiles;
1749
+ delete[] numYTiles;
1750
+
1751
+ return static_cast<int>(lineOffsetSize);
1752
+ }
1753
+ ```
1754
+
1755
+ ### File: OpenEXR/IlmImfTest/testDeepTiledBasic.cpp
1756
+ ```c
1757
+ void readFile (int channelCount,
1758
+ bool bulkRead,
1759
+ bool relativeCoords,
1760
+ bool randomChannels,
1761
+ const std::string & filename)
1762
+ {
1763
+ if (relativeCoords)
1764
+ assert(bulkRead == false);
1765
+
1766
+ cout << "reading " << flush;
1767
+
1768
+ DeepTiledInputFile file (filename.c_str(), 4);
1769
+
1770
+ const Header& fileHeader = file.header();
1771
+ assert (fileHeader.displayWindow() == header.displayWindow());
1772
+ assert (fileHeader.dataWindow() == header.dataWindow());
1773
+ assert (fileHeader.pixelAspectRatio() == header.pixelAspectRatio());
1774
+ assert (fileHeader.screenWindowCenter() == header.screenWindowCenter());
1775
+ assert (fileHeader.screenWindowWidth() == header.screenWindowWidth());
1776
+ assert (fileHeader.lineOrder() == header.lineOrder());
1777
+ assert (fileHeader.compression() == header.compression());
1778
+ assert (fileHeader.channels() == header.channels());
1779
+ assert (fileHeader.type() == header.type());
1780
+ assert (fileHeader.tileDescription() == header.tileDescription());
1781
+
1782
+ Array2D<unsigned int> localSampleCount;
1783
+ localSampleCount.resizeErase(height, width);
1784
+
1785
+ // also test filling channels. Generate up to 2 extra channels
1786
+ int fillChannels=random_int(3);
1787
+
1788
+ Array<Array2D< void* > > data(channelCount+fillChannels);
1789
+ for (int i = 0; i < channelCount+fillChannels; i++)
1790
+ data[i].resizeErase(height, width);
1791
+
1792
+ DeepFrameBuffer frameBuffer;
1793
+
1794
+ int memOffset;
1795
+ if (relativeCoords)
1796
+ memOffset = 0;
1797
+ else
1798
+ memOffset = dataWindow.min.x + dataWindow.min.y * width;
1799
+ frameBuffer.insertSampleCountSlice (Slice (IMF::UINT,
1800
+ (char *) (&localSampleCount[0][0] - memOffset),
1801
+ sizeof (unsigned int) * 1,
1802
+ sizeof (unsigned int) * width,
1803
+ 1, 1,
1804
+ 0,
1805
+ relativeCoords,
1806
+ relativeCoords));
1807
+
1808
+
1809
+ vector<int> read_channel(channelCount);
1810
+ int channels_added=0;
1811
+ for (int i = 0; i < channelCount; i++)
1812
+ {
1813
+ if(randomChannels)
1814
+ {
1815
+ read_channel[i] = random_int(2);
1816
+
1817
+ }
1818
+ if(!randomChannels || read_channel[i]==1)
1819
+ {
1820
+ PixelType type = IMF::NUM_PIXELTYPES;
1821
+ if (channelTypes[i] == 0)
1822
+ type = IMF::UINT;
1823
+ if (channelTypes[i] == 1)
1824
+ type = IMF::HALF;
1825
+ if (channelTypes[i] == 2)
1826
+ type = IMF::FLOAT;
1827
+
1828
+ stringstream ss;
1829
+ ss << i;
1830
+ string str = ss.str();
1831
+
1832
+ int sampleSize = 0;
1833
+ if (channelTypes[i] == 0) sampleSize = sizeof (unsigned int);
1834
+ if (channelTypes[i] == 1) sampleSize = sizeof (half);
1835
+ if (channelTypes[i] == 2) sampleSize = sizeof (float);
1836
+
1837
+ int pointerSize = sizeof (char *);
1838
+
1839
+ frameBuffer.insert (str,
1840
+ DeepSlice (type,
1841
+ (char *) (&data[i][0][0] - memOffset),
1842
+ pointerSize * 1,
1843
+ pointerSize * width,
1844
+ sampleSize,
1845
+ 1, 1,
1846
+ 0,
1847
+ relativeCoords,
1848
+ relativeCoords));
1849
+ channels_added++;
1850
+ }
1851
+ }
1852
+ if(channels_added==0)
1853
+ {
1854
+ cout << "skipping " <<flush;
1855
+ return;
1856
+ }
1857
+ for(int i = 0 ; i < fillChannels ; ++i )
1858
+ {
1859
+ PixelType type = IMF::FLOAT;
1860
+ int sampleSize = sizeof(float);
1861
+ int pointerSize = sizeof (char *);
1862
+ stringstream ss;
1863
+ // generate channel names that aren't in file but (might) interleave with existing file
1864
+ ss << i << "fill";
1865
+ string str = ss.str();
1866
+ frameBuffer.insert (str,
1867
+ DeepSlice (type,
1868
+ (char *) (&data[i+channelCount][0][0] - memOffset),
1869
+ pointerSize * 1,
1870
+ pointerSize * width,
1871
+ sampleSize,
1872
+ 1, 1,
1873
+ 0,
1874
+ relativeCoords,
1875
+ relativeCoords));
1876
+ }
1877
+
1878
+ file.setFrameBuffer(frameBuffer);
1879
+
1880
+ if (bulkRead)
1881
+ cout << "bulk " << flush;
1882
+ else
1883
+ {
1884
+ if (relativeCoords == false)
1885
+ cout << "per-tile " << flush;
1886
+ else
1887
+ cout << "per-tile with relative coordinates " << flush;
1888
+ }
1889
+
1890
+ for (int ly = 0; ly < file.numYLevels(); ly++)
1891
+ for (int lx = 0; lx < file.numXLevels(); lx++)
1892
+ {
1893
+ Box2i dataWindowL = file.dataWindowForLevel(lx, ly);
1894
+
1895
+ if (bulkRead)
1896
+ {
1897
+ //
1898
+ // Testing bulk read (without relative coordinates).
1899
+ //
1900
+
1901
+ file.readPixelSampleCounts(0, file.numXTiles(lx) - 1, 0, file.numYTiles(ly) - 1, lx, ly);
1902
+
1903
+ for (int i = 0; i < file.numYTiles(ly); i++)
1904
+ {
1905
+ for (int j = 0; j < file.numXTiles(lx); j++)
1906
+ {
1907
+ Box2i box = file.dataWindowForTile(j, i, lx, ly);
1908
+ for (int y = box.min.y; y <= box.max.y; y++)
1909
+ for (int x = box.min.x; x <= box.max.x; x++)
1910
+ {
1911
+ int dwy = y - dataWindowL.min.y;
1912
+ int dwx = x - dataWindowL.min.x;
1913
+ assert(localSampleCount[dwy][dwx] == sampleCountWhole[ly][lx][dwy][dwx]);
1914
+
1915
+ for (size_t k = 0; k < channelTypes.size(); k++)
1916
+ {
1917
+ if (channelTypes[k] == 0)
1918
+ data[k][dwy][dwx] = new unsigned int[localSampleCount[dwy][dwx]];
1919
+ if (channelTypes[k] == 1)
1920
+ data[k][dwy][dwx] = new half[localSampleCount[dwy][dwx]];
1921
+ if (channelTypes[k] == 2)
1922
+ data[k][dwy][dwx] = new float[localSampleCount[dwy][dwx]];
1923
+ }
1924
+
1925
+ for( int f = 0 ; f < fillChannels ; ++f )
1926
+ {
1927
+ data[f + channelTypes.size()][dwy][dwx] = new float[localSampleCount[dwy][dwx]];
1928
+ }
1929
+
1930
+ }
1931
+
1932
+ }
1933
+ }
1934
+
1935
+ file.readTiles(0, file.numXTiles(lx) - 1, 0, file.numYTiles(ly) - 1, lx, ly);
1936
+ }
1937
+ else if (bulkRead == false)
1938
+ {
1939
+ if (relativeCoords == false)
1940
+ {
1941
+ //
1942
+ // Testing per-tile read without relative coordinates.
1943
+ //
1944
+
1945
+ for (int i = 0; i < file.numYTiles(ly); i++)
1946
+ {
1947
+ for (int j = 0; j < file.numXTiles(lx); j++)
1948
+ {
1949
+ file.readPixelSampleCount(j, i, lx, ly);
1950
+
1951
+ Box2i box = file.dataWindowForTile(j, i, lx, ly);
1952
+ for (int y = box.min.y; y <= box.max.y; y++)
1953
+ for (int x = box.min.x; x <= box.max.x; x++)
1954
+ {
1955
+ int dwy = y - dataWindowL.min.y;
1956
+ int dwx = x - dataWindowL.min.x;
1957
+ assert(localSampleCount[dwy][dwx] == sampleCountWhole[ly][lx][dwy][dwx]);
1958
+
1959
+ for (size_t k = 0;
1960
+
1961
+ // ... (9001 more chars)
1962
+ ```
1963
+
1964
+ ### File: OpenEXR/IlmImfTest/testMultiPartApi.cpp
1965
+ ```c
1966
+ ///////////////////////////////////////////////////////////////////////////
1967
+ //
1968
+ // Copyright (c) 2011, Industrial Light & Magic, a division of Lucas
1969
+ // Digital Ltd. LLC
1970
+ //
1971
+ // All rights reserved.
1972
+ //
1973
+ // Redistribution and use in source and binary forms, with or without
1974
+ // modification, are permitted provided that the following conditions are
1975
+ // met:
1976
+ // * Redistributions of source code must retain the above copyright
1977
+ // notice, this list of conditions and the following disclaimer.
1978
+ // * Redistributions in binary form must reproduce the above
1979
+ // copyright notice, this list of conditions and the following disclaimer
1980
+ // in the documentation and/or other materials provided with the
1981
+ // distribution.
1982
+ // * Neither the name of Industrial Light & Magic nor the names of
1983
+ // its contributors may be used to endorse or promote products derived
1984
+ // from this software without specific prior written permission.
1985
+ //
1986
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1987
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1988
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1989
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1990
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1991
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1992
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1993
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1994
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1995
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1996
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1997
+ //
1998
+ ///////////////////////////////////////////////////////////////////////////
1999
+
2000
+ #ifdef NDEBUG
2001
+ # undef NDEBUG
2002
+ #endif
2003
+
2004
+ #include <iostream>
2005
+ #include <string>
2006
+ #include <vector>
2007
+ #include <stdio.h>
2008
+ #include <stdlib.h>
2009
+ #include <assert.h>
2010
+
2011
+ #include "tmpDir.h"
2012
+ #include "testMultiPartApi.h"
2013
+ #include "random.h"
2014
+
2015
+ #include <ImfPartType.h>
2016
+ #include <ImfMultiPartInputFile.h>
2017
+ #include <ImfMultiPartOutputFile.h>
2018
+ #include <ImfOutputFile.h>
2019
+ #include <ImfTiledOutputFile.h>
2020
+ #include <ImfGenericOutputFile.h>
2021
+ #include <ImfArray.h>
2022
+ #include <ImfChannelList.h>
2023
+ #include <ImfOutputPart.h>
2024
+ #include <ImfInputPart.h>
2025
+ #include <ImfTiledOutputPart.h>
2026
+ #include <ImfTiledInputPart.h>
2027
+ #include <ImfTiledMisc.h>
2028
+
2029
+ namespace IMF = OPENEXR_IMF_NAMESPACE;
2030
+ using namespace IMF;
2031
+ using namespace std;
2032
+ using namespace IMATH_NAMESPACE;
2033
+
2034
+ namespace
2035
+ {
2036
+
2037
+ const int height = 263;
2038
+ const int width = 197;
2039
+
2040
+ struct Task
2041
+ {
2042
+ int partNumber;
2043
+ int tx, ty, lx, ly;
2044
+
2045
+ Task(int partNumber):
2046
+ partNumber(partNumber)
2047
+ {}
2048
+
2049
+ Task(int partNumber, int tx, int ty, int lx, int ly):
2050
+ partNumber(partNumber),
2051
+ tx(tx),
2052
+ ty(ty),
2053
+ lx(lx),
2054
+ ly(ly)
2055
+ {}
2056
+ };
2057
+
2058
+ vector<Header> headers;
2059
+ vector<int> pixelTypes;
2060
+ vector<int> partTypes;
2061
+ vector<int> levelModes;
2062
+
2063
+ template <class T>
2064
+ void fillPixels (Array2D<T> &ph, int width, int height)
2065
+ {
2066
+ ph.resizeErase(height, width);
2067
+ for (int y = 0; y < height; ++y)
2068
+ for (int x = 0; x < width; ++x)
2069
+ {
2070
+ //
2071
+ // We do this because half cannot store number bigger than 2048 exactly.
2072
+ //
2073
+ ph[y][x] = (y * width + x) % 2049;
2074
+ }
2075
+ }
2076
+
2077
+ template <class T>
2078
+ bool checkPixels (Array2D<T> &ph, int lx, int rx, int ly, int ry, int width)
2079
+ {
2080
+ for (int y = ly; y <= ry; ++y)
2081
+ for (int x = lx; x <= rx; ++x)
2082
+ if (ph[y][x] != static_cast<T>(((y * width + x) % 2049)))
2083
+ {
2084
+ cout << "value at " << x << ", " << y << ": " << ph[y][x]
2085
+ << ", should be " << (y * width + x) % 2049 << endl << flush;
2086
+ return false;
2087
+ }
2088
+ return true;
2089
+ }
2090
+
2091
+ template <class T>
2092
+ bool checkPixels (Array2D<T> &ph, int width, int height)
2093
+ {
2094
+ return checkPixels<T> (ph, 0, width - 1, 0, height - 1, width);
2095
+ }
2096
+
2097
+ void generateRandomHeaders(int partCount, vector<Header>& headers, vector<Task>& taskList)
2098
+ {
2099
+ headers.clear();
2100
+ for (int i = 0; i < partCount; i++)
2101
+ {
2102
+ Header header(width, height);
2103
+ int pixelType = random_int(3);
2104
+ int partType = random_int(2);
2105
+ pixelTypes[i] = pixelType;
2106
+ partTypes[i] = partType;
2107
+
2108
+ stringstream ss;
2109
+ ss << i;
2110
+ header.setName(ss.str());
2111
+
2112
+ switch (pixelType)
2113
+ {
2114
+ case 0:
2115
+ header.channels().insert("UINT", Channel(IMF::UINT));
2116
+ break;
2117
+ case 1:
2118
+ header.channels().insert("FLOAT", Channel(IMF::FLOAT));
2119
+ break;
2120
+ case 2:
2121
+ header.channels().insert("HALF", Channel(IMF::HALF));
2122
+ break;
2123
+ }
2124
+
2125
+ switch (partType)
2126
+ {
2127
+ case 0:
2128
+ header.setType(SCANLINEIMAGE);
2129
+ break;
2130
+ case 1:
2131
+ header.setType(TILEDIMAGE);
2132
+ break;
2133
+ }
2134
+
2135
+ int tileX;
2136
+ int tileY;
2137
+ int levelMode = 0;
2138
+ if (partType == 1)
2139
+ {
2140
+ tileX = random_int(width) + 1;
2141
+ tileY = random_int(height) + 1;
2142
+ levelMode = random_int(3);
2143
+ levelModes[i] = levelMode;
2144
+ LevelMode lm = NUM_LEVELMODES;
2145
+ switch (levelMode)
2146
+ {
2147
+ case 0:
2148
+ lm = ONE_LEVEL;
2149
+ break;
2150
+ case 1:
2151
+ lm = MIPMAP_LEVELS;
2152
+ break;
2153
+ case 2:
2154
+ lm = RIPMAP_LEVELS;
2155
+ break;
2156
+ }
2157
+ header.setTileDescription(TileDescription(tileX, tileY, lm));
2158
+ }
2159
+
2160
+ //
2161
+ // Add lines or tiles to task list.
2162
+ //
2163
+ if (partType == 0)
2164
+ {
2165
+ for (int j = 0; j < height; j++)
2166
+ taskList.push_back(Task(i));
2167
+ }
2168
+ else
2169
+ {
2170
+ int numXLevel;
2171
+ int numYLevel;
2172
+ int* numXTiles;
2173
+ int* numYTiles;
2174
+ precalculateTileInfo (header.tileDescription(),
2175
+ 0, width - 1,
2176
+ 0, height - 1,
2177
+ numXTiles, numYTiles,
2178
+ numXLevel, numYLevel);
2179
+
2180
+ for (int lx = 0; lx < numXLevel; lx++)
2181
+ for (int ly = 0; ly < numYLevel; ly++)
2182
+ {
2183
+ if (levelMode == 1)
2184
+ if (lx != ly) continue;
2185
+
2186
+ // Get all tasks for this level.
2187
+ for (int tx = 0; tx < numXTiles[lx]; tx++)
2188
+ for (int ty = 0; ty < numYTiles[ly]; ty++)
2189
+ taskList.push_back(Task(i, tx, ty, lx, ly));
2190
+ }
2191
+
2192
+ delete[] numXTiles;
2193
+ delete[] numYTiles;
2194
+ }
2195
+
2196
+ // if (partType == 0)
2197
+ // {
2198
+ // cout << "pixelType = " << pixelType << " partType = " << partType
2199
+ // << endl << flush;
2200
+ // }
2201
+ // else
2202
+ // {
2203
+ // cout << "pixelType = " << pixelType << " partType = " << partType
2204
+ // << " levelMode = " << levelModes[i] << endl << flush;
2205
+ // }
2206
+
2207
+ headers.push_back(header);
2208
+ }
2209
+ }
2210
+
2211
+ void setOutputFrameBuffer(FrameBuffer& frameBuffer, int pixelType,
2212
+ Array2D<unsigned int>& uData, Array2D<float>& fData,
2213
+ Array2D<half>& hData, int width)
2214
+ {
2215
+ switch (pixelType)
2216
+ {
2217
+ case 0:
2218
+ frameBuffer.insert ("UINT",
2219
+ Slice (IMF::UINT,
2220
+ (char *) (&uData[0][0]),
2221
+ sizeof (uData[0][0]) * 1,
2222
+ sizeof (uData[0][0]) * width));
2223
+ break;
2224
+ case 1:
2225
+ frameBuffer.insert ("FLOAT",
2226
+ Slice (IMF::FLOAT,
2227
+
2228
+
2229
+ // ... (16431 more chars)
2230
+ ```
2231
+
2232
+ ### File: OpenEXR/IlmImfTest/testMultiPartThreading.cpp
2233
+ ```c
2234
+ ///////////////////////////////////////////////////////////////////////////
2235
+ //
2236
+ // Copyright (c) 2011, Industrial Light & Magic, a division of Lucas
2237
+ // Digital Ltd. LLC
2238
+ //
2239
+ // All rights reserved.
2240
+ //
2241
+ // Redistribution and use in source and binary forms, with or without
2242
+ // modification, are permitted provided that the following conditions are
2243
+ // met:
2244
+ // * Redistributions of source code must retain the above copyright
2245
+ // notice, this list of conditions and the following disclaimer.
2246
+ // * Redistributions in binary form must reproduce the above
2247
+ // copyright notice, this list of conditions and the following disclaimer
2248
+ // in the documentation and/or other materials provided with the
2249
+ // distribution.
2250
+ // * Neither the name of Industrial Light & Magic nor the names of
2251
+ // its contributors may be used to endorse or promote products derived
2252
+ // from this software without specific prior written permission.
2253
+ //
2254
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2255
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2256
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2257
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2258
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2259
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2260
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2261
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2262
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2263
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2264
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2265
+ //
2266
+ ///////////////////////////////////////////////////////////////////////////
2267
+
2268
+ #ifdef NDEBUG
2269
+ # undef NDEBUG
2270
+ #endif
2271
+
2272
+ #include <iostream>
2273
+ #include <string>
2274
+ #include <vector>
2275
+ #include <stdio.h>
2276
+ #include <stdlib.h>
2277
+ #include <assert.h>
2278
+
2279
+ #include "tmpDir.h"
2280
+ #include "testMultiPartThreading.h"
2281
+ #include "random.h"
2282
+
2283
+ #include <ImfPartType.h>
2284
+ #include <ImfMultiPartInputFile.h>
2285
+ #include <ImfMultiPartOutputFile.h>
2286
+ #include <ImfOutputFile.h>
2287
+ #include <ImfTiledOutputFile.h>
2288
+ #include <ImfGenericOutputFile.h>
2289
+ #include <ImfArray.h>
2290
+ #include <ImfChannelList.h>
2291
+ #include <ImfOutputPart.h>
2292
+ #include <ImfInputPart.h>
2293
+ #include <ImfTiledOutputPart.h>
2294
+ #include <ImfTiledInputPart.h>
2295
+ #include <IlmThreadPool.h>
2296
+ #include <IlmThreadMutex.h>
2297
+ #include <ImfTiledMisc.h>
2298
+
2299
+ namespace IMF = OPENEXR_IMF_NAMESPACE;
2300
+ using namespace IMF;
2301
+ using namespace std;
2302
+ using namespace IMATH_NAMESPACE;
2303
+ using namespace ILMTHREAD_NAMESPACE;
2304
+
2305
+ namespace
2306
+ {
2307
+
2308
+ const int height = 263;
2309
+ const int width = 197;
2310
+
2311
+ vector<Header> headers;
2312
+ vector<int> pixelTypes;
2313
+ vector<int> partTypes;
2314
+ vector<int> levelModes;
2315
+
2316
+ Mutex mutexes[200];
2317
+
2318
+ template <class T>
2319
+ void fillPixels (Array2D<T> &ph, int width, int height)
2320
+ {
2321
+ ph.resizeErase(height, width);
2322
+ for (int y = 0; y < height; ++y)
2323
+ for (int x = 0; x < width; ++x)
2324
+ {
2325
+ //
2326
+ // We do this because half cannot store number bigger than 2048 exactly.
2327
+ //
2328
+ ph[y][x] = (y * width + x) % 2049;
2329
+ }
2330
+ }
2331
+
2332
+ template <class T>
2333
+ bool checkPixels (Array2D<T> &ph, int lx, int rx, int ly, int ry, int width)
2334
+ {
2335
+ for (int y = ly; y <= ry; ++y)
2336
+ for (int x = lx; x <= rx; ++x)
2337
+ if (ph[y][x] != static_cast<T>(((y * width + x) % 2049)))
2338
+ {
2339
+ cout << "value at " << x << ", " << y << ": " << ph[y][x]
2340
+ << ", should be " << (y * width + x) % 2049 << endl << flush;
2341
+ return false;
2342
+ }
2343
+ return true;
2344
+ }
2345
+
2346
+ template <class T>
2347
+ bool checkPixels (Array2D<T> &ph, int width, int height)
2348
+ {
2349
+ return checkPixels<T> (ph, 0, width - 1, 0, height - 1, width);
2350
+ }
2351
+
2352
+ void setOutputFrameBuffer(FrameBuffer& frameBuffer, int pixelType,
2353
+ Array2D<unsigned int>& uData, Array2D<float>& fData,
2354
+ Array2D<half>& hData, int width)
2355
+ {
2356
+ switch (pixelType)
2357
+ {
2358
+ case 0:
2359
+ frameBuffer.insert ("UINT",
2360
+ Slice (IMF::UINT,
2361
+ (char *) (&uData[0][0]),
2362
+ sizeof (uData[0][0]) * 1,
2363
+ sizeof (uData[0][0]) * width));
2364
+ break;
2365
+ case 1:
2366
+ frameBuffer.insert ("FLOAT",
2367
+ Slice (IMF::FLOAT,
2368
+ (char *) (&fData[0][0]),
2369
+ sizeof (fData[0][0]) * 1,
2370
+ sizeof (fData[0][0]) * width));
2371
+ break;
2372
+ case 2:
2373
+ frameBuffer.insert ("HALF",
2374
+ Slice (IMF::HALF,
2375
+ (char *) (&hData[0][0]),
2376
+ sizeof (hData[0][0]) * 1,
2377
+ sizeof (hData[0][0]) * width));
2378
+ break;
2379
+ }
2380
+ }
2381
+
2382
+ void setInputFrameBuffer(FrameBuffer& frameBuffer, int pixelType,
2383
+ Array2D<unsigned int>& uData, Array2D<float>& fData,
2384
+ Array2D<half>& hData, int width, int height)
2385
+ {
2386
+ switch (pixelType)
2387
+ {
2388
+ case 0:
2389
+ uData.resizeErase(height, width);
2390
+ frameBuffer.insert ("UINT",
2391
+ Slice (IMF::UINT,
2392
+ (char *) (&uData[0][0]),
2393
+ sizeof (uData[0][0]) * 1,
2394
+ sizeof (uData[0][0]) * width,
2395
+ 1, 1,
2396
+ 0));
2397
+ break;
2398
+ case 1:
2399
+ fData.resizeErase(height, width);
2400
+ frameBuffer.insert ("FLOAT",
2401
+ Slice (IMF::FLOAT,
2402
+ (char *) (&fData[0][0]),
2403
+ sizeof (fData[0][0]) * 1,
2404
+ sizeof (fData[0][0]) * width,
2405
+ 1, 1,
2406
+ 0));
2407
+ break;
2408
+ case 2:
2409
+ hData.resizeErase(height, width);
2410
+ frameBuffer.insert ("HALF",
2411
+ Slice (IMF::HALF,
2412
+ (char *) (&hData[0][0]),
2413
+ sizeof (hData[0][0]) * 1,
2414
+ sizeof (hData[0][0]) * width,
2415
+ 1, 1,
2416
+ 0));
2417
+ break;
2418
+ }
2419
+ }
2420
+
2421
+ struct WritingTaskData
2422
+ {
2423
+ int partNumber;
2424
+ int tx, ty, lx, ly;
2425
+
2426
+ WritingTaskData(int partNumber):
2427
+ partNumber(partNumber)
2428
+ {}
2429
+
2430
+ WritingTaskData(int partNumber, int tx, int ty, int lx, int ly):
2431
+ partNumber(partNumber),
2432
+ tx(tx),
2433
+ ty(ty),
2434
+ lx(lx),
2435
+ ly(ly)
2436
+ {}
2437
+ };
2438
+
2439
+ class WritingTask: public Task
2440
+ {
2441
+ public:
2442
+ WritingTask (TaskGroup *group, MultiPartOutputFile* file, vector<WritingTaskData*> data,
2443
+ Array2D<FrameBuffer>* tiledFrameBuffers):
2444
+ Task(group),
2445
+ file(file),
2446
+ data(data),
2447
+ tiledFrameBuffers(tiledFrameBuffers)
2448
+ {}
2449
+
2450
+ void execute()
2451
+ {
2452
+ for (size_t i = 0; i < data.size(); i++)
2453
+ {
2454
+ int partNumber = data[i]->partNumber;
2455
+ int partType = partTypes[partNumber];
2456
+
2457
+ if (partType == 0)
2458
+ {
2459
+ OutputPart part(*file, partNumber);
2460
+ part.writePixels();
2461
+ }
2462
+ else
2463
+ {
2464
+ int tx = data[i]->tx;
2465
+ int ty = data[i]->ty;
2466
+ int lx = data[i]->lx;
2467
+ int ly = data[i]->ly;
2468
+ TiledOutputPart part(*file, partNumber);
2469
+
2470
+ //
2471
+ // We add lock here to assure that two threads that accessing
2472
+ // the same part won't mess things up.
2473
+
2474
+
2475
+ // ... (19261 more chars)
2476
+ ```
2477
+
2478
+ ### File: OpenEXR/exrmakepreview/makePreview.cpp
2479
+ ```c
2480
+ void
2481
+ generatePreview (const char inFileName[],
2482
+ float exposure,
2483
+ int previewWidth,
2484
+ int &previewHeight,
2485
+ Array2D <PreviewRgba> &previewPixels)
2486
+ {
2487
+ //
2488
+ // Read the input file
2489
+ //
2490
+
2491
+ RgbaInputFile in (inFileName);
2492
+
2493
+ Box2i dw = in.dataWindow();
2494
+ float a = in.pixelAspectRatio();
2495
+ int w = dw.max.x - dw.min.x + 1;
2496
+ int h = dw.max.y - dw.min.y + 1;
2497
+
2498
+ Array2D <Rgba> pixels (h, w);
2499
+ in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w);
2500
+ in.readPixels (dw.min.y, dw.max.y);
2501
+
2502
+ //
2503
+ // Make a preview image
2504
+ //
2505
+
2506
+ previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1);
2507
+ previewPixels.resizeErase (previewHeight, previewWidth);
2508
+
2509
+ float fx = (previewWidth > 1)? (float (w - 1) / (previewWidth - 1)): 1;
2510
+ float fy = (previewHeight > 1)? (float (h - 1) / (previewHeight - 1)): 1;
2511
+ float m = Math<float>::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f));
2512
+
2513
+ for (int y = 0; y < previewHeight; ++y)
2514
+ {
2515
+ for (int x = 0; x < previewWidth; ++x)
2516
+ {
2517
+ PreviewRgba &preview = previewPixels[y][x];
2518
+ const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)];
2519
+
2520
+ preview.r = gamma (pixel.r, m);
2521
+ preview.g = gamma (pixel.g, m);
2522
+ preview.b = gamma (pixel.b, m);
2523
+ preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f);
2524
+ }
2525
+ }
2526
+ }
2527
+ ```
tasks/csa159/pair_136251/task_prompt.md ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Task: Synthesize a CSA Checker from a CVE Patch
2
+
3
+ ## Your Role
4
+
5
+ You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker
6
+ that detects the bug pattern fixed by the CVE patch in this working directory.
7
+
8
+ You have full filesystem and bash access — use them.
9
+
10
+ ### Skills
11
+
12
+ Many skills are available under `.claude/skills/` — covering vulnerability analysis,
13
+ checker design, debugging, code audit, security patterns, and more. Each skill
14
+ encodes reusable expertise: take time to explore them, read their SKILL.md files,
15
+ and invoke those that look useful via the Skill tool. Let the task guide which
16
+ ones you reach for.
17
+
18
+ ## File Layout
19
+
20
+ ```
21
+ /work/
22
+ ├── compile.sh ← RUN ME: compile checker.cpp → checker.so
23
+ ├── checker_template.cpp ← skeleton, start here
24
+ ├── patch.diff ← the CVE fix
25
+ ├── pre_functions.txt ← buggy source (before_commit)
26
+ ├── post_functions.txt ← patched source (after_commit)
27
+ ├── config.json ← paths, commit_message, commit hashes, flags
28
+ ├── scan/
29
+ │ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy
30
+ │ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched
31
+ │ └── flags_*.txt ← pre-extracted compile flags (-I, -D)
32
+ ├── references/
33
+ │ ├── repo_knowledge.md ← project-specific API/convention reference
34
+ │ ├── patterns_summary.md ← (optional) historical bug pattern summary
35
+ │ ├── cwe_cards/ ← CWE knowledge library (all categories)
36
+ │ │ ├── index.json ← lookup index — use to find relevant cards
37
+ │ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns
38
+ │ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped)
39
+ │ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers)
40
+ │ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.)
41
+ │ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.)
42
+ │ └── examples/
43
+ │ └── llvm-official/ ← 5 official checker sources (with comments)
44
+ │ ├── 01_div_zero.cpp
45
+ │ ├── 02_simple_stream.cpp
46
+ │ ├── 03_undef_result.cpp
47
+ │ ├── 04_nullability.cpp
48
+ │ └── 05_malloc.cpp
49
+ │
50
+ ├── checker.cpp ← YOUR OUTPUT: synthesized checker
51
+ ├── checker.so ← YOUR OUTPUT: compiled checker
52
+ ├── state.json ← YOUR OUTPUT: structured task state
53
+ ├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3)
54
+ └── summary.json ← YOUR OUTPUT: final report
55
+ ```
56
+
57
+ ## Resources
58
+
59
+ **Read these before writing any code:**
60
+
61
+ 1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from
62
+ LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types,
63
+ MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.**
64
+
65
+ 2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested
66
+ patterns from official LLVM checkers: resource tracking, null checking, undefined
67
+ value detection, division-by-zero, and malloc/free. Each pattern includes skeleton
68
+ code, state traits, and key API usage.
69
+
70
+ 3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations
71
+ with explanatory comments:
72
+ - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback)
73
+ - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose)
74
+ - `03_undef_result.cpp` — PostStmt pattern (160 lines)
75
+ - `04_nullability.cpp` — multi-callback checker (1247 lines)
76
+ - `05_malloc.cpp` — comprehensive malloc/free (1511 lines)
77
+
78
+ 4. **`checker_template.cpp`** — Skeleton with placeholders. Start here.
79
+
80
+ 5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this
81
+ repository's memory allocation API, key data types, source layout, and typical
82
+ CVE patterns. **Read this before writing the checker** — knowing the project's
83
+ alloc/free conventions and common bug patterns saves many grep rounds.
84
+
85
+ 5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis
86
+ patterns for this project. If present, it contains a concise summary of the
87
+ most common bug patterns, frequent CWE categories, and reusable checker
88
+ architectures observed in previous synthesis runs. Read after repo_knowledge.md.
89
+
90
+ 6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all
91
+ vulnerability categories. **The framework provides the full library —
92
+ you must identify the vulnerability type yourself.** Workflow:
93
+
94
+ 1. Analyse the patch diff and commit message to determine the vulnerability
95
+ type (buffer overflow, UAF, null deref, integer overflow, race condition,
96
+ etc.). Do NOT rely on the CWE label — treat it as a hint at most.
97
+ 2. Open ``index.json`` to discover available cards and their tiers.
98
+ 3. Read the relevant card(s) for **detection strategies**, **checker
99
+ architecture suggestions**, and **known false-positive patterns**.
100
+
101
+ Card tiers:
102
+ - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel /
103
+ userspace variants when the detection strategy differs substantially.
104
+ - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by
105
+ category (input validation, resource management, etc.).
106
+
107
+ 7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for
108
+ checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`),
109
+ expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string
110
+ size extraction, MemRegion helpers, and `ExprHasName()` for robust function
111
+ matching. All verified against LLVM 18. **Read before implementing detection
112
+ logic** — these save writing boilerplate that's easy to get wrong.
113
+
114
+ ## Environment
115
+
116
+ Key paths are in ``config.json``.
117
+
118
+ ### Pre-built scripts
119
+
120
+ | Script | What it does |
121
+ |--------|-------------|
122
+ | `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) |
123
+ | `CHECKER_NAME=<name> bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy |
124
+ | `CHECKER_NAME=<name> bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched |
125
+
126
+ ```bash
127
+ # Compile (run from workdir root)
128
+ bash compile.sh
129
+
130
+ # Scan — set CHECKER_NAME to the string passed to addChecker<>()
131
+ CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy
132
+ CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched
133
+ ```
134
+
135
+ - ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags.
136
+ - ``scan/scan_*.sh`` count only warnings tagged with your checker name.
137
+ - Scan environments (source files + compile flags) are pre-built in ``scan/``.
138
+
139
+ ### Scan Script Integrity (CRITICAL)
140
+
141
+ The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only
142
+ valid measurement** of N_buggy and N_patched. They are the ground truth that the
143
+ Python-side validator will also use. You MUST obey these rules:
144
+
145
+ **1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly
146
+ to measure warning counts. The Python validator runs the same scan scripts
147
+ — if you measured with a different command, your numbers will not reproduce
148
+ and the synthesis will be rejected.
149
+
150
+ **2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared
151
+ identifiers, etc.), the scan environment needs repair. You MUST fix it:
152
+ - Add missing ``-I`` include paths to the flags files in ``scan/``
153
+ - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot
154
+ - If the file fundamentally cannot be compiled by clang, stop and write
155
+ ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason``
156
+
157
+ **3. Only trust scan script output.** The ``Total <name> warnings: N`` line
158
+ printed by the scan script is the number that goes into ``summary.json``.
159
+ If the scan script says 0, write 0. Fabricating numbers that the scan
160
+ script did not produce will cause the Python validator to reject the
161
+ synthesis.
162
+
163
+ - If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles).
164
+ - If validation fails: revise checker logic, re-compile, re-scan.
165
+
166
+ ## MCP Tools
167
+
168
+ You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`).
169
+ Each returns **source context embedded in the result** — no need to follow up with Read.
170
+
171
+ | Tool | What it does | Key advantage |
172
+ |------|-------------|---------------|
173
+ | `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call |
174
+ | `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file |
175
+ | `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed |
176
+
177
+ ### When to use each
178
+
179
+ - **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure.
180
+ - **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines.
181
+ - **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action.
182
+
183
+ ## Semantic Design Contract — before writing checker.cpp
184
+
185
+ Create the analysis portions of `state.json` and `scope_statement.md` **before**
186
+ writing checker.cpp. They are a design contract, not a retrospective summary.
187
+ After compilation, update only implementation facts such as `build_attempts`.
188
+
189
+ In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the
190
+ semantic fact introduced by the patch that makes it safe. In `detection_plan`,
191
+ make `report_condition`, `safe_condition`, and `source_level_signal` concrete
192
+ CSA-observable facts. In `api_choice`, record the mechanism level and explain
193
+ why the selected callback can observe and prove those facts.
194
+
195
+ In `scope_statement.md`, include this mapping table and check it again after
196
+ implementation:
197
+
198
+ | Semantic condition | CSA evidence | checker.cpp implementation |
199
+ | --- | --- | --- |
200
+ | report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports |
201
+ | safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report |
202
+
203
+ Every condition in the plan must have an implementation entry. Do not claim a
204
+ condition that checker.cpp does not implement, and do not silently add a code
205
+ condition absent from the plan.
206
+
207
+ ## Mechanism Selection — diagnose before coding
208
+
209
+ Choose the weakest CSA mechanism that can prove the vulnerability property:
210
+
211
+ 1. **syntax-only AST**: only when local AST shape itself is the defect;
212
+ 2. **control flow / dominance**: when guard placement relative to a sink matters;
213
+ 3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use;
214
+ 4. **cross-procedure/dataflow**: when the required fact crosses function boundaries.
215
+
216
+ For a guard-based patch, prove both that the guard rejects the unsafe value and
217
+ that it dominates the vulnerable use. For path-sensitive or cross-procedure
218
+ defects, do not replace the required state or flow proof with local AST matching
219
+ or source-text substring matching merely because it passes the differential scan.
220
+ Record the selected level as `api_choice.mechanism_level`.
221
+
222
+ ## Semantic identity, locality, and final validation
223
+
224
+ Before accepting the checker, verify that its primary matching logic does not
225
+ depend on patch-local variable names, labels, line numbers, commit IDs, or unique
226
+ literals. Project APIs, types, and stable semantic call relationships are valid
227
+ scope anchors when they define the vulnerability class. Attach the report to the
228
+ actual vulnerable operation, and implement every suppression as a real safe
229
+ condition rather than the mere presence of a nearby guard-shaped statement.
230
+
231
+ The required final sequence is: **compile → before scan → after scan → inspect
232
+ the final checker name, artifacts, and report locations → write summary.json**.
233
+ Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only
234
+ additional redesign cycles after a failed validation; if it is zero, preserve the
235
+ real validation evidence and report failure honestly rather than fabricating counts.
236
+
237
+ ## Validation Criteria
238
+
239
+ ```
240
+ VALID : N_buggy > N_patched AND N_patched < 50
241
+ INVALID : otherwise → revise and re-validate (max 1 attempts)
242
+ ```
243
+
244
+ ## Refinement
245
+
246
+ Do NOT self-refine the checker repeatedly. Your goal is to produce the first
247
+ checker that passes the Validation Criteria above — fix compile errors and
248
+ validation failures only. False positives are triaged and repaired by the
249
+ framework's refinement stage: you will receive a concrete FP list via
250
+ session resume (if needed) and fix only those. Reserve budget for that stage.
251
+
252
+ ## Output
253
+
254
+ Produce all of the following **only when completely done**:
255
+
256
+ | File | Content |
257
+ |------|---------|
258
+ | ``checker.cpp`` | Synthesized checker source code |
259
+ | ``checker.so`` | Compiled checker plugin |
260
+ | ``state.json`` | Structured task state (see schema below) |
261
+ | ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) |
262
+ | ``summary.json`` | Final report (see schema below) |
263
+
264
+ Writing ``summary.json`` signals completion. Do NOT write it early.
265
+
266
+ ### ``state.json``
267
+
268
+ Create this before writing checker.cpp to capture the design contract. After the
269
+ checker compiles, update only implementation facts and retain the original
270
+ semantic plan.
271
+
272
+ ```json
273
+ {
274
+ "patch_analysis": {
275
+ "summary": "One sentence describing the vulnerability this patch fixes",
276
+ "changed_files": ["file1.c", "file2.h"],
277
+ "changed_functions": ["func_a", "func_b"],
278
+ "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other",
279
+ "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other",
280
+ "affected_types": ["GF_BitStream", "custom_struct_t"],
281
+ "critical_calls": ["gf_strdup", "memcpy"]
282
+ },
283
+ "detection_plan": {
284
+ "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')",
285
+ "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')",
286
+ "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')",
287
+ "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')"
288
+ },
289
+ "api_choice": {
290
+ "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow",
291
+ "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...",
292
+ "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions",
293
+ "alternatives_considered": ["check::PostCall"]
294
+ },
295
+ "implementation": {
296
+ "scope_level": "patch_specific | project_general | cross_project",
297
+ "checker_name": "project.CheckerName",
298
+ "build_attempts": 1
299
+ }
300
+ }
301
+ ```
302
+
303
+ ### ``summary.json``
304
+
305
+ ```json
306
+ {
307
+ "status": "plausible | failed",
308
+ "bug_pattern": "One sentence describing the bug pattern",
309
+ "scope_level": "patch_specific | project_general | cross_project",
310
+ "checker_cpp": "checker.cpp",
311
+ "checker_so": "checker.so",
312
+ "n_buggy": 0,
313
+ "n_patched": 0,
314
+ "total_reports": 0,
315
+ "fp_rate_estimate": 0.0,
316
+ "failure_reason": null
317
+ }
318
+ ```
319
+
320
+ ## Feedback-derived requirements for this fresh synthesis
321
+
322
+ A prior independent rollout exposed the risks below. Start again from the patch
323
+ in this new session. Do not reconstruct, edit, or assume the prior checker.
324
+
325
+ Required mechanism level: `path_sensitive`
326
+
327
+ ### Current failure diagnosis
328
+
329
+ - The prior rollout achieved the required semantic result and differential result, but process quality was below threshold.
330
+ - Patch-local hardcoding was detected because the checker source embedded the patch commit identifier in its explanatory text, despite otherwise avoiding patch anchors.
331
+
332
+ ### Preserve from prior rollouts
333
+
334
+ - Preserve successful checker compilation, before/after validation, and code verification.
335
+ - Preserve objective eligibility gate G6.
336
+ - Preserve an accepted or clean refinement outcome.
337
+ - Preserve the path-sensitive CSA mechanism level as adequate for the vulnerability.
338
+ - Preserve semantic score at or above the configured threshold.
339
+ - Do not introduce dependence on patch anchors.
340
+
341
+ ### Required semantic proof
342
+
343
+ - Establish that the RLE decompressor can reach the input memcpy with a feasible path where the remaining input counter is negative.
344
+ - Treat the input pointer and remaining-length counter as the paired buffer invariant: after consuming the run-length byte and decrementing by count plus one, a negative remaining count means the memcpy may read beyond the input.
345
+ - Establish that the patched negative-length guard rejects every such path before the memcpy, making the negative-counter feasibility query infeasible at the sink.
346
+ - Report the unsafe relation only for the relevant input-buffer memcpy in the RLE decompressor.
347
+
348
+ ### Implementation constraints
349
+
350
+ - Use a path-sensitive sink callback such as check::PreCall so the query observes ProgramState immediately before the relevant memcpy.
351
+ - Recognize the three-argument memcpy operation and require its source expression to resolve to the function's input parameter.
352
+ - Restrict analysis to rleUncompress and obtain the remaining-length parameter through the function declaration and analyzer state rather than source-text matching.
353
+ - Construct and query the symbolic predicate remaining_length < 0 with the CSA constraint manager; remain silent when the value is unknown or undefined.
354
+ - Emit a non-fatal diagnostic at the relevant memcpy call, with no reports for unrelated copies or sibling branches such as the separate memset path.
355
+ - Do not encode commit identifiers, patch line numbers, patch-specific comments, source snippets, or other patch-local anchors.
356
+
357
+ ### Validation checklist
358
+
359
+ - Compile the new checker successfully against the available Clang Static Analyzer API and verify that registration and report logic are present.
360
+ - Run the official before-and-after scans and confirm at least one relevant report in the buggy program and no report in the patched program.
361
+ - Confirm the disappeared diagnostic belongs to rleUncompress and is located at or immediately around the relevant memcpy, with no warnings in unrelated functions.
362
+ - Check that non-patched code produces no reports attributable to this rule and that the result remains sparse.
363
+ - Verify the negative-state query is feasible on the buggy path and infeasible after the patched guard, rather than relying only on textual guard placement.
364
+ - Run code verification and refinement evaluation, preserving the objective gate, semantic threshold, and accepted or clean refinement outcome.
365
+ - Run process and hardcoding checks to ensure the implementation contains no patch-anchor dependence or commit-specific identifiers.
366
+
367
+ ### Avoid and forbidden regressions
368
+
369
+ - Do not replace the path-sensitive state query with syntax-only matching or dominance placement alone.
370
+ - Do not report merely because a memcpy exists in the function; require the source-parameter relation and feasible negative remaining-length state.
371
+ - Do not model unrelated OpenEXR fixes or broaden the rule to other decompressor functions without supplied semantic evidence.
372
+ - Do not report when analyzer information about the remaining-length value is unknown or undefined.
373
+ - Do not introduce patch-specific commit hashes, line numbers, copied patch text, or source-text signatures.
374
+ - Do not weaken the accepted path-sensitive semantic contract to improve process or hardcoding scores.
tasks/csa159/pair_136252/checker_template.cpp ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ============================================================================
2
+ // CSA Checker Template
3
+ // ============================================================================
4
+ // Fill in the sections marked with TODO to implement your checker.
5
+ // The checker is compiled with -fno-rtti to match the LLVM 18 build config.
6
+ // It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName
7
+ //
8
+ // Compilation:
9
+ // clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \
10
+ // -I${LLVM_BUILD_DIR}/include \
11
+ // checker.cpp -o checker.so \
12
+ // -Wl,--allow-shlib-undefined
13
+ //
14
+ // Usage:
15
+ // clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze <file>
16
+ // ============================================================================
17
+
18
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20
+ #include "clang/StaticAnalyzer/Core/Checker.h"
21
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23
+ #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
24
+
25
+ using namespace clang;
26
+ using namespace ento;
27
+
28
+ namespace {
29
+
30
+ // ────────────────────────────────────────────────────────────────
31
+ // TODO: Rename this class to describe your checker's purpose.
32
+ // ────────────────────────────────────────────────────────────────
33
+ class {{CHECKER_CLASS_NAME}}
34
+ : public Checker<check::PreCall, // for checking before function calls
35
+ check::PostCall> // for checking after function calls
36
+ {
37
+ // TODO: Customize the bug type name and category.
38
+ mutable std::unique_ptr<BugType> BT;
39
+
40
+ public:
41
+ {{CHECKER_CLASS_NAME}}()
42
+ : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {}
43
+
44
+ // ── PreCall callback (fires before every function call) ──────
45
+ void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
46
+ // TODO: Implement your pre-call analysis logic here.
47
+ //
48
+ // Common patterns:
49
+ //
50
+ // 1. Check if the called function matches a specific name:
51
+ // if (Call.getCalleeIdentifier()) {
52
+ // StringRef name = Call.getCalleeIdentifier()->getName();
53
+ // if (name == "target_function") { ... }
54
+ // }
55
+ //
56
+ // 2. Get the program state:
57
+ // ProgramStateRef State = C.getState();
58
+ //
59
+ // 3. Get arguments:
60
+ // SVal Arg = Call.getArgSVal(0);
61
+ //
62
+ // 4. Generate a bug report:
63
+ // ExplodedNode *ErrNode = C.generateErrorNode();
64
+ // if (ErrNode) {
65
+ // auto R = std::make_unique<PathSensitiveBugReport>(
66
+ // *BT, "Description of the bug", ErrNode);
67
+ // C.emitReport(std::move(R));
68
+ // }
69
+ }
70
+
71
+ // ── PostCall callback (fires after every function call) ─────
72
+ void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
73
+ // TODO: Implement your post-call analysis logic here.
74
+ //
75
+ // Common pattern — check the return value:
76
+ // SVal RetVal = Call.getReturnValue();
77
+ // if (RetVal.isUnknownOrUndef()) return;
78
+ //
79
+ // ProgramStateRef State = C.getState();
80
+ // // Modify state based on post-call conditions...
81
+ }
82
+ };
83
+
84
+ } // anonymous namespace
85
+
86
+ // ────────────────────────────────────────────────────────────────
87
+ // Registration — DO NOT modify the function signatures.
88
+ // ────────────────────────────────────────────────────────────────
89
+
90
+ extern "C" void clang_registerCheckers(CheckerRegistry &registry) {
91
+ registry.addChecker<{{CHECKER_CLASS_NAME}}>(
92
+ "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker"
93
+ "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference"
94
+ "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs"
95
+ }
96
+
97
+ extern "C" const char clang_analyzerAPIVersionString[] =
98
+ CLANG_ANALYZER_API_VERSION_STRING;
tasks/csa159/pair_136252/config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "project_id": "openexr_openexr",
3
+ "before_commit": "1cbf6b9a4497f71586ac11dc60ed21cf0cc529bd",
4
+ "after_commit": "6bad53af7eebed507564dd5fc90320e4c6a6c0bc",
5
+ "repo_path": "/workspace/repo/openexr/openexr",
6
+ "llvm_build_dir": "/opt/llvm",
7
+ "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/openexr_openexr/6546ff20961003825f86662efe16842ff6a64f32/compile_commands.json",
8
+ "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/openexr_openexr/6546ff20961003825f86662efe16842ff6a64f32/compile_commands.json",
9
+ "changed_files": [
10
+ "OpenEXR/IlmImf/ImfHeader.cpp"
11
+ ],
12
+ "commit_message": "Force tile sizes to be less than INT_MAX bytes, in line with the maximum dimensions of data windows\n\nSigned-off-by: Peter Hillman <peterh@wetafx.co.nz>",
13
+ "t_valid": 50,
14
+ "t_plausible": 20,
15
+ "triage_sample_size": 10,
16
+ "max_synthesis_retry": 0,
17
+ "max_in_session_redesigns": 1,
18
+ "max_refinement_iter": 3
19
+ }
tasks/csa159/pair_136252/patch.diff ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/OpenEXR/IlmImf/ImfHeader.cpp b/OpenEXR/IlmImf/ImfHeader.cpp
2
+ index e29ec421..f3655e3f 100644
3
+ --- a/OpenEXR/IlmImf/ImfHeader.cpp
4
+ +++ b/OpenEXR/IlmImf/ImfHeader.cpp
5
+ @@ -902,7 +902,7 @@ Header::sanityCheck (bool isTiled, bool isMultipartFile) const
6
+
7
+ const TileDescription &tileDesc = tileDescription();
8
+
9
+ - if (tileDesc.xSize <= 0 || tileDesc.ySize <= 0)
10
+ + if (tileDesc.xSize <= 0 || tileDesc.ySize <= 0 || tileDesc.xSize > INT_MAX || tileDesc.ySize > INT_MAX )
11
+ throw IEX_NAMESPACE::ArgExc ("Invalid tile size in image header.");
12
+
13
+ if (maxTileWidth > 0 &&
tasks/csa159/pair_136252/post_functions.txt ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: OpenEXR/IlmImf/ImfHeader.cpp
2
+ ```c
3
+ ///////////////////////////////////////////////////////////////////////////
4
+ //
5
+ // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
6
+ // Digital Ltd. LLC
7
+ //
8
+ // All rights reserved.
9
+ //
10
+ // Redistribution and use in source and binary forms, with or without
11
+ // modification, are permitted provided that the following conditions are
12
+ // met:
13
+ // * Redistributions of source code must retain the above copyright
14
+ // notice, this list of conditions and the following disclaimer.
15
+ // * Redistributions in binary form must reproduce the above
16
+ // copyright notice, this list of conditions and the following disclaimer
17
+ // in the documentation and/or other materials provided with the
18
+ // distribution.
19
+ // * Neither the name of Industrial Light & Magic nor the names of
20
+ // its contributors may be used to endorse or promote products derived
21
+ // from this software without specific prior written permission.
22
+ //
23
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
+ //
35
+ ///////////////////////////////////////////////////////////////////////////
36
+
37
+
38
+
39
+ //-----------------------------------------------------------------------------
40
+ //
41
+ // class Header
42
+ //
43
+ //-----------------------------------------------------------------------------
44
+
45
+ #include <ImfHeader.h>
46
+ #include <ImfStdIO.h>
47
+ #include <ImfVersion.h>
48
+ #include <ImfCompressor.h>
49
+ #include <ImfMisc.h>
50
+ #include <ImfBoxAttribute.h>
51
+ #include <ImfChannelListAttribute.h>
52
+ #include <ImfChromaticitiesAttribute.h>
53
+ #include <ImfCompressionAttribute.h>
54
+ #include <ImfDeepImageStateAttribute.h>
55
+ #include <ImfDoubleAttribute.h>
56
+ #include <ImfDwaCompressor.h>
57
+ #include <ImfEnvmapAttribute.h>
58
+ #include <ImfFloatAttribute.h>
59
+ #include <ImfFloatVectorAttribute.h>
60
+ #include <ImfIntAttribute.h>
61
+ #include <ImfKeyCodeAttribute.h>
62
+ #include <ImfLineOrderAttribute.h>
63
+ #include <ImfMatrixAttribute.h>
64
+ #include <ImfOpaqueAttribute.h>
65
+ #include <ImfPreviewImageAttribute.h>
66
+ #include <ImfRationalAttribute.h>
67
+ #include <ImfStringAttribute.h>
68
+ #include <ImfStringVectorAttribute.h>
69
+ #include <ImfTileDescriptionAttribute.h>
70
+ #include <ImfTimeCodeAttribute.h>
71
+ #include <ImfVecAttribute.h>
72
+ #include <ImfPartType.h>
73
+ #include "IlmThreadMutex.h"
74
+ #include "Iex.h"
75
+ #include <sstream>
76
+ #include <stdlib.h>
77
+ #include <time.h>
78
+ #include <cmath>
79
+ #include "ImfTiledMisc.h"
80
+ #include "ImfNamespace.h"
81
+
82
+ OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER
83
+
84
+ using namespace std;
85
+ using IMATH_NAMESPACE::Box2i;
86
+ using IMATH_NAMESPACE::V2i;
87
+ using IMATH_NAMESPACE::V2f;
88
+ using ILMTHREAD_NAMESPACE::Mutex;
89
+ using ILMTHREAD_NAMESPACE::Lock;
90
+
91
+
92
+ namespace {
93
+
94
+ int maxImageWidth = 0;
95
+ int maxImageHeight = 0;
96
+ int maxTileWidth = 0;
97
+ int maxTileHeight = 0;
98
+
99
+
100
+ void
101
+ initialize (Header &header,
102
+ const Box2i &displayWindow,
103
+ const Box2i &dataWindow,
104
+ float pixelAspectRatio,
105
+ const V2f &screenWindowCenter,
106
+ float screenWindowWidth,
107
+ LineOrder lineOrder,
108
+ Compression compression)
109
+ {
110
+ header.insert ("displayWindow", Box2iAttribute (displayWindow));
111
+ header.insert ("dataWindow", Box2iAttribute (dataWindow));
112
+ if ( !std::isnormal (pixelAspectRatio) || pixelAspectRatio < 0.f)
113
+ THROW (IEX_NAMESPACE::ArgExc, "Invalid pixel aspect ratio");
114
+ header.insert ("pixelAspectRatio", FloatAttribute (pixelAspectRatio));
115
+ header.insert ("screenWindowCenter", V2fAttribute (screenWindowCenter));
116
+ header.insert ("screenWindowWidth", FloatAttribute (screenWindowWidth));
117
+ header.insert ("lineOrder", LineOrderAttribute (lineOrder));
118
+ header.insert ("compression", CompressionAttribute (compression));
119
+ header.insert ("channels", ChannelListAttribute ());
120
+ }
121
+
122
+ template <size_t N>
123
+ void checkIsNullTerminated (const char (&str)[N], const char *what)
124
+ {
125
+ for (size_t i = 0; i < N; ++i) {
126
+ if (str[i] == '\0')
127
+ return;
128
+ }
129
+ std::stringstream s;
130
+ s << "Invalid " << what << ": it is more than " << (N - 1)
131
+ << " characters long.";
132
+ throw IEX_NAMESPACE::InputExc(s);
133
+ }
134
+
135
+ } // namespace
136
+
137
+
138
+ Header::Header (int width,
139
+ int height,
140
+ float pixelAspectRatio,
141
+ const V2f &screenWindowCenter,
142
+ float screenWindowWidth,
143
+ LineOrder lineOrder,
144
+ Compression compression)
145
+ :
146
+ _map()
147
+ {
148
+ staticInitialize();
149
+
150
+ Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1));
151
+
152
+ initialize (*this,
153
+ displayWindow,
154
+ displayWindow,
155
+ pixelAspectRatio,
156
+ screenWindowCenter,
157
+ screenWindowWidth,
158
+ lineOrder,
159
+ compression);
160
+ }
161
+
162
+
163
+ Header::Header (int width,
164
+ int height,
165
+ const Box2i &dataWindow,
166
+ float pixelAspectRatio,
167
+ const V2f &screenWindowCenter,
168
+ float screenWindowWidth,
169
+ LineOrder lineOrder,
170
+ Compression compression)
171
+ :
172
+ _map()
173
+ {
174
+ staticInitialize();
175
+
176
+ Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1));
177
+
178
+ initialize (*this,
179
+ displayWindow,
180
+ dataWindow,
181
+ pixelAspectRatio,
182
+ screenWindowCenter,
183
+ screenWindowWidth,
184
+ lineOrder,
185
+ compression);
186
+ }
187
+
188
+
189
+ Header::Header (const Box2i &displayWindow,
190
+ const Box2i &dataWindow,
191
+ float pixelAspectRatio,
192
+ const V2f &screenWindowCenter,
193
+ float screenWindowWidth,
194
+ LineOrder lineOrder,
195
+ Compression compression)
196
+ :
197
+ _map()
198
+ {
199
+ staticInitialize();
200
+
201
+ initialize (*this,
202
+ displayWindow,
203
+ dataWindow,
204
+ pixelAspectRatio,
205
+ screenWindowCenter,
206
+ screenWindowWidth,
207
+ lineOrder,
208
+ compression);
209
+ }
210
+
211
+
212
+ Header::Header (const Header &other): _map()
213
+ {
214
+ for (AttributeMap::const_iterator i = other._map.begin();
215
+ i != other._map.end();
216
+ ++i)
217
+ {
218
+ insert (*i->first, *i->second);
219
+ }
220
+ }
221
+
222
+
223
+ Header::~Header ()
224
+ {
225
+ for (AttributeMap::iterator i = _map.begin();
226
+ i != _map.end();
227
+ ++i)
228
+ {
229
+ delete i->second;
230
+ }
231
+ }
232
+
233
+
234
+ Header &
235
+ Header::operator = (const Header &other)
236
+ {
237
+ if (this != &other)
238
+ {
239
+ for (AttributeMap::iterator i = _map.begin();
240
+ i != _map.end();
241
+ ++i)
242
+ {
243
+ delete i->second;
244
+ }
245
+
246
+ _map.erase (_map.begin(), _map.end());
247
+
248
+ for (AttributeMap::const_iterator i = other._map.begin();
249
+ i != other._map.end();
250
+ ++i)
251
+ {
252
+ insert (*i->first, *i->second);
253
+ }
254
+ }
255
+
256
+ return *this;
257
+ }
258
+
259
+
260
+ void
261
+ Header::erase (const char name[])
262
+ {
263
+ if (name[0] == 0)
264
+ THROW (IEX_NAMESPACE::ArgExc, "Image attribute name cannot be an empty string.");
265
+
266
+
267
+ AttributeMap::iterator i = _map.find (name);
268
+ if (i != _map.end())
269
+ _map.erase (i);
270
+
271
+ }
272
+
273
+
274
+ void
275
+ Header::erase (const string &name)
276
+ {
277
+ erase (name.c_str());
278
+ }
279
+
280
+
281
+ void
282
+ Header::insert (const char name[], const Attribute &attribute)
283
+ {
284
+ if (name[0] == 0)
285
+ THROW (IEX_NAMESPACE::ArgExc, "Image attribute name cannot be an empty string.");
286
+
287
+ AttributeMap::iterator i = _map.find (name);
288
+
289
+ if (i == _map.end())
290
+ {
291
+ Attribute *tmp = attribute.copy();
292
+
293
+ try
294
+ {
295
+ _map[name] = tmp;
296
+ }
297
+ catch (...)
298
+ {
299
+ delete tmp;
300
+ throw;
301
+ }
302
+ }
303
+ else
304
+ {
305
+ if (strcmp (i->second->typeName(), attribute.typeName()))
306
+ THROW (IEX_NAMESPACE::TypeExc, "Cannot assign a value of "
307
+ "type \"" << attribute.typeName() << "\" "
308
+ "to image attribute \"" << name << "\" of "
309
+ "type \"" << i->second->typeName() << "\".");
310
+
311
+ Attribute *tmp = attribute.copy();
312
+ delete i->second;
313
+ i->second = tmp;
314
+ }
315
+ }
316
+
317
+
318
+ void
319
+ Header::insert (const string &name, const Attribute &attribute)
320
+ {
321
+ insert (name.c_str(), attribute);
322
+ }
323
+
324
+
325
+ Attribute &
326
+ Header::operator [] (const char name[])
327
+ {
328
+ AttributeMap::iterator i = _map.find (name);
329
+
330
+ if (i =
331
+
332
+ // ... (22606 more chars)
333
+ ```
tasks/csa159/pair_136252/pre_functions.txt ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: OpenEXR/IlmImf/ImfHeader.cpp
2
+ ```c
3
+ ///////////////////////////////////////////////////////////////////////////
4
+ //
5
+ // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
6
+ // Digital Ltd. LLC
7
+ //
8
+ // All rights reserved.
9
+ //
10
+ // Redistribution and use in source and binary forms, with or without
11
+ // modification, are permitted provided that the following conditions are
12
+ // met:
13
+ // * Redistributions of source code must retain the above copyright
14
+ // notice, this list of conditions and the following disclaimer.
15
+ // * Redistributions in binary form must reproduce the above
16
+ // copyright notice, this list of conditions and the following disclaimer
17
+ // in the documentation and/or other materials provided with the
18
+ // distribution.
19
+ // * Neither the name of Industrial Light & Magic nor the names of
20
+ // its contributors may be used to endorse or promote products derived
21
+ // from this software without specific prior written permission.
22
+ //
23
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
+ //
35
+ ///////////////////////////////////////////////////////////////////////////
36
+
37
+
38
+
39
+ //-----------------------------------------------------------------------------
40
+ //
41
+ // class Header
42
+ //
43
+ //-----------------------------------------------------------------------------
44
+
45
+ #include <ImfHeader.h>
46
+ #include <ImfStdIO.h>
47
+ #include <ImfVersion.h>
48
+ #include <ImfCompressor.h>
49
+ #include <ImfMisc.h>
50
+ #include <ImfBoxAttribute.h>
51
+ #include <ImfChannelListAttribute.h>
52
+ #include <ImfChromaticitiesAttribute.h>
53
+ #include <ImfCompressionAttribute.h>
54
+ #include <ImfDeepImageStateAttribute.h>
55
+ #include <ImfDoubleAttribute.h>
56
+ #include <ImfDwaCompressor.h>
57
+ #include <ImfEnvmapAttribute.h>
58
+ #include <ImfFloatAttribute.h>
59
+ #include <ImfFloatVectorAttribute.h>
60
+ #include <ImfIntAttribute.h>
61
+ #include <ImfKeyCodeAttribute.h>
62
+ #include <ImfLineOrderAttribute.h>
63
+ #include <ImfMatrixAttribute.h>
64
+ #include <ImfOpaqueAttribute.h>
65
+ #include <ImfPreviewImageAttribute.h>
66
+ #include <ImfRationalAttribute.h>
67
+ #include <ImfStringAttribute.h>
68
+ #include <ImfStringVectorAttribute.h>
69
+ #include <ImfTileDescriptionAttribute.h>
70
+ #include <ImfTimeCodeAttribute.h>
71
+ #include <ImfVecAttribute.h>
72
+ #include <ImfPartType.h>
73
+ #include "IlmThreadMutex.h"
74
+ #include "Iex.h"
75
+ #include <sstream>
76
+ #include <stdlib.h>
77
+ #include <time.h>
78
+ #include <cmath>
79
+ #include "ImfTiledMisc.h"
80
+ #include "ImfNamespace.h"
81
+
82
+ OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER
83
+
84
+ using namespace std;
85
+ using IMATH_NAMESPACE::Box2i;
86
+ using IMATH_NAMESPACE::V2i;
87
+ using IMATH_NAMESPACE::V2f;
88
+ using ILMTHREAD_NAMESPACE::Mutex;
89
+ using ILMTHREAD_NAMESPACE::Lock;
90
+
91
+
92
+ namespace {
93
+
94
+ int maxImageWidth = 0;
95
+ int maxImageHeight = 0;
96
+ int maxTileWidth = 0;
97
+ int maxTileHeight = 0;
98
+
99
+
100
+ void
101
+ initialize (Header &header,
102
+ const Box2i &displayWindow,
103
+ const Box2i &dataWindow,
104
+ float pixelAspectRatio,
105
+ const V2f &screenWindowCenter,
106
+ float screenWindowWidth,
107
+ LineOrder lineOrder,
108
+ Compression compression)
109
+ {
110
+ header.insert ("displayWindow", Box2iAttribute (displayWindow));
111
+ header.insert ("dataWindow", Box2iAttribute (dataWindow));
112
+ if ( !std::isnormal (pixelAspectRatio) || pixelAspectRatio < 0.f)
113
+ THROW (IEX_NAMESPACE::ArgExc, "Invalid pixel aspect ratio");
114
+ header.insert ("pixelAspectRatio", FloatAttribute (pixelAspectRatio));
115
+ header.insert ("screenWindowCenter", V2fAttribute (screenWindowCenter));
116
+ header.insert ("screenWindowWidth", FloatAttribute (screenWindowWidth));
117
+ header.insert ("lineOrder", LineOrderAttribute (lineOrder));
118
+ header.insert ("compression", CompressionAttribute (compression));
119
+ header.insert ("channels", ChannelListAttribute ());
120
+ }
121
+
122
+ template <size_t N>
123
+ void checkIsNullTerminated (const char (&str)[N], const char *what)
124
+ {
125
+ for (size_t i = 0; i < N; ++i) {
126
+ if (str[i] == '\0')
127
+ return;
128
+ }
129
+ std::stringstream s;
130
+ s << "Invalid " << what << ": it is more than " << (N - 1)
131
+ << " characters long.";
132
+ throw IEX_NAMESPACE::InputExc(s);
133
+ }
134
+
135
+ } // namespace
136
+
137
+
138
+ Header::Header (int width,
139
+ int height,
140
+ float pixelAspectRatio,
141
+ const V2f &screenWindowCenter,
142
+ float screenWindowWidth,
143
+ LineOrder lineOrder,
144
+ Compression compression)
145
+ :
146
+ _map()
147
+ {
148
+ staticInitialize();
149
+
150
+ Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1));
151
+
152
+ initialize (*this,
153
+ displayWindow,
154
+ displayWindow,
155
+ pixelAspectRatio,
156
+ screenWindowCenter,
157
+ screenWindowWidth,
158
+ lineOrder,
159
+ compression);
160
+ }
161
+
162
+
163
+ Header::Header (int width,
164
+ int height,
165
+ const Box2i &dataWindow,
166
+ float pixelAspectRatio,
167
+ const V2f &screenWindowCenter,
168
+ float screenWindowWidth,
169
+ LineOrder lineOrder,
170
+ Compression compression)
171
+ :
172
+ _map()
173
+ {
174
+ staticInitialize();
175
+
176
+ Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1));
177
+
178
+ initialize (*this,
179
+ displayWindow,
180
+ dataWindow,
181
+ pixelAspectRatio,
182
+ screenWindowCenter,
183
+ screenWindowWidth,
184
+ lineOrder,
185
+ compression);
186
+ }
187
+
188
+
189
+ Header::Header (const Box2i &displayWindow,
190
+ const Box2i &dataWindow,
191
+ float pixelAspectRatio,
192
+ const V2f &screenWindowCenter,
193
+ float screenWindowWidth,
194
+ LineOrder lineOrder,
195
+ Compression compression)
196
+ :
197
+ _map()
198
+ {
199
+ staticInitialize();
200
+
201
+ initialize (*this,
202
+ displayWindow,
203
+ dataWindow,
204
+ pixelAspectRatio,
205
+ screenWindowCenter,
206
+ screenWindowWidth,
207
+ lineOrder,
208
+ compression);
209
+ }
210
+
211
+
212
+ Header::Header (const Header &other): _map()
213
+ {
214
+ for (AttributeMap::const_iterator i = other._map.begin();
215
+ i != other._map.end();
216
+ ++i)
217
+ {
218
+ insert (*i->first, *i->second);
219
+ }
220
+ }
221
+
222
+
223
+ Header::~Header ()
224
+ {
225
+ for (AttributeMap::iterator i = _map.begin();
226
+ i != _map.end();
227
+ ++i)
228
+ {
229
+ delete i->second;
230
+ }
231
+ }
232
+
233
+
234
+ Header &
235
+ Header::operator = (const Header &other)
236
+ {
237
+ if (this != &other)
238
+ {
239
+ for (AttributeMap::iterator i = _map.begin();
240
+ i != _map.end();
241
+ ++i)
242
+ {
243
+ delete i->second;
244
+ }
245
+
246
+ _map.erase (_map.begin(), _map.end());
247
+
248
+ for (AttributeMap::const_iterator i = other._map.begin();
249
+ i != other._map.end();
250
+ ++i)
251
+ {
252
+ insert (*i->first, *i->second);
253
+ }
254
+ }
255
+
256
+ return *this;
257
+ }
258
+
259
+
260
+ void
261
+ Header::erase (const char name[])
262
+ {
263
+ if (name[0] == 0)
264
+ THROW (IEX_NAMESPACE::ArgExc, "Image attribute name cannot be an empty string.");
265
+
266
+
267
+ AttributeMap::iterator i = _map.find (name);
268
+ if (i != _map.end())
269
+ _map.erase (i);
270
+
271
+ }
272
+
273
+
274
+ void
275
+ Header::erase (const string &name)
276
+ {
277
+ erase (name.c_str());
278
+ }
279
+
280
+
281
+ void
282
+ Header::insert (const char name[], const Attribute &attribute)
283
+ {
284
+ if (name[0] == 0)
285
+ THROW (IEX_NAMESPACE::ArgExc, "Image attribute name cannot be an empty string.");
286
+
287
+ AttributeMap::iterator i = _map.find (name);
288
+
289
+ if (i == _map.end())
290
+ {
291
+ Attribute *tmp = attribute.copy();
292
+
293
+ try
294
+ {
295
+ _map[name] = tmp;
296
+ }
297
+ catch (...)
298
+ {
299
+ delete tmp;
300
+ throw;
301
+ }
302
+ }
303
+ else
304
+ {
305
+ if (strcmp (i->second->typeName(), attribute.typeName()))
306
+ THROW (IEX_NAMESPACE::TypeExc, "Cannot assign a value of "
307
+ "type \"" << attribute.typeName() << "\" "
308
+ "to image attribute \"" << name << "\" of "
309
+ "type \"" << i->second->typeName() << "\".");
310
+
311
+ Attribute *tmp = attribute.copy();
312
+ delete i->second;
313
+ i->second = tmp;
314
+ }
315
+ }
316
+
317
+
318
+ void
319
+ Header::insert (const string &name, const Attribute &attribute)
320
+ {
321
+ insert (name.c_str(), attribute);
322
+ }
323
+
324
+
325
+ Attribute &
326
+ Header::operator [] (const char name[])
327
+ {
328
+ AttributeMap::iterator i = _map.find (name);
329
+
330
+ if (i =
331
+
332
+ // ... (22549 more chars)
333
+ ```
tasks/csa159/pair_136252/task_prompt.md ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Task: Synthesize a CSA Checker from a CVE Patch
2
+
3
+ ## Your Role
4
+
5
+ You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker
6
+ that detects the bug pattern fixed by the CVE patch in this working directory.
7
+
8
+ You have full filesystem and bash access — use them.
9
+
10
+ ### Skills
11
+
12
+ Many skills are available under `.claude/skills/` — covering vulnerability analysis,
13
+ checker design, debugging, code audit, security patterns, and more. Each skill
14
+ encodes reusable expertise: take time to explore them, read their SKILL.md files,
15
+ and invoke those that look useful via the Skill tool. Let the task guide which
16
+ ones you reach for.
17
+
18
+ ## File Layout
19
+
20
+ ```
21
+ /work/
22
+ ├── compile.sh ← RUN ME: compile checker.cpp → checker.so
23
+ ├── checker_template.cpp ← skeleton, start here
24
+ ├── patch.diff ← the CVE fix
25
+ ├── pre_functions.txt ← buggy source (before_commit)
26
+ ├── post_functions.txt ← patched source (after_commit)
27
+ ├── config.json ← paths, commit_message, commit hashes, flags
28
+ ├── scan/
29
+ │ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy
30
+ │ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched
31
+ │ └── flags_*.txt ← pre-extracted compile flags (-I, -D)
32
+ ├── references/
33
+ │ ├── repo_knowledge.md ← project-specific API/convention reference
34
+ │ ├── patterns_summary.md ← (optional) historical bug pattern summary
35
+ │ ├── cwe_cards/ ← CWE knowledge library (all categories)
36
+ │ │ ├── index.json ← lookup index — use to find relevant cards
37
+ │ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns
38
+ │ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped)
39
+ │ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers)
40
+ │ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.)
41
+ │ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.)
42
+ │ └── examples/
43
+ │ └── llvm-official/ ← 5 official checker sources (with comments)
44
+ │ ├── 01_div_zero.cpp
45
+ │ ├── 02_simple_stream.cpp
46
+ │ ├── 03_undef_result.cpp
47
+ │ ├── 04_nullability.cpp
48
+ │ └── 05_malloc.cpp
49
+ │
50
+ ├── checker.cpp ← YOUR OUTPUT: synthesized checker
51
+ ├── checker.so ← YOUR OUTPUT: compiled checker
52
+ ├── state.json ← YOUR OUTPUT: structured task state
53
+ ├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3)
54
+ └── summary.json ← YOUR OUTPUT: final report
55
+ ```
56
+
57
+ ## Resources
58
+
59
+ **Read these before writing any code:**
60
+
61
+ 1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from
62
+ LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types,
63
+ MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.**
64
+
65
+ 2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested
66
+ patterns from official LLVM checkers: resource tracking, null checking, undefined
67
+ value detection, division-by-zero, and malloc/free. Each pattern includes skeleton
68
+ code, state traits, and key API usage.
69
+
70
+ 3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations
71
+ with explanatory comments:
72
+ - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback)
73
+ - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose)
74
+ - `03_undef_result.cpp` — PostStmt pattern (160 lines)
75
+ - `04_nullability.cpp` — multi-callback checker (1247 lines)
76
+ - `05_malloc.cpp` — comprehensive malloc/free (1511 lines)
77
+
78
+ 4. **`checker_template.cpp`** — Skeleton with placeholders. Start here.
79
+
80
+ 5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this
81
+ repository's memory allocation API, key data types, source layout, and typical
82
+ CVE patterns. **Read this before writing the checker** — knowing the project's
83
+ alloc/free conventions and common bug patterns saves many grep rounds.
84
+
85
+ 5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis
86
+ patterns for this project. If present, it contains a concise summary of the
87
+ most common bug patterns, frequent CWE categories, and reusable checker
88
+ architectures observed in previous synthesis runs. Read after repo_knowledge.md.
89
+
90
+ 6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all
91
+ vulnerability categories. **The framework provides the full library —
92
+ you must identify the vulnerability type yourself.** Workflow:
93
+
94
+ 1. Analyse the patch diff and commit message to determine the vulnerability
95
+ type (buffer overflow, UAF, null deref, integer overflow, race condition,
96
+ etc.). Do NOT rely on the CWE label — treat it as a hint at most.
97
+ 2. Open ``index.json`` to discover available cards and their tiers.
98
+ 3. Read the relevant card(s) for **detection strategies**, **checker
99
+ architecture suggestions**, and **known false-positive patterns**.
100
+
101
+ Card tiers:
102
+ - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel /
103
+ userspace variants when the detection strategy differs substantially.
104
+ - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by
105
+ category (input validation, resource management, etc.).
106
+
107
+ 7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for
108
+ checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`),
109
+ expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string
110
+ size extraction, MemRegion helpers, and `ExprHasName()` for robust function
111
+ matching. All verified against LLVM 18. **Read before implementing detection
112
+ logic** — these save writing boilerplate that's easy to get wrong.
113
+
114
+ ## Environment
115
+
116
+ Key paths are in ``config.json``.
117
+
118
+ ### Pre-built scripts
119
+
120
+ | Script | What it does |
121
+ |--------|-------------|
122
+ | `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) |
123
+ | `CHECKER_NAME=<name> bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy |
124
+ | `CHECKER_NAME=<name> bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched |
125
+
126
+ ```bash
127
+ # Compile (run from workdir root)
128
+ bash compile.sh
129
+
130
+ # Scan — set CHECKER_NAME to the string passed to addChecker<>()
131
+ CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy
132
+ CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched
133
+ ```
134
+
135
+ - ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags.
136
+ - ``scan/scan_*.sh`` count only warnings tagged with your checker name.
137
+ - Scan environments (source files + compile flags) are pre-built in ``scan/``.
138
+
139
+ ### Scan Script Integrity (CRITICAL)
140
+
141
+ The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only
142
+ valid measurement** of N_buggy and N_patched. They are the ground truth that the
143
+ Python-side validator will also use. You MUST obey these rules:
144
+
145
+ **1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly
146
+ to measure warning counts. The Python validator runs the same scan scripts
147
+ — if you measured with a different command, your numbers will not reproduce
148
+ and the synthesis will be rejected.
149
+
150
+ **2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared
151
+ identifiers, etc.), the scan environment needs repair. You MUST fix it:
152
+ - Add missing ``-I`` include paths to the flags files in ``scan/``
153
+ - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot
154
+ - If the file fundamentally cannot be compiled by clang, stop and write
155
+ ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason``
156
+
157
+ **3. Only trust scan script output.** The ``Total <name> warnings: N`` line
158
+ printed by the scan script is the number that goes into ``summary.json``.
159
+ If the scan script says 0, write 0. Fabricating numbers that the scan
160
+ script did not produce will cause the Python validator to reject the
161
+ synthesis.
162
+
163
+ - If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles).
164
+ - If validation fails: revise checker logic, re-compile, re-scan.
165
+
166
+ ## MCP Tools
167
+
168
+ You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`).
169
+ Each returns **source context embedded in the result** — no need to follow up with Read.
170
+
171
+ | Tool | What it does | Key advantage |
172
+ |------|-------------|---------------|
173
+ | `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call |
174
+ | `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file |
175
+ | `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed |
176
+
177
+ ### When to use each
178
+
179
+ - **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure.
180
+ - **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines.
181
+ - **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action.
182
+
183
+ ## Semantic Design Contract — before writing checker.cpp
184
+
185
+ Create the analysis portions of `state.json` and `scope_statement.md` **before**
186
+ writing checker.cpp. They are a design contract, not a retrospective summary.
187
+ After compilation, update only implementation facts such as `build_attempts`.
188
+
189
+ In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the
190
+ semantic fact introduced by the patch that makes it safe. In `detection_plan`,
191
+ make `report_condition`, `safe_condition`, and `source_level_signal` concrete
192
+ CSA-observable facts. In `api_choice`, record the mechanism level and explain
193
+ why the selected callback can observe and prove those facts.
194
+
195
+ In `scope_statement.md`, include this mapping table and check it again after
196
+ implementation:
197
+
198
+ | Semantic condition | CSA evidence | checker.cpp implementation |
199
+ | --- | --- | --- |
200
+ | report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports |
201
+ | safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report |
202
+
203
+ Every condition in the plan must have an implementation entry. Do not claim a
204
+ condition that checker.cpp does not implement, and do not silently add a code
205
+ condition absent from the plan.
206
+
207
+ ## Mechanism Selection — diagnose before coding
208
+
209
+ Choose the weakest CSA mechanism that can prove the vulnerability property:
210
+
211
+ 1. **syntax-only AST**: only when local AST shape itself is the defect;
212
+ 2. **control flow / dominance**: when guard placement relative to a sink matters;
213
+ 3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use;
214
+ 4. **cross-procedure/dataflow**: when the required fact crosses function boundaries.
215
+
216
+ For a guard-based patch, prove both that the guard rejects the unsafe value and
217
+ that it dominates the vulnerable use. For path-sensitive or cross-procedure
218
+ defects, do not replace the required state or flow proof with local AST matching
219
+ or source-text substring matching merely because it passes the differential scan.
220
+ Record the selected level as `api_choice.mechanism_level`.
221
+
222
+ ## Semantic identity, locality, and final validation
223
+
224
+ Before accepting the checker, verify that its primary matching logic does not
225
+ depend on patch-local variable names, labels, line numbers, commit IDs, or unique
226
+ literals. Project APIs, types, and stable semantic call relationships are valid
227
+ scope anchors when they define the vulnerability class. Attach the report to the
228
+ actual vulnerable operation, and implement every suppression as a real safe
229
+ condition rather than the mere presence of a nearby guard-shaped statement.
230
+
231
+ The required final sequence is: **compile → before scan → after scan → inspect
232
+ the final checker name, artifacts, and report locations → write summary.json**.
233
+ Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only
234
+ additional redesign cycles after a failed validation; if it is zero, preserve the
235
+ real validation evidence and report failure honestly rather than fabricating counts.
236
+
237
+ ## Validation Criteria
238
+
239
+ ```
240
+ VALID : N_buggy > N_patched AND N_patched < 50
241
+ INVALID : otherwise → revise and re-validate (max 1 attempts)
242
+ ```
243
+
244
+ ## Refinement
245
+
246
+ Do NOT self-refine the checker repeatedly. Your goal is to produce the first
247
+ checker that passes the Validation Criteria above — fix compile errors and
248
+ validation failures only. False positives are triaged and repaired by the
249
+ framework's refinement stage: you will receive a concrete FP list via
250
+ session resume (if needed) and fix only those. Reserve budget for that stage.
251
+
252
+ ## Output
253
+
254
+ Produce all of the following **only when completely done**:
255
+
256
+ | File | Content |
257
+ |------|---------|
258
+ | ``checker.cpp`` | Synthesized checker source code |
259
+ | ``checker.so`` | Compiled checker plugin |
260
+ | ``state.json`` | Structured task state (see schema below) |
261
+ | ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) |
262
+ | ``summary.json`` | Final report (see schema below) |
263
+
264
+ Writing ``summary.json`` signals completion. Do NOT write it early.
265
+
266
+ ### ``state.json``
267
+
268
+ Create this before writing checker.cpp to capture the design contract. After the
269
+ checker compiles, update only implementation facts and retain the original
270
+ semantic plan.
271
+
272
+ ```json
273
+ {
274
+ "patch_analysis": {
275
+ "summary": "One sentence describing the vulnerability this patch fixes",
276
+ "changed_files": ["file1.c", "file2.h"],
277
+ "changed_functions": ["func_a", "func_b"],
278
+ "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other",
279
+ "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other",
280
+ "affected_types": ["GF_BitStream", "custom_struct_t"],
281
+ "critical_calls": ["gf_strdup", "memcpy"]
282
+ },
283
+ "detection_plan": {
284
+ "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')",
285
+ "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')",
286
+ "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')",
287
+ "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')"
288
+ },
289
+ "api_choice": {
290
+ "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow",
291
+ "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...",
292
+ "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions",
293
+ "alternatives_considered": ["check::PostCall"]
294
+ },
295
+ "implementation": {
296
+ "scope_level": "patch_specific | project_general | cross_project",
297
+ "checker_name": "project.CheckerName",
298
+ "build_attempts": 1
299
+ }
300
+ }
301
+ ```
302
+
303
+ ### ``summary.json``
304
+
305
+ ```json
306
+ {
307
+ "status": "plausible | failed",
308
+ "bug_pattern": "One sentence describing the bug pattern",
309
+ "scope_level": "patch_specific | project_general | cross_project",
310
+ "checker_cpp": "checker.cpp",
311
+ "checker_so": "checker.so",
312
+ "n_buggy": 0,
313
+ "n_patched": 0,
314
+ "total_reports": 0,
315
+ "fp_rate_estimate": 0.0,
316
+ "failure_reason": null
317
+ }
318
+ ```
319
+
320
+ ## Feedback-derived requirements for this fresh synthesis
321
+
322
+ A prior independent rollout exposed the risks below. Start again from the patch
323
+ in this new session. Do not reconstruct, edit, or assume the prior checker.
324
+
325
+ Required mechanism level: `syntax_only`
326
+
327
+ ### Current failure diagnosis
328
+
329
+ - The rollout used CFG dominance even though the patch-local security requirement can be established from the validation condition, its TileDescription field identities, comparison polarity, and rejecting branch.
330
+ - Requiring a same-function direct call to getTiledChunkOffsetTableSize narrowed detection incorrectly: Header::sanityCheck can contain the defective validation without containing the eventual hazardous computation.
331
+ - The checker therefore remained only partially semantically correct despite producing the desired one-before, zero-after differential result and a patch-adjacent diagnostic.
332
+ - The control-flow model also had unsound refinements: treating goto as a function exit and using block dominance without proving the relevant branch edge can misclassify variants.
333
+ - The latest rollout regressed semantic score from 7.0 to 4.0, below the configured threshold, while semantic_mechanism remained failed.
334
+
335
+ ### Preserve from prior rollouts
336
+
337
+ - Preserve successful checker compilation, before/after validation, and code verification.
338
+ - Preserve objective eligibility gate G6.
339
+ - Preserve an accepted or clean refinement outcome.
340
+ - Preserve semantic and process scores at or above their configured thresholds.
341
+ - Preserve the observed differential behavior: one relevant warning on the buggy revision and none on the patched revision.
342
+ - Preserve diagnostic sharpness at the changed validation site and avoid warnings in non-patched scope.
343
+ - Remain independent of patch anchors and patch-local hardcoding.
344
+
345
+ ### Required semantic proof
346
+
347
+ - Identify the validation of unsigned TileDescription xSize and ySize fields obtained for a Header in Header::sanityCheck or an equivalent project-general validation context.
348
+ - For each relevant dimension, determine whether the rejecting condition excludes values above the maximum representable signed value used by downstream tile-size arithmetic.
349
+ - Accept semantically equivalent upper-bound predicates, including reversed operands and equivalent strict or inclusive bounds, only when their comparison polarity rejects the oversized value.
350
+ - Require both xSize and ySize to have effective upper-bound rejection; report when either dimension is protected only by the existing zero or lower-bound validation.
351
+ - Associate the predicates with the same TileDescription value being validated and require the rejection branch to throw, return, or invoke a recognized noreturn operation.
352
+ - Do not require the hazardous size-computation call to occur in the validation function; the source evidence establishes that successful validation permits later signed tile-size use.
353
+
354
+ ### Implementation constraints
355
+
356
+ - Use a function-body AST callback such as check::ASTCodeBody and semantic AST identities, including canonical FieldDecl and record/type information.
357
+ - Inspect the complete validation condition, including parenthesized expressions and logical disjunctions, and normalize comparison operand order and integer constant expressions.
358
+ - Recognize unsigned xSize and ySize members of canonical TileDescription rather than arbitrary unsigned members or textually similar expressions.
359
+ - Tie member accesses to the same TileDescription-producing expression or Header receiver using AST structure; do not use path-global symbols or unrelated-instance aggregation.
360
+ - Emit the report at the deficient validation condition or missing-bound-relevant field comparison so the location remains adjacent to the original changed span.
361
+ - Keep scope project-general while allowing project semantic names needed to identify TileDescription dimensions; do not depend on file paths, line numbers, commit identifiers, diff text, or source formatting.
362
+ - No CFG, dominance, ProgramState, constraint solving, or interprocedural propagation is required unless synthesis evidence demonstrates a validation form that cannot be decided by local AST relations.
363
+
364
+ ### Validation checklist
365
+
366
+ - Compile the checker against the supplied Clang Static Analyzer API and verify successful registration and loading.
367
+ - Scan both revisions with valid OpenEXR include and generated-configuration paths; reject results contaminated by source compile errors.
368
+ - Confirm exactly one relevant buggy-revision warning and zero patched-revision warnings.
369
+ - Confirm the buggy warning is located on the TileDescription validation condition at or immediately adjacent to the changed source span.
370
+ - Verify clean results for both dimensions correctly bounded, reversed-operand equivalents, equivalent inclusive bounds, unrelated unsigned members, and unrelated TileDescription instances.
371
+ - Verify warnings when only xSize or only ySize is upper-bounded, when a bound exceeds the signed maximum, and when an upper-bound-looking predicate has non-rejecting polarity.
372
+ - Verify that a terminating rejecting branch is accepted while a branch that falls through is not treated as effective validation.
373
+ - Run code verification and refinement, preserving G6, clean refinement, anchor-free and hardcoding-free status, and configured semantic/process score thresholds.
374
+
375
+ ### Avoid and forbidden regressions
376
+
377
+ - Do not require a direct getTiledChunkOffsetTableSize call in the same function as the validation.
378
+ - Do not repeat the prior CFG-dominance design merely because it produced the expected differential counts.
379
+ - Do not infer safety from the mere textual presence of INT_MAX, a greater-than operator, or either dimension alone.
380
+ - Do not treat the maxTileWidth and maxTileHeight narrowing-cast branch as proof that TileDescription xSize and ySize are bounded.
381
+ - Do not use path-global ProgramState or SymbolRef collections that can combine facts from different Header or TileDescription instances.
382
+ - Do not treat goto as proof that the current function terminates.
383
+ - Do not key detection or reporting to ImfHeader.cpp, line 905, exact patch text, local formatting, or revision-specific anchors.
384
+ - Do not trade away semantic-score compliance, process quality, differential validation, or false-positive control to simplify implementation.
tasks/csa159/pair_136342/checker_template.cpp ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ============================================================================
2
+ // CSA Checker Template
3
+ // ============================================================================
4
+ // Fill in the sections marked with TODO to implement your checker.
5
+ // The checker is compiled with -fno-rtti to match the LLVM 18 build config.
6
+ // It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName
7
+ //
8
+ // Compilation:
9
+ // clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \
10
+ // -I${LLVM_BUILD_DIR}/include \
11
+ // checker.cpp -o checker.so \
12
+ // -Wl,--allow-shlib-undefined
13
+ //
14
+ // Usage:
15
+ // clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze <file>
16
+ // ============================================================================
17
+
18
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20
+ #include "clang/StaticAnalyzer/Core/Checker.h"
21
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23
+ #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
24
+
25
+ using namespace clang;
26
+ using namespace ento;
27
+
28
+ namespace {
29
+
30
+ // ────────────────────────────────────────────────────────────────
31
+ // TODO: Rename this class to describe your checker's purpose.
32
+ // ────────────────────────────────────────────────────────────────
33
+ class {{CHECKER_CLASS_NAME}}
34
+ : public Checker<check::PreCall, // for checking before function calls
35
+ check::PostCall> // for checking after function calls
36
+ {
37
+ // TODO: Customize the bug type name and category.
38
+ mutable std::unique_ptr<BugType> BT;
39
+
40
+ public:
41
+ {{CHECKER_CLASS_NAME}}()
42
+ : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {}
43
+
44
+ // ── PreCall callback (fires before every function call) ──────
45
+ void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
46
+ // TODO: Implement your pre-call analysis logic here.
47
+ //
48
+ // Common patterns:
49
+ //
50
+ // 1. Check if the called function matches a specific name:
51
+ // if (Call.getCalleeIdentifier()) {
52
+ // StringRef name = Call.getCalleeIdentifier()->getName();
53
+ // if (name == "target_function") { ... }
54
+ // }
55
+ //
56
+ // 2. Get the program state:
57
+ // ProgramStateRef State = C.getState();
58
+ //
59
+ // 3. Get arguments:
60
+ // SVal Arg = Call.getArgSVal(0);
61
+ //
62
+ // 4. Generate a bug report:
63
+ // ExplodedNode *ErrNode = C.generateErrorNode();
64
+ // if (ErrNode) {
65
+ // auto R = std::make_unique<PathSensitiveBugReport>(
66
+ // *BT, "Description of the bug", ErrNode);
67
+ // C.emitReport(std::move(R));
68
+ // }
69
+ }
70
+
71
+ // ── PostCall callback (fires after every function call) ─────
72
+ void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
73
+ // TODO: Implement your post-call analysis logic here.
74
+ //
75
+ // Common pattern — check the return value:
76
+ // SVal RetVal = Call.getReturnValue();
77
+ // if (RetVal.isUnknownOrUndef()) return;
78
+ //
79
+ // ProgramStateRef State = C.getState();
80
+ // // Modify state based on post-call conditions...
81
+ }
82
+ };
83
+
84
+ } // anonymous namespace
85
+
86
+ // ────────────────────────────────────────────────────────────────
87
+ // Registration — DO NOT modify the function signatures.
88
+ // ────────────────────────────────────────────────────────────────
89
+
90
+ extern "C" void clang_registerCheckers(CheckerRegistry &registry) {
91
+ registry.addChecker<{{CHECKER_CLASS_NAME}}>(
92
+ "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker"
93
+ "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference"
94
+ "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs"
95
+ }
96
+
97
+ extern "C" const char clang_analyzerAPIVersionString[] =
98
+ CLANG_ANALYZER_API_VERSION_STRING;
tasks/csa159/pair_136342/config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "project_id": "vadz_libtiff",
3
+ "before_commit": "3206e0c752a62da1ae606867113ed3bf9bf73306",
4
+ "after_commit": "3996fa0f84f4a8b7e65fe4b8f0681711022034ea",
5
+ "repo_path": "/workspace/repo/vadz/libtiff",
6
+ "llvm_build_dir": "/opt/llvm",
7
+ "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/vadz_libtiff/2701f47b544ab7eb2d40bb9e0542f17a7ba1437a/compile_commands.json",
8
+ "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/vadz_libtiff/2701f47b544ab7eb2d40bb9e0542f17a7ba1437a/compile_commands.json",
9
+ "changed_files": [
10
+ "tools/pal2rgb.c",
11
+ "tools/thumbnail.c"
12
+ ],
13
+ "commit_message": "* tools/pal2rgb.c, tools/thumbnail.c: fix crash by disabling TIFFTAG_INKNAMES\ncopying. The right fix would be to properly copy it, but not worth the burden\nfor those esoteric utilities.\nhttp://bugzilla.maptools.org/show_bug.cgi?id=2484 (CVE-2014-8127)",
14
+ "t_valid": 50,
15
+ "t_plausible": 20,
16
+ "triage_sample_size": 10,
17
+ "max_synthesis_retry": 0,
18
+ "max_in_session_redesigns": 1,
19
+ "max_refinement_iter": 3
20
+ }
tasks/csa159/pair_136342/patch.diff ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/ChangeLog b/ChangeLog
2
+ index 2dc5f4b5..0f070dd9 100644
3
+ --- a/ChangeLog
4
+ +++ b/ChangeLog
5
+ @@ -1,3 +1,10 @@
6
+ +2014-12-21 Even Rouault <even.rouault@spatialys.com>
7
+ +
8
+ + * tools/pal2rgb.c, tools/thumbnail.c: fix crash by disabling TIFFTAG_INKNAMES
9
+ + copying. The right fix would be to properly copy it, but not worth the burden
10
+ + for those esoteric utilities.
11
+ + http://bugzilla.maptools.org/show_bug.cgi?id=2484 (CVE-2014-8127)
12
+ +
13
+ 2014-12-21 Even Rouault <even.rouault@spatialys.com>
14
+
15
+ * tools/thumbnail.c: fix out-of-buffer write
16
+ diff --git a/tools/pal2rgb.c b/tools/pal2rgb.c
17
+ index bfe7899d..3fc3de3e 100644
18
+ --- a/tools/pal2rgb.c
19
+ +++ b/tools/pal2rgb.c
20
+ @@ -372,7 +372,7 @@ static struct cpTag {
21
+ { TIFFTAG_CLEANFAXDATA, 1, TIFF_SHORT },
22
+ { TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG },
23
+ { TIFFTAG_INKSET, 1, TIFF_SHORT },
24
+ - { TIFFTAG_INKNAMES, 1, TIFF_ASCII },
25
+ + /*{ TIFFTAG_INKNAMES, 1, TIFF_ASCII },*/ /* Needs much more complicated logic. See tiffcp */
26
+ { TIFFTAG_DOTRANGE, 2, TIFF_SHORT },
27
+ { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII },
28
+ { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT },
29
+ diff --git a/tools/thumbnail.c b/tools/thumbnail.c
30
+ index c50bbffc..73f9c34a 100644
31
+ --- a/tools/thumbnail.c
32
+ +++ b/tools/thumbnail.c
33
+ @@ -257,7 +257,7 @@ static struct cpTag {
34
+ { TIFFTAG_CLEANFAXDATA, 1, TIFF_SHORT },
35
+ { TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG },
36
+ { TIFFTAG_INKSET, 1, TIFF_SHORT },
37
+ - { TIFFTAG_INKNAMES, 1, TIFF_ASCII },
38
+ + /*{ TIFFTAG_INKNAMES, 1, TIFF_ASCII },*/ /* Needs much more complicated logic. See tiffcp */
39
+ { TIFFTAG_DOTRANGE, 2, TIFF_SHORT },
40
+ { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII },
41
+ { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT },
tasks/csa159/pair_136342/post_functions.txt ADDED
@@ -0,0 +1,567 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: tools/pal2rgb.c
2
+ ```c
3
+ /* $Id$ */
4
+
5
+ /*
6
+ * Copyright (c) 1988-1997 Sam Leffler
7
+ * Copyright (c) 1991-1997 Silicon Graphics, Inc.
8
+ *
9
+ * Permission to use, copy, modify, distribute, and sell this software and
10
+ * its documentation for any purpose is hereby granted without fee, provided
11
+ * that (i) the above copyright notices and this permission notice appear in
12
+ * all copies of the software and related documentation, and (ii) the names of
13
+ * Sam Leffler and Silicon Graphics may not be used in any advertising or
14
+ * publicity relating to the software without the specific, prior written
15
+ * permission of Sam Leffler and Silicon Graphics.
16
+ *
17
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
18
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
19
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
20
+ *
21
+ * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
22
+ * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
23
+ * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
24
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
25
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
26
+ * OF THIS SOFTWARE.
27
+ */
28
+
29
+ #include "tif_config.h"
30
+
31
+ #include <stdio.h>
32
+ #include <string.h>
33
+ #include <stdlib.h>
34
+ #include <ctype.h>
35
+
36
+ #ifdef HAVE_UNISTD_H
37
+ # include <unistd.h>
38
+ #endif
39
+
40
+ #ifdef NEED_LIBPORT
41
+ # include "libport.h"
42
+ #endif
43
+
44
+ #include "tiffio.h"
45
+
46
+ #define streq(a,b) (strcmp(a,b) == 0)
47
+ #define strneq(a,b,n) (strncmp(a,b,n) == 0)
48
+
49
+ static void usage(void);
50
+ static void cpTags(TIFF* in, TIFF* out);
51
+
52
+ static int
53
+ checkcmap(int n, uint16* r, uint16* g, uint16* b)
54
+ {
55
+ while (n-- > 0)
56
+ if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
57
+ return (16);
58
+ fprintf(stderr, "Warning, assuming 8-bit colormap.\n");
59
+ return (8);
60
+ }
61
+
62
+ #define CopyField(tag, v) \
63
+ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
64
+ #define CopyField3(tag, v1, v2, v3) \
65
+ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
66
+
67
+ static uint16 compression = (uint16) -1;
68
+ static uint16 predictor = 0;
69
+ static int quality = 75; /* JPEG quality */
70
+ static int jpegcolormode = JPEGCOLORMODE_RGB;
71
+ static int processCompressOptions(char*);
72
+
73
+ int
74
+ main(int argc, char* argv[])
75
+ {
76
+ uint16 bitspersample, shortv;
77
+ uint32 imagewidth, imagelength;
78
+ uint16 config = PLANARCONFIG_CONTIG;
79
+ uint32 rowsperstrip = (uint32) -1;
80
+ uint16 photometric = PHOTOMETRIC_RGB;
81
+ uint16 *rmap, *gmap, *bmap;
82
+ uint32 row;
83
+ int cmap = -1;
84
+ TIFF *in, *out;
85
+ int c;
86
+ extern int optind;
87
+ extern char* optarg;
88
+
89
+ while ((c = getopt(argc, argv, "C:c:p:r:")) != -1)
90
+ switch (c) {
91
+ case 'C': /* force colormap interpretation */
92
+ cmap = atoi(optarg);
93
+ break;
94
+ case 'c': /* compression scheme */
95
+ if (!processCompressOptions(optarg))
96
+ usage();
97
+ break;
98
+ case 'p': /* planar configuration */
99
+ if (streq(optarg, "separate"))
100
+ config = PLANARCONFIG_SEPARATE;
101
+ else if (streq(optarg, "contig"))
102
+ config = PLANARCONFIG_CONTIG;
103
+ else
104
+ usage();
105
+ break;
106
+ case 'r': /* rows/strip */
107
+ rowsperstrip = atoi(optarg);
108
+ break;
109
+ case '?':
110
+ usage();
111
+ /*NOTREACHED*/
112
+ }
113
+ if (argc - optind != 2)
114
+ usage();
115
+ in = TIFFOpen(argv[optind], "r");
116
+ if (in == NULL)
117
+ return (-1);
118
+ if (!TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &shortv) ||
119
+ shortv != PHOTOMETRIC_PALETTE) {
120
+ fprintf(stderr, "%s: Expecting a palette image.\n",
121
+ argv[optind]);
122
+ return (-1);
123
+ }
124
+ if (!TIFFGetField(in, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
125
+ fprintf(stderr,
126
+ "%s: No colormap (not a valid palette image).\n",
127
+ argv[optind]);
128
+ return (-1);
129
+ }
130
+ bitspersample = 0;
131
+ TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample);
132
+ if (bitspersample != 8) {
133
+ fprintf(stderr, "%s: Sorry, can only handle 8-bit images.\n",
134
+ argv[optind]);
135
+ return (-1);
136
+ }
137
+ out = TIFFOpen(argv[optind+1], "w");
138
+ if (out == NULL)
139
+ return (-2);
140
+ cpTags(in, out);
141
+ TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &imagewidth);
142
+ TIFFGetField(in, TIFFTAG_IMAGELENGTH, &imagelength);
143
+ if (compression != (uint16)-1)
144
+ TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
145
+ else
146
+ TIFFGetField(in, TIFFTAG_COMPRESSION, &compression);
147
+ switch (compression) {
148
+ case COMPRESSION_JPEG:
149
+ if (jpegcolormode == JPEGCOLORMODE_RGB)
150
+ photometric = PHOTOMETRIC_YCBCR;
151
+ else
152
+ photometric = PHOTOMETRIC_RGB;
153
+ TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
154
+ TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
155
+ break;
156
+ case COMPRESSION_LZW:
157
+ case COMPRESSION_DEFLATE:
158
+ if (predictor != 0)
159
+ TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
160
+ break;
161
+ }
162
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
163
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 3);
164
+ TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
165
+ TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
166
+ rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip));
167
+ (void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv);
168
+ if (cmap == -1)
169
+ cmap = checkcmap(1<<bitspersample, rmap, gmap, bmap);
170
+ if (cmap == 16) {
171
+ /*
172
+ * Convert 16-bit colormap to 8-bit.
173
+ */
174
+ int i;
175
+
176
+ for (i = (1<<bitspersample)-1; i >= 0; i--) {
177
+ #define CVT(x) (((x) * 255) / ((1L<<16)-1))
178
+ rmap[i] = CVT(rmap[i]);
179
+ gmap[i] = CVT(gmap[i]);
180
+ bmap[i] = CVT(bmap[i]);
181
+ }
182
+ }
183
+ { unsigned char *ibuf, *obuf;
184
+ register unsigned char* pp;
185
+ register uint32 x;
186
+ ibuf = (unsigned char*)_TIFFmalloc(TIFFScanlineSize(in));
187
+ obuf = (unsigned char*)_TIFFmalloc(TIFFScanlineSize(out));
188
+ switch (config) {
189
+ case PLANARCONFIG_CONTIG:
190
+ for (row = 0; row < imagelength; row++) {
191
+ if (!TIFFReadScanline(in, ibuf, row, 0))
192
+ goto done;
193
+ pp = obuf;
194
+ for (x = 0; x < imagewidth; x++) {
195
+ *pp++ = (unsigned char) rmap[ibuf[x]];
196
+ *pp++ = (unsigned char) gmap[ibuf[x]];
197
+ *pp++ = (unsigned char) bmap[ibuf[x]];
198
+ }
199
+ if (!TIFFWriteScanline(out, obuf, row, 0))
200
+ goto done;
201
+ }
202
+ break;
203
+ case PLANARCONFIG_SEPARATE:
204
+ for (row = 0; row < imagelength; row++) {
205
+ if (!TIFFReadScanline(in, ibuf, row, 0))
206
+ goto done;
207
+ for (pp = obuf, x = 0; x < imagewidth; x++)
208
+ *pp++ = (unsigned char) rmap[ibuf[x]];
209
+ if (!TIFFWriteScanline(out, obuf, row, 0))
210
+ goto done;
211
+ for (pp = obuf, x = 0; x < imagewidth; x++)
212
+ *pp++ = (unsigned char) gmap[ibuf[x]];
213
+ if (!TIFFWriteScanline(out, obuf, row, 0))
214
+ goto done;
215
+ for (pp = obuf, x = 0; x < imagewidth; x++)
216
+ *pp++ = (unsigned char) bmap[ibuf[x]];
217
+ if (!TIFFWriteScanline(out, obuf, row, 0))
218
+ goto done;
219
+ }
220
+ break;
221
+ }
222
+ _TIFFfree(ibuf);
223
+ _TIFFfree(obuf);
224
+ }
225
+ done:
226
+ (void) TIFFClose(in);
227
+ (void) TIFFClose(out);
228
+ return (0);
229
+ }
230
+
231
+ static int
232
+ processCompressOptions(char* opt)
233
+ {
234
+ if (streq(opt, "none"))
235
+ compression = COMPRESSION_NONE;
236
+ else if (streq(opt, "packbits"))
237
+ compression = COMPRESSION_PACKBITS;
238
+ else if (strneq(opt, "jpeg", 4)) {
239
+ char* cp = strchr(opt, ':');
240
+
241
+ compression = COMPRESSION_JPEG;
242
+ while( cp )
243
+ {
244
+ if (isdigit((int)cp[1]))
245
+ quality = atoi(cp+1);
246
+ else if (cp[1] == 'r' )
247
+ jpegcolormode = JPEGCOLORMODE_RAW;
248
+ else
249
+ usage();
250
+
251
+ cp = strchr(cp+1,':');
252
+ }
253
+ } else if (strneq(opt, "lzw", 3)) {
254
+ char* cp = strchr(opt, ':');
255
+ if (cp)
256
+ predictor = atoi(cp+1);
257
+ compression = COMPRESSION_LZW;
258
+ } else if (strneq(opt, "zip", 3)) {
259
+ char* cp = strchr(opt, ':');
260
+ if (cp)
261
+ predictor = atoi(cp+1);
262
+ compression = COMPRESSION_DEFLATE;
263
+ } else
264
+ return (0);
265
+ return (1);
266
+ }
267
+
268
+ #define CopyField(tag, v) \
269
+ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
270
+ #define CopyField2(tag, v1, v2) \
271
+ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
272
+ #define CopyField3(tag, v1, v2, v3) \
273
+ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
274
+ #define CopyField4(tag, v1, v2, v3, v4) \
275
+ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)
276
+
277
+ static void
278
+ cpTag(TIFF* in, TIFF* out, uint16
279
+
280
+ // ... (4689 more chars)
281
+ ```
282
+
283
+ ### File: tools/thumbnail.c
284
+ ```c
285
+ /* $Id$ */
286
+
287
+ /*
288
+ * Copyright (c) 1994-1997 Sam Leffler
289
+ * Copyright (c) 1994-1997 Silicon Graphics, Inc.
290
+ *
291
+ * Permission to use, copy, modify, distribute, and sell this software and
292
+ * its documentation for any purpose is hereby granted without fee, provided
293
+ * that (i) the above copyright notices and this permission notice appear in
294
+ * all copies of the software and related documentation, and (ii) the names of
295
+ * Sam Leffler and Silicon Graphics may not be used in any advertising or
296
+ * publicity relating to the software without the specific, prior written
297
+ * permission of Sam Leffler and Silicon Graphics.
298
+ *
299
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
300
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
301
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
302
+ *
303
+ * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
304
+ * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
305
+ * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
306
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
307
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
308
+ * OF THIS SOFTWARE.
309
+ */
310
+
311
+ #include "tif_config.h"
312
+
313
+ #include <stdio.h>
314
+ #include <stdlib.h>
315
+ #include <string.h>
316
+ #include <math.h>
317
+
318
+ #ifdef HAVE_UNISTD_H
319
+ # include <unistd.h>
320
+ #endif
321
+
322
+ #ifdef NEED_LIBPORT
323
+ # include "libport.h"
324
+ #endif
325
+
326
+ #include "tiffio.h"
327
+
328
+ #ifndef HAVE_GETOPT
329
+ extern int getopt(int, char**, char*);
330
+ #endif
331
+
332
+ #define streq(a,b) (strcmp(a,b) == 0)
333
+
334
+ #ifndef TIFFhowmany8
335
+ # define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3)
336
+ #endif
337
+
338
+ typedef enum {
339
+ EXP50,
340
+ EXP60,
341
+ EXP70,
342
+ EXP80,
343
+ EXP90,
344
+ EXP,
345
+ LINEAR
346
+ } Contrast;
347
+
348
+ static uint32 tnw = 216; /* thumbnail width */
349
+ static uint32 tnh = 274; /* thumbnail height */
350
+ static Contrast contrast = LINEAR; /* current contrast */
351
+ static uint8* thumbnail;
352
+
353
+ static int cpIFD(TIFF*, TIFF*);
354
+ static int generateThumbnail(TIFF*, TIFF*);
355
+ static void initScale();
356
+ static void usage(void);
357
+
358
+ extern char* optarg;
359
+ extern int optind;
360
+
361
+ int
362
+ main(int argc, char* argv[])
363
+ {
364
+ TIFF* in;
365
+ TIFF* out;
366
+ int c;
367
+
368
+ while ((c = getopt(argc, argv, "w:h:c:")) != -1) {
369
+ switch (c) {
370
+ case 'w': tnw = strtoul(optarg, NULL, 0); break;
371
+ case 'h': tnh = strtoul(optarg, NULL, 0); break;
372
+ case 'c': contrast = streq(optarg, "exp50") ? EXP50 :
373
+ streq(optarg, "exp60") ? EXP60 :
374
+ streq(optarg, "exp70") ? EXP70 :
375
+ streq(optarg, "exp80") ? EXP80 :
376
+ streq(optarg, "exp90") ? EXP90 :
377
+ streq(optarg, "exp") ? EXP :
378
+ streq(optarg, "linear")? LINEAR :
379
+ EXP;
380
+ break;
381
+ default: usage();
382
+ }
383
+ }
384
+ if (argc-optind != 2)
385
+ usage();
386
+
387
+ out = TIFFOpen(argv[optind+1], "w");
388
+ if (out == NULL)
389
+ return 2;
390
+ in = TIFFOpen(argv[optind], "r");
391
+ if( in == NULL )
392
+ return 2;
393
+
394
+ thumbnail = (uint8*) _TIFFmalloc(tnw * tnh);
395
+ if (!thumbnail) {
396
+ TIFFError(TIFFFileName(in),
397
+ "Can't allocate space for thumbnail buffer.");
398
+ return 1;
399
+ }
400
+
401
+ if (in != NULL) {
402
+ initScale();
403
+ do {
404
+ if (!generateThumbnail(in, out))
405
+ goto bad;
406
+ if (!cpIFD(in, out) || !TIFFWriteDirectory(out))
407
+ goto bad;
408
+ } while (TIFFReadDirectory(in));
409
+ (void) TIFFClose(in);
410
+ }
411
+ (void) TIFFClose(out);
412
+ return 0;
413
+ bad:
414
+ (void) TIFFClose(out);
415
+ return 1;
416
+ }
417
+
418
+ #define CopyField(tag, v) \
419
+ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
420
+ #define CopyField2(tag, v1, v2) \
421
+ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
422
+ #define CopyField3(tag, v1, v2, v3) \
423
+ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
424
+ #define CopyField4(tag, v1, v2, v3, v4) \
425
+ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)
426
+
427
+ static void
428
+ cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type)
429
+ {
430
+ switch (type) {
431
+ case TIFF_SHORT:
432
+ if (count == 1) {
433
+ uint16 shortv;
434
+ CopyField(tag, shortv);
435
+ } else if (count == 2) {
436
+ uint16 shortv1, shortv2;
437
+ CopyField2(tag, shortv1, shortv2);
438
+ } else if (count == 4) {
439
+ uint16 *tr, *tg, *tb, *ta;
440
+ CopyField4(tag, tr, tg, tb, ta);
441
+ } else if (count == (uint16) -1) {
442
+ uint16 shortv1;
443
+ uint16* shortav;
444
+ CopyField2(tag, shortv1, shortav);
445
+ }
446
+ break;
447
+ case TIFF_LONG:
448
+ { uint32 longv;
449
+ CopyField(tag, longv);
450
+ }
451
+ break;
452
+ case TIFF_LONG8:
453
+ { uint64 longv8;
454
+ CopyField(tag, longv8);
455
+ }
456
+ break;
457
+ case TIFF_SLONG8:
458
+ { int64 longv8;
459
+ CopyField(tag, longv8);
460
+ }
461
+ break;
462
+ case TIFF_RATIONAL:
463
+ if (count == 1) {
464
+ float floatv;
465
+ CopyField(tag, floatv);
466
+ } else if (count == (uint16) -1) {
467
+ float* floatav;
468
+ CopyField(tag, floatav);
469
+ }
470
+ break;
471
+ case TIFF_ASCII:
472
+ { char* stringv;
473
+ CopyField(tag, stringv);
474
+ }
475
+ break;
476
+ case TIFF_DOUBLE:
477
+ if (count == 1) {
478
+ double doublev;
479
+ CopyField(tag, doublev);
480
+ } else if (count == (uint16) -1) {
481
+ double* doubleav;
482
+ CopyField(tag, doubleav);
483
+ }
484
+ break;
485
+ case TIFF_IFD8:
486
+ { toff_t ifd8;
487
+ CopyField(tag, ifd8);
488
+ }
489
+ break; default:
490
+ TIFFError(TIFFFileName(in),
491
+ "Data type %d is not supported, tag %d skipped.",
492
+ tag, type);
493
+ }
494
+ }
495
+
496
+ #undef CopyField4
497
+ #undef CopyField3
498
+ #undef CopyField2
499
+ #undef CopyField
500
+
501
+ static struct cpTag {
502
+ uint16 tag;
503
+ uint16 count;
504
+ TIFFDataType type;
505
+ } tags[] = {
506
+ { TIFFTAG_IMAGEWIDTH, 1, TIFF_LONG },
507
+ { TIFFTAG_IMAGELENGTH, 1, TIFF_LONG },
508
+ { TIFFTAG_BITSPERSAMPLE, 1, TIFF_SHORT },
509
+ { TIFFTAG_COMPRESSION, 1, TIFF_SHORT },
510
+ { TIFFTAG_FILLORDER, 1, TIFF_SHORT },
511
+ { TIFFTAG_SAMPLESPERPIXEL, 1, TIFF_SHORT },
512
+ { TIFFTAG_ROWSPERSTRIP, 1, TIFF_LONG },
513
+ { TIFFTAG_PLANARCONFIG, 1, TIFF_SHORT },
514
+ { TIFFTAG_GROUP3OPTIONS, 1, TIFF_LONG },
515
+ { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG },
516
+ { TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT },
517
+ { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT },
518
+ { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII },
519
+ { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII },
520
+ { TIFFTAG_MAKE, 1, TIFF_ASCII },
521
+ { TIFFTAG_MODEL, 1, TIFF_ASCII },
522
+ { TIFFTAG_ORIENTATION, 1, TIFF_SHORT },
523
+ { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT },
524
+ { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT },
525
+ { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL },
526
+ { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL },
527
+ { TIFFTAG_PAGENAME, 1, TIFF_ASCII },
528
+ { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL },
529
+ { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL },
530
+ { TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG },
531
+ { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT },
532
+ { TIFFTAG_PAGENUMBER, 2, TIFF_SHORT },
533
+ { TIFFTAG_SOFTWARE, 1, TIFF_ASCII },
534
+ { TIFFTAG_DATETIME, 1, TIFF_ASCII },
535
+ { TIFFTAG_ARTIST, 1, TIFF_ASCII },
536
+ { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII },
537
+ { TIFFTAG_WHITEPOINT, 2, TIFF_RATIONAL },
538
+ { TIFFTAG_PRIMARYCHROMATICITIES, (uint16) -1,TIFF_RATIONAL },
539
+ { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT },
540
+ { TIFFTAG_BADFAXLINES, 1, TIFF_LONG },
541
+ { TIFFTAG_CLEANFAXDATA, 1, TIFF_SHORT },
542
+ { TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG },
543
+ { TIFFTAG_INKSET, 1, TIFF_SHORT },
544
+ /*{ TIFFTAG_INKNAMES, 1, TIFF_ASCII },*/ /* Needs much more complicated logic. See tiffcp */
545
+ { TIFFTAG_DOTRANGE, 2, TIFF_SHORT },
546
+ { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII },
547
+ { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT },
548
+ { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL },
549
+ { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT },
550
+ { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT },
551
+ { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL },
552
+ { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT },
553
+ };
554
+ #define NTAGS (sizeof (tags) / sizeof (tags[0]))
555
+
556
+ static void
557
+ cpTags(TIFF* in, TIFF* out)
558
+ {
559
+ struct cpTag *p;
560
+ for (p = tags; p < &tags[NTAGS]; p++)
561
+ {
562
+ /* Horrible: but TIFFGetField() expects 2 arguments to be passed */
563
+ /* if we request a tag that is defined in a codec, but that codec */
564
+ /* is
565
+
566
+ // ... (10457 more chars)
567
+ ```
tasks/csa159/pair_136342/pre_functions.txt ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: tools/pal2rgb.c
2
+ ```c
3
+ /* $Id$ */
4
+
5
+ /*
6
+ * Copyright (c) 1988-1997 Sam Leffler
7
+ * Copyright (c) 1991-1997 Silicon Graphics, Inc.
8
+ *
9
+ * Permission to use, copy, modify, distribute, and sell this software and
10
+ * its documentation for any purpose is hereby granted without fee, provided
11
+ * that (i) the above copyright notices and this permission notice appear in
12
+ * all copies of the software and related documentation, and (ii) the names of
13
+ * Sam Leffler and Silicon Graphics may not be used in any advertising or
14
+ * publicity relating to the software without the specific, prior written
15
+ * permission of Sam Leffler and Silicon Graphics.
16
+ *
17
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
18
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
19
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
20
+ *
21
+ * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
22
+ * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
23
+ * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
24
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
25
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
26
+ * OF THIS SOFTWARE.
27
+ */
28
+
29
+ #include "tif_config.h"
30
+
31
+ #include <stdio.h>
32
+ #include <string.h>
33
+ #include <stdlib.h>
34
+ #include <ctype.h>
35
+
36
+ #ifdef HAVE_UNISTD_H
37
+ # include <unistd.h>
38
+ #endif
39
+
40
+ #ifdef NEED_LIBPORT
41
+ # include "libport.h"
42
+ #endif
43
+
44
+ #include "tiffio.h"
45
+
46
+ #define streq(a,b) (strcmp(a,b) == 0)
47
+ #define strneq(a,b,n) (strncmp(a,b,n) == 0)
48
+
49
+ static void usage(void);
50
+ static void cpTags(TIFF* in, TIFF* out);
51
+
52
+ static int
53
+ checkcmap(int n, uint16* r, uint16* g, uint16* b)
54
+ {
55
+ while (n-- > 0)
56
+ if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
57
+ return (16);
58
+ fprintf(stderr, "Warning, assuming 8-bit colormap.\n");
59
+ return (8);
60
+ }
61
+
62
+ #define CopyField(tag, v) \
63
+ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
64
+ #define CopyField3(tag, v1, v2, v3) \
65
+ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
66
+
67
+ static uint16 compression = (uint16) -1;
68
+ static uint16 predictor = 0;
69
+ static int quality = 75; /* JPEG quality */
70
+ static int jpegcolormode = JPEGCOLORMODE_RGB;
71
+ static int processCompressOptions(char*);
72
+
73
+ int
74
+ main(int argc, char* argv[])
75
+ {
76
+ uint16 bitspersample, shortv;
77
+ uint32 imagewidth, imagelength;
78
+ uint16 config = PLANARCONFIG_CONTIG;
79
+ uint32 rowsperstrip = (uint32) -1;
80
+ uint16 photometric = PHOTOMETRIC_RGB;
81
+ uint16 *rmap, *gmap, *bmap;
82
+ uint32 row;
83
+ int cmap = -1;
84
+ TIFF *in, *out;
85
+ int c;
86
+ extern int optind;
87
+ extern char* optarg;
88
+
89
+ while ((c = getopt(argc, argv, "C:c:p:r:")) != -1)
90
+ switch (c) {
91
+ case 'C': /* force colormap interpretation */
92
+ cmap = atoi(optarg);
93
+ break;
94
+ case 'c': /* compression scheme */
95
+ if (!processCompressOptions(optarg))
96
+ usage();
97
+ break;
98
+ case 'p': /* planar configuration */
99
+ if (streq(optarg, "separate"))
100
+ config = PLANARCONFIG_SEPARATE;
101
+ else if (streq(optarg, "contig"))
102
+ config = PLANARCONFIG_CONTIG;
103
+ else
104
+ usage();
105
+ break;
106
+ case 'r': /* rows/strip */
107
+ rowsperstrip = atoi(optarg);
108
+ break;
109
+ case '?':
110
+ usage();
111
+ /*NOTREACHED*/
112
+ }
113
+ if (argc - optind != 2)
114
+ usage();
115
+ in = TIFFOpen(argv[optind], "r");
116
+ if (in == NULL)
117
+ return (-1);
118
+ if (!TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &shortv) ||
119
+ shortv != PHOTOMETRIC_PALETTE) {
120
+ fprintf(stderr, "%s: Expecting a palette image.\n",
121
+ argv[optind]);
122
+ return (-1);
123
+ }
124
+ if (!TIFFGetField(in, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
125
+ fprintf(stderr,
126
+ "%s: No colormap (not a valid palette image).\n",
127
+ argv[optind]);
128
+ return (-1);
129
+ }
130
+ bitspersample = 0;
131
+ TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample);
132
+ if (bitspersample != 8) {
133
+ fprintf(stderr, "%s: Sorry, can only handle 8-bit images.\n",
134
+ argv[optind]);
135
+ return (-1);
136
+ }
137
+ out = TIFFOpen(argv[optind+1], "w");
138
+ if (out == NULL)
139
+ return (-2);
140
+ cpTags(in, out);
141
+ TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &imagewidth);
142
+ TIFFGetField(in, TIFFTAG_IMAGELENGTH, &imagelength);
143
+ if (compression != (uint16)-1)
144
+ TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
145
+ else
146
+ TIFFGetField(in, TIFFTAG_COMPRESSION, &compression);
147
+ switch (compression) {
148
+ case COMPRESSION_JPEG:
149
+ if (jpegcolormode == JPEGCOLORMODE_RGB)
150
+ photometric = PHOTOMETRIC_YCBCR;
151
+ else
152
+ photometric = PHOTOMETRIC_RGB;
153
+ TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
154
+ TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
155
+ break;
156
+ case COMPRESSION_LZW:
157
+ case COMPRESSION_DEFLATE:
158
+ if (predictor != 0)
159
+ TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
160
+ break;
161
+ }
162
+ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric);
163
+ TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 3);
164
+ TIFFSetField(out, TIFFTAG_PLANARCONFIG, config);
165
+ TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
166
+ rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip));
167
+ (void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv);
168
+ if (cmap == -1)
169
+ cmap = checkcmap(1<<bitspersample, rmap, gmap, bmap);
170
+ if (cmap == 16) {
171
+ /*
172
+ * Convert 16-bit colormap to 8-bit.
173
+ */
174
+ int i;
175
+
176
+ for (i = (1<<bitspersample)-1; i >= 0; i--) {
177
+ #define CVT(x) (((x) * 255) / ((1L<<16)-1))
178
+ rmap[i] = CVT(rmap[i]);
179
+ gmap[i] = CVT(gmap[i]);
180
+ bmap[i] = CVT(bmap[i]);
181
+ }
182
+ }
183
+ { unsigned char *ibuf, *obuf;
184
+ register unsigned char* pp;
185
+ register uint32 x;
186
+ ibuf = (unsigned char*)_TIFFmalloc(TIFFScanlineSize(in));
187
+ obuf = (unsigned char*)_TIFFmalloc(TIFFScanlineSize(out));
188
+ switch (config) {
189
+ case PLANARCONFIG_CONTIG:
190
+ for (row = 0; row < imagelength; row++) {
191
+ if (!TIFFReadScanline(in, ibuf, row, 0))
192
+ goto done;
193
+ pp = obuf;
194
+ for (x = 0; x < imagewidth; x++) {
195
+ *pp++ = (unsigned char) rmap[ibuf[x]];
196
+ *pp++ = (unsigned char) gmap[ibuf[x]];
197
+ *pp++ = (unsigned char) bmap[ibuf[x]];
198
+ }
199
+ if (!TIFFWriteScanline(out, obuf, row, 0))
200
+ goto done;
201
+ }
202
+ break;
203
+ case PLANARCONFIG_SEPARATE:
204
+ for (row = 0; row < imagelength; row++) {
205
+ if (!TIFFReadScanline(in, ibuf, row, 0))
206
+ goto done;
207
+ for (pp = obuf, x = 0; x < imagewidth; x++)
208
+ *pp++ = (unsigned char) rmap[ibuf[x]];
209
+ if (!TIFFWriteScanline(out, obuf, row, 0))
210
+ goto done;
211
+ for (pp = obuf, x = 0; x < imagewidth; x++)
212
+ *pp++ = (unsigned char) gmap[ibuf[x]];
213
+ if (!TIFFWriteScanline(out, obuf, row, 0))
214
+ goto done;
215
+ for (pp = obuf, x = 0; x < imagewidth; x++)
216
+ *pp++ = (unsigned char) bmap[ibuf[x]];
217
+ if (!TIFFWriteScanline(out, obuf, row, 0))
218
+ goto done;
219
+ }
220
+ break;
221
+ }
222
+ _TIFFfree(ibuf);
223
+ _TIFFfree(obuf);
224
+ }
225
+ done:
226
+ (void) TIFFClose(in);
227
+ (void) TIFFClose(out);
228
+ return (0);
229
+ }
230
+
231
+ static int
232
+ processCompressOptions(char* opt)
233
+ {
234
+ if (streq(opt, "none"))
235
+ compression = COMPRESSION_NONE;
236
+ else if (streq(opt, "packbits"))
237
+ compression = COMPRESSION_PACKBITS;
238
+ else if (strneq(opt, "jpeg", 4)) {
239
+ char* cp = strchr(opt, ':');
240
+
241
+ compression = COMPRESSION_JPEG;
242
+ while( cp )
243
+ {
244
+ if (isdigit((int)cp[1]))
245
+ quality = atoi(cp+1);
246
+ else if (cp[1] == 'r' )
247
+ jpegcolormode = JPEGCOLORMODE_RAW;
248
+ else
249
+ usage();
250
+
251
+ cp = strchr(cp+1,':');
252
+ }
253
+ } else if (strneq(opt, "lzw", 3)) {
254
+ char* cp = strchr(opt, ':');
255
+ if (cp)
256
+ predictor = atoi(cp+1);
257
+ compression = COMPRESSION_LZW;
258
+ } else if (strneq(opt, "zip", 3)) {
259
+ char* cp = strchr(opt, ':');
260
+ if (cp)
261
+ predictor = atoi(cp+1);
262
+ compression = COMPRESSION_DEFLATE;
263
+ } else
264
+ return (0);
265
+ return (1);
266
+ }
267
+
268
+ #define CopyField(tag, v) \
269
+ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
270
+ #define CopyField2(tag, v1, v2) \
271
+ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
272
+ #define CopyField3(tag, v1, v2, v3) \
273
+ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
274
+ #define CopyField4(tag, v1, v2, v3, v4) \
275
+ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)
276
+
277
+ static void
278
+ cpTag(TIFF* in, TIFF* out, uint16
279
+
280
+ // ... (4633 more chars)
281
+ ```
282
+
283
+ ### File: tools/thumbnail.c
284
+ ```c
285
+ /* $Id$ */
286
+
287
+ /*
288
+ * Copyright (c) 1994-1997 Sam Leffler
289
+ * Copyright (c) 1994-1997 Silicon Graphics, Inc.
290
+ *
291
+ * Permission to use, copy, modify, distribute, and sell this software and
292
+ * its documentation for any purpose is hereby granted without fee, provided
293
+ * that (i) the above copyright notices and this permission notice appear in
294
+ * all copies of the software and related documentation, and (ii) the names of
295
+ * Sam Leffler and Silicon Graphics may not be used in any advertising or
296
+ * publicity relating to the software without the specific, prior written
297
+ * permission of Sam Leffler and Silicon Graphics.
298
+ *
299
+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
300
+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
301
+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
302
+ *
303
+ * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
304
+ * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
305
+ * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
306
+ * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
307
+ * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
308
+ * OF THIS SOFTWARE.
309
+ */
310
+
311
+ #include "tif_config.h"
312
+
313
+ #include <stdio.h>
314
+ #include <stdlib.h>
315
+ #include <string.h>
316
+ #include <math.h>
317
+
318
+ #ifdef HAVE_UNISTD_H
319
+ # include <unistd.h>
320
+ #endif
321
+
322
+ #ifdef NEED_LIBPORT
323
+ # include "libport.h"
324
+ #endif
325
+
326
+ #include "tiffio.h"
327
+
328
+ #ifndef HAVE_GETOPT
329
+ extern int getopt(int, char**, char*);
330
+ #endif
331
+
332
+ #define streq(a,b) (strcmp(a,b) == 0)
333
+
334
+ #ifndef TIFFhowmany8
335
+ # define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3)
336
+ #endif
337
+
338
+ typedef enum {
339
+ EXP50,
340
+ EXP60,
341
+ EXP70,
342
+ EXP80,
343
+ EXP90,
344
+ EXP,
345
+ LINEAR
346
+ } Contrast;
347
+
348
+ static uint32 tnw = 216; /* thumbnail width */
349
+ static uint32 tnh = 274; /* thumbnail height */
350
+ static Contrast contrast = LINEAR; /* current contrast */
351
+ static uint8* thumbnail;
352
+
353
+ static int cpIFD(TIFF*, TIFF*);
354
+ static int generateThumbnail(TIFF*, TIFF*);
355
+ static void initScale();
356
+ static void usage(void);
357
+
358
+ extern char* optarg;
359
+ extern int optind;
360
+
361
+ int
362
+ main(int argc, char* argv[])
363
+ {
364
+ TIFF* in;
365
+ TIFF* out;
366
+ int c;
367
+
368
+ while ((c = getopt(argc, argv, "w:h:c:")) != -1) {
369
+ switch (c) {
370
+ case 'w': tnw = strtoul(optarg, NULL, 0); break;
371
+ case 'h': tnh = strtoul(optarg, NULL, 0); break;
372
+ case 'c': contrast = streq(optarg, "exp50") ? EXP50 :
373
+ streq(optarg, "exp60") ? EXP60 :
374
+ streq(optarg, "exp70") ? EXP70 :
375
+ streq(optarg, "exp80") ? EXP80 :
376
+ streq(optarg, "exp90") ? EXP90 :
377
+ streq(optarg, "exp") ? EXP :
378
+ streq(optarg, "linear")? LINEAR :
379
+ EXP;
380
+ break;
381
+ default: usage();
382
+ }
383
+ }
384
+ if (argc-optind != 2)
385
+ usage();
386
+
387
+ out = TIFFOpen(argv[optind+1], "w");
388
+ if (out == NULL)
389
+ return 2;
390
+ in = TIFFOpen(argv[optind], "r");
391
+ if( in == NULL )
392
+ return 2;
393
+
394
+ thumbnail = (uint8*) _TIFFmalloc(tnw * tnh);
395
+ if (!thumbnail) {
396
+ TIFFError(TIFFFileName(in),
397
+ "Can't allocate space for thumbnail buffer.");
398
+ return 1;
399
+ }
400
+
401
+ if (in != NULL) {
402
+ initScale();
403
+ do {
404
+ if (!generateThumbnail(in, out))
405
+ goto bad;
406
+ if (!cpIFD(in, out) || !TIFFWriteDirectory(out))
407
+ goto bad;
408
+ } while (TIFFReadDirectory(in));
409
+ (void) TIFFClose(in);
410
+ }
411
+ (void) TIFFClose(out);
412
+ return 0;
413
+ bad:
414
+ (void) TIFFClose(out);
415
+ return 1;
416
+ }
417
+
418
+ #define CopyField(tag, v) \
419
+ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
420
+ #define CopyField2(tag, v1, v2) \
421
+ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
422
+ #define CopyField3(tag, v1, v2, v3) \
423
+ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
424
+ #define CopyField4(tag, v1, v2, v3, v4) \
425
+ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)
426
+
427
+ static void
428
+ cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type)
429
+ {
430
+ switch (type) {
431
+ case TIFF_SHORT:
432
+ if (count == 1) {
433
+ uint16 shortv;
434
+ CopyField(tag, shortv);
435
+ } else if (count == 2) {
436
+ uint16 shortv1, shortv2;
437
+ CopyField2(tag, shortv1, shortv2);
438
+ } else if (count == 4) {
439
+ uint16 *tr, *tg, *tb, *ta;
440
+ CopyField4(tag, tr, tg, tb, ta);
441
+ } else if (count == (uint16) -1) {
442
+ uint16 shortv1;
443
+ uint16* shortav;
444
+ CopyField2(tag, shortv1, shortav);
445
+ }
446
+ break;
447
+ case TIFF_LONG:
448
+ { uint32 longv;
449
+ CopyField(tag, longv);
450
+ }
451
+ break;
452
+ case TIFF_LONG8:
453
+ { uint64 longv8;
454
+ CopyField(tag, longv8);
455
+ }
456
+ break;
457
+ case TIFF_SLONG8:
458
+ { int64 longv8;
459
+ CopyField(tag, longv8);
460
+ }
461
+ break;
462
+ case TIFF_RATIONAL:
463
+ if (count == 1) {
464
+ float floatv;
465
+ CopyField(tag, floatv);
466
+ } else if (count == (uint16) -1) {
467
+ float* floatav;
468
+ CopyField(tag, floatav);
469
+ }
470
+ break;
471
+ case TIFF_ASCII:
472
+ { char* stringv;
473
+ CopyField(tag, stringv);
474
+ }
475
+ break;
476
+ case TIFF_DOUBLE:
477
+ if (count == 1) {
478
+ double doublev;
479
+ CopyField(tag, doublev);
480
+ } else if (count == (uint16) -1) {
481
+ double* doubleav;
482
+ CopyField(tag, doubleav);
483
+ }
484
+ break;
485
+ case TIFF_IFD8:
486
+ { toff_t ifd8;
487
+ CopyField(tag, ifd8);
488
+ }
489
+ break; default:
490
+ TIFFError(TIFFFileName(in),
491
+ "Data type %d is not supported, tag %d skipped.",
492
+ tag, type);
493
+ }
494
+ }
495
+
496
+ #undef CopyField4
497
+ #undef CopyField3
498
+ #undef CopyField2
499
+ #undef CopyField
500
+
501
+ static struct cpTag {
502
+ uint16 tag;
503
+ uint16 count;
504
+ TIFFDataType type;
505
+ } tags[] = {
506
+ { TIFFTAG_IMAGEWIDTH, 1, TIFF_LONG },
507
+ { TIFFTAG_IMAGELENGTH, 1, TIFF_LONG },
508
+ { TIFFTAG_BITSPERSAMPLE, 1, TIFF_SHORT },
509
+ { TIFFTAG_COMPRESSION, 1, TIFF_SHORT },
510
+ { TIFFTAG_FILLORDER, 1, TIFF_SHORT },
511
+ { TIFFTAG_SAMPLESPERPIXEL, 1, TIFF_SHORT },
512
+ { TIFFTAG_ROWSPERSTRIP, 1, TIFF_LONG },
513
+ { TIFFTAG_PLANARCONFIG, 1, TIFF_SHORT },
514
+ { TIFFTAG_GROUP3OPTIONS, 1, TIFF_LONG },
515
+ { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG },
516
+ { TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT },
517
+ { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT },
518
+ { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII },
519
+ { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII },
520
+ { TIFFTAG_MAKE, 1, TIFF_ASCII },
521
+ { TIFFTAG_MODEL, 1, TIFF_ASCII },
522
+ { TIFFTAG_ORIENTATION, 1, TIFF_SHORT },
523
+ { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT },
524
+ { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT },
525
+ { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL },
526
+ { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL },
527
+ { TIFFTAG_PAGENAME, 1, TIFF_ASCII },
528
+ { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL },
529
+ { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL },
530
+ { TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG },
531
+ { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT },
532
+ { TIFFTAG_PAGENUMBER, 2, TIFF_SHORT },
533
+ { TIFFTAG_SOFTWARE, 1, TIFF_ASCII },
534
+ { TIFFTAG_DATETIME, 1, TIFF_ASCII },
535
+ { TIFFTAG_ARTIST, 1, TIFF_ASCII },
536
+ { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII },
537
+ { TIFFTAG_WHITEPOINT, 2, TIFF_RATIONAL },
538
+ { TIFFTAG_PRIMARYCHROMATICITIES, (uint16) -1,TIFF_RATIONAL },
539
+ { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT },
540
+ { TIFFTAG_BADFAXLINES, 1, TIFF_LONG },
541
+ { TIFFTAG_CLEANFAXDATA, 1, TIFF_SHORT },
542
+ { TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG },
543
+ { TIFFTAG_INKSET, 1, TIFF_SHORT },
544
+ { TIFFTAG_INKNAMES, 1, TIFF_ASCII },
545
+ { TIFFTAG_DOTRANGE, 2, TIFF_SHORT },
546
+ { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII },
547
+ { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT },
548
+ { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL },
549
+ { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT },
550
+ { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT },
551
+ { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL },
552
+ { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT },
553
+ };
554
+ #define NTAGS (sizeof (tags) / sizeof (tags[0]))
555
+
556
+ static void
557
+ cpTags(TIFF* in, TIFF* out)
558
+ {
559
+ struct cpTag *p;
560
+ for (p = tags; p < &tags[NTAGS]; p++)
561
+ {
562
+ /* Horrible: but TIFFGetField() expects 2 arguments to be passed */
563
+ /* if we request a tag that is defined in a codec, but that codec */
564
+ /* isn't used */
565
+ if( p->tag == TIFFTAG_GROUP3OPTIONS )
566
+ {
567
+
568
+
569
+ // ... (10401 more chars)
570
+ ```
tasks/csa159/pair_136342/task_prompt.md ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Task: Synthesize a CSA Checker from a CVE Patch
2
+
3
+ ## Your Role
4
+
5
+ You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker
6
+ that detects the bug pattern fixed by the CVE patch in this working directory.
7
+
8
+ You have full filesystem and bash access — use them.
9
+
10
+ ### Skills
11
+
12
+ Many skills are available under `.claude/skills/` — covering vulnerability analysis,
13
+ checker design, debugging, code audit, security patterns, and more. Each skill
14
+ encodes reusable expertise: take time to explore them, read their SKILL.md files,
15
+ and invoke those that look useful via the Skill tool. Let the task guide which
16
+ ones you reach for.
17
+
18
+ ## File Layout
19
+
20
+ ```
21
+ /work/
22
+ ├── compile.sh ← RUN ME: compile checker.cpp → checker.so
23
+ ├── checker_template.cpp ← skeleton, start here
24
+ ├── patch.diff ← the CVE fix
25
+ ├── pre_functions.txt ← buggy source (before_commit)
26
+ ├── post_functions.txt ← patched source (after_commit)
27
+ ├── config.json ← paths, commit_message, commit hashes, flags
28
+ ├── scan/
29
+ │ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy
30
+ │ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched
31
+ │ └── flags_*.txt ← pre-extracted compile flags (-I, -D)
32
+ ├── references/
33
+ │ ├── repo_knowledge.md ← project-specific API/convention reference
34
+ │ ├── patterns_summary.md ← (optional) historical bug pattern summary
35
+ │ ├── cwe_cards/ ← CWE knowledge library (all categories)
36
+ │ │ ├── index.json ← lookup index — use to find relevant cards
37
+ │ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns
38
+ │ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped)
39
+ │ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers)
40
+ │ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.)
41
+ │ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.)
42
+ │ └── examples/
43
+ │ └── llvm-official/ ← 5 official checker sources (with comments)
44
+ │ ├── 01_div_zero.cpp
45
+ │ ├── 02_simple_stream.cpp
46
+ │ ├── 03_undef_result.cpp
47
+ │ ├── 04_nullability.cpp
48
+ │ └── 05_malloc.cpp
49
+ │
50
+ ├── checker.cpp ← YOUR OUTPUT: synthesized checker
51
+ ├── checker.so ← YOUR OUTPUT: compiled checker
52
+ ├── state.json ← YOUR OUTPUT: structured task state
53
+ ├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3)
54
+ └── summary.json ← YOUR OUTPUT: final report
55
+ ```
56
+
57
+ ## Resources
58
+
59
+ **Read these before writing any code:**
60
+
61
+ 1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from
62
+ LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types,
63
+ MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.**
64
+
65
+ 2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested
66
+ patterns from official LLVM checkers: resource tracking, null checking, undefined
67
+ value detection, division-by-zero, and malloc/free. Each pattern includes skeleton
68
+ code, state traits, and key API usage.
69
+
70
+ 3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations
71
+ with explanatory comments:
72
+ - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback)
73
+ - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose)
74
+ - `03_undef_result.cpp` — PostStmt pattern (160 lines)
75
+ - `04_nullability.cpp` — multi-callback checker (1247 lines)
76
+ - `05_malloc.cpp` — comprehensive malloc/free (1511 lines)
77
+
78
+ 4. **`checker_template.cpp`** — Skeleton with placeholders. Start here.
79
+
80
+ 5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this
81
+ repository's memory allocation API, key data types, source layout, and typical
82
+ CVE patterns. **Read this before writing the checker** — knowing the project's
83
+ alloc/free conventions and common bug patterns saves many grep rounds.
84
+
85
+ 5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis
86
+ patterns for this project. If present, it contains a concise summary of the
87
+ most common bug patterns, frequent CWE categories, and reusable checker
88
+ architectures observed in previous synthesis runs. Read after repo_knowledge.md.
89
+
90
+ 6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all
91
+ vulnerability categories. **The framework provides the full library —
92
+ you must identify the vulnerability type yourself.** Workflow:
93
+
94
+ 1. Analyse the patch diff and commit message to determine the vulnerability
95
+ type (buffer overflow, UAF, null deref, integer overflow, race condition,
96
+ etc.). Do NOT rely on the CWE label — treat it as a hint at most.
97
+ 2. Open ``index.json`` to discover available cards and their tiers.
98
+ 3. Read the relevant card(s) for **detection strategies**, **checker
99
+ architecture suggestions**, and **known false-positive patterns**.
100
+
101
+ Card tiers:
102
+ - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel /
103
+ userspace variants when the detection strategy differs substantially.
104
+ - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by
105
+ category (input validation, resource management, etc.).
106
+
107
+ 7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for
108
+ checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`),
109
+ expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string
110
+ size extraction, MemRegion helpers, and `ExprHasName()` for robust function
111
+ matching. All verified against LLVM 18. **Read before implementing detection
112
+ logic** — these save writing boilerplate that's easy to get wrong.
113
+
114
+ ## Environment
115
+
116
+ Key paths are in ``config.json``.
117
+
118
+ ### Pre-built scripts
119
+
120
+ | Script | What it does |
121
+ |--------|-------------|
122
+ | `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) |
123
+ | `CHECKER_NAME=<name> bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy |
124
+ | `CHECKER_NAME=<name> bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched |
125
+
126
+ ```bash
127
+ # Compile (run from workdir root)
128
+ bash compile.sh
129
+
130
+ # Scan — set CHECKER_NAME to the string passed to addChecker<>()
131
+ CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy
132
+ CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched
133
+ ```
134
+
135
+ - ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags.
136
+ - ``scan/scan_*.sh`` count only warnings tagged with your checker name.
137
+ - Scan environments (source files + compile flags) are pre-built in ``scan/``.
138
+
139
+ ### Scan Script Integrity (CRITICAL)
140
+
141
+ The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only
142
+ valid measurement** of N_buggy and N_patched. They are the ground truth that the
143
+ Python-side validator will also use. You MUST obey these rules:
144
+
145
+ **1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly
146
+ to measure warning counts. The Python validator runs the same scan scripts
147
+ — if you measured with a different command, your numbers will not reproduce
148
+ and the synthesis will be rejected.
149
+
150
+ **2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared
151
+ identifiers, etc.), the scan environment needs repair. You MUST fix it:
152
+ - Add missing ``-I`` include paths to the flags files in ``scan/``
153
+ - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot
154
+ - If the file fundamentally cannot be compiled by clang, stop and write
155
+ ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason``
156
+
157
+ **3. Only trust scan script output.** The ``Total <name> warnings: N`` line
158
+ printed by the scan script is the number that goes into ``summary.json``.
159
+ If the scan script says 0, write 0. Fabricating numbers that the scan
160
+ script did not produce will cause the Python validator to reject the
161
+ synthesis.
162
+
163
+ - If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles).
164
+ - If validation fails: revise checker logic, re-compile, re-scan.
165
+
166
+ ## MCP Tools
167
+
168
+ You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`).
169
+ Each returns **source context embedded in the result** — no need to follow up with Read.
170
+
171
+ | Tool | What it does | Key advantage |
172
+ |------|-------------|---------------|
173
+ | `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call |
174
+ | `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file |
175
+ | `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed |
176
+
177
+ ### When to use each
178
+
179
+ - **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure.
180
+ - **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines.
181
+ - **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action.
182
+
183
+ ## Semantic Design Contract — before writing checker.cpp
184
+
185
+ Create the analysis portions of `state.json` and `scope_statement.md` **before**
186
+ writing checker.cpp. They are a design contract, not a retrospective summary.
187
+ After compilation, update only implementation facts such as `build_attempts`.
188
+
189
+ In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the
190
+ semantic fact introduced by the patch that makes it safe. In `detection_plan`,
191
+ make `report_condition`, `safe_condition`, and `source_level_signal` concrete
192
+ CSA-observable facts. In `api_choice`, record the mechanism level and explain
193
+ why the selected callback can observe and prove those facts.
194
+
195
+ In `scope_statement.md`, include this mapping table and check it again after
196
+ implementation:
197
+
198
+ | Semantic condition | CSA evidence | checker.cpp implementation |
199
+ | --- | --- | --- |
200
+ | report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports |
201
+ | safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report |
202
+
203
+ Every condition in the plan must have an implementation entry. Do not claim a
204
+ condition that checker.cpp does not implement, and do not silently add a code
205
+ condition absent from the plan.
206
+
207
+ ## Mechanism Selection — diagnose before coding
208
+
209
+ Choose the weakest CSA mechanism that can prove the vulnerability property:
210
+
211
+ 1. **syntax-only AST**: only when local AST shape itself is the defect;
212
+ 2. **control flow / dominance**: when guard placement relative to a sink matters;
213
+ 3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use;
214
+ 4. **cross-procedure/dataflow**: when the required fact crosses function boundaries.
215
+
216
+ For a guard-based patch, prove both that the guard rejects the unsafe value and
217
+ that it dominates the vulnerable use. For path-sensitive or cross-procedure
218
+ defects, do not replace the required state or flow proof with local AST matching
219
+ or source-text substring matching merely because it passes the differential scan.
220
+ Record the selected level as `api_choice.mechanism_level`.
221
+
222
+ ## Semantic identity, locality, and final validation
223
+
224
+ Before accepting the checker, verify that its primary matching logic does not
225
+ depend on patch-local variable names, labels, line numbers, commit IDs, or unique
226
+ literals. Project APIs, types, and stable semantic call relationships are valid
227
+ scope anchors when they define the vulnerability class. Attach the report to the
228
+ actual vulnerable operation, and implement every suppression as a real safe
229
+ condition rather than the mere presence of a nearby guard-shaped statement.
230
+
231
+ The required final sequence is: **compile → before scan → after scan → inspect
232
+ the final checker name, artifacts, and report locations → write summary.json**.
233
+ Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only
234
+ additional redesign cycles after a failed validation; if it is zero, preserve the
235
+ real validation evidence and report failure honestly rather than fabricating counts.
236
+
237
+ ## Validation Criteria
238
+
239
+ ```
240
+ VALID : N_buggy > N_patched AND N_patched < 50
241
+ INVALID : otherwise → revise and re-validate (max 1 attempts)
242
+ ```
243
+
244
+ ## Refinement
245
+
246
+ Do NOT self-refine the checker repeatedly. Your goal is to produce the first
247
+ checker that passes the Validation Criteria above — fix compile errors and
248
+ validation failures only. False positives are triaged and repaired by the
249
+ framework's refinement stage: you will receive a concrete FP list via
250
+ session resume (if needed) and fix only those. Reserve budget for that stage.
251
+
252
+ ## Output
253
+
254
+ Produce all of the following **only when completely done**:
255
+
256
+ | File | Content |
257
+ |------|---------|
258
+ | ``checker.cpp`` | Synthesized checker source code |
259
+ | ``checker.so`` | Compiled checker plugin |
260
+ | ``state.json`` | Structured task state (see schema below) |
261
+ | ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) |
262
+ | ``summary.json`` | Final report (see schema below) |
263
+
264
+ Writing ``summary.json`` signals completion. Do NOT write it early.
265
+
266
+ ### ``state.json``
267
+
268
+ Create this before writing checker.cpp to capture the design contract. After the
269
+ checker compiles, update only implementation facts and retain the original
270
+ semantic plan.
271
+
272
+ ```json
273
+ {
274
+ "patch_analysis": {
275
+ "summary": "One sentence describing the vulnerability this patch fixes",
276
+ "changed_files": ["file1.c", "file2.h"],
277
+ "changed_functions": ["func_a", "func_b"],
278
+ "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other",
279
+ "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other",
280
+ "affected_types": ["GF_BitStream", "custom_struct_t"],
281
+ "critical_calls": ["gf_strdup", "memcpy"]
282
+ },
283
+ "detection_plan": {
284
+ "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')",
285
+ "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')",
286
+ "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')",
287
+ "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')"
288
+ },
289
+ "api_choice": {
290
+ "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow",
291
+ "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...",
292
+ "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions",
293
+ "alternatives_considered": ["check::PostCall"]
294
+ },
295
+ "implementation": {
296
+ "scope_level": "patch_specific | project_general | cross_project",
297
+ "checker_name": "project.CheckerName",
298
+ "build_attempts": 1
299
+ }
300
+ }
301
+ ```
302
+
303
+ ### ``summary.json``
304
+
305
+ ```json
306
+ {
307
+ "status": "plausible | failed",
308
+ "bug_pattern": "One sentence describing the bug pattern",
309
+ "scope_level": "patch_specific | project_general | cross_project",
310
+ "checker_cpp": "checker.cpp",
311
+ "checker_so": "checker.so",
312
+ "n_buggy": 0,
313
+ "n_patched": 0,
314
+ "total_reports": 0,
315
+ "fp_rate_estimate": 0.0,
316
+ "failure_reason": null
317
+ }
318
+ ```
tasks/csa159/pair_136864/checker_template.cpp ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ============================================================================
2
+ // CSA Checker Template
3
+ // ============================================================================
4
+ // Fill in the sections marked with TODO to implement your checker.
5
+ // The checker is compiled with -fno-rtti to match the LLVM 18 build config.
6
+ // It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName
7
+ //
8
+ // Compilation:
9
+ // clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \
10
+ // -I${LLVM_BUILD_DIR}/include \
11
+ // checker.cpp -o checker.so \
12
+ // -Wl,--allow-shlib-undefined
13
+ //
14
+ // Usage:
15
+ // clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze <file>
16
+ // ============================================================================
17
+
18
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19
+ #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20
+ #include "clang/StaticAnalyzer/Core/Checker.h"
21
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22
+ #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23
+ #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
24
+
25
+ using namespace clang;
26
+ using namespace ento;
27
+
28
+ namespace {
29
+
30
+ // ────────────────────────────────────────────────────────────────
31
+ // TODO: Rename this class to describe your checker's purpose.
32
+ // ────────────────────────────────────────────────────────────────
33
+ class {{CHECKER_CLASS_NAME}}
34
+ : public Checker<check::PreCall, // for checking before function calls
35
+ check::PostCall> // for checking after function calls
36
+ {
37
+ // TODO: Customize the bug type name and category.
38
+ mutable std::unique_ptr<BugType> BT;
39
+
40
+ public:
41
+ {{CHECKER_CLASS_NAME}}()
42
+ : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {}
43
+
44
+ // ── PreCall callback (fires before every function call) ──────
45
+ void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
46
+ // TODO: Implement your pre-call analysis logic here.
47
+ //
48
+ // Common patterns:
49
+ //
50
+ // 1. Check if the called function matches a specific name:
51
+ // if (Call.getCalleeIdentifier()) {
52
+ // StringRef name = Call.getCalleeIdentifier()->getName();
53
+ // if (name == "target_function") { ... }
54
+ // }
55
+ //
56
+ // 2. Get the program state:
57
+ // ProgramStateRef State = C.getState();
58
+ //
59
+ // 3. Get arguments:
60
+ // SVal Arg = Call.getArgSVal(0);
61
+ //
62
+ // 4. Generate a bug report:
63
+ // ExplodedNode *ErrNode = C.generateErrorNode();
64
+ // if (ErrNode) {
65
+ // auto R = std::make_unique<PathSensitiveBugReport>(
66
+ // *BT, "Description of the bug", ErrNode);
67
+ // C.emitReport(std::move(R));
68
+ // }
69
+ }
70
+
71
+ // ── PostCall callback (fires after every function call) ─────
72
+ void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
73
+ // TODO: Implement your post-call analysis logic here.
74
+ //
75
+ // Common pattern — check the return value:
76
+ // SVal RetVal = Call.getReturnValue();
77
+ // if (RetVal.isUnknownOrUndef()) return;
78
+ //
79
+ // ProgramStateRef State = C.getState();
80
+ // // Modify state based on post-call conditions...
81
+ }
82
+ };
83
+
84
+ } // anonymous namespace
85
+
86
+ // ────────────────────────────────────────────────────────────────
87
+ // Registration — DO NOT modify the function signatures.
88
+ // ────────────────────────────────────────────────────────────────
89
+
90
+ extern "C" void clang_registerCheckers(CheckerRegistry &registry) {
91
+ registry.addChecker<{{CHECKER_CLASS_NAME}}>(
92
+ "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker"
93
+ "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference"
94
+ "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs"
95
+ }
96
+
97
+ extern "C" const char clang_analyzerAPIVersionString[] =
98
+ CLANG_ANALYZER_API_VERSION_STRING;
tasks/csa159/pair_136864/config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "project_id": "ImageMagick_ImageMagick6",
3
+ "before_commit": "b466a96965afc1308a4ace93f5535c2b770f294b",
4
+ "after_commit": "7486477aa00c5c7856b111506da075b6cdfa8b73",
5
+ "repo_path": "/workspace/repo/ImageMagick/ImageMagick6",
6
+ "llvm_build_dir": "/opt/llvm",
7
+ "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/ImageMagick_ImageMagick6/b7c9c8972ef11481d92b1f57172fe72c54b0c4a2/compile_commands.json",
8
+ "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/ImageMagick_ImageMagick6/b7c9c8972ef11481d92b1f57172fe72c54b0c4a2/compile_commands.json",
9
+ "changed_files": [
10
+ "coders/tiff.c"
11
+ ],
12
+ "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1857",
13
+ "t_valid": 50,
14
+ "t_plausible": 20,
15
+ "triage_sample_size": 10,
16
+ "max_synthesis_retry": 0,
17
+ "max_in_session_redesigns": 1,
18
+ "max_refinement_iter": 3
19
+ }
tasks/csa159/pair_136864/patch.diff ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/coders/tiff.c b/coders/tiff.c
2
+ index 0256a6c1e..15c993364 100644
3
+ --- a/coders/tiff.c
4
+ +++ b/coders/tiff.c
5
+ @@ -1701,7 +1701,8 @@ RestoreMSCWarning
6
+ }
7
+ if (TIFFIsTiled(tiff) != MagickFalse)
8
+ method=ReadTileMethod;
9
+ - if (photometric == PHOTOMETRIC_LOGLUV)
10
+ + if ((photometric == PHOTOMETRIC_LOGLUV) ||
11
+ + (photometric == PHOTOMETRIC_YCBCR))
12
+ method=ReadGenericMethod;
13
+ if (image->compression == JPEGCompression)
14
+ method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,
15
+ @@ -1834,8 +1835,6 @@ RestoreMSCWarning
16
+ Convert stripped TIFF image.
17
+ */
18
+ extent=TIFFStripSize(tiff)+sizeof(uint32);
19
+ - if (photometric == PHOTOMETRIC_YCBCR)
20
+ - extent<<=1;
21
+ strip_pixels=(unsigned char *) AcquireQuantumMemory(extent,
22
+ sizeof(*strip_pixels));
23
+ if (strip_pixels == (unsigned char *) NULL)
tasks/csa159/pair_136864/post_functions.txt ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: coders/tiff.c
2
+ ```c
3
+ static Image *ReadTIFFImage(const ImageInfo *image_info,
4
+ ExceptionInfo *exception)
5
+ {
6
+ #define ThrowTIFFException(severity,message) \
7
+ { \
8
+ if (pixel_info != (MemoryInfo *) NULL) \
9
+ pixel_info=RelinquishVirtualMemory(pixel_info); \
10
+ if (quantum_info != (QuantumInfo *) NULL) \
11
+ quantum_info=DestroyQuantumInfo(quantum_info); \
12
+ TIFFClose(tiff); \
13
+ ThrowReaderException(severity,message); \
14
+ }
15
+
16
+ const char
17
+ *option;
18
+
19
+ float
20
+ *chromaticity,
21
+ x_position,
22
+ y_position,
23
+ x_resolution,
24
+ y_resolution;
25
+
26
+ Image
27
+ *image;
28
+
29
+ int
30
+ tiff_status;
31
+
32
+ MagickBooleanType
33
+ more_frames,
34
+ status;
35
+
36
+ MemoryInfo
37
+ *pixel_info = (MemoryInfo *) NULL;
38
+
39
+ QuantumInfo
40
+ *quantum_info;
41
+
42
+ QuantumType
43
+ quantum_type;
44
+
45
+ register ssize_t
46
+ i;
47
+
48
+ size_t
49
+ number_pixels,
50
+ pad;
51
+
52
+ ssize_t
53
+ y;
54
+
55
+ TIFF
56
+ *tiff;
57
+
58
+ TIFFMethodType
59
+ method;
60
+
61
+ uint16
62
+ compress_tag,
63
+ bits_per_sample,
64
+ endian,
65
+ extra_samples,
66
+ interlace,
67
+ max_sample_value,
68
+ min_sample_value,
69
+ orientation,
70
+ pages,
71
+ photometric,
72
+ *sample_info,
73
+ sample_format,
74
+ samples_per_pixel,
75
+ units,
76
+ value;
77
+
78
+ uint32
79
+ height,
80
+ rows_per_strip,
81
+ width;
82
+
83
+ unsigned char
84
+ *pixels;
85
+
86
+ void
87
+ *sans[2] = { NULL, NULL };
88
+
89
+ /*
90
+ Open image.
91
+ */
92
+ assert(image_info != (const ImageInfo *) NULL);
93
+ assert(image_info->signature == MagickCoreSignature);
94
+ if (image_info->debug != MagickFalse)
95
+ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
96
+ image_info->filename);
97
+ assert(exception != (ExceptionInfo *) NULL);
98
+ assert(exception->signature == MagickCoreSignature);
99
+ image=AcquireImage(image_info);
100
+ status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
101
+ if (status == MagickFalse)
102
+ {
103
+ image=DestroyImageList(image);
104
+ return((Image *) NULL);
105
+ }
106
+ (void) SetMagickThreadValue(tiff_exception,exception);
107
+ tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
108
+ TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
109
+ TIFFUnmapBlob);
110
+ if (tiff == (TIFF *) NULL)
111
+ {
112
+ image=DestroyImageList(image);
113
+ return((Image *) NULL);
114
+ }
115
+ if (exception->severity > ErrorException)
116
+ {
117
+ TIFFClose(tiff);
118
+ image=DestroyImageList(image);
119
+ return((Image *) NULL);
120
+ }
121
+ if (image_info->number_scenes != 0)
122
+ {
123
+ /*
124
+ Generate blank images for subimage specification (e.g. image.tif[4].
125
+ We need to check the number of directores because it is possible that
126
+ the subimage(s) are stored in the photoshop profile.
127
+ */
128
+ if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff))
129
+ {
130
+ for (i=0; i < (ssize_t) image_info->scene; i++)
131
+ {
132
+ status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
133
+ if (status == MagickFalse)
134
+ {
135
+ TIFFClose(tiff);
136
+ image=DestroyImageList(image);
137
+ return((Image *) NULL);
138
+ }
139
+ AcquireNextImage(image_info,image);
140
+ if (GetNextImageInList(image) == (Image *) NULL)
141
+ {
142
+ TIFFClose(tiff);
143
+ image=DestroyImageList(image);
144
+ return((Image *) NULL);
145
+ }
146
+ image=SyncNextImageInList(image);
147
+ }
148
+ }
149
+ }
150
+ more_frames=MagickTrue;
151
+ do
152
+ {
153
+ DisableMSCWarning(4127)
154
+ if (0 && (image_info->verbose != MagickFalse))
155
+ TIFFPrintDirectory(tiff,stdout,MagickFalse);
156
+ RestoreMSCWarning
157
+ photometric=PHOTOMETRIC_RGB;
158
+ if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||
159
+ (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||
160
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric,sans) != 1) ||
161
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag,sans) != 1) ||
162
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian,sans) != 1) ||
163
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace,sans) != 1) ||
164
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel,sans) != 1) ||
165
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample,sans) != 1) ||
166
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format,sans) != 1) ||
167
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value,sans) != 1) ||
168
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value,sans) != 1))
169
+ {
170
+ TIFFClose(tiff);
171
+ ThrowReaderException(CorruptImageError,"ImproperImageHeader");
172
+ }
173
+ if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample != 64)) &&
174
+ ((bits_per_sample <= 0) || (bits_per_sample > 32)))
175
+ {
176
+ TIFFClose(tiff);
177
+ ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel");
178
+ }
179
+ if (sample_format == SAMPLEFORMAT_IEEEFP)
180
+ (void) SetImageProperty(image,"quantum:format","floating-point");
181
+ switch (photometric)
182
+ {
183
+ case PHOTOMETRIC_MINISBLACK:
184
+ {
185
+ (void) SetImageProperty(image,"tiff:photometric","min-is-black");
186
+ break;
187
+ }
188
+ case PHOTOMETRIC_MINISWHITE:
189
+ {
190
+ (void) SetImageProperty(image,"tiff:photometric","min-is-white");
191
+ break;
192
+ }
193
+ case PHOTOMETRIC_PALETTE:
194
+ {
195
+ (void) SetImageProperty(image,"tiff:photometric","palette");
196
+ break;
197
+ }
198
+ case PHOTOMETRIC_RGB:
199
+ {
200
+ (void) SetImageProperty(image,"tiff:photometric","RGB");
201
+ break;
202
+ }
203
+ case PHOTOMETRIC_CIELAB:
204
+ {
205
+ (void) SetImageProperty(image,"tiff:photometric","CIELAB");
206
+ break;
207
+ }
208
+ case PHOTOMETRIC_LOGL:
209
+ {
210
+ (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)");
211
+ break;
212
+ }
213
+ case PHOTOMETRIC_LOGLUV:
214
+ {
215
+ (void) SetImageProperty(image,"tiff:photometric","LOGLUV");
216
+ break;
217
+ }
218
+ #if defined(PHOTOMETRIC_MASK)
219
+ case PHOTOMETRIC_MASK:
220
+ {
221
+ (void) SetImageProperty(image,"tiff:photometric","MASK");
222
+ break;
223
+ }
224
+ #endif
225
+ case PHOTOMETRIC_SEPARATED:
226
+ {
227
+ (void) SetImageProperty(image,"tiff:photometric","separated");
228
+ break;
229
+ }
230
+ case PHOTOMETRIC_YCBCR:
231
+ {
232
+ (void) SetImageProperty(image,"tiff:photometric","YCBCR");
233
+ break;
234
+ }
235
+ default:
236
+ {
237
+ (void) SetImageProperty(image,"tiff:photometric","unknown");
238
+ break;
239
+ }
240
+ }
241
+ if (image->debug != MagickFalse)
242
+ {
243
+ (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
244
+ (unsigned int) width,(unsigned int) height);
245
+ (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
246
+ interlace);
247
+ (void) LogMagickEvent(CoderEvent,GetMagickModule(),
248
+ "Bits per sample: %u",bits_per_sample);
249
+ (void) LogMagickEvent(CoderEvent,GetMagickModule(),
250
+ "Min sample value: %u",min_sample_value);
251
+ (void) LogMagickEvent(CoderEvent,GetMagickModule(),
252
+ "Max sample value: %u",max_sample_value);
253
+ (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
254
+ "interpretation: %s",GetImageProperty(image,"tiff:photometric"));
255
+ }
256
+ image->columns=(size_t) width;
257
+ image->rows=(size_t) height;
258
+ image->depth=(size_t) bits_per_sample;
259
+ if (image->debug != MagickFalse)
260
+ (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
261
+ (double) image->depth);
262
+ image->endian=MSBEndian;
263
+ if (endian == FILLORDER_LSB2MSB)
264
+ image->endian=LSBEndian;
265
+ #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
266
+ if (TIFFIsBigEndian(tiff) == 0)
267
+ {
268
+ (void) SetImageProperty(image,"tiff:endian","lsb");
269
+ image->endian=LSBEndian;
270
+ }
271
+ else
272
+ {
273
+ (void) SetImageProperty(image,"tiff:endian","msb");
274
+ image->endian=MSBEndian;
275
+ }
276
+ #endif
277
+ if ((photometric == PHOTOMETRIC_MINISBLACK) ||
278
+ (photometric == PHOTOMETRIC_MINISWHITE))
279
+
280
+
281
+ // ... (24492 more chars)
282
+ ```
tasks/csa159/pair_136864/pre_functions.txt ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### File: coders/tiff.c
2
+ ```c
3
+ static Image *ReadTIFFImage(const ImageInfo *image_info,
4
+ ExceptionInfo *exception)
5
+ {
6
+ #define ThrowTIFFException(severity,message) \
7
+ { \
8
+ if (pixel_info != (MemoryInfo *) NULL) \
9
+ pixel_info=RelinquishVirtualMemory(pixel_info); \
10
+ if (quantum_info != (QuantumInfo *) NULL) \
11
+ quantum_info=DestroyQuantumInfo(quantum_info); \
12
+ TIFFClose(tiff); \
13
+ ThrowReaderException(severity,message); \
14
+ }
15
+
16
+ const char
17
+ *option;
18
+
19
+ float
20
+ *chromaticity,
21
+ x_position,
22
+ y_position,
23
+ x_resolution,
24
+ y_resolution;
25
+
26
+ Image
27
+ *image;
28
+
29
+ int
30
+ tiff_status;
31
+
32
+ MagickBooleanType
33
+ more_frames,
34
+ status;
35
+
36
+ MemoryInfo
37
+ *pixel_info = (MemoryInfo *) NULL;
38
+
39
+ QuantumInfo
40
+ *quantum_info;
41
+
42
+ QuantumType
43
+ quantum_type;
44
+
45
+ register ssize_t
46
+ i;
47
+
48
+ size_t
49
+ number_pixels,
50
+ pad;
51
+
52
+ ssize_t
53
+ y;
54
+
55
+ TIFF
56
+ *tiff;
57
+
58
+ TIFFMethodType
59
+ method;
60
+
61
+ uint16
62
+ compress_tag,
63
+ bits_per_sample,
64
+ endian,
65
+ extra_samples,
66
+ interlace,
67
+ max_sample_value,
68
+ min_sample_value,
69
+ orientation,
70
+ pages,
71
+ photometric,
72
+ *sample_info,
73
+ sample_format,
74
+ samples_per_pixel,
75
+ units,
76
+ value;
77
+
78
+ uint32
79
+ height,
80
+ rows_per_strip,
81
+ width;
82
+
83
+ unsigned char
84
+ *pixels;
85
+
86
+ void
87
+ *sans[2] = { NULL, NULL };
88
+
89
+ /*
90
+ Open image.
91
+ */
92
+ assert(image_info != (const ImageInfo *) NULL);
93
+ assert(image_info->signature == MagickCoreSignature);
94
+ if (image_info->debug != MagickFalse)
95
+ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
96
+ image_info->filename);
97
+ assert(exception != (ExceptionInfo *) NULL);
98
+ assert(exception->signature == MagickCoreSignature);
99
+ image=AcquireImage(image_info);
100
+ status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
101
+ if (status == MagickFalse)
102
+ {
103
+ image=DestroyImageList(image);
104
+ return((Image *) NULL);
105
+ }
106
+ (void) SetMagickThreadValue(tiff_exception,exception);
107
+ tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
108
+ TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
109
+ TIFFUnmapBlob);
110
+ if (tiff == (TIFF *) NULL)
111
+ {
112
+ image=DestroyImageList(image);
113
+ return((Image *) NULL);
114
+ }
115
+ if (exception->severity > ErrorException)
116
+ {
117
+ TIFFClose(tiff);
118
+ image=DestroyImageList(image);
119
+ return((Image *) NULL);
120
+ }
121
+ if (image_info->number_scenes != 0)
122
+ {
123
+ /*
124
+ Generate blank images for subimage specification (e.g. image.tif[4].
125
+ We need to check the number of directores because it is possible that
126
+ the subimage(s) are stored in the photoshop profile.
127
+ */
128
+ if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff))
129
+ {
130
+ for (i=0; i < (ssize_t) image_info->scene; i++)
131
+ {
132
+ status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
133
+ if (status == MagickFalse)
134
+ {
135
+ TIFFClose(tiff);
136
+ image=DestroyImageList(image);
137
+ return((Image *) NULL);
138
+ }
139
+ AcquireNextImage(image_info,image);
140
+ if (GetNextImageInList(image) == (Image *) NULL)
141
+ {
142
+ TIFFClose(tiff);
143
+ image=DestroyImageList(image);
144
+ return((Image *) NULL);
145
+ }
146
+ image=SyncNextImageInList(image);
147
+ }
148
+ }
149
+ }
150
+ more_frames=MagickTrue;
151
+ do
152
+ {
153
+ DisableMSCWarning(4127)
154
+ if (0 && (image_info->verbose != MagickFalse))
155
+ TIFFPrintDirectory(tiff,stdout,MagickFalse);
156
+ RestoreMSCWarning
157
+ photometric=PHOTOMETRIC_RGB;
158
+ if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||
159
+ (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||
160
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric,sans) != 1) ||
161
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag,sans) != 1) ||
162
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian,sans) != 1) ||
163
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace,sans) != 1) ||
164
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel,sans) != 1) ||
165
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample,sans) != 1) ||
166
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format,sans) != 1) ||
167
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value,sans) != 1) ||
168
+ (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value,sans) != 1))
169
+ {
170
+ TIFFClose(tiff);
171
+ ThrowReaderException(CorruptImageError,"ImproperImageHeader");
172
+ }
173
+ if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample != 64)) &&
174
+ ((bits_per_sample <= 0) || (bits_per_sample > 32)))
175
+ {
176
+ TIFFClose(tiff);
177
+ ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel");
178
+ }
179
+ if (sample_format == SAMPLEFORMAT_IEEEFP)
180
+ (void) SetImageProperty(image,"quantum:format","floating-point");
181
+ switch (photometric)
182
+ {
183
+ case PHOTOMETRIC_MINISBLACK:
184
+ {
185
+ (void) SetImageProperty(image,"tiff:photometric","min-is-black");
186
+ break;
187
+ }
188
+ case PHOTOMETRIC_MINISWHITE:
189
+ {
190
+ (void) SetImageProperty(image,"tiff:photometric","min-is-white");
191
+ break;
192
+ }
193
+ case PHOTOMETRIC_PALETTE:
194
+ {
195
+ (void) SetImageProperty(image,"tiff:photometric","palette");
196
+ break;
197
+ }
198
+ case PHOTOMETRIC_RGB:
199
+ {
200
+ (void) SetImageProperty(image,"tiff:photometric","RGB");
201
+ break;
202
+ }
203
+ case PHOTOMETRIC_CIELAB:
204
+ {
205
+ (void) SetImageProperty(image,"tiff:photometric","CIELAB");
206
+ break;
207
+ }
208
+ case PHOTOMETRIC_LOGL:
209
+ {
210
+ (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)");
211
+ break;
212
+ }
213
+ case PHOTOMETRIC_LOGLUV:
214
+ {
215
+ (void) SetImageProperty(image,"tiff:photometric","LOGLUV");
216
+ break;
217
+ }
218
+ #if defined(PHOTOMETRIC_MASK)
219
+ case PHOTOMETRIC_MASK:
220
+ {
221
+ (void) SetImageProperty(image,"tiff:photometric","MASK");
222
+ break;
223
+ }
224
+ #endif
225
+ case PHOTOMETRIC_SEPARATED:
226
+ {
227
+ (void) SetImageProperty(image,"tiff:photometric","separated");
228
+ break;
229
+ }
230
+ case PHOTOMETRIC_YCBCR:
231
+ {
232
+ (void) SetImageProperty(image,"tiff:photometric","YCBCR");
233
+ break;
234
+ }
235
+ default:
236
+ {
237
+ (void) SetImageProperty(image,"tiff:photometric","unknown");
238
+ break;
239
+ }
240
+ }
241
+ if (image->debug != MagickFalse)
242
+ {
243
+ (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
244
+ (unsigned int) width,(unsigned int) height);
245
+ (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
246
+ interlace);
247
+ (void) LogMagickEvent(CoderEvent,GetMagickModule(),
248
+ "Bits per sample: %u",bits_per_sample);
249
+ (void) LogMagickEvent(CoderEvent,GetMagickModule(),
250
+ "Min sample value: %u",min_sample_value);
251
+ (void) LogMagickEvent(CoderEvent,GetMagickModule(),
252
+ "Max sample value: %u",max_sample_value);
253
+ (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
254
+ "interpretation: %s",GetImageProperty(image,"tiff:photometric"));
255
+ }
256
+ image->columns=(size_t) width;
257
+ image->rows=(size_t) height;
258
+ image->depth=(size_t) bits_per_sample;
259
+ if (image->debug != MagickFalse)
260
+ (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
261
+ (double) image->depth);
262
+ image->endian=MSBEndian;
263
+ if (endian == FILLORDER_LSB2MSB)
264
+ image->endian=LSBEndian;
265
+ #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
266
+ if (TIFFIsBigEndian(tiff) == 0)
267
+ {
268
+ (void) SetImageProperty(image,"tiff:endian","lsb");
269
+ image->endian=LSBEndian;
270
+ }
271
+ else
272
+ {
273
+ (void) SetImageProperty(image,"tiff:endian","msb");
274
+ image->endian=MSBEndian;
275
+ }
276
+ #endif
277
+ if ((photometric == PHOTOMETRIC_MINISBLACK) ||
278
+ (photometric == PHOTOMETRIC_MINISWHITE))
279
+
280
+
281
+ // ... (24512 more chars)
282
+ ```