bh_common.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. #ifdef RSIZE_MAX
  7. #undef RSIZE_MAX
  8. #endif
  9. #define RSIZE_MAX 0x7FFFFFFF
  10. int
  11. b_memcpy_s(void *s1, unsigned int s1max, const void *s2, unsigned int n)
  12. {
  13. char *dest = (char *)s1;
  14. char *src = (char *)s2;
  15. if (n == 0) {
  16. return 0;
  17. }
  18. if (s1 == NULL || s1max > RSIZE_MAX) {
  19. return -1;
  20. }
  21. if (s2 == NULL || n > s1max) {
  22. memset(dest, 0, s1max);
  23. return -1;
  24. }
  25. memcpy(dest, src, n);
  26. return 0;
  27. }
  28. int
  29. b_memmove_s(void *s1, unsigned int s1max, const void *s2, unsigned int n)
  30. {
  31. char *dest = (char *)s1;
  32. char *src = (char *)s2;
  33. if (n == 0) {
  34. return 0;
  35. }
  36. if (s1 == NULL || s1max > RSIZE_MAX) {
  37. return -1;
  38. }
  39. if (s2 == NULL || n > s1max) {
  40. memset(dest, 0, s1max);
  41. return -1;
  42. }
  43. memmove(dest, src, n);
  44. return 0;
  45. }
  46. int
  47. b_strcat_s(char *s1, unsigned int s1max, const char *s2)
  48. {
  49. if (NULL == s1 || NULL == s2 || s1max < (strlen(s1) + strlen(s2) + 1)
  50. || s1max > RSIZE_MAX) {
  51. return -1;
  52. }
  53. memcpy(s1 + strlen(s1), s2, strlen(s2) + 1);
  54. return 0;
  55. }
  56. int
  57. b_strcpy_s(char *s1, unsigned int s1max, const char *s2)
  58. {
  59. if (NULL == s1 || NULL == s2 || s1max < (strlen(s2) + 1)
  60. || s1max > RSIZE_MAX) {
  61. return -1;
  62. }
  63. memcpy(s1, s2, strlen(s2) + 1);
  64. return 0;
  65. }
  66. char *
  67. bh_strdup(const char *s)
  68. {
  69. uint32 size;
  70. char *s1 = NULL;
  71. if (s) {
  72. size = (uint32)(strlen(s) + 1);
  73. if ((s1 = BH_MALLOC(size)))
  74. bh_memcpy_s(s1, size, s, size);
  75. }
  76. return s1;
  77. }
  78. char *
  79. wa_strdup(const char *s)
  80. {
  81. uint32 size;
  82. char *s1 = NULL;
  83. if (s) {
  84. size = (uint32)(strlen(s) + 1);
  85. if ((s1 = WA_MALLOC(size)))
  86. bh_memcpy_s(s1, size, s, size);
  87. }
  88. return s1;
  89. }