Move from memcpy to memcpy_s.

Change-Id: If7d53c6e54428f01f14528c3f281331d308af56a
diff --git a/src/api.c b/src/api.c
index ec98c22..a726404 100644
--- a/src/api.c
+++ b/src/api.c
@@ -809,7 +809,8 @@
 	/* Copy data. */
 	to_msg = to->mailbox.recv;
 	*to_msg = from_msg_replica;
-	memcpy(to_msg->payload, from->mailbox.send->payload, size);
+	memcpy_s(to_msg->payload, SPCI_MSG_PAYLOAD_MAX,
+		 from->mailbox.send->payload, size);
 	primary_ret.message.vm_id = to->id;
 	ret = SPCI_SUCCESS;
 
diff --git a/src/fdt_handler.c b/src/fdt_handler.c
index 0a0b294..8d701ee 100644
--- a/src/fdt_handler.c
+++ b/src/fdt_handler.c
@@ -35,7 +35,7 @@
 	case sizeof(uint32_t):
 		return be32toh(*(uint32_t *)data);
 	case sizeof(uint64_t):
-		memcpy(t.a, data, sizeof(uint64_t));
+		memcpy_s(t.a, sizeof(t.a), data, sizeof(uint64_t));
 		return be64toh(t.v);
 	default:
 		return 0;
@@ -86,7 +86,7 @@
 
 	case sizeof(uint64_t):
 		t.v = be64toh(value);
-		memcpy((void *)data, t.a, sizeof(uint64_t));
+		memcpy_s((void *)data, size, t.a, sizeof(uint64_t));
 		break;
 
 	default:
diff --git a/src/load.c b/src/load.c
index 7eea3dc..66b7034 100644
--- a/src/load.c
+++ b/src/load.c
@@ -49,7 +49,7 @@
 		return false;
 	}
 
-	memcpy(ptr, from, size);
+	memcpy_s(ptr, size, from, size);
 	arch_mm_write_back_dcache(ptr, size);
 
 	mm_unmap(to, to_end, ppool);
@@ -261,8 +261,8 @@
 	static_assert(sizeof(mem_ranges_available) < 500,
 		      "This will use too much stack, either make "
 		      "MAX_MEM_RANGES smaller or change this.");
-	memcpy(mem_ranges_available, params->mem_ranges,
-	       sizeof(mem_ranges_available));
+	memcpy_s(mem_ranges_available, sizeof(mem_ranges_available),
+		 params->mem_ranges, sizeof(params->mem_ranges));
 
 	primary = vm_get(HF_PRIMARY_VM_ID);
 
diff --git a/src/std.c b/src/std.c
index 00d4704..b7ea2ce 100644
--- a/src/std.c
+++ b/src/std.c
@@ -20,6 +20,7 @@
 
 /* Declare unsafe functions locally so they are not available globally. */
 void *memset(void *s, int c, size_t n);
+void *memcpy(void *dst, const void *src, size_t n);
 
 void memset_s(void *dest, rsize_t destsz, int ch, rsize_t count)
 {
@@ -41,3 +42,39 @@
 fail:
 	panic("memset_s failure");
 }
+
+void memcpy_s(void *dest, rsize_t destsz, const void *src, rsize_t count)
+{
+	uintptr_t d = (uintptr_t)dest;
+	uintptr_t s = (uintptr_t)src;
+
+	if (dest == NULL || src == NULL) {
+		goto fail;
+	}
+
+	if (destsz > RSIZE_MAX || count > RSIZE_MAX) {
+		goto fail;
+	}
+
+	if (count > destsz) {
+		goto fail;
+	}
+
+	/* Destination overlaps the end of source. */
+	if (d > s && d < (s + count)) {
+		goto fail;
+	}
+
+	/* Source overlaps the end of destination. */
+	if (s > d && s < (d + destsz)) {
+		goto fail;
+	}
+
+	/* TODO: consider wrapping? */
+
+	memcpy(dest, src, count);
+	return;
+
+fail:
+	panic("memcpy_s failure");
+}