Introduction
CodeQL treats source code as data. The build is extracted into a relational database (AST, control flow graph, data flow graph, macros), and bugs are expressed as declarative queries over it. For a security researcher, the payoff is variant analysis: once a bug pattern is understood, it is encoded as a query, and every other instance of it falls out across the codebase instead of being re-found by hand.
GitHub Security Lab CTF 1: SEGV hunt teaches that workflow against a real target, the GNU C Library. The challenge is split into levels, and each level adds one CodeQL concept:
| Step | Concept |
|---|---|
| 0 | Macros |
| 1 | Function calls and range analysis |
| 2 | Guard conditions and local data flow |
| 3 | Composing predicates |
| 4 | Global taint tracking and path queries |
| 5 | Proving the bug with a PoC |
Together they narrow hundreds of alloca call sites down to the few that are actually reachable with attacker-controlled sizes.
All queries in this writeup are run with the CodeQL CLI and use the current module-based data-flow API.
- Challenge: securitylab.github.com/ctf/segv
- Target: bminor/glibc @
3332218
Step 0: Finding the alloca macro
Question 0.0
Task: alloca is a macro. Find the definition of this macro and the name of the function that it expands to.
Approach: Macros are not functions in the CodeQL model. They live in the Macro class, which exposes the name, body and location of every #define the preprocessor saw during the build.
Query (q00_alloca_macro.ql):
import cpp
from Macro mwhere m.getName() = "alloca"select m, m.getBody(), m.getFile().getRelativePath(), m.getLocation().getStartLine()Result:

Answer: alloca expands to the GCC builtin __builtin_alloca.
Notes:
stdlib/alloca.hholds the canonical function-like definition. The other four are object-like copies inside#ifdef __GNUC__blocks in files shared with gnulib and GMP.- The non-GCC fallbacks (
_allocafor MSVC,#pragma allocafor AIX) don’t appear, because the preprocessor skipped those branches during extraction. CodeQL only sees code as it was actually compiled. __builtin_allocais a compiler builtin, not a macro.
Step 1: Finding calls to alloca and filtering small allocations
Question 1.0
Task: Find all the calls to alloca (using the function name that you found in step 0).
Approach: After macro expansion, every alloca(x) in the source becomes a call to __builtin_alloca(x), so a FunctionCall whose target has that name catches them all.
Query (q10_alloca_calls.ql):
import cpp
from FunctionCall fcwhere fc.getTarget().getName() = "__builtin_alloca"select fc, fc.getFile().getRelativePath(), fc.getLocation().getStartLine()Result:
383 calls to __builtin_alloca in the table. However, count() gives 386: 3 calls are in /usr/include/c++/8/ext/string_conversions.h:105, a system header outside the database’s source root, so getRelativePath() has no value and their rows are dropped.

q10_alloca_calls.ql: Evaluation completed (955ms).| fc | col1 | col2 |+--------------------------+------------------------------+------+| call to __builtin_alloca | nss/nss_files/files-ethers.c | 59 || call to __builtin_alloca | argp/argp-help.c | 1588 || call to __builtin_alloca | crypt/sha512-crypt.c | 247 || call to __builtin_alloca | elf/dl-load.c | 1773 || call to __builtin_alloca | iconv/gconv_conf.c | 565 || call to __builtin_alloca | posix/getopt.c | 253 || call to __builtin_alloca | stdlib/setenv.c | 186 || ... | ... | ... |
(7 of 383 rows shown)Shutting down query evaluator.Notes:
- The same
file:lineoften appears more than once. CodeQL extracts every compilation, not every file, and glibc builds many sources more than once:vfprintf-internal.c/vfscanf-internal.c: narrow, wide andlong doublevariantsdl-load.c,dl-deps.c,getaddrinfo.c,glob.c: compiled into bothld.soandlibcmpa.c: pulled in by several math builds Each compilation yields a distinctFunctionCallentity. Selecting only strings and integers (nofc) collapses the duplicates, because QL results are sets.
Question 1.1
Task: Use upperBound and lowerBound predicates from the SimpleRangeAnalysis library to filter out results which are safe because the allocation size is small. You can classify the allocation size as small if it is less than 65536. But don’t forget that negative sizes are very dangerous.
Approach: Range analysis computes conservative integer bounds for an expression. A call is kept (potentially dangerous) if the size can reach 65536 or above, or can be negative.
The lower bound is checked on the unconverted argument. Once the size is implicitly converted to size_t, a negative int turns into a huge unsigned value, and that hides the very case we care about.
Query (q11_large_alloca.ql):
import cppimport semmle.code.cpp.rangeanalysis.SimpleRangeAnalysis
from FunctionCall fc, Expr sizewhere fc.getTarget().getName() = "__builtin_alloca" and size = fc.getArgument(0) and ( upperBound(size.getFullyConverted()) >= 65536 or lowerBound(size) < 0 )select fc, size, lowerBound(size), upperBound(size.getFullyConverted())Result:

| fc | size | col2 | col3 |+--------------------------+--------------------+------+-----------------------+| call to __builtin_alloca | size | 0.0 | 1.8446744073709552E19 || call to __builtin_alloca | num_pattern_levels | 0.0 | 1.8446744073709552E19 || call to __builtin_alloca | ... + ... | 0.0 | 1.8446744073709552E19 || call to __builtin_alloca | ... * ... | 0.0 | 1.8446744073709552E19 || call to __builtin_alloca | key_len | 0.0 | 1.8446744073709552E19 || call to __builtin_alloca | salt_len | 0.0 | 1.8446744073709552E19 || ... | ... | ... | ... |
(6 of 283 rows shown; col2 = lowerBound, col3 = upperBound)Notes:
1.8446744073709552E19is 2^64, the full range ofsize_t. It is not a measured value: range analysis could not bound the expression, so it falls back to the full range of the type.- Range analysis is intra-procedural and conservative. An “unbounded” result doesn’t mean the call is exploitable, only that it can’t be proven safe this way.
Step 2: Filtering calls guarded by __libc_use_alloca
Question 2.0
Task: Find all calls to __libc_use_alloca.
Query (q20_use_alloca_calls.ql):
import cpp
from FunctionCall fcwhere fc.getTarget().getName() = "__libc_use_alloca"select fc, fc.getFile().getRelativePath(), fc.getLocation().getStartLine()Result:
60 calls to __libc_use_alloca, at 35 unique file:line locations.

| fc | col1 | col2 |+---------------------------+-------------------------------------------+------+| call to __libc_use_alloca | crypt/md5-crypt.c | 118 || call to __libc_use_alloca | iconv/iconv_open.c | 38 || call to __libc_use_alloca | posix/getopt.c | 252 || call to __libc_use_alloca | stdlib/setenv.c | 184 || call to __libc_use_alloca | sysdeps/posix/getaddrinfo.c | 2292 || call to __libc_use_alloca | sysdeps/unix/sysv/linux/setsourcefilter.c | 38 || ... | ... | ... |
(6 of 60 rows shown)Notes:
- There are 60 calls to
__libc_use_allocaagainst 383 calls toalloca. - The 60 rows collapse to 35 locations for the same reason as in Q1.0: some files are compiled more than once.
vfprintf-internal.calone accounts for 28 rows (narrow, wide andlong doublebuilds).
Question 2.1
Task: Find all guard conditions where the condition is a call to __libc_use_alloca.
Approach: A GuardCondition is an expression that decides whether a basic block is entered, such as the condition of an if, a loop, or a ternary. The simplest case is when the call itself is the guard.
Query (q21_guard_direct.ql):
import cppimport semmle.code.cpp.controlflow.Guards
from GuardCondition g, FunctionCall usewhere use.getTarget().getName() = "__libc_use_alloca" and g = useselect g, g.getFile().getRelativePath(), g.getLocation().getStartLine()Result:
60 guard conditions, the same 60 calls as in Q2.0.

| g | col1 | col2 |+---------------------------+-------------------------------------------+------+| call to __libc_use_alloca | crypt/md5-crypt.c | 118 || call to __libc_use_alloca | posix/getopt.c | 252 || call to __libc_use_alloca | stdlib/setenv.c | 184 || call to __libc_use_alloca | sysdeps/posix/getaddrinfo.c | 2292 || call to __libc_use_alloca | sysdeps/unix/sysv/linux/setsourcefilter.c | 38 || call to __libc_use_alloca | time/getdate.c | 159 || ... | ... | ... |
(6 of 60 rows shown)Notes:
- The current
GuardConditionis computed on CodeQL’s IR, not on the source syntax, so a call counts as a guard when its result decides a branch, even if it isn’t written directly insideif (...). 21 of the 60 calls are not anifor?:condition, yet they are matched, for examplesysdeps/unix/sysv/linux/setsourcefilter.c:38.
Question 2.2
Task: Sometimes the result of __libc_use_alloca is assigned to a variable, which is then used as the guard condition. For example, this happens at setsourcefilter.c:38-41. Enhance your query, using local dataflow, so that it also finds this guard condition.
Approach: DataFlow::localExprFlow(src, sink) holds when the value of src reaches sink within a single function, for example through an assignment to a local variable that is later read.
Query (q22_guard_localflow.ql):
import cppimport semmle.code.cpp.controlflow.Guardsimport semmle.code.cpp.dataflow.new.DataFlow
from GuardCondition g, FunctionCall usewhere use.getTarget().getName() = "__libc_use_alloca" and DataFlow::localExprFlow(use, g)select g, use, g.getFile().getRelativePath(), g.getLocation().getStartLine()Result:
83 guards: the 60 calls from Q2.1 plus 23 new guards where the result reaches the condition through a local variable.

| g | use | col2 | col3 |+---------------------------+---------------------------+-------------------------------------------+------+| call to __libc_use_alloca | call to __libc_use_alloca | sysdeps/unix/sysv/linux/setsourcefilter.c | 38 || use_alloca | call to __libc_use_alloca | sysdeps/unix/sysv/linux/setsourcefilter.c | 41 || use_alloca | call to __libc_use_alloca | sysdeps/unix/sysv/linux/setsourcefilter.c | 67 || tocode_usealloca | call to __libc_use_alloca | iconv/iconv_open.c | 39 || alloca_key | call to __libc_use_alloca | nscd/nscd_getserv_r.c | 95 || use_alloca | call to __libc_use_alloca | stdlib/setenv.c | 185 || ... | ... | ... | ... |
(6 of 83 rows shown)Notes:
- The CTF’s example is now found: in
setsourcefilter.c, the call on line 38 is stored inuse_alloca, and the variable is the guard on line 41. localExprFlowis reflexive (every expression flows to itself), so the 60 direct guards from Q2.1 are still in the result, withgandusebeing the same call. The 23 new rows are the ones wheregis a variable read.
Question 2.3
Task: Sometimes the call to __libc_use_alloca is wrapped in a call to __builtin_expect. For example, this happens at setenv.c:185. Enhance your query so that it also finds this guard condition.
Approach: __builtin_expect(expr, hint) returns expr unchanged; it only gives the compiler a branch-prediction hint. Treat it as transparent by recursing into its first argument. Defining a recursive predicate now makes it easy to add more wrappers in the next question.
Query (q23_guard_expect.ql):
import cppimport semmle.code.cpp.controlflow.Guardsimport semmle.code.cpp.dataflow.new.DataFlow
predicate useAllocaResult(Expr e) { exists(FunctionCall use | use.getTarget().getName() = "__libc_use_alloca" and DataFlow::localExprFlow(use, e) ) or exists(FunctionCall exp | exp = e | exp.getTarget().getName() = "__builtin_expect" and useAllocaResult(exp.getArgument(0)) )}
from GuardCondition gwhere useAllocaResult(g)select g, g.getFile().getRelativePath(), g.getLocation().getStartLine()Result:
85 guards: the 83 from Q2.2 plus 2 new ones, where the guard is the __builtin_expect wrapper itself.

| g | col1 | col2 |+---------------------------+-------------------------------------------+------+| call to __libc_use_alloca | nptl/pthread_create.c | 642 || call to __builtin_expect | nptl/pthread_create.c | 642 || call to __libc_use_alloca | stdlib/setenv.c | 184 || use_alloca | stdlib/setenv.c | 185 || call to __builtin_expect | stdlib/setenv.c | 185 || use_alloca | sysdeps/unix/sysv/linux/setsourcefilter.c | 41 || ... | ... | ... |
(6 of 85 rows shown)Notes:
- The two new rows are
__builtin_expectcalls that are themselves guard conditions:setenv.c:185(the CTF’s example): the call result is stored inuse_allocaon line 184, and theifon line 185 wraps the variable in__builtin_expect(via__glibc_likely). This one combines Q2.2 (variable) and Q2.3 (wrapper).pthread_create.c:642: here the wrapper sits directly around the call, on the same line.
- The CTF cites
setenv.c:185while Q2.0 found the call on line 184. Both are right: the call initialises the variable on 184, and the wrapped condition is on 185. - Q2.2 already listed
use_allocaatsetenv.c:185(the IR sees through__builtin_expectto the variable). This query adds the wrapper expression as a guard in its own right, which is what Q2.5 needs when it asks which branch of this exact condition protects thealloca. - Evaluation took 2.4s, down from 1m54s in Q2.2. The IR built for the first data-flow query is cached in the database and reused.
Question 2.4
Task: Sometimes the result of __libc_use_alloca is negated with the ! operator. For example, this happens at getaddrinfo.c:2291-2293. Enhance your query so that it can also handle negations.
Approach: Negation flips the meaning of the guard. In if (!__libc_use_alloca(n)) buf = malloc(n); else buf = alloca(n);, alloca sits on the false branch. Matching the ! alone is not enough; the query must also track polarity, meaning which branch is the safe one.
useAllocaResult(e, polarity) reads as: e is true exactly when __libc_use_alloca returned polarity. Every ! flips the polarity.
Query (q24_guard_negation.ql):
import cppimport semmle.code.cpp.controlflow.Guardsimport semmle.code.cpp.dataflow.new.DataFlow
predicate useAllocaResult(Expr e, boolean polarity) { exists(FunctionCall use | use.getTarget().getName() = "__libc_use_alloca" and DataFlow::localExprFlow(use, e) ) and polarity = true or exists(NotExpr n | n = e | useAllocaResult(n.getOperand(), polarity.booleanNot())) or exists(FunctionCall exp | exp = e | exp.getTarget().getName() = "__builtin_expect" and useAllocaResult(exp.getArgument(0), polarity) )}
from GuardCondition g, boolean polaritywhere useAllocaResult(g, polarity)select g, polarity, g.getFile().getRelativePath(), g.getLocation().getStartLine()Result:
109 guards: the 85 from Q2.3 (all polarity = true) plus 24 negated guards with polarity = false.

| g | polarity | col2 | col3 |+---------------------------+----------+-------------------------------------------+------+| call to __libc_use_alloca | true | sysdeps/posix/getaddrinfo.c | 2292 || ! ... | false | sysdeps/posix/getaddrinfo.c | 2292 || use_alloca | true | sysdeps/unix/sysv/linux/setsourcefilter.c | 67 || ! ... | false | sysdeps/unix/sysv/linux/setsourcefilter.c | 67 || call to __builtin_expect | false | stdlib/setenv.c | 210 || ! ... | false | stdlib/setenv.c | 210 || ... | ... | ... | ... |
(6 of 109 rows shown)Notes:
polarityreads as: this guard is true exactly when__libc_use_allocareturnedpolarity. Afalserow means the guard is true when the size was rejected.getaddrinfo.c:2292is the CTF’s example: the inner call is atruerow and the! ...expression around it is afalserow.- The cases compose. At
setenv.c:210the variableuse_allocaistrue, the!around it isfalse, and the__builtin_expectaround that is alsofalse: the polarity flips once at the!and passes unchanged through the wrapper.
Question 2.5
Task: Find calls to alloca that are safe because they are guarded by a call to __libc_use_alloca.
Approach: GuardCondition.controls(block, branch) holds when block can only be reached if the guard evaluated to branch. An alloca is safe when its basic block is controlled by the branch on which __libc_use_alloca returned true. Given the definition of polarity above, that branch is exactly polarity.
Query (q25_guarded_alloca.ql):
import cppimport semmle.code.cpp.controlflow.Guardsimport semmle.code.cpp.dataflow.new.DataFlow
predicate useAllocaResult(Expr e, boolean polarity) { exists(FunctionCall use | use.getTarget().getName() = "__libc_use_alloca" and DataFlow::localExprFlow(use, e) ) and polarity = true or exists(NotExpr n | n = e | useAllocaResult(n.getOperand(), polarity.booleanNot())) or exists(FunctionCall exp | exp = e | exp.getTarget().getName() = "__builtin_expect" and useAllocaResult(exp.getArgument(0), polarity) )}
predicate isGuarded(FunctionCall alloca) { exists(GuardCondition g, boolean polarity | useAllocaResult(g, polarity) and g.controls(alloca.getBasicBlock(), polarity) )}
from FunctionCall allocawhere alloca.getTarget().getName() = "__builtin_alloca" and isGuarded(alloca)select alloca, alloca.getFile().getRelativePath(), alloca.getLocation().getStartLine()Result:
28 alloca calls are protected by a __libc_use_alloca guard.

| alloca | col1 | col2 |+--------------------------+-----------------------------------------------+------+| call to __builtin_alloca | crypt/md5-crypt.c | 119 || call to __builtin_alloca | crypt/sha256-crypt.c | 151 || call to __builtin_alloca | crypt/sha256-crypt.c | 248 || call to __builtin_alloca | crypt/sha512-crypt.c | 151 || call to __builtin_alloca | crypt/sha512-crypt.c | 247 || call to __builtin_alloca | iconv/iconv_open.c | 40 || call to __builtin_alloca | iconv/iconv_open.c | 55 || call to __builtin_alloca | nptl/pthread_create.c | 643 || call to __builtin_alloca | nscd/grpcache.c | 231 || call to __builtin_alloca | nscd/nscd_getserv_r.c | 96 || call to __builtin_alloca | nscd/nscd_getserv_r.c | 255 || call to __builtin_alloca | nscd/nscd_netgroup.c | 174 || call to __builtin_alloca | posix/getopt.c | 253 || call to __builtin_alloca | stdio-common/fxprintf.c | 47 || call to __builtin_alloca | stdio-common/vfprintf-internal.c | 1969 || call to __builtin_alloca | stdio-common/vfprintf-internal.c | 1969 || call to __builtin_alloca | stdio-common/vfprintf-internal.c | 1969 || call to __builtin_alloca | stdio-common/vfprintf-internal.c | 1969 || call to __builtin_alloca | stdlib/setenv.c | 186 || call to __builtin_alloca | sysdeps/posix/getaddrinfo.c | 2303 || call to __builtin_alloca | sysdeps/posix/getaddrinfo.c | 2303 || call to __builtin_alloca | sysdeps/unix/sysv/linux/check_native.c | 92 || call to __builtin_alloca | sysdeps/unix/sysv/linux/getipv4sourcefilter.c | 41 || call to __builtin_alloca | sysdeps/unix/sysv/linux/getsourcefilter.c | 103 || call to __builtin_alloca | sysdeps/unix/sysv/linux/ifaddrs.c | 145 || call to __builtin_alloca | sysdeps/unix/sysv/linux/setipv4sourcefilter.c | 41 || call to __builtin_alloca | sysdeps/unix/sysv/linux/setsourcefilter.c | 42 || call to __builtin_alloca | time/getdate.c | 160 |Notes:
- All three CTF example cases are protected:
setsourcefilter.c:42(variable),setenv.c:186(__builtin_expect) andgetaddrinfo.c:2303(negation: theallocais on the false branch of the!guard). - Not every check protects an
alloca.fnmatch_loop.c,printf_fp.c,putenv.c,glob.candgetsysstats.ccall__libc_use_alloca(Q2.0) but have no protectedallocahere, and invfprintf-internal.conly theallocaon line 1969 is protected. - Using
controls(block, _)(ignoring polarity) would also mark anallocaon the rejecting branch as safe. That over-approximates “safe” and can hide exactly the bugs we are hunting.
Step 3: Unsafe calls to alloca
Question 3.0
Task: Use your answer from step 2 to enhance your query from step 1 by filtering out calls to alloca that are safe because they are guarded by a call to __libc_use_alloca.
Query (q30_unsafe_alloca.ql):
import cppimport semmle.code.cpp.rangeanalysis.SimpleRangeAnalysisimport semmle.code.cpp.controlflow.Guardsimport semmle.code.cpp.dataflow.new.DataFlow
predicate isLargeOrNegative(FunctionCall alloca) { exists(Expr size | size = alloca.getArgument(0) | upperBound(size.getFullyConverted()) >= 65536 or lowerBound(size) < 0 )}
predicate useAllocaResult(Expr e, boolean polarity) { exists(FunctionCall use | use.getTarget().getName() = "__libc_use_alloca" and DataFlow::localExprFlow(use, e) ) and polarity = true or exists(NotExpr n | n = e | useAllocaResult(n.getOperand(), polarity.booleanNot())) or exists(FunctionCall exp | exp = e | exp.getTarget().getName() = "__builtin_expect" and useAllocaResult(exp.getArgument(0), polarity) )}
predicate isGuarded(FunctionCall alloca) { exists(GuardCondition g, boolean polarity | useAllocaResult(g, polarity) and g.controls(alloca.getBasicBlock(), polarity) )}
from FunctionCall allocawhere alloca.getTarget().getName() = "__builtin_alloca" and isLargeOrNegative(alloca) and not isGuarded(alloca)select alloca, alloca.getFile().getRelativePath(), alloca.getLocation().getStartLine()Result:
254 potentially unsafe alloca calls: unbounded size (Q1.1) and no __libc_use_alloca guard (Q2.5).

| alloca | col1 | col2 |+--------------------------+-----------------------------+------+| call to __builtin_alloca | crypt/md5-crypt.c | 136 || call to __builtin_alloca | elf/dl-load.c | 1773 || call to __builtin_alloca | iconv/gconv_conf.c | 323 || call to __builtin_alloca | iconv/gconv_conf.c | 454 || call to __builtin_alloca | iconv/gconv_conf.c | 465 || call to __builtin_alloca | iconv/gconv_conf.c | 565 || call to __builtin_alloca | sysdeps/posix/getaddrinfo.c | 2303 || ... | ... | ... |
(7 of 254 rows shown)Notes:
- Compare this with Q1.1 (283), not Q2.5: 26 of the 283 unbounded calls are guarded (Q2.5), and the 3 system-header calls from Q1.0 have no file path, so they are not in this table, leaving 254. For example,
md5-crypt.c:119(guarded) is gone, whilemd5-crypt.c:136in the same file remains. getaddrinfo.c:2303is compiled three times (Q1.0). Two copies are guarded (Q2.5), and the remaining copy appears here.
Step 4: Taint tracking from fopen to alloca
Question 4.0
Task: Find calls to fopen. (Be aware that fopen is another macro.)
Approach: Same technique as Step 0. Code built inside libc calls fopen through the internal name _IO_new_fopen (see include/stdio.h), while programs and separately built modules call fopen directly. Matching every function whose name ends in fopen covers both.
Query (q40_fopen_calls.ql):
import cpp
from FunctionCall fcwhere fc.getTarget().getName().matches("%fopen")select fc, fc.getTarget().getName(), fc.getFile().getRelativePath(), fc.getLocation().getStartLine()Result:
80 calls to functions whose name ends in fopen:
| Function | Calls |
|---|---|
fopen | 58 |
_IO_new_fopen | 16 |
_IO_file_fopen | 4 |
iruserfopen | 2 |

| fc | col1 | col2 | col3 |+------------------------+----------------+-----------------------------+------+| call to fopen | fopen | iconv/iconv_prog.c | 443 || call to _IO_new_fopen | _IO_new_fopen | resolv/res_init.c | 558 || call to _IO_file_fopen | _IO_file_fopen | libio/iofopen.c | 75 || call to iruserfopen | iruserfopen | inet/rcmd.c | 528 || call to fopen | fopen | sysdeps/posix/getaddrinfo.c | 1795 || call to _IO_new_fopen | _IO_new_fopen | sysdeps/posix/getaddrinfo.c | 1795 || ... | ... | ... | ... |
(6 of 80 rows shown)Notes:
- Some locations appear more than once, as in Q1.0; for example,
nss/nss_files/files-XXX.c:77appears 10 times. sysdeps/posix/getaddrinfo.c:1795andresolv/res_hconf.c:281each appear once asfopenand once as_IO_new_fopen: the same call site resolves to a different function depending on how the file is compiled.- The pattern matches by name, so
_IO_file_fopenandiruserfopenare included as well asfopenand_IO_new_fopen.
Question 4.1
Task: Write a taint tracking query. The source should be a call to fopen and the sink should be the size argument of an unsafe call to alloca.
Approach: A global (inter-procedural) taint-tracking query, written as a path-problem.
- Source: the
FILE*returned by_IO_new_fopen. - Sink: argument 0 of an unsafe
allocacall (Step 3). - Flow models:
strlen-like functions propagate taint from their argument to their return value;getdelimpropagates taint from the stream to its return value and to the line buffer*lineptr. With the CTF boilerplate’s model (return value only), the query returns 0 results on the currentdataflow.newlibrary; adding*lineptrgives 2.
Query (q41_fopen_to_alloca.ql):
/** * @name 41_fopen_to_alloca_taint * @description Track taint from fopen to alloca. * @kind path-problem * @problem.severity warning * @id cpp/ctf/unsafe-alloca */
import cppimport semmle.code.cpp.rangeanalysis.SimpleRangeAnalysisimport semmle.code.cpp.dataflow.new.TaintTrackingimport semmle.code.cpp.models.interfaces.DataFlowimport semmle.code.cpp.controlflow.Guards
predicate isLargeOrNegative(FunctionCall alloca) { exists(Expr size | size = alloca.getArgument(0) | upperBound(size.getFullyConverted()) >= 65536 or lowerBound(size) < 0 )}
predicate useAllocaResult(Expr e, boolean polarity) { exists(FunctionCall use | use.getTarget().getName() = "__libc_use_alloca" and DataFlow::localExprFlow(use, e) ) and polarity = true or exists(NotExpr n | n = e | useAllocaResult(n.getOperand(), polarity.booleanNot())) or exists(FunctionCall exp | exp = e | exp.getTarget().getName() = "__builtin_expect" and useAllocaResult(exp.getArgument(0), polarity) )}
predicate isGuarded(FunctionCall alloca) { exists(GuardCondition g, boolean polarity | useAllocaResult(g, polarity) and g.controls(alloca.getBasicBlock(), polarity) )}
predicate isUnsafeAlloca(FunctionCall alloca) { alloca.getTarget().getName() = "__builtin_alloca" and isLargeOrNegative(alloca) and not isGuarded(alloca)}
class StrlenFunction extends DataFlowFunction { StrlenFunction() { this.getName().matches("%str%len%") }
override predicate hasDataFlow(FunctionInput i, FunctionOutput o) { i.isParameter(0) and o.isReturnValue() }}
class GetDelimFunction extends DataFlowFunction { GetDelimFunction() { this.getName().matches("%get%delim%") }
override predicate hasDataFlow(FunctionInput i, FunctionOutput o) { i.isParameter(3) and (o.isReturnValue() or o.isParameterDeref(0)) }}
module Config implements DataFlow::ConfigSig { predicate isSource(DataFlow::Node source) { exists(FunctionCall fopen | fopen.getTarget().getName() = "_IO_new_fopen" and source.asExpr() = fopen ) }
predicate isSink(DataFlow::Node sink) { exists(FunctionCall alloca | isUnsafeAlloca(alloca) and sink.asExpr() = alloca.getArgument(0) ) }}
module Flow = TaintTracking::Global<Config>;
import Flow::PathGraph
from Flow::PathNode source, Flow::PathNode sinkwhere Flow::flowPath(source, sink)select sink.getNode(), source, sink, "alloca size is read from a file opened by $@.", source.getNode(), "this fopen call"Run it with database analyze to get SARIF that contains the full paths:
codeql database analyze ../bminor_glibc_3332218 q41_fopen_to_alloca.ql --format=sarif-latest --output=q41.sarif --rerun
Result:
2 paths from fopen to an unsafe alloca size.

| # | Source (fopen) | Sink (alloca size) | Size expression |
|---|---|---|---|
| 1 | iconv/gconv_conf.c:369:14 | iconv/gconv_conf.c:323:25 | ... + ... |
| 2 | inet/rcmd.c:483:13 | nscd/nscd_helper.c:178:24 | real_sizeof_reqdata |
Notes:
- Of the 254 unsafe
allocacalls from Q3.0, 2 take a size argument tainted by data read from a stream opened withfopen.
References
Wojtek
Ever since I was young, I’ve been fascinated by how computers work. Today I’m a security engineer who finds and exploits vulnerabilities here and there. I specialize in application security and AI security, breaking modern apps and the LLM-powered systems built on top of them.
