Technical Article

HotPDF on Free Pascal: Deflate, AES and Codec Backends

A Free Pascal Win64 program wraps a decompression call in try..except, the callee raises ENotSupportedException, and the process ends with exit code 217 before the handler runs a single line. Runtime error 217 is how the Free Pascal RTL reports an unhandled exception, and it shows up here because the raise sits inside a function declared cdecl and exported under a C symbol name. The exception never makes it back to the caller. The repair is to refuse the call on the Pascal side, before anything C-shaped is entered

That same pattern explains why a port can look finished long before it is. Every unit of a large Delphi library can compile under Free Pascal while some call paths still end at a C entry point with nothing usable behind it, and the compiler output gives no hint which paths those are. The only evidence that counts is a runtime probe that drives a feature end to end on the toolchain you ship with

Which backends HotPDF uses under Free Pascal

HotPDF builds with Free Pascal 3.3.1 or later for i386-win32 and x86_64-win64 through the runtime package HotPDFLaz.lpk. The Delphi and C++Builder builds link prebuilt zlib-ng and AES object files, and those objects use a COFF ABI that neither Free Pascal linker accepts, so the Free Pascal build swaps in Pascal code behind the same entry points. Flate goes through HPDFFPCZLib, which exports the C symbols the rest of the library imports (deflate, inflate, crc32 and the others) on top of the paszlib package that ships with Free Pascal. AES goes through HPDFAES, whose Free Pascal branch implements the same routines over the FIPS-197 primitives in HPDFCrypt; the CBC routines update the caller's IV buffer in place exactly the way the native ones do

Document creation, loading, saving, Flate compression and decompression, and AES encryption and decryption therefore need no C code at all. Image codecs are different. TIFF, JPEG, JPEG 2000, LittleCMS color conversion, JBIG2 encoding and decoding, and Zopfli come from HotPDFFPCCodecs.dll, which you build from the bundled sources with Lib/thirdparty/FPC/Build-Codecs.ps1 in a Win32 and a Win64 flavor, each with a static C runtime

HotPDF Free Pascal capability map: Pascal deflate, AES and document backends beside native image codecs that load from a checked codec DLL and fail closed without it
Document, compression and encryption features run on Pascal-only backends, while native image codecs come from a matching codec DLL and fail closed when it is absent or does not match

The loader looks for that DLL in exactly one place: the directory of the executable. It checks the DLL's ABI version and pointer width first, then resolves the export set codec by codec, so a DLL that lacks the JPEG 2000 exports still enables TIFF and JPEG. Native JBIG2 encoding additionally requires the exact-batch capability, which keeps a lossless request from reaching an older approximate batch encoder; without it the Pascal JBIG2 fallback stays in charge. Searching only beside the executable is stricter than the normal Windows search order, and it is the right default here, because a stale copy left on PATH by another install cannot stand in for the DLL you actually shipped

Capability is fixed when the unit initializes, which makes it cheap to log. A Lazarus application can record what it got at startup with the public queries in HPDFFPCCodecStubs and the Flate self test in HPDFFPCZLib

uses
  Classes, SysUtils, HPDFFPCCodecStubs {$IFDEF FPC}, HPDFFPCZLib{$ENDIF};

procedure LogPDFBackends(Log: TStrings);
const
  Names: array [THPDFFPCNativeCodec] of string = ('TIFF', 'JPEG',
    'JPEG 2000', 'LittleCMS', 'JBIG2 encode', 'JBIG2 decode', 'Zopfli');
var
  Codec: THPDFFPCNativeCodec;
  Detail: string;
begin
{$IFDEF FPC}
  if HPDFFPCZLibSelfTest(Detail) then
    Log.Add('Flate: self test passed')
  else
    Log.Add('Flate: ' + Detail);

  for Codec := Low(THPDFFPCNativeCodec) to High(THPDFFPCNativeCodec) do
    if HPDFHasFPCNativeCodec(Codec) then
      Log.Add(Names[Codec] + ': ' + HPDFGetFPCNativeCodecLibrary)
    else
      Log.Add(Names[Codec] + ': off (' + HPDFGetFPCNativeCodecError + ')');
{$ENDIF}
end;

On a machine where the DLL was never deployed, every codec line ends with HotPDFFPCCodecs.dll was not found beside the executable. When the file is there but Windows refuses to load it, the line carries the system error for that load instead, and a DLL that loads but reports another ABI version or pointer width is turned away with a message naming the mismatch

Why does a raise inside a cdecl stub end the process?

Because on Free Pascal for Win64 the exception does not travel back through a frame that was written to look like C. Any Delphi codebase that replaces static C libraries with Pascal stand-ins will be tempted to write one like this

// Looks reasonable. On FPC Win64 it ends the process with exit code 217
function inflate(Strm: Pointer; Flush: Integer): PtrUInt; cdecl;
  public name 'inflate';
begin
  raise ENotSupportedException.Create('codec unavailable');
end;

The caller's try..except never sees it. From the application side there is no error dialog, no message and no log line, just a program that vanishes — and a vanished process is harder to deal with than a wrong result, because a wrong result can at least be checked

Why an exception raised inside a cdecl stub ends a Free Pascal process with exit code 217 and how gating the Pascal entry point fixes it
On Free Pascal Win64 an exception raised inside the cdecl stub never reaches the caller's handler and the process exits with code 217; the fix gates before the stub is ever reached

The obvious alternative is to make the stub return a failure code. For inflate that works, since zlib defines error returns and callers already test for them. It does not generalize: a stand-in for jpeg_read_header that returns zero tells the caller to keep going with a decoder structure nobody initialized. The dependable place to stop is the Pascal entry point that sits in front of the C-shaped call, using whatever failure convention that entry point already has

// MyDecodeScan is your own routine; the gate is the part that matters
function TryDecodeScan(const Data: TBytes; out Error: string): Boolean;
begin
{$IFDEF FPC}
  if not HPDFHasFPCNativeCodec(hncJPEG) then
  begin
    Error := HPDFGetFPCNativeCodecError;
    Exit(False);   // this API's own failure result, no exception
  end;
{$ENDIF}
  Result := MyDecodeScan(Data, Error);
end;

HotPDF's own codec entry points follow the same rule, each in its own idiom. The JPEG scan decoder returns False and carries the loader's reason in its error message, the ICC transform factory returns nil, the JBIG2 decoder returns False with zero width and height, and the Zopfli path returns False with error code 5. A missing codec looks like an ordinary decode failure to the caller, with a reason string attached

paszlib is not zlib: windowBits 31 and 47

The Pascal deflate implementation that ships with Free Pascal understands two framings, the zlib wrapper and raw deflate. It has no gzip framing, which zlib selects with windowBits values from 16 to 31, and no automatic header detection, which values 32 to 47 select. HotPDF uses both: the safe SVG import path asks for 31, and the loader's fallback ladder for streams with doubtful framing asks for 47. Leave either one out and an entire family of documents stops opening, with a decode error that points at the stream instead of at the missing framing

windowBits coverage of paszlib versus zlib: gzip framing and auto-detect ranges missing for HotPDF SVG import and loader fallback
paszlib handles the zlib wrapper and raw deflate, but HotPDF also needs windowBits 31 and 47, so the shim must supply gzip framing itself

So HPDFFPCZLib implements the gzip header and trailer, including the CRC and the eight-byte length trailer, in front of paszlib's raw codec. Callers keep passing the same windowBits they pass on Delphi, and nothing above the shim has a Free Pascal branch for it

The second mismatch is in the record itself. paszlib declares msg as a string[255] and total_in / total_out as qword, while the zlib record HotPDF's callers fill in has a PAnsiChar message and 32-bit counters. Passing the caller's record straight through would scribble over the wrong offsets. The shim keeps its paszlib state behind the opaque state pointer that the public record already reserves and copies the public fields in and out around every call. A few zlib options have no paszlib counterpart: Z_RLE and Z_FIXED fall back to the default strategy, since they only tune the ratio, and Z_BLOCK becomes a sync flush, the nearest byte-aligned equivalent

Symbol names need one more adjustment on Win32. Free Pascal adds a leading underscore to a cdecl; external import there, but exports a public name exactly as written, so an import already spelled _deflate gets looked up as __deflate. The shim carries a separate prefix for each target; the full story is in the Win32 C symbol ABI article. HPDFFPCZLibSelfTest round-trips a buffer through zlib framing (15), raw deflate (−15) and gzip (31), decodes gzip and zlib output with detection (47), and then checks that a reset stream detects its wrapper again

A dynamic array passed to an untyped var parameter

This is the bug most likely to be sitting in a codebase right now. Pass a dynamic array to an untyped var parameter and the callee receives the address of the array variable — the address of a pointer — instead of the address of the payload, so a read into it overwrites the variable and whatever sits next to it

var
  FBuffer: TBytes;
begin
  SetLength(FBuffer, 65536);

  // Wrong: hands over the address of the FBuffer variable
  FStream.Read(FBuffer, Length(FBuffer));

  // Right: hands over the address of the first payload byte
  FStream.Read(FBuffer[0], Length(FBuffer));
end;

Under Delphi the wrong form often appears to work, because what it corrupts is an adjacent stack slot that nothing reads afterward. Under Free Pascal the same line segfaults on first use. Reading the code does not reveal it either: a static array variable is its own payload, so Read(Buf, SizeOf(Buf)) is correct for a static array, and both spellings can appear in one file, correct or not depending on a declaration a few hundred lines away. A search for Read( and Write( calls whose first argument is a bare TBytes field finds them faster than a debugger

Reading ZIP containers without System.Zip

Free Pascal has no counterpart to System.Zip. Its zipper unit has a different API and does not implement traditional PKWARE encryption, so the Free Pascal build opens XPS, EPUB and CBZ containers through HPDFFPCZip, a small read-only reader that mirrors the part of the System.Zip surface the document handlers use. It reads stored and deflated entries, ZIP64 sizes and offsets, and traditionally encrypted entries whose keystream the caller supplies through IZipCryptor. Writing is out of scope; Open accepts only zmRead

Two details of the format are easy to get wrong. The last byte of the 12-byte encryption header is a password check value, normally the high byte of the CRC; when general-purpose flag bit 3 is set, the sizes and CRC live in a trailing data descriptor and are not known yet, so the check value is the high byte of the modification time instead. A reader that only implements the CRC form rejects the correct password on every archive written in streaming mode. The ZIP64 extra field is the other trap. Its 64-bit values appear in a fixed order (uncompressed size, compressed size, local header offset), but each one is present only when the matching 32-bit field holds $FFFFFFFF, so fixed offsets read the right value on one archive and garbage on the next

Inflating an entry does not touch the zlib shim. Free Pascal's TDecompressionStream.Create(Source, True) takes a second argument that skips the zlib header, which is exactly what ZIP's raw deflate entries need

LCL pixel access, build noise and render threads

Reading the alpha channel of a rasterized color glyph has no direct LCL translation. TPortableNetworkGraphic has no AlphaScanline, and Bitmap.Assign(Png) drops alpha, so a color emoji arrives opaque and composites over a black box. The working route is a TLazIntfImage read through Colors[X, Y]. The TFPColor components are 16-bit and need shr 8 to become bytes, and rows come in natural top-down order, so the Height - 1 - Y inversion that VCL scanline code needs has to go. In a NoGUI build, Png.CreateIntfImage fails because it asks the widgetset for a bitmap handle; TLazIntfImage.Create(Png.RawImage, False) borrows the decoded pixels without one

A full rebuild sometimes stops with an undefined symbol ending in $crc and a hex value. That suffix is computed from the parameter types, and it stops matching when one build pass compiles a unit against two versions of an interface. Running the build again clears it; the signature is fine

Rendering runs in parallel under Free Pascal as well: page, ordered-page, tile and band rendering run on explicit worker threads with the same memory admission, bounded output queues, ordered caller-thread callbacks and cancellation as the Delphi pipeline described in the parallel render pipeline article. Keep the document alive and leave its page contents alone while a parallel render is running. For the wider Lazarus picture, the Free Pascal and Lazarus Win64 support notes cover installation and package builds

Which image formats a Lazarus deployment can decode comes down to whether the matching codec DLL ships next to the executable, so settle that before the first release build. The HotPDF Delphi PDF component page lists editions and the compilers each one supports