bh_common.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "bh_common.h"
  6. int
  7. b_memcpy_s(void *s1, unsigned int s1max, const void *s2, unsigned int n)
  8. {
  9. char *dest = (char *)s1;
  10. char *src = (char *)s2;
  11. if (n == 0) {
  12. return 0;
  13. }
  14. if (s1 == NULL) {
  15. return -1;
  16. }
  17. if (s2 == NULL || n > s1max) {
  18. memset(dest, 0, s1max);
  19. return -1;
  20. }
  21. memcpy(dest, src, n);
  22. return 0;
  23. }
  24. int
  25. b_memmove_s(void *s1, unsigned int s1max, const void *s2, unsigned int n)
  26. {
  27. char *dest = (char *)s1;
  28. char *src = (char *)s2;
  29. if (n == 0) {
  30. return 0;
  31. }
  32. if (s1 == NULL) {
  33. return -1;
  34. }
  35. if (s2 == NULL || n > s1max) {
  36. memset(dest, 0, s1max);
  37. return -1;
  38. }
  39. memmove(dest, src, n);
  40. return 0;
  41. }
  42. int
  43. b_strcat_s(char *s1, unsigned int s1max, const char *s2)
  44. {
  45. if (NULL == s1 || NULL == s2 || s1max < (strlen(s1) + strlen(s2) + 1)) {
  46. return -1;
  47. }
  48. memcpy(s1 + strlen(s1), s2, strlen(s2) + 1);
  49. return 0;
  50. }
  51. int
  52. b_strcpy_s(char *s1, unsigned int s1max, const char *s2)
  53. {
  54. if (NULL == s1 || NULL == s2 || s1max < (strlen(s2) + 1)) {
  55. return -1;
  56. }
  57. memcpy(s1, s2, strlen(s2) + 1);
  58. return 0;
  59. }
  60. char *
  61. bh_strdup(const char *s)
  62. {
  63. uint32 size;
  64. char *s1 = NULL;
  65. if (s) {
  66. size = (uint32)(strlen(s) + 1);
  67. if ((s1 = BH_MALLOC(size)))
  68. bh_memcpy_s(s1, size, s, size);
  69. }
  70. return s1;
  71. }
  72. char *
  73. wa_strdup(const char *s)
  74. {
  75. uint32 size;
  76. char *s1 = NULL;
  77. if (s) {
  78. size = (uint32)(strlen(s) + 1);
  79. if ((s1 = WA_MALLOC(size)))
  80. bh_memcpy_s(s1, size, s, size);
  81. }
  82. return s1;
  83. }