How to patch a method in Classes.pas

Modifying the implementation side of Classes.pas will not require recompiling everything. Delphi figures out if a unit needs to be recompiled by an algorithm that looks roughly like this:

  • If DCU found:
    • Is DCU format out of date (old version of compiler)? If so, need source to recompile or compile-time error.
    • Is the source on the path? If so, if it's newer than the DCU, recompile
    • For each used unit:
      • Repeat analysis when loading
      • For each used symbol ("import": type, variable, routine, initialized constant etc.) from that unit:
        • Is symbol version of import different to symbol found in used unit? If so, recompile needed.
  • If DCU is not found, source will need to be found and compiled, otherwise compile-time error

The important concept is that of symbol version. When saving a DCU, Delphi calculates a hash based on the interface declaration of the symbol and associates it with the symbol. Other units that use the symbol also store the symbol version. In this way, link-time conflicts caused by stale symbols are avoided, unlike most C linkers.

The upshot of this is that you should be able to add Classes.pas to your project and modify its implementation section almost to your heart's content, and still be able to statically link with the rest of the RTL and VCL and third-party libraries, even those provided in object format only.

Things to be careful of:

  • Inlined routines; the body of inlined routines are part of the symbol version
  • Generics; the implementation side of generic types and methods are part of the respective symbol versions

I found VCLFixPack:

https://www.idefixpack.de/blog/bugfix-units/vclfixpack-10/

I used the techniques from this to replace the method I wanted to patch at runtime.