How to extract "flat" (non-bundled) pkg files and their Payload

Normally macOS Installer uses two pkg formats: either a bundle (a directory with an extension .pkg) or a flat format (a compressed file with an extension .pkg)

They can be distinguished in a terminal using the ls -l command, or by right(control)-clicking on them and checking for "Show Package Contents" menu item.

Either way, sometimes it is undesirable to launch it right away (especially if it is not signed or was downloaded from a suspicious chinese website) - you may not know what the installer actually does on your system.

In that case, it may be useful to extract the contents of such package and inspect it.

Bundled installer packages

If you are faced with an older package format, you may check its contents with a right mouse click:

Usually it consists of a number of files: Payload, Scripts, Description of the package, A bill-of-materials (BOM) file (which basically contains a list of files to install, permissions to set, checksums, dates and so on - see man bom and man mkbom for details). We are interested primarily in the Payload and Scripts files.

The Payload is just an archive, and contains a hierarchy of files to be installed. It is saved as a cpio archive and compressed with gzip. So, we can extract this hierarchy into the current directory using the following command:

cat Payload | gunzip -dc |cpio -i

The Scripts is exactly the same as the Payload, except that it contains the scripts to be executed on different stages of the installation process: before (preinstall) and after (postinstall) the Payload is installed:

cat Scripts | gunzip -dc |cpio -i

If you want to reassemble modified Scripts or Payload hierarchies back into the package, you can do it the following way:

find ./ | cpio -o | gzip -c > Payload
mkbom Bom

Flat installer packages

A newer "flat" package is actually just a .xar archive, with a .pkg extension.

So, to extract its contents, you can just enter:

xar -xf ThePackage.pkg

Later, you can re-assemble the modified contents back into a flat .pkg package:

xar -cf NewPackage.pkg *

Other than that, the packages can contain other packages, plugin bundles (which contain binary executables), resources (images, texts, and so on) and regular archives (.gz, .tar and others).