summaryrefslogtreecommitdiff
path: root/lib/mlibc/tests/posix/mkstemp.c
blob: d06783e11cdccee57b0db779f36ef5a9e07a1d0c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>

void validate_pattern(char *p) {
	assert(memcmp(p, "XXXXXX", 6));
	assert(memchr(p, 0, 6) == NULL);

	for (int i = 0; i < 6; i++) {
		assert(isalnum(p[i]));
	}
}

int main() {
	int ret;

	// Make sure the patterns themselves cannot be chosen.  This
	// *could* happen on glibc, or if we widen the character set
	// used for generating random names. Odds are 1 in 60 billion,
	// but I'd rather not worry about this.
	ret = open("prefixXXXXXX", O_RDWR | O_CREAT | O_EXCL, 0600);
	assert(ret >= 0 || (ret == -1 && errno == EEXIST));
	ret = open("longprefixXXXXXXlongsuffix", O_RDWR | O_CREAT | O_EXCL, 0600);
	assert(ret >= 0 || (ret == -1 && errno == EEXIST));

	ret = mkstemp("short");
	assert(ret == -1);
	assert(errno == EINVAL);

	ret = mkstemp("lessthan6XXX");
	assert(ret == -1);
	assert(errno == EINVAL);

	ret = mkstemps("lessthan6XXXswithsuffix", 11);
	assert(ret == -1);
	assert(errno == EINVAL);

	char *p = strdup("prefixXXXXXX");
	ret = mkstemp(p);
	// We can't really protect against EEXIST...
	assert(ret >= 0 || (ret == -1 && errno == EEXIST));
	assert(!memcmp(p, "prefix", 6));
	assert(p[12] == 0);
	validate_pattern(p + 6);

	if (ret >= 0) {
		ret = close(ret);
		assert(!ret);
	}
	free(p);

	p = strdup("longprefixXXXXXXlongsuffix");
	ret = mkstemps(p, 10);
	// We can't really protect against EEXIST...
	assert(ret >= 0 || (ret == -1 && errno == EEXIST));
	assert(!memcmp(p, "longprefix", 10));
	assert(!memcmp(p + 16, "longsuffix", 10));
	assert(p[26] == 0);
	validate_pattern(p + 10);

	if (ret >= 0) {
		ret = close(ret);
		assert(!ret);
	}
	free(p);
}