efi_string.c 1.6 KB

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