Format of resources in object files

Introduction

This appendix describes the format in which resources are stored in object files. This doesn't apply to PECOFF file format, where a format already exists and is well described in documentation from Microsoft.

On Microsoft Windows, resources are natively supported by the operating system. On other systems, Free Pascal RTL provides access to resources, which are embedded in the executable file in the format that is here described.

This appendix doesn't describe a particular object file format implementation (e.g. ELF or Mach-O), but the layout of the sections involved in supporting resources: the way these sections are actually laid out on a file are subject to the rules of the hosting object file format.

For external resource file details, see Description of external resource file format

Conventions

In this document, data sizes are specified with pascal-style data types. They are the following:

NameMeaning
longwordUnsigned 32 bit integer.
ptruintUnsigned integer of the size of a pointer

Byte order is the one of the target machine.

All data structures in the sections must be aligned on machine boundaries (4 bytes for 32 bit machines, 8 bytes for 64 bit machines).

Note that all pointers must be valid at runtime. This means that relocations must be written to the object file so that the linker can relocate pointers to the addresses they will have at runtime. Note also that pointers to strings are really pointers, and not offsets to the beginning of the string table.

Resource sections

Free Pascal uses two sections to store resource information:

  • fpc.resources. This is a data section that contains all required structures. It must be writable.
  • fpc.rehandles. This is a bss section whose size must be equal to (total number of resources)*(size of pointer). It must be writable.

The rest of this chapter will describe the contents of fpc.resources section.

Resource section layout

The fpc.resources section consists of these parts:

  • The initial header
  • The resource tree, in the form of nodes
  • The string table, which can be optional
  • The resource data

The initial header

The fpc.resources section starts with this header:

NameOffsetLengthDescription
rootptr 0 ptruint Pointer to the root node.
count 4/8 longword Total number of resources.
usedhandles 8/12 longword Used at runtime. Set to zero in object files.
handles 12/16 ptruint Pointer to the first byte of fpc.reshandles section.

The resource tree

Immediately following the initial header, the resource tree comes. It is made up by nodes that represent resource types, names and language ids.

Data is organized so that resource information (type, name and language id) is represented by a tree: root node contains resource types, that in turn contain resource names, which contain language ids, which describe resource data.

Given a node, its sub-nodes are ordered as follows:

  • First the "named" nodes (nodes that use a string as identifier) come, then the id ones (nodes that use an integer as identifier).
  • Named nodes are alphabetically sorted, in ascending order.
  • Id nodes are sorted in ascending order.

In the file, all sub-nodes of a node are written in the order described above. Then, all sub-nodes of the first sub-node are written, and so on.

Example:

There are three resources:

  1. a BITMAP resource with name MYBITMAP and language id $0409
  2. a BITMAP resource with name 1 and language id 0
  3. a resource with type MYTYPE and name 1 and language id 0

Nodes are laid out this way (note that BITMAP resources have type 2):

	
	root | MYTYPE 2 | 1 | 0 | MYBITMAP 1 | $0409 | 0

That is, types (MYTYPE is a string, so it comes before 2 which is BITMAP), then names for MYTYPE (1), then language id for resource 3 (0), then names for BITMAP (MYBITMAP and 1), then language id for resource 1 ($0409), then language id for resource 2 (0).

Node format

NameOffsetLengthDescription
nameid 0 ptruint name pointer, integer id or language id
ncount 4/8 longword named sub-nodes count
idcountsize 8/12 longword id sub-nodes count or resource size
subptr 12/16 ptruint pointer to first sub-node

If the node is identified by a string, nameid is a pointer to the null-terminated string holding the name. If it is identified by an id, nameid is that id. Language id nodes are always identified by and ID.

ncount is the number of named sub-nodes of this node (nodes that are identified by a string).

idcountsize is the number of id sub-nodes of this node (nodes that are identified by an integer id). For language id nodes, this field holds the size of the resource data.

subptr is an pointer to the first subnode of this node. Note that it allows to access every subnode of this node, since subnodes of a node always come one after the other. For language id nodes, subptr is the pointer to the resource data.

The string table

The string table is used to store strings used for resource types and names. If all resources use integer ids for name and types, it may not be present in the file.

The string table simply contains null-terminated strings, one after the other.

If present, the string table always contains a 0 (zero) at the beginning. This way, the empty string is located at the first byte of the string table.

The resource data

This part of the file contains raw resource data. As written before, all data structures must be aligned on machine boundaries, so if a resource data size is not a multiple of 4 (for 32 bit machines) or 8 (for 64 bit machines), bytes of padding must be inserted after that resource data.

Exported symbols

Object files containing resources must export a pointer to the first byte of fpc.resources section. The name of this symbol is FPC_RESSYMBOL.

Mach-O specific notes

fpc.resources and fpc.reshandles sections are to be contained in a __DATA segment.

How to implement a new resource writer This chapter assumes you have some experience in using this library.

We'll see how to implement a writer for a new resource file format. A resource writer is a descendant of TAbstractResourceWriter, and it's usually implemented in a unit named namewriter, where name is file format name.

Suppose we must write a writer for file format foo; we could start with a unit like this:

unit foowriter; {$MODE OBJFPC} {$H+} interface uses Classes, SysUtils, resource; type TFooResourceWriter = class (TAbstractResourceWriter) protected function GetExtensions : string; override; function GetDescription : string; override; procedure Write(aResources : TResources; aStream : TStream); override; public constructor Create; override; end; implementation function TFooResourceWriter.GetExtensions: string; begin end; function TFooResourceWriter.GetDescription: string; begin end; procedure TFooResourceWriter.Write(aResources: TResources; aStream: TStream); begin end; constructor TFooResourceWriter.Create; begin end; initialization TResources.RegisterWriter('.foo',TFooResourceWriter); end.

Note that in the initialization section, TFooResourceWriter is registered for extension .foo.

We must implement abstract methods of TAbstractResourceWriter. Let's start with the simpler ones, GetExtensions and GetDescription.

function TFooResourceWriter.GetExtensions: string; begin Result:='.foo'; end; function TFooResourceWriter.GetDescription: string; begin Result:='FOO resource writer'; end;

Now let's see Write. This method must write all resources in the TResources object to the stream.

Suppose that our foo format is very simple:

  • the header is made by a 4-byte signature (FOO*), a longword holding the number of resources in the file, and other 8 bytes of padding.
  • each resource has a 16-byte header containing:

    • a longword for the resource type (only IDs are allowed for types)
    • a longword for the resource name (only IDs are allowed for names)
    • a longword for the language ID
    • a longword for the size of the resource data
  • after the resource header immediately comes the resource data, possibly padded so that it ends on a 4 byte boundary.
  • file format is little-endian

Our Write method could be something like this:

procedure TFooResourceWriter.Write(aResources: TResources; aStream: TStream); var i : integer; begin WriteFileHeader(aStream,aResources); for i:=0 to aResources.Count-1 do WriteResource(aStream,aResources[i]); end;

So we must implement WriteFileHeader, which writes the 16-byte file header, and WriteResource, which writes a single resource with its header.

Let's start from the first one:

procedure TFooResourceWriter.WriteFileHeader(aStream: TStream; aResources: TResources); var signature : array[0..3] of char; rescount : longword; padding : qword; begin signature:='FOO*'; rescount:=aResources.Count; padding:=0; aStream.WriteBuffer(signature[0],4); aStream.WriteBuffer(rescount,sizeof(rescount)); aStream.WriteBuffer(padding,sizeof(padding)); end;

This code simply writes the file header as defined in foo format. Note that if we are running on a big endian system we should swap bytes before writing, e.g. calling SwapEndian function, but for simplicity this is omitted.

Now WriteResource comes. This method could be like this:

procedure TFooResourceWriter.WriteResource(aStream: TStream; aResource: TAbstractResource); var aType : longword; aName : longword; aLangID : longword; aDataSize : longword; begin aType:=aResource._Type.ID; aName:=aResource.Name.ID; aLangID:=aResource.LangID; aDataSize:=aResource.RawData.Size; //write resource header aStream.WriteBuffer(aType,sizeof(aType)); aStream.WriteBuffer(aName,sizeof(aName)); aStream.WriteBuffer(aLangID,sizeof(aLangID)); aStream.WriteBuffer(aDataSize,sizeof(aDataSize)); //write resource data aResource.RawData.Position:=0; aStream.CopyFrom(aResource.RawData,aResource.RawData.Size); //align data so that it ends on a 4-byte boundary Align4Bytes(aStream); end;

We write the 16-byte resource header, and then resource data. Note that if resources have been loaded from a stream and the user didn't modify resource data, we are copying data directly from the original stream.

Align4Bytes is a private method (not shown for simplicity) that writes some padding bytes to the stream if needed, since FOO file format specifies that resource data must be padded to end on a 4 byte boundary. Again, we didn't consider endianess for simplicity. And finally, note that foo format only supports IDs for types and names, so if one of them is a name (that is, a string) this code might cause exceptions to be raised.

Note: More complex file formats store resources in a tree hierarchy; since TResources internally stores resources in this way too, a writer can choose to acquire a reference to the internal tree used by the TResources object (see TAbstractResourceWriter.GetTree) and use it directly. For these file formats resources can be written faster, since there is no overhead involved in building a separate resource tree in the writer.

That's all. Now you should be able to create a real resource writer.

How to implement a new resource reader This chapter assumes you have some experience in using this library.

We'll see how to implement a reader for a new resource file format. A resource reader is a descendant of TAbstractResourceReader, and it's usually implemented in a unit named namereader, where name is file format name.

Suppose we must write a reader for file format foo; we could start with a unit like this:

unit fooreader; {$MODE OBJFPC} {$H+} interface uses Classes, SysUtils, resource; type TFooResourceReader = class(TAbstractResourceReader) protected function GetExtensions : string; override; function GetDescription : string; override; procedure Load(aResources : TResources; aStream : TStream); override; function CheckMagic(aStream : TStream) : boolean; override; public constructor Create; override; end; implementation function TFooResourceReader.GetExtensions: string; begin end; function TFooResourceReader.GetDescription: string; begin end; procedure TFooResourceReader.Load(aResources: TResources; aStream: TStream); begin end; function TFooResourceReader.CheckMagic(aStream: TStream): boolean; begin end; constructor TFooResourceReader.Create; begin end; initialization TResources.RegisterReader('.foo',TFooResourceReader); end.

Note that in the initialization section, TFooResourceReader is registered for extension .foo.

We must implement abstract methods of TAbstractResourceReader. Let's start with the simpler ones, GetExtensions and GetDescription.

function TFooResourceReader.GetExtensions: string; begin Result:='.foo'; end; function TFooResourceReader.GetDescription: string; begin Result:='FOO resource reader'; end;

Now let's see CheckMagic method. This method is called with a stream as a parameter, and the reader must return true if it recognizes the stream as a valid one. Usually this means checking some magic number or header.

function TFooResourceReader.CheckMagic(aStream: TStream): boolean; var signature : array[0..3] of char; begin Result:=false; try aStream.ReadBuffer(signature[0],4); except on e : EReadError do exit; end; Result:=signature='FOO*'; end;

Suppose our foo files start with a 4-byte signature 'FOO*'. This method checks the signature and returns true if it is verified. Note that it catches EReadError exception raised by TStream: this way, if the stream is too short it returns false (as it should, since magic is not valid) instead of letting the exception to propagate.

Now let's see Load. This method must read the stream and create resources in the TResources object, with information about their name, type, position and size of their raw data, and so on.

procedure TFooResourceReader.Load(aResources: TResources; aStream: TStream); begin if not CheckMagic(aStream) then raise EResourceReaderWrongFormatException.Create(''); try ReadResources(aResources,aStream); except on e : EReadError do raise EResourceReaderUnexpectedEndOfStreamException.Create(''); end; end;

First of all, this method checks file magic number, calling CheckMagic method we already implemented. This is necessary since CheckMagic is not called before Load: CheckMagic is invoked by TResources when probing a stream, while Load is invoked when loading resources (so if the user passed a reader object to a TResources object, CheckMagic is never called). Note also that the stream is always at its starting position when these methods are called.

If magic number is ok, our method invokes another method to do the actual loading. If during this process the stream can't be read, an EResourceReaderUnexpectedEndOfStreamException exception is raised.

So, let's implement the private method which will load resources.

Suppose that our foo format is very simple:

  • the header is made by the 4-byte signature we already saw, a longword holding the number of resources in the file, and other 8 bytes of padding.
  • each resource has a 16-byte header containing:

    • a longword for the resource type (only IDs are allowed for types)
    • a longword for the resource name (only IDs are allowed for names)
    • a longword for the language ID
    • a longword for the size of the resource data
  • after the resource header immediately comes the resource data, possibly padded so that it ends on a 4 byte boundary.
  • file format is little-endian

To start with, our method will be:

procedure TFooResourceReader.ReadResources(aResources: TResources; aStream: TStream); var Count, i: longword; aType, aName, aLangID : longword; aDataSize : longword; begin //read remaining file header aStream.ReadBuffer(Count,sizeof(Count)); aStream.Seek(8,soFromCurrent); for i:=1 to Count do begin //read resource header aStream.ReadBuffer(aType,sizeof(aType)); aStream.ReadBuffer(aName,sizeof(aName)); aStream.ReadBuffer(aLangID,sizeof(aLangID)); aStream.ReadBuffer(aDataSize,sizeof(aDataSize)); end; end;

Since in Load we called CheckMagic, which read the first 4 bytes of the header, we must read the remaining 12: we read the number of resources, and we skip the other 8 bytes of padding.

Then, for each resource, we read the resource header. Note that if we are running on a big endian system we should swap the bytes we read, e.g. calling SwapEndian function, but for simplicity this is omitted.

Now, we should create a resource. Of which class? Well, we must use unit. In fact it contains TResourceFactory class, which is an expert in creating resources of the right class: when the user adds a unit containing a resource class to the uses clause of its program, the resource class registers itself with TResourceFactory. This way it knows how to map resource types to resource classes.

We need to have type and name of the resource to create as TResourceDesc objects: instead of creating and destroying these objects for each resource, we'll create a couple in the creator of our reader and we'll destroy them in the destructor, so that they will live for the whole life of our reader. Let's name them workType and workName.

Our code becomes:

uses resfactory; procedure TFooResourceReader.ReadResources(aResources: TResources; aStream: TStream); var Count, i: longword; aType, aName, aLangID : longword; aDataSize : longword; aRes : TAbstractResource; begin //read remaining file header aStream.ReadBuffer(Count,sizeof(Count)); aStream.Seek(8,soFromCurrent); for i:=1 to Count do begin //read resource header aStream.ReadBuffer(aType,sizeof(aType)); aStream.ReadBuffer(aName,sizeof(aName)); aStream.ReadBuffer(aLangID,sizeof(aLangID)); aStream.ReadBuffer(aDataSize,sizeof(aDataSize)); //create the resource workType.ID:=aType; workName.ID:=aName; aRes:=TResourceFactory.CreateResource(workType,workName); SetDataSize(aRes,aDataSize); SetDataOffset(aRes,aStream.Position); aRes.LangID:=aLangID; end; end;

Note that after the resource has been created we set its data size and data offset. Data offset is the current position in the stream, since in our FOO file format resource data immediately follows resource header.

What else do we need to do? Of course we must create RawData stream for our resource, so that raw data can be accessed with the caching mechanism. We will create a TResourceDataStream object, telling it which resource and stream it is associated to, which its size will be and which class its underlying cached stream must be created from.

So we add to the uses clause, declare another local variable

aRawData : TResourceDataStream;

and add these lines in the for loop

aRawData:=TResourceDataStream.Create(aStream,aRes,aRes.DataSize,TCachedResourceDataStream); SetRawData(aRes,aRawData);

That is, aRawData will create its underlying stream as a TCachedResourceDataStream over the portion of aStream that starts at current position and ends after aRes.DataSize bytes.

We almost finished: now we must add the newly created resource to the TResources object and move stream position to the next resource header. Complete code for ReadResources method is:

procedure TFooResourceReader.ReadResources(aResources: TResources; aStream: TStream); var Count, i: longword; aType, aName, aLangID : longword; aDataSize : longword; aRes : TAbstractResource; aRawData : TResourceDataStream; begin //read remaining file header aStream.ReadBuffer(Count,sizeof(Count)); aStream.Seek(8,soFromCurrent); for i:=1 to Count do begin //read resource header aStream.ReadBuffer(aType,sizeof(aType)); aStream.ReadBuffer(aName,sizeof(aName)); aStream.ReadBuffer(aLangID,sizeof(aLangID)); aStream.ReadBuffer(aDataSize,sizeof(aDataSize)); //create the resource workType.ID:=aType; workName.ID:=aName; aRes:=TResourceFactory.CreateResource(workType,workName); SetDataSize(aRes,aDataSize); SetDataOffset(aRes,aStream.Position); aRes.LangID:=aLangID; //set raw data aRawData:=TResourceDataStream.Create(aStream,aRes,aRes.DataSize,TCachedResourceDataStream); SetRawData(aRes,aRawData); //add to aResources try aResources.Add(aRes); except on e : EResourceDuplicateException do begin aRes.Free; raise; end; end; //go to next resource header aStream.Seek(aDataSize,soFromCurrent); Align4Bytes(aStream); end; end;

Align4Bytes is a private method (not shown for simplicity) that sets stream position to the next multiple of 4 if needed, since FOO file format specifies that resource data must be padded to end on a 4 byte boundary.

Note: We have used Add method to populate the TResources object. More complex file formats store resources in a tree hierarchy; since TResources internally stores resources in this way too, a reader can choose to acquire a reference to the internal tree used by the TResources object (see TAbstractResourceReader.GetTree), populate it and notify the TResources object about the added resources (see TAbstractResourceReader.AddNoTree). For these file formats resources can be loaded faster, since there is no overhead involved in keeping a separate resource tree in the reader.

That's all. Now you should be able to create a real resource reader.

How to implement a new resource class This chapter assumes you have some experience in using this library.

Some considerations

Usually, a specific resource class is needed when resource data is encoded in a specific binary format that makes working with RawData uncomfortable.

However, there aren't many reasons to design a new binary format requiring a specific resource class: the classes provided with this package exist for compatibility with Microsoft Windows, but in the general case one should avoid such approach.

In Microsoft Windows, some resource types have a specific format, and the operating system supports them at runtime making it easy to access that kind of data: e.g. icons and bitmaps are stored in resources in a format that is slightly different from the one found in regular files, but the operating system allows the user to easily load them using LoadImage function, without having to deal with their internal format. Other resource types are used to obtain information about the executable: RT_VERSION resource type and RT_GROUP_ICON contain version information and program icon that can be displayed in Windows Explorer, respectively.

Using this kind of resources in a cross-platform perspective doesn't make much sense however, since there is no support by other operating systems for these types of resources (and for resources in general), and this means that it's up to you to provide support at runtime for these binary formats. So if you need to store images as resources it's better to use TGenericResource and store an image in PNG format (for instance), which can be read by existing libraries at runtime, instead of creating a RT_BITMAP resource with TBitmapResource, since libraries that read BMP files can't handle that resource contents.

New resource classes thus make sense when you want to add support for existing Windows-specific resources, e.g. because you are writing a resource compiler or editor, but in the general case they should be avoided.

Now that you've been warned, let's start with the topic of this chapter.

How to implement a new resource class

A resource class is a descendant of TAbstractResource, and it's usually implemented in a unit named typeresource, where type is resource type.

If you are implementing a new resource class, you are doing it to provide additional methods or properties to utilize resource data. You resource class must thus be able to read its RawData stream format and write data back to it when it is requested to do so.

Generally, your class shouldn't create private objects, records or memory buffers to provide these specific means of accessing data until it's requested to do so (lazy loading), and it should free these things when it is requested to write back data to the RawData stream.

We'll see these points in more detail, using TAcceleratorsResource as an example.

TAcceleratorsResource holds a collection of accelerators. An accelerator is a record defined as follows:

type TAccelerator = packed record Flags : word; Ansi : word; Id : word; padding : word; end;

The resource simply contains accelerators, one immediately following the other. Last accelerator must have $80 in its flags.

To provide easy access to the elements it contains, our accelerator resource class exposes these methods and properties in its public section:

procedure Add(aItem : TAccelerator); procedure Clear; procedure Delete(aIndex : integer); property Count : integer read GetCount; property Items[index : integer] : TAccelerator read GetItem write SetItem; default;

We must also implement abstract methods (and an abstract constructor) of TAbstractResource:

protected function GetType : TResourceDesc; override; function GetName : TResourceDesc; override; function ChangeDescTypeAllowed(aDesc : TResourceDesc) : boolean; override; function ChangeDescValueAllowed(aDesc : TResourceDesc) : boolean; override; procedure NotifyResourcesLoaded; override; public constructor Create(aType,aName : TResourceDesc); override; procedure UpdateRawData; override;

The protected methods are very easy to implement, so let's start from them. For GetType and GetName, we need to add two private fields, fType and fName, of type TResourceDesc. We create them in the constructor and destroy them in the destructor. Type will always be RT_ACCELERATOR. We make the parameterless constructor of TAbstractResource public, using 1 as the resource name, while in the other constructor we use the name passed as parameter, ignoring the type (since it must always be RT_ACCELERATOR).

So, GetType, GetName, the constructors and the destructor are implemented as follows:

function TAcceleratorsResource.GetType: TResourceDesc; begin Result:=fType; end; function TAcceleratorsResource.GetName: TResourceDesc; begin Result:=fName; end; constructor TAcceleratorsResource.Create; begin inherited Create; fType:=TResourceDesc.Create(RT_ACCELERATOR); fName:=TResourceDesc.Create(1); SetDescOwner(fType); SetDescOwner(fName); end; constructor TAcceleratorsResource.Create(aType, aName: TResourceDesc); begin Create; fName.Assign(aName); end; destructor TAcceleratorsResource.Destroy; begin fType.Free; fName.Free; inherited Destroy; end;

Note that we used SetDescOwner to let type and name know the resource that owns them.

Now ChangeDescTypeAllowed and ChangeDescValueAllowed come. As we said, resource type must be RT_ACCELERATOR, always. Thus, we only allow name to change value or type:

function TAcceleratorsResource.ChangeDescTypeAllowed(aDesc: TResourceDesc): boolean; begin Result:=aDesc=fName; end; function TAcceleratorsResource.ChangeDescValueAllowed(aDesc: TResourceDesc): boolean; begin Result:=aDesc=fName; end;

NotifyResourcesLoaded is called by TResources when it finishes loading all resources. Since we are not interested in this fact, we simply leave this method empty. This method is useful for resources that "own" other resources, like TGroupIconResource and TGroupCursorResource (note: you should not implement resource types that depend on other resources: it complicates things a lot and gives you a lot of headaches).

Now, let's see the more interesting - and more difficult - part: providing an easy way to deal with accelerators.

As we said earlier, we must implement some methods and properties to do so. Surely we'll need a list to hold pointers to accelerator records, but we must think a little bit about how this list is created, populated, written to RawData and so on.

When the object is created, we don't have to create (yet) single accelerator records, as said before; but if the user tries to access them we must do it. If the object is created and its RawData contains data (e.g. because a reader has created the resource when loading a resource file) and the user tries to access an accelerator, we must create accelerators from RawData contents. So, until a user tries to access accelerators our class doesn't do anything, while when the user does so it "lazy-loads" data, or creates empty structures if RawData is empty.

When data is loaded, RawData contents aren't considered anymore. When, however, our resource is requested to update RawData (that is, when UpdateRawData method is invoked), our "lazy-loaded" data must be freed. In fact, a user could ask our resource to update raw data, then he/she could modify it directly and then could use our resource's specialized methods and properties to do further processing: for this reason, when RawData is written, other buffered things must be freed, so that they'll created again from RawData if needed.

Note that other resource classes could behave differently: e.g. TBitmapResource uses a copy-on-write mechanism on top of RawData to insert a BMP file header at the beginning of the stream, but it doesn't copy RawData contents whenever possible.

Coming back to our TAcceleratorsResource example, let's see how to implement this behaviour.

Let's add a fList field in the private section of our class:

fList : TFPList;

In the constructor, we set this field to nil: we use it to check if data has been loaded from RawData or not. Consequently in the destructor we'll free the list only if it's not nil:

destructor TAcceleratorsResource.Destroy; begin fType.Free; fName.Free; if fList<>nil then begin Clear; fList.Free; end; inherited Destroy; end;

(we did not implement Clear method yet: we'll see it later).

We said that our resource must load data only when needed; to do this we add a private method, CheckDataLoaded that ensures that data is loaded. This method is called by whatever method needs to operate on the list: if data has already been loaded it will quickly return, otherwise it will load data.

procedure TAcceleratorsResource.CheckDataLoaded; var acc : TAccelerator; tot, i : integer; p : PAccelerator; begin if fList<>nil then exit; fList:=TFPList.Create; if RawData.Size=0 then exit; RawData.Position:=0; tot:=RawData.Size div 8; for i:=1 to tot do begin RawData.ReadBuffer(acc,sizeof(acc)); GetMem(p,sizeof(TAccelerator)); p^:=acc; fList.Add(p); end; end;

If fList is not nil data is already loaded, so exit. Otherwise, create the list. If RawData is empty we don't need to load anything, so exit. Otherwise allocate room for accelerators, read them from the stream, and add them to the list.

Note that if we are running on a big endian system we should swap the bytes we read, e.g. calling SwapEndian function, but for simplicity this is omitted.

The counterpart of CheckDataLoaded is UpdateRawData. When it is called, data from the list must be written back to RawData, and the list and its contents must be freed:

procedure TAcceleratorsResource.UpdateRawData; var acc : TAccelerator; i : integer; begin if fList=nil then exit; RawData.Size:=0; RawData.Position:=0; for i:=0 to fList.Count-1 do begin acc:=PAccelerator(fList[i])^; // $80 means 'this is the last entry', so be sure only the last one has this bit set. if i=Count-1 then acc.Flags:=acc.Flags or $80 else acc.Flags:=acc.Flags and $7F; RawData.WriteBuffer(acc,sizeof(acc)); end; Clear; FreeAndNil(fList); end;

If fList is nil data hasn't been loaded, so RawData is up to date, so exit. Otherwise, write each accelerator (ensuring that only last one has $80 flag set), clear the list, free it and set it to nil. Again, if we are on a big endian system we should swap each accelerator contents before writing it, but for simplicity this is omitted.

Other methods we named earlier (Add, Delete, Clear) are trivial to implement: remember only to call CheckDataLoaded before doing anything. The same is true for accessor methods of relevant properties (Count, Items).

If you are curious, you can check the full implementation of TAcceleratorsResource looking at source code.

Basic Usage

Resource files and TResources class

One of the most important classes is TResources class, contained in unit, which represents a format-independent view of a resource file. In fact, while single resources are important, they are of little use alone, since they can't be read or written to file directly: they need to be contained in a TResources object.

TResources provides methods to read itself from a file or stream, using specific objects that are able to read resource data from such a stream: these are the so called resource readers, that descend from TAbstractResourceReader.

There are also resource writers that do the opposite, and that descend from TAbstractResourceWriter.

Usually readers and writers register themselves with TResources in the initialization section of the unit they are implemented in, so you only need to add a certain unit to your program uses clause to let TResources "know" about a particular file format.

Let's see a very simple example: a program that converts a .res file to an object file in COFF format (the object file format used by Microsoft Windows).

program res1; {$mode objfpc} uses Classes, SysUtils, resource, resreader, coffwriter; var resources : TResources; begin resources:=TResources.Create; resources.LoadFromFile('myresource.res'); resources.WriteToFile('myobject.o'); resources.Free; end.

As you can see, the code is trivial. Note that resreader and coffwriter units were added to the uses clause of the program: this way, the resource reader for .res files and the resource writer for COFF files have been registered, letting the resources object know how to handle these file types.

There are cases where one doesn't want to let the TResources object to choose readers and writers by itself. In fact, while generally it is a good idea to let TResources probe all readers it knows to find one able to read the input file, this isn't true when it comes to write files: writers are selected based on the file extension, so if you are trying to write a file with .o extension you can't be sure about which writer will be selected: it could be the COFF or the ELF writer (it depends on which writer gets registered first). Moreover, writers generally make an object file for the host architecture, so if you are running the program on a i386 machine it will produce a COFF or ELF file for i386.

The solution is to provide TResources with a specific writer. In the following example the reader is automatically chosen among various readers, and we use a specific writer to produce an ELF file for SPARC.

program res2; {$mode objfpc} uses Classes, SysUtils, resource, resreader, coffreader, elfreader, winpeimagereader, //readers elfwriter, elfconsts; var resources : TResources; writer : TElfResourceWriter; begin resources:=TResources.Create; resources.LoadFromFile(paramstr(1)); writer:=TElfResourceWriter.Create; writer.MachineType:=emtsparc; resources.WriteToFile(ChangeFileExt(paramstr(1),'.o'),writer); resources.Free; writer.Free; end.

Note that the file to convert is taken from the command line. Its format is automatically detected among res (), coff (), elf (), PE (, e.g. a Windows exe or dll), and is written as an ELF file for SPARC. Note that we had to use unit since we used emtsparc constant to specify the machine type of the object file to generate.

With a small change to the above program we can let the user know which reader was selected to read the input file: we can use TResources.FindReader class method to obtain the appropriate reader for a given stream.

program res3; {$mode objfpc} uses Classes, SysUtils, resource, resreader, coffreader, elfreader, winpeimagereader, //readers elfwriter, elfconsts; var resources : TResources; writer : TElfResourceWriter; reader : TAbstractResourceReader; inFile : TFileStream; begin resources:=TResources.Create; inFile:=TFileStream.Create(paramstr(1), fmOpenRead or fmShareDenyNone); reader:=TResources.FindReader(inFile); writeln('Selected reader: ',reader.Description); resources.LoadFromStream(inFile,reader); writer:=TElfResourceWriter.Create; writer.MachineType:=emtsparc; resources.WriteToFile(ChangeFileExt(paramstr(1),'.o'),writer); resources.Free; reader.Free; writer.Free; inFile.Free; end.

Output example:

user@localhost:~$ ./res3 myresource.res
Selected reader: .res resource reader
user@localhost:~$

Single resources

You can do more with resources than simply converting between file formats.

TResources.Items property provides a simple way to access all resources contained in the TResources object.

In the following example we read a resource file and then dump each resource data in a file whose name is built from type and name of the dumped resource.

program res4; {$mode objfpc} uses Classes, SysUtils, resource, resreader; var resources : TResources; dumpFile : TFileStream; i : integer; fname : string; begin resources:=TResources.Create; resources.LoadFromFile('myresource.res'); for i:=0 to resources.Count-1 do begin fname:=resources[i]._Type.Name+'_'+resources[i].Name.Name; dumpFile:=TFileStream.Create(fname,fmCreate or fmShareDenyWrite); dumpFile.CopyFrom(resources[i].RawData,resources[i].RawData.Size); dumpFile.Free; end; resources.Free; end.

This code simply copies the content of each resource's RawData stream to a file stream, whose name is resourcetype_resourcename.

Resource raw data isn't always what one expected, however. While some resource types simply contain a copy of a file in their raw data, other types do some processing, so that dumping raw data doesn't result in a file in the format one expected.

E.g. a resource of type RT_MANIFEST is of the former type: its raw data is like an XML manifest file. On the other hand, in a resource of type RT_BITMAP the RawData stream isn't like a BMP file.

For this reason, several classes (descendants of TAbstractResource) are provided to handle the peculiarities of this or that resource type. Much like it's done with readers and writers, resource classes can be registered: adding the unit that contains a resource class to the uses clause of your program registers that class. This way, when resources are read from a file, they are created with the class that is registered for their type (the class responsible to do this is TResourceFactory, but probably you won't need to use it unless you're implementing a new resource reader or resource class).

In the following example, we read a resource file and then dump data of each resource of type RT_BITMAP as a BMP file.

program res5; {$mode objfpc} uses Classes, SysUtils, resource, resreader, bitmapresource; var resources : TResources; dumpFile : TFileStream; i : integer; fname : string; begin resources:=TResources.Create; resources.LoadFromFile('myresource.res'); for i:=0 to resources.Count-1 do if resources[i] is TBitmapResource then with resources[i] as TBitmapResource do begin fname:=Name.Name+'.bmp'; dumpFile:=TFileStream.Create(fname,fmCreate or fmShareDenyWrite); dumpFile.CopyFrom(BitmapData,BitmapData.Size); dumpFile.Free; end; resources.Free; end.

Note that we included in the uses clause of our program. This way, resources of type RT_BITMAP are created from TBitmapResource class. This class provides a stream, BitmapData that allows resource raw data to be accessed as if it was a bmp file.

We can of course do the opposite. In the following code we are creating a manifest resource from manifest.xml file.

program res6; {$mode objfpc} uses Classes, SysUtils, resource, reswriter; var resources : TResources; inFile : TFileStream; res : TGenericResource; rname,rtype : TResourceDesc; begin inFile:=TFileStream.Create('manifest.xml',fmOpenRead or fmShareDenyNone); rtype:=TResourceDesc.Create(RT_MANIFEST); rname:=TResourceDesc.Create(1); res:=TGenericResource.Create(rtype,rname); rtype.Free; //no longer needed rname.Free; res.SetCustomRawDataStream(inFile); resources:=TResources.Create; resources.Add(res); resources.WriteToFile('myresource.res'); resources.Free; //frees res as well inFile.Free; end.

Note that resources of type RT_MANIFEST contain a straight copy of a xml file, so TGenericResource class fits our needs. TGenericResource is a basic implementation of TAbstractResource. It is the default class used by TResourceFactory when it must create a resource whose type wasn't registered with any resource class.

Please note that instead of copying inFile contents to RawData we used SetCustomRawDataStream method: it sets a stream as the underlying stream for RawData, so that when final resource file is written, data is read directly from the original file.

Let's see a similar example, in which we use a specific class instead of TGenericResource. In the following code we are creating a resource containing the main program icon, which is read from mainicon.ico file.

program res7; {$mode objfpc} uses Classes, SysUtils, resource, reswriter, groupiconresource; var resources : TResources; inFile : TFileStream; iconres : TGroupIconResource; name : TResourceDesc; begin inFile:=TFileStream.Create('mainicon.ico',fmOpenRead or fmShareDenyNone); name:=TResourceDesc.Create('MAINICON'); //type is always RT_GROUP_ICON for this resource class iconres:=TGroupIconResource.Create(nil,name); iconres.SetCustomItemDataStream(inFile); resources:=TResources.Create; resources.Add(iconres); resources.WriteToFile('myicon.res'); resources.Free; //frees iconres as well inFile.Free; name.Free; end.

In this program we created a new TGroupIconResource with 'MAINICON' as name, and we loaded its contents from file 'mainicon.ico'. Please note that RT_GROUP_ICON resource raw data doesn't contain a .ico file, so we have to write to ItemData which is a ico-like stream. As we did for res6 program, we tell the resource to use our stream as the underlying stream for resource data: the only difference is that we are using TGroupResource.SetCustomItemDataStream instead of TAbstractResource.SetCustomRawDataStream method, for obvious reasons.

Other resource types

There are other resource types that allow to easily deal with resource data. E.g. TVersionResource makes it easy to create and read version information for Windows executables and dlls, TStringTableResource deals with string tables, and so on.

Data caching

Whenever possible, fcl-res tries to avoid to duplicate data. Generally a reader doesn't copy resource data from the original stream to RawData stream: instead, it only informs the resource about where its raw data is in the original stream. RawData uses a caching system so that it appears as a stream while it only redirects operations to its underlying stream, with a copy-on-write mechanism. Of course this behaviour can be controlled by the user. For further information, see TAbstractResource and TAbstractResource.RawData.

Introduction

This package contains a library to easily work with Microsoft Windows resources in a cross-platform way.

Classes are provided to create, load and write resources from/to different file formats in a transparent way, and to handle most common resource types without having to deal with their internal format.

Whenever possible data caching is performed, helped by a copy-on-write mechanism. This improves performance especially when converting big resources from a file format to another.

Since fcl-res architecture is extensible, it's always possible to extend the library with custom resource types or new file readers/writers.

Please note that resources aren't limited to Windows platform: Free Pascal can use them also on ELF and Mach-O targets. Moreover, this library can be useful for cross-compilation purposes even on other targets.

It is highly recommended to read topic if you are approaching this library for the first time.

Contains base classes for resource handling

This unit contains base classes needed to work with resources.

Single resources are represented by an instance of a descendant. They are grouped in a instance which can be read (written) to (from) a stream via a () descendant.

provides a basic implementation of .

Single cursor resource A single image in a cursor. Don't use it directly. TGroupCursorResource Bitmap resource TBitmapResource Single icon resource A single image in a icon. Don't use it directly. TGroupIconResource Menu resource Dialog resource String table resource TStringTableResource Font directory resource This resource type is obsolete and never appears in 32 bit resources. Single font resource This resource type is obsolete and never appears in 32 bit resources. Accelerator table resource TAcceleratorsResource Application-defined resource (raw data)

This resource type contains arbitrary binary data

Note that Delphi dfm files are stored in compiled form as a RCDATA resource

Message table resource Cursor resource

This resource type contains a cursor and it's the equivalent of a .cur file

Please note that is is made up of several resources (the single cursor images) that shouldn't be accessed singularly.
TGroupCursorResource
Icon resource

This resource type contains an icon and it's the equivalent of a .ico file

Please note that is is made up of several resources (the single icon images) that shouldn't be accessed singularly.
TGroupIconResource
Version resource This resource defines version information which is visible when viewing properties of a Windows executable or DLL. TVersionResource Never present in compiled form This resource is used internally by resource compilers but will never appear in compiled form Plug and Play resource VXD resource Animated cursor resource This resource type contains raw binary data taken from a .ani file Animated icon resource This resource type contains raw binary data taken from a .ani file HTML resource This resource type contains an HTML file. Windows XP Side-by-Side Assembly XML manifest

This resource contains data taken from a .manifest file

Resource name must be one of (mainly used for executables), or (mainly used for DLLs)
The resource can be moved This flag is ignored by Windows and Free Pascal RTL. It's provided for compatibility with 16-bit Windows. The resource contains dword-aligned data This flag is ignored by Windows and Free Pascal RTL. It's provided for compatibility with 16-bit Windows. The resource is loaded with the executable file This flag is ignored by Windows and Free Pascal RTL. It's provided for compatibility with 16-bit Windows. The resource can be discarded if no longer needed This flag is ignored by Windows and Free Pascal RTL. It's provided for compatibility with 16-bit Windows. A resource language ID A resource type or name in string form A resource type or name in ID form The type of a resource type or name The resource type or name is a string The resource type or name is an ID Base class for resource-related exceptions Wrong description type error

This exception is raised when a resource description is of type dtName and property is read.

Description is not allowed to change

This exception is raised when a resource description (either type or name) is tried to be changed, but the resource class doesn't allow it.

Language ID is not allowed to change

This exception is raised when the resource language ID is tried to be changed, but the resource is contained in a object.

There is already a resource with same type, name and language ID

This exception is raised when a resource is being added to a object, but another resource with the same type, name and language ID already exists.

No resource matching the search criteria is found

This exception is raised when searching for a resource in a object fails.

There are no more free IDs to use as name for a resource

This exception is raised by method when it is not possible to generate an ID to use as a name for the given resource, because all possible 65536 IDs are already assigned to resources of the same type as the given one.

Base class for resource reader-related exceptions No suitable resource reader was found

This exception is raised when no descendant able to read a stream was found.

The stream is not in the format the reader supports

This exception is raised by Load method of a descendant when the stream it was asked to read resources from is not in the format it supports.

The stream ended prematurely

This exception is raised by Load method of a descendant when the stream it was asked to read resources from ended prematurely.

Base class for resource writer-related exceptions No suitable resource writer was found

This exception is raised by WriteToFile method of when no descendant matching filename extension was found.

Base abstract resource class

This is the base class that represents a resource.

A resource is identified by its type, name and language ID even if some file formats or operating systems don't consider the latter.

There are also additional properties that aren't always present in all file formats, so their values aren't always meaningful: however, they can be used to display detailed information when possible.

Every resource has a RawData stream that holds resource data. This stream uses a copy-on-write mechanism: if the resource has been read from a stream or file, RawData redirects read operations to the original stream. This is particularly useful when a resource file must be converted from a format to another, or when more resource files must be merged, since (potentially large) resource data is directly copied from the original to the destination stream without the need of allocating a lot of memory.

When resource data is encoded in a resource-specific format, RawData can be uncomfortable: it's often better to use a more specialized descendant class that provides additional properties and methods.

Resources cannot be read or written alone from/to a stream: they need to be contained in a object, which represents an abstract view of a resource file.

Usually each descendant registers itself with TResourceFactory class in the initialization section of the unit in which it is implemented: this way TResourceFactory class can know which class to use to instantiate a resource of a given type.

An object of this class should never be directly instantiated: use a descendant class instead.
TAcceleratorsResource TBitmapResource TGroupCursorResource TGroupIconResource TStringTableResource TVersionResource TResourceFactory
A resource description (type or name)

This class represent a resource description (type or name).

Resources are identified by a type, name and (optionally) a language ID.

Type and name can be either a name (a string identifier) or an ID (an integer identifier in the range 0..65535).

Unfortunately, name is used both to refer to a the name of the resource and both to the format of a resource description

Example:

Typically, a Windows executable has a main icon, which is a resource of type (type is an ID) and name MAINICON (name is a name).

Protected method to let a resource set itself as owner of the TResourceDesc The resource that is to become the owner of the TResourceDesc Creates a new TResourceDesc object

Creates a new TResourceDesc object.

Without arguments, resource description is of type dtName and its name is empty.

If an argument is specified, resource description and name/id are set accordingly to the value passed as parameter.

The ID to use as the resource description ID The name to use as the resource description name Assigns the contents of another TResourceDesc object to this one

If changing values is not permitted because owner resource doesn't allow it (e.g. because owner resource is a TBitmapResource and values other than are not permitted for the resource type) an exception is raised.

The object from which data must be copied Compares the contents of another TResourceDesc object to this one True if the contents of the two objects are the same The object to compare with this one The value of the resource description as a name

Setting this property causes DescType to be dtName

When reading, if DescType is dtID, the ID is returned as a string value.

The value of the resource description as an ID

Setting this property causes DescType to be dtID

When reading, if DescType is dtName, an exception is raised.
The type of the resource description

When DescType is dtName, resource description value is a name and can be accessed via Name property

When DescType is dtID, resource description value is an ID and can be accessed via ID property

A collection of resources

This class represents a format-independent view of a resource file. It holds a collection of resources ( descendants).

Typically, a TResource object is loaded from and written to a stream via format-dependent readers and writers, which are descendants of and , respectively.

Single resources can be added, removed, searched and modified: a resource compiler or editor probably will create resources, set their data, and add them to a TResources object which can then be written to file in the desired format.

This class also provides some class methods to register and find resource readers and writers: these classes, once registered, will be used by a TResources object when it is asked to load or save itself to a stream and the user didn't specify a reader or writer.

Because of the copy-on-write mechanism of , care should be taken when loading resources, since by default resource data isn't immediately read from the stream: resources hold a reference to the original stream because they need it when their data is requested. For further information, see and .
Sets this resource as the owner of the given TResourceDesc

This method is provided so that descendants of can set themselves as the owners of the given TResourceDesc

The TResourceDesc that the resource must own Protected method to let a resource list set itself as the owner of the resource The resource list that is to become the owner of the resource Protected method to let a resource set itself as the owner of a sub-resource The sub-resource that the resource must own Returns the type of the resource

Descendant classes must implement this method to provide access to the resource type.

The object representing the type of the resource Returns the name of the resource

Descendant classes must implement this method to provide access to the resource name.

The object representing the name of the resource Reports whether changing the type of resource type or name is allowed

Descendant classes must implement this method to declare if the resource allows changing the type of one of its resource description (type or name): that is, if it allows one of its descriptions type to change from dtName to dtID or vice versa.

Example:

A certain resource class allows its name only to be changed: e.g. a TBitmapResource doesn't want its type to be anything else than . It then allows changing the type of the description only if the description is the resource name:

Result:=aDesc=fName;
True if the resource allows the given to change type The whose type should be changed Reports whether changing the value of resource type or name is allowed

Descendant classes must implement this method to declare if the resource allows changing the value of one of its resource description (type or name).

Example:

A certain resource class allows its name only to be changed: e.g. a TBitmapResource doesn't want its type to be anything else than . It then allows changing the value of the description only if the description is the resource name:

Result:=aDesc=fName;
True if the resource allows the given to change value The whose value should be changed Tells the resource that all resources have been loaded

This method is called by a object when the loading of all resources from a stream has completed.

Example:

A Group resource (e.g. TGroupIconResource) can use this method to find all its sub-resources, since all resources have been loaded from a stream.

Creates a new resource

A new resource is created with the given type and name.

Please note that the resource doesn't take ownership of the objects passed as parameters, it simply copies them: it's user responsibility to free them when no longer needed.
The type of the resource to be created The name of the resource to be created Destroys the object Compares the contents of the resource to the contents of another one

This methods compares the contents of the resource with the ones of aResource. If they are of the same length and their contents are the same, true is returned, false otherwise.

Usually this methods compares the contents of the two RawData streams, calling TResourceDataStream.Compare, but descendent classes can implement a different algorithm.

TResourceDataStream.Compare
True if the contents of the two resources are the same The resource to compare to this one Updates RawData stream.

When operating on resource data with more high-level streams than RawData (e.g: TBitmapResource.BitmapData) RawData contents are no longer valid. This method ensures that RawData stream is properly synchronized with the contents of the higher-level stream.

Normally a resource writer doesn't need to call this method when it is about to write the resource data to a stream, since class takes care of this before telling the resource writer to write resources to a stream.
Sets a custom stream as the underlying stream for RawData

Normally, RawData uses a memory stream or the original resource stream (e.g. the original file containing the resource) as its underlying stream. This method allows the user to use a custom stream as the underlying stream. This can be useful when a resource must be created from the contents of an original file as-is.

If aStream is nil, a new memory stream is used as the underlying stream. This can be used to remove a previously set custom stream as the underlying stream.

Sample code

This code creates a resource containing an html file

var aType, aName : TResourceDesc; aRes : TGenericResource; aFile : TFileStream; begin aType:=TResourceDesc.Create(RT_HTML); aName:=TResourceDesc.Create('index'); aRes:=TGenericResource.Create(aType,aName); aFile:=TFileStream.Create('index.html',fmOpenRead or fmShareDenyNone); aRes.SetCustomRawDataStream(aFile); //do something... aRes.Free; aFile.Free; aType.Free; aName.Free; end;
The custom stream to use as the underlying RawData stream. It can be nil The type of the resource

Please note that some descendants don't allow resource type to be changed (e.g: it's not possible for a TBitmapResource to have a type other than ). If it is the case, an exception is raised.

Moreover, if the resource is contained in a object, type change is not allowed.

The name of the resource

Please note that some descendants don't allow resource name to be changed (e.g: a TStringTableResource name is determined by the range of strings' ID it contains). If it is the case, an exception is raised.

Moreover, if the resource is contained in a object, name change is not allowed.

The language ID of the resource Please note that if the resource is contained in a object, language ID change is not allowed: trying to do so results in an exception being raised. The size of resource raw data

DataSize is the length, in bytes, of the resource data, accessible via RawData property.

The size of resource header

This property is not always meaningful, since not all file formats support it.

Its value, when nonzero, can be used for information purposes.

The version of the resource data

This property is not always meaningful, since not all file formats support it.

Its value, when nonzero, can be used for information purposes.

The memory flags of the resource

This field is a combination of the following flags

By default, a newly created resource has and flags set.

Please note that memory flags are ignored by Windows and Free Pascal RTL. They are provided only for compatibility with 16-bit Windows.

This property is not always meaningful, since not all file formats support it.

Its value, when nonzero, can be used for information purposes.

A user defined version number

A tool that writes resource files can write version information in this field.

This property is not always meaningful, since not all file formats support it.

Its value, when nonzero, can be used for information purposes.

A user defined piece of data

A tool that writes resource files can write arbitrary data in this field.

This property is not always meaningful, since not all file formats support it.

Its value, when nonzero, can be used for information purposes.

The offset of resource data from the beginning of the stream

A reader sets this property to let the resource know where its raw data begins in the resource stream.

The code page of the resource

This property is not always meaningful, since not all file formats support it.

Its value, when nonzero, can be used for information purposes.

The raw resource data stream

This property provides access to the resource raw data in a stream-like way.

When a resource has been read from a stream, RawData redirects read operations to the original stream. When RawData is written to, a copy-on-write mechanism copies data from the original stream to a memory stream.

The copy-on-write behaviour can be controlled via CacheData property.

Note that for some predefined resource types there are better ways to read and write resource data: some resource types use specific formats, so RawData might not always be what one expected. E.g. in a resource of type , RawData doesn't contain a valid BMP file: in this case it's better to use BitmapData stream of TBitmapResource class to work with a BMP-like stream.

When writing to a "specialized" stream in a descendant class (like the TBitmapResource.BitmapData stream mentioned earlier), RawData contents might not be valid anymore. If you need to access RawData again, be sure to call UpdateRawData method first.

Usually there isn't much penalty in using specialized streams in descendant classes, since data isn't duplicated in two or more streams, whenever possible. So, having a very large bitmap resource and reading/writing it via TBitmapResource.BitmapData doesn't mean the bitmap is allocated two times.

Controls the copy-on-write behaviour of the resource

When CacheData is true, copy-on-write mechanism of RawData is enabled.

Setting CacheData to false forces the raw resource data to be loaded in memory without performing any caching.

By default, CacheData is true.

The resource list that owns this resource

This property identifies the object to which this resource belongs to.

This property can be nil if the resource isn't part of a resource list.

The owner of this resource

This property is meaningful only for those sub-resources that are part of a larger group resource.

Example: an icon is made by a resource and many resources that hold single-image data. Each resource has a pointer to the resource in its Owner property.

Resource metaclass Generic resource class

This class represents a generic resource.

It is suitable to use in all situations where a higher level class is not needed (e.g. the resource raw data is made of arbitrary data) or when total low-level control is desirable.

This class is also the default one that is used by TResourceFactory when it finds no class matching the given type.

TResourceFactory.CreateResource
Base abstract resource reader class

This is the base class that represents a resource reader.

A resource reader is an object whose job is to populate a object with resources read from a stream in a specific format.

Typically, a object invokes CheckMagic method of the resource reader when it's searching for a reader able to read a certain stream, and Load method when it wants the reader to read data from the stream.

Usually each resource reader registers itself with class in the initialization section of the unit in which it is implemented: this way a object can find it when probing a stream that is to be read.

An object of this class should never be directly instantiated: use a descendant class instead.
TResResourceReader TCoffResourceReader TWinPEResourceReader TElfResourceReader TExternalResourceReader TDfmResourceReader
Base abstract resource writer class

This is the base class that represents a resource writer.

A resource writer is an object whose job is to write all resources contained in a object to a stream in a specific format.

Typically, a object invokes Write method of the resource writer when it wants the writer to write data to a stream.

Usually each resource writer registers itself with class in the initialization section of the unit in which it is implemented: this way a object can find it when it is asked to write itself to a file, and no writer was specified (the writer is found based on the extension of the file to write to).

An object of this class should never be directly instantiated: use a descendant class instead.
TResResourceWriter TCoffResourceWriter TElfResourceWriter TExternalResourceWriter
Resource reader metaclass Resource writer metaclass Searches for a resource

This method searches for a resource with the given type and name. If a language ID is not provided, the first resource found that matches aType and aName is returned.

If the resource is not found, an exception is raised.

The resource that matches the search criteria The type of the resource to search for The name of the resource to search for The language ID of the resource to search for Creates a new TResources object Destroys the object All resources are destroyed as well. Adds a resource

This method adds aResource to the object, and sets itself as the owner list of the resource.

If a resource with the same type, name and language ID already exists, an exception is raised.

The resource to add Adds a resource and gives it a new autogenerated name

This method tries to find a spare ID to use as a name for the given resource, assigns it to the resource, and adds it.

This method is useful when the name of the resource is not important. E.g. a group resource doesn't care about the names of its sub-resources, so it could use this method to ensure that its sub-resources don't clash with names of other sub-resources of the same type.

If there are no more free IDs for the resource type of the given resource (that is, when the number of resources of the same type of aResource with an ID name is equal to 65536) an exception is raised.

The autogenerated ID of the added resource The resource to add Deletes all resources

This method empties the TResources object destroying all resources.

Searches for a suitable resource reader

This method tries to find a resource reader able to read the stream passed as parameter.

If an extension is specified, only readers matching that extension are tried. The extension is case-insensitive and includes the leading dot, unless the empty string is passed (which means "no extension", e.g. a unix executable, which doesn't have an extension).

If a suitable reader is found, an instance of that reader is returned.

To make a resource reader class known, add that resource reader unit to the uses clause of your program.

If no suitable reader is found, an exception is raised.

An instance of a descendant. The stream to be probed The extension the reader is registered for Moves all resources of another TResources object to itself

This method takes all resources from object aResources and adds them to this object. aResources object is left empty.

If a resource with the same type, name and language ID already exists, an exception is raised.

The TResources object from which resources must be taken Removes a resource

This method searches for a resource based on passed parameters and removes it from the object.

The removed resource is then returned.

If no matching resource is found, an exception is raised.

The removed resource The type of the resource to search for The name of the resource to search for The language ID of the resource to search for The resource to remove The index of the resource to remove Loads the contents of the object from a stream

This method clears the TResources object and loads its contents from the stream passed as parameter.

If a reader is specified, that reader is used. Otherwise, the stream is probed to find a suitable reader.

If CacheData is set to true, the stream will be used as the underlying stream of each resource RawData stream. This means that the stream must not be freed until all resources in the TResources object are freed: this happens when the TResources object is cleared or is loaded again from a different source. If you need to free the stream while there are still resources, disable the copy-on-write mechanism by setting CacheData property to false.

If no reader is passed and probing fails, an exception is raised.

The stream to read from The resource reader to use to read the stream Loads the contents of the object from a file

This method clears the TResources object and loads its contents from the file passed as parameter.

If a reader is specified, that reader is used. Otherwise, the file is probed to find a suitable reader.

If CacheData is set to true, the file will be left open and used as the underlying stream of each resource RawData stream. This means that the file will be open until the TResources object is cleared or is loaded again from a different source. If you want the file to be closed while there are still resources, disable the copy-on-write mechanism by setting CacheData property to false.

Sample code

This code extracts resources from an exe file

var resources : TResources; begin resources:=TResources.Create; resources.LoadFromFile('myexe.exe'); resources.WriteToFile('myexe.res'); resources.Free; end;

If no reader is passed and probing fails, an exception is raised.

The name of file to read from The reader to use to read the file Registers a resource reader class

This class method registers a resource reader class.

When registered, a class is known to TResources class, and can be used by FindReader, LoadFromStream and LoadFromFile methods when probing.

Usually this method is called in the initialization section of the unit implementing a descendant.

A class can be registered multiple times, one for each extension it is able to read. Multiple class can be registered for the same extension (e.g. both a coff and a elf reader can be registered for the .o extension). The extension must include the leading dot unless the empty string is used (which means "no extension", e.g. a unix executable, which doesn't have an extension).

The extension for which the class must be registered The descendant to register Registers a resource writer class

This class method registers a resource writer class.

When registered, a class is known to TResources class, and can be used by WriteToFile method when probing.

Usually this method is called in the initialization section of the unit implementing a descendant.

A class can be registered multiple times, one for each extension it is able to write. Multiple class can be registered for the same extension (e.g. both a coff and a elf writer can be registered for the .o extension) although only the first one found will be used when probing. The extension must include the leading dot unless the empty string is used (which means "no extension", e.g. a unix executable, which doesn't have an extension).

The extension for which the class must be registered The descendant to register Writes the contents of the object to a stream

This method writes the contents of the object to a stream via the specified descendant

The stream to write to The resource writer to use to write the stream Writes the contents of the object to a file

This method writes the contents of the object to a file whose name is passed as parameter.

If a writer is specified, that writer is used. Otherwise, the first registered writer matching the file name extension is used.

If no writer is passed and no suitable writer is found, an exception is raised.

The name of the file to write to The resource writer to use to write to the file The number of resources in the object Indexed array of resources in the object

This property can be used to access all resources in the object.

This array is 0-based: valid elements range from 0 to Count-1.
The index of the resource to access Controls the copy-on-write behaviour of all resources

Changing this property changes CacheData property of all resources contained in the object.

This property affects existing resources and resources that are added or loaded.

By default, CacheData is true.

Protected method to let a reader set a resource DataSize property

This method allows a descendant class to set DataSize property of a resource that is being loaded.

The resource whose DataSize property must be set The value to set the property to Protected method to let a reader set a resource HeaderSize property

This method allows a descendant class to set HeaderSize property of a resource that is being loaded.

The resource whose HeaderSize property must be set The value to set the property to Protected method to let a reader set a resource DataOffset property

This method allows a descendant class to set DataOffset property of a resource that is being loaded.

The resource whose DataOffset property must be set The value to set the property to Protected method to let a reader set a resource RawData property

This method allows a descendant class to set RawData property of a resource that is being loaded.

The resource whose RawData property must be set The value to set the property to Calls another reader's Load method

This method allows a descendant class to call another reader's Load method. This can be useful when a reader needs to use another one.

The reader whose Load method must be called The aResources parameter of Load method The aStream parameter of Load method Adds a resource without updating the internal tree

This protected method is used by descendents of after they add new resources to the internal resource tree used by a object. Calling this method notifies the object about the newly-added resource.

TRootResTreeNode
The TResources object to be notified The resource that has been added to the tree Gets the internal resource tree of a TResources object

This protected method can be used by descendents of to obtain the internal resource tree used by a object. The internal resource tree is an instance of TRootResTreeNode.

Some resource readers can improve their performance if, instead of calling , add themselves resources to the internal tree used by a object.

After adding a resource to a resource tree, a reader must always call AddNoTree method to let the object know about the newly-added resource.
TRootResTreeNode
The object whose tree must be returned The resource tree. It is an instance of TRootResTreeNode. Returns the extensions the reader is registered for

Descendant classes must implement this method to provide access to Extensions property.

The extensions the reader is registered for Returns the description of the reader

Descendant classes must implement this method to provide access to Description property.

The description of the reader Loads resources from a stream

A object invokes this method when it needs to be loaded from a stream, passing itself as the aResources parameter and the stream as the aStream parameter.

aStream position is already correctly set: the reader must start to read from there.

Descendant classes must ensure that the the stream is in a format they recognize, otherwise an exception must be raised.

Each resource is then created, read from the stream and added to the object.

When reading a resource, a reader must:

  • Create the resource via TResourceFactory.CreateResource class method with the correct type and name.
  • Set at least the following resource properties:

    • DataSize, via SetDataSize method.
    • DataOffset, via SetDataSize method. This is the offset of the resource data from the beginning of the stream.
    • RawData. The reader must create a TResourceDataStream object and assign it to the resource via SetRawData method.

If the stream is in a format not recognized by the reader, a exception must be raised.

If the stream ends prematurely, a exception must be raised.

TResourceDataStream
The object to be loaded from the stream The stream which resources must be loaded from Checks whether a stream is in a format the reader recognizes

A object invokes this method when it is searching for a reader able to read a stream, passing that stream as the aStream parameter.

aStream position is already correctly set: the reader must start to read from there.

This method should read the minimum amount of information needed to recognize the contents of a stream as a valid format: it usually means reading a magic number or a file header.

true if the format of the stream is recognized The stream to check Creates a new reader object The extensions of file types the reader is able to read

This property is a string made of space-separated file extensions (each including the leading dot), all lowercase.

This property signals which file types the reader is able to read.

The reader description

This property provides a textual description of the reader, e.g. "FOO resource reader"

Gets the internal resource tree of a TResources object

This protected method can be used by descendents of to obtain the internal resource tree used by a object. The internal resource tree is an instance of TRootResTreeNode.

Some resource writers need to order resources with a tree structure before writing them to a file. Instead of doing this work themselves, they can use the already-ordered internal resource tree of the object they must write.

TRootResTreeNode
The object whose tree must be returned The resource tree. It is an instance of TRootResTreeNode. Returns the extensions the writer is registered for

Descendant classes must implement this method to provide access to Extensions property.

The extensions the writer is registered for Returns the description of the writer

Descendant classes must implement this method to provide access to Description property.

The description of the writer Writes resources to a stream

A object invokes this method when it needs to be written to a stream, passing itself as the aResources parameter and the stream as the aStream parameter.

aStream position is already correctly set: the writer must start to write from there.

A writer must write data in the way specified by the format it supports: usually this means writing a header and all resources contained in the object.

For each resource, a writer should write some information about the resource (like type and name) in a way defined by the format it implements, and the resource data, which is accessible by RawData property of the resource.

The object to be written to the stream The stream which resources must be written to Creates a new writer object The extensions of file types the writer is able to write

This property is a string made of space-separated file extensions (each including the leading dot), all lowercase.

This property signals which file types the writer is able to write.

The writer description

This property provides a textual description of the writer, e.g. "FOO resource writer"