Skip to content

Win64 dynamic packages - #4

Open
civilian7 wants to merge 6 commits into
Moonbot-Tech:mainfrom
civilian7:feat/win64-packages
Open

civilian7 wants to merge 6 commits into
Moonbot-Tech:mainfrom
civilian7:feat/win64-packages

Conversation

@civilian7

Copy link
Copy Markdown

What this adds

Delphi-style run-time packages on Win64. A package source with requires and contains builds into a package library (.fpl, a PE DLL) plus a symbol file (.fcp). Programs and other packages link against it with -FP<name>. Classes, VMTs, RTTI, unit initialization and the memory manager are shared across modules.

This is the structure of large Delphi applications that split into a common BPL (base forms, data-access components) and business BPLs that inherit from it and share its object instances. Without packages that structure can't be reproduced, because a shared component instance has to cross the module boundary.

Linux x86-64 is not covered here; tf_supports_packages is set for Win64 only.

How

The package path already existed in the compiler (pkgutil, fpcp, the $indirect machinery the RTL-in-a-DLL route uses), but no target enabled it. Almost every missing piece was something the program path did and the package path did not:

  • loading the system unit and the intern types
  • finishing the module in the task scheduler
  • clearing used units
  • exporting implementation symbols reached from inlined code
  • resource strings of a Unicode RTL

Three commits:

  1. Build Win64 dynamic packages (compiler). Notable MoonCompiler-specific points:
    • Runtime prefix. A package does not take the product runtime prefix. The bundled MM and the monitor are process-wide: the host installs them once, and every package shares them through the System of the RTL package. The prefix units were also queued without a wait point and exported while still unloaded, which caused an AV in export_unit.
    • Address-of references. Taking the address of a routine of another unit is now recorded as an imported symbol. An implementation-only routine whose address is taken is marked for export. Neither table saw address loads, which broke linking in two places:
      • @TMarshal.UnfixString in a statically linked SysUtils
      • @SysMonitorGetObjectDataFunc in an automatically inlined SetMonitorManager
    • GetTypes catalog. A module's catalog lists only the units linked into it.
    • $indirect slots read as data. Inside the system unit, the float abs mask and _FPC_TlsKey are now read directly. Before, the code read the $indirect slot itself as data.
  2. Load and unload packages at run time (RTL).
    • SysUtils: LoadPackage/UnloadPackage/InitializePackage/FinalizePackage and module-unload hooks.
    • Classes: UnRegisterModuleClasses removes the classes, aliases and palette entries of a leaving image.
  3. Qualify dynamic packages and document them: qualification/dynamic-packages/run.ps1, doc/DYNAMIC_PACKAGES.md, and a KNOWN_ISSUES.md section.

Package kinds: {$DESIGNONLY}/{$RUNONLY} are stored in the .fcp and enforced (13030 for declaring both, 13031 for linking a design-only package into a program). The library exports PACKAGEFLAGS and a REGPROCS table.

ABI note — please review

tf_supports_packages is a target-wide switch, not a project option. Data that may live in another module is addressed through $indirect slots, so the RTL and all packages are built in that mode, and so is every Win64 program, including those that use no packages.

This needs your judgement. If you would rather keep the default profile unchanged, this could become a separate package-enabled profile instead.

Verification (Win64, this branch vs. main at 65c7061)

Check Result
qualification/dynamic-packages/run.ps1 all checks pass (5 stages, 13 hosts, 2 expected rejections)
Product smoke, Debug and Release MOONBOT_BUILD_OK
qualification/pinned-unit/run.ps1 PASS
RTL-test/run.py (all sources, all modes) 813/819, identical to main on the same machine
Devil light registry, codegen, asm-oracle, main: 0 findings

The two RTL-test failures are the same on main: core_semantic debug TStringStream data fails because the machine's ANSI code page is 949 and © is not in it, and win64_trailing_call_semantic fails its executable gate. Devil chimera did not run (MoonORMot static objects not prepared on this machine).

Pulse (indicative, not a qualification run)

pulse_full.py with --keep-machine-settings --skip-preflight (no power-setting control on this machine), programs hot-rtl, managed, rtl-collections and heartbeat, 6 pairs, 224 cases with a metric:

  • Geometric mean cost ratio candidate/baseline: 1.006; median ≈ 1.000
  • heartbeat (application-shaped): 0.983
  • digests identical in all cases

The largest single deltas (SameText family +20–40%, interface-copy-call) are layout effects, not code changes:

  • asm-sametext-*: asm_sametext_pair_content is the same prebuilt .obj in both binaries. It sits at offset 0 mod 64 in the baseline and 32 mod 64 in the candidate.
  • CaseInterfaceCopy: its loop, FPC_INTF_ASSIGN, TInterfacedObject._AddRef and _Release disassemble to identical instruction sequences in both builds, shifted by 0x20. Repeated measurements of this case varied widely (+68% with 4 valid pairs, +155% with 1).
  • Code size of heartbeat grows by 0.5%.

A proper qualification run on one of your measurement machines would settle this.

Known boundaries

These are listed in KNOWN_ISSUES.md:

  • Contained units are compiled before the package. Compiling one from source together with -FP ends in IE 2013053103.
  • GetTypes does not see types inside packages.
  • Unload safety is the program's responsibility, as in Delphi.
  • The external GNU DLL route is not supported.

🤖 Generated with Claude Code

civilian7 and others added 3 commits November 26, 2026 23:44
A package source now builds into a package library on Win64, and programs
and packages link against it the way Delphi uses BPLs: classes, VMTs, RTTI,
unit initialization and the memory manager are shared across modules.

The package path existed in the compiler but no target enabled it. Every
missing piece was something the program path already did and the package
path did not: loading the system unit and the intern types, finishing the
module in the task scheduler, clearing used units, exporting
implementation symbols reached from inlined code, and resource strings of a
Unicode RTL.

- i_win: set tf_supports_packages for Win64. This is a target-wide ABI
  switch: data that may live in another module is addressed through
  $indirect slots, so the RTL and all packages are built in that mode.
- Package files are .fpl (library) and .fcp (symbols).
- {$DESIGNONLY}/{$RUNONLY} are stored in the .fcp and enforced (13030,
  13031); the library exports PACKAGEFLAGS and a REGPROCS table.
- The internal linker drops an empty .reloc section and an empty import
  directory, both of which made the loader reject small packages.
- A package does not take the product runtime prefix. The memory manager
  and the monitor are process-wide and are installed by the host; the
  prefix units were also queued without a wait point and exported while
  still unloaded (access violation in export_unit).
- Taking the address of a routine of another unit is recorded as an
  imported symbol, and an implementation-only routine whose address is
  taken is marked for export. Address loads reached neither table, so a
  program linking SysUtils statically against an RTL package failed on
  TMarshal.UnfixString, and an automatically inlined SetMonitorManager on
  SysMonitorGetObjectDataFunc.
- The GetTypes catalog of a module lists only the units linked into it.
- x86: the float abs mask and _FPC_TlsKey inside the system unit are read
  directly; reading the $indirect slot as data returned wrong values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SysUtils gets LoadPackage, UnloadPackage, InitializePackage and
FinalizePackage, driven by the INITFINAL table a package exports, plus
module-unload hooks. Classes registers UnRegisterModuleClasses there, so
classes, aliases and component-palette entries a leaving image registered
are removed and GetClass stays safe after the image is unmapped, also when
the package did not unregister them itself or when a dependency is unmapped
with it.

RegisterClassAlias keeps a private copy of the alias: the caller's constant
lives in the package's data section and is gone after UnloadPackage. The
same component class is registered on a palette page once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
qualification/dynamic-packages/run.ps1 builds and runs five stages:
importing from a required package; inheritance, virtual dispatch and
is/as across two packages; unit initialization in a load-time package;
LoadPackage, GetClass and UnloadPackage with the unload hooks and a
shared dependency unmapped with its last user; package kinds, PACKAGEFLAGS, design-time registration, and the
two rejections (13030, 13031).

doc/DYNAMIC_PACKAGES.md describes files, build order, kinds, run-time
loading, the runtime prefix and the ABI; KNOWN_ISSUES.md lists the
boundaries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The field class table of a class with published fields names the VMT of
each field's class. It is data: no code reference records that VMT for the
package import pass. When a class is used only as the type of a published
field - the usual case for a form whose components are created from a form
file - a program linked against the package that holds the class failed
with VMT_$<unit>_$$_<class>$indirect undefined.

The VMT is now registered as an external asm symbol when the class belongs
to another module, so the import pass finds it in the package.

qualification/dynamic-packages stage2/host_fields: a class with a published
field of a package class and no other reference to it. Fails to link before
the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@civilian7

Copy link
Copy Markdown
Author

Added 1579b48 Import the VMT of a published field's class from its package. A class used only as the type of a published field (a form whose components are created from a form file) left VMT_$<unit>_$$_<class>$indirect undefined at link time. The field class table is data, so no code reference recorded the VMT for the package import pass. New case dynamic-packages stage2/host_fields: fails to link before the fix and passes after it. The whole dynamic-packages gate passes on the updated branch.

{$LIBSUFFIX} and {$LIBPREFIX} recompute the output file name through
setfilename(), which knows only the plain shared-library extension. In a
package the directives come after the package header, which had already
switched the extension to .fpl, so a versioned package (Delphi's
rtl290.bpl) came out as Base42.dll. A tool that tells installable
packages from plain DLLs by the extension no longer saw it.

After either directive, a package gets its extension back. Requiring
packages import from the versioned file name (Base42.fpl).

qualification/dynamic-packages stage5: a suffixed package and a prefixed
and suffixed package that requires it; the files are .fpl, no .dll, and a
host links the first and loads the second at run time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@civilian7

Copy link
Copy Markdown
Author

Added d8b140d: Keep the package extension under LIBSUFFIX and LIBPREFIX.

A versioned package, as Delphi's rtl290.bpl, came out as Base42.dll. {$LIBSUFFIX} and {$LIBPREFIX} come after the package header and recompute the file name with the plain shared-library extension, which undid the switch to .fpl. Now a package gets .fpl back after either directive. A package or host that requires it imports from Base42.fpl.

Found while building a design-time host on top of these packages: an IDE loads several package versions side by side, so versioned names are needed.

  • qualification/dynamic-packages stage5: a suffixed package, plus a prefixed and suffixed package that requires it. The check confirms both files are .fpl with no .dll. A host links the first package and loads the second with LoadPackage → GetClass → UnloadPackage.
  • All six stages pass.
  • doc/DYNAMIC_PACKAGES.md describes the versioned names.

Three faults of a package that requires an RTL package with Rtti and the
generic collections, all found building an application platform on it:

- Unit Rtti references FPC_RTTITYPETABLES, the catalog of discoverable
  types, which only a program got. A package linking Rtti did not link.
  The package path now emits the catalog of the units it contains.

- Inlined System helpers reach implementation symbols of System:
  InlinedInitialize, an implementation inline routine expanded into the
  compilerproc fpc_Initialize, put InitializeRecord and the
  RTTIFlattenInitialize table into every consumer. Only references from
  interface routines were marked df_has_global_ref / vo_has_global_ref, so
  the RTL package did not export them and a package using a generic list or
  a managed record imported symbols nobody exported. References from inline
  routines are marked now.

- A kernel32 routine that System also calls (GetCurrentProcessId) was
  imported from the RTL package: importlocalrefprocdefs imported every
  df_has_global_ref procdef of a required package's unit, DLL routines
  included, and findpackagewithsym accepted the import thunk name. The
  package does not export thunks, so the module did not load
  (STATUS_ENTRYPOINT_NOT_FOUND). DLL routines are imported from the DLL,
  and _$dll$ thunks are never looked up in packages.

qualification/dynamic-packages stage6: an RTL package with rtti and
generics.*, a package using TObjectList<T>, TList<record>, a managed
record, Rtti and GetCurrentProcessId, and a host printing the result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@civilian7

civilian7 commented Nov 27, 2026 •

Copy link
Copy Markdown
Author

Added aaae9fc Link Rtti and generics in packages, import DLL routines from the DLL. Building an application platform on an RTL package that contains rtti and generics.* turned up three faults:

  • A package linking unit Rtti failed with FPC_RTTITYPETABLES undefined, because the catalog was emitted for programs only.
  • References made by implementation inline routines (System's InlinedInitialize, expanded into fpc_Initialize) were not marked as global refs. As a result the RTL package did not export InitializeRecord / RTTIFlattenInitialize, which its consumers import.
  • A kernel32 routine that System also calls (GetCurrentProcessId) was imported from the RTL package instead of kernel32, and the module did not load (STATUS_ENTRYPOINT_NOT_FOUND).

The new qualification/dynamic-packages stage6 covers all three. The whole gate passes on a toolchain built from this branch.

🤖 Generated with Claude Code

@Moonbot-Tech

Copy link
Copy Markdown
Owner

Sharing Pascal classes between a Win64 host and its plugins is useful. We tested aaae9fc43 and reproduced four runtime problems. Could you add these as executable regression tests?

  1. Load the same package twice and unload it once. Its finalizer already runs, while the second caller still owns the package. Delphi 12.2 runs initialization once and finalization only on the second unload. Please assert both counts after each operation.
  2. Load only a plugin whose base package initializes a value to 17. The plugin sees 0. Loading the base explicitly first gives 17. Loading the plugin alone should initialize its dependency before any plugin initializer reads it.
  3. Two separately declared threadvars in a package had the same address. Please write different values to both and check that they survive independently, both on one thread and across two threads.
  4. A package-global WideString initialized to ready had length 0; the same declaration in an ordinary executable had length 5. Check the actual value during package initialization.

Please make stage 3 fail when the host reports NOT initialized; checking the process exit code currently lets that case pass. The proposed Win64 ABI also applies to programs that use no packages. An opt-in package profile would keep ordinary EXEs on their existing ABI. If the intent is to change the default, please include the compatibility and cost comparison for those EXEs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants