1// SPDX-License-Identifier: GPL-2.0-or-later 2/* 3 * Copyright (c) International Business Machines Corp., 2001 4 */ 5 6/* 7 * DESCRIPTION 8 * Testcase to check the basic functionality of the getcwd(2) system call. 9 * 1) getcwd(2) works fine if buf and size are valid. 10 * 2) getcwd(2) works fine if buf points to NULL and size is set to 0. 11 * 3) getcwd(2) works fine if buf points to NULL and size is greater than strlen(path). 12 */ 13 14#include <errno.h> 15#include <unistd.h> 16#include <stdlib.h> 17#include <string.h> 18#include <sys/types.h> 19#include <sys/stat.h> 20 21#include "tst_test.h" 22 23static char exp_buf[PATH_MAX]; 24static char buffer[PATH_MAX]; 25 26static struct t_case { 27 char *buf; 28 size_t size; 29} tcases[] = { 30 {buffer, sizeof(buffer)}, 31 {NULL, 0}, 32 {NULL, PATH_MAX} 33}; 34 35static int dir_exists(const char *dirpath) 36{ 37 struct stat sb; 38 39 if (!stat(dirpath, &sb) && S_ISDIR(sb.st_mode)) 40 return 1; 41 42 return 0; 43} 44 45static void verify_getcwd(unsigned int n) 46{ 47 struct t_case *tc = &tcases[n]; 48 char *res = NULL; 49 50 errno = 0; 51 res = getcwd(tc->buf, tc->size); 52 TST_ERR = errno; 53 if (!res) { 54 tst_res(TFAIL | TTERRNO, "getcwd() failed"); 55 goto end; 56 } 57 58 if (strcmp(exp_buf, res)) { 59 tst_res(TFAIL, "getcwd() returned unexpected directory: %s, " 60 "expected: %s", res, exp_buf); 61 goto end; 62 } 63 64 tst_res(TPASS, "getcwd() returned expected directory: %s", res); 65 66end: 67 if (!tc->buf) 68 free(res); 69} 70 71static void setup(void) 72{ 73 const char *tmpdir = tst_get_tmpdir_root(); 74 75 if (!dir_exists(tmpdir)) 76 tst_brk(TBROK | TERRNO, "TMPDIR '%s' doesn't exist", tmpdir); 77 78 SAFE_CHDIR(tmpdir); 79 80 if (!realpath(tmpdir, exp_buf)) 81 tst_brk(TBROK | TERRNO, "realpath() failed"); 82 83 tst_res(TINFO, "Expected path '%s'", exp_buf); 84} 85 86static struct tst_test test = { 87 .setup = setup, 88 .tcnt = ARRAY_SIZE(tcases), 89 .test = verify_getcwd 90}; 91