Skip to content

Commit e1438e5

Browse files
Merge pull request #60 from hbgit/fix/target-coverage-warning
fix(reachability): announce a target that is never called (finding B)
2 parents 05a5535 + 3526ae5 commit e1438e5

5 files changed

Lines changed: 245 additions & 15 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,7 @@ jobs:
364364
bash tests/integration/test_modes.sh
365365
bash tests/integration/test_add_invariants.sh
366366
bash tests/integration/test_test_suite_emission.sh
367+
bash tests/integration/test_target_coverage.sh
367368
'
368369
369370
# ===========================================================

‎docs/TESTCOMP-CHECKLIST.md‎

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ Estado das frentes do [plano de desenvolvimento](../.opencode/Plano%20de%20desen
44
(local, fora do repositório). Este arquivo é o índice vivo: cada item aponta para a
55
evidência que sustenta o estado declarado.
66

7-
**Última atualização:** 2026-08-16
7+
**Última atualização:** 2026-08-22
88

99
## Legenda
1010

@@ -47,25 +47,31 @@ disso mudam o quadro, e **nenhuma das duas é explosão de caminhos**:
4747
não resolvidas**, e 575 se perdem. Quatro fontes de entrada ficam em exatamente
4848
**50,0%** de acerto entre os decididos — assinatura de provar a variante segura e
4949
errar a vulnerável.
50-
2. O **achado K, já investigado**: o timeout descarta violações que a ferramenta
51-
já encontrou e gravou em disco. `isTimeout()` tem precedência sobre a
52-
propriedade violada, então um FALSE legítimo vira UNKNOWN só porque o
50+
2. O **achado K, corrigido**: o timeout descartava violações que a ferramenta
51+
já tinha encontrado e gravado em disco. `isTimeout()` tinha precedência sobre
52+
a propriedade violada, então um FALSE legítimo virava UNKNOWN só porque o
5353
orçamento acabou *depois* do trabalho estar feito.
5454

55-
**Recomendação de sequência:** medir quantos UNKNOWN do v5 são violações
56-
descartadas pelo achado K antes de comprometer qualquer pessoa-semana em
57-
slicing. É uma pergunta respondível com os dados que já temos.
55+
**O que a medição do v6 respondeu.** No CASTLE, a correção do K mudou **zero**
56+
vereditos — e o motivo não é que K fosse pequeno, é que o **achado B o mascara**:
57+
dos 22 casos indecididos no v5 que rerodaram, 20 usam o modo degenerado, onde
58+
nenhuma violação chega a ser registrada e portanto K não tem o que resgatar.
59+
Medir K exige um corpus onde os modos sejam reais — o Juliet, ainda em execução.
60+
61+
**Recomendação de sequência:** corrigir o achado B antes de comprometer qualquer
62+
pessoa-semana em slicing. Ele bloqueia 45% das execuções do CASTLE *e* impede
63+
medir o efeito de K nesse corpus.
5864

5965
---
6066

6167
## Frentes fora do plano original
6268

6369
| Frente | Estado | Evidência |
6470
|---|---|---|
65-
| **Invariantes (`--add-invariants`)** | ✅ Fase A + B | Clam `dev16`, `-DENABLE_CLAM=ON`, **desligado por default**. Ver [a revisão da dependência](reports/2026-08-16-crabllvm-review.md) |
71+
| **Invariantes (`--add-invariants`)** | ✅ **vivo e provado em CI** | Clam `dev16` pinado, `-DENABLE_CLAM=ON`, **desligado por default**. O job `Invariants (Clam)` passou de `ABSENT` para `PRESENT (exit 0)` quando a imagem republicou; a sonda do Dockerfile confirma `Clam injects invariants: OK`. Issue #54 fechada. Ver [a revisão da dependência](reports/2026-08-16-crabllvm-review.md) |
6672
| Invariantes: gate diferencial p/ promover a default | ⬜ | Task 7 do [plano de revival](superpowers/plans/2026-08-16-add-invariants-revival.md). Depende de rodar sobre corpus real |
6773
| **Baseline CASTLE + Juliet (v5)** | ✅ | PR #55. CASTLE 98,2% precisão, Juliet 90,8% (99,2% descontando artefatos de mapeamento) |
68-
| Corrida v6 (depois/antes) | ⬜ | **Regra de atribuição: invariantes DESLIGADOS na corrida principal**, senão overflow + timeout + amostragem + invariantes ficam conjuntamente não creditáveis |
74+
| Corrida v6 (depois/antes) | 🟡 | **CASTLE fechado** (217/250): precisão 98,2%, recall 74,0%; excluindo o modo degenerado do achado B, recall 79,4%. Juliet: 3 de 4 fatias fechadas, `c` em andamento. **Regra de atribuição: invariantes DESLIGADOS na corrida principal**, senão overflow + timeout + amostragem + invariantes ficam conjuntamente não creditáveis |
6975
| **Alcançabilidade (CWE-843/628/770/835)** | ⬜ | Adiado por decisão. Sob a lente SV-COMP as quatro colapsam em uma: só 835 mapeia para categoria pontuável (Termination), e os wrappers declaram não suportar |
7076

7177
---
@@ -82,16 +88,19 @@ Todos com evidência em [findings](reports/2026-08-12-castle-juliet-findings.md)
8288
| — | `--add-invariants` aceito e ignorado sem rastro na entrada `.bc` (issue #54) | ✅ sai com código 3 |
8389
| — | Invocação legada do Crab: `--llvm-pp-loops` e `--crab-promote-assume` anulavam a injeção | ✅ removidas, medido |
8490
| — | Pass 2 do CASTLE era re-execução byte-idêntica do pass 1 em todo o v5 | ✅ reconhece código 3 |
91+
| **K** | `isTimeout()` descartava violações já encontradas e gravadas: `TARGET-REACHED found` → `Forcing timeout` → `VERIFICATION UNKNOWN`. Disparava em 80% das execuções do Juliet v5 | ✅ resgate restrito a evidência confiável (`c4ef3a355`) |
92+
| — | Imagem: Clam compilava com GCC 11 em vez de clang-16 (o `ENV CC` está 88 linhas abaixo do `RUN`), e GCC rejeita o que o clang só avisa. **A receita nunca compilou** | ✅ compiladores nomeados no `CLAM_CFG` (#58) |
93+
| — | `Dockerfile.dev` só era compilado **depois** do merge, então um Dockerfile inválido chegava à `develop` sem nada poder barrá-lo | ✅ o workflow de publish roda em PRs que tocam o arquivo, com `push: false` (#58) |
94+
| — | Clam e suas três dependências vinham de branches móveis; `crab@dev` mudou em 21/08 | ✅ pinados por SHA como `ARG` (#59) |
8595

8696
## Defeitos abertos
8797

8898
| # | Defeito | Prioridade |
8999
|---|---|---|
90-
| **K** | **Investigado.** `isTimeout()` descarta violações já encontradas e gravadas: `TARGET-REACHED found` → `Forcing timeout` → `VERIFICATION UNKNOWN`. Correção proposta, não aplicada (muda a contagem UNKNOWN→FALSE de todo o baseline) | **Alta** — mecanismo barato de inflar UNKNOWN, sem relação com explosão de caminhos |
91100
| **K2** | Custo por leitura nondet cresce muito: 1 → 21 → 114 → 861 caminhos parciais para 2 → 4 leituras. Nenhum `.err`, então não são erros | Média — segundo fio a puxar |
92101
| **G** | `main()` descarta o retorno de `map2check_execution()`; código de saída nunca reflete a análise | Média |
93-
| **B** | Modo reachability degenerado com `target-function-name main` | Média |
94-
| — | Garantia de ordenação do corpus depende de um único programa (`two_guards.c`) | Baixa — some quando K for corrigido |
102+
| **B** | **Medido no v6.** Modo reachability degenerado com `target-function-name main`: 98 de 217 execuções, **zero vereditos FALSE**, 59 programas vulneráveis, 0 detectados. 12 TN e 5 FN pontuados sobre um oráculo que só sabe responder "correto" | **Alta** — 🟡 o caso trivial agora se anuncia (`TargetPass`); falta corrigir o mapeamento CWE→modo do harness, o que **muda a pontuação do baseline** e por isso espera o v6 fechar |
103+
| — | Garantia de ordenação do corpus depende de um único programa (`two_guards.c`) | Baixa — K já foi corrigido; falta reconferir se ainda vale |
95104
| — | `CLAUDE.md` linka um `.clang-format` que não existe | Baixa |
96105

97106
---
@@ -101,9 +110,9 @@ Todos com evidência em [findings](reports/2026-08-12-castle-juliet-findings.md)
101110
| O quê | Contagem |
102111
|---|---|
103112
| `ctest` (unitários) | 8 |
104-
| Integração | 78 asserções em 7 scripts |
113+
| Integração | 82 asserções em 8 scripts |
105114
| Conformidade Test-Comp | 6 programas |
106-
| Jobs de CI | 9, todos verdes na PR #56 |
115+
| Jobs de CI | 10, todos verdes na PR #59 (o 10º builda a imagem no próprio PR) |
107116

108117
Gates que provei que **conseguem falhar** (um gate nunca visto vermelho não protege
109118
ninguém): o do TestCov, invertendo a ordem dos `<input>` no emissor; e o de

‎docs/reports/2026-08-12-castle-juliet-findings.md‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@
105105
|---|---|---|---|
106106
| A | Truncamento 32-bit no allocation log | `AllocationLog.c` | ✅ corrigido (§1.3) |
107107
| A2 | Assinatura i64/i32 + ponto de inserção dos binops (overflow runtime quebrado) | `OperationsFunctions.hpp`, `OverflowPass.cpp` | ✅ corrigido (§1.9) |
108-
| B | `--target-function --target-function-name main` é **degenerado**: TargetPass instrumenta chamadas *para* `main` (que ninguém faz) e `AnalysisModeNone` sempre retorna "correct" | `TargetPass.cpp`, `AnalysisModeNone.c` | aberto (afeta 253/362/369/628/674/770/835) |
108+
| B | `--target-function --target-function-name main` é **degenerado**: TargetPass instrumenta chamadas *para* `main` (que ninguém faz) e `AnalysisModeNone` sempre retorna "correct" | `TargetPass.cpp`, `AnalysisModeNone.c` | **medido no v6** (§2.1) — 🟡 o caso trivial agora se anuncia; o mapeamento do harness continua aberto |
109109
| C | `divisionByZeroError()` era TODO no-op | `AnalysisModeOverflow.c:86` | ✅ corrigido (§1.8) |
110110
| D | Overhead "fuzzer-first": default roda LibFuzzer (60s) antes do KLEE | `map2check.cpp:498-508` | aberto (G5 — lean reachability via `--nondet-generator symex`) |
111111
| E | 33/250 CASTLE não compilam por headers externos (`mysql.h`, `openssl/*.h`) | imagem Docker | aberto (maioria CWE-89/798, fora de escopo) |
@@ -117,6 +117,65 @@
117117
| K | **Investigado e corrigido.** O timeout descartava violações já encontradas e gravadas: `isTimeout()` tinha precedência sobre a propriedade violada. Disparava em 80% das execuções do Juliet v5 | `map2check.cpp` | ✅ corrigido — resgate restrito a evidência confiável |
118118
| K2 | Custo por leitura nondet cresce muito: 1 → 21 → 114 → 861 caminhos parciais para 2 → 4 leituras, sem nenhum `.err` | KLEE + instrumentação | aberto |
119119

120+
### Achado B, medido: um oráculo que só sabe dizer "correto"
121+
122+
O achado B foi registrado em agosto como uma suspeita estrutural: `TargetPass`
123+
instrumenta *call sites* cujo callee tem o nome pedido, e um programa não chama
124+
o próprio `main`, logo nada é instrumentado. O baseline v6 do CASTLE permite
125+
sair da suspeita e medir.
126+
127+
**98 das 217 execuções (45%) rodaram nesse modo.** O que elas produziram:
128+
129+
| veredito | n |
130+
|---|---|
131+
| TRUE | 57 |
132+
| TIMEOUT | 22 |
133+
| UNKNOWN | 10 |
134+
| ERROR | 9 |
135+
| **FALSE-\*** | **0** |
136+
137+
Nenhum FALSE. Não é escassez: nos outros modos, as mesmas 217 execuções
138+
produzem 49 vereditos FALSE-\* (`FALSE-DEREF` 21, `FALSE-FREE` 12, `FALSE` 10,
139+
`FALSE-DIVBYZERO` 6, `FALSE-MEMCLEANUP` 6). O modo degenerado é o único que
140+
nunca acusa nada.
141+
142+
**59 dos 98 programas eram sabidamente vulneráveis. Zero foram detectados.**
143+
144+
O efeito na pontuação tem dois lados, e o segundo é o mais incômodo:
145+
146+
| | efeito |
147+
|---|---|
148+
| 5 FN | perdas garantidas — o oráculo não podia acertar |
149+
| **12 TN** | **crédito por acertos que um oráculo que só diz "correto" não tinha como errar** |
150+
151+
Descontando o modo inteiro, o CASTLE v6 sai de **recall 74,0% para 79,4%**
152+
(precisão fica em 98,2%: nenhum TP ou FP vem desse modo — ele não produz
153+
nenhum dos dois). Ou seja, B **não** infla precisão; ele **deprime recall** e
154+
**infla TN**.
155+
156+
Os outros 61 casos do modo são CWEs que o harness já declara fora de escopo e
157+
pontua N/A, então não distorcem métrica alguma. Vale corrigir o registro: uma
158+
leitura anterior atribuiu os 61 N/A ao achado B — eles são N/A por decisão de
159+
escopo, não por causa dele. O custo real de B são os 17 casos pontuados.
160+
161+
#### O que foi feito e o que falta
162+
163+
Zero call sites **não é um erro**. Se um programa realmente nunca chama
164+
`reach_error`, então "o erro é inalcançável" é a resposta certa e TRUE é
165+
legítimo. O defeito é que esse TRUE é **indistinguível**, na saída, de um TRUE
166+
conquistado explorando o programa.
167+
168+
Então a correção do lado da ferramenta é de visibilidade, não de veredito:
169+
`TargetPass` agora varre o módulo uma vez e, se o alvo não é chamado em lugar
170+
nenhum, avisa dizendo o que o veredito vale ali. Coberto por
171+
`tests/integration/test_target_coverage.sh` (4 asserções), que exige as duas
172+
direções — o alvo real fica em silêncio, o alvo ausente se anuncia.
173+
174+
O que **falta** é o lado do harness: o mapeamento CWE→modo usa
175+
`--target-function-name main` como default de escape para 13 CWEs. Corrigi-lo
176+
muda a pontuação do baseline, então espera o v6 fechar — trocar o critério no
177+
meio da corrida é exatamente o que torna duas medições incomparáveis.
178+
120179
### Achado K, investigado: o timeout descarta violações já encontradas
121180

122181
**Sintoma.** Ao montar o corpus de conformidade do Test-Comp, o programa mais

‎modules/backend/pass/TargetPass.cpp‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,67 @@
1313
#include <llvm/Passes/PassBuilder.h>
1414
#include <llvm/Passes/PassPlugin.h>
1515

16+
namespace {
17+
18+
/// Counts the call sites TargetPass will match, across the whole module.
19+
unsigned countTargetCallSites(const llvm::Module& M, llvm::StringRef Name) {
20+
unsigned sites = 0;
21+
for (const Function& Fn : M) {
22+
for (const BasicBlock& BB : Fn) {
23+
for (const llvm::Instruction& I : BB) {
24+
const CallInst* callInst = dyn_cast<CallInst>(&I);
25+
if (callInst == nullptr) continue;
26+
const Function* callee = callInst->getCalledFunction();
27+
if (callee == nullptr) {
28+
callee = dyn_cast<Function>(
29+
callInst->getCalledOperand()->stripPointerCasts());
30+
}
31+
if (callee != nullptr && callee->getName() == Name) ++sites;
32+
}
33+
}
34+
}
35+
return sites;
36+
}
37+
38+
} // namespace
39+
1640
PreservedAnalyses TargetPass::run(Function& F,
1741
llvm::FunctionAnalysisManager& AM) {
1842
llvm::errs() << "Running TargetPass with: " << this->targetFunctionName;
1943

44+
// Reported once per module, not once per function. This is a function pass,
45+
// so there is no module-entry hook to hang it on; opt runs once per
46+
// invocation, which makes a local static the honest way to say "first
47+
// function we see".
48+
//
49+
// A target that is never called is NOT an error. If a program genuinely
50+
// never calls reach_error, then "the error is unreachable" is the correct
51+
// answer and TRUE is right. What is wrong is that such a TRUE looks exactly
52+
// like a TRUE earned by exploring the program, and nothing in the output
53+
// tells them apart.
54+
//
55+
// That indistinguishability is the whole of finding B. The CASTLE harness
56+
// mapped seven CWEs onto `--target-function-name main`; TargetPass looks for
57+
// calls TO main, a program does not call its own entry point, so zero sites
58+
// were instrumented. Measured on the v6 baseline: 98 of 217 runs went through
59+
// that mode and produced TRUE, TIMEOUT or ERROR -- not one FALSE among them,
60+
// on 59 programs known to be vulnerable. Twelve of those runs were scored as
61+
// true negatives, credit for answers an oracle that can only say "correct"
62+
// could not have failed to give.
63+
static bool announcedTargetCoverage = false;
64+
if (!announcedTargetCoverage) {
65+
announcedTargetCoverage = true;
66+
if (countTargetCallSites(*F.getParent(), this->targetFunctionName) == 0) {
67+
llvm::errs() << "\n[map2check] WARNING: target function '"
68+
<< this->targetFunctionName
69+
<< "' is never called in this module. TargetPass"
70+
" instruments call sites, so nothing was instrumented"
71+
" and the reachability property holds trivially: a TRUE"
72+
" verdict here means the target is absent, not that the"
73+
" program is safe.\n";
74+
}
75+
}
76+
2077
this->targetFunctionMap2Check = F.getParent()->getOrInsertFunction(
2178
"map2check_target_function", Type::getVoidTy(F.getContext()),
2279
PointerType::get(F.getContext(), 0), Type::getInt32Ty(F.getContext()),
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
#!/bin/bash
2+
# test_target_coverage.sh -- reachability targets that are never called.
3+
#
4+
# TargetPass instruments CALL SITES whose callee matches --target-function-name.
5+
# If the program never calls that function, nothing is instrumented, and the
6+
# reachability property holds for a reason that has nothing to do with the
7+
# program: the target simply is not there.
8+
#
9+
# That is not an error, and this test does not treat it as one. A program that
10+
# genuinely never calls reach_error IS safe with respect to reach_error, and
11+
# TRUE is the right answer. The defect is that such a TRUE is indistinguishable
12+
# in the output from a TRUE earned by exploring the program.
13+
#
14+
# That indistinguishability is finding B, and it is not hypothetical. The
15+
# CASTLE harness mapped seven CWEs onto `--target-function-name main`; a
16+
# program does not call its own entry point, so zero sites were instrumented.
17+
# On the v6 baseline, 98 of 217 runs went through that mode: 57 TRUE, 22
18+
# TIMEOUT, 9 ERROR, 10 UNKNOWN -- and not one FALSE, across 59 programs known
19+
# to be vulnerable. Twelve of them were scored as true negatives.
20+
#
21+
# So the contract asserted here is about VISIBILITY: the trivial case must
22+
# announce itself, and the real case must not cry wolf.
23+
24+
set -u
25+
26+
MAP2CHECK_DIR="${MAP2CHECK_PATH:-/workspace/install_e2e}"
27+
MAP2CHECK="$MAP2CHECK_DIR/map2check"
28+
29+
PASSED=0
30+
FAILED=0
31+
ok() { echo " PASS $1"; PASSED=$((PASSED+1)); }
32+
fail() { echo " FAIL $1: $2"; FAILED=$((FAILED+1)); }
33+
34+
WORK=$(mktemp -d)
35+
trap 'rm -rf "$WORK"' EXIT
36+
37+
# One program, used for both cases. It really does call reach_error, so the
38+
# difference between the two runs below is only which name is asked for --
39+
# which is the point: the same program is trivially safe with respect to a
40+
# target it does not contain, and genuinely analysable with respect to one it
41+
# does.
42+
cat > "$WORK/prog.c" <<'EOF'
43+
extern int __VERIFIER_nondet_int(void);
44+
extern void reach_error(void);
45+
int main(void) {
46+
int x = __VERIFIER_nondet_int();
47+
if (x == 7) {
48+
reach_error();
49+
}
50+
return 0;
51+
}
52+
EOF
53+
54+
MARKER="is never called in this module"
55+
56+
echo "=== Target coverage warning ==="
57+
58+
# --- Case 1: a target the program really calls -------------------------------
59+
# The budget is small on purpose. The warning is emitted during instrumentation,
60+
# long before any solving, so this test never needs the analysis to finish.
61+
out_real=$( cd "$WORK" && MAP2CHECK_PATH="$MAP2CHECK_DIR" timeout -k 5 90 \
62+
"$MAP2CHECK" --target-function --target-function-name reach_error \
63+
--timeout 10 prog.c 2>&1 )
64+
65+
if echo "$out_real" | grep -q "$MARKER"; then
66+
fail "a called target stays quiet" \
67+
"warned about reach_error, which this program does call"
68+
else
69+
ok "a called target stays quiet"
70+
fi
71+
72+
# --- Case 2: the degenerate target (finding B) -------------------------------
73+
out_main=$( cd "$WORK" && MAP2CHECK_PATH="$MAP2CHECK_DIR" timeout -k 5 90 \
74+
"$MAP2CHECK" --target-function --target-function-name main \
75+
--timeout 10 prog.c 2>&1 )
76+
77+
if echo "$out_main" | grep -q "$MARKER"; then
78+
ok "an uncalled target announces itself"
79+
else
80+
fail "an uncalled target announces itself" \
81+
"no warning for --target-function-name main, which nothing calls"
82+
fi
83+
84+
# The warning has to name the target. A generic "target not found" would send
85+
# whoever reads the log looking for the wrong thing.
86+
if echo "$out_main" | grep -q "'main'"; then
87+
ok "the warning names the target it is about"
88+
else
89+
fail "the warning names the target it is about" "target name absent"
90+
fi
91+
92+
# And it has to say what the verdict is worth, not just that something is
93+
# missing. "TRUE means the target is absent, not that the program is safe" is
94+
# the part a reader acts on.
95+
if echo "$out_main" | grep -qi "not that the program is safe"; then
96+
ok "the warning says what a TRUE verdict is worth here"
97+
else
98+
fail "the warning says what a TRUE verdict is worth here" \
99+
"no statement about the meaning of the verdict"
100+
fi
101+
102+
echo " ---"
103+
echo " Results: $PASSED passed, $FAILED failed"
104+
[ "$FAILED" -eq 0 ] || exit 1

0 commit comments

Comments
 (0)