A Delphi service that wraps image extraction in try..except can look perfectly healthy in its log: an EAccessViolation gets caught, the upload is marked as bad, and the next job starts. Minutes later an unrelated request can die with EInvalidPointer whilst freeing a string list. The two events are connected. A JPEG 2000 or JBIG2 decoder that wrote past the end of a buffer before it faulted has already damaged the heap, and catching the exception restores control flow whilst leaving that damage exactly where it was. Memory you cannot trust can only be thrown away, and the unit of memory Windows lets you throw away cleanly is a process
Why a try..except around the decoder is not enough
An image codec is the part of a PDF reader that runs the most complicated state machine over the least checked data. By the time bytes reach a JPEG 2000 or JBIG2 decoder, the cross-reference table has been parsed, the image object resolved and the filter chain unwound. What remains is a raw codestream that announces how many tiles, how many components and how many bits per sample it contains. A wrong number there is not a syntax error the parser can reject. It becomes an allocation size, a loop bound or an array index inside a tight decode loop
Byte budgets cover part of this, and an intake path should have them anyway. HotPDF bounds expansion with DecodeBudgetBytes and DocumentDecodeBudgetBytes, and bounds filter chains with DecodeFilterLimit and DecodePipelineDepthLimit; the reasoning behind those caps is in bounded decoding for nested filters and PDF bombs. A budget answers one question: how much output is allowed. It has nothing to say about a decoder that faults after writing a handful of bytes into the wrong place
The fault that does get caught is in some ways the worse outcome. An unhandled crash at least stops the process. A caught one lets it keep serving requests on top of a corrupted heap, and the eventual failure carries a stack trace that points nowhere near the PDF that caused it
Moving DCTDecode, JPXDecode and JBIG2Decode into a worker process
HotPDF can run the three high-risk image filters, DCTDecode, JPXDecode and JBIG2Decode, in a short-lived worker process, HotPDFCodecWorker.exe, instead of inside your application. The HPDFCodecIsolation unit names them hckDCT, hckJPX and hckJBIG2. Flate, LZW, RunLength, ASCII85 and CCITT stay in-process: those decoders have simple state, and the decode budgets are the right tool for them
Each request gets a fresh process. The host creates one randomly named shared-memory mapping, writes a fixed THPDFCodecSharedHeader followed by the compressed codestream and, for JBIG2, the global segments, then starts the worker suspended, places it in a Windows Job Object and only then lets it run. The job allows exactly one active process, so a compromised decoder cannot spawn a child, and it is created with kill-on-close, so the worker cannot outlive the job handle. Decoded pixels come back as 24-bit BGR in the same mapping, together with a status word
Turning it on takes four properties on THotPDF. The image calls stay the same ones you already use:
uses
Vcl.Graphics, HPDFDoc, HPDFCodecIsolation;
procedure ExtractUntrustedImages(const FileName: string);
var
Pdf: THotPDF;
Info: THPDFCodecWorkerInfo;
Bmp: TBitmap;
I: Integer;
begin
Pdf := THotPDF.Create(nil);
try
Pdf.CodecIsolationMode := cimRequired; // never decode these in-process
Pdf.CodecWorkerExecutable := ''; // '' = next to the host EXE
Pdf.CodecWorkerTimeoutMilliseconds := 5000; // 1..600000, else ERangeError
Pdf.CodecWorkerMemoryLimitBytes := 256 * 1024 * 1024; // 0 or >= 64 MiB
Pdf.DecodeBudgetBytes := 128 * 1024 * 1024;
if Pdf.LoadFromFile(FileName) > 0 then // returns the page count
for I := 0 to Pdf.GetLoadedImageCount - 1 do
begin
Bmp := Pdf.ExtractLoadedImage(I);
try
// Read the verdict right away: it describes the latest request only
if Pdf.GetLastCodecWorkerInfo(Info) then
LogCodecOutcome(FileName, I, Info);
if Bmp <> nil then
StoreImage(FileName, I, Bmp); // your own code
finally
Bmp.Free;
end;
end;
finally
Pdf.Free;
end;
end;
When an isolated decode fails, ExtractLoadedImage returns nil, so the Bmp <> nil check carries real weight here. GetLastCodecWorkerInfo returns False when no worker request was recorded, which is what you see for a Flate-compressed image or with cimDisabled
Two deployment details cause most of the trouble. An empty CodecWorkerExecutable resolves to HotPDFCodecWorker.exe in the directory of ParamStr(0). A non-empty value goes through ExpandFileName, which means a relative path resolves against the current directory. For a Windows service that directory is usually System32, so 'bin\HotPDFCodecWorker.exe' works from the IDE and fails after installation. The other detail is bitness: the worker build script produces separate Win32 and Win64 binaries, and the one you ship must match the architecture of the host process
Automatic or required: what happens when the worker is missing?
The three values of THPDFCodecIsolationMode answer a single question, which is what to do when the worker cannot be used at all. cimDisabled never tries it and decodes everything in-process. cimAutomatic, the default, uses the worker when HotPDFCodecWorker.exe exists and falls back to in-process decoding when the file is not there, recording cwsUnavailable. cimRequired refuses the fallback; a missing worker means the image is not decoded
The fallback is narrower than it first looks, and the narrowness is deliberate. Only a missing executable falls back. If the file exists but CreateProcess fails, typically because an endpoint security product blocks it, the result is cwsLaunchFailed and the image is not decoded, even under cimAutomatic. A worker that started and then crashed, timed out or exceeded a limit is never retried in-process in either mode. Retrying a file that just killed the worker inside your own process would hand the attacker a second attempt at precisely the target the worker was there to protect
For anything that reads uploads, mail attachments or partner drops, set cimRequired. The default mode has a trap that only shows up after deployment: an installer that forgets the worker produces a server that extracts every image correctly, passes every functional test, and runs the codecs inside the host on every single request. Nothing looks broken. cimAutomatic is reasonable for a desktop viewer opening files the user already has, where a missing worker should degrade rather than stop the product. cimRequired also switches off ProgressiveJPEGScanDecoding, the scan-by-scan progressive JPEG path, because that path decodes in the host
A startup check turns a forgotten worker into an immediate, loud failure. HPDFResolveCodecWorkerExecutable is public in HPDFCodecIsolation and applies the same resolution rule as the component:
// A startup check you add yourself: refuse to start without the worker
procedure RequireCodecWorker(Pdf: THotPDF);
var
WorkerPath: string;
begin
WorkerPath := HPDFResolveCodecWorkerExecutable(Pdf.CodecWorkerExecutable);
if not FileExists(WorkerPath) then
raise Exception.CreateFmt(
'Codec worker missing at %s; refusing to accept PDF uploads',
[WorkerPath]);
end;
Reading THPDFCodecWorkerStatus
THPDFCodecWorkerInfo carries Status, ProcessId, ExitCode, ElapsedMilliseconds and a host-side ErrorMessage. The status values are cwsNotRun, cwsSucceeded, cwsUnavailable, cwsLaunchFailed, cwsTimedOut, cwsCrashed, cwsDecodeFailed, cwsProtocolError and cwsOutputLimit, and they sort into three operational groups
- Deployment:
cwsUnavailableandcwsLaunchFailed. The worker is missing, blocked, or could not be started inside its job. Page whoever owns the server; the document itself may be fine - Document:
cwsDecodeFailedandcwsOutputLimit. The codestream is malformed or bigger than your policy allows. Rejecting the file is the correct answer - Containment:
cwsTimedOut,cwsCrashedandcwsProtocolError. A hang, a dead worker, or a reply whose header does not match the protocol version or whose claimed geometry does not add up. These are the events the process boundary exists for, and the file deserves quarantine instead of a plain rejection
The line between cwsDecodeFailed and cwsCrashed is worth knowing when you read the numbers. Delphi turns most access violations into exceptions, and the worker catches exceptions around the decoder and reports them as a failed decode. cwsCrashed means the worker process ended with a nonzero exit code, which happens when the fault was severe enough that no exception handler got to run. ExitCode is a Cardinal, so format it with %u or as hex; $C0000005 printed with %d turns into a negative number that nobody searches for correctly
procedure LogCodecOutcome(const FileName: string; ImageIndex: Integer;
const Info: THPDFCodecWorkerInfo);
begin
case Info.Status of
cwsSucceeded:
;
cwsUnavailable, cwsLaunchFailed:
AlertOps('Codec worker not usable: ' + Info.ErrorMessage); // your own code
cwsTimedOut, cwsCrashed, cwsProtocolError:
Quarantine(FileName, Format('image %d: pid %u exit $%.8x after %u ms: %s',
[ImageIndex, Info.ProcessId, Info.ExitCode,
Info.ElapsedMilliseconds, Info.ErrorMessage])); // your own code
else
RejectDocument(FileName, Info.ErrorMessage); // your own code
end;
end;
The worker also suppresses the Windows fault dialog for itself, so a crash on an unattended server shows up in this log instead of as a modal box waiting for someone to click OK on a machine nobody is looking at
The three ceilings on every isolated decode
Each isolated decode runs under a time limit, a memory limit and an output limit, and the status tells you which one ended it. CodecWorkerTimeoutMilliseconds defaults to 10,000 and accepts 1 to 600,000; anything outside that range raises ERangeError at assignment instead of being clamped. On timeout the host terminates the whole job and reports cwsTimedOut. CodecWorkerMemoryLimitBytes defaults to 536,870,912 bytes and must be zero, meaning no cap, or at least 67,108,864 bytes; it becomes a per-process committed-memory limit on the Job Object
The output limit is derived. HotPDF computes the bytes the decoded image should need from the requested target size, the requested region, or the image geometry declared in the PDF, at three bytes per pixel, and then caps that figure at DecodeBudgetBytes when a budget is set. The shared mapping is sized from that figure, so the worker has no space to write beyond it. Suppose a scan declares 10,000 by 10,000 pixels: that is 300,000,000 bytes of BGR output, more than the default 268,435,456-byte DecodeBudgetBytes, so the limit becomes 256 MiB and the decode ends with cwsOutputLimit
The host does not trust the size the worker reports back, either. A reply is accepted only if its width times height times three equals the byte count it claims, and that count fits both the host's own output limit and the mapping. A worker that has been subverted can write any value into the header; a mismatch gets reported as cwsProtocolError and no pixels are copied
Keep the memory limit comfortably above the output limit. With the settings in the first example, a 128 MiB output budget inside a 256 MiB process cap leaves room for the compressed input and the decoder's own working set. Set the two close together and large legitimate scans start failing inside the worker for reasons that have nothing to do with hostile input
What the process boundary costs
Starting a process per isolated image costs time, and a document with several hundred scanned JPEG pages will feel it. On an unattended batch converter that cost disappears into the overnight window and the containment is the reason the job exists. An interactive viewer showing files the user already trusts is a different case; there cimAutomatic, or cimDisabled for a known internal archive, is a fair choice. CodecIsolationMode is an ordinary property, so one service can apply cimRequired to uploads and a lighter mode to documents it generated itself
The codec in question also changes the risk picture. JPXDecode streams carry tile and component counts that drive allocations directly, whilst JBIG2 images often depend on a /JBIG2Globals stream shared by several pages. A sandbox that shipped only the per-image stream would decode those pages wrongly or not at all, which is why the global segments travel into the worker together with each image
Codec isolation, decode budgets and the parser's structural limits all live in one native VCL component, and the only extra file to deploy is the worker executable. Setup notes, the worker build for Win32 and Win64, and a trial download are on the HotPDF component page for Delphi and C++Builder