xref: /illumos-gate/usr/src/test/libc-tests/tests/env-7076.c (revision 66582b606a8194f7f3ba5b3a3a6dca5b0d346361)
1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright 2016 Joyent, Inc.
14  */
15 
16 /*
17  * Regression test for 7076 where doing a putenv() call without an '=' sign
18  * may lead to a segmentation fault when doing a getenv() depending on the
19  * circumstances of the environment's layout. Verify putenv() mimics
20  * unsetenv().
21  */
22 
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <string.h>
27 #include <sys/debug.h>
28 
29 int
30 main(void)
31 {
32 	if (putenv("FOO=bar") != 0) {
33 		fprintf(stderr, "failed to put FOO into the environment: %s\n",
34 		    strerror(errno));
35 		return (1);
36 	}
37 
38 	if (getenv("FOO") == NULL) {
39 		fprintf(stderr, "failed to retrieve FOO from the "
40 		    "environment!\n");
41 		return (1);
42 	}
43 
44 	VERIFY0(unsetenv("FOO"));
45 
46 	if (getenv("FOO") != NULL) {
47 		fprintf(stderr, "Somehow retrieved FOO from the "
48 		    "environment after unsetenv()!\n");
49 		return (1);
50 	}
51 
52 	if (putenv("FOO=bar") != 0) {
53 		fprintf(stderr, "failed to put FOO into the environment: %s\n",
54 		    strerror(errno));
55 		return (1);
56 	}
57 
58 	if (getenv("FOO") == NULL) {
59 		fprintf(stderr, "failed to retrieve FOO from the "
60 		    "environment!\n");
61 		return (1);
62 	}
63 
64 	VERIFY0(putenv("FOO"));
65 
66 	if (getenv("FOO") != NULL) {
67 		fprintf(stderr, "Somehow retrieved FOO from the "
68 		    "environment after putenv()!\n");
69 		return (1);
70 	}
71 
72 	return (0);
73 }
74