Assembly coding
Skill nguyenthdat/opencode-manager/registry/skills/assembly-coding
Project-scoped OpenCode TUI plugin for grouping and managing MCP servers, custom agent skills, and pinned vendor skill registries.
npx -y skills add nguyenthdat/opencode-manager --skill assembly-codingAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
2 things to look at
- 13 days oldThe repository was created 13 days ago. New is not bad, but a brand new repository carrying a familiar-sounding name is the shape a typosquat arrives in, and there has been no time for anyone else to find a problem with it.
- 1 stars1 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
What its author says it does
Copied from the file, not written here
Comprehensive assembly language guidance: 166 prioritized rules across 15 categories covering x86-64 (AT&T/GAS and Intel/NASM syntax), ARM64/AArch64 (AAPCS64), and RISC-V. Use when writing, reviewing, refactoring, or debugging `.s`/`.asm`/`.S` files, inline asm blocks, calling-convention/ABI code, SIMD (SSE/AVX/NEON/RVV) routines, or any hand-written machine-code-adjacent logic. Covers calling conventions, register discipline, memory addressing/alignment, control flow, syntax pitfalls (AT&T vs Intel operand order), C/asm interop, testing, and toolchain integration.
SKILL.md
27.8 KB, as published. Nobody here has run it
Assembly Best Practices
Comprehensive guide for writing correct, portable, and maintainable assembly language code. Contains 166 rules across 15 categories, prioritized by impact. Assembly has no compiler-enforced types, ownership, or error handling — correctness instead rests on calling-convention discipline, register and memory-addressing precision, and toolchain verification. Project constraints override generic defaults: preserve the target ISA(s), ABI, assembler, and syntax convention the project has already declared unless the user explicitly asks to change them.
When to Apply
Reference these guidelines when:
- Writing new hand-written routines in x86-64, ARM64/AArch64, or RISC-V assembly
- Reviewing
.s/.asm/.Sfiles or inlineasm/asm volatileblocks in C/C++ - Implementing or auditing a calling-convention boundary (SysV AMD64, AAPCS64, RISC-V, Windows x64)
- Writing or reviewing SIMD-optimized code (SSE/AVX, NEON, RVV)
- Debugging a crash or wrong-answer bug that traces into hand-written asm
- Porting a routine between x86-64, ARM64, and RISC-V
- Setting up or reviewing a build system that assembles
.s/.asmfiles alongside C/C++ - Auditing a binary's security-relevant properties (NX, PIE, stack canary) where hand-written asm is in the mix
Choosing an ISA and Syntax
Most projects target one or more of three ISA families, each with its own calling convention and idioms:
- x86-64 — the dominant server/desktop ISA. Two competing syntaxes exist for the same instruction set: AT&T (GNU assembler/GAS default, used on Linux/BSD/macOS toolchains,
%register/$immediatesigils) and Intel (NASM, MASM, and Intel's own documentation, no sigils,dword ptr-style size annotations). Operand order is the single biggest gotcha: AT&T orders operandssrc, dst; Intel orders themdst, src. The exact same two operands in the exact same registers mean opposite things depending on which syntax you're reading — seesyntax-att-operand-order. - ARM64/AArch64 — the dominant mobile/embedded/increasingly-server ISA (Apple Silicon, AWS Graviton, most phones). Effectively one dominant syntax (GNU/Clang assembler, AAPCS64 calling convention), a load/store-only architecture (no memory-to-memory arithmetic), and NEON SIMD is part of the mandatory baseline.
- RISC-V — an open, modular ISA gaining ground in embedded and increasingly server contexts. No flags register (branches compare two registers directly), ABI role names (
a0-a7,s0-s11) layered over rawx0-x31registers, and an optional, length-agnostic Vector ("V") extension rather than fixed-width SIMD registers.
When a target isn't specified, default to matching whatever ISA/syntax the surrounding project already uses (check existing .s/.asm files, build scripts, and doc-abi-assumption-comment-style header comments) rather than picking a favorite. When writing genuinely new, portable logic, prefer showing the x86-64 AT&T, ARM64, and (where it adds value) RISC-V forms side by side, since a reader of any one variant benefits from seeing how the same logic maps onto the others.
Rule Categories by Priority
| Priority | Category | Impact | Prefix | Rules |
|---|---|---|---|---|
| 1 | Calling Conventions & ABI | CRITICAL | abi- | 14 |
| 2 | Registers & Data Movement | CRITICAL | reg- | 13 |
| 3 | Memory Addressing & Alignment | CRITICAL | mem- | 14 |
| 4 | Control Flow | HIGH | ctrl- | 12 |
| 5 | Syntax & Toolchain | HIGH | syntax- | 13 |
| 6 | Interop with C/High-Level Languages | HIGH | interop- | 12 |
| 7 | SIMD & Vectorization | HIGH | simd- | 10 |
| 8 | Naming Conventions | MEDIUM | name- | 8 |
| 9 | Testing & Verification | MEDIUM | test- | 10 |
| 10 | Documentation | MEDIUM | doc- | 8 |
| 11 | Performance Patterns | MEDIUM | perf- | 10 |
| 12 | Safety & Correctness | MEDIUM/HIGH | safe- | 10 |
| 13 | Project Structure | LOW | proj- | 9 |
| 14 | Linting/Static Analysis | LOW | lint- | 8 |
| 15 | Anti-patterns | REFERENCE | anti- | 15 |
Quick Reference
1. Calling Conventions & ABI (CRITICAL)
abi-sysv-amd64-args- System V AMD64 arg registers: rdi, rsi, rdx, rcx, r8, r9abi-aapcs64-args- ARM64 AAPCS64 arg registers: x0-x7abi-riscv-args- RISC-V arg registers: a0-a7 (aliases for x10-x17)abi-stack-alignment-call- Keep rsp 16-byte aligned at everycallabi-red-zone- Using the 128-byte red zone safely (leaf functions only)abi-callee-saved-regs- Save/restore callee-saved registers you modifyabi-caller-saved-regs- Never assume caller-saved registers survive a callabi-return-value-regs- Return values: rax / x0 / a0 (and wide pairs)abi-large-struct-return- Hidden-pointer convention for large aggregate returnsabi-varargs-al- Set al to the vector-register count for SysV variadic callsabi-stack-frame-prologue- Standard, symmetric prologue/epilogue setupabi-leaf-function-omit-frame- Skip frame setup in true leaf functionsabi-float-regs-separate- Float/vector args use a separate register fileabi-syscall-convention- Direct syscalls use a different register mapping than calls
2. Registers & Data Movement (CRITICAL)
reg-lea-address-compute- Useleafor address computation, not memory accessreg-lea-arithmetic-trick-leaas a documented multiply/add trickreg-movzx-zero-extend- Usemovzxto zero-extend narrower loads correctlyreg-movsx-sign-extend- Usemovsx/movsxdto sign-extend correctlyreg-32bit-implicit-zero-x86-64- 32-bit writes auto-zero-extend to 64-bitreg-arm64-w-x-registers- Wn vs Xn register views on ARM64reg-riscv-x-registers- RISC-V ABI register names over raw x0-x31reg-avoid-redundant-mov- Eliminate register moves that add no valuereg-partial-register-stall- Avoid partial-register write/read stallsreg-xor-zero-idiom- Usexor reg,regto zero a register on x86reg-arm64-zero-register- ARM64's xzr/wzr hardwired zero registerreg-riscv-zero-register- RISC-V's x0/zero hardwired zero registerreg-flags-clobber-awareness- Track which instructions clobber flags
3. Memory Addressing & Alignment (CRITICAL)
mem-x86-addressing-modes- x86-64 base+index*scale+displacement addressingmem-arm64-addressing-modes- ARM64 base+offset / shifted-register addressingmem-riscv-addressing-modes- RISC-V base+12-bit-immediate addressing onlymem-natural-alignment- Align data to its own size (2/4/8/16 bytes)mem-arm64-alignment-fault- ARM64 exclusive/SIMD ops can fault on misalignmentmem-x86-unaligned-penalty- x86 tolerates misalignment but pays a penaltymem-stack-16byte-call- Track running stack alignment as an invariantmem-struct-field-padding- Compute offsets from real (padded) struct layoutmem-endianness-explicit- Handle byte order explicitly across boundariesmem-align-directive- Use.balign/.p2align, not ambiguous.alignmem-array-index-scale- Match the addressing scale to the element sizemem-rip-relative- RIP-relative addressing for PIC on x86-64mem-arm64-adrp-adr-adrp+addto reach a symbol's address on ARM64mem-cache-line-alignment- Align hot shared data to 64-byte cache lines
4. Control Flow (HIGH)
ctrl-flags-after-arith- Know exactly which flags each instruction setsctrl-cmp-vs-test-testfor zero/mask checks,cmpfor relational checksctrl-signed-vs-unsigned-jcc- Pick the signed vs unsigned jump familyctrl-cmov-branchless- Usecmov/cselto avoid unpredictable branchesctrl-loop-unroll-tradeoff- Measure before unrolling; handle the remainderctrl-jump-table- Implement dense switches as bounds-checked jump tablesctrl-arm64-cbz-cbnz- Single-instruction zero-comparison branches on ARM64ctrl-riscv-branch-immediate- RISC-V's flagless register-to-register branchesctrl-avoid-mispredict-hot-loop- Structure hot loops for predictable branchesctrl-tail-call-jmp- Replacecall+retwithjmpin tail positionctrl-loop-counter-direction- Count down to fold the exit test into the decrementctrl-short-circuit-branches- Order checks cheapest/most-likely-to-fail first
5. Syntax & Toolchain (HIGH)
syntax-att-operand-order- AT&T is src,dst; Intel is dst,srcsyntax-att-immediate-percent- AT&T requires$/%sigilssyntax-intel-size-directives- Intel'sdword ptr-style size annotationsyntax-att-suffix-size- AT&T mnemonic suffixes (b/w/l/q) encode sizesyntax-section-directives- Correct use of.text/.data/.bss/.rodatasyntax-global-visibility- Mark externally-callable symbols with.globalsyntax-pic-pie-default- Write position-independent code by defaultsyntax-equ-named-constants- Use.equ/%defineover magic numberssyntax-local-vs-global-symbols-.L-prefix internal-only labelssyntax-nasm-vs-gas-directives- NASM-to-GAS directive mappingsyntax-consistent-syntax-per-file- Never mix AT&T and Intel in one filesyntax-gas-intel-syntax-directive- Using.intel_syntax noprefixdeliberatelysyntax-assembler-directive-portability- Don't assume directives port across assemblers
6. Interop with C/High-Level Languages (HIGH)
interop-extended-asm-basic- Use extendedasmwith input/output/clobber listsinterop-clobber-list-complete- Declare every register the asm block modifiesinterop-asm-volatile-side-effects- Mark asmvolatilewhen it has side effectsinterop-name-mangling-c- Match C (not C++ mangled) symbol namesinterop-c-callable-wrapper- Expose asm through a clean C-callable signatureinterop-preserve-caller-state- Leave every non-scratch register/stack state untouchedinterop-symbol-naming-underscore- Platform leading-underscore symbol conventionsinterop-inline-asm-constraints- Choose the correct GCC/Clang constraint letterinterop-asm-memory-clobber- Add a"memory"clobber for hidden memory effectsinterop-plt-got-external-calls- Call externals through the PLT/GOT under PICinterop-struct-layout-agreement- Keep asm offsets synced with C struct layoutinterop-callback-function-pointers- Invoke C function pointers ABI-correctly
7. SIMD & Vectorization (HIGH)
simd-sse-basic-xmm- Basic SSE packed operations using xmm registerssimd-avx-ymm-256- AVX 256-bit ymm registers, withvzerouppersimd-neon-basic-vector- Basic ARM64 NEON vector operationssimd-riscv-vector-extension- RISC-V "V" extension, length-agnostic vectorssimd-alignment-requirement- Match aligned vs unaligned SIMD load/store to realitysimd-vzeroupper-transition-vzeroupperbefore calling non-AVX-aware codesimd-data-layout-soa- Structure-of-Arrays layout for effective vectorizationsimd-horizontal-vs-vertical- Prefer vertical ops; reduce horizontally oncesimd-masked-operations- Masked/predicated SIMD for remainder handlingsimd-fallback-scalar-path- Always ship a runtime-selected scalar fallback
8. Naming Conventions (MEDIUM)
name-label-snake-case- Descriptive snake_case routine labelsname-local-label-dot-L-.L-prefix internal-only jump labelsname-global-symbol-verb-noun- verb_noun naming for exported routinesname-section-name-standard- Stick to standard section namesname-constant-screaming-snake- SCREAMING_SNAKE_CASE for.equconstantsname-register-alias-descriptive- Alias registers descriptively in long routinesname-file-per-arch-suffix- Suffix per-ISA files (_x86_64.s,_arm64.s)name-avoid-reserved-mnemonics- Never name symbols like mnemonics/registers
9. Testing & Verification (MEDIUM)
test-c-harness-wrapper- Test asm via a small C harness calling its ABI boundarytest-gdb-register-inspect- Step and inspect registers/memory with gdbtest-lldb-register-inspect- The lldb equivalent on macOS/BSDtest-disassemble-verify- Disassemble and confirm the actual encoded bytestest-compare-compiler-output- Diff againstgcc -S/clang -Sfor idiom checkstest-fuzz-via-wrapper- Fuzz asm indirectly through its C wrappertest-unit-test-known-vectors- Cover zero, max, negative, and empty inputstest-sanitizer-wrapper- Run the C harness under ASan/UBSantest-golden-file-disasm- Snapshot disassembly to catch codegen drifttest-cross-platform-ci- Test every targeted ISA in CI, real or emulated
10. Documentation (MEDIUM)
doc-entry-register-contract- Document each routine's register/stack contractdoc-clobber-comment- Comment which registers a routine clobbersdoc-frame-layout-comment- Document hand-managed stack frame layoutsdoc-bit-trick-explain- Explain non-obvious bit tricks with the underlying mathdoc-abi-assumption-comment- State the assumed ABI/OS/syntax at the file topdoc-algorithm-reference- Cite the algorithm/reference a routine implementsdoc-section-purpose-comment- Comment the purpose of each data section/blobdoc-todo-fixme-tracked- Track unfinished/unsafe shortcuts with tracked comments
11. Performance Patterns (MEDIUM)
perf-avoid-false-dependency- Break false register dependenciesperf-instruction-level-parallelism- Expose independent work for ILPperf-avoid-self-modifying-code- Never modify executing instructionsperf-cache-line-access-pattern- Access memory sequentially where possibleperf-avoid-lock-prefix-uncontended- Reservelockfor genuinely shared stateperf-string-op-rep-movsb-rep movsb/stosbfor large copies, measuredperf-minimize-memory-traffic- Keep loop-invariant values in registersperf-branch-free-arithmetic- Replace simple branches with mask arithmeticperf-prefetch-hint- Software-prefetch predictable-but-non-sequential accessperf-profile-before-hand-tuning- Profile before hand-optimizing anything
12. Safety & Correctness (MEDIUM/HIGH)
safe-stack-overflow-bounds- Never write past allocated stack spacesafe-stack-canary-respect- Never bypass or "fix" the compiler's stack canarysafe-integer-overflow-manual- Check OF/CF after manual arithmeticsafe-no-undocumented-flag-reliance- Only rely on documented flag guaranteessafe-return-address-integrity- Never clobber the return address / link registersafe-shadow-space-windows- Reserve the 32-byte Windows x64 shadow spacesafe-nx-stack-no-exec- Never execute code from non-executable memorysafe-division-by-zero-check- Guarddiv/idivagainst a zero divisorsafe-signed-division-truncation- Sign-extend (cqo/cdq) before signed divisionsafe-uninitialized-register-read- Never read before writing/initializing
13. Project Structure (LOW)
proj-separate-text-data-bss- Consistent.text/.data/.bssorganizationproj-one-routine-per-file-large- Split large modules by cohesive purposeproj-makefile-integration- Wire.s/.Ssources into a Makefile properlyproj-cmake-asm-language- Enable CMake'sASM/ASM_NASMlanguagesproj-per-arch-directory-layout- Organize per-ISA implementations by directoryproj-header-shared-constants- One source of truth for C/asm shared constantsproj-build-both-syntaxes- Maintain dual AT&T/Intel variants only when justifiedproj-versioned-abi-comment- Document supported platforms at the project levelproj-avoid-vendoring-generated-asm- Don't hand-patch compiler-generated asm
14. Linting/Static Analysis (LOW)
lint-assembler-warnings-as-errors-as --fatal-warningsin the buildlint-nasm-w-all- NASM's-Wall/-Werrorwarning disciplinelint-objdump-cross-check- Make disassembly review a routine review steplint-static-analyzer-compiler-asm- Compare against compiler-idiomatic outputlint-checksec-binary- Verify NX/PIE/canary flags on the final binarylint-consistent-indentation-style- Consistent mnemonic/operand column alignmentlint-no-dead-code-sections- Remove unused labels/routines, don't comment them outlint-ci-multi-assembler- Test every supported assembler/version in CI
15. Anti-patterns (REFERENCE)
anti-hardcoded-stack-offset- Don't hardcode undocumented stack offsetsanti-assume-register-allocation- Don't assume a register role without checking the ABIanti-ignore-alignment-requirement- Don't ignore call-boundary alignment rulesanti-self-modifying-code- Don't write self-modifying codeanti-mixed-syntax- Don't mix AT&T and Intel syntax carelesslyanti-premature-hand-optimization- Don't hand-optimize before profiling a working C versionanti-clobber-callee-saved- Don't clobber a callee-saved register unrestoredanti-missing-red-zone-awareness- Don't assume the red zone is safe in non-leaf functionsanti-magic-number-offset- Don't use unexplained magic-number offsetsanti-ignoring-endianness- Don't ignore byte order when porting/parsing dataanti-unbounded-string-op- Don't runrep/loop copies without a verified boundanti-forgetting-vzeroupper- Don't skipvzeroupperat the AVX/SSE boundaryanti-copy-paste-abi-mismatch- Don't copy x86-64 ABI assumptions into ARM64/RISC-Vanti-unsynced-flags-across-calls- Don't assume flags survive a function callanti-no-verification-of-hand-asm- Don't ship hand-written asm unverified
Recommended Tooling & Build Configuration
# GNU assembler (GAS) + linker, AT&T syntax, warnings as errors, debug symbols
as --fatal-warnings -g -o checksum.o checksum.s
ld -o app checksum.o main.o
# GCC/Clang driving the whole pipeline (preferred for most projects: handles PIC/PIE,
# links libc, and runs the C preprocessor over .S files automatically)
gcc -Wall -Wextra -Wa,--fatal-warnings -g -fPIC -pie -c checksum.s -o checksum.o
gcc -fPIC -pie checksum.o main.o -o app
# NASM (Intel syntax), warnings as errors, debug info, ELF64 object format
nasm -f elf64 -Wall -Werror -g checksum.asm -o checksum.o
gcc checksum.o main.o -o app
# Makefile snippet: assembling .s files alongside C, with debug symbols and warnings enabled
CC := gcc
AS := as
CFLAGS := -Wall -Wextra -g -O2 -fPIC -pie
ASFLAGS := -g --fatal-warnings
SRCS_C := main.c parser.c
SRCS_S := checksum_x86_64.s
OBJS := $(SRCS_C:.c=.o) $(SRCS_S:.s=.o)
app: $(OBJS)
$(CC) $(CFLAGS) $(OBJS) -o $@
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
%.o: %.s
$(AS) $(ASFLAGS) $< -o $@
test: app
./run_tests.sh
clean:
rm -f $(OBJS) app
.PHONY: test clean
Verify the shipped binary's security-relevant properties once the build is wired up:
checksec --file=./app # confirms NX, PIE, RELRO, and stack-canary status
How to Use
This skill provides rule identifiers for quick reference. When generating or reviewing assembly code:
- Identify the target ISA(s) and syntax — check existing files, build scripts, or ask if unclear
- Check the relevant category based on the task type
- Apply rules with the matching prefix, showing multi-ISA variants where the skill covers more than one
- Prioritize CRITICAL > HIGH > MEDIUM > LOW
- Read rule files in
rules/for detailed, ISA-labeled examples
Rule Application by Task
| Task | Primary Categories |
|---|---|
| New routine, any ISA | abi-, reg-, mem- |
| Calling-convention boundary / C interop | abi-, interop- |
| Hot loop / branch structuring | ctrl-, perf- |
| SIMD / vectorized code | simd-, mem-, perf- |
| Porting between x86-64/ARM64/RISC-V | abi-, reg-, mem-, anti-copy-paste-abi-mismatch |
| Debugging a crash or wrong answer | test-, safe-, doc- |
| Build system integration | proj-, syntax- |
| Code review | anti-, lint-, safe- |
Related Skills
- c-coding - assembly work is very often paired with C, via inline
asm/asm volatileblocks,extern "C"linkage boundaries, and shared struct layouts; see this skill'sinterop-category for the seams between the two. - design-patterns - architectural patterns for the higher-level code that calls into hand-written asm routines.
- security-review - broader security-audit checklists; this skill's
safe-category andlint-checksec-binarycover the asm-specific slice (stack canaries, NX, PIE) of that same concern.
Sources
This skill synthesizes best practices from:
- Intel® 64 and IA-32 Architectures Software Developer's Manuals
- AMD64 Architecture Programmer's Manual
- System V Application Binary Interface, AMD64 Architecture Processor Supplement
- Arm Architecture Reference Manual for A-profile architecture; Procedure Call Standard for the Arm 64-bit Architecture (AAPCS64)
- RISC-V Instruction Set Manual; RISC-V ELF psABI specification
- "Programming from the Ground Up" — Jonathan Bartlett
- "Modern X86 Assembly Language Programming" — Daniel Kusswurm
- OSDev Wiki
- GNU Binutils (
as,ld,objdump) and NASM documentation - Community conventions and production open-source assembly (glibc, Linux kernel, zlib, compiler-generated codegen idioms) (2024-2025)