Senior-engineer / QA audit landed 13 silent-miscompile and data-
integrity fixes spanning the whole compiler+runtime+storage stack.
Each fix is paired with either an integration test in the suite or
a focused regression check; all 6 release gates stay green:
go test ./..., FiveSql2 43/43, Harbour compat 56/56, std.ch 17/17,
FRB 7/7, examples 65/71.
Compiler
--------
* genpc IF/ELSEIF jumpEnd2 patching (compiler/genpc/genpc.go).
Per-ELSEIF branch terminators were stashed into `_ = jumpEnd2`
and never patched — the relative offset stayed 0 and the runtime
walked the next ELSEIF's PcOpJumpFalse opcode as if it were
jump-offset data. Bytecode-level corruption in pcode mode. Now
collected into a slice and patched at end-of-IF. Verified via
Grade(95..50) cases 11a-e added to tests/frb/test_frb_pcode_sweep.
* countLocalsInStmts / scanBodyLocals missing bodies
(compiler/gengo/gen_util.go, compiler/gengo/gengo.go). Frame-size
counter skipped WATCH/TIMEOUT/PARALLEL FOR bodies, so a LOCAL
declared inside one of those constructs got a slot index past
the runtime's allocated count — silent NIL reads or out-of-range
stomps.
* emitMethodDeclStandalone nested LOCAL (compiler/gengo/gen_class.go).
Same bug class but on the *method* side. Pre-fix repro:
METHOD Stomp(n) CLASS T
LOCAL a := 1, b := 2
IF n > 0
LOCAL c := 30, d := 40, e := 50, f := 60
Inner( n )
IF c != 30 .OR. d != 40 .OR. e != 50 .OR. f != 60 ...
printed `c, d, e, f = 5, NIL, NIL, NIL` because Inner's frame
collided with Stomp's underallocated slot range. Now counts
body-nested LOCALs into the frame and pre-allocates indices via
scanBodyLocals.
* genpc unsupported-AST diagnostic surface (compiler/genpc/genpc.go,
hbrt/pcode.go, cmd/five/main.go, hbrtl/frb.go). The `default`
cases in emitStmt / emitExpr silently emitted PushNil / no-op
for nodes the pcode generator doesn't implement (ClassDecl,
MethodDecl, xBase commands, concurrency primitives, …). Added
`PcodeModule.Warnings []string` populated by noteUnsupported,
surfaced on stderr from the build pipeline. Users now see
"pcode: AST node not supported in --pcode/FRB-pcode mode: stmt
*ast.GoBlockStmt" instead of getting a silently broken module.
Runtime
-------
* class.go Send/tryBinaryOp t.self defer-restore (hbrt/class.go).
Restoration was a plain `t.self = oldSelf` after `fn(t)`. Any
panic in the method body skipped the line, so the next BEGIN
SEQUENCE / RECOVER handler ran with the THROWING object's Self
— `::field` resolved against the wrong receiver. Wrapped both
restore sites in `defer func() { t.self = oldSelf }()`.
Verified: pre-fix RECOVER saw "THROWER", post-fix "OUTER".
* hbfunc.go HB_FUNC parameter Frame() (hbrt/hbfunc.go). The
RegisterDynamicFunc wrapper called `fn(ctx)` without ever
calling Frame, so `ctx.ParC(1)` / `ctx.Local(n)` read through
`t.curFrame.localBase + n - 1` against the *caller's* frame.
Every #pragma BEGINDUMP HB_FUNC taking parameters silently
returned "" / 0 / "" for them — masked by ParNIDef-style
defaults. Wrapper now does `t.Frame(t.pendingParams, 0); defer
t.EndProc()` before dispatch.
* pcode codeblock closure capture (hbrt/pcinterp.go, hbrt/pcode.go,
hbrt/thread.go, compiler/genpc/genpc.go). PcOpPushBlock recorded
`nDetached` but never copied enclosing locals; free vars in the
block body fell through to memvar lookup → NIL. Wired full
capture pipeline:
- New opcodes PcOpPushDetached (0x59) / PcOpPopDetached (0x5A).
- PushBlock now reads per-slot source-local indices and
snapshots into bb.Detached at construction time.
- New detachedMap in genpc auto-promotes any free var that
resolves to an enclosing-frame local into a capture slot.
- emitAssignAsExpr leaves the assigned value on the eval stack
so SeqExpr items like `{|v| acc += v, acc }` work.
- Thread tracks curBlock with paired Set/restore in the block's
Fn wrapper for nested-block evaluation.
Mutating capture (acc += v across successive Evals) now works.
* vm.NewThread statics + waFactory propagation (hbrt/vm.go).
GoLaunch / GoLaunchBlock call NewThread directly. Previously
the statics map and WA factory were applied only in Run(), so
goroutine-spawned PRG code panicked on STATIC access ("static
index out of range") and crashed dereferencing nil WA on any
DB call. Both now happen inside NewThread under the same lock
as TID assignment.
Data layer
----------
* dbf concurrent Append lock (hbrdd/dbf/dbf.go,
hbrdd/dbf/locks_posix.go, hbrdd/dbf/locks_windows.go). Append
bumped a local recCount with no file-system serialization. Two
shared-mode processes both wrote at the same RecordOffset; one
record silently overwrote the other. Added an append-intent
byte-range lock at offset 0x7FFFFFFE + bounded retry, on-disk
header refresh inside the locked region, and immediate header
write so peers refresh past our slot.
* indexer negative numeric key encoding (hbrdd/dbf/indexer.go +
new hbrdd/dbf/encode_numeric_test.go). `%20.10f` formats `-100`
as `" -100.0000000000"` and `99` as `" 99.0000000000"`.
ASCII ' ' (0x20) < '-' (0x2D), so `99` lex-compared LESS than
`-100` — every NTX/CDX index over a column that ever held a
negative number returned wrong rows for SEEK / range scans.
Replaced with a 1-byte sign prefix + 21-byte zero-padded
magnitude (negatives use digit-complement) so byte order
matches numeric order across signs and magnitudes. Format
change: existing indexes built with the old encoding must be
REINDEXed. Three unit tests pin the order.
* dbf Append index maintenance hooks (hbrdd/dbf/dbf.go,
hbrdd/dbf/indexer.go). Append never inserted into open NTX/CDX
indexes — the audit's canonical scenario `SET INDEX TO …;
APPEND BLANK; REPLACE …; dbSeek …` silently missed the new
record. Added optional IndexWriter interface, queue the new
recNo in pendingIdxInserts, drain after flushRecord by calling
InsertKey on every open writer-supporting engine. NTX
participates (its existing rebuild-on-insert is correct);
CDX online maintenance is deferred to a follow-up — those
indexes still need REINDEX. Verified: post-fix SEEK("Charlie")
after APPEND BLANK + REPLACE finds the new record.
* dbf PACK crash-safety (hbrdd/dbf/dbf.go). The old in-place
rewrite read record N, overwrote slot M<N, then truncated.
Power loss after partial loop left a file with overwritten
prefix and no original copies of the records already advanced
past — silent data loss. Rewrote to:
1) drop mmap, build `<file>.pack.tmp` with all surviving
records,
2) Sync(),
3) close original handle + os.Rename(tmp, orig) (atomic on
same FS),
4) reopen + re-mmap.
TestComp_Pack passes; readers always see either the pre-PACK
or post-PACK contents, never a half-state.
* mem RDD torn reads (hbrdd/mem/memrdd.go). The comment claimed
in-place PutValue was safe because hbrt.Value "fits in a
single machine word + pointer". hbrt.Value is 24 bytes (3
words) — a concurrent reader could observe new type tag with
stale scalar/ptr and type-confuse on the next AsXxx() call.
Switched mu to sync.RWMutex; GetValue takes RLock,
Append/PutValue/Delete/Recall take Lock. `go test -race
./hbrdd/mem/` clean.
Files touched
-------------
compiler/gengo/gen_class.go, gen_util.go, gengo.go
compiler/genpc/genpc.go
hbrt/class.go, hbfunc.go, pcinterp.go, pcode.go, thread.go, vm.go
hbrdd/dbf/dbf.go, indexer.go, locks_posix.go, locks_windows.go
hbrdd/dbf/encode_numeric_test.go (new)
hbrdd/mem/memrdd.go
cmd/five/main.go
hbrtl/frb.go
tests/frb/test_frb_pcode_sweep.prg
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
286 lines
7.3 KiB
Go
286 lines
7.3 KiB
Go
// Copyright (c) 2026 Charles KWON OhJun (charleskwonohjun@gmail.com)
|
|
// All rights reserved.
|
|
|
|
// FRB (Five Runtime Binary) RTL functions.
|
|
//
|
|
// PRG Usage:
|
|
// pMod := FrbLoad("module.frb") // load module
|
|
// FrbDo(pMod, "MYFUNC", args...) // call function
|
|
// FrbUnload(pMod) // unload
|
|
//
|
|
// // Or one-shot:
|
|
// result := FrbRun("module.frb", arg1, arg2)
|
|
|
|
package hbrtl
|
|
|
|
import (
|
|
"five/compiler/genpc"
|
|
"five/compiler/parser"
|
|
"five/compiler/pp"
|
|
"five/hbrt"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
// frbCompileInProc compiles PRG source to a pcode FrbModule entirely
|
|
// in-process — no external `five` binary needed. Used by FrbCompile/
|
|
// FrbExec when the host can't shell out (running from a directory
|
|
// where `five` isn't on PATH and isn't next to the binary). Avoids
|
|
// the plugin-runtime-mismatch failure mode of native FRB plugins
|
|
// AND removes the "find the five exe" fragility entirely.
|
|
func frbCompileInProc(vm *hbrt.VM, prgSource string) (*hbrt.FrbModule, error) {
|
|
prep := pp.New()
|
|
processed, errs := prep.Process("dynamic.prg", prgSource)
|
|
if len(errs) > 0 {
|
|
return nil, fmt.Errorf("preprocess: %s", strings.Join(errs, "; "))
|
|
}
|
|
file, perrs := parser.Parse("dynamic.prg", processed)
|
|
if len(perrs) > 0 {
|
|
msgs := make([]string, 0, len(perrs))
|
|
for _, e := range perrs {
|
|
msgs = append(msgs, e.Error())
|
|
}
|
|
return nil, fmt.Errorf("parse: %s", strings.Join(msgs, "; "))
|
|
}
|
|
pcMod := genpc.Generate(file)
|
|
// Surface unsupported-AST-node warnings on stderr so dynamic
|
|
// FrbCompile callers see "pcode: AST node X not supported …"
|
|
// instead of getting a silently-broken module back.
|
|
for _, w := range pcMod.Warnings {
|
|
fmt.Fprintln(os.Stderr, w)
|
|
}
|
|
|
|
// Build a FrbModule from the pcode functions. Mirrors what
|
|
// hbrt/frb.go's frbLoadPcode does, but without the disk hop.
|
|
frbMod := &hbrt.FrbModule{
|
|
Name: "dynamic",
|
|
LocalSyms: make(map[string]*hbrt.Symbol),
|
|
OldSyms: make(map[string]*hbrt.Symbol),
|
|
BindMode: hbrt.FrbBindDefault,
|
|
VM: vm,
|
|
}
|
|
for name, fn := range pcMod.Funcs {
|
|
pcFn := fn
|
|
pcModRef := pcMod
|
|
goFunc := func(t *hbrt.Thread) {
|
|
hbrt.ExecPcode(t, pcFn, pcModRef)
|
|
}
|
|
frbMod.LocalSyms[name] = &hbrt.Symbol{
|
|
Name: name,
|
|
Scope: hbrt.FsPublic | hbrt.FsLocal,
|
|
Func: goFunc,
|
|
}
|
|
}
|
|
// Register non-Main symbols globally (Main stays module-local).
|
|
for name, sym := range frbMod.LocalSyms {
|
|
if name == "MAIN" {
|
|
continue
|
|
}
|
|
old := vm.FindSymbol(name)
|
|
if old != nil {
|
|
frbMod.OldSyms[name] = old
|
|
continue
|
|
}
|
|
vm.RegisterSymbol(sym)
|
|
frbMod.Registered = append(frbMod.Registered, name)
|
|
}
|
|
return frbMod, nil
|
|
}
|
|
|
|
// findFiveExe locates the 'five' compiler binary
|
|
func findFiveExe() string {
|
|
// 1. Check same directory as running executable
|
|
if exe, err := os.Executable(); err == nil {
|
|
dir := filepath.Dir(exe)
|
|
fiveExe := filepath.Join(dir, "five")
|
|
if _, err := os.Stat(fiveExe); err == nil {
|
|
return fiveExe
|
|
}
|
|
}
|
|
// 2. Check PATH
|
|
if p, err := exec.LookPath("five"); err == nil {
|
|
return p
|
|
}
|
|
// 3. Check current directory
|
|
if _, err := os.Stat("./five"); err == nil {
|
|
abs, _ := filepath.Abs("./five")
|
|
return abs
|
|
}
|
|
return "five" // hope it's in PATH
|
|
}
|
|
|
|
// FRBLOAD(cFileName) → pModule
|
|
func FrbLoadFunc(t *hbrt.Thread) {
|
|
t.Frame(1, 0)
|
|
defer t.EndProc()
|
|
|
|
filename := t.Local(1).AsString()
|
|
mod, err := hbrt.FrbLoad(t.VM(), filename)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "FrbLoad error: %v\n", err)
|
|
t.RetNil()
|
|
return
|
|
}
|
|
t.RetPointer(mod)
|
|
}
|
|
|
|
// FRBDO(pModule, cFuncName [, args...]) → xResult
|
|
func FrbDoFunc(t *hbrt.Thread) {
|
|
nParams := t.ParamCount()
|
|
t.Frame(nParams, 0)
|
|
defer t.EndProc()
|
|
|
|
modVal := t.Local(1)
|
|
funcName := strings.ToUpper(t.Local(2).AsString())
|
|
|
|
// Look up function: module-local scope first, then VM global
|
|
var fn func(*hbrt.Thread)
|
|
if modVal.IsPointer() {
|
|
if mod, ok := modVal.AsPointer().(*hbrt.FrbModule); ok {
|
|
fn = mod.FindFunc(funcName)
|
|
}
|
|
}
|
|
if fn == nil {
|
|
sym := t.VM().FindSymbol(funcName)
|
|
if sym != nil {
|
|
fn = sym.Func
|
|
}
|
|
}
|
|
if fn == nil {
|
|
t.RetNil()
|
|
return
|
|
}
|
|
|
|
// Snapshot SP *before* pushing args. After the inner call,
|
|
// Frame()/PcOpRetValue should have left SP back at this baseline,
|
|
// but pcode-mode bodies can occasionally leak intermediate stack
|
|
// values (e.g. FOR-loop control vestiges). Reseating SP to the
|
|
// snapshot before reading retVal stops those leaks from polluting
|
|
// the caller's argument frame — which is what made
|
|
// `? "label", FrbDo(...), "tail"` show "1" or "2" in place of the
|
|
// label string when the inner function had a loop.
|
|
savedSP := t.SP()
|
|
|
|
// Push args for the function
|
|
for i := 3; i <= nParams; i++ {
|
|
t.PushValue(t.Local(i))
|
|
}
|
|
t.PendingParams2(nParams - 2)
|
|
fn(t)
|
|
|
|
t.SetSP(savedSP)
|
|
t.PushValue(t.GetRetValue())
|
|
t.RetValue()
|
|
}
|
|
|
|
// FRBUNLOAD(pModule) → NIL
|
|
func FrbUnloadFunc(t *hbrt.Thread) {
|
|
t.Frame(1, 0)
|
|
defer t.EndProc()
|
|
|
|
v := t.Local(1)
|
|
if !v.IsNil() && v.IsPointer() {
|
|
if mod, ok := v.AsPointer().(*hbrt.FrbModule); ok {
|
|
hbrt.FrbUnload(mod)
|
|
}
|
|
}
|
|
t.RetNil()
|
|
}
|
|
|
|
// FRBCOMPILE(cPrgSource) → pModule
|
|
// Compile PRG source string to FRB module in memory. In-process pcode
|
|
// compilation is the default — no external `five` binary or `go`
|
|
// toolchain needed at runtime. The legacy native-plugin path is still
|
|
// reachable via hbrt.FrbCompileSource for callers that want it, but
|
|
// that path is fragile (Go plugins require byte-identical runtime).
|
|
func FrbCompileFunc(t *hbrt.Thread) {
|
|
t.Frame(1, 0)
|
|
defer t.EndProc()
|
|
|
|
source := t.Local(1).AsString()
|
|
mod, err := frbCompileInProc(t.VM(), source)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "FrbCompile error: %v\n", err)
|
|
t.RetNil()
|
|
return
|
|
}
|
|
t.RetPointer(mod)
|
|
}
|
|
|
|
// FRBEXEC(cPrgSource [, args...]) → xResult
|
|
// Compile PRG source, run Main(), unload — all in one call.
|
|
func FrbExecFunc(t *hbrt.Thread) {
|
|
nParams := t.ParamCount()
|
|
t.Frame(nParams, 0)
|
|
defer t.EndProc()
|
|
|
|
source := t.Local(1).AsString()
|
|
mod, err := frbCompileInProc(t.VM(), source)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "FrbExec error: %v\n", err)
|
|
t.RetNil()
|
|
return
|
|
}
|
|
defer hbrt.FrbUnload(mod)
|
|
|
|
// Look up MAIN inside the freshly-compiled module first, NOT
|
|
// via t.VM().FindSymbol — Main is intentionally kept module-local
|
|
// (frbLoadPcode skips it during VM registration), so a global
|
|
// lookup would resolve to the *caller's* Main and recurse forever.
|
|
fn := mod.FindFunc("MAIN")
|
|
if fn == nil {
|
|
t.RetNil()
|
|
return
|
|
}
|
|
|
|
savedSP := t.SP()
|
|
for i := 2; i <= nParams; i++ {
|
|
t.PushValue(t.Local(i))
|
|
}
|
|
t.PendingParams2(nParams - 1)
|
|
fn(t)
|
|
t.SetSP(savedSP)
|
|
|
|
t.PushValue(t.GetRetValue())
|
|
t.RetValue()
|
|
}
|
|
|
|
// FRBRUN(cFileName [, args...]) → xResult
|
|
// Load, execute startup function, unload — all in one call.
|
|
func FrbRunFunc(t *hbrt.Thread) {
|
|
nParams := t.ParamCount()
|
|
t.Frame(nParams, 0)
|
|
defer t.EndProc()
|
|
|
|
filename := t.Local(1).AsString()
|
|
mod, err := hbrt.FrbLoad(t.VM(), filename)
|
|
if err != nil {
|
|
t.RetNil()
|
|
return
|
|
}
|
|
defer hbrt.FrbUnload(mod)
|
|
|
|
// Same module-local Main lookup as FrbExec — see comment there
|
|
// for why a t.VM().FindSymbol("MAIN") would recurse into the
|
|
// outer (caller's) Main.
|
|
fn := mod.FindFunc("MAIN")
|
|
if fn == nil {
|
|
t.RetNil()
|
|
return
|
|
}
|
|
|
|
savedSP := t.SP()
|
|
for i := 2; i <= nParams; i++ {
|
|
t.PushValue(t.Local(i))
|
|
}
|
|
t.PendingParams2(nParams - 1)
|
|
fn(t)
|
|
t.SetSP(savedSP)
|
|
|
|
t.PushValue(t.GetRetValue())
|
|
t.RetValue()
|
|
}
|