[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,91 +2,169 @@
|
||||
id: wiki-2026-0508-index-masking
|
||||
title: Index Masking
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-42C840]
|
||||
aliases: [Bitmask Index, Power-of-Two Masking]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [optimization, low-level, ring-buffer, hash]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - Index Masking"
|
||||
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/C++/Rust/JavaScript
|
||||
framework: General
|
||||
---
|
||||
|
||||
# [[Index Masking]]
|
||||
# Index Masking
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> Index Masking은 [[Spectre]] 및 Meltdown과 같은 캐시 사이드 채널 공격을 방어하기 위해 브라우저 엔진에 도입된 보안 완화(security mitigation) 기법 중 하나이다 [1, 2]. 이 기법은 길이(length)를 다음 2의 거듭제곱으로 올림한 후 1을 빼는 방식으로 마스크(mask)를 계산하여 적용하는 분기 없는(branchless) 보안 검사 방식이다 [3, 4]. 비록 경계를 벗어난(out-of-bounds) 읽기를 완전히 막지는 못하지만, 공격자가 임의의 메모리에 접근하는 것을 방지하는 역할을 한다 [4].
|
||||
## 매 한 줄
|
||||
> **"매 capacity 가 power-of-two 일 때 `% N` 의 `& (N-1)` replacement"**. 매 modulo 의 expensive (CPU cycle 10-30) 의 single-cycle `AND` 로 대체. Ring buffer, hash table bucket, fixed-size LRU, lock-free queue 의 hot path 의 universal trick. CPU branch predictor 와 cache line 의 friendly.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **동작 원리 및 한계:** Index Masking은 데이터의 길이를 다음 2의 거듭제곱으로 올림하고 1을 빼는 방식으로 마스크를 계산하여 사용한다 [4]. 이 방법은 OOB(Out-of-Bounds) 접근에 대한 완벽한 해결책은 아니며 여전히 범위를 벗어난 읽기를 허용할 수 있지만, 임의의 메모리 영역(arbitrary [[memory]])에 대한 접근은 확실하게 차단한다 [4].
|
||||
- **보안을 위한 아키텍처 도입:** Spectre 및 Meltdown 공격을 방어하기 위해 [[WebKit]]을 비롯한 웹 브라우저 엔진들은 기존의 분기(branch) 기반 보안 검사의 한계를 보완하고자 Index Masking과 [[Pointer Poisoning]] 같은 분기 없는(branchless) 보안 검사 방식을 도입하였다 [1, 3, 4].
|
||||
- **성능에 미치는 영향:** 이 보안 완화 기법은 자바스크립트 엔진 및 JIT(Just-In-Time) 컴파일러가 수행하는 그래픽 실행의 크리티컬 패스에 추가 명령어를 도입하므로, 기본 마이크로 지연 시간(base micro-latency)을 약간 증가시킨다 [5]. 그러나 WebKit의 테스트에 따르면 Speedometer 및 ARES-6 벤치마크에서는 측정 가능한 성능 영향이 없었으며, JetStream 벤치마크에서는 성능에 미치는 영향이 2.5% 미만인 것으로 확인되었다 [4].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 정확성 조건
|
||||
- N 이 power-of-two: `2^k`.
|
||||
- `index % N == index & (N - 1)` (unsigned 또는 non-negative).
|
||||
- `N - 1` 이 모든 lower bit 의 1 의 mask.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[Spectre and Meltdown]], [[Pointer Poisoning]], [[Branchless Security Checks]]
|
||||
- **Projects/Contexts:** [[WebKit]], Micro-latency Measurement in Web Graphics Pipelines
|
||||
- **Contradictions/Notes:** 소스 [5]에서는 Index Masking 기술이 그래픽 실행의 크리티컬 패스에 명령어를 추가하여 마이크로 지연 시간을 증가시킨다고 설명하지만, 소스 [4]의 벤치마크 결과에 따르면 실제 환경의 주요 성능 테스트(Speedometer 등)에서는 그 영향이 측정되지 않거나 2.5% 미만으로 매우 미미하다고 보고합니다.
|
||||
### 매 대표 사용 처
|
||||
- Ring buffer / circular queue.
|
||||
- Open-addressing hash table bucket index.
|
||||
- Game loop frame index modulo history size.
|
||||
- Hardware register address calc.
|
||||
- Lock-free SPSC/MPMC queue (Disruptor pattern).
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-19*
|
||||
### 매 응용
|
||||
1. LMAX Disruptor (Java) — sequence & ringMask.
|
||||
2. Linux kernel ringbuffer.
|
||||
3. Redis hash table — sizemask.
|
||||
4. V8 hidden class transitions table.
|
||||
|
||||
---
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### Basic ring buffer (C)
|
||||
```c
|
||||
#define RB_CAP 1024 // must be power of two
|
||||
typedef struct {
|
||||
int data[RB_CAP];
|
||||
uint32_t head, tail; // free-running counters
|
||||
} RingBuf;
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(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
|
||||
static inline void rb_push(RingBuf *r, int v) {
|
||||
r->data[r->head & (RB_CAP - 1)] = v;
|
||||
r->head++;
|
||||
}
|
||||
static inline int rb_pop(RingBuf *r) {
|
||||
int v = r->data[r->tail & (RB_CAP - 1)];
|
||||
r->tail++;
|
||||
return v;
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### TypeScript fixed-size circular log
|
||||
```typescript
|
||||
class CircularLog<T> {
|
||||
private buf: (T | undefined)[]
|
||||
private mask: number
|
||||
private head = 0
|
||||
constructor(capacityPow2: number) {
|
||||
if ((capacityPow2 & (capacityPow2 - 1)) !== 0)
|
||||
throw new Error('capacity must be power of two')
|
||||
this.buf = new Array(capacityPow2)
|
||||
this.mask = capacityPow2 - 1
|
||||
}
|
||||
push(v: T) {
|
||||
this.buf[this.head & this.mask] = v
|
||||
this.head++
|
||||
}
|
||||
recent(n: number): T[] {
|
||||
const out: T[] = []
|
||||
for (let i = 0; i < n; i++) {
|
||||
const v = this.buf[(this.head - 1 - i) & this.mask]
|
||||
if (v !== undefined) out.push(v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Round-up to next power of two
|
||||
```c
|
||||
uint32_t next_pow2(uint32_t v) {
|
||||
v--;
|
||||
v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16;
|
||||
return v + 1;
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Hash table bucket
|
||||
```rust
|
||||
struct Map<K, V> {
|
||||
buckets: Vec<Option<(K, V)>>,
|
||||
mask: usize,
|
||||
}
|
||||
impl<K: Hash + Eq, V> Map<K, V> {
|
||||
fn bucket(&self, k: &K) -> usize {
|
||||
let mut h = DefaultHasher::new();
|
||||
k.hash(&mut h);
|
||||
(h.finish() as usize) & self.mask // mask = capacity - 1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### SPSC lock-free (Disruptor-style)
|
||||
```c
|
||||
// producer
|
||||
void produce(RingBuf *r, int v) {
|
||||
uint32_t h = atomic_load(&r->head);
|
||||
while (h - atomic_load(&r->tail) >= RB_CAP) cpu_relax(); // full
|
||||
r->data[h & (RB_CAP - 1)] = v;
|
||||
atomic_store(&r->head, h + 1);
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Branch-free wrap (negative-safe)
|
||||
```c
|
||||
// for signed wrap, use bit-and after cast
|
||||
int idx = ((int)(counter) & ((int)CAP - 1)); // counter must be non-negative
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Hot path, capacity 가 control 가능 | Power-of-2 + masking |
|
||||
| Capacity 가 user-input arbitrary | `%` (or round up to pow2) |
|
||||
| Capacity 가 dynamic resize | resize 시 `mask` recompute |
|
||||
| Signed counter | unsigned cast 또는 modulo |
|
||||
| Hardware-aligned (cache line) | pow2 + alignment 조합 |
|
||||
|
||||
**기본값**: 매 ring/hash table 는 power-of-two + bitmask. 매 capacity 의 dynamic 이면 round-up.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Bitwise Operations]]
|
||||
- 변형: [[Modulo Reduction]] · [[Fastrange]]
|
||||
- 응용: [[Ring Buffer]] · [[Object Pooling (오브젝트 풀링)]] · [[Hash Table]]
|
||||
- Adjacent: [[SharedArrayBuffer로 스레드 간 메모리 공유 효율 높이기]] · [[Pointer Compression]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 high-throughput data structure, lock-free queue, HFT, game engine frame loop.
|
||||
**언제 X**: capacity 의 control 안 되거나 readability priority 인 일반 application code.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Non-pow2 size 에 mask 적용**: 매 silent index out-of-range, data corruption.
|
||||
- **Signed negative index 의 masking**: `-1 & (N-1)` 의 N-1 이 됨 → 매 unsigned cast 또는 `((i % N) + N) % N` pattern.
|
||||
- **Capacity 1 의 mask 0**: 매 always index 0, degenerate.
|
||||
- **Premature application**: 매 측정 없이 micro-optimization. 매 hot path 만 의 적용.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Hacker's Delight Ch.3, LMAX Disruptor paper, Linux kfifo source, Redis dict.c).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — power-of-2 masking patterns + ring/hash applications |
|
||||
|
||||
Reference in New Issue
Block a user