Making custom ramdisk
Unfortunately there is no way of restoring our inverted image if disk0 is mounted, so we have to use a custom ramdisk.
Adding needed binariesThe custom ramdisk has to execute apfs_invert, so we need to make changes to it's filesystem so it will execute our custom binary.
Note: The ramdisk can be either one of the two smaller ".dmg" files present in the ipsw.
Unpack original ramdisk into raw dmg:
img4 -i xxx.xxxxx.xxx.dmg -o ramdisk.dmgAnd mount it:
hdiutil attach ramdisk.dmgCompile restored-hax (thanks to @b1n4r1b01) and sign it using ldid (iOS 10) or ldid2 (iOS 11+):
xcrun -sdk iphoneos clang -arch arm64 restored-hax.c -o restored_hax
ldid(2) -S restored_haxNote: don't forget to change disk0s1s3 in source code if new system is a different partition. Rename original restored_external:
mv /Volumes/ramdisk_name/usr/local/bin/restored_external /Volumes/ramdisk_name/usr/local/bin/restored_external_bakAnd replace it with the compiled binary:
cp -a restored_hax /Volumes/ramdisk_name/usr/local/bin/restored_externalNow pack ramdisk into img4:
img4 -i ramdisk.dmg -o ramdisk -M IM4M -A -T rdsk
Important! if your target iOS system is iOS 12.x or newer, you must also sign the matching trustcache for the ramdisk.
In the Firmware folder of the ipsw, there are three files with a ".trustcache" extension. Use the exact one with the same name as the ramdisk that was just created.
Now we need to sign and apply the rtsc (Restore Trustcache) tag.
img4 -i xxx.xxxxx.xxx.dmg.trustcache -o trustcache.img4 -M IM4M -T rtsc