1 /*
2  * Copyright (c) 2016-2022, ARM Limited and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include <assert.h>
8 #include <errno.h>
9 #include <string.h>
10 
11 #include <common/debug.h>
12 #include <drivers/partition/efi.h>
13 #include <drivers/partition/gpt.h>
14 #include <lib/utils.h>
15 
unicode_to_ascii(unsigned short * str_in,unsigned char * str_out)16 static int unicode_to_ascii(unsigned short *str_in, unsigned char *str_out)
17 {
18 	uint8_t *name;
19 	int i;
20 
21 	assert((str_in != NULL) && (str_out != NULL));
22 
23 	name = (uint8_t *)str_in;
24 
25 	assert(name[0] != '\0');
26 
27 	/* check whether the unicode string is valid */
28 	for (i = 1; i < (EFI_NAMELEN << 1); i += 2) {
29 		if (name[i] != '\0') {
30 			return -EINVAL;
31 		}
32 	}
33 	/* convert the unicode string to ascii string */
34 	for (i = 0; i < (EFI_NAMELEN << 1); i += 2) {
35 		str_out[i >> 1] = name[i];
36 		if (name[i] == '\0') {
37 			break;
38 		}
39 	}
40 	return 0;
41 }
42 
parse_gpt_entry(gpt_entry_t * gpt_entry,partition_entry_t * entry)43 int parse_gpt_entry(gpt_entry_t *gpt_entry, partition_entry_t *entry)
44 {
45 	int result;
46 
47 	assert((gpt_entry != NULL) && (entry != NULL));
48 
49 	if ((gpt_entry->first_lba == 0) && (gpt_entry->last_lba == 0)) {
50 		return -EINVAL;
51 	}
52 
53 	zeromem(entry, sizeof(partition_entry_t));
54 	result = unicode_to_ascii(gpt_entry->name, (uint8_t *)entry->name);
55 	if (result != 0) {
56 		return result;
57 	}
58 	entry->start = (uint64_t)gpt_entry->first_lba *
59 		       PLAT_PARTITION_BLOCK_SIZE;
60 	entry->length = (uint64_t)(gpt_entry->last_lba -
61 				   gpt_entry->first_lba + 1) *
62 			PLAT_PARTITION_BLOCK_SIZE;
63 	guidcpy(&entry->part_guid, &gpt_entry->unique_uuid);
64 	guidcpy(&entry->type_guid, &gpt_entry->type_uuid);
65 
66 	return 0;
67 }
68