/* See LICENSE file for copyright and license details. */
#include "common.h"
#ifndef TEST
const char *
libexec_getenv_last(struct libexec_command *cmd, const char *name)
{
char **env;
size_t i, len;
const char *ret = NULL;
if (!cmd || !name) {
errno = EINVAL;
return NULL;
}
if (strchr(name, '='))
return NULL;
env = cmd->environ ? cmd->environ : environ;
len = strlen(name);
for (i = 0; env[i]; i++)
if (!strncmp(env[i], name, len) && env[i][len] == '=')
ret = &env[i][len + 1];
return ret;
}
#else
int
main(void)
{
struct libexec_command cmd, ref;
char **env;
cmd = LIBEXEC_COMMAND_INIT;
memcpy(&ref, &cmd, sizeof(cmd));
env = environ;
environ = calloc(12, sizeof(*environ));
ASSERT_NOT_NULL(environ);
environ[0] = strdup("AA=aa");
environ[1] = strdup("A=a0");
environ[2] = strdup("B=b0");
environ[3] = strdup("A=a1");
environ[4] = strdup("B=b1");
environ[5] = strdup("A=a2");
environ[6] = strdup("B=b2");
environ[7] = strdup("A=a3");
environ[8] = strdup("B=b3");
environ[9] = strdup("BB=bb");
environ[10] = strdup("X=Y=Z");
ASSERT_NOT_NULL(environ[0]);
ASSERT_NOT_NULL(environ[1]);
ASSERT_NOT_NULL(environ[2]);
ASSERT_NOT_NULL(environ[3]);
ASSERT_NOT_NULL(environ[4]);
ASSERT_NOT_NULL(environ[5]);
ASSERT_NOT_NULL(environ[6]);
ASSERT_NOT_NULL(environ[7]);
ASSERT_NOT_NULL(environ[8]);
ASSERT_NOT_NULL(environ[9]);
ASSERT_NOT_NULL(environ[10]);
ASSERT_IS_NULL(environ[11]);
errno = 0;
ASSERT_IS_NULL(libexec_getenv_last(&cmd, "PATH"));
ASSERT_IS_TRUE(errno == 0);
errno = 0;
ASSERT_IS_NULL(libexec_getenv_last(NULL, "x"));
ASSERT_EQ_INT(errno, EINVAL);
errno = 0;
ASSERT_IS_NULL(libexec_getenv_last(&cmd, "x"));
ASSERT_IS_TRUE(errno == 0);
errno = 0;
ASSERT_IS_NULL(libexec_getenv_last(&cmd, NULL));
ASSERT_EQ_INT(errno, EINVAL);
errno = 0;
ASSERT_IS_NULL(libexec_getenv_last(&cmd, "X=Y"));
ASSERT_IS_TRUE(errno == 0 || errno == EINVAL);
errno = 0;
ASSERT_IS_NULL(libexec_getenv_last(&cmd, ""));
ASSERT_IS_TRUE(errno == 0);
ASSERT_EQ_STR(libexec_getenv_last(&cmd, "X"), "Y=Z");
ASSERT_EQ_STR(libexec_getenv_last(&cmd, "AA"), "aa");
ASSERT_EQ_STR(libexec_getenv_last(&cmd, "BB"), "bb");
ASSERT_EQ_STR(libexec_getenv_last(&cmd, "A"), "a3");
ASSERT_EQ_STR(libexec_getenv_last(&cmd, "B"), "b3");
ASSERT_IS_TRUE(!memcmp(&cmd, &ref, sizeof(cmd)));
libexec_destroy_command(&cmd);
ASSERT_IS_NULL(libexec_getenv_last(&cmd, "PATH"));
ASSERT_IS_NULL(libexec_getenv_last(NULL, "x"));
ASSERT_IS_NULL(libexec_getenv_last(&cmd, "x"));
ASSERT_IS_NULL(libexec_getenv_last(&cmd, NULL));
ASSERT_IS_NULL(libexec_getenv_last(&cmd, "X=Y"));
ASSERT_IS_NULL(libexec_getenv_last(&cmd, ""));
ASSERT_EQ_STR(libexec_getenv_last(&cmd, "X"), "Y=Z");
ASSERT_EQ_STR(libexec_getenv_last(&cmd, "AA"), "aa");
ASSERT_EQ_STR(libexec_getenv_last(&cmd, "BB"), "bb");
ASSERT_EQ_STR(libexec_getenv_last(&cmd, "A"), "a3");
ASSERT_EQ_STR(libexec_getenv_last(&cmd, "B"), "b3");
libexec_set_environ(&cmd, environ);
environ = env;
return 0;
}
#endif