bh_common.c 1.8 KB

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