bh_common.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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
  30. b_strcat_s(char * s1, unsigned int s1max, const char * s2)
  31. {
  32. if (NULL == s1 || NULL == s2
  33. || s1max < (strlen(s1) + strlen(s2) + 1)
  34. || s1max > RSIZE_MAX) {
  35. return -1;
  36. }
  37. memcpy(s1 + strlen(s1), s2, strlen(s2) + 1);
  38. return 0;
  39. }
  40. int
  41. b_strcpy_s(char * s1, unsigned int s1max, const char * s2)
  42. {
  43. if (NULL == s1 || NULL == s2
  44. || s1max < (strlen(s2) + 1)
  45. || s1max > RSIZE_MAX) {
  46. return -1;
  47. }
  48. memcpy(s1, s2, strlen(s2) + 1);
  49. return 0;
  50. }
  51. char *
  52. bh_strdup(const char *s)
  53. {
  54. uint32 size;
  55. char *s1 = NULL;
  56. if (s) {
  57. size = (uint32)(strlen(s) + 1);
  58. if ((s1 = BH_MALLOC(size)))
  59. bh_memcpy_s(s1, size, s, size);
  60. }
  61. return s1;
  62. }
  63. char *
  64. wa_strdup(const char *s)
  65. {
  66. uint32 size;
  67. char *s1 = NULL;
  68. if (s) {
  69. size = (uint32)(strlen(s) + 1);
  70. if ((s1 = WA_MALLOC(size)))
  71. bh_memcpy_s(s1, size, s, size);
  72. }
  73. return s1;
  74. }