From 3922c873b3001ff56a228fe303d6ed645c5a108d Mon Sep 17 00:00:00 2001 From: Damian Suess Date: Sun, 15 Nov 2026 21:52:06 -0500 Subject: [PATCH 1/4] Created Zero Assembly Programmer's Guide with various sections and chapters explaining the ins and outs of (Zero) Assembly Language, including samples --- docs/dbg/index.md | 42 +++++ docs/ide/index.md | 41 +++++ docs/index.md | 15 +- docs/zasm/ZASM-Examples.md | 2 + docs/zasm/ZASM-Intro.md | 2 + docs/zasm/ZASM-Reference.md | 2 + docs/zasm/index.md | 103 +++++++++++ docs/zasm/zasm-01-01-what-is-zero-assembly.md | 37 ++++ .../zasm-01-02-why-learn-assembly-today.md | 33 ++++ docs/zasm/zasm-01-03-installing-zero-ide.md | 42 +++++ ...m-01-04-using-zero-ide-my-first-project.md | 40 +++++ docs/zasm/zasm-01-05-hello-zero-assembly.md | 54 ++++++ docs/zasm/zasm-02-01-moving-numbers.md | 36 ++++ docs/zasm/zasm-02-02-performing-jumps.md | 39 +++++ .../zasm-02-03-storing-data-and-printing.md | 44 +++++ docs/zasm/zasm-02-04-boolean-algebra.md | 39 +++++ docs/zasm/zasm-02-05-basic-variables.md | 38 ++++ ...3-01-calling-external-library-functions.md | 43 +++++ docs/zasm/zasm-03-02-creating-structs.md | 44 +++++ docs/zasm/zasm-03-03-working-with-strings.md | 39 +++++ .../zasm/zasm-03-04-organizing-your-system.md | 44 +++++ docs/zasm/zasm-03-05-arithmetic-operations.md | 47 +++++ ...zasm-03-06-performing-bit-manipulations.md | 37 ++++ docs/zasm/zasm-03-07-creating-functions.md | 46 +++++ docs/zasm/zasm-04-01-notepad-project-setup.md | 37 ++++ .../zasm-04-02-notepad-create-the-window.md | 36 ++++ .../zasm-04-03-notepad-add-the-text-editor.md | 53 ++++++ .../zasm-04-04-notepad-open-and-save-files.md | 51 ++++++ ...sm-04-05-notepad-testing-and-next-steps.md | 39 +++++ docs/zasm/zasm-05-01-zero-cli-compiler.md | 43 +++++ docs/zasm/zasm-05-02-compiler-switches.md | 41 +++++ docs/zasm/zasm-05-03-zero-debugger.md | 38 ++++ docs/zasm/zasm-06-01-x86-instruction-set.md | 40 +++++ docs/zasm/zasm-06-02-x64-instruction-set.md | 39 +++++ docs/zasm/zasm-06-03-what-is-windows-pe.md | 34 ++++ docs/zasm/zasm-06-04-what-is-elf.md | 34 ++++ docs/zasm/zasm-06-05-what-is-arm.md | 32 ++++ docs/zasm/zasm-07-01-mnemonic-lookup.md | 43 +++++ docs/zasm/zasm-07-02-ascii-character-set.md | 162 ++++++++++++++++++ docs/zero/index.md | 40 +++++ readme.md | 6 + 41 files changed, 1676 insertions(+), 1 deletion(-) create mode 100644 docs/dbg/index.md create mode 100644 docs/ide/index.md create mode 100644 docs/zasm/index.md create mode 100644 docs/zasm/zasm-01-01-what-is-zero-assembly.md create mode 100644 docs/zasm/zasm-01-02-why-learn-assembly-today.md create mode 100644 docs/zasm/zasm-01-03-installing-zero-ide.md create mode 100644 docs/zasm/zasm-01-04-using-zero-ide-my-first-project.md create mode 100644 docs/zasm/zasm-01-05-hello-zero-assembly.md create mode 100644 docs/zasm/zasm-02-01-moving-numbers.md create mode 100644 docs/zasm/zasm-02-02-performing-jumps.md create mode 100644 docs/zasm/zasm-02-03-storing-data-and-printing.md create mode 100644 docs/zasm/zasm-02-04-boolean-algebra.md create mode 100644 docs/zasm/zasm-02-05-basic-variables.md create mode 100644 docs/zasm/zasm-03-01-calling-external-library-functions.md create mode 100644 docs/zasm/zasm-03-02-creating-structs.md create mode 100644 docs/zasm/zasm-03-03-working-with-strings.md create mode 100644 docs/zasm/zasm-03-04-organizing-your-system.md create mode 100644 docs/zasm/zasm-03-05-arithmetic-operations.md create mode 100644 docs/zasm/zasm-03-06-performing-bit-manipulations.md create mode 100644 docs/zasm/zasm-03-07-creating-functions.md create mode 100644 docs/zasm/zasm-04-01-notepad-project-setup.md create mode 100644 docs/zasm/zasm-04-02-notepad-create-the-window.md create mode 100644 docs/zasm/zasm-04-03-notepad-add-the-text-editor.md create mode 100644 docs/zasm/zasm-04-04-notepad-open-and-save-files.md create mode 100644 docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md create mode 100644 docs/zasm/zasm-05-01-zero-cli-compiler.md create mode 100644 docs/zasm/zasm-05-02-compiler-switches.md create mode 100644 docs/zasm/zasm-05-03-zero-debugger.md create mode 100644 docs/zasm/zasm-06-01-x86-instruction-set.md create mode 100644 docs/zasm/zasm-06-02-x64-instruction-set.md create mode 100644 docs/zasm/zasm-06-03-what-is-windows-pe.md create mode 100644 docs/zasm/zasm-06-04-what-is-elf.md create mode 100644 docs/zasm/zasm-06-05-what-is-arm.md create mode 100644 docs/zasm/zasm-07-01-mnemonic-lookup.md create mode 100644 docs/zasm/zasm-07-02-ascii-character-set.md create mode 100644 docs/zero/index.md diff --git a/docs/dbg/index.md b/docs/dbg/index.md new file mode 100644 index 0000000..22c16ab --- /dev/null +++ b/docs/dbg/index.md @@ -0,0 +1,42 @@ +--- +layout: default +title: "Zero.DBG User Guide" +--- + +# Zero.DBG User Guide + +[Documentation library](../index.md) · [Zero Assembly book](../zasm/index.md) + +**Planned companion book.** This page reserves a home and section structure for +future chapters. The outline is documentation work to come, not a promise that +every named feature is implemented. Use the current guides below today. + +## Planned sections + +### Section 1 — Getting Started + +Chapter placeholders: Supported hosts and targets, setup, and a first session. + +### Section 2 — Controlling Execution + +Chapter placeholders: Breakpoints, continue, pause, stepping, and stop. + +### Section 3 — Inspecting State + +Chapter placeholders: Registers today; further inspection features as implemented. + +### Section 4 — Source Maps and Backends + +Chapter placeholders: Map format, session contract, and Windows PE engine. + +### Section 5 — Troubleshooting and Development + +Chapter placeholders: Unbound breakpoints, diagnostics, testing, and extension points. + +## Available documentation + +- [Current walkthrough](../zasm/zasm-05-03-zero-debugger.md) +- [Existing debugger guide](../debugger/index.md) +- [Architecture](../debugger/architecture.md) +- [Windows PE engine](../debugger/winpe.md) +- [Testing](../debugger/testing.md) diff --git a/docs/ide/index.md b/docs/ide/index.md new file mode 100644 index 0000000..83a70cd --- /dev/null +++ b/docs/ide/index.md @@ -0,0 +1,41 @@ +--- +layout: default +title: "Zero.IDE User Guide" +--- + +# Zero.IDE User Guide + +[Documentation library](../index.md) · [Zero Assembly book](../zasm/index.md) + +**Planned companion book.** This page reserves a home and section structure for +future chapters. The outline is documentation work to come, not a promise that +every named feature is implemented. Use the current guides below today. + +## Planned sections + +### Section 1 — Getting Started + +Chapter placeholders: Installation, configuration, folders, and a first source file. + +### Section 2 — Editing + +Chapter placeholders: Documents, shortcuts, appearance, indentation, and cleanup. + +### Section 3 — Building and Running + +Chapter placeholders: Compiler selection, configurations, outputs, and diagnostics. + +### Section 4 — Debugging + +Chapter placeholders: Breakpoints, stepping, registers, and session controls. + +### Section 5 — Reference and Troubleshooting + +Chapter placeholders: Settings, updates, workflows, and failures. + +## Available documentation + +- [Current installation chapter](../zasm/zasm-01-03-installing-zero-ide.md) +- [Current first-project chapter](../zasm/zasm-01-04-using-zero-ide-my-first-project.md) +- [Settings and build notes](../building.md) +- [Execution architecture](../ide-execution.md) diff --git a/docs/index.md b/docs/index.md index f4b9d77..321a782 100644 --- a/docs/index.md +++ b/docs/index.md @@ -22,6 +22,19 @@ define data, share headers, call Windows DLL functions, or use Linux syscalls. [Debugger](debugger/index.md) · [Source code](https://github.com/SuessLabs/ZeroCompiler) +## Documentation Library + +Start with the chapter-based [Zero Assembly Programmers Guide](zasm/index.md). +It includes a first program, fundamentals, functions, a Notepad project workshop, +compiler/debugger usage, architecture, and mnemonic/ASCII appendices. + +| Book | Status | +| --- | --- | +| [Zero Assembly Programmers Guide](zasm/index.md) | Main learning guide | +| [Zero and Zero.CLI Guide](zero/index.md) | Companion book placeholder | +| [Zero.IDE User Guide](ide/index.md) | Companion book placeholder | +| [Zero.DBG User Guide](dbg/index.md) | Companion book placeholder; existing debugger docs retained | + ## About The Zero programming language and compiler project (_AKA: Null Compiler_). **Zero** is a simple, fast, and efficient programming language for the x86-64 architecture. @@ -29,7 +42,7 @@ The Zero programming language and compiler project (_AKA: Null Compiler_). **Zer The compiler generates Windows x86 PE32 console executables (including programs that create Windows GUI controls) and static Linux x86-64 ELF64 executables using syscalls. Shared-library ELF linking, DLL output, additional architectures, macOS, -and STM32 remain future work. See [Linux x86-64 support](docs/linux64.md). +and STM32 remain future work. See [Linux x86-64 support](linux64.md). ## Zero Language Suite diff --git a/docs/zasm/ZASM-Examples.md b/docs/zasm/ZASM-Examples.md index addfc45..af437e2 100644 --- a/docs/zasm/ZASM-Examples.md +++ b/docs/zasm/ZASM-Examples.md @@ -5,6 +5,8 @@ title: ZASM Basic Examples # ZASM Basic Examples +For a chapter-based learning path, read the [Zero Assembly Programmers Guide](index.md). + [Documentation home](../index.md) · [Language reference](ZASM-Reference.md) · [Mnemonic support](ZASM-Mnemonics.md) diff --git a/docs/zasm/ZASM-Intro.md b/docs/zasm/ZASM-Intro.md index 5a39414..8f9eea8 100644 --- a/docs/zasm/ZASM-Intro.md +++ b/docs/zasm/ZASM-Intro.md @@ -5,6 +5,8 @@ title: Zero Assembly Overview # Zero Assembly Overview +For a chapter-based learning path, read the [Zero Assembly Programmers Guide](index.md). + [Documentation home](../index.md) · [Full language reference](ZASM-Reference.md) · [Basic examples](ZASM-Examples.md) · [Mnemonic support](ZASM-Mnemonics.md) diff --git a/docs/zasm/ZASM-Reference.md b/docs/zasm/ZASM-Reference.md index 81ba356..6d4faeb 100644 --- a/docs/zasm/ZASM-Reference.md +++ b/docs/zasm/ZASM-Reference.md @@ -5,6 +5,8 @@ title: ZASM Language Reference # ZASM Language Reference +For a chapter-based learning path, read the [Zero Assembly Programmers Guide](index.md). + [Documentation home](../index.md) · [Complete examples](ZASM-Examples.md) · [Include files](ZASM-Include-Files.md) · [Mnemonic support](ZASM-Mnemonics.md) diff --git a/docs/zasm/index.md b/docs/zasm/index.md new file mode 100644 index 0000000..ad5dc9c --- /dev/null +++ b/docs/zasm/index.md @@ -0,0 +1,103 @@ +--- +layout: default +title: Zero Assembly Programmers Guide +--- + +# Zero Assembly Programmers Guide + +[Documentation library](../index.md) · [Start reading](zasm-01-01-what-is-zero-assembly.md) + +Learn Zero Assembly from your first instruction to a small Windows editing +application. Read in order or revisit individual topics through the contents. +Every chapter links to its neighbors and back to this page. + +## How to use this book + +The main path uses Windows x86 on a Windows x64 computer. Linux x64 examples +are labeled separately. Fragments require surrounding code; chapters explicitly +identify complete programs. Commands assume the stated working directory and +compiler layout. + +Current compiler limits appear beside the affected lessons. Structure declarations, +full instruction-set coverage, and advanced Notepad features are not implied by +a chapter title. The Notepad project starts with a working sample, builds a +multiline editor, then provides a workshop for persistence and later features. + +Sections are consecutive in reading order: Notepad is Section 4, Compiler and +Debugging is Section 5, and Architecture is Section 6. Section 7 holds the two +appendices. Filenames follow `zasm-{section}-{chapter}-{title}.md`, using two-digit +numbers and lowercase, hyphenated titles. For example, +`zasm-02-01-moving-numbers.md` is Chapter 2.1. + +## Contents + +### Section 1 — Intro + +1. [What Is Zero Assembly?](zasm-01-01-what-is-zero-assembly.md) +2. [Why Learn Assembly Today?](zasm-01-02-why-learn-assembly-today.md) +3. [Installing Zero.IDE](zasm-01-03-installing-zero-ide.md) +4. [Using Zero.IDE — My First Project](zasm-01-04-using-zero-ide-my-first-project.md) +5. [Hello, Zero Assembly](zasm-01-05-hello-zero-assembly.md) + +### Section 2 — Basics + +1. [Moving Numbers](zasm-02-01-moving-numbers.md) +2. [Performing Jumps](zasm-02-02-performing-jumps.md) +3. [Storing Data and Printing](zasm-02-03-storing-data-and-printing.md) +4. [Boolean Algebra](zasm-02-04-boolean-algebra.md) +5. [Basic Variables](zasm-02-05-basic-variables.md) + +### Section 3 — Level-Up Learning + +1. [Calling External Library Functions](zasm-03-01-calling-external-library-functions.md) +2. [Creating Structs](zasm-03-02-creating-structs.md) +3. [Working with Strings](zasm-03-03-working-with-strings.md) +4. [Organizing Your System](zasm-03-04-organizing-your-system.md) +5. [Arithmetic Operations](zasm-03-05-arithmetic-operations.md) +6. [Performing Bit Manipulations](zasm-03-06-performing-bit-manipulations.md) +7. [Creating Functions](zasm-03-07-creating-functions.md) + +### Section 4 — Creating a Notepad Project + +1. [Notepad Project — Set Up the Workspace](zasm-04-01-notepad-project-setup.md) +2. [Notepad Project — Create the Window](zasm-04-02-notepad-create-the-window.md) +3. [Notepad Project — Add the Text Editor](zasm-04-03-notepad-add-the-text-editor.md) +4. [Notepad Project — Open and Save Files](zasm-04-04-notepad-open-and-save-files.md) +5. [Notepad Project — Test and Extend](zasm-04-05-notepad-testing-and-next-steps.md) + +### Section 5 — Compiler and Debugging + +1. [Zero Compiler (Zero.CLI)](zasm-05-01-zero-cli-compiler.md) +2. [Compiler Switches](zasm-05-02-compiler-switches.md) +3. [Zero Debugger (Zero.DBG)](zasm-05-03-zero-debugger.md) + +### Section 6 — Architecture + +1. [The x86 Instruction Set](zasm-06-01-x86-instruction-set.md) +2. [The x64 Instruction Set](zasm-06-02-x64-instruction-set.md) +3. [What Is Windows PE?](zasm-06-03-what-is-windows-pe.md) +4. [What Is ELF?](zasm-06-04-what-is-elf.md) +5. [What Is ARM?](zasm-06-05-what-is-arm.md) + +### Appendices + +1. [Appendix I — Mnemonic Lookup](zasm-07-01-mnemonic-lookup.md) +2. [Appendix II — ASCII Character Set](zasm-07-02-ascii-character-set.md) + +## Reference shelf + +Existing reference filenames remain intact for bookmarks and external links. +Use the book for learning and these pages for detailed lookup: + +- [Language reference](ZASM-Reference.md): syntax, operands, imports, and limitations. +- [Mnemonic inventory](ZASM-Mnemonics.md): implemented and missing forms by target. +- [Include files](ZASM-Include-Files.md): header loading and search rules. +- [Complete examples](ZASM-Examples.md) and [assembly overview](ZASM-Intro.md). +- [Linux x64](../linux64.md) and [Windows headers](../windows-headers.md). +- [Feature roadmap](ZASM-Coming-Soon.md) and [syntax proposals](ZASM-vNext-Sandbox.md). + +## Companion books + +- [Zero and Zero.CLI](../zero/index.md) — planned language and compiler guide. +- [Zero.IDE](../ide/index.md) — planned IDE user guide. +- [Zero.DBG](../dbg/index.md) — planned debugger user guide; existing technical docs remain available. diff --git a/docs/zasm/zasm-01-01-what-is-zero-assembly.md b/docs/zasm/zasm-01-01-what-is-zero-assembly.md new file mode 100644 index 0000000..a2d80a4 --- /dev/null +++ b/docs/zasm/zasm-01-01-what-is-zero-assembly.md @@ -0,0 +1,37 @@ +--- +layout: default +title: "What Is Zero Assembly?" +--- + +# What Is Zero Assembly? + +Section 1 — Intro · Chapter 1.1 + +[Library](../index.md) · [Contents](index.md) · [Next](zasm-01-02-why-learn-assembly-today.md) + +Zero Assembly (ZASM) is the assembly language accepted by the Zero compiler. +You describe instructions, data, and operating-system calls in a text file; +Zero turns them into a native executable. + +```asm +mov eax, 42 +add eax, 8 +``` + +This fragment puts 42 in EAX, then adds 8. A register is a small storage location +in the processor. The destination comes first: `add eax, 8` changes EAX. + +ZASM currently targets Windows x86 PE32 and static Linux x64 ELF64. Most lessons +use **Windows x86**, including the GUI project. Linux examples are labeled. +A Windows x64 compiler executable does not mean it produces Windows x64 programs. + +Source files use `.zasm`; shared headers use `.zh`. The higher-level Zero +language uses `.zsrc` and remains under redesign. Future features are labeled +where they arise. + +> **Checkpoint:** Explain the difference between source text, a compiler, and an +executable. The [language reference](ZASM-Reference.md) supplies exact operand rules. + +--- + +[Library](../index.md) · [Contents](index.md) · [Next](zasm-01-02-why-learn-assembly-today.md) diff --git a/docs/zasm/zasm-01-02-why-learn-assembly-today.md b/docs/zasm/zasm-01-02-why-learn-assembly-today.md new file mode 100644 index 0000000..4d1c9b9 --- /dev/null +++ b/docs/zasm/zasm-01-02-why-learn-assembly-today.md @@ -0,0 +1,33 @@ +--- +layout: default +title: "Why Learn Assembly Today?" +--- + +# Why Learn Assembly Today? + +Section 1 — Intro · Chapter 1.2 + +[Previous](zasm-01-01-what-is-zero-assembly.md) · [Contents](index.md) · [Next](zasm-01-03-installing-zero-ide.md) + +Assembly makes the work of a program visible: values move through registers, +branches choose the next instruction, and calls enter another routine or the +operating system. These steps help you read debugger output and understand +code generated by higher-level languages. + +Begin with a small goal: follow one value from input to output. You do not need +to memorize instruction encodings before writing your first program. Here you +will print text, manipulate numbers, and build a small Windows editor. + +Assembly makes responsibilities explicit. A buffer has a capacity; a pointer +has an address; a called function expects arguments in a particular layout. +The compiler cannot infer all of these contracts for you. + +Keep three questions beside each example: What value changes? Where is it +stored? Who owns the storage? They become useful when stepping through calls. + +**Exercise:** Identify an operation in a familiar application that needs +arithmetic, one that needs a branch, and one that asks the OS for a service. + +--- + +[Previous](zasm-01-01-what-is-zero-assembly.md) · [Contents](index.md) · [Next](zasm-01-03-installing-zero-ide.md) diff --git a/docs/zasm/zasm-01-03-installing-zero-ide.md b/docs/zasm/zasm-01-03-installing-zero-ide.md new file mode 100644 index 0000000..c3adc28 --- /dev/null +++ b/docs/zasm/zasm-01-03-installing-zero-ide.md @@ -0,0 +1,42 @@ +--- +layout: default +title: "Installing Zero.IDE" +--- + +# Installing Zero.IDE + +Section 1 — Intro · Chapter 1.3 + +[Previous](zasm-01-02-why-learn-assembly-today.md) · [Contents](index.md) · [Next](zasm-01-04-using-zero-ide-my-first-project.md) + +Use a Windows x64 computer for the main learning path and native debugger. +The IDE and compiler have independent versions; retain a compatible pair. + +1. Open the release downloads from the + [documentation home](../index.md#download-and-install). +2. If the release provides a Windows x64 **Zero.IDE setup** asset, download and + run it. IDE setup includes the CLI installer and uses a shared install root. +3. Launch `Zero.Ide.exe` from the installed `ide` directory or its launcher. +4. Open **Tools > Options > Compiler**. The IDE discovers the sibling + `bin/zero.exe` for new or blank settings; select it explicitly if necessary. +5. Save a new `.zasm` file in a writable folder outside Program Files. + +```text +Zero/ + bin/zero.exe + ide/Zero.Ide.exe + include/windows/ + samples/ + docs/ +``` + +A portable CLI ZIP is useful for terminal lessons. Keep its `include` directory +beside `zero.exe`. If a release has no IDE installer, build the IDE using the +[build instructions](../building.md); do not expect the compiler ZIP to contain it. + +See the [installer guide](../../installer/README.md) for packaging and other hosts. +**Checkpoint:** Confirm the selected compiler displays `--help` in a terminal. + +--- + +[Previous](zasm-01-02-why-learn-assembly-today.md) · [Contents](index.md) · [Next](zasm-01-04-using-zero-ide-my-first-project.md) diff --git a/docs/zasm/zasm-01-04-using-zero-ide-my-first-project.md b/docs/zasm/zasm-01-04-using-zero-ide-my-first-project.md new file mode 100644 index 0000000..3bb428f --- /dev/null +++ b/docs/zasm/zasm-01-04-using-zero-ide-my-first-project.md @@ -0,0 +1,40 @@ +--- +layout: default +title: "Using Zero.IDE — My First Project" +--- + +# Using Zero.IDE — My First Project + +Section 1 — Intro · Chapter 1.4 + +[Previous](zasm-01-03-installing-zero-ide.md) · [Contents](index.md) · [Next](zasm-01-05-hello-zero-assembly.md) + +A project in these lessons is a folder containing a main `.zasm` file and optional +headers. A dedicated Zero project-file format is future work. + +1. Create a writable folder named `HelloZero`. +2. Choose **File > Open Folder...** in Zero.IDE and select it. +3. Choose **File > New**, then **File > Save As...** to save `hello.zasm` there. +4. Enter the complete program from the next chapter and save it. +5. Choose **Build > Build** (`Ctrl+B`). Use **Build > Build Output...** to + inspect diagnostics if compilation fails. +6. Choose **Build > Run Without Debugging** to launch normally. For console + output that should stay visible, run the CLI from an existing terminal. +7. Press **F9** on an instruction to set a breakpoint, then **F5** to debug. + The debugger initially pauses at entry. **F10** steps over an instruction + or call; **Shift+F5** stops the session. + +The IDE writes output under the source folder at +`.zeroide///`. Use **Build > Build Output...** to find +the artifact. CLI default output locations are described later. + +If a header is missing, check the compiler location and installed `include` +layout. Save modified headers before debugging. Source editors are read-only +during a debug session. + +**Checkpoint:** Locate your source file, compiler executable, and generated +executable. Each has a different role. + +--- + +[Previous](zasm-01-03-installing-zero-ide.md) · [Contents](index.md) · [Next](zasm-01-05-hello-zero-assembly.md) diff --git a/docs/zasm/zasm-01-05-hello-zero-assembly.md b/docs/zasm/zasm-01-05-hello-zero-assembly.md new file mode 100644 index 0000000..ebe9ead --- /dev/null +++ b/docs/zasm/zasm-01-05-hello-zero-assembly.md @@ -0,0 +1,54 @@ +--- +layout: default +title: "Hello, Zero Assembly" +--- + +# Hello, Zero Assembly + +Section 1 — Intro · Chapter 1.5 + +[Previous](zasm-01-04-using-zero-ide-my-first-project.md) · [Contents](index.md) · [Next](zasm-02-01-moving-numbers.md) + +Save this complete Windows x86 program as `hello.zasm`: + +```asm +using "windows/console.zh" + + jmp start + +message db 'Hello, Zero Assembly!', 0 + +start: + push message + call [puts] + add esp, 4 + + push 0 + call [exit] +``` + +Open PowerShell in the source folder. For the default installed compiler: + +```powershell +& 'C:\Program Files\SuessLabs\Zero\bin\zero.exe' run hello.zasm +``` + +For a portable compiler, substitute its full executable path. The program prints: + +```text +Hello, Zero Assembly! +``` + +`using` loads DLL declarations. `jmp start` skips inline data: the first emitted +byte is the entry point, and `start` is only a label. `db` emits text and an +ending zero. `push message` passes its address. `call [puts]` calls through an +imported function pointer. `puts` adds a newline. Its cdecl convention makes us +remove four argument bytes with `add esp, 4`. `exit(0)` ends the process. + +Later snippets are **fragments** unless called complete programs. Insert them +into a complete program before termination; never execute inline data. +**Exercise:** Change the greeting and run it again. + +--- + +[Previous](zasm-01-04-using-zero-ide-my-first-project.md) · [Contents](index.md) · [Next](zasm-02-01-moving-numbers.md) diff --git a/docs/zasm/zasm-02-01-moving-numbers.md b/docs/zasm/zasm-02-01-moving-numbers.md new file mode 100644 index 0000000..02d4dae --- /dev/null +++ b/docs/zasm/zasm-02-01-moving-numbers.md @@ -0,0 +1,36 @@ +--- +layout: default +title: "Moving Numbers" +--- + +# Moving Numbers + +Section 2 — Basics · Chapter 2.1 + +[Previous](zasm-01-05-hello-zero-assembly.md) · [Contents](index.md) · [Next](zasm-02-02-performing-jumps.md) + +A number written in an instruction is an immediate value. `42`, `0x2A`, and +`2Ah` are spellings of the same integer. + +```asm +mov eax, 42 +mov ebx, 0x2A +push eax +pop ecx +``` + +EAX, EBX, and ECX now hold 42. Windows x86 supports immediate loads and memory +loads with `MOV`, but not register-to-register `MOV`. The balanced `push`/`pop` +pair copies through the stack. It temporarily changes ESP; do not insert +unrelated stack operations between the pair. + +A register holds bits. Whether those bits represent a signed integer, an +unsigned integer, or an address depends on the operation using them. On this +target the general-purpose registers are 32 bits wide. + +**Exercise:** Load 100 into EAX, copy it into EDX using the stack, and inspect +both registers. Linux x64 has broader `MOV` forms; see [Linux x64](../linux64.md). + +--- + +[Previous](zasm-01-05-hello-zero-assembly.md) · [Contents](index.md) · [Next](zasm-02-02-performing-jumps.md) diff --git a/docs/zasm/zasm-02-02-performing-jumps.md b/docs/zasm/zasm-02-02-performing-jumps.md new file mode 100644 index 0000000..97cac3d --- /dev/null +++ b/docs/zasm/zasm-02-02-performing-jumps.md @@ -0,0 +1,39 @@ +--- +layout: default +title: "Performing Jumps" +--- + +# Performing Jumps + +Section 2 — Basics · Chapter 2.2 + +[Previous](zasm-02-01-moving-numbers.md) · [Contents](index.md) · [Next](zasm-02-03-storing-data-and-printing.md) + +A jump changes which instruction executes next. `JMP` always branches. `JZ` +branches when the zero flag is set; `JNZ` branches when it is clear. + +```asm +mov ecx, 3 +again: + sub ecx, 1 + cmp ecx, 0 + jnz again +``` + +The loop stops after three subtractions. `CMP` sets flags as if subtracting its +second operand from the first, without changing either operand. Equality sets +the zero flag. `SUB` also sets flags, but the explicit comparison makes the +condition easy to see. + +Keep a branch near the instruction establishing its condition: intervening +arithmetic can replace those flags. Labels and forward references are resolved +by the compiler. Use unique labels for distinct locations. + +Use `JZ` and `JNZ` normally. `JZ8` and `JNZ8` require a short displacement in +range. `JE`, `JNE`, and greater/less-than branches are not implemented. + +**Exercise:** Start the loop at 5. Step through and watch ECX and EIP. + +--- + +[Previous](zasm-02-01-moving-numbers.md) · [Contents](index.md) · [Next](zasm-02-03-storing-data-and-printing.md) diff --git a/docs/zasm/zasm-02-03-storing-data-and-printing.md b/docs/zasm/zasm-02-03-storing-data-and-printing.md new file mode 100644 index 0000000..78ac17e --- /dev/null +++ b/docs/zasm/zasm-02-03-storing-data-and-printing.md @@ -0,0 +1,44 @@ +--- +layout: default +title: "Storing Data and Printing" +--- + +# Storing Data and Printing + +Section 2 — Basics · Chapter 2.3 + +[Previous](zasm-02-02-performing-jumps.md) · [Contents](index.md) · [Next](zasm-02-04-boolean-algebra.md) + +`DB` emits bytes and UTF-8 strings, `DW` emits 16-bit integers, and `DD` emits +32-bit integers. + +```asm + jmp start +format db 'Value: %d', 0 +value: dd 42 +start: + mov eax, [value] + push eax + push format + call [printf] + add esp, 8 +``` + +This fragment requires `using "windows/console.zh"` before the jump and an +explicit process exit afterward. `printf` receives arguments right to left: +the value first, then the format address. Two 32-bit arguments occupy eight +bytes, which the caller removes. For a Windows line ending, append bytes +`13, 10` before the format's ending zero. + +`value` means an address; `[value]` reads its contents. Do not confuse pointers +and numbers when passing arguments. + +Inline data is in the read-only code section. `value: dd 42` does not make a +writable variable. Use stack or allocated storage for values that change. + +**Exercise:** Change the initial value and predict the output. Compare the +[complete output sample](../../samples/Windows/win-cli-02-console-printf-db-vars.zasm). + +--- + +[Previous](zasm-02-02-performing-jumps.md) · [Contents](index.md) · [Next](zasm-02-04-boolean-algebra.md) diff --git a/docs/zasm/zasm-02-04-boolean-algebra.md b/docs/zasm/zasm-02-04-boolean-algebra.md new file mode 100644 index 0000000..7180f73 --- /dev/null +++ b/docs/zasm/zasm-02-04-boolean-algebra.md @@ -0,0 +1,39 @@ +--- +layout: default +title: "Boolean Algebra" +--- + +# Boolean Algebra + +Section 2 — Basics · Chapter 2.4 + +[Previous](zasm-02-03-storing-data-and-printing.md) · [Contents](index.md) · [Next](zasm-02-05-basic-variables.md) + +Boolean operations act on individual bits: + +| A | B | A AND B | A OR B | A XOR B | +| --- | --- | --- | --- | --- | +| 0 | 0 | 0 | 0 | 0 | +| 0 | 1 | 0 | 1 | 1 | +| 1 | 0 | 0 | 1 | 1 | +| 1 | 1 | 1 | 1 | 0 | + +```asm +mov eax, 0x0A ; 1010 in binary. +and eax, 0x0C ; EAX = 8. +or eax, 1 ; EAX = 9. +xor eax, 3 ; EAX = 10. +test eax, 2 ; Test without modifying EAX. +``` + +`TEST` sets flags from AND but leaves its operands unchanged. `AND`, `OR`, and +`XOR` store the result and update flags. After `test eax, 2`, `JZ` would branch +if that bit were clear. Supply the branch target in your complete program. + +Use hexadecimal masks: binary literal syntax is not currently supported. + +**Exercise:** Work out `0x0F AND 0x05` on paper, then verify it in EAX. + +--- + +[Previous](zasm-02-03-storing-data-and-printing.md) · [Contents](index.md) · [Next](zasm-02-05-basic-variables.md) diff --git a/docs/zasm/zasm-02-05-basic-variables.md b/docs/zasm/zasm-02-05-basic-variables.md new file mode 100644 index 0000000..488cbf1 --- /dev/null +++ b/docs/zasm/zasm-02-05-basic-variables.md @@ -0,0 +1,38 @@ +--- +layout: default +title: "Basic Variables" +--- + +# Basic Variables + +Section 2 — Basics · Chapter 2.5 + +[Previous](zasm-02-04-boolean-algebra.md) · [Contents](index.md) · [Next](zasm-03-01-calling-external-library-functions.md) + +A variable is storage with an agreed meaning and lifetime. Registers provide +temporary storage. Named data declarations provide initial bytes, but current +inline data is read-only. + +```asm +push 42 +lea esi, [esp] ; Address of a writable four-byte slot. +mov eax, [esi] ; Read 42. +add esp, 4 ; Release it; ESI must no longer be used for that slot. +``` + +`LEA` calculates an address without reading memory. For an API output buffer, +reserve sufficient bytes with `sub esp, capacity` and pass its address. Release +the reservation only when all users of that storage have finished. + +Windows x86 memory-store instructions are not implemented: do not write +`mov [value], eax`. Stack pushes and imported functions can populate writable +storage. Linux x64 supports register-to-memory stores, but its inline data is +still read-only. An instruction cannot override memory permissions. + +Calls can overwrite temporary registers. Follow the calling convention and +preserve values needed afterward. **Exercise:** Explain why a pointer to +released stack storage cannot serve as a lasting variable. + +--- + +[Previous](zasm-02-04-boolean-algebra.md) · [Contents](index.md) · [Next](zasm-03-01-calling-external-library-functions.md) diff --git a/docs/zasm/zasm-03-01-calling-external-library-functions.md b/docs/zasm/zasm-03-01-calling-external-library-functions.md new file mode 100644 index 0000000..d498dfb --- /dev/null +++ b/docs/zasm/zasm-03-01-calling-external-library-functions.md @@ -0,0 +1,43 @@ +--- +layout: default +title: "Calling External Library Functions" +--- + +# Calling External Library Functions + +Section 3 — Level-Up Learning · Chapter 3.1 + +[Previous](zasm-02-05-basic-variables.md) · [Contents](index.md) · [Next](zasm-03-02-creating-structs.md) + +On Windows x86, `#IMPORT` declares DLL exports. Shipped `.zh` headers group +these declarations, so programs usually include a header instead. + +```asm +#IMPORT kernel32.dll, ExitProcess +push 0 +call [ExitProcess] +``` + +This is a complete minimal program. Brackets mean an indirect call through the +import slot populated by the Windows loader. Preserve export spelling. + +| Convention | Argument order | Argument cleanup | Examples | +| --- | --- | --- | --- | +| cdecl | Push right to left | Caller | `puts`, `printf`, `strcpy` | +| stdcall | Push right to left | Callee | `MessageBoxA`, `WriteFile` | + +Do not remove a stdcall function's arguments a second time with `add esp, ...`. +Independently reserved local buffers still need their own cleanup. EAX commonly +carries the result; EAX, ECX, and EDX are volatile in these conventions. Preserve +EBX, ESI, EDI, and EBP in procedures that change them. + +An import declaration does not validate argument types, capacity, or callbacks. +Read the API contract before adding a call. Linux's current backend uses system +calls rather than imported Windows DLLs. + +**Exercise:** Find caller cleanup in the hello program and callee cleanup in the +[MessageBox sample](../../samples/Windows/win-ui-01-msgbox.zasm). + +--- + +[Previous](zasm-02-05-basic-variables.md) · [Contents](index.md) · [Next](zasm-03-02-creating-structs.md) diff --git a/docs/zasm/zasm-03-02-creating-structs.md b/docs/zasm/zasm-03-02-creating-structs.md new file mode 100644 index 0000000..8ddaf8c --- /dev/null +++ b/docs/zasm/zasm-03-02-creating-structs.md @@ -0,0 +1,44 @@ +--- +layout: default +title: "Creating Structs" +--- + +# Creating Structs + +Section 3 — Level-Up Learning · Chapter 3.2 + +[Previous](zasm-03-01-calling-external-library-functions.md) · [Contents](index.md) · [Next](zasm-03-03-working-with-strings.md) + +A structure is a layout agreement: fields occupy known offsets in contiguous +storage. ZASM does not yet provide `struct` declarations, typed fields, or +automatic layout. Use explicit storage and offsets. + +For an x86 record containing a 32-bit count and a 32-bit pointer: + +| Offset | Size | Meaning | +| --- | --- | --- | +| 0 | 4 bytes | Count | +| 4 | 4 bytes | Pointer | + +```asm +; Assume EAX contains a valid pointer. +push eax ; Last field first. +push 3 ; Count at the lowest address. +lea edx, [esp] ; Address of the record. +mov ecx, [edx] ; Count = 3. +mov eax, [edx + 4] +add esp, 8 +``` + +The stack grows toward lower addresses, so pushing fields in reverse creates +the layout shown. OS structures require ABI-defined offsets and alignment; +changing pointer width can change their layout. + +The [Windows controls sample](../../samples/Windows/win-ui-02-controls.zasm) +builds `WNDCLASSA` this way. Study its 40-byte layout and callback pointer before +the Notepad project. **Exercise:** Add a third 32-bit field on paper and derive +its offset and the total size. + +--- + +[Previous](zasm-03-01-calling-external-library-functions.md) · [Contents](index.md) · [Next](zasm-03-03-working-with-strings.md) diff --git a/docs/zasm/zasm-03-03-working-with-strings.md b/docs/zasm/zasm-03-03-working-with-strings.md new file mode 100644 index 0000000..8fbab4a --- /dev/null +++ b/docs/zasm/zasm-03-03-working-with-strings.md @@ -0,0 +1,39 @@ +--- +layout: default +title: "Working with Strings" +--- + +# Working with Strings + +Section 3 — Level-Up Learning · Chapter 3.3 + +[Previous](zasm-03-02-creating-structs.md) · [Contents](index.md) · [Next](zasm-03-04-organizing-your-system.md) + +`DB` can encode text with an explicit zero terminator: + +```asm +greeting db 'Hello', 0 +newline db 13, 10, 0 +``` + +These are data fragments; place them behind a jump. A C-style string ends at +its first zero byte. Its length excludes that terminator; capacity includes it. + +To concatenate text, use writable destination storage. The complete +[string concatenation sample](../../samples/Windows/win-cli-05-string-concat.zasm) +reserves 64 stack bytes and calls `strcpy` and `strcat` to build +`Hello Zero Assembly!`. It needs 21 bytes including the ending zero. These +functions do not know the destination capacity: prove the bound before calling +them. Do not copy unbounded user input with this pattern. + +ZASM literals emit UTF-8 bytes. Windows `A` APIs interpret bytes using an ANSI +code page; `W` APIs require UTF-16. ASCII is a common starting point; arbitrary +UTF-8 is not automatically compatible with either API family. Choose an encoding +and convert deliberately for a larger editor. + +**Exercise:** Count bytes for two ASCII strings, a space, and an ending zero. +Compare the [ASCII appendix](zasm-07-02-ascii-character-set.md). + +--- + +[Previous](zasm-03-02-creating-structs.md) · [Contents](index.md) · [Next](zasm-03-04-organizing-your-system.md) diff --git a/docs/zasm/zasm-03-04-organizing-your-system.md b/docs/zasm/zasm-03-04-organizing-your-system.md new file mode 100644 index 0000000..cb7f768 --- /dev/null +++ b/docs/zasm/zasm-03-04-organizing-your-system.md @@ -0,0 +1,44 @@ +--- +layout: default +title: "Organizing Your System" +--- + +# Organizing Your System + +Section 3 — Level-Up Learning · Chapter 3.4 + +[Previous](zasm-03-03-working-with-strings.md) · [Contents](index.md) · [Next](zasm-03-05-arithmetic-operations.md) + +Start with a small layout: + +```text +MyProgram/ + main.zasm + headers/ + imports.zh + notes/ +``` + +Put shared import declarations in `headers/imports.zh`. Include them with +`using "headers/imports.zh"`. Includes compose source; they do not provide +separate object-file compilation or linking. + +The loader searches the current working directory, repeatable `-I` directories +in order, `include` beside the compiler, then `../include` for a compiler +installed in `bin`. Nested includes use the same search order; do not assume +they resolve relative to their containing header. Run terminal builds from a +consistent directory. The IDE uses the source folder as the working directory. + +A file is included once; cycles are diagnosed. Use unique labels across the +combined source. Included code and data affect the first emitted byte and +control flow, even though import declarations emit no instructions. + +See [include-file details](ZASM-Include-Files.md). Multi-file linking, namespaces, +and a project manifest are future work. + +**Exercise:** Move only the hello program's import declarations into a local +header and verify that the program behaves the same way. + +--- + +[Previous](zasm-03-03-working-with-strings.md) · [Contents](index.md) · [Next](zasm-03-05-arithmetic-operations.md) diff --git a/docs/zasm/zasm-03-05-arithmetic-operations.md b/docs/zasm/zasm-03-05-arithmetic-operations.md new file mode 100644 index 0000000..be193b7 --- /dev/null +++ b/docs/zasm/zasm-03-05-arithmetic-operations.md @@ -0,0 +1,47 @@ +--- +layout: default +title: "Arithmetic Operations" +--- + +# Arithmetic Operations + +Section 3 — Level-Up Learning · Chapter 3.5 + +[Previous](zasm-03-04-organizing-your-system.md) · [Contents](index.md) · [Next](zasm-03-06-performing-bit-manipulations.md) + +The implemented integer arithmetic begins with `ADD` and `SUB`: + +```asm +mov eax, 20 +add eax, 22 ; 42. +sub eax, 2 ; 40. +mov ebx, 10 +add eax, ebx ; 50. +``` + +Arithmetic changes its destination and flags. A 32-bit result retains the low +32 bits: adding 1 to `0xFFFFFFFF` yields zero. Decide whether wrapping is valid +for your program and choose checks appropriate to that decision. + +For a small repeated-addition exercise, multiply 7 by 3: + +```asm +mov eax, 0 +mov ecx, 3 +multiply_again: + add eax, 7 + sub ecx, 1 + jnz multiply_again +``` + +This assumes a positive, nonzero count. Starting at zero would wrap on the first +subtraction and create a very long loop. General algorithms must handle zero +and other boundaries explicitly. + +`MUL`, `IMUL`, `DIV`, `IDIV`, `INC`, and `DEC` are not implemented. Check the +[mnemonic inventory](ZASM-Mnemonics.md) before adapting another assembler's code. +**Exercise:** Print the result using the earlier `printf` pattern. + +--- + +[Previous](zasm-03-04-organizing-your-system.md) · [Contents](index.md) · [Next](zasm-03-06-performing-bit-manipulations.md) diff --git a/docs/zasm/zasm-03-06-performing-bit-manipulations.md b/docs/zasm/zasm-03-06-performing-bit-manipulations.md new file mode 100644 index 0000000..344dad8 --- /dev/null +++ b/docs/zasm/zasm-03-06-performing-bit-manipulations.md @@ -0,0 +1,37 @@ +--- +layout: default +title: "Performing Bit Manipulations" +--- + +# Performing Bit Manipulations + +Section 3 — Level-Up Learning · Chapter 3.6 + +[Previous](zasm-03-05-arithmetic-operations.md) · [Contents](index.md) · [Next](zasm-03-07-creating-functions.md) + +A mask identifies bit positions in a value. For a 32-bit flags value in EAX: + +```asm +or eax, 0x04 ; Set bit 2, counting from bit 0. +and eax, 0xFFFFFFFB ; Clear bit 2; keep the other bits. +xor eax, 0x04 ; Toggle bit 2. +test eax, 0x04 ; Set ZF according to whether bit 2 is clear. +``` + +Setting an already-set bit leaves it set. Clearing an already-clear bit leaves +it clear. Toggling twice restores the original value. Testing changes flags +without changing the value. + +Match masks to register width. The clear mask above is the 32-bit complement +of `0x04`. Linux 64-bit destinations have different immediate encoding +constraints; consult that target's operand rules before porting masks. + +Shifts, rotates, `NOT`, and `BT`/`BTS`/`BTR` are not implemented. These concepts +can be added when the encoders support them. For now use AND/OR/XOR/TEST. + +**Exercise:** From zero, set bits 0 and 3, clear bit 0, and predict EAX before +inspecting it in the debugger. + +--- + +[Previous](zasm-03-05-arithmetic-operations.md) · [Contents](index.md) · [Next](zasm-03-07-creating-functions.md) diff --git a/docs/zasm/zasm-03-07-creating-functions.md b/docs/zasm/zasm-03-07-creating-functions.md new file mode 100644 index 0000000..9693a2c --- /dev/null +++ b/docs/zasm/zasm-03-07-creating-functions.md @@ -0,0 +1,46 @@ +--- +layout: default +title: "Creating Functions" +--- + +# Creating Functions + +Section 3 — Level-Up Learning · Chapter 3.7 + +[Previous](zasm-03-06-performing-bit-manipulations.md) · [Contents](index.md) · [Next](zasm-04-01-notepad-project-setup.md) + +A local function is a label reached with `CALL` and left with `RET`. Agree on +inputs, outputs, and preserved registers before writing its body. + +```asm +#IMPORT kernel32.dll, ExitProcess + + mov eax, 40 + call add_two + push eax + call [ExitProcess] + +; Input: EAX. Output: EAX + 2. Changes EAX and arithmetic flags. +add_two: + add eax, 2 + ret +``` + +This complete Windows x86 program exits with code 42. `CALL` pushes the return +address; `RET` pops it and resumes the caller. Process termination prevents +execution from falling through into the function a second time. + +At entry to an x86 stack-argument function, `[esp]` is the return address and +`[esp + 4]` is the first argument. Saving registers changes those offsets. +The controls sample uses `push ebp` and `lea ebp, [esp]` for stable offsets. + +A plain `ret` leaves arguments for the caller. `ret 16` also discards sixteen +argument bytes, as required by the four-argument stdcall window callback. Match +the caller's and callee's cleanup conventions. + +**Exercise:** Make `add_two` preserve EBX if you change it to use that register. +Balance pushes and pops on every return path. + +--- + +[Previous](zasm-03-06-performing-bit-manipulations.md) · [Contents](index.md) · [Next](zasm-04-01-notepad-project-setup.md) diff --git a/docs/zasm/zasm-04-01-notepad-project-setup.md b/docs/zasm/zasm-04-01-notepad-project-setup.md new file mode 100644 index 0000000..143efac --- /dev/null +++ b/docs/zasm/zasm-04-01-notepad-project-setup.md @@ -0,0 +1,37 @@ +--- +layout: default +title: "Notepad Project — Set Up the Workspace" +--- + +# Notepad Project — Set Up the Workspace + +Section 4 — Creating a Notepad Project · Chapter 4.1 + +[Previous](zasm-03-07-creating-functions.md) · [Contents](index.md) · [Next](zasm-04-02-notepad-create-the-window.md) + +Grow the shipped controls example into a small Notepad-like editor. The first +milestone is an editable window; the second is file saving and loading. This +Windows x86 project retains the current console subsystem, so a console window +may accompany the editor. + +1. Create a writable `ZeroNotepad` folder. +2. Copy [win-ui-02-controls.zasm](../../samples/Windows/win-ui-02-controls.zasm) + into it as `notepad.zasm`. Keep the original for comparison. +3. Open the folder and file in Zero.IDE. Select the installed compiler. +4. Build and run unchanged. Type text and press **Show message**. +5. Close the window and verify the process exits. + +Alternatively, from a terminal in the new source folder: + +```powershell +& 'C:\Program Files\SuessLabs\Zero\bin\zero.exe' notepad.zasm +.\notepad.exe +``` + +Use the next chapters in order and save a working copy after each milestone. +**Checkpoint:** Get the original sample working before changing registration, +the callback, or the message loop. + +--- + +[Previous](zasm-03-07-creating-functions.md) · [Contents](index.md) · [Next](zasm-04-02-notepad-create-the-window.md) diff --git a/docs/zasm/zasm-04-02-notepad-create-the-window.md b/docs/zasm/zasm-04-02-notepad-create-the-window.md new file mode 100644 index 0000000..4cd0143 --- /dev/null +++ b/docs/zasm/zasm-04-02-notepad-create-the-window.md @@ -0,0 +1,36 @@ +--- +layout: default +title: "Notepad Project — Create the Window" +--- + +# Notepad Project — Create the Window + +Section 4 — Creating a Notepad Project · Chapter 4.2 + +[Previous](zasm-04-01-notepad-project-setup.md) · [Contents](index.md) · [Next](zasm-04-03-notepad-add-the-text-editor.md) + +Read `start` in your copy. It obtains an instance handle, builds `WNDCLASSA` on +the stack, registers it, and creates a window. `window_proc` is its callback. + +1. Change `window_class` to `ZeroNotepadWindow` and `window_title` to + `Zero Notepad`. Retain their ending zero bytes. +2. In the top-level `CreateWindowExA` block, change height 220 to 480 and + width 420 to 680. Height is pushed before width because argument order is + right to left. +3. Retain `ShowWindow`, `UpdateWindow`, and the `GetMessageA` loop. +4. Retain the zero check for `WM_QUIT` and the `0xFFFFFFFF` error check. +5. Retain the `WM_DESTROY` handler calling `PostQuitMessage`. + +Build and run. The larger window should have its new title, with controls at +their old positions. Closing it must still end the program. + +The callback forwards unhandled messages to `DefWindowProcA`. Its EBP-based +frame exposes `hwnd` at +8, message at +12, `wParam` at +16, and `lParam` at +20. +Keep `pop ebp` and `ret 16` matched on every callback exit. + +**Checkpoint:** A visible window needs both a responsive message loop and a +working destruction path. + +--- + +[Previous](zasm-04-01-notepad-project-setup.md) · [Contents](index.md) · [Next](zasm-04-03-notepad-add-the-text-editor.md) diff --git a/docs/zasm/zasm-04-03-notepad-add-the-text-editor.md b/docs/zasm/zasm-04-03-notepad-add-the-text-editor.md new file mode 100644 index 0000000..ba7d8d9 --- /dev/null +++ b/docs/zasm/zasm-04-03-notepad-add-the-text-editor.md @@ -0,0 +1,53 @@ +--- +layout: default +title: "Notepad Project — Add the Text Editor" +--- + +# Notepad Project — Add the Text Editor + +Section 4 — Creating a Notepad Project · Chapter 4.3 + +[Previous](zasm-04-02-notepad-create-the-window.md) · [Contents](index.md) · [Next](zasm-04-04-notepad-open-and-save-files.md) + +Convert the single-line textbox into a multiline editing area. Keep ID 102 and +the Show message button for a quick readback test. + +1. Replace the block labeled `; Textbox:` up to, but not including, the + `; Button:` block with: + +```asm + ; Multiline EDIT control, ID 102, at (20, 46), size 620 x 300. + push 0 + push esi + push 102 + push ebx + push 300 + push 620 + push 46 + push 20 + push 0x50B110C4 + push initial_text + push edit_class + push 0 + call [CreateWindowExA] + test eax, eax + jz failed +``` + +2. The style combines child/visible/border/tab-stop, scroll bars, multiline, + automatic scrolling, and Enter-key input. In the `; Button:` block change + y from `push 90` to `push 360` to position the button below the editor. +3. Rebuild. Enter multiple lines, scroll, then click Show message. The callback + reads up to 255 characters into a 256-byte stack buffer: the popup is a + short preview, not a full-document export. +4. Keep fixed dimensions for now. Later, handle `WM_SIZE` and call `MoveWindow` + after obtaining the client area to implement resizing. + +This milestone provides a basic editor with readback. Persistence comes next. +The current APIs are ANSI; start with ASCII test input. + +**Checkpoint:** Confirm Enter inserts a line break and closing still exits. + +--- + +[Previous](zasm-04-02-notepad-create-the-window.md) · [Contents](index.md) · [Next](zasm-04-04-notepad-open-and-save-files.md) diff --git a/docs/zasm/zasm-04-04-notepad-open-and-save-files.md b/docs/zasm/zasm-04-04-notepad-open-and-save-files.md new file mode 100644 index 0000000..c201bc9 --- /dev/null +++ b/docs/zasm/zasm-04-04-notepad-open-and-save-files.md @@ -0,0 +1,51 @@ +--- +layout: default +title: "Notepad Project — Open and Save Files" +--- + +# Notepad Project — Open and Save Files + +Section 4 — Creating a Notepad Project · Chapter 4.4 + +[Previous](zasm-04-03-notepad-add-the-text-editor.md) · [Contents](index.md) · [Next](zasm-04-05-notepad-testing-and-next-steps.md) + +**Extension workshop:** the preceding edits and shipped sample do not implement +persistence. These are the next implementation steps, not a supplied finished +Notepad application. The file APIs are available through imports today. + +Start with a fixed test filename in the workspace; add dialogs after loading +and saving work. `kernel32.zh` declares file APIs and `user32.zh` declares text +control APIs. Declarations alone do not implement these routines. + +For **Save**: + +1. Obtain control 102 with `GetDlgItem`; call `GetWindowTextLengthA`. +2. Allocate length plus one for an ending zero. Use a bounded stack reservation + for a deliberately small exercise, or heap storage for variable-sized text. + Keep it alive until the write finishes. +3. Call `GetWindowTextA` with capacity including the zero. Use its returned + count as the byte count for this ANSI exercise, excluding the terminator. +4. Call `CreateFileA` with write access and a deliberate creation policy. + Check its failure sentinel before writing. +5. Call `WriteFile` with writable storage for the bytes-written result. Check + success and the byte count, then call `CloseHandle`. +6. On every failure, release acquired resources and show an error. Preserve + document state until saving is confirmed. + +For **Open**, open an existing file, determine and bound its size, allocate +size plus one, and call `ReadFile`. Check the actual count. Append an ending +zero in writable storage before `SetWindowTextA`. Direct x86 stores are missing: +use an imported routine such as `memset` for initialization/termination or a +zero-initialized heap allocation. Close the file and free the buffer on every +path. Treat embedded zero bytes as unsupported input. + +Retain the current document if reading fails. Do not mark it saved after a +failed or partial write. Then add New/Open/Save commands, dialogs, encoding +conversion, and an unsaved-changes prompt as separate tested features. + +**Checkpoint:** Define ownership, capacity, failure handling, and cleanup for +every pointer and handle before implementing these calls. + +--- + +[Previous](zasm-04-03-notepad-add-the-text-editor.md) · [Contents](index.md) · [Next](zasm-04-05-notepad-testing-and-next-steps.md) diff --git a/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md b/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md new file mode 100644 index 0000000..fe8ac2a --- /dev/null +++ b/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md @@ -0,0 +1,39 @@ +--- +layout: default +title: "Notepad Project — Test and Extend" +--- + +# Notepad Project — Test and Extend + +Section 4 — Creating a Notepad Project · Chapter 4.5 + +[Previous](zasm-04-04-notepad-open-and-save-files.md) · [Contents](index.md) · [Next](zasm-05-01-zero-cli-compiler.md) + +Validate one behavior at a time. Compare with the original sample to distinguish +existing behavior from regressions caused by edits. + +| Milestone | Check | Expected result | +| --- | --- | --- | +| Window | Launch and close repeatedly | Responsive window; process exits | +| Editing | Type, select, copy, paste, Enter | Multiline input works | +| Preview | Read fewer than 256 bytes | Popup matches entered text | +| Bounds | Preview a longer document | Bounded text; no stack corruption | +| Open extension | Missing or oversized file | Error; current document retained | +| Save extension | Empty and multiline text | Successful round trip | +| Save extension | Unwritable destination | Error; no false success state | + +Set a source breakpoint at `window_proc` or `window_command`, press F5, and +step over API calls with F10. Observe EAX results and ESP around calls. A +callback breakpoint can fire frequently as Windows delivers messages. + +Prioritize file persistence, error reporting, unsaved changes, resizing, and +encoding after the editing milestone. These are extensions to implement and +test: menu entries alone do not complete them. A production editor also needs +a deliberate large-file policy. + +**Checkpoint:** Record which milestones your copy implements. Keep a known +working copy until each new behavior passes its checks. + +--- + +[Previous](zasm-04-04-notepad-open-and-save-files.md) · [Contents](index.md) · [Next](zasm-05-01-zero-cli-compiler.md) diff --git a/docs/zasm/zasm-05-01-zero-cli-compiler.md b/docs/zasm/zasm-05-01-zero-cli-compiler.md new file mode 100644 index 0000000..99d799e --- /dev/null +++ b/docs/zasm/zasm-05-01-zero-cli-compiler.md @@ -0,0 +1,43 @@ +--- +layout: default +title: "Zero Compiler (Zero.CLI)" +--- + +# Zero Compiler (Zero.CLI) + +Section 5 — Compiler and Debugging · Chapter 5.1 + +[Previous](zasm-04-05-notepad-testing-and-next-steps.md) · [Contents](index.md) · [Next](zasm-05-02-compiler-switches.md) + +The `Zero.Cli` project produces `zero` (`zero.exe` on Windows). It accepts a +main `.zasm` source and an optional output path: + +```text +zero [output] [options] +zero run [output] [options] +``` + +Use the executable's full path if it is not on PATH. From a portable release +folder containing `zero.exe` and `hello.zasm`: + +```powershell +.\zero.exe hello.zasm +.\zero.exe hello.zasm greeting.exe +.\zero.exe run hello.zasm +``` + +Without an output path, Windows output uses `.exe` beside the source; Linux +output has no extension. `run` compiles, launches on a compatible host, waits, +and returns the program's exit code. Compilation failure prevents an older +executable from launching. Run Linux output on Linux or compatible WSL. + +The loader resolves includes, then the backend emits instructions and packages +the executable. Diagnostics identify source filenames and lines, including +headers. Begin troubleshooting at the first error. + +This chapter covers the assembly workflow. The future standalone +[Zero and Zero.CLI guide](../zero/index.md) has its own reserved book structure. + +--- + +[Previous](zasm-04-05-notepad-testing-and-next-steps.md) · [Contents](index.md) · [Next](zasm-05-02-compiler-switches.md) diff --git a/docs/zasm/zasm-05-02-compiler-switches.md b/docs/zasm/zasm-05-02-compiler-switches.md new file mode 100644 index 0000000..9eee655 --- /dev/null +++ b/docs/zasm/zasm-05-02-compiler-switches.md @@ -0,0 +1,41 @@ +--- +layout: default +title: "Compiler Switches" +--- + +# Compiler Switches + +Section 5 — Compiler and Debugging · Chapter 5.2 + +[Previous](zasm-05-01-zero-cli-compiler.md) · [Contents](index.md) · [Next](zasm-05-03-zero-debugger.md) + +Substitute your compiler executable's path for `zero` below. + +| Argument | Purpose | Example | +| --- | --- | --- | +| `-h`, `--help` | Display usage | `zero --help` | +| `run` | Compile and execute; placed first | `zero run hello.zasm` | +| `-I ` | Add a search path; repeatable | `zero main.zasm -I headers` | +| `--include ` | Alternative to `-I` | `zero main.zasm --include headers` | +| `--target ` | `windows-x86` or `linux-x64` | `zero main.zasm --target linux-x64` | +| `--debug` | Emit a `.zdbg.json` source map | `zero main.zasm --debug` | +| Second positional path | Choose output filename | `zero main.zasm app.exe` | + +Windows x86 is the default. Source can select `#TARGET linux-x64`; an explicit +command-line target must agree. Quote paths containing spaces. + +```powershell +.\zero.exe main.zasm app.exe --debug -I "shared headers" -I headers +``` + +`run` is a command, not a switch. The output path is positional: there is no +`-o` option. Unknown switches and missing values are errors. The CLI has no +optimization-level or Debug/Release selector; IDE configurations separate +output folders, and debugging requests source maps. + +See [command-line errors](ZASM-Reference.md#command-line-and-errors) for codes and +[Program.cs](../../source/Zero.Cli/Program.cs) when maintaining this table. + +--- + +[Previous](zasm-05-01-zero-cli-compiler.md) · [Contents](index.md) · [Next](zasm-05-03-zero-debugger.md) diff --git a/docs/zasm/zasm-05-03-zero-debugger.md b/docs/zasm/zasm-05-03-zero-debugger.md new file mode 100644 index 0000000..c8b4257 --- /dev/null +++ b/docs/zasm/zasm-05-03-zero-debugger.md @@ -0,0 +1,38 @@ +--- +layout: default +title: "Zero Debugger (Zero.DBG)" +--- + +# Zero Debugger (Zero.DBG) + +Section 5 — Compiler and Debugging · Chapter 5.3 + +[Previous](zasm-05-02-compiler-switches.md) · [Contents](index.md) · [Next](zasm-06-01-x86-instruction-set.md) + +Zero.DBG supplies the session contract; `Zero.Dbg.WinPe` implements Windows x86 +process debugging on Windows x64. Use it through Zero.IDE. A standalone debugger +CLI and Linux debugging are not documented as supported. + +1. Select a compiler accepting `--debug` under **Tools > Options > Compiler**. +2. Save source and modified headers. Set an instruction breakpoint with F9 + or the editor gutter. +3. Press F5. Startup builds with a source map and pauses at entry. +4. Inspect Registers in **Debugger — Locals**. The highlighted instruction + executes next. +5. F10 executes an instruction, stepping over a call. F5 continues, Pause + interrupts, and Shift+F5 stops the session. + +A pending breakpoint has no bound instruction yet. Comments, data, and standalone +labels do not map to instructions. Pausing in OS code may show registers with +no matching ZASM source line. + +The custom `.zdbg.json` sidecar is neither PDB nor DWARF. Rebuild after changing +or moving sources. Typed locals, watches, a memory editor, and a call-stack +unwinder are not currently exposed by the IDE. + +See the [existing debugger guide](../debugger/index.md) for boundaries and the +[future Zero.DBG book](../dbg/index.md) for its reserved structure. + +--- + +[Previous](zasm-05-02-compiler-switches.md) · [Contents](index.md) · [Next](zasm-06-01-x86-instruction-set.md) diff --git a/docs/zasm/zasm-06-01-x86-instruction-set.md b/docs/zasm/zasm-06-01-x86-instruction-set.md new file mode 100644 index 0000000..a91b187 --- /dev/null +++ b/docs/zasm/zasm-06-01-x86-instruction-set.md @@ -0,0 +1,40 @@ +--- +layout: default +title: "The x86 Instruction Set" +--- + +# The x86 Instruction Set + +Section 6 — Architecture · Chapter 6.1 + +[Previous](zasm-05-03-zero-debugger.md) · [Contents](index.md) · [Next](zasm-06-02-x64-instruction-set.md) + +An instruction set defines operations and machine encodings a processor can +execute. Assembly mnemonics are readable names for operations. An assembler must +implement each operand form before you can use it. + +Zero's Windows backend emits 32-bit x86 and PE32 executables. Its general-purpose +registers are EAX, EBX, ECX, EDX, ESI, EDI, EBP, and ESP. Execution also involves +EIP and status flags such as the zero flag. + +```asm +mov eax, 5 +cmp eax, 5 +jz equal +``` + +This fragment loads, compares, and branches. Supply the `equal` label and +termination path in a complete program. Understanding its data and control flow +matters more initially than memorizing bytes. + +ZASM implements a subset of x86. CPU support does not establish compiler support; +a supported mnemonic may still accept only some operands. Use +[Appendix I](zasm-07-01-mnemonic-lookup.md) with the +[operand reference](ZASM-Reference.md#instruction-reference). + +Architecture, executable format, and OS calling convention are separate choices. +A Windows import call is not a Linux system call. + +--- + +[Previous](zasm-05-03-zero-debugger.md) · [Contents](index.md) · [Next](zasm-06-02-x64-instruction-set.md) diff --git a/docs/zasm/zasm-06-02-x64-instruction-set.md b/docs/zasm/zasm-06-02-x64-instruction-set.md new file mode 100644 index 0000000..4f5f311 --- /dev/null +++ b/docs/zasm/zasm-06-02-x64-instruction-set.md @@ -0,0 +1,39 @@ +--- +layout: default +title: "The x64 Instruction Set" +--- + +# The x64 Instruction Set + +Section 6 — Architecture · Chapter 6.2 + +[Previous](zasm-06-01-x86-instruction-set.md) · [Contents](index.md) · [Next](zasm-06-03-what-is-windows-pe.md) + +x64, also called x86-64 or AMD64, extends x86 with 64-bit registers and additional +general-purpose registers. A 64-bit pointer and ABI differ from x86: porting +requires more than renaming EAX to RAX. + +Zero currently uses x64 for **Linux ELF64**. Windows x64 output is future work. +This complete Linux-only example exits successfully: + +```asm +#TARGET linux-x64 +mov eax, 60 +xor edi, edi +syscall +``` + +60 is the Linux x64 exit system-call number; RDI carries the status. Writing +EAX or EDI clears the upper half of its 64-bit register. Linux system calls +use registers for arguments; `SYSCALL` clobbers RCX and R11. + +The Linux backend supports matching-width register moves, loads/stores, and +additional indirect-call forms. This does not make the entire AMD64 set +available. Inline data remains read-only even when store instructions encode. + +See [Linux x64 support](../linux64.md) for examples and operand restrictions. +**Exercise:** Compare this exit with Windows x86 `push 0` / `call [ExitProcess]`. + +--- + +[Previous](zasm-06-01-x86-instruction-set.md) · [Contents](index.md) · [Next](zasm-06-03-what-is-windows-pe.md) diff --git a/docs/zasm/zasm-06-03-what-is-windows-pe.md b/docs/zasm/zasm-06-03-what-is-windows-pe.md new file mode 100644 index 0000000..adf7490 --- /dev/null +++ b/docs/zasm/zasm-06-03-what-is-windows-pe.md @@ -0,0 +1,34 @@ +--- +layout: default +title: "What Is Windows PE?" +--- + +# What Is Windows PE? + +Section 6 — Architecture · Chapter 6.3 + +[Previous](zasm-06-02-x64-instruction-set.md) · [Contents](index.md) · [Next](zasm-06-04-what-is-elf.md) + +Portable Executable (PE) is a Windows executable-file format. It packages code, +data, entry-point information, and loader metadata. The Windows loader maps +it into memory and resolves imported DLL functions. + +Zero currently emits **PE32 for x86**. The import address table supplies slots +for calls such as `call [MessageBoxA]`. Source `#IMPORT` declarations identify +which exports to describe there. + +Sections describe image regions and permissions. Inline ZASM data currently +shares a read-only executable section with instructions. A label on `DD` names +bytes; it does not request writable storage. + +Output uses the console subsystem today. Windows APIs can create graphical +windows, but selecting a GUI subsystem without an accompanying console is +future work. Windows x64 PE32+ and DLL output are also future targets. + +See the [Windows debugger engine](../debugger/winpe.md) and +[future target design](../designs/Future-Formats-and-Targets.md). +**Checkpoint:** Distinguish executable format, CPU architecture, and subsystem. + +--- + +[Previous](zasm-06-02-x64-instruction-set.md) · [Contents](index.md) · [Next](zasm-06-04-what-is-elf.md) diff --git a/docs/zasm/zasm-06-04-what-is-elf.md b/docs/zasm/zasm-06-04-what-is-elf.md new file mode 100644 index 0000000..fa84c18 --- /dev/null +++ b/docs/zasm/zasm-06-04-what-is-elf.md @@ -0,0 +1,34 @@ +--- +layout: default +title: "What Is ELF?" +--- + +# What Is ELF? + +Section 6 — Architecture · Chapter 6.4 + +[Previous](zasm-06-03-what-is-windows-pe.md) · [Contents](index.md) · [Next](zasm-06-05-what-is-arm.md) + +Executable and Linkable Format (ELF) is used by Linux and other systems for +executables and other binary artifacts. Its headers describe how a loader maps +a program and begins execution. + +Zero produces **static Linux x64 ELF64 executables**, using Linux system calls +rather than a C runtime or shared-library linker. Select the target with +`#TARGET linux-x64` or `--target linux-x64`; both must agree if present. + +Cross-compilation means host and target can differ. A Windows compiler can +build Linux output, but you run it on x64 Linux or compatible WSL. On Linux, +ensure execute permission before launching `./program`. + +ELF alone does not specify an architecture or runtime interface. An ARM ELF +program would need an ARM encoder and platform conventions. Linux shared-library +linking and ARM backends remain future work. + +See [Linux x64 and ELF64](../linux64.md) for implemented layout and syscall examples. +**Checkpoint:** Explain why renaming `app.exe` to `app` cannot convert a Windows +program into a Linux program. + +--- + +[Previous](zasm-06-03-what-is-windows-pe.md) · [Contents](index.md) · [Next](zasm-06-05-what-is-arm.md) diff --git a/docs/zasm/zasm-06-05-what-is-arm.md b/docs/zasm/zasm-06-05-what-is-arm.md new file mode 100644 index 0000000..69ca7ac --- /dev/null +++ b/docs/zasm/zasm-06-05-what-is-arm.md @@ -0,0 +1,32 @@ +--- +layout: default +title: "What Is ARM?" +--- + +# What Is ARM? + +Section 6 — Architecture · Chapter 6.5 + +[Previous](zasm-06-04-what-is-elf.md) · [Contents](index.md) · [Next](zasm-07-01-mnemonic-lookup.md) + +ARM is a family of processor architectures with its own instruction sets and +register conventions. AArch64 is the 64-bit execution architecture commonly +associated with ARM64. Its instructions are not x86 instructions with new names. + +**Zero has no ARM output backend today.** An ARM64 host package, where available, +describes where the compiler or IDE runs; it does not establish ARM output. +Do not pass invented ARM target names or substitute ARM registers in this book. + +A port needs encoding, relocations, registers and calling conventions, binary +packaging, and target-specific tests. Bare-metal boards also require startup +and memory-layout decisions beyond those of an OS application. + +This chapter reserves a place for ARM while the working paths remain Windows +x86 and Linux x64. See [future formats and targets](../designs/Future-Formats-and-Targets.md). + +**Exercise:** Separate the algorithm in a hello program from its CPU-dependent +and OS-dependent operations. Those boundaries define much of the porting work. + +--- + +[Previous](zasm-06-04-what-is-elf.md) · [Contents](index.md) · [Next](zasm-07-01-mnemonic-lookup.md) diff --git a/docs/zasm/zasm-07-01-mnemonic-lookup.md b/docs/zasm/zasm-07-01-mnemonic-lookup.md new file mode 100644 index 0000000..4e888cc --- /dev/null +++ b/docs/zasm/zasm-07-01-mnemonic-lookup.md @@ -0,0 +1,43 @@ +--- +layout: default +title: "Appendix I — Mnemonic Lookup" +--- + +# Appendix I — Mnemonic Lookup + +Appendices + +[Previous](zasm-06-05-what-is-arm.md) · [Contents](index.md) · [Next](zasm-07-02-ascii-character-set.md) + +This compact **Windows x86** table summarizes operations used in the book. +It does not enumerate every addressing restriction. + +| Mnemonic | Purpose | Typical supported form | +| --- | --- | --- | +| `MOV` | Load a value | `mov eax, 42`; `mov eax, [value]` | +| `LEA` | Calculate an address | `lea esi, [esp]` | +| `PUSH` | Push a stack value | `push eax`; `push 42` | +| `POP` | Pop a stack value | `pop eax` | +| `ADD`, `SUB` | Integer arithmetic | `add eax, 4`; `sub eax, ebx` | +| `AND`, `OR`, `XOR` | Bitwise operations | `and eax, 0xFF`; `xor eax, eax` | +| `CMP` | Compare without storing | `cmp eax, 42` | +| `TEST` | Test bits without storing | `test eax, 4` | +| `JMP` | Unconditional direct branch | `jmp start` | +| `JZ`, `JNZ` | Branch on zero flag | `jz done`; `jnz again` | +| `JZ8`, `JNZ8` | Explicit short branch | `jz8 nearby` | +| `CALL` | Call a routine | `call calculate`; `call [puts]` | +| `RET` | Return with optional cleanup | `ret`; `ret 16` | +| `NOP` | No operation | `nop` | +| `INT` | Software interrupt | `int 3` | + +`INT` depends on OS permissions and behavior; it is not the Windows console +interface. Example labels and memory locations must exist in a complete program. + +Linux x64 adds `SYSCALL`, 64-bit/extended registers, and broader movement and +indirect branch forms. For exact support and missing instructions, use the +[mnemonic inventory](ZASM-Mnemonics.md) and [Linux operand guide](../linux64.md). +`DB`, `DW`, `DD`, and Linux numeric `DQ` are data directives, not CPU instructions. + +--- + +[Previous](zasm-06-05-what-is-arm.md) · [Contents](index.md) · [Next](zasm-07-02-ascii-character-set.md) diff --git a/docs/zasm/zasm-07-02-ascii-character-set.md b/docs/zasm/zasm-07-02-ascii-character-set.md new file mode 100644 index 0000000..7290e0c --- /dev/null +++ b/docs/zasm/zasm-07-02-ascii-character-set.md @@ -0,0 +1,162 @@ +--- +layout: default +title: "Appendix II — ASCII Character Set" +--- + +# Appendix II — ASCII Character Set + +Appendices + +[Previous](zasm-07-01-mnemonic-lookup.md) · [Contents](index.md) · [Back to contents](index.md) + +ASCII defines values 0–127. Values 0–31 and 127 are controls; 32 is space. +Values 128–255 are not a universal extended ASCII set. ZASM strings use UTF-8, +where the ASCII range has the same byte values. + +Useful values: NUL (0, string terminator), HT (9, tab), LF (10, line feed), CR +(13, carriage return), and space (32). Windows text commonly uses CR followed +by LF. A string's ending zero is separate from its line ending. + +```asm +message db 'Hello', 13, 10, 0 +``` + +Place this data behind a jump. `puts` adds its own newline; omit the explicit +CR/LF if you want only the line ending supplied by `puts`. + +## Complete 7-bit table + +| Decimal | Hex | Character or control | +| --- | --- | --- | +| 0 | 00 | NUL | +| 1 | 01 | SOH | +| 2 | 02 | STX | +| 3 | 03 | ETX | +| 4 | 04 | EOT | +| 5 | 05 | ENQ | +| 6 | 06 | ACK | +| 7 | 07 | BEL | +| 8 | 08 | BS | +| 9 | 09 | HT | +| 10 | 0A | LF | +| 11 | 0B | VT | +| 12 | 0C | FF | +| 13 | 0D | CR | +| 14 | 0E | SO | +| 15 | 0F | SI | +| 16 | 10 | DLE | +| 17 | 11 | DC1 | +| 18 | 12 | DC2 | +| 19 | 13 | DC3 | +| 20 | 14 | DC4 | +| 21 | 15 | NAK | +| 22 | 16 | SYN | +| 23 | 17 | ETB | +| 24 | 18 | CAN | +| 25 | 19 | EM | +| 26 | 1A | SUB | +| 27 | 1B | ESC | +| 28 | 1C | FS | +| 29 | 1D | GS | +| 30 | 1E | RS | +| 31 | 1F | US | +| 32 | 20 | Space | +| 33 | 21 | ! | +| 34 | 22 | " | +| 35 | 23 | # | +| 36 | 24 | $ | +| 37 | 25 | % | +| 38 | 26 | & | +| 39 | 27 | ' | +| 40 | 28 | ( | +| 41 | 29 | ) | +| 42 | 2A | * | +| 43 | 2B | + | +| 44 | 2C | , | +| 45 | 2D | - | +| 46 | 2E | . | +| 47 | 2F | / | +| 48 | 30 | 0 | +| 49 | 31 | 1 | +| 50 | 32 | 2 | +| 51 | 33 | 3 | +| 52 | 34 | 4 | +| 53 | 35 | 5 | +| 54 | 36 | 6 | +| 55 | 37 | 7 | +| 56 | 38 | 8 | +| 57 | 39 | 9 | +| 58 | 3A | : | +| 59 | 3B | ; | +| 60 | 3C | < | +| 61 | 3D | = | +| 62 | 3E | > | +| 63 | 3F | ? | +| 64 | 40 | @ | +| 65 | 41 | A | +| 66 | 42 | B | +| 67 | 43 | C | +| 68 | 44 | D | +| 69 | 45 | E | +| 70 | 46 | F | +| 71 | 47 | G | +| 72 | 48 | H | +| 73 | 49 | I | +| 74 | 4A | J | +| 75 | 4B | K | +| 76 | 4C | L | +| 77 | 4D | M | +| 78 | 4E | N | +| 79 | 4F | O | +| 80 | 50 | P | +| 81 | 51 | Q | +| 82 | 52 | R | +| 83 | 53 | S | +| 84 | 54 | T | +| 85 | 55 | U | +| 86 | 56 | V | +| 87 | 57 | W | +| 88 | 58 | X | +| 89 | 59 | Y | +| 90 | 5A | Z | +| 91 | 5B | [ | +| 92 | 5C | \ | +| 93 | 5D | ] | +| 94 | 5E | ^ | +| 95 | 5F | _ | +| 96 | 60 | ` | +| 97 | 61 | a | +| 98 | 62 | b | +| 99 | 63 | c | +| 100 | 64 | d | +| 101 | 65 | e | +| 102 | 66 | f | +| 103 | 67 | g | +| 104 | 68 | h | +| 105 | 69 | i | +| 106 | 6A | j | +| 107 | 6B | k | +| 108 | 6C | l | +| 109 | 6D | m | +| 110 | 6E | n | +| 111 | 6F | o | +| 112 | 70 | p | +| 113 | 71 | q | +| 114 | 72 | r | +| 115 | 73 | s | +| 116 | 74 | t | +| 117 | 75 | u | +| 118 | 76 | v | +| 119 | 77 | w | +| 120 | 78 | x | +| 121 | 79 | y | +| 122 | 7A | z | +| 123 | 7B | { | +| 124 | 7C | | | +| 125 | 7D | } | +| 126 | 7E | ~ | +| 127 | 7F | DEL | + +--- + +[Previous](zasm-07-01-mnemonic-lookup.md) · [Contents](index.md) · [Back to contents](index.md) diff --git a/docs/zero/index.md b/docs/zero/index.md new file mode 100644 index 0000000..cc51d4a --- /dev/null +++ b/docs/zero/index.md @@ -0,0 +1,40 @@ +--- +layout: default +title: "Zero and Zero.CLI Guide" +--- + +# Zero and Zero.CLI Guide + +[Documentation library](../index.md) · [Zero Assembly book](../zasm/index.md) + +**Planned companion book.** This page reserves a home and section structure for +future chapters. The outline is documentation work to come, not a promise that +every named feature is implemented. Use the current guides below today. + +## Planned sections + +### Section 1 — Getting Started + +Chapter placeholders: Installation, command-line workflow, and a first program. + +### Section 2 — The Zero Language + +Chapter placeholders: Future .zsrc grammar, types, expressions, and control flow. + +### Section 3 — Projects and Libraries + +Chapter placeholders: Headers today; project files and linking as implemented. + +### Section 4 — Compiler Reference + +Chapter placeholders: Switches, targets, diagnostics, and artifacts. + +### Section 5 — Architecture and Contributing + +Chapter placeholders: Pipeline, backend contracts, and testing. + +## Available documentation + +- [Current ZASM compiler chapter](../zasm/zasm-05-01-zero-cli-compiler.md) +- [Current switches](../zasm/zasm-05-02-compiler-switches.md) +- [Build instructions](../building.md) diff --git a/readme.md b/readme.md index 5eee51b..7756bdf 100644 --- a/readme.md +++ b/readme.md @@ -9,6 +9,12 @@ that create Windows GUI controls) and static Linux x86-64 ELF64 executables usin syscalls. Shared-library ELF linking, DLL output, additional architectures, macOS, and STM32 remain future work. See [Linux x86-64 support](docs/linux64.md). +## Documentation + +Read the [Zero Assembly Programmers Guide](docs/zasm/index.md), or browse the +[documentation library](docs/index.md#documentation-library) for companion book +placeholders for Zero/Zero.CLI, Zero.IDE, and Zero.DBG. + ## Zero Language Suite * **Zero** - _Zero Assembly and command line compiler tooling (Zero.Cli)_ From 13a4e744ddfc0ec343590249cfe6c9f23c6f1fa3 Mon Sep 17 00:00:00 2001 From: Damian Suess Date: Sun, 15 Nov 2026 22:36:40 -0500 Subject: [PATCH 2/4] End of chapter highlights. Added ZASM Keywords and Directives section --- docs/zasm/index.md | 5 +- docs/zasm/zasm-01-01-what-is-zero-assembly.md | 2 +- .../zasm-01-02-why-learn-assembly-today.md | 4 +- docs/zasm/zasm-01-03-installing-zero-ide.md | 3 +- ...m-01-04-using-zero-ide-my-first-project.md | 4 +- docs/zasm/zasm-01-05-hello-zero-assembly.md | 7 +- .../zasm-01-06-keywords-and-directives.md | 113 ++++++++++++++++++ docs/zasm/zasm-02-01-moving-numbers.md | 8 +- docs/zasm/zasm-02-02-performing-jumps.md | 2 +- .../zasm-02-03-storing-data-and-printing.md | 4 +- docs/zasm/zasm-02-04-boolean-algebra.md | 2 +- docs/zasm/zasm-02-05-basic-variables.md | 10 +- ...importing-and-calling-external-library.md} | 21 +++- docs/zasm/zasm-03-02-creating-structs.md | 87 +++++++++++--- docs/zasm/zasm-03-03-working-with-strings.md | 4 +- .../zasm/zasm-03-04-organizing-your-system.md | 4 +- docs/zasm/zasm-03-05-arithmetic-operations.md | 3 +- ...zasm-03-06-performing-bit-manipulations.md | 4 +- docs/zasm/zasm-03-07-creating-functions.md | 4 +- docs/zasm/zasm-04-01-notepad-project-setup.md | 5 +- .../zasm-04-02-notepad-create-the-window.md | 4 +- .../zasm-04-03-notepad-add-the-text-editor.md | 28 +++-- .../zasm-04-04-notepad-open-and-save-files.md | 4 +- ...sm-04-05-notepad-testing-and-next-steps.md | 4 +- docs/zasm/zasm-06-02-x64-instruction-set.md | 3 +- docs/zasm/zasm-06-03-what-is-windows-pe.md | 3 +- docs/zasm/zasm-06-04-what-is-elf.md | 5 +- docs/zasm/zasm-06-05-what-is-arm.md | 4 +- docs/zasm/zasm-07-01-mnemonic-lookup.md | 2 + 29 files changed, 276 insertions(+), 77 deletions(-) create mode 100644 docs/zasm/zasm-01-06-keywords-and-directives.md rename docs/zasm/{zasm-03-01-calling-external-library-functions.md => zasm-03-01-importing-and-calling-external-library.md} (66%) diff --git a/docs/zasm/index.md b/docs/zasm/index.md index ad5dc9c..cc94848 100644 --- a/docs/zasm/index.md +++ b/docs/zasm/index.md @@ -3,7 +3,7 @@ layout: default title: Zero Assembly Programmers Guide --- -# Zero Assembly Programmers Guide +# Zero Assembly Programmer's Guide [Documentation library](../index.md) · [Start reading](zasm-01-01-what-is-zero-assembly.md) @@ -38,6 +38,7 @@ numbers and lowercase, hyphenated titles. For example, 3. [Installing Zero.IDE](zasm-01-03-installing-zero-ide.md) 4. [Using Zero.IDE — My First Project](zasm-01-04-using-zero-ide-my-first-project.md) 5. [Hello, Zero Assembly](zasm-01-05-hello-zero-assembly.md) +6. [Zero Assembly Keywords and Directives](zasm-01-06-keywords-and-directives.md) ### Section 2 — Basics @@ -49,7 +50,7 @@ numbers and lowercase, hyphenated titles. For example, ### Section 3 — Level-Up Learning -1. [Calling External Library Functions](zasm-03-01-calling-external-library-functions.md) +1. [Calling External Library Functions](zasm-03-01-importing-and-calling-external-library.md) 2. [Creating Structs](zasm-03-02-creating-structs.md) 3. [Working with Strings](zasm-03-03-working-with-strings.md) 4. [Organizing Your System](zasm-03-04-organizing-your-system.md) diff --git a/docs/zasm/zasm-01-01-what-is-zero-assembly.md b/docs/zasm/zasm-01-01-what-is-zero-assembly.md index a2d80a4..2885701 100644 --- a/docs/zasm/zasm-01-01-what-is-zero-assembly.md +++ b/docs/zasm/zasm-01-01-what-is-zero-assembly.md @@ -30,7 +30,7 @@ language uses `.zsrc` and remains under redesign. Future features are labeled where they arise. > **Checkpoint:** Explain the difference between source text, a compiler, and an -executable. The [language reference](ZASM-Reference.md) supplies exact operand rules. +> executable. The [language reference](ZASM-Reference.md) supplies exact operand rules. --- diff --git a/docs/zasm/zasm-01-02-why-learn-assembly-today.md b/docs/zasm/zasm-01-02-why-learn-assembly-today.md index 4d1c9b9..bcfbc43 100644 --- a/docs/zasm/zasm-01-02-why-learn-assembly-today.md +++ b/docs/zasm/zasm-01-02-why-learn-assembly-today.md @@ -25,8 +25,8 @@ The compiler cannot infer all of these contracts for you. Keep three questions beside each example: What value changes? Where is it stored? Who owns the storage? They become useful when stepping through calls. -**Exercise:** Identify an operation in a familiar application that needs -arithmetic, one that needs a branch, and one that asks the OS for a service. +> **Exercise:** Identify an operation in a familiar application that needs +> arithmetic, one that needs a branch, and one that asks the OS for a service. --- diff --git a/docs/zasm/zasm-01-03-installing-zero-ide.md b/docs/zasm/zasm-01-03-installing-zero-ide.md index c3adc28..e611736 100644 --- a/docs/zasm/zasm-01-03-installing-zero-ide.md +++ b/docs/zasm/zasm-01-03-installing-zero-ide.md @@ -35,7 +35,8 @@ beside `zero.exe`. If a release has no IDE installer, build the IDE using the [build instructions](../building.md); do not expect the compiler ZIP to contain it. See the [installer guide](../../installer/README.md) for packaging and other hosts. -**Checkpoint:** Confirm the selected compiler displays `--help` in a terminal. + +> **Checkpoint:** Confirm the selected compiler displays `--help` in a terminal. --- diff --git a/docs/zasm/zasm-01-04-using-zero-ide-my-first-project.md b/docs/zasm/zasm-01-04-using-zero-ide-my-first-project.md index 3bb428f..cfc3cb5 100644 --- a/docs/zasm/zasm-01-04-using-zero-ide-my-first-project.md +++ b/docs/zasm/zasm-01-04-using-zero-ide-my-first-project.md @@ -32,8 +32,8 @@ If a header is missing, check the compiler location and installed `include` layout. Save modified headers before debugging. Source editors are read-only during a debug session. -**Checkpoint:** Locate your source file, compiler executable, and generated -executable. Each has a different role. +> **Checkpoint:** Locate your source file, compiler executable, and generated +> executable. Each has a different role. --- diff --git a/docs/zasm/zasm-01-05-hello-zero-assembly.md b/docs/zasm/zasm-01-05-hello-zero-assembly.md index ebe9ead..0510170 100644 --- a/docs/zasm/zasm-01-05-hello-zero-assembly.md +++ b/docs/zasm/zasm-01-05-hello-zero-assembly.md @@ -7,7 +7,7 @@ title: "Hello, Zero Assembly" Section 1 — Intro · Chapter 1.5 -[Previous](zasm-01-04-using-zero-ide-my-first-project.md) · [Contents](index.md) · [Next](zasm-02-01-moving-numbers.md) +[Previous](zasm-01-04-using-zero-ide-my-first-project.md) · [Contents](index.md) · [Next](zasm-01-06-keywords-and-directives.md) Save this complete Windows x86 program as `hello.zasm`: @@ -47,8 +47,9 @@ remove four argument bytes with `add esp, 4`. `exit(0)` ends the process. Later snippets are **fragments** unless called complete programs. Insert them into a complete program before termination; never execute inline data. -**Exercise:** Change the greeting and run it again. + +> **Exercise:** Change the greeting and run it again. --- -[Previous](zasm-01-04-using-zero-ide-my-first-project.md) · [Contents](index.md) · [Next](zasm-02-01-moving-numbers.md) +[Previous](zasm-01-04-using-zero-ide-my-first-project.md) · [Contents](index.md) · [Next](zasm-01-06-keywords-and-directives.md) diff --git a/docs/zasm/zasm-01-06-keywords-and-directives.md b/docs/zasm/zasm-01-06-keywords-and-directives.md new file mode 100644 index 0000000..8bbf0b1 --- /dev/null +++ b/docs/zasm/zasm-01-06-keywords-and-directives.md @@ -0,0 +1,113 @@ +--- +layout: default +title: "Zero Assembly Keywords and Directives" +--- + +# Zero Assembly Keywords and Directives + +Section 1 — Intro · Chapter 1.6 + +[Previous](zasm-01-05-hello-zero-assembly.md) · [Contents](index.md) · [Next](zasm-02-01-moving-numbers.md) + +Some words in a ZASM file tell the compiler how to build the program. These +keywords and directives serve a different role from CPU instructions such as +`MOV` or `CALL`: the compiler processes them while building the executable. + +## Select the Target with #TARGET + +`#TARGET` selects the platform and architecture for the generated program. +Write it as a standalone statement, conventionally near the top of the source. +The currently implemented choices also determine the executable format: + +| Directive | Platform | CPU architecture | Output | +| --- | --- | --- | --- | +| `#TARGET windows-x86` | Windows | 32-bit x86 | PE32 executable (`.exe`) | +| `#TARGET linux-x64` | Linux | 64-bit x86-64 | Static ELF64 executable | + +If you omit the directive and the command-line target, Zero defaults to +`windows-x86`. The target describes the program you are building, independently +of the computer running the compiler. + +This complete Windows example makes the default choice explicit: + +```asm +#TARGET windows-x86 +#IMPORT kernel32.dll, ExitProcess + +push 0 +call [ExitProcess] +``` + +The corresponding minimal Linux x64 program uses the Linux system-call interface: + +```asm +#TARGET linux-x64 + +mov eax, 60 ; Linux x64 exit system-call number. +xor edi, edi ; Exit status 0. +syscall +``` + +Changing the target directive does not translate Windows API calls into Linux +system calls. The instructions, registers, and external interfaces must match +the chosen target. + +You can also choose a target on the command line: + +```text +zero main.zasm --target linux-x64 +``` + +Use your compiler's full path if needed. If the source contains `#TARGET`, the +command-line choice must agree with it. Conflicting target declarations produce +an error; a command-line option does not override a different source target. +Cross-compiling is supported, but running the result requires a compatible host. + +## Other Keywords and Directives You Will Meet + +| Syntax | Purpose | Example | +| --- | --- | --- | +| `using` | Include shared source, commonly import declarations | `using "windows/console.zh"` | +| `#IMPORT` | Declare one or more exports from a Windows DLL | `#IMPORT kernel32.dll, Sleep, ExitProcess` | +| `DB` | Emit bytes or UTF-8 string bytes | `message db 'Hello', 0` | +| `DW` | Emit 16-bit integer values | `count: dw 10` | +| `DD` | Emit 32-bit integer values | `value: dd 42` | +| `DQ` | Emit numeric 64-bit values on Linux x64 | `value: dq 42` | + +The data declarations in this table are fragments. Keep inline data behind a +jump so execution starts with an instruction. Data directives emit bytes; +`#TARGET` and `#IMPORT` configure compilation rather than emit CPU instructions. +`using` loads source that may itself contain declarations, instructions, or data. + +## Future Output Configuration + +The planned direction is to expand keywords and directives so source can +describe more aspects of the output. Keep these choices distinct: + +| Configuration | What it describes | Current support and future direction | +| --- | --- | --- | +| Platform | Which operating system or environment runs the program | Windows and Linux today; additional environments are future work | +| Binary format | How code and loader metadata are packaged | PE32 and ELF64 through the implemented targets | +| CPU architecture and bitness | Which instructions, registers, and pointer widths apply | x86 (32-bit) and x64 (64-bit) today; ARM/ARM64 output is future work | +| Output kind | Whether the result is an application or shared library | Executables today; DLL output and Linux shared-library linking are future work | + +PE and ELF are binary formats; ARM is a processor architecture. An EXE and a +DLL can both use PE, but they have different loading and entry-point contracts. +Those dimensions must form a supported combination to produce a working binary. + +**Future syntax is not defined here.** There are no documented standalone +directives for independently selecting PE/ELF, ARM, 32/64-bit mode, or EXE/DLL +output today. Use the two working `#TARGET` choices above. Importing a DLL with +`#IMPORT` calls an existing library; it does not make your output a DLL. + +See the [target design](../designs/Future-Formats-and-Targets.md), +[feature roadmap](ZASM-Coming-Soon.md), and +[compiler switches](zasm-05-02-compiler-switches.md) for related details. + +> **Checkpoint:** Identify the platform, architecture, bitness, binary format, +> and output kind selected by `#TARGET windows-x86`. Explain why changing a +> filename extension to `.dll` does not change the compiled output kind. + +--- + +[Previous](zasm-01-05-hello-zero-assembly.md) · [Contents](index.md) · [Next](zasm-02-01-moving-numbers.md) diff --git a/docs/zasm/zasm-02-01-moving-numbers.md b/docs/zasm/zasm-02-01-moving-numbers.md index 02d4dae..ea299de 100644 --- a/docs/zasm/zasm-02-01-moving-numbers.md +++ b/docs/zasm/zasm-02-01-moving-numbers.md @@ -7,7 +7,7 @@ title: "Moving Numbers" Section 2 — Basics · Chapter 2.1 -[Previous](zasm-01-05-hello-zero-assembly.md) · [Contents](index.md) · [Next](zasm-02-02-performing-jumps.md) +[Previous](zasm-01-06-keywords-and-directives.md) · [Contents](index.md) · [Next](zasm-02-02-performing-jumps.md) A number written in an instruction is an immediate value. `42`, `0x2A`, and `2Ah` are spellings of the same integer. @@ -28,9 +28,9 @@ A register holds bits. Whether those bits represent a signed integer, an unsigned integer, or an address depends on the operation using them. On this target the general-purpose registers are 32 bits wide. -**Exercise:** Load 100 into EAX, copy it into EDX using the stack, and inspect -both registers. Linux x64 has broader `MOV` forms; see [Linux x64](../linux64.md). +> **Exercise:** Load 100 into EAX, copy it into EDX using the stack, and inspect +> both registers. Linux x64 has broader `MOV` forms; see [Linux x64](../linux64.md). --- -[Previous](zasm-01-05-hello-zero-assembly.md) · [Contents](index.md) · [Next](zasm-02-02-performing-jumps.md) +[Previous](zasm-01-06-keywords-and-directives.md) · [Contents](index.md) · [Next](zasm-02-02-performing-jumps.md) diff --git a/docs/zasm/zasm-02-02-performing-jumps.md b/docs/zasm/zasm-02-02-performing-jumps.md index 97cac3d..9aaed6e 100644 --- a/docs/zasm/zasm-02-02-performing-jumps.md +++ b/docs/zasm/zasm-02-02-performing-jumps.md @@ -32,7 +32,7 @@ by the compiler. Use unique labels for distinct locations. Use `JZ` and `JNZ` normally. `JZ8` and `JNZ8` require a short displacement in range. `JE`, `JNE`, and greater/less-than branches are not implemented. -**Exercise:** Start the loop at 5. Step through and watch ECX and EIP. +> **Exercise:** Start the loop at 5. Step through and watch ECX and EIP. --- diff --git a/docs/zasm/zasm-02-03-storing-data-and-printing.md b/docs/zasm/zasm-02-03-storing-data-and-printing.md index 78ac17e..742277c 100644 --- a/docs/zasm/zasm-02-03-storing-data-and-printing.md +++ b/docs/zasm/zasm-02-03-storing-data-and-printing.md @@ -36,8 +36,8 @@ and numbers when passing arguments. Inline data is in the read-only code section. `value: dd 42` does not make a writable variable. Use stack or allocated storage for values that change. -**Exercise:** Change the initial value and predict the output. Compare the -[complete output sample](../../samples/Windows/win-cli-02-console-printf-db-vars.zasm). +> **Exercise:** Change the initial value and predict the output. Compare the +> [complete output sample](../../samples/Windows/win-cli-02-console-printf-db-vars.zasm). --- diff --git a/docs/zasm/zasm-02-04-boolean-algebra.md b/docs/zasm/zasm-02-04-boolean-algebra.md index 7180f73..c515323 100644 --- a/docs/zasm/zasm-02-04-boolean-algebra.md +++ b/docs/zasm/zasm-02-04-boolean-algebra.md @@ -32,7 +32,7 @@ if that bit were clear. Supply the branch target in your complete program. Use hexadecimal masks: binary literal syntax is not currently supported. -**Exercise:** Work out `0x0F AND 0x05` on paper, then verify it in EAX. +> **Exercise:** Work out `0x0F AND 0x05` on paper, then verify it in EAX. --- diff --git a/docs/zasm/zasm-02-05-basic-variables.md b/docs/zasm/zasm-02-05-basic-variables.md index 488cbf1..7961ed4 100644 --- a/docs/zasm/zasm-02-05-basic-variables.md +++ b/docs/zasm/zasm-02-05-basic-variables.md @@ -7,7 +7,7 @@ title: "Basic Variables" Section 2 — Basics · Chapter 2.5 -[Previous](zasm-02-04-boolean-algebra.md) · [Contents](index.md) · [Next](zasm-03-01-calling-external-library-functions.md) +[Previous](zasm-02-04-boolean-algebra.md) · [Contents](index.md) · [Next](zasm-03-01-importing-and-calling-external-library.md) A variable is storage with an agreed meaning and lifetime. Registers provide temporary storage. Named data declarations provide initial bytes, but current @@ -30,9 +30,11 @@ storage. Linux x64 supports register-to-memory stores, but its inline data is still read-only. An instruction cannot override memory permissions. Calls can overwrite temporary registers. Follow the calling convention and -preserve values needed afterward. **Exercise:** Explain why a pointer to -released stack storage cannot serve as a lasting variable. +preserve values needed afterward. + +> **Exercise:** Explain why a pointer to +> released stack storage cannot serve as a lasting variable. --- -[Previous](zasm-02-04-boolean-algebra.md) · [Contents](index.md) · [Next](zasm-03-01-calling-external-library-functions.md) +[Previous](zasm-02-04-boolean-algebra.md) · [Contents](index.md) · [Next](zasm-03-01-importing-and-calling-external-library.md) diff --git a/docs/zasm/zasm-03-01-calling-external-library-functions.md b/docs/zasm/zasm-03-01-importing-and-calling-external-library.md similarity index 66% rename from docs/zasm/zasm-03-01-calling-external-library-functions.md rename to docs/zasm/zasm-03-01-importing-and-calling-external-library.md index d498dfb..a979579 100644 --- a/docs/zasm/zasm-03-01-calling-external-library-functions.md +++ b/docs/zasm/zasm-03-01-importing-and-calling-external-library.md @@ -21,6 +21,23 @@ call [ExitProcess] This is a complete minimal program. Brackets mean an indirect call through the import slot populated by the Windows loader. Preserve export spelling. +To import multiple functions from the same DLL, list their export names after +the DLL name, separated by commas. This complete program imports both `Sleep` +and `ExitProcess` from `kernel32.dll`, waits one second, and then exits: + +```asm +#IMPORT kernel32.dll, Sleep, ExitProcess + +push 1000 ; Sleep: wait for 1,000 milliseconds. +call [Sleep] + +push 0 ; ExitProcess: exit with status 0. +call [ExitProcess] +``` + +Each function has its own import slot and is called by name in brackets. Both +functions use stdcall on Windows x86, so they remove their own arguments. + | Convention | Argument order | Argument cleanup | Examples | | --- | --- | --- | --- | | cdecl | Push right to left | Caller | `puts`, `printf`, `strcpy` | @@ -35,8 +52,8 @@ An import declaration does not validate argument types, capacity, or callbacks. Read the API contract before adding a call. Linux's current backend uses system calls rather than imported Windows DLLs. -**Exercise:** Find caller cleanup in the hello program and callee cleanup in the -[MessageBox sample](../../samples/Windows/win-ui-01-msgbox.zasm). +> **Exercise:** Find caller cleanup in the hello program and callee cleanup in the +> [MessageBox sample](../../samples/Windows/win-ui-01-msgbox.zasm). --- diff --git a/docs/zasm/zasm-03-02-creating-structs.md b/docs/zasm/zasm-03-02-creating-structs.md index 8ddaf8c..180a01a 100644 --- a/docs/zasm/zasm-03-02-creating-structs.md +++ b/docs/zasm/zasm-03-02-creating-structs.md @@ -7,38 +7,93 @@ title: "Creating Structs" Section 3 — Level-Up Learning · Chapter 3.2 -[Previous](zasm-03-01-calling-external-library-functions.md) · [Contents](index.md) · [Next](zasm-03-03-working-with-strings.md) +[Previous](zasm-03-01-importing-and-calling-external-library.md) · [Contents](index.md) · [Next](zasm-03-03-working-with-strings.md) A structure is a layout agreement: fields occupy known offsets in contiguous storage. ZASM does not yet provide `struct` declarations, typed fields, or automatic layout. Use explicit storage and offsets. -For an x86 record containing a 32-bit count and a 32-bit pointer: +## A Point in C/C++ + +A `Point` groups two coordinates, `x` and `y`, into one value. On the Windows +x86 target used in this book, each C/C++ `int` occupies four bytes. + +```cpp +struct Point +{ + int x; + int y; +}; + +struct Point point = { 10, 20 }; +``` + +The compiler calculates the field offsets and storage size. Access the +coordinates with `point.x` and `point.y`. + +## The Same Point in C# + +C# `int` is a signed 32-bit integer. Sequential layout keeps these fields in +declaration order for the corresponding native layout. + +```csharp +using System.Runtime.InteropServices; + +[StructLayout(LayoutKind.Sequential)] +struct Point +{ + public int x; + public int y; +} +``` + +Inside a method, create the same value: + +```csharp +Point point = new Point { x = 10, y = 20 }; +``` + +## The Same Point in Zero Assembly + +For these two 32-bit fields, the layout is eight bytes in total: | Offset | Size | Meaning | | --- | --- | --- | -| 0 | 4 bytes | Count | -| 4 | 4 bytes | Pointer | +| 0 | 4 bytes | `x` = 10 | +| 4 | 4 bytes | `y` = 20 | + +ZASM uses explicit storage rather than a `struct` declaration. This Windows +x86 fragment constructs the same Point on the writable process stack: ```asm -; Assume EAX contains a valid pointer. -push eax ; Last field first. -push 3 ; Count at the lowest address. -lea edx, [esp] ; Address of the record. -mov ecx, [edx] ; Count = 3. -mov eax, [edx + 4] -add esp, 8 +push 20 ; point.y: push the last field first. +push 10 ; point.x: placed at the lowest address. +lea edx, [esp] ; EDX = address of the Point. +mov ecx, [edx] ; ECX = point.x (10), at offset 0. +mov eax, [edx + 4] ; EAX = point.y (20), at offset 4. +add esp, 8 ; Release the Point's eight bytes of stack storage. ``` The stack grows toward lower addresses, so pushing fields in reverse creates -the layout shown. OS structures require ABI-defined offsets and alignment; -changing pointer width can change their layout. +the layout shown. `[edx]` corresponds to `point.x`; `[edx + 4]` corresponds to +`point.y`. EDX no longer points to live Point storage after `add esp, 8`. + +Unlike the C/C++ and C# examples, ZASM does not associate a type or field names +with this address. You must keep offsets, sizes, and storage lifetime consistent. +Direct memory-store instructions are not implemented for Windows x86, so this +example initializes the writable fields with `PUSH`. + +OS structures require ABI-defined offsets and alignment. Adding pointers or +changing targets can change a structure's layout; derive it for the target +rather than assuming every field occupies four bytes. The [Windows controls sample](../../samples/Windows/win-ui-02-controls.zasm) builds `WNDCLASSA` this way. Study its 40-byte layout and callback pointer before -the Notepad project. **Exercise:** Add a third 32-bit field on paper and derive -its offset and the total size. +the Notepad project. + +> **Exercise:** Extend Point with a third 32-bit coordinate, `z`. Derive its +> offset, the total size, and the order of pushes needed to construct it. --- -[Previous](zasm-03-01-calling-external-library-functions.md) · [Contents](index.md) · [Next](zasm-03-03-working-with-strings.md) +[Previous](zasm-03-01-importing-and-calling-external-library.md) · [Contents](index.md) · [Next](zasm-03-03-working-with-strings.md) diff --git a/docs/zasm/zasm-03-03-working-with-strings.md b/docs/zasm/zasm-03-03-working-with-strings.md index 8fbab4a..8d5ee3b 100644 --- a/docs/zasm/zasm-03-03-working-with-strings.md +++ b/docs/zasm/zasm-03-03-working-with-strings.md @@ -31,8 +31,8 @@ code page; `W` APIs require UTF-16. ASCII is a common starting point; arbitrary UTF-8 is not automatically compatible with either API family. Choose an encoding and convert deliberately for a larger editor. -**Exercise:** Count bytes for two ASCII strings, a space, and an ending zero. -Compare the [ASCII appendix](zasm-07-02-ascii-character-set.md). +> **Exercise:** Count bytes for two ASCII strings, a space, and an ending zero. +> Compare the [ASCII appendix](zasm-07-02-ascii-character-set.md). --- diff --git a/docs/zasm/zasm-03-04-organizing-your-system.md b/docs/zasm/zasm-03-04-organizing-your-system.md index cb7f768..fbcd611 100644 --- a/docs/zasm/zasm-03-04-organizing-your-system.md +++ b/docs/zasm/zasm-03-04-organizing-your-system.md @@ -36,8 +36,8 @@ control flow, even though import declarations emit no instructions. See [include-file details](ZASM-Include-Files.md). Multi-file linking, namespaces, and a project manifest are future work. -**Exercise:** Move only the hello program's import declarations into a local -header and verify that the program behaves the same way. +> **Exercise:** Move only the hello program's import declarations into a local +> header and verify that the program behaves the same way. --- diff --git a/docs/zasm/zasm-03-05-arithmetic-operations.md b/docs/zasm/zasm-03-05-arithmetic-operations.md index be193b7..d402420 100644 --- a/docs/zasm/zasm-03-05-arithmetic-operations.md +++ b/docs/zasm/zasm-03-05-arithmetic-operations.md @@ -40,7 +40,8 @@ and other boundaries explicitly. `MUL`, `IMUL`, `DIV`, `IDIV`, `INC`, and `DEC` are not implemented. Check the [mnemonic inventory](ZASM-Mnemonics.md) before adapting another assembler's code. -**Exercise:** Print the result using the earlier `printf` pattern. + +> **Exercise:** Print the result using the earlier `printf` pattern. --- diff --git a/docs/zasm/zasm-03-06-performing-bit-manipulations.md b/docs/zasm/zasm-03-06-performing-bit-manipulations.md index 344dad8..0816aae 100644 --- a/docs/zasm/zasm-03-06-performing-bit-manipulations.md +++ b/docs/zasm/zasm-03-06-performing-bit-manipulations.md @@ -29,8 +29,8 @@ constraints; consult that target's operand rules before porting masks. Shifts, rotates, `NOT`, and `BT`/`BTS`/`BTR` are not implemented. These concepts can be added when the encoders support them. For now use AND/OR/XOR/TEST. -**Exercise:** From zero, set bits 0 and 3, clear bit 0, and predict EAX before -inspecting it in the debugger. +> **Exercise:** From zero, set bits 0 and 3, clear bit 0, and predict EAX before +> inspecting it in the debugger. --- diff --git a/docs/zasm/zasm-03-07-creating-functions.md b/docs/zasm/zasm-03-07-creating-functions.md index 9693a2c..401d345 100644 --- a/docs/zasm/zasm-03-07-creating-functions.md +++ b/docs/zasm/zasm-03-07-creating-functions.md @@ -38,8 +38,8 @@ A plain `ret` leaves arguments for the caller. `ret 16` also discards sixteen argument bytes, as required by the four-argument stdcall window callback. Match the caller's and callee's cleanup conventions. -**Exercise:** Make `add_two` preserve EBX if you change it to use that register. -Balance pushes and pops on every return path. +> **Exercise:** Make `add_two` preserve EBX if you change it to use that register. +> Balance pushes and pops on every return path. --- diff --git a/docs/zasm/zasm-04-01-notepad-project-setup.md b/docs/zasm/zasm-04-01-notepad-project-setup.md index 143efac..f9b3869 100644 --- a/docs/zasm/zasm-04-01-notepad-project-setup.md +++ b/docs/zasm/zasm-04-01-notepad-project-setup.md @@ -29,8 +29,9 @@ Alternatively, from a terminal in the new source folder: ``` Use the next chapters in order and save a working copy after each milestone. -**Checkpoint:** Get the original sample working before changing registration, -the callback, or the message loop. + +> **Checkpoint:** Get the original sample working before changing registration, +> the callback, or the message loop. --- diff --git a/docs/zasm/zasm-04-02-notepad-create-the-window.md b/docs/zasm/zasm-04-02-notepad-create-the-window.md index 4cd0143..9b4020e 100644 --- a/docs/zasm/zasm-04-02-notepad-create-the-window.md +++ b/docs/zasm/zasm-04-02-notepad-create-the-window.md @@ -28,8 +28,8 @@ The callback forwards unhandled messages to `DefWindowProcA`. Its EBP-based frame exposes `hwnd` at +8, message at +12, `wParam` at +16, and `lParam` at +20. Keep `pop ebp` and `ret 16` matched on every callback exit. -**Checkpoint:** A visible window needs both a responsive message loop and a -working destruction path. +> **Checkpoint:** A visible window needs both a responsive message loop and a +> working destruction path. --- diff --git a/docs/zasm/zasm-04-03-notepad-add-the-text-editor.md b/docs/zasm/zasm-04-03-notepad-add-the-text-editor.md index ba7d8d9..4b0ea80 100644 --- a/docs/zasm/zasm-04-03-notepad-add-the-text-editor.md +++ b/docs/zasm/zasm-04-03-notepad-add-the-text-editor.md @@ -17,18 +17,20 @@ the Show message button for a quick readback test. ```asm ; Multiline EDIT control, ID 102, at (20, 46), size 620 x 300. - push 0 - push esi - push 102 - push ebx - push 300 - push 620 - push 46 - push 20 - push 0x50B110C4 - push initial_text - push edit_class - push 0 + ; CreateWindowExA arguments are pushed right to left (last parameter first). + push 0 ; lpParam: No application-defined creation data. + push esi ; hInstance: This application's instance handle. + push 102 ; hMenu: Control ID 102 for this child window. + push ebx ; hWndParent: Handle of the main application window. + push 300 ; nHeight: Editor height in pixels. + push 620 ; nWidth: Editor width in pixels. + push 46 ; Y: Top position in the parent's client area, in pixels. + push 20 ; X: Left position in the parent's client area, in pixels. + push 0x50B110C4 ; dwStyle: Child, visible, border, tab stop, scroll bars, + ; multiline, automatic scrolling, and Enter-key input. + push initial_text ; lpWindowName: Address of the initial zero-terminated text. + push edit_class ; lpClassName: Address of the zero-terminated "EDIT" class name. + push 0 ; dwExStyle: No extended window styles. call [CreateWindowExA] test eax, eax jz failed @@ -46,7 +48,7 @@ the Show message button for a quick readback test. This milestone provides a basic editor with readback. Persistence comes next. The current APIs are ANSI; start with ASCII test input. -**Checkpoint:** Confirm Enter inserts a line break and closing still exits. +> **Checkpoint:** Confirm Enter inserts a line break and closing still exits. --- diff --git a/docs/zasm/zasm-04-04-notepad-open-and-save-files.md b/docs/zasm/zasm-04-04-notepad-open-and-save-files.md index c201bc9..eceaa31 100644 --- a/docs/zasm/zasm-04-04-notepad-open-and-save-files.md +++ b/docs/zasm/zasm-04-04-notepad-open-and-save-files.md @@ -43,8 +43,8 @@ Retain the current document if reading fails. Do not mark it saved after a failed or partial write. Then add New/Open/Save commands, dialogs, encoding conversion, and an unsaved-changes prompt as separate tested features. -**Checkpoint:** Define ownership, capacity, failure handling, and cleanup for -every pointer and handle before implementing these calls. +> **Checkpoint:** Define ownership, capacity, failure handling, and cleanup for +> every pointer and handle before implementing these calls. --- diff --git a/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md b/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md index fe8ac2a..141b539 100644 --- a/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md +++ b/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md @@ -31,8 +31,8 @@ encoding after the editing milestone. These are extensions to implement and test: menu entries alone do not complete them. A production editor also needs a deliberate large-file policy. -**Checkpoint:** Record which milestones your copy implements. Keep a known -working copy until each new behavior passes its checks. +> **Checkpoint:** Record which milestones your copy implements. Keep a known +> working copy until each new behavior passes its checks. --- diff --git a/docs/zasm/zasm-06-02-x64-instruction-set.md b/docs/zasm/zasm-06-02-x64-instruction-set.md index 4f5f311..e2b0019 100644 --- a/docs/zasm/zasm-06-02-x64-instruction-set.md +++ b/docs/zasm/zasm-06-02-x64-instruction-set.md @@ -32,7 +32,8 @@ additional indirect-call forms. This does not make the entire AMD64 set available. Inline data remains read-only even when store instructions encode. See [Linux x64 support](../linux64.md) for examples and operand restrictions. -**Exercise:** Compare this exit with Windows x86 `push 0` / `call [ExitProcess]`. + +> **Exercise:** Compare this exit with Windows x86 `push 0` / `call [ExitProcess]`. --- diff --git a/docs/zasm/zasm-06-03-what-is-windows-pe.md b/docs/zasm/zasm-06-03-what-is-windows-pe.md index adf7490..f76cf67 100644 --- a/docs/zasm/zasm-06-03-what-is-windows-pe.md +++ b/docs/zasm/zasm-06-03-what-is-windows-pe.md @@ -27,7 +27,8 @@ future work. Windows x64 PE32+ and DLL output are also future targets. See the [Windows debugger engine](../debugger/winpe.md) and [future target design](../designs/Future-Formats-and-Targets.md). -**Checkpoint:** Distinguish executable format, CPU architecture, and subsystem. + +> **Checkpoint:** Distinguish executable format, CPU architecture, and subsystem. --- diff --git a/docs/zasm/zasm-06-04-what-is-elf.md b/docs/zasm/zasm-06-04-what-is-elf.md index fa84c18..b595969 100644 --- a/docs/zasm/zasm-06-04-what-is-elf.md +++ b/docs/zasm/zasm-06-04-what-is-elf.md @@ -26,8 +26,9 @@ program would need an ARM encoder and platform conventions. Linux shared-library linking and ARM backends remain future work. See [Linux x64 and ELF64](../linux64.md) for implemented layout and syscall examples. -**Checkpoint:** Explain why renaming `app.exe` to `app` cannot convert a Windows -program into a Linux program. + +> **Checkpoint:** Explain why renaming `app.exe` to `app` cannot convert a Windows +> program into a Linux program. --- diff --git a/docs/zasm/zasm-06-05-what-is-arm.md b/docs/zasm/zasm-06-05-what-is-arm.md index 69ca7ac..ba5a35b 100644 --- a/docs/zasm/zasm-06-05-what-is-arm.md +++ b/docs/zasm/zasm-06-05-what-is-arm.md @@ -24,8 +24,8 @@ and memory-layout decisions beyond those of an OS application. This chapter reserves a place for ARM while the working paths remain Windows x86 and Linux x64. See [future formats and targets](../designs/Future-Formats-and-Targets.md). -**Exercise:** Separate the algorithm in a hello program from its CPU-dependent -and OS-dependent operations. Those boundaries define much of the porting work. +> **Exercise:** Separate the algorithm in a hello program from its CPU-dependent +> and OS-dependent operations. Those boundaries define much of the porting work. --- diff --git a/docs/zasm/zasm-07-01-mnemonic-lookup.md b/docs/zasm/zasm-07-01-mnemonic-lookup.md index 4e888cc..d447a59 100644 --- a/docs/zasm/zasm-07-01-mnemonic-lookup.md +++ b/docs/zasm/zasm-07-01-mnemonic-lookup.md @@ -12,6 +12,8 @@ Appendices This compact **Windows x86** table summarizes operations used in the book. It does not enumerate every addressing restriction. +For a full list of Mnemonics, reference [ZASM-Mnemonics](ZASM-Mnemonics.md) documentation. + | Mnemonic | Purpose | Typical supported form | | --- | --- | --- | | `MOV` | Load a value | `mov eax, 42`; `mov eax, [value]` | From dbb20d78bc638748dc4ea3636e9758257ca8c2b6 Mon Sep 17 00:00:00 2001 From: Damian Suess Date: Sun, 15 Nov 2026 23:03:49 -0500 Subject: [PATCH 3/4] Zero Docs - Improved the notepad sample and added full code --- docs/index.md | 2 +- docs/zasm/index.md | 9 +- docs/zasm/zasm-04-01-notepad-project-setup.md | 76 +- .../zasm-04-02-notepad-create-the-window.md | 284 ++++++- .../zasm-04-03-notepad-add-the-text-editor.md | 342 ++++++++- .../zasm-04-04-notepad-open-and-save-files.md | 719 +++++++++++++++++- ...sm-04-05-notepad-testing-and-next-steps.md | 136 +++- .../Windows/notepad/notepad-01-window.zasm | 220 ++++++ .../Windows/notepad/notepad-02-editor.zasm | 283 +++++++ .../Windows/notepad/notepad-03-complete.zasm | 583 ++++++++++++++ samples/Windows/notepad/verify.py | 213 ++++++ samples/readme.md | 1 + 12 files changed, 2734 insertions(+), 134 deletions(-) create mode 100644 samples/Windows/notepad/notepad-01-window.zasm create mode 100644 samples/Windows/notepad/notepad-02-editor.zasm create mode 100644 samples/Windows/notepad/notepad-03-complete.zasm create mode 100644 samples/Windows/notepad/verify.py diff --git a/docs/index.md b/docs/index.md index 321a782..2e49463 100644 --- a/docs/index.md +++ b/docs/index.md @@ -25,7 +25,7 @@ define data, share headers, call Windows DLL functions, or use Linux syscalls. ## Documentation Library Start with the chapter-based [Zero Assembly Programmers Guide](zasm/index.md). -It includes a first program, fundamentals, functions, a Notepad project workshop, +It includes a first program, fundamentals, functions, a complete Notepad project, compiler/debugger usage, architecture, and mnemonic/ASCII appendices. | Book | Status | diff --git a/docs/zasm/index.md b/docs/zasm/index.md index cc94848..d155b9d 100644 --- a/docs/zasm/index.md +++ b/docs/zasm/index.md @@ -20,8 +20,9 @@ compiler layout. Current compiler limits appear beside the affected lessons. Structure declarations, full instruction-set coverage, and advanced Notepad features are not implied by -a chapter title. The Notepad project starts with a working sample, builds a -multiline editor, then provides a workshop for persistence and later features. +a chapter title. The Notepad project provides complete source at each stage, +ending with a resizable editor with Open, Save, Save As, Close, and +unsaved-change handling. Sections are consecutive in reading order: Notepad is Section 4, Compiler and Debugging is Section 5, and Architecture is Section 6. Section 7 holds the two @@ -60,10 +61,10 @@ numbers and lowercase, hyphenated titles. For example, ### Section 4 — Creating a Notepad Project -1. [Notepad Project — Set Up the Workspace](zasm-04-01-notepad-project-setup.md) +1. [Notepad Project — Overview and Setup](zasm-04-01-notepad-project-setup.md) 2. [Notepad Project — Create the Window](zasm-04-02-notepad-create-the-window.md) 3. [Notepad Project — Add the Text Editor](zasm-04-03-notepad-add-the-text-editor.md) -4. [Notepad Project — Open and Save Files](zasm-04-04-notepad-open-and-save-files.md) +4. [Notepad Project — Open, Save, Save As, and Close](zasm-04-04-notepad-open-and-save-files.md) 5. [Notepad Project — Test and Extend](zasm-04-05-notepad-testing-and-next-steps.md) ### Section 5 — Compiler and Debugging diff --git a/docs/zasm/zasm-04-01-notepad-project-setup.md b/docs/zasm/zasm-04-01-notepad-project-setup.md index f9b3869..3c76a28 100644 --- a/docs/zasm/zasm-04-01-notepad-project-setup.md +++ b/docs/zasm/zasm-04-01-notepad-project-setup.md @@ -1,37 +1,81 @@ --- layout: default -title: "Notepad Project — Set Up the Workspace" +title: "Notepad Project — Overview and Setup" --- -# Notepad Project — Set Up the Workspace +# Notepad Project — Overview and Setup Section 4 — Creating a Notepad Project · Chapter 4.1 [Previous](zasm-03-07-creating-functions.md) · [Contents](index.md) · [Next](zasm-04-02-notepad-create-the-window.md) -Grow the shipped controls example into a small Notepad-like editor. The first -milestone is an editable window; the second is file saving and loading. This -Windows x86 project retains the current console subsystem, so a console window -may accompany the editor. +## What You Will Build -1. Create a writable `ZeroNotepad` folder. -2. Copy [win-ui-02-controls.zasm](../../samples/Windows/win-ui-02-controls.zasm) - into it as `notepad.zasm`. Keep the original for comparison. -3. Open the folder and file in Zero.IDE. Select the installed compiler. -4. Build and run unchanged. Type text and press **Show message**. -5. Close the window and verify the process exits. +Build a working Windows x86 text editor entirely in Zero Assembly. The finished +program has an initial 800×600 window, a top row of Open, Save, Save As, and Close +buttons, and a multiline editor that fills the remaining client area as you resize. +Native dialogs choose filenames. Save remembers the current path; Save As selects +a new one. Open and Close ask whether to save modified text first. -Alternatively, from a terminal in the new source folder: +This section provides **complete source listings**, not replacement fragments. +Save each chapter's listing as `notepad.zasm`, replacing the previous stage's +contents. Each stage compiles independently. Chapter 4.4 contains the finished +application with every routine included; no earlier code needs to be assembled +by hand. + +## Project Stages and Source Files + +| Chapter | Result | Standalone source | +| --- | --- | --- | +| 4.2 | Titled 800×600 window, message handler, three top buttons | [notepad-01-window.zasm](../../samples/Windows/notepad/notepad-01-window.zasm) | +| 4.3 | Multiline editor and resize handling | [notepad-02-editor.zasm](../../samples/Windows/notepad/notepad-02-editor.zasm) | +| 4.4 | Open, Save, Save As, Close, and unsaved-change handling | [win-ui-10-notepad.zasm](../../samples/Windows/win-ui-10-notepad.zasm) | +| 4.5 | Build, round-trip tests, boundaries, and further work | Use the completed source above | + +The first two stages show an informational message when a file button is clicked; +the third replaces that temporary handler with real file operations. + +## Prerequisites + +Use Windows with support for x86 applications, a working Zero compiler, and a +writable project folder. The earlier setup chapters explain IDE installation. +These sources declare imports directly, so no local headers or assets are needed. +Windows supplies the standard DLLs used by the program. + +Create this folder and open it with **File > Open Folder...** in Zero.IDE: + +```text +ZeroNotepad/ + notepad.zasm +``` + +Select your compiler under **Tools > Options > Compiler**. Save a listing, then +choose **Build > Run Without Debugging**, or compile from PowerShell in that folder: ```powershell & 'C:\Program Files\SuessLabs\Zero\bin\zero.exe' notepad.zasm .\notepad.exe ``` -Use the next chapters in order and save a working copy after each milestone. +Replace the compiler path if installed elsewhere. The repository samples can +also be compiled directly using `publish/zero.exe` from the repository root. + +## Scope of This Editor + +The example supports small, zero-free text files up to **65,535 bytes**, using +Windows ANSI APIs. Use ASCII text for predictable results across code pages. +It preserves text bytes through binary C-runtime I/O; it is not a UTF-8/UTF-16 +encoding converter. Paths have a 260-byte buffer, including their ending zero. +The initial 800×600 dimensions include the title bar and frame, so the client +area is smaller. The current compiler emits a console-subsystem executable. + +The code uses zero-initialized heap storage because inline data is read-only. +`store_dword` uses `memcpy` to update four-byte state fields because the current +Windows x86 encoder lacks direct memory stores. This keeps all source compatible +with the implemented instruction set. -> **Checkpoint:** Get the original sample working before changing registration, -> the callback, or the message loop. +> **Checkpoint:** Locate the three standalone sources and identify which chapter +> contains the finished editor. Create a writable folder before continuing. --- diff --git a/docs/zasm/zasm-04-02-notepad-create-the-window.md b/docs/zasm/zasm-04-02-notepad-create-the-window.md index 9b4020e..2980c56 100644 --- a/docs/zasm/zasm-04-02-notepad-create-the-window.md +++ b/docs/zasm/zasm-04-02-notepad-create-the-window.md @@ -9,27 +9,269 @@ Section 4 — Creating a Notepad Project · Chapter 4.2 [Previous](zasm-04-01-notepad-project-setup.md) · [Contents](index.md) · [Next](zasm-04-03-notepad-add-the-text-editor.md) -Read `start` in your copy. It obtains an instance handle, builds `WNDCLASSA` on -the stack, registers it, and creates a window. `window_proc` is its callback. - -1. Change `window_class` to `ZeroNotepadWindow` and `window_title` to - `Zero Notepad`. Retain their ending zero bytes. -2. In the top-level `CreateWindowExA` block, change height 220 to 480 and - width 420 to 680. Height is pushed before width because argument order is - right to left. -3. Retain `ShowWindow`, `UpdateWindow`, and the `GetMessageA` loop. -4. Retain the zero check for `WM_QUIT` and the `0xFFFFFFFF` error check. -5. Retain the `WM_DESTROY` handler calling `PostQuitMessage`. - -Build and run. The larger window should have its new title, with controls at -their old positions. Closing it must still end the program. - -The callback forwards unhandled messages to `DefWindowProcA`. Its EBP-based -frame exposes `hwnd` at +8, message at +12, `wParam` at +16, and `lParam` at +20. -Keep `pop ebp` and `ret 16` matched on every callback exit. - -> **Checkpoint:** A visible window needs both a responsive message loop and a -> working destruction path. +## Define the Title, Size, and Buttons + +Save the complete listing below as `notepad.zasm`, or use +[notepad-01-window.zasm](../../samples/Windows/notepad/notepad-01-window.zasm). +`window_title` defines the title, and the main `CreateWindowExA` call requests an +**800×600 outer window**. Its style enables resizing and standard title-bar controls. + +Three child buttons occupy the top strip. The reusable `add_button` routine +receives an ID, caption pointer, and horizontal position. Every `PUSH` argument +to `CreateWindowExA` is labeled with its parameter name and meaning. + +| Button | ID | Horizontal position | +| --- | --- | --- | +| Open | 101 | 8 | +| Save | 102 | 104 | +| Save As | 103 | 200 | + +## Handle Window Messages + +`RegisterClassA` associates `window_proc` with the window class. The message loop +uses `GetMessageA`, `TranslateMessage`, and `DispatchMessageA`. The callback handles +button clicks through `WM_COMMAND` and shutdown through `WM_DESTROY`; other +messages go to `DefWindowProcA`. That default handler processes the title-bar X. + +Window callbacks preserve EBX, ESI, EDI, and EBP and return with `ret 16`. State is +attached using `GWL_USERDATA`, so callbacks can recover it without writable global +data. Early creation messages arrive before that pointer is attached and use +the default handler safely. + +## Complete Source: Window and Three Buttons + + +```asm +; Zero Notepad: Windows x86. Compile this file with zero.exe. +; Numeric constants below are Win32 values; no macros or writable sections needed. +#TARGET windows-x86 +#IMPORT kernel32.dll, GetModuleHandleA, GlobalAlloc, GlobalFree, ExitProcess +#IMPORT user32.dll, LoadCursorA, RegisterClassA, CreateWindowExA, ShowWindow, UpdateWindow +#IMPORT user32.dll, GetMessageA, TranslateMessage, DispatchMessageA, DefWindowProcA, PostQuitMessage +#IMPORT user32.dll, GetWindowLongA, SetWindowLongA, SendMessageA, MessageBoxA +#IMPORT user32.dll, GetClientRect, MoveWindow, GetWindowTextA, GetWindowTextLengthA, SetWindowTextA, DestroyWindow +#IMPORT msvcrt.dll, memcpy +jmp start + +window_class db 'ZeroNotepadClass', 0 +window_title db 'Zero Notepad', 0 +button_class db 'BUTTON', 0 +edit_class db 'EDIT', 0 +empty_text db 0 +open_text db 'Open', 0 +save_text db 'Save', 0 +save_as_text db 'Save As', 0 +close_text db 'Close', 0 +stage_text db 'The file buttons are connected in Chapter 4.4.', 0 +start: + ; Zero-initialized, writable state: +0 editor HWND, +4 dirty flag, + ; +8 current path[260], +268 dialog path[260], +528 text buffer[65537]. + push 66080 + push 0x40 ; GPTR: fixed, zero-initialized allocation. + call [GlobalAlloc] + test eax, eax + jz failed + push eax + pop esi ; ESI = state for the lifetime of the application. + + push 0 + call [GetModuleHandleA] + push eax + pop edi ; EDI = application instance. + push 32512 ; IDC_ARROW. + push 0 + call [LoadCursorA] + + ; WNDCLASSA: 40 bytes, constructed last field first. + push window_class ; lpszClassName. + push 0 ; lpszMenuName. + push 16 ; hbrBackground = COLOR_BTNFACE + 1. + push eax ; hCursor. + push 0 ; hIcon. + push edi ; hInstance. + push 0 ; cbWndExtra. + push 0 ; cbClsExtra. + push window_proc ; lpfnWndProc. + push 3 ; style: redraw on horizontal/vertical changes. + lea eax, [esp] + push eax + call [RegisterClassA] + add esp, 40 + test eax, eax + jz failed + + ; CreateWindowExA parameters, last to first. + push 0 ; lpParam: no creation data. + push edi ; hInstance: application instance. + push 0 ; hMenu: no menu bar. + push 0 ; hWndParent: top-level window. + push 600 ; nHeight: outer height, including frame/title. + push 800 ; nWidth: outer width in pixels. + push 0x80000000 ; Y: CW_USEDEFAULT. + push 0x80000000 ; X: CW_USEDEFAULT. + push 0x02CF0000 ; dwStyle: WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN. + push window_title ; lpWindowName: zero-terminated title. + push window_class ; lpClassName: registered class name. + push 0 ; dwExStyle: no extended styles. + call [CreateWindowExA] + test eax, eax + jz failed + push eax + pop ebx ; EBX = main window HWND. + + push esi ; New window user-data value: state pointer. + push 0xFFFFFFEB ; GWL_USERDATA = -21. + push ebx + call [SetWindowLongA] + + ; add_button(id, text, x): arguments pushed right to left. + push 8 + push open_text + push 101 + call add_button + push 104 + push save_text + push 102 + call add_button + push 200 + push save_as_text + push 103 + call add_button +push 1 + push ebx + call [ShowWindow] + push ebx + call [UpdateWindow] + sub esp, 32 ; Writable x86 MSG storage. + lea edi, [esp] +message_loop: + push 0 + push 0 + push 0 + push edi + call [GetMessageA] + test eax, eax + jz finished + cmp eax, 0xFFFFFFFF ; GetMessageA returns -1 on failure. + jz failed + push edi + call [TranslateMessage] + push edi + call [DispatchMessageA] + jmp message_loop +finished: + add esp, 32 + push esi + call [GlobalFree] + push 0 + call [ExitProcess] +failed: + push 1 + call [ExitProcess] ; Process teardown releases startup allocations. + +; EBX = parent, EDI = instance. Callee removes our three arguments. +add_button: + push ebp + lea ebp, [esp] + push 0 ; lpParam: no creation data. + push edi ; hInstance: application instance. + mov eax, [ebp + 8] + push eax ; hMenu: child button ID. + push ebx ; hWndParent: main window. + push 28 ; nHeight: button height. + push 88 ; nWidth: button width. + push 8 ; Y: top padding. + mov eax, [ebp + 16] + push eax ; X: horizontal position supplied by caller. + push 0x50010000 ; dwStyle: child, visible, tab stop, push button. + mov eax, [ebp + 12] + push eax ; lpWindowName: button caption. + push button_class ; lpClassName: built-in BUTTON class. + push 0 ; dwExStyle: no extended styles. + call [CreateWindowExA] + test eax, eax + jz failed + pop ebp + ret 12 + +; Windows x86 lacks MOV memory stores in ZASM. Copy four bytes via memcpy. +; Input: EDX = destination, EAX = value. Preserves EBX/ESI/EDI/EBP. +store_dword: + push eax + lea ecx, [esp] + push 4 + push ecx + push edx + call [memcpy] + add esp, 12 ; cdecl: remove memcpy's arguments. + add esp, 4 ; Remove the temporary value. + ret + +window_proc: + push ebp + lea ebp, [esp] ; +8 hwnd, +12 message, +16 wParam, +20 lParam. + push ebx + push esi + push edi ; Preserve the Win32 callback's nonvolatile registers. + mov ebx, [ebp + 8] + push 0xFFFFFFEB ; GWL_USERDATA. + push ebx + call [GetWindowLongA] + push eax + pop esi + test esi, esi ; Early creation messages arrive before state is set. + jz default_message + mov eax, [ebp + 12] + cmp eax, 2 ; WM_DESTROY. + jz window_destroyed + cmp eax, 0x111 ; WM_COMMAND. + jz window_command +default_message: + mov eax, [ebp + 20] + push eax + mov eax, [ebp + 16] + push eax + mov eax, [ebp + 12] + push eax + push ebx + call [DefWindowProcA] + jmp callback_done +window_destroyed: + push 0 + call [PostQuitMessage] + jmp callback_handled +window_command: + mov eax, [ebp + 16] +cmp eax, 101 + jz stage_notice + cmp eax, 102 + jz stage_notice + cmp eax, 103 + jnz default_message +stage_notice: + push 0x40 + push window_title + push stage_text + push ebx + call [MessageBoxA] +callback_handled: + xor eax, eax +callback_done: + pop edi + pop esi + pop ebx + pop ebp + ret 16 ; stdcall: discard four window-procedure arguments. +``` + +## Build and Check + +Build and run the listing using the command from Chapter 4.1. Expect the title +**Zero Notepad**, an empty client area, and the three buttons. Each button shows +the temporary Chapter 4.4 notice. Close the window using its title-bar X. + +> **Checkpoint:** Build this listing independently. Verify the title, initial +> window dimensions, three buttons, and normal process exit before adding text. --- diff --git a/docs/zasm/zasm-04-03-notepad-add-the-text-editor.md b/docs/zasm/zasm-04-03-notepad-add-the-text-editor.md index 4b0ea80..1fd1341 100644 --- a/docs/zasm/zasm-04-03-notepad-add-the-text-editor.md +++ b/docs/zasm/zasm-04-03-notepad-add-the-text-editor.md @@ -9,46 +9,328 @@ Section 4 — Creating a Notepad Project · Chapter 4.3 [Previous](zasm-04-02-notepad-create-the-window.md) · [Contents](index.md) · [Next](zasm-04-04-notepad-open-and-save-files.md) -Convert the single-line textbox into a multiline editing area. Keep ID 102 and -the Show message button for a quick readback test. +## Create the Multiline Textbox + +Replace your file with the complete listing below, also available as +[notepad-02-editor.zasm](../../samples/Windows/notepad/notepad-02-editor.zasm). +This stage retains all three buttons and adds an `EDIT` control with ID 201. +Its style enables multiline input, Enter-key line breaks, scrolling, and a border. +All twelve `CreateWindowExA` parameters are commented in the source. + +## Stretch the Editor with the Window + +The editor fills the **entire client width** and all client height below the +44-pixel button strip. It cannot cover the toolbar without hiding the buttons. +`WM_SIZE` calls `layout_editor`, which obtains the client rectangle using +`GetClientRect`, subtracts 44 from its height, and passes the result to `MoveWindow`. +It clamps negative heights to zero when the window becomes very small. + +The initial 1×1 control size is temporary: startup calls `layout_editor` before +showing the window. Later resize messages repeat the same calculation. The +editor handle lives at offset 0 of the writable state block. `EM_SETLIMITTEXT` +sets the input limit to 65,535 bytes, matching the finished program's file bound. +This message limits typing/pasting; Chapter 4.4 separately bounds file reads. +See Microsoft's [edit-control overview](https://learn.microsoft.com/en-us/windows/win32/controls/about-edit-controls) +for the control's text and buffer behavior. + +## Complete Source: Resizable Multiline Editor -1. Replace the block labeled `; Textbox:` up to, but not including, the - `; Button:` block with: ```asm - ; Multiline EDIT control, ID 102, at (20, 46), size 620 x 300. - ; CreateWindowExA arguments are pushed right to left (last parameter first). - push 0 ; lpParam: No application-defined creation data. - push esi ; hInstance: This application's instance handle. - push 102 ; hMenu: Control ID 102 for this child window. - push ebx ; hWndParent: Handle of the main application window. - push 300 ; nHeight: Editor height in pixels. - push 620 ; nWidth: Editor width in pixels. - push 46 ; Y: Top position in the parent's client area, in pixels. - push 20 ; X: Left position in the parent's client area, in pixels. - push 0x50B110C4 ; dwStyle: Child, visible, border, tab stop, scroll bars, - ; multiline, automatic scrolling, and Enter-key input. - push initial_text ; lpWindowName: Address of the initial zero-terminated text. - push edit_class ; lpClassName: Address of the zero-terminated "EDIT" class name. - push 0 ; dwExStyle: No extended window styles. +; Zero Notepad: Windows x86. Compile this file with zero.exe. +; Numeric constants below are Win32 values; no macros or writable sections needed. +#TARGET windows-x86 +#IMPORT kernel32.dll, GetModuleHandleA, GlobalAlloc, GlobalFree, ExitProcess +#IMPORT user32.dll, LoadCursorA, RegisterClassA, CreateWindowExA, ShowWindow, UpdateWindow +#IMPORT user32.dll, GetMessageA, TranslateMessage, DispatchMessageA, DefWindowProcA, PostQuitMessage +#IMPORT user32.dll, GetWindowLongA, SetWindowLongA, SendMessageA, MessageBoxA +#IMPORT user32.dll, GetClientRect, MoveWindow, GetWindowTextA, GetWindowTextLengthA, SetWindowTextA, DestroyWindow +#IMPORT msvcrt.dll, memcpy +jmp start + +window_class db 'ZeroNotepadClass', 0 +window_title db 'Zero Notepad', 0 +button_class db 'BUTTON', 0 +edit_class db 'EDIT', 0 +empty_text db 0 +open_text db 'Open', 0 +save_text db 'Save', 0 +save_as_text db 'Save As', 0 +close_text db 'Close', 0 +stage_text db 'The file buttons are connected in Chapter 4.4.', 0 +start: + ; Zero-initialized, writable state: +0 editor HWND, +4 dirty flag, + ; +8 current path[260], +268 dialog path[260], +528 text buffer[65537]. + push 66080 + push 0x40 ; GPTR: fixed, zero-initialized allocation. + call [GlobalAlloc] + test eax, eax + jz failed + push eax + pop esi ; ESI = state for the lifetime of the application. + + push 0 + call [GetModuleHandleA] + push eax + pop edi ; EDI = application instance. + push 32512 ; IDC_ARROW. + push 0 + call [LoadCursorA] + + ; WNDCLASSA: 40 bytes, constructed last field first. + push window_class ; lpszClassName. + push 0 ; lpszMenuName. + push 16 ; hbrBackground = COLOR_BTNFACE + 1. + push eax ; hCursor. + push 0 ; hIcon. + push edi ; hInstance. + push 0 ; cbWndExtra. + push 0 ; cbClsExtra. + push window_proc ; lpfnWndProc. + push 3 ; style: redraw on horizontal/vertical changes. + lea eax, [esp] + push eax + call [RegisterClassA] + add esp, 40 + test eax, eax + jz failed + + ; CreateWindowExA parameters, last to first. + push 0 ; lpParam: no creation data. + push edi ; hInstance: application instance. + push 0 ; hMenu: no menu bar. + push 0 ; hWndParent: top-level window. + push 600 ; nHeight: outer height, including frame/title. + push 800 ; nWidth: outer width in pixels. + push 0x80000000 ; Y: CW_USEDEFAULT. + push 0x80000000 ; X: CW_USEDEFAULT. + push 0x02CF0000 ; dwStyle: WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN. + push window_title ; lpWindowName: zero-terminated title. + push window_class ; lpClassName: registered class name. + push 0 ; dwExStyle: no extended styles. call [CreateWindowExA] test eax, eax jz failed + push eax + pop ebx ; EBX = main window HWND. + + push esi ; New window user-data value: state pointer. + push 0xFFFFFFEB ; GWL_USERDATA = -21. + push ebx + call [SetWindowLongA] + + ; add_button(id, text, x): arguments pushed right to left. + push 8 + push open_text + push 101 + call add_button + push 104 + push save_text + push 102 + call add_button + push 200 + push save_as_text + push 103 + call add_button +; Multiline editing area. WM_SIZE supplies its final dimensions. +push 0 ; lpParam: no creation data. +push edi ; hInstance: application instance. +push 201 ; hMenu: child control ID 201. +push ebx ; hWndParent: main window. +push 1 ; nHeight: temporary; layout_editor resizes it. +push 1 ; nWidth: temporary; layout_editor resizes it. +push 44 ; Y: below the 44-pixel button strip. +push 0 ; X: align with the client area's left edge. +push 0x50B110C4 ; dwStyle: child/visible/border/tab stop, + ; scroll bars, multiline, auto scroll, want Return. +push empty_text ; lpWindowName: initially empty document. +push edit_class ; lpClassName: built-in EDIT class. +push 0x200 ; dwExStyle: WS_EX_CLIENTEDGE. +call [CreateWindowExA] +test eax, eax +jz failed +lea edx, [esi] +call store_dword ; state.editor = returned HWND. + +push 0 ; lParam: unused. +push 65535 ; wParam: maximum typed/pasted text bytes. +push 0xC5 ; EM_SETLIMITTEXT. +mov eax, [esi] +push eax +call [SendMessageA] +call layout_editor +push 1 + push ebx + call [ShowWindow] + push ebx + call [UpdateWindow] + sub esp, 32 ; Writable x86 MSG storage. + lea edi, [esp] +message_loop: + push 0 + push 0 + push 0 + push edi + call [GetMessageA] + test eax, eax + jz finished + cmp eax, 0xFFFFFFFF ; GetMessageA returns -1 on failure. + jz failed + push edi + call [TranslateMessage] + push edi + call [DispatchMessageA] + jmp message_loop +finished: + add esp, 32 + push esi + call [GlobalFree] + push 0 + call [ExitProcess] +failed: + push 1 + call [ExitProcess] ; Process teardown releases startup allocations. + +; EBX = parent, EDI = instance. Callee removes our three arguments. +add_button: + push ebp + lea ebp, [esp] + push 0 ; lpParam: no creation data. + push edi ; hInstance: application instance. + mov eax, [ebp + 8] + push eax ; hMenu: child button ID. + push ebx ; hWndParent: main window. + push 28 ; nHeight: button height. + push 88 ; nWidth: button width. + push 8 ; Y: top padding. + mov eax, [ebp + 16] + push eax ; X: horizontal position supplied by caller. + push 0x50010000 ; dwStyle: child, visible, tab stop, push button. + mov eax, [ebp + 12] + push eax ; lpWindowName: button caption. + push button_class ; lpClassName: built-in BUTTON class. + push 0 ; dwExStyle: no extended styles. + call [CreateWindowExA] + test eax, eax + jz failed + pop ebp + ret 12 + +; Windows x86 lacks MOV memory stores in ZASM. Copy four bytes via memcpy. +; Input: EDX = destination, EAX = value. Preserves EBX/ESI/EDI/EBP. +store_dword: + push eax + lea ecx, [esp] + push 4 + push ecx + push edx + call [memcpy] + add esp, 12 ; cdecl: remove memcpy's arguments. + add esp, 4 ; Remove the temporary value. + ret + +window_proc: + push ebp + lea ebp, [esp] ; +8 hwnd, +12 message, +16 wParam, +20 lParam. + push ebx + push esi + push edi ; Preserve the Win32 callback's nonvolatile registers. + mov ebx, [ebp + 8] + push 0xFFFFFFEB ; GWL_USERDATA. + push ebx + call [GetWindowLongA] + push eax + pop esi + test esi, esi ; Early creation messages arrive before state is set. + jz default_message + mov eax, [ebp + 12] + cmp eax, 2 ; WM_DESTROY. + jz window_destroyed + cmp eax, 0x111 ; WM_COMMAND. + jz window_command +cmp eax, 5 ; WM_SIZE. +jz window_size +default_message: + mov eax, [ebp + 20] + push eax + mov eax, [ebp + 16] + push eax + mov eax, [ebp + 12] + push eax + push ebx + call [DefWindowProcA] + jmp callback_done +window_destroyed: + push 0 + call [PostQuitMessage] + jmp callback_handled +window_size: + call layout_editor + jmp callback_handled +window_command: + mov eax, [ebp + 16] +cmp eax, 101 + jz stage_notice + cmp eax, 102 + jz stage_notice + cmp eax, 103 + jnz default_message +stage_notice: + push 0x40 + push window_title + push stage_text + push ebx + call [MessageBoxA] +callback_handled: + xor eax, eax +callback_done: + pop edi + pop esi + pop ebx + pop ebp + ret 16 ; stdcall: discard four window-procedure arguments. +; EBX = parent, ESI = state. Query the client area on every resize. +layout_editor: + mov eax, [esi] + test eax, eax + jz layout_done ; No editor yet during early startup messages. + sub esp, 16 ; RECT { left, top, right, bottom }. + lea eax, [esp] + push eax + push ebx + call [GetClientRect] + test eax, eax + jz layout_release + mov ecx, [esp + 8] ; Client width (left is zero). + mov edx, [esp + 12] ; Client height (top is zero). + sub edx, 44 ; Leave room for buttons. + test edx, 0x80000000 ; Clamp a negative editor height to zero. + jz layout_move + xor edx, edx +layout_move: + push 1 ; bRepaint. + push edx ; nHeight: remaining client height. + push ecx ; nWidth: entire client width. + push 44 ; Y: immediately below the toolbar. + push 0 ; X: left edge. + mov eax, [esi] + push eax ; hWnd: multiline editor. + call [MoveWindow] +layout_release: + add esp, 16 +layout_done: + ret ``` -2. The style combines child/visible/border/tab-stop, scroll bars, multiline, - automatic scrolling, and Enter-key input. In the `; Button:` block change - y from `push 90` to `push 360` to position the button below the editor. -3. Rebuild. Enter multiple lines, scroll, then click Show message. The callback - reads up to 255 characters into a 256-byte stack buffer: the popup is a - short preview, not a full-document export. -4. Keep fixed dimensions for now. Later, handle `WM_SIZE` and call `MoveWindow` - after obtaining the client area to implement resizing. +## Try the Editor -This milestone provides a basic editor with readback. Persistence comes next. -The current APIs are ANSI; start with ASCII test input. +Type several lines, press Enter, select text, and use copy/paste. Drag the window +edges or maximize it: the textbox should follow the client area while the buttons +stay at the top. At this stage, the file buttons still display their temporary +notice. Saving and loading are implemented in the next complete listing. -> **Checkpoint:** Confirm Enter inserts a line break and closing still exits. +> **Checkpoint:** Verify multiline entry and resizing in both directions. The +> textbox must occupy the remaining client area without covering the buttons. --- diff --git a/docs/zasm/zasm-04-04-notepad-open-and-save-files.md b/docs/zasm/zasm-04-04-notepad-open-and-save-files.md index eceaa31..491f045 100644 --- a/docs/zasm/zasm-04-04-notepad-open-and-save-files.md +++ b/docs/zasm/zasm-04-04-notepad-open-and-save-files.md @@ -1,50 +1,693 @@ --- layout: default -title: "Notepad Project — Open and Save Files" +title: "Notepad Project — Open, Save, Save As, and Close" --- -# Notepad Project — Open and Save Files +# Notepad Project — Open, Save, Save As, and Close Section 4 — Creating a Notepad Project · Chapter 4.4 [Previous](zasm-04-03-notepad-add-the-text-editor.md) · [Contents](index.md) · [Next](zasm-04-05-notepad-testing-and-next-steps.md) -**Extension workshop:** the preceding edits and shipped sample do not implement -persistence. These are the next implementation steps, not a supplied finished -Notepad application. The file APIs are available through imports today. - -Start with a fixed test filename in the workspace; add dialogs after loading -and saving work. `kernel32.zh` declares file APIs and `user32.zh` declares text -control APIs. Declarations alone do not implement these routines. - -For **Save**: - -1. Obtain control 102 with `GetDlgItem`; call `GetWindowTextLengthA`. -2. Allocate length plus one for an ending zero. Use a bounded stack reservation - for a deliberately small exercise, or heap storage for variable-sized text. - Keep it alive until the write finishes. -3. Call `GetWindowTextA` with capacity including the zero. Use its returned - count as the byte count for this ANSI exercise, excluding the terminator. -4. Call `CreateFileA` with write access and a deliberate creation policy. - Check its failure sentinel before writing. -5. Call `WriteFile` with writable storage for the bytes-written result. Check - success and the byte count, then call `CloseHandle`. -6. On every failure, release acquired resources and show an error. Preserve - document state until saving is confirmed. - -For **Open**, open an existing file, determine and bound its size, allocate -size plus one, and call `ReadFile`. Check the actual count. Append an ending -zero in writable storage before `SetWindowTextA`. Direct x86 stores are missing: -use an imported routine such as `memset` for initialization/termination or a -zero-initialized heap allocation. Close the file and free the buffer on every -path. Treat embedded zero bytes as unsupported input. - -Retain the current document if reading fails. Do not mark it saved after a -failed or partial write. Then add New/Open/Save commands, dialogs, encoding -conversion, and an unsaved-changes prompt as separate tested features. - -> **Checkpoint:** Define ownership, capacity, failure handling, and cleanup for -> every pointer and handle before implementing these calls. +## The Finished Application + +Replace `notepad.zasm` with the **entire listing below**. It is also provided as +[win-ui-10-notepad.zasm](../../samples/Windows/win-ui-10-notepad.zasm). +This listing includes window creation, all four buttons, resizing, dialogs, +file routines, error reporting, and shutdown. No additional project files are +required. + +## Connect the Four Buttons + +`WM_COMMAND` combines the notification code with the control ID. For an ordinary +button click, `BN_CLICKED` is zero, so comparing `wParam` with its ID is sufficient. +Editor changes arrive with `EN_CHANGE` in the high word and ID 201 in the low +word; the handler marks the document dirty. + +| Button | ID | Handler | Behavior | +| --- | --- | --- | --- | +| Open | 101 | `button_open` → `open_document` | Confirm unsaved changes, choose a file, read and display it | +| Save | 102 | `button_save` → `save_document` | Write to the current path; use Save As for an unnamed document | +| Save As | 103 | `button_save_as` → `save_as_document` | Choose a destination and write the document | +| Close | 104 | `button_close` → `WM_CLOSE` | Confirm unsaved changes and destroy the window | + +The Close button sits after Save As. Both it and the title-bar X reach +`window_close`, so neither bypasses the unsaved-changes prompt. + +## Build the File Dialog Structure + +`choose_path` constructs the 88-byte x86 `OPENFILENAMEA` on the stack. Every field +is commented with its offset. It calls `GetOpenFileNameA` or `GetSaveFileNameA` +and distinguishes user cancellation from an API error with `CommDlgExtendedError`. +The filter contains display/pattern pairs and ends with two zero bytes. See +[Microsoft's OPENFILENAMEA reference](https://learn.microsoft.com/en-us/windows/win32/api/commdlg/ns-commdlg-openfilenamea) +for its fields and flags. + +The dialog writes to a **pending path**, keeping the current path unchanged +until file I/O succeeds. Save As requests overwrite confirmation. Both dialogs +preserve the application's working directory with `OFN_NOCHANGEDIR`. + +## Read, Write, and Own the Buffers + +The state block is allocated once and freed after the message loop exits: + +| Offset | Storage | Purpose | +| --- | --- | --- | +| 0 | 4 bytes | Editor HWND | +| 4 | 4 bytes | Unsaved-change flag | +| 8 | 260 bytes | Current filename, including terminator | +| 268 | 260 bytes | Pending dialog filename | +| 528 | 65,537 bytes | File/text buffer and termination space | + +`open_document` reads up to 65,536 bytes, one beyond the accepted limit. A read +of that size is rejected; smaller reads are checked for embedded zero bytes. +The buffer is zeroed first, ensuring termination for accepted input. Only a +successful read replaces the editor text and current path. + +`write_pending` retrieves the editor text, writes the returned byte count without +its terminator, checks the write count, and checks `fclose` for flush failures. +The code uses `rb`/`wb` C-runtime modes so newline bytes are not translated by +the file layer. Every cdecl call has explicit argument cleanup. + +Successful I/O copies the pending path to the current path, updates the title +to show that path, and clears the dirty flag. Failed writes retain the dirty flag. +Saving replaces the destination directly; a disk failure can leave a partial +file. Atomic replacement and backup files are further improvements, not provided +by this teaching example. + +## Confirm Unsaved Changes and Close + +`confirm_discard` shows Yes/No/Cancel before opening another file or closing. +Yes calls Save, No proceeds without saving, and Cancel aborts the action. +Canceling Save As or encountering a save error also aborts the pending action. +`DestroyWindow` leads to `WM_DESTROY`, which posts `WM_QUIT`. The main loop then +frees the state and calls `ExitProcess`. + +## Complete Source: Finished Zero Notepad + + +```asm +; Zero Notepad: Windows x86. Compile this file with zero.exe. +; Numeric constants below are Win32 values; no macros or writable sections needed. +#TARGET windows-x86 +#IMPORT kernel32.dll, GetModuleHandleA, GlobalAlloc, GlobalFree, ExitProcess +#IMPORT user32.dll, LoadCursorA, RegisterClassA, CreateWindowExA, ShowWindow, UpdateWindow +#IMPORT user32.dll, GetMessageA, TranslateMessage, DispatchMessageA, DefWindowProcA, PostQuitMessage +#IMPORT user32.dll, GetWindowLongA, SetWindowLongA, SendMessageA, MessageBoxA +#IMPORT user32.dll, GetClientRect, MoveWindow, GetWindowTextA, GetWindowTextLengthA, SetWindowTextA, DestroyWindow +#IMPORT msvcrt.dll, memcpy +#IMPORT comdlg32.dll, GetOpenFileNameA, GetSaveFileNameA, CommDlgExtendedError +#IMPORT msvcrt.dll, memset, strcpy, strlen, fopen, fread, fwrite, ferror, fclose +jmp start + +window_class db 'ZeroNotepadClass', 0 +window_title db 'Zero Notepad', 0 +button_class db 'BUTTON', 0 +edit_class db 'EDIT', 0 +empty_text db 0 +open_text db 'Open', 0 +save_text db 'Save', 0 +save_as_text db 'Save As', 0 +close_text db 'Close', 0 +stage_text db 'The file buttons are connected in Chapter 4.4.', 0 +file_filter db 'Text files (*.txt)', 0, '*.txt', 0, 'All files (*.*)', 0, '*.*', 0, 0 +default_ext db 'txt', 0 +read_mode db 'rb', 0 +write_mode db 'wb', 0 +read_error db 'Cannot open this text file. It must be at most 65535 bytes and contain no zero bytes.', 0 +write_error db 'Saving failed. Check the destination and available disk space. The file may be incomplete.', 0 +dialog_error db 'The file dialog could not be opened.', 0 +discard_text db 'Save changes before continuing?', 0 +start: + ; Zero-initialized, writable state: +0 editor HWND, +4 dirty flag, + ; +8 current path[260], +268 dialog path[260], +528 text buffer[65537]. + push 66080 + push 0x40 ; GPTR: fixed, zero-initialized allocation. + call [GlobalAlloc] + test eax, eax + jz failed + push eax + pop esi ; ESI = state for the lifetime of the application. + + push 0 + call [GetModuleHandleA] + push eax + pop edi ; EDI = application instance. + push 32512 ; IDC_ARROW. + push 0 + call [LoadCursorA] + + ; WNDCLASSA: 40 bytes, constructed last field first. + push window_class ; lpszClassName. + push 0 ; lpszMenuName. + push 16 ; hbrBackground = COLOR_BTNFACE + 1. + push eax ; hCursor. + push 0 ; hIcon. + push edi ; hInstance. + push 0 ; cbWndExtra. + push 0 ; cbClsExtra. + push window_proc ; lpfnWndProc. + push 3 ; style: redraw on horizontal/vertical changes. + lea eax, [esp] + push eax + call [RegisterClassA] + add esp, 40 + test eax, eax + jz failed + + ; CreateWindowExA parameters, last to first. + push 0 ; lpParam: no creation data. + push edi ; hInstance: application instance. + push 0 ; hMenu: no menu bar. + push 0 ; hWndParent: top-level window. + push 600 ; nHeight: outer height, including frame/title. + push 800 ; nWidth: outer width in pixels. + push 0x80000000 ; Y: CW_USEDEFAULT. + push 0x80000000 ; X: CW_USEDEFAULT. + push 0x02CF0000 ; dwStyle: WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN. + push window_title ; lpWindowName: zero-terminated title. + push window_class ; lpClassName: registered class name. + push 0 ; dwExStyle: no extended styles. + call [CreateWindowExA] + test eax, eax + jz failed + push eax + pop ebx ; EBX = main window HWND. + + push esi ; New window user-data value: state pointer. + push 0xFFFFFFEB ; GWL_USERDATA = -21. + push ebx + call [SetWindowLongA] + + ; add_button(id, text, x): arguments pushed right to left. + push 8 + push open_text + push 101 + call add_button + push 104 + push save_text + push 102 + call add_button + push 200 + push save_as_text + push 103 + call add_button +push 296 +push close_text +push 104 +call add_button +; Multiline editing area. WM_SIZE supplies its final dimensions. +push 0 ; lpParam: no creation data. +push edi ; hInstance: application instance. +push 201 ; hMenu: child control ID 201. +push ebx ; hWndParent: main window. +push 1 ; nHeight: temporary; layout_editor resizes it. +push 1 ; nWidth: temporary; layout_editor resizes it. +push 44 ; Y: below the 44-pixel button strip. +push 0 ; X: align with the client area's left edge. +push 0x50B110C4 ; dwStyle: child/visible/border/tab stop, + ; scroll bars, multiline, auto scroll, want Return. +push empty_text ; lpWindowName: initially empty document. +push edit_class ; lpClassName: built-in EDIT class. +push 0x200 ; dwExStyle: WS_EX_CLIENTEDGE. +call [CreateWindowExA] +test eax, eax +jz failed +lea edx, [esi] +call store_dword ; state.editor = returned HWND. + +push 0 ; lParam: unused. +push 65535 ; wParam: maximum typed/pasted text bytes. +push 0xC5 ; EM_SETLIMITTEXT. +mov eax, [esi] +push eax +call [SendMessageA] +call layout_editor +push 1 + push ebx + call [ShowWindow] + push ebx + call [UpdateWindow] + sub esp, 32 ; Writable x86 MSG storage. + lea edi, [esp] +message_loop: + push 0 + push 0 + push 0 + push edi + call [GetMessageA] + test eax, eax + jz finished + cmp eax, 0xFFFFFFFF ; GetMessageA returns -1 on failure. + jz failed + push edi + call [TranslateMessage] + push edi + call [DispatchMessageA] + jmp message_loop +finished: + add esp, 32 + push esi + call [GlobalFree] + push 0 + call [ExitProcess] +failed: + push 1 + call [ExitProcess] ; Process teardown releases startup allocations. + +; EBX = parent, EDI = instance. Callee removes our three arguments. +add_button: + push ebp + lea ebp, [esp] + push 0 ; lpParam: no creation data. + push edi ; hInstance: application instance. + mov eax, [ebp + 8] + push eax ; hMenu: child button ID. + push ebx ; hWndParent: main window. + push 28 ; nHeight: button height. + push 88 ; nWidth: button width. + push 8 ; Y: top padding. + mov eax, [ebp + 16] + push eax ; X: horizontal position supplied by caller. + push 0x50010000 ; dwStyle: child, visible, tab stop, push button. + mov eax, [ebp + 12] + push eax ; lpWindowName: button caption. + push button_class ; lpClassName: built-in BUTTON class. + push 0 ; dwExStyle: no extended styles. + call [CreateWindowExA] + test eax, eax + jz failed + pop ebp + ret 12 + +; Windows x86 lacks MOV memory stores in ZASM. Copy four bytes via memcpy. +; Input: EDX = destination, EAX = value. Preserves EBX/ESI/EDI/EBP. +store_dword: + push eax + lea ecx, [esp] + push 4 + push ecx + push edx + call [memcpy] + add esp, 12 ; cdecl: remove memcpy's arguments. + add esp, 4 ; Remove the temporary value. + ret + +window_proc: + push ebp + lea ebp, [esp] ; +8 hwnd, +12 message, +16 wParam, +20 lParam. + push ebx + push esi + push edi ; Preserve the Win32 callback's nonvolatile registers. + mov ebx, [ebp + 8] + push 0xFFFFFFEB ; GWL_USERDATA. + push ebx + call [GetWindowLongA] + push eax + pop esi + test esi, esi ; Early creation messages arrive before state is set. + jz default_message + mov eax, [ebp + 12] + cmp eax, 2 ; WM_DESTROY. + jz window_destroyed + cmp eax, 0x111 ; WM_COMMAND. + jz window_command +cmp eax, 5 ; WM_SIZE. +jz window_size +cmp eax, 0x10 ; WM_CLOSE from title-bar X or our Close button. +jz window_close +default_message: + mov eax, [ebp + 20] + push eax + mov eax, [ebp + 16] + push eax + mov eax, [ebp + 12] + push eax + push ebx + call [DefWindowProcA] + jmp callback_done +window_destroyed: + push 0 + call [PostQuitMessage] + jmp callback_handled +window_size: + call layout_editor + jmp callback_handled +window_command: + mov eax, [ebp + 16] +cmp eax, 0x030000C9 ; EN_CHANGE (0x300), editor ID 201 (0xC9). + jz document_changed + cmp eax, 101 ; BN_CLICKED = 0, Open ID 101. + jz button_open + cmp eax, 102 + jz button_save + cmp eax, 103 + jz button_save_as + cmp eax, 104 + jz button_close + jmp default_message +document_changed: + mov eax, 1 + lea edx, [esi + 4] + call store_dword + jmp callback_handled +button_open: + call open_document + jmp callback_handled +button_save: + call save_document + jmp callback_handled +button_save_as: + call save_as_document + jmp callback_handled +button_close: + push 0 + push 0 + push 0x10 ; Send WM_CLOSE through the same unsaved-check path. + push ebx + call [SendMessageA] + jmp callback_handled +window_close: + call confirm_discard + test eax, eax + jz callback_handled + push ebx + call [DestroyWindow] ; WM_DESTROY posts WM_QUIT for the message loop. + jmp callback_handled +callback_handled: + xor eax, eax +callback_done: + pop edi + pop esi + pop ebx + pop ebp + ret 16 ; stdcall: discard four window-procedure arguments. +; EBX = parent, ESI = state. Query the client area on every resize. +layout_editor: + mov eax, [esi] + test eax, eax + jz layout_done ; No editor yet during early startup messages. + sub esp, 16 ; RECT { left, top, right, bottom }. + lea eax, [esp] + push eax + push ebx + call [GetClientRect] + test eax, eax + jz layout_release + mov ecx, [esp + 8] ; Client width (left is zero). + mov edx, [esp + 12] ; Client height (top is zero). + sub edx, 44 ; Leave room for buttons. + test edx, 0x80000000 ; Clamp a negative editor height to zero. + jz layout_move + xor edx, edx +layout_move: + push 1 ; bRepaint. + push edx ; nHeight: remaining client height. + push ecx ; nWidth: entire client width. + push 44 ; Y: immediately below the toolbar. + push 0 ; X: left edge. + mov eax, [esi] + push eax ; hWnd: multiline editor. + call [MoveWindow] +layout_release: + add esp, 16 +layout_done: + ret +; Shared file routines: EBX = parent HWND, ESI = state. Return EAX = 1/0. +; C runtime functions use cdecl, so every call removes its argument bytes. + +; Ask before Open or Close discards edits. Yes saves; No proceeds; Cancel stops. +confirm_discard: + mov eax, [esi + 4] + test eax, eax + jz operation_ok + push 0x23 ; MB_YESNOCANCEL | MB_ICONQUESTION. + push window_title + push discard_text + push ebx + call [MessageBoxA] + cmp eax, 6 ; IDYES. + jz save_document + cmp eax, 7 ; IDNO. + jz operation_ok +operation_cancel: + xor eax, eax + ret +operation_ok: + mov eax, 1 + ret + +; Save uses the current path, or Save As for a new document. +save_document: + lea eax, [esi + 8] + push eax + call [strlen] + add esp, 4 + test eax, eax + jz save_as_document + lea eax, [esi + 8] + push eax + lea eax, [esi + 268] + push eax + call [strcpy] ; pending_path = current_path (both 260-byte buffers). + add esp, 8 + jmp write_pending +save_as_document: + mov eax, 1 ; Save dialog mode. + call choose_path + test eax, eax + jz operation_cancel + jmp write_pending + +; EAX = 0 for Open, 1 for Save As. Current path changes only after successful I/O. +choose_path: + push edi + push eax + pop edi ; Preserve the dialog mode across cdecl calls. + lea eax, [esi + 8] + push eax + lea eax, [esi + 268] + push eax + call [strcpy] + add esp, 8 + mov ecx, 0x81808 ; EXPLORER | FILEMUSTEXIST | PATHMUSTEXIST | NOCHANGEDIR. + test edi, edi + jz dialog_structure + mov ecx, 0x8080A ; EXPLORER | PATHMUSTEXIST | NOCHANGEDIR | OVERWRITEPROMPT. +dialog_structure: + ; x86 OPENFILENAMEA: 88 bytes. Fields pushed in reverse offset order. + push 0 ; +84 FlagsEx. + push 0 ; +80 dwReserved. + push 0 ; +76 pvReserved. + push 0 ; +72 lpTemplateName. + push 0 ; +68 lpfnHook. + push 0 ; +64 lCustData. + push default_ext ; +60 lpstrDefExt: append .txt when appropriate. + push 0 ; +56 nFileOffset and nFileExtension (two WORDs). + push ecx ; +52 Flags: Open or Save As behavior. + push 0 ; +48 lpstrTitle: use the dialog's default title. + push 0 ; +44 lpstrInitialDir. + push 0 ; +40 nMaxFileTitle. + push 0 ; +36 lpstrFileTitle. + push 260 ; +32 nMaxFile: capacity including the ending zero. + lea eax, [esi + 268] + push eax ; +28 lpstrFile: writable pending-path buffer. + push 1 ; +24 nFilterIndex: first filter. + push 0 ; +20 nMaxCustFilter. + push 0 ; +16 lpstrCustomFilter. + push file_filter ; +12 lpstrFilter: double-zero-terminated pairs. + push 0 ; +8 hInstance: no custom template. + push ebx ; +4 hwndOwner: main window. + push 88 ; +0 lStructSize: x86 OPENFILENAMEA size. + lea eax, [esp] + push eax + test edi, edi + jnz dialog_save + call [GetOpenFileNameA] + jmp dialog_finished +dialog_save: + call [GetSaveFileNameA] +dialog_finished: + add esp, 88 + pop edi + test eax, eax + jnz operation_ok + call [CommDlgExtendedError] + test eax, eax ; Zero means the user canceled, not an API failure. + jz operation_cancel + mov eax, dialog_error + jmp show_error + +open_document: + push edi + call confirm_discard + test eax, eax + jz open_cancel + xor eax, eax + call choose_path + test eax, eax + jz open_cancel + + push 65537 + push 0 + lea eax, [esi + 528] + push eax + call [memset] ; Ensure a zero terminator after any accepted read. + add esp, 12 + push read_mode + lea eax, [esi + 268] + push eax + call [fopen] + add esp, 8 + test eax, eax + jz open_error + push eax + pop edi ; EDI = FILE*, preserved by the CRT. + push edi + push 65536 ; Read one byte beyond the accepted 65535-byte limit. + push 1 + lea eax, [esi + 528] + push eax + call [fread] + add esp, 16 + push eax ; Save actual byte count across ferror/fclose. + push edi + call [ferror] + add esp, 4 + test eax, eax + jnz open_close_error + push edi + call [fclose] + add esp, 4 + pop edx ; Restore count and balance the stack even on failure. + test eax, eax + jnz open_error + cmp edx, 65536 + jz open_error ; Reject oversized input instead of silently truncating. + push edx + lea eax, [esi + 528] + push eax + call [strlen] + add esp, 4 + pop edx + cmp eax, edx + jnz open_error ; Embedded NUL would truncate the edit control's text. + lea eax, [esi + 528] + push eax + mov eax, [esi] + push eax + call [SetWindowTextA] + test eax, eax + jz open_error + call commit_path + pop edi + mov eax, 1 + ret +open_close_error: + push edi + call [fclose] + add esp, 4 + add esp, 4 ; Drop the saved count on the read-error path. +open_error: + mov eax, read_error + call show_error +open_cancel: + pop edi + xor eax, eax + ret + +write_pending: + push edi + push 65536 ; Buffer capacity: limit + ending zero. + lea eax, [esi + 528] + push eax + mov eax, [esi] + push eax + call [GetWindowTextA] + push eax ; Actual byte count; do not write the ending zero. + push write_mode + lea eax, [esi + 268] + push eax + call [fopen] ; Binary write: replace/create the chosen file. + add esp, 8 + test eax, eax + jz write_error_count + push eax + pop edi + mov eax, [esp] ; Saved text length. + push edi + push eax + push 1 + lea eax, [esi + 528] + push eax + call [fwrite] + add esp, 16 + mov ecx, [esp] + cmp eax, ecx + jnz write_close_error + push edi + call [fclose] ; Detect buffered flush/close failures as well. + add esp, 4 + test eax, eax + jnz write_error_count + add esp, 4 + call commit_path + pop edi + mov eax, 1 + ret +write_close_error: + push edi + call [fclose] + add esp, 4 +write_error_count: + add esp, 4 ; Drop saved length; retain dirty flag and current path. + pop edi + mov eax, write_error + jmp show_error + +commit_path: + lea eax, [esi + 268] + push eax + lea eax, [esi + 8] + push eax + call [strcpy] + add esp, 8 + xor eax, eax + lea edx, [esi + 4] + call store_dword ; Mark clean only after successful loading/saving. + lea eax, [esi + 8] + push eax + push ebx + call [SetWindowTextA] ; Show the current full filename in the title bar. + ret + +; Input EAX = error message address. Returns zero to cancel the operation. +show_error: + push 0x10 ; MB_OK | MB_ICONERROR. + push window_title + push eax + push ebx + call [MessageBoxA] + xor eax, eax + ret +``` + +## Build and Use the Finished Program + +From the folder containing your saved `notepad.zasm`: + +```powershell +& 'C:\Program Files\SuessLabs\Zero\bin\zero.exe' notepad.zasm +.\notepad.exe +``` + +Type text and click Save. Because the document has no filename yet, the Save As +dialog appears. Choose a new `.txt` file in your workspace. Modify the text and +click Save again: it writes to that path. Save As selects a different path; Open +loads a chosen file. Close and the title-bar X share the unsaved-change prompt. + +> **Checkpoint:** Create, save, reopen, and modify a text file. Save a second copy +> with Save As, then close using the fourth button. Verify the file contents on disk. --- diff --git a/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md b/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md index 141b539..8f12f28 100644 --- a/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md +++ b/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md @@ -9,30 +9,118 @@ Section 4 — Creating a Notepad Project · Chapter 4.5 [Previous](zasm-04-04-notepad-open-and-save-files.md) · [Contents](index.md) · [Next](zasm-05-01-zero-cli-compiler.md) -Validate one behavior at a time. Compare with the original sample to distinguish -existing behavior from regressions caused by edits. - -| Milestone | Check | Expected result | -| --- | --- | --- | -| Window | Launch and close repeatedly | Responsive window; process exits | -| Editing | Type, select, copy, paste, Enter | Multiline input works | -| Preview | Read fewer than 256 bytes | Popup matches entered text | -| Bounds | Preview a longer document | Bounded text; no stack corruption | -| Open extension | Missing or oversized file | Error; current document retained | -| Save extension | Empty and multiline text | Successful round trip | -| Save extension | Unwritable destination | Error; no false success state | - -Set a source breakpoint at `window_proc` or `window_command`, press F5, and -step over API calls with F10. Observe EAX results and ESP around calls. A -callback breakpoint can fire frequently as Windows delivers messages. - -Prioritize file persistence, error reporting, unsaved changes, resizing, and -encoding after the editing milestone. These are extensions to implement and -test: menu entries alone do not complete them. A production editor also needs -a deliberate large-file policy. - -> **Checkpoint:** Record which milestones your copy implements. Keep a known -> working copy until each new behavior passes its checks. +## Build the Finished Source + +Use the full listing from Chapter 4.4 or the standalone +[finished source](../../samples/Windows/win-ui-10-notepad.zasm). +From the repository root, compile to an explicit path: + +```powershell +.\publish\zero.exe samples\Windows\win-ui-10-notepad.zasm output\notepad.exe +.\output\notepad.exe +``` + +For your own `ZeroNotepad` folder, use the commands from Chapter 4.4 instead. +No NuGet packages, headers, images, or resource files are required by the sample. + +## Run the Automated Source and File Checks + +With Python 3 and the native compiler available on Windows, run from the +repository root: + +```powershell +python samples/Windows/notepad/verify.py +``` + +Pass `--compiler "C:\Path\To\zero.exe"` to select another compiler. The check +compares each chapter's full listing with its standalone sample, compiles all +three stages, and exercises the finished file routines against a hidden multiline +edit control. It verifies text bytes, empty files, size limits, rejection of zero +bytes, failed-write dirty state, and balanced stacks. Fixtures and executables +stay beneath `output/notepad-check`. + +Interactive filename selection and error popups are replaced with deterministic +test stubs. Run the manual dialog and unsaved-prompt checks below as well. + +## Test the Window and Editor + +| Action | Expected result | +| --- | --- | +| Launch | Initial 800×600 outer window titled Zero Notepad | +| Inspect top row | Open, Save, Save As, Close in that order | +| Enter several lines | Enter inserts line breaks; text remains editable | +| Resize or maximize | Editor fills the width and height below the button strip | +| Select/copy/paste | Standard Windows edit-control operations work | +| Minimize and restore | Document and controls remain available | + +The dimensions describe the outer window in the API's coordinate space; display +scaling and window borders affect the visible client dimensions. + +## Test Open, Save, and Save As + +Use new test files inside a writable workspace: + +1. Type two lines and click **Save**. A new document should open Save As. +2. Save as `first.txt`. Verify the two lines in another text editor. +3. Append a third line and click **Save**. The same file should change without + asking for its filename again. +4. Click **Save As** and choose `second.txt`. The title should show the new path; + later Save operations should update `second.txt`. +5. Click **Open** and load `first.txt`. Its original saved contents should return. +6. Repeat with an empty file and a path containing spaces. +7. Cancel each dialog. The current document and filename should remain intact. + +## Test Unsaved Changes and Closing + +After typing an edit, try both Open and Close. Repeat the close test with the +title-bar X as well as the Close button. + +| Prompt choice | Expected result | +| --- | --- | +| Yes | Save first; continue only after a successful save | +| No | Continue without saving the edits | +| Cancel | Keep the current document and window | +| Yes, then cancel Save As | Abort the original Open/Close action | +| Yes, then encounter a save error | Report error and keep the document open | + +Programmatic `SetWindowTextA` is not a substitute for a typing test of dirty +tracking: this multiline control's normal user edits send `EN_CHANGE`. + +## Test Limits and Failures + +| Input or condition | Expected result | +| --- | --- | +| Zero-byte file | Opens as an empty document and saves successfully | +| Zero-free ASCII file of 65,535 bytes | Accepted | +| File of 65,536 bytes or more | Rejected without replacing the current text | +| File containing a zero byte | Rejected as unsupported text | +| Missing/unreadable source | Dialog or application reports an error | +| Unwritable destination | Saving reports failure; dirty state remains | +| Existing Save As destination | Native dialog asks before overwrite | + +Only the current file-I/O operation reports success after its count and close +checks pass. Writes are direct replacements, so use disposable test destinations +when exercising failure conditions. + +## Debug the Message and File Paths + +Save sources, press F9 on an instruction, then F5 to launch a debug build. +Useful labels are `window_command`, `window_close`, `choose_path`, +`open_document`, `write_pending`, and `commit_path`. Step over API calls with F10. +Check EAX for results and ESP for balanced cleanup. The callback restores EBX, +ESI, EDI, and EBP before `ret 16`; changing that contract can corrupt message dispatch. + +## Next Steps + +The source already implements the requested four-button editor. Further projects +can add UTF-8/UTF-16 conversion, Unicode filenames and long paths, atomic saves, +backups, New, keyboard shortcuts, a modified-title indicator, and larger documents. +The buttons intentionally remain a fixed-width row; a more elaborate toolbar +could reflow them in very narrow windows. GUI-subsystem output also requires +future compiler support if you want to remove the accompanying console. + +> **Checkpoint:** Finish a full open/edit/save/save-as/close round trip and verify +> Cancel preserves work. Keep the completed source as your baseline before extending it. --- diff --git a/samples/Windows/notepad/notepad-01-window.zasm b/samples/Windows/notepad/notepad-01-window.zasm new file mode 100644 index 0000000..40ee769 --- /dev/null +++ b/samples/Windows/notepad/notepad-01-window.zasm @@ -0,0 +1,220 @@ +; Zero Notepad: Windows x86. Compile this file with zero.exe. +; Numeric constants below are Win32 values; no macros or writable sections needed. +#TARGET windows-x86 +#IMPORT kernel32.dll, GetModuleHandleA, GlobalAlloc, GlobalFree, ExitProcess +#IMPORT user32.dll, LoadCursorA, RegisterClassA, CreateWindowExA, ShowWindow, UpdateWindow +#IMPORT user32.dll, GetMessageA, TranslateMessage, DispatchMessageA, DefWindowProcA, PostQuitMessage +#IMPORT user32.dll, GetWindowLongA, SetWindowLongA, SendMessageA, MessageBoxA +#IMPORT user32.dll, GetClientRect, MoveWindow, GetWindowTextA, GetWindowTextLengthA, SetWindowTextA, DestroyWindow +#IMPORT msvcrt.dll, memcpy +jmp start + +window_class db 'ZeroNotepadClass', 0 +window_title db 'Zero Notepad', 0 +button_class db 'BUTTON', 0 +edit_class db 'EDIT', 0 +empty_text db 0 +open_text db 'Open', 0 +save_text db 'Save', 0 +save_as_text db 'Save As', 0 +close_text db 'Close', 0 +stage_text db 'The file buttons are connected in Chapter 4.4.', 0 +start: + ; Zero-initialized, writable state: +0 editor HWND, +4 dirty flag, + ; +8 current path[260], +268 dialog path[260], +528 text buffer[65537]. + push 66080 + push 0x40 ; GPTR: fixed, zero-initialized allocation. + call [GlobalAlloc] + test eax, eax + jz failed + push eax + pop esi ; ESI = state for the lifetime of the application. + + push 0 + call [GetModuleHandleA] + push eax + pop edi ; EDI = application instance. + push 32512 ; IDC_ARROW. + push 0 + call [LoadCursorA] + + ; WNDCLASSA: 40 bytes, constructed last field first. + push window_class ; lpszClassName. + push 0 ; lpszMenuName. + push 16 ; hbrBackground = COLOR_BTNFACE + 1. + push eax ; hCursor. + push 0 ; hIcon. + push edi ; hInstance. + push 0 ; cbWndExtra. + push 0 ; cbClsExtra. + push window_proc ; lpfnWndProc. + push 3 ; style: redraw on horizontal/vertical changes. + lea eax, [esp] + push eax + call [RegisterClassA] + add esp, 40 + test eax, eax + jz failed + + ; CreateWindowExA parameters, last to first. + push 0 ; lpParam: no creation data. + push edi ; hInstance: application instance. + push 0 ; hMenu: no menu bar. + push 0 ; hWndParent: top-level window. + push 600 ; nHeight: outer height, including frame/title. + push 800 ; nWidth: outer width in pixels. + push 0x80000000 ; Y: CW_USEDEFAULT. + push 0x80000000 ; X: CW_USEDEFAULT. + push 0x02CF0000 ; dwStyle: WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN. + push window_title ; lpWindowName: zero-terminated title. + push window_class ; lpClassName: registered class name. + push 0 ; dwExStyle: no extended styles. + call [CreateWindowExA] + test eax, eax + jz failed + push eax + pop ebx ; EBX = main window HWND. + + push esi ; New window user-data value: state pointer. + push 0xFFFFFFEB ; GWL_USERDATA = -21. + push ebx + call [SetWindowLongA] + + ; add_button(id, text, x): arguments pushed right to left. + push 8 + push open_text + push 101 + call add_button + push 104 + push save_text + push 102 + call add_button + push 200 + push save_as_text + push 103 + call add_button +push 1 + push ebx + call [ShowWindow] + push ebx + call [UpdateWindow] + sub esp, 32 ; Writable x86 MSG storage. + lea edi, [esp] +message_loop: + push 0 + push 0 + push 0 + push edi + call [GetMessageA] + test eax, eax + jz finished + cmp eax, 0xFFFFFFFF ; GetMessageA returns -1 on failure. + jz failed + push edi + call [TranslateMessage] + push edi + call [DispatchMessageA] + jmp message_loop +finished: + add esp, 32 + push esi + call [GlobalFree] + push 0 + call [ExitProcess] +failed: + push 1 + call [ExitProcess] ; Process teardown releases startup allocations. + +; EBX = parent, EDI = instance. Callee removes our three arguments. +add_button: + push ebp + lea ebp, [esp] + push 0 ; lpParam: no creation data. + push edi ; hInstance: application instance. + mov eax, [ebp + 8] + push eax ; hMenu: child button ID. + push ebx ; hWndParent: main window. + push 28 ; nHeight: button height. + push 88 ; nWidth: button width. + push 8 ; Y: top padding. + mov eax, [ebp + 16] + push eax ; X: horizontal position supplied by caller. + push 0x50010000 ; dwStyle: child, visible, tab stop, push button. + mov eax, [ebp + 12] + push eax ; lpWindowName: button caption. + push button_class ; lpClassName: built-in BUTTON class. + push 0 ; dwExStyle: no extended styles. + call [CreateWindowExA] + test eax, eax + jz failed + pop ebp + ret 12 + +; Windows x86 lacks MOV memory stores in ZASM. Copy four bytes via memcpy. +; Input: EDX = destination, EAX = value. Preserves EBX/ESI/EDI/EBP. +store_dword: + push eax + lea ecx, [esp] + push 4 + push ecx + push edx + call [memcpy] + add esp, 12 ; cdecl: remove memcpy's arguments. + add esp, 4 ; Remove the temporary value. + ret + +window_proc: + push ebp + lea ebp, [esp] ; +8 hwnd, +12 message, +16 wParam, +20 lParam. + push ebx + push esi + push edi ; Preserve the Win32 callback's nonvolatile registers. + mov ebx, [ebp + 8] + push 0xFFFFFFEB ; GWL_USERDATA. + push ebx + call [GetWindowLongA] + push eax + pop esi + test esi, esi ; Early creation messages arrive before state is set. + jz default_message + mov eax, [ebp + 12] + cmp eax, 2 ; WM_DESTROY. + jz window_destroyed + cmp eax, 0x111 ; WM_COMMAND. + jz window_command +default_message: + mov eax, [ebp + 20] + push eax + mov eax, [ebp + 16] + push eax + mov eax, [ebp + 12] + push eax + push ebx + call [DefWindowProcA] + jmp callback_done +window_destroyed: + push 0 + call [PostQuitMessage] + jmp callback_handled +window_command: + mov eax, [ebp + 16] +cmp eax, 101 + jz stage_notice + cmp eax, 102 + jz stage_notice + cmp eax, 103 + jnz default_message +stage_notice: + push 0x40 + push window_title + push stage_text + push ebx + call [MessageBoxA] +callback_handled: + xor eax, eax +callback_done: + pop edi + pop esi + pop ebx + pop ebp + ret 16 ; stdcall: discard four window-procedure arguments. diff --git a/samples/Windows/notepad/notepad-02-editor.zasm b/samples/Windows/notepad/notepad-02-editor.zasm new file mode 100644 index 0000000..64a508c --- /dev/null +++ b/samples/Windows/notepad/notepad-02-editor.zasm @@ -0,0 +1,283 @@ +; Zero Notepad: Windows x86. Compile this file with zero.exe. +; Numeric constants below are Win32 values; no macros or writable sections needed. +#TARGET windows-x86 +#IMPORT kernel32.dll, GetModuleHandleA, GlobalAlloc, GlobalFree, ExitProcess +#IMPORT user32.dll, LoadCursorA, RegisterClassA, CreateWindowExA, ShowWindow, UpdateWindow +#IMPORT user32.dll, GetMessageA, TranslateMessage, DispatchMessageA, DefWindowProcA, PostQuitMessage +#IMPORT user32.dll, GetWindowLongA, SetWindowLongA, SendMessageA, MessageBoxA +#IMPORT user32.dll, GetClientRect, MoveWindow, GetWindowTextA, GetWindowTextLengthA, SetWindowTextA, DestroyWindow +#IMPORT msvcrt.dll, memcpy +jmp start + +window_class db 'ZeroNotepadClass', 0 +window_title db 'Zero Notepad', 0 +button_class db 'BUTTON', 0 +edit_class db 'EDIT', 0 +empty_text db 0 +open_text db 'Open', 0 +save_text db 'Save', 0 +save_as_text db 'Save As', 0 +close_text db 'Close', 0 +stage_text db 'The file buttons are connected in Chapter 4.4.', 0 +start: + ; Zero-initialized, writable state: +0 editor HWND, +4 dirty flag, + ; +8 current path[260], +268 dialog path[260], +528 text buffer[65537]. + push 66080 + push 0x40 ; GPTR: fixed, zero-initialized allocation. + call [GlobalAlloc] + test eax, eax + jz failed + push eax + pop esi ; ESI = state for the lifetime of the application. + + push 0 + call [GetModuleHandleA] + push eax + pop edi ; EDI = application instance. + push 32512 ; IDC_ARROW. + push 0 + call [LoadCursorA] + + ; WNDCLASSA: 40 bytes, constructed last field first. + push window_class ; lpszClassName. + push 0 ; lpszMenuName. + push 16 ; hbrBackground = COLOR_BTNFACE + 1. + push eax ; hCursor. + push 0 ; hIcon. + push edi ; hInstance. + push 0 ; cbWndExtra. + push 0 ; cbClsExtra. + push window_proc ; lpfnWndProc. + push 3 ; style: redraw on horizontal/vertical changes. + lea eax, [esp] + push eax + call [RegisterClassA] + add esp, 40 + test eax, eax + jz failed + + ; CreateWindowExA parameters, last to first. + push 0 ; lpParam: no creation data. + push edi ; hInstance: application instance. + push 0 ; hMenu: no menu bar. + push 0 ; hWndParent: top-level window. + push 600 ; nHeight: outer height, including frame/title. + push 800 ; nWidth: outer width in pixels. + push 0x80000000 ; Y: CW_USEDEFAULT. + push 0x80000000 ; X: CW_USEDEFAULT. + push 0x02CF0000 ; dwStyle: WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN. + push window_title ; lpWindowName: zero-terminated title. + push window_class ; lpClassName: registered class name. + push 0 ; dwExStyle: no extended styles. + call [CreateWindowExA] + test eax, eax + jz failed + push eax + pop ebx ; EBX = main window HWND. + + push esi ; New window user-data value: state pointer. + push 0xFFFFFFEB ; GWL_USERDATA = -21. + push ebx + call [SetWindowLongA] + + ; add_button(id, text, x): arguments pushed right to left. + push 8 + push open_text + push 101 + call add_button + push 104 + push save_text + push 102 + call add_button + push 200 + push save_as_text + push 103 + call add_button +; Multiline editing area. WM_SIZE supplies its final dimensions. +push 0 ; lpParam: no creation data. +push edi ; hInstance: application instance. +push 201 ; hMenu: child control ID 201. +push ebx ; hWndParent: main window. +push 1 ; nHeight: temporary; layout_editor resizes it. +push 1 ; nWidth: temporary; layout_editor resizes it. +push 44 ; Y: below the 44-pixel button strip. +push 0 ; X: align with the client area's left edge. +push 0x50B110C4 ; dwStyle: child/visible/border/tab stop, + ; scroll bars, multiline, auto scroll, want Return. +push empty_text ; lpWindowName: initially empty document. +push edit_class ; lpClassName: built-in EDIT class. +push 0x200 ; dwExStyle: WS_EX_CLIENTEDGE. +call [CreateWindowExA] +test eax, eax +jz failed +lea edx, [esi] +call store_dword ; state.editor = returned HWND. + +push 0 ; lParam: unused. +push 65535 ; wParam: maximum typed/pasted text bytes. +push 0xC5 ; EM_SETLIMITTEXT. +mov eax, [esi] +push eax +call [SendMessageA] +call layout_editor +push 1 + push ebx + call [ShowWindow] + push ebx + call [UpdateWindow] + sub esp, 32 ; Writable x86 MSG storage. + lea edi, [esp] +message_loop: + push 0 + push 0 + push 0 + push edi + call [GetMessageA] + test eax, eax + jz finished + cmp eax, 0xFFFFFFFF ; GetMessageA returns -1 on failure. + jz failed + push edi + call [TranslateMessage] + push edi + call [DispatchMessageA] + jmp message_loop +finished: + add esp, 32 + push esi + call [GlobalFree] + push 0 + call [ExitProcess] +failed: + push 1 + call [ExitProcess] ; Process teardown releases startup allocations. + +; EBX = parent, EDI = instance. Callee removes our three arguments. +add_button: + push ebp + lea ebp, [esp] + push 0 ; lpParam: no creation data. + push edi ; hInstance: application instance. + mov eax, [ebp + 8] + push eax ; hMenu: child button ID. + push ebx ; hWndParent: main window. + push 28 ; nHeight: button height. + push 88 ; nWidth: button width. + push 8 ; Y: top padding. + mov eax, [ebp + 16] + push eax ; X: horizontal position supplied by caller. + push 0x50010000 ; dwStyle: child, visible, tab stop, push button. + mov eax, [ebp + 12] + push eax ; lpWindowName: button caption. + push button_class ; lpClassName: built-in BUTTON class. + push 0 ; dwExStyle: no extended styles. + call [CreateWindowExA] + test eax, eax + jz failed + pop ebp + ret 12 + +; Windows x86 lacks MOV memory stores in ZASM. Copy four bytes via memcpy. +; Input: EDX = destination, EAX = value. Preserves EBX/ESI/EDI/EBP. +store_dword: + push eax + lea ecx, [esp] + push 4 + push ecx + push edx + call [memcpy] + add esp, 12 ; cdecl: remove memcpy's arguments. + add esp, 4 ; Remove the temporary value. + ret + +window_proc: + push ebp + lea ebp, [esp] ; +8 hwnd, +12 message, +16 wParam, +20 lParam. + push ebx + push esi + push edi ; Preserve the Win32 callback's nonvolatile registers. + mov ebx, [ebp + 8] + push 0xFFFFFFEB ; GWL_USERDATA. + push ebx + call [GetWindowLongA] + push eax + pop esi + test esi, esi ; Early creation messages arrive before state is set. + jz default_message + mov eax, [ebp + 12] + cmp eax, 2 ; WM_DESTROY. + jz window_destroyed + cmp eax, 0x111 ; WM_COMMAND. + jz window_command +cmp eax, 5 ; WM_SIZE. +jz window_size +default_message: + mov eax, [ebp + 20] + push eax + mov eax, [ebp + 16] + push eax + mov eax, [ebp + 12] + push eax + push ebx + call [DefWindowProcA] + jmp callback_done +window_destroyed: + push 0 + call [PostQuitMessage] + jmp callback_handled +window_size: + call layout_editor + jmp callback_handled +window_command: + mov eax, [ebp + 16] +cmp eax, 101 + jz stage_notice + cmp eax, 102 + jz stage_notice + cmp eax, 103 + jnz default_message +stage_notice: + push 0x40 + push window_title + push stage_text + push ebx + call [MessageBoxA] +callback_handled: + xor eax, eax +callback_done: + pop edi + pop esi + pop ebx + pop ebp + ret 16 ; stdcall: discard four window-procedure arguments. +; EBX = parent, ESI = state. Query the client area on every resize. +layout_editor: + mov eax, [esi] + test eax, eax + jz layout_done ; No editor yet during early startup messages. + sub esp, 16 ; RECT { left, top, right, bottom }. + lea eax, [esp] + push eax + push ebx + call [GetClientRect] + test eax, eax + jz layout_release + mov ecx, [esp + 8] ; Client width (left is zero). + mov edx, [esp + 12] ; Client height (top is zero). + sub edx, 44 ; Leave room for buttons. + test edx, 0x80000000 ; Clamp a negative editor height to zero. + jz layout_move + xor edx, edx +layout_move: + push 1 ; bRepaint. + push edx ; nHeight: remaining client height. + push ecx ; nWidth: entire client width. + push 44 ; Y: immediately below the toolbar. + push 0 ; X: left edge. + mov eax, [esi] + push eax ; hWnd: multiline editor. + call [MoveWindow] +layout_release: + add esp, 16 +layout_done: + ret diff --git a/samples/Windows/notepad/notepad-03-complete.zasm b/samples/Windows/notepad/notepad-03-complete.zasm new file mode 100644 index 0000000..a306da4 --- /dev/null +++ b/samples/Windows/notepad/notepad-03-complete.zasm @@ -0,0 +1,583 @@ +; Zero Notepad: Windows x86. Compile this file with zero.exe. +; Numeric constants below are Win32 values; no macros or writable sections needed. +#TARGET windows-x86 +#IMPORT kernel32.dll, GetModuleHandleA, GlobalAlloc, GlobalFree, ExitProcess +#IMPORT user32.dll, LoadCursorA, RegisterClassA, CreateWindowExA, ShowWindow, UpdateWindow +#IMPORT user32.dll, GetMessageA, TranslateMessage, DispatchMessageA, DefWindowProcA, PostQuitMessage +#IMPORT user32.dll, GetWindowLongA, SetWindowLongA, SendMessageA, MessageBoxA +#IMPORT user32.dll, GetClientRect, MoveWindow, GetWindowTextA, GetWindowTextLengthA, SetWindowTextA, DestroyWindow +#IMPORT msvcrt.dll, memcpy +#IMPORT comdlg32.dll, GetOpenFileNameA, GetSaveFileNameA, CommDlgExtendedError +#IMPORT msvcrt.dll, memset, strcpy, strlen, fopen, fread, fwrite, ferror, fclose +jmp start + +window_class db 'ZeroNotepadClass', 0 +window_title db 'Zero Notepad', 0 +button_class db 'BUTTON', 0 +edit_class db 'EDIT', 0 +empty_text db 0 +open_text db 'Open', 0 +save_text db 'Save', 0 +save_as_text db 'Save As', 0 +close_text db 'Close', 0 +stage_text db 'The file buttons are connected in Chapter 4.4.', 0 +file_filter db 'Text files (*.txt)', 0, '*.txt', 0, 'All files (*.*)', 0, '*.*', 0, 0 +default_ext db 'txt', 0 +read_mode db 'rb', 0 +write_mode db 'wb', 0 +read_error db 'Cannot open this text file. It must be at most 65535 bytes and contain no zero bytes.', 0 +write_error db 'Saving failed. Check the destination and available disk space. The file may be incomplete.', 0 +dialog_error db 'The file dialog could not be opened.', 0 +discard_text db 'Save changes before continuing?', 0 +start: + ; Zero-initialized, writable state: +0 editor HWND, +4 dirty flag, + ; +8 current path[260], +268 dialog path[260], +528 text buffer[65537]. + push 66080 + push 0x40 ; GPTR: fixed, zero-initialized allocation. + call [GlobalAlloc] + test eax, eax + jz failed + push eax + pop esi ; ESI = state for the lifetime of the application. + + push 0 + call [GetModuleHandleA] + push eax + pop edi ; EDI = application instance. + push 32512 ; IDC_ARROW. + push 0 + call [LoadCursorA] + + ; WNDCLASSA: 40 bytes, constructed last field first. + push window_class ; lpszClassName. + push 0 ; lpszMenuName. + push 16 ; hbrBackground = COLOR_BTNFACE + 1. + push eax ; hCursor. + push 0 ; hIcon. + push edi ; hInstance. + push 0 ; cbWndExtra. + push 0 ; cbClsExtra. + push window_proc ; lpfnWndProc. + push 3 ; style: redraw on horizontal/vertical changes. + lea eax, [esp] + push eax + call [RegisterClassA] + add esp, 40 + test eax, eax + jz failed + + ; CreateWindowExA parameters, last to first. + push 0 ; lpParam: no creation data. + push edi ; hInstance: application instance. + push 0 ; hMenu: no menu bar. + push 0 ; hWndParent: top-level window. + push 600 ; nHeight: outer height, including frame/title. + push 800 ; nWidth: outer width in pixels. + push 0x80000000 ; Y: CW_USEDEFAULT. + push 0x80000000 ; X: CW_USEDEFAULT. + push 0x02CF0000 ; dwStyle: WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN. + push window_title ; lpWindowName: zero-terminated title. + push window_class ; lpClassName: registered class name. + push 0 ; dwExStyle: no extended styles. + call [CreateWindowExA] + test eax, eax + jz failed + push eax + pop ebx ; EBX = main window HWND. + + push esi ; New window user-data value: state pointer. + push 0xFFFFFFEB ; GWL_USERDATA = -21. + push ebx + call [SetWindowLongA] + + ; add_button(id, text, x): arguments pushed right to left. + push 8 + push open_text + push 101 + call add_button + push 104 + push save_text + push 102 + call add_button + push 200 + push save_as_text + push 103 + call add_button +push 296 +push close_text +push 104 +call add_button +; Multiline editing area. WM_SIZE supplies its final dimensions. +push 0 ; lpParam: no creation data. +push edi ; hInstance: application instance. +push 201 ; hMenu: child control ID 201. +push ebx ; hWndParent: main window. +push 1 ; nHeight: temporary; layout_editor resizes it. +push 1 ; nWidth: temporary; layout_editor resizes it. +push 44 ; Y: below the 44-pixel button strip. +push 0 ; X: align with the client area's left edge. +push 0x50B110C4 ; dwStyle: child/visible/border/tab stop, + ; scroll bars, multiline, auto scroll, want Return. +push empty_text ; lpWindowName: initially empty document. +push edit_class ; lpClassName: built-in EDIT class. +push 0x200 ; dwExStyle: WS_EX_CLIENTEDGE. +call [CreateWindowExA] +test eax, eax +jz failed +lea edx, [esi] +call store_dword ; state.editor = returned HWND. + +push 0 ; lParam: unused. +push 65535 ; wParam: maximum typed/pasted text bytes. +push 0xC5 ; EM_SETLIMITTEXT. +mov eax, [esi] +push eax +call [SendMessageA] +call layout_editor +push 1 + push ebx + call [ShowWindow] + push ebx + call [UpdateWindow] + sub esp, 32 ; Writable x86 MSG storage. + lea edi, [esp] +message_loop: + push 0 + push 0 + push 0 + push edi + call [GetMessageA] + test eax, eax + jz finished + cmp eax, 0xFFFFFFFF ; GetMessageA returns -1 on failure. + jz failed + push edi + call [TranslateMessage] + push edi + call [DispatchMessageA] + jmp message_loop +finished: + add esp, 32 + push esi + call [GlobalFree] + push 0 + call [ExitProcess] +failed: + push 1 + call [ExitProcess] ; Process teardown releases startup allocations. + +; EBX = parent, EDI = instance. Callee removes our three arguments. +add_button: + push ebp + lea ebp, [esp] + push 0 ; lpParam: no creation data. + push edi ; hInstance: application instance. + mov eax, [ebp + 8] + push eax ; hMenu: child button ID. + push ebx ; hWndParent: main window. + push 28 ; nHeight: button height. + push 88 ; nWidth: button width. + push 8 ; Y: top padding. + mov eax, [ebp + 16] + push eax ; X: horizontal position supplied by caller. + push 0x50010000 ; dwStyle: child, visible, tab stop, push button. + mov eax, [ebp + 12] + push eax ; lpWindowName: button caption. + push button_class ; lpClassName: built-in BUTTON class. + push 0 ; dwExStyle: no extended styles. + call [CreateWindowExA] + test eax, eax + jz failed + pop ebp + ret 12 + +; Windows x86 lacks MOV memory stores in ZASM. Copy four bytes via memcpy. +; Input: EDX = destination, EAX = value. Preserves EBX/ESI/EDI/EBP. +store_dword: + push eax + lea ecx, [esp] + push 4 + push ecx + push edx + call [memcpy] + add esp, 12 ; cdecl: remove memcpy's arguments. + add esp, 4 ; Remove the temporary value. + ret + +window_proc: + push ebp + lea ebp, [esp] ; +8 hwnd, +12 message, +16 wParam, +20 lParam. + push ebx + push esi + push edi ; Preserve the Win32 callback's nonvolatile registers. + mov ebx, [ebp + 8] + push 0xFFFFFFEB ; GWL_USERDATA. + push ebx + call [GetWindowLongA] + push eax + pop esi + test esi, esi ; Early creation messages arrive before state is set. + jz default_message + mov eax, [ebp + 12] + cmp eax, 2 ; WM_DESTROY. + jz window_destroyed + cmp eax, 0x111 ; WM_COMMAND. + jz window_command +cmp eax, 5 ; WM_SIZE. +jz window_size +cmp eax, 0x10 ; WM_CLOSE from title-bar X or our Close button. +jz window_close +default_message: + mov eax, [ebp + 20] + push eax + mov eax, [ebp + 16] + push eax + mov eax, [ebp + 12] + push eax + push ebx + call [DefWindowProcA] + jmp callback_done +window_destroyed: + push 0 + call [PostQuitMessage] + jmp callback_handled +window_size: + call layout_editor + jmp callback_handled +window_command: + mov eax, [ebp + 16] +cmp eax, 0x030000C9 ; EN_CHANGE (0x300), editor ID 201 (0xC9). + jz document_changed + cmp eax, 101 ; BN_CLICKED = 0, Open ID 101. + jz button_open + cmp eax, 102 + jz button_save + cmp eax, 103 + jz button_save_as + cmp eax, 104 + jz button_close + jmp default_message +document_changed: + mov eax, 1 + lea edx, [esi + 4] + call store_dword + jmp callback_handled +button_open: + call open_document + jmp callback_handled +button_save: + call save_document + jmp callback_handled +button_save_as: + call save_as_document + jmp callback_handled +button_close: + push 0 + push 0 + push 0x10 ; Send WM_CLOSE through the same unsaved-check path. + push ebx + call [SendMessageA] + jmp callback_handled +window_close: + call confirm_discard + test eax, eax + jz callback_handled + push ebx + call [DestroyWindow] ; WM_DESTROY posts WM_QUIT for the message loop. + jmp callback_handled +callback_handled: + xor eax, eax +callback_done: + pop edi + pop esi + pop ebx + pop ebp + ret 16 ; stdcall: discard four window-procedure arguments. +; EBX = parent, ESI = state. Query the client area on every resize. +layout_editor: + mov eax, [esi] + test eax, eax + jz layout_done ; No editor yet during early startup messages. + sub esp, 16 ; RECT { left, top, right, bottom }. + lea eax, [esp] + push eax + push ebx + call [GetClientRect] + test eax, eax + jz layout_release + mov ecx, [esp + 8] ; Client width (left is zero). + mov edx, [esp + 12] ; Client height (top is zero). + sub edx, 44 ; Leave room for buttons. + test edx, 0x80000000 ; Clamp a negative editor height to zero. + jz layout_move + xor edx, edx +layout_move: + push 1 ; bRepaint. + push edx ; nHeight: remaining client height. + push ecx ; nWidth: entire client width. + push 44 ; Y: immediately below the toolbar. + push 0 ; X: left edge. + mov eax, [esi] + push eax ; hWnd: multiline editor. + call [MoveWindow] +layout_release: + add esp, 16 +layout_done: + ret +; Shared file routines: EBX = parent HWND, ESI = state. Return EAX = 1/0. +; C runtime functions use cdecl, so every call removes its argument bytes. + +; Ask before Open or Close discards edits. Yes saves; No proceeds; Cancel stops. +confirm_discard: + mov eax, [esi + 4] + test eax, eax + jz operation_ok + push 0x23 ; MB_YESNOCANCEL | MB_ICONQUESTION. + push window_title + push discard_text + push ebx + call [MessageBoxA] + cmp eax, 6 ; IDYES. + jz save_document + cmp eax, 7 ; IDNO. + jz operation_ok +operation_cancel: + xor eax, eax + ret +operation_ok: + mov eax, 1 + ret + +; Save uses the current path, or Save As for a new document. +save_document: + lea eax, [esi + 8] + push eax + call [strlen] + add esp, 4 + test eax, eax + jz save_as_document + lea eax, [esi + 8] + push eax + lea eax, [esi + 268] + push eax + call [strcpy] ; pending_path = current_path (both 260-byte buffers). + add esp, 8 + jmp write_pending +save_as_document: + mov eax, 1 ; Save dialog mode. + call choose_path + test eax, eax + jz operation_cancel + jmp write_pending + +; EAX = 0 for Open, 1 for Save As. Current path changes only after successful I/O. +choose_path: + push edi + push eax + pop edi ; Preserve the dialog mode across cdecl calls. + lea eax, [esi + 8] + push eax + lea eax, [esi + 268] + push eax + call [strcpy] + add esp, 8 + mov ecx, 0x81808 ; EXPLORER | FILEMUSTEXIST | PATHMUSTEXIST | NOCHANGEDIR. + test edi, edi + jz dialog_structure + mov ecx, 0x8080A ; EXPLORER | PATHMUSTEXIST | NOCHANGEDIR | OVERWRITEPROMPT. +dialog_structure: + ; x86 OPENFILENAMEA: 88 bytes. Fields pushed in reverse offset order. + push 0 ; +84 FlagsEx. + push 0 ; +80 dwReserved. + push 0 ; +76 pvReserved. + push 0 ; +72 lpTemplateName. + push 0 ; +68 lpfnHook. + push 0 ; +64 lCustData. + push default_ext ; +60 lpstrDefExt: append .txt when appropriate. + push 0 ; +56 nFileOffset and nFileExtension (two WORDs). + push ecx ; +52 Flags: Open or Save As behavior. + push 0 ; +48 lpstrTitle: use the dialog's default title. + push 0 ; +44 lpstrInitialDir. + push 0 ; +40 nMaxFileTitle. + push 0 ; +36 lpstrFileTitle. + push 260 ; +32 nMaxFile: capacity including the ending zero. + lea eax, [esi + 268] + push eax ; +28 lpstrFile: writable pending-path buffer. + push 1 ; +24 nFilterIndex: first filter. + push 0 ; +20 nMaxCustFilter. + push 0 ; +16 lpstrCustomFilter. + push file_filter ; +12 lpstrFilter: double-zero-terminated pairs. + push 0 ; +8 hInstance: no custom template. + push ebx ; +4 hwndOwner: main window. + push 88 ; +0 lStructSize: x86 OPENFILENAMEA size. + lea eax, [esp] + push eax + test edi, edi + jnz dialog_save + call [GetOpenFileNameA] + jmp dialog_finished +dialog_save: + call [GetSaveFileNameA] +dialog_finished: + add esp, 88 + pop edi + test eax, eax + jnz operation_ok + call [CommDlgExtendedError] + test eax, eax ; Zero means the user canceled, not an API failure. + jz operation_cancel + mov eax, dialog_error + jmp show_error + +open_document: + push edi + call confirm_discard + test eax, eax + jz open_cancel + xor eax, eax + call choose_path + test eax, eax + jz open_cancel + + push 65537 + push 0 + lea eax, [esi + 528] + push eax + call [memset] ; Ensure a zero terminator after any accepted read. + add esp, 12 + push read_mode + lea eax, [esi + 268] + push eax + call [fopen] + add esp, 8 + test eax, eax + jz open_error + push eax + pop edi ; EDI = FILE*, preserved by the CRT. + push edi + push 65536 ; Read one byte beyond the accepted 65535-byte limit. + push 1 + lea eax, [esi + 528] + push eax + call [fread] + add esp, 16 + push eax ; Save actual byte count across ferror/fclose. + push edi + call [ferror] + add esp, 4 + test eax, eax + jnz open_close_error + push edi + call [fclose] + add esp, 4 + pop edx ; Restore count and balance the stack even on failure. + test eax, eax + jnz open_error + cmp edx, 65536 + jz open_error ; Reject oversized input instead of silently truncating. + push edx + lea eax, [esi + 528] + push eax + call [strlen] + add esp, 4 + pop edx + cmp eax, edx + jnz open_error ; Embedded NUL would truncate the edit control's text. + lea eax, [esi + 528] + push eax + mov eax, [esi] + push eax + call [SetWindowTextA] + test eax, eax + jz open_error + call commit_path + pop edi + mov eax, 1 + ret +open_close_error: + push edi + call [fclose] + add esp, 4 + add esp, 4 ; Drop the saved count on the read-error path. +open_error: + mov eax, read_error + call show_error +open_cancel: + pop edi + xor eax, eax + ret + +write_pending: + push edi + push 65536 ; Buffer capacity: limit + ending zero. + lea eax, [esi + 528] + push eax + mov eax, [esi] + push eax + call [GetWindowTextA] + push eax ; Actual byte count; do not write the ending zero. + push write_mode + lea eax, [esi + 268] + push eax + call [fopen] ; Binary write: replace/create the chosen file. + add esp, 8 + test eax, eax + jz write_error_count + push eax + pop edi + mov eax, [esp] ; Saved text length. + push edi + push eax + push 1 + lea eax, [esi + 528] + push eax + call [fwrite] + add esp, 16 + mov ecx, [esp] + cmp eax, ecx + jnz write_close_error + push edi + call [fclose] ; Detect buffered flush/close failures as well. + add esp, 4 + test eax, eax + jnz write_error_count + add esp, 4 + call commit_path + pop edi + mov eax, 1 + ret +write_close_error: + push edi + call [fclose] + add esp, 4 +write_error_count: + add esp, 4 ; Drop saved length; retain dirty flag and current path. + pop edi + mov eax, write_error + jmp show_error + +commit_path: + lea eax, [esi + 268] + push eax + lea eax, [esi + 8] + push eax + call [strcpy] + add esp, 8 + xor eax, eax + lea edx, [esi + 4] + call store_dword ; Mark clean only after successful loading/saving. + lea eax, [esi + 8] + push eax + push ebx + call [SetWindowTextA] ; Show the current full filename in the title bar. + ret + +; Input EAX = error message address. Returns zero to cancel the operation. +show_error: + push 0x10 ; MB_OK | MB_ICONERROR. + push window_title + push eax + push ebx + call [MessageBoxA] + xor eax, eax + ret diff --git a/samples/Windows/notepad/verify.py b/samples/Windows/notepad/verify.py new file mode 100644 index 0000000..b9c76a5 --- /dev/null +++ b/samples/Windows/notepad/verify.py @@ -0,0 +1,213 @@ +# Copyright Xeno Innovations, Inc. 2026 +# See LICENSE in the repository root. +"""Windows-only integration check for the Section 4 Notepad source listings. + +Run from any directory: python samples/Windows/notepad/verify.py +Use --compiler to select a different native zero.exe. Interactive file dialogs +and prompts are stubbed; their behavior is covered by Chapter 4.5's manual checks. +""" +from pathlib import Path +import argparse +import subprocess +import sys + +if sys.platform != 'win32': + raise SystemExit('This runtime check requires Windows.') +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('--compiler', type=Path) +args = parser.parse_args() + +root=Path(__file__).resolve().parents[3] +compiler=(args.compiler or root/'publish/zero.exe').resolve() +if not compiler.is_file(): + raise SystemExit(f'Compiler not found: {compiler}. Build it or pass --compiler.') +out=root/'output/notepad-check' +out.mkdir(parents=True, exist_ok=True) +# Keep every printed listing identical to its runnable sample and compile each stage. +import re +stages = [ + ('notepad-01-window', 'zasm-04-02-notepad-create-the-window'), + ('notepad-02-editor', 'zasm-04-03-notepad-add-the-text-editor'), + ('notepad-03-complete', 'zasm-04-04-notepad-open-and-save-files'), +] +for stem, chapter in stages: + src = root/'samples/Windows/notepad'/f'{stem}.zasm' + listing = (root/'docs/zasm'/f'{chapter}.md').read_text(encoding='utf-8') + blocks = re.findall(r'```asm\n(.*?)```', listing, re.S) + assert blocks == [src.read_text(encoding='utf-8')], f'Listing differs: {chapter}' + result = subprocess.run([str(compiler), str(src), str(out/f'{stem}.exe')], + capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr +print('PASS: All three complete chapter listings match their standalone sources and compile.') +sample=(root/'samples/Windows/win-ui-10-notepad.zasm').read_text(encoding='utf-8') +assert sample == (root/'samples/Windows/notepad/notepad-03-complete.zasm').read_text(encoding='utf-8'), 'Finished sample differs from the final tutorial stage.' +# Exercise the exact I/O routines against a hidden EDIT control. Replace only +# interactive filename selection and error popups with deterministic test stubs. +assert 'jmp start' in sample +sample=sample.replace('jmp start','jmp test_start',1) +start=sample.index('choose_path:\n') +end=sample.index('open_document:\n',start) +sample=sample[:start]+'choose_path:\n mov eax, 1\n ret\n\n'+sample[end:] +sample=sample[:sample.index('show_error:\n')]+'show_error:\n xor eax, eax\n ret\n' +sample+='#IMPORT msvcrt.dll, strcmp\n' +paths={} +fixtures={'input':b'Loaded text\r\nSecond line', 'empty':b'', + 'maximum':b'A'*65535, 'oversized':b'B'*65536, 'nul':b'one\x00two'} +for key,data in fixtures.items(): + path=out/f'{key}.txt' + path.write_bytes(data) + paths[key]=path +paths['saved']=out/'saved.txt' +paths['empty_saved']=out/'empty-saved.txt' +paths['bad']=out/'directory-that-does-not-exist'/'bad.txt' +for key,path in paths.items(): + sample+=f"test_path_{key} db '{path.as_posix()}', 0\n" +sample+="test_initial db 'Initial text', 13, 10, 'Second line', 0\n" +sample+="test_revised db 'Revised text', 13, 10, 'Second line', 0\n" +sample+="test_loaded db 'Loaded text', 13, 10, 'Second line', 0\n" +sample+="test_parent_class db 'STATIC', 0\n" +sample+=''' +test_start: + lea ebp, [esp] + push 66080 + push 0x40 + call [GlobalAlloc] + test eax, eax + jz test_fail + push eax + pop esi + push 0 + push 0 + push 0 + push 0 + push 100 + push 100 + push 0 + push 0 + push 0x80000000 + push empty_text + push test_parent_class + push 0 + call [CreateWindowExA] + test eax, eax + jz test_fail + push eax + pop ebx + push 0 + push 0 + push 201 + push ebx + push 100 + push 100 + push 0 + push 0 + push 0x40B110C4 + push empty_text + push edit_class + push 0 + call [CreateWindowExA] + test eax, eax + jz test_fail + lea edx, [esi] + call store_dword + push 0 + push 65535 + push 0xC5 + mov eax, [esi] + push eax + call [SendMessageA] +''' + +def pending(key): + return f''' push test_path_{key} + lea eax, [esi + 268] + push eax + call [strcpy] + add esp, 8 +''' + +def text(key): + return f''' push test_{key} + mov eax, [esi] + push eax + call [SetWindowTextA] + test eax, eax + jz test_fail +''' + +def check(result): + return f''' cmp eax, {result} + jnz test_fail + cmp esp, ebp + jnz test_fail +''' + +def clean(): + return ''' xor eax, eax + lea edx, [esi + 4] + call store_dword +''' + +sample+=text('initial')+pending('saved')+' call save_as_document\n'+check(1) +sample+=text('revised')+''' mov eax, 1 + lea edx, [esi + 4] + call store_dword + call save_document +'''+check(1) +sample+=''' mov eax, [esi + 4] + test eax, eax + jnz test_fail +''' +sample+=pending('input')+' call open_document\n'+check(1) +sample+=''' push 65536 + lea eax, [esi + 528] + push eax + mov eax, [esi] + push eax + call [GetWindowTextA] + push test_loaded + lea eax, [esi + 528] + push eax + call [strcmp] + add esp, 8 +'''+check(0) +for key in ['maximum','oversized','nul','empty']: + sample+=clean()+pending(key)+' call open_document\n'+check(0 if key in ['oversized','nul'] else 1) + if key in ['oversized','nul']: + # Rejected reads must leave the previously loaded 65535-byte editor intact. + sample+=' mov eax, [esi]\n push eax\n call [GetWindowTextLengthA]\n'+check(65535) +sample+=pending('empty_saved')+' call save_as_document\n'+check(1) +sample+=pending('bad')+''' mov eax, 1 + lea edx, [esi + 4] + call store_dword + call write_pending +'''+check(0) +sample+=''' mov eax, [esi + 4] +'''+check(1) +sample+=''' push ebx + call [DestroyWindow] + push esi + call [GlobalFree] + push 0 + call [ExitProcess] +test_fail: + push 99 + call [ExitProcess] +''' +branches=[] +def label_failure(match): + branches.append(sample[max(0,match.start()-180):match.end()]) + return match.group(1)+f' test_failure_{len(branches)}' +sample=re.sub(r'(jz|jnz) test_fail\b',label_failure,sample) +for i in range(1,len(branches)+1): + sample+=f'\ntest_failure_{i}:\n push {i}\n call [ExitProcess]\n' +src=out/'runtime-check.zasm' +src.write_text(sample,encoding='utf-8') +exe=src.with_suffix('.exe') +compile=subprocess.run([str(compiler),str(src),str(exe)],capture_output=True,text=True) +assert compile.returncode==0,compile.stdout+compile.stderr +run=subprocess.run([str(exe)],timeout=20) +assert run.returncode==0,f'Runtime check failed with exit code {run.returncode}:\n'+(branches[run.returncode-1] if 0 [output.exe]` builds the source, then runs the executable in the From 2e798d97fba9b776fed424202a974d536c5aa010 Mon Sep 17 00:00:00 2001 From: Damian Suess Date: Sun, 15 Nov 2026 23:14:02 -0500 Subject: [PATCH 4/4] Updated notepad example. Replaced notepad sample's validation with verify.cs (C#) instead of python for consistency --- docs/zasm/zasm-04-01-notepad-project-setup.md | 2 +- .../zasm-04-04-notepad-open-and-save-files.md | 44 ++- ...sm-04-05-notepad-testing-and-next-steps.md | 21 +- samples/Windows/notepad/verify.cs | 342 ++++++++++++++++++ samples/Windows/notepad/verify.py | 213 ----------- samples/readme.md | 2 +- 6 files changed, 401 insertions(+), 223 deletions(-) create mode 100644 samples/Windows/notepad/verify.cs delete mode 100644 samples/Windows/notepad/verify.py diff --git a/docs/zasm/zasm-04-01-notepad-project-setup.md b/docs/zasm/zasm-04-01-notepad-project-setup.md index 3c76a28..c3aaf2a 100644 --- a/docs/zasm/zasm-04-01-notepad-project-setup.md +++ b/docs/zasm/zasm-04-01-notepad-project-setup.md @@ -29,7 +29,7 @@ by hand. | --- | --- | --- | | 4.2 | Titled 800×600 window, message handler, three top buttons | [notepad-01-window.zasm](../../samples/Windows/notepad/notepad-01-window.zasm) | | 4.3 | Multiline editor and resize handling | [notepad-02-editor.zasm](../../samples/Windows/notepad/notepad-02-editor.zasm) | -| 4.4 | Open, Save, Save As, Close, and unsaved-change handling | [win-ui-10-notepad.zasm](../../samples/Windows/win-ui-10-notepad.zasm) | +| 4.4 | Open, Save, Save As, Close, and unsaved-change handling | [notepad-03-complete.zasm](../../samples/Windows/notepad/notepad-03-complete.zasm) | | 4.5 | Build, round-trip tests, boundaries, and further work | Use the completed source above | The first two stages show an informational message when a file button is clicked; diff --git a/docs/zasm/zasm-04-04-notepad-open-and-save-files.md b/docs/zasm/zasm-04-04-notepad-open-and-save-files.md index 491f045..7ab6d44 100644 --- a/docs/zasm/zasm-04-04-notepad-open-and-save-files.md +++ b/docs/zasm/zasm-04-04-notepad-open-and-save-files.md @@ -12,7 +12,7 @@ Section 4 — Creating a Notepad Project · Chapter 4.4 ## The Finished Application Replace `notepad.zasm` with the **entire listing below**. It is also provided as -[win-ui-10-notepad.zasm](../../samples/Windows/win-ui-10-notepad.zasm). +[notepad-03-complete.zasm](../../samples/Windows/notepad/notepad-03-complete.zasm). This listing includes window creation, all four buttons, resizing, dialogs, file routines, error reporting, and shutdown. No additional project files are required. @@ -124,6 +124,7 @@ start: push 66080 push 0x40 ; GPTR: fixed, zero-initialized allocation. call [GlobalAlloc] + test eax, eax jz failed push eax @@ -151,6 +152,7 @@ start: lea eax, [esp] push eax call [RegisterClassA] + add esp, 40 test eax, eax jz failed @@ -169,6 +171,7 @@ start: push window_class ; lpClassName: registered class name. push 0 ; dwExStyle: no extended styles. call [CreateWindowExA] + test eax, eax jz failed push eax @@ -184,14 +187,17 @@ start: push open_text push 101 call add_button + push 104 push save_text push 102 call add_button + push 200 push save_as_text push 103 call add_button + push 296 push close_text push 104 @@ -303,6 +309,7 @@ window_proc: push 0xFFFFFFEB ; GWL_USERDATA. push ebx call [GetWindowLongA] + push eax pop esi test esi, esi ; Early creation messages arrive before state is set. @@ -312,10 +319,13 @@ window_proc: jz window_destroyed cmp eax, 0x111 ; WM_COMMAND. jz window_command + cmp eax, 5 ; WM_SIZE. jz window_size + cmp eax, 0x10 ; WM_CLOSE from title-bar X or our Close button. jz window_close + default_message: mov eax, [ebp + 20] push eax @@ -326,13 +336,16 @@ default_message: push ebx call [DefWindowProcA] jmp callback_done + window_destroyed: push 0 call [PostQuitMessage] jmp callback_handled + window_size: call layout_editor jmp callback_handled + window_command: mov eax, [ebp + 16] cmp eax, 0x030000C9 ; EN_CHANGE (0x300), editor ID 201 (0xC9). @@ -346,20 +359,25 @@ cmp eax, 0x030000C9 ; EN_CHANGE (0x300), editor ID 201 (0xC9). cmp eax, 104 jz button_close jmp default_message + document_changed: mov eax, 1 lea edx, [esi + 4] call store_dword jmp callback_handled + button_open: call open_document jmp callback_handled + button_save: call save_document jmp callback_handled + button_save_as: call save_as_document jmp callback_handled + button_close: push 0 push 0 @@ -367,6 +385,7 @@ button_close: push ebx call [SendMessageA] jmp callback_handled + window_close: call confirm_discard test eax, eax @@ -374,8 +393,10 @@ window_close: push ebx call [DestroyWindow] ; WM_DESTROY posts WM_QUIT for the message loop. jmp callback_handled + callback_handled: xor eax, eax + callback_done: pop edi pop esi @@ -383,6 +404,7 @@ callback_done: pop ebp ret 16 ; stdcall: discard four window-procedure arguments. ; EBX = parent, ESI = state. Query the client area on every resize. + layout_editor: mov eax, [esi] test eax, eax @@ -392,6 +414,7 @@ layout_editor: push eax push ebx call [GetClientRect] + test eax, eax jz layout_release mov ecx, [esp + 8] ; Client width (left is zero). @@ -409,6 +432,7 @@ layout_move: mov eax, [esi] push eax ; hWnd: multiline editor. call [MoveWindow] + layout_release: add esp, 16 layout_done: @@ -442,6 +466,7 @@ save_document: lea eax, [esi + 8] push eax call [strlen] + add esp, 4 test eax, eax jz save_as_document @@ -450,6 +475,7 @@ save_document: lea eax, [esi + 268] push eax call [strcpy] ; pending_path = current_path (both 260-byte buffers). + add esp, 8 jmp write_pending save_as_document: @@ -469,6 +495,7 @@ choose_path: lea eax, [esi + 268] push eax call [strcpy] + add esp, 8 mov ecx, 0x81808 ; EXPLORER | FILEMUSTEXIST | PATHMUSTEXIST | NOCHANGEDIR. test edi, edi @@ -504,15 +531,19 @@ dialog_structure: test edi, edi jnz dialog_save call [GetOpenFileNameA] + jmp dialog_finished + dialog_save: call [GetSaveFileNameA] + dialog_finished: add esp, 88 pop edi test eax, eax jnz operation_ok call [CommDlgExtendedError] + test eax, eax ; Zero means the user canceled, not an API failure. jz operation_cancel mov eax, dialog_error @@ -533,11 +564,13 @@ open_document: lea eax, [esi + 528] push eax call [memset] ; Ensure a zero terminator after any accepted read. + add esp, 12 push read_mode lea eax, [esi + 268] push eax call [fopen] + add esp, 8 test eax, eax jz open_error @@ -549,15 +582,18 @@ open_document: lea eax, [esi + 528] push eax call [fread] + add esp, 16 push eax ; Save actual byte count across ferror/fclose. push edi call [ferror] + add esp, 4 test eax, eax jnz open_close_error push edi call [fclose] + add esp, 4 pop edx ; Restore count and balance the stack even on failure. test eax, eax @@ -568,6 +604,7 @@ open_document: lea eax, [esi + 528] push eax call [strlen] + add esp, 4 pop edx cmp eax, edx @@ -577,6 +614,7 @@ open_document: mov eax, [esi] push eax call [SetWindowTextA] + test eax, eax jz open_error call commit_path @@ -635,10 +673,13 @@ write_pending: pop edi mov eax, 1 ret + write_close_error: push edi call [fclose] + add esp, 4 + write_error_count: add esp, 4 ; Drop saved length; retain dirty flag and current path. pop edi @@ -655,6 +696,7 @@ commit_path: xor eax, eax lea edx, [esi + 4] call store_dword ; Mark clean only after successful loading/saving. + lea eax, [esi + 8] push eax push ebx diff --git a/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md b/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md index 8f12f28..daddef5 100644 --- a/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md +++ b/docs/zasm/zasm-04-05-notepad-testing-and-next-steps.md @@ -12,11 +12,11 @@ Section 4 — Creating a Notepad Project · Chapter 4.5 ## Build the Finished Source Use the full listing from Chapter 4.4 or the standalone -[finished source](../../samples/Windows/win-ui-10-notepad.zasm). +[finished source](../../samples/Windows/notepad/notepad-03-complete.zasm). From the repository root, compile to an explicit path: ```powershell -.\publish\zero.exe samples\Windows\win-ui-10-notepad.zasm output\notepad.exe +.\publish\zero.exe samples\Windows\notepad\notepad-03-complete.zasm output\notepad.exe .\output\notepad.exe ``` @@ -25,15 +25,22 @@ No NuGet packages, headers, images, or resource files are required by the sample ## Run the Automated Source and File Checks -With Python 3 and the native compiler available on Windows, run from the -repository root: +With the .NET 10 SDK and the native compiler available on Windows, run from +the repository root: ```powershell -python samples/Windows/notepad/verify.py +dotnet run --file samples/Windows/notepad/verify.cs ``` -Pass `--compiler "C:\Path\To\zero.exe"` to select another compiler. The check -compares each chapter's full listing with its standalone sample, compiles all +This is a [single-file C# application](https://learn.microsoft.com/en-us/dotnet/core/sdk/file-based-apps), +with no project file or package dependencies. To select another compiler, pass +its path after the argument separator: + +```powershell +dotnet run --file samples/Windows/notepad/verify.cs -- --compiler "C:\Path\To\zero.exe" +``` + +The check compares each chapter's full listing with its standalone sample, compiles all three stages, and exercises the finished file routines against a hidden multiline edit control. It verifies text bytes, empty files, size limits, rejection of zero bytes, failed-write dirty state, and balanced stacks. Fixtures and executables diff --git a/samples/Windows/notepad/verify.cs b/samples/Windows/notepad/verify.cs new file mode 100644 index 0000000..8cb0e64 --- /dev/null +++ b/samples/Windows/notepad/verify.cs @@ -0,0 +1,342 @@ +// Copyright Xeno Innovations, Inc. 2026 +// See LICENSE in the repository root. +// Run: dotnet run --file samples/Windows/notepad/verify.cs -- [--compiler ] +// Requires Windows and .NET 10 SDK or later. No project or NuGet packages needed. +#:property TargetFramework=net10.0 +#:property NuGetAudit=false +#:property UseSharedCompilation=false + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +return await Verify.RunAsync(args); + +internal static class Verify +{ + public static async Task RunAsync(string[] args) + { + try + { + string? compilerOption = null; + for (int i = 0; i < args.Length; i++) + { + if (args[i] is "--help" or "-h") + { + Console.WriteLine("Usage: dotnet run --file samples/Windows/notepad/verify.cs -- [--compiler ]"); + Console.WriteLine("Windows-only source and file-I/O checks. Dialog selection and error popups are stubbed."); + return 0; + } + + Require(args[i] == "--compiler" && compilerOption is null && i + 1 < args.Length && + !args[i + 1].StartsWith("--", StringComparison.Ordinal), + "Expected --compiler . Use --help for usage."); + compilerOption = args[++i]; + } + + Require(OperatingSystem.IsWindows(), "This runtime check requires Windows."); + // CallerFilePath is the source location, independent of the SDK build cache or working directory. + string root = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(SourcePath())!, "../../..")); + string compiler = Path.GetFullPath(compilerOption ?? Path.Combine(root, "publish/zero.exe")); + Require(File.Exists(compiler), $"Compiler not found: {compiler}. Build it or pass --compiler."); + string output = Path.Combine(root, "output/notepad-check"); + Directory.CreateDirectory(output); + + var stages = new[] + { + ("notepad-01-window", "zasm-04-02-notepad-create-the-window"), + ("notepad-02-editor", "zasm-04-03-notepad-add-the-text-editor"), + ("notepad-03-complete", "zasm-04-04-notepad-open-and-save-files"), + }; + + foreach (var (stem, chapter) in stages) + { + string source = Path.Combine(root, $"samples/Windows/notepad/{stem}.zasm"); + string listing = ReadText(Path.Combine(root, $"docs/zasm/{chapter}.md")); + MatchCollection blocks = Regex.Matches(listing, @"```asm\n(.*?)```", RegexOptions.Singleline); + Require(blocks.Count == 1 && blocks[0].Groups[1].Value == ReadText(source), + $"Listing differs: {chapter}"); + await CompileAsync(compiler, source, Path.Combine(output, stem + ".exe")); + } + + Console.WriteLine("PASS: All three complete chapter listings match their standalone sources and compile."); + string sample = ReadText(Path.Combine(root, "samples/Windows/notepad/notepad-03-complete.zasm")); + + // Exercise the real file routines against a hidden multiline EDIT control. + // Replace only interactive filename selection and error popups with deterministic stubs. + int entry = Find(sample, "jmp start"); + sample = sample[..entry] + "jmp test_start" + sample[(entry + "jmp start".Length)..]; + int dialog = Find(sample, "choose_path:\n"); + int open = Find(sample, "open_document:\n", dialog); + sample = sample[..dialog] + "choose_path:\n mov eax, 1\n ret\n\n" + sample[open..]; + sample = sample[..Find(sample, "show_error:\n")] + "show_error:\n xor eax, eax\n ret\n"; + var assembly = new StringBuilder(sample).AppendLine("#IMPORT msvcrt.dll, strcmp"); + + var fixtures = new Dictionary + { + ["input"] = Encoding.ASCII.GetBytes("Loaded text\r\nSecond line"), + ["empty"] = [], + ["maximum"] = Enumerable.Repeat((byte)'A', 65535).ToArray(), + ["oversized"] = Enumerable.Repeat((byte)'B', 65536).ToArray(), + ["nul"] = Encoding.ASCII.GetBytes("one\0two"), + }; + var paths = new Dictionary(); + foreach (var (key, bytes) in fixtures) + { + paths[key] = Path.Combine(output, key + ".txt"); + File.WriteAllBytes(paths[key], bytes); + } + + paths["saved"] = Path.Combine(output, "saved.txt"); + paths["empty_saved"] = Path.Combine(output, "empty-saved.txt"); + paths["bad"] = Path.Combine(output, "directory-that-does-not-exist", "bad.txt"); + Require(!Directory.Exists(Path.GetDirectoryName(paths["bad"])), + "The failed-write fixture directory must not exist: " + Path.GetDirectoryName(paths["bad"])); + foreach (var (key, path) in paths) + { + // Numeric UTF-8 bytes also handle apostrophes in the workspace path safely. + string bytes = string.Join(", ", Encoding.UTF8.GetBytes(path.Replace('\\', '/')).Select(b => b.ToString())); + assembly.AppendLine($"test_path_{key} db {bytes}, 0"); + } + + assembly.AppendLine("test_initial db 'Initial text', 13, 10, 'Second line', 0"); + assembly.AppendLine("test_revised db 'Revised text', 13, 10, 'Second line', 0"); + assembly.AppendLine("test_loaded db 'Loaded text', 13, 10, 'Second line', 0"); + assembly.AppendLine("test_parent_class db 'STATIC', 0"); + assembly.AppendLine(Setup); + assembly.Append(Text("initial")).Append(Pending("saved")) + .AppendLine(" call save_as_document").Append(Check(1)); + assembly.Append(Text("revised")).AppendLine(""" + mov eax, 1 + lea edx, [esi + 4] + call store_dword + call save_document + """).Append(Check(1)); + assembly.AppendLine(""" + mov eax, [esi + 4] + test eax, eax + jnz test_fail + """); + assembly.Append(Pending("input")).AppendLine(" call open_document").Append(Check(1)); + assembly.AppendLine(""" + push 65536 + lea eax, [esi + 528] + push eax + mov eax, [esi] + push eax + call [GetWindowTextA] + push test_loaded + lea eax, [esi + 528] + push eax + call [strcmp] + add esp, 8 + """).Append(Check(0)); + + foreach (string key in new[] { "maximum", "oversized", "nul", "empty" }) + { + bool rejected = key is "oversized" or "nul"; + assembly.AppendLine(""" + xor eax, eax + lea edx, [esi + 4] + call store_dword + """).Append(Pending(key)).AppendLine(" call open_document").Append(Check(rejected ? 0 : 1)); + if (rejected) + { + // Rejected reads must retain the previously loaded 65535-byte document. + assembly.AppendLine(""" + mov eax, [esi] + push eax + call [GetWindowTextLengthA] + """).Append(Check(65535)); + } + } + + assembly.Append(Pending("empty_saved")).AppendLine(" call save_as_document").Append(Check(1)); + assembly.Append(Pending("bad")).AppendLine(""" + mov eax, 1 + lea edx, [esi + 4] + call store_dword + call write_pending + """).Append(Check(0)); + assembly.AppendLine(" mov eax, [esi + 4]").Append(Check(1)); + assembly.AppendLine(""" + push ebx + call [DestroyWindow] + push esi + call [GlobalFree] + push 0 + call [ExitProcess] + test_fail: + push 99 + call [ExitProcess] + """); + + // Give each assertion a distinct exit code and print its assembly context on failure. + var branches = new List(); + string harness = assembly.ToString().ReplaceLineEndings("\n"); + string diagnosticSource = harness; + harness = Regex.Replace(harness, @"(jz|jnz) test_fail\b", match => + { + int contextStart = Math.Max(0, match.Index - 180); + branches.Add(diagnosticSource[contextStart..(match.Index + match.Length)]); + return $"{match.Groups[1].Value} test_failure_{branches.Count}"; + }); + for (int i = 1; i <= branches.Count; i++) + harness += $"\ntest_failure_{i}:\n push {i}\n call [ExitProcess]\n"; + + string harnessSource = Path.Combine(output, "runtime-check.zasm"); + string harnessExecutable = Path.ChangeExtension(harnessSource, ".exe"); + File.WriteAllText(harnessSource, harness, new UTF8Encoding(false)); + await CompileAsync(compiler, harnessSource, harnessExecutable); + var run = await ExecuteAsync(harnessExecutable, [], TimeSpan.FromSeconds(20)); + string context = run.ExitCode > 0 && run.ExitCode <= branches.Count ? branches[run.ExitCode - 1] : ""; + Require(run.ExitCode == 0, $"Runtime check failed with exit code {run.ExitCode}:\n{context}\n{run.Output}"); + Require(File.ReadAllBytes(paths["saved"]).SequenceEqual(Encoding.ASCII.GetBytes("Revised text\r\nSecond line")), + "Saved text bytes differ from the expected document."); + Require(new FileInfo(paths["empty_saved"]).Length == 0, "The saved empty file is not empty."); + Console.WriteLine("PASS: Save As, Save current path, Open, exact text bytes, empty files, 65535-byte boundary, oversized/NUL rejection, failed-write dirty state, and stack balance."); + return 0; + } + catch (Exception ex) + { + Console.Error.WriteLine("FAIL: " + ex.Message); + return 1; + } + } + + private static string SourcePath([CallerFilePath] string path = "") => path; + + private static string ReadText(string path) => File.ReadAllText(path).ReplaceLineEndings("\n"); + + private static void Require(bool condition, string message) + { + if (!condition) + throw new InvalidOperationException(message); + } + + private static int Find(string text, string marker, int start = 0) + { + int index = text.IndexOf(marker, start, StringComparison.Ordinal); + Require(index >= 0, "Cannot build runtime harness: missing " + marker.Trim()); + return index; + } + + private static async Task CompileAsync(string compiler, string source, string output) + { + var result = await ExecuteAsync(compiler, [source, output], TimeSpan.FromSeconds(60)); + Require(result.ExitCode == 0, $"Compilation failed for {source}:\n{result.Output}"); + } + + private static async Task<(int ExitCode, string Output)> ExecuteAsync(string file, string[] arguments, TimeSpan timeout) + { + var start = new ProcessStartInfo(file) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true, + }; + foreach (string argument in arguments) + start.ArgumentList.Add(argument); + using var process = Process.Start(start) ?? throw new InvalidOperationException("Cannot start " + file); + Task stdout = process.StandardOutput.ReadToEndAsync(); + Task stderr = process.StandardError.ReadToEndAsync(); + using var cancellation = new CancellationTokenSource(timeout); + try + { + await process.WaitForExitAsync(cancellation.Token); + } + catch (OperationCanceledException) + { + if (!process.HasExited) + process.Kill(entireProcessTree: true); + await process.WaitForExitAsync(); + throw new TimeoutException($"{Path.GetFileName(file)} exceeded {timeout.TotalSeconds} seconds."); + } + + return (process.ExitCode, await stdout + await stderr); + } + + private static string Pending(string key) => $""" + push test_path_{key} + lea eax, [esi + 268] + push eax + call [strcpy] + add esp, 8 + """ + "\n"; + + private static string Text(string key) => $""" + push test_{key} + mov eax, [esi] + push eax + call [SetWindowTextA] + test eax, eax + jz test_fail + """ + "\n"; + + private static string Check(int result) => $""" + cmp eax, {result} + jnz test_fail + cmp esp, ebp + jnz test_fail + """ + "\n"; + + private const string Setup = """ + test_start: + lea ebp, [esp] + push 66080 + push 0x40 + call [GlobalAlloc] + test eax, eax + jz test_fail + push eax + pop esi + push 0 + push 0 + push 0 + push 0 + push 100 + push 100 + push 0 + push 0 + push 0x80000000 + push empty_text + push test_parent_class + push 0 + call [CreateWindowExA] + test eax, eax + jz test_fail + push eax + pop ebx + push 0 + push 0 + push 201 + push ebx + push 100 + push 100 + push 0 + push 0 + push 0x40B110C4 + push empty_text + push edit_class + push 0 + call [CreateWindowExA] + test eax, eax + jz test_fail + lea edx, [esi] + call store_dword + push 0 + push 65535 + push 0xC5 + mov eax, [esi] + push eax + call [SendMessageA] + """; +} diff --git a/samples/Windows/notepad/verify.py b/samples/Windows/notepad/verify.py deleted file mode 100644 index b9c76a5..0000000 --- a/samples/Windows/notepad/verify.py +++ /dev/null @@ -1,213 +0,0 @@ -# Copyright Xeno Innovations, Inc. 2026 -# See LICENSE in the repository root. -"""Windows-only integration check for the Section 4 Notepad source listings. - -Run from any directory: python samples/Windows/notepad/verify.py -Use --compiler to select a different native zero.exe. Interactive file dialogs -and prompts are stubbed; their behavior is covered by Chapter 4.5's manual checks. -""" -from pathlib import Path -import argparse -import subprocess -import sys - -if sys.platform != 'win32': - raise SystemExit('This runtime check requires Windows.') -parser = argparse.ArgumentParser(description=__doc__) -parser.add_argument('--compiler', type=Path) -args = parser.parse_args() - -root=Path(__file__).resolve().parents[3] -compiler=(args.compiler or root/'publish/zero.exe').resolve() -if not compiler.is_file(): - raise SystemExit(f'Compiler not found: {compiler}. Build it or pass --compiler.') -out=root/'output/notepad-check' -out.mkdir(parents=True, exist_ok=True) -# Keep every printed listing identical to its runnable sample and compile each stage. -import re -stages = [ - ('notepad-01-window', 'zasm-04-02-notepad-create-the-window'), - ('notepad-02-editor', 'zasm-04-03-notepad-add-the-text-editor'), - ('notepad-03-complete', 'zasm-04-04-notepad-open-and-save-files'), -] -for stem, chapter in stages: - src = root/'samples/Windows/notepad'/f'{stem}.zasm' - listing = (root/'docs/zasm'/f'{chapter}.md').read_text(encoding='utf-8') - blocks = re.findall(r'```asm\n(.*?)```', listing, re.S) - assert blocks == [src.read_text(encoding='utf-8')], f'Listing differs: {chapter}' - result = subprocess.run([str(compiler), str(src), str(out/f'{stem}.exe')], - capture_output=True, text=True) - assert result.returncode == 0, result.stdout + result.stderr -print('PASS: All three complete chapter listings match their standalone sources and compile.') -sample=(root/'samples/Windows/win-ui-10-notepad.zasm').read_text(encoding='utf-8') -assert sample == (root/'samples/Windows/notepad/notepad-03-complete.zasm').read_text(encoding='utf-8'), 'Finished sample differs from the final tutorial stage.' -# Exercise the exact I/O routines against a hidden EDIT control. Replace only -# interactive filename selection and error popups with deterministic test stubs. -assert 'jmp start' in sample -sample=sample.replace('jmp start','jmp test_start',1) -start=sample.index('choose_path:\n') -end=sample.index('open_document:\n',start) -sample=sample[:start]+'choose_path:\n mov eax, 1\n ret\n\n'+sample[end:] -sample=sample[:sample.index('show_error:\n')]+'show_error:\n xor eax, eax\n ret\n' -sample+='#IMPORT msvcrt.dll, strcmp\n' -paths={} -fixtures={'input':b'Loaded text\r\nSecond line', 'empty':b'', - 'maximum':b'A'*65535, 'oversized':b'B'*65536, 'nul':b'one\x00two'} -for key,data in fixtures.items(): - path=out/f'{key}.txt' - path.write_bytes(data) - paths[key]=path -paths['saved']=out/'saved.txt' -paths['empty_saved']=out/'empty-saved.txt' -paths['bad']=out/'directory-that-does-not-exist'/'bad.txt' -for key,path in paths.items(): - sample+=f"test_path_{key} db '{path.as_posix()}', 0\n" -sample+="test_initial db 'Initial text', 13, 10, 'Second line', 0\n" -sample+="test_revised db 'Revised text', 13, 10, 'Second line', 0\n" -sample+="test_loaded db 'Loaded text', 13, 10, 'Second line', 0\n" -sample+="test_parent_class db 'STATIC', 0\n" -sample+=''' -test_start: - lea ebp, [esp] - push 66080 - push 0x40 - call [GlobalAlloc] - test eax, eax - jz test_fail - push eax - pop esi - push 0 - push 0 - push 0 - push 0 - push 100 - push 100 - push 0 - push 0 - push 0x80000000 - push empty_text - push test_parent_class - push 0 - call [CreateWindowExA] - test eax, eax - jz test_fail - push eax - pop ebx - push 0 - push 0 - push 201 - push ebx - push 100 - push 100 - push 0 - push 0 - push 0x40B110C4 - push empty_text - push edit_class - push 0 - call [CreateWindowExA] - test eax, eax - jz test_fail - lea edx, [esi] - call store_dword - push 0 - push 65535 - push 0xC5 - mov eax, [esi] - push eax - call [SendMessageA] -''' - -def pending(key): - return f''' push test_path_{key} - lea eax, [esi + 268] - push eax - call [strcpy] - add esp, 8 -''' - -def text(key): - return f''' push test_{key} - mov eax, [esi] - push eax - call [SetWindowTextA] - test eax, eax - jz test_fail -''' - -def check(result): - return f''' cmp eax, {result} - jnz test_fail - cmp esp, ebp - jnz test_fail -''' - -def clean(): - return ''' xor eax, eax - lea edx, [esi + 4] - call store_dword -''' - -sample+=text('initial')+pending('saved')+' call save_as_document\n'+check(1) -sample+=text('revised')+''' mov eax, 1 - lea edx, [esi + 4] - call store_dword - call save_document -'''+check(1) -sample+=''' mov eax, [esi + 4] - test eax, eax - jnz test_fail -''' -sample+=pending('input')+' call open_document\n'+check(1) -sample+=''' push 65536 - lea eax, [esi + 528] - push eax - mov eax, [esi] - push eax - call [GetWindowTextA] - push test_loaded - lea eax, [esi + 528] - push eax - call [strcmp] - add esp, 8 -'''+check(0) -for key in ['maximum','oversized','nul','empty']: - sample+=clean()+pending(key)+' call open_document\n'+check(0 if key in ['oversized','nul'] else 1) - if key in ['oversized','nul']: - # Rejected reads must leave the previously loaded 65535-byte editor intact. - sample+=' mov eax, [esi]\n push eax\n call [GetWindowTextLengthA]\n'+check(65535) -sample+=pending('empty_saved')+' call save_as_document\n'+check(1) -sample+=pending('bad')+''' mov eax, 1 - lea edx, [esi + 4] - call store_dword - call write_pending -'''+check(0) -sample+=''' mov eax, [esi + 4] -'''+check(1) -sample+=''' push ebx - call [DestroyWindow] - push esi - call [GlobalFree] - push 0 - call [ExitProcess] -test_fail: - push 99 - call [ExitProcess] -''' -branches=[] -def label_failure(match): - branches.append(sample[max(0,match.start()-180):match.end()]) - return match.group(1)+f' test_failure_{len(branches)}' -sample=re.sub(r'(jz|jnz) test_fail\b',label_failure,sample) -for i in range(1,len(branches)+1): - sample+=f'\ntest_failure_{i}:\n push {i}\n call [ExitProcess]\n' -src=out/'runtime-check.zasm' -src.write_text(sample,encoding='utf-8') -exe=src.with_suffix('.exe') -compile=subprocess.run([str(compiler),str(src),str(exe)],capture_output=True,text=True) -assert compile.returncode==0,compile.stdout+compile.stderr -run=subprocess.run([str(exe)],timeout=20) -assert run.returncode==0,f'Runtime check failed with exit code {run.returncode}:\n'+(branches[run.returncode-1] if 0 [output.exe]` builds the source, then runs the executable in the