Branch data Line data Source code
1 : : #include <stdint.h>
2 : :
3 : : #include "common.h"
4 : : #include "mbr.h"
5 : :
6 : : #define BOOT_SIGNATURE_OFFSET 0x1FE
7 : : #define MBR_PT_OFFSET 0x1BE
8 : : #define MBR_PT_SIZE 16
9 : : #define MBR_TYPE_OFF 4
10 : : #define MBR_LBA_OFF 8
11 : :
12 : 5 : w_status_t mbr_parse(uint8_t *first_sector, uint8_t partition_type, uint32_t *sector_lba) {
13 [ + + ]: 5 : if (!first_sector || !sector_lba) {
14 : : return W_INVALID_PARAM;
15 : : }
16 : :
17 : : // Boot signature starts at 0x01FE in the first sector
18 : : uint8_t *boot_signature = first_sector + BOOT_SIGNATURE_OFFSET;
19 : : // Boot signature check
20 [ + + - + ]: 3 : if (boot_signature[0] != 0x55 || boot_signature[1] != 0xAA) {
21 : : return W_FAILURE;
22 : : }
23 : :
24 : : // Set sector_lba to 0 as default
25 : 2 : *sector_lba = 0;
26 : :
27 : : // First partition entry starts at 0x01BE in the first sector
28 : 2 : uint8_t *entry = first_sector + MBR_PT_OFFSET;
29 : :
30 : : // Each partition entry has a size of 16 bytes
31 [ + + ]: 6 : for (int i = 0; i < 4; i++, entry += MBR_PT_SIZE) {
32 : : // Partition type locates at 0x04 in each partition
33 : 5 : uint8_t type = entry[MBR_TYPE_OFF];
34 [ + + ]: 5 : if (type == partition_type) {
35 : 1 : *sector_lba = (uint32_t)entry[MBR_LBA_OFF] | ((uint32_t)entry[MBR_LBA_OFF + 1] << 8) |
36 : 1 : ((uint32_t)entry[MBR_LBA_OFF + 2] << 16) |
37 : 1 : ((uint32_t)entry[MBR_LBA_OFF + 3] << 24);
38 : 1 : return W_SUCCESS;
39 : : }
40 : : }
41 : : return W_FAILURE;
42 : : }
|