proj_name
stringclasses
26 values
relative_path
stringlengths
42
188
class_name
stringlengths
2
53
func_name
stringlengths
2
49
masked_class
stringlengths
68
178k
func_body
stringlengths
56
6.8k
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/dmg/DmgLoader64.java
DmgLoader64
load
class DmgLoader64 extends DmgLoader { public DmgLoader64(File dmgDir, File rootDir) { super(dmgDir, rootDir); } @Override public LoadedDmg load(EmulatorConfigurator configurator, String... loads) {<FILL_FUNCTION_BODY>} }
try { return load64(configurator, loads); } catch (IOException e) { throw new IllegalStateException(e); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/dmg/DmgResolver.java
DmgResolver
resolve
class DmgResolver implements IOResolver<DarwinFileIO> { private final File dmgDir; DmgResolver(File dmgDir) { this.dmgDir = dmgDir; } @Override public FileResult<DarwinFileIO> resolve(Emulator<DarwinFileIO> emulator, String pathname, int oflags) {<FILL_FUNCTION_BODY>} }
pathname = FilenameUtils.normalize(pathname, true); String dmgDir = FilenameUtils.normalize(this.dmgDir.getAbsolutePath(), true); if (pathname.startsWith(dmgDir)) { File file = new File(pathname); if (file.exists()) { return file.isFile() ? FileResult.<DarwinFileIO>success(new SimpleFileIO(oflags, file, pathname)) : FileResult.<DarwinFileIO>success(new DirectoryFileIO(oflags, pathname, file)); } } return null;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/dmg/LoadedDmg.java
LoadedDmg
callEntry
class LoadedDmg { private final Emulator<DarwinFileIO> emulator; private final Module executable; private final String bundleIdentifier; private final String bundleVersion; LoadedDmg(Emulator<DarwinFileIO> emulator, Module executable, String bundleIdentifier, String bundleVersion) { this.emulator = emulator; this.executable = executable; this.bundleIdentifier = bundleIdentifier; this.bundleVersion = bundleVersion; } public String getBundleIdentifier() { return bundleIdentifier; } public String getBundleVersion() { return bundleVersion; } private boolean callFinishLaunchingWithOptions; public void setCallFinishLaunchingWithOptions(boolean callFinishLaunchingWithOptions) { this.callFinishLaunchingWithOptions = callFinishLaunchingWithOptions; } private String systemName; // iPhone OS private String systemVersion; // 8.3 private String model; // iPhone private String name; // My iPhone private String identifierForVendor; private String advertisingIdentifier; private String carrierName; public void callEntry() {<FILL_FUNCTION_BODY>} public Module getExecutable() { return executable; } public Emulator<DarwinFileIO> getEmulator() { return emulator; } public void setSystemName(String systemName) { this.systemName = systemName; } public void setSystemVersion(String systemVersion) { this.systemVersion = systemVersion; } public void setModel(String model) { this.model = model; } public void setName(String name) { this.name = name; } public void setIdentifierForVendor(String identifierForVendor) { this.identifierForVendor = identifierForVendor; } public void setAdvertisingIdentifier(String advertisingIdentifier) { this.advertisingIdentifier = advertisingIdentifier; } public void setCarrierName(String carrierName) { this.carrierName = carrierName; } }
ArgsRequest args = new ArgsRequest(); args.setCallFinishLaunchingWithOptions(callFinishLaunchingWithOptions); args.setSystemName(systemName); args.setSystemVersion(systemVersion); args.setModel(model); args.setName(name); args.setIdentifierForVendor(identifierForVendor); args.setAdvertisingIdentifier(advertisingIdentifier); args.setCarrierName(carrierName); executable.callEntry(emulator, "-args", JSON.toJSONString(args));
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/file/ByteArrayFileIO.java
ByteArrayFileIO
read
class ByteArrayFileIO extends BaseDarwinFileIO { protected final byte[] bytes; protected final String path; public ByteArrayFileIO(int oflags, String path, byte[] bytes) { super(oflags); this.path = path; this.bytes = bytes; } private int pos; @Override public void close() { pos = 0; } @Override public int write(byte[] data) { throw new UnsupportedOperationException(); } @Override public int read(Backend backend, Pointer buffer, int count) {<FILL_FUNCTION_BODY>} @Override public int lseek(int offset, int whence) { switch (whence) { case SEEK_SET: pos = offset; return pos; case SEEK_CUR: pos += offset; return pos; case SEEK_END: pos = bytes.length + offset; return pos; } return super.lseek(offset, whence); } @Override protected byte[] getMmapData(long addr, int offset, int length) { if (offset == 0 && length == bytes.length) { return bytes; } else { byte[] data = new byte[length]; System.arraycopy(bytes, offset, data, 0, data.length); return data; } } @Override public int ioctl(Emulator<?> emulator, long request, long argp) { return 0; } @Override public int fstat(Emulator<?> emulator, StatStructure stat) { int blockSize = emulator.getPageAlign(); stat.st_dev = 1; stat.st_mode = (short) (IO.S_IFREG | 0x777); stat.setSize(bytes.length); stat.setBlockCount(bytes.length / blockSize); stat.st_blksize = blockSize; stat.st_ino = 7; stat.st_uid = 0; stat.st_gid = 0; stat.setLastModification(System.currentTimeMillis()); stat.pack(); return 0; } @Override public String toString() { return path; } @Override public String getPath() { return path; } }
if (pos >= bytes.length) { return 0; } int remain = bytes.length - pos; if (count > remain) { count = remain; } buffer.write(0, bytes, pos, count); pos += count; return count;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/file/DirectoryFileIO.java
DirectoryFileIO
setxattr
class DirectoryFileIO extends BaseDarwinFileIO { public static class DirectoryEntry { private final boolean isFile; private final String name; public DirectoryEntry(boolean isFile, String name) { this.isFile = isFile; this.name = name; } } private static DirectoryEntry[] createEntries(File dir) { List<DirectoryEntry> list = new ArrayList<>(); File[] files = dir.listFiles(new UnidbgFileFilter()); if (files != null) { Arrays.sort(files); for (File file : files) { list.add(new DirectoryEntry(file.isFile(), file.getName())); } } return list.toArray(new DirectoryEntry[0]); } private final String path; private final List<DirectoryEntry> entries; private final File dir; public DirectoryFileIO(int oflags, String path, File dir) { this(oflags, path, dir, createEntries(dir)); } public DirectoryFileIO(int oflags, String path, DirectoryEntry... entries) { this(oflags, path, null, entries); } public DirectoryFileIO(int oflags, String path, File dir, DirectoryEntry... entries) { super(oflags); this.path = path; this.dir = dir; this.entries = new ArrayList<>(); this.entries.add(new DirectoryEntry(false, ".")); this.entries.add(new DirectoryEntry(false, "..")); if (entries != null) { Collections.addAll(this.entries, entries); } } @Override public int fstatfs(StatFS statFS) { return 0; } @Override public int fstat(Emulator<?> emulator, StatStructure stat) { stat.st_dev = 1; stat.st_mode = IO.S_IFDIR | 0x777; stat.setSize(0); stat.st_blksize = 0; stat.st_ino = 7; stat.pack(); return 0; } @Override public void close() { } @Override public String toString() { return path; } @Override public int fcntl(Emulator<?> emulator, int cmd, long arg) { if (cmd == F_GETPATH) { UnidbgPointer pointer = UnidbgPointer.pointer(emulator, arg); if (pointer != null) { pointer.setString(0, getPath()); } return 0; } return super.fcntl(emulator, cmd, arg); } @Override public String getPath() { return path; } @Override public int getdirentries64(Pointer buf, int bufSize) { int offset = 0; for (Iterator<DirectoryFileIO.DirectoryEntry> iterator = this.entries.iterator(); iterator.hasNext(); ) { DirectoryFileIO.DirectoryEntry entry = iterator.next(); byte[] data = entry.name.getBytes(StandardCharsets.UTF_8); long d_reclen = ARM.alignSize(data.length + 24, 8); if (offset + d_reclen >= bufSize) { break; } Dirent dirent = new Dirent(buf.share(offset)); dirent.d_fileno = 1; dirent.d_reclen = (short) d_reclen; dirent.d_type = entry.isFile ? Dirent.DT_REG : Dirent.DT_DIR; dirent.d_namlen = (short) (data.length); dirent.d_name = Arrays.copyOf(data, data.length + 1); dirent.pack(); offset += d_reclen; iterator.remove(); } return offset; } @Override public int listxattr(Pointer namebuf, int size, int options) { if (dir == null) { throw new UnsupportedOperationException("path=" + path + ", options=0x" + Integer.toHexString(options)); } return listxattr(dir, namebuf, size); } @Override public int removexattr(String name) { if (dir == null) { throw new UnsupportedOperationException("path=" + path + ", name=" + name); } return removexattr(dir, name); } @Override public int setxattr(String name, byte[] data) {<FILL_FUNCTION_BODY>} @Override public int getxattr(Emulator<?> emulator, String name, Pointer value, int size) { if (dir == null) { throw new UnsupportedOperationException("path=" + path + ", name=" + name); } return getxattr(emulator, dir, name, value, size); } @Override public int chmod(int mode) { if (dir == null) { throw new UnsupportedOperationException("path=" + path + ", mode=0x" + Integer.toHexString(mode)); } return chmod(dir, mode); } @Override public int chown(int uid, int gid) { if (dir == null) { throw new UnsupportedOperationException("path=" + path + ", uid=" + uid + ", gid=" + gid); } return chown(dir, uid, gid); } @Override public int chflags(int flags) { if (dir == null) { throw new UnsupportedOperationException("path=" + path + ", flags=0x" + Integer.toHexString(flags)); } return chflags(dir, flags); } }
if (dir == null) { throw new UnsupportedOperationException("path=" + path + ", name=" + name); } return setxattr(dir, name, data);
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/file/DriverFileIO.java
DriverFileIO
create
class DriverFileIO extends BaseDarwinFileIO implements NewFileIO, DarwinFileIO { public static DriverFileIO create(Emulator<?> emulator, int oflags, String pathname) {<FILL_FUNCTION_BODY>} private final String path; @SuppressWarnings("unused") DriverFileIO(Emulator<?> emulator, int oflags, String path) { super(oflags); this.path = path; } @Override public void close() { } @Override public int write(byte[] data) { throw new AbstractMethodError(); } @Override public int read(Backend backend, Pointer buffer, int count) { throw new AbstractMethodError(); } @Override public int ioctl(Emulator<?> emulator, long request, long argp) { return super.ioctl(emulator, request, argp); } @Override public int fstat(Emulator<?> emulator, StatStructure stat) { return 0; } @Override public int fstatfs(StatFS statFS) { throw new UnsupportedOperationException(); } @Override public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) { throw new UnsupportedOperationException(); } @Override public int getdirentries64(Pointer buf, int bufSize) { throw new UnsupportedOperationException(); } @Override public String toString() { return path; } }
if ("/dev/urandom".equals(pathname) || "/dev/random".equals(pathname) || "/dev/srandom".equals(pathname)) { return new RandomFileIO(emulator, pathname); } if ("/dev/null".equals(pathname)) { return new DriverFileIO(emulator, oflags, pathname); } return null;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/file/DumpFileIO.java
DumpFileIO
write
class DumpFileIO extends BaseDarwinFileIO implements DarwinFileIO { private final int fd; public DumpFileIO(int fd) { super(0); this.fd = fd; } @Override public int write(byte[] data) {<FILL_FUNCTION_BODY>} @Override public void close() { } @Override public FileIO dup2() { return this; } @Override public int fstat(Emulator<?> emulator, StatStructure stat) { throw new UnsupportedOperationException(); } @Override public int fstatfs(StatFS statFS) { throw new UnsupportedOperationException(); } @Override public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) { throw new UnsupportedOperationException(); } @Override public int getdirentries64(Pointer buf, int bufSize) { throw new UnsupportedOperationException(); } }
Inspector.inspect(data, "Dump for fd: " + fd); return data.length;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/file/JarEntryFileIO.java
JarEntryFileIO
fstat
class JarEntryFileIO extends BaseDarwinFileIO { private final String path; private final File jarFile; private final JarEntry entry; public JarEntryFileIO(int oflags, String path, File jarFile, JarEntry entry) { super(oflags); this.path = path; this.jarFile = jarFile; this.entry = entry; } @Override public int fcntl(Emulator<?> emulator, int cmd, long arg) { if (cmd == F_GETPATH) { UnidbgPointer pointer = UnidbgPointer.pointer(emulator, arg); if (pointer != null) { pointer.setString(0, getPath()); } return 0; } return super.fcntl(emulator, cmd, arg); } private int pos; private JarFile openedJarFile; @Override public void close() { pos = 0; if (openedJarFile != null) { com.alibaba.fastjson.util.IOUtils.close(openedJarFile); openedJarFile = null; } } @Override public int read(Backend backend, Pointer buffer, int count) { try { if (pos >= entry.getSize()) { return 0; } if (openedJarFile == null) { openedJarFile = new JarFile(this.jarFile); } int remain = (int) entry.getSize() - pos; if (count > remain) { count = remain; } try (InputStream inputStream = openedJarFile.getInputStream(entry)) { if (inputStream.skip(pos) != pos) { throw new IllegalStateException(); } buffer.write(0, IOUtils.toByteArray(inputStream, count), 0, count); } pos += count; return count; } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int write(byte[] data) { throw new UnsupportedOperationException(); } @Override public int lseek(int offset, int whence) { switch (whence) { case SEEK_SET: pos = offset; return pos; case SEEK_CUR: pos += offset; return pos; case SEEK_END: pos = (int) entry.getSize() + offset; return pos; } return super.lseek(offset, whence); } @Override protected byte[] getMmapData(long addr, int offset, int length) { try (JarFile jarFile = new JarFile(this.jarFile); InputStream inputStream = jarFile.getInputStream(entry)) { if (offset == 0 && length == entry.getSize()) { return IOUtils.toByteArray(inputStream); } else { if (inputStream.skip(offset) != offset) { throw new IllegalStateException(); } return IOUtils.toByteArray(inputStream, length); } } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int ioctl(Emulator<?> emulator, long request, long argp) { return 0; } @Override public int fstat(Emulator<?> emulator, StatStructure stat) {<FILL_FUNCTION_BODY>} @Override public int listxattr(Pointer namebuf, int size, int options) { return 0; } @Override public int fstatfs(StatFS statFS) { statFS.f_iosize = (int) entry.getSize(); statFS.pack(); return 0; } @Override public String toString() { return path; } @Override public String getPath() { return path; } }
int blockSize = emulator.getPageAlign(); stat.st_dev = 1; stat.st_mode = (short) (IO.S_IFREG | 0x777); stat.setSize(entry.getSize()); stat.setBlockCount(entry.getSize() / blockSize); stat.st_blksize = blockSize; stat.st_ino = 7; stat.st_uid = 0; stat.st_gid = 0; stat.setLastModification(System.currentTimeMillis()); stat.pack(); return 0;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/file/LocalDarwinUdpSocket.java
LocalDarwinUdpSocket
connect
class LocalDarwinUdpSocket extends LocalUdpSocket { private static final Log log = LogFactory.getLog(LocalDarwinUdpSocket.class); public LocalDarwinUdpSocket(Emulator<?> emulator) { super(emulator); } @Override public int connect(Pointer addr, int addrlen) {<FILL_FUNCTION_BODY>} @Override protected int connect(String path) { emulator.getMemory().setErrno(UnixEmulator.EPERM); return -1; } @Override public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) { throw new UnsupportedOperationException(); } @Override public int getdirentries64(Pointer buf, int bufSize) { throw new UnsupportedOperationException(); } }
String path = addr.getString(2); log.debug("connect path=" + path); return connect(path);
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/file/LocalUdpSocket.java
LocalUdpSocket
connect
class LocalUdpSocket extends SocketIO implements FileIO { private static final Log log = LogFactory.getLog(LocalUdpSocket.class); protected interface UdpHandler { void handle(byte[] request) throws IOException; } protected final Emulator<?> emulator; protected LocalUdpSocket(Emulator<?> emulator) { this.emulator = emulator; } protected UdpHandler handler; @Override public void close() { handler = null; } @Override public int write(byte[] data) { try { handler.handle(data); return data.length; } catch (IOException e) { throw new IllegalStateException(e); } } protected abstract int connect(String path); @Override public int connect(Pointer addr, int addrlen) {<FILL_FUNCTION_BODY>} @Override protected int getTcpNoDelay() { throw new AbstractMethodError(); } @Override protected void setTcpNoDelay(int tcpNoDelay) { throw new AbstractMethodError(); } @Override protected void setReuseAddress(int reuseAddress) { throw new AbstractMethodError(); } @Override protected void setKeepAlive(int keepAlive) { throw new AbstractMethodError(); } @Override protected void setSocketRecvBuf(int recvBuf) { throw new AbstractMethodError(); } @Override protected InetSocketAddress getLocalSocketAddress() { throw new AbstractMethodError(); } @Override protected int connect_ipv6(Pointer addr, int addrlen) { throw new AbstractMethodError(); } @Override protected int connect_ipv4(Pointer addr, int addrlen) { throw new AbstractMethodError(); } }
short sa_family = addr.getShort(0); if (sa_family != AF_LOCAL) { throw new UnsupportedOperationException("sa_family=" + sa_family); } String path = addr.getString(2); log.debug("connect sa_family=" + sa_family + ", path=" + path); return connect(path);
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/file/RandomFileIO.java
RandomFileIO
read
class RandomFileIO extends DriverFileIO { public RandomFileIO(Emulator<?> emulator, String path) { super(emulator, IOConstants.O_RDONLY, path); } @Override public int read(Backend backend, Pointer buffer, int count) {<FILL_FUNCTION_BODY>} protected void randBytes(byte[] bytes) { ThreadLocalRandom.current().nextBytes(bytes); } }
int total = 0; byte[] buf = new byte[Math.min(0x1000, count)]; randBytes(buf); Pointer pointer = buffer; while (total < count) { int read = Math.min(buf.length, count - total); pointer.write(0, buf, 0, read); total += read; pointer = pointer.share(read); } return total;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/file/Stdin.java
Stdin
read
class Stdin extends BaseDarwinFileIO implements DarwinFileIO { public Stdin(int oflags) { super(oflags); stdio = true; } @Override public void close() { } @Override public int write(byte[] data) { throw new AbstractMethodError(new String(data)); } @Override public int read(Backend backend, Pointer buffer, int count) {<FILL_FUNCTION_BODY>} @Override public FileIO dup2() { return this; } @Override public int ioctl(Emulator<?> emulator, long request, long argp) { return 0; } @Override public int fstat(Emulator<?> emulator, StatStructure stat) { throw new UnsupportedOperationException(); } @Override public int fstatfs(StatFS statFS) { throw new UnsupportedOperationException(); } @Override public String toString() { return "stdin"; } @Override public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) { throw new UnsupportedOperationException(); } @Override public int getdirentries64(Pointer buf, int bufSize) { throw new UnsupportedOperationException(); } }
try { byte[] data = new byte[count]; int read = System.in.read(data, 0, count); if (read <= 0) { return read; } buffer.write(0, Arrays.copyOf(data, read), 0, read); return read; } catch (IOException e) { throw new IllegalStateException(e); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/file/Stdout.java
Stdout
write
class Stdout extends SimpleFileIO { private static final Log log = LogFactory.getLog(Stdout.class); private final boolean err; private final PrintStream out; private final StdoutCallback callback; public Stdout(int oflags, File file, String path, boolean err, StdoutCallback callback) { super(oflags, file, path); this.callback = callback; this.err = err; out = err ? System.err : System.out; if (log.isDebugEnabled()) { setDebugStream(err ? System.err : System.out); } stdio = true; } @Override public void close() { super.close(); IOUtils.close(output); } private RandomAccessFile output; @Override public int write(byte[] data) {<FILL_FUNCTION_BODY>} @Override public int lseek(int offset, int whence) { try { switch (whence) { case FileIO.SEEK_SET: output.seek(offset); return (int) output.getFilePointer(); case FileIO.SEEK_CUR: output.seek(output.getFilePointer() + offset); return (int) output.getFilePointer(); } } catch (IOException e) { throw new IllegalStateException(e); } return super.lseek(offset, whence); } @Override public int ftruncate(int length) { try { output.getChannel().truncate(length); return 0; } catch (IOException e) { throw new IllegalStateException(e); } } @Override public FileIO dup2() { Stdout dup = new Stdout(0, file, path, err, callback); dup.debugStream = debugStream; dup.op = op; dup.oflags = oflags; return dup; } }
try { if (output == null) { output = new RandomAccessFile(file, "rw"); output.getChannel().truncate(0); } if (debugStream != null) { debugStream.write(data); } if (log.isWarnEnabled()) { out.write(data); out.flush(); } if (callback != null) { callback.notifyOut(data, err); } output.write(data); return data.length; } catch (IOException e) { throw new IllegalStateException(e); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/file/UdpSocket.java
UdpSocket
sendto
class UdpSocket extends SocketIO implements FileIO { private static final Log log = LogFactory.getLog(UdpSocket.class); private final Emulator<?> emulator; private final DatagramSocket datagramSocket; public UdpSocket(Emulator<?> emulator) { this.emulator = emulator; try { this.datagramSocket = new DatagramSocket(); } catch (SocketException e) { throw new IllegalStateException(e); } if (emulator.getSyscallHandler().isVerbose()) { System.out.printf("Udp opened '%s' from %s%n", this, emulator.getContext().getLRPointer()); } } @Override public String toString() { return datagramSocket.toString(); } @Override public void close() { this.datagramSocket.close(); } @Override protected int connect_ipv6(Pointer addr, int addrlen) { if (log.isDebugEnabled()) { byte[] data = addr.getByteArray(0, addrlen); Inspector.inspect(data, "addr"); } int sa_family = addr.getShort(0); if (sa_family != AF_INET6) { throw new AbstractMethodError("sa_family=" + sa_family); } try { int port = Short.reverseBytes(addr.getShort(2)) & 0xffff; InetSocketAddress address = new InetSocketAddress(InetAddress.getByAddress(addr.getByteArray(4, 16)), port); datagramSocket.connect(address); return 0; } catch (IOException e) { log.debug("connect ipv6 failed", e); emulator.getMemory().setErrno(UnixEmulator.ECONNREFUSED); return -1; } } @Override protected int connect_ipv4(Pointer addr, int addrlen) { if (log.isDebugEnabled()) { byte[] data = addr.getByteArray(0, addrlen); Inspector.inspect(data, "addr"); } int sa_family = addr.getShort(0); if (sa_family != AF_INET) { throw new AbstractMethodError("sa_family=" + sa_family); } try { int port = Short.reverseBytes(addr.getShort(2)) & 0xffff; InetSocketAddress address = new InetSocketAddress(InetAddress.getByAddress(addr.getByteArray(8, 4)), port); datagramSocket.connect(address); return 0; } catch (IOException e) { log.debug("connect ipv4 failed", e); emulator.getMemory().setErrno(UnixEmulator.ECONNREFUSED); return -1; } } @Override protected InetSocketAddress getLocalSocketAddress() { return (InetSocketAddress) datagramSocket.getLocalSocketAddress(); } @Override public int write(byte[] data) { throw new AbstractMethodError(); } @Override public int read(Backend backend, Pointer buffer, int count) { throw new AbstractMethodError(); } @Override public FileIO dup2() { return new UdpSocket(emulator); } @Override public int sendto(byte[] data, int flags, Pointer dest_addr, int addrlen) {<FILL_FUNCTION_BODY>} @Override protected void setKeepAlive(int keepAlive) { throw new AbstractMethodError(); } @Override protected void setSocketRecvBuf(int recvBuf) { throw new AbstractMethodError(); } @Override protected void setReuseAddress(int reuseAddress) { throw new AbstractMethodError(); } @Override protected void setTcpNoDelay(int tcpNoDelay) { throw new AbstractMethodError(); } @Override protected int getTcpNoDelay() { throw new AbstractMethodError(); } @Override public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) { throw new UnsupportedOperationException(); } @Override public int getdirentries64(Pointer buf, int bufSize) { throw new UnsupportedOperationException(); } }
if (addrlen != 16) { throw new IllegalStateException("addrlen=" + addrlen); } if (log.isDebugEnabled()) { byte[] addr = dest_addr.getByteArray(0, addrlen); Inspector.inspect(addr, "addr"); } int sa_family = dest_addr.getInt(0); if (sa_family != AF_INET) { throw new AbstractMethodError("sa_family=" + sa_family); } try { InetAddress address = InetAddress.getByAddress(dest_addr.getByteArray(4, 4)); throw new UnsupportedOperationException("address=" + address); } catch (IOException e) { log.debug("sendto failed", e); emulator.getMemory().setErrno(UnixEmulator.EACCES); return -1; }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/gpb/GPBDescriptor.java
GPBDescriptor
toProtobufDef
class GPBDescriptor { private static final Log log = LogFactory.getLog(GPBDescriptor.class); private final Emulator<?> emulator; private final ObjcObject descriptor; public static String toProtobufDef(Emulator<?> emulator, ObjC objc, String msgClass) {<FILL_FUNCTION_BODY>} private GPBDescriptor(Emulator<?> emulator, ObjcObject descriptor) { this.emulator = emulator; this.descriptor = descriptor; } private String buildMsgDef() { StringBuilder builder = new StringBuilder(); ObjcObject file = descriptor.callObjc("file"); String _package = file.callObjc("package").toNSString().getString(); ObjcObject obj = file.callObjc("objcPrefix"); NSString nsString = obj == null ? null : obj.toNSString(); String objcPrefix = nsString == null ? null : nsString.getString(); builder.append("// package=").append(_package).append(", objcPrefix=").append(objcPrefix).append("\n"); String name = descriptor.callObjc("name").toNSString().getString(); builder.append("message ").append(name).append(" {\n"); List<GPBEnumDescriptor> enumDescriptors = new ArrayList<>(); ObjcObject fieldsObject = descriptor.callObjc("fields"); if (fieldsObject == null) { log.warn("descriptor=" + descriptor.getDescription()); } else { NSArray fields = fieldsObject.toNSArray(); for (ObjcObject field : fields) { String fieldName = field.callObjc("name").toNSString().getString(); int number = field.callObjcInt("number"); int dataTypeValue = field.callObjcInt("dataType"); int required = field.callObjcInt("isRequired"); int optional = field.callObjcInt("isOptional"); int fieldTypeValue = field.callObjcInt("fieldType"); int hasDefaultValue = field.callObjcInt("hasDefaultValue"); if (hasDefaultValue != 0) { log.warn("hasDefaultValue=" + hasDefaultValue); } builder.append(" "); GPBFieldType fieldType = GPBFieldType.of(fieldTypeValue); switch (fieldType) { case GPBFieldTypeSingle: { if (required == optional) { throw new IllegalStateException("fieldName=" + fieldName + ", fieldType=" + fieldTypeValue + ", required=" + required); } if (optional != 0) { builder.append("optional "); } break; } case GPBFieldTypeRepeated: builder.append("repeated "); break; case GPBFieldTypeMap: { int mapKeyDataType = field.callObjcInt("mapKeyDataType"); GPBDataType dataType = GPBDataType.of(mapKeyDataType); builder.append("map<").append(dataType.buildMsgDef(field, name, GPBFieldType.GPBFieldTypeSingle, enumDescriptors)).append(", "); break; } default: throw new UnsupportedOperationException("fieldType=" + fieldType); } GPBDataType dataType = GPBDataType.of(dataTypeValue); builder.append(dataType.buildMsgDef(field, name, fieldType, enumDescriptors)); builder.append(" "); builder.append(fieldName); builder.append(" = ").append(number).append(";"); builder.append("\n"); } } builder.append("}"); for (GPBEnumDescriptor descriptor : enumDescriptors) { builder.append("\n").append(descriptor.buildMsgDef(emulator, name)); } return builder.toString(); } }
ObjcClass objcClass = objc.getClass(msgClass); boolean hasDescriptor = objc.respondsToSelector(objcClass, "descriptor"); if (hasDescriptor) { ObjcObject descriptor = objcClass.callObjc("descriptor"); return new GPBDescriptor(emulator, descriptor).buildMsgDef(); } else { throw new UnsupportedOperationException(objcClass.getName() + " is NOT protobuf class"); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/gpb/GPBEnumDescriptor.java
GPBEnumDescriptor
buildMsgDef
class GPBEnumDescriptor { private final ObjcObject descriptor; private final String name; public GPBEnumDescriptor(ObjcObject descriptor) { this.descriptor = descriptor; name = descriptor.callObjc("name").toNSString().getString(); } String getName() { return name; } final String buildMsgDef(Emulator<?> emulator, String msgName) {<FILL_FUNCTION_BODY>} }
StringBuilder builder = new StringBuilder(); String prefix = msgName + "_"; String name = this.name; if (name.startsWith(prefix)) { name = name.substring(prefix.length()); } builder.append("enum ").append(name).append(" {\n"); MemoryBlock block = emulator.getMemory().malloc(4, false); Pointer ptr = block.getPointer(); ptr.setInt(0, 0); int enumNameCount = descriptor.callObjcInt("enumNameCount"); for (int i = 0; i < enumNameCount; i++) { ObjcObject enumNameObject = descriptor.callObjc("getEnumNameForIndex:", i); String enumName = enumNameObject.toNSString().getString(); prefix = this.name + "_"; if (enumName.startsWith(prefix)) { enumName = enumName.substring(prefix.length()); } if (descriptor.callObjcInt("getValue:forEnumName:", ptr, enumNameObject) != 1) { throw new IllegalStateException(); } builder.append(" ").append(enumName).append(" = ").append(ptr.getInt(0)).append(";\n"); } block.free(); builder.append("}"); return builder.toString();
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/hook/FishHook.java
FishHook
rebindSymbolImage
class FishHook extends BaseHook implements IFishHook { private static final Log log = LogFactory.getLog(FishHook.class); public static IFishHook getInstance(Emulator<?> emulator) { IFishHook fishHook = emulator.get(FishHook.class.getName()); if (fishHook == null) { fishHook = new FishHook(emulator); emulator.set(FishHook.class.getName(), fishHook); } return fishHook; } private final Symbol rebind_symbols, rebind_symbols_image; private FishHook(Emulator<?> emulator) { super(emulator, "libfishhook"); rebind_symbols = module.findSymbolByName("_rebind_symbols", false); rebind_symbols_image = module.findSymbolByName("_rebind_symbols_image", false); if (log.isDebugEnabled()) { log.debug("rebind_symbols=" + rebind_symbols + ", rebind_symbols_image=" + rebind_symbols_image); } if (rebind_symbols == null) { throw new IllegalStateException("rebind_symbols is null"); } if (rebind_symbols_image == null) { throw new IllegalStateException("rebind_symbols_image is null"); } } @Override public void rebindSymbol(String symbol, ReplaceCallback callback) { rebindSymbol(symbol, callback, false); } @Override public void rebindSymbol(String symbol, ReplaceCallback callback, boolean enablePostCall) { Pointer rebinding = createRebinding(symbol, callback, enablePostCall); int ret = rebind_symbols.call(emulator, rebinding, 1).intValue(); if (ret != RET_SUCCESS) { throw new IllegalStateException("ret=" + ret); } } private Pointer createRebinding(String symbol, ReplaceCallback callback, boolean enablePostCall) { Memory memory = emulator.getMemory(); Pointer symbolPointer = memory.malloc(symbol.length() + 1, false).getPointer(); symbolPointer.setString(0, symbol); final Pointer originCall = memory.malloc(emulator.getPointerSize(), false).getPointer(); Pointer replaceCall = createReplacePointer(callback, originCall, enablePostCall); Pointer rebinding = memory.malloc(emulator.getPointerSize() * 3, false).getPointer(); rebinding.setPointer(0, symbolPointer); rebinding.setPointer(emulator.getPointerSize(), replaceCall); rebinding.setPointer(2L * emulator.getPointerSize(), originCall); return rebinding; } @Override public void rebindSymbolImage(Module module, String symbol, ReplaceCallback callback) { rebindSymbolImage(module, symbol, callback, false); } @Override public void rebindSymbolImage(Module module, String symbol, ReplaceCallback callback, boolean enablePostCall) {<FILL_FUNCTION_BODY>} }
MachOModule mm = (MachOModule) module; long header = mm.machHeader; long slide = Dyld.computeSlide(emulator, header); Pointer rebinding = createRebinding(symbol, callback, enablePostCall); int ret = rebind_symbols_image.call(emulator, UnidbgPointer.pointer(emulator, header), UnidbgPointer.pointer(emulator, slide), rebinding, 1).intValue(); if (ret != RET_SUCCESS) { throw new IllegalStateException("ret=" + ret); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/hook/Substrate.java
Substrate
findSymbol
class Substrate extends BaseHook implements ISubstrate { private static final Log log = LogFactory.getLog(Substrate.class); public static ISubstrate getInstance(Emulator<?> emulator) { Substrate substrate = emulator.get(Substrate.class.getName()); if (substrate == null) { substrate = new Substrate(emulator); emulator.set(Substrate.class.getName(), substrate); } return substrate; } private final Symbol _MSGetImageByName; private final Symbol _MSFindSymbol; private final Symbol _MSHookFunction; private final Symbol _MSHookMessageEx; private Substrate(Emulator<?> emulator) { super(emulator, "libsubstrate"); _MSGetImageByName = module.findSymbolByName("_MSGetImageByName", false); _MSFindSymbol = module.findSymbolByName("_MSFindSymbol", false); _MSHookFunction = module.findSymbolByName("_MSHookFunction", false); _MSHookMessageEx = module.findSymbolByName("_MSHookMessageEx", false); if (_MSGetImageByName == null) { throw new IllegalStateException("_MSGetImageByName is null"); } if (_MSFindSymbol == null) { throw new IllegalStateException("_MSFindSymbol is null"); } if (_MSHookFunction == null) { throw new IllegalStateException("_MSHookFunction is null"); } if (_MSHookMessageEx == null) { throw new IllegalStateException("_MSHookMessageEx is null"); } Symbol _MSDebug = module.findSymbolByName("_MSDebug", false); if (_MSDebug == null) { throw new IllegalStateException("_MSDebug is null"); } if (log.isDebugEnabled()) { log.debug("_MSGetImageByName=" + UnidbgPointer.pointer(emulator, _MSGetImageByName.getAddress()) + ", _MSFindSymbol=" + UnidbgPointer.pointer(emulator, _MSFindSymbol.getAddress()) + ", _MSHookFunction=" + UnidbgPointer.pointer(emulator, _MSHookFunction.getAddress()) + ", _MSHookMessageEx=" + UnidbgPointer.pointer(emulator, _MSHookMessageEx.getAddress()) + ", _MSDebug=" + UnidbgPointer.pointer(emulator, _MSDebug.getAddress())); } if (log.isDebugEnabled()) { _MSDebug.createPointer(emulator).setInt(0, 1); } } @Override public Module getImageByName(String file) { Number number = _MSGetImageByName.call(emulator, file); long ret = number.longValue(); if (emulator.is32Bit()) { ret &= 0xffffffffL; } if (ret == 0) { return null; } else { for (Module module : emulator.getMemory().getLoadedModules()) { MachOModule mm = (MachOModule) module; if (mm.machHeader == ret) { return module; } } throw new IllegalStateException("ret=0x" + Long.toHexString(ret)); } } @Override public Symbol findSymbol(Module image, String name) {<FILL_FUNCTION_BODY>} @Override public void hookFunction(Symbol symbol, ReplaceCallback callback) { hookFunction(symbol, callback, false); } @Override public void hookFunction(long address, ReplaceCallback callback) { hookFunction(address, callback, false); } @Override public void hookFunction(Symbol symbol, ReplaceCallback callback, boolean enablePostCall) { hookFunction(symbol.getAddress(), callback, enablePostCall); } @Override public void hookFunction(long address, ReplaceCallback callback, boolean enablePostCall) { final Pointer backup = emulator.getMemory().malloc(emulator.getPointerSize(), false).getPointer(); Pointer replace = createReplacePointer(callback, backup, enablePostCall); _MSHookFunction.call(emulator, UnidbgPointer.pointer(emulator, address), replace, backup); } @Override public void replace(long functionAddress, Svc svc) { if (svc == null) { throw new NullPointerException(); } final Pointer originCall = emulator.getMemory().malloc(emulator.getPointerSize(), false).getPointer(); Pointer callback = emulator.getSvcMemory().registerSvc(svc); _MSHookFunction.call(emulator, UnidbgPointer.pointer(emulator, functionAddress), callback, originCall); } @Override public void replace(Symbol symbol, Svc svc) { replace(symbol.getAddress(), svc); } @Override public void replace(long functionAddress, ReplaceCallback callback) { hookFunction(functionAddress, callback); } @Override public void replace(Symbol symbol, ReplaceCallback callback) { hookFunction(symbol, callback); } @Override public void replace(long functionAddress, ReplaceCallback callback, boolean enablePostCall) { hookFunction(functionAddress, callback, enablePostCall); } @Override public void replace(Symbol symbol, ReplaceCallback callback, boolean enablePostCall) { hookFunction(symbol, callback, enablePostCall); } @Override public void hookMessageEx(Pointer _class, Pointer message, ReplaceCallback callback) { hookMessageEx(_class, message, callback, false); } @Override public void hookMessageEx(ObjcClass _class, Pointer message, ReplaceCallback callback) { hookMessageEx(_class.getPointer(), message, callback); } @Override public void hookMessageEx(Pointer _class, Pointer message, ReplaceCallback callback, boolean enablePostCall) { final Pointer backup = emulator.getMemory().malloc(emulator.getPointerSize(), false).getPointer(); Pointer replace = createReplacePointer(callback, backup, enablePostCall); _MSHookMessageEx.call(emulator, _class, message, replace, backup); } @Override public void hookMessageEx(ObjcClass _class, Pointer message, ReplaceCallback callback, boolean enablePostCall) { hookMessageEx(_class.getPointer(), message, callback, enablePostCall); } }
MachOModule mm = (MachOModule) image; Number number = _MSFindSymbol.call(emulator, mm == null ? null : UnidbgPointer.pointer(emulator, mm.machHeader), name); long ret = number.longValue(); if (emulator.is32Bit()) { ret &= 0xffffffffL; } if (ret == 0) { return null; } else { return new SubstrateSymbol(name, ret); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/ipa/BundleLoader.java
BundleLoader
load
class BundleLoader extends BaseLoader { private static final Log log = LogFactory.getLog(BundleLoader.class); public static final String APP_NAME = "UniDbg"; private final File frameworkDir; protected final File rootDir; public BundleLoader(File frameworkDir, File rootDir) { this.frameworkDir = frameworkDir; this.rootDir = rootDir; if (!frameworkDir.exists() || !frameworkDir.isDirectory()) { throw new IllegalArgumentException("Invalid frameworkDir: " + frameworkDir); } } private String generateRandomSeed(String bundleIdentifier, String bundleVersion) { return bundleIdentifier + "_" + bundleVersion; } private String generateExecutableBundlePath(String bundleIdentifier, String bundleVersion) { String seed = generateRandomSeed(bundleIdentifier, bundleVersion); UUID uuid = UUID.nameUUIDFromBytes((seed + "_Application").getBytes(StandardCharsets.UTF_8)); return APP_DIR + uuid.toString().toUpperCase() + "/" + APP_NAME + ".app"; } public LoadedBundle load(String name, EmulatorConfigurator configurator) {<FILL_FUNCTION_BODY>} protected void config(final Emulator<DarwinFileIO> emulator, String executableBundlePath, File rootDir) throws IOException { File executable = new File(executableBundlePath); SyscallHandler<DarwinFileIO> syscallHandler = emulator.getSyscallHandler(); File appDir = executable.getParentFile(); syscallHandler.addIOResolver(new BundleResolver(appDir.getPath(), getBundleIdentifier())); FileUtils.forceMkdir(new File(rootDir, appDir.getParentFile().getPath())); emulator.getMemory().addHookListener(new SymbolResolver(emulator)); // ((DarwinSyscallHandler) syscallHandler).setExecutableBundlePath(executableBundlePath); } protected String getBundleIdentifier() { return getClass().getPackage().getName(); } protected String[] getEnvs(File rootDir, String seed) throws IOException { List<String> list = new ArrayList<>(); list.add("OBJC_PRINT_EXCEPTION_THROW=YES"); // log backtrace of every objc_exception_throw() addEnv(list); UUID uuid = UUID.nameUUIDFromBytes((seed + "_Documents").getBytes(StandardCharsets.UTF_8)); String homeDir = "/var/mobile/Containers/Data/Application/" + uuid.toString().toUpperCase(); list.add("CFFIXED_USER_HOME=" + homeDir); FileUtils.forceMkdir(new File(rootDir, homeDir + "/Documents")); return list.toArray(new String[0]); } private Module load(Emulator<DarwinFileIO> emulator, EmulatorConfigurator configurator, File executable, String executableBundleDir) throws IOException { MachOLoader loader = (MachOLoader) emulator.getMemory(); loader.setLoader(this); Module module = loader.load(new BundleLibraryFile(executable, executableBundleDir), forceCallInit); if (configurator != null) { configurator.onExecutableLoaded(emulator, (MachOModule) module); } loader.onExecutableLoaded(executable.getName()); return module; } @Override public boolean isPayloadModule(String path) { return false; } }
final File bundleDir = new File(this.frameworkDir, name + ".framework"); String executable; String bundleVersion; String bundleIdentifier; try { File infoFile = new File(bundleDir, "Info.plist"); if (!infoFile.canRead()) { throw new IllegalStateException("load " + name + " failed"); } byte[] data = FileUtils.readFileToByteArray(infoFile); NSDictionary info = (NSDictionary) PropertyListParser.parse(data); executable = parseExecutable(info); bundleVersion = parseVersion(info); bundleIdentifier = parseCFBundleIdentifier(info); } catch (IOException | PropertyListFormatException | ParseException | ParserConfigurationException | SAXException e) { throw new IllegalStateException("load " + name + " failed", e); } String executableBundleDir = generateExecutableBundlePath(bundleIdentifier, bundleVersion); String executableBundlePath = executableBundleDir + "/" + APP_NAME; // String bundleAppDir = new File(executableBundlePath).getParentFile().getParentFile().getPath(); File rootDir = new File(this.rootDir, bundleVersion); try { Emulator<DarwinFileIO> emulator = new DarwinARM64Emulator(executableBundlePath, rootDir, backendFactories, getEnvs(rootDir, executableBundlePath)) { }; emulator.getSyscallHandler().setVerbose(log.isDebugEnabled()); if (configurator != null) { configurator.configure(emulator, executableBundlePath, rootDir, bundleIdentifier); } config(emulator, executableBundlePath, rootDir); MachOLoader memory = (MachOLoader) emulator.getMemory(); memory.setObjcRuntime(true); DarwinResolver resolver = createLibraryResolver(); if (overrideResolver) { resolver.setOverride(); } memory.setLibraryResolver(resolver); Module module = load(emulator, configurator, new File(bundleDir, executable), executableBundleDir); return new LoadedBundle(emulator, module, bundleIdentifier, bundleVersion); } catch (IOException e) { throw new IllegalStateException(e); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/ipa/BundleResolver.java
BundleResolver
resolve
class BundleResolver implements IOResolver<DarwinFileIO> { private final String executableBundleDir; private final String bundleIdentifier; BundleResolver(String executableBundleDir, String bundleIdentifier) { this.executableBundleDir = executableBundleDir; this.bundleIdentifier = bundleIdentifier; } @Override public FileResult<DarwinFileIO> resolve(Emulator<DarwinFileIO> emulator, String pathname, int oflags) {<FILL_FUNCTION_BODY>} }
if (executableBundleDir.equals(pathname)) { List<DirectoryFileIO.DirectoryEntry> list = new ArrayList<>(); list.add(new DirectoryFileIO.DirectoryEntry(true, "Info.plist")); return FileResult.<DarwinFileIO>success(new DirectoryFileIO(oflags, pathname, list.toArray(new DirectoryFileIO.DirectoryEntry[0]))); } if ((executableBundleDir + "/Info.plist").equals(pathname)) { Map<String, Object> map = new LinkedHashMap<>(); map.put("CFBundleExecutable", BundleLoader.APP_NAME); map.put("CFBundleIdentifier", bundleIdentifier); map.put("CFBundleInfoDictionaryVersion", "6.0"); map.put("CFBundleName", BundleLoader.APP_NAME); map.put("CFBundleVersion", "1.0.0"); NSDictionary root = (NSDictionary) NSDictionary.fromJavaObject(map); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { PropertyListParser.saveAsBinary(root, outputStream); } catch (IOException e) { throw new IllegalStateException("save plist failed", e); } return FileResult.<DarwinFileIO>success(new ByteArrayFileIO(oflags, pathname, outputStream.toByteArray())); } return null;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/ipa/IpaLibraryFile.java
IpaLibraryFile
resolveLibrary
class IpaLibraryFile implements LibraryFile { private static final Log log = LogFactory.getLog(IpaLibraryFile.class); private final String appDir; private final File ipa; private final String executable; private final byte[] data; private final String bundleAppDir; IpaLibraryFile(String appDir, File ipa, String executable, String bundleAppDir, String... loads) throws IOException { this(appDir, ipa, executable, bundleAppDir, IpaLoader.loadZip(ipa, appDir + executable), Arrays.asList(loads)); } private final List<String> loadList; private IpaLibraryFile(String appDir, File ipa, String executable, String bundleAppDir, byte[] data, List<String> loadList) { this.appDir = appDir; this.ipa = ipa; this.executable = executable; this.data = data; this.bundleAppDir = bundleAppDir; this.loadList = loadList; } @Override public long getFileSize() { return data.length; } @Override public String getName() { return executable; } @Override public String getMapRegionName() { return getPath(); } @Override public LibraryFile resolveLibrary(Emulator<?> emulator, String soName) throws IOException {<FILL_FUNCTION_BODY>} @Override public ByteBuffer mapBuffer() { return ByteBuffer.wrap(data); } @Override public String getPath() { return appDir.replace(IpaLoader.PAYLOAD_PREFIX, bundleAppDir) + executable; } }
if (!soName.contains("@")) { return null; } String path = soName.replace("@executable_path/", appDir); if (log.isDebugEnabled()) { log.debug("Try resolve library soName=" + soName + ", path=" + path); } if (path.contains("@")) { log.warn("Try resolve library soName=" + soName + ", path=" + path, new Exception()); return null; } if (!loadList.isEmpty() && !loadList.contains(FilenameUtils.getName(path))) { return null; } byte[] libData = IpaLoader.loadZip(ipa, path); if (libData != null) { return new IpaLibraryFile(appDir, ipa, soName, bundleAppDir, libData, loadList); } else { return null; }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/ipa/IpaLoader32.java
IpaLoader32
load
class IpaLoader32 extends IpaLoader { public IpaLoader32(File ipa, File rootDir) { super(ipa, rootDir); } @Override public LoadedIpa load(EmulatorConfigurator configurator, String... loads) {<FILL_FUNCTION_BODY>} }
try { return load32(configurator, loads); } catch (IOException e) { throw new IllegalStateException(e); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/ipa/IpaLoader64.java
IpaLoader64
load
class IpaLoader64 extends IpaLoader { @SuppressWarnings("unused") public IpaLoader64(Class<?> callingClass, File rootDir) { super(callingClass, rootDir); } public IpaLoader64(File ipa, File rootDir) { super(ipa, rootDir); } @Override public LoadedIpa load(EmulatorConfigurator configurator, String... loads) {<FILL_FUNCTION_BODY>} }
try { return load64(configurator, loads); } catch (IOException e) { throw new IllegalStateException(e); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/ipa/IpaResolver.java
IpaResolver
createDirectoryFileIO
class IpaResolver implements IOResolver<DarwinFileIO> { private static final Log log = LogFactory.getLog(IpaResolver.class); private final String appDir; private final File ipa; private final String randomDir; IpaResolver(String appDir, File ipa) { this.appDir = FilenameUtils.normalize(appDir, true); this.ipa = ipa; this.randomDir = FilenameUtils.normalize(new File(appDir).getParentFile().getPath(), true); } @Override public FileResult<DarwinFileIO> resolve(Emulator<DarwinFileIO> emulator, String pathname, int oflags) { if ((randomDir + "/StoreKit/receipt").equals(pathname)) { return FileResult.<DarwinFileIO>success(new ByteArrayFileIO(oflags, pathname, new byte[0])); } pathname = FilenameUtils.normalize(pathname, true); if (pathname.startsWith(appDir)) { String path = IpaLoader.PAYLOAD_PREFIX + pathname.substring(randomDir.length()); try (JarFile jarFile = new JarFile(ipa)) { Enumeration<JarEntry> enumeration = jarFile.entries(); JarEntry entry = null; boolean hasChild = false; String dir = path; if (!dir.endsWith("/")) { dir += "/"; } while (enumeration.hasMoreElements()) { JarEntry jarEntry = enumeration.nextElement(); if (path.equals(jarEntry.getName()) || (path + "/").equals(jarEntry.getName())) { entry = jarEntry; break; } if (!hasChild && jarEntry.getName().startsWith(dir)) { hasChild = true; } } if (entry == null && hasChild) { return FileResult.success(createDirectoryFileIO(dir, pathname, oflags)); } if (entry == null) { if (log.isDebugEnabled()) { log.debug("Resolve appDir=" + appDir + ", path=" + path); } return null; } if (entry.isDirectory()) { return FileResult.success(createDirectoryFileIO(entry.getName(), pathname, oflags)); } else { return FileResult.<DarwinFileIO>success(new JarEntryFileIO(oflags, pathname, ipa, entry)); } } catch (IOException e) { throw new IllegalStateException(e); } } return null; } private DarwinFileIO createDirectoryFileIO(String dirEntry, String pathname, int oflags) throws IOException {<FILL_FUNCTION_BODY>} }
List<DirectoryFileIO.DirectoryEntry> list = new ArrayList<>(); list.add(new DirectoryFileIO.DirectoryEntry(false, ".")); list.add(new DirectoryFileIO.DirectoryEntry(false, "..")); Set<String> dirSet = new HashSet<>(); try (JarFile jarFile = new JarFile(ipa)) { Enumeration<JarEntry> enumeration = jarFile.entries(); while (enumeration.hasMoreElements()) { JarEntry entry = enumeration.nextElement(); if (entry.getName().startsWith(dirEntry)) { String subName = entry.getName().substring(dirEntry.length()); if (subName.isEmpty()) { continue; } int index = subName.indexOf('/'); if (index == -1) { // file list.add(new DirectoryFileIO.DirectoryEntry(true, subName)); } else { int endIndex = subName.indexOf('/', index + 1); if (endIndex == -1 || endIndex == subName.length() - 1) { // dir String dir = subName.substring(0, index); if (dirSet.add(dir)) { list.add(new DirectoryFileIO.DirectoryEntry(false, dir)); } } } } } } return new DirectoryFileIO(oflags, pathname, ipa.getParentFile(), list.toArray(new DirectoryFileIO.DirectoryEntry[0]));
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/ipa/LoadedIpa.java
LoadedIpa
callEntry
class LoadedIpa { private final Emulator<DarwinFileIO> emulator; private final Module executable; private final String bundleIdentifier; private final String bundleVersion; LoadedIpa(Emulator<DarwinFileIO> emulator, Module executable, String bundleIdentifier, String bundleVersion) { this.emulator = emulator; this.executable = executable; this.bundleIdentifier = bundleIdentifier; this.bundleVersion = bundleVersion; } public String getBundleIdentifier() { return bundleIdentifier; } public String getBundleVersion() { return bundleVersion; } private boolean callFinishLaunchingWithOptions; public void setCallFinishLaunchingWithOptions(boolean callFinishLaunchingWithOptions) { this.callFinishLaunchingWithOptions = callFinishLaunchingWithOptions; } private String systemName; // iPhone OS private String systemVersion; // 8.3 private String model; // iPhone private String name; // My iPhone private String identifierForVendor; private String advertisingIdentifier; private String carrierName; public void callEntry() {<FILL_FUNCTION_BODY>} public Module getExecutable() { return executable; } public Emulator<DarwinFileIO> getEmulator() { return emulator; } public void setSystemName(String systemName) { this.systemName = systemName; } public void setSystemVersion(String systemVersion) { this.systemVersion = systemVersion; } public void setModel(String model) { this.model = model; } public void setName(String name) { this.name = name; } public void setIdentifierForVendor(String identifierForVendor) { this.identifierForVendor = identifierForVendor; } public void setAdvertisingIdentifier(String advertisingIdentifier) { this.advertisingIdentifier = advertisingIdentifier; } public void setCarrierName(String carrierName) { this.carrierName = carrierName; } }
ArgsRequest args = new ArgsRequest(); args.setCallFinishLaunchingWithOptions(callFinishLaunchingWithOptions); args.setSystemName(systemName); args.setSystemVersion(systemVersion); args.setModel(model); args.setName(name); args.setIdentifierForVendor(identifierForVendor); args.setAdvertisingIdentifier(advertisingIdentifier); args.setCarrierName(carrierName); executable.callEntry(emulator, "-args", JSON.toJSONString(args));
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/ipa/NSUserDefaultsResolver.java
NSUserDefaultsResolver
resolve
class NSUserDefaultsResolver implements IOResolver<DarwinFileIO> { private final String bundleIdentifier; private final Map<String, Object> map; public NSUserDefaultsResolver(String bundleIdentifier, Map<String, Object> map) { this.bundleIdentifier = bundleIdentifier; this.map = map; } @Override public FileResult<DarwinFileIO> resolve(Emulator<DarwinFileIO> emulator, String pathname, int oflags) {<FILL_FUNCTION_BODY>} }
if (pathname.endsWith(("/Library/Preferences/" + bundleIdentifier + ".plist"))) { NSDictionary root = (NSDictionary) NSDictionary.fromJavaObject(map); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { PropertyListParser.saveAsBinary(root, outputStream); } catch (IOException e) { throw new IllegalStateException("save plist failed", e); } return FileResult.<DarwinFileIO>success(new ByteArrayFileIO(oflags, pathname, outputStream.toByteArray())); } return null;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/kevent/KEvent.java
KEvent
processKev
class KEvent extends BaseDarwinFileIO { private static final Log log = LogFactory.getLog(KEvent.class); private static final short EVFILT_SIGNAL = (-6); /* attached to struct proc */ private static final short EVFILT_MACHPORT = (-8); /* Mach portsets */ private static final short EVFILT_USER = (-10); /* User events */ private static final short EVFILT_VM = (-12); /* Virtual memory events */ private final Map<Integer, KEvent64> registerMap = new HashMap<>(); final List<KEvent64> pendingEventList = new ArrayList<>(); public KEvent(int oflags) { super(oflags); } private static final int EV_ADD = 0x0001; /* add event to kq (implies enable) */ private static final int EV_DELETE = 0x0002; /* delete event from kq */ public static final int EV_ENABLE = 0x0004; /* enable event */ public static final int EV_DISABLE = 0x0008; /* disable event (not reported) */ private static final int EV_RECEIPT = 0x0040; /* force EV_ERROR on success, data == 0 */ /* * On input, NOTE_TRIGGER causes the event to be triggered for output. */ private static final int NOTE_TRIGGER = 0x01000000; private void processKev(KEvent64 kev) {<FILL_FUNCTION_BODY>} public void processChangeList(Pointer changelist, int nchanges) { int size = UnidbgStructure.calculateSize(KEvent64.class); Pointer ptr = changelist; for (int i = 0; i < nchanges; i++, ptr = ptr.share(size)) { KEvent64 kev = new KEvent64(ptr); kev.unpack(); if (log.isDebugEnabled()) { log.debug("processChangeList i=" + i + ", kev=" + kev); } processKev(kev); } } @Override public void close() { registerMap.clear(); pendingEventList.clear(); } }
switch (kev.filter) { case EVFILT_USER: { if ((kev.fflags & NOTE_TRIGGER) != 0) { KEvent64 reg = registerMap.get(kev.hashCode()); if (reg == null) { throw new IllegalStateException(); } else { pendingEventList.add(reg); } } else { if ((kev.flags & EV_ADD) != 0) { registerMap.put(kev.hashCode(), kev); } if ((kev.flags & EV_DELETE) != 0) { throw new UnsupportedOperationException(); } if ((kev.flags & EV_ENABLE) != 0) { throw new UnsupportedOperationException(); } if ((kev.flags & EV_DISABLE) != 0) { throw new UnsupportedOperationException(); } if ((kev.flags & EV_RECEIPT) != 0) { throw new UnsupportedOperationException(); } } break; } case EVFILT_VM: case EVFILT_MACHPORT: { if ((kev.flags & EV_ADD) != 0) { registerMap.put(kev.hashCode(), kev); } if ((kev.flags & EV_DELETE) != 0) { throw new UnsupportedOperationException(); } if (kev.isEnabled() && kev.isDisabled()) { throw new UnsupportedOperationException(); } break; } case EVFILT_SIGNAL: default: throw new UnsupportedOperationException("filter=" + kev.filter); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/kevent/KEvent64.java
KEvent64
copy
class KEvent64 extends UnidbgStructure { public KEvent64(Pointer p) { super(p); } public long ident; /* identifier for this event */ public short filter; /* filter for event */ public short flags; /* general flags */ public int fflags; /* filter-specific flags */ public long data; /* filter-specific data */ public long udata; /* opaque user data identifier */ public long[] ext = new long[2]; /* filter-specific extensions */ public void copy(KEvent64 pending) {<FILL_FUNCTION_BODY>} @Override protected List<String> getFieldOrder() { return Arrays.asList("ident", "filter", "flags", "fflags", "data", "udata", "ext"); } public boolean isEnabled() { return (flags & KEvent.EV_ENABLE) != 0; } public boolean isDisabled() { return (flags & KEvent.EV_DISABLE) != 0; } @Override public int hashCode() { return Objects.hash(ident, filter); } }
this.ident = pending.ident; this.filter = pending.filter; this.flags = pending.flags; this.fflags = pending.fflags; this.data = pending.data; this.udata = pending.udata; this.ext = pending.ext;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/kevent/KEventWaiter.java
KEventWaiter
onContinueRun
class KEventWaiter extends AbstractWaiter implements Waiter { private static final Log log = LogFactory.getLog(KEventWaiter.class); private final KEvent event; private final Pointer eventlist; private final int nevents; public KEventWaiter(KEvent event, Pointer eventlist, int nevents) { this.event = event; this.eventlist = eventlist; this.nevents = nevents; } @Override public boolean canDispatch() { return !event.pendingEventList.isEmpty(); } @Override public void onContinueRun(Emulator<?> emulator) {<FILL_FUNCTION_BODY>} }
int size = UnidbgStructure.calculateSize(KEvent64.class); Pointer ptr = eventlist; int i = 0; for (; i < nevents && !event.pendingEventList.isEmpty(); i++, ptr = ptr.share(size)) { KEvent64 pending = event.pendingEventList.remove(0); KEvent64 kev = new KEvent64(ptr); kev.copy(pending); kev.pack(); if (log.isDebugEnabled()) { log.debug("onContinueRun i=" + i + ", kev=" + kev); } } Backend backend = emulator.getBackend(); if (emulator.is32Bit()) { backend.reg_write(ArmConst.UC_ARM_REG_R0, i); } else { backend.reg_write(Arm64Const.UC_ARM64_REG_X0, i); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/objc/NSArray.java
NSArray
create
class NSArray implements Iterable<ObjcObject>, PointerArg { public static NSArray create(ObjcObject object) {<FILL_FUNCTION_BODY>} private final ObjcObject object; private NSArray(ObjcObject object) { this.object = object; } @Override public Pointer getPointer() { return object.getPointer(); } private class NSArrayIterator implements Iterator<ObjcObject> { private final int count; public NSArrayIterator() { count = object.callObjcInt("count"); } private int index; @Override public boolean hasNext() { return index < count; } @Override public ObjcObject next() { return object.callObjc("objectAtIndex:", index++); } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public Iterator<ObjcObject> iterator() { return new NSArrayIterator(); } }
return object == null ? null : new NSArray(object);
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/objc/NSData.java
NSData
create
class NSData implements PointerArg { public static NSData create(ObjcObject object) {<FILL_FUNCTION_BODY>} private final ObjcObject object; private NSData(ObjcObject object) { this.object = object; } @Override public Pointer getPointer() { return object.getPointer(); } public byte[] getBytes() { int length = object.callObjcInt("length"); Pointer bytes = getBytesPointer(); return bytes.getByteArray(0, length); } public Pointer getBytesPointer() { return object.call("bytes"); } }
return object == null ? null : new NSData(object);
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/objc/NSString.java
NSString
getString
class NSString implements PointerArg { public static NSString create(ObjcObject object) { return object == null ? null : new NSString(object); } private final ObjcObject object; private NSString(ObjcObject object) { this.object = object; } @Override public Pointer getPointer() { return object.getPointer(); } public String getString() {<FILL_FUNCTION_BODY>} }
int length = object.callObjcInt("lengthOfBytesUsingEncoding:", NSUTF8StringEncoding); byte[] bytes = object.call("UTF8String").getByteArray(0, length); return new String(bytes, StandardCharsets.UTF_8);
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/objc/ObjC.java
ObjC
getInstance
class ObjC { public static ObjC getInstance(Emulator<?> emulator) {<FILL_FUNCTION_BODY>} public abstract ObjcClass getMetaClass(String className); public abstract ObjcClass lookUpClass(String className); public abstract ObjcClass getClass(String className); public abstract Pointer registerName(String selectorName); public abstract UnidbgPointer getMethodImplementation(ObjcClass objcClass, String selectorName); public abstract Number msgSend(Emulator<?> emulator, Object... args); public abstract void setInstanceVariable(Emulator<?> emulator, ObjcObject obj, String name, Object value); public abstract UnidbgPointer getInstanceVariable(Emulator<?> emulator, ObjcObject obj, String name); public abstract boolean respondsToSelector(ObjcClass objcClass, String selectorName); public abstract NSString newString(String str); public abstract NSData newData(byte[] bytes); }
ObjC objc = emulator.get(ObjC.class.getName()); if (objc == null) { objc = new ObjcImpl(emulator); emulator.set(ObjC.class.getName(), objc); } return objc;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/objc/ObjcImpl.java
ObjcImpl
newData
class ObjcImpl extends ObjC { private final Emulator<?> emulator; private final Symbol _objc_msgSend; private final Symbol _objc_getMetaClass; private final Symbol _objc_getClass; private final Symbol _objc_lookUpClass; private final Symbol _sel_registerName; private final Symbol _class_getMethodImplementation; private final Symbol _class_respondsToSelector; private final Symbol _object_setInstanceVariable; private final Symbol _object_getInstanceVariable; public ObjcImpl(Emulator<?> emulator) { this.emulator = emulator; Module module = emulator.getMemory().findModule("libobjc.A.dylib"); if (module == null) { throw new IllegalStateException("libobjc.A.dylib NOT loaded"); } _objc_msgSend = module.findSymbolByName("_objc_msgSend", false); if (_objc_msgSend == null) { throw new IllegalStateException("_objc_msgSend is null"); } _objc_getMetaClass = module.findSymbolByName("_objc_getMetaClass", false); if (_objc_getMetaClass == null) { throw new IllegalStateException("_objc_getMetaClass is null"); } _objc_getClass = module.findSymbolByName("_objc_getClass", false); if (_objc_getClass == null) { throw new IllegalStateException("_objc_getClass is null"); } _objc_lookUpClass = module.findSymbolByName("_objc_lookUpClass", false); if (_objc_lookUpClass == null) { throw new IllegalStateException("_objc_lookUpClass is null"); } _sel_registerName = module.findSymbolByName("_sel_registerName", false); if (_sel_registerName == null) { throw new IllegalStateException("_sel_registerName is null"); } _class_getMethodImplementation = module.findSymbolByName("_class_getMethodImplementation", false); if (_class_getMethodImplementation == null) { throw new IllegalStateException("_class_getMethodImplementation is null"); } _class_respondsToSelector = module.findSymbolByName("_class_respondsToSelector", false); if (_class_respondsToSelector == null) { throw new IllegalStateException("_class_respondsToSelector is null"); } _object_setInstanceVariable = module.findSymbolByName("_object_setInstanceVariable", false); if (_object_setInstanceVariable == null) { throw new IllegalStateException("_object_setInstanceVariable is null"); } _object_getInstanceVariable = module.findSymbolByName("_object_getInstanceVariable", false); if (_object_getInstanceVariable == null) { throw new IllegalStateException("_object_getInstanceVariable is null"); } } @Override public void setInstanceVariable(Emulator<?> emulator, ObjcObject obj, String name, Object value) { if (value instanceof Float) { float f = (Float) value; ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putFloat(f); buffer.flip(); value = buffer.getLong(); } else if (value instanceof Double) { double d = (Double) value; ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putDouble(d); buffer.flip(); value = buffer.getLong(); } _object_setInstanceVariable.call(emulator, obj, name, value); } @Override public UnidbgPointer getInstanceVariable(Emulator<?> emulator, ObjcObject obj, String name) { MemoryBlock block = null; try { block = emulator.getMemory().malloc(16, true); UnidbgPointer pointer = block.getPointer(); _object_getInstanceVariable.call(emulator, obj, name, pointer); return pointer.getPointer(0); } finally { if (block != null) { block.free(); } } } @Override public ObjcClass getMetaClass(String className) { Number number = _objc_getMetaClass.call(emulator, className); Pointer pointer = UnidbgPointer.pointer(emulator, number); if (pointer == null) { throw new IllegalArgumentException(className + " NOT found"); } return ObjcClass.create(emulator, pointer); } @Override public ObjcClass getClass(String className) { Number number = _objc_getClass.call(emulator, className); Pointer pointer = UnidbgPointer.pointer(emulator, number); if (pointer == null) { throw new IllegalArgumentException(className + " NOT found"); } return ObjcClass.create(emulator, pointer); } @Override public ObjcClass lookUpClass(String className) { Number number = _objc_lookUpClass.call(emulator, className); Pointer pointer = UnidbgPointer.pointer(emulator, number); return pointer == null ? null : ObjcClass.create(emulator, pointer); } @Override public Pointer registerName(String selectorName) { Number number = _sel_registerName.call(emulator, selectorName); Pointer pointer = UnidbgPointer.pointer(emulator, number); if (pointer == null) { throw new IllegalStateException(selectorName); } return pointer; } @Override public boolean respondsToSelector(ObjcClass objcClass, String selectorName) { Pointer selector = registerName(selectorName); Number number = _class_respondsToSelector.call(emulator, objcClass, selector); return number.intValue() == 1; } @Override public UnidbgPointer getMethodImplementation(ObjcClass objcClass, String selectorName) { Pointer selector = registerName(selectorName); Number number = _class_getMethodImplementation.call(emulator, objcClass, selector); UnidbgPointer pointer = UnidbgPointer.pointer(emulator, number); if (pointer == null) { throw new IllegalStateException(selectorName); } return pointer; } @Override public Number msgSend(Emulator<?> emulator, Object... args) { return _objc_msgSend.call(emulator, args); } private ObjcClass cNSString; private ObjcClass cNSData; @Override public NSString newString(String str) { if (str == null) { return null; } if (cNSString == null) { cNSString = getClass("NSString"); } ObjcObject obj = cNSString.callObjc("stringWithUTF8String:", str); return NSString.create(obj); } @Override public NSData newData(byte[] bytes) {<FILL_FUNCTION_BODY>} }
if (bytes == null) { return null; } if (cNSData == null) { cNSData = getClass("NSData"); } ObjcObject obj = cNSData.callObjc("dataWithBytes:length:", bytes, bytes.length); return NSData.create(obj);
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/objc/processor/CDObjectiveC2Processor.java
CDObjectiveC2Processor
loadClasses
class CDObjectiveC2Processor extends CDObjectiveCProcessor { final ByteBuffer buffer; public CDObjectiveC2Processor(MachOModule module, Emulator<?> emulator, ByteBuffer buffer) { super(emulator, module); this.buffer = buffer; load(); } private final Map<Long, Objc2Class> classMap = new HashMap<>(); @Override void loadClasses() {<FILL_FUNCTION_BODY>} @Override void loadCategories() { MachO.SegmentCommand64.Section64 section = objcSections.get("__objc_catlist"); if (section == null) { return; } MachO.SegmentCommand64.Section64.PointerList pointerList = (MachO.SegmentCommand64.Section64.PointerList) section.data(); for (long item : pointerList.items()) { Objc2Category category = Objc2Category.read(classMap, buffer, item, module, emulator); categoryList.add(category); } } }
MachO.SegmentCommand64.Section64 section = objcSections.get("__objc_classlist"); if (section == null) { return; } MachO.SegmentCommand64.Section64.PointerList pointerList = (MachO.SegmentCommand64.Section64.PointerList) section.data(); for (long item : pointerList.items()) { Objc2Class objc2Class = Objc2Class.read(classMap, buffer, item, module); if (objc2Class != null) { objc2Class.readMetaClass(classMap, buffer, module); classList.add(objc2Class); } }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/objc/processor/CDObjectiveCProcessor.java
CDObjectiveCProcessor
findObjcSymbol
class CDObjectiveCProcessor implements ObjectiveCProcessor { final Emulator<?> emulator; final MachOModule module; final Map<String, MachO.SegmentCommand64.Section64> objcSections; final List<ObjcClass> classList = new ArrayList<>(); final List<Objc2Category> categoryList = new ArrayList<>(); CDObjectiveCProcessor(Emulator<?> emulator, MachOModule module) { super(); this.emulator = emulator; this.module = module; this.objcSections = module.objcSections; } @Override public Symbol findObjcSymbol(Symbol bestSymbol, long targetAddress, MachOModule module) {<FILL_FUNCTION_BODY>} final void load() { loadClasses(); loadCategories(); } abstract void loadClasses(); abstract void loadCategories(); }
String className = null; ObjcMethod objc2Method = null; boolean isClassMethod = false; for (ObjcClass clazz : classList) { for (ObjcMethod method : clazz.getMethods()) { if ( objc2Method == null ) { if ( method.getImp() <= targetAddress ) { className = clazz.getName(); objc2Method = method; } } else if ( (method.getImp() <= targetAddress) && (objc2Method.getImp() < method.getImp()) ) { isClassMethod = false; className = clazz.getName(); objc2Method = method; } } ObjcClass metaClass = clazz.getMeta(); if (metaClass != null) { for (ObjcMethod method : metaClass.getMethods()) { if ( objc2Method == null ) { if ( method.getImp() <= targetAddress ) { isClassMethod = true; className = clazz.getName(); objc2Method = method; } } else if ( (method.getImp() <= targetAddress) && (objc2Method.getImp() < method.getImp()) ) { isClassMethod = true; className = clazz.getName(); objc2Method = method; } } } } for (Objc2Category category : categoryList) { for (Objc2Method method : category.instanceMethodList) { if ( objc2Method == null ) { if ( method.imp <= targetAddress ) { className = category.name; objc2Method = method; } } else if ( (method.imp <= targetAddress) && (objc2Method.getImp() < method.imp) ) { isClassMethod = false; className = category.name; objc2Method = method; } } for (Objc2Method method : category.classMethodList) { if ( objc2Method == null ) { if ( method.imp <= targetAddress ) { isClassMethod = true; className = category.name; objc2Method = method; } } else if ( (method.imp <= targetAddress) && (objc2Method.getImp() < method.imp) ) { isClassMethod = true; className = category.name; objc2Method = method; } } } if (bestSymbol != null && objc2Method != null && bestSymbol.getAddress() < module.base + objc2Method.getImp()) { bestSymbol = null; } if (bestSymbol != null) { return bestSymbol; } if (objc2Method != null) { String symbolName = String.valueOf(isClassMethod ? '+' : '-') + '[' + className + ' ' + objc2Method.getName() + ']'; return new ExportSymbol(symbolName, module.base + objc2Method.getImp(), module, 0, com.github.unidbg.ios.MachO.EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE); } return null;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/objc/processor/Objc2Category.java
Objc2Category
read
class Objc2Category { @SuppressWarnings("unused") static Objc2Category read(Map<Long, Objc2Class> classMap, ByteBuffer buffer, long item, MachOModule mm, Emulator<?> emulator) {<FILL_FUNCTION_BODY>} final Objc2Class objc2Class; final String name; final List<Objc2Method> instanceMethodList; final List<Objc2Method> classMethodList; private Objc2Category(Objc2Class objc2Class, String name, List<Objc2Method> instanceMethodList, List<Objc2Method> classMethodList) { this.objc2Class = objc2Class; this.name = name; this.instanceMethodList = instanceMethodList; this.classMethodList = classMethodList; } @Override public String toString() { return "Objc2Category{" + "name='" + name + '\'' + ", objc2Class=" + objc2Class + ", instanceMethodList=" + instanceMethodList + ", classMethodList=" + classMethodList + '}'; } }
int pos = mm.virtualMemoryAddressToFileOffset(item); buffer.position(pos); long name = buffer.getLong(); long clazz = buffer.getLong(); long instanceMethods = buffer.getLong(); long classMethods = buffer.getLong(); long protocols = buffer.getLong(); long instanceProperties = buffer.getLong(); long v7 = buffer.getLong(); long v8 = buffer.getLong(); pos = mm.virtualMemoryAddressToFileOffset(name); buffer.position(pos); String categoryName = Utils.readCString(buffer); List<Objc2Method> instanceMethodList = Objc2Method.loadMethods(buffer, instanceMethods, mm); List<Objc2Method> classMethodList = Objc2Method.loadMethods(buffer, classMethods, mm); Objc2Class objc2Class; String ownerClassName; if (clazz == 0) { objc2Class = null; UnidbgPointer ptr = UnidbgPointer.pointer(emulator, mm.base + item + 8); assert ptr != null; UnidbgPointer owner = ptr.getPointer(0); if (owner == null) { String symbolName = mm.findSymbolNameByAddress(mm.base + item + 8); if (symbolName == null) { ownerClassName = "??"; } else if (symbolName.startsWith("_OBJC_CLASS_$_")) { ownerClassName = symbolName.substring(14); } else { ownerClassName = symbolName; } } else { try { ObjcClass objcClass = ObjcClass.create(emulator, owner); ownerClassName = objcClass.getName(); } catch (BackendException e) { throw new IllegalStateException(e); } } } else { boolean valid = mm.validAddress(clazz); if (valid) { objc2Class = Objc2Class.read(classMap, buffer, clazz, mm); if (objc2Class == null) { ownerClassName = "???"; } else { ownerClassName = objc2Class.getName(); } } else { objc2Class = null; ownerClassName = "<DEREK BUG Categories!>"; } } String cName = ownerClassName + ' ' + '(' + categoryName + ')'; return new Objc2Category(objc2Class, cName, instanceMethodList, classMethodList);
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/objc/processor/Objc2Class.java
Objc2Class
read
class Objc2Class implements ObjcClass { private static final long FAST_DATA_MASK = 0x7ffffffffff8L; private static final int FAST_IS_SWIFT_LEGACY = 1; private static final int FAST_IS_SWIFT_STABLE = 2; @SuppressWarnings("unused") static Objc2Class read(Map<Long, Objc2Class> classMap, ByteBuffer buffer, long item, MachOModule mm) {<FILL_FUNCTION_BODY>} private final long isa; final long superclass; final long cache; final long vtable; final boolean isSwiftClass; final int flags; private final String name; private final List<Objc2Method> methods; private Objc2Class(long isa, long superclass, long cache, long vtable, boolean isSwiftClass, int flags, String name, List<Objc2Method> methods) { this.isa = isa; this.superclass = superclass; this.cache = cache; this.vtable = vtable; this.isSwiftClass = isSwiftClass; this.flags = flags; this.name = name; this.methods = methods; } @Override public String toString() { return name; } private ObjcClass metaClass; void readMetaClass(Map<Long, Objc2Class> classMap, ByteBuffer buffer, MachOModule mm) { metaClass = read(classMap, buffer, isa, mm); } @Override public String getName() { return name; } @Override public ObjcClass getMeta() { return metaClass; } @Override public ObjcMethod[] getMethods() { return methods.toArray(new ObjcMethod[0]); } }
if (item == 0) { return null; } if (classMap.containsKey(item)) { return classMap.get(item); } int pos = mm.virtualMemoryAddressToFileOffset(item); buffer.position(pos); long isa = buffer.getLong(); long superclass = buffer.getLong(); long cache = buffer.getLong(); long vtable = buffer.getLong(); long data = buffer.getLong(); long reserved1 = buffer.getLong(); long reserved2 = buffer.getLong(); long reserved3 = buffer.getLong(); boolean isSwiftClass = (data & (FAST_IS_SWIFT_LEGACY | FAST_IS_SWIFT_STABLE)) != 0; data &= FAST_DATA_MASK; if (data == 0) { throw new IllegalStateException("Invalid objc2class data"); } pos = mm.virtualMemoryAddressToFileOffset(data); buffer.position(pos); int flags = buffer.getInt(); int instanceStart = buffer.getInt(); int instanceSize = buffer.getInt(); int reserved = buffer.getInt(); long ivarLayout = buffer.getLong(); long name = buffer.getLong(); long baseMethods = buffer.getLong(); long baseProtocols = buffer.getLong(); long ivars = buffer.getLong(); long weakIvarLayout = buffer.getLong(); long baseProperties = buffer.getLong(); pos = mm.virtualMemoryAddressToFileOffset(name); buffer.position(pos); String className = Utils.readCString(buffer); List<Objc2Method> methods = Objc2Method.loadMethods(buffer, baseMethods, mm); Objc2Class objc2Class = new Objc2Class(isa, superclass, cache, vtable, isSwiftClass, flags, className, methods); classMap.put(item, objc2Class); return objc2Class;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/objc/processor/Objc2Method.java
Objc2Method
loadMethods
class Objc2Method implements ObjcMethod { private static class Method { private final int name; private final int types; private final long imp; private final boolean isSmallMethod; private Method(int name, int types, long imp, boolean isSmallMethod) { this.name = name; this.types = types; this.imp = imp; this.isSmallMethod = isSmallMethod; } private Objc2Method createMethod(ByteBuffer buffer) { if (isSmallMethod) { buffer.position(this.name); long name = buffer.getLong(); buffer.position((int) name); String methodName = Utils.readCString(buffer); buffer.position(this.types); String typesName = Utils.readCString(buffer); return new Objc2Method(methodName, typesName, imp); } else { buffer.position(this.name); String methodName = Utils.readCString(buffer); buffer.position(this.types); String typesName = Utils.readCString(buffer); return new Objc2Method(methodName, typesName, imp); } } } static List<Objc2Method> loadMethods(ByteBuffer buffer, long baseMethods, MachOModule mm) {<FILL_FUNCTION_BODY>} final String name; private final String types; final long imp; private Objc2Method(String name, String types, long imp) { this.name = name; this.types = types; this.imp = imp; } @Override public String getName() { return name; } @Override public long getImp() { return imp; } @Override public String toString() { return "Objc2Method{" + "name=" + name + ", types=" + types + ", imp=0x" + Long.toHexString(imp) + '}'; } }
if (baseMethods == 0) { return Collections.emptyList(); } int pos = mm.virtualMemoryAddressToFileOffset(baseMethods); buffer.position(pos); int entsize = buffer.getInt() & ~3; boolean isSmallMethod = (entsize & 0x80000000) != 0; entsize &= ~0x80000000; int count = buffer.getInt(); if (entsize != 24 && entsize != 12) { throw new IllegalStateException("Invalid entsize: " + entsize + ", baseMethods=0x" + Long.toHexString(baseMethods) + ", isSmallMethod=" + isSmallMethod); } List<Method> methods = new ArrayList<>(count); if (entsize == 24) { if (isSmallMethod) { throw new UnsupportedOperationException(); } for (int i = 0; i < count; i++) { long name = buffer.getLong(); long types = buffer.getLong(); long imp = buffer.getLong(); Method method = new Method(mm.virtualMemoryAddressToFileOffset(name), mm.virtualMemoryAddressToFileOffset(types), imp, false); methods.add(method); } } else { if (!isSmallMethod) { throw new UnsupportedOperationException(); } for (int i = 0; i < count; i++) { long offset = baseMethods + 8 + (long) entsize * i; long name = buffer.getInt() + offset; long types = buffer.getInt() + offset + 4; long imp = buffer.getInt() + offset + 8; Method method = new Method(mm.virtualMemoryAddressToFileOffset(name), mm.virtualMemoryAddressToFileOffset(types), imp, true); methods.add(method); } } List<Objc2Method> list = new ArrayList<>(count); for (Method method : methods) { list.add(method.createMethod(buffer)); } return list;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/objc/processor/UniObjectiveProcessor.java
UniObjectiveProcessor
loadClasses
class UniObjectiveProcessor extends CDObjectiveCProcessor { public UniObjectiveProcessor(Emulator<?> emulator, MachOModule module) { super(emulator, module); load(); } final void loadClasses() {<FILL_FUNCTION_BODY>} @Override final void loadCategories() { } }
MachO.SegmentCommand64.Section64 section = objcSections.get("__objc_classlist"); if (section == null) { return; } UnidbgPointer classListPointer = UnidbgPointer.pointer(emulator, module.base + section.addr()); assert classListPointer != null; classListPointer.setSize(section.size()); try { for (int i = 0; i < section.size(); i += 8) { Pointer item = classListPointer.getPointer(i); if (item == null) { continue; } ObjcClass objcClass = ObjcClass.create(emulator, item); classList.add(objcClass); } } catch (BackendException e) { throw new IllegalStateException(e); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/patch/LibDispatchPatcher.java
LibDispatchPatcher
patch32
class LibDispatchPatcher extends ModulePatcher { public LibDispatchPatcher() { super("/usr/lib/system/libdispatch.dylib"); } protected void patch32(Emulator<?> emulator, Module module) {<FILL_FUNCTION_BODY>} @Override protected void patch64(Emulator<?> emulator, Module module) { { Pointer pointer = UnidbgPointer.pointer(emulator, module.base + 0x9908); // dispatch_barrier_sync_f assert pointer != null; int code = pointer.getInt(0); if (code != 0xf9402008) { throw new IllegalStateException("code=0x" + Integer.toHexString(code)); } pointer.setInt(0, 0xd2800008); // movz x8, #0 } { Pointer pointer = UnidbgPointer.pointer(emulator, module.base + 0x72e0); // dispatch_sync_f assert pointer != null; int code = pointer.getInt(0); if (code != 0xf9402008) { throw new IllegalStateException("code=0x" + Integer.toHexString(code)); } pointer.setInt(0, 0xd2800008); // movz x8, #0 } { Pointer pointer = UnidbgPointer.pointer(emulator, module.base + 0x9928); // dispatch_barrier_sync_f assert pointer != null; int code = pointer.getInt(0); if (code != 0x350000ea) { throw new IllegalStateException("code=0x" + Integer.toHexString(code)); } pointer.setInt(0, 0x5280000a); // movz w10, #0 } Pointer pointer = UnidbgPointer.pointer(emulator, module.base + 0xa830); // _dispatch_runloop_root_queue_perform_4CF assert pointer != null; int code = pointer.getInt(0); if (code != 0x91336129) { throw new IllegalStateException("code=0x" + Integer.toHexString(code)); } pointer.setInt(0, 0xaa0803e9); // mov x9, x8 } }
Pointer pointer = UnidbgPointer.pointer(emulator, module.base + 0x211b4); // dispatch_semaphore_wait assert pointer != null; int code = pointer.getInt(0); if (code != 0xe59fc004) { throw new IllegalStateException("code=0x" + Integer.toHexString(code)); } pointer.setInt(0, 0xe12fff1e); // bx lr
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/patch/LibDyldPatcher.java
LibDyldPatcher
setSymbolPointer
class LibDyldPatcher extends ModulePatcher { private final Pointer _NSGetArgc; private final Pointer _NSGetArgv; private final Pointer _NSGetEnviron; private final Pointer _NSGetProgname; public LibDyldPatcher(Pointer _NSGetArgc, Pointer _NSGetArgv, Pointer _NSGetEnviron, Pointer _NSGetProgname) { super("/usr/lib/system/libdyld.dylib"); this._NSGetArgc = _NSGetArgc; this._NSGetArgv = _NSGetArgv; this._NSGetEnviron = _NSGetEnviron; this._NSGetProgname = _NSGetProgname; } @Override protected void patch32(Emulator<?> emulator, Module module) { patch(emulator, module); } private void setSymbolPointer(Emulator<?> emulator, Symbol symbol, Pointer pointer) {<FILL_FUNCTION_BODY>} @Override protected void patch64(Emulator<?> emulator, Module module) { patch(emulator, module); } private void patch(Emulator<?> emulator, Module module) { Symbol _NXArgc = module.findSymbolByName("_NXArgc", false); setSymbolPointer(emulator, _NXArgc, _NSGetArgc); Symbol _NXArgv = module.findSymbolByName("_NXArgv", false); setSymbolPointer(emulator, _NXArgv, _NSGetArgv); Symbol _environ = module.findSymbolByName("_environ", false); setSymbolPointer(emulator, _environ, _NSGetEnviron); Symbol ___progname = module.findSymbolByName("___progname", false); setSymbolPointer(emulator, ___progname, _NSGetProgname); } }
Pointer ptr = UnidbgPointer.pointer(emulator, symbol.getAddress()); assert ptr != null; ptr.setPointer(0, pointer.getPointer(0));
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/patch/NewObjcPatcher.java
NewObjcPatcher
patch64
class NewObjcPatcher extends ModulePatcher { public NewObjcPatcher() { super("/usr/lib/libobjc.A.dylib"); } @Override protected void patch32(Emulator<?> emulator, Module module) { throw new UnsupportedOperationException(); } @Override protected void patch64(Emulator<?> emulator, Module module) {<FILL_FUNCTION_BODY>} }
{ Pointer pointer = UnidbgPointer.pointer(emulator, module.base + 0x9f8c); // dataSegmentsContain assert pointer != null; int code = pointer.getInt(0); if (code != 0xd100c3ff) { throw new IllegalStateException("code=0x" + Integer.toHexString(code)); } pointer.setInt(0, 0x52800020); // movz w0, #0x1 } { Pointer pointer = UnidbgPointer.pointer(emulator, module.base + 0x9f90); // dataSegmentsContain assert pointer != null; int code = pointer.getInt(0); if (code != 0xa9014ff4) { throw new IllegalStateException("code=0x" + Integer.toHexString(code)); } pointer.setInt(0, 0xd65f03c0); // ret }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/patch/OldObjcPatcher.java
OldObjcPatcher
hook
class OldObjcPatcher implements HookListener { private long _objc_opt_self; @Override public long hook(SvcMemory svcMemory, String libraryName, String symbolName, long old) {<FILL_FUNCTION_BODY>} }
if ("_objc_opt_self".equals(symbolName)) { if (_objc_opt_self == 0) { _objc_opt_self = svcMemory.registerSvc(new Arm64Svc("objc_opt_self") { @Override public long handle(Emulator<?> emulator) { RegisterContext context = emulator.getContext(); return context.getLongArg(0); } }).peer; } return _objc_opt_self; } return 0;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/service/FrameworkHooker.java
FrameworkHooker
processHook
class FrameworkHooker { private final String moduleName; public FrameworkHooker() { this(null); } public FrameworkHooker(String moduleName) { this.moduleName = moduleName; } public final void processHook(Emulator<?> emulator) {<FILL_FUNCTION_BODY>} protected abstract void doHook(Emulator<?> emulator, Module module); }
Memory memory = emulator.getMemory(); String moduleName = this.moduleName == null ? getClass().getSimpleName() : this.moduleName; Module module = memory.findModule(moduleName); if (module == null) { throw new IllegalStateException("Find module failed: " + moduleName); } doHook(emulator, module);
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/service/Security.java
Security
onCall
class Security extends FrameworkHooker { private static final Log log = LogFactory.getLog(Security.class); private static final int errSecSuccess = 0; /* No error. */ private static final int errSecItemNotFound = -25300; /* The specified item could not be found in the keychain. */ @Override protected void doHook(Emulator<?> emulator, Module module) { Symbol _SecItemCopyMatching = module.findSymbolByName("_SecItemCopyMatching", false); if (_SecItemCopyMatching == null) { throw new IllegalStateException("_SecItemCopyMatching is null"); } Symbol _SecItemDelete = module.findSymbolByName("_SecItemDelete", false); if (_SecItemDelete == null) { throw new IllegalStateException("_SecItemDelete is null"); } Symbol _SecItemAdd = module.findSymbolByName("_SecItemAdd", false); if (_SecItemAdd == null) { throw new IllegalStateException("_SecItemAdd is null"); } ISubstrate substrate = Substrate.getInstance(emulator); substrate.hookFunction(_SecItemCopyMatching, new ReplaceCallback() { @Override public HookStatus onCall(Emulator<?> emulator, long originFunction) { RegisterContext context = emulator.getContext(); Pointer query = context.getPointerArg(0); Pointer result = context.getPointerArg(1); if (log.isDebugEnabled()) { log.debug("_SecItemCopyMatching query=" + query + ", result=" + result); } return HookStatus.LR(emulator, errSecItemNotFound); } }); substrate.hookFunction(_SecItemDelete, new ReplaceCallback() { @Override public HookStatus onCall(Emulator<?> emulator, long originFunction) { RegisterContext context = emulator.getContext(); Pointer query = context.getPointerArg(0); if (log.isDebugEnabled()) { log.debug("_SecItemDelete query=" + query); } return HookStatus.LR(emulator, errSecSuccess); } }); substrate.hookFunction(_SecItemAdd, new ReplaceCallback() { @Override public HookStatus onCall(Emulator<?> emulator, long originFunction) {<FILL_FUNCTION_BODY>} }); } }
RegisterContext context = emulator.getContext(); Pointer attributes = context.getPointerArg(0); Pointer result = context.getPointerArg(1); if (log.isDebugEnabled()) { log.debug("_SecItemAdd attributes=" + attributes + ", result=" + result); } return HookStatus.LR(emulator, errSecSuccess);
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/signal/SigAction.java
SigAction
create
class SigAction extends UnidbgStructure { private static final int SA_SIGINFO = 0x0040; /* signal handler with SA_SIGINFO args */ public static SigAction create(Emulator<?> emulator, Pointer ptr) {<FILL_FUNCTION_BODY>} public int sa_mask; public int sa_flags; public SigAction(Pointer p) { super(p); } public final boolean needSigInfo() { return (sa_flags & SA_SIGINFO) != 0; } public abstract long getSaHandler(); public abstract void setSaHandler(long sa_handler); }
if (ptr == null) { return null; } else { SigAction action = emulator.is64Bit() ? new SigAction64(ptr) : new SigAction32(ptr); action.unpack(); return action; }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/signal/SignalTask.java
SignalTask
callHandler
class SignalTask extends AbstractSignalTask { private final SigAction action; public SignalTask(int signum, SigAction action) { super(signum); this.action = action; } private UnidbgPointer stack; @Override public Number callHandler(SignalOps signalOps, AbstractEmulator<?> emulator) {<FILL_FUNCTION_BODY>} private Number runHandler(AbstractEmulator<?> emulator) { Backend backend = emulator.getBackend(); if (stack == null) { stack = allocateStack(emulator); } if (action.needSigInfo() && infoBlock == null) { infoBlock = emulator.getMemory().malloc(128, true); infoBlock.getPointer().setInt(0, signum); } if (emulator.is32Bit()) { backend.reg_write(ArmConst.UC_ARM_REG_SP, stack.peer); backend.reg_write(ArmConst.UC_ARM_REG_R0, signum); backend.reg_write(ArmConst.UC_ARM_REG_R1, infoBlock == null ? 0 : infoBlock.getPointer().peer); // siginfo_t *info backend.reg_write(ArmConst.UC_ARM_REG_R2, 0); // void *ucontext backend.reg_write(ArmConst.UC_ARM_REG_LR, emulator.getReturnAddress()); } else { backend.reg_write(Arm64Const.UC_ARM64_REG_SP, stack.peer); backend.reg_write(Arm64Const.UC_ARM64_REG_X0, signum); backend.reg_write(Arm64Const.UC_ARM64_REG_X1, infoBlock == null ? 0 : infoBlock.getPointer().peer); // siginfo_t *info backend.reg_write(Arm64Const.UC_ARM64_REG_X2, 0); // void *ucontext backend.reg_write(Arm64Const.UC_ARM64_REG_LR, emulator.getReturnAddress()); } return emulator.emulate(action.getSaHandler(), emulator.getReturnAddress()); } @Override public String toThreadString() { return "SignalTask sa_handler=" + action.getSaHandler() + ", stack=" + stack + ", signum=" + signum; } private MemoryBlock infoBlock; @Override public void destroy(Emulator<?> emulator) { super.destroy(emulator); if (infoBlock != null) { infoBlock.free(); infoBlock = null; } } }
SigSet sigSet = signalOps.getSigMaskSet(); try { long sa_mask = action.sa_mask; if (sigSet == null) { SigSet newSigSet = new UnixSigSet(sa_mask); signalOps.setSigMaskSet(newSigSet); } else { sigSet.blockSigSet(sa_mask); } if (isContextSaved()) { return continueRun(emulator, emulator.getReturnAddress()); } return runHandler(emulator); } finally { signalOps.setSigMaskSet(sigSet); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/simulator/CoreSimulatorResolver.java
CoreSimulatorResolver
resolveLibrary
class CoreSimulatorResolver implements LibraryResolver, IOResolver<DarwinFileIO> { private final File runtimeRoot; public CoreSimulatorResolver(File runtimeRoot) { this.runtimeRoot = runtimeRoot; if (!runtimeRoot.exists() || !runtimeRoot.isDirectory()) { throw new IllegalArgumentException("runtimeRoot=" + runtimeRoot); } } @Override public LibraryFile resolveLibrary(Emulator<?> emulator, String libraryName) {<FILL_FUNCTION_BODY>} @Override public FileResult<DarwinFileIO> resolve(Emulator<DarwinFileIO> emulator, String pathname, int oflags) { return null; } @Override public void onSetToLoader(Emulator<?> emulator) { } }
if ("/usr/lib/system/libsystem_platform.dylib".equals(libraryName) || "/usr/lib/system/libsystem_pthread.dylib".equals(libraryName) || "/usr/lib/system/libsystem_kernel.dylib".equals(libraryName)) { return new SimpleLibraryFile(this, new File(libraryName), libraryName); } File lib = new File(runtimeRoot, libraryName); if (lib.exists()) { return new SimpleLibraryFile(this, lib, libraryName); } return null;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/MachHeader.java
MachHeader
setExecutable
class MachHeader extends UnidbgStructure { public MachHeader(Pointer p) { super(p); } public int magic; public int cpuType; public int cpuSubType; public int fileType; public int ncmds; public int sizeOfCmds; public int flags; @Override protected List<String> getFieldOrder() { return Arrays.asList("magic", "cpuType", "cpuSubType", "fileType", "ncmds", "sizeOfCmds", "flags"); } private int backupFileType; public boolean setExecutable() {<FILL_FUNCTION_BODY>} public void resetFileType() { fileType = backupFileType; this.pack(); } }
if (fileType != MachO.FileType.EXECUTE.id()) { backupFileType = fileType; fileType = (int) MachO.FileType.EXECUTE.id(); this.pack(); return true; } else { return false; }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/SegmentCommand32.java
SegmentCommand32
getFieldOrder
class SegmentCommand32 extends SegmentCommand { public SegmentCommand32(Pointer p) { super(p); } public int vmaddr; @Override public long getVmAddress() { return vmaddr; } @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} }
List<String> list = new ArrayList<>(super.getFieldOrder()); Collections.addAll(list, "segname", "vmaddr"); return list;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/SegmentCommand64.java
SegmentCommand64
getFieldOrder
class SegmentCommand64 extends SegmentCommand { public SegmentCommand64(Pointer p) { super(p); } public long vmaddr; @Override public long getVmAddress() { return vmaddr; } @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} }
List<String> list = new ArrayList<>(super.getFieldOrder()); Collections.addAll(list, "segname", "vmaddr"); return list;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/AttrReference.java
AttrReference
check
class AttrReference extends UnidbgStructure { private final byte[] bytes; public AttrReference(Pointer p, byte[] bytes) { super(p); this.bytes = bytes; attr_length = (int) ARM.alignSize(bytes.length + 1, 8); } public int attr_dataoffset; public int attr_length; @Override protected List<String> getFieldOrder() { return Arrays.asList("attr_dataoffset", "attr_length"); } private boolean started; public void check(UnidbgStructure structure, int size) {<FILL_FUNCTION_BODY>} public void writeAttr(Pointer pointer) { pointer.write(0, Arrays.copyOf(bytes, attr_length), 0, attr_length); pack(); } }
if (structure == this) { started = true; } if (started) { attr_dataoffset += size; }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/cf/CFString.java
CFString
getData
class CFString extends UnidbgStructure { public CFString(Pointer p) { super(p); unpack(); } public long isa; // ptr public long info; // ptr public long data; // ptr public int length; public String getData(Emulator<?> emulator) {<FILL_FUNCTION_BODY>} @Override protected List<String> getFieldOrder() { return Arrays.asList("isa", "info", "data", "length"); } }
Pointer ptr = UnidbgPointer.pointer(emulator, data); byte[] data = Objects.requireNonNull(ptr).getByteArray(0, length); return new String(data, StandardCharsets.UTF_8);
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/DyldCacheHeader.java
DyldCacheHeader
getFieldOrder
class DyldCacheHeader extends UnidbgStructure { public byte[] magic; // e.g. "dyld_v0 i386" public int mappingOffset; // file offset to first dyld_cache_mapping_info public int mappingCount; // number of dyld_cache_mapping_info entries public int imagesOffset; // file offset to first dyld_cache_image_info public int imagesCount; // number of dyld_cache_image_info entries public long dyldBaseAddress; // base address of dyld when cache was built public long codeSignatureOffset; // file offset of code signature blob public long codeSignatureSize; // size of code signature blob (zero means to end of file) public long slideInfoOffset; // file offset of kernel slid info public long slideInfoSize; // size of kernel slid info public long localSymbolsOffset; // file offset of where local symbols are stored public long localSymbolsSize; // size of local symbols information public byte[] uuid = new byte[16]; // unique value for each shared cache file public DyldCacheHeader(Pointer p) { super(p); byte[] magic = "dyld_v1 arm64e".getBytes(); this.magic = Arrays.copyOf(magic, magic.length + 1); } @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} }
return Arrays.asList("magic", "mappingOffset", "mappingCount", "imagesOffset", "imagesCount", "dyldBaseAddress", "codeSignatureOffset", "codeSignatureSize", "slideInfoOffset", "slideInfoSize", "localSymbolsOffset", "localSymbolsSize", "uuid");
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/HostStatisticsReply.java
HostStatisticsReply
writeVMStatistics
class HostStatisticsReply extends UnidbgStructure { public HostStatisticsReply(Pointer p, int size) { super(p); this.data = new byte[size]; } public NDR_record NDR; public int retCode; public int host_info_outCnt; public byte[] data; @Override protected List<String> getFieldOrder() { return Arrays.asList("NDR", "retCode", "host_info_outCnt", "data"); } public void writeVMStatistics() {<FILL_FUNCTION_BODY>} }
VMStatistics vmStatistics = new VMStatistics(getPointer().share(fieldOffset("data"))); vmStatistics.free_count = 0xff37; vmStatistics.active_count = 0x1f426; vmStatistics.inactive_count = 0x4c08; vmStatistics.wire_count = 0x8746; vmStatistics.zero_fill_count = 0x1407025; vmStatistics.reactivations = 0x3e58; vmStatistics.pageins = 0x2eb94; vmStatistics.pageouts = 0x14; vmStatistics.faults = 0x199469d; vmStatistics.cow_faults = 0xb2d22; vmStatistics.lookups = 0x12fd5; vmStatistics.hits = 0xc; vmStatistics.purgeable_count = 0x22a; vmStatistics.purges = 0x2ca0; vmStatistics.speculative_count = 0xc9d; vmStatistics.pack(); this.unpack();
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/MachMsgHeader.java
MachMsgHeader
setMsgBits
class MachMsgHeader extends UnidbgStructure implements DarwinSyscall { public MachMsgHeader(Pointer p) { super(p); } public int msgh_bits; public int msgh_size; public int msgh_remote_port; public int msgh_local_port; public int msgh_voucher_port; public int msgh_id; public void setMsgBits(boolean complex) {<FILL_FUNCTION_BODY>} @Override protected List<String> getFieldOrder() { return Arrays.asList("msgh_bits", "msgh_size", "msgh_remote_port", "msgh_local_port", "msgh_voucher_port", "msgh_id"); } }
msgh_bits &= 0xff; if (complex) { msgh_bits |= MACH_MSGH_BITS_COMPLEX; }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/Pthread.java
Pthread
create
class Pthread extends UnidbgStructure { public static Pthread create(Emulator<?> emulator, Pointer pointer) {<FILL_FUNCTION_BODY>} private static final int MAXTHREADNAMESIZE = 64; public static final int PTHREAD_CREATE_JOINABLE = 1; public Pthread(Emulator<?> emulator, byte[] data) { super(emulator, data); } public Pthread(Pointer p) { super(p); } public byte[] pthread_name = new byte[MAXTHREADNAMESIZE]; // includes NUL public String getName() { return new String(pthread_name, StandardCharsets.UTF_8).trim(); } public UnidbgPointer getTSD() { return (UnidbgPointer) getPointer().share(fieldOffset("self")); } public Pointer getErrno() { return getPointer().share(fieldOffset("errno")); } public abstract void setStack(Pointer stackAddress, long stackSize); public abstract void setThreadId(int threadId); public abstract int getThreadId(); public abstract void setSig(long sig); public abstract void setDetached(int detached); public abstract void setExitValue(int value); public abstract void setSelf(Pointer self); public abstract void setMachThreadSelf(long machThreadSelf); public abstract Pointer getErrnoPointer(Emulator<?> emulator); }
Pthread pthread = emulator.is64Bit() ? new Pthread64(pointer) : new Pthread32(pointer); pthread.unpack(); return pthread;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/Pthread32.java
Pthread32
getFieldOrder
class Pthread32 extends Pthread { public Pthread32(Emulator<?> emulator, byte[] data) { super(emulator, data); setAlignType(ALIGN_NONE); } public Pthread32(Pointer p) { super(p); setAlignType(ALIGN_NONE); } @Override public void setThreadId(int threadId) { this.thread_id = threadId; } @Override public int getThreadId() { return (int) thread_id; } @Override public void setDetached(int detached) { this.detached |= PTHREAD_CREATE_JOINABLE; } @Override public void setExitValue(int value) { this.exit_value = value; } public int sig; // _PTHREAD_SIG public int __cleanup_stack; public int childrun; public int lock; public int detached; public long thread_id; // 64-bit unique thread id public int pad0; public int fun; // thread start routine public int arg; // thread start routine argument public int exit_value; // thread exit value storage public int joiner_notify; // pthread_join notification public int max_tsd_key; public int cancel_state; // whether the thread can be cancelled public int cancel_error; public int err_no; // thread-local errno public int joiner; public int sched_priority; public TailqPthread32 plist; // global thread list public int stackaddr; // base of the stack public int stacksize; // size of stack (page multiple and >= PTHREAD_STACK_MIN) @Override public void setStack(Pointer stackAddress, long stackSize) { this.stackaddr = (int) UnidbgPointer.nativeValue(stackAddress); this.stacksize = (int) stackSize; } @Override public void setSig(long sig) { this.sig = (int) sig; } public int freeaddr; // stack/thread allocation base address public int freesize; // stack/thread allocation size public int guardsize; // guard page size in bytes @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} // thread specific data public int self; public int errno; public int mig_reply; public int machThreadSelf; @Override public void setSelf(Pointer self) { this.self = (int) UnidbgPointer.nativeValue(self); } @Override public void setMachThreadSelf(long machThreadSelf) { this.machThreadSelf = (int) machThreadSelf; } @Override public Pointer getErrnoPointer(Emulator<?> emulator) { return UnidbgPointer.pointer(emulator, errno); } }
return Arrays.asList("sig", "__cleanup_stack", "childrun", "lock", "detached", "thread_id", "fun", "arg", "exit_value", "joiner_notify", "max_tsd_key", "cancel_state", "cancel_error", "err_no", "joiner", "sched_priority", "plist", "pad0", "pthread_name", "stackaddr", "stacksize", "freeaddr", "freesize", "guardsize", "self", "errno", "mig_reply", "machThreadSelf");
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/Pthread64.java
Pthread64
getFieldOrder
class Pthread64 extends Pthread { public Pthread64(Pointer p) { super(p); } @Override public void setThreadId(int threadId) { this.thread_id = threadId; } @Override public int getThreadId() { return (int) thread_id; } public long sig; // _PTHREAD_SIG public long __cleanup_stack; public int childrun; public int lock; public int detached; public int pad0; public long thread_id; // 64-bit unique thread id public long fun; // thread start routine public long arg; // thread start routine argument public long exit_value; // thread exit value storage public long joiner_notify; // pthread_join notification public int max_tsd_key; public int cancel_state; // whether the thread can be cancelled public int cancel_error; public int err_no; // thread-local errno public long joiner; public SchedParam param; public TailqPthread64 plist; // global thread list public long stackaddr; // base of the stack public long stacksize; // size of stack (page multiple and >= PTHREAD_STACK_MIN) @Override public void setStack(Pointer stackAddress, long stackSize) { this.stackaddr = UnidbgPointer.nativeValue(stackAddress); this.stacksize = stackSize; } public long freeaddr; // stack/thread allocation base address public long freesize; // stack/thread allocation size public long guardsize; // guard page size in bytes @Override public void setSig(long sig) { throw new UnsupportedOperationException(); } @Override public void setDetached(int detached) { throw new UnsupportedOperationException(); } @Override public void setExitValue(int value) { throw new UnsupportedOperationException(); } @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} // thread specific data public long self; public long errno; public long mig_reply; public long machThreadSelf; @Override public void setSelf(Pointer self) { this.self = UnidbgPointer.nativeValue(self); } @Override public void setMachThreadSelf(long machThreadSelf) { this.machThreadSelf = machThreadSelf; } @Override public Pointer getErrnoPointer(Emulator<?> emulator) { return UnidbgPointer.pointer(emulator, errno); } }
return Arrays.asList("sig", "__cleanup_stack", "childrun", "lock", "detached", "pad0", "thread_id", "fun", "arg", "exit_value", "joiner_notify", "max_tsd_key", "cancel_state", "cancel_error", "err_no", "joiner", "param", "plist", "pthread_name", "stackaddr", "stacksize", "freeaddr", "freesize", "guardsize", "self", "errno", "mig_reply", "machThreadSelf");
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/RUsage64.java
RUsage64
fillDefault
class RUsage64 extends UnidbgStructure { public TimeVal64 ru_utime; /* user time used */ public TimeVal64 ru_stime; /* system time used */ public long ru_maxrss; /* max resident set size */ public long ru_ixrss; /* integral shared text memory size */ public long ru_idrss; /* integral unshared data size */ public long ru_isrss; /* integral unshared stack size */ public long ru_minflt; /* page reclaims */ public long ru_majflt; /* page faults */ public long ru_nswap; /* swaps */ public long ru_inblock; /* block input operations */ public long ru_oublock; /* block output operations */ public long ru_msgsnd; /* messages sent */ public long ru_msgrcv; /* messages received */ public long ru_nsignals; /* signals received */ public long ru_nvcsw; /* voluntary context switches */ public long ru_nivcsw; /* involuntary context switches */ public void fillDefault() {<FILL_FUNCTION_BODY>} public RUsage64(Pointer p) { super(p); } @Override protected List<String> getFieldOrder() { return Arrays.asList("ru_utime", "ru_stime", "ru_maxrss", "ru_ixrss", "ru_idrss", "ru_isrss", "ru_minflt", "ru_majflt", "ru_nswap", "ru_inblock", "ru_oublock", "ru_msgsnd", "ru_msgrcv", "ru_nsignals", "ru_nvcsw", "ru_nivcsw"); } }
ru_utime.tv_sec = 1; ru_utime.tv_usec = System.nanoTime(); ru_stime.tv_sec = 2; ru_stime.tv_usec = System.nanoTime(); ru_maxrss = 0; ru_ixrss = 0; ru_idrss = 0; ru_isrss = 0; ru_minflt = 0; ru_majflt = 0; ru_nswap = 0; ru_inblock = 0; ru_oublock = 0; ru_msgsnd = 0; ru_msgrcv = 0; ru_nsignals = 0; ru_nvcsw = 0; ru_nivcsw = 0;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/Stat.java
Stat
getFieldOrder
class Stat extends StatStructure { public Stat(byte[] data) { super(data); } public Stat(Pointer p) { super(p); setAlignType(Structure.ALIGN_NONE); unpack(); } public TimeSpec32 st_atimespec; /* time of last access */ public TimeSpec32 st_mtimespec; /* time of last data modification */ public TimeSpec32 st_ctimespec; /* time of last status change */ public TimeSpec32 st_birthtimespec; /* time of file creation(birth) */ @Override public void setSt_atimespec(long tv_sec, long tv_nsec) { st_atimespec.tv_sec = (int) tv_sec; st_atimespec.tv_nsec = (int) tv_nsec; } @Override public void setSt_mtimespec(long tv_sec, long tv_nsec) { st_mtimespec.tv_sec = (int) tv_sec; st_mtimespec.tv_nsec = (int) tv_nsec; } @Override public void setSt_ctimespec(long tv_sec, long tv_nsec) { st_ctimespec.tv_sec = (int) tv_sec; st_ctimespec.tv_nsec = (int) tv_nsec; } @Override public void setSt_birthtimespec(long tv_sec, long tv_nsec) { st_birthtimespec.tv_sec = (int) tv_sec; st_birthtimespec.tv_nsec = (int) tv_nsec; } @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} }
return Arrays.asList("st_dev", "st_mode", "st_nlink", "st_ino", "st_uid", "st_gid", "st_rdev", "st_atimespec", "st_mtimespec", "st_ctimespec", "st_birthtimespec", "st_size", "st_blocks", "st_blksize", "st_flags", "st_gen");
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/Stat64.java
Stat64
getFieldOrder
class Stat64 extends StatStructure { public Stat64(byte[] data) { super(data); } public Stat64(Pointer p) { super(p); unpack(); } public TimeSpec64 st_atimespec; /* time of last access */ public TimeSpec64 st_mtimespec; /* time of last data modification */ public TimeSpec64 st_ctimespec; /* time of last status change */ public TimeSpec64 st_birthtimespec; /* time of file creation(birth) */ @Override public void setSt_atimespec(long tv_sec, long tv_nsec) { st_atimespec.tv_sec = tv_sec; st_atimespec.tv_nsec = tv_nsec; } @Override public void setSt_mtimespec(long tv_sec, long tv_nsec) { st_mtimespec.tv_sec = tv_sec; st_mtimespec.tv_nsec = tv_nsec; } @Override public void setSt_ctimespec(long tv_sec, long tv_nsec) { st_ctimespec.tv_sec = tv_sec; st_ctimespec.tv_nsec = tv_nsec; } @Override public void setSt_birthtimespec(long tv_sec, long tv_nsec) { st_birthtimespec.tv_sec = tv_sec; st_birthtimespec.tv_nsec = tv_nsec; } @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} }
return Arrays.asList("st_dev", "st_mode", "st_nlink", "st_ino", "st_uid", "st_gid", "st_rdev", "st_atimespec", "st_mtimespec", "st_ctimespec", "st_birthtimespec", "st_size", "st_blocks", "st_blksize", "st_flags", "st_gen");
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/StatFS.java
StatFS
setFsTypeName
class StatFS extends UnidbgStructure { private static final int MFSTYPENAMELEN = 16; /* length of fs type name including null */ private static final int MAXPATHLEN = 1024; /* max bytes in pathname */ public StatFS(byte[] data) { super(data); } public StatFS(Pointer p) { super(p); } public int f_bsize; /* fundamental file system block size */ public int f_iosize; /* optimal transfer block size */ public long f_blocks; /* total data blocks in file system */ public long f_bfree; /* free blocks in fs */ public long f_bavail; /* free blocks avail to non-superuser */ public long f_files; /* total file nodes in file system */ public long f_ffree; /* free file nodes in fs */ public long f_fsid; /* file system id */ public int f_owner; /* user that mounted the filesystem */ public int f_type; /* type of filesystem */ public int f_flags; /* copy of mount exported flags */ public int f_fssubtype; /* fs sub-type (flavor) */ public byte[] f_fstypename = new byte[MFSTYPENAMELEN]; /* fs type name */ public byte[] f_mntonname = new byte[MAXPATHLEN]; /* directory on which mounted */ public byte[] f_mntfromname = new byte[MAXPATHLEN]; /* mounted filesystem */ public int[] f_reserved = new int[8]; /* For future use */ public void setFsTypeName(String fsTypeName) {<FILL_FUNCTION_BODY>} public void setMntOnName(String mntOnName) { if (mntOnName == null) { throw new NullPointerException(); } byte[] data = mntOnName.getBytes(StandardCharsets.UTF_8); if (data.length + 1 >= MAXPATHLEN) { throw new IllegalStateException("Invalid MAXPATHLEN: " + MAXPATHLEN); } f_mntonname = Arrays.copyOf(data, MAXPATHLEN); } public void setMntFromName(String mntFromName) { if (mntFromName == null) { throw new NullPointerException(); } byte[] data = mntFromName.getBytes(StandardCharsets.UTF_8); if (data.length + 1 >= MAXPATHLEN) { throw new IllegalStateException("Invalid MAXPATHLEN: " + MAXPATHLEN); } f_mntfromname = Arrays.copyOf(data, MAXPATHLEN); } @Override protected List<String> getFieldOrder() { return Arrays.asList("f_bsize", "f_iosize", "f_blocks", "f_bfree", "f_bavail", "f_files", "f_ffree", "f_fsid", "f_owner", "f_type", "f_flags", "f_fssubtype", "f_fstypename", "f_mntonname", "f_mntfromname", "f_reserved"); } }
if (fsTypeName == null) { throw new NullPointerException(); } byte[] data = fsTypeName.getBytes(StandardCharsets.UTF_8); if (data.length + 1 >= MFSTYPENAMELEN) { throw new IllegalStateException("Invalid MFSTYPENAMELEN: " + MFSTYPENAMELEN); } f_fstypename = Arrays.copyOf(data, MFSTYPENAMELEN);
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/objc/ClassRW32.java
ClassRW32
ro
class ClassRW32 extends ClassRW { public int ro; public int methodList; public int properties; public int protocols; public int firstSubclass; public int nextSiblingClass; public int demangledName; public ClassRW32(Pointer p) { super(p); } @Override public ClassRO ro(Emulator<?> emulator) {<FILL_FUNCTION_BODY>} }
ClassRO ro = new ClassRO32(UnidbgPointer.pointer(emulator, this.ro)); ro.unpack(); return ro;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/objc/ClassRW64.java
ClassRW64
ro
class ClassRW64 extends ClassRW { public long ro; public long methodList; public long properties; public long protocols; public long firstSubclass; public long nextSiblingClass; public long demangledName; public ClassRW64(Pointer p) { super(p); } @Override public ClassRO ro(Emulator<?> emulator) {<FILL_FUNCTION_BODY>} }
long ro = this.ro; boolean newObjc = (ro & 1) != 0; if (newObjc) { // override objc runtime Pointer pointer = UnidbgPointer.pointer(emulator, ro & FAST_DATA_MASK); assert pointer != null; ro = pointer.getLong(0); } ClassRO classRO = new ClassRO64(UnidbgPointer.pointer(emulator, ro & FAST_DATA_MASK)); classRO.unpack(); return classRO;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/objc/ObjcClass.java
ObjcClass
data
class ObjcClass extends ObjcObject implements ObjcConstants, com.github.unidbg.ios.objc.processor.ObjcClass { public static ObjcClass create(Emulator<?> emulator, Pointer pointer) { if (pointer == null) { return null; } ObjcClass objcClass = emulator.is64Bit() ? new ObjcClass64(emulator, pointer) : new ObjcClass32(emulator, pointer); objcClass.unpack(); return objcClass; } protected ObjcClass(Emulator<?> emulator, Pointer p) { super(emulator, p); } @SuppressWarnings("unused") public ObjcObject newObjc() { return callObjc("new"); } @Override protected List<String> getFieldOrder() { List<String> fields = new ArrayList<>(super.getFieldOrder()); Collections.addAll(fields, "superClass", "cache", "vtable", "data"); return fields; } protected abstract UnidbgPointer getDataPointer(Emulator<?> emulator); private ClassRW data() {<FILL_FUNCTION_BODY>} private ClassRO ro() { UnidbgPointer pointer = getDataPointer(emulator); long address = pointer.peer & FAST_DATA_MASK; ClassRO classRO = emulator.is64Bit() ? new ClassRO64(UnidbgPointer.pointer(emulator, address)) : new ClassRO32(UnidbgPointer.pointer(emulator, address)); classRO.unpack(); return classRO; } public boolean isMetaClass() { return (data().ro(emulator).flags & RO_META) != 0; } @Override public ObjcClass getMeta() { if (isMetaClass()) { return this; } else { return getObjClass(); } } private boolean isRealized() { return (data().flags & RW_REALIZED) != 0; } private boolean isFuture() { return (data().flags & RO_FUTURE) != 0; } @Override public String getName() { ClassRO ro; if (isRealized() || isFuture()) { ClassRW data = data(); ro = data.ro(emulator); } else { ro = ro(); } Pointer pointer = ro.getNamePointer(emulator); if (pointer == null) { ClassRW data = data(); throw new IllegalStateException("data=" + data); } return pointer.getString(0); } }
UnidbgPointer pointer = getDataPointer(emulator); long address = pointer.peer & FAST_DATA_MASK; ClassRW classRW = emulator.is64Bit() ? new ClassRW64(UnidbgPointer.pointer(emulator, address)) : new ClassRW32(UnidbgPointer.pointer(emulator, address)); classRW.unpack(); return classRW;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/objc/ObjcObject.java
ObjcObject
create
class ObjcObject extends UnidbgStructure { public static ObjcObject create(Emulator<?> emulator, Pointer pointer) {<FILL_FUNCTION_BODY>} final Emulator<?> emulator; protected ObjcObject(Emulator<?> emulator, Pointer p) { super(p); this.emulator = emulator; } public ObjcClass getObjClass() { if (emulator.is64Bit()) { UnidbgPointer pointer = getIsa(emulator); long address = pointer.peer & 0x1fffffff8L; return ObjcClass.create(emulator, UnidbgPointer.pointer(emulator, address)); } else { return ObjcClass.create(emulator, getIsa(emulator)); } } public abstract UnidbgPointer getIsa(Emulator<?> emulator); public void setInstanceVariable(String name, Object value) { ObjC objc = ObjC.getInstance(emulator); objc.setInstanceVariable(emulator, this, name, value); } public UnidbgPointer getInstanceVariable(String name) { ObjC objc = ObjC.getInstance(emulator); return objc.getInstanceVariable(emulator, this, name); } public UnidbgPointer call(String selectorName, Object... args) { ObjC objc = ObjC.getInstance(emulator); Pointer selector = objc.registerName(selectorName); List<Object> list = new ArrayList<>(args.length + 2); list.add(this); list.add(selector); Collections.addAll(list, args); Number number = objc.msgSend(emulator, list.toArray()); return UnidbgPointer.pointer(emulator, number); } public ObjcObject callObjc(String selectorName, Object... args) { return create(emulator, call(selectorName, args)); } public long callObjcLong(String selectorName, Object... args) { UnidbgPointer ptr = call(selectorName, args); return ptr == null ? 0 : ptr.peer; } public int callObjcInt(String selectorName, Object... args) { return (int) (callObjcLong(selectorName, args) & 0xffffffffL); } @SuppressWarnings("unused") public ObjcClass toClass() { return ObjcClass.create(emulator, getPointer()); } @SuppressWarnings("unused") public NSData toNSData() { return NSData.create(this); } public NSString toNSString() { return NSString.create(this); } @SuppressWarnings("unused") public NSArray toNSArray() { return NSArray.create(this); } public String getDescription() { ObjcObject str = callObjc("description"); if (str == null) { return "<description not available>"; } else { return str.toNSString().getString(); } } @Override protected List<String> getFieldOrder() { return Collections.singletonList("isa"); } }
if (pointer == null) { return null; } else { ObjcObject obj = emulator.is64Bit() ? new ObjcObject64(emulator, pointer) : new ObjcObject32(emulator, pointer); obj.unpack(); return obj; }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/DyldAllImageInfos32.java
DyldAllImageInfos32
getFieldOrder
class DyldAllImageInfos32 extends UnidbgStructure { public DyldAllImageInfos32(Pointer p) { super(p); } public int version; public int infoArrayCount; public int infoArray; public int notification; public byte processDetachedFromSharedRegion; public byte libSystemInitialized; public int dyldImageLoadAddress; public int jitInfo; public int dyldVersion; public int errorMessage; public int terminationFlags; public int coreSymbolicationShmPage; public int systemOrderFlag; public int uuidArrayCount; public int uuidArray; public int dyldAllImageInfosAddress; public int initialImageCount; public int errorKind; public int errorClientOfDylibPath; public int errorTargetDylibPath; public int errorSymbol; public int sharedCacheSlide; public byte[] sharedCacheUUID = new byte[16]; public int[] reserved = new int[16]; @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} }
return Arrays.asList("version", "infoArrayCount", "infoArray", "notification", "processDetachedFromSharedRegion", "libSystemInitialized", "dyldImageLoadAddress", "jitInfo", "dyldVersion", "errorMessage", "terminationFlags", "coreSymbolicationShmPage", "systemOrderFlag", "uuidArrayCount", "uuidArray", "dyldAllImageInfosAddress", "initialImageCount", "errorKind", "errorClientOfDylibPath", "errorTargetDylibPath", "errorSymbol", "sharedCacheSlide", "sharedCacheUUID", "reserved");
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/DyldAllImageInfos64.java
DyldAllImageInfos64
getFieldOrder
class DyldAllImageInfos64 extends UnidbgStructure { public DyldAllImageInfos64(Pointer p) { super(p); } public int version; public int infoArrayCount; public long infoArray; public long notification; public byte processDetachedFromSharedRegion; public byte libSystemInitialized; public long dyldImageLoadAddress; public long jitInfo; public long dyldVersion; public long errorMessage; public long terminationFlags; public long coreSymbolicationShmPage; public long systemOrderFlag; public long uuidArrayCount; public long uuidArray; public long dyldAllImageInfosAddress; public long initialImageCount; public long errorKind; public long errorClientOfDylibPath; public long errorTargetDylibPath; public long errorSymbol; public long sharedCacheSlide; public byte[] sharedCacheUUID = new byte[16]; public long[] reserved = new long[16]; @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} }
return Arrays.asList("version", "infoArrayCount", "infoArray", "notification", "processDetachedFromSharedRegion", "libSystemInitialized", "dyldImageLoadAddress", "jitInfo", "dyldVersion", "errorMessage", "terminationFlags", "coreSymbolicationShmPage", "systemOrderFlag", "uuidArrayCount", "uuidArray", "dyldAllImageInfosAddress", "initialImageCount", "errorKind", "errorClientOfDylibPath", "errorTargetDylibPath", "errorSymbol", "sharedCacheSlide", "sharedCacheUUID", "reserved");
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/EProc32.java
EProc32
getFieldOrder
class EProc32 extends UnidbgStructure { private static final int WMESGLEN = 7; private static final int COMAPT_MAXLOGNAME = 12; public EProc32(Pointer p) { super(p); } public int e_paddr; /* address of proc */ public int e_sess; /* session pointer */ public Pcred32 e_pcred; /* process credentials */ public Ucred e_ucred; /* current credentials */ public VmSpace32 e_vm; /* address space */ public int e_ppid; /* parent process id */ public int e_pgid; /* process group id */ public short e_jobc; /* job control counter */ public int e_tdev; /* controlling tty dev */ public int e_tpgid; /* tty process group id */ public int e_tsess; /* tty session pointer */ public byte[] e_wmesg = new byte[WMESGLEN + 1]; /* wchan message */ public int e_xsize; /* text size */ public short e_xrssize; /* text rss */ public short e_xccount; /* text references */ public short e_xswrss; public int e_flag; public byte[] e_login = new byte[COMAPT_MAXLOGNAME]; /* short setlogin() name */ public int[] e_spare = new int[4]; @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} }
return Arrays.asList("e_paddr", "e_sess", "e_pcred", "e_ucred", "e_vm", "e_ppid", "e_pgid", "e_jobc", "e_tdev", "e_tpgid", "e_tsess", "e_wmesg", "e_xsize", "e_xrssize", "e_xccount", "e_xswrss", "e_flag", "e_login", "e_spare");
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/EProc64.java
EProc64
getFieldOrder
class EProc64 extends UnidbgStructure { private static final int WMESGLEN = 7; private static final int COMAPT_MAXLOGNAME = 12; public EProc64(Pointer p) { super(p); } public long e_paddr; /* address of proc */ public long e_sess; /* session pointer */ public Pcred64 e_pcred; /* process credentials */ public Ucred e_ucred; /* current credentials */ public VmSpace64 e_vm; /* address space */ public int e_ppid; /* parent process id */ public int e_pgid; /* process group id */ public short e_jobc; /* job control counter */ public int e_tdev; /* controlling tty dev */ public int e_tpgid; /* tty process group id */ public long e_tsess; /* tty session pointer */ public byte[] e_wmesg = new byte[WMESGLEN + 1]; /* wchan message */ public int e_xsize; /* text size */ public short e_xrssize; /* text rss */ public short e_xccount; /* text references */ public short e_xswrss; public int e_flag; public byte[] e_login = new byte[COMAPT_MAXLOGNAME]; /* short setlogin() name */ public int[] e_spare = new int[4]; @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} }
return Arrays.asList("e_paddr", "e_sess", "e_pcred", "e_ucred", "e_vm", "e_ppid", "e_pgid", "e_jobc", "e_tdev", "e_tpgid", "e_tsess", "e_wmesg", "e_xsize", "e_xrssize", "e_xccount", "e_xswrss", "e_flag", "e_login", "e_spare");
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/ExternProc32.java
ExternProc32
getFieldOrder
class ExternProc32 extends UnidbgStructure { private static final int MAXCOMLEN = 16; /* max command name remembered */ public ExternProc32(Pointer p) { super(p); } public int __p_forw; // ptr public int __p_back; // ptr public int p_vmspace; /* Address space. */ public int p_sigacts; /* Signal actions, state (PROC ONLY). */ public int p_flag; /* P_* flags. */ public byte p_stat; /* S* process status. */ public int p_pid; /* Process identifier. */ public int p_oppid; /* Save parent pid during ptrace. XXX */ public int p_dupfd; /* Sideways return value from fdopen. XXX */ public int user_stack; /* where user stack was allocated */ public int exit_thread; /* XXX Which thread is exiting? */ public int p_debugger; /* allow to debug */ public boolean sigwait; /* indication to suspend */ public int p_estcpu; /* Time averaged value of p_cpticks. */ public int p_cpticks; /* Ticks of cpu time. */ public int p_pctcpu; /* %cpu for this process during p_swtime */ public int p_wchan; /* Sleep address. */ public int p_wmesg; /* Reason for sleep. */ public int p_swtime; /* Time swapped in or out. */ public int p_slptime; /* Time since last blocked. */ public ITimerVal32 p_realtimer; /* Alarm timer. */ public TimeVal32 p_rtime; /* Real time. */ public long p_uticks; /* Statclock hits in user mode. */ public long p_sticks; /* Statclock hits in system mode. */ public long p_iticks; /* Statclock hits processing intr. */ public int p_traceflag; /* Kernel trace points. */ public int p_tracep; /* Trace to vnode. */ public int p_siglist; public int p_textvp; /* Vnode of executable. */ public int p_holdcnt; /* If non-zero, don't swap. */ public int p_sigmask; public int p_sigignore; /* Signals being ignored. */ public int p_sigcatch; /* Signals being caught by user. */ public byte p_priority; /* Process priority. */ public byte p_usrpri; /* User-priority based on p_cpu and p_nice. */ public byte p_nice; /* Process "nice" value. */ public byte[] p_comm = new byte[MAXCOMLEN + 1]; public int p_pgrp; /* Pointer to process group. */ public int p_addr; /* Kernel virtual addr of u-area (PROC ONLY). */ public short p_xstat; /* Exit status for wait; also stop signal. */ public short p_acflag; /* Accounting flags. */ public int p_ru; /* Exit information. XXX */ @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} }
return Arrays.asList("__p_forw", "__p_back", "p_vmspace", "p_sigacts", "p_flag", "p_stat", "p_pid", "p_oppid", "p_dupfd", "user_stack", "exit_thread", "p_debugger", "sigwait", "p_estcpu", "p_cpticks", "p_pctcpu", "p_wchan", "p_wmesg", "p_swtime", "p_slptime", "p_realtimer", "p_rtime", "p_uticks", "p_sticks", "p_iticks", "p_traceflag", "p_tracep", "p_siglist", "p_textvp", "p_holdcnt", "p_sigmask", "p_sigignore", "p_sigcatch", "p_priority", "p_usrpri", "p_nice", "p_comm", "p_pgrp", "p_addr", "p_xstat", "p_acflag", "p_ru");
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/ExternProc64.java
ExternProc64
getFieldOrder
class ExternProc64 extends UnidbgStructure implements DarwinSyscall { public ExternProc64(Pointer p) { super(p); } public long __p_forw; public long __p_back; public long p_vmspace; /* Address space. */ public long p_sigacts; /* Signal actions, state (PROC ONLY). */ public int p_flag; /* P_* flags. */ public byte p_stat; /* S* process status. */ public int p_pid; /* Process identifier. */ public int p_oppid; /* Save parent pid during ptrace. XXX */ public int p_dupfd; /* Sideways return value from fdopen. XXX */ public long user_stack; /* where user stack was allocated */ public long exit_thread; /* XXX Which thread is exiting? */ public int p_debugger; /* allow to debug */ public boolean sigwait; /* indication to suspend */ public int p_estcpu; /* Time averaged value of p_cpticks. */ public int p_cpticks; /* Ticks of cpu time. */ public int p_pctcpu; /* %cpu for this process during p_swtime */ public long p_wchan; /* Sleep address. */ public long p_wmesg; /* Reason for sleep. */ public int p_swtime; /* Time swapped in or out. */ public int p_slptime; /* Time since last blocked. */ public ITimerVal64 p_realtimer; /* Alarm timer. */ public TimeVal64 p_rtime; /* Real time. */ public long p_uticks; /* Statclock hits in user mode. */ public long p_sticks; /* Statclock hits in system mode. */ public long p_iticks; /* Statclock hits processing intr. */ public int p_traceflag; /* Kernel trace points. */ public long p_tracep; /* Trace to vnode. */ public int p_siglist; public long p_textvp; /* Vnode of executable. */ public int p_holdcnt; /* If non-zero, don't swap. */ public int p_sigmask; public int p_sigignore; /* Signals being ignored. */ public int p_sigcatch; /* Signals being caught by user. */ public byte p_priority; /* Process priority. */ public byte p_usrpri; /* User-priority based on p_cpu and p_nice. */ public byte p_nice; /* Process "nice" value. */ public byte[] p_comm = new byte[MAXCOMLEN + 1]; public long p_pgrp; /* Pointer to process group. */ public long p_addr; /* Kernel virtual addr of u-area (PROC ONLY). */ public short p_xstat; /* Exit status for wait; also stop signal. */ public short p_acflag; /* Accounting flags. */ public long p_ru; /* Exit information. XXX */ @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} }
return Arrays.asList("__p_forw", "__p_back", "p_vmspace", "p_sigacts", "p_flag", "p_stat", "p_pid", "p_oppid", "p_dupfd", "user_stack", "exit_thread", "p_debugger", "sigwait", "p_estcpu", "p_cpticks", "p_pctcpu", "p_wchan", "p_wmesg", "p_swtime", "p_slptime", "p_realtimer", "p_rtime", "p_uticks", "p_sticks", "p_iticks", "p_traceflag", "p_tracep", "p_siglist", "p_textvp", "p_holdcnt", "p_sigmask", "p_sigignore", "p_sigcatch", "p_priority", "p_usrpri", "p_nice", "p_comm", "p_pgrp", "p_addr", "p_xstat", "p_acflag", "p_ru");
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/IfData.java
IfData
getFieldOrder
class IfData extends UnidbgStructure { public IfData(Pointer p) { super(p); } /* generic interface information */ public byte ifi_type; /* ethernet, tokenring, etc */ public byte ifi_typelen; /* Length of frame type id */ public byte ifi_physical; /* e.g., AUI, Thinnet, 10base-T, etc */ public byte ifi_addrlen; /* media address length */ public byte ifi_hdrlen; /* media header length */ public byte ifi_recvquota; /* polling quota for receive intrs */ public byte ifi_xmitquota; /* polling quota for xmit intrs */ public byte ifi_unused1; /* for future use */ public int ifi_mtu; /* maximum transmission unit */ public int ifi_metric; /* routing metric (external only) */ public int ifi_baudrate; /* linespeed */ /* volatile statistics */ public int ifi_ipackets; /* packets received on interface */ public int ifi_ierrors; /* input errors on interface */ public int ifi_opackets; /* packets sent on interface */ public int ifi_oerrors; /* output errors on interface */ public int ifi_collisions; /* collisions on csma interfaces */ public int ifi_ibytes; /* total number of octets received */ public int ifi_obytes; /* total number of octets sent */ public int ifi_imcasts; /* packets received via multicast */ public int ifi_omcasts; /* packets sent via multicast */ public int ifi_iqdrops; /* dropped on input, this interface */ public int ifi_noproto; /* destined for unsupported protocol */ public int ifi_recvtiming; /* usec spent receiving when timing */ public int ifi_xmittiming; /* usec spent xmitting when timing */ public TimeVal32 ifi_lastchange; /* time of last administrative change */ public int ifi_unused2; /* used to be the default_proto */ public int ifi_hwassist; /* HW offload capabilities */ public int ifi_reserved1; /* for future use */ public int ifi_reserved2; /* for future use */ @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} }
return Arrays.asList("ifi_type", "ifi_typelen", "ifi_physical", "ifi_addrlen", "ifi_hdrlen", "ifi_recvquota", "ifi_xmitquota", "ifi_unused1", "ifi_mtu", "ifi_metric", "ifi_baudrate", "ifi_ipackets", "ifi_ierrors", "ifi_opackets", "ifi_oerrors", "ifi_collisions", "ifi_ibytes", "ifi_obytes", "ifi_imcasts", "ifi_omcasts", "ifi_iqdrops", "ifi_noproto", "ifi_recvtiming", "ifi_xmittiming", "ifi_lastchange", "ifi_unused2", "ifi_hwassist", "ifi_reserved1", "ifi_reserved2");
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/TaskDyldInfo.java
TaskDyldInfo
allocateAllImage
class TaskDyldInfo extends UnidbgStructure { private static final Log log = LogFactory.getLog(TaskDyldInfo.class); private static final String DYLD_VERSION = "324.1"; private static final int TASK_DYLD_ALL_IMAGE_INFO_32 = 0; /* format value */ private static final int TASK_DYLD_ALL_IMAGE_INFO_64 = 1; /* format value */ public TaskDyldInfo(Pointer p) { super(p); setAlignType(Structure.ALIGN_NONE); } private static MemoryBlock infoArrayBlock; private static Pointer dyldVersion; private static MemoryBlock dyldAllImageInfosAddressBlock; public void allocateAllImage(Emulator<?> emulator) {<FILL_FUNCTION_BODY>} private void allocateAllImage64(SvcMemory svcMemory, Collection<Module> modules, MachOModule libdyld) { int all_image_info_size = UnidbgStructure.calculateSize(DyldAllImageInfos64.class); this.all_image_info_format = TASK_DYLD_ALL_IMAGE_INFO_64; this.all_image_info_size = all_image_info_size; UnidbgPointer all_image_info_addr = dyldAllImageInfosAddressBlock.getPointer(); this.all_image_info_addr = all_image_info_addr.peer; int size = UnidbgStructure.calculateSize(DyldImageInfo64.class); Pointer infoArray = infoArrayBlock.getPointer(); Pointer pointer = infoArray; for (Module module : modules) { MachOModule mm = (MachOModule) module; DyldImageInfo64 info = new DyldImageInfo64(pointer); info.imageLoadAddress = mm.machHeader; info.imageFilePath = UnidbgPointer.nativeValue(mm.createPathMemory(svcMemory)); info.imageFileModDate = 0; info.pack(); pointer = pointer.share(size); } DyldAllImageInfos64 infos = new DyldAllImageInfos64(all_image_info_addr); infos.version = 14; infos.infoArrayCount = modules.size(); infos.infoArray = UnidbgPointer.nativeValue(infoArray); infos.libSystemInitialized = Constants.YES; infos.dyldImageLoadAddress = libdyld == null ? 0x0L : libdyld.machHeader; infos.dyldVersion = UnidbgPointer.nativeValue(dyldVersion); infos.uuidArrayCount = 0; infos.uuidArray = 0L; infos.dyldAllImageInfosAddress = UnidbgPointer.nativeValue(all_image_info_addr); infos.initialImageCount = modules.size(); infos.pack(); } private void allocateAllImage32(SvcMemory svcMemory, Collection<Module> modules, MachOModule libdyld) { int all_image_info_size = UnidbgStructure.calculateSize(DyldAllImageInfos32.class); this.all_image_info_format = TASK_DYLD_ALL_IMAGE_INFO_32; this.all_image_info_size = all_image_info_size; UnidbgPointer all_image_info_addr = dyldAllImageInfosAddressBlock.getPointer(); this.all_image_info_addr = all_image_info_addr.peer; int size = UnidbgStructure.calculateSize(DyldImageInfo32.class); Pointer infoArray = infoArrayBlock.getPointer(); Pointer pointer = infoArray; for (Module module : modules) { MachOModule mm = (MachOModule) module; DyldImageInfo32 info = new DyldImageInfo32(pointer); info.imageLoadAddress = (int) mm.machHeader; info.imageFilePath = (int) UnidbgPointer.nativeValue(mm.createPathMemory(svcMemory)); info.imageFileModDate = 0; info.pack(); pointer = pointer.share(size); } DyldAllImageInfos32 infos = new DyldAllImageInfos32(all_image_info_addr); infos.version = 14; infos.infoArrayCount = modules.size(); infos.infoArray = (int) UnidbgPointer.nativeValue(infoArray); infos.libSystemInitialized = Constants.YES; infos.dyldImageLoadAddress = libdyld == null ? 0x0 : (int) libdyld.machHeader; infos.dyldVersion = (int) UnidbgPointer.nativeValue(dyldVersion); infos.uuidArrayCount = 0; infos.uuidArray = 0; infos.dyldAllImageInfosAddress = (int) UnidbgPointer.nativeValue(all_image_info_addr); infos.initialImageCount = modules.size(); infos.pack(); } public long all_image_info_addr; public long all_image_info_size; public int all_image_info_format; @Override protected List<String> getFieldOrder() { return Arrays.asList("all_image_info_addr", "all_image_info_size", "all_image_info_format"); } }
SvcMemory svcMemory = emulator.getSvcMemory(); MachOLoader loader = (MachOLoader) emulator.getMemory(); Collection<Module> modules = loader.getLoadedModules(); for (Iterator<Module> iterator = modules.iterator(); iterator.hasNext(); ) { Module module = iterator.next(); if (module.isVirtual()) { iterator.remove(); } } if (dyldVersion == null) { dyldVersion = svcMemory.writeStackString(DYLD_VERSION); } if (infoArrayBlock == null) { infoArrayBlock = loader.malloc(emulator.getPageAlign(), true); } if (dyldAllImageInfosAddressBlock == null) { dyldAllImageInfosAddressBlock = loader.malloc(emulator.getPageAlign(), true); } if (emulator.getSyscallHandler().isVerbose()) { System.out.printf("task_info TASK_DYLD_INFO called with %d modules from %s%n", modules.size(), emulator.getContext().getLRPointer()); } if (log.isTraceEnabled()) { emulator.attach().debug(); } MachOModule libdyld = (MachOModule) emulator.getMemory().findModule("libdyld.dylib"); if (emulator.is64Bit()) { allocateAllImage64(svcMemory, modules, libdyld); } else { allocateAllImage32(svcMemory, modules, libdyld); }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/struct/sysctl/TaskVmInfo64.java
TaskVmInfo64
getFieldOrder
class TaskVmInfo64 extends UnidbgStructure { public TaskVmInfo64(Pointer p) { super(p); } public TaskVmInfo64(byte[] data) { super(data); } public long virtual_size; /* virtual memory size (bytes) */ public int region_count; /* number of memory regions */ public int page_size; public long resident_size; /* resident memory size (bytes) */ public long resident_size_peak; /* peak resident size (bytes) */ public long device; public long device_peak; public long internal; public long internal_peak; public long external; public long external_peak; public long reusable; public long reusable_peak; public long purgeable_volatile_pmap; public long purgeable_volatile_resident; public long purgeable_volatile_virtual; public long compressed; public long compressed_peak; public long compressed_lifetime; @Override protected List<String> getFieldOrder() {<FILL_FUNCTION_BODY>} }
return Arrays.asList("virtual_size", "region_count", "page_size", "resident_size", "resident_size_peak", "device", "device_peak", "internal", "internal_peak", "external", "external_peak", "reusable", "reusable_peak", "purgeable_volatile_pmap", "purgeable_volatile_resident", "purgeable_volatile_virtual", "compressed", "compressed_peak", "compressed_lifetime");
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/thread/BsdThread.java
BsdThread
runThread
class BsdThread extends ThreadTask { private final UnidbgPointer thread_start; private final UnidbgPointer thread; private final UnidbgPointer fun; private final UnidbgPointer arg; private final UnidbgPointer stack; private final int stackSize; public BsdThread(Emulator<?> emulator, int tid, UnidbgPointer thread_start, UnidbgPointer thread, UnidbgPointer fun, UnidbgPointer arg, int stackSize) { super(tid, emulator.getReturnAddress()); this.thread_start = thread_start; this.thread = thread; this.fun = fun; this.arg = arg; this.stack = thread; this.stackSize = stackSize; } @Override protected Number runThread(AbstractEmulator<?> emulator) {<FILL_FUNCTION_BODY>} @Override public boolean setErrno(Emulator<?> emulator, int errno) { Pthread pthread = Pthread.create(emulator, thread); Pointer errnoPointer = pthread.getErrnoPointer(emulator); if (errnoPointer != null) { errnoPointer.setInt(0, errno); return true; } return super.setErrno(emulator, errno); } @Override public String toThreadString() { return "BsdThread fun=" + fun + ", arg=" + arg + ", stack=" + stack; } }
Backend backend = emulator.getBackend(); int pflags = 0; if (emulator.is32Bit()) { backend.reg_write(ArmConst.UC_ARM_REG_R0, this.thread.peer); backend.reg_write(ArmConst.UC_ARM_REG_R1, getId()); backend.reg_write(ArmConst.UC_ARM_REG_R2, this.fun.peer); backend.reg_write(ArmConst.UC_ARM_REG_R3, this.arg == null ? 0 : this.arg.peer); backend.reg_write(ArmConst.UC_ARM_REG_R4, stackSize); backend.reg_write(ArmConst.UC_ARM_REG_R5, pflags); backend.reg_write(ArmConst.UC_ARM_REG_SP, stack.peer); backend.reg_write(ArmConst.UC_ARM_REG_LR, until); } else { backend.reg_write(Arm64Const.UC_ARM64_REG_X0, this.thread.peer); backend.reg_write(Arm64Const.UC_ARM64_REG_X1, getId()); backend.reg_write(Arm64Const.UC_ARM64_REG_X2, this.fun.peer); backend.reg_write(Arm64Const.UC_ARM64_REG_X3, this.arg == null ? 0 : this.arg.peer); backend.reg_write(Arm64Const.UC_ARM64_REG_X4, stackSize); backend.reg_write(Arm64Const.UC_ARM64_REG_X5, pflags); backend.reg_write(Arm64Const.UC_ARM64_REG_SP, stack.peer); backend.reg_write(Arm64Const.UC_ARM64_REG_LR, until); } return emulator.emulate(thread_start.peer, until);
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/thread/BsdThreadCreatePatcher64.java
BsdThreadCreatePatcher64
handle
class BsdThreadCreatePatcher64 extends Arm64Svc { private static final Log log = LogFactory.getLog(BsdThreadCreatePatcher64.class); private final ThreadJoinVisitor visitor; private final AtomicLong value_ptr; private int threadId; BsdThreadCreatePatcher64(ThreadJoinVisitor visitor, AtomicLong value_ptr) { this.visitor = visitor; this.value_ptr = value_ptr; } @Override public long handle(Emulator<?> emulator) {<FILL_FUNCTION_BODY>} @Override public UnidbgPointer onRegister(SvcMemory svcMemory, int svcNumber) { try (Keystone keystone = new Keystone(KeystoneArchitecture.Arm64, KeystoneMode.LittleEndian)) { KeystoneEncoded encoded = keystone.assemble(Arrays.asList( "sub sp, sp, #0x10", "stp x29, x30, [sp]", "svc #0x" + Integer.toHexString(svcNumber), "ldr x13, [sp]", "add sp, sp, #0x8", "cmp x13, #0", "b.eq #0x48", "ldp x0, x13, [sp]", "add sp, sp, #0x10", "mov x8, #0", "mov x12, #0x" + Integer.toHexString(svcNumber), "mov x16, #0x" + Integer.toHexString(Svc.PRE_CALLBACK_SYSCALL_NUMBER), "svc #0", "blr x13", "mov x8, #0", "mov x12, #0x" + Integer.toHexString(svcNumber), "mov x16, #0x" + Integer.toHexString(Svc.POST_CALLBACK_SYSCALL_NUMBER), "svc #0", "ldr x0, [sp]", "add sp, sp, #0x8", "ldp x29, x30, [sp]", "add sp, sp, #0x10", "ret")); byte[] code = encoded.getMachineCode(); UnidbgPointer pointer = svcMemory.allocate(code.length, getClass().getSimpleName()); pointer.write(code); return pointer; } } @Override public void handlePreCallback(Emulator<?> emulator) { if (visitor.isSaveContext()) { emulator.pushContext(0x4); } } @Override public void handlePostCallback(Emulator<?> emulator) { super.handlePostCallback(emulator); value_ptr.set(emulator.getContext().getLongArg(0)); } }
RegisterContext context = emulator.getContext(); Pointer start_routine = context.getPointerArg(0); Pointer arg = context.getPointerArg(1); Pointer stack = context.getPointerArg(2); Pointer thread = context.getPointerArg(3); int flags = context.getIntArg(4); log.info("bsdthread_create start_routine=" + start_routine + ", arg=" + arg + ", stack=" + stack + ", thread=" + thread + ", flags=0x" + Integer.toHexString(flags)); if (thread == null) { MemoryBlock memoryBlock = emulator.getMemory().malloc(0x100, true); thread = memoryBlock.getPointer(); } Pthread pThread = new Pthread64(thread); pThread.setSelf(thread); pThread.setMachThreadSelf(DarwinSyscall.STATIC_PORT); pThread.pack(); Backend backend = emulator.getBackend(); boolean join = visitor == null || visitor.canJoin(start_routine, ++threadId); UnidbgPointer pointer = UnidbgPointer.register(emulator, Arm64Const.UC_ARM64_REG_SP); try { pointer = pointer.share(-8, 0); pointer.setPointer(0, thread); if (join) { pointer = pointer.share(-8, 0); pointer.setPointer(0, start_routine); pointer = pointer.share(-8, 0); pointer.setPointer(0, arg); } pointer = pointer.share(-8, 0); // can join pointer.setLong(0, join ? 1 : 0); } finally { backend.reg_write(Arm64Const.UC_ARM64_REG_SP, pointer.peer); } return 0;
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/thread/DarwinThread.java
DarwinThread
runThread
class DarwinThread extends ThreadTask { private static final Log log = LogFactory.getLog(DarwinThread.class); private final UnidbgPointer start_routine; private final UnidbgPointer arg; private final Pthread pthread; private final int threadId; private final Pointer errno; public DarwinThread(Emulator<?> emulator, UnidbgPointer start_routine, UnidbgPointer arg, Pthread pthread, int threadId, Pointer errno) { super(emulator.getPid(), emulator.getReturnAddress()); this.start_routine = start_routine; this.arg = arg; this.pthread = pthread; this.threadId = threadId; this.errno = errno; } @Override public void setResult(Emulator<?> emulator, Number ret) { super.setResult(emulator, ret); pthread.unpack(); pthread.setExitValue(ret.intValue()); pthread.pack(); } public int getThreadId() { return threadId; } @Override public String toThreadString() { return "DarwinThread start_routine=" + start_routine + ", arg=" + arg; } @Override protected Number runThread(AbstractEmulator<?> emulator) {<FILL_FUNCTION_BODY>} @Override public boolean setErrno(Emulator<?> emulator, int errno) { this.errno.setInt(0, errno); return true; } }
Backend backend = emulator.getBackend(); UnidbgPointer stack = allocateStack(emulator); pthread.setStack(stack, THREAD_STACK_SIZE); pthread.pack(); backend.reg_write(emulator.is32Bit() ? ArmConst.UC_ARM_REG_R0 : Arm64Const.UC_ARM64_REG_X0, this.arg == null ? 0L : this.arg.peer); backend.reg_write(emulator.is32Bit() ? ArmConst.UC_ARM_REG_SP : Arm64Const.UC_ARM64_REG_SP, stack.peer); UnidbgPointer tsd = pthread.getTSD(); tsd.setPointer(0, pthread.getPointer()); tsd.setPointer(emulator.getPointerSize(), pthread.getErrno()); pthread.getErrno().setPointer(0, errno); if (emulator.is32Bit()) { backend.reg_write(ArmConst.UC_ARM_REG_C13_C0_3, tsd.peer); backend.reg_write(ArmConst.UC_ARM_REG_LR, until); } else { backend.reg_write(Arm64Const.UC_ARM64_REG_TPIDRRO_EL0, tsd.peer); backend.reg_write(Arm64Const.UC_ARM64_REG_LR, until); } return emulator.emulate(this.start_routine.peer, until);
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/thread/SemWaiter.java
SemWaiter
onContinueRun
class SemWaiter extends AbstractWaiter implements Waiter { private final int sem; private final Map<Integer, Boolean> semaphoreMap; private final long waitMillis; private final long startWaitTimeInMillis; public SemWaiter(int sem, Map<Integer, Boolean> semaphoreMap) { this(sem, semaphoreMap, 0L, 0); } public SemWaiter(int sem, Map<Integer, Boolean> semaphoreMap, long tv_sec, int tv_nsec) { this.sem = sem; this.semaphoreMap = semaphoreMap; this.waitMillis = tv_sec * 1000L + tv_nsec / 1000L; this.startWaitTimeInMillis = System.currentTimeMillis(); } private boolean timeout; @Override public boolean canDispatch() { Boolean val = semaphoreMap.remove(sem); if (val != null) { return true; } if (waitMillis > 0) { if (System.currentTimeMillis() - startWaitTimeInMillis >= waitMillis) { timeout = true; return true; } Thread.yield(); } return false; } @Override public void onContinueRun(Emulator<?> emulator) {<FILL_FUNCTION_BODY>} }
if (timeout) { Backend backend = emulator.getBackend(); emulator.getMemory().setErrno(DarwinSyscall.ETIMEDOUT); if (emulator.is32Bit()) { backend.reg_write(ArmConst.UC_ARM_REG_R0, -1); } else { backend.reg_write(Arm64Const.UC_ARM64_REG_X0, -1); } }
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/com/github/unidbg/ios/thread/ThreadJoin64.java
ThreadJoin64
patch
class ThreadJoin64 { public static void patch(final Emulator<?> emulator, InlineHook inlineHook, final ThreadJoinVisitor visitor) {<FILL_FUNCTION_BODY>} }
Memory memory = emulator.getMemory(); Module kernel = memory.findModule("libsystem_kernel.dylib"); Module pthread = memory.findModule("libsystem_pthread.dylib"); Symbol thread_create = kernel.findSymbolByName("___bsdthread_create", false); Symbol pthread_join = pthread.findSymbolByName("_pthread_join", false); if (thread_create == null || pthread_join == null) { throw new IllegalStateException("thread_create=" + thread_create + ", pthread_join=" + pthread_join); } final AtomicLong value_ptr = new AtomicLong(); inlineHook.replace(pthread_join, new ReplaceCallback() { @Override public HookStatus onCall(Emulator<?> emulator, HookContext context, long originFunction) { Pointer ptr = context.getPointerArg(1); if (ptr != null) { ptr.setLong(0, value_ptr.get()); } return HookStatus.LR(emulator, 0); } }); inlineHook.replace(thread_create, new BsdThreadCreatePatcher64(visitor, value_ptr));
zhkl0228_unidbg
unidbg/unidbg-ios/src/main/java/io/kaitai/MachO.java
MachO
_read
class MachO extends KaitaiStruct { public static MachO fromFile(String fileName) throws IOException { return new MachO(new ByteBufferKaitaiStream(fileName)); } public enum MagicType { FAT_LE(0xbebafecaL), FAT_BE(0xcafebabeL), MACHO_LE_X86(0xcefaedfeL), MACHO_LE_X64(0xcffaedfeL), MACHO_BE_X86(0xfeedfaceL), MACHO_BE_X64(0xfeedfacfL); private final long id; MagicType(long id) { this.id = id; } public long id() { return id; } private static final Map<Long, MagicType> byId = new HashMap<Long, MagicType>(6); static { for (MagicType e : MagicType.values()) byId.put(e.id(), e); } public static MagicType byId(long id) { return byId.get(id); } } public enum CpuType { VAX(0x1L), ROMP(0x2L), NS32032(0x4L), NS32332(0x5L), I386(0x7L), MIPS(0x8L), NS32532(0x9L), HPPA(0xbL), ARM(0xcL), MC88000(0xdL), SPARC(0xeL), I860(0xfL), I860_LITTLE(0x10L), RS6000(0x11L), POWERPC(0x12L), ABI64(0x1000000L), X86_64(0x1000007L), ARM64(0x100000cL), POWERPC64(0x1000012L), ANY(0xffffffffL); private final long id; CpuType(long id) { this.id = id; } public long id() { return id; } private static final Map<Long, CpuType> byId = new HashMap<Long, CpuType>(20); static { for (CpuType e : CpuType.values()) byId.put(e.id(), e); } public static CpuType byId(long id) { return byId.get(id); } } public enum FileType { OBJECT(0x1L), EXECUTE(0x2L), FVMLIB(0x3L), CORE(0x4L), PRELOAD(0x5L), DYLIB(0x6L), DYLINKER(0x7L), BUNDLE(0x8L), DYLIB_STUB(0x9L), DSYM(0xaL), KEXT_BUNDLE(0xbL); private final long id; FileType(long id) { this.id = id; } public long id() { return id; } private static final Map<Long, FileType> byId = new HashMap<Long, FileType>(11); static { for (FileType e : FileType.values()) byId.put(e.id(), e); } public static FileType byId(long id) { return byId.get(id); } } public enum LoadCommandType { SEGMENT(0x1L), SYMTAB(0x2L), SYMSEG(0x3L), THREAD(0x4L), UNIX_THREAD(0x5L), LOAD_FVM_LIB(0x6L), ID_FVM_LIB(0x7L), IDENT(0x8L), FVM_FILE(0x9L), PREPAGE(0xaL), DYSYMTAB(0xbL), LOAD_DYLIB(0xcL), ID_DYLIB(0xdL), LOAD_DYLINKER(0xeL), ID_DYLINKER(0xfL), PREBOUND_DYLIB(0x10L), ROUTINES(0x11L), SUB_FRAMEWORK(0x12L), SUB_UMBRELLA(0x13L), SUB_CLIENT(0x14L), SUB_LIBRARY(0x15L), TWOLEVEL_HINTS(0x16L), PREBIND_CKSUM(0x17L), SEGMENT_64(0x19L), ROUTINES_64(0x1aL), UUID(0x1bL), CODE_SIGNATURE(0x1dL), SEGMENT_SPLIT_INFO(0x1eL), LAZY_LOAD_DYLIB(0x20L), ENCRYPTION_INFO(0x21L), DYLD_INFO(0x22L), VERSION_MIN_MACOSX(0x24L), VERSION_MIN_IPHONEOS(0x25L), FUNCTION_STARTS(0x26L), DYLD_ENVIRONMENT(0x27L), DATA_IN_CODE(0x29L), SOURCE_VERSION(0x2aL), DYLIB_CODE_SIGN_DRS(0x2bL), ENCRYPTION_INFO_64(0x2cL), LINKER_OPTION(0x2dL), LINKER_OPTIMIZATION_HINT(0x2eL), VERSION_MIN_TVOS(0x2fL), VERSION_MIN_WATCHOS(0x30L), BUILD_VERSION(0x32L), REQ_DYLD(0x80000000L), LOAD_WEAK_DYLIB(0x80000018L), RPATH(0x8000001cL), REEXPORT_DYLIB(0x8000001fL), DYLD_INFO_ONLY(0x80000022L), LOAD_UPWARD_DYLIB(0x80000023L), MAIN(0x80000028L), DYLD_EXPORTS_TRIE(0x80000033L), DYLD_CHAINED_FIXUPS(0x80000034L), DYLD_FILESET_ENTRY(0x80000035L); private final long id; LoadCommandType(long id) { this.id = id; } public long id() { return id; } private static final Map<Long, LoadCommandType> byId = new HashMap<Long, LoadCommandType>(54); static { for (LoadCommandType e : LoadCommandType.values()) byId.put(e.id(), e); } public static LoadCommandType byId(long id) { return byId.get(id); } } public MachO(KaitaiStream _io) { this(_io, null, null); } public MachO(KaitaiStream _io, KaitaiStruct _parent) { this(_io, _parent, null); } public MachO(KaitaiStream _io, KaitaiStruct _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root == null ? this : _root; _read(); } private void _read() { this.magic = MagicType.byId(this._io.readU4be()); if ( ((magic() == MagicType.FAT_BE) || (magic() == MagicType.FAT_LE)) ) { this.fatHeader = new FatHeader(this._io, this, _root); } if ( ((magic() != MagicType.FAT_BE) && (magic() != MagicType.FAT_LE)) ) { this.header = new MachHeader(this._io, this, _root); } if ( ((magic() != MagicType.FAT_BE) && (magic() != MagicType.FAT_LE)) ) { this.loadCommands = new ArrayList<LoadCommand>(); for (int i = 0; i < header().ncmds(); i++) { this.loadCommands.add(new LoadCommand(this._io, this, _root)); } } } public static class RpathCommand extends KaitaiStruct { public static RpathCommand fromFile(String fileName) throws IOException { return new RpathCommand(new ByteBufferKaitaiStream(fileName)); } public RpathCommand(KaitaiStream _io) { this(_io, null, null); } public RpathCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public RpathCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.pathOffset = this._io.readU4le(); this.path = new String(this._io.readBytesTerm((byte) 0, false, true, true), Charset.forName("utf-8")); } private long pathOffset; private String path; private MachO _root; private MachO.LoadCommand _parent; public long pathOffset() { return pathOffset; } public String path() { return path; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class Uleb128 extends KaitaiStruct { public static Uleb128 fromFile(String fileName) throws IOException { return new Uleb128(new ByteBufferKaitaiStream(fileName)); } public Uleb128(KaitaiStream _io) { this(_io, null, null); } public Uleb128(KaitaiStream _io, KaitaiStruct _parent) { this(_io, _parent, null); } public Uleb128(KaitaiStream _io, KaitaiStruct _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() {<FILL_FUNCTION_BODY>} private Integer value; public Integer value() { if (this.value != null) return this.value; int _tmp = (int) (((KaitaiStream.mod(b1(), 128) << 0) + ((b1() & 128) == 0 ? 0 : ((KaitaiStream.mod(b2(), 128) << 7) + ((b2() & 128) == 0 ? 0 : ((KaitaiStream.mod(b3(), 128) << 14) + ((b3() & 128) == 0 ? 0 : ((KaitaiStream.mod(b4(), 128) << 21) + ((b4() & 128) == 0 ? 0 : ((KaitaiStream.mod(b5(), 128) << 28) + ((b5() & 128) == 0 ? 0 : ((KaitaiStream.mod(b6(), 128) << 35) + ((b6() & 128) == 0 ? 0 : ((KaitaiStream.mod(b7(), 128) << 42) + ((b7() & 128) == 0 ? 0 : ((KaitaiStream.mod(b8(), 128) << 49) + ((b8() & 128) == 0 ? 0 : ((KaitaiStream.mod(b9(), 128) << 56) + ((b8() & 128) == 0 ? 0 : (KaitaiStream.mod(b10(), 128) << 63)))))))))))))))))))); this.value = _tmp; return this.value; } private int b1; private Integer b2; private Integer b3; private Integer b4; private Integer b5; private Integer b6; private Integer b7; private Integer b8; private Integer b9; private Integer b10; private MachO _root; private KaitaiStruct _parent; public int b1() { return b1; } public Integer b2() { return b2; } public Integer b3() { return b3; } public Integer b4() { return b4; } public Integer b5() { return b5; } public Integer b6() { return b6; } public Integer b7() { return b7; } public Integer b8() { return b8; } public Integer b9() { return b9; } public Integer b10() { return b10; } public MachO _root() { return _root; } public KaitaiStruct _parent() { return _parent; } } public static class SourceVersionCommand extends KaitaiStruct { public static SourceVersionCommand fromFile(String fileName) throws IOException { return new SourceVersionCommand(new ByteBufferKaitaiStream(fileName)); } public SourceVersionCommand(KaitaiStream _io) { this(_io, null, null); } public SourceVersionCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public SourceVersionCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.version = this._io.readU8le(); } private long version; private MachO _root; private MachO.LoadCommand _parent; public long version() { return version; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class CsBlob extends KaitaiStruct { public static CsBlob fromFile(String fileName) throws IOException { return new CsBlob(new ByteBufferKaitaiStream(fileName)); } public enum CsMagic { BLOB_WRAPPER(0xfade0b01L), REQUIREMENT(0xfade0c00L), REQUIREMENTS(0xfade0c01L), CODE_DIRECTORY(0xfade0c02L), EMBEDDED_SIGNATURE(0xfade0cc0L), DETACHED_SIGNATURE(0xfade0cc1L), ENTITLEMENT(0xfade7171L); private final long id; CsMagic(long id) { this.id = id; } public long id() { return id; } private static final Map<Long, CsMagic> byId = new HashMap<Long, CsMagic>(7); static { for (CsMagic e : CsMagic.values()) byId.put(e.id(), e); } public static CsMagic byId(long id) { return byId.get(id); } } public CsBlob(KaitaiStream _io) { this(_io, null, null); } public CsBlob(KaitaiStream _io, KaitaiStruct _parent) { this(_io, _parent, null); } public CsBlob(KaitaiStream _io, KaitaiStruct _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.magic = CsMagic.byId(this._io.readU4be()); this.length = this._io.readU4be(); { CsMagic on = magic(); if (on != null) { switch (magic()) { case REQUIREMENT: { this._raw_body = this._io.readBytes((length() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new Requirement(_io__raw_body, this, _root); break; } case CODE_DIRECTORY: { this._raw_body = this._io.readBytes((length() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new CodeDirectory(_io__raw_body, this, _root); break; } case ENTITLEMENT: { this._raw_body = this._io.readBytes((length() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new Entitlement(_io__raw_body, this, _root); break; } case REQUIREMENTS: { this._raw_body = this._io.readBytes((length() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new Requirements(_io__raw_body, this, _root); break; } case BLOB_WRAPPER: { this._raw_body = this._io.readBytes((length() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new BlobWrapper(_io__raw_body, this, _root); break; } case EMBEDDED_SIGNATURE: { this._raw_body = this._io.readBytes((length() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new SuperBlob(_io__raw_body, this, _root); break; } case DETACHED_SIGNATURE: { this._raw_body = this._io.readBytes((length() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new SuperBlob(_io__raw_body, this, _root); break; } default: { this.body = this._io.readBytes((length() - 8)); break; } } } else { this.body = this._io.readBytes((length() - 8)); } } } public static class Entitlement extends KaitaiStruct { public static Entitlement fromFile(String fileName) throws IOException { return new Entitlement(new ByteBufferKaitaiStream(fileName)); } public Entitlement(KaitaiStream _io) { this(_io, null, null); } public Entitlement(KaitaiStream _io, MachO.CsBlob _parent) { this(_io, _parent, null); } public Entitlement(KaitaiStream _io, MachO.CsBlob _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.data = this._io.readBytesFull(); } private byte[] data; private MachO _root; private MachO.CsBlob _parent; public byte[] data() { return data; } public MachO _root() { return _root; } public MachO.CsBlob _parent() { return _parent; } } public static class CodeDirectory extends KaitaiStruct { public static CodeDirectory fromFile(String fileName) throws IOException { return new CodeDirectory(new ByteBufferKaitaiStream(fileName)); } public CodeDirectory(KaitaiStream _io) { this(_io, null, null); } public CodeDirectory(KaitaiStream _io, MachO.CsBlob _parent) { this(_io, _parent, null); } public CodeDirectory(KaitaiStream _io, MachO.CsBlob _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.version = this._io.readU4be(); this.flags = this._io.readU4be(); this.hashOffset = this._io.readU4be(); this.identOffset = this._io.readU4be(); this.nSpecialSlots = this._io.readU4be(); this.nCodeSlots = this._io.readU4be(); this.codeLimit = this._io.readU4be(); this.hashSize = this._io.readU1(); this.hashType = this._io.readU1(); this.spare1 = this._io.readU1(); this.pageSize = this._io.readU1(); this.spare2 = this._io.readU4be(); if (version() >= 131328) { this.scatterOffset = this._io.readU4be(); } if (version() >= 131584) { this.teamIdOffset = this._io.readU4be(); } } private String ident; public String ident() { if (this.ident != null) return this.ident; long _pos = this._io.pos(); this._io.seek((identOffset() - 8)); this.ident = new String(this._io.readBytesTerm((byte) 0, false, true, true), Charset.forName("utf-8")); this._io.seek(_pos); return this.ident; } private String teamId; public String teamId() { if (this.teamId != null) return this.teamId; long _pos = this._io.pos(); this._io.seek((teamIdOffset() - 8)); this.teamId = new String(this._io.readBytesTerm((byte) 0, false, true, true), Charset.forName("utf-8")); this._io.seek(_pos); return this.teamId; } private ArrayList<byte[]> hashes; public ArrayList<byte[]> hashes() { if (this.hashes != null) return this.hashes; long _pos = this._io.pos(); this._io.seek(((hashOffset() - 8) - (hashSize() * nSpecialSlots()))); this.hashes = new ArrayList<byte[]>(); for (int i = 0; i < (nSpecialSlots() + nCodeSlots()); i++) { this.hashes.add(this._io.readBytes(hashSize())); } this._io.seek(_pos); return this.hashes; } private long version; private long flags; private long hashOffset; private long identOffset; private long nSpecialSlots; private long nCodeSlots; private long codeLimit; private int hashSize; private int hashType; private int spare1; private int pageSize; private long spare2; private Long scatterOffset; private Long teamIdOffset; private MachO _root; private MachO.CsBlob _parent; public long version() { return version; } public long flags() { return flags; } public long hashOffset() { return hashOffset; } public long identOffset() { return identOffset; } public long nSpecialSlots() { return nSpecialSlots; } public long nCodeSlots() { return nCodeSlots; } public long codeLimit() { return codeLimit; } public int hashSize() { return hashSize; } public int hashType() { return hashType; } public int spare1() { return spare1; } public int pageSize() { return pageSize; } public long spare2() { return spare2; } public Long scatterOffset() { return scatterOffset; } public Long teamIdOffset() { return teamIdOffset; } public MachO _root() { return _root; } public MachO.CsBlob _parent() { return _parent; } } public static class Data extends KaitaiStruct { public static Data fromFile(String fileName) throws IOException { return new Data(new ByteBufferKaitaiStream(fileName)); } public Data(KaitaiStream _io) { this(_io, null, null); } public Data(KaitaiStream _io, KaitaiStruct _parent) { this(_io, _parent, null); } public Data(KaitaiStream _io, KaitaiStruct _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.length = this._io.readU4be(); this.value = this._io.readBytes(length()); this.padding = this._io.readBytes((4 - (length() & 3))); } private long length; private byte[] value; private byte[] padding; private MachO _root; private KaitaiStruct _parent; public long length() { return length; } public byte[] value() { return value; } public byte[] padding() { return padding; } public MachO _root() { return _root; } public KaitaiStruct _parent() { return _parent; } } public static class SuperBlob extends KaitaiStruct { public static SuperBlob fromFile(String fileName) throws IOException { return new SuperBlob(new ByteBufferKaitaiStream(fileName)); } public SuperBlob(KaitaiStream _io) { this(_io, null, null); } public SuperBlob(KaitaiStream _io, MachO.CsBlob _parent) { this(_io, _parent, null); } public SuperBlob(KaitaiStream _io, MachO.CsBlob _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.count = this._io.readU4be(); this.blobs = new ArrayList<BlobIndex>(); for (int i = 0; i < count(); i++) { this.blobs.add(new BlobIndex(this._io, this, _root)); } } private long count; private ArrayList<BlobIndex> blobs; private MachO _root; private MachO.CsBlob _parent; public long count() { return count; } public ArrayList<BlobIndex> blobs() { return blobs; } public MachO _root() { return _root; } public MachO.CsBlob _parent() { return _parent; } } public static class Expr extends KaitaiStruct { public static Expr fromFile(String fileName) throws IOException { return new Expr(new ByteBufferKaitaiStream(fileName)); } public enum OpEnum { FALSE(0x0L), TRUE(0x1L), IDENT(0x2L), APPLE_ANCHOR(0x3L), ANCHOR_HASH(0x4L), INFO_KEY_VALUE(0x5L), AND_OP(0x6L), OR_OP(0x7L), CD_HASH(0x8L), NOT_OP(0x9L), INFO_KEY_FIELD(0xaL), CERT_FIELD(0xbL), TRUSTED_CERT(0xcL), TRUSTED_CERTS(0xdL), CERT_GENERIC(0xeL), APPLE_GENERIC_ANCHOR(0xfL), ENTITLEMENT_FIELD(0x10L); private final long id; OpEnum(long id) { this.id = id; } public long id() { return id; } private static final Map<Long, OpEnum> byId = new HashMap<Long, OpEnum>(17); static { for (OpEnum e : OpEnum.values()) byId.put(e.id(), e); } public static OpEnum byId(long id) { return byId.get(id); } } public enum CertSlot { LEFT_CERT(0x0L), ANCHOR_CERT(0xffffffffL); private final long id; CertSlot(long id) { this.id = id; } public long id() { return id; } private static final Map<Long, CertSlot> byId = new HashMap<Long, CertSlot>(2); static { for (CertSlot e : CertSlot.values()) byId.put(e.id(), e); } public static CertSlot byId(long id) { return byId.get(id); } } public Expr(KaitaiStream _io) { this(_io, null, null); } public Expr(KaitaiStream _io, KaitaiStruct _parent) { this(_io, _parent, null); } public Expr(KaitaiStream _io, KaitaiStruct _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.op = OpEnum.byId(this._io.readU4be()); { OpEnum on = op(); if (on != null) { switch (op()) { case IDENT: { this.data = new IdentExpr(this._io, this, _root); break; } case OR_OP: { this.data = new OrExpr(this._io, this, _root); break; } case INFO_KEY_VALUE: { this.data = new Data(this._io, this, _root); break; } case ANCHOR_HASH: { this.data = new AnchorHashExpr(this._io, this, _root); break; } case INFO_KEY_FIELD: { this.data = new InfoKeyFieldExpr(this._io, this, _root); break; } case NOT_OP: { this.data = new Expr(this._io, this, _root); break; } case ENTITLEMENT_FIELD: { this.data = new EntitlementFieldExpr(this._io, this, _root); break; } case TRUSTED_CERT: { this.data = new CertSlotExpr(this._io, this, _root); break; } case AND_OP: { this.data = new AndExpr(this._io, this, _root); break; } case CERT_GENERIC: { this.data = new CertGenericExpr(this._io, this, _root); break; } case CERT_FIELD: { this.data = new CertFieldExpr(this._io, this, _root); break; } case CD_HASH: { this.data = new Data(this._io, this, _root); break; } case APPLE_GENERIC_ANCHOR: { this.data = new AppleGenericAnchorExpr(this._io, this, _root); break; } } } } } public static class InfoKeyFieldExpr extends KaitaiStruct { public static InfoKeyFieldExpr fromFile(String fileName) throws IOException { return new InfoKeyFieldExpr(new ByteBufferKaitaiStream(fileName)); } public InfoKeyFieldExpr(KaitaiStream _io) { this(_io, null, null); } public InfoKeyFieldExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent) { this(_io, _parent, null); } public InfoKeyFieldExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.data = new Data(this._io, this, _root); this.match = new Match(this._io, this, _root); } private Data data; private Match match; private MachO _root; private MachO.CsBlob.Expr _parent; public Data data() { return data; } public Match match() { return match; } public MachO _root() { return _root; } public MachO.CsBlob.Expr _parent() { return _parent; } } public static class CertSlotExpr extends KaitaiStruct { public static CertSlotExpr fromFile(String fileName) throws IOException { return new CertSlotExpr(new ByteBufferKaitaiStream(fileName)); } public CertSlotExpr(KaitaiStream _io) { this(_io, null, null); } public CertSlotExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent) { this(_io, _parent, null); } public CertSlotExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.value = MachO.CsBlob.Expr.CertSlot.byId(this._io.readU4be()); } private CertSlot value; private MachO _root; private MachO.CsBlob.Expr _parent; public CertSlot value() { return value; } public MachO _root() { return _root; } public MachO.CsBlob.Expr _parent() { return _parent; } } public static class CertGenericExpr extends KaitaiStruct { public static CertGenericExpr fromFile(String fileName) throws IOException { return new CertGenericExpr(new ByteBufferKaitaiStream(fileName)); } public CertGenericExpr(KaitaiStream _io) { this(_io, null, null); } public CertGenericExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent) { this(_io, _parent, null); } public CertGenericExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.certSlot = MachO.CsBlob.Expr.CertSlot.byId(this._io.readU4be()); this.data = new Data(this._io, this, _root); this.match = new Match(this._io, this, _root); } private CertSlot certSlot; private Data data; private Match match; private MachO _root; private MachO.CsBlob.Expr _parent; public CertSlot certSlot() { return certSlot; } public Data data() { return data; } public Match match() { return match; } public MachO _root() { return _root; } public MachO.CsBlob.Expr _parent() { return _parent; } } public static class IdentExpr extends KaitaiStruct { public static IdentExpr fromFile(String fileName) throws IOException { return new IdentExpr(new ByteBufferKaitaiStream(fileName)); } public IdentExpr(KaitaiStream _io) { this(_io, null, null); } public IdentExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent) { this(_io, _parent, null); } public IdentExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.identifier = new Data(this._io, this, _root); } private Data identifier; private MachO _root; private MachO.CsBlob.Expr _parent; public Data identifier() { return identifier; } public MachO _root() { return _root; } public MachO.CsBlob.Expr _parent() { return _parent; } } public static class CertFieldExpr extends KaitaiStruct { public static CertFieldExpr fromFile(String fileName) throws IOException { return new CertFieldExpr(new ByteBufferKaitaiStream(fileName)); } public CertFieldExpr(KaitaiStream _io) { this(_io, null, null); } public CertFieldExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent) { this(_io, _parent, null); } public CertFieldExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.certSlot = MachO.CsBlob.Expr.CertSlot.byId(this._io.readU4be()); this.data = new Data(this._io, this, _root); this.match = new Match(this._io, this, _root); } private CertSlot certSlot; private Data data; private Match match; private MachO _root; private MachO.CsBlob.Expr _parent; public CertSlot certSlot() { return certSlot; } public Data data() { return data; } public Match match() { return match; } public MachO _root() { return _root; } public MachO.CsBlob.Expr _parent() { return _parent; } } public static class AnchorHashExpr extends KaitaiStruct { public static AnchorHashExpr fromFile(String fileName) throws IOException { return new AnchorHashExpr(new ByteBufferKaitaiStream(fileName)); } public AnchorHashExpr(KaitaiStream _io) { this(_io, null, null); } public AnchorHashExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent) { this(_io, _parent, null); } public AnchorHashExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.certSlot = MachO.CsBlob.Expr.CertSlot.byId(this._io.readU4be()); this.data = new Data(this._io, this, _root); } private CertSlot certSlot; private Data data; private MachO _root; private MachO.CsBlob.Expr _parent; public CertSlot certSlot() { return certSlot; } public Data data() { return data; } public MachO _root() { return _root; } public MachO.CsBlob.Expr _parent() { return _parent; } } public static class AppleGenericAnchorExpr extends KaitaiStruct { public static AppleGenericAnchorExpr fromFile(String fileName) throws IOException { return new AppleGenericAnchorExpr(new ByteBufferKaitaiStream(fileName)); } public AppleGenericAnchorExpr(KaitaiStream _io) { this(_io, null, null); } public AppleGenericAnchorExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent) { this(_io, _parent, null); } public AppleGenericAnchorExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { } private String value; public String value() { if (this.value != null) return this.value; this.value = "anchor apple generic"; return this.value; } private MachO _root; private MachO.CsBlob.Expr _parent; public MachO _root() { return _root; } public MachO.CsBlob.Expr _parent() { return _parent; } } public static class EntitlementFieldExpr extends KaitaiStruct { public static EntitlementFieldExpr fromFile(String fileName) throws IOException { return new EntitlementFieldExpr(new ByteBufferKaitaiStream(fileName)); } public EntitlementFieldExpr(KaitaiStream _io) { this(_io, null, null); } public EntitlementFieldExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent) { this(_io, _parent, null); } public EntitlementFieldExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.data = new Data(this._io, this, _root); this.match = new Match(this._io, this, _root); } private Data data; private Match match; private MachO _root; private MachO.CsBlob.Expr _parent; public Data data() { return data; } public Match match() { return match; } public MachO _root() { return _root; } public MachO.CsBlob.Expr _parent() { return _parent; } } public static class AndExpr extends KaitaiStruct { public static AndExpr fromFile(String fileName) throws IOException { return new AndExpr(new ByteBufferKaitaiStream(fileName)); } public AndExpr(KaitaiStream _io) { this(_io, null, null); } public AndExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent) { this(_io, _parent, null); } public AndExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.left = new Expr(this._io, this, _root); this.right = new Expr(this._io, this, _root); } private Expr left; private Expr right; private MachO _root; private MachO.CsBlob.Expr _parent; public Expr left() { return left; } public Expr right() { return right; } public MachO _root() { return _root; } public MachO.CsBlob.Expr _parent() { return _parent; } } public static class OrExpr extends KaitaiStruct { public static OrExpr fromFile(String fileName) throws IOException { return new OrExpr(new ByteBufferKaitaiStream(fileName)); } public OrExpr(KaitaiStream _io) { this(_io, null, null); } public OrExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent) { this(_io, _parent, null); } public OrExpr(KaitaiStream _io, MachO.CsBlob.Expr _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.left = new Expr(this._io, this, _root); this.right = new Expr(this._io, this, _root); } private Expr left; private Expr right; private MachO _root; private MachO.CsBlob.Expr _parent; public Expr left() { return left; } public Expr right() { return right; } public MachO _root() { return _root; } public MachO.CsBlob.Expr _parent() { return _parent; } } private OpEnum op; private KaitaiStruct data; private MachO _root; private KaitaiStruct _parent; public OpEnum op() { return op; } public KaitaiStruct data() { return data; } public MachO _root() { return _root; } public KaitaiStruct _parent() { return _parent; } } public static class BlobIndex extends KaitaiStruct { public static BlobIndex fromFile(String fileName) throws IOException { return new BlobIndex(new ByteBufferKaitaiStream(fileName)); } public enum CsslotType { CODE_DIRECTORY(0x0L), INFO_SLOT(0x1L), REQUIREMENTS(0x2L), RESOURCE_DIR(0x3L), APPLICATION(0x4L), ENTITLEMENTS(0x5L), ALTERNATE_CODE_DIRECTORIES(0x1000L), SIGNATURE_SLOT(0x10000L); private final long id; CsslotType(long id) { this.id = id; } public long id() { return id; } private static final Map<Long, CsslotType> byId = new HashMap<Long, CsslotType>(8); static { for (CsslotType e : CsslotType.values()) byId.put(e.id(), e); } public static CsslotType byId(long id) { return byId.get(id); } } public BlobIndex(KaitaiStream _io) { this(_io, null, null); } public BlobIndex(KaitaiStream _io, MachO.CsBlob.SuperBlob _parent) { this(_io, _parent, null); } public BlobIndex(KaitaiStream _io, MachO.CsBlob.SuperBlob _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.type = CsslotType.byId(this._io.readU4be()); this.offset = this._io.readU4be(); } private CsBlob blob; public CsBlob blob() { if (this.blob != null) return this.blob; KaitaiStream io = _parent()._io(); long _pos = io.pos(); io.seek((offset() - 8)); this._raw_blob = io.readBytesFull(); KaitaiStream _io__raw_blob = new ByteBufferKaitaiStream(_raw_blob); this.blob = new CsBlob(_io__raw_blob, this, _root); io.seek(_pos); return this.blob; } private CsslotType type; private long offset; private MachO _root; private MachO.CsBlob.SuperBlob _parent; private byte[] _raw_blob; public CsslotType type() { return type; } public long offset() { return offset; } public MachO _root() { return _root; } public MachO.CsBlob.SuperBlob _parent() { return _parent; } public byte[] _raw_blob() { return _raw_blob; } } public static class Match extends KaitaiStruct { public static Match fromFile(String fileName) throws IOException { return new Match(new ByteBufferKaitaiStream(fileName)); } public enum Op { EXISTS(0x0L), EQUAL(0x1L), CONTAINS(0x2L), BEGINS_WITH(0x3L), ENDS_WITH(0x4L), LESS_THAN(0x5L), GREATER_THAN(0x6L), LESS_EQUAL(0x7L), GREATER_EQUAL(0x8L); private final long id; Op(long id) { this.id = id; } public long id() { return id; } private static final Map<Long, Op> byId = new HashMap<Long, Op>(9); static { for (Op e : Op.values()) byId.put(e.id(), e); } public static Op byId(long id) { return byId.get(id); } } public Match(KaitaiStream _io) { this(_io, null, null); } public Match(KaitaiStream _io, KaitaiStruct _parent) { this(_io, _parent, null); } public Match(KaitaiStream _io, KaitaiStruct _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.matchOp = Op.byId(this._io.readU4be()); if (matchOp() != Op.EXISTS) { this.data = new Data(this._io, this, _root); } } private Op matchOp; private Data data; private MachO _root; private KaitaiStruct _parent; public Op matchOp() { return matchOp; } public Data data() { return data; } public MachO _root() { return _root; } public KaitaiStruct _parent() { return _parent; } } public static class Requirement extends KaitaiStruct { public static Requirement fromFile(String fileName) throws IOException { return new Requirement(new ByteBufferKaitaiStream(fileName)); } public Requirement(KaitaiStream _io) { this(_io, null, null); } public Requirement(KaitaiStream _io, MachO.CsBlob _parent) { this(_io, _parent, null); } public Requirement(KaitaiStream _io, MachO.CsBlob _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.kind = this._io.readU4be(); this.expr = new Expr(this._io, this, _root); } private long kind; private Expr expr; private MachO _root; private MachO.CsBlob _parent; public long kind() { return kind; } public Expr expr() { return expr; } public MachO _root() { return _root; } public MachO.CsBlob _parent() { return _parent; } } public static class Requirements extends KaitaiStruct { public static Requirements fromFile(String fileName) throws IOException { return new Requirements(new ByteBufferKaitaiStream(fileName)); } public Requirements(KaitaiStream _io) { this(_io, null, null); } public Requirements(KaitaiStream _io, MachO.CsBlob _parent) { this(_io, _parent, null); } public Requirements(KaitaiStream _io, MachO.CsBlob _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.count = this._io.readU4be(); this.items = new ArrayList<RequirementsBlobIndex>(); for (int i = 0; i < count(); i++) { this.items.add(new RequirementsBlobIndex(this._io, this, _root)); } } private long count; private ArrayList<RequirementsBlobIndex> items; private MachO _root; private MachO.CsBlob _parent; public long count() { return count; } public ArrayList<RequirementsBlobIndex> items() { return items; } public MachO _root() { return _root; } public MachO.CsBlob _parent() { return _parent; } } public static class BlobWrapper extends KaitaiStruct { public static BlobWrapper fromFile(String fileName) throws IOException { return new BlobWrapper(new ByteBufferKaitaiStream(fileName)); } public BlobWrapper(KaitaiStream _io) { this(_io, null, null); } public BlobWrapper(KaitaiStream _io, MachO.CsBlob _parent) { this(_io, _parent, null); } public BlobWrapper(KaitaiStream _io, MachO.CsBlob _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.data = this._io.readBytesFull(); } private byte[] data; private MachO _root; private MachO.CsBlob _parent; public byte[] data() { return data; } public MachO _root() { return _root; } public MachO.CsBlob _parent() { return _parent; } } public static class RequirementsBlobIndex extends KaitaiStruct { public static RequirementsBlobIndex fromFile(String fileName) throws IOException { return new RequirementsBlobIndex(new ByteBufferKaitaiStream(fileName)); } public enum RequirementType { HOST(0x1L), GUEST(0x2L), DESIGNATED(0x3L), LIBRARY(0x4L); private final long id; RequirementType(long id) { this.id = id; } public long id() { return id; } private static final Map<Long, RequirementType> byId = new HashMap<Long, RequirementType>(4); static { for (RequirementType e : RequirementType.values()) byId.put(e.id(), e); } public static RequirementType byId(long id) { return byId.get(id); } } public RequirementsBlobIndex(KaitaiStream _io) { this(_io, null, null); } public RequirementsBlobIndex(KaitaiStream _io, MachO.CsBlob.Requirements _parent) { this(_io, _parent, null); } public RequirementsBlobIndex(KaitaiStream _io, MachO.CsBlob.Requirements _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.type = RequirementType.byId(this._io.readU4be()); this.offset = this._io.readU4be(); } private CsBlob value; public CsBlob value() { if (this.value != null) return this.value; long _pos = this._io.pos(); this._io.seek((offset() - 8)); this.value = new CsBlob(this._io, this, _root); this._io.seek(_pos); return this.value; } private RequirementType type; private long offset; private MachO _root; private MachO.CsBlob.Requirements _parent; public RequirementType type() { return type; } public long offset() { return offset; } public MachO _root() { return _root; } public MachO.CsBlob.Requirements _parent() { return _parent; } } private CsMagic magic; private long length; private Object body; private MachO _root; private KaitaiStruct _parent; private byte[] _raw_body; public CsMagic magic() { return magic; } public long length() { return length; } public Object body() { return body; } public MachO _root() { return _root; } public KaitaiStruct _parent() { return _parent; } public byte[] _raw_body() { return _raw_body; } } public static class BuildVersionCommand extends KaitaiStruct { public static BuildVersionCommand fromFile(String fileName) throws IOException { return new BuildVersionCommand(new ByteBufferKaitaiStream(fileName)); } public enum BuildPlatform { MACOS(0x1L), IOS(0x2L), TVOS(0x3L), WATCHOS(0x4L), BRIDGEOS(0x5L); private final long id; BuildPlatform(long id) { this.id = id; } public long id() { return id; } private static final Map<Long, BuildPlatform> byId = new HashMap<Long, BuildPlatform>(5); static { for (BuildPlatform e : BuildPlatform.values()) byId.put(e.id(), e); } public static BuildPlatform byId(long id) { return byId.get(id); } } public BuildVersionCommand(KaitaiStream _io) { this(_io, null, null); } public BuildVersionCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public BuildVersionCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.platform = BuildPlatform.byId(this._io.readU4le()); this.minos = new Version(this._io, this, _root); this.sdk = new Version(this._io, this, _root); this.ntools = this._io.readU4le(); this.buildToolVersions = new ArrayList<BuildToolVersion>(); for (int i = 0; i < ntools(); i++) { this.buildToolVersions.add(new BuildToolVersion(this._io, this, _root)); } } private BuildPlatform platform; private Version minos; private Version sdk; private long ntools; private ArrayList<BuildToolVersion> buildToolVersions; private MachO _root; private MachO.LoadCommand _parent; public BuildPlatform platform() { return platform; } public Version minos() { return minos; } public Version sdk() { return sdk; } public long ntools() { return ntools; } public ArrayList<BuildToolVersion> buildToolVersions() { return buildToolVersions; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class RoutinesCommand extends KaitaiStruct { public static RoutinesCommand fromFile(String fileName) throws IOException { return new RoutinesCommand(new ByteBufferKaitaiStream(fileName)); } public RoutinesCommand(KaitaiStream _io) { this(_io, null, null); } public RoutinesCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public RoutinesCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.initAddress = this._io.readU4le(); this.initModule = this._io.readU4le(); this.reserved = this._io.readBytes(24); } private long initAddress; private long initModule; private byte[] reserved; private MachO _root; private MachO.LoadCommand _parent; public long initAddress() { return initAddress; } public long initModule() { return initModule; } public byte[] reserved() { return reserved; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class MachoFlags extends KaitaiStruct { public MachoFlags(KaitaiStream _io, long value) { this(_io, null, null, value); } public MachoFlags(KaitaiStream _io, MachO.MachHeader _parent, long value) { this(_io, _parent, null, value); } public MachoFlags(KaitaiStream _io, MachO.MachHeader _parent, MachO _root, long value) { super(_io); this._parent = _parent; this._root = _root; this.value = value; _read(); } private void _read() { } private Boolean subsectionsViaSymbols; /** * safe to divide up the sections into sub-sections via symbols for dead code stripping */ public Boolean subsectionsViaSymbols() { if (this.subsectionsViaSymbols != null) return this.subsectionsViaSymbols; boolean _tmp = (boolean) ((value() & 8192) != 0); this.subsectionsViaSymbols = _tmp; return this.subsectionsViaSymbols; } private Boolean deadStrippableDylib; public Boolean deadStrippableDylib() { if (this.deadStrippableDylib != null) return this.deadStrippableDylib; boolean _tmp = (boolean) ((value() & 4194304) != 0); this.deadStrippableDylib = _tmp; return this.deadStrippableDylib; } private Boolean weakDefines; /** * the final linked image contains external weak symbols */ public Boolean weakDefines() { if (this.weakDefines != null) return this.weakDefines; boolean _tmp = (boolean) ((value() & 32768) != 0); this.weakDefines = _tmp; return this.weakDefines; } private Boolean prebound; /** * the file has its dynamic undefined references prebound. */ public Boolean prebound() { if (this.prebound != null) return this.prebound; boolean _tmp = (boolean) ((value() & 16) != 0); this.prebound = _tmp; return this.prebound; } private Boolean allModsBound; /** * indicates that this binary binds to all two-level namespace modules of its dependent libraries. only used when MH_PREBINDABLE and MH_TWOLEVEL are both set. */ public Boolean allModsBound() { if (this.allModsBound != null) return this.allModsBound; boolean _tmp = (boolean) ((value() & 4096) != 0); this.allModsBound = _tmp; return this.allModsBound; } private Boolean hasTlvDescriptors; public Boolean hasTlvDescriptors() { if (this.hasTlvDescriptors != null) return this.hasTlvDescriptors; boolean _tmp = (boolean) ((value() & 8388608) != 0); this.hasTlvDescriptors = _tmp; return this.hasTlvDescriptors; } private Boolean forceFlat; /** * the executable is forcing all images to use flat name space bindings */ public Boolean forceFlat() { if (this.forceFlat != null) return this.forceFlat; boolean _tmp = (boolean) ((value() & 256) != 0); this.forceFlat = _tmp; return this.forceFlat; } private Boolean rootSafe; /** * When this bit is set, the binary declares it is safe for use in processes with uid zero */ public Boolean rootSafe() { if (this.rootSafe != null) return this.rootSafe; boolean _tmp = (boolean) ((value() & 262144) != 0); this.rootSafe = _tmp; return this.rootSafe; } private Boolean noUndefs; /** * the object file has no undefined references */ public Boolean noUndefs() { if (this.noUndefs != null) return this.noUndefs; boolean _tmp = (boolean) ((value() & 1) != 0); this.noUndefs = _tmp; return this.noUndefs; } private Boolean setuidSafe; /** * When this bit is set, the binary declares it is safe for use in processes when issetugid() is true */ public Boolean setuidSafe() { if (this.setuidSafe != null) return this.setuidSafe; boolean _tmp = (boolean) ((value() & 524288) != 0); this.setuidSafe = _tmp; return this.setuidSafe; } private Boolean noHeapExecution; public Boolean noHeapExecution() { if (this.noHeapExecution != null) return this.noHeapExecution; boolean _tmp = (boolean) ((value() & 16777216) != 0); this.noHeapExecution = _tmp; return this.noHeapExecution; } private Boolean noReexportedDylibs; /** * When this bit is set on a dylib, the static linker does not need to examine dependent dylibs to see if any are re-exported */ public Boolean noReexportedDylibs() { if (this.noReexportedDylibs != null) return this.noReexportedDylibs; boolean _tmp = (boolean) ((value() & 1048576) != 0); this.noReexportedDylibs = _tmp; return this.noReexportedDylibs; } private Boolean noMultiDefs; /** * this umbrella guarantees no multiple defintions of symbols in its sub-images so the two-level namespace hints can always be used. */ public Boolean noMultiDefs() { if (this.noMultiDefs != null) return this.noMultiDefs; boolean _tmp = (boolean) ((value() & 512) != 0); this.noMultiDefs = _tmp; return this.noMultiDefs; } private Boolean appExtensionSafe; public Boolean appExtensionSafe() { if (this.appExtensionSafe != null) return this.appExtensionSafe; boolean _tmp = (boolean) ((value() & 33554432) != 0); this.appExtensionSafe = _tmp; return this.appExtensionSafe; } private Boolean prebindable; /** * the binary is not prebound but can have its prebinding redone. only used when MH_PREBOUND is not set. */ public Boolean prebindable() { if (this.prebindable != null) return this.prebindable; boolean _tmp = (boolean) ((value() & 2048) != 0); this.prebindable = _tmp; return this.prebindable; } private Boolean incrLink; /** * the object file is the output of an incremental link against a base file and can't be link edited again */ public Boolean incrLink() { if (this.incrLink != null) return this.incrLink; boolean _tmp = (boolean) ((value() & 2) != 0); this.incrLink = _tmp; return this.incrLink; } private Boolean bindAtLoad; /** * the object file's undefined references are bound by the dynamic linker when loaded. */ public Boolean bindAtLoad() { if (this.bindAtLoad != null) return this.bindAtLoad; boolean _tmp = (boolean) ((value() & 8) != 0); this.bindAtLoad = _tmp; return this.bindAtLoad; } private Boolean canonical; /** * the binary has been canonicalized via the unprebind operation */ public Boolean canonical() { if (this.canonical != null) return this.canonical; boolean _tmp = (boolean) ((value() & 16384) != 0); this.canonical = _tmp; return this.canonical; } private Boolean twoLevel; /** * the image is using two-level name space bindings */ public Boolean twoLevel() { if (this.twoLevel != null) return this.twoLevel; boolean _tmp = (boolean) ((value() & 128) != 0); this.twoLevel = _tmp; return this.twoLevel; } private Boolean splitSegs; /** * the file has its read-only and read-write segments split */ public Boolean splitSegs() { if (this.splitSegs != null) return this.splitSegs; boolean _tmp = (boolean) ((value() & 32) != 0); this.splitSegs = _tmp; return this.splitSegs; } private Boolean lazyInit; /** * the shared library init routine is to be run lazily via catching memory faults to its writeable segments (obsolete) */ public Boolean lazyInit() { if (this.lazyInit != null) return this.lazyInit; boolean _tmp = (boolean) ((value() & 64) != 0); this.lazyInit = _tmp; return this.lazyInit; } private Boolean allowStackExecution; /** * When this bit is set, all stacks in the task will be given stack execution privilege. Only used in MH_EXECUTE filetypes. */ public Boolean allowStackExecution() { if (this.allowStackExecution != null) return this.allowStackExecution; boolean _tmp = (boolean) ((value() & 131072) != 0); this.allowStackExecution = _tmp; return this.allowStackExecution; } private Boolean bindsToWeak; /** * the final linked image uses weak symbols */ public Boolean bindsToWeak() { if (this.bindsToWeak != null) return this.bindsToWeak; boolean _tmp = (boolean) ((value() & 65536) != 0); this.bindsToWeak = _tmp; return this.bindsToWeak; } private Boolean noFixPrebinding; /** * do not have dyld notify the prebinding agent about this executable */ public Boolean noFixPrebinding() { if (this.noFixPrebinding != null) return this.noFixPrebinding; boolean _tmp = (boolean) ((value() & 1024) != 0); this.noFixPrebinding = _tmp; return this.noFixPrebinding; } private Boolean dyldLink; /** * the object file is input for the dynamic linker and can't be staticly link edited again */ public Boolean dyldLink() { if (this.dyldLink != null) return this.dyldLink; boolean _tmp = (boolean) ((value() & 4) != 0); this.dyldLink = _tmp; return this.dyldLink; } private Boolean pie; /** * When this bit is set, the OS will load the main executable at a random address. Only used in MH_EXECUTE filetypes. */ public Boolean pie() { if (this.pie != null) return this.pie; boolean _tmp = (boolean) ((value() & 2097152) != 0); this.pie = _tmp; return this.pie; } private long value; private MachO _root; private MachO.MachHeader _parent; public long value() { return value; } public MachO _root() { return _root; } public MachO.MachHeader _parent() { return _parent; } } public static class FatHeader extends KaitaiStruct { public static FatHeader fromFile(String fileName) throws IOException { return new FatHeader(new ByteBufferKaitaiStream(fileName)); } public FatHeader(KaitaiStream _io) { this(_io, null, null); } public FatHeader(KaitaiStream _io, MachO _parent) { this(_io, _parent, null); } public FatHeader(KaitaiStream _io, MachO _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.nfatArch = this._io.readU4be(); this.fatArchs = new ArrayList<FatArch>(); for (int i = 0; i < nfatArch(); i++) { this.fatArchs.add(new FatArch(this._io, this, _root)); } } private long nfatArch; private ArrayList<FatArch> fatArchs; private MachO _root; private MachO _parent; public long nfatArch() { return nfatArch; } public ArrayList<FatArch> fatArchs() { return fatArchs; } public MachO _root() { return _root; } public MachO _parent() { return _parent; } } public static class RoutinesCommand64 extends KaitaiStruct { public static RoutinesCommand64 fromFile(String fileName) throws IOException { return new RoutinesCommand64(new ByteBufferKaitaiStream(fileName)); } public RoutinesCommand64(KaitaiStream _io) { this(_io, null, null); } public RoutinesCommand64(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public RoutinesCommand64(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.initAddress = this._io.readU8le(); this.initModule = this._io.readU8le(); this.reserved = this._io.readBytes(48); } private long initAddress; private long initModule; private byte[] reserved; private MachO _root; private MachO.LoadCommand _parent; public long initAddress() { return initAddress; } public long initModule() { return initModule; } public byte[] reserved() { return reserved; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class BuildToolVersion extends KaitaiStruct { public static BuildToolVersion fromFile(String fileName) throws IOException { return new BuildToolVersion(new ByteBufferKaitaiStream(fileName)); } public enum BuildTool { CLANG(0x1L), SWIFT(0x2L), LD(0x3L); private final long id; BuildTool(long id) { this.id = id; } public long id() { return id; } private static final Map<Long, BuildTool> byId = new HashMap<Long, BuildTool>(3); static { for (BuildTool e : BuildTool.values()) byId.put(e.id(), e); } public static BuildTool byId(long id) { return byId.get(id); } } public BuildToolVersion(KaitaiStream _io) { this(_io, null, null); } public BuildToolVersion(KaitaiStream _io, MachO.BuildVersionCommand _parent) { this(_io, _parent, null); } public BuildToolVersion(KaitaiStream _io, MachO.BuildVersionCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.tool = BuildTool.byId(this._io.readU4le()); this.version = new Version(this._io, this, _root); } private BuildTool tool; private Version version; private MachO _root; private MachO.BuildVersionCommand _parent; public BuildTool tool() { return tool; } public Version version() { return version; } public MachO _root() { return _root; } public MachO.BuildVersionCommand _parent() { return _parent; } } public static class LinkerOptionCommand extends KaitaiStruct { public static LinkerOptionCommand fromFile(String fileName) throws IOException { return new LinkerOptionCommand(new ByteBufferKaitaiStream(fileName)); } public LinkerOptionCommand(KaitaiStream _io) { this(_io, null, null); } public LinkerOptionCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public LinkerOptionCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.numStrings = this._io.readU4le(); this.strings = new ArrayList<String>(); for (int i = 0; i < numStrings(); i++) { this.strings.add(new String(this._io.readBytesTerm((byte) 0, false, true, true), Charset.forName("utf-8"))); } } private long numStrings; private ArrayList<String> strings; private MachO _root; private MachO.LoadCommand _parent; public long numStrings() { return numStrings; } public ArrayList<String> strings() { return strings; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class SegmentCommand64 extends KaitaiStruct { public static SegmentCommand64 fromFile(String fileName) throws IOException { return new SegmentCommand64(new ByteBufferKaitaiStream(fileName)); } public SegmentCommand64(KaitaiStream _io) { this(_io, null, null); } public SegmentCommand64(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public SegmentCommand64(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.segname = new String(KaitaiStream.bytesStripRight(this._io.readBytes(16), (byte) 0), Charset.forName("ascii")); this.vmaddr = this._io.readU8le(); this.vmsize = this._io.readU8le(); this.fileoff = this._io.readU8le(); this.filesize = this._io.readU8le(); this.maxprot = new VmProt(this._io, this, _root); this.initprot = new VmProt(this._io, this, _root); this.nsects = this._io.readU4le(); this.flags = this._io.readU4le(); this.sections = new ArrayList<Section64>(); for (int i = 0; i < nsects(); i++) { this.sections.add(new Section64(this._io, this, _root)); } } public static class Section64 extends KaitaiStruct { public static Section64 fromFile(String fileName) throws IOException { return new Section64(new ByteBufferKaitaiStream(fileName)); } public Section64(KaitaiStream _io) { this(_io, null, null); } public Section64(KaitaiStream _io, MachO.SegmentCommand64 _parent) { this(_io, _parent, null); } public Section64(KaitaiStream _io, MachO.SegmentCommand64 _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.sectName = new String(KaitaiStream.bytesStripRight(this._io.readBytes(16), (byte) 0), Charset.forName("ascii")); this.segName = new String(KaitaiStream.bytesStripRight(this._io.readBytes(16), (byte) 0), Charset.forName("ascii")); this.addr = this._io.readU8le(); this.size = this._io.readU8le(); this.offset = this._io.readU4le(); this.align = this._io.readU4le(); this.reloff = this._io.readU4le(); this.nreloc = this._io.readU4le(); this.flags = this._io.readU4le(); this.reserved1 = this._io.readU4le(); this.reserved2 = this._io.readU4le(); this.reserved3 = this._io.readU4le(); } public static class CfStringList extends KaitaiStruct { public static CfStringList fromFile(String fileName) throws IOException { return new CfStringList(new ByteBufferKaitaiStream(fileName)); } public CfStringList(KaitaiStream _io) { this(_io, null, null); } public CfStringList(KaitaiStream _io, MachO.SegmentCommand64.Section64 _parent) { this(_io, _parent, null); } public CfStringList(KaitaiStream _io, MachO.SegmentCommand64.Section64 _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.items = new ArrayList<CfString>(); { int i = 0; while (!this._io.isEof()) { this.items.add(new CfString(this._io, this, _root)); i++; } } } private ArrayList<CfString> items; private MachO _root; private MachO.SegmentCommand64.Section64 _parent; public ArrayList<CfString> items() { return items; } public MachO _root() { return _root; } public MachO.SegmentCommand64.Section64 _parent() { return _parent; } } public static class CfString extends KaitaiStruct { public static CfString fromFile(String fileName) throws IOException { return new CfString(new ByteBufferKaitaiStream(fileName)); } public CfString(KaitaiStream _io) { this(_io, null, null); } public CfString(KaitaiStream _io, MachO.SegmentCommand64.Section64.CfStringList _parent) { this(_io, _parent, null); } public CfString(KaitaiStream _io, MachO.SegmentCommand64.Section64.CfStringList _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.isa = this._io.readU8le(); this.info = this._io.readU8le(); this.data = this._io.readU8le(); this.length = this._io.readU8le(); } private long isa; private long info; private long data; private long length; private MachO _root; private MachO.SegmentCommand64.Section64.CfStringList _parent; public long isa() { return isa; } public long info() { return info; } public long data() { return data; } public long length() { return length; } public MachO _root() { return _root; } public MachO.SegmentCommand64.Section64.CfStringList _parent() { return _parent; } } public static class EhFrameItem extends KaitaiStruct { public static EhFrameItem fromFile(String fileName) throws IOException { return new EhFrameItem(new ByteBufferKaitaiStream(fileName)); } public EhFrameItem(KaitaiStream _io) { this(_io, null, null); } public EhFrameItem(KaitaiStream _io, MachO.SegmentCommand64.Section64.EhFrame _parent) { this(_io, _parent, null); } public EhFrameItem(KaitaiStream _io, MachO.SegmentCommand64.Section64.EhFrame _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.length = this._io.readU4le(); if (length() == 4294967295L) { this.length64 = this._io.readU8le(); } this.id = this._io.readU4le(); if ( ((length() > 0) && (id() == 0)) ) { this._raw_body = this._io.readBytes((length() - 4)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new Cie(_io__raw_body, this, _root); } } public static class CharChain extends KaitaiStruct { public static CharChain fromFile(String fileName) throws IOException { return new CharChain(new ByteBufferKaitaiStream(fileName)); } public CharChain(KaitaiStream _io) { this(_io, null, null); } public CharChain(KaitaiStream _io, KaitaiStruct _parent) { this(_io, _parent, null); } public CharChain(KaitaiStream _io, KaitaiStruct _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.chr = this._io.readU1(); if (chr() != 0) { this.next = new CharChain(this._io, this, _root); } } private int chr; private CharChain next; private MachO _root; private KaitaiStruct _parent; public int chr() { return chr; } public CharChain next() { return next; } public MachO _root() { return _root; } public KaitaiStruct _parent() { return _parent; } } public static class Cie extends KaitaiStruct { public static Cie fromFile(String fileName) throws IOException { return new Cie(new ByteBufferKaitaiStream(fileName)); } public Cie(KaitaiStream _io) { this(_io, null, null); } public Cie(KaitaiStream _io, MachO.SegmentCommand64.Section64.EhFrameItem _parent) { this(_io, _parent, null); } public Cie(KaitaiStream _io, MachO.SegmentCommand64.Section64.EhFrameItem _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.version = this._io.readU1(); this.augStr = new CharChain(this._io, this, _root); this.codeAlignmentFactor = new Uleb128(this._io, this, _root); this.dataAlignmentFactor = new Uleb128(this._io, this, _root); this.returnAddressRegister = this._io.readU1(); if (augStr().chr() == 122) { this.augmentation = new AugmentationEntry(this._io, this, _root); } } private int version; private CharChain augStr; private Uleb128 codeAlignmentFactor; private Uleb128 dataAlignmentFactor; private int returnAddressRegister; private AugmentationEntry augmentation; private MachO _root; private MachO.SegmentCommand64.Section64.EhFrameItem _parent; public int version() { return version; } public CharChain augStr() { return augStr; } public Uleb128 codeAlignmentFactor() { return codeAlignmentFactor; } public Uleb128 dataAlignmentFactor() { return dataAlignmentFactor; } public int returnAddressRegister() { return returnAddressRegister; } public AugmentationEntry augmentation() { return augmentation; } public MachO _root() { return _root; } public MachO.SegmentCommand64.Section64.EhFrameItem _parent() { return _parent; } } public static class AugmentationEntry extends KaitaiStruct { public static AugmentationEntry fromFile(String fileName) throws IOException { return new AugmentationEntry(new ByteBufferKaitaiStream(fileName)); } public AugmentationEntry(KaitaiStream _io) { this(_io, null, null); } public AugmentationEntry(KaitaiStream _io, MachO.SegmentCommand64.Section64.EhFrameItem.Cie _parent) { this(_io, _parent, null); } public AugmentationEntry(KaitaiStream _io, MachO.SegmentCommand64.Section64.EhFrameItem.Cie _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.length = new Uleb128(this._io, this, _root); if (_parent().augStr().next().chr() == 82) { this.fdePointerEncoding = this._io.readU1(); } } private Uleb128 length; private Integer fdePointerEncoding; private MachO _root; private MachO.SegmentCommand64.Section64.EhFrameItem.Cie _parent; public Uleb128 length() { return length; } public Integer fdePointerEncoding() { return fdePointerEncoding; } public MachO _root() { return _root; } public MachO.SegmentCommand64.Section64.EhFrameItem.Cie _parent() { return _parent; } } private long length; private Long length64; private long id; private Cie body; private MachO _root; private MachO.SegmentCommand64.Section64.EhFrame _parent; private byte[] _raw_body; public long length() { return length; } public Long length64() { return length64; } public long id() { return id; } public Cie body() { return body; } public MachO _root() { return _root; } public MachO.SegmentCommand64.Section64.EhFrame _parent() { return _parent; } public byte[] _raw_body() { return _raw_body; } } public static class EhFrame extends KaitaiStruct { public static EhFrame fromFile(String fileName) throws IOException { return new EhFrame(new ByteBufferKaitaiStream(fileName)); } public EhFrame(KaitaiStream _io) { this(_io, null, null); } public EhFrame(KaitaiStream _io, MachO.SegmentCommand64.Section64 _parent) { this(_io, _parent, null); } public EhFrame(KaitaiStream _io, MachO.SegmentCommand64.Section64 _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.items = new ArrayList<EhFrameItem>(); { int i = 0; while (!this._io.isEof()) { this.items.add(new EhFrameItem(this._io, this, _root)); i++; } } } private ArrayList<EhFrameItem> items; private MachO _root; private MachO.SegmentCommand64.Section64 _parent; public ArrayList<EhFrameItem> items() { return items; } public MachO _root() { return _root; } public MachO.SegmentCommand64.Section64 _parent() { return _parent; } } public static class PointerList extends KaitaiStruct { public static PointerList fromFile(String fileName) throws IOException { return new PointerList(new ByteBufferKaitaiStream(fileName)); } public PointerList(KaitaiStream _io) { this(_io, null, null); } public PointerList(KaitaiStream _io, MachO.SegmentCommand64.Section64 _parent) { this(_io, _parent, null); } public PointerList(KaitaiStream _io, MachO.SegmentCommand64.Section64 _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.items = new ArrayList<Long>(); { int i = 0; while (!this._io.isEof()) { this.items.add(this._io.readU8le()); i++; } } } private ArrayList<Long> items; private MachO _root; private MachO.SegmentCommand64.Section64 _parent; public ArrayList<Long> items() { return items; } public MachO _root() { return _root; } public MachO.SegmentCommand64.Section64 _parent() { return _parent; } } public static class StringList extends KaitaiStruct { public static StringList fromFile(String fileName) throws IOException { return new StringList(new ByteBufferKaitaiStream(fileName)); } public StringList(KaitaiStream _io) { this(_io, null, null); } public StringList(KaitaiStream _io, MachO.SegmentCommand64.Section64 _parent) { this(_io, _parent, null); } public StringList(KaitaiStream _io, MachO.SegmentCommand64.Section64 _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.strings = new ArrayList<String>(); { int i = 0; while (!this._io.isEof()) { this.strings.add(new String(this._io.readBytesTerm((byte) 0, false, true, true), Charset.forName("ascii"))); i++; } } } private ArrayList<String> strings; private MachO _root; private MachO.SegmentCommand64.Section64 _parent; public ArrayList<String> strings() { return strings; } public MachO _root() { return _root; } public MachO.SegmentCommand64.Section64 _parent() { return _parent; } } private Object data; public Object data() { if (this.data != null) return this.data; KaitaiStream io = _root._io(); long _pos = io.pos(); io.seek(offset()); switch (sectName()) { case "__objc_nlclslist": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new PointerList(_io__raw_data, this, _root); break; } case "__objc_methname": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new StringList(_io__raw_data, this, _root); break; } case "__nl_symbol_ptr": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new PointerList(_io__raw_data, this, _root); break; } case "__la_symbol_ptr": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new PointerList(_io__raw_data, this, _root); break; } case "__objc_selrefs": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new PointerList(_io__raw_data, this, _root); break; } case "__cstring": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new StringList(_io__raw_data, this, _root); break; } case "__objc_classlist": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new PointerList(_io__raw_data, this, _root); break; } case "__objc_protolist": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new PointerList(_io__raw_data, this, _root); break; } case "__objc_catlist": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new PointerList(_io__raw_data, this, _root); break; } case "__objc_imageinfo": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new PointerList(_io__raw_data, this, _root); break; } case "__objc_methtype": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new StringList(_io__raw_data, this, _root); break; } case "__cfstring": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new CfStringList(_io__raw_data, this, _root); break; } case "__objc_classrefs": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new PointerList(_io__raw_data, this, _root); break; } case "__objc_protorefs": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new PointerList(_io__raw_data, this, _root); break; } case "__objc_classname": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new StringList(_io__raw_data, this, _root); break; } case "__got": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new PointerList(_io__raw_data, this, _root); break; } case "__eh_frame": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new EhFrame(_io__raw_data, this, _root); break; } case "__objc_superrefs": { this._raw_data = io.readBytes(size()); KaitaiStream _io__raw_data = new ByteBufferKaitaiStream(_raw_data); this.data = new PointerList(_io__raw_data, this, _root); break; } default: { this.data = io.readBytes(size()); break; } } io.seek(_pos); return this.data; } private String sectName; private String segName; private long addr; private long size; private long offset; private long align; private long reloff; private long nreloc; private long flags; private long reserved1; private long reserved2; private long reserved3; private MachO _root; private MachO.SegmentCommand64 _parent; private byte[] _raw_data; public String sectName() { return sectName; } public String segName() { return segName; } public long addr() { return addr; } public long size() { return size; } public long offset() { return offset; } public long align() { return align; } public long reloff() { return reloff; } public long nreloc() { return nreloc; } public long flags() { return flags; } public long reserved1() { return reserved1; } public long reserved2() { return reserved2; } public long reserved3() { return reserved3; } public MachO _root() { return _root; } public MachO.SegmentCommand64 _parent() { return _parent; } public byte[] _raw_data() { return _raw_data; } } private String segname; private long vmaddr; private long vmsize; private long fileoff; private long filesize; private VmProt maxprot; private VmProt initprot; private long nsects; private long flags; private ArrayList<Section64> sections; private MachO _root; private MachO.LoadCommand _parent; public String segname() { return segname; } public long vmaddr() { return vmaddr; } public long vmsize() { return vmsize; } public long fileoff() { return fileoff; } public long filesize() { return filesize; } public VmProt maxprot() { return maxprot; } public VmProt initprot() { return initprot; } public long nsects() { return nsects; } public long flags() { return flags; } public ArrayList<Section64> sections() { return sections; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class VmProt extends KaitaiStruct { public static VmProt fromFile(String fileName) throws IOException { return new VmProt(new ByteBufferKaitaiStream(fileName)); } public VmProt(KaitaiStream _io) { this(_io, null, null); } public VmProt(KaitaiStream _io, KaitaiStruct _parent) { this(_io, _parent, null); } public VmProt(KaitaiStream _io, KaitaiStruct _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.stripRead = this._io.readBitsInt(1) != 0; this.isMask = this._io.readBitsInt(1) != 0; this.reserved0 = this._io.readBitsInt(1) != 0; this.copy = this._io.readBitsInt(1) != 0; this.noChange = this._io.readBitsInt(1) != 0; this.execute = this._io.readBitsInt(1) != 0; this.write = this._io.readBitsInt(1) != 0; this.read = this._io.readBitsInt(1) != 0; this.reserved1 = this._io.readBitsInt(24); } private boolean stripRead; private boolean isMask; private boolean reserved0; private boolean copy; private boolean noChange; private boolean execute; private boolean write; private boolean read; private long reserved1; private MachO _root; private KaitaiStruct _parent; /** * Special marker to support execute-only protection. */ public boolean stripRead() { return stripRead; } /** * Indicates to use value as a mask against the actual protection bits. */ public boolean isMask() { return isMask; } /** * Reserved (unused) bit. */ public boolean reserved0() { return reserved0; } /** * Used when write permission can not be obtained, to mark the entry as COW. */ public boolean copy() { return copy; } /** * Used only by memory_object_lock_request to indicate no change to page locks. */ public boolean noChange() { return noChange; } /** * Execute permission. */ public boolean execute() { return execute; } /** * Write permission. */ public boolean write() { return write; } /** * Read permission. */ public boolean read() { return read; } /** * Reserved (unused) bits. */ public long reserved1() { return reserved1; } public MachO _root() { return _root; } public KaitaiStruct _parent() { return _parent; } } public static class DysymtabCommand extends KaitaiStruct { public static DysymtabCommand fromFile(String fileName) throws IOException { return new DysymtabCommand(new ByteBufferKaitaiStream(fileName)); } public DysymtabCommand(KaitaiStream _io) { this(_io, null, null); } public DysymtabCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public DysymtabCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.iLocalSym = this._io.readU4le(); this.nLocalSym = this._io.readU4le(); this.iExtDefSym = this._io.readU4le(); this.nExtDefSym = this._io.readU4le(); this.iUndefSym = this._io.readU4le(); this.nUndefSym = this._io.readU4le(); this.tocOff = this._io.readU4le(); this.nToc = this._io.readU4le(); this.modTabOff = this._io.readU4le(); this.nModTab = this._io.readU4le(); this.extRefSymOff = this._io.readU4le(); this.nExtRefSyms = this._io.readU4le(); this.indirectSymOff = this._io.readU4le(); this.nIndirectSyms = this._io.readU4le(); this.extRelOff = this._io.readU4le(); this.nExtRel = this._io.readU4le(); this.locRelOff = this._io.readU4le(); this.nLocRel = this._io.readU4le(); } private ArrayList<Long> indirectSymbols; public ArrayList<Long> indirectSymbols() { if (this.indirectSymbols != null) return this.indirectSymbols; KaitaiStream io = _root._io(); long _pos = io.pos(); io.seek(indirectSymOff()); this.indirectSymbols = new ArrayList<Long>(); for (int i = 0; i < nIndirectSyms(); i++) { this.indirectSymbols.add(io.readU4le()); } io.seek(_pos); return this.indirectSymbols; } private long iLocalSym; private long nLocalSym; private long iExtDefSym; private long nExtDefSym; private long iUndefSym; private long nUndefSym; private long tocOff; private long nToc; private long modTabOff; private long nModTab; private long extRefSymOff; private long nExtRefSyms; private long indirectSymOff; private long nIndirectSyms; private long extRelOff; private long nExtRel; private long locRelOff; private long nLocRel; private MachO _root; private MachO.LoadCommand _parent; public long iLocalSym() { return iLocalSym; } public long nLocalSym() { return nLocalSym; } public long iExtDefSym() { return iExtDefSym; } public long nExtDefSym() { return nExtDefSym; } public long iUndefSym() { return iUndefSym; } public long nUndefSym() { return nUndefSym; } public long tocOff() { return tocOff; } public long nToc() { return nToc; } public long modTabOff() { return modTabOff; } public long nModTab() { return nModTab; } public long extRefSymOff() { return extRefSymOff; } public long nExtRefSyms() { return nExtRefSyms; } public long indirectSymOff() { return indirectSymOff; } public long nIndirectSyms() { return nIndirectSyms; } public long extRelOff() { return extRelOff; } public long nExtRel() { return nExtRel; } public long locRelOff() { return locRelOff; } public long nLocRel() { return nLocRel; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class MachHeader extends KaitaiStruct { public static MachHeader fromFile(String fileName) throws IOException { return new MachHeader(new ByteBufferKaitaiStream(fileName)); } public MachHeader(KaitaiStream _io) { this(_io, null, null); } public MachHeader(KaitaiStream _io, MachO _parent) { this(_io, _parent, null); } public MachHeader(KaitaiStream _io, MachO _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.cputype = MachO.CpuType.byId(this._io.readU4le()); this.cpusubtype = this._io.readU4le(); this.filetype = MachO.FileType.byId(this._io.readU4le()); this.ncmds = this._io.readU4le(); this.sizeofcmds = this._io.readU4le(); this.flags = this._io.readU4le(); if ( ((_root.magic() == MachO.MagicType.MACHO_BE_X64) || (_root.magic() == MachO.MagicType.MACHO_LE_X64)) ) { this.reserved = this._io.readU4le(); } } private MachoFlags flagsObj; public MachoFlags flagsObj() { if (this.flagsObj != null) return this.flagsObj; this.flagsObj = new MachoFlags(this._io, this, _root, flags()); return this.flagsObj; } private CpuType cputype; private long cpusubtype; private FileType filetype; private long ncmds; private long sizeofcmds; private long flags; private Long reserved; private MachO _root; private MachO _parent; public CpuType cputype() { return cputype; } public long cpusubtype() { return cpusubtype; } public FileType filetype() { return filetype; } public long ncmds() { return ncmds; } public long sizeofcmds() { return sizeofcmds; } public long flags() { return flags; } public Long reserved() { return reserved; } public MachO _root() { return _root; } public MachO _parent() { return _parent; } } public static class LinkeditDataCommand extends KaitaiStruct { public static LinkeditDataCommand fromFile(String fileName) throws IOException { return new LinkeditDataCommand(new ByteBufferKaitaiStream(fileName)); } public LinkeditDataCommand(KaitaiStream _io) { this(_io, null, null); } public LinkeditDataCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public LinkeditDataCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.dataOff = this._io.readU4le(); this.dataSize = this._io.readU4le(); } private long dataOff; private long dataSize; private MachO _root; private MachO.LoadCommand _parent; public long dataOff() { return dataOff; } public long dataSize() { return dataSize; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class SubCommand extends KaitaiStruct { public static SubCommand fromFile(String fileName) throws IOException { return new SubCommand(new ByteBufferKaitaiStream(fileName)); } public SubCommand(KaitaiStream _io) { this(_io, null, null); } public SubCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public SubCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.name = new LcStr(this._io, this, _root); } private LcStr name; private MachO _root; private MachO.LoadCommand _parent; public LcStr name() { return name; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class TwolevelHintsCommand extends KaitaiStruct { public static TwolevelHintsCommand fromFile(String fileName) throws IOException { return new TwolevelHintsCommand(new ByteBufferKaitaiStream(fileName)); } public TwolevelHintsCommand(KaitaiStream _io) { this(_io, null, null); } public TwolevelHintsCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public TwolevelHintsCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.offset = this._io.readU4le(); this.numHints = this._io.readU4le(); } private long offset; private long numHints; private MachO _root; private MachO.LoadCommand _parent; public long offset() { return offset; } public long numHints() { return numHints; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class Version extends KaitaiStruct { public static Version fromFile(String fileName) throws IOException { return new Version(new ByteBufferKaitaiStream(fileName)); } public Version(KaitaiStream _io) { this(_io, null, null); } public Version(KaitaiStream _io, KaitaiStruct _parent) { this(_io, _parent, null); } public Version(KaitaiStream _io, KaitaiStruct _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.p1 = this._io.readU1(); this.minor = this._io.readU1(); this.major = this._io.readU1(); this.release = this._io.readU1(); } private int p1; private int minor; private int major; private int release; private MachO _root; private KaitaiStruct _parent; public int p1() { return p1; } public int minor() { return minor; } public int major() { return major; } public int release() { return release; } public MachO _root() { return _root; } public KaitaiStruct _parent() { return _parent; } } public static class EncryptionInfoCommand extends KaitaiStruct { public static EncryptionInfoCommand fromFile(String fileName) throws IOException { return new EncryptionInfoCommand(new ByteBufferKaitaiStream(fileName)); } public EncryptionInfoCommand(KaitaiStream _io) { this(_io, null, null); } public EncryptionInfoCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public EncryptionInfoCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.cryptoff = this._io.readU4le(); this.cryptsize = this._io.readU4le(); this.cryptid = this._io.readU4le(); if ( ((_root.magic() == MachO.MagicType.MACHO_BE_X64) || (_root.magic() == MachO.MagicType.MACHO_LE_X64)) ) { this.pad = this._io.readU4le(); } } private long cryptoff; private long cryptsize; private long cryptid; private Long pad; private MachO _root; private MachO.LoadCommand _parent; public long cryptoff() { return cryptoff; } public long cryptsize() { return cryptsize; } public long cryptid() { return cryptid; } public Long pad() { return pad; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class CodeSignatureCommand extends KaitaiStruct { public static CodeSignatureCommand fromFile(String fileName) throws IOException { return new CodeSignatureCommand(new ByteBufferKaitaiStream(fileName)); } public CodeSignatureCommand(KaitaiStream _io) { this(_io, null, null); } public CodeSignatureCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public CodeSignatureCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.dataOff = this._io.readU4le(); this.dataSize = this._io.readU4le(); } private CsBlob codeSignature; public CsBlob codeSignature() { if (this.codeSignature != null) return this.codeSignature; KaitaiStream io = _root._io(); long _pos = io.pos(); io.seek(dataOff()); this._raw_codeSignature = io.readBytes(dataSize()); KaitaiStream _io__raw_codeSignature = new ByteBufferKaitaiStream(_raw_codeSignature); this.codeSignature = new CsBlob(_io__raw_codeSignature, this, _root); io.seek(_pos); return this.codeSignature; } private long dataOff; private long dataSize; private MachO _root; private MachO.LoadCommand _parent; private byte[] _raw_codeSignature; public long dataOff() { return dataOff; } public long dataSize() { return dataSize; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } public byte[] _raw_codeSignature() { return _raw_codeSignature; } } public static class DyldInfoCommand extends KaitaiStruct { public static DyldInfoCommand fromFile(String fileName) throws IOException { return new DyldInfoCommand(new ByteBufferKaitaiStream(fileName)); } public enum BindOpcode { DONE(0x0L), SET_DYLIB_ORDINAL_IMMEDIATE(0x10L), SET_DYLIB_ORDINAL_ULEB(0x20L), SET_DYLIB_SPECIAL_IMMEDIATE(0x30L), SET_SYMBOL_TRAILING_FLAGS_IMMEDIATE(0x40L), SET_TYPE_IMMEDIATE(0x50L), SET_APPEND_SLEB(0x60L), SET_SEGMENT_AND_OFFSET_ULEB(0x70L), ADD_ADDRESS_ULEB(0x80L), DO_BIND(0x90L), DO_BIND_ADD_ADDRESS_ULEB(0xa0L), DO_BIND_ADD_ADDRESS_IMMEDIATE_SCALED(0xb0L), DO_BIND_ULEB_TIMES_SKIPPING_ULEB(0xc0L); private final long id; BindOpcode(long id) { this.id = id; } public long id() { return id; } private static final Map<Long, BindOpcode> byId = new HashMap<Long, BindOpcode>(13); static { for (BindOpcode e : BindOpcode.values()) byId.put(e.id(), e); } public static BindOpcode byId(long id) { return byId.get(id); } } public DyldInfoCommand(KaitaiStream _io) { this(_io, null, null); } public DyldInfoCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public DyldInfoCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.rebaseOff = this._io.readU4le(); this.rebaseSize = this._io.readU4le(); this.bindOff = this._io.readU4le(); this.bindSize = this._io.readU4le(); this.weakBindOff = this._io.readU4le(); this.weakBindSize = this._io.readU4le(); this.lazyBindOff = this._io.readU4le(); this.lazyBindSize = this._io.readU4le(); this.exportOff = this._io.readU4le(); this.exportSize = this._io.readU4le(); } public static class BindItem extends KaitaiStruct { public static BindItem fromFile(String fileName) throws IOException { return new BindItem(new ByteBufferKaitaiStream(fileName)); } public BindItem(KaitaiStream _io) { this(_io, null, null); } public BindItem(KaitaiStream _io, KaitaiStruct _parent) { this(_io, _parent, null); } public BindItem(KaitaiStream _io, KaitaiStruct _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.opcodeAndImmediate = this._io.readU1(); if ( ((opcode() == MachO.DyldInfoCommand.BindOpcode.SET_DYLIB_ORDINAL_ULEB) || (opcode() == MachO.DyldInfoCommand.BindOpcode.SET_APPEND_SLEB) || (opcode() == MachO.DyldInfoCommand.BindOpcode.SET_SEGMENT_AND_OFFSET_ULEB) || (opcode() == MachO.DyldInfoCommand.BindOpcode.ADD_ADDRESS_ULEB) || (opcode() == MachO.DyldInfoCommand.BindOpcode.DO_BIND_ADD_ADDRESS_ULEB) || (opcode() == MachO.DyldInfoCommand.BindOpcode.DO_BIND_ULEB_TIMES_SKIPPING_ULEB)) ) { this.uleb = new Uleb128(this._io, this, _root); } if (opcode() == MachO.DyldInfoCommand.BindOpcode.DO_BIND_ULEB_TIMES_SKIPPING_ULEB) { this.skip = new Uleb128(this._io, this, _root); } if (opcode() == MachO.DyldInfoCommand.BindOpcode.SET_SYMBOL_TRAILING_FLAGS_IMMEDIATE) { this.symbol = new String(this._io.readBytesTerm((byte) 0, false, true, true), Charset.forName("ascii")); } } private BindOpcode opcode; public BindOpcode opcode() { if (this.opcode != null) return this.opcode; this.opcode = MachO.DyldInfoCommand.BindOpcode.byId((opcodeAndImmediate() & 240)); return this.opcode; } private Integer immediate; public Integer immediate() { if (this.immediate != null) return this.immediate; int _tmp = (int) ((opcodeAndImmediate() & 15)); this.immediate = _tmp; return this.immediate; } private int opcodeAndImmediate; private Uleb128 uleb; private Uleb128 skip; private String symbol; private MachO _root; private KaitaiStruct _parent; public int opcodeAndImmediate() { return opcodeAndImmediate; } public Uleb128 uleb() { return uleb; } public Uleb128 skip() { return skip; } public String symbol() { return symbol; } public MachO _root() { return _root; } public KaitaiStruct _parent() { return _parent; } } public static class RebaseData extends KaitaiStruct { public static RebaseData fromFile(String fileName) throws IOException { return new RebaseData(new ByteBufferKaitaiStream(fileName)); } public enum Opcode { DONE(0x0L), SET_TYPE_IMMEDIATE(0x10L), SET_SEGMENT_AND_OFFSET_ULEB(0x20L), ADD_ADDRESS_ULEB(0x30L), ADD_ADDRESS_IMMEDIATE_SCALED(0x40L), DO_REBASE_IMMEDIATE_TIMES(0x50L), DO_REBASE_ULEB_TIMES(0x60L), DO_REBASE_ADD_ADDRESS_ULEB(0x70L), DO_REBASE_ULEB_TIMES_SKIPPING_ULEB(0x80L); private final long id; Opcode(long id) { this.id = id; } public long id() { return id; } private static final Map<Long, Opcode> byId = new HashMap<Long, Opcode>(9); static { for (Opcode e : Opcode.values()) byId.put(e.id(), e); } public static Opcode byId(long id) { return byId.get(id); } } public RebaseData(KaitaiStream _io) { this(_io, null, null); } public RebaseData(KaitaiStream _io, MachO.DyldInfoCommand _parent) { this(_io, _parent, null); } public RebaseData(KaitaiStream _io, MachO.DyldInfoCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.items = new ArrayList<RebaseItem>(); { RebaseItem _it; int i = 0; do { _it = new RebaseItem(this._io, this, _root); this.items.add(_it); i++; } while (!(_it.opcode() == Opcode.DONE)); } } public static class RebaseItem extends KaitaiStruct { public static RebaseItem fromFile(String fileName) throws IOException { return new RebaseItem(new ByteBufferKaitaiStream(fileName)); } public RebaseItem(KaitaiStream _io) { this(_io, null, null); } public RebaseItem(KaitaiStream _io, MachO.DyldInfoCommand.RebaseData _parent) { this(_io, _parent, null); } public RebaseItem(KaitaiStream _io, MachO.DyldInfoCommand.RebaseData _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.opcodeAndImmediate = this._io.readU1(); if ( ((opcode() == MachO.DyldInfoCommand.RebaseData.Opcode.SET_SEGMENT_AND_OFFSET_ULEB) || (opcode() == MachO.DyldInfoCommand.RebaseData.Opcode.ADD_ADDRESS_ULEB) || (opcode() == MachO.DyldInfoCommand.RebaseData.Opcode.DO_REBASE_ULEB_TIMES) || (opcode() == MachO.DyldInfoCommand.RebaseData.Opcode.DO_REBASE_ADD_ADDRESS_ULEB) || (opcode() == MachO.DyldInfoCommand.RebaseData.Opcode.DO_REBASE_ULEB_TIMES_SKIPPING_ULEB)) ) { this.uleb = new Uleb128(this._io, this, _root); } if (opcode() == MachO.DyldInfoCommand.RebaseData.Opcode.DO_REBASE_ULEB_TIMES_SKIPPING_ULEB) { this.skip = new Uleb128(this._io, this, _root); } } private Opcode opcode; public Opcode opcode() { if (this.opcode != null) return this.opcode; this.opcode = MachO.DyldInfoCommand.RebaseData.Opcode.byId((opcodeAndImmediate() & 240)); return this.opcode; } private Integer immediate; public Integer immediate() { if (this.immediate != null) return this.immediate; int _tmp = (int) ((opcodeAndImmediate() & 15)); this.immediate = _tmp; return this.immediate; } private int opcodeAndImmediate; private Uleb128 uleb; private Uleb128 skip; private MachO _root; private MachO.DyldInfoCommand.RebaseData _parent; public int opcodeAndImmediate() { return opcodeAndImmediate; } public Uleb128 uleb() { return uleb; } public Uleb128 skip() { return skip; } public MachO _root() { return _root; } public MachO.DyldInfoCommand.RebaseData _parent() { return _parent; } } private ArrayList<RebaseItem> items; private MachO _root; private MachO.DyldInfoCommand _parent; public ArrayList<RebaseItem> items() { return items; } public MachO _root() { return _root; } public MachO.DyldInfoCommand _parent() { return _parent; } } public static class ExportNode extends KaitaiStruct { public static ExportNode fromFile(String fileName) throws IOException { return new ExportNode(new ByteBufferKaitaiStream(fileName)); } public ExportNode(KaitaiStream _io) { this(_io, null, null); } public ExportNode(KaitaiStream _io, KaitaiStruct _parent) { this(_io, _parent, null); } public ExportNode(KaitaiStream _io, KaitaiStruct _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.terminalSize = new Uleb128(this._io, this, _root); this.childrenCount = this._io.readU1(); this.children = new ArrayList<Child>(); for (int i = 0; i < childrenCount(); i++) { this.children.add(new Child(this._io, this, _root)); } this.terminal = this._io.readBytes(terminalSize().value()); } public static class Child extends KaitaiStruct { public static Child fromFile(String fileName) throws IOException { return new Child(new ByteBufferKaitaiStream(fileName)); } public Child(KaitaiStream _io) { this(_io, null, null); } public Child(KaitaiStream _io, MachO.DyldInfoCommand.ExportNode _parent) { this(_io, _parent, null); } public Child(KaitaiStream _io, MachO.DyldInfoCommand.ExportNode _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.name = new String(this._io.readBytesTerm((byte) 0, false, true, true), Charset.forName("ascii")); this.nodeOffset = new Uleb128(this._io, this, _root); } private ExportNode value; public ExportNode value() { if (this.value != null) return this.value; long _pos = this._io.pos(); this._io.seek(nodeOffset().value()); this.value = new ExportNode(this._io, this, _root); this._io.seek(_pos); return this.value; } private String name; private Uleb128 nodeOffset; private MachO _root; private MachO.DyldInfoCommand.ExportNode _parent; public String name() { return name; } public Uleb128 nodeOffset() { return nodeOffset; } public MachO _root() { return _root; } public MachO.DyldInfoCommand.ExportNode _parent() { return _parent; } } private Uleb128 terminalSize; private int childrenCount; private ArrayList<Child> children; private byte[] terminal; private MachO _root; private KaitaiStruct _parent; public Uleb128 terminalSize() { return terminalSize; } public int childrenCount() { return childrenCount; } public ArrayList<Child> children() { return children; } public byte[] terminal() { return terminal; } public MachO _root() { return _root; } public KaitaiStruct _parent() { return _parent; } } public static class BindData extends KaitaiStruct { public static BindData fromFile(String fileName) throws IOException { return new BindData(new ByteBufferKaitaiStream(fileName)); } public BindData(KaitaiStream _io) { this(_io, null, null); } public BindData(KaitaiStream _io, MachO.DyldInfoCommand _parent) { this(_io, _parent, null); } public BindData(KaitaiStream _io, MachO.DyldInfoCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.items = new ArrayList<BindItem>(); { BindItem _it; int i = 0; do { _it = new BindItem(this._io, this, _root); this.items.add(_it); i++; } while (!(_it.opcode() == MachO.DyldInfoCommand.BindOpcode.DONE)); } } private ArrayList<BindItem> items; private MachO _root; private MachO.DyldInfoCommand _parent; public ArrayList<BindItem> items() { return items; } public MachO _root() { return _root; } public MachO.DyldInfoCommand _parent() { return _parent; } } public static class LazyBindData extends KaitaiStruct { public static LazyBindData fromFile(String fileName) throws IOException { return new LazyBindData(new ByteBufferKaitaiStream(fileName)); } public LazyBindData(KaitaiStream _io) { this(_io, null, null); } public LazyBindData(KaitaiStream _io, MachO.DyldInfoCommand _parent) { this(_io, _parent, null); } public LazyBindData(KaitaiStream _io, MachO.DyldInfoCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.items = new ArrayList<BindItem>(); { int i = 0; while (!this._io.isEof()) { this.items.add(new BindItem(this._io, this, _root)); i++; } } } private ArrayList<BindItem> items; private MachO _root; private MachO.DyldInfoCommand _parent; public ArrayList<BindItem> items() { return items; } public MachO _root() { return _root; } public MachO.DyldInfoCommand _parent() { return _parent; } } private RebaseData rebase; public RebaseData rebase() { if (this.rebase != null) return this.rebase; KaitaiStream io = _root._io(); long _pos = io.pos(); io.seek(rebaseOff()); this._raw_rebase = io.readBytes(rebaseSize()); KaitaiStream _io__raw_rebase = new ByteBufferKaitaiStream(_raw_rebase); this.rebase = new RebaseData(_io__raw_rebase, this, _root); io.seek(_pos); return this.rebase; } private BindData bind; public BindData bind() { if (this.bind != null) return this.bind; KaitaiStream io = _root._io(); long _pos = io.pos(); io.seek(bindOff()); this._raw_bind = io.readBytes(bindSize()); KaitaiStream _io__raw_bind = new ByteBufferKaitaiStream(_raw_bind); this.bind = new BindData(_io__raw_bind, this, _root); io.seek(_pos); return this.bind; } private LazyBindData lazyBind; public LazyBindData lazyBind() { if (this.lazyBind != null) return this.lazyBind; KaitaiStream io = _root._io(); long _pos = io.pos(); io.seek(lazyBindOff()); this._raw_lazyBind = io.readBytes(lazyBindSize()); KaitaiStream _io__raw_lazyBind = new ByteBufferKaitaiStream(_raw_lazyBind); this.lazyBind = new LazyBindData(_io__raw_lazyBind, this, _root); io.seek(_pos); return this.lazyBind; } private ExportNode exports; public ExportNode exports() { if (this.exports != null) return this.exports; KaitaiStream io = _root._io(); long _pos = io.pos(); io.seek(exportOff()); this._raw_exports = io.readBytes(exportSize()); KaitaiStream _io__raw_exports = new ByteBufferKaitaiStream(_raw_exports); this.exports = new ExportNode(_io__raw_exports, this, _root); io.seek(_pos); return this.exports; } private long rebaseOff; private long rebaseSize; private long bindOff; private long bindSize; private long weakBindOff; private long weakBindSize; private long lazyBindOff; private long lazyBindSize; private long exportOff; private long exportSize; private MachO _root; private MachO.LoadCommand _parent; private byte[] _raw_rebase; private byte[] _raw_bind; private byte[] _raw_lazyBind; private byte[] _raw_exports; public long rebaseOff() { return rebaseOff; } public long rebaseSize() { return rebaseSize; } public long bindOff() { return bindOff; } public long bindSize() { return bindSize; } public long weakBindOff() { return weakBindOff; } public long weakBindSize() { return weakBindSize; } public long lazyBindOff() { return lazyBindOff; } public long lazyBindSize() { return lazyBindSize; } public long exportOff() { return exportOff; } public long exportSize() { return exportSize; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } public byte[] _raw_rebase() { return _raw_rebase; } public byte[] _raw_bind() { return _raw_bind; } public byte[] _raw_lazyBind() { return _raw_lazyBind; } public byte[] _raw_exports() { return _raw_exports; } } public static class DylinkerCommand extends KaitaiStruct { public static DylinkerCommand fromFile(String fileName) throws IOException { return new DylinkerCommand(new ByteBufferKaitaiStream(fileName)); } public DylinkerCommand(KaitaiStream _io) { this(_io, null, null); } public DylinkerCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public DylinkerCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.name = new LcStr(this._io, this, _root); } private LcStr name; private MachO _root; private MachO.LoadCommand _parent; public LcStr name() { return name; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class FatArch extends KaitaiStruct { public static FatArch fromFile(String fileName) throws IOException { return new FatArch(new ByteBufferKaitaiStream(fileName)); } public FatArch(KaitaiStream _io) { this(_io, null, null); } public FatArch(KaitaiStream _io, MachO.FatHeader _parent) { this(_io, _parent, null); } public FatArch(KaitaiStream _io, MachO.FatHeader _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.cputype = MachO.CpuType.byId(this._io.readU4be()); this.cpusubtype = this._io.readU4be(); this.offset = this._io.readU4be(); this.size = this._io.readU4be(); this.align = this._io.readU4be(); } private CpuType cputype; private long cpusubtype; private long offset; private long size; private long align; private MachO _root; private MachO.FatHeader _parent; public CpuType cputype() { return cputype; } public long cpusubtype() { return cpusubtype; } public long offset() { return offset; } public long size() { return size; } public long align() { return align; } public MachO _root() { return _root; } public MachO.FatHeader _parent() { return _parent; } } public static class DylibCommand extends KaitaiStruct { public static DylibCommand fromFile(String fileName) throws IOException { return new DylibCommand(new ByteBufferKaitaiStream(fileName)); } public DylibCommand(KaitaiStream _io) { this(_io, null, null); } public DylibCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public DylibCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.nameOffset = this._io.readU4le(); this.timestamp = this._io.readU4le(); this.currentVersion = this._io.readU4le(); this.compatibilityVersion = this._io.readU4le(); this.name = new String(this._io.readBytesTerm((byte) 0, false, true, true), Charset.forName("utf-8")); } private long nameOffset; private long timestamp; private long currentVersion; private long compatibilityVersion; private String name; private MachO _root; private MachO.LoadCommand _parent; public long nameOffset() { return nameOffset; } public long timestamp() { return timestamp; } public long currentVersion() { return currentVersion; } public long compatibilityVersion() { return compatibilityVersion; } public String name() { return name; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class SegmentCommand extends KaitaiStruct { public static SegmentCommand fromFile(String fileName) throws IOException { return new SegmentCommand(new ByteBufferKaitaiStream(fileName)); } public SegmentCommand(KaitaiStream _io) { this(_io, null, null); } public SegmentCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public SegmentCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.segname = new String(KaitaiStream.bytesStripRight(this._io.readBytes(16), (byte) 0), Charset.forName("ascii")); this.vmaddr = this._io.readU4le(); this.vmsize = this._io.readU4le(); this.fileoff = this._io.readU4le(); this.filesize = this._io.readU4le(); this.maxprot = new VmProt(this._io, this, _root); this.initprot = new VmProt(this._io, this, _root); this.nsects = this._io.readU4le(); this.flags = this._io.readU4le(); this.sections = new ArrayList<Section>(); for (int i = 0; i < nsects(); i++) { this.sections.add(new Section(this._io, this, _root)); } } public static class Section extends KaitaiStruct { public static Section fromFile(String fileName) throws IOException { return new Section(new ByteBufferKaitaiStream(fileName)); } public Section(KaitaiStream _io) { this(_io, null, null); } public Section(KaitaiStream _io, MachO.SegmentCommand _parent) { this(_io, _parent, null); } public Section(KaitaiStream _io, MachO.SegmentCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.sectName = new String(KaitaiStream.bytesStripRight(this._io.readBytes(16), (byte) 0), Charset.forName("ascii")); this.segName = new String(KaitaiStream.bytesStripRight(this._io.readBytes(16), (byte) 0), Charset.forName("ascii")); this.addr = this._io.readU4le(); this.size = this._io.readU4le(); this.offset = this._io.readU4le(); this.align = this._io.readU4le(); this.reloff = this._io.readU4le(); this.nreloc = this._io.readU4le(); this.flags = this._io.readU4le(); this.reserved1 = this._io.readU4le(); this.reserved2 = this._io.readU4le(); } private String sectName; private String segName; private long addr; private long size; private long offset; private long align; private long reloff; private long nreloc; private long flags; private long reserved1; private long reserved2; private MachO _root; private MachO.SegmentCommand _parent; public String sectName() { return sectName; } public String segName() { return segName; } public long addr() { return addr; } public long size() { return size; } public long offset() { return offset; } public long align() { return align; } public long reloff() { return reloff; } public long nreloc() { return nreloc; } public long flags() { return flags; } public long reserved1() { return reserved1; } public long reserved2() { return reserved2; } public MachO _root() { return _root; } public MachO.SegmentCommand _parent() { return _parent; } } private String segname; private long vmaddr; private long vmsize; private long fileoff; private long filesize; private VmProt maxprot; private VmProt initprot; private long nsects; private long flags; private ArrayList<Section> sections; private MachO _root; private MachO.LoadCommand _parent; public String segname() { return segname; } public long vmaddr() { return vmaddr; } public long vmsize() { return vmsize; } public long fileoff() { return fileoff; } public long filesize() { return filesize; } public VmProt maxprot() { return maxprot; } public VmProt initprot() { return initprot; } public long nsects() { return nsects; } public long flags() { return flags; } public ArrayList<Section> sections() { return sections; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class LcStr extends KaitaiStruct { public static LcStr fromFile(String fileName) throws IOException { return new LcStr(new ByteBufferKaitaiStream(fileName)); } public LcStr(KaitaiStream _io) { this(_io, null, null); } public LcStr(KaitaiStream _io, KaitaiStruct _parent) { this(_io, _parent, null); } public LcStr(KaitaiStream _io, KaitaiStruct _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.length = this._io.readU4le(); this.value = new String(this._io.readBytesTerm((byte) 0, false, true, true), Charset.forName("UTF-8")); } private long length; private String value; private MachO _root; private KaitaiStruct _parent; public long length() { return length; } public String value() { return value; } public MachO _root() { return _root; } public KaitaiStruct _parent() { return _parent; } } public static class LoadCommand extends KaitaiStruct { public static LoadCommand fromFile(String fileName) throws IOException { return new LoadCommand(new ByteBufferKaitaiStream(fileName)); } public LoadCommand(KaitaiStream _io) { this(_io, null, null); } public LoadCommand(KaitaiStream _io, MachO _parent) { this(_io, _parent, null); } public LoadCommand(KaitaiStream _io, MachO _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.type = MachO.LoadCommandType.byId(this._io.readU4le()); this.size = this._io.readU4le(); { LoadCommandType on = type(); if (on != null) { switch (type()) { case ID_DYLINKER: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new DylinkerCommand(_io__raw_body, this, _root); break; } case REEXPORT_DYLIB: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new DylibCommand(_io__raw_body, this, _root); break; } case BUILD_VERSION: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new BuildVersionCommand(_io__raw_body, this, _root); break; } case SOURCE_VERSION: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new SourceVersionCommand(_io__raw_body, this, _root); break; } case FUNCTION_STARTS: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new LinkeditDataCommand(_io__raw_body, this, _root); break; } case RPATH: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new RpathCommand(_io__raw_body, this, _root); break; } case SUB_FRAMEWORK: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new SubCommand(_io__raw_body, this, _root); break; } case ROUTINES: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new RoutinesCommand(_io__raw_body, this, _root); break; } case SUB_LIBRARY: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new SubCommand(_io__raw_body, this, _root); break; } case DYLD_INFO_ONLY: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new DyldInfoCommand(_io__raw_body, this, _root); break; } case DYLD_ENVIRONMENT: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new DylinkerCommand(_io__raw_body, this, _root); break; } case DYLD_CHAINED_FIXUPS: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new LinkeditDataCommand(_io__raw_body, this, _root); break; } case LOAD_DYLINKER: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new DylinkerCommand(_io__raw_body, this, _root); break; } case SEGMENT_SPLIT_INFO: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new LinkeditDataCommand(_io__raw_body, this, _root); break; } case MAIN: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new EntryPointCommand(_io__raw_body, this, _root); break; } case LOAD_DYLIB: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new DylibCommand(_io__raw_body, this, _root); break; } case ENCRYPTION_INFO: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new EncryptionInfoCommand(_io__raw_body, this, _root); break; } case DYSYMTAB: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new DysymtabCommand(_io__raw_body, this, _root); break; } case TWOLEVEL_HINTS: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new TwolevelHintsCommand(_io__raw_body, this, _root); break; } case ENCRYPTION_INFO_64: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new EncryptionInfoCommand(_io__raw_body, this, _root); break; } case LINKER_OPTION: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new LinkerOptionCommand(_io__raw_body, this, _root); break; } case DYLD_INFO: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new DyldInfoCommand(_io__raw_body, this, _root); break; } case VERSION_MIN_TVOS: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new VersionMinCommand(_io__raw_body, this, _root); break; } case LOAD_UPWARD_DYLIB: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new DylibCommand(_io__raw_body, this, _root); break; } case SEGMENT_64: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new SegmentCommand64(_io__raw_body, this, _root); break; } case SEGMENT: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new SegmentCommand(_io__raw_body, this, _root); break; } case SUB_UMBRELLA: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new SubCommand(_io__raw_body, this, _root); break; } case VERSION_MIN_WATCHOS: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new VersionMinCommand(_io__raw_body, this, _root); break; } case ROUTINES_64: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new RoutinesCommand64(_io__raw_body, this, _root); break; } case ID_DYLIB: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new DylibCommand(_io__raw_body, this, _root); break; } case SUB_CLIENT: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new SubCommand(_io__raw_body, this, _root); break; } case DYLIB_CODE_SIGN_DRS: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new LinkeditDataCommand(_io__raw_body, this, _root); break; } case SYMTAB: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new SymtabCommand(_io__raw_body, this, _root); break; } case LINKER_OPTIMIZATION_HINT: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new LinkeditDataCommand(_io__raw_body, this, _root); break; } case DATA_IN_CODE: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new LinkeditDataCommand(_io__raw_body, this, _root); break; } case CODE_SIGNATURE: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new CodeSignatureCommand(_io__raw_body, this, _root); break; } case VERSION_MIN_IPHONEOS: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new VersionMinCommand(_io__raw_body, this, _root); break; } case LOAD_WEAK_DYLIB: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new DylibCommand(_io__raw_body, this, _root); break; } case DYLD_EXPORTS_TRIE: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new LinkeditDataCommand(_io__raw_body, this, _root); break; } case DYLD_FILESET_ENTRY: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new LinkeditDataCommand(_io__raw_body, this, _root); break; } case LAZY_LOAD_DYLIB: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new DylibCommand(_io__raw_body, this, _root); break; } case UUID: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new UuidCommand(_io__raw_body, this, _root); break; } case VERSION_MIN_MACOSX: { this._raw_body = this._io.readBytes((size() - 8)); KaitaiStream _io__raw_body = new ByteBufferKaitaiStream(_raw_body); this.body = new VersionMinCommand(_io__raw_body, this, _root); break; } default: { this.body = this._io.readBytes((size() - 8)); break; } } } else { this.body = this._io.readBytes((size() - 8)); } } } private LoadCommandType type; private long size; private Object body; private MachO _root; private MachO _parent; private byte[] _raw_body; public LoadCommandType type() { return type; } public long size() { return size; } public Object body() { return body; } public MachO _root() { return _root; } public MachO _parent() { return _parent; } public byte[] _raw_body() { return _raw_body; } } public static class UuidCommand extends KaitaiStruct { public static UuidCommand fromFile(String fileName) throws IOException { return new UuidCommand(new ByteBufferKaitaiStream(fileName)); } public UuidCommand(KaitaiStream _io) { this(_io, null, null); } public UuidCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public UuidCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.uuid = this._io.readBytes(16); } private byte[] uuid; private MachO _root; private MachO.LoadCommand _parent; public byte[] uuid() { return uuid; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class SymtabCommand extends KaitaiStruct { public static SymtabCommand fromFile(String fileName) throws IOException { return new SymtabCommand(new ByteBufferKaitaiStream(fileName)); } public SymtabCommand(KaitaiStream _io) { this(_io, null, null); } public SymtabCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public SymtabCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.symOff = this._io.readU4le(); this.nSyms = this._io.readU4le(); this.strOff = this._io.readU4le(); this.strSize = this._io.readU4le(); } public static class StrTable extends KaitaiStruct { public static StrTable fromFile(String fileName) throws IOException { return new StrTable(new ByteBufferKaitaiStream(fileName)); } public StrTable(KaitaiStream _io) { this(_io, null, null); } public StrTable(KaitaiStream _io, MachO.SymtabCommand _parent) { this(_io, _parent, null); } public StrTable(KaitaiStream _io, MachO.SymtabCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.unknown = this._io.readU4le(); this.items = new ArrayList<String>(); { String _it; int i = 0; do { _it = new String(this._io.readBytesTerm((byte) 0, false, true, true), Charset.forName("ascii")); this.items.add(_it); i++; } while (!(_it.equals(""))); } } private long unknown; private ArrayList<String> items; private MachO _root; private MachO.SymtabCommand _parent; public long unknown() { return unknown; } public ArrayList<String> items() { return items; } public MachO _root() { return _root; } public MachO.SymtabCommand _parent() { return _parent; } } public static class Nlist extends KaitaiStruct { public static Nlist fromFile(String fileName) throws IOException { return new Nlist(new ByteBufferKaitaiStream(fileName)); } public Nlist(KaitaiStream _io) { this(_io, null, null); } public Nlist(KaitaiStream _io, MachO.SymtabCommand _parent) { this(_io, _parent, null); } public Nlist(KaitaiStream _io, MachO.SymtabCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.un = this._io.readU4le(); this.type = this._io.readU1(); this.sect = this._io.readU1(); this.desc = this._io.readU2le(); { MagicType on = _root.magic(); if (on != null) { switch (_root.magic()) { case MACHO_BE_X64: { this.value = this._io.readU8le(); break; } case MACHO_LE_X64: { this.value = this._io.readU8le(); break; } case MACHO_BE_X86: { this.value = (long) (this._io.readU4le()); break; } case MACHO_LE_X86: { this.value = (long) (this._io.readU4le()); break; } } } } } private long un; private int type; private int sect; private int desc; private Long value; private MachO _root; private MachO.SymtabCommand _parent; public long un() { return un; } public int type() { return type; } public int sect() { return sect; } public int desc() { return desc; } public Long value() { return value; } public MachO _root() { return _root; } public MachO.SymtabCommand _parent() { return _parent; } } private ArrayList<Nlist> symbols; public ArrayList<Nlist> symbols() { if (this.symbols != null) return this.symbols; KaitaiStream io = _root._io(); long _pos = io.pos(); io.seek(symOff()); this.symbols = new ArrayList<Nlist>(); for (int i = 0; i < nSyms(); i++) { this.symbols.add(new Nlist(io, this, _root)); } io.seek(_pos); return this.symbols; } private StrTable strs; public StrTable strs() { if (this.strs != null) return this.strs; KaitaiStream io = _root._io(); long _pos = io.pos(); io.seek(strOff()); this._raw_strs = io.readBytes(strSize()); KaitaiStream _io__raw_strs = new ByteBufferKaitaiStream(_raw_strs); this.strs = new StrTable(_io__raw_strs, this, _root); io.seek(_pos); return this.strs; } private long symOff; private long nSyms; private long strOff; private long strSize; private MachO _root; private MachO.LoadCommand _parent; private byte[] _raw_strs; public long symOff() { return symOff; } public long nSyms() { return nSyms; } public long strOff() { return strOff; } public long strSize() { return strSize; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } public byte[] _raw_strs() { return _raw_strs; } } public static class VersionMinCommand extends KaitaiStruct { public static VersionMinCommand fromFile(String fileName) throws IOException { return new VersionMinCommand(new ByteBufferKaitaiStream(fileName)); } public VersionMinCommand(KaitaiStream _io) { this(_io, null, null); } public VersionMinCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public VersionMinCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.version = new Version(this._io, this, _root); this.sdk = new Version(this._io, this, _root); } private Version version; private Version sdk; private MachO _root; private MachO.LoadCommand _parent; public Version version() { return version; } public Version sdk() { return sdk; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } public static class EntryPointCommand extends KaitaiStruct { public static EntryPointCommand fromFile(String fileName) throws IOException { return new EntryPointCommand(new ByteBufferKaitaiStream(fileName)); } public EntryPointCommand(KaitaiStream _io) { this(_io, null, null); } public EntryPointCommand(KaitaiStream _io, MachO.LoadCommand _parent) { this(_io, _parent, null); } public EntryPointCommand(KaitaiStream _io, MachO.LoadCommand _parent, MachO _root) { super(_io); this._parent = _parent; this._root = _root; _read(); } private void _read() { this.entryOff = this._io.readU8le(); this.stackSize = this._io.readU8le(); } private long entryOff; private long stackSize; private MachO _root; private MachO.LoadCommand _parent; public long entryOff() { return entryOff; } public long stackSize() { return stackSize; } public MachO _root() { return _root; } public MachO.LoadCommand _parent() { return _parent; } } private MagicType magic; private FatHeader fatHeader; private MachHeader header; private ArrayList<LoadCommand> loadCommands; private MachO _root; private KaitaiStruct _parent; public MagicType magic() { return magic; } public FatHeader fatHeader() { return fatHeader; } public MachHeader header() { return header; } public ArrayList<LoadCommand> loadCommands() { return loadCommands; } public MachO _root() { return _root; } public KaitaiStruct _parent() { return _parent; } }
this.b1 = this._io.readU1(); if ((b1() & 128) != 0) { this.b2 = this._io.readU1(); } if ( (((b1() & 128) != 0) && ((b2() & 128) != 0)) ) { this.b3 = this._io.readU1(); } if ( (((b1() & 128) != 0) && ((b2() & 128) != 0) && ((b3() & 128) != 0)) ) { this.b4 = this._io.readU1(); } if ( (((b1() & 128) != 0) && ((b2() & 128) != 0) && ((b3() & 128) != 0) && ((b4() & 128) != 0)) ) { this.b5 = this._io.readU1(); } if ( (((b1() & 128) != 0) && ((b2() & 128) != 0) && ((b3() & 128) != 0) && ((b4() & 128) != 0) && ((b5() & 128) != 0)) ) { this.b6 = this._io.readU1(); } if ( (((b1() & 128) != 0) && ((b2() & 128) != 0) && ((b3() & 128) != 0) && ((b4() & 128) != 0) && ((b5() & 128) != 0) && ((b6() & 128) != 0)) ) { this.b7 = this._io.readU1(); } if ( (((b1() & 128) != 0) && ((b2() & 128) != 0) && ((b3() & 128) != 0) && ((b4() & 128) != 0) && ((b5() & 128) != 0) && ((b6() & 128) != 0) && ((b7() & 128) != 0)) ) { this.b8 = this._io.readU1(); } if ( (((b1() & 128) != 0) && ((b2() & 128) != 0) && ((b3() & 128) != 0) && ((b4() & 128) != 0) && ((b5() & 128) != 0) && ((b6() & 128) != 0) && ((b7() & 128) != 0) && ((b8() & 128) != 0)) ) { this.b9 = this._io.readU1(); } if ( (((b1() & 128) != 0) && ((b2() & 128) != 0) && ((b3() & 128) != 0) && ((b4() & 128) != 0) && ((b5() & 128) != 0) && ((b6() & 128) != 0) && ((b7() & 128) != 0) && ((b8() & 128) != 0) && ((b9() & 128) != 0)) ) { this.b10 = this._io.readU1(); }
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-aop/autoload-cache-aop-aspectj/src/main/java/com/jarvis/cache/aop/aspectj/AspectjAopInterceptor.java
AspectjAopInterceptor
checkAndProceed
class AspectjAopInterceptor { private final CacheHandler cacheHandler; public AspectjAopInterceptor(CacheHandler cacheHandler) { this.cacheHandler = cacheHandler; } public Object checkAndProceed(ProceedingJoinPoint pjp) throws Throwable {<FILL_FUNCTION_BODY>} public void checkAndDeleteCache(JoinPoint jp, Object retVal) throws Throwable { Signature signature = jp.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); if (method.isAnnotationPresent(CacheDelete.class)) { CacheDelete cacheDelete = method.getAnnotation(CacheDelete.class); this.deleteCache(jp, cacheDelete, retVal); } } public Object checkAndDeleteCacheTransactional(ProceedingJoinPoint pjp) throws Throwable { Signature signature = pjp.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); if (method.isAnnotationPresent(CacheDeleteTransactional.class)) { CacheDeleteTransactional cache = method.getAnnotation(CacheDeleteTransactional.class);// method.getAnnotationsByType(Cache.class)[0]; return this.deleteCacheTransactional(pjp, cache); } try { return pjp.proceed(); } catch (Throwable e) { throw e; } } public Object proceed(ProceedingJoinPoint aopProxyChain, Cache cache) throws Throwable { return cacheHandler.proceed(new AspectjCacheAopProxyChain(aopProxyChain), cache); } public void deleteCache(JoinPoint aopProxyChain, CacheDelete cacheDelete, Object retVal) throws Throwable { cacheHandler.deleteCache(new AspectjDeleteCacheAopProxyChain(aopProxyChain), cacheDelete, retVal); } public Object deleteCacheTransactional(ProceedingJoinPoint aopProxyChain, CacheDeleteTransactional cacheDeleteTransactional) throws Throwable { return cacheHandler.proceedDeleteCacheTransactional( new AspectjDeleteCacheTransactionalAopProxyChain(aopProxyChain), cacheDeleteTransactional); } public CacheHandler getCacheHandler() { return cacheHandler; } }
Signature signature = pjp.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); if (method.isAnnotationPresent(Cache.class)) { Cache cache = method.getAnnotation(Cache.class);// method.getAnnotationsByType(Cache.class)[0]; return this.proceed(pjp, cache); } try { return pjp.proceed(); } catch (Throwable e) { throw e; }
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-aop/autoload-cache-aop-aspectj/src/main/java/com/jarvis/cache/aop/aspectj/AspectjCacheAopProxyChain.java
AspectjCacheAopProxyChain
getMethod
class AspectjCacheAopProxyChain implements CacheAopProxyChain { private final ProceedingJoinPoint jp; private Method method; public AspectjCacheAopProxyChain(ProceedingJoinPoint jp) { this.jp = jp; } @Override public Object[] getArgs() { return jp.getArgs(); } @Override public Object getTarget() { return jp.getTarget(); } @Override public Method getMethod() {<FILL_FUNCTION_BODY>} @Override public Object doProxyChain(Object[] arguments) throws Throwable { return jp.proceed(arguments); } }
if (null == method) { Signature signature = jp.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; this.method = methodSignature.getMethod(); } return method;
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-aop/autoload-cache-aop-aspectj/src/main/java/com/jarvis/cache/aop/aspectj/AspectjDeleteCacheAopProxyChain.java
AspectjDeleteCacheAopProxyChain
getMethod
class AspectjDeleteCacheAopProxyChain implements DeleteCacheAopProxyChain { private JoinPoint jp; public AspectjDeleteCacheAopProxyChain(JoinPoint jp) { this.jp = jp; } @Override public Object[] getArgs() { return jp.getArgs(); } @Override public Object getTarget() { return jp.getTarget(); } @Override public Method getMethod() {<FILL_FUNCTION_BODY>} }
Signature signature = jp.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; return methodSignature.getMethod();
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/CacheUtil.java
CacheUtil
getMiscHashCode
class CacheUtil { private static final String SPLIT_STR = "_"; @SuppressWarnings("rawtypes") public static boolean isEmpty(Object obj) { if (null == obj) { return true; } if (obj instanceof String) { return ((String) obj).length() == 0; } Class cl = obj.getClass(); if (cl.isArray()) { int len = Array.getLength(obj); return len == 0; } if (obj instanceof Collection) { Collection tempCol = (Collection) obj; return tempCol.isEmpty(); } if (obj instanceof Map) { Map tempMap = (Map) obj; return tempMap.isEmpty(); } return false; } /** * 生成字符串的HashCode * * @param buf * @return int hashCode */ private static int getHashCode(String buf) { int hash = 5381; int len = buf.length(); while (len-- > 0) { hash = ((hash << 5) + hash) + buf.charAt(len); } return hash; } /** * 将Object 对象转换为唯一的Hash字符串 * * @param obj Object * @return Hash字符串 */ public static String getUniqueHashStr(Object obj) { return getMiscHashCode(BeanUtil.toString(obj)); } /** * 通过混合Hash算法,将长字符串转为短字符串(字符串长度小于等于20时,不做处理) * * @param str String * @return Hash字符串 */ public static String getMiscHashCode(String str) {<FILL_FUNCTION_BODY>} /** * 生成缓存Key * * @param className 类名称 * @param method 方法名称 * @param arguments 参数 * @return CacheKey 缓存Key */ public static String getDefaultCacheKey(String className, String method, Object[] arguments) { StringBuilder sb = new StringBuilder(); sb.append(getDefaultCacheKeyPrefix(className, method, arguments)); if (null != arguments && arguments.length > 0) { sb.append(getUniqueHashStr(arguments)); } return sb.toString(); } /** * 生成缓存Key的前缀 * * @param className 类名称 * @param method 方法名称 * @param arguments 参数 * @return CacheKey 缓存Key */ public static String getDefaultCacheKeyPrefix(String className, String method, Object[] arguments) { StringBuilder sb = new StringBuilder(); sb.append(className); if (null != method && method.length() > 0) { sb.append(".").append(method); } return sb.toString(); } }
if (null == str || str.length() == 0) { return ""; } int originSize = 20; if (str.length() <= originSize) { return str; } StringBuilder tmp = new StringBuilder(); tmp.append(str.hashCode()).append(SPLIT_STR).append(getHashCode(str)); int mid = str.length() / 2; String str1 = str.substring(0, mid); String str2 = str.substring(mid); tmp.append(SPLIT_STR).append(str1.hashCode()); tmp.append(SPLIT_STR).append(str2.hashCode()); return tmp.toString();
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/comparator/AutoLoadOldestComparator.java
AutoLoadOldestComparator
compare
class AutoLoadOldestComparator implements Comparator<AutoLoadTO> { @Override public int compare(AutoLoadTO autoLoadTO1, AutoLoadTO autoLoadTO2) {<FILL_FUNCTION_BODY>} }
if (autoLoadTO1 == null && autoLoadTO2 != null) { return 1; } else if (autoLoadTO1 != null && autoLoadTO2 == null) { return -1; } else if (autoLoadTO1 == null && autoLoadTO2 == null) { return 0; } long now = System.currentTimeMillis(); long dif1 = now - autoLoadTO1.getLastLoadTime() - autoLoadTO1.getCache().expire() * 1000; long dif2 = now - autoLoadTO2.getLastLoadTime() - autoLoadTO2.getCache().expire() * 1000; if (dif1 > dif2) { return -1; } else if (dif1 < dif2) { return 1; } else { if (autoLoadTO1.getAverageUseTime() > autoLoadTO2.getAverageUseTime()) { return -1; } else if (autoLoadTO1.getAverageUseTime() < autoLoadTO2.getAverageUseTime()) { return 1; } } return 0;
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/comparator/AutoLoadRequestTimesComparator.java
AutoLoadRequestTimesComparator
compare
class AutoLoadRequestTimesComparator implements Comparator<AutoLoadTO> { @Override public int compare(AutoLoadTO autoLoadTO1, AutoLoadTO autoLoadTO2) {<FILL_FUNCTION_BODY>} }
if (autoLoadTO1 == null && autoLoadTO2 != null) { return 1; } else if (autoLoadTO1 != null && autoLoadTO2 == null) { return -1; } else if (autoLoadTO1 == null && autoLoadTO2 == null) { return 0; } if (autoLoadTO1.getRequestTimes() > autoLoadTO2.getRequestTimes()) { return -1; } else if (autoLoadTO1.getRequestTimes() < autoLoadTO2.getRequestTimes()) { return 1; } return 0;
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/reflect/generics/ParameterizedTypeImpl.java
ParameterizedTypeImpl
validateConstructorArguments
class ParameterizedTypeImpl implements ParameterizedType { private Type[] actualTypeArguments; private Class<?> rawType; private Type ownerType; private ParameterizedTypeImpl(Class<?> paramClass, Type[] paramArrayOfType, Type paramType) { this.actualTypeArguments = paramArrayOfType; this.rawType = paramClass; if (paramType != null) { this.ownerType = paramType; } else { this.ownerType = paramClass.getDeclaringClass(); } validateConstructorArguments(); } private void validateConstructorArguments() {<FILL_FUNCTION_BODY>} public static ParameterizedTypeImpl make(Class<?> paramClass, Type[] paramArrayOfType, Type paramType) { return new ParameterizedTypeImpl(paramClass, paramArrayOfType, paramType); } @Override public Type[] getActualTypeArguments() { return (Type[]) this.actualTypeArguments.clone(); } @Override public Class<?> getRawType() { return this.rawType; } @Override public Type getOwnerType() { return this.ownerType; } @Override public boolean equals(Object paramObject) { if ((paramObject instanceof ParameterizedType)) { ParameterizedType localParameterizedType = (ParameterizedType) paramObject; if (this == localParameterizedType) { return true; } Type localType1 = localParameterizedType.getOwnerType(); Type localType2 = localParameterizedType.getRawType(); return (this.ownerType == null ? localType1 == null : this.ownerType.equals(localType1)) && (this.rawType == null ? localType2 == null : this.rawType.equals(localType2)) && (Arrays.equals(this.actualTypeArguments, localParameterizedType.getActualTypeArguments())); } return false; } @Override public int hashCode() { return Arrays.hashCode(this.actualTypeArguments) ^ (this.ownerType == null ? 0 : this.ownerType.hashCode()) ^ (this.rawType == null ? 0 : this.rawType.hashCode()); } @Override public String toString() { StringBuilder localStringBuilder = new StringBuilder(); if (this.ownerType != null) { if ((this.ownerType instanceof Class<?>)) localStringBuilder.append(((Class<?>) this.ownerType).getName()); else { localStringBuilder.append(this.ownerType.toString()); } localStringBuilder.append("."); if ((this.ownerType instanceof ParameterizedTypeImpl)) { localStringBuilder.append(this.rawType.getName() .replace(((ParameterizedTypeImpl) this.ownerType).rawType.getName() + "$", "")); } else { localStringBuilder.append(this.rawType.getName()); } } else { localStringBuilder.append(this.rawType.getName()); } if ((this.actualTypeArguments != null) && (this.actualTypeArguments.length > 0)) { localStringBuilder.append("<"); int i = 1; for (Type localType : this.actualTypeArguments) { if (i == 0) { localStringBuilder.append(", "); } if ((localType instanceof Class<?>)) { localStringBuilder.append(((Class<?>) localType).getName()); } else { // if(null!=localType){ localStringBuilder.append(localType.toString()); // } } i = 0; } localStringBuilder.append(">"); } return localStringBuilder.toString(); } }
@SuppressWarnings("rawtypes") TypeVariable[] arrayOfTypeVariable = this.rawType.getTypeParameters(); if (arrayOfTypeVariable.length != this.actualTypeArguments.length) { throw new MalformedParameterizedTypeException(); } // for(int i=0; i < this.actualTypeArguments.length; i++);
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/to/AutoLoadTO.java
AutoLoadTO
toString
class AutoLoadTO implements Serializable { private static final long serialVersionUID = 1L; private final CacheAopProxyChain joinPoint; private final Object[] args; /** * 缓存注解 */ private final Cache cache; /** * 缓存时长 */ private int expire; /** * 缓存Key */ private final CacheKeyTO cacheKey; /** * 上次从DAO加载数据时间 */ private long lastLoadTime = 0L; /** * 上次请求数据时间 */ private long lastRequestTime = 0L; /** * 第一次请求数据时间 */ private long firstRequestTime = 0L; /** * 请求数据次数 */ private long requestTimes = 0L; private volatile boolean loading = false; /** * 加载次数 */ private long loadCnt = 0L; /** * 从DAO中加载数据,使用时间的总和 */ private long useTotalTime = 0L; public AutoLoadTO(CacheKeyTO cacheKey, CacheAopProxyChain joinPoint, Object args[], Cache cache, int expire) { this.cacheKey = cacheKey; this.joinPoint = joinPoint; this.args = args; this.cache = cache; this.expire = expire; } public CacheAopProxyChain getJoinPoint() { return joinPoint; } public long getLastRequestTime() { return lastRequestTime; } public AutoLoadTO setLastRequestTime(long lastRequestTime) { synchronized (this) { this.lastRequestTime = lastRequestTime; if (firstRequestTime == 0) { firstRequestTime = lastRequestTime; } requestTimes++; } return this; } /** * @param firstRequestTime System.currentTimeMillis() */ public void setFirstRequestTime(long firstRequestTime) { this.firstRequestTime = firstRequestTime; } public long getFirstRequestTime() { return firstRequestTime; } public long getRequestTimes() { return requestTimes; } public Cache getCache() { return cache; } public long getLastLoadTime() { return lastLoadTime; } /** * @param lastLoadTime last load time * @return this */ public AutoLoadTO setLastLoadTime(long lastLoadTime) { this.lastLoadTime = lastLoadTime; return this; } public CacheKeyTO getCacheKey() { return cacheKey; } public boolean isLoading() { return loading; } /** * @param loading 是否正在加载 * @return this */ public AutoLoadTO setLoading(boolean loading) { this.loading = loading; return this; } public Object[] getArgs() { return args; } public long getLoadCnt() { return loadCnt; } public long getUseTotalTime() { return useTotalTime; } /** * 记录用时 * * @param useTime 用时 * @return this */ public AutoLoadTO addUseTotalTime(long useTime) { synchronized (this) { this.loadCnt++; this.useTotalTime += useTime; } return this; } /** * 平均耗时 * * @return long 平均耗时 */ public long getAverageUseTime() { if (loadCnt == 0) { return 0; } return this.useTotalTime / this.loadCnt; } public int getExpire() { return expire; } /** * @param expire expire * @return this */ public AutoLoadTO setExpire(int expire) { this.expire = expire; return this; } public void flushRequestTime(CacheWrapper<Object> cacheWrapper) { // 同步最后加载时间 this.setLastRequestTime(System.currentTimeMillis()) // 同步加载时间 .setLastLoadTime(cacheWrapper.getLastLoadTime()) // 同步过期时间 .setExpire(cacheWrapper.getExpire()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AutoLoadTO that = (AutoLoadTO) o; return expire == that.expire && lastLoadTime == that.lastLoadTime && lastRequestTime == that.lastRequestTime && firstRequestTime == that.firstRequestTime && requestTimes == that.requestTimes && loading == that.loading && loadCnt == that.loadCnt && useTotalTime == that.useTotalTime && Objects.equals(joinPoint, that.joinPoint) && Arrays.equals(args, that.args) && Objects.equals(cache, that.cache) && Objects.equals(cacheKey, that.cacheKey); } @Override public int hashCode() { int result = Objects.hash(joinPoint, cache, expire, cacheKey, lastLoadTime, lastRequestTime, firstRequestTime, requestTimes, loading, loadCnt, useTotalTime); result = 31 * result + Arrays.hashCode(args); return result; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "AutoLoadTO{" + "joinPoint=" + joinPoint + ", args=" + Arrays.toString(args) + ", cache=" + cache + ", expire=" + expire + ", cacheKey=" + cacheKey + ", lastLoadTime=" + lastLoadTime + ", lastRequestTime=" + lastRequestTime + ", firstRequestTime=" + firstRequestTime + ", requestTimes=" + requestTimes + ", loading=" + loading + ", loadCnt=" + loadCnt + ", useTotalTime=" + useTotalTime + '}';
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/to/CacheKeyTO.java
CacheKeyTO
getCacheKey
class CacheKeyTO implements Serializable { private static final long serialVersionUID = 7229320497442357252L; private final String namespace; private final String key;// 缓存Key private final String hfield;// 设置哈希表中的字段,如果设置此项,则用哈希表进行存储 public CacheKeyTO(String namespace, String key, String hfield) { this.namespace = namespace; this.key = key; this.hfield = hfield; } public String getCacheKey() {<FILL_FUNCTION_BODY>} public String getLockKey() { StringBuilder key = new StringBuilder(getCacheKey()); if (null != hfield && hfield.length() > 0) { key.append(":").append(hfield); } key.append(":lock"); return key.toString(); } public String getNamespace() { return namespace; } public String getHfield() { return hfield; } public String getKey() { return key; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CacheKeyTO that = (CacheKeyTO) o; return Objects.equals(namespace, that.namespace) && Objects.equals(key, that.key) && Objects.equals(hfield, that.hfield); } @Override public int hashCode() { return Objects.hash(namespace, key, hfield); } @Override public String toString() { return "CacheKeyTO{" + "namespace='" + namespace + '\'' + ", key='" + key + '\'' + ", hfield='" + hfield + '\'' + '}'; } }
if (null != this.namespace && this.namespace.length() > 0) { return new StringBuilder(this.namespace).append(":").append(this.key).toString(); } return this.key;
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/to/CacheWrapper.java
CacheWrapper
clone
class CacheWrapper<T> implements Serializable, Cloneable { private static final long serialVersionUID = 1L; /** * 缓存数据 */ private T cacheObject; /** * 最后加载时间 */ private long lastLoadTime; /** * 缓存时长 */ private int expire; public CacheWrapper() { } public CacheWrapper(T cacheObject, int expire) { this.cacheObject = cacheObject; this.lastLoadTime = System.currentTimeMillis(); this.expire = expire; } public CacheWrapper(T cacheObject, int expire, long lastLoadTime) { this.cacheObject = cacheObject; this.lastLoadTime = lastLoadTime; this.expire = expire; } /** * 判断缓存是否已经过期 * * @return boolean */ public boolean isExpired() { if (expire > 0) { return (System.currentTimeMillis() - lastLoadTime) > expire * 1000; } return false; } public int getExpire() { return expire; } public void setCacheObject(T cacheObject) { this.cacheObject = cacheObject; } public long getLastLoadTime() { return lastLoadTime; } public T getCacheObject() { return cacheObject; } public void setLastLoadTime(long lastLoadTime) { this.lastLoadTime = lastLoadTime; } public void setExpire(int expire) { this.expire = expire; } @Override public Object clone() throws CloneNotSupportedException {<FILL_FUNCTION_BODY>} }
@SuppressWarnings("unchecked") CacheWrapper<T> tmp = (CacheWrapper<T>) super.clone(); tmp.setCacheObject(this.cacheObject); return tmp;
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/to/ProcessingTO.java
ProcessingTO
toString
class ProcessingTO { private volatile long startTime; private volatile CacheWrapper<Object> cache; private volatile boolean firstFinished = false; private volatile Throwable error; public ProcessingTO() { startTime = System.currentTimeMillis(); } public CacheWrapper<Object> getCache() { return cache; } public void setCache(CacheWrapper<Object> cache) { this.cache = cache; } public void setFirstFinished(boolean firstFinished) { this.firstFinished = firstFinished; } public boolean isFirstFinished() { return this.firstFinished; } public long getStartTime() { return startTime; } public void setError(Throwable error) { this.error = error; } public Throwable getError() { return this.error; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ProcessingTO that = (ProcessingTO) o; return startTime == that.startTime && firstFinished == that.firstFinished && Objects.equals(cache, that.cache) && Objects.equals(error, that.error); } @Override public int hashCode() { return Objects.hash(startTime, cache, firstFinished, error); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "ProcessingTO{" + "startTime=" + startTime + ", cache=" + cache + ", firstFinished=" + firstFinished + ", error=" + error + '}';
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/lib/util/BeanUtil.java
BeanUtil
toString
class BeanUtil { @SuppressWarnings("rawtypes") private static final ConcurrentHashMap<Class, Field[]> FIELDS_CAHCE = new ConcurrentHashMap<Class, Field[]>(); /** * 是否为基础数据类型 * * @param obj Object * @return boolean true or false */ public static boolean isPrimitive(Object obj) { boolean rv = obj.getClass().isPrimitive() || obj instanceof String || obj instanceof Integer || obj instanceof Long || obj instanceof Byte || obj instanceof Character || obj instanceof Boolean || obj instanceof Short || obj instanceof Float || obj instanceof Double || obj instanceof BigDecimal || obj instanceof BigInteger; return rv; } /** * 把Bean转换为字符串 * * @param obj Object * @return String String */ @SuppressWarnings("rawtypes") public static String toString(Object obj) {<FILL_FUNCTION_BODY>} }
if (obj == null) { return "null"; } Class cl = obj.getClass(); if (isPrimitive(obj)) { return String.valueOf(obj); } else if (obj instanceof Enum) { return ((Enum) obj).name(); } else if (obj instanceof Date) { return String.valueOf(((Date) obj).getTime()); } else if (obj instanceof Calendar) { return String.valueOf(((Calendar) obj).getTime().getTime()); } else if (cl.isArray()) { String r = "["; int len = Array.getLength(obj); for (int i = 0; i < len; i++) { if (i > 0) { r += ","; } Object val = Array.get(obj, i); r += toString(val); } return r + "]"; } else if (obj instanceof Collection) { Collection tempCol = (Collection) obj; Iterator it = tempCol.iterator(); String r = "["; for (int i = 0; it.hasNext(); i++) { if (i > 0) { r += ","; } Object val = it.next(); r += toString(val); } return r + "]"; } else if (obj instanceof Map) { Map tempMap = (Map) obj; String r = "{"; Iterator it = tempMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Entry) it.next(); Object key = entry.getKey(); r += toString(key); r += "="; Object val = entry.getValue(); r += toString(val); if (it.hasNext()) { r += ","; } } return r + "}"; } else if (obj instanceof Class) { Class tmpCls = (Class) obj; return tmpCls.getName(); } String r = cl.getName(); do { Field[] fields = FIELDS_CAHCE.get(cl); if (null == fields) { fields = cl.getDeclaredFields(); if (null != fields) { AccessibleObject.setAccessible(fields, true); } FIELDS_CAHCE.put(cl, fields); } if (null == fields || fields.length == 0) { cl = cl.getSuperclass(); continue; } r += "["; // get the names and values of all fields for (Field f : fields) { if (Modifier.isStatic(f.getModifiers())) { continue; } if (f.isSynthetic() || f.getName().indexOf("this$") != -1) { continue; } r += f.getName() + "="; try { Object val = f.get(obj); r += toString(val); } catch (Exception e) { e.printStackTrace(); } r += ","; } String comma = ","; if (r.endsWith(comma)) { r = r.substring(0, r.length() - 1); } r += "]"; cl = cl.getSuperclass(); } while (cl != null); return r;
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/lib/util/StringUtil.java
StringUtil
containsText
class StringUtil { /** * Check whether the given {@code CharSequence} contains actual <em>text</em>. * <p>More specifically, this method returns {@code true} if the * {@code CharSequence} is not {@code null}, its length is greater than * 0, and it contains at least one non-whitespace character. * <p><pre class="code"> * StringUtils.hasText(null) = false * StringUtils.hasText("") = false * StringUtils.hasText(" ") = false * StringUtils.hasText("12345") = true * StringUtils.hasText(" 12345 ") = true * </pre> * @param str the {@code CharSequence} to check (may be {@code null}) * @return {@code true} if the {@code CharSequence} is not {@code null}, * its length is greater than 0, and it does not contain whitespace only * @see Character#isWhitespace */ public static boolean hasText(CharSequence str) { return (str != null && str.length() > 0 && containsText(str)); } /** * Check whether the given {@code String} contains actual <em>text</em>. * <p>More specifically, this method returns {@code true} if the * {@code String} is not {@code null}, its length is greater than 0, * and it contains at least one non-whitespace character. * @param str the {@code String} to check (may be {@code null}) * @return {@code true} if the {@code String} is not {@code null}, its * length is greater than 0, and it does not contain whitespace only * @see #hasText(CharSequence) */ public static boolean hasText(String str) { return (str != null && !str.isEmpty() && containsText(str)); } private static boolean containsText(CharSequence str) {<FILL_FUNCTION_BODY>} }
int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i))) { return true; } } return false;
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/CacheHelper.java
CacheHelper
initDeleteCacheKeysSet
class CacheHelper { private static final ThreadLocal<CacheOpType> OP_TYPE = new ThreadLocal<CacheOpType>(); private static final ThreadLocal<Set<CacheKeyTO>> DELETE_CACHE_KEYS = new ThreadLocal<Set<CacheKeyTO>>(); /** * 获取CacheOpType * * @return ThreadLocal中设置的CacheOpType */ public static CacheOpType getCacheOpType() { return OP_TYPE.get(); } /** * 设置CacheOpType * * @param opType CacheOpType */ public static void setCacheOpType(CacheOpType opType) { OP_TYPE.set(opType); } /** * 移除CacheOpType */ public static void clearCacheOpType() { OP_TYPE.remove(); } public static void initDeleteCacheKeysSet() {<FILL_FUNCTION_BODY>} public static Set<CacheKeyTO> getDeleteCacheKeysSet() { return DELETE_CACHE_KEYS.get(); } public static void addDeleteCacheKey(CacheKeyTO key) { Set<CacheKeyTO> set = DELETE_CACHE_KEYS.get(); if (null != set) { set.add(key); } } public static boolean isOnTransactional() { Set<CacheKeyTO> set = DELETE_CACHE_KEYS.get(); return null != set; } public static void clearDeleteCacheKeysSet() { DELETE_CACHE_KEYS.remove(); } }
Set<CacheKeyTO> set = DELETE_CACHE_KEYS.get(); if (null == set) { set = new HashSet<CacheKeyTO>(); DELETE_CACHE_KEYS.set(set); }
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/ComboCacheManager.java
ComboCacheManager
mset
class ComboCacheManager implements ICacheManager { /** * 表达式解析器 */ private final AbstractScriptParser scriptParser; /** * 本地缓存实现 */ private ICacheManager localCache; /** * 远程缓存实现 */ private ICacheManager remoteCache; private static final Logger log = LoggerFactory.getLogger(ComboCacheManager.class); public ComboCacheManager(ICacheManager localCache, ICacheManager remoteCache, AbstractScriptParser scriptParser) { this.localCache = localCache; this.remoteCache = remoteCache; this.scriptParser = scriptParser; } @Override public void setCache(CacheKeyTO cacheKey, CacheWrapper<Object> result, Method method) throws CacheCenterConnectionException { if (method.isAnnotationPresent(LocalCache.class)) { LocalCache lCache = method.getAnnotation(LocalCache.class); setLocalCache(lCache, cacheKey, result, method); // 只本地缓存 if (lCache.localOnly()) { return; } } remoteCache.setCache(cacheKey, result, method); } @Override public void mset(Method method, Collection<MSetParam> params) throws CacheCenterConnectionException {<FILL_FUNCTION_BODY>} private void setLocalCache(LocalCache lCache, CacheKeyTO cacheKey, CacheWrapper<Object> result, Method method) { try { LocalCacheWrapper<Object> localResult = new LocalCacheWrapper<Object>(); localResult.setLastLoadTime(System.currentTimeMillis()); int expire = scriptParser.getRealExpire(lCache.expire(), lCache.expireExpression(), null, result.getCacheObject()); localResult.setExpire(expire); localResult.setCacheObject(result.getCacheObject()); localResult.setRemoteExpire(result.getExpire()); localResult.setRemoteLastLoadTime(result.getLastLoadTime()); localCache.setCache(cacheKey, result, method); } catch (Exception e) { log.error(e.getMessage(), e); } } @Override public CacheWrapper<Object> get(CacheKeyTO key, Method method) throws CacheCenterConnectionException { LocalCache lCache = null; if (method.isAnnotationPresent(LocalCache.class)) { lCache = method.getAnnotation(LocalCache.class); } String threadName = Thread.currentThread().getName(); // 如果是自动加载线程,则只从远程缓存获取。 if (null != lCache && !threadName.startsWith(AutoLoadHandler.THREAD_NAME_PREFIX)) { CacheWrapper<Object> result = localCache.get(key, method); if (null != result) { if (result instanceof LocalCacheWrapper) { LocalCacheWrapper<Object> localResult = (LocalCacheWrapper<Object>) result; return new CacheWrapper<Object>(localResult.getCacheObject(), localResult.getRemoteExpire(), localResult.getRemoteLastLoadTime()); } else { return result; } } } CacheWrapper<Object> result = remoteCache.get(key, method); // 如果取到了则先放到本地缓存里 if (null != lCache && result != null) { setLocalCache(lCache, key, result, method); } return result; } @Override public Map<CacheKeyTO, CacheWrapper<Object>> mget(final Method method, final Type returnType, final Set<CacheKeyTO> keys) throws CacheCenterConnectionException { LocalCache lCache = null; if (method.isAnnotationPresent(LocalCache.class)) { lCache = method.getAnnotation(LocalCache.class); } else { return remoteCache.mget(method, returnType, keys); } String threadName = Thread.currentThread().getName(); Map<CacheKeyTO, CacheWrapper<Object>> all; Map<CacheKeyTO, CacheWrapper<Object>> remoteResults = null; if (!threadName.startsWith(AutoLoadHandler.THREAD_NAME_PREFIX)) { all = new HashMap<>(keys.size()); Map<CacheKeyTO, CacheWrapper<Object>> localResults = localCache.mget(method, returnType, keys); if (null != localResults && !localResults.isEmpty()) { Iterator<Map.Entry<CacheKeyTO, CacheWrapper<Object>>> iterator = localResults.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<CacheKeyTO, CacheWrapper<Object>> item = iterator.next(); CacheWrapper<Object> result = item.getValue(); if (result instanceof LocalCacheWrapper) { LocalCacheWrapper<Object> localResult = (LocalCacheWrapper<Object>) result; CacheWrapper<Object> result2 = new CacheWrapper<Object>(localResult.getCacheObject(), localResult.getRemoteExpire(), localResult.getRemoteLastLoadTime()); all.put(item.getKey(), result2); } else { all.put(item.getKey(), result); } } } if(all.size() < keys.size()) { Set<CacheKeyTO> unCachekeys = new HashSet<>(keys.size() - all.size()); for(CacheKeyTO key : keys) { if(!all.containsKey(key)) { unCachekeys.add(key); } } remoteResults = remoteCache.mget(method, returnType, keys); if(null != remoteResults && !remoteResults.isEmpty()) { all.putAll(remoteResults); } } } else { remoteResults = remoteCache.mget(method, returnType, keys); all = remoteResults; } if(null != remoteResults && !remoteResults.isEmpty()) { // 放到本地缓存里 Iterator<Map.Entry<CacheKeyTO, CacheWrapper<Object>>> iterator = remoteResults.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<CacheKeyTO, CacheWrapper<Object>> item = iterator.next(); setLocalCache(lCache, item.getKey(), item.getValue(), method); } } return all; } @Override public void delete(Set<CacheKeyTO> keys) throws CacheCenterConnectionException { localCache.delete(keys); remoteCache.delete(keys); } }
if (method.isAnnotationPresent(LocalCache.class)) { LocalCache lCache = method.getAnnotation(LocalCache.class); for (MSetParam param : params) { if (param == null) { continue; } setLocalCache(lCache, param.getCacheKey(), param.getResult(), method); } // 只本地缓存 if (lCache.localOnly()) { return; } } remoteCache.mset(method, params);
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/DataLoaderFactory.java
DataLoaderFactory
getDataLoader
class DataLoaderFactory extends BasePooledObjectFactory<DataLoader> { private static volatile DataLoaderFactory instance; private final GenericObjectPool<DataLoader> factory; private DataLoaderFactory() { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(1024); config.setMaxIdle(50); config.setMinIdle(8); // 当Pool中没有对象时不等待,而是直接new个新的 config.setBlockWhenExhausted(false); AbandonedConfig abandonConfig = new AbandonedConfig(); abandonConfig.setRemoveAbandonedTimeout(300); abandonConfig.setRemoveAbandonedOnBorrow(true); abandonConfig.setRemoveAbandonedOnMaintenance(true); factory = new GenericObjectPool<DataLoader>(this, config, abandonConfig); } public static DataLoaderFactory getInstance() { if (null == instance) { synchronized (DataLoaderFactory.class) { if (null == instance) { instance = new DataLoaderFactory(); } } } return instance; } public DataLoader getDataLoader() {<FILL_FUNCTION_BODY>} public void returnObject(DataLoader loader) { loader.reset(); factory.returnObject(loader); } @Override public DataLoader create() throws Exception { return new DataLoader(); } @Override public PooledObject<DataLoader> wrap(DataLoader obj) { return new DefaultPooledObject<DataLoader>(obj); } }
try { return factory.borrowObject(); } catch (Exception e) { e.printStackTrace(); } return new DataLoader();
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/DeleteCacheMagicHandler.java
DeleteCacheMagicHandler
getCacheKeyForMagic
class DeleteCacheMagicHandler { private final CacheHandler cacheHandler; private final DeleteCacheAopProxyChain jp; private final CacheDeleteMagicKey[] cacheDeleteKeys; private final Object[] arguments; private final Method method; private final Object retVal; private final Object target; private final String methodName; private final Class<?>[] parameterTypes; public DeleteCacheMagicHandler(CacheHandler cacheHandler, DeleteCacheAopProxyChain jp, CacheDeleteMagicKey[] cacheDeleteKeys, Object retVal) { this.cacheHandler = cacheHandler; this.jp = jp; this.cacheDeleteKeys = cacheDeleteKeys; this.arguments = jp.getArgs(); this.method = jp.getMethod(); this.retVal = retVal; this.target = jp.getTarget(); this.methodName = jp.getMethod().getName(); this.parameterTypes = method.getParameterTypes(); } /** * @param cacheDeleteKey * @return * @throws Exception */ private void isMagic(CacheDeleteMagicKey cacheDeleteKey) throws Exception { String key = cacheDeleteKey.value(); if (null == key || key.length() == 0) { throw new Exception("value不允许为空"); } int iterableArgIndex = cacheDeleteKey.iterableArgIndex(); if (parameterTypes.length > 0 && iterableArgIndex >= 0) { if (iterableArgIndex >= parameterTypes.length) { throw new Exception("iterableArgIndex必须小于参数长度:" + parameterTypes.length); } if (iterableArgIndex >= 0 && cacheDeleteKey.iterableReturnValue()) { throw new Exception("不支持iterableArgIndex大于0且iterableReturnValue=true的情况"); } Class<?> tmp = parameterTypes[iterableArgIndex]; if (tmp.isArray() || Collection.class.isAssignableFrom(tmp)) { //rv = true; } else { throw new Exception("magic模式下,参数" + iterableArgIndex + "必须是数组或Collection的类型"); } } if (cacheDeleteKey.iterableReturnValue()) { Class<?> returnType = method.getReturnType(); if (returnType.isArray() || Collection.class.isAssignableFrom(returnType)) { // rv = true; } else { throw new Exception("当iterableReturnValue=true时,返回值必须是数组或Collection的类型"); } } } public List<List<CacheKeyTO>> getCacheKeyForMagic() throws Exception {<FILL_FUNCTION_BODY>} private List<CacheKeyTO> splitReturnValueOnly(CacheDeleteMagicKey cacheDeleteKey, Object retVal, String keyExpression, String hfieldExpression) throws Exception { if (null == retVal) { return Collections.emptyList(); } List<CacheKeyTO> list; if (retVal.getClass().isArray()) { Object[] newValues = (Object[]) retVal; list = new ArrayList<>(newValues.length); for (Object value : newValues) { if (!cacheHandler.getScriptParser().isCanDelete(cacheDeleteKey, arguments, value)) { continue; } list.add(this.cacheHandler.getCacheKey(target, methodName, arguments, keyExpression, hfieldExpression, value, true)); } } else if (retVal instanceof Collection) { Collection<Object> newValues = (Collection<Object>) retVal; list = new ArrayList<>(newValues.size()); for (Object value : newValues) { if (!cacheHandler.getScriptParser().isCanDelete(cacheDeleteKey, arguments, value)) { continue; } list.add(this.cacheHandler.getCacheKey(target, methodName, arguments, keyExpression, hfieldExpression, value, true)); } } else { return Collections.emptyList(); } return list; } private List<CacheKeyTO> splitArgOnly(CacheDeleteMagicKey cacheDeleteKey, Object retVal, String keyExpression, String hfieldExpression) throws Exception { int iterableArgIndex = cacheDeleteKey.iterableArgIndex(); Object tmpArg = arguments[iterableArgIndex]; List<CacheKeyTO> list = null; if (tmpArg instanceof Collection) { Collection<Object> iterableCollectionArg = (Collection<Object>) tmpArg; list = new ArrayList<>(iterableCollectionArg.size()); for (Object arg : iterableCollectionArg) { Optional<CacheKeyTO> tmp = getKey(arg, cacheDeleteKey, retVal, keyExpression, hfieldExpression); if (tmp.isPresent()) { list.add(tmp.get()); } } } else if (tmpArg.getClass().isArray()) { Object[] iterableArrayArg = (Object[]) tmpArg; list = new ArrayList<>(iterableArrayArg.length); for (Object arg : iterableArrayArg) { Optional<CacheKeyTO> tmp = getKey(arg, cacheDeleteKey, retVal, keyExpression, hfieldExpression); if (tmp.isPresent()) { list.add(tmp.get()); } } } else { return Collections.emptyList(); } return list; } private Optional<CacheKeyTO> getKey(Object arg, CacheDeleteMagicKey cacheDeleteKey, Object retVal, String keyExpression, String hfieldExpression) throws Exception { Object[] tmpArgs = new Object[arguments.length]; for (int i = 0; i < arguments.length; i++) { if (i == cacheDeleteKey.iterableArgIndex()) { tmpArgs[i] = arg; } else { tmpArgs[i] = arguments[i]; } } if (!cacheHandler.getScriptParser().isCanDelete(cacheDeleteKey, tmpArgs, retVal)) { return Optional.empty(); } return Optional.of(this.cacheHandler.getCacheKey(target, methodName, tmpArgs, keyExpression, hfieldExpression, retVal, true)); } }
List<List<CacheKeyTO>> lists = new ArrayList<>(cacheDeleteKeys.length); for (CacheDeleteMagicKey cacheDeleteKey : cacheDeleteKeys) { isMagic(cacheDeleteKey); String keyExpression = cacheDeleteKey.value(); String hfieldExpression = cacheDeleteKey.hfield(); // 只对返回值进行分割处理 if (parameterTypes.length == 0 || cacheDeleteKey.iterableArgIndex() < 0) { if (cacheDeleteKey.iterableReturnValue()) { lists.add(splitReturnValueOnly(cacheDeleteKey, retVal, keyExpression, hfieldExpression)); } continue; } int iterableArgIndex = cacheDeleteKey.iterableArgIndex(); // 只对参数进行分割处理 if (iterableArgIndex >= 0 && !cacheDeleteKey.iterableReturnValue()) { lists.add(splitArgOnly(cacheDeleteKey, retVal, keyExpression, hfieldExpression)); continue; } if (iterableArgIndex >= 0 && cacheDeleteKey.iterableReturnValue()) { } } return lists;