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/backend/dynarmic/src/main/java/com/github/unidbg/arm/backend/DynarmicBackend.java | DynarmicBackend | hook_add_new | class DynarmicBackend extends FastBackend implements Backend, DynarmicCallback {
private static final Log log = LogFactory.getLog(DynarmicBackend.class);
protected final Dynarmic dynarmic;
protected DynarmicBackend(Emulator<?> emulator, Dynarmic dynarmic) throws BackendException {
super(emulator);
this.dynarmic = dynarmic;
try {
this.dynarmic.setDynarmicCallback(this);
} catch (DynarmicException e) {
throw new BackendException(e);
}
}
@Override
public final boolean handleInterpreterFallback(long pc, int num_instructions) {
interruptHookNotifier.notifyCallSVC(this, ARMEmulator.EXCP_UDEF, 0);
return false;
}
private static final int EXCEPTION_BREAKPOINT = 8;
@Override
public void handleExceptionRaised(long pc, int exception) {
if (exception == EXCEPTION_BREAKPOINT) {
interruptHookNotifier.notifyCallSVC(this, ARMEmulator.EXCP_BKPT, 0);
return;
}
try {
emulator.attach().debug();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void handleMemoryReadFailed(long vaddr, int size) {
if (eventMemHookNotifier != null) {
eventMemHookNotifier.handleMemoryReadFailed(this, vaddr, size);
}
}
@Override
public void handleMemoryWriteFailed(long vaddr, int size) {
if (eventMemHookNotifier != null) {
eventMemHookNotifier.handleMemoryWriteFailed(this, vaddr, size);
}
}
@Override
public final void switchUserMode() {
// Only user-mode is emulated, there is no emulation of any other privilege levels.
}
@Override
public final void enableVFP() {
}
protected long until;
@Override
public final synchronized void emu_start(long begin, long until, long timeout, long count) throws BackendException {
if (log.isDebugEnabled()) {
log.debug("emu_start begin=0x" + Long.toHexString(begin) + ", until=0x" + Long.toHexString(until) + ", timeout=" + timeout + ", count=" + count);
}
this.until = until + 4;
try {
dynarmic.emu_start(begin);
} catch (DynarmicException e) {
throw new BackendException(e);
}
}
@Override
public void emu_stop() throws BackendException {
try {
dynarmic.emu_stop();
} catch (DynarmicException e) {
throw new BackendException(e);
}
}
@Override
public void destroy() {
IOUtils.close(dynarmic);
}
@Override
public byte[] mem_read(long address, long size) throws BackendException {
try {
return dynarmic.mem_read(address, (int) size);
} catch (DynarmicException e) {
throw new BackendException(e);
}
}
@Override
public void mem_write(long address, byte[] bytes) throws BackendException {
try {
dynarmic.mem_write(address, bytes);
} catch (DynarmicException e) {
throw new BackendException(e);
}
}
@Override
public void mem_map(long address, long size, int perms) throws BackendException {
try {
dynarmic.mem_map(address, size, perms);
} catch (DynarmicException e) {
throw new BackendException(e);
}
}
@Override
public void mem_protect(long address, long size, int perms) throws BackendException {
try {
dynarmic.mem_protect(address, size, perms);
} catch (DynarmicException e) {
throw new BackendException(e);
}
}
@Override
public void mem_unmap(long address, long size) throws BackendException {
try {
dynarmic.mem_unmap(address, size);
} catch (DynarmicException e) {
throw new BackendException(e);
}
}
private EventMemHookNotifier eventMemHookNotifier;
@Override
public void hook_add_new(EventMemHook callback, int type, Object user_data) {<FILL_FUNCTION_BODY>}
protected InterruptHookNotifier interruptHookNotifier;
@Override
public void hook_add_new(InterruptHook callback, Object user_data) {
if (interruptHookNotifier != null) {
throw new IllegalStateException();
} else {
interruptHookNotifier = new InterruptHookNotifier(callback, user_data);
}
}
@Override
public void hook_add_new(CodeHook callback, long begin, long end, Object user_data) {
throw new UnsupportedOperationException();
}
@Override
public void debugger_add(DebugHook callback, long begin, long end, Object user_data) {
}
@Override
public void hook_add_new(ReadHook callback, long begin, long end, Object user_data) {
throw new UnsupportedOperationException();
}
@Override
public void hook_add_new(WriteHook callback, long begin, long end, Object user_data) {
throw new UnsupportedOperationException();
}
@Override
public void hook_add_new(BlockHook callback, long begin, long end, Object user_data) {
throw new UnsupportedOperationException();
}
@Override
public long context_alloc() {
return dynarmic.context_alloc();
}
@Override
public void context_free(long context) {
Dynarmic.free(context);
}
@Override
public void context_save(long context) {
dynarmic.context_save(context);
}
@Override
public void context_restore(long context) {
dynarmic.context_restore(context);
}
} |
if (eventMemHookNotifier != null) {
throw new IllegalStateException();
} else {
eventMemHookNotifier = new EventMemHookNotifier(callback, type, user_data);
}
|
zhkl0228_unidbg | unidbg/backend/dynarmic/src/main/java/com/github/unidbg/arm/backend/DynarmicFactory.java | DynarmicFactory | newBackendInternal | class DynarmicFactory extends BackendFactory {
static {
try {
org.scijava.nativelib.NativeLoader.loadLibrary("dynarmic");
} catch (IOException ignored) {
}
}
public DynarmicFactory(boolean fallbackUnicorn) {
super(fallbackUnicorn);
}
@Override
protected Backend newBackendInternal(Emulator<?> emulator, boolean is64Bit) {<FILL_FUNCTION_BODY>}
} |
Dynarmic dynarmic = new Dynarmic(is64Bit);
return is64Bit ? new DynarmicBackend64(emulator, dynarmic) : new DynarmicBackend32(emulator, dynarmic);
|
zhkl0228_unidbg | unidbg/backend/dynarmic/src/main/java/com/github/unidbg/arm/backend/dynarmic/DynarmicBackend32.java | DynarmicBackend32 | reg_read | class DynarmicBackend32 extends DynarmicBackend {
private static final Log log = LogFactory.getLog(DynarmicBackend32.class);
public DynarmicBackend32(Emulator<?> emulator, Dynarmic dynarmic) {
super(emulator, dynarmic);
}
@Override
public void callSVC(long pc, int swi) {
if (log.isDebugEnabled()) {
log.debug("callSVC pc=0x" + Long.toHexString(pc) + ", swi=" + swi);
}
if (pc == until) {
emu_stop();
return;
}
interruptHookNotifier.notifyCallSVC(this, ARMEmulator.EXCP_SWI, swi);
}
@Override
public Number reg_read(int regId) throws BackendException {<FILL_FUNCTION_BODY>}
@Override
public void reg_write(int regId, Number value) throws BackendException {
try {
switch (regId) {
case ArmConst.UC_ARM_REG_R0:
case ArmConst.UC_ARM_REG_R1:
case ArmConst.UC_ARM_REG_R2:
case ArmConst.UC_ARM_REG_R3:
case ArmConst.UC_ARM_REG_R4:
case ArmConst.UC_ARM_REG_R5:
case ArmConst.UC_ARM_REG_R6:
case ArmConst.UC_ARM_REG_R7:
case ArmConst.UC_ARM_REG_R8:
case ArmConst.UC_ARM_REG_R9:
case ArmConst.UC_ARM_REG_R10:
case ArmConst.UC_ARM_REG_R11:
case ArmConst.UC_ARM_REG_R12:
dynarmic.reg_write32(regId - ArmConst.UC_ARM_REG_R0, value.intValue());
break;
case ArmConst.UC_ARM_REG_SP:
dynarmic.reg_write32(13, value.intValue());
break;
case ArmConst.UC_ARM_REG_LR:
dynarmic.reg_write32(14, value.intValue());
break;
case ArmConst.UC_ARM_REG_C13_C0_3:
dynarmic.reg_write_c13_c0_3(value.intValue());
break;
case ArmConst.UC_ARM_REG_CPSR:
dynarmic.reg_write_cpsr(value.intValue());
break;
default:
throw new DynarmicException("regId=" + regId);
}
} catch (DynarmicException e) {
throw new BackendException(e);
}
}
@Override
public byte[] reg_read_vector(int regId) throws BackendException {
return null;
}
@Override
public void reg_write_vector(int regId, byte[] vector) throws BackendException {
throw new UnsupportedOperationException();
}
@Override
protected byte[] addSoftBreakPoint(long address, int svcNumber, boolean thumb) {
try (Keystone keystone = new Keystone(KeystoneArchitecture.Arm, thumb ? KeystoneMode.ArmThumb : KeystoneMode.Arm)) {
KeystoneEncoded encoded = keystone.assemble("bkpt #" + svcNumber);
return encoded.getMachineCode();
}
}
} |
try {
switch (regId) {
case ArmConst.UC_ARM_REG_R0:
case ArmConst.UC_ARM_REG_R1:
case ArmConst.UC_ARM_REG_R2:
case ArmConst.UC_ARM_REG_R3:
case ArmConst.UC_ARM_REG_R4:
case ArmConst.UC_ARM_REG_R5:
case ArmConst.UC_ARM_REG_R6:
case ArmConst.UC_ARM_REG_R7:
case ArmConst.UC_ARM_REG_R8:
case ArmConst.UC_ARM_REG_R9:
case ArmConst.UC_ARM_REG_R10:
case ArmConst.UC_ARM_REG_R11:
case ArmConst.UC_ARM_REG_R12:
return dynarmic.reg_read32(regId - ArmConst.UC_ARM_REG_R0);
case ArmConst.UC_ARM_REG_SP:
return dynarmic.reg_read32(13);
case ArmConst.UC_ARM_REG_LR:
return dynarmic.reg_read32(14);
case ArmConst.UC_ARM_REG_PC:
return dynarmic.reg_read32(15);
case ArmConst.UC_ARM_REG_CPSR:
return dynarmic.reg_read_cpsr();
default:
throw new DynarmicException("regId=" + regId);
}
} catch (DynarmicException e) {
throw new BackendException(e);
}
|
zhkl0228_unidbg | unidbg/backend/dynarmic/src/main/java/com/github/unidbg/arm/backend/dynarmic/EventMemHookNotifier.java | EventMemHookNotifier | handleMemoryReadFailed | class EventMemHookNotifier {
private final EventMemHook callback;
private final int type;
private final Object user_data;
public EventMemHookNotifier(EventMemHook callback, int type, Object user_data) {
this.callback = callback;
this.type = type;
this.user_data = user_data;
}
public void handleMemoryReadFailed(Backend backend, long vaddr, int size) {<FILL_FUNCTION_BODY>}
public void handleMemoryWriteFailed(Backend backend, long vaddr, int size) {
if ((type & UnicornConst.UC_HOOK_MEM_WRITE_UNMAPPED) != 0) {
callback.hook(backend, vaddr, size, 0, user_data, EventMemHook.UnmappedType.Write);
}
}
} |
if ((type & UnicornConst.UC_HOOK_MEM_READ_UNMAPPED) != 0) {
callback.hook(backend, vaddr, size, 0, user_data, EventMemHook.UnmappedType.Read);
}
|
zhkl0228_unidbg | unidbg/backend/hypervisor/src/main/java/com/github/unidbg/arm/backend/HypervisorFactory.java | HypervisorFactory | newBackendInternal | class HypervisorFactory extends BackendFactory {
static {
try {
NativeLoader.loadLibrary("hypervisor");
} catch (IOException ignored) {
}
}
public HypervisorFactory(boolean fallbackUnicorn) {
super(fallbackUnicorn);
}
@Override
protected Backend newBackendInternal(Emulator<?> emulator, boolean is64Bit) {<FILL_FUNCTION_BODY>}
} |
Hypervisor hypervisor = new Hypervisor(is64Bit);
if (is64Bit) {
return new HypervisorBackend64(emulator, hypervisor);
} else {
throw new UnsupportedOperationException();
}
|
zhkl0228_unidbg | unidbg/backend/hypervisor/src/main/java/com/github/unidbg/arm/backend/hypervisor/ExceptionVisitor.java | ExceptionVisitor | breakRestorerVisitor | class ExceptionVisitor {
public abstract boolean onException(Hypervisor hypervisor, int ec, long address);
static ExceptionVisitor breakRestorerVisitor(final BreakRestorer breakRestorer) {<FILL_FUNCTION_BODY>}
} |
return new ExceptionVisitor() {
@Override
public boolean onException(Hypervisor hypervisor, int ec, long address) {
breakRestorer.install(hypervisor);
return false;
}
};
|
zhkl0228_unidbg | unidbg/backend/hypervisor/src/main/java/com/github/unidbg/arm/backend/hypervisor/HypervisorWatchpoint.java | HypervisorWatchpoint | onHit | class HypervisorWatchpoint implements BreakRestorer {
private static final Log log = LogFactory.getLog(HypervisorWatchpoint.class);
private final Object callback;
private final long begin;
private final long end;
private final Object user_data;
final int n;
private final boolean isWrite;
private final long dbgwcr, dbgwvr, bytes;
HypervisorWatchpoint(Object callback, long begin, long end, Object user_data, int n, boolean isWrite) {
if (begin >= end) {
throw new IllegalArgumentException("begin=0x" + Long.toHexString(begin) + ", end=" + Long.toHexString(end));
}
long size = end - begin;
if ((size >>> 31) != 0) {
throw new IllegalArgumentException("too large size=0x" + Long.toHexString(size));
}
this.callback = callback;
this.begin = begin;
this.end = end;
this.user_data = user_data;
this.n = n;
this.isWrite = isWrite;
long dbgwcr = 0x5;
if (isWrite) {
dbgwcr |= 0b10 << 3;
} else {
dbgwcr |= 0b01 << 3;
}
for (int i = 2; i <= 31; i++) {
int bytes = 1 << i;
int mask = bytes - 1;
long dbgwvr = begin & ~mask;
long offset = begin - dbgwvr;
if(offset + size <= bytes) {
long bas;
int maskBits;
if (i <= 3) {
maskBits = 0;
bas = 0;
for (long m = 0; m < size; m++) {
bas |= (1L << (offset + m));
}
} else {
maskBits = i;
bas = 0xff;
}
dbgwcr |= (bas << 5);
dbgwcr |= (maskBits << 24);
if (log.isDebugEnabled()) {
log.debug("begin=0x" + Long.toHexString(begin) + ", end=0x" + Long.toHexString(end) + ", dbgwvr=0x" + Long.toHexString(dbgwvr) + ", dbgwcr=0x" + Long.toHexString(dbgwcr) + ", offset=" + offset + ", size=" + size + ", i=" + i);
}
this.bytes = bytes;
this.dbgwvr = dbgwvr;
this.dbgwcr = dbgwcr;
return;
}
}
throw new UnsupportedOperationException("begin=0x" + Long.toHexString(begin) + ", end=0x" + Long.toHexString(end));
}
final boolean contains(long address, boolean isWrite) {
if (isWrite ^ this.isWrite) {
return false;
}
return address >= dbgwvr && address < (dbgwvr + bytes);
}
final boolean onHit(Backend backend, long address, boolean isWrite, Disassembler disassembler, byte[] code, long pc) {<FILL_FUNCTION_BODY>}
@Override
public final void install(Hypervisor hypervisor) {
hypervisor.install_watchpoint(n, dbgwvr, dbgwcr);
}
} |
MemorySizeDetector memorySizeDetector = new SimpleMemorySizeDetector();
if (address >= begin && address <= end) {
if (isWrite) {
((WriteHook) callback).hook(backend, address, 0, 0, user_data);
} else {
int size = memorySizeDetector.detectReadSize(disassembler, code, pc);
((ReadHook) callback).hook(backend, address, size, user_data);
}
return true;
} else {
return false;
}
|
zhkl0228_unidbg | unidbg/backend/hypervisor/src/main/java/com/github/unidbg/arm/backend/hypervisor/arm64/SimpleMemorySizeDetector.java | SimpleMemorySizeDetector | detectReadSize | class SimpleMemorySizeDetector implements MemorySizeDetector {
private static final Log log = LogFactory.getLog(SimpleMemorySizeDetector.class);
@Override
public int detectReadSize(Disassembler disassembler, byte[] code, long pc) {<FILL_FUNCTION_BODY>}
} |
Instruction insn = disassembler.disasm(code, pc, 1)[0];
int size = 0;
switch (insn.getMnemonic()) {
case "ldursb":
size = 1;
break;
case "ldursh":
size = 2;
break;
case "ldr":
case "ldxr":
case "ldur":
if (insn.getOpStr().startsWith("w")) {
size = 4;
break;
}
if (insn.getOpStr().startsWith("x")) {
size = 8;
break;
}
default:
log.info("onHit: insn=" + insn);
break;
}
return size;
|
zhkl0228_unidbg | unidbg/backend/kvm/src/main/java/com/github/unidbg/arm/backend/KvmFactory.java | KvmFactory | newBackendInternal | class KvmFactory extends BackendFactory {
private static boolean supportKvm() {
File kvm = new File("/dev/kvm");
return kvm.exists();
}
static {
try {
if (NativeLibraryUtil.getArchitecture() == NativeLibraryUtil.Architecture.LINUX_ARM64 &&
supportKvm()) {
org.scijava.nativelib.NativeLoader.loadLibrary("kvm");
}
} catch (IOException ignored) {
}
}
public KvmFactory(boolean fallbackUnicorn) {
super(fallbackUnicorn);
}
@Override
protected Backend newBackendInternal(Emulator<?> emulator, boolean is64Bit) {<FILL_FUNCTION_BODY>}
} |
if (supportKvm()) {
Kvm kvm = new Kvm(is64Bit);
if (is64Bit) {
return new KvmBackend64(emulator, kvm);
} else {
return new KvmBackend32(emulator, kvm);
}
} else {
throw new UnsupportedOperationException();
}
|
zhkl0228_unidbg | unidbg/backend/kvm/src/main/java/com/github/unidbg/arm/backend/UserMemoryRegion.java | UserMemoryRegion | toString | class UserMemoryRegion {
final int slot;
// int flags;
final long guest_phys_addr;
final long memory_size; /* bytes */
final long userspace_addr; /* start of the userspace allocated memory */
UserMemoryRegion(int slot, long guest_phys_addr, long memory_size, long userspace_addr) {
this.slot = slot;
this.guest_phys_addr = guest_phys_addr;
this.memory_size = memory_size;
this.userspace_addr = userspace_addr;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
} |
return "UserMemoryRegion{" +
"slot=" + slot +
", guest_phys_addr=0x" + Long.toHexString(guest_phys_addr) +
", memory_size=0x" + Long.toHexString(memory_size) +
", userspace_addr=0x" + Long.toHexString(userspace_addr) +
'}';
|
zhkl0228_unidbg | unidbg/backend/unicorn2/src/main/java/com/github/unidbg/arm/backend/unicorn/Unicorn.java | Unicorn | registerEmuCountHook | class Unicorn {
private static final Hashtable<Integer,Integer> eventMemMap = new Hashtable<>();
static {
eventMemMap.put(UnicornConst.UC_HOOK_MEM_READ_UNMAPPED, UnicornConst.UC_MEM_READ_UNMAPPED);
eventMemMap.put(UnicornConst.UC_HOOK_MEM_WRITE_UNMAPPED, UnicornConst.UC_MEM_WRITE_UNMAPPED);
eventMemMap.put(UnicornConst.UC_HOOK_MEM_FETCH_UNMAPPED, UnicornConst.UC_MEM_FETCH_UNMAPPED);
eventMemMap.put(UnicornConst.UC_HOOK_MEM_READ_PROT, UnicornConst.UC_MEM_READ_PROT);
eventMemMap.put(UnicornConst.UC_HOOK_MEM_WRITE_PROT, UnicornConst.UC_MEM_WRITE_PROT);
eventMemMap.put(UnicornConst.UC_HOOK_MEM_FETCH_PROT, UnicornConst.UC_MEM_FETCH_PROT);
eventMemMap.put(UnicornConst.UC_HOOK_MEM_READ, UnicornConst.UC_MEM_READ);
eventMemMap.put(UnicornConst.UC_HOOK_MEM_WRITE, UnicornConst.UC_MEM_WRITE);
eventMemMap.put(UnicornConst.UC_HOOK_MEM_FETCH, UnicornConst.UC_MEM_FETCH);
eventMemMap.put(UnicornConst.UC_HOOK_MEM_READ_AFTER, UnicornConst.UC_MEM_READ_AFTER);
}
private static class Tuple {
public Hook function;
public Object data;
public Tuple(Hook f, Object d) {
function = f;
data = d;
}
}
public class UnHook {
private final long handle;
public UnHook(long handle) {
this.handle = handle;
newHookList.add(this);
}
public void unhook() {
unhookInternal();
newHookList.remove(this);
}
private boolean unhooked;
private void unhookInternal() {
if (!unhooked && handle != 0) {
hook_del(handle);
}
unhooked = true;
}
}
private class NewHook extends Tuple {
public NewHook(Hook f, Object d) {
super(f, d);
}
/**
* for UC_HOOK_BLOCK
*/
void onBlock(long address, int size) {
BlockHook hook = (BlockHook) function;
hook.hook(Unicorn.this, address, size, data);
}
/**
* for UC_HOOK_CODE
*/
void onCode(long address, int size) {
CodeHook hook = (CodeHook) function;
hook.hook(Unicorn.this, address, size, data);
}
/**
* on breakpoint hit
*/
void onBreak(long address, int size) {
DebugHook hook = (DebugHook) function;
hook.onBreak(Unicorn.this, address, size, data);
}
/**
* for UC_HOOK_MEM_READ
*/
void onRead(long address, int size) {
ReadHook hook = (ReadHook) function;
hook.hook(Unicorn.this, address, size, data);
}
/**
* for UC_HOOK_MEM_WRITE
*/
void onWrite(long address, int size, long value) {
WriteHook hook = (WriteHook) function;
hook.hook(Unicorn.this, address, size, value, data);
}
/**
* for UC_HOOK_INTR
*/
void onInterrupt(int intno) {
InterruptHook hook = (InterruptHook) function;
hook.hook(Unicorn.this, intno, data);
}
/**
* for UC_HOOK_MEM_*
*/
boolean onMemEvent(int type, long address, int size, long value) {
EventMemHook hook = (EventMemHook) function;
return hook.hook(Unicorn.this, address, size, value, data);
}
}
/**
* Native access to uc_open
*
* @param arch Architecture type (UC_ARCH_*)
* @param mode Hardware mode. This is combined of UC_MODE_*
*/
private static native long nativeInitialize(int arch, int mode) throws UnicornException;
/**
* Close the underlying uc_engine* eng associated with this Unicorn object
*
*/
private static native void nativeDestroy(long handle) throws UnicornException;
/**
* Hook registration helper for unhook.
*
* @param handle Unicorn uch returned for registered hook function
*/
private static native void hook_del(long handle) throws UnicornException;
/**
* Read register value.
*
* @param regid Register ID that is to be retrieved.
* @param regsz Size of the register being retrieved.
* @return Byte array containing the requested register value.
*/
public byte[] reg_read(int regid, int regsz) throws UnicornException {
return reg_read(nativeHandle, regid, regsz);
}
private static native byte[] reg_read(long handle, int regid, int regsz) throws UnicornException;
/**
* Write to register.
*
* @param regid Register ID that is to be modified.
* @param value Array containing value that will be written into register @regid
*/
public void reg_write(int regid, byte[] value) throws UnicornException {
reg_write(nativeHandle, regid, value);
}
private static native void reg_write(long handle, int regid, byte[] value) throws UnicornException;
/**
* Read register value.
*
* @param regid Register ID that is to be retrieved.
* @return Number containing the requested register value.
*/
public long reg_read(int regid) throws UnicornException {
return reg_read(nativeHandle, regid);
}
private static native long reg_read(long handle, int regid) throws UnicornException;
/**
* Write to register.
*
* @param regid Register ID that is to be modified.
* @param value Number containing the new register value
*/
public void reg_write(int regid, long value) throws UnicornException {
reg_write(nativeHandle, regid, value);
}
private static native void reg_write(long handle, int regid, long value) throws UnicornException;
public UnHook registerEmuCountHook(long emu_count) {<FILL_FUNCTION_BODY>}
private static native long register_emu_count_hook(long handle, long emu_count, NewHook hook);
/**
* Read memory contents.
*
* @param address Start addres of the memory region to be read.
* @param size Number of bytes to be retrieved.
* @return Byte array containing the contents of the requested memory range.
*/
public byte[] mem_read(long address, long size) throws UnicornException {
return mem_read(nativeHandle, address, size);
}
private static native byte[] mem_read(long handle, long address, long size) throws UnicornException;
/**
* Write to memory.
*
* @param address Start addres of the memory region to be written.
* @param bytes The values to be written into memory. bytes.length bytes will be written.
*/
public void mem_write(long address, byte[] bytes) throws UnicornException {
mem_write(nativeHandle, address, bytes);
}
private static native void mem_write(long handle, long address, byte[] bytes) throws UnicornException;
/**
* Map a range of memory.
*
* @param address Base address of the memory range
* @param size Size of the memory block.
* @param perms Permissions on the memory block. A combination of UC_PROT_READ, UC_PROT_WRITE, UC_PROT_EXEC
*/
public void mem_map(long address, long size, int perms) throws UnicornException {
mem_map(nativeHandle, address, size, perms);
}
private static native void mem_map(long handle, long address, long size, int perms) throws UnicornException;
/**
* Change permissions on a range of memory.
*
* @param address Base address of the memory range
* @param size Size of the memory block.
* @param perms New permissions on the memory block. A combination of UC_PROT_READ, UC_PROT_WRITE, UC_PROT_EXEC
*/
public void mem_protect(long address, long size, int perms) throws UnicornException {
mem_protect(nativeHandle, address, size, perms);
}
private static native void mem_protect(long handle, long address, long size, int perms) throws UnicornException;
/**
* Unmap a range of memory.
*
* @param address Base address of the memory range
* @param size Size of the memory block.
*/
public void mem_unmap(long address, long size) throws UnicornException {
mem_unmap(nativeHandle, address, size);
}
private static native void mem_unmap(long handle, long address, long size) throws UnicornException;
public void setFastDebug(boolean fastDebug) {
setFastDebug(nativeHandle, fastDebug);
}
private static native void setFastDebug(long handle, boolean fastDebug);
public void setSingleStep(int singleStep) {
setSingleStep(nativeHandle, singleStep);
}
private static native void setSingleStep(long handle, int singleStep);
public void addBreakPoint(long address) {
addBreakPoint(nativeHandle, address);
}
private static native void addBreakPoint(long handle, long address);
public void removeBreakPoint(long address) {
removeBreakPoint(nativeHandle, address);
}
private static native void removeBreakPoint(long handle, long address);
/**
* Hook registration helper for hook types that require two additional arguments.
*
* @param handle Internal unicorn uc_engine* eng associated with hooking Unicorn object
* @param type UC_HOOK_* hook type
* @return Unicorn uch returned for registered hook function
*/
private native static long registerHook(long handle, int type, long begin, long end, NewHook hook);
/**
* Hook registration helper for hook types that require no additional arguments.
*
* @param handle Internal unicorn uc_engine* eng associated with hooking Unicorn object
* @param type UC_HOOK_* hook type
* @return Unicorn uch returned for registered hook function
*/
private native static long registerHook(long handle, int type, NewHook hook);
private native static long registerDebugger(long handle, long begin, long end, NewHook hook);
/**
* Emulate machine code in a specific duration of time.
*
* @param begin Address where emulation starts
* @param until Address where emulation stops (i.e when this address is hit)
* @param timeout Duration to emulate the code (in microseconds). When this value is 0, we will emulate the code in infinite time, until the code is finished.
* @param count The number of instructions to be emulated. When this value is 0, we will emulate all the code available, until the code is finished.
*/
public void emu_start(long begin, long until, long timeout, long count) throws UnicornException {
emu_start(nativeHandle, begin, until, timeout, count);
}
private static native void emu_start(long handle, long begin, long until, long timeout, long count) throws UnicornException;
/**
* Stop emulation (which was started by emu_start() ).
* This is typically called from callback functions registered via tracing APIs.
* NOTE: for now, this will stop the execution only after the current block.
*/
public void emu_stop() throws UnicornException {
emu_stop(nativeHandle);
}
private static native void emu_stop(long handle) throws UnicornException;
/**
* Allocate a region that can be used with uc_context_{save,restore} to perform
* quick save/rollback of the CPU context, which includes registers and some
* internal metadata. Contexts may not be shared across engine instances with
* differing arches or modes.
*
* @return context handle for use with save/restore.
*/
public long context_alloc() {
return context_alloc(nativeHandle);
}
private static native long context_alloc(long handle);
/**
* Free a resource allocated within Unicorn. Use for handles
* allocated by context_alloc.
*
* @param handle Previously allocated Unicorn object handle.
*/
public static native void free(long handle);
/**
* Save a copy of the internal CPU context.
* This API should be used to efficiently make or update a saved copy of the
* internal CPU state.
*
* @param context handle previously returned by context_alloc.
*/
public void context_save(long context) {
context_save(nativeHandle, context);
}
private static native void context_save(long handle, long context);
/**
* Restore the current CPU context from a saved copy.
* This API should be used to roll the CPU context back to a previous
* state saved by uc_context_save().
*
* @param context handle previously returned by context_alloc.
*/
public void context_restore(long context) {
context_restore(nativeHandle, context);
}
private static native void context_restore(long handle, long context);
public static native void testSampleArm();
public static native void testSampleArm64();
public final void removeJitCodeCache(long begin, long end) {
removeCache(nativeHandle, begin, end);
}
private static native void removeCache(long handle, long begin, long end);
public UnHook hook_add_new(BlockHook callback, long begin, long end, Object user_data) throws UnicornException {
NewHook hook = new NewHook(callback, user_data);
long handle = registerHook(nativeHandle, UnicornConst.UC_HOOK_BLOCK, begin, end, hook);
return new UnHook(handle);
}
public UnHook hook_add_new(InterruptHook callback, Object user_data) throws UnicornException {
NewHook hook = new NewHook(callback, user_data);
long handle = registerHook(nativeHandle, UnicornConst.UC_HOOK_INTR, hook);
return new UnHook(handle);
}
public Map<Integer, UnHook> hook_add_new(EventMemHook callback, int type, Object user_data) throws UnicornException {
//test all of the EventMem related bits in type
Map<Integer, UnHook> map = new HashMap<>(eventMemMap.size());
for (Integer htype : eventMemMap.keySet()) {
if ((type & htype) != 0) { //the 'htype' bit is set in type
NewHook hook = new NewHook(callback, user_data);
long handle = registerHook(nativeHandle, htype, hook);
map.put(htype, new UnHook(handle));
}
}
return map;
}
public UnHook hook_add_new(ReadHook callback, long begin, long end, Object user_data) throws UnicornException {
NewHook hook = new NewHook(callback, user_data);
long handle = registerHook(nativeHandle, UnicornConst.UC_HOOK_MEM_READ, begin, end, hook);
return new UnHook(handle);
}
public UnHook hook_add_new(WriteHook callback, long begin, long end, Object user_data) throws UnicornException {
NewHook hook = new NewHook(callback, user_data);
long handle = registerHook(nativeHandle, UnicornConst.UC_HOOK_MEM_WRITE, begin, end, hook);
return new UnHook(handle);
}
public UnHook hook_add_new(CodeHook callback, long begin, long end, Object user_data) throws UnicornException {
NewHook hook = new NewHook(callback, user_data);
long handle = registerHook(nativeHandle, UnicornConst.UC_HOOK_CODE, begin, end, hook);
return new UnHook(handle);
}
public UnHook debugger_add(DebugHook callback, long begin, long end, Object user_data) throws UnicornException {
NewHook hook = new NewHook(callback, user_data);
long handle = registerDebugger(nativeHandle, begin, end, hook);
return new UnHook(handle);
}
private final List<UnHook> newHookList = new ArrayList<>();
private final long nativeHandle;
public Unicorn(int arch, int mode) throws UnicornException {
this.nativeHandle = nativeInitialize(arch, mode);
}
public void closeAll() throws UnicornException {
for (UnHook unHook : newHookList) {
unHook.unhookInternal();
}
nativeDestroy(nativeHandle);
}
} |
NewHook hook = new NewHook(new CodeHook() {
@Override
public void hook(Unicorn u, long address, int size, Object user) {
throw new ThreadContextSwitchException();
}
}, null);
return new UnHook(register_emu_count_hook(nativeHandle, emu_count, hook));
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/file/linux/BaseAndroidFileIO.java | BaseAndroidFileIO | setFlags | class BaseAndroidFileIO extends BaseFileIO implements AndroidFileIO {
public BaseAndroidFileIO(int oflags) {
super(oflags);
}
@Override
public int fstat(Emulator<?> emulator, StatStructure stat) {
throw new UnsupportedOperationException(getClass().getName());
}
@Override
public int getdents64(Pointer dirp, int size) {
throw new UnsupportedOperationException(getClass().getName());
}
@Override
public AndroidFileIO accept(Pointer addr, Pointer addrlen) {
throw new UnsupportedOperationException(getClass().getName());
}
@Override
public int statfs(StatFS statFS) {
throw new UnsupportedOperationException(getClass().getName());
}
@Override
protected void setFlags(long arg) {<FILL_FUNCTION_BODY>}
} |
if ((IOConstants.O_APPEND & arg) != 0) {
oflags |= IOConstants.O_APPEND;
}
if ((IOConstants.O_RDWR & arg) != 0) {
oflags |= IOConstants.O_RDWR;
}
if ((IOConstants.O_NONBLOCK & arg) != 0) {
oflags |= IOConstants.O_NONBLOCK;
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/file/linux/LinuxFileSystem.java | LinuxFileSystem | open | class LinuxFileSystem extends BaseFileSystem<AndroidFileIO> implements FileSystem<AndroidFileIO>, IOConstants {
public LinuxFileSystem(Emulator<AndroidFileIO> emulator, File rootDir) {
super(emulator, rootDir);
}
@Override
public FileResult<AndroidFileIO> open(String pathname, int oflags) {<FILL_FUNCTION_BODY>}
public LogCatHandler getLogCatHandler() {
return null;
}
@Override
protected void initialize(File rootDir) throws IOException {
super.initialize(rootDir);
FileUtils.forceMkdir(new File(rootDir, "system"));
FileUtils.forceMkdir(new File(rootDir, "data"));
}
@Override
public AndroidFileIO createSimpleFileIO(File file, int oflags, String path) {
return new SimpleFileIO(oflags, file, path);
}
@Override
public AndroidFileIO createDirectoryFileIO(File file, int oflags, String path) {
return new DirectoryFileIO(oflags, path, file);
}
@Override
protected AndroidFileIO createStdin(int oflags) {
return new Stdin(oflags);
}
@Override
protected AndroidFileIO createStdout(int oflags, File stdio, String pathname) {
return new Stdout(oflags, stdio, pathname, IO.STDERR.equals(pathname), null);
}
@Override
protected boolean hasCreat(int oflags) {
return (oflags & O_CREAT) != 0;
}
@Override
protected boolean hasDirectory(int oflags) {
return (oflags & O_DIRECTORY) != 0;
}
@Override
protected boolean hasAppend(int oflags) {
return (oflags & O_APPEND) != 0;
}
@Override
protected boolean hasExcl(int oflags) {
return (oflags & O_EXCL) != 0;
}
} |
if ("/dev/tty".equals(pathname)) {
return FileResult.<AndroidFileIO>success(new NullFileIO(pathname));
}
if ("/proc/self/maps".equals(pathname) || ("/proc/" + emulator.getPid() + "/maps").equals(pathname) ||
("/proc/self/task/" + emulator.getPid() + "/maps").equals(pathname)) {
return FileResult.<AndroidFileIO>success(new MapsFileIO(emulator, oflags, pathname, emulator.getMemory().getLoadedModules()));
}
return super.open(pathname, oflags);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/AbsoluteInitFunction.java | AbsoluteInitFunction | call | class AbsoluteInitFunction extends InitFunction {
private static final Log log = LogFactory.getLog(AbsoluteInitFunction.class);
private final UnidbgPointer ptr;
private static long getFuncAddress(UnidbgPointer ptr) {
UnidbgPointer func = ptr.getPointer(0);
return func == null ? 0 : func.peer;
}
AbsoluteInitFunction(long load_base, String libName, UnidbgPointer ptr) {
super(load_base, libName, getFuncAddress(ptr));
this.ptr = ptr;
}
@Override
public long getAddress() {
return address;
}
@Override
public long call(Emulator<?> emulator) {<FILL_FUNCTION_BODY>}
} |
long address = getFuncAddress(ptr);
if (address == 0) {
address = this.address;
}
if (emulator.is32Bit()) {
address = (int) address;
}
if (address == 0 || address == -1) {
if (log.isDebugEnabled()) {
log.debug("[" + libName + "]CallInitFunction: address=0x" + Long.toHexString(address) + ", ptr=" + ptr + ", func=" + ptr.getPointer(0));
}
return address;
}
Pointer pointer = UnidbgPointer.pointer(emulator, address);
if (log.isDebugEnabled()) {
log.debug("[" + libName + "]CallInitFunction: " + pointer);
}
long start = System.currentTimeMillis();
emulator.eFunc(address);
if (AbsoluteInitFunction.log.isDebugEnabled()) {
System.err.println("[" + libName + "]CallInitFunction: " + pointer + ", offset=" + (System.currentTimeMillis() - start) + "ms");
}
return address;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/LinuxInitFunction.java | LinuxInitFunction | call | class LinuxInitFunction extends InitFunction {
private static final Log log = LogFactory.getLog(LinuxInitFunction.class);
LinuxInitFunction(long load_base, String soName, long address) {
super(load_base, soName, address);
}
@Override
public long getAddress() {
return load_base + address;
}
@Override
public long call(Emulator<?> emulator) {<FILL_FUNCTION_BODY>}
} |
if (address == 0 || address == -1) {
return address;
}
if (log.isDebugEnabled()) {
log.debug("[" + libName + "]CallInitFunction: 0x" + Long.toHexString(address));
}
long start = System.currentTimeMillis();
emulator.eFunc(getAddress());
if (log.isDebugEnabled()) {
System.err.println("[" + libName + "]CallInitFunction: 0x" + Long.toHexString(address) + ", offset=" + (System.currentTimeMillis() - start) + "ms");
}
return address;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/ModuleSymbol.java | ModuleSymbol | resolve | class ModuleSymbol {
static final long WEAK_BASE = -1;
final String soName;
private final long load_base;
final ElfSymbol symbol;
final Pointer relocationAddr;
final String toSoName;
final long offset;
ModuleSymbol(String soName, long load_base, ElfSymbol symbol, Pointer relocationAddr, String toSoName, long offset) {
this.soName = soName;
this.load_base = load_base;
this.symbol = symbol;
this.relocationAddr = relocationAddr;
this.toSoName = toSoName;
this.offset = offset;
}
ModuleSymbol resolve(Collection<Module> modules, boolean resolveWeak, List<HookListener> listeners, SvcMemory svcMemory) throws IOException {<FILL_FUNCTION_BODY>}
void relocation(Emulator<?> emulator, LinuxModule module, ElfSymbol symbol) {
final long value;
if (load_base == WEAK_BASE) {
value = offset;
} else {
value = module.base + (symbol == null ? 0 : symbol.value) + offset;
}
relocationAddr.setPointer(0, UnidbgPointer.pointer(emulator, value));
}
void relocation(Emulator<?> emulator, LinuxModule owner) throws IOException {
if (symbol != null) {
owner.resolvedSymbols.put(symbol.getName(), this);
}
final long value;
if (load_base == WEAK_BASE) {
value = offset;
} else {
value = load_base + (symbol == null ? 0 : symbol.value) + offset;
}
relocationAddr.setPointer(0, UnidbgPointer.pointer(emulator, value));
}
public ElfSymbol getSymbol() {
return symbol;
}
Pointer getRelocationAddr() {
return relocationAddr;
}
} |
final String symbolName = symbol.getName();
for (Module m : modules) {
LinuxModule module = (LinuxModule) m;
Long symbolHook = module.hookMap.get(symbolName);
if (symbolHook != null) {
return new ModuleSymbol(soName, WEAK_BASE, symbol, relocationAddr, module.name, symbolHook);
}
ElfSymbol elfSymbol = module.getELFSymbolByName(symbolName);
if (elfSymbol != null && !elfSymbol.isUndef()) {
switch (elfSymbol.getBinding()) {
case ElfSymbol.BINDING_GLOBAL:
case ElfSymbol.BINDING_WEAK:
for (HookListener listener : listeners) {
long hook = listener.hook(svcMemory, module.name, symbolName, module.base + elfSymbol.value + offset);
if (hook > 0) {
module.hookMap.put(symbolName, hook);
return new ModuleSymbol(soName, WEAK_BASE, elfSymbol, relocationAddr, module.name, hook);
}
}
return new ModuleSymbol(soName, module.base, elfSymbol, relocationAddr, module.name, offset);
}
}
}
if (resolveWeak && symbol.getBinding() == ElfSymbol.BINDING_WEAK) {
return new ModuleSymbol(soName, WEAK_BASE, symbol, relocationAddr, "0", 0);
}
if ("dlopen".equals(symbolName) ||
"dlclose".equals(symbolName) ||
"dlsym".equals(symbolName) ||
"dlerror".equals(symbolName) ||
"dladdr".equals(symbolName) ||
"android_update_LD_LIBRARY_PATH".equals(symbolName) ||
"android_get_LD_LIBRARY_PATH".equals(symbolName) ||
"dl_iterate_phdr".equals(symbolName) ||
"android_dlopen_ext".equals(symbolName) ||
"android_set_application_target_sdk_version".equals(symbolName) ||
"android_get_application_target_sdk_version".equals(symbolName) ||
"android_init_namespaces".equals(symbolName) ||
"android_create_namespace".equals(symbolName) ||
"dlvsym".equals(symbolName) ||
"android_dlwarning".equals(symbolName) ||
"dl_unwind_find_exidx".equals(symbolName)) {
if (resolveWeak) {
for (HookListener listener : listeners) {
long hook = listener.hook(svcMemory, "libdl.so", symbolName, offset);
if (hook > 0) {
return new ModuleSymbol(soName, WEAK_BASE, symbol, relocationAddr, "libdl.so", hook);
}
}
}
}
return null;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/AndroidARM64Emulator.java | AndroidARM64Emulator | createDalvikVM | class AndroidARM64Emulator extends AbstractARM64Emulator<AndroidFileIO> implements AndroidEmulator {
protected AndroidARM64Emulator(String processName, File rootDir, Collection<BackendFactory> backendFactories) {
super(processName, rootDir, Family.Android64, backendFactories);
}
@Override
protected FileSystem<AndroidFileIO> createFileSystem(File rootDir) {
return new LinuxFileSystem(this, rootDir);
}
@Override
protected Memory createMemory(UnixSyscallHandler<AndroidFileIO> syscallHandler, String[] envs) {
return new AndroidElfLoader(this, syscallHandler);
}
@Override
protected Dlfcn createDyld(SvcMemory svcMemory) {
return new ArmLD64(backend, svcMemory);
}
@Override
protected UnixSyscallHandler<AndroidFileIO> createSyscallHandler(SvcMemory svcMemory) {
return new ARM64SyscallHandler(svcMemory);
}
private VM createDalvikVMInternal(File apkFile) {
return new DalvikVM64(this, apkFile);
}
@Override
public LibraryFile createURLibraryFile(URL url, String libName) {
return new URLibraryFile(url, libName, -1, true);
}
@Override
protected boolean isPaddingArgument() {
return false;
}
private VM vm;
@Override
public VM createDalvikVM() {
return createDalvikVM((File) null);
}
@Override
public final VM createDalvikVM(File apkFile) {<FILL_FUNCTION_BODY>}
@Override
public VM createDalvikVM(Class<?> callingClass) {
return createDalvikVM(new File(callingClass.getProtectionDomain().getCodeSource().getLocation().getPath()));
}
@Override
public final VM getDalvikVM() {
return vm;
}
@Override
public Unwinder getUnwinder() {
return new AndroidARM64Unwinder(this);
}
} |
if (vm != null) {
throw new IllegalStateException("vm is already created");
}
vm = createDalvikVMInternal(apkFile);
return vm;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/AndroidARM64Unwinder.java | AndroidARM64Unwinder | unw_step | class AndroidARM64Unwinder extends SimpleARM64Unwinder {
private static final Log log = LogFactory.getLog(AndroidARM64Unwinder.class);
private final DwarfCursor context;
public AndroidARM64Unwinder(Emulator<?> emulator) {
super(emulator);
this.context = new DwarfCursor64(emulator);
}
@Override
protected Frame unw_step(Emulator<?> emulator, Frame frame) {<FILL_FUNCTION_BODY>}
} |
try {
LinuxModule module = (LinuxModule) emulator.getMemory().findModuleByAddress(this.context.ip);
MemoizedObject<GnuEhFrameHeader> ehFrameHeader = module == null ? null : module.ehFrameHeader;
if (ehFrameHeader != null) {
long fun = this.context.ip - module.base;
GnuEhFrameHeader frameHeader = ehFrameHeader.getValue();
Frame ret = frameHeader == null ? null : frameHeader.dwarf_step(emulator, this, module, fun, context);
if (ret != null) {
return ret;
}
}
} catch (RuntimeException exception) {
log.warn("unw_step", exception);
} catch (IOException e) {
throw new IllegalStateException(e);
}
return super.unw_step(emulator, frame);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/AndroidARMEmulator.java | AndroidARMEmulator | createDalvikVM | class AndroidARMEmulator extends AbstractARMEmulator<AndroidFileIO> implements AndroidEmulator {
protected AndroidARMEmulator(String processName, File rootDir, Collection<BackendFactory> backendFactories) {
super(processName, rootDir, Family.Android32, backendFactories);
}
@Override
protected FileSystem<AndroidFileIO> createFileSystem(File rootDir) {
return new LinuxFileSystem(this, rootDir);
}
@Override
protected Memory createMemory(UnixSyscallHandler<AndroidFileIO> syscallHandler, String[] envs) {
return new AndroidElfLoader(this, syscallHandler);
}
@Override
protected Dlfcn createDyld(SvcMemory svcMemory) {
return new ArmLD(backend, svcMemory);
}
@Override
protected UnixSyscallHandler<AndroidFileIO> createSyscallHandler(SvcMemory svcMemory) {
return new ARM32SyscallHandler(svcMemory);
}
private VM createDalvikVMInternal(File apkFile) {
return new DalvikVM(this, apkFile);
}
/**
* https://github.com/lunixbochs/usercorn/blob/master/go/arch/arm/linux.go
*/
@Override
protected final void setupTraps() {
super.setupTraps();
int __kuser_memory_barrier = 0xe12fff1e; // bx lr
memory.pointer(0xffff0fa0L).setInt(0, __kuser_memory_barrier);
ByteBuffer buffer = ByteBuffer.allocate(32);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(0xf57ff05f); // dmb sy
buffer.putInt(0xe1923f9f); // ldrex r3, [r2]
buffer.putInt(0xe0533000); // subs r3, r3, r0
buffer.putInt(0x01823f91); // strexeq r3, r1, [r2]
buffer.putInt(0x03330001); // teqeq r3, #1
buffer.putInt(0x0afffffa); // beq #0xffff0fc4
buffer.putInt(0xe2730000); // rsbs r0, r3, #0
buffer.putInt(0xeaffffef); // b #0xffff0fa0
byte[] __kuser_cmpxchg = buffer.array();
memory.pointer(0xffff0fc0L).write(__kuser_cmpxchg);
}
@Override
public LibraryFile createURLibraryFile(URL url, String libName) {
return new URLibraryFile(url, libName, -1, false);
}
@Override
protected boolean isPaddingArgument() {
return true;
}
private VM vm;
@Override
public VM createDalvikVM() {
return createDalvikVM((File) null);
}
@Override
public final VM createDalvikVM(File apkFile) {<FILL_FUNCTION_BODY>}
@Override
public VM createDalvikVM(Class<?> callingClass) {
return createDalvikVM(new File(callingClass.getProtectionDomain().getCodeSource().getLocation().getPath()));
}
@Override
public final VM getDalvikVM() {
return vm;
}
@Override
public Unwinder getUnwinder() {
return new AndroidARMUnwinder(this);
}
} |
if (vm != null) {
throw new IllegalStateException("vm is already created");
}
vm = createDalvikVMInternal(apkFile);
return vm;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/AndroidARMUnwinder.java | AndroidARMUnwinder | unw_step | class AndroidARMUnwinder extends SimpleARMUnwinder {
private static final Log log = LogFactory.getLog(AndroidARMUnwinder.class);
private final DwarfCursor context;
public AndroidARMUnwinder(Emulator<?> emulator) {
super(emulator);
this.context = new DwarfCursor32(emulator);
}
@Override
protected Frame unw_step(Emulator<?> emulator, Frame frame) {<FILL_FUNCTION_BODY>}
} |
try {
LinuxModule module = (LinuxModule) emulator.getMemory().findModuleByAddress(this.context.ip);
MemoizedObject<GnuEhFrameHeader> ehFrameHeader = module == null ? null : module.ehFrameHeader;
if (ehFrameHeader != null) {
long fun = this.context.ip - module.base;
GnuEhFrameHeader frameHeader = ehFrameHeader.getValue();
Frame ret = frameHeader == null ? null : frameHeader.dwarf_step(emulator, this, module, fun, context);
if (ret != null) {
return ret;
}
}
MemoizedObject<ArmExIdx> armExIdx = module == null ? null : module.armExIdx;
if (armExIdx != null) {
long fun = this.context.ip - module.base;
return armExIdx.getValue().arm_exidx_step(emulator, this, module, fun, context);
}
} catch (RuntimeException exception) {
log.warn("unw_step", exception);
} catch (IOException e) {
throw new IllegalStateException(e);
}
return super.unw_step(emulator, frame);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/AndroidEmulatorBuilder.java | AndroidEmulatorBuilder | build | class AndroidEmulatorBuilder extends EmulatorBuilder<AndroidEmulator> {
public static AndroidEmulatorBuilder for32Bit() {
return new AndroidEmulatorBuilder(false);
}
public static AndroidEmulatorBuilder for64Bit() {
return new AndroidEmulatorBuilder(true);
}
protected AndroidEmulatorBuilder(boolean is64Bit) {
super(is64Bit);
}
@Override
public AndroidEmulator build() {<FILL_FUNCTION_BODY>}
} |
return is64Bit ? new AndroidARM64Emulator(processName, rootDir, backendFactories) : new AndroidARMEmulator(processName, rootDir, backendFactories);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/AndroidResolver.java | AndroidResolver | resolve | class AndroidResolver implements LibraryResolver, IOResolver<AndroidFileIO> {
private final int sdk;
private final List<String> needed;
public AndroidResolver(int sdk, String... needed) {
this.sdk = sdk;
this.needed = needed == null ? null : Arrays.asList(needed);
}
public void patchThread(Emulator<?> emulator, InlineHook inlineHook, ThreadJoinVisitor visitor) {
switch (sdk) {
case 19:
ThreadJoin19.patch(emulator, inlineHook, visitor);
break;
case 23:
ThreadJoin23.patch(emulator, inlineHook, visitor);
break;
default:
throw new UnsupportedOperationException();
}
}
public int getSdk() {
return sdk;
}
@Override
public LibraryFile resolveLibrary(Emulator<?> emulator, String libraryName) {
if (needed == null) {
return null;
}
if (!needed.isEmpty() && !needed.contains(libraryName)) {
return null;
}
return resolveLibrary(emulator, libraryName, sdk, getClass());
}
static LibraryFile resolveLibrary(Emulator<?> emulator, String libraryName, int sdk) {
return resolveLibrary(emulator, libraryName, sdk, AndroidResolver.class);
}
protected static LibraryFile resolveLibrary(Emulator<?> emulator, String libraryName, int sdk, Class<?> resClass) {
final String lib = emulator.is32Bit() ? "lib" : "lib64";
String name = "/android/sdk" + sdk + "/" + lib + "/" + libraryName.replace('+', 'p');
URL url = resClass.getResource(name);
if (url != null) {
return new URLibraryFile(url, libraryName, sdk, emulator.is64Bit());
}
return null;
}
@Override
public FileResult<AndroidFileIO> resolve(Emulator<AndroidFileIO> emulator, String path, int oflags) {<FILL_FUNCTION_BODY>}
private AndroidFileIO createFileIO(URL url, String pathname, int oflags) {
File file = ResourceUtils.toFile(url);
if (file != null) {
return createFileIO(file, pathname, oflags);
}
try {
URLConnection connection = url.openConnection();
try (InputStream inputStream = connection.getInputStream()) {
if (connection instanceof JarURLConnection) {
JarURLConnection jarURLConnection = (JarURLConnection) connection;
JarFile jarFile = jarURLConnection.getJarFile();
JarEntry entry = jarURLConnection.getJarEntry();
if (entry.isDirectory()) {
Enumeration<JarEntry> entryEnumeration = jarFile.entries();
List<DirectoryFileIO.DirectoryEntry> list = new ArrayList<>();
while (entryEnumeration.hasMoreElements()) {
JarEntry check = entryEnumeration.nextElement();
if (entry.getName().equals(check.getName())) {
continue;
}
if (check.getName().startsWith(entry.getName())) {
boolean isDir = check.isDirectory();
String sub = check.getName().substring(entry.getName().length());
if (isDir) {
sub = sub.substring(0, sub.length() - 1);
}
if (!sub.contains("/")) {
list.add(new DirectoryFileIO.DirectoryEntry(true, sub));
}
}
}
return new DirectoryFileIO(oflags, pathname, list.toArray(new DirectoryFileIO.DirectoryEntry[0]));
} else {
byte[] data = IOUtils.toByteArray(inputStream);
return new ByteArrayFileIO(oflags, pathname, data);
}
} else {
throw new IllegalStateException(connection.getClass().getName());
}
}
} catch (Exception e) {
throw new IllegalStateException(pathname, e);
}
}
private AndroidFileIO createFileIO(File file, String pathname, int oflags) {
if (file.canRead()) {
return file.isDirectory() ? new DirectoryFileIO(oflags, pathname) : new SimpleFileIO(oflags, file, pathname);
}
return null;
}
@Override
public void onSetToLoader(Emulator<?> emulator) {
AndroidEmulator androidEmulator = (AndroidEmulator) emulator;
SyscallHandler<AndroidFileIO> syscallHandler = androidEmulator.getSyscallHandler();
syscallHandler.addIOResolver(this);
}
} |
FileSystem<AndroidFileIO> fileSystem = emulator.getFileSystem();
File rootDir = fileSystem.getRootDir();
if (path.startsWith(LogCatFileIO.LOG_PATH_PREFIX)) {
try {
File log = new File(rootDir, path);
File logDir = log.getParentFile();
if (!logDir.exists() && !logDir.mkdirs()) {
throw new IOException("mkdirs failed: " + logDir);
}
if (!log.exists() && !log.createNewFile()) {
throw new IOException("create new file failed: " + log);
}
return FileResult.<AndroidFileIO>success(new LogCatFileIO(emulator, oflags, log, path));
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
if (".".equals(path)) {
return FileResult.success(createFileIO(fileSystem.createWorkDir(), path, oflags));
}
String androidResource = FilenameUtils.normalize("/android/sdk" + sdk + "/" + path, true);
URL url = getClass().getResource(androidResource);
if (url != null) {
return FileResult.fallback(createFileIO(url, path, oflags));
}
return null;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/ElfLibraryFile.java | ElfLibraryFile | resolveLibrary | class ElfLibraryFile implements LibraryFile {
private final File elfFile;
private final boolean is64Bit;
public ElfLibraryFile(File elfFile, boolean is64Bit) {
this.elfFile = elfFile;
this.is64Bit = is64Bit;
}
@Override
public long getFileSize() {
return elfFile.length();
}
@Override
public String getName() {
return elfFile.getName();
}
@Override
public String getMapRegionName() {
return getPath();
}
@Override
public LibraryFile resolveLibrary(Emulator<?> emulator, String soName) {<FILL_FUNCTION_BODY>}
@Override
public ByteBuffer mapBuffer() throws IOException {
return Utils.mapBuffer(elfFile);
}
@Override
public String getPath() {
String name = getName();
if (name.endsWith(".so")) {
return "/system/" + (is64Bit ? "lib64/" : "lib/") + name;
} else {
return "/system/bin/" + name;
}
}
} |
File file = new File(elfFile.getParentFile(), soName);
return file.canRead() ? new ElfLibraryFile(file, is64Bit) : null;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/SystemPropertyHook.java | SystemPropertyHook | hook | class SystemPropertyHook implements HookListener {
private static final Logger log = LoggerFactory.getLogger(SystemPropertyHook.class);
public static final int PROP_VALUE_MAX = 92;
private final Emulator<?> emulator;
public SystemPropertyHook(Emulator<?> emulator) {
this.emulator = emulator;
}
@Override
public long hook(SvcMemory svcMemory, String libraryName, String symbolName, final long old) {<FILL_FUNCTION_BODY>}
private HookStatus __system_property_get(long old, String key, int index) {
RegisterContext context = emulator.getContext();
if (propertyProvider != null) {
String value = propertyProvider.getProperty(key);
if (value != null) {
log.debug("__system_property_get key={}, value={}", key, value);
byte[] data = value.getBytes(StandardCharsets.UTF_8);
if (data.length >= PROP_VALUE_MAX) {
throw new BackendException("invalid property value length: key=" + key + ", value=" + value);
}
byte[] newData = Arrays.copyOf(data, data.length + 1);
Pointer pointer = context.getPointerArg(index + 1);
pointer.write(0, newData, 0, newData.length);
return HookStatus.LR(emulator, data.length);
}
}
log.debug("__system_property_get key={}", key);
return HookStatus.RET(emulator, old);
}
private SystemPropertyProvider propertyProvider;
public void setPropertyProvider(SystemPropertyProvider propertyProvider) {
this.propertyProvider = propertyProvider;
}
} |
if ("libc.so".equals(libraryName)) {
if ("__system_property_get".equals(symbolName)) {
log.debug("Hook {}", symbolName);
if (emulator.is64Bit()) {
return svcMemory.registerSvc(new Arm64Hook() {
@Override
protected HookStatus hook(Emulator<?> emulator) {
RegisterContext context = emulator.getContext();
int index = 0;
Pointer pointer = context.getPointerArg(index);
String key = pointer.getString(0);
return __system_property_get(old, key, index);
}
}).peer;
} else {
return svcMemory.registerSvc(new ArmHook() {
@Override
protected HookStatus hook(Emulator<?> emulator) {
RegisterContext context = emulator.getContext();
int index = 0;
Pointer pointer = context.getPointerArg(index);
String key = pointer.getString(0);
return __system_property_get(old, key, index);
}
}).peer;
}
}
if ("__system_property_read".equals(symbolName)) {
log.debug("Hook {}", symbolName);
if (emulator.is64Bit()) {
return svcMemory.registerSvc(new Arm64Hook() {
@Override
protected HookStatus hook(Emulator<?> emulator) {
RegisterContext context = emulator.getContext();
Pointer pi = context.getPointerArg(0);
String key = pi.share(PROP_VALUE_MAX + 4).getString(0);
return __system_property_get(old, key, 1);
}
}).peer;
} else {
return svcMemory.registerSvc(new ArmHook() {
@Override
protected HookStatus hook(Emulator<?> emulator) {
RegisterContext context = emulator.getContext();
Pointer pi = context.getPointerArg(0);
String key = pi.share(PROP_VALUE_MAX + 4).getString(0);
return __system_property_get(old, key, 1);
}
}).peer;
}
}
if ("__system_property_find".equals(symbolName)) {
log.debug("Hook {}", symbolName);
if (emulator.is64Bit()) {
return svcMemory.registerSvc(new Arm64Hook(true) {
private String name;
@Override
protected HookStatus hook(Emulator<?> emulator) {
RegisterContext context = emulator.getContext();
Pointer name = context.getPointerArg(0);
this.name = name.getString(0);
if (log.isDebugEnabled()) {
log.debug("__system_property_find key={}, LR={}", this.name, context.getLRPointer());
}
if (log.isTraceEnabled()) {
emulator.attach().debug();
}
return HookStatus.RET(emulator, old);
}
@Override
public void handlePostCallback(Emulator<?> emulator) {
super.handlePostCallback(emulator);
EditableArm64RegisterContext context = emulator.getContext();
Pointer pi = context.getPointerArg(0);
if (log.isDebugEnabled()) {
log.debug("__system_property_find key={}, pi={}, value={}", this.name, pi, pi == null ? null : pi.share(4).getString(0));
}
if (propertyProvider != null) {
Pointer replace = propertyProvider.__system_property_find(this.name);
if (replace != null) {
context.setXLong(0, UnidbgPointer.nativeValue(replace));
}
}
}
}).peer;
} else {
return svcMemory.registerSvc(new ArmHook() {
@Override
protected HookStatus hook(Emulator<?> emulator) {
RegisterContext context = emulator.getContext();
Pointer name = context.getPointerArg(0);
if (log.isDebugEnabled()) {
log.debug("__system_property_find key={}, LR={}", name.getString(0), context.getLRPointer());
}
if (log.isTraceEnabled()) {
emulator.attach().debug();
}
return HookStatus.RET(emulator, old);
}
}).peer;
}
}
}
return 0;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/URLibraryFile.java | URLibraryFile | getFileSize | class URLibraryFile implements LibraryFile {
private final URL url;
private final String name;
private final int sdk;
private final boolean is64Bit;
public URLibraryFile(URL url, String name, int sdk, boolean is64Bit) {
this.url = url;
this.name = name;
this.sdk = sdk;
this.is64Bit = is64Bit;
}
@Override
public String getName() {
return name;
}
@Override
public String getMapRegionName() {
return getPath();
}
@Override
public LibraryFile resolveLibrary(Emulator<?> emulator, String soName) {
if (sdk <= 0) {
return null;
}
return AndroidResolver.resolveLibrary(emulator, soName, sdk);
}
@Override
public ByteBuffer mapBuffer() throws IOException {
if ("file".equalsIgnoreCase(url.getProtocol())) {
return Utils.mapBuffer(new File(url.getPath()));
} else {
return ByteBuffer.wrap(IOUtils.toByteArray(url));
}
}
@Override
public long getFileSize() {<FILL_FUNCTION_BODY>}
@Override
public String getPath() {
return "/system/" + (is64Bit ? "lib64/" : "lib/") + name;
}
} |
if ("file".equalsIgnoreCase(url.getProtocol())) {
return new File(url.getPath()).length();
} else {
try {
return IOUtils.toByteArray(url).length;
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/XHookImpl.java | XHookImpl | refresh | class XHookImpl extends BaseHook implements IxHook {
private static final Log log = LogFactory.getLog(XHookImpl.class);
public static IxHook getInstance(Emulator<?> emulator) {
IxHook ixHook = emulator.get(XHookImpl.class.getName());
if (ixHook == null) {
ixHook = new XHookImpl(emulator);
emulator.set(XHookImpl.class.getName(), ixHook);
}
return ixHook;
}
private final Symbol xhook_register;
private final Symbol xhook_refresh;
private XHookImpl(Emulator<?> emulator) {
super(emulator, "libxhook");
xhook_register = module.findSymbolByName("xhook_register", false);
xhook_refresh = module.findSymbolByName("xhook_refresh", false);
if (log.isDebugEnabled()) {
log.debug("xhook_register=" + xhook_register + ", xhook_refresh=" + xhook_refresh);
}
if (xhook_register == null) {
throw new IllegalStateException("xhook_register is null");
}
if (xhook_refresh == null) {
throw new IllegalStateException("xhook_refresh is null");
}
Symbol xhook_enable_sigsegv_protection = module.findSymbolByName("xhook_enable_sigsegv_protection", false);
if (xhook_enable_sigsegv_protection == null) {
throw new IllegalStateException("xhook_enable_sigsegv_protection is null");
} else {
xhook_enable_sigsegv_protection.call(emulator, 0);
}
Symbol xhook_enable_debug = module.findSymbolByName("xhook_enable_debug", false);
if (xhook_enable_debug == null) {
throw new IllegalStateException("xhook_enable_debug is null");
} else {
xhook_enable_debug.call(emulator, log.isDebugEnabled() ? 1 : 0);
}
}
@Override
public void register(String pathname_regex_str, String symbol, final ReplaceCallback callback) {
register(pathname_regex_str, symbol, callback, false);
}
@Override
public void register(String pathname_regex_str, String symbol, ReplaceCallback callback, boolean enablePostCall) {
final Pointer old_func = emulator.getMemory().malloc(emulator.getPointerSize(), false).getPointer();
Pointer new_func = createReplacePointer(callback, old_func, enablePostCall);
int ret = xhook_register.call(emulator, pathname_regex_str, symbol, new_func, old_func).intValue();
if (ret != RET_SUCCESS) {
throw new IllegalStateException("ret=" + ret);
}
}
@Override
public void refresh() {<FILL_FUNCTION_BODY>}
} |
int ret = xhook_refresh.call(emulator, 0).intValue();
if (ret != RET_SUCCESS) {
throw new IllegalStateException("ret=" + ret);
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/ApkLibraryFile.java | ApkLibraryFile | resolveLibrary | class ApkLibraryFile implements LibraryFile {
private final BaseVM baseVM;
private final Apk apk;
private final String soName;
private final byte[] soData;
private final String packageName;
private final String appDir;
private final boolean is64Bit;
ApkLibraryFile(BaseVM baseVM, Apk apk, String soName, byte[] soData, String packageName, boolean is64Bit) {
this.baseVM = baseVM;
this.apk = apk;
this.soName = soName;
this.soData = soData;
this.packageName = packageName;
this.appDir = packageName == null ? "" : ('/' + packageName + "-1");
this.is64Bit = is64Bit;
}
@Override
public long getFileSize() {
return soData.length;
}
@Override
public String getName() {
return soName;
}
@Override
public String getMapRegionName() {
return getPath();
}
@Override
public LibraryFile resolveLibrary(Emulator<?> emulator, String soName) {<FILL_FUNCTION_BODY>}
@Override
public ByteBuffer mapBuffer() {
return ByteBuffer.wrap(soData);
}
@Override
public String getPath() {
return "/data/app" + appDir + "/lib/" + (is64Bit ? "arm64/" : "arm/") + soName;
}
} |
byte[] libData = baseVM.loadLibraryData(apk, soName);
return libData == null ? null : new ApkLibraryFile(baseVM, this.apk, soName, libData, packageName, is64Bit);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/ArmVarArg64.java | ArmVarArg64 | getVectorArg | class ArmVarArg64 extends ArmVarArg {
ArmVarArg64(Emulator<?> emulator, BaseVM vm, DvmMethod method) {
super(emulator, vm, method);
int offset = 0;
int floatOff = 0;
for (Shorty shorty : shorties) {
switch (shorty.getType()) {
case 'L':
case 'B':
case 'C':
case 'I':
case 'S':
case 'Z': {
args.add(getInt(offset++));
break;
}
case 'D': {
args.add(getVectorArg(floatOff++));
break;
}
case 'F': {
args.add((float) getVectorArg(floatOff++));
break;
}
case 'J': {
UnidbgPointer ptr = getArg(offset++);
args.add(ptr == null ? 0L : ptr.peer);
break;
}
default:
throw new IllegalStateException("c=" + shorty.getType());
}
}
}
private double getVectorArg(int index) {<FILL_FUNCTION_BODY>}
} |
ByteBuffer buffer = ByteBuffer.allocate(16);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.put(emulator.getBackend().reg_read_vector(Arm64Const.UC_ARM64_REG_Q0 + index));
buffer.flip();
return buffer.getDouble();
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/ArrayListObject.java | ArrayListObject | newStringList | class ArrayListObject extends DvmObject<List<? extends DvmObject<?>>> {
@SuppressWarnings("unused")
public static ArrayListObject newStringList(VM vm, String... strings) {<FILL_FUNCTION_BODY>}
public ArrayListObject(VM vm, List<? extends DvmObject<?>> value) {
super(vm.resolveClass("java/util/ArrayList", vm.resolveClass("java/util/List")), value);
}
public int size() {
return value.size();
}
public boolean isEmpty() {
return value.isEmpty();
}
} |
List<StringObject> list = new ArrayList<>();
for (String str : strings) {
if (str != null) {
list.add(new StringObject(vm, str));
}
}
return new ArrayListObject(vm, list);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/BaseVM.java | BaseVM | addObject | class BaseVM implements VM, DvmClassFactory {
private static final Log log = LogFactory.getLog(BaseVM.class);
public static boolean valueOf(int value) {
if (value == VM.JNI_TRUE) {
return true;
} else if (value == VM.JNI_FALSE) {
return false;
} else {
throw new IllegalStateException("Invalid boolean value=" + value);
}
}
final Map<Integer, DvmClass> classMap = new HashMap<>();
Jni jni;
DvmObject<?> throwable;
boolean verbose, verboseMethodOperation, verboseFieldOperation;
@Override
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
@Override
public void setVerboseMethodOperation(boolean verboseMethodOperation) {
this.verboseMethodOperation = verboseMethodOperation;
}
@Override
public void setVerboseFieldOperation(boolean verboseFieldOperation) {
this.verboseFieldOperation = verboseFieldOperation;
}
@Override
public void throwException(DvmObject<?> throwable) {
this.throwable = throwable;
}
@Override
public final void setJni(Jni jni) {
this.jni = jni;
}
private final AndroidEmulator emulator;
private final Apk apk;
final Set<String> notFoundClassSet = new HashSet<>();
@Override
public void addNotFoundClass(String className) {
notFoundClassSet.add(className);
}
BaseVM(AndroidEmulator emulator, File apkFile) {
this.emulator = emulator;
this.apk = apkFile == null ? null : ApkFactory.createApk(apkFile);
}
final static class ObjRef {
final DvmObject<?> obj;
final boolean weak;
ObjRef(DvmObject<?> obj, boolean weak) {
this.obj = obj;
this.weak = weak;
this.refCount = 1;
}
int refCount;
@Override
public String toString() {
return String.valueOf(obj);
}
}
final Map<Integer, ObjRef> globalObjectMap = new HashMap<>();
final Map<Integer, ObjRef> weakGlobalObjectMap = new HashMap<>();
final Map<Integer, ObjRef> localObjectMap = new HashMap<>();
private DvmClassFactory dvmClassFactory;
@Override
public void setDvmClassFactory(DvmClassFactory factory) {
this.dvmClassFactory = factory;
}
@Override
public final DvmClass resolveClass(String className, DvmClass... interfaceClasses) {
className = className.replace('.', '/');
int hash = Objects.hash(className);
DvmClass dvmClass = classMap.get(hash);
DvmClass superClass = null;
if (interfaceClasses != null && interfaceClasses.length > 0) {
superClass = interfaceClasses[0];
interfaceClasses = Arrays.copyOfRange(interfaceClasses, 1, interfaceClasses.length);
}
if (dvmClass == null) {
if (dvmClassFactory != null) {
dvmClass = dvmClassFactory.createClass(this, className, superClass, interfaceClasses);
}
if (dvmClass == null) {
dvmClass = this.createClass(this, className, superClass, interfaceClasses);
}
classMap.put(hash, dvmClass);
}
addGlobalObject(dvmClass);
return dvmClass;
}
@Override
public DvmClass createClass(BaseVM vm, String className, DvmClass superClass, DvmClass[] interfaceClasses) {
return new DvmClass(vm, className, superClass, interfaceClasses);
}
final int addObject(DvmObject<?> object, boolean global, boolean weak) {<FILL_FUNCTION_BODY>}
@Override
public final int addLocalObject(DvmObject<?> object) {
if (object == null) {
return JNI_NULL;
}
return addObject(object, false, false);
}
@Override
public final int addGlobalObject(DvmObject<?> object) {
if (object == null) {
return JNI_NULL;
}
return addObject(object, true, false);
}
@SuppressWarnings("unchecked")
@Override
public final <T extends DvmObject<?>> T getObject(int hash) {
ObjRef ref;
if (localObjectMap.containsKey(hash)) {
ref = localObjectMap.get(hash);
} else if(globalObjectMap.containsKey(hash)) {
ref = globalObjectMap.get(hash);
} else {
ref = weakGlobalObjectMap.get(hash);
}
return ref == null ? null : (T) ref.obj;
}
@Override
public final DvmClass findClass(String className) {
return classMap.get(Objects.hash(className));
}
final void deleteLocalRefs() {
for (ObjRef ref : localObjectMap.values()) {
ref.obj.onDeleteRef();
}
localObjectMap.clear();
if (throwable != null) {
throwable.onDeleteRef();
throwable = null;
}
}
final void checkVersion(int version) {
if (version != JNI_VERSION_1_1 &&
version != JNI_VERSION_1_2 &&
version != JNI_VERSION_1_4 &&
version != JNI_VERSION_1_6 &&
version != JNI_VERSION_1_8) {
if (log.isTraceEnabled()) {
emulator.attach().debug();
}
throw new IllegalStateException("Illegal JNI version: 0x" + Integer.toHexString(version));
}
}
abstract byte[] loadLibraryData(Apk apk, String soName);
@Override
public LibraryFile findLibrary(String soName) {
if (apk == null) {
throw new UnsupportedOperationException();
}
ApkLibraryFile libraryFile = findLibrary(apk, soName);
if (libraryFile == null) {
File split = new File(apk.getParentFile(), emulator.is64Bit() ? "config.arm64_v8a.apk" : "config.armeabi_v7a.apk");
if (split.canRead()) {
libraryFile = findLibrary(ApkFactory.createApk(split), soName);
}
}
return libraryFile;
}
@Override
public final DalvikModule loadLibrary(String libname, boolean forceCallInit) {
String soName = "lib" + libname + ".so";
LibraryFile libraryFile = findLibrary(soName);
if (libraryFile == null) {
throw new IllegalStateException("load library failed: " + libname);
}
Module module = emulator.getMemory().load(libraryFile, forceCallInit);
return new DalvikModule(this, module);
}
@Override
public final DalvikModule loadLibrary(String libname, byte[] raw, boolean forceCallInit) {
if (raw == null || raw.length == 0) {
throw new IllegalArgumentException();
}
Module module = emulator.getMemory().load(new ElfLibraryRawFile(libname, raw, emulator.is64Bit()), forceCallInit);
return new DalvikModule(this, module);
}
private ApkLibraryFile findLibrary(Apk apk, String soName) {
byte[] libData = loadLibraryData(apk, soName);
if (libData == null) {
return null;
}
return new ApkLibraryFile(this, apk, soName, libData, apk.getPackageName(), emulator.is64Bit());
}
@Override
public CertificateMeta[] getSignatures() {
return apk == null ? null : apk.getSignatures();
}
@Override
public String getPackageName() {
return apk == null ? null : apk.getPackageName();
}
@Override
public String getManifestXml() {
return apk == null ? null : apk.getManifestXml();
}
@Override
public byte[] openAsset(String fileName) {
if (assetResolver != null) {
byte[] bytes = assetResolver.resolveAsset(fileName);
if (bytes != null) {
return bytes;
}
}
return apk == null ? null : apk.openAsset(fileName);
}
@Override
public byte[] unzip(String path) {
if (path.length() > 1 && path.charAt(0) == '/') {
path = path.substring(1);
}
return apk == null ? null : apk.getFileData(path);
}
private AssetResolver assetResolver;
@Override
public void setAssetResolver(AssetResolver assetResolver) {
this.assetResolver = assetResolver;
}
@Override
public final String getVersionName() {
return apk == null ? null : apk.getVersionName();
}
@Override
public long getVersionCode() {
return apk == null ? 0 : apk.getVersionCode();
}
@Override
public final DalvikModule loadLibrary(File elfFile, boolean forceCallInit) {
Module module = emulator.getMemory().load(new ElfLibraryFile(elfFile, emulator.is64Bit()), forceCallInit);
return new DalvikModule(this, module);
}
@Override
public final void printMemoryInfo() {
System.gc();
MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
MemoryUsage heap = memoryMXBean.getHeapMemoryUsage();
MemoryUsage nonHeap = memoryMXBean.getNonHeapMemoryUsage();
Map<Integer, ObjRef> map = new HashMap<>(globalObjectMap);
for (Integer key : classMap.keySet()) {
map.remove(key);
}
System.err.println("globalObjectSize=" + globalObjectMap.size() + ", localObjectSize=" + localObjectMap.size() + ", weakGlobalObjectSize=" + weakGlobalObjectMap.size() + ", classSize=" + classMap.size() + ", globalObjectSize=" + map.size());
System.err.println("heap: " + memoryUsage(heap) + ", nonHeap: " + memoryUsage(nonHeap));
}
private String toMB(long memory) {
return (memory * 100 / (1024 * 1024)) / 100F + "MB";
}
private String memoryUsage(MemoryUsage usage) {
return "init=" + toMB(usage.getInit()) + ", used="
+ toMB(usage.getUsed()) + ", committed="
+ toMB(usage.getCommitted()) + ", max="
+ toMB(usage.getMax());
}
@Override
public void callJNI_OnLoad(Emulator<?> emulator, Module module) {
new DalvikModule(this, module).callJNI_OnLoad(emulator);
}
@Override
public Emulator<?> getEmulator() {
return emulator;
}
} |
int hash = object.hashCode();
if (log.isDebugEnabled()) {
log.debug("addObject hash=0x" + Long.toHexString(hash) + ", global=" + global);
}
Object value = object.getValue();
if (value instanceof DvmAwareObject) {
((DvmAwareObject) value).initializeDvm(emulator, this, object);
}
if (global) {
ObjRef old = weak ? weakGlobalObjectMap.get(hash) : globalObjectMap.get(hash);
if (old == null) {
old = new ObjRef(object, weak);
} else {
old.refCount++;
}
if (weak) {
weakGlobalObjectMap.put(hash, old);
} else {
globalObjectMap.put(hash, old);
}
} else {
localObjectMap.put(hash, new ObjRef(object, weak));
}
return hash;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/DalvikModule.java | DalvikModule | callJNI_OnLoad | class DalvikModule {
private static final Log log = LogFactory.getLog(DalvikModule.class);
private final BaseVM vm;
private final Module module;
DalvikModule(BaseVM vm, Module module) {
this.vm = vm;
this.module = module;
}
public Module getModule() {
return module;
}
public void callJNI_OnLoad(Emulator<?> emulator) {<FILL_FUNCTION_BODY>}
} |
Symbol onLoad = module.findSymbolByName("JNI_OnLoad", false);
if (onLoad != null) {
try {
long start = System.currentTimeMillis();
if (log.isDebugEnabled()) {
log.debug("Call [" + module.name + "]JNI_OnLoad: 0x" + Long.toHexString(onLoad.getAddress()));
}
Number ret = onLoad.call(emulator, vm.getJavaVM(), null);
int version = ret.intValue();
if (log.isDebugEnabled()) {
log.debug("Call [" + module.name + "]JNI_OnLoad finished: version=0x" + Integer.toHexString(version) + ", offset=" + (System.currentTimeMillis() - start) + "ms");
}
vm.checkVersion(version);
} finally {
vm.deleteLocalRefs();
}
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/DvmObject.java | DvmObject | callJniMethodLong | class DvmObject<T> extends Hashable {
private final DvmClass objectType;
protected T value;
private final BaseVM vm;
protected DvmObject(DvmClass objectType, T value) {
this(objectType == null ? null : objectType.vm, objectType, value);
}
private DvmObject(BaseVM vm, DvmClass objectType, T value) {
this.vm = vm;
this.objectType = objectType;
this.value = value;
}
@SuppressWarnings("unchecked")
final void setValue(Object obj) {
this.value = (T) obj;
}
public T getValue() {
return value;
}
public DvmClass getObjectType() {
return objectType;
}
protected boolean isInstanceOf(DvmClass dvmClass) {
return objectType != null && objectType.isInstance(dvmClass);
}
@SuppressWarnings("unused")
public void callJniMethod(Emulator<?> emulator, String method, Object...args) {
if (objectType == null) {
throw new IllegalStateException("objectType is null");
}
try {
callJniMethod(emulator, vm, objectType, this, method, args);
} finally {
vm.deleteLocalRefs();
}
}
@SuppressWarnings("unused")
public boolean callJniMethodBoolean(Emulator<?> emulator, String method, Object...args) {
return BaseVM.valueOf(callJniMethodInt(emulator, method, args));
}
@SuppressWarnings("unused")
public int callJniMethodInt(Emulator<?> emulator, String method, Object...args) {
if (objectType == null) {
throw new IllegalStateException("objectType is null");
}
try {
return callJniMethod(emulator, vm, objectType, this, method, args).intValue();
} finally {
vm.deleteLocalRefs();
}
}
@SuppressWarnings("unused")
public long callJniMethodLong(Emulator<?> emulator, String method, Object...args) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unused")
public <V extends DvmObject<?>> V callJniMethodObject(Emulator<?> emulator, String method, Object...args) {
if (objectType == null) {
throw new IllegalStateException("objectType is null");
}
try {
Number number = callJniMethod(emulator, vm, objectType, this, method, args);
return objectType.vm.getObject(number.intValue());
} finally {
vm.deleteLocalRefs();
}
}
protected static Number callJniMethod(Emulator<?> emulator, VM vm, DvmClass objectType, DvmObject<?> thisObj, String method, Object...args) {
UnidbgPointer fnPtr = objectType.findNativeFunction(emulator, method);
vm.addLocalObject(thisObj);
List<Object> list = new ArrayList<>(10);
list.add(vm.getJNIEnv());
list.add(thisObj.hashCode());
if (args != null) {
for (Object arg : args) {
if (arg instanceof Boolean) {
list.add((Boolean) arg ? VM.JNI_TRUE : VM.JNI_FALSE);
continue;
} else if(arg instanceof Hashable) {
list.add(arg.hashCode()); // dvm object
if(arg instanceof DvmObject) {
vm.addLocalObject((DvmObject<?>) arg);
}
continue;
} else if (arg instanceof DvmAwareObject ||
arg instanceof String ||
arg instanceof byte[] ||
arg instanceof short[] ||
arg instanceof int[] ||
arg instanceof float[] ||
arg instanceof double[] ||
arg instanceof Enum) {
DvmObject<?> obj = ProxyDvmObject.createObject(vm, arg);
list.add(obj.hashCode());
vm.addLocalObject(obj);
continue;
}
list.add(arg);
}
}
return Module.emulateFunction(emulator, fnPtr.peer, list.toArray());
}
@Override
public String toString() {
if (value instanceof Enum) {
return value.toString();
}
if (objectType == null) {
return getClass().getSimpleName() + "{" +
"value=" + value +
'}';
}
return objectType.getName() + "@" + Integer.toHexString(hashCode());
}
protected MemoryBlock memoryBlock;
protected final UnidbgPointer allocateMemoryBlock(Emulator<?> emulator, int length) {
if (memoryBlock == null) {
memoryBlock = emulator.getMemory().malloc(length, true);
}
return memoryBlock.getPointer();
}
protected final void freeMemoryBlock(Pointer pointer) {
if (this.memoryBlock != null && (pointer == null || this.memoryBlock.isSame(pointer))) {
this.memoryBlock.free();
this.memoryBlock = null;
}
}
final void onDeleteRef() {
freeMemoryBlock(null);
}
} |
if (objectType == null) {
throw new IllegalStateException("objectType is null");
}
try {
return callJniMethod(emulator, vm, objectType, this, method, args).longValue();
} finally {
vm.deleteLocalRefs();
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/Hashable.java | Hashable | checkJni | class Hashable {
protected final Jni checkJni(BaseVM vm, DvmClass dvmClass) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return super.hashCode();
}
} |
Jni classJni = dvmClass.getJni();
if (vm.jni == null && classJni == null) {
throw new IllegalStateException("Please vm.setJni(jni)");
}
return classJni != null ? classJni : vm.jni;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/Shorty.java | Shorty | toString | class Shorty {
private final int arrayDimensions;
private final char type;
private String binaryName;
Shorty(int arrayDimensions, char type) {
this.arrayDimensions = arrayDimensions;
this.type = type;
}
final void setBinaryName(String binaryName) {
this.binaryName = binaryName;
}
public char getType() {
return arrayDimensions > 0 ? 'L' : type;
}
private static Class<?> getPrimitiveType(char c) {
switch (c) {
case 'B':
return byte.class;
case 'C':
return char.class;
case 'I':
return int.class;
case 'S':
return short.class;
case 'Z':
return boolean.class;
case 'F':
return float.class;
case 'D':
return double.class;
case 'J':
return long.class;
default:
return null;
}
}
public Class<?> decodeType(ClassLoader classLoader) {
if (classLoader == null) {
classLoader = Shorty.class.getClassLoader();
}
Class<?> clazz = getPrimitiveType(getType());
if (clazz != null) {
return clazz;
}
int dimensions = this.arrayDimensions;
if (dimensions > 0) {
try {
clazz = binaryName == null ? getPrimitiveType(type) : classLoader.loadClass(binaryName.replace('/', '.'));
if (clazz == null) {
throw new IllegalStateException("type=" + type);
}
while (dimensions-- > 0) {
clazz = Array.newInstance(clazz, 1).getClass();
}
return clazz;
} catch (ClassNotFoundException ignored) {
}
return null;
} else {
if (binaryName == null) {
throw new IllegalStateException("binaryName is null");
}
try {
clazz = classLoader.loadClass(binaryName.replace('/', '.'));
} catch (ClassNotFoundException ignored) {
}
return clazz;
}
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
} |
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arrayDimensions; i++) {
sb.append('[');
}
sb.append(type);
if (binaryName != null) {
sb.append(binaryName).append(';');
}
return sb.toString();
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/StringObject.java | StringObject | toString | class StringObject extends DvmObject<String> {
public StringObject(VM vm, String value) {
super(vm.resolveClass("java/lang/String"), value);
if (value == null) {
throw new NullPointerException();
}
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
} |
if (value == null) {
return null;
} else {
return '"' + value + '"';
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/VarArg.java | VarArg | formatArgs | class VarArg {
private final BaseVM vm;
final List<Object> args;
protected final DvmMethod method;
protected Shorty[] shorties;
protected VarArg(BaseVM vm, DvmMethod method) {
this.vm = vm;
this.shorties = method.decodeArgsShorty();
this.method = method;
this.args = new ArrayList<>(shorties.length);
}
/**
* @param index 0 based
*/
public final <T extends DvmObject<?>> T getObjectArg(int index) {
int hash = getIntArg(index);
return vm.getObject(hash);
}
/**
* @param index 0 based
*/
public final int getIntArg(int index) {
return (Integer) args.get(index);
}
/**
* @param index 0 based
*/
public final long getLongArg(int index) {
return (Long) args.get(index);
}
/**
* @param index 0 based
*/
public final float getFloatArg(int index) {
return (Float) args.get(index);
}
/**
* @param index 0 based
*/
public final double getDoubleArg(int index) {
return (Double) args.get(index);
}
final String formatArgs() {<FILL_FUNCTION_BODY>}
} |
Shorty[] shorties = method.decodeArgsShorty();
List<String> format = new ArrayList<>(shorties.length);
List<Object> args = new ArrayList<>(shorties.length);
for (int i = 0; i < shorties.length; i++) {
Shorty shorty = shorties[i];
switch (shorty.getType()) {
case 'B':
format.add("%s");
args.add((byte) getIntArg(i));
break;
case 'C':
format.add("%c");
args.add((char) getIntArg(i));
break;
case 'I':
format.add("0x%x");
args.add(getIntArg(i));
break;
case 'S':
format.add("%s");
args.add((short) getIntArg(i));
break;
case 'Z':
format.add("%s");
args.add(BaseVM.valueOf(getIntArg(i)));
break;
case 'F':
format.add("%fF");
args.add(getFloatArg(i));
break;
case 'L':
format.add("%s");
args.add(getObjectArg(i));
break;
case 'D':
format.add("%sD");
args.add(getDoubleArg(i));
break;
case 'J':
format.add("0x%xL");
args.add(getLongArg(i));
break;
default:
throw new IllegalStateException("c=" + shorty.getType());
}
}
StringBuilder sb = new StringBuilder();
if (!format.isEmpty()) {
sb.append(format.remove(0));
}
for (String str : format) {
sb.append(", ").append(str);
}
return String.format(sb.toString(), args.toArray());
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/api/Asset.java | Asset | read | class Asset extends DvmObject<String> {
public Asset(VM vm, String value) {
super(vm.resolveClass("android/content/res/Asset"), value);
}
public void open(Emulator<?> emulator, byte[] data) {
Pointer pointer = allocateMemoryBlock(emulator, data.length + 8);
pointer.setInt(0, 0); // index
pointer.setInt(4, data.length);
pointer.write(8, data, 0, data.length);
}
public void close() {
freeMemoryBlock(null);
}
public UnidbgPointer getBuffer() {
return memoryBlock.getPointer().share(8, 0);
}
public int getLength() {
return memoryBlock.getPointer().getInt(4);
}
public byte[] read(int count) {<FILL_FUNCTION_BODY>}
} |
Pointer pointer = memoryBlock.getPointer();
int index = pointer.getInt(0);
int length = pointer.getInt(4);
Pointer data = pointer.share(8, 0);
int remaining = length - index;
int read = Math.min(remaining, count);
pointer.setInt(0, index + read);
return data.getByteArray(index, read);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/api/Bitmap.java | Bitmap | lockPixels | class Bitmap extends DvmObject<BufferedImage> {
public Bitmap(VM vm, BufferedImage image) {
super(vm.resolveClass("android/graphics/Bitmap"), image);
}
public Pointer lockPixels(Emulator<?> emulator, BufferedImage image, ByteBuffer buffer) {<FILL_FUNCTION_BODY>}
public void unlockPixels() {
freeMemoryBlock(null);
}
} |
Pointer pointer = allocateMemoryBlock(emulator, image.getWidth() * image.getHeight() * 4);
pointer.write(0, buffer.array(), 0, buffer.capacity());
return pointer;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/api/Bundle.java | Bundle | getInt | class Bundle extends DvmObject<Properties> {
public Bundle(VM vm, Properties properties) {
super(vm.resolveClass("android/os/Bundle"), properties);
}
public int getInt(String key) {<FILL_FUNCTION_BODY>}
} |
String value = super.value.getProperty(key);
if (value == null) {
throw new BackendException("key=" + key);
}
return Integer.parseInt(value, 16);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/api/SystemService.java | SystemService | getObjectType | class SystemService extends DvmObject<String> {
public static final String WIFI_SERVICE = "wifi";
public static final String CONNECTIVITY_SERVICE = "connectivity";
public static final String TELEPHONY_SERVICE = "phone";
public static final String ACCESSIBILITY_SERVICE = "accessibility";
public static final String KEYGUARD_SERVICE = "keyguard";
public static final String ACTIVITY_SERVICE = "activity";
public static final String SENSOR_SERVICE = "sensor";
public static final String INPUT_METHOD_SERVICE = "input_method";
public static final String LOCATION_SERVICE = "location";
public static final String WINDOW_SERVICE = "window";
public static final String UI_MODE_SERVICE = "uimode";
public static final String DISPLAY_SERVICE = "display";
public static final String AUDIO_SERVICE = "audio";
public SystemService(VM vm, String serviceName) {
super(getObjectType(vm, serviceName), serviceName);
}
private static DvmClass getObjectType(VM vm, String serviceName) {<FILL_FUNCTION_BODY>}
} |
switch (serviceName) {
case TELEPHONY_SERVICE:
return vm.resolveClass("android/telephony/TelephonyManager");
case WIFI_SERVICE:
return vm.resolveClass("android/net/wifi/WifiManager");
case CONNECTIVITY_SERVICE:
return vm.resolveClass("android/net/ConnectivityManager");
case ACCESSIBILITY_SERVICE:
return vm.resolveClass("android/view/accessibility/AccessibilityManager");
case KEYGUARD_SERVICE:
return vm.resolveClass("android/app/KeyguardManager");
case ACTIVITY_SERVICE:
return vm.resolveClass("android/os/BinderProxy"); // android/app/ActivityManager
case SENSOR_SERVICE:
return vm.resolveClass("android/hardware/SensorManager");
case INPUT_METHOD_SERVICE:
return vm.resolveClass("android/view/inputmethod/InputMethodManager");
case LOCATION_SERVICE:
return vm.resolveClass("android/location/LocationManager");
case WINDOW_SERVICE:
return vm.resolveClass("android/view/WindowManager");
case UI_MODE_SERVICE:
return vm.resolveClass("android/app/UiModeManager");
case DISPLAY_SERVICE:
return vm.resolveClass("android/hardware/display/DisplayManager");
case AUDIO_SERVICE:
return vm.resolveClass("android/media/AudioManager");
default:
throw new BackendException("service failed: " + serviceName);
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/apk/ApkDir.java | ApkDir | parseCertificates | class ApkDir implements Apk {
private final File dir;
ApkDir(File dir) {
this.dir = dir;
}
@Override
public long getVersionCode() {
parseManifest();
return apkMeta == null ? 0L : apkMeta.getVersionCode();
}
@Override
public String getVersionName() {
parseManifest();
return apkMeta == null ? null : apkMeta.getVersionName();
}
@Override
public String getManifestXml() {
parseManifest();
return manifestXml;
}
@Override
public byte[] openAsset(String fileName) {
return getFileData("assets/" + fileName);
}
@Override
public byte[] getFileData(String path) {
File file = new File(dir, path);
if (file.canRead()) {
try {
return FileUtils.readFileToByteArray(file);
} catch (IOException e) {
throw new IllegalStateException(e);
}
} else {
return null;
}
}
private CertificateMeta[] signatures;
@Override
public CertificateMeta[] getSignatures() {
if (signatures == null) {
try {
parseCertificates();
} catch (IOException | CertificateException e) {
throw new IllegalStateException(e);
}
}
return this.signatures;
}
private static class CertificateFile {
private final String path;
private final byte[] data;
CertificateFile(String path, byte[] data) {
this.path = path;
this.data = data;
}
public String getPath() {
return path;
}
public byte[] getData() {
return data;
}
}
private List<CertificateFile> getAllCertificateData() throws IOException {
List<CertificateFile> list = new ArrayList<>();
scanCertificateFile(list, dir);
return list;
}
private void scanCertificateFile(List<CertificateFile> list, File dir) throws IOException {
File[] files = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
String ext;
return pathname.isDirectory() || (ext = FilenameUtils.getExtension(pathname.getName())).equalsIgnoreCase("RSA") || ext.equalsIgnoreCase("DSA");
}
});
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
scanCertificateFile(list, file);
} else {
list.add(new CertificateFile(file.getPath(), FileUtils.readFileToByteArray(file)));
}
}
}
}
private void parseCertificates() throws IOException, CertificateException {<FILL_FUNCTION_BODY>}
@Override
public String getPackageName() {
parseManifest();
return apkMeta == null ? null : apkMeta.getPackageName();
}
@Override
public File getParentFile() {
return dir.getParentFile();
}
private boolean manifestParsed;
private String manifestXml;
private ApkMeta apkMeta;
private void parseManifest() {
if (manifestParsed) {
return;
}
ResourceTable resourceTable = new ResourceTable();
Locale preferredLocale = Locale.US;
XmlTranslator xmlTranslator = new XmlTranslator();
ApkMetaTranslator apkTranslator = new ApkMetaTranslator(resourceTable, preferredLocale);
XmlStreamer xmlStreamer = new CompositeXmlStreamer(xmlTranslator, apkTranslator);
byte[] data = getFileData(AndroidConstants.MANIFEST_FILE);
if (data != null) {
transBinaryXml(data, xmlStreamer, resourceTable, preferredLocale);
this.manifestXml = xmlTranslator.getXml();
this.apkMeta = apkTranslator.getApkMeta();
manifestParsed = true;
}
}
private void transBinaryXml(byte[] data, XmlStreamer xmlStreamer, ResourceTable resourceTable, Locale preferredLocale) {
ByteBuffer buffer = ByteBuffer.wrap(data);
BinaryXmlParser binaryXmlParser = new BinaryXmlParser(buffer, resourceTable);
binaryXmlParser.setLocale(preferredLocale);
binaryXmlParser.setXmlStreamer(xmlStreamer);
binaryXmlParser.parse();
}
} |
List<ApkSigner> apkSigners = new ArrayList<>();
for (CertificateFile file : getAllCertificateData()) {
CertificateParser parser = CertificateParser.getInstance(file.getData());
List<CertificateMeta> certificateMetas = parser.parse();
apkSigners.add(new ApkSigner(file.getPath(), certificateMetas));
}
List<CertificateMeta> signatures = new ArrayList<>(apkSigners.size());
for (ApkSigner signer : apkSigners) {
signatures.addAll(signer.getCertificateMetas());
}
this.signatures = signatures.toArray(new CertificateMeta[0]);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/apk/ApkFile.java | ApkFile | getPackageName | class ApkFile implements Apk {
private final File apkFile;
ApkFile(File file) {
this.apkFile = file;
}
private ApkMeta apkMeta;
@Override
public long getVersionCode() {
if (apkMeta != null) {
return apkMeta.getVersionCode();
}
try (net.dongliu.apk.parser.ApkFile apkFile = new net.dongliu.apk.parser.ApkFile(this.apkFile)) {
apkMeta = apkFile.getApkMeta();
return apkMeta.getVersionCode();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public String getVersionName() {
if (apkMeta != null) {
return apkMeta.getVersionName();
}
try (net.dongliu.apk.parser.ApkFile apkFile = new net.dongliu.apk.parser.ApkFile(this.apkFile)) {
apkMeta = apkFile.getApkMeta();
return apkMeta.getVersionName();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public String getManifestXml() {
try (net.dongliu.apk.parser.ApkFile apkFile = new net.dongliu.apk.parser.ApkFile(this.apkFile)) {
return apkFile.getManifestXml();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public byte[] openAsset(String fileName) {
try (net.dongliu.apk.parser.ApkFile apkFile = new net.dongliu.apk.parser.ApkFile(this.apkFile)) {
return apkFile.getFileData("assets/" + fileName);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private CertificateMeta[] signatures;
@Override
public CertificateMeta[] getSignatures() {
if (signatures != null) {
return signatures;
}
try (net.dongliu.apk.parser.ApkFile apkFile = new net.dongliu.apk.parser.ApkFile(this.apkFile)) {
List<CertificateMeta> signatures = new ArrayList<>(10);
for (ApkSigner signer : apkFile.getApkSingers()) {
signatures.addAll(signer.getCertificateMetas());
}
this.signatures = signatures.toArray(new CertificateMeta[0]);
return this.signatures;
} catch (IOException | CertificateException e) {
throw new IllegalStateException(e);
}
}
@Override
public String getPackageName() {<FILL_FUNCTION_BODY>}
@Override
public File getParentFile() {
return apkFile.getParentFile();
}
@Override
public byte[] getFileData(String path) {
try (net.dongliu.apk.parser.ApkFile apkFile = new net.dongliu.apk.parser.ApkFile(this.apkFile)) {
return apkFile.getFileData(path);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
} |
if (apkMeta != null) {
return apkMeta.getPackageName();
}
try (net.dongliu.apk.parser.ApkFile apkFile = new net.dongliu.apk.parser.ApkFile(this.apkFile)) {
apkMeta = apkFile.getApkMeta();
return apkMeta.getPackageName();
} catch (ParserException e) { // Manifest file not found
return null;
} catch (IOException e) {
throw new IllegalStateException(e);
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/array/ArrayObject.java | ArrayObject | newStringArray | class ArrayObject extends BaseArray<DvmObject<?>[]> implements Array<DvmObject<?>[]> {
@SuppressWarnings("unused")
public static ArrayObject newStringArray(VM vm, String... strings) {<FILL_FUNCTION_BODY>}
public ArrayObject(DvmObject<?>... value) {
super(null, value);
}
@Override
public int length() {
return value.length;
}
@Override
public void setData(int start, DvmObject<?>[] data) {
System.arraycopy(data, 0, value, start, data.length);
}
@Override
public String toString() {
return Arrays.toString(value);
}
} |
StringObject[] objects = new StringObject[strings.length];
for (int i = 0; i < strings.length; i++) {
String str = strings[i];
if (str != null) {
objects[i] = new StringObject(vm, str);
}
}
return new ArrayObject(objects);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/array/ByteArray.java | ByteArray | toString | class ByteArray extends BaseArray<byte[]> implements PrimitiveArray<byte[]> {
public ByteArray(VM vm, byte[] value) {
super(vm.resolveClass("[B"), value);
}
@Override
public int length() {
return value.length;
}
public void setValue(byte[] value) {
super.value = value;
}
@Override
public void setData(int start, byte[] data) {
System.arraycopy(data, 0, value, start, data.length);
}
@Override
public UnidbgPointer _GetArrayCritical(Emulator<?> emulator, Pointer isCopy) {
if (isCopy != null) {
isCopy.setInt(0, VM.JNI_TRUE);
}
UnidbgPointer pointer = this.allocateMemoryBlock(emulator, value.length);
pointer.write(0, value, 0, value.length);
return pointer;
}
@Override
public void _ReleaseArrayCritical(Pointer elems, int mode) {
switch (mode) {
case VM.JNI_COMMIT:
this.setValue(elems.getByteArray(0, this.value.length));
break;
case 0:
this.setValue(elems.getByteArray(0, this.value.length));
case VM.JNI_ABORT:
this.freeMemoryBlock(elems);
break;
}
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
} |
if (value != null && value.length <= 64) {
return "[B@0x" + Hex.encodeHexString(value);
} else {
return super.toString();
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/array/DoubleArray.java | DoubleArray | _ReleaseArrayCritical | class DoubleArray extends BaseArray<double[]> implements PrimitiveArray<double[]> {
public DoubleArray(VM vm, double[] value) {
super(vm.resolveClass("[D"), value);
}
@Override
public int length() {
return value.length;
}
public void setValue(double[] value) {
super.value = value;
}
@Override
public void setData(int start, double[] data) {
System.arraycopy(data, 0, value, start, data.length);
}
@Override
public UnidbgPointer _GetArrayCritical(Emulator<?> emulator, Pointer isCopy) {
if (isCopy != null) {
isCopy.setInt(0, VM.JNI_TRUE);
}
UnidbgPointer pointer = this.allocateMemoryBlock(emulator, value.length * 8);
pointer.write(0, value, 0, value.length);
return pointer;
}
@Override
public void _ReleaseArrayCritical(Pointer elems, int mode) {<FILL_FUNCTION_BODY>}
} |
switch (mode) {
case VM.JNI_COMMIT:
this.setValue(elems.getDoubleArray(0, this.value.length));
break;
case 0:
this.setValue(elems.getDoubleArray(0, this.value.length));
case VM.JNI_ABORT:
this.freeMemoryBlock(elems);
break;
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/array/FloatArray.java | FloatArray | _ReleaseArrayCritical | class FloatArray extends BaseArray<float[]> implements PrimitiveArray<float[]> {
public FloatArray(VM vm, float[] value) {
super(vm.resolveClass("[F"), value);
}
@Override
public int length() {
return value.length;
}
public void setValue(float[] value) {
super.value = value;
}
@Override
public void setData(int start, float[] data) {
System.arraycopy(data, 0, value, start, data.length);
}
@Override
public UnidbgPointer _GetArrayCritical(Emulator<?> emulator, Pointer isCopy) {
if (isCopy != null) {
isCopy.setInt(0, VM.JNI_TRUE);
}
UnidbgPointer pointer = this.allocateMemoryBlock(emulator, value.length * 4);
pointer.write(0, value, 0, value.length);
return pointer;
}
@Override
public void _ReleaseArrayCritical(Pointer elems, int mode) {<FILL_FUNCTION_BODY>}
} |
switch (mode) {
case VM.JNI_COMMIT:
this.setValue(elems.getFloatArray(0, this.value.length));
break;
case 0:
this.setValue(elems.getFloatArray(0, this.value.length));
case VM.JNI_ABORT:
this.freeMemoryBlock(elems);
break;
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/array/IntArray.java | IntArray | _ReleaseArrayCritical | class IntArray extends BaseArray<int[]> implements PrimitiveArray<int[]> {
public IntArray(VM vm, int[] value) {
super(vm.resolveClass("[I"), value);
}
@Override
public int length() {
return value.length;
}
public void setValue(int[] value) {
super.value = value;
}
@Override
public void setData(int start, int[] data) {
System.arraycopy(data, 0, value, start, data.length);
}
@Override
public UnidbgPointer _GetArrayCritical(Emulator<?> emulator, Pointer isCopy) {
if (isCopy != null) {
isCopy.setInt(0, VM.JNI_TRUE);
}
UnidbgPointer pointer = this.allocateMemoryBlock(emulator, value.length * 4);
pointer.write(0, value, 0, value.length);
return pointer;
}
@Override
public void _ReleaseArrayCritical(Pointer elems, int mode) {<FILL_FUNCTION_BODY>}
} |
switch (mode) {
case VM.JNI_COMMIT:
this.setValue(elems.getIntArray(0, this.value.length));
break;
case 0:
this.setValue(elems.getIntArray(0, this.value.length));
case VM.JNI_ABORT:
this.freeMemoryBlock(elems);
break;
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/array/ShortArray.java | ShortArray | _GetArrayCritical | class ShortArray extends BaseArray<short[]> implements PrimitiveArray<short[]> {
public ShortArray(VM vm, short[] value) {
super(vm.resolveClass("[S"), value);
}
@Override
public int length() {
return value.length;
}
public void setValue(short[] value) {
super.value = value;
}
@Override
public void setData(int start, short[] data) {
System.arraycopy(data, 0, value, start, data.length);
}
@Override
public UnidbgPointer _GetArrayCritical(Emulator<?> emulator, Pointer isCopy) {<FILL_FUNCTION_BODY>}
@Override
public void _ReleaseArrayCritical(Pointer elems, int mode) {
switch (mode) {
case VM.JNI_COMMIT:
this.setValue(elems.getShortArray(0, this.value.length));
break;
case 0:
this.setValue(elems.getShortArray(0, this.value.length));
case VM.JNI_ABORT:
this.freeMemoryBlock(elems);
break;
}
}
} |
if (isCopy != null) {
isCopy.setInt(0, VM.JNI_TRUE);
}
UnidbgPointer pointer = this.allocateMemoryBlock(emulator, value.length * 2);
pointer.write(0, value, 0, value.length);
return pointer;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/jni/ProxyClassFactory.java | ProxyClassFactory | createClass | class ProxyClassFactory implements DvmClassFactory {
protected final ProxyClassLoader classLoader;
public ProxyClassFactory() {
this(ProxyClassFactory.class.getClassLoader());
}
public ProxyClassFactory(ClassLoader classLoader) {
this.classLoader = new ProxyClassLoader(classLoader);
}
public ProxyClassFactory configClassNameMapper(ProxyClassMapper mapper) {
classLoader.setClassNameMapper(mapper);
return this;
}
protected ProxyDvmObjectVisitor visitor;
public ProxyClassFactory configObjectVisitor(ProxyDvmObjectVisitor visitor) {
this.visitor = visitor;
return this;
}
@Override
public DvmClass createClass(BaseVM vm, String className, DvmClass superClass, DvmClass[] interfaceClasses) {<FILL_FUNCTION_BODY>}
private Jni fallbackJni;
public void setFallbackJni(Jni fallbackJni) {
this.fallbackJni = fallbackJni;
}
} |
return new ProxyDvmClass(vm, className, superClass, interfaceClasses, classLoader, visitor, fallbackJni);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/jni/ProxyClassLoader.java | ProxyClassLoader | loadClass | class ProxyClassLoader {
private final ClassLoader classLoader;
ProxyClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
private ProxyClassMapper classNameMapper;
final void setClassNameMapper(ProxyClassMapper classNameMapper) {
this.classNameMapper = classNameMapper;
}
final Class<?> loadClass(String name) throws ClassNotFoundException {<FILL_FUNCTION_BODY>}
} |
Class<?> newClass = classNameMapper == null ? null : classNameMapper.map(name);
if (newClass != null) {
return newClass;
}
return classLoader.loadClass(name);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/jni/ProxyConstructor.java | ProxyConstructor | call | class ProxyConstructor implements ProxyCall {
private final ProxyDvmObjectVisitor visitor;
private final Constructor<?> constructor;
private final Object[] args;
ProxyConstructor(ProxyDvmObjectVisitor visitor, Constructor<?> constructor, Object[] args) {
this.visitor = visitor;
this.constructor = constructor;
this.args = args;
}
@Override
public Object call(VM vm, Object obj) throws IllegalAccessException, InvocationTargetException, InstantiationException {<FILL_FUNCTION_BODY>}
} |
try {
Object inst = constructor.newInstance(args);
if (visitor != null) {
visitor.onProxyVisit(constructor, inst, args);
inst = visitor.postProxyVisit(constructor, inst, args, inst);
}
return inst;
} catch (InvocationTargetException e) {
Throwable cause = e.getTargetException();
if (cause instanceof BackendException) {
throw (BackendException) cause;
}
if (cause instanceof ProxyDvmException) {
vm.throwException(ProxyDvmObject.createObject(vm, cause));
return null;
}
throw e;
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/jni/ProxyDvmObject.java | ProxyDvmObject | getObjectType | class ProxyDvmObject extends DvmObject<Object> {
private static DvmClass getObjectType(VM vm, Class<?> clazz) {<FILL_FUNCTION_BODY>}
/**
* mapping java object to dvm object
*/
public static DvmObject<?> createObject(VM vm, Object value) {
if (value == null) {
return null;
}
if (value instanceof Class<?>) {
return getObjectType(vm, (Class<?>) value);
}
if (value instanceof DvmObject) {
return (DvmObject<?>) value;
}
if (value instanceof byte[]) {
return new ByteArray(vm, (byte[]) value);
}
if (value instanceof short[]) {
return new ShortArray(vm, (short[]) value);
}
if (value instanceof int[]) {
return new IntArray(vm, (int[]) value);
}
if (value instanceof float[]) {
return new FloatArray(vm, (float[]) value);
}
if (value instanceof double[]) {
return new DoubleArray(vm, (double[]) value);
}
if (value instanceof String) {
return new StringObject(vm, (String) value);
}
Class<?> clazz = value.getClass();
if (clazz.isArray()) {
if (clazz.getComponentType().isPrimitive()) {
throw new UnsupportedOperationException(String.valueOf(value));
}
Object[] array = (Object[]) value;
DvmObject<?>[] dvmArray = new DvmObject[array.length];
for (int i = 0; i < array.length; i++) {
dvmArray[i] = createObject(vm, array[i]);
}
return new ArrayObject(dvmArray);
}
return new ProxyDvmObject(vm, value);
}
private ProxyDvmObject(VM vm, Object value) {
super(getObjectType(vm, value.getClass()), value);
}
} |
Class<?> superClass = clazz.getSuperclass();
DvmClass[] interfaces = new DvmClass[clazz.getInterfaces().length + (superClass == null ? 0 : 1)];
int i = 0;
if (superClass != null) {
interfaces[i++] = getObjectType(vm, superClass);
}
for (Class<?> cc : clazz.getInterfaces()) {
interfaces[i++] = getObjectType(vm, cc);
}
return vm.resolveClass(clazz.getName().replace('.', '/'), interfaces);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/jni/ProxyField.java | ProxyField | getInt | class ProxyField {
private final ProxyDvmObjectVisitor visitor;
private final Field field;
ProxyField(ProxyDvmObjectVisitor visitor, Field field) {
this.visitor = visitor;
this.field = field;
}
final Object get(Object thisObj) throws IllegalAccessException {
if (visitor != null) {
visitor.onProxyVisit(field, thisObj, null);
}
Object result = field.get(thisObj);
if (visitor != null) {
result = visitor.postProxyVisit(field, thisObj, null, result);
}
return result;
}
final long getLong(Object thisObj) throws IllegalAccessException {
if (visitor != null) {
visitor.onProxyVisit(field, thisObj, null);
}
long result = field.getLong(thisObj);
if (visitor != null) {
result = visitor.postProxyVisit(field, thisObj, null, result);
}
return result;
}
final float getFloat(Object thisObj) throws IllegalAccessException {
if (visitor != null) {
visitor.onProxyVisit(field, thisObj, null);
}
float result = field.getFloat(thisObj);
if (visitor != null) {
result = visitor.postProxyVisit(field, thisObj, null, result);
}
return result;
}
final boolean getBoolean(Object thisObj) throws IllegalAccessException {
if (visitor != null) {
visitor.onProxyVisit(field, thisObj, null);
}
boolean result = field.getBoolean(thisObj);
if (visitor != null) {
result = visitor.postProxyVisit(field, thisObj, null, result);
}
return result;
}
final byte getByte(Object thisObj) throws IllegalAccessException {
if (visitor != null) {
visitor.onProxyVisit(field, thisObj, null);
}
byte result = field.getByte(thisObj);
if (visitor != null) {
result = visitor.postProxyVisit(field, thisObj, null, result);
}
return result;
}
final int getInt(Object thisObj) throws IllegalAccessException {<FILL_FUNCTION_BODY>}
final void setInt(Object thisObj, int value) throws IllegalAccessException {
if (visitor != null) {
visitor.onProxyVisit(field, thisObj, new Object[] { value });
}
field.setInt(thisObj, value);
}
final void setFloat(Object thisObj, float value) throws IllegalAccessException {
if (visitor != null) {
visitor.onProxyVisit(field, thisObj, new Object[] { value });
}
field.setFloat(thisObj, value);
}
final void setDouble(Object thisObj, double value) throws IllegalAccessException {
if (visitor != null) {
visitor.onProxyVisit(field, thisObj, new Object[] { value });
}
field.setDouble(thisObj, value);
}
final void setObject(Object thisObj, Object value) throws IllegalAccessException {
if (visitor != null) {
visitor.onProxyVisit(field, thisObj, new Object[] { value });
}
field.set(thisObj, value);
}
final void setBoolean(Object thisObj, boolean value) throws IllegalAccessException {
if (visitor != null) {
visitor.onProxyVisit(field, thisObj, new Object[] { value });
}
field.setBoolean(thisObj, value);
}
final void setLong(Object thisObj, long value) throws IllegalAccessException {
if (visitor != null) {
visitor.onProxyVisit(field, thisObj, new Object[] { value });
}
field.setLong(thisObj, value);
}
} |
if (visitor != null) {
visitor.onProxyVisit(field, thisObj, null);
}
int result = field.getInt(thisObj);
if (visitor != null) {
result = visitor.postProxyVisit(field, thisObj, null, result);
}
return result;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/android/dvm/jni/ProxyMethod.java | ProxyMethod | patchClassName | class ProxyMethod implements ProxyCall {
private final ProxyDvmObjectVisitor visitor;
private final Member method;
private final Object[] args;
ProxyMethod(ProxyDvmObjectVisitor visitor, Member method, Object[] args) {
this.visitor = visitor;
this.method = method;
this.args = args;
}
@Override
public Object call(VM vm, Object obj) throws IllegalAccessException, InvocationTargetException {
try {
patchClassName(obj, args);
if (visitor != null) {
visitor.onProxyVisit(method, obj, args);
}
if (method instanceof Method) {
Object result = ((Method) method).invoke(obj, args);
if (visitor != null) {
result = visitor.postProxyVisit(method, obj, args, result);
}
return result;
}
throw new UnsupportedOperationException("method=" + method);
} catch (InvocationTargetException e) {
Throwable cause = e.getTargetException();
if (cause instanceof BackendException) {
throw (BackendException) cause;
}
if (cause instanceof ProxyDvmException) {
vm.throwException(ProxyDvmObject.createObject(vm, cause));
return null;
}
if (cause instanceof ClassNotFoundException) {
vm.throwException(ProxyDvmObject.createObject(vm, cause));
return null;
}
throw e;
}
}
private void patchClassName(Object obj, Object[] args) {<FILL_FUNCTION_BODY>}
} |
if (obj instanceof ClassLoader &&
args.length == 1 &&
("loadClass".equals(method.getName()) || "findClass".equals(method.getName()))) {
String binaryName = (String) args[0];
args[0] = binaryName.replace('/', '.');
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/file/Ashmem.java | Ashmem | ioctl | class Ashmem extends DriverFileIO {
private static final Log log = LogFactory.getLog(Ashmem.class);
Ashmem(Emulator<?> emulator, int oflags, String path) {
super(emulator, oflags, path);
}
private static final int ASHMEM_SET_NAME = 0x41007701;
private static final int ASHMEM_SET_SIZE_32 = 0x40047703;
private static final int ASHMEM_SET_SIZE_64 = 0x40087703;
private String name;
private int size;
@Override
public int ioctl(Emulator<?> emulator, long request, long argp) {<FILL_FUNCTION_BODY>}
@Override
protected byte[] getMmapData(long addr, int offset, int length) {
return new byte[0];
}
@Override
public String toString() {
return "Ashmem{" +
"name='" + name + '\'' +
", size=" + size +
'}';
}
} |
if (request == ASHMEM_SET_NAME) {
Pointer pointer = UnidbgPointer.pointer(emulator, argp);
assert pointer != null;
this.name = pointer.getString(0);
log.debug("ashmem set name: " + this.name);
return 0;
}
if (request == ASHMEM_SET_SIZE_32 || request == ASHMEM_SET_SIZE_64) {
this.size = (int) argp;
log.debug("ashmem set size: " + this.size);
return 0;
}
return super.ioctl(emulator, request, argp);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/file/ByteArrayFileIO.java | ByteArrayFileIO | getMmapData | class ByteArrayFileIO extends BaseAndroidFileIO {
private static final Log log = LogFactory.getLog(ByteArrayFileIO.class);
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 pread(Backend backend, Pointer buffer, int count, long offset) {
int pos = this.pos;
try {
this.pos = (int) offset;
return read(backend, buffer, count);
} finally {
this.pos = pos;
}
}
@Override
public int read(Backend backend, Pointer buffer, int count) {
if (pos >= bytes.length) {
return 0;
}
int remain = bytes.length - pos;
if (count > remain) {
count = remain;
}
buffer.write(0, bytes, pos, count);
if (log.isDebugEnabled()) {
log.debug(Inspector.inspectString(Arrays.copyOfRange(bytes, pos, pos + count), "read path=" + path + ", fp=" + pos + ", _count=" + count + ", length=" + bytes.length + ", buffer=" + buffer));
}
pos += count;
return count;
}
@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
public int fstat(Emulator<?> emulator, StatStructure stat) {
stat.st_dev = 1;
stat.st_mode = IO.S_IFREG;
stat.st_uid = 0;
stat.st_gid = 0;
stat.st_size = bytes.length;
stat.st_blksize = emulator.getPageAlign();
stat.st_blocks = ((bytes.length + emulator.getPageAlign() - 1) / emulator.getPageAlign());
stat.st_ino = 1;
stat.setLastModification(System.currentTimeMillis());
stat.pack();
return 0;
}
@Override
protected byte[] getMmapData(long addr, int offset, int length) {<FILL_FUNCTION_BODY>}
@Override
public int ioctl(Emulator<?> emulator, long request, long argp) {
return 0;
}
@Override
public String toString() {
return path;
}
@Override
public int ftruncate(int length) {
return 0;
}
} |
if (offset == 0 && length == bytes.length) {
return bytes;
} else {
byte[] data = new byte[length];
System.arraycopy(bytes, offset, data, 0, data.length);
return data;
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/file/DirectoryFileIO.java | DirectoryFileIO | createEntries | class DirectoryFileIO extends BaseAndroidFileIO {
public enum DirentType {
DT_FIFO(1), /* FIFO */
DT_CHR(2), /* character device */
DT_DIR(4), /* directory */
DT_BLK(6), /* block device */
DT_REG(8), /* regular file */
DT_LNK(10), /* symbolic link */
DT_SOCK(12), /* socket */
DT_WHT(14); /* whiteout */
private final byte type;
DirentType(int type) {
this.type = (byte) type;
}
}
public static class DirectoryEntry {
private final DirentType type;
private final String name;
public DirectoryEntry(boolean isFile, String name) {
this(isFile ? DirentType.DT_REG : DirentType.DT_DIR, name);
}
public DirectoryEntry(DirentType type, String name) {
this.type = type;
this.name = name;
}
}
private static DirectoryEntry[] createEntries(File dir) {<FILL_FUNCTION_BODY>}
private final String path;
private final List<DirectoryEntry> entries;
public DirectoryFileIO(int oflags, String path, File dir) {
this(oflags, path, createEntries(dir));
}
public DirectoryFileIO(int oflags, String path, DirectoryEntry...entries) {
super(oflags);
this.path = path;
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 getdents64(Pointer dirp, int size) {
int offset = 0;
for (Iterator<DirectoryEntry> iterator = this.entries.iterator(); iterator.hasNext(); ) {
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 >= size) {
break;
}
Dirent dirent = new Dirent(dirp.share(offset));
dirent.d_ino = 0;
dirent.d_off = 0;
dirent.d_reclen = (short) d_reclen;
dirent.d_type = entry.type.type;
dirent.d_name = Arrays.copyOf(data, data.length + 1);
dirent.pack();
offset += d_reclen;
iterator.remove();
}
return offset;
}
@Override
public void close() {
}
@Override
public int fstat(Emulator<?> emulator, StatStructure stat) {
stat.st_mode = IO.S_IFDIR;
stat.st_dev = 0;
stat.st_size = 0;
stat.st_blksize = 0;
stat.st_ino = 0;
stat.pack();
return 0;
}
@Override
public String toString() {
return path;
}
@Override
public String getPath() {
return path;
}
@Override
public int statfs(StatFS statFS) {
statFS.setType(0xef53);
statFS.setBlockSize(0x1000);
statFS.f_blocks = 0x3235af;
statFS.f_bfree = 0x2b5763;
statFS.f_bavail = 0x2b5763;
statFS.f_files = 0xcccb0;
statFS.f_ffree = 0xcbd2e;
statFS.f_fsid = new int[] { 0xd3609fe8, 0x4970d6b };
statFS.setNameLen(0xff);
statFS.setFrSize(0x1000);
statFS.setFlags(0x426);
statFS.pack();
return 0;
}
} |
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]);
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/file/DnsProxyDaemon.java | DnsProxyDaemon | getaddrinfo | class DnsProxyDaemon implements LocalSocketIO.SocketHandler {
private static final Log log = LogFactory.getLog(DnsProxyDaemon.class);
private static final int DnsProxyQueryResult = 222;
private static final int DnsProxyOperationFailed = 401;
private final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
private final int sdk;
DnsProxyDaemon(int sdk) {
this.sdk = sdk;
}
@Override
public int fstat(StatStructure stat) {
stat.st_size = 0;
stat.st_blksize = 0;
stat.pack();
return 0;
}
@Override
public byte[] handle(byte[] request) throws IOException {
baos.write(request);
byte[] data = baos.toByteArray();
int endIndex = -1;
for (int i = 0; i < data.length; i++) {
if (data[i] == 0) {
endIndex = i;
break;
}
}
if (endIndex == -1) {
return null;
}
baos.reset();
String command = new String(data, 0, endIndex);
if (command.startsWith("getaddrinfo")) {
return getaddrinfo(command);
} else if (command.startsWith("gethostbyaddr")) {
return gethostbyaddr(command);
}
throw new AbstractMethodError(command);
}
private byte[] gethostbyaddr(String command) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
String[] tokens = command.split("\\s");
String addr = tokens[1];
try {
InetAddress address = InetAddress.getByName(addr);
String host = address.getCanonicalHostName();
if (host != null && host.equals(addr)) {
host = null;
}
if (host == null) {
throw new UnknownHostException();
} else {
buffer.put((DnsProxyQueryResult + "\0").getBytes());
byte[] bytes = host.getBytes(StandardCharsets.UTF_8);
buffer.putInt(bytes.length + 1);
buffer.put(bytes);
buffer.put((byte) 0); // NULL-terminated string
buffer.putInt(0); // null to indicate we're done aliases
buffer.putInt(SocketIO.AF_INET); // addrtype
buffer.putInt(4); // unknown length
buffer.putInt(0); // null to indicate we're done addr_list
}
} catch (UnknownHostException e) {
buffer.put((DnsProxyOperationFailed + "\0").getBytes());
buffer.putInt(0);
}
buffer.flip();
byte[] response = new byte[buffer.remaining()];
buffer.get(response);
if (log.isDebugEnabled()) {
Inspector.inspect(response, "gethostbyaddr");
}
return response;
}
private byte[] getaddrinfo(String command) {<FILL_FUNCTION_BODY>}
private void putAddress(ByteBuffer buffer, InetAddress address, int ai_flags, int ai_socktype, short port) {
if (sdk == 19) {
buffer.order(ByteOrder.BIG_ENDIAN);
buffer.putInt(32); // sizeof(struct addrinfo)
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(ai_flags);
buffer.putInt(SocketIO.AF_INET);
buffer.putInt(ai_socktype);
buffer.putInt(SocketIO.IPPROTO_TCP);
buffer.putInt(16); // ai_addrlen
buffer.putInt(0); // ai_canonname
buffer.putInt(0); // ai_addr
buffer.putInt(0); // ai_next
buffer.order(ByteOrder.BIG_ENDIAN);
buffer.putInt(16); // ai_addrlen
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putShort((short) SocketIO.AF_INET); // sin_family
buffer.putShort(Short.reverseBytes(port)); // sin_port
buffer.put(Arrays.copyOf(address.getAddress(), 4));
buffer.put(new byte[8]); // __pad
buffer.order(ByteOrder.BIG_ENDIAN);
buffer.putInt(0); // ai_canonname
} else if (sdk == 23) {
buffer.order(ByteOrder.BIG_ENDIAN);
buffer.putInt(1); // sizeof(struct addrinfo)
buffer.putInt(ai_flags);
buffer.putInt(SocketIO.AF_INET);
buffer.putInt(ai_socktype);
buffer.putInt(SocketIO.IPPROTO_TCP);
buffer.putInt(16); // ai_addrlen
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putShort((short) SocketIO.AF_INET); // sin_family
buffer.putShort(Short.reverseBytes(port)); // sin_port
buffer.put(Arrays.copyOf(address.getAddress(), 4));
buffer.put(new byte[8]); // __pad
buffer.order(ByteOrder.BIG_ENDIAN);
buffer.putInt(0); // ai_canonname
} else {
throw new IllegalStateException("sdk=" + sdk);
}
}
} |
String[] tokens = command.split("\\s");
String hostname = tokens[1];
String servername = tokens[2];
short port = 0;
if (!"^".equals(servername)) {
try {
port = Short.parseShort(servername);
} catch (NumberFormatException ignored) {
}
}
int ai_flags = Integer.parseInt(tokens[3]);
int ai_family = Integer.parseInt(tokens[4]);
int ai_socktype = Integer.parseInt(tokens[5]);
int ai_protocol = Integer.parseInt(tokens[6]);
ByteBuffer buffer = ByteBuffer.allocate(1024);
try {
InetAddress[] addresses = InetAddress.getAllByName(hostname);
if (log.isDebugEnabled()) {
log.debug("getaddrinfo hostname=" + hostname + ", servername=" + servername + ", addresses=" + Arrays.toString(addresses) + ", ai_flags=" + ai_flags + ", ai_family=" + ai_family + ", ai_socktype=" + ai_socktype + ", ai_protocol=" + ai_protocol);
}
buffer.put((DnsProxyQueryResult + "\0").getBytes());
for (InetAddress address : addresses) {
putAddress(buffer, address, ai_flags, ai_socktype, port);
}
buffer.order(ByteOrder.BIG_ENDIAN);
buffer.putInt(0); // NULL-terminated
} catch (UnknownHostException e) {
final int EAI_NODATA = 7;
buffer.put((DnsProxyOperationFailed + "\0").getBytes());
buffer.putInt(4);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(EAI_NODATA);
}
buffer.flip();
byte[] response = new byte[buffer.remaining()];
buffer.get(response);
if (log.isDebugEnabled()) {
Inspector.inspect(response, "getaddrinfo");
}
return response;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/file/DriverFileIO.java | DriverFileIO | androidAlarm | class DriverFileIO extends BaseAndroidFileIO implements NewFileIO, AndroidFileIO {
private static final Log log = LogFactory.getLog(DriverFileIO.class);
public static DriverFileIO create(Emulator<?> emulator, int oflags, String pathname) {
if ("/dev/urandom".equals(pathname) || "/dev/random".equals(pathname) || "/dev/srandom".equals(pathname)) {
return new RandomFileIO(emulator, pathname);
}
if ("/dev/alarm".equals(pathname) || "/dev/null".equals(pathname)) {
return new DriverFileIO(emulator, oflags, pathname);
}
if ("/dev/ashmem".equals(pathname)) {
return new Ashmem(emulator, oflags, pathname);
}
if ("/dev/zero".equals(pathname)) {
return new ZeroFileIO(emulator, oflags, pathname);
}
return null;
}
private final Emulator<?> emulator;
private final String path;
DriverFileIO(Emulator<?> emulator, int oflags, String path) {
super(oflags);
this.emulator = emulator;
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();
}
private static final int _IOC_NRBITS = 8;
private static final int _IOC_TYPEBITS = 8;
private static final int _IOC_SIZEBITS = 14;
private enum AndroidAlarmType {
ANDROID_ALARM_RTC_WAKEUP,
ANDROID_ALARM_RTC,
ANDROID_ALARM_ELAPSED_REALTIME_WAKEUP,
ANDROID_ALARM_ELAPSED_REALTIME,
ANDROID_ALARM_SYSTEMTIME,
ANDROID_ALARM_TYPE_COUNT;
static AndroidAlarmType valueOf(long type) {
for (AndroidAlarmType alarmType : values()) {
if (alarmType.ordinal() == type) {
return alarmType;
}
}
throw new IllegalArgumentException("type=" + type);
}
}
@Override
public int ioctl(Emulator<?> emulator, long request, long argp) {
if ("/dev/alarm".equals(path)) {
long ioc = request;
long nr = ioc & 0xff;
ioc >>= _IOC_NRBITS;
long type = ioc & 0xff;
ioc >>= _IOC_TYPEBITS;
long size = ioc & 0x3fff;
ioc >>= _IOC_SIZEBITS;
long dir = ioc;
if (type == 'a') {
long c = nr & 0xf;
type = nr >> 4;
return androidAlarm(dir, c, AndroidAlarmType.valueOf(type), size, argp);
}
log.info("alarm ioctl request=0x" + Long.toHexString(request) + ", argp=0x" + Long.toHexString(argp) + ", nr=" + nr + ", type=" + type + ", size=" + size + ", dir=" + dir);
return -1;
}
return super.ioctl(emulator, request, argp);
}
private static final int _IOC_WRITE = 1;
private static final int _IOC_READ = 2;
private static final int ANDROID_ALARM_GET_TIME = 4;
private int androidAlarm(long dir, long c, AndroidAlarmType type, long size, long argp) {<FILL_FUNCTION_BODY>}
@Override
public int fstat(Emulator<?> emulator, com.github.unidbg.file.linux.StatStructure stat) {
stat.st_blksize = emulator.getPageAlign();
stat.pack();
return 0;
}
@Override
public int getdents64(Pointer dirp, int size) {
throw new UnsupportedOperationException(path);
}
@Override
public String toString() {
return path;
}
} |
if (dir == _IOC_WRITE && c == ANDROID_ALARM_GET_TIME && type == AndroidAlarmType.ANDROID_ALARM_ELAPSED_REALTIME) {
long offset = System.currentTimeMillis();
long tv_sec = offset / 1000000000L;
long tv_nsec = offset % 1000000000L;
Pointer pointer = UnidbgPointer.pointer(emulator, argp);
if (pointer == null) {
throw new IllegalArgumentException();
}
if (size == 8) {
pointer.setInt(0, (int) tv_sec);
pointer.setInt(4, (int) tv_nsec);
return 0;
} else if (size == 16) {
pointer.setLong(0, tv_sec);
pointer.setLong(8, tv_nsec);
return 0;
} else {
throw new IllegalArgumentException("size=" + size);
}
}
log.info("androidAlarm argp=0x" + Long.toHexString(argp) + ", c=" + c + ", type=" + type + ", size=" + size + ", dir=" + dir);
return -1;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/file/DumpFileIO.java | DumpFileIO | write | class DumpFileIO extends BaseAndroidFileIO implements AndroidFileIO {
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, com.github.unidbg.file.linux.StatStructure stat) {
throw new UnsupportedOperationException();
}
@Override
public int getdents64(Pointer dirp, int size) {
throw new UnsupportedOperationException();
}
} |
Inspector.inspect(data, "Dump for fd: " + fd);
return data.length;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/file/EventFD.java | EventFD | write | class EventFD extends BaseAndroidFileIO implements NewFileIO {
private static final Log log = LogFactory.getLog(EventFD.class);
private final boolean semaphore;
private final boolean nonblock;
private long counter;
public EventFD(int initval, boolean semaphore, boolean nonblock) {
super(IOConstants.O_RDWR);
this.counter = initval;
this.semaphore = semaphore;
this.nonblock = nonblock;
}
@Override
public int read(Backend backend, Pointer buffer, int count) {
if (count != 8) {
return super.read(backend, buffer, count);
}
if (counter == 0) {
if (nonblock) {
return -1;
} else {
throw new UnsupportedOperationException();
}
}
if (semaphore) {
buffer.setLong(0, 1);
counter--;
} else {
buffer.setLong(0, counter);
counter = 0;
}
return 8;
}
@Override
public int write(byte[] data) {<FILL_FUNCTION_BODY>}
@Override
public void close() {
}
} |
if (data.length != 8) {
return super.write(data);
}
ByteBuffer buffer = ByteBuffer.wrap(data);
buffer.order(ByteOrder.LITTLE_ENDIAN);
long cnt = buffer.getLong();
counter += cnt;
if (log.isDebugEnabled()) {
log.debug("write cnt=" + cnt + ", counter=" + counter);
}
return 8;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/file/LocalAndroidUdpSocket.java | LocalAndroidUdpSocket | connect | class LocalAndroidUdpSocket extends LocalUdpSocket implements AndroidFileIO {
private static final Log log = LogFactory.getLog(LocalAndroidUdpSocket.class);
public LocalAndroidUdpSocket(Emulator<?> emulator) {
super(emulator);
}
@Override
protected int connect(String path) {<FILL_FUNCTION_BODY>}
} |
if ("/dev/socket/logdw".equals(path)) {
handler = new UdpHandler() {
private static final int LOG_ID_MAIN = 0;
private static final int LOG_ID_RADIO = 1;
private static final int LOG_ID_EVENTS = 2;
private static final int LOG_ID_SYSTEM = 3;
private static final int LOG_ID_CRASH = 4;
private static final int LOG_ID_KERNEL = 5;
private final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
@Override
public void handle(byte[] request) {
try {
byteArrayOutputStream.write(request);
if (byteArrayOutputStream.size() <= 11) {
return;
}
int tagIndex = -1;
int bodyIndex = -1;
byte[] body = byteArrayOutputStream.toByteArray();
ByteBuffer buffer = ByteBuffer.wrap(body);
buffer.order(ByteOrder.LITTLE_ENDIAN);
int id = buffer.get() & 0xff;
int tid = buffer.getShort() & 0xffff;
int tv_sec = buffer.getInt();
int tv_nsec = buffer.getInt();
if (log.isDebugEnabled()) {
log.debug("handle id=" + id + ", tid=" + tid + ", tv_sec=" + tv_sec + ", tv_nsec=" + tv_nsec);
}
String type;
switch (id) {
case LOG_ID_MAIN:
type = "main";
break;
case LOG_ID_RADIO:
type = "radio";
break;
case LOG_ID_EVENTS:
type = "events";
break;
case LOG_ID_SYSTEM:
type = "system";
break;
case LOG_ID_CRASH:
type = "crash";
break;
case LOG_ID_KERNEL:
type = "kernel";
break;
default:
type = Integer.toString(id);
break;
}
for (int i = 12; i < body.length; i++) {
if (body[i] != 0) {
continue;
}
if (tagIndex == -1) {
tagIndex = i;
continue;
}
bodyIndex = i;
break;
}
if (tagIndex != -1 && bodyIndex != -1) {
byteArrayOutputStream.reset();
int value = body[11] & 0xff;
String tag = new String(body, 12, tagIndex - 12);
String text = new String(body, tagIndex + 1, bodyIndex - tagIndex - 1);
LogCatLevel level = LogCatLevel.valueOf(value);
LinuxFileSystem fileSystem = (LinuxFileSystem) emulator.getFileSystem();
LogCatHandler handler = fileSystem.getLogCatHandler();
if (handler != null) {
handler.handleLog(type, level, tag, text);
} else {
System.err.printf("[%s]%s/%s: %s%n", type, level, tag, text);
}
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
};
return 0;
}
emulator.getMemory().setErrno(UnixEmulator.EPERM);
return -1;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/file/LocalSocketIO.java | LocalSocketIO | read | class LocalSocketIO extends SocketIO implements FileIO {
private static final Log log = LogFactory.getLog(LocalSocketIO.class);
public interface SocketHandler {
byte[] handle(byte[] request) throws IOException;
int fstat(StatStructure stat);
}
private final Emulator<?> emulator;
private final int sdk;
public LocalSocketIO(Emulator<?> emulator, int sdk) {
this.emulator = emulator;
this.sdk = sdk;
}
@Override
public void close() {
response = null;
handler = null;
}
private byte[] response;
@Override
public int write(byte[] data) {
try {
byte[] response = handler.handle(data);
if (response != null) {
this.response = response;
}
return data.length;
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public int read(Backend backend, Pointer buffer, int count) {<FILL_FUNCTION_BODY>}
@Override
public int fstat(Emulator<?> emulator, StatStructure stat) {
return handler.fstat(stat);
}
@Override
protected InetSocketAddress getLocalSocketAddress() {
throw new AbstractMethodError();
}
private SocketHandler handler;
protected SocketHandler resolveHandler(String path) {
if ("/dev/socket/dnsproxyd".equals(path)) {
return new DnsProxyDaemon(sdk);
}
return null;
}
@Override
public final int connect(final Pointer addr, int addrlen) {
short sa_family = addr.getShort(0);
if (sa_family != AF_LOCAL) {
throw new UnsupportedOperationException("sa_family=" + sa_family);
}
String path = new String(addr.getByteArray(2, addrlen - 2), StandardCharsets.UTF_8).trim();
if (log.isDebugEnabled()) {
log.debug("connect sa_family=" + sa_family + ", path=" + path);
}
handler = resolveHandler(path);
if (handler != null) {
return 0;
} else {
emulator.getMemory().setErrno(UnixEmulator.EPERM);
return -1;
}
}
@Override
public int bind(Pointer addr, int addrlen) {
if (log.isDebugEnabled()) {
log.debug(Inspector.inspectString(addr.getByteArray(0, addrlen), "bind addrlen=" + addrlen));
}
emulator.getMemory().setErrno(UnixEmulator.EPERM);
return -1;
}
@Override
protected int connect_ipv6(Pointer addr, int addrlen) {
throw new AbstractMethodError();
}
@Override
protected int connect_ipv4(Pointer addr, int addrlen) {
throw new AbstractMethodError();
}
@Override
protected void setReuseAddress(int reuseAddress) {
}
@Override
protected void setKeepAlive(int keepAlive) {
throw new AbstractMethodError();
}
@Override
protected void setSendBufferSize(int size) {
throw new AbstractMethodError();
}
@Override
protected void setReceiveBufferSize(int size) {
throw new AbstractMethodError();
}
@Override
protected void setTcpNoDelay(int tcpNoDelay) {
throw new AbstractMethodError();
}
@Override
protected int getTcpNoDelay() {
throw new AbstractMethodError();
}
} |
if (response == null) {
throw new IllegalStateException("response is null");
}
if (response.length <= count) {
buffer.write(0, response, 0, response.length);
int ret = response.length;
response = null;
return ret;
} else {
buffer.write(0, Arrays.copyOf(response, count), 0, count);
byte[] temp = new byte[response.length - count];
System.arraycopy(response, count, temp, 0, temp.length);
response = temp;
return count;
}
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/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 setSendBufferSize(int size) {
throw new AbstractMethodError();
}
@Override
protected void setReceiveBufferSize(int size) {
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-android/src/main/java/com/github/unidbg/linux/file/LogCatFileIO.java | LogCatFileIO | write | class LogCatFileIO extends SimpleFileIO {
private static final Log log = LogFactory.getLog(LogCatFileIO.class);
public static final String LOG_PATH_PREFIX = "/dev/log/";
private final Emulator<?> emulator;
private final String type;
public LogCatFileIO(Emulator<?> emulator, int oflags, File file, String path) {
super(oflags, file, path);
this.emulator = emulator;
this.type = path.substring(LOG_PATH_PREFIX.length());
if (log.isDebugEnabled()) {
setDebugStream(System.out);
}
}
@Override
void onFileOpened(RandomAccessFile randomAccessFile) throws IOException {
super.onFileOpened(randomAccessFile);
randomAccessFile.getChannel().truncate(0);
}
private final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
@Override
public int write(byte[] data) {<FILL_FUNCTION_BODY>}
} |
try {
byteArrayOutputStream.write(data);
if (byteArrayOutputStream.size() <= 1) {
return data.length;
}
int tagIndex = -1;
int bodyIndex = -1;
byte[] body = byteArrayOutputStream.toByteArray();
for (int i = 1; i < body.length; i++) {
if (body[i] != 0) {
continue;
}
if (tagIndex == -1) {
tagIndex = i;
continue;
}
bodyIndex = i;
break;
}
if (tagIndex != -1 && bodyIndex != -1) {
byteArrayOutputStream.reset();
int level = body[0] & 0xff;
String tag = new String(body, 1, tagIndex - 1);
String text = new String(body, tagIndex + 1, bodyIndex - tagIndex - 1);
LogCatLevel value = LogCatLevel.valueOf(level);
super.write(String.format("%s/%s: %s\n", value, tag, text).getBytes());
LinuxFileSystem fileSystem = (LinuxFileSystem) emulator.getFileSystem();
LogCatHandler handler = fileSystem.getLogCatHandler();
if (handler != null) {
handler.handleLog(type, value, tag, text);
}
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
return data.length;
|
zhkl0228_unidbg | unidbg/unidbg-android/src/main/java/com/github/unidbg/linux/file/MapsFileIO.java | MapsFileIO | getMapsData | class MapsFileIO extends ByteArrayFileIO implements FileIO {
private static final Log log = LogFactory.getLog(MapsFileIO.class);
public MapsFileIO(Emulator<?> emulator, int oflags, String path, Collection<Module> modules) {
super(oflags, path, getMapsData(emulator, modules, null));
}
@SuppressWarnings("unused")
protected MapsFileIO(Emulator<?> emulator, int oflags, String path, Collection<Module> modules, String additionContent) {
this(oflags, path, getMapsData(emulator, modules, additionContent));
}
protected MapsFileIO(int oflags, String path, byte[] bytes) {
super(oflags, path, bytes);
}
protected static byte[] getMapsData(Emulator<?> emulator, Collection<Module> modules, String additionContent) {<FILL_FUNCTION_BODY>}
private static class MapItem {
private final long start;
private final long end;
private final int perms;
private final int offset;
private final String device;
private final String label;
public MapItem(long start, long end, int perms, int offset, String device, String label) {
this.start = start;
this.end = end;
this.perms = perms;
this.offset = offset;
this.device = device;
this.label = label;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(String.format("%08x-%08x", start, end)).append(' ');
if ((perms & UnicornConst.UC_PROT_READ) != 0) {
builder.append('r');
} else {
builder.append('-');
}
if ((perms & UnicornConst.UC_PROT_WRITE) != 0) {
builder.append('w');
} else {
builder.append('-');
}
if ((perms & UnicornConst.UC_PROT_EXEC) != 0) {
builder.append('x');
} else {
builder.append('-');
}
builder.append("p ");
builder.append(String.format("%08x", offset));
builder.append(" ").append(device).append(" 0");
for (int i = 0; i < 10; i++) {
builder.append(' ');
}
builder.append(label);
builder.append('\n');
return builder.toString();
}
}
@Override
public int ioctl(Emulator<?> emulator, long request, long argp) {
return 0;
}
} |
List<MemRegion> list = new ArrayList<>(modules.size());
for (Module module : modules) {
list.addAll(module.getRegions());
}
Collections.sort(list);
List<MapItem> items = new ArrayList<>();
for (MemRegion memRegion : list) {
items.add(new MapItem(memRegion.virtualAddress, memRegion.end, memRegion.perms, 0, "b3:19", memRegion.getName()));
}
long stackSize = (long) Memory.STACK_SIZE_OF_PAGE * emulator.getPageAlign();
items.add(new MapItem(Memory.STACK_BASE - stackSize, Memory.STACK_BASE, UnicornConst.UC_PROT_WRITE | UnicornConst.UC_PROT_READ, 0, "00:00", "[stack]"));
List<MapItem> mapItems = new ArrayList<>();
for (MemoryMap memoryMap : emulator.getMemory().getMemoryMap()) {
boolean contains = false;
for (MapItem item : items) {
if (Math.max(memoryMap.base, item.start) <= Math.min(memoryMap.base + memoryMap.size, item.end)) {
contains = true;
break;
}
}
if (!contains) {
mapItems.add(new MapItem(memoryMap.base, memoryMap.base + memoryMap.size, memoryMap.prot, 0, "00:00", "anonymous"));
}
}
items.addAll(mapItems);
StringBuilder builder = new StringBuilder();
for (MapItem item : items) {
builder.append(item);
}
if (additionContent != null) {
builder.append(additionContent).append('\n');
}
if (log.isDebugEnabled()) {
log.debug("\n" + builder);
}
return builder.toString().getBytes();
|
End of preview. Expand
in Dataset Viewer.
No dataset card yet
New: Create and edit this dataset card directly on the website!
Contribute a Dataset Card- Downloads last month
- 11