"Das U-Boot" Source Tree
1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * String functions
4 *
5 * Copyright (c) 2020 AKASHI Takahiro, Linaro Limited
6 */
7
8#define LOG_CATEGORY LOGC_EFI
9
10#include <charset.h>
11#include <efi_loader.h>
12#include <malloc.h>
13
14/**
15 * efi_create_indexed_name - create a string name with an index
16 * @buffer: Buffer
17 * @name: Name string
18 * @index: Index
19 *
20 * Create a utf-16 string with @name, appending @index.
21 * For example, u"Capsule0001"
22 *
23 * The caller must ensure that the buffer has enough space for the resulting
24 * string including the trailing L'\0'.
25 *
26 * Return: A pointer to the next position after the created string
27 * in @buffer, or NULL otherwise
28 */
29u16 *efi_create_indexed_name(u16 *buffer, size_t buffer_size, const char *name,
30 unsigned int index)
31{
32 u16 *p = buffer;
33 char index_buf[5];
34 size_t size;
35
36 size = (utf8_utf16_strlen(name) * sizeof(u16) +
37 sizeof(index_buf) * sizeof(u16));
38 if (buffer_size < size)
39 return NULL;
40 utf8_utf16_strcpy(&p, name);
41 snprintf(index_buf, sizeof(index_buf), "%04X", index);
42 utf8_utf16_strcpy(&p, index_buf);
43
44 return p;
45}
46
47/**
48 * efi_convert_string - Convert an ASCII or UTF-8 string to UTF-16
49 * @str: String to be converted
50 *
51 * Return: Converted string in UTF-16 format. The caller is responsible for
52 * freeing this string when it is no longer needed.
53 */
54efi_string_t efi_convert_string(const char *str)
55{
56 efi_string_t str_16, tmp;
57 size_t sz_16;
58
59 sz_16 = utf8_utf16_strlen(str);
60 str_16 = calloc(sz_16 + 1, sizeof(u16));
61 if (!str_16)
62 return NULL;
63
64 tmp = str_16;
65 utf8_utf16_strcpy(&tmp, str);
66
67 return str_16;
68}