Windows Metafile


Windows Metafile is an image file format originally designed for Microsoft Windows in the 1990s. The original Windows Metafile format was not device-independent and may contain both vector graphics and bitmap components. It acts in a similar manner to SVG files. WMF files were later superseded by Enhanced Metafiles which did provide for device-independence. EMF files were then themselves enhanced via EMF+ files.
Essentially, a metafile stores a list of records consisting of drawing commands, property definitions and graphics objects to display an image on screen. The drawing commands used are closely related to the commands of the Graphics Device Interface API used for drawing in Microsoft Windows.
There are three major types of metafiles - a WMF is a 16-bit format introduced in Windows 3.0. It is the native vector format for Microsoft Office applications such as Word, PowerPoint, and Publisher. revision 14 of the Windows Metafile Format specification is available for online reading or download as PDF. EMF files, which replaced WMF files, work on the same principle only it is a 32-bit file format that also allows for the embedding of private data within "comment" records. EMF+ is an extension to EMF files and embedded in these comment records, allowing for images and text using commands, objects and properties that are similar to Windows GDI+.

History

The original 16 bit WMF file format was fully specified in volume 4 of the 1992 Windows 3.1 SDK documentation, but that specification was vague about a few details. These manuals were published as printed books available in bookstores with no click through EULA or other unusual licensing restrictions.
Over time the existence of that historic specification was largely forgotten and some alternative implementations resorted to reverse engineering to figure out the file format from existing WMF files, which was difficult and error prone. In September 2006, Microsoft again published the WMF file format specification in a more complete form in the context of the Microsoft Open Specification Promise, promising to not assert patent rights to file format implementors.
Microsoft later deprecated WMF files in favour of 32-bit EMF files as WMF files had real issues with device independence, despite the use of a "placeable" file header which provided basic device independence. Microsoft found that developers who use the format were " application, location, or scaling comments in the metafiles... Others added headers to the metafile that provided various application-specific information", causing major compatibility issues. Thus, in 1992 with Windows NT 3.1, Microsoft introduced the Enhanced Metafile format — a format which was based on the Win32 API and with which they built-in in device independence. — these were also known as NT metafiles. With the release of Windows XP and GDI+, the set of records had to be significantly increased and so Microsoft released EMF+ as an extension to the existing EMF file format.

Metafile structure

WMF, EMF and EMF+ files all consist of a series of records that are played back to produce graphical output. Some records define objects which can specify graphical objects used to determine how graphics should be drawn. Each of these objects are stored in metafiles and are placed into an object table, which tracks the usage of graphic objects while processing the metafile. The object table is an associative array of indexes to graphical object structures defined within the metafile.
WMF and EMF files handle object processing differently to EMF+ records in EMF files. As a WMF and EMF file is being processed, the records are read into an object table once an object is defined. If an object is deleted then the object is released from the table and the identifier can be reused. Notably an object will not be used until it is specifically selected during record playback. This differs for EMF+ files, which also use an associative array via a hashmap which records the object along with an object identifier. However, unlike WMF and EMF files which can delete an object, when a new object is created that has the same index as an existing object, the entry in the table is replaced with the new object. An EMF file also does not need to specifically select an object before it is used.

WMF

WMF files were not originally designed to be device independent, meaning that you could not playback the file on output devices that differed from the original device on which the file was recorded. A partial solution to this issue was invented by Aldus Corporation, who added an additional "placeable" header, called the "APM header", which added a bounding rectable, a metafile version, metafile size, number of objects in the metafile and the size of the largest single record in the metafile. This was later incorporated into the WMF format by Microsoft, starting in Windows 2000.
WMF files are structured by a series of records, starting with a number of control records: the header record, the aforementioned optional placeable record, and finished by an end of file record.
Encapsulated by the control records are the records that make up the image itself. These records work within what is known as the playback device context, which is the collection of properties and objects that make up a device's graphical environment as the metafile is being "played back" onto this output device.
Records other than control records can be largely grouped into bitmap records, drawing records, object records, state records and escape records.

Bitmap records

Bitmap records manage and output bitmap images.
NameDescription
META_BITBLTSpecifies how to do a bit block transfer. These records can specify a bitmap to use as the source, or a region.
META_DIBBITBLTSpecifies how to do a bit block transfer of a device-independent bitmap image. These records can specify a bitmap to use as the source, or a region.
META_DIBSTRETCHBITBLTSpecifies how to do a bit block transfer of a device-independent bitmap image, but allows for expansion or contraction of the image. These records can specify a bitmap to use as the source, or a region.
META_SETDIBTODEVSpecifies color to set a block of pixels in a device-independent bitmap image. These records can specify a bitmap to use as the source, or a region.
META_STRETCHBLTSpecifies how to do a bit block transfer, but allows for expansion or contraction of the image.
META_STRETCHDIBSpecifies how to do a bit block transfer of a device-independent bitmap image, but allows for expansion or contraction of the image. These records can specify a bitmap to use as the source, or a region.

Drawing records

Drawing records produce graphics output.
NameDescription
META_ARCDraws an elliptical arc.
META_CHORDDraws a chord.
META_ELLIPSEDraws an elliptical arc.
META_EXTFLOODFILLFills an area with a brush.
META_EXTTEXTOUTDraw text with font, background color and text color of the playback device context.
META_FILLREGIONFills a region with a specified brush.
META_FLOODFILLFills an area with a brush.
META_FRAMEREGIONDraws a border around a region of the page with a brush.
META_INVERTREGIONPaints a region of the graphic with inverted colors.
META_LINETODraws a half-open line from the drawing position defined in the playback device context to a specified point.
META_PAINTREGIONPaint a region with the current brush specified in the playback device context.
META_PATBLTPaint a region with the current brush specified in the playback device context and then combine the brush color and surface color using a raster operation.
META_PIEDraw a pie-shaped wedge bounded by the intersection of an ellipse and two radials — the line is set via the pen set via the playback device context, and the area bounded by the pie shape is filled in by the current brush of the playback device context.
META_POLYLINEDraws a series of line segnments by connecting the points in a specified array.
META_POLYGONPaints a polygon consisting of two or more vertices connected by straight lines. The polygon is outlined by using the pen and filled by using the brush and polygon fill mode that are defined in the playback device context.
META_POLYPOLYGONPaints a series of closed polygons, which may overlap. Each polygon is outlined by using the pen and filled by using the brush and polygon fill mode that are defined in the playback device context.
META_RECTANGLEPaints a rectangle, which is outlined by using the pen and filled by using the brush and is filled by using the brush that is defined in the playback device context.
META_ROUNDRECTPaints a rectangle with rounded corners. The rectangle is outlined by using the pen and filled by using the brush and is filled by using the brush that is defined in the playback device context.
META_SETPIXELSets the pixel at the specified coordinates to the specified color.
META_TEXTOUTOutputs a character string at the specified location by using the font, background color, and text color that are defined in the playback device context.

Object records

Object records create and manage graphics objects. In WMF files there are two broad categories of objects - graphics objects and structure objects. Structure objects are not explicitly created or deleted in a WMF, they are instead of complex structures. For example, the BitmapCoreHeader contains information about the dimensions and color format of a device-independent bitmap, which is itself part of a DeviceIndependentBitmap object. A graphics object, however, specifies parameters for graphics output and during playback of the WMF it sets up the playback device context.
Graphics objects can be brushes, fonts, palettes, pens, and regions.
NameDescription
META_CREATEBRUSHINDIRECTCreates a brush object from a LogBrush object.
META_CREATEFONTINDIRECTCreates a brush object from a font object.
META_CREATEPALETTECreates a palette object.
META_CREATEPATTERNBRUSHCreates a brush object from a LogBrush object.
META_CREATEPENINDIRECTCreates a pen object.
META_CREATEREGIONCreates a region object.
META_DELETEOBJECTDelete a object.
META_CREATEBRUSHINDIRECTCreates a brush object from a LogBrush object.
META_DIBCREATEPATTERNBRUSHCreates a brush object from a device-independent bitmap.
META_SELECTCLIPREGIONSpecifies the region object that will be the current clipping region.
META_SELECTOBJECTSelects the object that will be the current object for the playback device context, which works on all graphics objects except palette objects, which must be set with META_SELECTPALETTE.
META_SELECTPLAETTESelects the logical palette for the playback device context.

State records

State records manage the graphics properties of the playback device context.
NameDescription
META_ANIMATEPALETTERedefines entries in the logical palette that is defined in the playback device context with a specified Palette Object.
META_EXCLUDECLIPRECTSets the clipping region that is defined in the playback device context to the existing clipping region minus a specified rectangle.
META_INTERSECTCLIPRECTSets the clipping region that is defined in the playback device context to the intersection of the existing clipping region and a specified rectangle.
META_MOVETOSets the output position in the playback device context to a specified point.
META_OFFSETCLIPRGNMoves the clipping region that is defined in the playback device context by specified offsets.
META_OFFSETVIEWPORTORGMoves the viewport origin in the playback device context by specified horizontal and vertical offsets.
META_OFFSETWINDOWORGMoves the output window origin in the playback device context by specified horizontal and vertical offsets.
META_REALIZEPALETTEMaps entries from the logical palette that is defined in the playback device context to the system palette.
META_RESIZEPALETTERedefines the size of the logical palette that is defined in the playback device context.
META_RESTOREDCRestores the playback device context from a previously saved device context.
META_SAVEDCSaves the playback device context for later retrieval.
META_SCALEVIEWPORTEXTScales the horizontal and vertical extents of the viewport that is defined in the playback device context using the ratios formed by specified multiplicands and divisors.
META_SCALEWINDOWEXTScales the horizontal and vertical extents of the output window that is defined in the playback device context using the ratios formed by specified multiplicands and divisors.
META_SETBKCOLORSets the background color in the playback device context to a specified color.
META_SETBKMODESets the background mix mode in the playback device context.
META_SETLAYOUTDefines the layout orientation in the playback device context.
META_SETMAPMODEDefines the mapping mode in the playback device context.
META_SETMAPPERFLAGSDefines the algorithm that the font mapper uses when it maps logical fonts to physical fonts.
META_SETPALENTRIESDefines RGB color values in a range of entries in the logical palette that is defined in the playback device context.
META_SETPOLYFILLMODEDefines polygon fill mode in the playback device context for graphics operations that fill polygons.
META_SETRELABSUnused record.
META_SETROP2Defines the foreground raster operation mixing mode in the playback device context.
META_SETSTRETCHBLTMODEDefines the bitmap stretching mode in the playback device context.
META_SETTEXTALIGNDefines text-alignment values in the playback device context.
META_SETTEXTCHAREXTRADefines inter-character spacing for text justification in the playback device context.
META_SETTEXTCOLORDefines the text foreground color in the playback device context.
META_SETTEXTJUSTIFICATIONDefines the amount of space to add to break characters in a string of justified text.
META_SETVIEWPORTEXTDefines the horizontal and vertical extents of the viewport in the playback device context.
META_SETVIEWPORTORGDefines the viewport origin in the playback device context.
META_SETWINDOWEXTDefines the horizontal and vertical extents of the output window in the playback device context.
META_SETWINDOWORGDefines the output window origin in the playback device context.

Escape records

Escape records are a means to extend metafile functionality via records that are not otherwise defined as a WMF record type. Each escape record contains a record function, an escape function and potentially escape data.
The following escape records make up a WMF file.
NameDescription
ABORTDOCStops processing the current document.
BEGIN_PATHOpens a path.
CHECK_JPEGFORMATDetermines whether it can handle the given JPEG image.
CHECK_PNGFORMATDetermines whether it can handle the given PNG image.
CLIP_TO_PATHApplies a function to the current PostScript clipping path.
CLOSE_CHANNELSame as ENDDOC.
DOWNLOAD_FACESets the font face name on the output device.
DOWNLOAD_HEADERDownloads sets of PostScript procedures.
DRAW_PATTERNRECTDraws a rectangle with a defined pattern.
ENCAPSULATED_POSTSCRIPTSends arbitrary encapsulated PostScript data directly to the printer driver.
END_PATHEnds a path.
ENDDOCNotifies the printer driver that a new print job is ending.
EPS_PRINTINGIndicates the start and end of EPS printing.
EXTTEXTOUTDraws text using the currently selected font, background color, and text color.
GET_COLORTABLEGets color table values from the printer driver.
GET_DEVICEUNITSGets the device units currently configured on the output device.
GET_EXTENDED_TEXTMETRICSGets the extended text metrics that are currently configured on the printer driver.
GET_FACENAMEGets the font face name currently configured on the output device.
GET_PAIRKERNTABLEGets the font kern table currently defined on the output device.
GET_PHYSPAGESIZERetrieves the physical page size currently selected on the output device.
GET_PRINTINGOFFSETRetrieves the offset from the upper-left corner of the physical page where the actual printing or drawing begins.
GET_PS_FEATURESETTINGQueries the printer driver for information about PostScript features supported on the output device.
GET_SCALINGFACTORRetrieves the scaling factors for the x-axis and the y-axis of a printer.
META_ESCAPE_ENHANCED_METAFILEUsed to embed an EMF metafile within a WMF metafile.
METAFILE_DRIVERQueries the printer driver about its support for metafiles on the output device.
NEWFRAMENotifies the printer driver that the application has finished writing to a page.
NEXTBANDNotifies the printer driver that the application has finished writing to a band.
PASSTHROUGHPasses through arbitrary data to the printer driver.
POSTSCRIPT_DATASends arbitrary PostScript data to the output device.
POSTSCRIPT_IDENTIFYSets the printer driver to either PostScript-centric or GDI-centric mode.
POSTSCRIPT_IGNORENotifies the output device to ignore PostScript data.
POSTSCRIPT_INJECTIONInserts a block of raw data into a PostScript stream.
POSTSCRIPT_PASSTHROUGHSends arbitrary data directly to a printer driver, which is expected to process this data only when in PostScript mode.
OPEN_CHANNELActs the same as STARTDOC, with a NULL document and output filename, and data in raw mode.
QUERY_DIBSUPPORTQueries the printer driver about its support for DIBs on the output device.
QUERY_ESCSUPPORTQueries the printer driver to determine whether a specific WMF escape function is supported on the output device.
SET_COLORTABLESets color table values.
SET_COPYCOUNTSets the number of copies.
SET_LINECAPSpecifies the line-ending mode to use in drawing to the output device.
SET_LINEJOINSpecifies the line-joining mode to use in drawing to the output device.
SET_MITERLIMITSets the limit for the length of miter joins to use in drawing to the output device.
SPCLPASSTHROUGH2Enables documents to include private procedures and other arbitrary data in documents.
STARTDOCNotifies the printer driver that a new print job is starting.

There was a major vulnerability found in escape records around the Abort escape record, which stores the abort procedure code within the record itself. This affected Windows systems and the Wine project. According to Secunia, "The vulnerability is caused due to an error in the handling of Windows Metafile files containing specially crafted SETABORTPROC 'Escape' records. Such records allow arbitrary user-defined function to be executed when the rendering of a WMF file fails." According to the Windows 3.1 SDK documentation, the SETABORTPROC escape was obsoleted and replaced by the function of the same name in Windows 3.1, long before the WMF vulnerability was discovered. However the obsoleted escape code was retained for compatibility with 16 bit programs written for Windows 3.0. This change happened at approximately the same time as Microsoft was creating the 32 bit reimplementation of GDI for Windows NT, and it is likely that the vulnerability occurred during this effort.
After Steve Gibson from Gibson Research Corporation accused Microsoft of deliberately implementing a backdoor into their code, Mark Russinovich provided a rebuttal, and stated that:
Peter Ferrie of Symantec Security Response, USA also disagreed with Gibson, noting that:

EMF

EMF files have three possible versions of headers. The original headers is just a container for images, the second and third version encapsulates the original header and contains a pixel format record and support for OpenGL records, and the third version encapsulates the second header extension and increases EMF accuracy and scalability of EMFs as it adds the ability to measure distances of device surfaces using the metric system.
Each EMF header starts with an EMR_HEADER record, and records the relevant properties of the device on which the metafile image was recorded. The original EMF header has an 80 byte header and an optional variable length description string. Other metafiles contain extension fields, which encapsulate the original header. EmfMetafileHeaderExtension1 is a record that is inserted directly after the original EMF header, specifies whether there is a pixel format descriptor and the offset to the descriptor object within the header, as well as a field that specifies if OpenGL records exist in the metafile. The pixel format descriptor specifies the capabilities of the drawing surface and whether a pixel is encoded in RGBA or is an index into a color table. EmfMetafileHeaderExtension2 is a record that is inserted directly after the EmfMetafileHeaderExtension1 record, and it contains two fields with the X and Y values to measure the device surface in micrometers.
Like WMF files, records can be classified by function, however there are more record types in EMF files than there are in WMF files. Records can be classified as control, bitmap, clipping, comment, drawing, escape, object creation, object manipulation, OpenGL, path bracket, state and transform records.

EMF+

With the release of Windows XP, the Enhanced Metafile Format Plus Extensions format was introduced. EMF+ provides a way to serialize calls to the GDI+ API in the same way that WMF/EMF stores calls to GDI.
There are also compressed versions of Windows Metafiles known as Compressed Windows Metafile and Compressed Windows Enhanced Metafile, which are basically gzip compressed WMF and EMF files correspondingly.

Implementations

The WMF format was designed to be executed by the Windows GDI layer in order to restore the image, but as the WMF binary files contain the definition of the GDI graphic primitives that constitute this image, it is possible to design alternative libraries that render WMF binary files or convert them into other graphic formats.