1 // Copyright 2017 The Emscripten Authors.  All rights reserved.
2 // Emscripten is available under two separate licenses, the MIT license and the
3 // University of Illinois/NCSA Open Source License.  Both these licenses can be
4 // found in the LICENSE file.
5 
6 #include <memory.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <vector>
11 #include <iostream>
12 #include <algorithm>
13 
14 #include <emscripten/emscripten.h>
15 
16 char dst[1024*1024*2+64] = {};
17 char src[1024*1024*2+64] = {};
18 
19 #define GUARDSIZE 32
test_memcpy(int copySize,int srcOffset,int dstOffset)20 void test_memcpy(int copySize, int srcOffset, int dstOffset)
21 {
22 	char *dstContent = dst + GUARDSIZE + dstOffset;
23 	char *srcContent = src + GUARDSIZE + srcOffset;
24 
25 	char *dstGuardBefore = dstContent - GUARDSIZE;
26 	char *dstGuardAfter  = dstContent + copySize;
27 
28 	char *srcGuardBefore = srcContent - GUARDSIZE;
29 	char *srcGuardAfter  = srcContent + copySize;
30 
31 	char guard = (char)rand();
32 
33 	for(int i = 0; i < GUARDSIZE; ++i)
34 	{
35 		// Generate a guardband area around dst memory that should not change.
36 		dstGuardBefore[i] = (char)(guard ^ i);
37 		dstGuardAfter[i] = (char)(guard ^ i);
38 	}
39 
40 	// Generate copy source data
41 	char s = (char)rand();
42 	for(int i = 0; i < copySize + srcOffset + 2*GUARDSIZE; ++i)
43 		src[i] = (char)(s - i);
44 
45 	memcpy(dstContent, srcContent, copySize);
46 	if (!!memcmp(dstContent, srcContent, copySize))
47 	{
48 		printf("test_memcpy(copySize=%d, srcOffset=%d, dstOffset=%d failed!\n", copySize, srcOffset, dstOffset);
49 		exit(1);
50 	}
51 
52 	// Verify guardband area
53 	for(int i = 0; i < GUARDSIZE; ++i)
54 	{
55 		// Generate a guardband area around dst memory that should not change.
56 		if (dstGuardBefore[i] != (char)(guard ^ i))
57 		{
58 			printf("test_memcpy(copySize=%d, srcOffset=%d, dstOffset=%d failed! Pre-guardband area at i=%d overwritten!\n", copySize, srcOffset, dstOffset, i);
59 			exit(1);
60 		}
61 		if (dstGuardAfter[i] != (char)(guard ^ i))
62 		{
63 			printf("test_memcpy(copySize=%d, srcOffset=%d, dstOffset=%d failed! Post-guardband area at i=%d overwritten!\n", copySize, srcOffset, dstOffset, i);
64 			exit(1);
65 		}
66 	}
67 }
68 
test_copysize(int copySize)69 void test_copysize(int copySize)
70 {
71 	int offsets[6] = { 0, 3, 4, 5, 8, 11 };
72 
73 	for(int srcOffset = 0; srcOffset < 6; ++srcOffset)
74 		for(int dstOffset = 0; dstOffset < 6; ++dstOffset)
75 			test_memcpy(copySize, offsets[srcOffset], offsets[dstOffset]);
76 }
77 
main()78 int main()
79 {
80 	for(int copySize = 0; copySize < 128; ++copySize)
81 		test_copysize(copySize);
82 
83 	for(int copySizeI = 128; copySizeI <= 1048576; copySizeI <<= 1)
84 		for(int copySizeJ = 1; copySizeJ <= 16; copySizeJ <<= 1)
85 			test_copysize(copySizeI | copySizeJ);
86 
87 	printf("OK.\n");
88 }
89