bool IOGUIDPartitionScheme::isPartitionInvalid( gpt_ent * partition,
                                                UInt32    partitionID )
{
    //
    // Ask whether the given partition appears to be invalid.  A partition that
    // is invalid will cause it to be skipped in the scan, but will not cause a
    // failure of the GUID partition map recognition.
    //

    IOMedia * media          = getProvider();
    UInt64    mediaBlockSize = media->getPreferredBlockSize();
    UInt64    partitionBase  = 0;
    UInt64    partitionSize  = 0;

    // Compute the relative byte position and size of the new partition.

    partitionBase  = OSSwapLittleToHostInt64(partition->ent_lba_start);
    partitionSize  = OSSwapLittleToHostInt64(partition->ent_lba_end);
    partitionBase *= mediaBlockSize;
    partitionSize *= mediaBlockSize;

    // Determine whether the partition is a placeholder.

    if ( partitionBase == partitionSize )  return true;

    // Compute the relative byte position and size of the new partition.

    partitionSize -= partitionBase - mediaBlockSize;

    // Determine whether the new partition leaves the confines of the container.

    if ( partitionBase + partitionSize > media->getSize() )  return true;

    return false;
}
IOMedia * IOGUIDPartitionScheme::instantiateMediaObject( gpt_ent * partition,
                                                         UInt32    partitionID )
{
    //
    // Instantiate a new media object to represent the given partition.
    //

    IOMedia *     media          = getProvider();
    UInt64        mediaBlockSize = media->getPreferredBlockSize();
    UInt64        partitionBase  = 0;
    uuid_string_t partitionHint;
    char          partitionName[36 * 3 + 1];
    UInt64        partitionSize  = 0;

    ucs2_to_utf8( partition->ent_name,
                  sizeof(partition->ent_name),
                  partitionName,
                  sizeof(partitionName),
                  UCS_LITTLE_ENDIAN );

    uuid_unparse( partition->ent_type,
                  partitionHint );

    // Compute the relative byte position and size of the new partition.

    partitionBase  = OSSwapLittleToHostInt64(partition->ent_lba_start);
    partitionSize  = OSSwapLittleToHostInt64(partition->ent_lba_end);
    partitionBase *= mediaBlockSize;
    partitionSize *= mediaBlockSize;
    partitionSize -= partitionBase - mediaBlockSize;

    // Create the new media object.

    IOMedia * newMedia = instantiateDesiredMediaObject(
                                   /* partition   */ partition,
                                   /* partitionID */ partitionID );

    if ( newMedia )
    {
         if ( newMedia->init(
                /* base               */ partitionBase,
                /* size               */ partitionSize,
                /* preferredBlockSize */ mediaBlockSize,
                /* attributes         */ media->getAttributes(),
                /* isWhole            */ false,
                /* isWritable         */ media->isWritable(),
                /* contentHint        */ partitionHint ) )
        {
            // Set a name for this partition.

            char name[24];
            snprintf(name, sizeof(name), "Untitled %d", (int) partitionID);
            newMedia->setName(partitionName[0] ? partitionName : name);

            // Set a location value (the partition number) for this partition.

            char location[12];
            snprintf(location, sizeof(location), "%d", (int) partitionID);
            newMedia->setLocation(location);

            // Set the "Base" key for this partition.

            newMedia->setProperty(kIOMediaBaseKey, partitionBase, 64);
            
            // Set the "Partition ID" key for this partition.

            newMedia->setProperty(kIOMediaPartitionIDKey, partitionID, 32);

            // Set the "Universal Unique ID" key for this partition.

            uuid_string_t uuid;
            uuid_unparse(partition->ent_uuid, uuid);
            newMedia->setProperty(kIOMediaUUIDKey, uuid);
        }
        else
        {
            newMedia->release();
            newMedia = 0;
        }
    }

    return newMedia;
}
Exemplo n.º 3
0
BVRef diskScanGPTBootVolumes(int biosdev, int * countPtr)
{
    _DISK_DEBUG_DUMP("In diskScanGPTBootVolumes(%d)\n", biosdev);

    void *buffer = malloc(BPS);

    if (readBytes(biosdev, 1, 0, BPS, buffer) == 0)
    {
        int gptID = 1;

        gpt_ent * gptMap = 0;
        gpt_hdr * headerMap = buffer;

        // Partition header signature present?
        if (memcmp(headerMap->hdr_sig, GPT_HDR_SIG, strlen(GPT_HDR_SIG)) == 0)
        {
            UInt32 headerSize = OSSwapLittleToHostInt32(headerMap->hdr_size);

            // Valid partition header size?
            if (headerSize >= offsetof(gpt_hdr, padding))
            {
                // No header size overrun (limiting to 512 bytes)?
                if (headerSize <= BPS)
                {
                    UInt32 headerCheck = OSSwapLittleToHostInt32(headerMap->hdr_crc_self);

                    headerMap->hdr_crc_self = 0;

                    // Valid partition header checksum?
                    if (crc32(0, headerMap, headerSize) == headerCheck)
                    {
                        UInt64	gptBlock = OSSwapLittleToHostInt64(headerMap->hdr_lba_table);
                        UInt32	gptCount = OSSwapLittleToHostInt32(headerMap->hdr_entries);
                        UInt32	gptSize  = OSSwapLittleToHostInt32(headerMap->hdr_entsz);

                        free(buffer);

                        if (gptSize >= sizeof(gpt_ent))
                        {
                            UInt32 bufferSize = IORound(gptCount * gptSize, BPS);

                            buffer = malloc(bufferSize); // Allocate a buffer.

                            if (readBytes(biosdev, gptBlock, 0, bufferSize, buffer) == 0)
                            {
                                // Allocate a new map for this device and insert it into the chain.
                                struct DiskBVMap *map = malloc(sizeof(*map));

                                map->biosdev	= biosdev;
                                map->bvr		= NULL;
                                map->bvrcnt		= 0;
                                map->next		= gDiskBVMap;
                                gDiskBVMap		= map;

                                for (; gptID <= gptCount; gptID++)
                                {
                                    gptMap = (gpt_ent *) (buffer + ((gptID - 1) * gptSize));

                                    if (isPartitionUsed(gptMap))
                                    {
                                        BVRef bvr = NULL;
                                        int bvrFlags = -1;
#if DEBUG_DISK
                                        char stringuuid[100];
                                        efi_guid_unparse_upper((EFI_GUID*)gptMap->ent_type, stringuuid);
                                        printf("Reading GPT partition %d, type %s\n", gptID, stringuuid);
                                        sleep(1);
#endif

                                        if (efi_guid_compare(&GPT_HFS_GUID, (EFI_GUID const *)gptMap->ent_type) == 0)
                                        {
                                            _DISK_DEBUG_DUMP("Matched: GPT_HFS_GUID\n");

                                            bvrFlags = kBVFlagZero;
                                        }
                                        /* else if (efi_guid_compare(&GPT_BOOT_GUID, (EFI_GUID const *)gptMap->ent_type) == 0)
                                        {
                                        	_DISK_DEBUG_DUMP("Matched: GPT_BOOT_GUID\n");

                                        	bvrFlags = kBVFlagBooter;
                                        } */
#if EFI_SYSTEM_PARTITION_SUPPORT
                                        else if (efi_guid_compare(&GPT_EFISYS_GUID, (EFI_GUID const *)gptMap->ent_type) == 0)
                                        {
                                            _DISK_DEBUG_DUMP("Matched: GPT_EFISYS_GUID, probing for HFS format...\n");

                                            //-------------- START -------------
                                            // Allocate buffer for 4 sectors.
                                            void * probeBuffer = malloc(2048);

                                            bool probeOK = false;

                                            // Read the first 4 sectors.
                                            if (readBytes(biosdev, gptMap->ent_lba_start, 0, 2048, (void *)probeBuffer) == 0)
                                            {
                                                //  Probing (returns true for HFS partitions).
                                                probeOK = HFSProbe(probeBuffer);

                                                _DISK_DEBUG_DUMP("HFSProbe status: Is %s a HFS partition.\n", probeOK ? "" : "not");

                                            }

                                            free(probeBuffer);

                                            // Veto non-HFS partitions to be invalid.
                                            if (!probeOK)
                                            {
                                                continue;
                                            }

                                            //-------------- END ---------------

                                            bvrFlags = kBVFlagEFISystem;
                                        }
#endif
                                        // Only true when we found a usable partition.
                                        if (bvrFlags >= 0)
                                        {
                                            bvr = newGPTBVRef(biosdev, gptID, gptMap->ent_lba_start, gptMap, bvrFlags);

                                            if (bvr)
                                            {
                                                bvr->part_type = FDISK_HFS;
                                                bvr->next = map->bvr;
                                                map->bvr = bvr;
                                                ++map->bvrcnt;

                                                // Don't waste time checking for boot.efi on ESP partitions.
                                                if ((bvrFlags & kBVFlagEFISystem) == 0)
                                                {
                                                    // Flag System Volumes with kBVFlagSystemVolume.
                                                    hasBootEFI(bvr);
                                                }

                                                // True on the initial run only.
                                                if (gPlatform.BootVolume == NULL)
                                                {
                                                    // Initialize with the first bootable volume.
                                                    gPlatform.BootVolume = gPlatform.RootVolume = bvr;

                                                    _DISK_DEBUG_DUMP("Init B/RootVolume - partition: %d, flags: %d, gptID: %d\n", bvr->part_no, bvr->flags, gptID);
                                                }

                                                // Bail out after finding the first System Volume.
                                                if (bvr->flags & kBVFlagSystemVolume)
                                                {
                                                    _DISK_DEBUG_DUMP("Partition %d is a System Volume\n", gptID);

                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }

                                free(buffer);
                                *countPtr = map->bvrcnt;

                                _DISK_DEBUG_DUMP("map->bvrcnt: %d\n", map->bvrcnt);
                                _DISK_DEBUG_SLEEP(5);

                                return map->bvr;
                            }
                        }
                    }
                }
            }
        }
    }

    free(buffer);
    *countPtr = 0;

    _DISK_DEBUG_SLEEP(5);

    return NULL;
}
OSSet * IOGUIDPartitionScheme::scan(SInt32 * score)
{
    //
    // Scan the provider media for a GUID partition map.    Returns the set
    // of media objects representing each of the partitions (the retain for
    // the set is passed to the caller), or null should no partition map be
    // found.  The default probe score can be adjusted up or down, based on
    // the confidence of the scan.
    //

    IOBufferMemoryDescriptor * buffer         = 0;
    IOByteCount                bufferSize     = 0;
    UInt32                     fdiskID        = 0;
    disk_blk0 *                fdiskMap       = 0;
    UInt64                     gptBlock       = 0;
    UInt32                     gptCheck       = 0;
    UInt32                     gptCount       = 0;
    UInt32                     gptID          = 0;
    gpt_ent *                  gptMap         = 0;
    UInt32                     gptSize        = 0;
    UInt32                     headerCheck    = 0;
    gpt_hdr *                  headerMap      = 0;
    UInt32                     headerSize     = 0;
    IOMedia *                  media          = getProvider();
    UInt64                     mediaBlockSize = media->getPreferredBlockSize();
    bool                       mediaIsOpen    = false;
    OSSet *                    partitions     = 0;
    IOReturn                   status         = kIOReturnError;

    // Determine whether this media is formatted.

    if ( media->isFormatted() == false )  goto scanErr;

    // Determine whether this media has an appropriate block size.

    if ( (mediaBlockSize % sizeof(disk_blk0)) )  goto scanErr;

    // Allocate a buffer large enough to hold one map, rounded to a media block.

    bufferSize = IORound(sizeof(disk_blk0), mediaBlockSize);
    buffer     = IOBufferMemoryDescriptor::withCapacity(
                                           /* capacity      */ bufferSize,
                                           /* withDirection */ kIODirectionIn );
    if ( buffer == 0 )  goto scanErr;

    // Allocate a set to hold the set of media objects representing partitions.

    partitions = OSSet::withCapacity(8);
    if ( partitions == 0 )  goto scanErr;

    // Open the media with read access.

    mediaIsOpen = open(this, 0, kIOStorageAccessReader);
    if ( mediaIsOpen == false )  goto scanErr;

    // Read the protective map into our buffer.

    status = media->read(this, 0, buffer);
    if ( status != kIOReturnSuccess )  goto scanErr;

    fdiskMap = (disk_blk0 *) buffer->getBytesNoCopy();

    // Determine whether the protective map signature is present.

    if ( OSSwapLittleToHostInt16(fdiskMap->signature) != DISK_SIGNATURE )
    {
         goto scanErr;
    }

    // Scan for valid partition entries in the protective map.

    for ( unsigned index = 0; index < DISK_NPART; index++ )
    {
        if ( fdiskMap->parts[index].systid )
        {
            if ( fdiskMap->parts[index].systid == 0xEE )
            {
                if ( fdiskID )  goto scanErr;

                fdiskID = index + 1;
            }
        }
    }

    if ( fdiskID == 0 )  goto scanErr;

    // Read the partition header into our buffer.

    status = media->read(this, mediaBlockSize, buffer);
    if ( status != kIOReturnSuccess )  goto scanErr;

    headerMap = (gpt_hdr *) buffer->getBytesNoCopy();

    // Determine whether the partition header signature is present.

    if ( memcmp(headerMap->hdr_sig, GPT_HDR_SIG, strlen(GPT_HDR_SIG)) )
    {
        goto scanErr;
    }

    // Determine whether the partition header size is valid.

    headerCheck = OSSwapLittleToHostInt32(headerMap->hdr_crc_self);
    headerSize  = OSSwapLittleToHostInt32(headerMap->hdr_size);

    if ( headerSize < offsetof(gpt_hdr, padding) )
    {
        goto scanErr;
    }

    if ( headerSize > mediaBlockSize )
    {
        goto scanErr;
    }

    // Determine whether the partition header checksum is valid.

    headerMap->hdr_crc_self = 0;

    if ( crc32(0, headerMap, headerSize) != headerCheck )
    {
        goto scanErr;
    }

    // Determine whether the partition entry size is valid.

    gptCheck = OSSwapLittleToHostInt32(headerMap->hdr_crc_table);
    gptSize  = OSSwapLittleToHostInt32(headerMap->hdr_entsz);

    if ( gptSize < sizeof(gpt_ent) )
    {
        goto scanErr;
    }

    if ( gptSize > UINT16_MAX )
    {
        goto scanErr;
    }

    // Determine whether the partition entry count is valid.

    gptBlock = OSSwapLittleToHostInt64(headerMap->hdr_lba_table);
    gptCount = OSSwapLittleToHostInt32(headerMap->hdr_entries);

    if ( gptCount > UINT16_MAX )
    {
        goto scanErr;
    }

    // Allocate a buffer large enough to hold one map, rounded to a media block.

    buffer->release();

    bufferSize = IORound(gptCount * gptSize, mediaBlockSize);
    buffer     = IOBufferMemoryDescriptor::withCapacity(
                                           /* capacity      */ bufferSize,
                                           /* withDirection */ kIODirectionIn );
    if ( buffer == 0 )  goto scanErr;

    // Read the partition header into our buffer.

    status = media->read(this, gptBlock * mediaBlockSize, buffer);
    if ( status != kIOReturnSuccess )  goto scanErr;

    gptMap = (gpt_ent *) buffer->getBytesNoCopy();

    // Determine whether the partition entry checksum is valid.

    if ( crc32(0, gptMap, gptCount * gptSize) != gptCheck )
    {
        goto scanErr;
    }

    // Scan for valid partition entries in the partition map.

    for ( gptID = 1; gptID <= gptCount; gptID++ )
    {
        gptMap = (gpt_ent *) ( ((UInt8 *) buffer->getBytesNoCopy()) +
                               (gptID * gptSize) - gptSize );

        uuid_unswap( gptMap->ent_type );
        uuid_unswap( gptMap->ent_uuid );
 
        if ( isPartitionUsed( gptMap ) )
        {
            // Determine whether the partition is corrupt (fatal).

            if ( isPartitionCorrupt( gptMap, gptID ) )
            {
                goto scanErr;
            }

            // Determine whether the partition is invalid (skipped).

            if ( isPartitionInvalid( gptMap, gptID ) )
            {
                continue;
            }

            // Create a media object to represent this partition.

            IOMedia * newMedia = instantiateMediaObject( gptMap, gptID );

            if ( newMedia )
            {
                partitions->setObject(newMedia);
                newMedia->release();
            }
        }
    }

    // Release our resources.

    close(this);
    buffer->release();

    return partitions;

scanErr:

    // Release our resources.

    if ( mediaIsOpen )  close(this);
    if ( partitions )  partitions->release();
    if ( buffer )  buffer->release();

    return 0;
}
Exemplo n.º 5
0
uint64_t fmle64(uint64_t x) { return OSSwapLittleToHostInt64(x); }