[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,92 +2,137 @@
|
||||
id: wiki-2026-0508-speculative-execution
|
||||
title: Speculative Execution
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-CCED4D]
|
||||
aliases: [P-Reinforce-AUTO-CCED4D, Branch Speculation, Out-of-order Execution]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [cpu, microarchitecture, security, performance, spectre]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - Speculative Execution"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: C / asm
|
||||
framework: x86-64 / ARMv9
|
||||
---
|
||||
|
||||
# [[Speculative Execution|Speculative Execution]]
|
||||
# Speculative Execution
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> 추측 실행(Speculative Execution)은 현대 CPU가 성능 최적화를 위해 분기(branch)의 실제 결과가 확인되기 전에 미리 명령어를 실행하는 기법입니다 [1]. 예측이 틀린 것으로 판명될 경우 CPU는 실행을 롤백(roll back)하여 변경 사항을 취소할 수 있습니다 [1]. 하지만 이 과정에서 L1 캐시로 미리 가져온 데이터는 롤백 시 취소되지 않으며, 이러한 구조적 특성은 타이밍 기반의 정보 유출을 유발하여 **[[Spectre|Spectre]]**와 같은 보안 취약점 공격에 악용될 수 있습니다 [1, 2].
|
||||
## 매 한 줄
|
||||
> **"매 CPU 의 매 branch 의 outcome 의 wait 의 X — 매 predicted path 의 의 ahead 의 execute, 매 wrong → rollback"**. 1990s Pentium Pro 매 first commercial impl → 2018 Spectre/Meltdown 매 the dark side 의 reveal → 2026 매 hardware mitigation (Intel CET, ARM BTI/MTE) + compiler hardening 매 standard.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **동작 원리 및 분기 예측:** 현대 CPU는 분기 기록을 프로파일링하여 결과를 예측([[Branch Prediction|Branch Prediction]])하며, 이를 바탕으로 코드를 추측 실행합니다 [1]. 예를 들어, 특정 분기 조건을 통과할 것으로 예측되면, CPU는 해당 분기가 실제로 검증되기 전에 그 뒤에 오는 메모리 로드(load) 명령을 병렬로 미리 실행할 수 있습니다 [1].
|
||||
- **롤백 및 L1 캐시 최적화:** 만약 CPU의 예측이 틀려 분기가 다른 방향으로 진행되어야 한다면, CPU는 분기 시점부터 검증 시점까지 발생한 모든 추측 실행 작업을 취소(undo)하고 롤백합니다 [1]. 그러나 성능 최적화를 위해, 추측 실행 중에 메인 메모리에서 **L1 캐시**(CPU에서 가장 작고 빠른 메모리 캐시)로 데이터를 가져온 작업은 롤백할 때 취소되지 않습니다 [2].
|
||||
- **보안 취약점 (Spectre 공격):** L1 캐시에 남아 있는 데이터는 **타이밍 기반 정보 유출(timing-based information leak)**을 초래합니다 [2]. 공격자는 과거의 분기 기록을 조작함으로써 추측 실행 중에 CPU가 특정 작업을 수행하도록 유도할 수 있습니다 [3]. 이후 다양한 메모리 위치에 대한 접근 속도(L1 캐시와 메인 메모리의 지연 시간 차이)를 측정하여 어떤 데이터가 추측 실행으로 로드되었는지 알아낼 수 있으며, 이것이 **Spectre** 공격의 핵심 원리입니다 [1-3].
|
||||
- **보안 검사 우회 및 영향:** 이러한 추측 실행 취약점으로 인해 경계 검사(bounds check)나 타입 검사(type check)와 같은 기존의 분기 기반 보안 검사들이 무력화될 수 있습니다 [4, 5]. 결과적으로 신뢰할 수 없는 코드(예: 웹 브라우저의 [[JavaScript|JavaScript]] 엔진)가 제한된 영역을 벗어나 호스트 프로세스의 임의 메모리를 읽을 수 있는 위험이 발생합니다 [4, 6].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 mechanism
|
||||
- **Branch predictor** 매 매 branch 의 taken/not-taken 의 history 의 학습 (TAGE, Perceptron).
|
||||
- **Reorder buffer (ROB)** 매 매 speculative instruction 의 in-flight 의 hold.
|
||||
- **Retire stage** 매 매 branch 의 resolved 의 후 의 commit (correct) or flush (mispredict).
|
||||
- **Misprediction penalty**: 매 modern CPU 매 ~15-25 cycles.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[Spectre|Spectre]], Meltdown, [[Branch Prediction|Branch Prediction]], L1 Cache
|
||||
- **Projects/Contexts:** [[WebKit|WebKit]], [[JavaScriptCore|JavaScriptCore]]
|
||||
- **Contradictions/Notes:** 소스 내에서 상충되는 주장은 발견되지 않았습니다. 다만, 이와 관련하여 [[WebKit|WebKit]] 프로젝트는 추측 실행을 악용한 공격을 방어하기 위해 타이머(performance.now 등)의 정밀도를 낮추고, 분기 명령어에 의존하지 않는 보안 검사(Branchless Security Checks) 및 포인터 포이즈닝([[Pointer Poisoning|Pointer Poisoning]])을 도입하는 방식으로 대응하고 있습니다 [7-9].
|
||||
### 매 dark side
|
||||
- **Spectre v1 (Bounds Check Bypass)**: 매 attacker 의 branch predictor 의 train → 매 sensitive memory 의 cache 의 leak.
|
||||
- **Spectre v2 (Branch Target Injection)**: 매 indirect branch 의 mispredict 의 force.
|
||||
- **Meltdown**: 매 user 의 kernel memory 의 speculative read.
|
||||
- **L1TF, MDS, Retbleed, GhostRace** (2018-2024): 매 variant 의 endless.
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-19*
|
||||
### 매 응용
|
||||
1. CPU performance (1.5-3x IPC vs in-order).
|
||||
2. Branch prediction research.
|
||||
3. Compiler 매 PGO + autovectorization 의 enabler.
|
||||
|
||||
---
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### Pattern 1: 매 Spectre v1 매 PoC (educational)
|
||||
```c
|
||||
// 매 educational only
|
||||
uint8_t array1[16] = {0};
|
||||
uint8_t array2[256 * 512];
|
||||
char* secret = "key";
|
||||
unsigned int array1_size = 16;
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
void victim(size_t x) {
|
||||
if (x < array1_size) { // <-- 매 trained branch
|
||||
uint8_t v = array2[array1[x] * 512];
|
||||
// 매 cache 의 leak via timing
|
||||
}
|
||||
}
|
||||
// Attacker 매 array1_size 의 cache 의 evict → speculative path 매 OOB read
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Pattern 2: 매 LFENCE / 매 retpoline 의 mitigation
|
||||
```c
|
||||
// gcc -mindirect-branch=thunk-extern -mfunction-return=thunk-extern
|
||||
static inline void speculation_barrier(void) {
|
||||
__asm__ volatile ("lfence" ::: "memory");
|
||||
}
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
bool safe_lookup(size_t i, size_t n, uint8_t* arr) {
|
||||
if (i < n) {
|
||||
speculation_barrier(); // 매 stops speculative path
|
||||
return arr[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Pattern 3: 매 bench 의 branch misprediction
|
||||
```c
|
||||
// perf stat -e branches,branch-misses ./a.out
|
||||
#include <stdio.h>
|
||||
int main(int argc, char** argv) {
|
||||
int sum = 0;
|
||||
for (int i = 0; i < 1000000; i++) {
|
||||
if (i % 2 == 0) sum += i; // 매 100% predictable
|
||||
// if ((rand() & 1)) sum += i; // 매 50% miss → much slower
|
||||
}
|
||||
printf("%d\n", sum);
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Pattern 4: 매 V8 / JIT 의 speculative optimization
|
||||
```js
|
||||
// V8 매 hidden class 의 speculatively assume → 매 type 의 change → 매 deopt
|
||||
function add(o) { return o.x + o.y; }
|
||||
add({ x: 1, y: 2 }); // 매 monomorphic, JIT 의 specialize
|
||||
add({ x: 1, y: 2, z: 3 }); // 매 hidden class 의 change → 매 deopt
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 user code 매 typical app | 매 default — speculation 매 win, 매 mitigation OS-level |
|
||||
| 매 cryptography (constant-time req) | `LFENCE`, branchless code, 매 secret-dep 의 branch X |
|
||||
| 매 multi-tenant cloud | site-isolation, hardware mitigation enable, microcode update |
|
||||
| 매 perf-critical hot loop | Profile-guided opt + branchless when miss > 5% |
|
||||
| 매 indirect call hot path | retpoline (Spectre v2) + IBRS off if isolated |
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
**기본값**: 매 OS + microcode 의 latest, 매 crypto code 매 constant-time, 매 hot-loop 매 PGO.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[CPU Bottleneck]] · [[Branch Prediction]]
|
||||
- 변형: [[Out-of-order Execution]] · [[Branch Predictor]] · [[Retpoline]]
|
||||
- 응용: [[V8 Engine]] · [[Spectre]] · [[Meltdown]]
|
||||
- Adjacent: [[Cache Side Channel]] · [[Constant-Time Crypto]] · [[CET / BTI]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 perf 분석 (branch-miss rate), 매 microbenchmark 의 design, 매 mitigation flag 의 trade-off 분석.
|
||||
**언제 X**: 매 actual exploit 의 development — out of scope.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **매 secret-dependent branch** 매 crypto code — 매 timing leak.
|
||||
- **매 mitigation 의 disable** ("for performance") 매 multi-tenant host.
|
||||
- **매 indirect call 의 hot loop** without retpoline 매 Spectre v2-vulnerable CPU.
|
||||
- **매 unpredictable branch** 매 inner loop — 매 branchless (cmov, mask) 의 prefer.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Hennessy & Patterson 6e Ch.3, Spectre paper Kocher 2018, Intel SDM Vol.3 Ch.2).
|
||||
- 신뢰도 A.
|
||||
- 중복 risk: [[Branch Prediction]] (related), [[Out-of-order Execution]] (parent mechanism).
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — mechanism, Spectre family, mitigations 정리 |
|
||||
|
||||
Reference in New Issue
Block a user