memcpy_s.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //
  2. // Copyright (c) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
  4. //
  5. /***
  6. *memcpy_s.c - contains memcpy_s routine
  7. *
  8. *
  9. *Purpose:
  10. * memcpy_s() copies a source memory buffer to a destination buffer.
  11. * Overlapping buffers are not treated specially, so propagation may occur.
  12. *
  13. *Revision History:
  14. * 10-07-03 AC Module created.
  15. * 03-10-04 AC Return ERANGE when buffer is too small
  16. * 01-14-05 AC Prefast (espx) fixes
  17. *
  18. *******************************************************************************/
  19. #include <string.h>
  20. #include <errno.h>
  21. #include "internal_securecrt.h"
  22. #include "mbusafecrt_internal.h"
  23. /***
  24. *memcpy_s - Copy source buffer to destination buffer
  25. *
  26. *Purpose:
  27. * memcpy_s() copies a source memory buffer to a destination memory buffer.
  28. * This routine does NOT recognize overlapping buffers, and thus can lead
  29. * to propagation.
  30. *
  31. * For cases where propagation must be avoided, memmove_s() must be used.
  32. *
  33. *Entry:
  34. * void *dst = pointer to destination buffer
  35. * size_t sizeInBytes = size in bytes of the destination buffer
  36. * const void *src = pointer to source buffer
  37. * size_t count = number of bytes to copy
  38. *
  39. *Exit:
  40. * Returns 0 if everything is ok, else return the error code.
  41. *
  42. *Exceptions:
  43. * Input parameters are validated. Refer to the validation section of the function.
  44. * On error, the error code is returned and the destination buffer is zeroed.
  45. *
  46. *******************************************************************************/
  47. errno_t __cdecl memcpy_s(
  48. void * dst,
  49. size_t sizeInBytes,
  50. const void * src,
  51. size_t count
  52. )
  53. {
  54. if (count == 0)
  55. {
  56. /* nothing to do */
  57. return 0;
  58. }
  59. /* validation section */
  60. _VALIDATE_RETURN_ERRCODE(dst != NULL, EINVAL);
  61. if (src == NULL || sizeInBytes < count)
  62. {
  63. /* zeroes the destination buffer */
  64. memset(dst, 0, sizeInBytes);
  65. _VALIDATE_RETURN_ERRCODE(src != NULL, EINVAL);
  66. _VALIDATE_RETURN_ERRCODE(sizeInBytes >= count, ERANGE);
  67. /* useless, but prefast is confused */
  68. return EINVAL;
  69. }
  70. memcpy(dst, src, count);
  71. return 0;
  72. }