vm_write

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <mach/mach.h>

int write32(vm_address_t offset, unsigned int data) {
  data = CFSwapInt32(data);
  kern_return_t err;
  mach_port_t port = mach_task_self();
  err = vm_protect(port, (vm_address_t) offset, sizeof(data), NO,
                   VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);
  if (err != KERN_SUCCESS) {
    NSLog(@"prot error: %s \n", mach_error_string(err));
    return 0;
  }

  vm_write(port, (vm_address_t) offset, (vm_address_t) & data, sizeof(data));
  err = vm_protect(port, (vm_address_t) offset, sizeof(data), NO,
                   VM_PROT_READ | VM_PROT_EXECUTE);
  if (err != KERN_SUCCESS) {
    NSLog(@"prot error: %s \n", mach_error_string(err));
    return 0;
  }

  NSLog(@"all is well here shipmate");
  return 1;
}

int write16(vm_address_t offset, unsigned short data) {
  data = CFSwapInt16(data);
  kern_return_t err;
  mach_port_t port = mach_task_self();
  err = vm_protect(port, (vm_address_t) offset, sizeof(data), NO,
                   VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);

  if (err != KERN_SUCCESS) {
    NSLog(@"prot error: %s \n", mach_error_string(err));
    return 0;
  }

  vm_write(port, (vm_address_t) offset, (vm_address_t) & data, sizeof(data));
  err = vm_protect(port, (vm_address_t) offset, sizeof(data), NO,
                   VM_PROT_READ | VM_PROT_EXECUTE);
  if (err != KERN_SUCCESS) {
    NSLog(@"prot error: %s \n", mach_error_string(err));
    return 0;
  }

  NSLog(@"all is well here shipmate");
  return 1;
}

bool getType(unsigned int x) {
  int a = x & 0xffff8000;
  int b = a + 0x00008000;
  int c = b & 0xffff7fff;

  return c; //true = 32bit false = 16bit
}

int writeData(vm_address_t offset, unsigned int data) {
  if (getType(data)) {
    write32(offset, data);
  } else {
    write16(offset, (unsigned short) data);
  }

  return 0;
}

 

posted @ 2014-03-28 23:12  Proteas  阅读(1154)  评论(0编辑  收藏  举报