Lesson 21-Large-Scale Project Architecture

Modularization and Componentization Techniques

Assembly Module Design

Function Library Design Principles:

  1. Single Responsibility Principle: Each function accomplishes a specific task
  2. Interface Standardization: Unified calling convention (e.g., System V ABI)
  3. Minimize Dependencies: Avoid cross-module global variables

Macro Library Design Example:

; x86_64 macro library: Safe memory operations
%macro SAFE_MOV 3
    ; %1=destination, %2=source, %3=size(1/4/8)
    cmp %3, 1
    je .byte_copy
    cmp %3, 4
    je .dword_copy
    cmp %3, 8
    je .qword_copy
    jmp .error

.byte_copy:
    movzbq %2, %1
    jmp .done
.dword_copy:
    movl %2, %1
    jmp .done
.qword_copy:
    movq %2, %1
    jmp .done
.error:
    ud2  ; Trigger invalid instruction exception
%endmacro

Cross-Module Calling Mechanisms

Symbol Export/Import Specifications:

; Linux export symbol (ELF)
.global export_func
.type export_func, @function

; Windows export symbol (PE)
.global _export_func@4
.export _export_func@4, func

; Symbol versioning (GNU extension)
.global export_func
.version_info "1.0"

Calling Convention Comparison Table:

PlatformCalling ConventionParameter PassingStack Cleanup
Linux x86cdeclStack (right to left)Caller
Windows x64Microsoft x64RCX/RDX/R8/R9 + stackCallee
ARM AAPCSAAPCSR0-R3 + stackCallee

Assembly and High-Level Language Interface

C Calling Assembly Function Example:

// C header declaration
extern int asm_add(int a, int b);

// Assembly implementation (x86_64)
.global asm_add
asm_add:
    mov eax, edi    ; First parameter
    add eax, esi    ; Second parameter
    ret

Structure Passing Specification:

// C structure definition
struct Point { int x; int y; };

// Assembly access method
mov eax, [rdi]    ; Access x member (assuming rdi points to structure)
mov edx, [rdi+4]  ; Access y member

Code Reuse Techniques

Macro Abstraction Design:

; Configurable loop unrolling macro
%macro LOOP_UNROLL 2
    ; %1=iteration count, %2=loop body macro
    %rep %1
        %2
    %endrep
%endmacro

; Usage example
%define PROCESS_PIXEL(r,g,b) \
    mov [dst+r], al; \
    mov [dst+g], ah; \
    mov [dst+b], bl

LOOP_UNROLL 4, PROCESS_PIXEL

Templated Code Generation:

# Makefile automatically generates different bit-width versions
ASM_SOURCES = $(wildcard *.asm)
ASM_OBJECTS = $(patsubst %.asm,%.o,$(ASM_SOURCES))

all: $(ASM_OBJECTS)

%.o: %.asm
    nasm -f elf64 -DARCH_64BIT $< -o $@  # 64-bit version
    # nasm -f elf32 -DARCH_32BIT $< -o $@  # 32-bit version

Build System Integration

CMake Cross-Platform Build Example:

# Find assembler
find_program(NASM_EXE nasm)
if(NASM_EXE)
    enable_language(ASM_NASM)
    set(CMAKE_ASM_NASM_COMPILE_OBJECT "<CMAKE_ASM_NASM_COMPILER> <FLAGS> -f ${CMAKE_SYSTEM_PROCESSOR} -o <OBJECT> <SOURCE>")
endif()

# Add assembly source files
add_library(asm_lib STATIC
    src/core.asm
    src/math.asm
)

# Link with high-level language
add_executable(main_program main.c)
target_link_libraries(main_program asm_lib)

Performance Architecture Optimization

HPC Assembly Optimization

Matrix Multiplication Optimization Case:

; AVX2-optimized matrix multiplication (4x4 float)
vmovaps ymm0, [matrixA]  ; Load 4 rows
vmovaps ymm1, [matrixB]  ; Load 4 columns
vmulps ymm2, ymm0, ymm1  ; Element-wise multiply
vpermps ymm3, ymm2, ymm2 ; Rearrange data
vextractf128 xmm4, ymm3, 1
vaddps xmm0, xmm3, xmm4  ; Horizontal sum

Performance Optimization Metrics:

  1. Instruction-Level Parallelism (ILP): 4-8 instructions/cycle
  2. Memory Bandwidth Utilization: >80% theoretical bandwidth
  3. Vectorization Efficiency: >90% SIMD instruction ratio

Game Engine Optimization

Physics Simulation Assembly Optimization:

; SIMD-optimized rigid body collision detection
movaps xmm0, [posA]    ; Load position A
movaps xmm1, [posB]    ; Load position B
subps xmm2, xmm0, xmm1 ; Position difference
mulps xmm2, xmm2       ; Square difference
haddps xmm2, xmm2      ; Horizontal add
haddps xmm2, xmm2      ; Final result
sqrtss xmm3, xmm2      ; Square root

Rendering Pipeline Critical Path:

  1. Vertex transformation: SIMD matrix multiplication
  2. Rasterization: Integer pixel processing
  3. Pixel shading: SIMD color blending

Database Index Optimization

B+ Tree Search Assembly Implementation:

; Fast path comparison (avoid branch prediction failure)
mov eax, [key]
mov ebx, [node_min_key]
cmp eax, ebx
jae .search_right  ; No branch prediction

mov ebx, [node_max_key]
cmp eax, ebx
jbe .found         ; Direct hit

Memory Access Pattern Optimization:

  1. Cache line alignment (64-byte boundary)
  2. Prefetch critical data paths
  3. Avoid random access patterns

Network Protocol Stack Optimization

TCP/IP Checksum Calculation:

; 16-bit one's complement sum optimization
mov edi, packet_ptr
mov ecx, packet_len/2
xor eax, eax         ; Clear accumulator
loop_start:
    lodsw              ; Load 16-bit word
    add eax, ax        ; Accumulate
    jnc .no_carry      ; No carry jump
    inc edx            ; Record carry
.no_carry:
    loop loop_start
adc eax, 0           ; Final carry handling
not eax              ; One's complement

Zero-Copy Technique Implementation:

  1. Memory-mapped I/O (MMIO)
  2. Huge page memory support
  3. DMA direct transfer

RTOS Real-Time Optimization

Task Switching Assembly Implementation:

; Cortex-M context switch
PendSV_Handler:
    mrs r0, psp        ; Get process stack pointer
    stmdb r0!, {r4-r11} ; Save registers
    str r0, [r1]       ; Save stack pointer to TCB

    ; Load new task context
    ldr r0, [r2]       ; New task stack pointer
    ldmia r0!, {r4-r11} ; Restore registers
    msr psp, r0
    bx lr

Deterministic Scheduling Strategies:

  1. Priority bitmap scheduling
  2. Time-triggered scheduling (TTS)
  3. Interrupt latency <1μs guarantee

Security Architecture Design

Assembly Security Vulnerabilities

Typical Vulnerability Patterns:

  1. Buffer overflow:
; Dangerous code example
mov ecx, [user_input_len]
mov edi, buffer
rep movsb            ; No bounds checking
  1. Format string:
; Dangerous call
mov eax, user_string
push eax
call printf          ; User-controlled format string

Secure Programming Practices

Defensive Programming Techniques:

; Safe string copy
safe_strcpy:
    mov rdi, dest
    mov rsi, src
    mov rcx, max_len
    xor rax, rax
    repne scasb          ; Calculate destination length
    sub rcx, rax
    jbe .overflow        ; Length check
    mov rsi, src
    rep movsb
.overflow:
    mov byte [rdi], 0    ; Force termination

Stack Protection Mechanism:

; GCC stack protection implementation
prologue:
    mov rax, fs:0x28     ; Load Canary
    mov [rbp-8], rax
    ; ...function body...
epilogue:
    mov rax, [rbp-8]
    cmp rax, fs:0x28
    jne .stack_smashing

Cryptographic Algorithm Optimization

AES-NI Instruction Sequence:

; AES-128 encryption round functions
movdqu xmm0, [plaintext]
movdqu xmm1, [key]
aesenc xmm0, xmm1  ; Round function 1
aesenc xmm0, xmm2  ; Round function 2
...
aesenclast xmm0, xmm10 ; Final round
movdqu [ciphertext], xmm0

Performance Comparison (128-bit data):

ImplementationCyclesThroughput
C Language12001.0x
SSE4003.0x
AVX22006.0x
AES-NI3040x

Anti-Reverse Engineering Techniques

Code Obfuscation Techniques:

  1. Control flow flattening:
dispatch_loop:
	movzx eax, byte [state_var]
	jmp [dispatch_table + eax*4]
  1. Fake control flow:
; Insert meaningless branches
cmp eax, 0xDEADBEEF
je .fake_block
; ...real code...
  1. Instruction substitution:
; Replace with equivalent instructions
add eax, ebx  →  sub eax, -ebx

Anti-Debugging Techniques:

; Detect debugger presence
mov eax, [fs:0x30]  ; PEB address
mov al, [eax+2]     ; BeingDebugged flag
test al, al
jnz debugger_present

Hardware Security Modules

TPM 2.0 Key Operations:

  1. Key generation:
TSS2_RC rc = Tss2_Sys_CreatePrimary(
	sysContext,
	ESYS_TR_RH_OWNER,
	&inSensitive,
	&inPublic,
	&outsideInfo,
	&creationPCR,
	&primaryHandle,
	&outPublic,
	&creationData,
	&creationHash,
	&creationTicket
);
  1. Sealing operation:
Tss2_Sys_Seal(
	sysContext,
	primaryHandle,
	&session,
	&inSensitive,
	&inPublic,
	&policySession,
	&sealedData
);

HSM Security Features:

  1. Physical tamper detection
  2. True Random Number Generator (TRNG)
  3. Secure key storage (keys never leave HSM)

By comprehensively applying these techniques, developers can achieve:

  1. High-performance security-critical systems
  2. Verifiable software trustworthiness
  3. Efficient cross-platform componentized design
  4. Real-time system determinism guarantees
  5. Anti-reverse engineering protection
  6. Compliance with modern security standards (e.g., CC EAL5+)

Share your love