blob: 50d1daf33a979461db4b80069edc2be184581816 [file] [log] [blame]
AKASHI Takahiro94074682020-10-29 13:47:46 +09001// SPDX-License-Identifier: GPL-2.0+
2/*
3 * String functions
4 *
5 * Copyright (c) 2020 AKASHI Takahiro, Linaro Limited
6 */
7
Heinrich Schuchardt955a3212025-01-16 20:26:59 +01008#define LOG_CATEGORY LOGC_EFI
9
AKASHI Takahiro94074682020-10-29 13:47:46 +090010#include <charset.h>
Heinrich Schuchardt476ff2c2021-04-21 12:39:15 +020011#include <efi_loader.h>
Paul Barker8acc3d92022-10-05 13:18:35 +010012#include <malloc.h>
AKASHI Takahiro94074682020-10-29 13:47:46 +090013
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.
Simon Glass90975372022-01-23 12:55:12 -070021 * For example, u"Capsule0001"
AKASHI Takahiro94074682020-10-29 13:47:46 +090022 *
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 */
Ilias Apalodimas21575292020-12-31 12:26:46 +020029u16 *efi_create_indexed_name(u16 *buffer, size_t buffer_size, const char *name,
30 unsigned int index)
AKASHI Takahiro94074682020-10-29 13:47:46 +090031{
32 u16 *p = buffer;
33 char index_buf[5];
Ilias Apalodimas21575292020-12-31 12:26:46 +020034 size_t size;
AKASHI Takahiro94074682020-10-29 13:47:46 +090035
Ilias Apalodimas21575292020-12-31 12:26:46 +020036 size = (utf8_utf16_strlen(name) * sizeof(u16) +
37 sizeof(index_buf) * sizeof(u16));
38 if (buffer_size < size)
39 return NULL;
AKASHI Takahiro94074682020-10-29 13:47:46 +090040 utf8_utf16_strcpy(&p, name);
Ilias Apalodimas21575292020-12-31 12:26:46 +020041 snprintf(index_buf, sizeof(index_buf), "%04X", index);
AKASHI Takahiro94074682020-10-29 13:47:46 +090042 utf8_utf16_strcpy(&p, index_buf);
43
44 return p;
45}
Paul Barker8acc3d92022-10-05 13:18:35 +010046
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}