summaryrefslogtreecommitdiff
path: root/ltp_framework/lib
diff options
context:
space:
mode:
Diffstat (limited to 'ltp_framework/lib')
-rw-r--r--ltp_framework/lib/Makefile45
-rw-r--r--ltp_framework/lib/cloner.c111
-rw-r--r--ltp_framework/lib/dataascii.c217
-rw-r--r--ltp_framework/lib/databin.c297
-rw-r--r--ltp_framework/lib/datapid.c373
-rw-r--r--ltp_framework/lib/file_lock.c208
-rw-r--r--ltp_framework/lib/forker.c281
-rw-r--r--ltp_framework/lib/get_high_address.c40
-rw-r--r--ltp_framework/lib/get_path.c100
-rw-r--r--ltp_framework/lib/libltp.abin0 -> 264326 bytes
-rw-r--r--ltp_framework/lib/libtestsuite.c164
-rw-r--r--ltp_framework/lib/ltp.pc10
-rw-r--r--ltp_framework/lib/ltp.pc.in10
-rw-r--r--ltp_framework/lib/mount_utils.c213
-rw-r--r--ltp_framework/lib/open_flags.c330
-rw-r--r--ltp_framework/lib/parse_opts.c879
-rw-r--r--ltp_framework/lib/pattern.c168
-rw-r--r--ltp_framework/lib/random_range.c917
-rw-r--r--ltp_framework/lib/rmobj.c211
-rw-r--r--ltp_framework/lib/safe_macros.c312
-rw-r--r--ltp_framework/lib/search_path.c277
-rw-r--r--ltp_framework/lib/self_exec.c218
-rw-r--r--ltp_framework/lib/str_to_bytes.c210
-rw-r--r--ltp_framework/lib/string_to_tokens.c109
-rw-r--r--ltp_framework/lib/system_specific_hugepages_info.c93
-rw-r--r--ltp_framework/lib/system_specific_process_info.c88
-rw-r--r--ltp_framework/lib/tlibio.c2084
-rw-r--r--ltp_framework/lib/tst_cwd_has_free.c22
-rw-r--r--ltp_framework/lib/tst_is_cwd.c52
-rw-r--r--ltp_framework/lib/tst_kvercmp.c68
-rw-r--r--ltp_framework/lib/tst_res.c812
-rw-r--r--ltp_framework/lib/tst_sig.c271
-rw-r--r--ltp_framework/lib/tst_tmpdir.c405
-rw-r--r--ltp_framework/lib/write_log.c503
34 files changed, 10098 insertions, 0 deletions
diff --git a/ltp_framework/lib/Makefile b/ltp_framework/lib/Makefile
new file mode 100644
index 0000000..661c0a1
--- /dev/null
+++ b/ltp_framework/lib/Makefile
@@ -0,0 +1,45 @@
+#
+# lib Makefile.
+#
+# Copyright (C) 2009, Cisco Systems Inc.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Garrett Cooper, July 2009
+#
+
+top_srcdir ?= ..
+
+include $(top_srcdir)/include/mk/env_pre.mk
+
+ifeq ($(UCLINUX),1)
+CFLAGS += -D_USC_LIB_
+endif
+
+#CPPFLAGS += -DGARRETT_IS_A_PEDANTIC_BASTARD
+
+FILTER_OUT_LIBSRCS := mount_utils.c
+
+LIB := libltp.a
+
+pc_file := $(DESTDIR)/$(datarootdir)/pkgconfig/ltp.pc
+
+INSTALL_TARGETS := $(pc_file)
+
+$(pc_file):
+ test -d "$(@D)" || mkdir -p "$(@D)"
+ install -m $(INSTALL_MODE) "$(builddir)/$(@F)" "$@"
+
+include $(top_srcdir)/include/mk/lib.mk
diff --git a/ltp_framework/lib/cloner.c b/ltp_framework/lib/cloner.c
new file mode 100644
index 0000000..bf9eed1
--- /dev/null
+++ b/ltp_framework/lib/cloner.c
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) International Business Machines Corp., 2009
+ * Some wrappers for clone functionality. Thrown together by Serge Hallyn
+ * <serue@us.ibm.com> based on existing clone usage in ltp.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
+ * the GNU General Public License for more details.
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include <stdio.h>
+#include <errno.h>
+#include <unistd.h> /* fork, getpid, sleep */
+#include <string.h>
+#include <stdlib.h> /* exit */
+#include <sched.h> /* clone */
+#include "test.h"
+
+#undef clone /* we want to use clone() */
+
+/* copied from several other files under ltp */
+#if defined (__s390__) || (__s390x__)
+#define clone __clone
+extern int __clone(int(void*),void*,int,void*);
+#elif defined(__ia64__)
+#define clone2 __clone2
+/* Prototype provided by David Mosberger */
+extern int __clone2(int (*fn) (void *arg), void *child_stack_base,
+ size_t child_stack_size, int flags, void *arg,
+ pid_t *parent_tid, void *tls, pid_t *child_tid);
+#endif
+
+/***********************************************************************
+ * ltp_clone: wrapper for clone to hide the architecture dependencies.
+ * 1. hppa takes bottom of stack and no stacksize (stack grows up)
+ * 2. __ia64__ takes bottom of stack and uses clone2
+ * 3. all others take top of stack (stack grows down)
+ ***********************************************************************/
+int
+ltp_clone(unsigned long clone_flags, int (*fn)(void *arg), void *arg,
+ size_t stack_size, void *stack)
+{
+ int ret;
+
+#if defined(__hppa__)
+ ret = clone(fn, stack, clone_flags, arg);
+#elif defined(__ia64__)
+ ret = clone2(fn, stack, stack_size, clone_flags, arg, NULL, NULL, NULL);
+#else
+ /*
+ * For archs where stack grows downwards, stack points to the topmost
+ * address of the memory space set up for the child stack.
+ */
+ ret = clone(fn, (stack ? stack + stack_size : NULL),
+ clone_flags, arg);
+#endif
+
+ return ret;
+}
+
+/***********************************************************************
+ * ltp_clone_malloc: also does the memory allocation for clone with a
+ * caller-specified size.
+ ***********************************************************************/
+int
+ltp_clone_malloc(unsigned long clone_flags, int (*fn)(void *arg), void *arg,
+ size_t stack_size)
+{
+ void *stack;
+ int ret;
+ int saved_errno;
+
+ if ((stack = malloc(stack_size)) == NULL)
+ return -1;
+
+ ret = ltp_clone(clone_flags, fn, arg, stack_size, stack);
+
+ if (ret == -1) {
+ saved_errno = errno;
+ free(stack);
+ errno = saved_errno;
+ }
+
+ return ret;
+}
+
+/***********************************************************************
+ * ltp_clone_quick: calls ltp_clone_malloc with predetermined stack size.
+ * Experience thus far suggests that one page is often insufficient,
+ * while 4*getpagesize() seems adequate.
+ ***********************************************************************/
+int
+ltp_clone_quick(unsigned long clone_flags, int (*fn)(void *arg), void *arg)
+{
+ size_t stack_size = getpagesize() * 4;
+
+ return ltp_clone_malloc(clone_flags, fn, arg, stack_size);
+} \ No newline at end of file
diff --git a/ltp_framework/lib/dataascii.c b/ltp_framework/lib/dataascii.c
new file mode 100644
index 0000000..0188eca
--- /dev/null
+++ b/ltp_framework/lib/dataascii.c
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+#include <stdio.h>
+#include <string.h>
+#include "dataascii.h"
+
+#define CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghjiklmnopqrstuvwxyz\n"
+#define CHARS_SIZE sizeof(CHARS)
+
+#ifdef UNIT_TEST
+#include <stdlib.h> /* malloc */
+#endif
+
+static char Errmsg[80];
+
+int
+dataasciigen(listofchars, buffer, bsize, offset)
+char *listofchars; /* a null terminated list of characters */
+char *buffer;
+int bsize;
+int offset;
+{
+ int cnt;
+ int total;
+ int ind; /* index into CHARS array */
+ char *chr;
+ int chars_size;
+ char *charlist;
+
+ chr=buffer;
+ total=offset+bsize;
+
+ if (listofchars == NULL) {
+ charlist=CHARS;
+ chars_size=CHARS_SIZE;
+ }
+ else {
+ charlist=listofchars;
+ chars_size=strlen(listofchars);
+ }
+
+ for (cnt=offset; cnt<total; cnt++) {
+ ind=cnt%chars_size;
+ *chr++=charlist[ind];
+ }
+
+ return bsize;
+
+} /* end of dataasciigen */
+
+int
+dataasciichk(listofchars, buffer, bsize, offset, errmsg)
+char *listofchars; /* a null terminated list of characters */
+char *buffer;
+int bsize;
+int offset;
+char **errmsg;
+{
+ int cnt;
+ int total;
+ int ind; /* index into CHARS array */
+ char *chr;
+ int chars_size;
+ char *charlist;
+
+ chr=buffer;
+ total=offset+bsize;
+
+ if (listofchars == NULL) {
+ charlist=CHARS;
+ chars_size=CHARS_SIZE;
+ }
+ else {
+ charlist=listofchars;
+ chars_size=strlen(listofchars);
+ }
+
+ if (errmsg != NULL) {
+ *errmsg = Errmsg;
+ }
+
+ for (cnt=offset; cnt<total; chr++, cnt++) {
+ ind=cnt%chars_size;
+ if (*chr != charlist[ind]) {
+ sprintf(Errmsg,
+ "data mismatch at offset %d, exp:%#o, act:%#o", cnt,
+ charlist[ind], *chr);
+ return cnt;
+ }
+ }
+
+ sprintf(Errmsg, "all %d bytes match desired pattern", bsize);
+ return -1; /* buffer is ok */
+
+} /* end of dataasciichk */
+
+
+#if UNIT_TEST
+
+/***********************************************************************
+ * main for doing unit testing
+ ***********************************************************************/
+int
+main(ac, ag)
+int ac;
+char **ag;
+{
+
+int size=1023;
+char *buffer;
+int ret;
+char *errmsg;
+
+ if ((buffer=(char *)malloc(size)) == NULL) {
+ perror("malloc");
+ exit(2);
+ }
+
+ dataasciigen(NULL, buffer, size, 0);
+ printf("dataasciigen(NULL, buffer, %d, 0)\n", size);
+
+ ret=dataasciichk(NULL, buffer, size, 0, &errmsg);
+ printf("dataasciichk(NULL, buffer, %d, 0, &errmsg) returned %d %s\n",
+ size, ret, errmsg);
+
+ if (ret == -1)
+ printf("\tPASS return value is -1 as expected\n");
+ else
+ printf("\tFAIL return value is %d, expected -1\n", ret);
+
+ ret=dataasciichk(NULL, &buffer[1], size-1, 1, &errmsg);
+ printf("dataasciichk(NULL, &buffer[1], %d, 1, &errmsg) returned %d %s\n",
+ size-1, ret, errmsg);
+
+ if (ret == -1)
+ printf("\tPASS return value is -1 as expected\n");
+ else
+ printf("\tFAIL return value is %d, expected -1\n", ret);
+
+ buffer[25]= 0x0;
+ printf("changing char 25\n");
+
+ ret=dataasciichk(NULL, &buffer[1], size-1, 1, &errmsg);
+ printf("dataasciichk(NULL, &buffer[1], %d, 1, &errmsg) returned %d %s\n",
+ size-1, ret, errmsg);
+
+ if (ret == 25)
+ printf("\tPASS return value is 25 as expected\n");
+ else
+ printf("\tFAIL return value is %d, expected 25\n", ret);
+
+ dataasciigen("this is a test of the my string" , buffer, size, 0);
+ printf("dataasciigen(\"this is a test of the my string\", buffer, %d, 0)\n", size);
+
+ ret=dataasciichk("this is a test of the my string", buffer, size, 0, &errmsg);
+ printf("dataasciichk(\"this is a test of the my string\", buffer, %d, 0, &errmsg) returned %d %s\n",
+ size, ret, errmsg);
+
+ if (ret == -1)
+ printf("\tPASS return value is -1 as expected\n");
+ else
+ printf("\tFAIL return value is %d, expected -1\n", ret);
+
+ ret=dataasciichk("this is a test of the my string", &buffer[1], size-1, 1, &errmsg);
+ printf("dataasciichk(\"this is a test of the my string\", &buffer[1], %d, 1, &errmsg) returned %d %s\n",
+ size-1, ret, errmsg);
+
+ if (ret == -1)
+ printf("\tPASS return value is -1 as expected\n");
+ else
+ printf("\tFAIL return value is %d, expected -1\n", ret);
+
+ buffer[25]= 0x0;
+ printf("changing char 25\n");
+
+ ret=dataasciichk("this is a test of the my string", &buffer[1], size-1, 1, &errmsg);
+ printf("dataasciichk(\"this is a test of the my string\", &buffer[1], %d, 1, &errmsg) returned %d %s\n",
+ size-1, ret, errmsg);
+
+ if (ret == 25)
+ printf("\tPASS return value is 25 as expected\n");
+ else
+ printf("\tFAIL return value is %d, expected 25\n", ret);
+
+ exit(0);
+}
+
+#endif
diff --git a/ltp_framework/lib/databin.c b/ltp_framework/lib/databin.c
new file mode 100644
index 0000000..c0f4307
--- /dev/null
+++ b/ltp_framework/lib/databin.c
@@ -0,0 +1,297 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+#include <stdio.h>
+#include <sys/param.h>
+#include <string.h> /* memset */
+#include <stdlib.h> /* rand */
+#include "databin.h"
+
+#if UNIT_TEST
+#include <malloc.h>
+#endif
+
+static char Errmsg[80];
+
+void
+databingen (mode, buffer, bsize, offset)
+int mode; /* either a, c, r, o, z or C */
+char *buffer; /* buffer pointer */
+int bsize; /* size of buffer */
+int offset; /* offset into the file where buffer starts */
+{
+int ind;
+
+ switch (mode)
+ {
+ default:
+ case 'a': /* alternating bit pattern */
+ memset(buffer,0x55,bsize);
+ break;
+
+ case 'c': /* checkerboard pattern */
+ memset(buffer,0xf0,bsize);
+ break;
+
+ case 'C': /* */
+ for (ind=0;ind< bsize;ind++) {
+ buffer[ind] = ((offset+ind)%8 & 0177);
+ }
+ break;
+
+ case 'o':
+ memset(buffer,0xff,bsize);
+ break;
+
+ case 'z':
+ memset(buffer,0x0,bsize);
+ break;
+
+ case 'r': /* random */
+ for (ind=0;ind< bsize;ind++) {
+ buffer[ind] = (rand () & 0177) | 0100;
+ }
+ }
+}
+
+/***********************************************************************
+ *
+ * return values:
+ * >= 0 : error at byte offset into the file, offset+buffer[0-(bsize-1)]
+ * < 0 : no error
+ ***********************************************************************/
+int
+databinchk(mode, buffer, bsize, offset, errmsg)
+int mode; /* either a, c, r, z, o, or C */
+char *buffer; /* buffer pointer */
+int bsize; /* size of buffer */
+int offset; /* offset into the file where buffer starts */
+char **errmsg;
+{
+ int cnt;
+ unsigned char *chr;
+ int total;
+ long expbits;
+ long actbits;
+
+ chr = (unsigned char *) buffer;
+ total=bsize;
+
+ if (errmsg != NULL) {
+ *errmsg = Errmsg;
+ }
+
+ switch (mode)
+ {
+ default:
+ case 'a': /* alternating bit pattern */
+ expbits=0x55;
+ break;
+
+ case 'c': /* checkerboard pattern */
+ expbits=0xf0;
+ break;
+
+ case 'C': /* counting pattern */
+ for (cnt=0;cnt< bsize;cnt++) {
+ expbits = ((offset+cnt)%8 & 0177);
+
+ if (buffer[cnt] != expbits) {
+ sprintf(Errmsg,
+ "data mismatch at offset %d, exp:%#lo, act:%#o",
+ offset+cnt, expbits, buffer[cnt]);
+ return offset+cnt;
+ }
+ }
+ sprintf(Errmsg, "all %d bytes match desired pattern", bsize);
+ return -1;
+
+ case 'o':
+ expbits=0xff;
+ break;
+
+ case 'z':
+ expbits=0;
+ break;
+
+ case 'r':
+ return -1; /* no check can be done for random */
+ }
+
+ for (cnt=0; cnt<bsize; chr++, cnt++) {
+ actbits = (long)*chr;
+
+ if (actbits != expbits) {
+ sprintf(Errmsg, "data mismatch at offset %d, exp:%#lo, act:%#lo",
+ offset+cnt, expbits, actbits);
+ return offset+cnt;
+ }
+ }
+
+ sprintf(Errmsg, "all %d bytes match desired pattern", bsize);
+ return -1; /* all ok */
+}
+
+#if UNIT_TEST
+
+/***********************************************************************
+ * main for doing unit testing
+ ***********************************************************************/
+int
+main(ac, ag)
+int ac;
+char **ag;
+{
+
+ int size=1023;
+ int offset;
+ int number;
+ unsigned char *buffer;
+ int ret;
+ char *errmsg;
+
+ if ((buffer=(unsigned char *)malloc(size)) == NULL) {
+ perror("malloc");
+ exit(2);
+ }
+
+
+printf("***** for a ****************************\n");
+ databingen('a', buffer, size, 0);
+ printf("databingen('a', buffer, %d, 0)\n", size);
+
+ ret=databinchk('a', buffer, size, 0, &errmsg);
+ printf("databinchk('a', buffer, %d, 0, &errmsg) returned %d: %s\n",
+ size, ret, errmsg);
+ if (ret == -1)
+ printf("\tPASS return value of -1 as expected\n");
+ else
+ printf("\tFAIL return value %d, expected -1\n", ret);
+
+ offset=232400;
+ ret=databinchk('a', &buffer[1], size-1, offset, &errmsg);
+ printf("databinchk('a', &buffer[1], %d, %d, &errmsg) returned %d: %s\n",
+ size, offset, ret, errmsg);
+ if (ret == -1)
+ printf("\tPASS return value of -1 as expected\n");
+ else
+ printf("\tFAIL return value %d, expected -1\n", ret);
+
+ buffer[15]= 0x0;
+ printf("changing char 15 (offset (%d+15) = %d) to 0x0\n", offset, offset+15);
+ number=offset+15;
+
+ ret=databinchk('a', &buffer[1], size-1, offset+1, &errmsg);
+ printf("databinchk('a', &buffer[1], %d, %d, &errmsg) returned %d: %s\n",
+ size-1, offset+1, ret, errmsg);
+ if (ret == number)
+ printf("\tPASS return value of %d as expected\n", number);
+ else
+ printf("\tFAIL return value %d, expected %d\n", ret, number);
+
+
+
+printf("***** for c ****************************\n");
+ databingen('c', buffer, size, 0);
+ printf("databingen('c', buffer, %d, 0)\n", size);
+
+ ret=databinchk('c', buffer, size, 0, &errmsg);
+ printf("databinchk('c', buffer, %d, 0, &errmsg) returned %d: %s\n",
+ size, ret, errmsg);
+ if (ret == -1)
+ printf("\tPASS return value of -1 as expected\n");
+ else
+ printf("\tFAIL return value %d, expected -1\n", ret);
+
+ offset=232400;
+ ret=databinchk('c', &buffer[1], size-1, offset, &errmsg);
+ printf("databinchk('c', &buffer[1], %d, %d, &errmsg) returned %d: %s\n",
+ size, offset, ret, errmsg);
+ if (ret == -1)
+ printf("\tPASS return value of -1 as expected\n");
+ else
+ printf("\tFAIL return value %d, expected -1\n", ret);
+
+ buffer[15]= 0x0;
+ printf("changing char 15 (offset (%d+15) = %d) to 0x0\n", offset, offset+15);
+ number=offset+15;
+
+ ret=databinchk('c', &buffer[1], size-1, offset+1, &errmsg);
+ printf("databinchk('c', &buffer[1], %d, %d, &errmsg) returned %d: %s\n",
+ size-1, offset+1, ret, errmsg);
+ if (ret == number)
+ printf("\tPASS return value of %d as expected\n", number);
+ else
+ printf("\tFAIL return value %d, expected %d\n", ret, number);
+
+printf("***** for C ****************************\n");
+
+ databingen('C', buffer, size, 0);
+ printf("databingen('C', buffer, %d, 0)\n", size);
+
+ ret=databinchk('C', buffer, size, 0, &errmsg);
+ printf("databinchk('C', buffer, %d, 0, &errmsg) returned %d: %s\n",
+ size, ret, errmsg);
+ if (ret == -1)
+ printf("\tPASS return value of -1 as expected\n");
+ else
+ printf("\tFAIL return value %d, expected -1\n", ret);
+
+ offset=18;
+ ret=databinchk('C', &buffer[18], size-18, 18, &errmsg);
+ printf("databinchk('C', &buffer[18], %d, 18, &errmsg) returned %d: %s\n",
+ size-18, ret, errmsg);
+ if (ret == -1)
+ printf("\tPASS return value of -1 as expected\n");
+ else
+ printf("\tFAIL return value %d, expected -1\n", ret);
+
+ buffer[20]= 0x0;
+ buffer[21]= 0x0;
+ printf("changing char 20 and 21 to 0x0 (offset %d and %d)\n", 20,
+ 21);
+
+ ret=databinchk('C', &buffer[18], size-18, 18, &errmsg);
+ printf("databinchk('C', &buffer[18], %d, 18, &errmsg) returned %d: %s\n",
+ size-18, ret, errmsg);
+
+ if (ret == 20 || ret == 21)
+ printf("\tPASS return value of %d or %d as expected\n",
+ 20, 21);
+ else
+ printf("\tFAIL return value %d, expected %d or %d\n", ret,
+ 20, 21 );
+
+ exit(0);
+
+}
+
+#endif
diff --git a/ltp_framework/lib/datapid.c b/ltp_framework/lib/datapid.c
new file mode 100644
index 0000000..eb84b1d
--- /dev/null
+++ b/ltp_framework/lib/datapid.c
@@ -0,0 +1,373 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+/************
+
+64 bits in a Cray word
+
+ 12345678901234567890123456789012
+1234567890123456789012345678901234567890123456789012345678901234
+________________________________________________________________
+< pid >< word-offset in file (same #) >< pid >
+
+1234567890123456789012345678901234567890123456789012345678901234
+________________________________________________________________
+< pid >< offset in file of this word >< pid >
+
+
+8 bits to a bytes == character
+ NBPW 8
+************/
+
+#include <stdio.h>
+#include <sys/param.h>
+#ifdef UNIT_TEST
+#include <unistd.h>
+#include <stdlib.h>
+#endif
+
+static char Errmsg[80];
+
+#define LOWER16BITS(X) (X & 0177777)
+#define LOWER32BITS(X) (X & 0xffffffff)
+
+/***
+#define HIGHBITS(WRD, bits) ( (-1 << (64-bits)) & WRD)
+#define LOWBITS(WRD, bits) ( (-1 >> (64-bits)) & WRD)
+****/
+
+#define NBPBYTE 8 /* number bits per byte */
+
+#ifndef DEBUG
+#define DEBUG 0
+#endif
+
+/***********************************************************************
+ *
+ *
+ * 1 2 3 4 5 6 7 8 9 10 11 12 13 14 14 15 bytes
+ * 1234567890123456789012345678901234567890123456789012345678901234 bits
+ * ________________________________________________________________ 1 word
+ * < pid >< offset in file of this word >< pid >
+ *
+ * the words are put together where offset zero is the start.
+ * thus, offset 16 is the start of the second full word
+ * Thus, offset 8 is in middle of word 1
+ ***********************************************************************/
+int
+datapidgen(pid, buffer, bsize, offset)
+int pid;
+char *buffer;
+int bsize;
+int offset;
+{
+#if CRAY
+
+ int cnt;
+ int tmp;
+ char *chr;
+ long *wptr;
+ long word;
+ int woff; /* file offset for the word */
+ int boff; /* buffer offset or index */
+ int num_full_words;
+
+ num_full_words = bsize/NBPW;
+ boff = 0;
+
+ if (cnt=(offset % NBPW)) { /* partial word */
+
+ woff = offset - cnt;
+#if DEBUG
+printf("partial at beginning, cnt = %d, woff = %d\n", cnt, woff);
+#endif
+
+ word = ((LOWER16BITS(pid) << 48) | (LOWER32BITS(woff) << 16) | LOWER16BITS(pid));
+
+ chr = (char *)&word;
+
+ for (tmp=0; tmp<cnt; tmp++) { /* skip unused bytes */
+ chr++;
+ }
+
+ for (; boff<(NBPW-cnt) && boff<bsize; boff++, chr++) {
+ buffer[boff] = *chr;
+ }
+ }
+
+ /*
+ * full words
+ */
+
+ num_full_words = (bsize-boff)/NBPW;
+
+ woff = offset+boff;
+
+ for (cnt=0; cnt<num_full_words; woff += NBPW, cnt++) {
+
+ word = ((LOWER16BITS(pid) << 48) | (LOWER32BITS(woff) << 16) | LOWER16BITS(pid));
+
+ chr = (char *)&word;
+ for (tmp=0; tmp<NBPW; tmp++, chr++) {
+ buffer[boff++] = *chr;
+ }
+/****** Only if wptr is a word ellined
+ wptr = (long *)&buffer[boff];
+ *wptr = word;
+ boff += NBPW;
+*****/
+
+ }
+
+ /*
+ * partial word at end of buffer
+ */
+
+ if (cnt=((bsize-boff) % NBPW)) {
+#if DEBUG
+printf("partial at end\n");
+#endif
+ word = ((LOWER16BITS(pid) << 48) | (LOWER32BITS(woff) << 16) | LOWER16BITS(pid));
+
+ chr = (char *)&word;
+
+ for (tmp=0; tmp<cnt && boff<bsize; tmp++, chr++) {
+ buffer[boff++] = *chr;
+ }
+ }
+
+ return bsize;
+
+#else
+ return -1; /* not support on non-64 bits word machines */
+
+#endif
+
+}
+
+/***********************************************************************
+ *
+ *
+ ***********************************************************************/
+int
+datapidchk(pid, buffer, bsize, offset, errmsg)
+int pid;
+char *buffer;
+int bsize;
+int offset;
+char **errmsg;
+{
+#if CRAY
+
+ int cnt;
+ int tmp;
+ char *chr;
+ long *wptr;
+ long word;
+ int woff; /* file offset for the word */
+ int boff; /* buffer offset or index */
+ int num_full_words;
+
+
+ if (errmsg != NULL) {
+ *errmsg = Errmsg;
+ }
+
+
+ num_full_words = bsize/NBPW;
+ boff = 0;
+
+ if (cnt=(offset % NBPW)) { /* partial word */
+ woff = offset - cnt;
+ word = ((LOWER16BITS(pid) << 48) | (LOWER32BITS(woff) << 16) | LOWER16BITS(pid));
+
+ chr = (char *)&word;
+
+ for (tmp=0; tmp<cnt; tmp++) { /* skip unused bytes */
+ chr++;
+ }
+
+ for (; boff<(NBPW-cnt) && boff<bsize; boff++, chr++) {
+ if (buffer[boff] != *chr) {
+ sprintf(Errmsg, "Data mismatch at offset %d, exp:%#o, act:%#o",
+ offset+boff, *chr, buffer[boff]);
+ return offset+boff;
+ }
+ }
+ }
+
+ /*
+ * full words
+ */
+
+ num_full_words = (bsize-boff)/NBPW;
+
+ woff = offset+boff;
+
+ for (cnt=0; cnt<num_full_words; woff += NBPW, cnt++) {
+ word = ((LOWER16BITS(pid) << 48) | (LOWER32BITS(woff) << 16) | LOWER16BITS(pid));
+
+ chr = (char *)&word;
+ for (tmp=0; tmp<NBPW; tmp++, boff++, chr++) {
+ if (buffer[boff] != *chr) {
+ sprintf(Errmsg, "Data mismatch at offset %d, exp:%#o, act:%#o",
+ woff, *chr, buffer[boff]);
+ return woff;
+ }
+ }
+
+/****** only if a word elined
+ wptr = (long *)&buffer[boff];
+ if (*wptr != word) {
+ sprintf(Errmsg, "Data mismatch at offset %d, exp:%#o, act:%#o",
+ woff, word, *wptr);
+ return woff;
+ }
+ boff += NBPW;
+******/
+ }
+
+ /*
+ * partial word at end of buffer
+ */
+
+ if (cnt=((bsize-boff) % NBPW)) {
+#if DEBUG
+printf("partial at end\n");
+#endif
+ word = ((LOWER16BITS(pid) << 48) | (LOWER32BITS(woff) << 16) | LOWER16BITS(pid));
+
+ chr = (char *)&word;
+
+
+ for (tmp=0; tmp<cnt && boff<bsize; boff++, tmp++, chr++) {
+ if (buffer[boff] != *chr) {
+ sprintf(Errmsg, "Data mismatch at offset %d, exp:%#o, act:%#o",
+ offset+boff, *chr, buffer[boff]);
+ return offset+boff;
+ }
+ }
+ }
+
+ sprintf(Errmsg, "all %d bytes match desired pattern", bsize);
+ return -1; /* buffer is ok */
+
+#else
+
+ if (errmsg != NULL) {
+ *errmsg = Errmsg;
+ }
+ sprintf(Errmsg, "Not supported on this OS.");
+ return 0;
+
+#endif
+
+
+} /* end of datapidchk */
+
+#if UNIT_TEST
+
+/***********************************************************************
+ * main for doing unit testing
+ ***********************************************************************/
+int
+main(ac, ag)
+int ac;
+char **ag;
+{
+
+int size=1234;
+char *buffer;
+int ret;
+char *errmsg;
+
+ if ((buffer=(char *)malloc(size)) == NULL) {
+ perror("malloc");
+ exit(2);
+ }
+
+
+ datapidgen(-1, buffer, size, 3);
+
+/***
+fwrite(buffer, size, 1, stdout);
+fwrite("\n", 1, 1, stdout);
+****/
+
+ printf("datapidgen(-1, buffer, size, 3)\n");
+
+ ret=datapidchk(-1, buffer, size, 3, &errmsg);
+ printf("datapidchk(-1, buffer, %d, 3, &errmsg) returned %d %s\n",
+ size, ret, errmsg);
+ ret=datapidchk(-1, &buffer[1], size-1, 4, &errmsg);
+ printf("datapidchk(-1, &buffer[1], %d, 4, &errmsg) returned %d %s\n",
+ size-1, ret, errmsg);
+
+ buffer[25]= 0x0;
+ buffer[26]= 0x0;
+ buffer[27]= 0x0;
+ buffer[28]= 0x0;
+ printf("changing char 25-28\n");
+
+ ret=datapidchk(-1, &buffer[1], size-1, 4, &errmsg);
+ printf("datapidchk(-1, &buffer[1], %d, 4, &errmsg) returned %d %s\n",
+ size-1, ret, errmsg);
+
+printf("------------------------------------------\n");
+
+ datapidgen(getpid(), buffer, size, 5);
+
+/*******
+fwrite(buffer, size, 1, stdout);
+fwrite("\n", 1, 1, stdout);
+******/
+
+ printf("\ndatapidgen(getpid(), buffer, size, 5)\n");
+
+ ret=datapidchk(getpid(), buffer, size, 5, &errmsg);
+ printf("datapidchk(getpid(), buffer, %d, 5, &errmsg) returned %d %s\n",
+ size, ret, errmsg);
+
+ ret=datapidchk(getpid(), &buffer[1], size-1, 6, &errmsg);
+ printf("datapidchk(getpid(), &buffer[1], %d, 6, &errmsg) returned %d %s\n",
+ size-1, ret, errmsg);
+
+ buffer[25]= 0x0;
+ printf("changing char 25\n");
+
+ ret=datapidchk(getpid(), &buffer[1], size-1, 6, &errmsg);
+ printf("datapidchk(getpid(), &buffer[1], %d, 6, &errmsg) returned %d %s\n",
+ size-1, ret, errmsg);
+
+ exit(0);
+}
+
+#endif
diff --git a/ltp_framework/lib/file_lock.c b/ltp_framework/lib/file_lock.c
new file mode 100644
index 0000000..300b9d7
--- /dev/null
+++ b/ltp_framework/lib/file_lock.c
@@ -0,0 +1,208 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/file.h>
+#include <sys/param.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <errno.h>
+#include <sys/sysmacros.h>
+#include <string.h> /* memset, strerror */
+#include "file_lock.h"
+
+
+#ifndef EFSEXCLWR
+#define EFSEXCLWR 503
+#endif
+
+/*
+ * String containing the last system call.
+ *
+ */
+char Fl_syscall_str[128];
+
+static char errmsg[256];
+
+/***********************************************************************
+ *
+ * Test interface to the fcntl system call.
+ * It will loop if the LOCK_NB flags is NOT set.
+ ***********************************************************************/
+int
+file_lock(fd, flags, errormsg)
+int fd;
+int flags;
+char **errormsg;
+{
+ register int cmd, ret;
+ struct flock flocks;
+
+ memset(&flocks, 0, sizeof(struct flock));
+
+ if (flags&LOCK_NB)
+ cmd = F_SETLK;
+ else
+ cmd = F_SETLKW;
+
+ flocks.l_whence = 0;
+ flocks.l_start = 0;
+ flocks.l_len = 0;
+
+ if (flags&LOCK_UN)
+ flocks.l_type = F_UNLCK;
+ else if (flags&LOCK_EX)
+ flocks.l_type = F_WRLCK;
+ else if (flags&LOCK_SH)
+ flocks.l_type = F_RDLCK;
+ else {
+ errno = EINVAL;
+ if (errormsg != NULL) {
+ sprintf(errmsg,
+ "Programmer error, called file_lock with in valid flags\n");
+ *errormsg = errmsg;
+ }
+ return -1;
+ }
+
+ sprintf(Fl_syscall_str,
+ "fcntl(%d, %d, &flocks): type:%d whence:%d, start:%lld len:%lld\n",
+ fd, cmd, flocks.l_type, flocks.l_whence,
+ (long long)flocks.l_start, (long long)flocks.l_len);
+
+ while (1) {
+ ret = fcntl(fd, cmd, &flocks);
+
+ if (ret < 0) {
+ if (cmd == F_SETLK)
+ switch (errno) {
+ /* these errors are okay */
+ case EACCES: /* Permission denied */
+ case EINTR: /* interrupted system call */
+#ifdef EFILESH
+ case EFILESH: /* file shared */
+#endif
+ case EFSEXCLWR: /* File is write protected */
+ continue; /* retry getting lock */
+ }
+ if (errormsg != NULL) {
+ sprintf(errmsg, "fcntl(%d, %d, &flocks): errno:%d %s\n",
+ fd, cmd, errno, strerror(errno));
+ *errormsg = errmsg;
+ }
+ return -1;
+ }
+ break;
+ }
+
+ return ret;
+
+} /* end of file_lock */
+
+/***********************************************************************
+ *
+ * Test interface to the fcntl system call.
+ * It will loop if the LOCK_NB flags is NOT set.
+ ***********************************************************************/
+int
+record_lock(fd, flags, start, len, errormsg)
+int fd;
+int flags;
+int start;
+int len;
+char **errormsg;
+{
+ register int cmd, ret;
+ struct flock flocks;
+
+ memset(&flocks, 0, sizeof(struct flock));
+
+ if (flags&LOCK_NB)
+ cmd = F_SETLK;
+ else
+ cmd = F_SETLKW;
+
+ flocks.l_whence = 0;
+ flocks.l_start = start;
+ flocks.l_len = len;
+
+ if (flags&LOCK_UN)
+ flocks.l_type = F_UNLCK;
+ else if (flags&LOCK_EX)
+ flocks.l_type = F_WRLCK;
+ else if (flags&LOCK_SH)
+ flocks.l_type = F_RDLCK;
+ else {
+ errno = EINVAL;
+ if (errormsg != NULL) {
+ sprintf(errmsg,
+ "Programmer error, called record_lock with in valid flags\n");
+ *errormsg = errmsg;
+ }
+ return -1;
+ }
+
+ sprintf(Fl_syscall_str,
+ "fcntl(%d, %d, &flocks): type:%d whence:%d, start:%lld len:%lld\n",
+ fd, cmd, flocks.l_type, flocks.l_whence,
+ (long long)flocks.l_start, (long long)flocks.l_len);
+
+ while (1) {
+ ret = fcntl(fd, cmd, &flocks);
+
+ if (ret < 0) {
+ if (cmd == F_SETLK)
+ switch (errno) {
+ /* these errors are okay */
+ case EACCES: /* Permission denied */
+ case EINTR: /* interrupted system call */
+#ifdef EFILESH
+ case EFILESH: /* file shared */
+#endif
+ case EFSEXCLWR: /* File is write protected */
+ continue; /* retry getting lock */
+ }
+ if (errormsg != NULL) {
+ sprintf(errmsg, "fcntl(%d, %d, &flocks): errno:%d %s\n",
+ fd, cmd, errno, strerror(errno));
+ *errormsg = errmsg;
+ }
+ return -1;
+ }
+ break;
+ }
+
+ return ret;
+
+} /* end of record_lock */
+
diff --git a/ltp_framework/lib/forker.c b/ltp_framework/lib/forker.c
new file mode 100644
index 0000000..ad8b4a7
--- /dev/null
+++ b/ltp_framework/lib/forker.c
@@ -0,0 +1,281 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+/**************************************************************
+ *
+ * OS Testing - Silicon Graphics, Inc.
+ *
+ * FUNCTION NAME : forker
+ * background
+ *
+ * FUNCTION TITLE : fork desired number of copies of the current process
+ * fork a process and return control to caller
+ *
+ * SYNOPSIS:
+ * int forker(ncopies, mode, prefix)
+ * int ncopies;
+ * int mode;
+ * char *prefix;
+ *
+ * int background(prefix);
+ * char *prefix;
+ *
+ * AUTHOR : Richard Logan
+ *
+ * CO-PILOT(s) : Dean Roehrich
+ *
+ * INITIAL RELEASE : UNICOS 8.0
+ *
+ * DESIGN DESCRIPTION
+ * The background function will do a fork of the current process.
+ * The parent process will then exit, thus orphaning the
+ * child process. Doing this will not nice the child process
+ * like executing a cmd in the background using "&" from the shell.
+ * If the fork fails and prefix is not NULL, a error message is printed
+ * to stderr and the process will exit with a value of errno.
+ *
+ * The forker function will fork <ncopies> minus one copies
+ * of the current process. There are two modes in how the forks
+ * will be done. Mode 0 (default) will have all new processes
+ * be childern of the parent process. Using Mode 1,
+ * the parent process will have one child and that child will
+ * fork the next process, if necessary, and on and on.
+ * The forker function will return the number of successful
+ * forks. This value will be different for the parent and each child.
+ * Using mode 0, the parent will get the total number of successful
+ * forks. Using mode 1, the newest child will get the total number
+ * of forks. The parent will get a return value of 1.
+ *
+ * The forker function also updates the global variables
+ * Forker_pids[] and Forker_npids. The Forker_pids array will
+ * be updated to contain the pid of each new process. The
+ * Forker_npids variable contains the number of entries
+ * in Forker_pids. Note, not all processes will have
+ * access to all pids via Forker_pids. If using mode 0, only the
+ * parent process and the last process will have all information.
+ * If using mode 1, only the last child process will have all information.
+ *
+ * If the prefix parameter is not NULL and the fork system call fails,
+ * a error message will be printed to stderr. The error message
+ * the be preceeded with prefix string. If prefix is NULL,
+ * no error message is printed.
+ *
+ * SPECIAL REQUIREMENTS
+ * None.
+ *
+ * UPDATE HISTORY
+ * This should contain the description, author, and date of any
+ * "interesting" modifications (i.e. info should helpful in
+ * maintaining/enhancing this module).
+ * username description
+ * ----------------------------------------------------------------
+ * rrl This functions will first written during
+ * the SFS testing days, 1993.
+ *
+ * BUGS/LIMITATIONS
+ * The child pids are stored in the fixed array, Forker_pids.
+ * The array only has space for 4098 pids. Only the first
+ * 4098 pids will be stored in the array.
+ *
+ **************************************************************/
+
+#include <stdio.h>
+#include <errno.h>
+#include <unistd.h> /* fork, getpid, sleep */
+#include <string.h>
+#include <stdlib.h> /* exit */
+#include "forker.h"
+
+int Forker_pids[FORKER_MAX_PIDS]; /* holds pids of forked processes */
+int Forker_npids=0; /* number of entries in Forker_pids */
+
+/***********************************************************************
+ *
+ * This function will fork and the parent will exit zero and
+ * the child will return. This will orphan the returning process
+ * putting it in the background.
+ *
+ * Return Value
+ * 0 : if fork did not fail
+ * !0 : if fork failed, the return value will be the errno.
+ ***********************************************************************/
+int
+background(prefix)
+char *prefix;
+{
+ switch (fork()) {
+ case -1:
+ if (prefix != NULL)
+ fprintf(stderr, "%s: In %s background(), fork() failed, errno:%d %s\n",
+ prefix, __FILE__, errno, strerror(errno));
+ exit(errno);
+
+ case 0: /* child process */
+ break;
+
+ default:
+ exit(0);
+ }
+
+ return 0;
+
+} /* end of background */
+
+/***********************************************************************
+ * Forker will fork ncopies-1 copies of self.
+ *
+ ***********************************************************************/
+int
+forker(ncopies, mode, prefix)
+int ncopies;
+int mode; /* 0 - all childern of parent, 1 - only 1 direct child */
+char *prefix; /* if ! NULL, an message will be printed to stderr */
+ /* if fork fails. The prefix (program name) will */
+ /* preceed the message */
+{
+ int cnt;
+ int pid;
+ static int ind = 0;
+
+ Forker_pids[ind]=0;
+
+ for (cnt=1; cnt < ncopies; cnt++) {
+
+ switch ( mode ) {
+ case 1 : /* only 1 direct child */
+ if ((pid = fork()) == -1) {
+ if (prefix != NULL)
+ fprintf(stderr, "%s: %s,forker(): fork() failed, errno:%d %s\n",
+ prefix, __FILE__, errno, strerror(errno));
+ return 0;
+ }
+ Forker_npids++;
+
+ switch (pid ) {
+ case 0: /* child - continues the forking */
+
+ if (Forker_npids < FORKER_MAX_PIDS)
+ Forker_pids[Forker_npids-1]=getpid();
+ break;
+
+ default: /* parent - stop the forking */
+ if (Forker_npids < FORKER_MAX_PIDS)
+ Forker_pids[Forker_npids-1]=pid;
+ return cnt-1;
+ }
+
+ break;
+
+ default : /* all new processes are childern of parent */
+ if ((pid = fork()) == -1) {
+ if (prefix != NULL)
+ fprintf(stderr, "%s: %s,forker(): fork() failed, errno:%d %s\n",
+ prefix, __FILE__, errno, strerror(errno));
+ return cnt-1;
+ }
+ Forker_npids++;
+
+ switch (pid ) {
+ case 0: /* child - stops the forking */
+ if (Forker_npids < FORKER_MAX_PIDS)
+ Forker_pids[Forker_npids-1]=getpid();
+ return cnt;
+
+ default: /* parent - continues the forking */
+ if (Forker_npids < FORKER_MAX_PIDS)
+ Forker_pids[Forker_npids-1]=pid;
+ break;
+ }
+ break;
+ }
+ }
+
+ if (Forker_npids < FORKER_MAX_PIDS)
+ Forker_pids[Forker_npids]=0;
+ return cnt-1;
+
+} /* end of forker */
+
+
+#if UNIT_TEST
+
+/*
+ * The following is a unit test main for the background and forker
+ * functions.
+ */
+
+int
+main(argc, argv)
+int argc;
+char **argv;
+{
+ int ncopies=1;
+ int mode=0;
+ int ret;
+ int ind;
+
+ if (argc == 1) {
+ printf("Usage: %s ncopies [mode]\n", argv[0]);
+ exit(1);
+ }
+
+ if (sscanf(argv[1], "%i", &ncopies) != 1) {
+ printf("%s: ncopies argument must be integer\n", argv[0]);
+ exit(1);
+ }
+
+ if (argc == 3)
+ if (sscanf(argv[2], "%i", &mode) != 1) {
+ printf("%s: mode argument must be integer\n", argv[0]);
+ exit(1);
+ }
+
+ printf("Starting Pid = %d\n", getpid());
+ ret=background(argv[0]);
+ printf("After background() ret:%d, pid = %d\n", ret, getpid());
+
+ ret=forker(ncopies, mode, argv[0]);
+
+ printf("forker(%d, %d, %s) ret:%d, pid = %d, sleeping 30 seconds.\n",
+ ncopies, mode, argv[0], ret, getpid());
+
+ printf("%d My version of Forker_pids[], Forker_npids = %d\n",
+ getpid(), Forker_npids);
+
+ for (ind=0; ind<Forker_npids; ind++) {
+ printf("%d ind:%-2d pid:%d\n", getpid(), ind, Forker_pids[ind]);
+ }
+
+ sleep(30);
+ exit(0);
+}
+
+#endif /* UNIT_TEST */ \ No newline at end of file
diff --git a/ltp_framework/lib/get_high_address.c b/ltp_framework/lib/get_high_address.c
new file mode 100644
index 0000000..72cacef
--- /dev/null
+++ b/ltp_framework/lib/get_high_address.c
@@ -0,0 +1,40 @@
+/* $Header: /cvsroot/ltp/ltp/lib/get_high_address.c,v 1.6 2009/07/20 10:59:32 vapier Exp $ */
+
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+
+#include <unistd.h>
+
+char *get_high_address(void)
+{
+ return (char *)sbrk(0) + (4 * getpagesize());
+} \ No newline at end of file
diff --git a/ltp_framework/lib/get_path.c b/ltp_framework/lib/get_path.c
new file mode 100644
index 0000000..6501a06
--- /dev/null
+++ b/ltp_framework/lib/get_path.c
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2010 Cyril Hrubis chrubis@suse.cz
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ */
+
+ /*
+ * Looks for binary prog_name in $PATH.
+ *
+ * If such file exists and if you are able at least to read it, zero is
+ * returned and absolute path to the file is filled into buf. In case buf is
+ * too short to hold the absolute path + prog_name for the file we are looking
+ * for -1 is returned as well as when there is no such file in all paths in
+ * $PATH.
+ */
+
+#include "test.h"
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#define MIN(a, b) ((a)<(b)?(a):(b))
+
+static int file_exist(const char *path)
+{
+ struct stat st;
+
+ if (!access(path, R_OK) && !stat(path, &st) && S_ISREG(st.st_mode))
+ return 1;
+
+ return 0;
+}
+
+int tst_get_path(const char *prog_name, char *buf, size_t buf_len)
+{
+ const char *path = (const char*) getenv("PATH");
+ const char *start = path;
+ const char *end;
+ size_t size, ret;
+
+
+ if (path == NULL)
+ return -1;
+
+ do {
+ end = strchr(start, ':');
+
+ if (end != NULL)
+ snprintf(buf, MIN(buf_len, (size_t)(end - start + 1)), "%s", start);
+ else
+ snprintf(buf, buf_len, "%s", start);
+
+ size = strlen(buf);
+
+ /*
+ * "::" inside $PATH, $PATH ending with ':' or $PATH starting
+ * with ':' should be expanded into current working directory.
+ */
+ if (size == 0) {
+ snprintf(buf, buf_len, ".");
+ size = strlen(buf);
+ }
+
+ /*
+ * If there is no '/' ad the end of path from $PATH add it.
+ */
+ if (buf[size - 1] != '/')
+ ret = snprintf(buf + size, buf_len - size, "/%s", prog_name);
+ else
+ ret = snprintf(buf + size, buf_len - size, "%s", prog_name);
+
+ if (buf_len - size > ret && file_exist(buf))
+ return 0;
+
+ start = end + 1;
+
+ } while (end != NULL);
+
+ return -1;
+} \ No newline at end of file
diff --git a/ltp_framework/lib/libltp.a b/ltp_framework/lib/libltp.a
new file mode 100644
index 0000000..6f969a4
--- /dev/null
+++ b/ltp_framework/lib/libltp.a
Binary files differ
diff --git a/ltp_framework/lib/libtestsuite.c b/ltp_framework/lib/libtestsuite.c
new file mode 100644
index 0000000..1703ff7
--- /dev/null
+++ b/ltp_framework/lib/libtestsuite.c
@@ -0,0 +1,164 @@
+/*
+ *
+ * Copyright (c) International Business Machines Corp., 2001
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
+ * the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * NAME
+ * libtestsuite.c
+ *
+ * DESCRIPTION
+ * file containing generic routines which are used by some of the LTP
+ * testsuite tests. Currently, the following routines are present in
+ * this library:
+ *
+ * my_getpwnam(), do_file_setup()
+ *
+ * HISTORY
+ * 11/03/2008 Renaud Lottiaux (Renaud.Lottiaux@kerlabs.com)
+ * - Add the following functions to synchronise father and sons processes
+ * sync_pipe_create(), sync_pipe_wait(), sync_pipe_notify()
+ */
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <pwd.h>
+#include <errno.h>
+
+#include "libtestsuite.h"
+#include "test.h"
+#include "usctest.h"
+
+struct passwd *
+my_getpwnam(char *name)
+{
+ struct passwd *saved_pwent;
+ struct passwd *pwent;
+
+ if ((pwent = getpwnam(name)) == NULL) {
+ perror("getpwnam");
+ tst_brkm(TBROK, NULL, "getpwnam() failed");
+ }
+ saved_pwent = (struct passwd *)malloc(sizeof(struct passwd));
+
+ *saved_pwent = *pwent;
+
+ return(saved_pwent);
+}
+
+void
+do_file_setup(char *fname)
+{
+ int fd;
+
+ if ((fd = open(fname,O_RDWR|O_CREAT,0700)) == -1) {
+ tst_resm(TBROK, "open(%s, O_RDWR|O_CREAT,0700) Failed, "
+ "errno=%d : %s", fname, errno, strerror(errno));
+ }
+
+ if (close(fd) == -1) {
+ tst_resm(TWARN, "close(%s) Failed on file create, errno=%d : "
+ "%s", fname, errno, strerror(errno));
+ }
+}
+
+static char pipe_name[256];
+
+void generate_pipe_name(const char *name)
+{
+ char *p;
+
+ p = strrchr(name, '/');
+ if (p == NULL)
+ p = (char *) name;
+ else
+ p++;
+ snprintf(pipe_name, 255, "%s/ltp_fifo_%s", P_tmpdir, p);
+}
+
+int sync_pipe_create(int fd[], const char *name)
+{
+ int ret;
+
+ if (name != NULL) {
+ generate_pipe_name(name);
+
+ ret = open(pipe_name, O_RDWR);
+ if (ret != -1) {
+ fd[0] = ret;
+ fd[1] = open(pipe_name, O_RDWR);
+ } else {
+ ret = mkfifo(pipe_name, S_IRWXU);
+ if (!ret) {
+ fd[0] = open(pipe_name, O_RDWR);
+ fd[1] = open(pipe_name, O_RDWR);
+ }
+ }
+ return ret;
+ } else
+ return pipe(fd);
+}
+
+int sync_pipe_close(int fd[], const char *name)
+{
+ int r = 0;
+
+ if (fd[0] != -1)
+ r = close (fd[0]);
+ if (fd[1] != -1)
+ r |= close (fd[1]);
+
+ if (name != NULL) {
+ generate_pipe_name(name);
+ unlink(pipe_name);
+ }
+ return r;
+}
+
+int sync_pipe_wait(int fd[])
+{
+ char buf;
+ int r;
+
+ if (fd[1] != -1) {
+ close (fd[1]);
+ fd[1] = -1;
+ }
+
+ r = read (fd[0], &buf, 1);
+
+ if ((r != 1) || (buf != 'A'))
+ return -1;
+ return 0;
+}
+
+int sync_pipe_notify(int fd[])
+{
+ char buf = 'A';
+ int r;
+
+ if (fd[0] != -1) {
+ close (fd[0]);
+ fd[0] = -1;
+ }
+
+ r = write (fd[1], &buf, 1);
+
+ if (r != 1)
+ return -1;
+ return 0;
+} \ No newline at end of file
diff --git a/ltp_framework/lib/ltp.pc b/ltp_framework/lib/ltp.pc
new file mode 100644
index 0000000..5c4c042
--- /dev/null
+++ b/ltp_framework/lib/ltp.pc
@@ -0,0 +1,10 @@
+prefix=/opt/ltp
+exec_prefix=${prefix}
+includedir=${prefix}/include
+libdir=${exec_prefix}/lib
+
+Name: LTP
+Description: Linux Test Project
+Version: LTP_VERSION
+Libs: -L${libdir} -lltp
+Cflags: -I${includedir}
diff --git a/ltp_framework/lib/ltp.pc.in b/ltp_framework/lib/ltp.pc.in
new file mode 100644
index 0000000..9620129
--- /dev/null
+++ b/ltp_framework/lib/ltp.pc.in
@@ -0,0 +1,10 @@
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+includedir=@includedir@
+libdir=@libdir@
+
+Name: LTP
+Description: Linux Test Project
+Version: @VERSION@
+Libs: -L${libdir} -lltp
+Cflags: -I${includedir}
diff --git a/ltp_framework/lib/mount_utils.c b/ltp_framework/lib/mount_utils.c
new file mode 100644
index 0000000..5a9fd8c
--- /dev/null
+++ b/ltp_framework/lib/mount_utils.c
@@ -0,0 +1,213 @@
+#define _GNU_SOURCE
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <stdio.h>
+#include <mntent.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+/*
+ * Return the block device for a given path. You must free the string after you
+ * call this function.
+ *
+ * Returns NULL if the device isn't found, memory couldn't be allocated, or if
+ * the `block device' isn't a real block device (e.g. nfs mounts, etc).
+ */
+char *
+get_block_device(const char *path)
+{
+
+ char *mnt_dir = NULL, *mnt_fsname = NULL;
+ char *resolved_path = NULL;
+ FILE *mtab_f;
+ int done = 0;
+ struct mntent *entry;
+ struct stat junk;
+
+ if (path == NULL) {
+ errno = EINVAL;
+ } else if ((resolved_path = realpath(path, NULL)) != NULL &&
+ (mtab_f = setmntent("/etc/mtab", "r")) != NULL)
+ {
+
+ do {
+
+ entry = getmntent(mtab_f);
+
+ if (entry != NULL) {
+
+ if (!strncmp(entry->mnt_dir, resolved_path, strlen(entry->mnt_dir))) {
+
+ char copy_string = 0;
+
+ if (mnt_dir == NULL) {
+
+ mnt_dir = malloc(strlen(entry->mnt_dir)+1);
+ mnt_fsname = malloc(strlen(entry->mnt_fsname)+1);
+
+ copy_string = mnt_dir != NULL && mnt_fsname != NULL;
+
+ } else {
+
+ if (!strncmp(entry->mnt_dir, mnt_dir, strlen(entry->mnt_dir))) {
+
+ mnt_dir = realloc(mnt_dir, strlen(entry->mnt_dir));
+ mnt_fsname = realloc(mnt_fsname, strlen(entry->mnt_fsname));
+ copy_string = 1;
+
+ }
+
+ }
+
+ if (copy_string != 0) {
+ strcpy(mnt_dir, entry->mnt_dir);
+ strcpy(mnt_fsname, entry->mnt_fsname);
+#if DEBUG
+ printf("%s is a subset of %s\n", path, entry->mnt_dir);
+ } else {
+ printf("%s is not a subset of %s\n", path, entry->mnt_dir);
+#endif
+ }
+
+#if DEBUG
+ } else {
+ printf("%s is not a subset of %s\n", path, entry->mnt_dir);
+#endif
+ }
+
+ }
+
+ } while (done == 0 && entry != NULL);
+
+ endmntent(mtab_f);
+
+ }
+
+ if (mnt_dir != NULL) {
+ free(mnt_dir);
+ }
+ if (resolved_path != NULL) {
+ free(resolved_path);
+ }
+
+ if (mnt_fsname != NULL && stat(mnt_fsname, &junk) < 0 &&
+ errno == ENOENT) {
+ free(mnt_fsname);
+ mnt_fsname = NULL;
+ errno = ENODEV;
+ }
+
+ return mnt_fsname;
+
+}
+
+/*
+ * Return the mountpoint for a given path. You must free the string after you
+ * call this function.
+ *
+ * Returns NULL if memory couldn't be allocated.
+ */
+char *
+get_mountpoint(const char *path)
+{
+
+ char *mnt_dir = NULL;
+ char *resolved_path = NULL;
+ FILE *mtab_f;
+ int done = 0;
+ struct mntent *entry;
+
+ if (path == NULL) {
+ errno = EINVAL;
+ } else if ((resolved_path = realpath(path, NULL)) != NULL &&
+ (mtab_f = setmntent("/etc/mtab", "r")) != NULL)
+ {
+
+ do {
+
+ entry = getmntent(mtab_f);
+
+ if (entry != NULL) {
+
+ if (!strncmp(entry->mnt_dir, resolved_path, strlen(entry->mnt_dir))) {
+
+ char copy_string = 0;
+
+ if (mnt_dir == NULL) {
+
+ mnt_dir = malloc(strlen(entry->mnt_dir)+1);
+ copy_string = mnt_dir != NULL;
+
+ } else {
+
+ if (!strncmp(entry->mnt_dir, mnt_dir, strlen(entry->mnt_dir))) {
+
+ mnt_dir = realloc(mnt_dir, strlen(entry->mnt_dir));
+ copy_string = 1;
+
+ }
+
+ }
+
+ if (copy_string != 0) {
+ strcpy(mnt_dir, entry->mnt_dir);
+#if DEBUG
+ printf("%s is a subset of %s\n", path, entry->mnt_dir);
+ } else {
+ printf("%s is not a subset of %s\n", path, entry->mnt_dir);
+#endif
+ }
+
+#if DEBUG
+ } else {
+ printf("%s is not a subset of %s\n", path, entry->mnt_dir);
+#endif
+ }
+
+ }
+
+ } while (done == 0 && entry != NULL);
+
+ endmntent(mtab_f);
+
+ }
+
+ if (resolved_path != NULL) {
+ free(resolved_path);
+ }
+
+ return mnt_dir;
+
+}
+#if UNIT_TEST
+int
+main(void)
+{
+
+ char *mnt_fsname;
+ char *paths[] = {
+ "/home",
+ "/mnt",
+ "/tmp/foo", /* mkdir /tmp/foo; mount -t tmpfs none /tmp/foo/ */
+ "/proc",
+ "/optimus/store"
+ };
+ int i;
+
+ for (i = 0; i < sizeof(paths) / sizeof(*paths); i++) {
+ mnt_fsname = get_block_device(paths[i]);
+ printf("%s - %s\n", paths[i], mnt_fsname);
+ if (mnt_fsname != NULL) {
+ free(mnt_fsname);
+ mnt_fsname = NULL;
+ }
+ }
+
+ return 0;
+
+}
+#endif \ No newline at end of file
diff --git a/ltp_framework/lib/open_flags.c b/ltp_framework/lib/open_flags.c
new file mode 100644
index 0000000..5623382
--- /dev/null
+++ b/ltp_framework/lib/open_flags.c
@@ -0,0 +1,330 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+/**************************************************************
+ *
+ * OS Testing - Silicon Graphics, Inc.
+ *
+ * FUNCTION NAME : parse_open_flags
+ * openflags2symbols
+ *
+ * FUNCTION TITLE : converts open flag symbols into bitmask
+ * converts open flag bitmask into symbols
+ *
+ * SYNOPSIS:
+ * int parse_open_flags(symbols, badname)
+ * char *symbols;
+ * char **badname;
+ *
+ * char *openflags2symbols(openflags, sep, mode)
+ * int openflags;
+ * char *sep;
+ * int mode;
+ *
+ * AUTHOR : Richard Logan
+ *
+ * CO-PILOT(s) : Dean Roehrich
+ *
+ * INITIAL RELEASE : UNICOS 8.0
+ *
+ * DESIGN DESCRIPTION
+ * The parse_open_flags function can be used to convert
+ * a list of comma separated open(2) flag symbols (i.e. O_TRUNC)
+ * into the bitmask that can be used by open(2).
+ * If a symbol is unknown and <badname> is not NULL, <badname>
+ * will updated to point that symbol in <string>.
+ * Parse_open_flags will return -1 on this error.
+ * Otherwise parse_open_flags will return the open flag bitmask.
+ * If parse_open_flags returns, <string> will left unchanged.
+ *
+ * The openflags2symbols function attempts to convert open flag
+ * bits into human readable symbols (i.e. O_TRUNC). If there
+ * are more than one symbol, the <sep> string will be placed as
+ * a separator between symbols. Commonly used separators would
+ * be a comma "," or pipe "|". If <mode> is one and not all
+ * <openflags> bits can be converted to symbols, the "UNKNOWN"
+ * symbol will be added to return string.
+ * Openflags2symbols will return the indentified symbols.
+ * If no symbols are recognized the return value will be a empty
+ * string or the "UNKNOWN" symbol.
+ *
+ * SPECIAL REQUIREMENTS
+ * None.
+ *
+ * UPDATE HISTORY
+ * This should contain the description, author, and date of any
+ * "interesting" modifications (i.e. info should helpful in
+ * maintaining/enhancing this module).
+ * username description
+ * ----------------------------------------------------------------
+ * rrl This code was first created during the beginning
+ * of the SFS testing days. I think that was in 1993.
+ * This code was updated in 05/96.
+ * (05/96) openflags2symbols was written.
+ *
+ * BUGS/LIMITATIONS
+ * Currently (05/96) all known symbols are coded into openflags2symbols.
+ * If new open flags are added this code will have to updated
+ * to know about them or they will not be recognized.
+ *
+ **************************************************************/
+
+#include <stdio.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/param.h>
+#include <string.h> /* strcat */
+#include "open_flags.h"
+
+#define UNKNOWN_SYMBOL "UNKNOWN"
+
+static char Open_symbols[512]; /* space for openflags2symbols return value */
+
+struct open_flag_t {
+ char *symbol;
+ int flag;
+};
+
+static struct open_flag_t Open_flags[] = {
+ { "O_RDONLY", O_RDONLY },
+ { "O_WRONLY", O_WRONLY },
+ { "O_RDWR", O_RDWR },
+ { "O_SYNC", O_SYNC },
+ { "O_CREAT", O_CREAT },
+ { "O_TRUNC", O_TRUNC },
+ { "O_EXCL", O_EXCL },
+ { "O_APPEND", O_APPEND },
+ { "O_NONBLOCK", O_NONBLOCK },
+#if O_NOCTTY
+ { "O_NOCTTY", O_NOCTTY },
+#endif
+#if O_DSYNC
+ { "O_DSYNC", O_DSYNC },
+#endif
+#if O_RSYNC
+ { "O_RSYNC", O_RSYNC },
+#endif
+#if O_ASYNC
+ { "O_ASYNC", O_ASYNC },
+#endif
+#if O_PTYIGN
+ { "O_PTYIGN", O_PTYIGN },
+#endif
+#if O_NDELAY
+ { "O_NDELAY", O_NDELAY },
+#endif
+#if O_RAW
+ { "O_RAW", O_RAW },
+#endif
+#ifdef O_SSD
+ { "O_SSD", O_SSD },
+#endif
+#if O_BIG
+ { "O_BIG", O_BIG },
+#endif
+#if O_PLACE
+ { "O_PLACE", O_PLACE },
+#endif
+#if O_RESTART
+ { "O_RESTART", O_RESTART },
+#endif
+#if O_SFSXOP
+ { "O_SFSXOP", O_SFSXOP },
+#endif
+#if O_SFS_DEFER_TM
+ { "O_SFS_DEFER_TM", O_SFS_DEFER_TM },
+#endif
+#if O_WELLFORMED
+ { "O_WELLFORMED", O_WELLFORMED },
+#endif
+#if O_LDRAW
+ { "O_LDRAW", O_LDRAW },
+#endif
+#if O_T3D
+ { "O_T3D", O_T3D },
+#endif /* O_T3D */
+#if O_PARALLEL
+ { "O_PARALLEL", O_PARALLEL },
+ { "O_FSA", O_PARALLEL|O_WELLFORMED|O_RAW }, /* short cut */
+#endif /* O_PARALLEL */
+#ifdef O_LARGEFILE
+ { "O_LARGEFILE", O_LARGEFILE },
+#endif
+#ifdef O_DIRECT
+ { "O_DIRECT", O_DIRECT },
+#endif
+#ifdef O_PRIV
+ { "O_PRIV", O_PRIV },
+#endif
+
+};
+
+int
+parse_open_flags(char *string, char **badname)
+{
+ int bits = 0;
+ char *name;
+ char *cc;
+ char savecc;
+ int found;
+ unsigned int ind;
+
+ name=string;
+ cc=name;
+
+ while ( 1 ) {
+
+ for (; ((*cc != ',') && (*cc != '\0')); cc++);
+ savecc = *cc;
+ *cc = '\0';
+
+ found = 0;
+
+ for (ind=0; ind < sizeof(Open_flags)/sizeof(struct open_flag_t); ind++) {
+ if (strcmp(name, Open_flags[ind].symbol) == 0) {
+ bits |= Open_flags[ind].flag;
+ found=1;
+ break;
+ }
+ }
+
+ *cc = savecc; /* restore string */
+
+ if (found == 0) { /* invalid name */
+ if (badname != NULL)
+ *badname = name;
+ return -1;
+ }
+
+ if (savecc == '\0')
+ break;
+
+ name = ++cc;
+
+ } /* end while */
+
+ return bits;
+
+} /* end of parse_open_flags */
+
+
+char *
+openflags2symbols(int openflags, char *sep, int mode)
+{
+ int ind;
+ int size;
+ int bits = openflags;
+ int havesome=0;
+
+ Open_symbols[0]='\0';
+
+ size=sizeof(Open_flags)/sizeof(struct open_flag_t);
+
+ /*
+ * Deal with special case of O_RDONLY. If O_WRONLY nor O_RDWR
+ * bits are not set, assume O_RDONLY.
+ */
+
+ if ((bits & (O_WRONLY | O_RDWR)) == 0) {
+ strcat(Open_symbols, "O_RDONLY");
+ havesome=1;
+ }
+
+ /*
+ * Loop through all but O_RDONLY elments of Open_flags
+ */
+ for (ind=1; ind < size; ind++) {
+
+ if ((bits & Open_flags[ind].flag) == Open_flags[ind].flag) {
+ if (havesome)
+ strcat(Open_symbols, sep);
+
+ strcat(Open_symbols, Open_flags[ind].symbol);
+ havesome++;
+
+ /* remove flag bits from bits */
+ bits = bits & (~Open_flags[ind].flag);
+ }
+ }
+
+ /*
+ * If not all bits were identified and mode was equal to 1,
+ * added UNKNOWN_SYMBOL to return string
+ */
+ if (bits && mode == 1) { /* not all bits were identified */
+ if (havesome)
+ strcat(Open_symbols, sep);
+ strcat(Open_symbols, UNKNOWN_SYMBOL);
+ }
+
+ return Open_symbols;
+
+} /* end of openflags2symbols */
+
+
+#ifdef UNIT_TEST
+
+/*
+ * The following code provides a UNIT test main for
+ * parse_open_flags and openflags2symbols functions.
+ */
+
+int
+main(argc, argv)
+int argc;
+char **argv;
+{
+ int bits;
+ int ret;
+ char *err;
+
+ if (argc == 1) {
+ printf("Usage: %s openflagsbits\n\t%s symbols\n", argv[0], argv[0]);
+ exit(1);
+ }
+
+ if (sscanf(argv[1], "%i", &bits) == 1) {
+ printf("openflags2symbols(%#o, \",\", 1) returned %s\n",
+ bits, openflags2symbols(bits, ",", 1));
+
+ } else {
+ ret=parse_open_flags(argv[1], &err);
+ if (ret == -1)
+ printf("parse_open_flags(%s, &err) returned -1, err = %s\n",
+ argv[0], err);
+ else
+ printf("parse_open_flags(%s, &err) returned %#o\n", argv[0], ret);
+ }
+
+ exit(0);
+}
+
+#endif /* end of UNIT_TEST */ \ No newline at end of file
diff --git a/ltp_framework/lib/parse_opts.c b/ltp_framework/lib/parse_opts.c
new file mode 100644
index 0000000..358106e
--- /dev/null
+++ b/ltp_framework/lib/parse_opts.c
@@ -0,0 +1,879 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+
+/* $Id: parse_opts.c,v 1.14 2009/08/28 09:59:52 vapier Exp $ */
+
+/**********************************************************
+ *
+ * OS Testing - Silicon Graphics, Inc.
+ *
+ * FUNCTION NAME : parse_opts
+ *
+ * FUNCTION TITLE : parse standard & user options for system call tests
+ *
+ * SYNOPSIS:
+ * #include "usctest.h"
+ *
+ * char *parse_opts(ac, av, user_optarr, uhf)
+ * int ac;
+ * char **av;
+ * option_t user_optarr[];
+ * void (*uhf)();
+ *
+ * AUTHOR : William Roske/Richard Logan
+ *
+ * INITIAL RELEASE : UNICOS 7.0
+ *
+ * DESCRIPTION
+ * The parse_opts library routine takes that argc and argv parameters
+ * recevied by main() and an array of structures defining user options.
+ * It parses the command line setting flag and argument locations
+ * associated with the options. It uses getopt to do the actual cmd line
+ * parsing. uhf() is a function to print user define help
+ *
+ * This module contains the functions usc_global_setup_hook and
+ * usc_test_looping, which are called by marcos defined in usctest.h.
+ *
+ * RETURN VALUE
+ * parse_opts returns a pointer to an error message if an error occurs.
+ * This pointer is (char *)NULL if parsing is successful.
+ *
+ *#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**/
+#include "config.h"
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/param.h>
+#include <sys/signal.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <sys/time.h>
+
+
+#if UNIT_TEST
+#include <time.h>
+#endif /* UNIT_TEST */
+
+#include "test.h"
+#define _USC_LIB_ 1 /* indicates we are the library to the usctest.h include */
+#include "usctest.h"
+
+#ifndef USC_COPIES
+#define USC_COPIES "USC_COPIES"
+#endif
+
+#ifndef UNIT_TEST
+#define UNIT_TEST 0
+#endif
+
+#ifndef DEBUG
+#define DEBUG 0
+#endif
+
+/* The timing information block. */
+struct tblock tblock={0,((long) -1)>>1,0,0};
+
+#ifdef GARRETT_IS_A_PEDANTIC_BASTARD
+extern pid_t spawned_program_pid;
+#endif
+
+/* Define flags and args for standard options */
+int STD_FUNCTIONAL_TEST=1, /* flag indicating to do functional testing code */
+ STD_TIMING_ON=0, /* flag indicating to print timing stats */
+ STD_PAUSE=0, /* flag indicating to pause before actual start, */
+ /* for contention mode */
+ STD_INFINITE=0, /* flag indciating to loop forever */
+ STD_LOOP_COUNT=1, /* number of iterations */
+ STD_COPIES=1, /* number of copies */
+ STD_ERRNO_LOG=0; /* flag indicating to do errno logging */
+
+float STD_LOOP_DURATION=0.0, /* duration value in fractional seconds */
+ STD_LOOP_DELAY=0.0; /* loop delay value in fractional seconds */
+
+
+char **STD_opt_arr = NULL; /* array of option strings */
+int STD_nopts=0, /* number of elements in STD_opt_arr */
+ STD_argind=1; /* argv index to next argv element */
+ /* (first argument) */
+ /* To getopt users, it is like optind */
+
+/*
+ * The following variables are to support system testing additions.
+ */
+static int STD_TP_barrier=0; /* flag to do barrier in TEST_PAUSE */
+ /* 2 - wait_barrier(), 3 - set_barrier(), * - barrier() */
+static int STD_LP_barrier=0; /* flag to do barrier in TEST_LOOPING */
+ /* 2 - wait_barrier(), 3 - set_barrier(), * - barrier() */
+static int STD_TP_shmem_sz=0; /* shmalloc this many words per pe in TEST_PAUSE */
+static int STD_LD_shmem=0; /* flag to do shmem_puts and shmem_gets during delay */
+static int STD_LP_shmem=0; /* flag to do shmem_puts and gets during TEST_LOOPING */
+static int STD_LD_recfun=0; /* do recressive function calls in loop delay */
+static int STD_LP_recfun=0; /* do recressive function calls in TEST_LOOPING */
+static int STD_TP_sbrk=0; /* do sbrk in TEST_PAUSE */
+static int STD_LP_sbrk=0; /* do sbrk in TEST_LOOPING */
+static char *STD_start_break=0; /* original sbrk size */
+static int Debug=0;
+
+struct std_option_t {
+ char *optstr;
+ char *help;
+ char *flag;
+ char **arg;
+} std_options[] = {
+ { "c:", " -c n Run n copies concurrently\n", NULL, NULL},
+ { "e" , " -e Turn on errno logging\n", NULL, NULL},
+ { "f" , " -f Turn off functional testing\n", NULL, NULL},
+ { "h" , " -h Show this help screen\n", NULL, NULL},
+ { "i:", " -i n Execute test n times\n", NULL, NULL},
+ { "I:", " -I x Execute test for x seconds\n", NULL, NULL},
+ { "p" , " -p Pause for SIGUSR1 before starting\n", NULL, NULL},
+ { "P:", " -P x Pause for x seconds between iterations\n", NULL, NULL},
+ { "t" , " -t Turn on syscall timing\n", NULL, NULL},
+#ifdef UCLINUX
+ { "C:", " -C ARG Run the child process with arguments ARG (for internal use)\n",
+ NULL, NULL},
+#endif
+ {NULL, NULL, NULL, NULL}};
+
+void print_help(void (*user_help)());
+
+/*
+ * Structure for usc_recressive_func argument
+ */
+struct usc_bigstack_t {
+ char space[4096];
+};
+
+static struct usc_bigstack_t *STD_bigstack=NULL;
+
+/*
+ * Counter of errnos returned (-e option). Indexed by errno.
+ * Make the array USC_MAX_ERRNO long. That is the first Fortran
+ * Lib errno. No syscall should return an errno that high.
+ */
+int STD_ERRNO_LIST[USC_MAX_ERRNO];
+
+/* define the string length for Mesg and Mesg2 strings */
+#define STRLEN 2048
+
+static char Mesg2[STRLEN]; /* holds possible return string */
+static void usc_recressive_func();
+
+/*
+ * Define bits for options that might have env variable default
+ */
+#define OPT_iteration 01
+#define OPT_nofunccheck 02
+#define OPT_duration 04
+#define OPT_delay 010
+#define OPT_copies 020
+
+#ifdef UCLINUX
+/* Allocated and used in self_exec.c: */
+extern char *child_args; /* Arguments to child when -C is used */
+#endif
+
+/**********************************************************************
+ * parse_opts:
+ **********************************************************************/
+char *
+parse_opts(int ac, char **av, const option_t *user_optarr, void (*uhf)())
+{
+ int found; /* flag to indicate that an option specified was */
+ /* found in the user's list */
+ int k; /* scratch integer for returns and short time usage */
+ float ftmp; /* tmp float for parsing env variables */
+ char *ptr; /* used in getting env variables */
+ int options=0; /* no options specified */
+ int optstrlen, i;
+ char *optionstr;
+ int opt; /* return of getopt */
+
+ /*
+ * If not the first time this function is called, release the old STD_opt_arr
+ * vector.
+ */
+
+#ifdef GARRETT_IS_A_PEDANTIC_BASTARD
+ spawned_program_pid = getpid();
+#endif
+
+ if (STD_opt_arr != NULL) {
+ free(STD_opt_arr);
+ STD_opt_arr = NULL;
+ }
+ /* Calculate how much space we need for the option string */
+ optstrlen = 0;
+ for (i = 0; std_options[i].optstr; ++i)
+ optstrlen += strlen(std_options[i].optstr);
+ if (user_optarr)
+ for (i = 0; user_optarr[i].option; ++i) {
+ if (strlen(user_optarr[i].option) > 2)
+ return "parse_opts: ERROR - Only short options are allowed";
+ optstrlen += strlen(user_optarr[i].option);
+ }
+ optstrlen += 1;
+
+ /* Create the option string for getopt */
+ optionstr = malloc(optstrlen);
+ if (!optionstr)
+ return "parse_opts: ERROR - Could not allocate memory for optionstr";
+
+ optionstr[0] = '\0';
+
+ for (i = 0; std_options[i].optstr; ++i)
+ strcat(optionstr, std_options[i].optstr);
+ if (user_optarr)
+ for (i = 0; user_optarr[i].option; ++i)
+ /* only add the option if it wasn't there already */
+ if (strchr(optionstr, user_optarr[i].option[0]) == NULL)
+ strcat(optionstr, user_optarr[i].option);
+
+#if DEBUG > 1
+ printf("STD_nopts = %d\n", STD_nopts);
+#endif
+
+ /*
+ * Loop through av parsing options.
+ */
+ while ((opt = getopt(ac, av, optionstr)) > 0) {
+
+ STD_argind = optind;
+#if DEBUG > 0
+ printf("parse_opts: getopt returned '%c'\n", opt);
+#endif
+
+ switch (opt) {
+ case '?': /* Unknown option */
+ return "Unknown option";
+ break;
+ case ':': /* Missing Arg */
+ return "Missing argument";
+ break;
+ case 'i': /* Iterations */
+ options |= OPT_iteration;
+ STD_LOOP_COUNT = atoi(optarg);
+ if (STD_LOOP_COUNT == 0) STD_INFINITE = 1;
+ break;
+ case 'P': /* Delay between iterations */
+ options |= OPT_delay;
+ STD_LOOP_DELAY = atof(optarg);
+ break;
+ case 'I': /* Time duration */
+ options |= OPT_duration;
+ STD_LOOP_DURATION = atof(optarg);
+ if (STD_LOOP_DURATION == 0.0) STD_INFINITE=1;
+ break;
+ case 'c': /* Copies */
+ options |= OPT_copies;
+ STD_COPIES = atoi(optarg);
+ break;
+ case 'f': /* Functional testing */
+ STD_FUNCTIONAL_TEST = 0;
+ break;
+ case 'p': /* Pause for SIGUSR1 */
+ STD_PAUSE = 1;
+ break;
+ case 't': /* syscall timing */
+ STD_TIMING_ON = 1;
+ break;
+ case 'e': /* errno loggin */
+ STD_ERRNO_LOG = 1;
+ break;
+ case 'h': /* Help */
+ print_help(uhf);
+ exit(0);
+ break;
+#ifdef UCLINUX
+ case 'C': /* Run child */
+ child_args = optarg;
+ break;
+#endif
+ default:
+
+ /* Check all the user specified options */
+ found=0;
+ for (i = 0; user_optarr[i].option; ++i) {
+
+ if (opt == user_optarr[i].option[0]) {
+ /* Yup, This is a user option, set the flag and look for argument */
+ if (user_optarr[i].flag) {
+ *user_optarr[i].flag=1;
+ }
+ found++;
+
+ /* save the argument at the user's location */
+ if (user_optarr[i].option[strlen(user_optarr[i].option)-1] == ':') {
+ *user_optarr[i].arg = optarg;
+ }
+ break; /* option found - break out of the for loop */
+ }
+ }
+ /* This condition "should never happen". SO CHECK FOR IT!!!! */
+ if (!found) {
+ sprintf(Mesg2,
+ "parse_opts: ERROR - option:\"%c\" NOT FOUND... INTERNAL "
+ "ERROR", opt);
+ return(Mesg2);
+ }
+ }
+
+ } /* end of while */
+ free(optionstr);
+
+ STD_argind = optind;
+
+ /*
+ * Turn on debug
+ */
+ if ((ptr = getenv("USC_DEBUG")) != NULL) {
+ Debug = 1;
+ printf("env USC_DEBUG is defined, turning on debug\n");
+ }
+ if ((ptr = getenv("USC_VERBOSE")) != NULL) {
+ Debug = 1;
+ printf("env USC_VERBOSE is defined, turning on debug\n");
+ }
+
+ /*
+ * If the USC_ITERATION_ENV environmental variable is set to
+ * a number, use that number as iteration count (same as -c option).
+ * The -c option with arg will be used even if this env var is set.
+ */
+ if (!(options & OPT_iteration) && (ptr = getenv(USC_ITERATION_ENV)) != NULL) {
+ if (sscanf(ptr, "%i", &k) == 1) {
+ if (k == 0) { /* if arg is 0, set infinite loop flag */
+ STD_INFINITE = 1;
+ if (Debug)
+ printf("Using env %s, set STD_INFINITE to 1\n",
+ USC_ITERATION_ENV);
+ } else { /* else, set the loop count to the arguement */
+ STD_LOOP_COUNT=k;
+ if (Debug)
+ printf("Using env %s, set STD_LOOP_COUNT to %d\n",
+ USC_ITERATION_ENV, k);
+ }
+ }
+ }
+
+ /*
+ * If the USC_NO_FUNC_CHECK environmental variable is set, we'll
+ * unset the STD_FUNCTIONAL_TEST variable.
+ */
+ if (!(options & OPT_nofunccheck) &&
+ (ptr = getenv(USC_NO_FUNC_CHECK)) != NULL) {
+ STD_FUNCTIONAL_TEST=0; /* Turn off functional testing */
+ if (Debug)
+ printf("Using env %s, set STD_FUNCTIONAL_TEST to 0\n",
+ USC_NO_FUNC_CHECK);
+ }
+
+ /*
+ * If the USC_LOOP_WALLTIME environmental variable is set,
+ * use that number as duration (same as -I option).
+ * The -I option with arg will be used even if this env var is set.
+ */
+
+ if (!(options & OPT_duration) &&
+ (ptr = getenv(USC_LOOP_WALLTIME)) != NULL) {
+ if (sscanf(ptr, "%f", &ftmp) == 1 && ftmp >= 0.0) {
+ STD_LOOP_DURATION = ftmp;
+ if (Debug)
+ printf("Using env %s, set STD_LOOP_DURATION to %f\n",
+ USC_LOOP_WALLTIME, ftmp);
+ if (STD_LOOP_DURATION == 0.0) { /* if arg is 0, set infinite loop flag */
+ STD_INFINITE = 1;
+ if (Debug)
+ printf("Using env %s, set STD_INFINITE to 1\n", USC_LOOP_WALLTIME);
+ }
+ }
+ }
+ if (!(options & OPT_duration) && (ptr = getenv("USC_DURATION")) != NULL) {
+ if (sscanf(ptr, "%f", &ftmp) == 1 && ftmp >= 0.0) {
+ STD_LOOP_DURATION = ftmp;
+ if (Debug)
+ printf("Using env USC_DURATION, set STD_LOOP_DURATION to %f\n", ftmp);
+ if (STD_LOOP_DURATION == 0.0) { /* if arg is 0, set infinite loop flag */
+ STD_INFINITE = 1;
+ if (Debug)
+ printf("Using env USC_DURATION, set STD_INFINITE to 1\n");
+ }
+ }
+ }
+ /*
+ * If the USC_LOOP_DELAY environmental variable is set,
+ * use that number as delay in factional seconds (same as -P option).
+ * The -P option with arg will be used even if this env var is set.
+ */
+ if (!(options & OPT_delay) && (ptr = getenv(USC_LOOP_DELAY)) != NULL) {
+ if (sscanf(ptr, "%f", &ftmp) == 1 && ftmp >= 0.0) {
+ STD_LOOP_DELAY = ftmp;
+ if (Debug)
+ printf("Using env %s, set STD_LOOP_DELAY = %f\n",
+ USC_LOOP_DELAY, ftmp);
+ }
+ }
+
+ /*
+ * If the USC_COPIES environmental variable is set,
+ * use that number as copies (same as -c option).
+ * The -c option with arg will be used even if this env var is set.
+ */
+ if (!(options & OPT_copies) && (ptr = getenv(USC_COPIES)) != NULL) {
+ if (sscanf(ptr, "%d", &STD_COPIES) == 1 && STD_COPIES >= 0) {
+ if (Debug)
+ printf("Using env %s, set STD_COPIES = %d\n",
+ USC_COPIES, STD_COPIES);
+ }
+ }
+
+ /*
+ * The following are special system testing envs to turn on special
+ * hooks in the code.
+ */
+ if ((ptr = getenv("USC_TP_BARRIER")) != NULL) {
+ if (sscanf(ptr, "%i", &k) == 1 && k >= 0)
+ STD_TP_barrier=k;
+ else
+ STD_TP_barrier=1;
+ if (Debug)
+ printf("using env USC_TP_BARRIER, Set STD_TP_barrier to %d\n",
+ STD_TP_barrier);
+ }
+
+ if ((ptr = getenv("USC_LP_BARRIER")) != NULL) {
+ if (sscanf(ptr, "%i", &k) == 1 && k >= 0)
+ STD_LP_barrier=k;
+ else
+ STD_LP_barrier=1;
+ if (Debug)
+ printf("using env USC_LP_BARRIER, Set STD_LP_barrier to %d\n",
+ STD_LP_barrier);
+ }
+
+ if ((ptr = getenv("USC_TP_SHMEM")) != NULL) {
+ if (sscanf(ptr, "%i", &k) == 1 && k >= 0) {
+ STD_TP_shmem_sz=k;
+ if (Debug)
+ printf("Using env USC_TP_SHMEM, Set STD_TP_shmem_sz to %d\n",
+ STD_TP_shmem_sz);
+ }
+ }
+
+ if ((ptr = getenv("USC_LP_SHMEM")) != NULL) {
+ if (sscanf(ptr, "%i", &k) == 1 && k >= 0) {
+ STD_LP_shmem=k;
+ if (Debug)
+ printf("Using env USC_LP_SHMEM, Set STD_LP_shmem to %d\n",
+ STD_LP_shmem);
+ }
+ }
+
+ if ((ptr = getenv("USC_LD_SHMEM")) != NULL) {
+ if (sscanf(ptr, "%i", &k) == 1 && k >= 0) {
+ STD_LD_shmem=k;
+ if (Debug)
+ printf("Using env USC_LD_SHMEM, Set STD_LD_shmem to %d\n",
+ STD_LD_shmem);
+ }
+ }
+
+ if ((ptr = getenv("USC_TP_SBRK")) != NULL) {
+ if (sscanf(ptr, "%i", &k) == 1 && k >= 0) {
+ STD_TP_sbrk=k;
+ if (Debug)
+ printf("Using env USC_TP_SBRK, Set STD_TP_sbrk to %d\n",
+ STD_TP_sbrk);
+ }
+ }
+
+#if !defined(UCLINUX)
+ if ((ptr = getenv("USC_LP_SBRK")) != NULL) {
+ if (sscanf(ptr, "%i", &k) == 1 && k >= 0) {
+ STD_LP_sbrk=k;
+ if (Debug)
+ printf("Using env USC_LP_SBRK, Set STD_LP_sbrk to %d\n",
+ STD_LP_sbrk);
+ }
+ }
+#endif /* if !defined(UCLINUX) */
+
+ if ((ptr = getenv("USC_LP_RECFUN")) != NULL) {
+ if (sscanf(ptr, "%i", &k) == 1 && k >= 0) {
+ STD_LP_recfun = k;
+ if (STD_bigstack != NULL)
+ STD_bigstack = malloc(sizeof(struct usc_bigstack_t));
+ if (Debug)
+ printf("Using env USC_LP_RECFUN, Set STD_LP_recfun to %d\n",
+ STD_LP_recfun);
+ }
+ }
+
+ if ((ptr = getenv("USC_LD_RECFUN")) != NULL) {
+ if (sscanf(ptr, "%i", &k) == 1 && k >= 0) {
+ STD_LD_recfun = k;
+ if (STD_bigstack != NULL)
+ STD_bigstack = malloc(sizeof(struct usc_bigstack_t));
+ if (Debug)
+ printf("Using env USC_LD_RECFUN, Set STD_LD_recfun to %d\n",
+ STD_LD_recfun);
+ }
+ }
+
+#if UNIT_TEST
+ printf("The following variables after option and env parsing:\n");
+ printf("STD_FUNCTIONAL_TEST = %d\n", STD_FUNCTIONAL_TEST);
+ printf("STD_LOOP_DURATION = %f\n", STD_LOOP_DURATION);
+ printf("STD_LOOP_DELAY = %f\n", STD_LOOP_DELAY);
+ printf("STD_COPIES = %d\n", STD_COPIES);
+ printf("STD_LOOP_COUNT = %d\n", STD_LOOP_COUNT);
+ printf("STD_INFINITE = %d\n", STD_INFINITE);
+ printf("STD_TIMING_ON = %d\n", STD_TIMING_ON);
+ printf("STD_ERRNO_LOG = %d\n", STD_ERRNO_LOG);
+ printf("STD_PAUSE = %d\n", STD_PAUSE);
+#endif
+
+ return((char *) NULL);
+
+} /* end of parse_opts */
+
+/*********************************************************************
+ * print_help() - print help message and user help message
+ *********************************************************************/
+void print_help(void (*user_help)())
+{
+ STD_opts_help();
+
+ if (user_help)
+ user_help();
+}
+
+/*********************************************************************
+ * STD_opts_help() - return a help string for the STD_OPTIONS.
+ *********************************************************************/
+void STD_opts_help()
+{
+ int i;
+
+ for (i = 0; std_options[i].optstr; ++i) {
+ if (std_options[i].help)
+ printf("%s", std_options[i].help);
+ }
+}
+
+/*
+ * routine to goto when we get the SIGUSR1 for STD_PAUSE
+ */
+void STD_go(int sig)
+{
+ return;
+}
+
+/***********************************************************************
+ * This function will do desired end of global setup test
+ * hooks.
+ * Currently it will only do a pause waiting for sigusr1 if
+ * STD_PAUSE is set.
+ *
+ ***********************************************************************/
+int usc_global_setup_hook()
+{
+#ifndef UCLINUX
+ int cnt;
+ /* temp variable to store old signal action to be restored after pause */
+ int (*_TMP_FUNC)(void);
+
+ /*
+ * Fork STD_COPIES-1 copies.
+ */
+ for (cnt=1;cnt<STD_COPIES;cnt++) {
+ switch (fork() ) {
+ case -1:
+ fprintf(stderr, "%s: fork failed: %d - %s\n",
+ __FILE__, errno, strerror(errno));
+ break;
+ case 0: /* child */
+ cnt=STD_COPIES; /* to stop the forking */
+ break;
+
+ default: /* parent */
+ break;
+ }
+ }
+
+ /*
+ * pause waiting for sigusr1.
+ */
+ if (STD_PAUSE) {
+ _TMP_FUNC = (int (*)())signal(SIGUSR1, STD_go);
+ pause();
+ signal(SIGUSR1, (void (*)())_TMP_FUNC);
+ }
+
+#if !defined(UCLINUX)
+
+ if (STD_TP_sbrk || STD_LP_sbrk) {
+ STD_start_break=sbrk(0); /* get original sbreak size */
+ }
+
+ if (STD_TP_sbrk) {
+ sbrk(STD_TP_sbrk);
+ if (Debug)
+ printf("after sbrk(%d)\n", STD_TP_sbrk);
+ }
+
+#endif /* if !defined(UCLINUX) */
+#endif
+ return 0;
+}
+
+#define USECS_PER_SEC 1000000 /* microseconds per second */
+
+/***********************************************************************
+ * This function returns the number of get_current_time()'s return
+ * per second.
+ ***********************************************************************/
+
+static int get_timepersec()
+{
+ return USECS_PER_SEC; /* microseconds per second */
+
+}
+
+/***********************************************************************
+ * this function will get current time in microseconds since 1970.
+ ***********************************************************************/
+static int get_current_time()
+{
+ struct timeval curtime;
+
+ gettimeofday(&curtime, NULL);
+
+ /* microseconds since 1970 */
+ return (curtime.tv_sec*USECS_PER_SEC) + curtime.tv_usec;
+}
+
+/***********************************************************************
+ *
+ * This function will determine if test should continue iterating
+ * If the STD_INFINITE flag is set, return 1.
+ * If the STD_LOOP_COUNT variable is set, compare it against
+ * the counter.
+ * If the STD_LOOP_DURATION variable is set, compare current time against
+ * calculated stop_time.
+ * This function will return 1 until all desired looping methods
+ * have been met.
+ *
+ * counter integer is supplied by the user program.
+ ***********************************************************************/
+int usc_test_looping(int counter)
+{
+ static int first_time = 1;
+ static int stop_time = 0; /* stop time in rtc or usecs */
+ static int delay; /* delay in clocks or usecs */
+ int hertz = 0; /* clocks per second or usecs per second */
+ int ct, end; /* current time, end delay time */
+ int keepgoing = 0; /* used to determine return value */
+
+ /*
+ * If this is the first iteration and we are looping for
+ * duration of STD_LOOP_DURATION seconds (fractional) or
+ * doing loop delays, get the clocks per second.
+ */
+ if (first_time) {
+
+ first_time = 0;
+ if (STD_LOOP_DELAY || STD_LOOP_DURATION) {
+ hertz = get_timepersec();
+ }
+
+ /*
+ * If looping for duration, calculate stop time in
+ * clocks.
+ */
+
+ if (STD_LOOP_DURATION) {
+ ct=get_current_time();
+ stop_time = (int)((float)hertz * STD_LOOP_DURATION) + ct;
+ }
+
+ /*
+ * If doing delay each iteration, calcuate the number
+ * of clocks for each delay.
+ */
+ if (STD_LOOP_DELAY) {
+ delay = (int)((float)hertz * STD_LOOP_DELAY);
+ }
+
+ }
+
+ /*
+ * if delay each iteration, loop for delay clocks.
+ * This will not be done on first iteration.
+ * The delay will happen before determining if
+ * there will be another iteration.
+ */
+ else if (STD_LOOP_DELAY) {
+ ct = get_current_time();
+ end = ct + delay;
+ while (ct < end) {
+ /*
+ * The following are special test hooks in the delay loop.
+ */
+ if (STD_LD_recfun) {
+ if (Debug)
+ printf("calling usc_recressive_func(0, %d, *STD_bigstack)\n",
+ STD_LD_recfun);
+ usc_recressive_func(0, STD_LD_recfun, *STD_bigstack);
+ }
+
+ ct=get_current_time();
+ }
+ }
+
+ if (STD_INFINITE) {
+ keepgoing++;
+ }
+
+ if (STD_LOOP_COUNT && counter < STD_LOOP_COUNT) {
+ keepgoing++;
+ }
+
+ if (STD_LOOP_DURATION != 0.0 && get_current_time() < stop_time) {
+ keepgoing++;
+ }
+
+ if (keepgoing == 0)
+ return 0;
+
+ /*
+ * The following code allows special system testing hooks.
+ */
+
+ if (STD_LP_recfun) {
+ if (Debug)
+ printf("calling usc_recressive_func(0, %d, *STD_bigstack)\n",
+ STD_LP_recfun);
+ usc_recressive_func(0, STD_LP_recfun, *STD_bigstack);
+ }
+
+#if !defined(UCLINUX)
+
+ if (STD_LP_sbrk) {
+ if (Debug)
+ printf("about to do sbrk(%d)\n", STD_LP_sbrk);
+ sbrk(STD_LP_sbrk);
+ }
+#endif
+
+
+ if (keepgoing)
+ return 1;
+ else
+ return 0; /* done - stop iterating */
+}
+
+
+/*
+ * This function recressively calls itself max times.
+ */
+static void usc_recressive_func(int cnt, int max, struct usc_bigstack_t bstack)
+{
+ if (cnt < max)
+ usc_recressive_func(cnt+1, max, bstack);
+
+}
+
+#if UNIT_TEST
+/******************************************************************************
+ * UNIT TEST CODE
+ * UNIT TEST CODE
+ *
+ * this following code is provide so that unit testing can
+ * be done fairly easily.
+ ******************************************************************************/
+
+int Help = 0;
+int Help2 = 0;
+char *ptr;
+
+/*
+ * Code from usctest.h that not part of this file since we are the library.
+ */
+
+struct usc_errno_t TEST_VALID_ENO[USC_MAX_ERRNO];
+
+int TEST_RETURN;
+int TEST_ERRNO;
+
+/* for test specific parse_opts options */
+option_t Options[] = {
+ { "help", &Help2, NULL }, /* -help option */
+ { "h", &Help, NULL }, /* -h option */
+ { TIMING, NULL, NULL}, /* disable -timing option */
+
+#if INVALID_TEST_CASES
+ { "missingflag", NULL, &ptr }, /* error */
+ { "missingarg:", &Help, NULL }, /* error */
+#endif /* INVALID_TEST_CASES */
+
+ { NULL, NULL, NULL }
+};
+
+int main(int argc, char **argv)
+{
+ int lc;
+ char *msg;
+ struct timeval t;
+ int cnt;
+
+ if ((msg = parse_opts(argc, argv, Options)) != NULL) {
+ printf("ERROR: %s\n", msg);
+ exit(1);
+ }
+
+ TEST_PAUSE;
+
+ for (lc = 0; TEST_LOOPING(lc); lc++) {
+
+ TEST(gettimeofday(&t, NULL));
+ printf("iter=%d: sec:%d, usec:%6.6d %s", lc+1, t.tv_sec,
+ t.tv_usec, ctime(&t.tv_sec));
+ }
+
+
+ TEST_CLEANUP;
+
+ exit(0);
+}
+
+#endif /* UNIT_TEST */
diff --git a/ltp_framework/lib/pattern.c b/ltp_framework/lib/pattern.c
new file mode 100644
index 0000000..fc59d9b
--- /dev/null
+++ b/ltp_framework/lib/pattern.c
@@ -0,0 +1,168 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+#include <string.h>
+#include "pattern.h"
+
+/*
+ * The routines in this module are used to fill/check a data buffer
+ * with/against a known pattern.
+ */
+
+int
+pattern_check(buf, buflen, pat, patlen, patshift)
+char *buf;
+int buflen;
+char *pat;
+int patlen;
+int patshift;
+{
+ int nb, ncmp, nleft;
+ char *cp;
+
+ if (patlen)
+ patshift = patshift % patlen;
+
+ cp = buf;
+ nleft = buflen;
+
+ /*
+ * The following 2 blocks of code are to compare the first patlen
+ * bytes of buf. We need 2 checks if patshift is > 0 since we
+ * must check the last (patlen - patshift) bytes, and then the
+ * first (patshift) bytes.
+ */
+
+ nb = patlen - patshift;
+ if (nleft < nb) {
+ return (memcmp(cp, pat + patshift, nleft) ? -1 : 0);
+ } else {
+ if (memcmp(cp, pat + patshift, nb))
+ return -1;
+
+ nleft -= nb;
+ cp += nb;
+ }
+
+ if (patshift > 0) {
+ nb = patshift;
+ if (nleft < nb) {
+ return (memcmp(cp, pat, nleft) ? -1 : 0);
+ } else {
+ if (memcmp(cp, pat, nb))
+ return -1;
+
+ nleft -= nb;
+ cp += nb;
+ }
+ }
+
+ /*
+ * Now, verify the rest of the buffer using the algorithm described
+ * in the function header.
+ */
+
+ ncmp = cp - buf;
+ while (ncmp < buflen) {
+ nb = (ncmp < nleft) ? ncmp : nleft;
+ if (memcmp(buf, cp, nb))
+ return -1;
+
+ cp += nb;
+ ncmp += nb;
+ nleft -= nb;
+ }
+
+ return 0;
+}
+
+int
+pattern_fill(buf, buflen, pat, patlen, patshift)
+char *buf;
+int buflen;
+char *pat;
+int patlen;
+int patshift;
+{
+ int trans, ncopied, nleft;
+ char *cp;
+
+ if (patlen)
+ patshift = patshift % patlen;
+
+ cp = buf;
+ nleft = buflen;
+
+ /*
+ * The following 2 blocks of code are to fill the first patlen
+ * bytes of buf. We need 2 sections if patshift is > 0 since we
+ * must first copy the last (patlen - patshift) bytes into buf[0]...,
+ * and then the first (patshift) bytes of pattern following them.
+ */
+
+ trans = patlen - patshift;
+ if (nleft < trans) {
+ memcpy(cp, pat + patshift, nleft);
+ return 0;
+ } else {
+ memcpy(cp, pat + patshift, trans);
+ nleft -= trans;
+ cp += trans;
+ }
+
+ if (patshift > 0) {
+ trans = patshift;
+ if (nleft < trans) {
+ memcpy(cp, pat, nleft);
+ return 0;
+ } else {
+ memcpy(cp, pat, trans);
+ nleft -= trans;
+ cp += trans;
+ }
+ }
+
+ /*
+ * Now, fill the rest of the buffer using the algorithm described
+ * in the function header comment.
+ */
+
+ ncopied = cp - buf;
+ while (ncopied < buflen) {
+ trans = (ncopied < nleft) ? ncopied : nleft;
+ memcpy(cp, buf, trans);
+ cp += trans;
+ ncopied += trans;
+ nleft -= trans;
+ }
+
+ return(0);
+} \ No newline at end of file
diff --git a/ltp_framework/lib/random_range.c b/ltp_framework/lib/random_range.c
new file mode 100644
index 0000000..b1bde84
--- /dev/null
+++ b/ltp_framework/lib/random_range.c
@@ -0,0 +1,917 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <malloc.h>
+#include "random_range.h"
+
+/*
+ * Internal format of the range array set up by parse_range()
+ */
+
+struct range {
+ int min;
+ int max;
+ int mult;
+};
+
+/*
+ * parse_ranges() is a function to parse a comma-separated list of range
+ * tokens each having the following form:
+ *
+ * num
+ * or
+ * min:max[:mult]
+ *
+ * any of the values may be blank (ie. min::mult, :max, etc.) and default
+ * values for missing arguments may be supplied by the caller.
+ *
+ * The special first form is short hand for 'num:num'.
+ *
+ * After parsing the string, the ranges are put into an array of integers,
+ * which is malloc'd by the routine. The min, max, and mult entries of each
+ * range can be extracted from the array using the range_min(), range_max(),
+ * and range_mult() functions.
+ *
+ * It is the responsibility of the caller to free the space allocated by
+ * parse_ranges() - a single call to free() will free the space.
+ *
+ * str The string to parse - assumed to be a comma-separated
+ * list of tokens having the above format.
+ * defmin default value to plug in for min, if it is missing
+ * defmax default value to plug in for max, if it is missing
+ * defmult default value to plug in for mult, if missing
+ * parse_func A user-supplied function pointer, which parse_ranges()
+ * can call to parse the min, max, and mult strings. This
+ * allows for customized number formats. The function
+ * MUST have the following prototype:
+ * parse_func(char *str, int *val)
+ * The function should return -1 if str cannot be parsed
+ * into an integer, or >= 0 if it was successfully
+ * parsed. The resulting integer will be stored in
+ * *val. If parse_func is NULL, parse_ranges will parse
+ * the tokens in a manner consistent with the the sscanf
+ * %i format.
+ * range_ptr A user-supplied char **, which will be set to point
+ * at malloc'd space which holds the parsed range
+ * values. If range_ptr is NULL, parse_ranges() just
+ * parses the string. The data returned in range_ptr
+ * should not be processed directly - use the functions
+ * range_min(), range_max(), and range_mult() to access
+ * data for a given range.
+ * errptr user-supplied char ** which can be set to point to a
+ * static error string. If errptr is NULL, it is ignored.
+ *
+ * parse_range() returns -1 on error, or the number of ranges parsed.
+ */
+
+static int str_to_int();
+static long long divider(long long, long long, long long, long long);
+
+int
+parse_ranges(str, defmin, defmax, defmult, parse_func, rangeptr, errptr)
+char *str;
+int defmin;
+int defmax;
+int defmult;
+int (*parse_func)();
+char **rangeptr;
+char **errptr;
+{
+ int ncommas;
+ char *tmpstr, *cp, *tok, *n1str, *n2str, *multstr;
+ struct range *rp, *ranges;
+ static char errmsg[256];
+
+ if (errptr != NULL) {
+ *errptr = errmsg;
+ }
+
+ for (ncommas = 0, cp = str; *cp != '\0'; cp++) {
+ if (*cp == ',') {
+ ncommas++;
+ }
+ }
+
+ if (parse_func == NULL) {
+ parse_func = str_to_int;
+ }
+
+ tmpstr = strdup(str);
+ ranges = (struct range *)malloc((ncommas+1) * sizeof(struct range));
+ rp = ranges;
+
+ tok = strtok(tmpstr, ",");
+ while (tok != NULL) {
+ n1str = tok;
+ n2str = NULL;
+ multstr = NULL;
+
+ rp->min = defmin;
+ rp->max = defmax;
+ rp->mult = defmult;
+
+ if ((cp = strchr(n1str, ':')) != NULL) {
+ *cp = '\0';
+ n2str = cp+1;
+
+ if ((cp = strchr(n2str, ':')) != NULL) {
+ *cp = '\0';
+ multstr = cp+1;
+ }
+ }
+
+ /*
+ * Parse the 'min' field - if it is zero length (:n2[:mult]
+ * format), retain the default value, otherwise, pass the
+ * string to the parse function.
+ */
+
+ if ((int)strlen(n1str) > 0) {
+ if ((*parse_func)(n1str, &rp->min) < 0) {
+ sprintf(errmsg, "error parsing string %s into an integer", n1str);
+ free(tmpstr);
+ free(ranges);
+ return -1;
+ }
+ }
+
+ /*
+ * Process the 'max' field - if one was not present (n1 format)
+ * set max equal to min. If the field was present, but
+ * zero length (n1: format), retain the default. Otherwise
+ * pass the string to the parse function.
+ */
+
+ if (n2str == NULL) {
+ rp->max = rp->min;
+ } else if ((int)strlen(n2str) > 0) {
+ if ((*parse_func)(n2str, &rp->max) < 0) {
+ sprintf(errmsg, "error parsing string %s into an integer", n2str);
+ free(tmpstr);
+ free(ranges);
+ return -1;
+ }
+ }
+
+ /*
+ * Process the 'mult' field - if one was not present
+ * (n1:n2 format), or the field was zero length (n1:n2: format)
+ * then set the mult field to defmult - otherwise pass then
+ * mult field to the parse function.
+ */
+
+ if (multstr != NULL && (int)strlen(multstr) > 0) {
+ if ((*parse_func)(multstr, &rp->mult) < 0) {
+ sprintf(errmsg, "error parsing string %s into an integer", multstr);
+ free(tmpstr);
+ free(ranges);
+ return -1;
+ }
+ }
+
+ rp++;
+ tok = strtok(NULL, ",");
+ }
+
+ free(tmpstr);
+
+ if (rangeptr != NULL) {
+ *rangeptr = (char *)ranges;
+ } else {
+ free(ranges); /* just running in parse mode */
+ }
+
+ return (rp - ranges);
+}
+
+/*
+ * The default integer-parsing function
+ */
+
+static int
+str_to_int(str, ip)
+char *str;
+int *ip;
+{
+ char c;
+
+ if (sscanf(str, "%i%c", ip, &c) != 1) {
+ return -1;
+ } else {
+ return 0;
+ }
+}
+
+/*
+ * Three simple functions to return the min, max, and mult values for a given
+ * range. It is assumed that rbuf is a range buffer set up by parse_ranges(),
+ * and that r is a valid range within that buffer.
+ */
+
+int
+range_min(rbuf, r)
+char *rbuf;
+int r;
+{
+ return ((struct range *)rbuf)[r].min;
+}
+
+int
+range_max(rbuf, r)
+char *rbuf;
+int r;
+{
+ return ((struct range *)rbuf)[r].max;
+}
+
+int
+range_mult(rbuf, r)
+char *rbuf;
+int r;
+{
+ return ((struct range *)rbuf)[r].mult;
+}
+
+/*****************************************************************************
+ * random_range(int start, int end, int mult, char **errp)
+ *
+ * Returns a psuedo-random number which is >= 'start', <= 'end', and a multiple
+ * of 'mult'. Start and end may be any valid integer, but mult must be an
+ * integer > 0. errp is a char ** which will be set to point to a static
+ * error message buffer if it is not NULL, and an error occurs.
+ *
+ * The errp is the only way to check if the routine fails - currently the only
+ * failure conditions are:
+ *
+ * mult < 1
+ * no numbers in the start-end range that are a multiple of 'mult'
+ *
+ * If random_range_fails, and errp is a valid pointer, it will point to an
+ * internal error buffer. If errp is a vaild pointer, and random_range
+ * is successful, errp will be set to NULL.
+ *
+ * Note - if mult is 1 (the most common case), there are error conditions
+ * possible, and errp need not be used.
+ *
+ * Note: Uses lrand48(), assuming that set_random_seed() uses srand48() when
+ * setting the seed.
+ *****************************************************************************/
+
+long
+random_range(min, max, mult, errp)
+int min;
+int max;
+int mult;
+char **errp;
+{
+ int r, nmults, orig_min, orig_max, orig_mult, tmp;
+ extern long lrand48();
+ static char errbuf[128];
+
+ /*
+ * Sanity check
+ */
+
+ if (mult < 1) {
+ if (errp != NULL) {
+ sprintf(errbuf, "mult arg must be greater than 0");
+ *errp = errbuf;
+ }
+ return -1;
+ }
+
+ /*
+ * Save original parameter values for use in error message
+ */
+
+ orig_min = min;
+ orig_max = max;
+ orig_mult = mult;
+
+ /*
+ * switch min/max if max < min
+ */
+
+ if (max < min) {
+ tmp = max;
+ max = min;
+ min = tmp;
+ }
+
+ /*
+ * select the random number
+ */
+
+ if ((r = min % mult)) /* bump to the next higher 'mult' multiple */
+ min += mult - r;
+
+ if ((r = max % mult)) /* reduce to the next lower 'mult' multiple */
+ max -= r;
+
+ if (min > max) { /* no 'mult' multiples between min & max */
+ if (errp != NULL) {
+ sprintf(errbuf, "no numbers in the range %d:%d that are a multiple of %d", orig_min, orig_max, orig_mult);
+ *errp = errbuf;
+ }
+ return -1;
+ }
+
+ if (errp != NULL) {
+ *errp = NULL;
+ }
+
+ nmults = ((max - min) / mult) + 1;
+#if CRAY
+ /*
+ * If max is less than 2gb, then the value can fit in 32 bits
+ * and the standard lrand48() routine can be used.
+ */
+ if (max <= (long)2147483647) {
+ return (long) (min + (((long)lrand48() % nmults) * mult));
+ } else {
+ /*
+ * max is greater than 2gb - meeds more than 32 bits.
+ * Since lrand48 only will get a number up to 32bits.
+ */
+ long randnum;
+ randnum=divider(min, max, 0, -1);
+ return (long) (min + ((randnum % nmults) * mult));
+ }
+
+#else
+ return (min + ((lrand48() % nmults) * mult));
+#endif
+
+}
+
+/*
+ * Just like random_range, but all values are longs.
+ */
+long
+random_rangel(min, max, mult, errp)
+long min;
+long max;
+long mult;
+char **errp;
+{
+ long r, nmults, orig_min, orig_max, orig_mult, tmp;
+ extern long lrand48();
+ static char errbuf[128];
+
+ /*
+ * Sanity check
+ */
+
+ if (mult < 1) {
+ if (errp != NULL) {
+ sprintf(errbuf, "mult arg must be greater than 0");
+ *errp = errbuf;
+ }
+ return -1;
+ }
+
+ /*
+ * Save original parameter values for use in error message
+ */
+
+ orig_min = min;
+ orig_max = max;
+ orig_mult = mult;
+
+ /*
+ * switch min/max if max < min
+ */
+
+ if (max < min) {
+ tmp = max;
+ max = min;
+ min = tmp;
+ }
+
+ /*
+ * select the random number
+ */
+
+ if ((r = min % mult)) /* bump to the next higher 'mult' multiple */
+ min += mult - r;
+
+ if ((r = max % mult)) /* reduce to the next lower 'mult' multiple */
+ max -= r;
+
+ if (min > max) { /* no 'mult' multiples between min & max */
+ if (errp != NULL) {
+ sprintf(errbuf,
+ "no numbers in the range %ld:%ld that are a multiple of %ld",
+ orig_min, orig_max, orig_mult);
+ *errp = errbuf;
+ }
+ return -1;
+ }
+
+ if (errp != NULL) {
+ *errp = NULL;
+ }
+
+ nmults = ((max - min) / mult) + 1;
+#if CRAY || (_MIPS_SZLONG == 64)
+ /*
+ * If max is less than 2gb, then the value can fit in 32 bits
+ * and the standard lrand48() routine can be used.
+ */
+ if (max <= (long)2147483647) {
+ return (long) (min + (((long)lrand48() % nmults) * mult));
+ } else {
+ /*
+ * max is greater than 2gb - meeds more than 32 bits.
+ * Since lrand48 only will get a number up to 32bits.
+ */
+ long randnum;
+ randnum=divider(min, max, 0, -1);
+ return (long) (min + ((randnum % nmults) * mult));
+ }
+
+#else
+ return (min + ((lrand48() % nmults) * mult));
+#endif
+}
+
+/*
+ * Attempts to be just like random_range, but everything is long long (64 bit)
+ */
+long long
+random_rangell(min, max, mult, errp)
+long long min;
+long long max;
+long long mult;
+char **errp;
+{
+ long long r, nmults, orig_min, orig_max, orig_mult, tmp;
+ long long randnum;
+ extern long lrand48();
+ static char errbuf[128];
+
+ /*
+ * Sanity check
+ */
+
+ if (mult < 1) {
+ if (errp != NULL) {
+ sprintf(errbuf, "mult arg must be greater than 0");
+ *errp = errbuf;
+ }
+ return -1;
+ }
+
+ /*
+ * Save original parameter values for use in error message
+ */
+
+ orig_min = min;
+ orig_max = max;
+ orig_mult = mult;
+
+ /*
+ * switch min/max if max < min
+ */
+
+ if (max < min) {
+ tmp = max;
+ max = min;
+ min = tmp;
+ }
+
+ /*
+ * select the random number
+ */
+
+ if ((r = min % mult)) /* bump to the next higher 'mult' multiple */
+ min += mult - r;
+
+ if ((r = max % mult)) /* reduce to the next lower 'mult' multiple */
+ max -= r;
+
+ if (min > max) { /* no 'mult' multiples between min & max */
+ if (errp != NULL) {
+ sprintf(errbuf,
+ "no numbers in the range %lld:%lld that are a multiple of %lld",
+ orig_min, orig_max, orig_mult);
+ *errp = errbuf;
+ }
+ return -1;
+ }
+
+ if (errp != NULL) {
+ *errp = NULL;
+ }
+
+ nmults = ((max - min) / mult) + 1;
+ /*
+ * If max is less than 2gb, then the value can fit in 32 bits
+ * and the standard lrand48() routine can be used.
+ */
+ if (max <= (long)2147483647) {
+ return (long long) (min + (((long long)lrand48() % nmults) * mult));
+ } else {
+ /*
+ * max is greater than 2gb - meeds more than 32 bits.
+ * Since lrand48 only will get a number up to 32bits.
+ */
+ randnum=divider(min, max, 0, -1);
+ return (long long) (min + ((randnum % nmults) * mult));
+ }
+
+}
+
+/*
+ * This functional will recusively call itself to return a random
+ * number min and max. It was designed to work the 64bit numbers
+ * even when compiled as 32 bit process.
+ * algorithm: to use the official lrand48() routine - limited to 32 bits.
+ * find the difference between min and max (max-min).
+ * if the difference is 2g or less, use the random number gotton from lrand48().
+ * Determine the midway point between min and max.
+ * if the midway point is less than 2g from min or max,
+ * randomly add the random number gotton from lrand48() to
+ * either min or the midpoint.
+ * Otherwise, call outself with min and max being min and midway value or
+ * midway value and max. This will reduce the range in half.
+ */
+static long long
+divider(long long min, long long max, long long cnt, long long rand)
+{
+ long long med, half, diff;
+
+ /*
+ * prevent run away code. We are dividing by two each count.
+ * if we get to a count of more than 32, we should have gotten
+ * to 2gb.
+ */
+ if (cnt > 32)
+ return -1;
+
+ /*
+ * Only get a random number the first time.
+ */
+ if (cnt == 0 || rand < -1) {
+ rand = (long long)lrand48(); /* 32 bit random number */
+ }
+
+ diff = max - min;
+
+ if (diff <= 2147483647)
+ return min + rand;
+
+ half = diff/(long long)2; /* half the distance between min and max */
+ med = min + half; /* med way point between min and max */
+
+#if DEBUG
+printf("divider: min=%lld, max=%lld, cnt=%lld, rand=%lld\n", min, max, cnt, rand);
+printf(" diff = %lld, half = %lld, med = %lld\n", diff, half, med);
+#endif
+
+ if (half <= 2147483647) {
+ /*
+ * If half is smaller than 2gb, we can use the random number
+ * to pick the number within the min to med or med to max
+ * if the cnt bit of rand is zero or one, respectively.
+ */
+ if (rand & (1<<cnt))
+ return med + rand;
+ else
+ return min + rand;
+ } else {
+ /*
+ * recursively call ourself to reduce the value to the bottom half
+ * or top half (bit cnt is set).
+ */
+ if (rand & (1<<cnt)) {
+ return divider(med, max, cnt+1, rand);
+ } else {
+ return divider(min, med, cnt+1, rand);
+ }
+
+ }
+
+}
+
+
+/*****************************************************************************
+ * random_range_seed(s)
+ *
+ * Sets the random seed to s. Uses srand48(), assuming that lrand48() will
+ * be used in random_range().
+ *****************************************************************************/
+
+void
+random_range_seed(s)
+long s;
+{
+ extern void srand48();
+
+ srand48(s);
+}
+
+/****************************************************************************
+ * random_bit(mask)
+ *
+ * This function randomly returns a single bit from the bits
+ * set in mask. If mask is zero, zero is returned.
+ *
+ ****************************************************************************/
+long
+random_bit(long mask)
+{
+ int nbits = 0; /* number of set bits in mask */
+ long bit; /* used to count bits and num of set bits choosen */
+ int nshift; /* used to count bit shifts */
+
+ if (mask == 0)
+ return 0;
+
+ /*
+ * get the number of bits set in mask
+ */
+#ifndef CRAY
+
+ bit=1L;
+ for (nshift=0; (unsigned int)nshift<sizeof(long)*8; nshift++) {
+ if (mask & bit)
+ nbits++;
+ bit=bit<<1;
+ }
+
+#else
+ nbits=_popcnt(mask);
+#endif /* if CRAY */
+
+ /*
+ * randomly choose a bit.
+ */
+ bit=random_range(1, nbits, 1, NULL);
+
+ /*
+ * shift bits until you determine which bit was randomly choosen.
+ * nshift will hold the number of shifts to make.
+ */
+
+ nshift=0;
+ while (bit) {
+ /* check if the current one's bit is set */
+ if (mask & 1L) {
+ bit--;
+ }
+ mask = mask >> 1;
+ nshift++;
+ }
+
+ return 01L << (nshift-1);
+
+}
+
+
+#if RANDOM_BIT_UNITTEST
+/*
+ * The following is a unit test main function for random_bit().
+ */
+main(argc, argv)
+int argc;
+char **argv;
+{
+ int ind;
+ int cnt, iter;
+ long mask, ret;
+
+ printf("test for first and last bit set\n");
+ mask=1L;
+ ret=random_bit(mask);
+ printf("random_bit(%#o) returned %#o\n", mask, ret);
+
+ mask=1L<<(sizeof(long)*8-1);
+ ret=random_bit(mask);
+ printf("random_bit(%#o) returned %#o\n", mask, ret);
+
+ if (argc >= 3) {
+ iter=atoi(argv[1]);
+ for (ind=2; ind<argc; ind++) {
+ printf("Calling random_bit %d times for mask %#o\n", iter, mask);
+ sscanf(argv[ind], "%i", &mask);
+ for (cnt=0; cnt<iter; cnt++) {
+ ret=random_bit(mask);
+ printf("random_bit(%#o) returned %#o\n", mask, ret);
+ }
+ }
+ }
+ exit(0);
+}
+
+#endif /* end if RANDOM_BIT_UNITTEST */
+
+
+#if UNIT_TEST
+/*
+ * The following is a unit test main function for random_range*().
+ */
+
+#define PARTNUM 10 /* used to determine even distribution of random numbers */
+#define MEG 1024*1024*1024
+#define GIG 1073741824
+int
+main(argc, argv)
+int argc;
+char **argv;
+{
+ int ind;
+ int cnt, iter=10;
+ int imin=0, imult=1, itmin, itmax=0;
+#if CRAY
+ int imax=6*GIG; /* higher than 32 bits */
+#else
+ int imax=1048576;
+#endif
+
+ long lret, lmin=0, lmult=1, ltmin, ltmax=0;
+#if CRAY || (_MIPS_SZLONG == 64)
+ long lmax=6*(long)GIG; /* higher than 32 bits */
+#else
+ long lmax=1048576;
+#endif
+ long long llret, llmin=0, llmult=1, lltmin, lltmax=0;
+ long long llmax=(long long)80*(long long)GIG;
+
+ long part;
+ long long lpart;
+ long cntarr[PARTNUM];
+ long valbound[PARTNUM];
+ long long lvalbound[PARTNUM];
+
+ for (ind=0; ind<PARTNUM; ind++)
+ cntarr[ind]=0;
+
+ if (argc < 2) {
+ printf("Usage: %s func [iterations] \n", argv[0]);
+ printf("func can be random_range, random_rangel, random_rangell\n");
+ exit(1);
+ }
+
+ if (argc >= 3) {
+ if (sscanf(argv[2], "%i", &iter) != 1) {
+ printf("Usage: %s [func iterations] \n", argv[0]);
+ printf("argv[2] is not a number\n");
+ exit(1);
+ }
+ }
+
+
+ /*
+ * random_rangel ()
+ */
+ if (strcmp(argv[1], "random_rangel") == 0) {
+ ltmin=lmax;
+ part = lmax/PARTNUM;
+ for (ind=0; ind<PARTNUM; ind++) {
+ valbound[ind]=part*ind;
+ }
+
+ for (cnt=0; cnt<iter; cnt++) {
+ lret=random_rangel(lmin, lmax, lmult, NULL);
+ if (iter < 100)
+ printf("%ld\n", lret);
+ if (lret < ltmin)
+ ltmin = lret;
+ if (lret > ltmax)
+ ltmax = lret;
+ for (ind=0; ind<PARTNUM-1; ind++) {
+ if (valbound[ind] < lret && lret <= valbound[ind+1]) {
+ cntarr[ind]++;
+ break;
+ }
+ }
+ if (lret > valbound[PARTNUM-1]) {
+ cntarr[PARTNUM-1]++;
+ }
+ }
+ for (ind=0; ind<PARTNUM-1; ind++) {
+ printf("%2d %-13ld to %-13ld %5ld %4.4f\n", ind+1,
+ valbound[ind], valbound[ind+1], cntarr[ind],
+ (float)(cntarr[ind]/(float)iter));
+ }
+ printf("%2d %-13ld to %-13ld %5ld %4.4f\n", PARTNUM,
+ valbound[PARTNUM-1], lmax, cntarr[PARTNUM-1],
+ (float)(cntarr[PARTNUM-1]/(float)iter));
+ printf(" min=%ld, max=%ld\n", ltmin, ltmax);
+
+ } else if (strcmp(argv[1], "random_rangell") == 0) {
+ /*
+ * random_rangell() unit test
+ */
+ lltmin=llmax;
+ lpart = llmax/PARTNUM;
+ for (ind=0; ind<PARTNUM; ind++) {
+ lvalbound[ind]=(long long)(lpart*ind);
+ }
+
+ for (cnt=0; cnt<iter; cnt++) {
+ llret=random_rangell(llmin, llmax, llmult, NULL);
+ if (iter < 100)
+ printf("random_rangell returned %lld\n", llret);
+ if (llret < lltmin)
+ lltmin = llret;
+ if (llret > lltmax)
+ lltmax = llret;
+
+ for (ind=0; ind<PARTNUM-1; ind++) {
+ if (lvalbound[ind] < llret && llret <= lvalbound[ind+1]) {
+ cntarr[ind]++;
+ break;
+ }
+ }
+ if (llret > lvalbound[PARTNUM-1]) {
+ cntarr[PARTNUM-1]++;
+ }
+ }
+ for (ind=0; ind<PARTNUM-1; ind++) {
+ printf("%2d %-13lld to %-13lld %5ld %4.4f\n", ind+1,
+ lvalbound[ind], lvalbound[ind+1], cntarr[ind],
+ (float)(cntarr[ind]/(float)iter));
+ }
+ printf("%2d %-13lld to %-13lld %5ld %4.4f\n", PARTNUM,
+ lvalbound[PARTNUM-1], llmax, cntarr[PARTNUM-1],
+ (float)(cntarr[PARTNUM-1]/(float)iter));
+ printf(" min=%lld, max=%lld\n", lltmin, lltmax);
+
+ } else {
+ /*
+ * random_range() unit test
+ */
+ itmin=imax;
+ part = imax/PARTNUM;
+ for (ind=0; ind<PARTNUM; ind++) {
+ valbound[ind]=part*ind;
+ }
+
+ for (cnt=0; cnt<iter; cnt++) {
+ lret=random_range(imin, imax, imult, NULL);
+ if (iter < 100)
+ printf("%ld\n", lret);
+ if (lret < itmin)
+ itmin = lret;
+ if (lret > itmax)
+ itmax = lret;
+
+ for (ind=0; ind<PARTNUM-1; ind++) {
+ if (valbound[ind] < lret && lret <= valbound[ind+1]) {
+ cntarr[ind]++;
+ break;
+ }
+ }
+ if (lret > valbound[PARTNUM-1]) {
+ cntarr[PARTNUM-1]++;
+ }
+ }
+ for (ind=0; ind<PARTNUM-1; ind++) {
+ printf("%2d %-13ld to %-13ld %5ld %4.4f\n", ind+1,
+ valbound[ind], valbound[ind+1], cntarr[ind],
+ (float)(cntarr[ind]/(float)iter));
+ }
+ printf("%2d %-13ld to %-13ld %5ld %4.4f\n", PARTNUM,
+ valbound[PARTNUM-1], (long)imax, cntarr[PARTNUM-1],
+ (float)(cntarr[PARTNUM-1]/(float)iter));
+ printf(" min=%d, max=%d\n", itmin, itmax);
+
+ }
+
+ exit(0);
+}
+
+#endif \ No newline at end of file
diff --git a/ltp_framework/lib/rmobj.c b/ltp_framework/lib/rmobj.c
new file mode 100644
index 0000000..1ac9ee3
--- /dev/null
+++ b/ltp_framework/lib/rmobj.c
@@ -0,0 +1,211 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+
+/* $Id: rmobj.c,v 1.5 2009/07/20 10:59:32 vapier Exp $ */
+
+/**********************************************************
+ *
+ * OS Testing - Silicon Graphics, Inc.
+ *
+ * FUNCTION NAME : rmobj()
+ *
+ * FUNCTION TITLE : Remove an object
+ *
+ * SYNOPSIS:
+ * int rmobj(char *obj, char **errmsg)
+ *
+ * AUTHOR : Kent Rogers
+ *
+ * INITIAL RELEASE : UNICOS 7.0
+ *
+ * USER DESCRIPTION
+ * This routine will remove the specified object. If the specified
+ * object is a directory, it will recursively remove the directory
+ * and everything underneath it. It assumes that it has privilege
+ * to remove everything that it tries to remove. If rmobj() encounters
+ * any problems, and errmsg is not NULL, errmsg is set to point to a
+ * string explaining the error.
+ *
+ * DETAILED DESCRIPTION
+ * Allocate space for the directory and its contents
+ * Open the directory to get access to what is in it
+ * Loop through the objects in the directory:
+ * If the object is not "." or "..":
+ * Determine the file type by calling lstat()
+ * If the object is not a directory:
+ * Remove the object with unlink()
+ * Else:
+ * Call rmobj(object) to remove the object's contents
+ * Determine the link count on object by calling lstat()
+ * If the link count >= 3:
+ * Remove the directory with unlink()
+ * Else
+ * Remove the directory with rmdir()
+ * Close the directory and free the pointers
+ *
+ * RETURN VALUE
+ * If there are any problems, rmobj() will set errmsg (if it was not
+ * NULL) and return -1. Otherwise it will return 0.
+ *
+ ************************************************************/
+#include <errno.h> /* for errno */
+#include <stdio.h> /* for NULL */
+#include <stdlib.h> /* for malloc() */
+#include <string.h> /* for string function */
+#include <limits.h> /* for PATH_MAX */
+#include <sys/types.h> /* for opendir(), readdir(), closedir(), stat() */
+#include <sys/stat.h> /* for [l]stat() */
+#include <dirent.h> /* for opendir(), readdir(), closedir() */
+#include <unistd.h> /* for rmdir(), unlink() */
+#include "rmobj.h"
+
+#define SYSERR strerror(errno)
+
+int
+rmobj(char *obj, char **errmsg)
+{
+ int ret_val = 0; /* return value from this routine */
+ DIR *dir; /* pointer to a directory */
+ struct dirent *dir_ent; /* pointer to directory entries */
+ char dirobj[PATH_MAX]; /* object inside directory to modify */
+ struct stat statbuf; /* used to hold stat information */
+ static char err_msg[1024]; /* error message */
+
+ /* Determine the file type */
+ if (lstat(obj, &statbuf) < 0) {
+ if (errmsg != NULL) {
+ sprintf(err_msg, "lstat(%s) failed; errno=%d: %s",
+ obj, errno, SYSERR);
+ *errmsg = err_msg;
+ }
+ return -1;
+ }
+
+ /* Take appropriate action, depending on the file type */
+ if ((statbuf.st_mode & S_IFMT) == S_IFDIR) {
+ /* object is a directory */
+
+ /* Do NOT perform the request if the directory is "/" */
+ if (!strcmp(obj, "/")) {
+ if (errmsg != NULL) {
+ sprintf(err_msg, "Cannot remove /");
+ *errmsg = err_msg;
+ }
+ return -1;
+ }
+
+ /* Open the directory to get access to what is in it */
+ if ((dir = opendir(obj)) == NULL) {
+ if (rmdir(obj) != 0) {
+ if (errmsg != NULL) {
+ sprintf(err_msg, "rmdir(%s) failed; errno=%d: %s",
+ obj, errno, SYSERR);
+ *errmsg = err_msg;
+ }
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+
+ /* Loop through the entries in the directory, removing each one */
+ for (dir_ent = (struct dirent *)readdir(dir);
+ dir_ent != NULL;
+ dir_ent = (struct dirent *)readdir(dir)) {
+
+ /* Don't remove "." or ".." */
+ if (!strcmp(dir_ent->d_name, ".") || !strcmp(dir_ent->d_name, ".."))
+ continue;
+
+ /* Recursively call this routine to remove the current entry */
+ sprintf(dirobj, "%s/%s", obj, dir_ent->d_name);
+ if (rmobj(dirobj, errmsg) != 0)
+ ret_val = -1;
+ }
+
+ /* Close the directory */
+ closedir(dir);
+
+ /* If there were problems removing an entry, don't attempt to
+ remove the directory itself */
+ if (ret_val == -1)
+ return -1;
+
+ /* Get the link count, now that all the entries have been removed */
+ if (lstat(obj, &statbuf) < 0) {
+ if (errmsg != NULL) {
+ sprintf(err_msg, "lstat(%s) failed; errno=%d: %s",
+ obj, errno, SYSERR);
+ *errmsg = err_msg;
+ }
+ return -1;
+ }
+
+ /* Remove the directory itself */
+ if (statbuf.st_nlink >= 3) {
+ /* The directory is linked; unlink() must be used */
+ if (unlink(obj) < 0) {
+ if (errmsg != NULL) {
+ sprintf(err_msg, "unlink(%s) failed; errno=%d: %s",
+ obj, errno, SYSERR);
+ *errmsg = err_msg;
+ }
+ return -1;
+ }
+ } else {
+ /* The directory is not linked; remove() can be used */
+ if (remove(obj) < 0) {
+ if (errmsg != NULL) {
+ sprintf(err_msg, "remove(%s) failed; errno=%d: %s",
+ obj, errno, SYSERR);
+ *errmsg = err_msg;
+ }
+ return -1;
+ }
+ }
+ } else {
+ /* object is not a directory; just use unlink() */
+ if (unlink(obj) < 0) {
+ if (errmsg != NULL) {
+ sprintf(err_msg, "unlink(%s) failed; errno=%d: %s",
+ obj, errno, SYSERR);
+ *errmsg = err_msg;
+ }
+ return -1;
+ }
+ } /* if obj is a directory */
+
+ /*
+ * Everything must have went ok.
+ */
+ return 0;
+} /* rmobj() */ \ No newline at end of file
diff --git a/ltp_framework/lib/safe_macros.c b/ltp_framework/lib/safe_macros.c
new file mode 100644
index 0000000..11f5fe6
--- /dev/null
+++ b/ltp_framework/lib/safe_macros.c
@@ -0,0 +1,312 @@
+#include <sys/types.h>
+#include <sys/mman.h>
+#include <sys/resource.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <libgen.h>
+#include <pwd.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include "test.h"
+#include "safe_macros.h"
+
+char *
+safe_basename(const char *file, const int lineno, void (*cleanup_fn)(void),
+ char *path)
+{
+ char *rval;
+
+ rval = basename(path);
+ if (rval == NULL)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "basename failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+int
+safe_chdir(const char *file, const int lineno, void (*cleanup_fn)(void),
+ const char *path)
+{
+ int rval;
+
+ rval = chdir(path);
+ if (rval == -1)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "chdir failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+int
+safe_close(const char *file, const int lineno, void (*cleanup_fn)(void),
+ int fildes)
+{
+ int rval;
+
+ rval = close(fildes);
+ if (rval == -1)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "close failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+int
+safe_creat(const char *file, const int lineno, void (*cleanup_fn)(void),
+ char *pathname, mode_t mode)
+{
+ int rval;
+
+ rval = creat(pathname, mode);
+ if (rval == -1)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "pipe failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+char *
+safe_dirname(const char *file, const int lineno, void (*cleanup_fn)(void),
+ char *path)
+{
+ char *rval;
+
+ rval = dirname(path);
+ if (rval == NULL)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "dirname failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+char *
+safe_getcwd(const char *file, const int lineno, void (*cleanup_fn)(void),
+ char *buf, size_t size)
+{
+ char *rval;
+
+ rval = getcwd(buf, size);
+ if (rval == NULL)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "getcwd failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+struct passwd*
+safe_getpwnam(const char *file, const int lineno, void (*cleanup_fn)(void),
+ const char *name)
+{
+ struct passwd *rval;
+
+ rval = getpwnam(name);
+ if (rval == NULL)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "getpwnam failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+int
+safe_getrusage(const char *file, const int lineno, void (*cleanup_fn)(void),
+ int who, struct rusage *usage)
+{
+ int rval;
+
+ rval = getrusage(who, usage);
+ if (rval == -1)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "getrusage failed at %s:%d",
+ file, lineno);
+
+ return rval;
+}
+
+void*
+safe_malloc(const char *file, const int lineno, void (*cleanup_fn)(void),
+ size_t size)
+{
+ void *rval;
+
+ rval = malloc(size);
+ if (rval == NULL)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "malloc failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+int
+safe_mkdir(const char *file, const int lineno, void (*cleanup_fn)(void),
+ const char *pathname, mode_t mode)
+{
+ int rval;
+
+ rval = mkdir(pathname, mode);
+ if (rval == -1)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "mkdir failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+void*
+safe_mmap(const char *file, const int lineno, void (*cleanup_fn)(void),
+ void *addr, size_t length, int prot, int flags, int fd, off_t offset)
+{
+ void *rval;
+
+ rval = mmap(addr, length, prot, flags, fd, offset);
+ if (rval == MAP_FAILED)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "mmap failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+int
+safe_munmap(const char *file, const int lineno, void (*cleanup_fn)(void),
+ void *addr, size_t length)
+{
+ int rval;
+
+ rval = munmap(addr, length);
+ if (rval == -1)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "munmap failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+int
+safe_open(const char *file, const int lineno, void (*cleanup_fn)(void),
+ const char *pathname, int oflags, ...)
+{
+ va_list ap;
+ int rval;
+ mode_t mode;
+
+ va_start(ap, oflags);
+ mode = va_arg(ap, mode_t);
+ va_end(ap);
+
+ rval = open(pathname, oflags, mode);
+ if (rval == -1)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "open failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+int
+safe_pipe(const char *file, const int lineno, void (*cleanup_fn)(void),
+ int fildes[2])
+{
+ int rval;
+
+ rval = pipe(fildes);
+ if (rval == -1)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "pipe failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+ssize_t
+safe_read(const char *file, const int lineno, void (*cleanup_fn)(void),
+ char len_strict, int fildes, void *buf, size_t nbyte)
+{
+ ssize_t rval;
+
+ rval = read(fildes, buf, nbyte);
+ if ((len_strict == 0 && rval == -1) || rval != nbyte)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "read failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+ int
+safe_setegid(const char *file, const int lineno, void (*cleanup_fn)(void),
+ gid_t egid)
+{
+ int rval;
+
+ rval = setegid(egid);
+ if (rval == -1)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "setegid failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+int
+safe_seteuid(const char *file, const int lineno, void (*cleanup_fn)(void),
+ uid_t euid)
+{
+ int rval;
+
+ rval = seteuid(euid);
+ if (rval == -1)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "seteuid failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+int
+safe_setgid(const char *file, const int lineno, void (*cleanup_fn)(void),
+ gid_t gid)
+{
+ int rval;
+
+ rval = setgid(gid);
+ if (rval == -1)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "setgid failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+int
+safe_setuid(const char *file, const int lineno, void (*cleanup_fn)(void),
+ uid_t uid)
+{
+ int rval;
+
+ rval = setuid(uid);
+ if (rval == -1)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "setuid failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+int
+safe_unlink(const char *file, const int lineno, void (*cleanup_fn)(void),
+ const char *pathname)
+{
+ int rval;
+
+ rval = unlink(pathname);
+ if (rval == -1)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "unlink failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
+
+ssize_t
+safe_write(const char *file, const int lineno, void (cleanup_fn)(void),
+ char len_strict, int fildes, const void *buf, size_t nbyte)
+{
+ ssize_t rval;
+
+ rval = write(fildes, buf, nbyte);
+ if ((len_strict == 0 && rval == -1) || rval != nbyte)
+ tst_brkm(TBROK|TERRNO, cleanup_fn, "write failed at %s:%d",
+ file, lineno);
+
+ return (rval);
+}
diff --git a/ltp_framework/lib/search_path.c b/ltp_framework/lib/search_path.c
new file mode 100644
index 0000000..a9dff82
--- /dev/null
+++ b/ltp_framework/lib/search_path.c
@@ -0,0 +1,277 @@
+/* $Header: /cvsroot/ltp/ltp/lib/search_path.c,v 1.4 2009/07/20 10:59:32 vapier Exp $ */
+
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+
+
+/**********************************************************
+ *
+ * UNICOS Feature Test and Evaluation - Cray Research, Inc.
+ *
+ * FUNCTION NAME : search_path
+ *
+ * FUNCTION TITLE : search PATH locations for desired filename
+ *
+ * SYNOPSIS:
+ * int search_path(cmd, res_path, access_mode, fullpath)
+ * char *cmd;
+ * char *res_path;
+ * int access_mode;
+ * int fullpath;
+ *
+ * AUTHOR : Richard Logan
+ *
+ * INITIAL RELEASE : UNICOS 7.0
+ *
+ * DESCRIPTION
+ * Search_path will walk through PATH and attempt to find "cmd". If cmd is
+ * a full or relative path, it is checked but PATH locations are not scanned.
+ * search_path will put the resulting path in res_path. It is assumed
+ * that res_path points to a string that is at least PATH_MAX
+ * (or MAXPATHLEN on the suns) in size. Access_mode is just as is
+ * says, the mode to be used on access to determine if cmd can be found.
+ * If fullpath is set, res_path will contain the full path to cmd.
+ * If it is not set, res_path may or may not contain the full path to cmd.
+ * If fullpath is not set, the path in PATH prepended to cmd is used,
+ * which could be a relative path. If fullpath is set, the current
+ * directory is prepended to path/cmd before access is called.
+ * If cmd is found, search_path will return 0. If cmd cannot be
+ * found, 1 is returned. If an error has occurred, -1 is returned
+ * and an error mesg is placed in res_path.
+ * If the length of path/cmd is larger then PATH_MAX, then that path
+ * location is skipped.
+ *
+ *#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**/
+
+#include <stdio.h>
+#include <unistd.h>
+#include <string.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+
+
+struct stat stbuf;
+
+#ifndef AS_CMD
+#define AS_CMD 0
+#endif
+
+/*
+ * Make sure PATH_MAX is defined. Define it to MAXPATHLEN, if set. Otherwise
+ * set it to 1024.
+ */
+#ifndef PATH_MAX
+#ifndef MAXPATHLEN
+#define PATH_MAX 1024
+#else /* MAXPATHLEN */
+#define PATH_MAX MAXPATHLEN
+#endif /* MAXPATHLEN */
+#endif /* PATH_MAX */
+
+
+#if AS_CMD
+main(argc, argv)
+int argc;
+char **argv;
+{
+ char path[PATH_MAX];
+ int ind;
+
+ if (argc <= 1) {
+ printf("missing argument\n");
+ exit(1);
+ }
+
+ for (ind=1;ind < argc; ind++) {
+ if (search_path(argv[ind], path, F_OK, 0) < 0) {
+ printf("ERROR: %s\n", path);
+ }
+ else {
+ printf("path of %s is %s\n", argv[ind], path);
+ }
+ }
+
+}
+
+#endif
+
+/*
+ */
+int
+search_path(cmd, res_path, access_mode, fullpath)
+char *cmd; /* The requested filename */
+char *res_path; /* The resulting path or error mesg */
+int access_mode; /* the mode used by access(2) */
+int fullpath; /* if set, cwd will be prepended to all non-full paths */
+{
+ char *cp; /* used to scan PATH for directories */
+ int ret; /* return value from access */
+ char *pathenv;
+ char tmppath[PATH_MAX];
+ char curpath[PATH_MAX];
+ char *path;
+ int lastpath;
+ int toolong=0;
+
+#if DEBUG
+printf("search_path: cmd = %s, access_mode = %d, fullpath = %d\n", cmd, access_mode, fullpath);
+#endif
+
+ /*
+ * full or relative path was given
+ */
+ if ((cmd[0] == '/') || ( (cp=strchr(cmd, '/')) != NULL )) {
+ if (access(cmd, access_mode) == 0) {
+
+ if (cmd[0] != '/') { /* relative path */
+ if (getcwd(curpath, PATH_MAX) == NULL) {
+ strcpy(res_path, curpath);
+ return -1;
+ }
+ if ((strlen(curpath) + strlen(cmd) + 1) > (size_t)PATH_MAX) {
+ sprintf(res_path, "cmd (as relative path) and cwd is longer than %d",
+ PATH_MAX);
+ return -1;
+ }
+ sprintf(res_path, "%s/%s", curpath, cmd);
+ }
+ else
+ strcpy(res_path, cmd);
+ return 0;
+ }
+ else {
+ sprintf(res_path, "file %s not found", cmd);
+ return -1;
+ }
+ }
+
+ /* get the PATH variable */
+ if ((pathenv=getenv("PATH")) == NULL) {
+ /* no path to scan, return */
+ sprintf(res_path, "Unable to get PATH env. variable");
+ return -1;
+ }
+
+ /*
+ * walk through each path in PATH.
+ * Each path in PATH is placed in tmppath.
+ * pathenv cannot be modified since it will affect PATH.
+ * If a signal came in while we have modified the PATH
+ * memory, we could create a problem for the caller.
+ */
+
+ curpath[0]='\0';
+
+ cp = pathenv;
+ path = pathenv;
+ lastpath = 0;
+ for (;;) {
+
+ if (lastpath)
+ break;
+
+ if (cp != pathenv)
+ path = ++cp; /* already set on first iteration */
+
+ /* find end of current path */
+
+ for (; ((*cp != ':') && (*cp != '\0')); cp++);
+
+ /*
+ * copy path to tmppath so it can be NULL terminated
+ * and so we do not modify path memory.
+ */
+ strncpy(tmppath, path, (cp-path) );
+ tmppath[cp-path]='\0';
+#if DEBUG
+printf("search_path: tmppath = %s\n", tmppath);
+#endif
+
+ if (*cp == '\0')
+ lastpath=1; /* this is the last path entry */
+
+ /* Check lengths so not to overflow res_path */
+ if (strlen(tmppath) + strlen(cmd) + 2 > (size_t)PATH_MAX) {
+ toolong++;
+ continue;
+ }
+
+ sprintf(res_path, "%s/%s", tmppath, cmd);
+#if DEBUG
+printf("search_path: res_path = '%s'\n", res_path);
+#endif
+
+
+ /* if the path is not full at this point, prepend the current
+ * path to get the full path.
+ * Note: this could not be wise to do when under a protected
+ * directory.
+ */
+
+ if (fullpath && res_path[0] != '/') { /* not a full path */
+ if (curpath[0] == '\0') {
+ if (getcwd(curpath, PATH_MAX) == NULL) {
+ strcpy(res_path, curpath);
+ return -1;
+ }
+ }
+ if ((strlen(curpath) + strlen(res_path) + 2) > (size_t)PATH_MAX) {
+ toolong++;
+ continue;
+ }
+ sprintf(tmppath, "%s/%s", curpath, res_path);
+ strcpy(res_path, tmppath);
+#if DEBUG
+printf("search_path: full res_path= '%s'\n", res_path);
+#endif
+
+ }
+
+
+ if ((ret=access(res_path, access_mode)) == 0) {
+#if DEBUG
+printf("search_path: found res_path = %s\n", res_path);
+#endif
+ return 0;
+ }
+ }
+
+ /* return failure */
+ if (toolong)
+ sprintf(res_path,
+ "Unable to find file, %d path/file strings were too long", toolong);
+ else
+ strcpy(res_path, "Unable to find file");
+ return 1; /* not found */
+}
diff --git a/ltp_framework/lib/self_exec.c b/ltp_framework/lib/self_exec.c
new file mode 100644
index 0000000..a457468
--- /dev/null
+++ b/ltp_framework/lib/self_exec.c
@@ -0,0 +1,218 @@
+/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: t -*- */
+/*
+ * self_exec.c: self_exec magic required to run child functions on uClinux
+ *
+ * Copyright (C) 2005 Paul J.Y. Lahaie <pjlahaie-at-steamballoon.com>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * This software was produced by Steamballoon Incorporated
+ * 55 Byward Market Square, 2nd Floor North, Ottawa, ON K1N 9C3, Canada
+ */
+
+#define _GNU_SOURCE /* for asprintf */
+
+#include "config.h"
+
+#ifdef UCLINUX
+
+#include <stdarg.h>
+#include <string.h>
+#include <stdio.h>
+#include "test.h"
+
+/* Set from parse_opts.c: */
+char *child_args; /* Arguments to child when -C is used */
+
+static char *start_cwd; /* Stores the starting directory for self_exec */
+
+int asprintf(char **app, const char *fmt, ...)
+{
+ va_list ptr;
+ int rv;
+ char *p;
+
+ /*
+ * First iteration - find out size of buffer required and allocate it.
+ */
+ va_start(ptr, fmt);
+ rv = vsnprintf(NULL, 0, fmt, ptr);
+ va_end(ptr);
+
+ p = malloc(++rv); /* allocate the buffer */
+ *app = p;
+ if (!p) {
+ return -1;
+ }
+
+ /*
+ * Second iteration - actually produce output.
+ */
+ va_start(ptr, fmt);
+ rv = vsnprintf(p, rv, fmt, ptr);
+ va_end(ptr);
+
+ return rv;
+}
+
+void
+maybe_run_child(void (*child)(), char *fmt, ...)
+{
+ va_list ap;
+ char *child_dir;
+ char *p, *tok;
+ int *iptr, i, j;
+ char *s;
+ char **sptr;
+ char *endptr;
+
+ /* Store the current directory for later use. */
+ start_cwd = getcwd(NULL, 0);
+
+ if (child_args) {
+ char *args = strdup(child_args);
+
+ child_dir = strtok(args, ",");
+ if (strlen(child_dir) == 0) {
+ tst_resm(TBROK, NULL, "Could not get directory from -C option");
+ tst_exit();
+ }
+
+ va_start(ap, fmt);
+
+ for (p = fmt; *p; p++) {
+ tok = strtok(NULL, ",");
+ if (!tok || strlen(tok) == 0) {
+ tst_resm(TBROK, "Invalid argument to -C option");
+ tst_exit();
+ }
+
+ switch (*p) {
+ case 'd':
+ iptr = va_arg(ap, int *);
+ i = strtol(tok, &endptr, 10);
+ if (*endptr != '\0') {
+ tst_resm(TBROK, "Invalid argument to -C option");
+ tst_exit();
+ }
+ *iptr = i;
+ break;
+ case 'n':
+ j = va_arg(ap, int);
+ i = strtol(tok, &endptr, 10);
+ if (*endptr != '\0') {
+ tst_resm(TBROK, "Invalid argument to -C option");
+ tst_exit();
+ }
+ if (j != i) {
+ va_end(ap);
+ return;
+ }
+ break;
+ case 's':
+ s = va_arg(ap, char *);
+ if (!strncpy(s, tok, strlen(tok)+1)) {
+ tst_resm(TBROK, "Could not strncpy for -C option");
+ tst_exit();
+ }
+ break;
+ case 'S':
+ sptr = va_arg(ap, char **);
+ *sptr = strdup(tok);
+ if (!*sptr) {
+ tst_resm(TBROK, "Could not strdup for -C option");
+ tst_exit();
+ }
+ break;
+ default:
+ tst_resm(TBROK, "Format string option %c not implemented", *p);
+ tst_exit();
+ break;
+ }
+ }
+
+ va_end(ap);
+
+ if (chdir(child_dir) < 0) {
+ tst_resm(TBROK, "Could not change to %s for child", child_dir);
+ tst_exit();
+ }
+
+ (*child)();
+ tst_resm(TWARN, "Child function returned unexpectedly");
+ /* Exit here? or exit silently? */
+ }
+}
+
+int
+self_exec(char *argv0, char *fmt, ...)
+{
+ va_list ap;
+ char *p;
+ char *tmp_cwd;
+ char *arg;
+ int ival;
+ char *str;
+
+ if ((tmp_cwd = getcwd(NULL, 0)) == NULL) {
+ tst_resm(TBROK, "Could not getcwd()");
+ return -1;
+ }
+
+ arg = strdup( tmp_cwd );
+
+ if (( arg = strdup( tmp_cwd )) == NULL) {
+ tst_resm(TBROK, "Could not produce self_exec string");
+ return -1;
+ }
+
+ va_start(ap, fmt);
+
+ for (p = fmt; *p; p++) {
+ switch (*p) {
+ case 'd':
+ case 'n':
+ ival = va_arg(ap, int);
+ if (asprintf(&arg, "%s,%d", arg, ival) < 0) {
+ tst_resm(TBROK, "Could not produce self_exec string");
+ return -1;
+ }
+ break;
+ case 's':
+ case 'S':
+ str = va_arg(ap, char *);
+ if (asprintf(&arg, "%s,%s", arg, str) < 0) {
+ tst_resm(TBROK, "Could not produce self_exec string");
+ return -1;
+ }
+ break;
+ default:
+ tst_resm(TBROK, "Format string option %c not implemented", *p);
+ return -1;
+ break;
+ }
+ }
+
+ va_end(ap);
+
+ if (chdir(start_cwd) < 0) {
+ tst_resm(TBROK, "Could not change to %s for self_exec", start_cwd);
+ return -1;
+ }
+
+ return execlp(argv0, argv0, "-C", arg, (char *) NULL);
+}
+
+#endif /* UCLINUX */ \ No newline at end of file
diff --git a/ltp_framework/lib/str_to_bytes.c b/ltp_framework/lib/str_to_bytes.c
new file mode 100644
index 0000000..26e4897
--- /dev/null
+++ b/ltp_framework/lib/str_to_bytes.c
@@ -0,0 +1,210 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+#include <stdio.h>
+#include <sys/param.h>
+#include "str_to_bytes.h"
+
+/****************************************************************************
+ * str_to_bytes(s)
+ *
+ * Computes the number of bytes described by string s. s is assumed to be
+ * a base 10 positive (ie. >= 0) number followed by an optional single
+ * character multiplier. The following multipliers are supported:
+ *
+ * char mult
+ * -----------------
+ * b BSIZE or BBSIZE
+ * k 1024 bytes
+ * K 1024 * sizeof(long)
+ * m 2^20 (1048576)
+ * M 2^20 (1048576 * sizeof(long)
+ * g 2^30 (1073741824)
+ * G 2^30 (1073741824) * sizeof(long)
+ *
+ * for instance, "1k" and "1024" would both cause str_to_bytes to return 1024.
+ *
+ * Returns -1 if mult is an invalid character, or if the integer portion of
+ * s is not a positive integer.
+ *
+ ****************************************************************************/
+
+#if CRAY
+#define B_MULT BSIZE /* block size */
+#elif sgi
+#define B_MULT BBSIZE /* block size */
+#elif defined(__linux__) || defined(__sun) || defined(__hpux)
+#define B_MULT DEV_BSIZE /* block size */
+#elif defined(_AIX)
+#define B_MULT UBSIZE
+#endif
+
+
+#define K_MULT 1024 /* Kilo or 2^10 */
+#define M_MULT 1048576 /* Mega or 2^20 */
+#define G_MULT 1073741824 /* Giga or 2^30 */
+#define T_MULT 1099511627776 /* tera or 2^40 */
+
+int
+str_to_bytes(s)
+char *s;
+{
+ char mult, junk;
+ int nconv;
+ float num;
+
+ nconv = sscanf(s, "%f%c%c", &num, &mult, &junk);
+ if (nconv == 0 || nconv == 3)
+ return -1;
+
+ if (nconv == 1)
+ return num;
+
+ switch (mult) {
+ case 'b':
+ return (int)(num * (float)B_MULT);
+ case 'k':
+ return (int)(num * (float)K_MULT);
+ case 'K':
+ return (int)((num * (float)K_MULT) * sizeof(long));
+ case 'm':
+ return (int)(num * (float)M_MULT);
+ case 'M':
+ return (int)((num * (float)M_MULT) * sizeof(long));
+ case 'g':
+ return (int)(num * (float)G_MULT);
+ case 'G':
+ return (int)((num * (float)G_MULT) * sizeof(long));
+ default:
+ return -1;
+ }
+}
+
+long
+str_to_lbytes(s)
+char *s;
+{
+ char mult, junk;
+ long nconv;
+ float num;
+
+ nconv = sscanf(s, "%f%c%c", &num, &mult, &junk);
+ if (nconv == 0 || nconv == 3)
+ return -1;
+
+ if (nconv == 1)
+ return (long)num;
+
+ switch (mult) {
+ case 'b':
+ return (long)(num * (float)B_MULT);
+ case 'k':
+ return (long)(num * (float)K_MULT);
+ case 'K':
+ return (long)((num * (float)K_MULT) * sizeof(long));
+ case 'm':
+ return (long)(num * (float)M_MULT);
+ case 'M':
+ return (long)((num * (float)M_MULT) * sizeof(long));
+ case 'g':
+ return (long)(num * (float)G_MULT);
+ case 'G':
+ return (long)((num * (float)G_MULT) * sizeof(long));
+ default:
+ return -1;
+ }
+}
+
+/*
+ * Force 64 bits number when compiled as 32 IRIX binary.
+ * This allows for a number bigger than 2G.
+ */
+
+long long
+str_to_llbytes(s)
+char *s;
+{
+ char mult, junk;
+ long nconv;
+ double num;
+
+ nconv = sscanf(s, "%lf%c%c", &num, &mult, &junk);
+ if (nconv == 0 || nconv == 3)
+ return -1;
+
+ if (nconv == 1)
+ return (long long)num;
+
+ switch (mult) {
+ case 'b':
+ return (long long)(num * (float)B_MULT);
+ case 'k':
+ return (long long)(num * (float)K_MULT);
+ case 'K':
+ return (long long)((num * (float)K_MULT) * sizeof(long long));
+ case 'm':
+ return (long long)(num * (float)M_MULT);
+ case 'M':
+ return (long long)((num * (float)M_MULT) * sizeof(long long));
+ case 'g':
+ return (long long)(num * (float)G_MULT);
+ case 'G':
+ return (long long)((num * (float)G_MULT) * sizeof(long long));
+ default:
+ return -1;
+ }
+}
+
+#ifdef UNIT_TEST
+
+main(int argc, char **argv)
+{
+ int ind;
+
+ if (argc == 1) {
+ fprintf(stderr, "missing str_to_bytes() parameteres\n");
+ exit(1);
+ }
+
+ for (ind=1; ind<argc; ind++) {
+
+ printf("str_to_bytes(%s) returned %d\n",
+ argv[ind], str_to_bytes(argv[ind]));
+
+ printf("str_to_lbytes(%s) returned %ld\n",
+ argv[ind], str_to_lbytes(argv[ind]));
+
+ printf("str_to_llbytes(%s) returned %lld\n",
+ argv[ind], str_to_llbytes(argv[ind]));
+ }
+}
+
+#endif \ No newline at end of file
diff --git a/ltp_framework/lib/string_to_tokens.c b/ltp_framework/lib/string_to_tokens.c
new file mode 100644
index 0000000..5bbd8e3
--- /dev/null
+++ b/ltp_framework/lib/string_to_tokens.c
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+/**********************************************************
+ *
+ * OS Testing - Silicon Graphics, Inc.
+ *
+ * FUNCTION NAME : string_to_tokens
+ *
+ * FUNCTION TITLE : Break a string into its tokens
+ *
+ * SYNOPSIS:
+ *
+ * int string_to_tokens(arg_string, arg_array, array_size, separator)
+ * char *arg_string;
+ * char *arg_array[];
+ * int array_size;
+ * char *separator;
+ *
+ * AUTHOR : Richard Logan
+ *
+ * DATE : 10/94
+ *
+ * INITIAL RELEASE : UNICOS 7.0
+ *
+ * DESCRIPTION
+ * This function parses the string 'arg_string', placing pointers to
+ * the 'separator' separated tokens into the elements of 'arg_array'.
+ * The array is terminated with a null pointer.
+ * 'arg_array' must contains at least 'array_size' elements.
+ * Only the first 'array_size' minus one tokens will be placed into
+ * 'arg_array'. If there are more than 'array_size'-1 tokens, the rest are
+ * ignored by this routine.
+ *
+ * RETURN VALUE
+ * This function returns the number of 'separator' separated tokens that
+ * were found in 'arg_string'.
+ * If 'arg_array' or 'separator' is NULL or 'array_size' is less than 2, -1 is returned.
+ *
+ * WARNING
+ * This function uses strtok() to parse 'arg_string', and thus
+ * physically alters 'arg_string' by placing null characters where the
+ * separators originally were.
+ *
+ *
+ *#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**/
+#include <stdio.h>
+#include <string.h> /* for string functions */
+#include "string_to_tokens.h"
+
+int
+string_to_tokens(char *arg_string, char *arg_array[], int array_size, char *separator)
+{
+ int num_toks = 0; /* number of tokens found */
+ char *strtok();
+
+ if (arg_array == NULL || array_size <= 1 || separator == NULL)
+ return -1;
+
+ /*
+ * Use strtok() to parse 'arg_string', placing pointers to the
+ * individual tokens into the elements of 'arg_array'.
+ */
+ if ((arg_array[num_toks] = strtok(arg_string, separator)) == NULL) {
+ return 0;
+ }
+
+ for (num_toks=1;num_toks<array_size; num_toks++) {
+ if ((arg_array[num_toks] = strtok(NULL, separator)) == NULL)
+ break;
+ }
+
+ if (num_toks == array_size)
+ arg_array[num_toks] = NULL;
+
+ /*
+ * Return the number of tokens that were found in 'arg_string'.
+ */
+ return(num_toks);
+
+} /* end of string_to_tokens */ \ No newline at end of file
diff --git a/ltp_framework/lib/system_specific_hugepages_info.c b/ltp_framework/lib/system_specific_hugepages_info.c
new file mode 100644
index 0000000..2344add
--- /dev/null
+++ b/ltp_framework/lib/system_specific_hugepages_info.c
@@ -0,0 +1,93 @@
+/*
+ *
+ * Copyright (c) International Business Machines Corp., 2009
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
+ * the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * DESCRIPTION
+ * get_no_of_hugepages() --> Return No. of hugepages for this systems
+ * from /proc/meminfo
+ * hugepages_size() --> Return Hugepages Size for this system
+ * from /proc/meminfo
+ */
+
+#include <fcntl.h>
+#include <sys/types.h>
+#include <test.h>
+
+int get_no_of_hugepages() {
+ #ifdef __linux__
+ FILE *f;
+ char buf[BUFSIZ];
+
+ f = popen("grep 'HugePages_Total' /proc/meminfo | cut -d ':' -f2 | tr -d ' \n'", "r");
+ if (!f)
+ tst_brkm(TBROK, NULL,
+ "Could not get info about Total_Hugepages from /proc/meminfo");
+ if (!fgets(buf, 10, f)) {
+ fclose(f);
+ tst_brkm(TBROK, NULL,
+ "Could not read Total_Hugepages from /proc/meminfo");
+ }
+ pclose(f);
+ return(atoi(buf));
+ #else
+ return -1;
+ #endif
+}
+
+int get_no_of_free_hugepages() {
+ #ifdef __linux__
+ FILE *f;
+ char buf[BUFSIZ];
+
+ f = popen("grep 'HugePages_Free' /proc/meminfo | cut -d ':' -f2 | tr -d ' \n'", "r");
+ if (!f)
+ tst_brkm(TBROK, NULL,
+ "Could not get info about HugePages_Free from /proc/meminfo");
+ if (!fgets(buf, 10, f)) {
+ fclose(f);
+ tst_brkm(TBROK, NULL,
+ "Could not read HugePages_Free from /proc/meminfo");
+ }
+ pclose(f);
+ return(atoi(buf));
+ #else
+ return -1;
+ #endif
+}
+
+int hugepages_size() {
+ #ifdef __linux__
+ FILE *f;
+ char buf[BUFSIZ];
+
+ f = popen("grep 'Hugepagesize' /proc/meminfo | cut -d ':' -f2 | tr -d 'kB \n'", "r");
+ if (!f)
+ tst_brkm(TBROK, NULL,
+ "Could not get info about HugePages_Size from /proc/meminfo");
+ if (!fgets(buf, 10, f)) {
+ fclose(f);
+ tst_brkm(TBROK, NULL,
+ "Could not read HugePages_Size from /proc/meminfo");
+ }
+ pclose(f);
+ return(atoi(buf));
+ #else
+ return -1;
+ #endif
+}
diff --git a/ltp_framework/lib/system_specific_process_info.c b/ltp_framework/lib/system_specific_process_info.c
new file mode 100644
index 0000000..d3c9638
--- /dev/null
+++ b/ltp_framework/lib/system_specific_process_info.c
@@ -0,0 +1,88 @@
+/*
+ *
+ * Copyright (c) International Business Machines Corp., 2009
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
+ * the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * DESCRIPTION
+ * get_max_pids(): Return the maximum number of pids for this system by
+ * reading /proc/sys/kernel/pid_max
+ *
+ * get_free_pids(): Return number of free pids by subtracting the number
+ * of pids currently used ('ps -eT') from max_pids
+ */
+
+
+#include <fcntl.h>
+#include <limits.h>
+#include <sys/types.h>
+#include "test.h"
+
+#define BUFSIZE 512
+
+int get_max_pids(void)
+{
+#ifdef __linux__
+
+ FILE *f;
+ char buf[BUFSIZE];
+
+ f = fopen("/proc/sys/kernel/pid_max", "r");
+ if (!f) {
+ tst_resm(TBROK, "Could not open /proc/sys/kernel/pid_max");
+ return -1;
+ }
+ if (!fgets(buf, BUFSIZE, f)) {
+ fclose(f);
+ tst_resm(TBROK, "Could not read /proc/sys/kernel/pid_max");
+ return -1;
+ }
+ fclose(f);
+ return atoi(buf);
+#else
+ return SHRT_MAX;
+#endif
+}
+
+
+int get_free_pids(void)
+{
+ FILE *f;
+ int rc, used_pids, max_pids;
+
+ f = popen("ps -eT | wc -l", "r");
+ if (!f) {
+ tst_resm(TBROK, "Could not run 'ps' to calculate used "
+ "pids");
+ return -1;
+ }
+ rc = fscanf(f, "%i", &used_pids);
+ pclose(f);
+
+ if (rc != 1 || used_pids < 0) {
+ tst_resm(TBROK, "Could not read output of 'ps' to "
+ "calculate used pids");
+ return -1;
+ }
+
+ max_pids = get_max_pids();
+
+ if (max_pids < 0)
+ return -1;
+
+ return max_pids - used_pids;
+}
diff --git a/ltp_framework/lib/tlibio.c b/ltp_framework/lib/tlibio.c
new file mode 100644
index 0000000..eaaaaa0
--- /dev/null
+++ b/ltp_framework/lib/tlibio.c
@@ -0,0 +1,2084 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+/*
+ *
+ * Lib i/o
+ *
+ * This file contains several functions to doing reads and writes.
+ * It was written so that a single function could be called in a test
+ * program and only a io type field value would have to change to
+ * do different types of io. There is even a couple of functions that
+ * will allow you to parse a string to determine the iotype.
+ *
+ * This file contains functions for writing/reading to/from open files
+ * Prototypes:
+ *
+ * Functions declared in this module - see individual function code for
+ * usage comments:
+ *
+ * int stride_bounds(int offset, int stride, int nstrides,
+ * int bytes_per_stride, int *min, int *max);
+
+ * int lio_write_buffer(int fd, int method, char *buffer, int size,
+ * char **errmsg, long wrd);
+ * int lio_read_buffer(int fd, int method, char *buffer, int size,
+ * char **errmsg, long wrd);
+ *
+ * #ifdef CRAY
+ * int lio_wait4asyncio(int method, int fd, struct iosw **statptr)
+ * int lio_check_asyncio(char *io_type, int size, struct iosw *status)
+ * #endif
+ * #ifdef sgi
+ * int lio_wait4asyncio(int method, int fd, aiocb_t *aiocbp)
+ * int lio_check_asyncio(char *io_type, int size, aiocb_t *aiocbp, int method)
+ * #endif
+ *
+ * int lio_parse_io_arg1(char *string)
+ * void lio_help1(char *prefix);
+ *
+ * int lio_parse_io_arg2(char *string, char **badtoken)
+ * void lio_help2(char *prefix);
+ *
+ * int lio_set_debug(int level);
+ *
+ * char Lio_SysCall[];
+ * struct lio_info_type Lio_info1[];
+ * struct lio_info_type Lio_info2[];
+ *
+ * Author : Richard Logan
+ *
+ */
+
+#ifdef __linux__
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#define _LARGEFILE64_SOURCE
+#endif
+#include "config.h"
+#include <stdio.h>
+#include <ctype.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/param.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/file.h>
+#include <signal.h>
+#include <stdint.h>
+#ifdef CRAY
+#include <sys/secparm.h>
+#include <sys/iosw.h>
+#include <sys/listio.h>
+#else
+/* for linux or sgi */
+#include <sys/uio.h> /* readv(2)/writev(2) */
+#include <string.h> /* bzero */
+#endif
+#if defined(__linux__) || defined(__sun) || defined(__hpux) || defined(_AIX)
+#if !defined(UCLINUX) && !defined(__UCLIBC__)
+#include <aio.h>
+#endif
+#endif
+#include <stdlib.h> /* atoi, abs */
+
+#include "tlibio.h" /* defines LIO* marcos */
+#include "random_range.h"
+
+#ifndef PATH_MAX
+#define PATH_MAX MAXPATHLEN
+#endif
+
+#if 0 /* disabled until it's needed -- roehrich 6/11/97 */
+#define BUG1_workaround 1 /* Work around a condition where aio_return gives
+ * a value of zero but there is no errno followup
+ * and the read/write operation actually did its
+ * job. spr/pv 705244
+ */
+#endif
+
+
+static void lio_async_signal_handler();
+#ifdef sgi
+static void lio_async_callback_handler();
+#endif
+
+/*
+ * Define the structure as used in lio_parse_arg1 and lio_help1
+ */
+struct lio_info_type Lio_info1[] = {
+ { "s", LIO_IO_SYNC, "sync i/o" },
+ { "p", LIO_IO_ASYNC|LIO_WAIT_SIGACTIVE, "async i/o using a loop to wait for a signal" },
+ { "b", LIO_IO_ASYNC|LIO_WAIT_SIGPAUSE, "async i/o using pause" },
+ { "a", LIO_IO_ASYNC|LIO_WAIT_RECALL, "async i/o using recall/aio_suspend" },
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ { "r",
+ LIO_RANDOM|LIO_IO_TYPES|LIO_WAIT_TYPES, "random sync i/o types and wait methods" },
+ { "R",
+ LIO_RANDOM|LIO_IO_ATYPES|LIO_WAIT_ATYPES, "random i/o types and wait methods" },
+#else
+ { "r",
+ LIO_RANDOM|LIO_IO_TYPES|LIO_WAIT_TYPES, "random i/o types and wait methods" },
+ { "R",
+ LIO_RANDOM|LIO_IO_TYPES|LIO_WAIT_TYPES, "random i/o types and wait methods" },
+#endif
+ { "l", LIO_IO_SLISTIO|LIO_WAIT_RECALL, "single stride sync listio" },
+ { "L", LIO_IO_ALISTIO|LIO_WAIT_RECALL, "single stride async listio using recall" },
+ { "X", LIO_IO_ALISTIO|LIO_WAIT_SIGPAUSE, "single stride async listio using pause" },
+ { "v", LIO_IO_SYNCV, "single buffer sync readv/writev" },
+ { "P", LIO_IO_SYNCP, "sync pread/pwrite" },
+};
+
+/*
+ * Define the structure used by lio_parse_arg2 and lio_help2
+ */
+struct lio_info_type Lio_info2[] = {
+ { "sync", LIO_IO_SYNC, "sync i/o (read/write)"},
+ { "async", LIO_IO_ASYNC, "async i/o (reada/writea/aio_read/aio_write)" },
+ { "slistio", LIO_IO_SLISTIO, "single stride sync listio" },
+ { "alistio", LIO_IO_ALISTIO, "single stride async listio" },
+ { "syncv", LIO_IO_SYNCV, "single buffer sync readv/writev"},
+ { "syncp", LIO_IO_SYNCP, "pread/pwrite"},
+ { "active", LIO_WAIT_ACTIVE, "spin on status/control values" },
+ { "recall", LIO_WAIT_RECALL, "use recall(2)/aio_suspend(3) to wait for i/o to complete" },
+ { "sigactive", LIO_WAIT_SIGACTIVE, "spin waiting for signal" },
+ { "sigpause", LIO_WAIT_SIGPAUSE, "call pause(2) to wait for signal" },
+/* nowait is a touchy thing, it's an accident that this implementation worked at all. 6/27/97 roehrich */
+/* { "nowait", LIO_WAIT_NONE, "do not wait for async io to complete" },*/
+ { "random", LIO_RANDOM, "set random bit" },
+ { "randomall",
+ LIO_RANDOM|LIO_IO_TYPES|LIO_WAIT_TYPES,
+ "all random i/o types and wait methods (except nowait)" },
+};
+
+char Lio_SysCall[PATH_MAX]; /* string containing last i/o system call */
+
+static volatile int Received_signal = 0; /* number of signals received */
+static volatile int Rec_signal;
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+static volatile int Received_callback = 0; /* number of callbacks received */
+static volatile int Rec_callback;
+#endif
+static char Errormsg[500];
+static int Debug_level = 0;
+
+
+
+/***********************************************************************
+ * stride_bounds()
+ *
+ * Determine the bounds of a strided request, normalized to offset. Returns
+ * the number of bytes needed to satisfy the request, and optionally sets
+ * *min and *max to the mininum and maximum bytes referenced, normalized
+ * around offset.
+ *
+ * Returns -1 on error - the only possible error conditions are illegal values
+ * for nstrides and/or bytes_per_stride - both parameters must be >= 0.
+ *
+ * (maule, 11/16/95)
+ ***********************************************************************/
+
+int
+stride_bounds(offset, stride, nstrides, bytes_per_stride, min, max)
+int offset;
+int stride;
+int nstrides;
+int bytes_per_stride;
+int *min;
+int *max;
+{
+ int nbytes, min_byte, max_byte;
+
+ /*
+ * sanity checks ...
+ */
+
+ if (nstrides < 0 || bytes_per_stride < 0) {
+ return -1;
+ }
+
+ if (stride == 0) {
+ stride = bytes_per_stride;
+ }
+
+ /*
+ * Determine the # of bytes needed to satisfy the request. This
+ * value, along with the offset argument, determines the min and max
+ * bytes referenced.
+ */
+
+
+ nbytes = abs(stride) * (nstrides-1) + bytes_per_stride;
+
+ if (stride < 0) {
+ max_byte = offset + bytes_per_stride - 1;
+ min_byte = max_byte - nbytes + 1;
+ } else {
+ min_byte = offset;
+ max_byte = min_byte + nbytes - 1;
+ }
+
+ if (min != NULL) {
+ *min = min_byte;
+ }
+
+ if (max != NULL) {
+ *max = max_byte;
+ }
+
+ return nbytes;
+}
+
+/***********************************************************************
+ * This function will allow someone to set the debug level.
+ ***********************************************************************/
+int
+lio_set_debug(level)
+{
+ int old;
+
+ old = Debug_level;
+ Debug_level = level;
+ return old;
+}
+
+/***********************************************************************
+ * This function will parse a string and return desired io-method.
+ * Only the first character of the string is used.
+ *
+ * This function does not provide for meaningful option arguments,
+ * but it supports current growfiles/btlk interface.
+ *
+ * (rrl 04/96)
+ ***********************************************************************/
+int
+lio_parse_io_arg1(char *string)
+{
+ unsigned int ind;
+ int found=0;
+ int mask=0;
+
+ /*
+ * Determine if token is a valid string.
+ */
+ for (ind=0; ind<sizeof(Lio_info1)/sizeof(struct lio_info_type); ind++) {
+ if (strcmp(string, Lio_info1[ind].token) == 0) {
+ mask |= Lio_info1[ind].bits;
+ found = 1;
+ break;
+ }
+ }
+
+ if (found == 0) {
+ return -1;
+ }
+
+ return mask;
+
+}
+
+/***********************************************************************
+ * This function will print a help message describing the characters
+ * that can be parsed by lio_parse_io_arg1().
+ * They will be printed one per line.
+ * (rrl 04/96)
+ ***********************************************************************/
+void
+lio_help1(char *prefix)
+{
+ unsigned int ind;
+
+ for (ind=0; ind<sizeof(Lio_info1)/sizeof(struct lio_info_type); ind++) {
+ printf("%s %s : %s\n", prefix,
+ Lio_info1[ind].token, Lio_info1[ind].desc);
+ }
+
+ return;
+}
+
+/***********************************************************************
+ * This function will parse a string and return the desired io-method.
+ * This function will take a comma separated list of io type and wait
+ * method tokens as defined in Lio_info2[]. If a token does not match
+ * any of the tokens in Lio_info2[], it will be coverted to a number.
+ * If it was a number, those bits are also set.
+ *
+ * (rrl 04/96)
+ ***********************************************************************/
+int
+lio_parse_io_arg2(char *string, char **badtoken)
+{
+ char *token = string;
+ char *cc = token;
+ char savecc;
+ int found;
+ int mask=0;
+
+ int tmp;
+ unsigned int ind;
+ char chr;
+
+ if (token == NULL)
+ return -1;
+
+ for (;;) {
+ for (; ((*cc != ',') && (*cc != '\0')); cc++);
+ savecc = *cc;
+ *cc = '\0';
+
+ found = 0;
+
+ /*
+ * Determine if token is a valid string or number and if
+ * so, add the bits to the mask.
+ */
+ for (ind=0; ind<sizeof(Lio_info2)/sizeof(struct lio_info_type); ind++) {
+ if (strcmp(token, Lio_info2[ind].token) == 0) {
+ mask |= Lio_info2[ind].bits;
+ found = 1;
+ break;
+ }
+ }
+
+ /*
+ * If token does not match one of the defined tokens, determine
+ * if it is a number, if so, add the bits.
+ */
+ if (!found) {
+ if (sscanf(token, "%i%c", &tmp, &chr) == 1) {
+ mask |= tmp;
+ found=1;
+ }
+ }
+
+ *cc = savecc;
+
+ if (!found) { /* token is not valid */
+ if (badtoken != NULL)
+ *badtoken = token;
+ return(-1);
+ }
+
+ if (savecc == '\0')
+ break;
+
+ token = ++cc;
+ }
+
+ return mask;
+}
+
+/***********************************************************************
+ * This function will print a help message describing the tokens
+ * that can be parsed by lio_parse_io_arg2().
+ * It will print them one per line.
+ *
+ * (rrl 04/96)
+ ***********************************************************************/
+void
+lio_help2(char *prefix)
+{
+ unsigned int ind;
+
+ for (ind=0; ind<sizeof(Lio_info2)/sizeof(struct lio_info_type); ind++) {
+ printf("%s %s : %s\n", prefix,
+ Lio_info2[ind].token, Lio_info2[ind].desc);
+ }
+ return;
+}
+
+/***********************************************************************
+ * This is an internal signal handler.
+ * If the handler is called, it will increment the Received_signal
+ * global variable.
+ ***********************************************************************/
+static void
+lio_async_signal_handler(int sig)
+{
+ if (Debug_level)
+ printf("DEBUG %s/%d: received signal %d, a signal caught %d times\n",
+ __FILE__, __LINE__, sig, Received_signal+1);
+
+ Received_signal++;
+
+ return;
+}
+
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+/***********************************************************************
+ * This is an internal callback handler.
+ * If the handler is called, it will increment the Received_callback
+ * global variable.
+ ***********************************************************************/
+static void
+lio_async_callback_handler(sigval_t sigval)
+{
+ if (Debug_level)
+ printf("DEBUG %s/%d: received callback, nbytes=%ld, a callback called %d times\n",
+ __FILE__, __LINE__, (long)sigval.sival_int, Received_callback+1);
+
+ Received_callback++;
+
+ return;
+}
+#endif /* sgi */
+
+/***********************************************************************
+ * lio_random_methods
+ * This function will randomly choose an io type and wait method
+ * from set of io types and wait methods. Since this information
+ * is stored in a bitmask, it randomly chooses an io type from
+ * the io type bits specified and does the same for wait methods.
+ *
+ * Return Value
+ * This function will return a value with all non choosen io type
+ * and wait method bits cleared. The LIO_RANDOM bit is also
+ * cleared. All other bits are left unchanged.
+ *
+ * (rrl 04/96)
+ ***********************************************************************/
+int
+lio_random_methods(long curr_mask)
+{
+ int mask=0;
+
+ /* remove random select, io type, and wait method bits from curr_mask */
+ mask = curr_mask & (~(LIO_IO_TYPES | LIO_WAIT_TYPES | LIO_RANDOM));
+
+ /* randomly select io type from specified io types */
+ mask = mask | random_bit(curr_mask & LIO_IO_TYPES);
+
+ /* randomly select wait methods from specified wait methods */
+ mask = mask | random_bit(curr_mask & LIO_WAIT_TYPES);
+
+ return mask;
+}
+
+static void wait4sync_io(int fd, int read)
+{
+ fd_set s;
+ FD_ZERO(&s);
+ FD_SET(fd, &s);
+
+ select(fd+1, read ? &s : NULL, read ? NULL : &s, NULL, NULL);
+}
+
+/***********************************************************************
+ * Generic write function
+ * This function can be used to do a write using write(2), writea(2),
+ * aio_write(3), writev(2), pwrite(2),
+ * or single stride listio(2)/lio_listio(3).
+ * By setting the desired bits in the method
+ * bitmask, the caller can control the type of write and the wait method
+ * that will be used. If no io type bits are set, write will be used.
+ *
+ * If async io was attempted and no wait method bits are set then the
+ * wait method is: recall(2) for writea(2) and listio(2); aio_suspend(3) for
+ * aio_write(3) and lio_listio(3).
+ *
+ * If multiple wait methods are specified,
+ * only one wait method will be used. The order is predetermined.
+ *
+ * If the call specifies a signal and one of the two signal wait methods,
+ * a signal handler for the signal is set. This will reset an already
+ * set handler for this signal.
+ *
+ * If the LIO_RANDOM method bit is set, this function will randomly
+ * choose a io type and wait method from bits in the method argument.
+ *
+ * If an error is encountered, an error message will be generated
+ * in a internal static buffer. If errmsg is not NULL, it will
+ * be updated to point to the static buffer, allowing the caller
+ * to print the error message.
+ *
+ * Return Value
+ * If a system call fails, -errno is returned.
+ * If LIO_WAIT_NONE bit is set, the return value is the return value
+ * of the system call.
+ * If the io did not fail, the amount of data written is returned.
+ * If the size the system call say was written is different
+ * then what was asked to be written, errmsg is updated for
+ * this error condition. The return value is still the amount
+ * the system call says was written.
+ *
+ * (rrl 04/96)
+ ***********************************************************************/
+int
+lio_write_buffer(fd, method, buffer, size, sig, errmsg, wrd)
+int fd; /* open file descriptor */
+int method; /* contains io type and wait method bitmask */
+char *buffer; /* pointer to buffer */
+int size; /* the size of the io */
+int sig; /* signal to use if async io */
+char **errmsg; /* char pointer that will be updated to point to err message */
+long wrd; /* to allow future features, use zero for now */
+{
+ int ret = 0; /* syscall return or used to get random method */
+ char *io_type; /* Holds string of type of io */
+ int omethod = method;
+ int listio_cmd; /* Holds the listio/lio_listio cmd */
+#ifdef CRAY
+ struct listreq request; /* Used when a listio is wanted */
+ struct iosw status, *statptr[1];
+#else
+ /* for linux or sgi */
+ struct iovec iov; /* iovec for writev(2) */
+#endif
+#if defined (sgi)
+ aiocb_t aiocbp; /* POSIX aio control block */
+ aiocb_t *aiolist[1]; /* list of aio control blocks for lio_listio */
+ off64_t poffset; /* pwrite(2) offset */
+#endif
+#if defined(__linux__) && !defined(__UCLIBC__)
+ struct aiocb aiocbp; /* POSIX aio control block */
+ struct aiocb *aiolist[1]; /* list of aio control blocks for lio_listio */
+ off64_t poffset; /* pwrite(2) offset */
+#endif
+ /*
+ * If LIO_RANDOM bit specified, get new method randomly.
+ */
+ if (method & LIO_RANDOM) {
+ if (Debug_level > 3)
+ printf("DEBUG %s/%d: method mask to choose from: %#o\n", __FILE__, __LINE__, method );
+ method = lio_random_methods(method);
+ if (Debug_level > 2)
+ printf("DEBUG %s/%d: random chosen method %#o\n", __FILE__, __LINE__, method);
+ }
+
+ if (errmsg != NULL)
+ *errmsg = Errormsg;
+
+ Rec_signal=Received_signal; /* get the current number of signals received */
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ Rec_callback=Received_callback; /* get the current number of callbacks received */
+#endif
+
+#ifdef CRAY
+ memset(&status, 0x00, sizeof(struct iosw));
+ memset(&request, 0x00, sizeof(struct listreq));
+ statptr[0] = &status;
+#else
+ /* for linux or sgi */
+ memset(&iov, 0x00, sizeof(struct iovec));
+ iov.iov_base = buffer;
+ iov.iov_len = size;
+#endif
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+#if defined(sgi)
+ memset(&aiocbp, 0x00, sizeof(aiocb_t));
+#else
+ memset(&aiocbp, 0x00, sizeof(struct aiocb));
+#endif
+ aiocbp.aio_fildes = fd;
+ aiocbp.aio_nbytes = size;
+ aiocbp.aio_buf = buffer;
+/* aiocbp.aio_offset = lseek( fd, 0, SEEK_CUR ); -- set below */
+ aiocbp.aio_sigevent.sigev_notify = SIGEV_NONE;
+ aiocbp.aio_sigevent.sigev_signo = 0;
+#ifdef sgi
+ aiocbp.aio_sigevent.sigev_func = NULL;
+ aiocbp.aio_sigevent.sigev_value.sival_int = 0;
+#elif defined(__linux__) && !defined(__UCLIBC__)
+ aiocbp.aio_sigevent.sigev_notify_function = NULL;
+ aiocbp.aio_sigevent.sigev_notify_attributes = 0;
+#endif
+ aiolist[0] = &aiocbp;
+
+ if ((ret = lseek( fd, 0, SEEK_CUR )) == -1) {
+ ret = 0;
+ /* If there is an error and it is not ESPIPE then kick out the error.
+ * If the fd is a fifo then we have to make sure that
+ * lio_random_methods() didn't select pwrite/pread; if it did then
+ * switch to write/read.
+ */
+ if (errno == ESPIPE) {
+ if (method & LIO_IO_SYNCP) {
+ if (omethod & LIO_RANDOM) {
+ method &= ~LIO_IO_SYNCP;
+ method |= LIO_IO_SYNC;
+ if (Debug_level > 2)
+ printf("DEBUG %s/%d: random chosen method switched to %#o for fifo\n", __FILE__, __LINE__, method );
+ }
+ else if (Debug_level) {
+ printf("DEBUG %s/%d: pwrite will fail when it writes to a fifo\n",
+ __FILE__, __LINE__ );
+ }
+ }
+ /* else: let it ride */
+ }
+ else{
+ sprintf(Errormsg, "%s/%d lseek(fd=%d,0,SEEK_CUR) failed, errno=%d %s",
+ __FILE__, __LINE__, fd, errno, strerror(errno));
+ return -errno;
+ }
+ }
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ poffset = (off64_t)ret;
+#endif
+ aiocbp.aio_offset = ret;
+
+#endif
+
+ /*
+ * If the LIO_USE_SIGNAL bit is not set, only use the signal
+ * if the LIO_WAIT_SIGPAUSE or the LIO_WAIT_SIGACTIVE bits are bit.
+ * Otherwise there is not necessary a signal handler to trap
+ * the signal.
+ */
+ if (sig && !(method & LIO_USE_SIGNAL) &&
+ ! (method & LIO_WAIT_SIGTYPES) ) {
+
+ sig=0; /* ignore signal parameter */
+ }
+
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ if (sig && (method & LIO_WAIT_CBTYPES))
+ sig=0; /* ignore signal parameter */
+#endif
+
+ /*
+ * only setup signal hander if sig was specified and
+ * a sig wait method was specified.
+ * Doing this will change the handler for this signal. The
+ * old signal handler will not be restored.
+ *** restoring the signal handler could be added ***
+ */
+
+ if (sig && (method & LIO_WAIT_SIGTYPES)) {
+#ifdef CRAY
+ sigctl(SCTL_REG, sig, lio_async_signal_handler);
+#endif
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ aiocbp.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
+ aiocbp.aio_sigevent.sigev_signo = sig;
+ sigset(sig, lio_async_signal_handler);
+#endif /* sgi */
+ }
+#if defined(sgi)
+ else if (method & LIO_WAIT_CBTYPES) {
+ /* sival_int just has to be something that I can use
+ * to identify the callback, and "size" happens to be handy...
+ */
+ aiocbp.aio_sigevent.sigev_notify = SIGEV_CALLBACK;
+ aiocbp.aio_sigevent.sigev_func = lio_async_callback_handler;
+ aiocbp.aio_sigevent.sigev_value.sival_int = size;
+ }
+#endif
+#if defined(__linux__) && !defined(__UCLIBC__)
+ else if (method & LIO_WAIT_CBTYPES) {
+ /* sival_int just has to be something that I can use
+ * to identify the callback, and "size" happens to be handy...
+ */
+ aiocbp.aio_sigevent.sigev_notify = SIGEV_THREAD;
+ aiocbp.aio_sigevent.sigev_notify_function = lio_async_callback_handler;
+ aiocbp.aio_sigevent.sigev_notify_attributes = (void*)(uintptr_t)size;
+ }
+#endif
+ /*
+ * Determine the system call that will be called and produce
+ * the string of the system call and place it in Lio_SysCall.
+ * Also update the io_type char pointer to give brief description
+ * of system call. Execute the system call and check for
+ * system call failure. If sync i/o, return the number of
+ * bytes written/read.
+ */
+
+ if ((method & LIO_IO_SYNC) || (method & (LIO_IO_TYPES | LIO_IO_ATYPES)) == 0) {
+ /*
+ * write(2) is used if LIO_IO_SYNC bit is set or not none
+ * of the LIO_IO_TYPES bits are set (default).
+ */
+
+ sprintf(Lio_SysCall,
+ "write(%d, buf, %d)", fd, size);
+ io_type="write";
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+ while (1) {
+ if (((ret = write(fd, buffer, size)) == -1) && errno!=EAGAIN && errno!=EINTR) {
+ sprintf(Errormsg, "%s/%d write(%d, buf, %d) ret:-1, errno=%d %s",
+ __FILE__, __LINE__,
+ fd, size, errno, strerror(errno));
+ return -errno;
+ }
+
+ if (ret!=-1) {
+ if (ret != size) {
+ sprintf(Errormsg,
+ "%s/%d write(%d, buf, %d) returned=%d",
+ __FILE__, __LINE__,
+ fd, size, ret);
+ size-=ret;
+ buffer+=ret;
+ }
+ else {
+ if (Debug_level > 1)
+ printf("DEBUG %s/%d: write completed without error (ret %d)\n",
+ __FILE__, __LINE__, ret);
+
+ return ret;
+ }
+ }
+ wait4sync_io(fd, 0);
+ }
+
+ }
+
+ else if (method & LIO_IO_ASYNC) {
+#ifdef CRAY
+ sprintf(Lio_SysCall,
+ "writea(%d, buf, %d, &status, %d)", fd, size, sig);
+ io_type="writea";
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+
+ sigoff();
+ if ((ret = writea(fd, buffer, size, &status, sig)) == -1) {
+ sprintf(Errormsg,
+ "%s/%d writea(%d, buf, %d, &stat, %d) ret:-1, errno=%d %s",
+ __FILE__, __LINE__,
+ fd, size, sig, errno, strerror(errno));
+ sigon();
+ return -errno;
+ }
+#endif
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ sprintf(Lio_SysCall,
+ "aio_write(fildes=%d, buf, nbytes=%d, signo=%d)", fd, size, sig);
+ io_type="aio_write";
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+
+ if (sig)
+ sighold( sig );
+ if ((ret = aio_write(&aiocbp)) == -1) {
+ sprintf(Errormsg,
+ "%s/%d aio_write(fildes=%d, buf, nbytes=%d, signo=%d) ret:-1, errno=%d %s",
+ __FILE__, __LINE__,
+ fd, size, sig, errno, strerror(errno));
+ if (sig)
+ sigrelse( sig );
+ return -errno;
+ }
+#endif
+ } /* LIO_IO_ASYNC */
+
+ else if (method & LIO_IO_SLISTIO) {
+#ifdef CRAY
+ request.li_opcode = LO_WRITE;
+ request.li_fildes = fd;
+ request.li_buf = buffer;
+ request.li_nbyte = size;
+ request.li_status = &status;
+ request.li_signo = sig;
+ request.li_nstride = 0;
+ request.li_filstride = 0;
+ request.li_memstride = 0;
+
+ listio_cmd=LC_WAIT;
+ io_type="listio(2) sync write";
+
+ sprintf(Lio_SysCall,
+ "listio(LC_WAIT, &req, 1) LO_WRITE, fd:%d, nbyte:%d",
+ fd, size);
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+
+ sigoff();
+ if (listio(listio_cmd, &request, 1) == -1) {
+ sprintf(Errormsg, "%s/%d %s failed, fd:%d, nbyte:%d errno=%d %s",
+ __FILE__, __LINE__,
+ Lio_SysCall, fd, size, errno, strerror(errno));
+ sigon();
+ return -errno;
+ }
+
+ if (Debug_level > 1)
+ printf("DEBUG %s/%d: %s did not return -1\n",
+ __FILE__, __LINE__, Lio_SysCall);
+
+ ret=lio_check_asyncio(io_type, size, &status);
+ return ret;
+
+#endif
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+
+ aiocbp.aio_lio_opcode = LIO_WRITE;
+ listio_cmd=LIO_WAIT;
+ io_type="lio_listio(3) sync write";
+
+ sprintf(Lio_SysCall,
+ "lio_listio(LIO_WAIT, aiolist, 1, NULL) LIO_WRITE, fd:%d, nbyte:%d, sig:%d",
+ fd, size, sig );
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+
+ if (sig)
+ sighold( sig );
+ if (lio_listio(listio_cmd, aiolist, 1, NULL) == -1) {
+ sprintf(Errormsg, "%s/%d %s failed, fd:%d, nbyte:%d errno=%d %s",
+ __FILE__, __LINE__,
+ Lio_SysCall, fd, size, errno, strerror(errno));
+ if (sig)
+ sigrelse( sig );
+ return -errno;
+ }
+
+ if (Debug_level > 1)
+ printf("DEBUG %s/%d: %s did not return -1\n",
+ __FILE__, __LINE__, Lio_SysCall);
+
+ ret=lio_check_asyncio(io_type, size, &aiocbp, method);
+ return ret;
+#endif
+ } /* LIO_IO_SLISTIO */
+
+ else if (method & LIO_IO_ALISTIO) {
+#ifdef CRAY
+ request.li_opcode = LO_WRITE;
+ request.li_fildes = fd;
+ request.li_buf = buffer;
+ request.li_nbyte = size;
+ request.li_status = &status;
+ request.li_signo = sig;
+ request.li_nstride = 0;
+ request.li_filstride = 0;
+ request.li_memstride = 0;
+
+ listio_cmd=LC_START;
+ io_type="listio(2) async write";
+
+ sprintf(Lio_SysCall,
+ "listio(LC_START, &req, 1) LO_WRITE, fd:%d, nbyte:%d",
+ fd, size);
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+
+ sigoff();
+ if (listio(listio_cmd, &request, 1) == -1) {
+ sprintf(Errormsg, "%s/%d %s failed, fd:%d, nbyte:%d errno=%d %s",
+ __FILE__, __LINE__,
+ Lio_SysCall, fd, size, errno, strerror(errno));
+ sigon();
+ return -errno;
+ }
+#endif
+#if defined (sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ aiocbp.aio_lio_opcode = LIO_WRITE;
+ listio_cmd=LIO_NOWAIT;
+ io_type="lio_listio(3) async write";
+
+ sprintf(Lio_SysCall,
+ "lio_listio(LIO_NOWAIT, aiolist, 1, NULL) LIO_WRITE, fd:%d, nbyte:%d",
+ fd, size);
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+
+ if (sig)
+ sighold( sig );
+ if (lio_listio(listio_cmd, aiolist, 1, NULL) == -1) {
+ sprintf(Errormsg, "%s/%d %s failed, fd:%d, nbyte:%d errno=%d %s",
+ __FILE__, __LINE__,
+ Lio_SysCall, fd, size, errno, strerror(errno));
+ if (sig)
+ sigrelse( sig );
+ return -errno;
+ }
+#endif
+ }/* LIO_IO_ALISTIO */
+
+#ifndef CRAY
+ else if (method & LIO_IO_SYNCV) {
+ io_type="writev(2)";
+
+ sprintf(Lio_SysCall,
+ "writev(%d, &iov, 1) nbyte:%d", fd, size);
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+ if ((ret = writev(fd, &iov, 1)) == -1) {
+ sprintf(Errormsg, "%s/%d writev(%d, iov, 1) nbyte:%d ret:-1, errno=%d %s",
+ __FILE__, __LINE__,
+ fd, size, errno, strerror(errno));
+ return -errno;
+ }
+
+ if (ret != size) {
+ sprintf(Errormsg,
+ "%s/%d writev(%d, iov, 1) nbyte:%d returned=%d",
+ __FILE__, __LINE__,
+ fd, size, ret);
+ }
+ else if (Debug_level > 1)
+ printf("DEBUG %s/%d: writev completed without error (ret %d)\n",
+ __FILE__, __LINE__, ret);
+
+ return ret;
+ } /* LIO_IO_SYNCV */
+#endif
+
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ else if (method & LIO_IO_SYNCP) {
+ io_type="pwrite(2)";
+
+ sprintf(Lio_SysCall,
+ "pwrite(%d, buf, %d, %lld)", fd, size, (long long)poffset);
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+ if ((ret = pwrite(fd, buffer, size, poffset)) == -1) {
+ sprintf(Errormsg, "%s/%d pwrite(%d, buf, %d, %lld) ret:-1, errno=%d %s",
+ __FILE__, __LINE__,
+ fd, size, (long long)poffset, errno, strerror(errno));
+ return -errno;
+ }
+
+ if (ret != size) {
+ sprintf(Errormsg,
+ "%s/%d pwrite(%d, buf, %d, %lld) returned=%d",
+ __FILE__, __LINE__,
+ fd, size, (long long)poffset, ret);
+ }
+ else if (Debug_level > 1)
+ printf("DEBUG %s/%d: pwrite completed without error (ret %d)\n",
+ __FILE__, __LINE__, ret);
+
+ return ret;
+ } /* LIO_IO_SYNCP */
+#endif
+
+ else {
+ printf("DEBUG %s/%d: No I/O method chosen\n", __FILE__, __LINE__ );
+ return -1;
+ }
+
+ /*
+ * wait for async io to complete.
+ */
+#ifdef CRAY
+ ret=lio_wait4asyncio(method, fd, statptr);
+#endif
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ ret=lio_wait4asyncio(method, fd, &aiocbp);
+#endif
+
+ /*
+ * If there was an error waiting for async i/o to complete,
+ * return the error value (errno) to the caller.
+ * Note: Errormsg should already have been updated.
+ */
+ if (ret < 0) {
+ return ret;
+ }
+
+ /*
+ * If i/o was not waited for (may not have been completed at this time),
+ * return the size that was requested.
+ */
+ if (ret == 1)
+ return size;
+
+ /*
+ * check that async io was successful.
+ * Note: if the there was an system call failure, -errno
+ * was returned and Errormsg should already have been updated.
+ * If amount i/o was different than size, Errormsg should already
+ * have been updated but the actual i/o size if returned.
+ */
+
+#ifdef CRAY
+ ret=lio_check_asyncio(io_type, size, &status);
+#endif
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ ret=lio_check_asyncio(io_type, size, &aiocbp, method);
+#endif
+
+ return ret;
+} /* end of lio_write_buffer */
+
+/***********************************************************************
+ * Generic read function
+ * This function can be used to do a read using read(2), reada(2),
+ * aio_read(3), readv(2), pread(2),
+ * or single stride listio(2)/lio_listio(3).
+ * By setting the desired bits in the method
+ * bitmask, the caller can control the type of read and the wait method
+ * that will be used. If no io type bits are set, read will be used.
+ *
+ * If async io was attempted and no wait method bits are set then the
+ * wait method is: recall(2) for reada(2) and listio(2); aio_suspend(3) for
+ * aio_read(3) and lio_listio(3).
+ *
+ * If multiple wait methods are specified,
+ * only one wait method will be used. The order is predetermined.
+ *
+ * If the call specifies a signal and one of the two signal wait methods,
+ * a signal handler for the signal is set. This will reset an already
+ * set handler for this signal.
+ *
+ * If the LIO_RANDOM method bit is set, this function will randomly
+ * choose a io type and wait method from bits in the method argument.
+ *
+ * If an error is encountered, an error message will be generated
+ * in a internal static buffer. If errmsg is not NULL, it will
+ * be updated to point to the static buffer, allowing the caller
+ * to print the error message.
+ *
+ * Return Value
+ * If a system call fails, -errno is returned.
+ * If LIO_WAIT_NONE bit is set, the return value is the return value
+ * of the system call.
+ * If the io did not fail, the amount of data written is returned.
+ * If the size the system call say was written is different
+ * then what was asked to be written, errmsg is updated for
+ * this error condition. The return value is still the amount
+ * the system call says was written.
+ *
+ * (rrl 04/96)
+ ***********************************************************************/
+int
+lio_read_buffer(fd, method, buffer, size, sig, errmsg, wrd)
+int fd; /* open file descriptor */
+int method; /* contains io type and wait method bitmask */
+char *buffer; /* pointer to buffer */
+int size; /* the size of the io */
+int sig; /* signal to use if async io */
+char **errmsg; /* char pointer that will be updated to point to err message */
+long wrd; /* to allow future features, use zero for now */
+{
+ int ret = 0; /* syscall return or used to get random method */
+ char *io_type; /* Holds string of type of io */
+ int listio_cmd; /* Holds the listio/lio_listio cmd */
+ int omethod = method;
+#ifdef CRAY
+ struct listreq request; /* Used when a listio is wanted */
+ struct iosw status, *statptr[1];
+#else
+ /* for linux or sgi */
+ struct iovec iov; /* iovec for readv(2) */
+#endif
+#ifdef sgi
+ aiocb_t aiocbp; /* POSIX aio control block */
+ aiocb_t *aiolist[1]; /* list of aio control blocks for lio_listio */
+ off64_t poffset; /* pread(2) offset */
+#endif
+#if defined (__linux__) && !defined(__UCLIBC__)
+ struct aiocb aiocbp; /* POSIX aio control block */
+ struct aiocb *aiolist[1]; /* list of aio control blocks for lio_listio */
+ off64_t poffset; /* pread(2) offset */
+#endif
+
+ /*
+ * If LIO_RANDOM bit specified, get new method randomly.
+ */
+ if (method & LIO_RANDOM) {
+ if (Debug_level > 3)
+ printf("DEBUG %s/%d: method mask to choose from: %#o\n", __FILE__, __LINE__, method );
+ method = lio_random_methods(method);
+ if (Debug_level > 2)
+ printf("DEBUG %s/%d: random chosen method %#o\n", __FILE__, __LINE__, method);
+ }
+
+ if (errmsg != NULL)
+ *errmsg = Errormsg;
+
+ Rec_signal=Received_signal; /* get the current number of signals received */
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ Rec_callback=Received_callback; /* get the current number of callbacks received */
+#endif
+
+#ifdef CRAY
+ memset(&status, 0x00, sizeof(struct iosw));
+ memset(&request, 0x00, sizeof(struct listreq));
+ statptr[0] = &status;
+#else
+ /* for linux or sgi */
+ memset(&iov, 0x00, sizeof(struct iovec));
+ iov.iov_base = buffer;
+ iov.iov_len = size;
+#endif
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+#if defined(sgi)
+ memset(&aiocbp, 0x00, sizeof(aiocb_t));
+#else
+ memset(&aiocbp, 0x00, sizeof(struct aiocb));
+#endif
+ aiocbp.aio_fildes = fd;
+ aiocbp.aio_nbytes = size;
+ aiocbp.aio_buf = buffer;
+/* aiocbp.aio_offset = lseek( fd, 0, SEEK_CUR ); -- set below */
+ aiocbp.aio_sigevent.sigev_notify = SIGEV_NONE;
+ aiocbp.aio_sigevent.sigev_signo = 0;
+#ifdef sgi
+ aiocbp.aio_sigevent.sigev_func = NULL;
+ aiocbp.aio_sigevent.sigev_value.sival_int = 0;
+#elif defined(__linux__) && !defined(__UCLIBC__)
+ aiocbp.aio_sigevent.sigev_notify_function = NULL;
+ aiocbp.aio_sigevent.sigev_notify_attributes = 0;
+#endif
+ aiolist[0] = &aiocbp;
+
+ if ((ret = lseek( fd, 0, SEEK_CUR )) == -1) {
+ ret = 0;
+ /* If there is an error and it is not ESPIPE then kick out the error.
+ * If the fd is a fifo then we have to make sure that
+ * lio_random_methods() didn't select pwrite/pread; if it did then
+ * switch to write/read.
+ */
+ if (errno == ESPIPE) {
+ if (method & LIO_IO_SYNCP) {
+ if (omethod & LIO_RANDOM) {
+ method &= ~LIO_IO_SYNCP;
+ method |= LIO_IO_SYNC;
+ if (Debug_level > 2)
+ printf("DEBUG %s/%d: random chosen method switched to %#o for fifo\n", __FILE__, __LINE__, method );
+ }
+ else if (Debug_level) {
+ printf("DEBUG %s/%d: pread will fail when it reads from a fifo\n",
+ __FILE__, __LINE__ );
+ }
+ }
+ /* else: let it ride */
+ }
+ else{
+ sprintf(Errormsg, "%s/%d lseek(fd=%d,0,SEEK_CUR) failed, errno=%d %s",
+ __FILE__, __LINE__, fd, errno, strerror(errno));
+ return -errno;
+ }
+ }
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ poffset = (off64_t)ret;
+#endif
+ aiocbp.aio_offset = ret;
+
+#endif
+
+ /*
+ * If the LIO_USE_SIGNAL bit is not set, only use the signal
+ * if the LIO_WAIT_SIGPAUSE or the LIO_WAIT_SIGACTIVE bits are set.
+ * Otherwise there is not necessarily a signal handler to trap
+ * the signal.
+ */
+ if (sig && !(method & LIO_USE_SIGNAL) &&
+ ! (method & LIO_WAIT_SIGTYPES) ) {
+
+ sig=0; /* ignore signal parameter */
+ }
+
+#if defined(sgi) || (defined(__linux__)&& !defined(__UCLIBC__))
+ if (sig && (method & LIO_WAIT_CBTYPES))
+ sig=0; /* ignore signal parameter */
+#endif
+
+ /*
+ * only setup signal hander if sig was specified and
+ * a sig wait method was specified.
+ * Doing this will change the handler for this signal. The
+ * old signal handler will not be restored.
+ *** restoring the signal handler could be added ***
+ */
+
+ if (sig && (method & LIO_WAIT_SIGTYPES)) {
+#ifdef CRAY
+ sigctl(SCTL_REG, sig, lio_async_signal_handler);
+#endif
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ aiocbp.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
+ aiocbp.aio_sigevent.sigev_signo = sig;
+ sigset(sig, lio_async_signal_handler);
+#endif /* CRAY */
+ }
+#if defined(sgi)
+ else if (method & LIO_WAIT_CBTYPES) {
+ aiocbp.aio_sigevent.sigev_notify = SIGEV_CALLBACK;
+ aiocbp.aio_sigevent.sigev_func = lio_async_callback_handler;
+ /* sival_int just has to be something that I can use
+ * to identify the callback, and "size" happens to be handy...
+ */
+ aiocbp.aio_sigevent.sigev_value.sival_int = size;
+ }
+#endif
+#if defined(__linux__) && !defined(__UCLIBC__)
+ else if (method & LIO_WAIT_CBTYPES) {
+ aiocbp.aio_sigevent.sigev_notify = SIGEV_THREAD;
+ aiocbp.aio_sigevent.sigev_notify_function = lio_async_callback_handler;
+ /* sival_int just has to be something that I can use
+ * to identify the callback, and "size" happens to be handy...
+ */
+ aiocbp.aio_sigevent.sigev_notify_attributes = (void*)(uintptr_t)size;
+ }
+#endif
+
+ /*
+ * Determine the system call that will be called and produce
+ * the string of the system call and place it in Lio_SysCall.
+ * Also update the io_type char pointer to give brief description
+ * of system call. Execute the system call and check for
+ * system call failure. If sync i/o, return the number of
+ * bytes written/read.
+ */
+
+ if ((method & LIO_IO_SYNC) || (method & (LIO_IO_TYPES | LIO_IO_ATYPES)) == 0) {
+ /*
+ * read(2) is used if LIO_IO_SYNC bit is set or not none
+ * of the LIO_IO_TYPES bits are set (default).
+ */
+
+ sprintf(Lio_SysCall,
+ "read(%d, buf, %d)", fd, size);
+ io_type="read";
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+
+ while (1) {
+ if (((ret = read(fd, buffer, size)) == -1) && errno!=EINTR && errno!=EAGAIN) {
+ sprintf(Errormsg, "%s/%d read(%d, buf, %d) ret:-1, errno=%d %s",
+ __FILE__, __LINE__,
+ fd, size, errno, strerror(errno));
+ return -errno;
+ }
+
+ if (ret==0) return 0;
+ if (ret!=-1) {
+ if (ret != size) {
+ sprintf(Errormsg,
+ "%s/%d read(%d, buf, %d) returned=%d",
+ __FILE__, __LINE__,
+ fd, size, ret);
+ size-=ret;
+ buffer+=ret;
+ }
+ else {
+ if (Debug_level > 1)
+ printf("DEBUG %s/%d: read completed without error (ret %d)\n",
+ __FILE__, __LINE__, ret);
+
+ return ret;
+ }
+ }
+ wait4sync_io(fd, 1);
+ }
+
+ }
+
+ else if (method & LIO_IO_ASYNC) {
+#ifdef CRAY
+ sprintf(Lio_SysCall,
+ "reada(%d, buf, %d, &status, %d)", fd, size, sig);
+ io_type="reada";
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+
+ sigoff();
+ if ((ret = reada(fd, buffer, size, &status, sig)) == -1) {
+ sprintf(Errormsg,
+ "%s/%d reada(%d, buf, %d, &stat, %d) ret:-1, errno=%d %s",
+ __FILE__, __LINE__,
+ fd, size, sig, errno, strerror(errno));
+ sigon();
+ return -errno;
+ }
+#endif
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ sprintf(Lio_SysCall,
+ "aio_read(fildes=%d, buf, nbytes=%d, signo=%d)", fd, size, sig);
+ io_type="aio_read";
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+
+ if (sig)
+ sighold( sig );
+ if ((ret = aio_read(&aiocbp)) == -1) {
+ sprintf(Errormsg,
+ "%s/%d aio_read(fildes=%d, buf, nbytes=%d, signo=%d) ret:-1, errno=%d %s",
+ __FILE__, __LINE__,
+ fd, size, sig, errno, strerror(errno));
+ if (sig)
+ sigrelse( sig );
+ return -errno;
+ }
+#endif
+ } /* LIO_IO_ASYNC */
+
+ else if (method & LIO_IO_SLISTIO) {
+#ifdef CRAY
+ request.li_opcode = LO_READ;
+ request.li_fildes = fd;
+ request.li_buf = buffer;
+ request.li_nbyte = size;
+ request.li_status = &status;
+ request.li_signo = sig;
+ request.li_nstride = 0;
+ request.li_filstride = 0;
+ request.li_memstride = 0;
+
+ listio_cmd=LC_WAIT;
+ io_type="listio(2) sync read";
+
+ sprintf(Lio_SysCall,
+ "listio(LC_WAIT, &req, 1) LO_READ, fd:%d, nbyte:%d",
+ fd, size);
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+
+ sigoff();
+ if (listio(listio_cmd, &request, 1) == -1) {
+ sprintf(Errormsg, "%s/%d %s failed, fd:%d, nbyte:%d errno=%d %s",
+ __FILE__, __LINE__,
+ Lio_SysCall, fd, size, errno, strerror(errno));
+ sigon();
+ return -errno;
+ }
+
+ if (Debug_level > 1)
+ printf("DEBUG %s/%d: %s did not return -1\n",
+ __FILE__, __LINE__, Lio_SysCall);
+
+ ret=lio_check_asyncio(io_type, size, &status);
+ return ret;
+#endif
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ aiocbp.aio_lio_opcode = LIO_READ;
+ listio_cmd=LIO_WAIT;
+ io_type="lio_listio(3) sync read";
+
+ sprintf(Lio_SysCall,
+ "lio_listio(LIO_WAIT, aiolist, 1, NULL) LIO_READ, fd:%d, nbyte:%d",
+ fd, size);
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+
+ if (sig)
+ sighold( sig );
+ if (lio_listio(listio_cmd, aiolist, 1, NULL) == -1) {
+ sprintf(Errormsg, "%s/%d %s failed, fd:%d, nbyte:%d errno=%d %s",
+ __FILE__, __LINE__,
+ Lio_SysCall, fd, size, errno, strerror(errno));
+ if (sig)
+ sigrelse( sig );
+ return -errno;
+ }
+
+ if (Debug_level > 1)
+ printf("DEBUG %s/%d: %s did not return -1\n",
+ __FILE__, __LINE__, Lio_SysCall);
+
+ ret=lio_check_asyncio(io_type, size, &aiocbp, method);
+ return ret;
+#endif
+ }/* LIO_IO_SLISTIO */
+
+ else if (method & LIO_IO_ALISTIO) {
+#ifdef CRAY
+ request.li_opcode = LO_READ;
+ request.li_fildes = fd;
+ request.li_buf = buffer;
+ request.li_nbyte = size;
+ request.li_status = &status;
+ request.li_signo = sig;
+ request.li_nstride = 0;
+ request.li_filstride = 0;
+ request.li_memstride = 0;
+
+ listio_cmd=LC_START;
+ io_type="listio(2) async read";
+
+ sprintf(Lio_SysCall,
+ "listio(LC_START, &req, 1) LO_READ, fd:%d, nbyte:%d",
+ fd, size);
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+
+ sigoff();
+ if (listio(listio_cmd, &request, 1) == -1) {
+ sprintf(Errormsg, "%s/%d %s failed, fd:%d, nbyte:%d errno=%d %s",
+ __FILE__, __LINE__,
+ Lio_SysCall, fd, size, errno, strerror(errno));
+ sigon();
+ return -errno;
+ }
+#endif
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ aiocbp.aio_lio_opcode = LIO_READ;
+ listio_cmd=LIO_NOWAIT;
+ io_type="lio_listio(3) async read";
+
+ sprintf(Lio_SysCall,
+ "lio_listio(LIO_NOWAIT, aiolist, 1, NULL) LIO_READ, fd:%d, nbyte:%d",
+ fd, size);
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+
+ if (sig)
+ sighold( sig );
+ if (lio_listio(listio_cmd, aiolist, 1, NULL) == -1) {
+ sprintf(Errormsg, "%s/%d %s failed, fd:%d, nbyte:%d errno=%d %s",
+ __FILE__, __LINE__,
+ Lio_SysCall, fd, size, errno, strerror(errno));
+ if (sig)
+ sigrelse( sig );
+ return -errno;
+ }
+#endif
+ } /* LIO_IO_ALISTIO */
+
+#ifndef CRAY
+ else if (method & LIO_IO_SYNCV) {
+ io_type="readv(2)";
+
+ sprintf(Lio_SysCall,
+ "readv(%d, &iov, 1) nbyte:%d", fd, size);
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+ if ((ret = readv(fd, &iov, 1)) == -1) {
+ sprintf(Errormsg, "%s/%d readv(%d, iov, 1) nbyte:%d ret:-1, errno=%d %s",
+ __FILE__, __LINE__,
+ fd, size, errno, strerror(errno));
+ return -errno;
+ }
+
+ if (ret != size) {
+ sprintf(Errormsg,
+ "%s/%d readv(%d, iov, 1) nbyte:%d returned=%d",
+ __FILE__, __LINE__,
+ fd, size, ret);
+ }
+ else if (Debug_level > 1)
+ printf("DEBUG %s/%d: readv completed without error (ret %d)\n",
+ __FILE__, __LINE__, ret);
+
+ return ret;
+ } /* LIO_IO_SYNCV */
+#endif
+
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ else if (method & LIO_IO_SYNCP) {
+ io_type="pread(2)";
+
+ sprintf(Lio_SysCall,
+ "pread(%d, buf, %d, %lld)", fd, size, (long long)poffset);
+
+ if (Debug_level) {
+ printf("DEBUG %s/%d: %s\n", __FILE__, __LINE__, Lio_SysCall);
+ }
+ if ((ret = pread(fd, buffer, size, poffset)) == -1) {
+ sprintf(Errormsg, "%s/%d pread(%d, buf, %d, %lld) ret:-1, errno=%d %s",
+ __FILE__, __LINE__,
+ fd, size, (long long)poffset, errno, strerror(errno));
+ return -errno;
+ }
+
+ if (ret != size) {
+ sprintf(Errormsg,
+ "%s/%d pread(%d, buf, %d, %lld) returned=%d",
+ __FILE__, __LINE__,
+ fd, size, (long long)poffset, ret);
+ }
+ else if (Debug_level > 1)
+ printf("DEBUG %s/%d: pread completed without error (ret %d)\n",
+ __FILE__, __LINE__, ret);
+
+ return ret;
+ } /* LIO_IO_SYNCP */
+#endif
+
+ else {
+ printf("DEBUG %s/%d: No I/O method chosen\n", __FILE__, __LINE__ );
+ return -1;
+ }
+
+ /*
+ * wait for async io to complete.
+ * Note: Sync io should have returned prior to getting here.
+ */
+#ifdef CRAY
+ ret=lio_wait4asyncio(method, fd, statptr);
+#endif
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ ret=lio_wait4asyncio(method, fd, &aiocbp);
+#endif
+
+ /*
+ * If there was an error waiting for async i/o to complete,
+ * return the error value (errno) to the caller.
+ * Note: Errormsg should already have been updated.
+ */
+ if (ret < 0) {
+ return ret;
+ }
+
+ /*
+ * If i/o was not waited for (may not have been completed at this time),
+ * return the size that was requested.
+ */
+ if (ret == 1)
+ return size;
+
+ /*
+ * check that async io was successful.
+ * Note: if the there was an system call failure, -errno
+ * was returned and Errormsg should already have been updated.
+ * If amount i/o was different than size, Errormsg should already
+ * have been updated but the actual i/o size if returned.
+ */
+
+#ifdef CRAY
+ ret=lio_check_asyncio(io_type, size, &status);
+#endif
+#if defined(sgi) || (defined(__linux__) && !defined(__UCLIBC__))
+ ret=lio_check_asyncio(io_type, size, &aiocbp, method);
+#endif
+
+ return ret;
+} /* end of lio_read_buffer */
+
+
+#if !defined(__sun) && !defined(__hpux) && !defined(_AIX)
+/***********************************************************************
+ * This function will check that async io was successful.
+ * It can also be used to check sync listio since it uses the
+ * same method.
+ *
+ * Return Values
+ * If status.sw_error is set, -status.sw_error is returned.
+ * Otherwise sw_count's field value is returned.
+ *
+ * (rrl 04/96)
+ ***********************************************************************/
+#ifdef CRAY
+int lio_check_asyncio(char *io_type, int size, struct iosw *status)
+#elif defined(sgi)
+ int lio_check_asyncio(char *io_type, int size, aiocb_t *aiocbp, int method)
+#elif defined(__linux__) && !defined(__UCLIBC__)
+ int lio_check_asyncio(char *io_type, int size, struct aiocb *aiocbp, int method)
+{
+ int ret;
+
+#ifdef CRAY
+ if (status->sw_error) {
+ sprintf(Errormsg,
+ "%s/%d %s, sw_error set = %d %s, sw_count = %d",
+ __FILE__, __LINE__, io_type,
+ status->sw_error, strerror(status->sw_error), status->sw_count);
+ return -status->sw_error;
+ }
+ else if (status->sw_count != size) {
+ sprintf(Errormsg,
+ "%s/%d %s, sw_count not as expected(%d), but actual:%d",
+ __FILE__, __LINE__, io_type,
+ size, status->sw_count);
+ }
+ else if (Debug_level > 1) {
+ printf("DEBUG %s/%d: %s completed without error (sw_error == 0, sw_count == %d)\n",
+ __FILE__, __LINE__, io_type, status->sw_count);
+ }
+
+ return status->sw_count;
+
+#else
+
+ int cnt = 1;
+
+ /* The I/O may have been synchronous with signal completion. It doesn't
+ * make sense, but the combination could be generated. Release the
+ * completion signal here otherwise it'll hang around and bite us
+ * later.
+ */
+ if (aiocbp->aio_sigevent.sigev_notify == SIGEV_SIGNAL)
+ sigrelse( aiocbp->aio_sigevent.sigev_signo );
+
+ ret = aio_error( aiocbp );
+
+ while (ret == EINPROGRESS) {
+ ret = aio_error( aiocbp );
+ ++cnt;
+ }
+ if (cnt > 1) {
+ sprintf(Errormsg,
+ "%s/%d %s, aio_error had to loop on EINPROGRESS, cnt=%d; random method %#o; sigev_notify=%s",
+ __FILE__, __LINE__, io_type, cnt, method,
+ (aiocbp->aio_sigevent.sigev_notify == SIGEV_SIGNAL ? "signal" :
+ aiocbp->aio_sigevent.sigev_notify == SIGEV_NONE ? "none" :
+#ifdef SIGEV_CALLBACK
+ aiocbp->aio_sigevent.sigev_notify == SIGEV_CALLBACK ? "callback" :
+#endif
+ aiocbp->aio_sigevent.sigev_notify == SIGEV_THREAD ? "thread" :
+ "unknown") );
+ return -ret;
+ }
+
+ if (ret != 0) {
+ sprintf(Errormsg,
+ "%s/%d %s, aio_error = %d %s; random method %#o",
+ __FILE__, __LINE__, io_type,
+ ret, strerror(ret),
+ method );
+ return -ret;
+ }
+ ret = aio_return( aiocbp );
+ if (ret != size) {
+ sprintf(Errormsg,
+ "%s/%d %s, aio_return not as expected(%d), but actual:%d",
+ __FILE__, __LINE__, io_type,
+ size, ret);
+
+#ifdef BUG1_workaround
+ if (ret == 0) {
+ ret = size;
+ if (Debug_level > 1) {
+ printf("WARN %s/%d: %s completed with bug1_workaround (aio_error == 0, aio_return now == %d)\n",
+ __FILE__, __LINE__, io_type, ret);
+ }
+ }
+#endif /* BUG1_workaround */
+
+ }
+ else if (Debug_level > 1) {
+ printf("DEBUG %s/%d: %s completed without error (aio_error == 0, aio_return == %d)\n",
+ __FILE__, __LINE__, io_type, ret);
+ }
+
+ return ret;
+
+#endif
+} /* end of lio_check_asyncio */
+#endif
+
+/***********************************************************************
+ *
+ * This function will wait for async io to complete.
+ * If multiple wait methods are specified, the order is predetermined
+ * to LIO_WAIT_RECALL,
+ * LIO_WAIT_ACTIVE, LIO_WAIT_SIGPAUSE, LIO_WAIT_SIGACTIVE,
+ * then LIO_WAIT_NONE.
+ *
+ * If no wait method was specified the default wait method is: recall(2)
+ * or aio_suspend(3), as appropriate.
+ *
+ * Return Values
+ * <0: errno of failed recall
+ * 0 : async io was completed
+ * 1 : async was not waited for, io may not have completed.
+ *
+ * (rrl 04/96)
+ ***********************************************************************/
+#ifdef CRAY
+int lio_wait4asyncio(int method, int fd, struct iosw **statptr)
+#elif defined(sgi)
+ int lio_wait4asyncio(int method, int fd, aiocb_t *aiocbp)
+#elif defined(__linux__) && !defined(__UCLIBC__)
+ int lio_wait4asyncio(int method, int fd, struct aiocb *aiocbp)
+{
+ int cnt;
+#ifdef sgi
+ int ret;
+ const aiocb_t *aioary[1];
+#endif
+#if defined(__linux__)&& !defined(__UCLIBC__)
+ int ret;
+ const struct aiocb *aioary[1];
+#endif
+
+ if ((method & LIO_WAIT_RECALL)
+#if defined(sgi) || (defined(__linux__)&& !defined(__UCLIBC__))
+ || (method & LIO_WAIT_CBSUSPEND)
+ || (method & LIO_WAIT_SIGSUSPEND)
+#endif
+ || ((method & LIO_WAIT_TYPES) == 0) ) {
+ /*
+ * If method has LIO_WAIT_RECALL bit set or method does
+ * not have any wait method bits set (default), use recall/aio_suspend.
+ */
+#ifdef CRAY
+ if (Debug_level > 2)
+ printf("DEBUG %s/%d: wait method : recall\n", __FILE__, __LINE__);
+ sigon();
+ if (recall(fd, 1, statptr)) {
+ sprintf(Errormsg, "%s/%d recall(%d, 1, stat) failed, errno:%d %s",
+ __FILE__, __LINE__,
+ fd, errno, strerror(errno));
+ return -errno;
+ }
+#else
+ if (Debug_level > 2)
+ printf("DEBUG %s/%d: wait method : aio_suspend, sigev_notify=%s\n", __FILE__, __LINE__,
+ (aiocbp->aio_sigevent.sigev_notify == SIGEV_SIGNAL ? "signal" :
+ aiocbp->aio_sigevent.sigev_notify == SIGEV_NONE ? "none" :
+#ifdef SIGEV_CALLBACK
+ aiocbp->aio_sigevent.sigev_notify == SIGEV_CALLBACK ? "callback" :
+#endif
+ aiocbp->aio_sigevent.sigev_notify == SIGEV_THREAD ? "thread" :
+ "unknown") );
+
+ aioary[0] = aiocbp;
+ ret = aio_suspend( aioary, 1, NULL );
+ if ((ret == -1) && (errno == EINTR)) {
+ if (aiocbp->aio_sigevent.sigev_notify == SIGEV_SIGNAL) {
+ if (Debug_level > 2) {
+ printf("DEBUG %s/%d: aio_suspend received EINTR, sigev_notify=SIGEV_SIGNAL -- ok\n",
+ __FILE__, __LINE__ );
+ }
+ }
+ else {
+ sprintf(Errormsg, "%s/%d aio_suspend received EINTR, sigev_notify=%s, not ok\n",
+ __FILE__, __LINE__,
+ (aiocbp->aio_sigevent.sigev_notify == SIGEV_SIGNAL ? "signal" :
+ aiocbp->aio_sigevent.sigev_notify == SIGEV_NONE ? "none" :
+#ifdef SIGEV_CALLBACK
+ aiocbp->aio_sigevent.sigev_notify == SIGEV_CALLBACK ? "callback" :
+#endif
+ aiocbp->aio_sigevent.sigev_notify == SIGEV_THREAD ? "thread" :
+ "unknown") );
+ return -errno;
+ }
+ }
+ else if (ret) {
+ sprintf(Errormsg, "%s/%d aio_suspend(fildes=%d, aioary, 1, NULL) failed, errno:%d %s",
+ __FILE__, __LINE__,
+ fd, errno, strerror(errno));
+ return -errno;
+ }
+#endif
+
+ } else if (method & LIO_WAIT_ACTIVE) {
+ if (Debug_level > 2)
+ printf("DEBUG %s/%d: wait method : active\n", __FILE__, __LINE__);
+#ifdef CRAY
+ sigon();
+ /*
+ * loop until sw_flag, sw_count or sw_error field elements
+ * change to non-zero.
+ */
+ cnt=0;
+ while ((*statptr)->sw_flag == 0 &&
+ (*statptr)->sw_count == 0 &&
+ (*statptr)->sw_error == 0 ) {
+ cnt++;
+ }
+#else
+ /* loop while aio_error() returns EINPROGRESS */
+ cnt=0;
+ while (1) {
+ ret = aio_error( aiocbp );
+ if ((ret == 0) || (ret != EINPROGRESS)) {
+ break;
+ }
+ ++cnt;
+ }
+
+#endif
+ if (Debug_level > 5 && cnt && (cnt % 50) == 0)
+ printf("DEBUG %s/%d: wait active cnt = %d\n",
+ __FILE__, __LINE__, cnt);
+
+ } else if (method & LIO_WAIT_SIGPAUSE) {
+ if (Debug_level > 2)
+ printf("DEBUG %s/%d: wait method : sigpause\n", __FILE__, __LINE__);
+#ifdef sgi
+ /* note: don't do the sigon() for CRAY in this case. why? -- roehrich 6/11/97 */
+ if (aiocbp->aio_sigevent.sigev_notify == SIGEV_SIGNAL)
+ sigrelse( aiocbp->aio_sigevent.sigev_signo );
+ else {
+ printf("DEBUG %s/%d: sigev_notify != SIGEV_SIGNAL\n", __FILE__, __LINE__ );
+ return -1;
+ }
+#endif
+ pause();
+
+ } else if (method & LIO_WAIT_SIGACTIVE) {
+ if (Debug_level > 2)
+ printf("DEBUG %s/%d: wait method : sigactive\n", __FILE__, __LINE__);
+#ifdef CRAY
+ sigon();
+#else
+ if (aiocbp->aio_sigevent.sigev_notify == SIGEV_SIGNAL)
+ sigrelse( aiocbp->aio_sigevent.sigev_signo );
+ else {
+ printf("DEBUG %s/%d: sigev_notify != SIGEV_SIGNAL\n", __FILE__, __LINE__ );
+ return -1;
+ }
+#endif
+ /* loop waiting for signal */
+ while (Received_signal == Rec_signal) {
+#ifdef CRAY
+ sigon();
+#else
+ sigrelse( aiocbp->aio_sigevent.sigev_signo );
+#endif
+ }
+
+ } else if (method & LIO_WAIT_NONE) {
+ if (Debug_level > 2)
+ printf("DEBUG %s/%d: wait method : none\n", __FILE__, __LINE__);
+ /* It's broken because the aiocb/iosw is an automatic variable in
+ * lio_{read,write}_buffer, so when the function returns and the
+ * I/O completes there will be nowhere to write the I/O status.
+ * It doesn't cause a problem on unicos--probably because of some
+ * compiler quirk, or an accident. It causes POSIX async I/O
+ * to core dump some threads. spr/pv 705909. 6/27/97 roehrich
+ */
+ sprintf(Errormsg, "%s/%d LIO_WAIT_NONE was selected (this is broken)\n",
+ __FILE__, __LINE__ );
+#ifdef CRAY
+ sigon();
+#endif
+/* return 1;*/
+ return -1;
+ }
+ else {
+ if (Debug_level > 2)
+ printf("DEBUG %s/%d: no wait method was chosen\n", __FILE__, __LINE__ );
+ return -1;
+ }
+
+ return 0;
+
+} /* end of lio_wait4asyncio */
+
+#endif /* ifndef linux */
+#endif
+
+#if UNIT_TEST
+/***********************************************************************
+ * The following code is provided as unit test.
+ * Just define add "-DUNIT_TEST=1" to the cc line.
+ *
+ * (rrl 04/96)
+ ***********************************************************************/
+struct unit_info_t {
+ int method;
+ int sig;
+ char *str;
+} Unit_info[] = {
+ { LIO_IO_SYNC, 0, "sync io" },
+ { LIO_IO_SYNCV, 0, "sync readv/writev" },
+ { LIO_IO_SYNCP, 0, "sync pread/pwrite" },
+ { LIO_IO_ASYNC, 0, "async io, def wait" },
+ { LIO_IO_SLISTIO, 0, "sync listio" },
+ { LIO_IO_ALISTIO, 0, "async listio, def wait" },
+ { LIO_IO_ASYNC|LIO_WAIT_ACTIVE, 0, "async active" },
+ { LIO_IO_ASYNC|LIO_WAIT_RECALL, 0, "async recall/suspend" },
+ { LIO_IO_ASYNC|LIO_WAIT_SIGPAUSE, SIGUSR1, "async sigpause" },
+ { LIO_IO_ASYNC|LIO_WAIT_SIGACTIVE, SIGUSR1, "async sigactive" },
+ { LIO_IO_ALISTIO|LIO_WAIT_ACTIVE, 0, "async listio active" },
+ { LIO_IO_ALISTIO|LIO_WAIT_RECALL, 0, "async listio recall" },
+ { LIO_IO_ALISTIO|LIO_WAIT_SIGACTIVE, SIGUSR1, "async listio sigactive" },
+ { LIO_IO_ALISTIO|LIO_WAIT_SIGPAUSE, SIGUSR1, "async listio sigpause" },
+ { LIO_IO_ASYNC, SIGUSR2, "async io, def wait, sigusr2" },
+ { LIO_IO_ALISTIO, SIGUSR2, "async listio, def wait, sigusr2" },
+};
+
+int
+main(argc, argv)
+int argc;
+char **argv;
+{
+ extern char *optarg;
+ extern int optind;
+
+ int fd;
+ char *err;
+ char buffer[4096];
+ int size=4096;
+ int ret;
+ int ind;
+ int iter=3;
+ int method;
+ int exit_status = 0;
+ int c;
+ int i;
+ char *symbols = NULL;
+ int die_on_err = 0;
+
+ while ((c = getopt(argc,argv,"s:di:")) != -1) {
+ switch(c) {
+ case 's': symbols = optarg; break;
+ case 'd': ++die_on_err; break;
+ case 'i': iter = atoi(optarg); break;
+ }
+ }
+
+ if ((fd=open("unit_test_file", O_CREAT|O_RDWR|O_TRUNC, 0777)) == -1) {
+ perror("open(unit_test_file, O_CREAT|O_RDWR|O_TRUNC, 0777) failed");
+ exit(1);
+ }
+
+ Debug_level=9;
+
+ if (symbols != NULL) {
+ if ((method=lio_parse_io_arg2(symbols, &err)) == -1) {
+ printf("lio_parse_io_arg2(%s, &err) failed, bad token starting at %s\n",
+ symbols, err);
+ if (die_on_err)
+ exit(1);
+ }
+ else
+ printf("lio_parse_io_arg2(%s, &err) returned %#o\n", symbols, method);
+
+ exit_status = 0;
+ for (ind=0; ind < iter; ind++) {
+ memset( buffer, 'A', 4096 );
+ if (lseek(fd, 0, 0) == -1) {
+ printf("lseek(fd,0,0), %d, failed, errno %d\n",
+ __LINE__, errno );
+ ++exit_status;
+ }
+ if ((ret=lio_write_buffer(fd, method, buffer,
+ size, SIGUSR1, &err, 0)) != size ) {
+ printf("lio_write_buffer returned -1, err = %s\n", err);
+ } else
+ printf("lio_write_buffer returned %d\n", ret);
+
+ memset( buffer, 'B', 4096 );
+ if (lseek(fd, 0, 0) == -1) {
+ printf("lseek(fd,0,0), %d, failed, errno %d\n",
+ __LINE__, errno );
+ ++exit_status;
+ }
+ if ((ret=lio_read_buffer(fd, method, buffer,
+ size, SIGUSR2, &err, 0)) != size ) {
+ printf("lio_read_buffer returned -1, err = %s\n", err);
+ } else
+ printf("lio_read_buffer returned %d\n", ret);
+
+ for (i = 0; i < 4096; ++i) {
+ if (buffer[i] != 'A') {
+ printf(" buffer[%d] = %d\n", i, buffer[i] );
+ ++exit_status;
+ break;
+ }
+ }
+
+ if (exit_status)
+ exit(exit_status);
+
+ }
+
+ unlink("unit_test_file");
+ exit(0);
+ }
+
+ for (ind=0; ind < sizeof(Unit_info)/sizeof(struct unit_info_t); ind++) {
+
+ printf("\n********* write %s ***************\n", Unit_info[ind].str);
+ if (lseek(fd, 0, 0) == -1) {
+ printf("lseek(fd,0,0), %d, failed, errno %d\n",
+ __LINE__, errno );
+ ++exit_status;
+ }
+
+ memset( buffer, 'A', 4096 );
+ if ((ret=lio_write_buffer(fd, Unit_info[ind].method, buffer,
+ size, Unit_info[ind].sig, &err, 0)) != size ) {
+ printf(">>>>> lio_write_buffer(fd,0%x,buffer,%d,%d,err,0) returned -1,\n err = %s\n",
+ Unit_info[ind].method, size, Unit_info[ind].sig, err);
+ ++exit_status;
+ if (die_on_err)
+ exit(exit_status);
+ } else{
+ printf("lio_write_buffer returned %d\n", ret);
+ }
+
+ printf("\n********* read %s ***************\n", Unit_info[ind].str);
+ if (lseek(fd, 0, 0) == -1) {
+ printf("lseek(fd,0,0), %d, failed, errno %d\n",
+ __LINE__, errno );
+ ++exit_status;
+ }
+ memset( buffer, 'B', 4096 );
+ if ((ret=lio_read_buffer(fd, Unit_info[ind].method, buffer,
+ size, Unit_info[ind].sig, &err, 0)) != size ) {
+ printf(">>>>> lio_read_buffer(fd,0%x,buffer,%d,%d,err,0) returned -1,\n err = %s\n",
+ Unit_info[ind].method, size, Unit_info[ind].sig, err);
+ ++exit_status;
+ if (die_on_err)
+ exit(exit_status);
+ } else {
+ printf("lio_read_buffer returned %d\n", ret);
+ }
+
+ for (i = 0; i < 4096; ++i) {
+ if (buffer[i] != 'A') {
+ printf(" buffer[%d] = %d\n", i, buffer[i] );
+ ++exit_status;
+ if (die_on_err)
+ exit(exit_status);
+ break;
+ }
+ }
+
+ fflush(stdout);
+ fflush(stderr);
+ sleep(1);
+
+ }
+
+ unlink("unit_test_file");
+
+ exit(exit_status);
+}
+#endif
diff --git a/ltp_framework/lib/tst_cwd_has_free.c b/ltp_framework/lib/tst_cwd_has_free.c
new file mode 100644
index 0000000..791df09
--- /dev/null
+++ b/ltp_framework/lib/tst_cwd_has_free.c
@@ -0,0 +1,22 @@
+/*
+ * AUTHOR
+ * Ricky Ng-Adam <rngadam@yahoo.com>, 2005-01-01
+ *
+ * DESCRIPTION
+ * Check if there is enough blocks to fill number of KiB specified
+ * If current directory has enough blocks, return 1
+ * If current directory has NOT enough blocks, return 0
+ *
+ *
+ */
+#include <sys/vfs.h>
+
+int
+tst_cwd_has_free(int required_kib)
+{
+ struct statfs sf;
+ statfs(".", &sf);
+
+ /* check that we have enough blocks to create swap file */
+ return ((float)sf.f_bfree)/(1024/sf.f_bsize) >= required_kib?1:0;
+} \ No newline at end of file
diff --git a/ltp_framework/lib/tst_is_cwd.c b/ltp_framework/lib/tst_is_cwd.c
new file mode 100644
index 0000000..636aaca
--- /dev/null
+++ b/ltp_framework/lib/tst_is_cwd.c
@@ -0,0 +1,52 @@
+/*
+ * Michal Simek <monstr@monstr.eu>, 2009-08-03 - ramfs
+ * Kumar Gala <galak@kernel.crashing.org>, 2007-11-14 - nfs
+ * Ricky Ng-Adam <rngadam@yahoo.com>, 2005-01-01 - tmpfs
+ *
+ * DESCRIPTION
+ * Check if current directory is on a tmpfs/nfs/ramfs filesystem
+ * If current directory is tmpfs/nfs/ramfs, return 1
+ * If current directory is NOT tmpfs/nfs/ramfs, return 0
+ */
+
+#include <sys/vfs.h>
+
+#define TMPFS_MAGIC 0x01021994 /* man 2 statfs */
+int tst_is_cwd_tmpfs(void)
+{
+ struct statfs sf;
+ statfs(".", &sf);
+
+ /* Verify that the file is not on a tmpfs (in-memory) filesystem */
+ return (sf.f_type == TMPFS_MAGIC);
+}
+
+#define NFS_MAGIC 0x6969 /* man 2 statfs */
+int tst_is_cwd_nfs(void)
+{
+ struct statfs sf;
+ statfs(".", &sf);
+
+ /* Verify that the file is not on a nfs filesystem */
+ return (sf.f_type == NFS_MAGIC);
+}
+
+#define V9FS_MAGIC 0x01021997 /* kernel-source/include/linux/magic.h */
+int tst_is_cwd_v9fs(void)
+{
+ struct statfs sf;
+ statfs(".", &sf);
+
+ /* Verify that the file is not on a nfs filesystem */
+ return (sf.f_type == V9FS_MAGIC);
+}
+
+#define RAMFS_MAGIC 0x858458f6
+int tst_is_cwd_ramfs(void)
+{
+ struct statfs sf;
+ statfs(".", &sf);
+
+ /* Verify that the file is not on a ramfs (in-memory) filesystem */
+ return (sf.f_type == RAMFS_MAGIC);
+}
diff --git a/ltp_framework/lib/tst_kvercmp.c b/ltp_framework/lib/tst_kvercmp.c
new file mode 100644
index 0000000..f132164
--- /dev/null
+++ b/ltp_framework/lib/tst_kvercmp.c
@@ -0,0 +1,68 @@
+/*
+ *
+ * Copyright (c) International Business Machines Corp., 2003
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
+ * the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ *
+ * AUTHOR
+ * Paul Larson <plars@linuxtestproject.org>
+ *
+ * DESCRIPTION
+ * Compare a given kernel version against the current kernel version.
+ * If they are the same - return 0
+ * If the argument is > current kernel version - return positive int
+ * If the argument is < current kernel version - return negative int
+ *
+ */
+
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include <sys/utsname.h>
+
+void get_kver(int *k1, int *k2, int *k3)
+{
+ struct utsname uval;
+ char *kver;
+ char *r1, *r2, *r3;
+#if !defined(linux)
+ extern char *strsep(); /* shut up some compilers */
+#endif
+
+ uname(&uval);
+ kver = uval.release;
+ r1 = strsep(&kver, ".");
+ r2 = strsep(&kver, ".");
+ r3 = strsep(&kver, ".");
+
+ *k1 = atoi(r1);
+ *k2 = atoi(r2);
+ *k3 = atoi(r3);
+}
+
+int tst_kvercmp(int r1, int r2, int r3) {
+ int a1, a2, a3;
+ int testver, currver;
+
+ get_kver(&a1, &a2, &a3);
+ testver = (r1 << 16) + (r2 << 8) + r3;
+ currver = (a1 << 16) + (a2 << 8) + a3;
+
+ return currver - testver;
+} \ No newline at end of file
diff --git a/ltp_framework/lib/tst_res.c b/ltp_framework/lib/tst_res.c
new file mode 100644
index 0000000..f958279
--- /dev/null
+++ b/ltp_framework/lib/tst_res.c
@@ -0,0 +1,812 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ * Copyright (c) 2009 Cyril Hrubis chrubis@suse.cz
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+
+
+/* $Id: tst_res.c,v 1.14 2009/12/01 08:57:20 yaberauneya Exp $ */
+
+/**********************************************************
+ *
+ * OS Testing - Silicon Graphics, Inc.
+ *
+ * FUNCTION NAME :
+ * tst_res() - Print result message (include file contents)
+ * tst_resm() - Print result message
+ * tst_brk() - Print result message (include file contents)
+ * and break remaining test cases
+ * tst_brkm() - Print result message and break remaining test
+ * cases
+ * tst_flush() - Print any messages pending in the output stream
+ * tst_exit() - Exit test with a meaningful exit value.
+ * tst_environ() - Keep results coming to original stdout
+ *
+ * FUNCTION TITLE : Standard automated test result reporting mechanism
+ *
+ * SYNOPSIS:
+ * #include "test.h"
+ *
+ * void tst_res(ttype, fname, tmesg [,arg]...)
+ * int ttype;
+ * char *fname;
+ * char *tmesg;
+ *
+ * void tst_resm(ttype, tmesg [,arg]...)
+ * int ttype;
+ * char *tmesg;
+ *
+ * void tst_brk(ttype, fname, cleanup, tmesg, [,argv]...)
+ * int ttype;
+ * char *fname;
+ * void (*cleanup)();
+ * char *tmesg;
+ *
+ * void tst_brkm(ttype, cleanup, tmesg [,arg]...)
+ * int ttype;
+ * void (*cleanup)();
+ * char *tmesg;
+ *
+ * void tst_flush()
+ *
+ * void tst_exit()
+ *
+ * int tst_environ()
+ *
+ * AUTHOR : Kent Rogers (from Dave Fenner's original)
+ *
+ * CO-PILOT : Rich Logan
+ *
+ * DATE STARTED : 05/01/90 (rewritten 1/96)
+ *
+ * MAJOR CLEANUPS BY : Cyril Hrubis
+ *
+ * DESCRIPTION
+ * See the man page(s).
+ *
+ *#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**/
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <unistd.h>
+#include "test.h"
+#include "usctest.h"
+
+/* Break bad habits. */
+#ifdef GARRETT_IS_A_PEDANTIC_BASTARD
+pid_t spawned_program_pid;
+#endif
+
+#define VERBOSE 1 /* flag values for the T_mode variable */
+#define NOPASS 3
+#define DISCARD 4
+
+#define MAXMESG 80 /* max length of internal messages */
+#define USERMESG 2048 /* max length of user message */
+#define TRUE 1
+#define FALSE 0
+
+/*
+ * EXPAND_VAR_ARGS - Expand the variable portion (arg_fmt) of a result
+ * message into the specified string.
+ *
+ * NOTE (garrcoop): arg_fmt _must_ be the last element in each function
+ * argument list that employs this.
+ */
+#define EXPAND_VAR_ARGS(buf, arg_fmt, buf_len) do {\
+ va_list ap; \
+ assert(arg_fmt != NULL); \
+ va_start(ap, arg_fmt); \
+ vsnprintf(buf, buf_len, arg_fmt, ap); \
+ va_end(ap); \
+ assert(strlen(buf) > 0); \
+} while (0)
+
+/*
+ * Define local function prototypes.
+ */
+static void check_env(void);
+static void tst_condense(int tnum, int ttype, char *tmesg);
+static void tst_print(char *tcid, int tnum, int ttype, char *tmesg);
+static void cat_file(char *filename);
+
+/*
+ * Define some static/global variables.
+ */
+static FILE *T_out = NULL; /* tst_res() output file descriptor */
+static char *File; /* file whose contents is part of result */
+static int T_exitval = 0; /* exit value used by tst_exit() */
+static int T_mode = VERBOSE; /* flag indicating print mode: VERBOSE, */
+ /* NOPASS, DISCARD */
+
+static char Warn_mesg[MAXMESG]; /* holds warning messages */
+
+/*
+ * These are used for condensing output when NOT in verbose mode.
+ */
+static int Buffered = FALSE; /* TRUE if condensed output is currently */
+ /* buffered (i.e. not yet printed) */
+static char *Last_tcid; /* previous test case id */
+static int Last_num; /* previous test case number */
+static int Last_type; /* previous test result type */
+static char *Last_mesg; /* previous test result message */
+
+
+/*
+ * These globals may be externed by the test.
+ */
+int Tst_count = 0; /* current count of test cases executed; NOTE: */
+ /* Tst_count may be externed by other programs */
+
+/*
+ * These globals must be defined in the test.
+ */
+extern char *TCID; /* Test case identifier from the test source */
+extern int TST_TOTAL; /* Total number of test cases from the test */
+ /* source */
+
+struct pair {
+ const char *name;
+ int val;
+};
+#define PAIR(def) [def] = { .name = #def, .val = def, },
+const char *pair_lookup(struct pair *pair, int pair_size, int idx)
+{
+ if (idx < 0 || idx >= pair_size || pair[idx].name == NULL)
+ return "???";
+ return pair[idx].name;
+}
+#define pair_lookup(pair, idx) pair_lookup(pair, ARRAY_SIZE(pair), idx)
+
+/*
+ * strttype() - convert a type result to the human readable string
+ */
+const char *strttype(int ttype)
+{
+ struct pair ttype_pairs[] = {
+ PAIR(TPASS)
+ PAIR(TFAIL)
+ PAIR(TBROK)
+ PAIR(TRETR)
+ PAIR(TCONF)
+ PAIR(TWARN)
+ PAIR(TINFO)
+ };
+ return pair_lookup(ttype_pairs, TTYPE_RESULT(ttype));
+}
+
+/*
+ * strerrnodef() - convert an errno value to its C define
+ */
+static const char *strerrnodef(int err)
+{
+ struct pair errno_pairs[] = {
+ PAIR(EPERM)
+ PAIR(ENOENT)
+ PAIR(ESRCH)
+ PAIR(EINTR)
+ PAIR(EIO)
+ PAIR(ENXIO)
+ PAIR(E2BIG)
+ PAIR(ENOEXEC)
+ PAIR(EBADF)
+ PAIR(ECHILD)
+ PAIR(EAGAIN)
+ PAIR(ENOMEM)
+ PAIR(EACCES)
+ PAIR(EFAULT)
+ PAIR(ENOTBLK)
+ PAIR(EBUSY)
+ PAIR(EEXIST)
+ PAIR(EXDEV)
+ PAIR(ENODEV)
+ PAIR(ENOTDIR)
+ PAIR(EISDIR)
+ PAIR(EINVAL)
+ PAIR(ENFILE)
+ PAIR(EMFILE)
+ PAIR(ENOTTY)
+ PAIR(ETXTBSY)
+ PAIR(EFBIG)
+ PAIR(ENOSPC)
+ PAIR(ESPIPE)
+ PAIR(EROFS)
+ PAIR(EMLINK)
+ PAIR(EPIPE)
+ PAIR(EDOM)
+ PAIR(ERANGE)
+ PAIR(ENAMETOOLONG)
+ };
+ return pair_lookup(errno_pairs, err);
+}
+
+/*
+ * tst_res() - Main result reporting function. Handle test information
+ * appropriately depending on output display mode. Call
+ * tst_condense() or tst_print() to actually print results.
+ * All result functions (tst_resm(), tst_brk(), etc.)
+ * eventually get here to print the results.
+ */
+void tst_res(int ttype, char *fname, char *arg_fmt, ...)
+{
+ char tmesg[USERMESG];
+ int ttype_result = TTYPE_RESULT(ttype);
+
+#if DEBUG
+ printf("IN tst_res; Tst_count = %d\n", Tst_count);
+ fflush(stdout);
+#endif
+
+ EXPAND_VAR_ARGS(tmesg, arg_fmt, USERMESG);
+
+ /*
+ * Save the test result type by ORing ttype into the current exit
+ * value (used by tst_exit()).
+ */
+ T_exitval |= ttype_result;
+
+ /*
+ * Unless T_out has already been set by tst_environ(), make tst_res()
+ * output go to standard output.
+ */
+ if (T_out == NULL)
+ T_out = stdout;
+
+ /*
+ * Check TOUTPUT environment variable (if first time) and set T_mode
+ * flag.
+ */
+ check_env();
+
+ if (fname != NULL && access(fname, F_OK) == 0)
+ File = fname;
+
+ /*
+ * Set the test case number and print the results, depending on the
+ * display type.
+ */
+ if (ttype_result == TWARN || ttype_result == TINFO) {
+ tst_print(TCID, 0, ttype, tmesg);
+ } else {
+ if (Tst_count < 0)
+ tst_print(TCID, 0, TWARN,
+ "tst_res(): Tst_count < 0 is not valid");
+
+ /*
+ * Process each display type.
+ */
+ switch (T_mode) {
+ case DISCARD:
+ break;
+ case NOPASS: /* filtered by tst_print() */
+ tst_condense(Tst_count+1, ttype, tmesg);
+ break;
+ default: /* VERBOSE */
+ tst_print(TCID, Tst_count+1, ttype, tmesg);
+ break;
+ }
+
+ Tst_count++;
+ }
+
+}
+
+
+/*
+ * tst_condense() - Handle test cases in NOPASS mode (i.e.
+ * buffer the current result and print the last result
+ * if different than the current). If a file was
+ * specified, print the current result and do not
+ * buffer it.
+ */
+static void tst_condense(int tnum, int ttype, char *tmesg)
+{
+ char *file;
+ int ttype_result = TTYPE_RESULT(ttype);
+
+#if DEBUG
+ printf( "IN tst_condense: tcid = %s, tnum = %d, ttype = %d, "
+ "tmesg = %s\n",
+ TCID, tnum, ttype, tmesg);
+ fflush(stdout);
+#endif
+
+ /*
+ * If this result is the same as the previous result, return.
+ */
+ if (Buffered == TRUE) {
+ if (strcmp(Last_tcid, TCID) == 0 && Last_type == ttype_result &&
+ strcmp(Last_mesg, tmesg) == 0 && File == NULL)
+ return;
+
+ /*
+ * This result is different from the previous result. First,
+ * print the previous result.
+ */
+ file = File;
+ File = NULL;
+ tst_print(Last_tcid, Last_num, Last_type, Last_mesg);
+ free(Last_tcid);
+ free(Last_mesg);
+ File = file;
+ }
+
+ /*
+ * If a file was specified, print the current result since we have no
+ * way of retaining the file contents for comparing with future
+ * results. Otherwise, buffer the current result info for next time.
+ */
+ if (File != NULL) {
+ tst_print(TCID, tnum, ttype, tmesg);
+ Buffered = FALSE;
+ } else {
+ Last_tcid = (char *)malloc(strlen(TCID) + 1);
+ strcpy(Last_tcid, TCID);
+ Last_num = tnum;
+ Last_type = ttype_result;
+ Last_mesg = (char *)malloc(strlen(tmesg) + 1);
+ strcpy(Last_mesg, tmesg);
+ Buffered = TRUE;
+ }
+}
+
+
+/*
+ * tst_flush() - Print any messages pending because due to tst_condense,
+ * and flush T_out.
+ */
+void tst_flush(void)
+{
+#if DEBUG
+ printf("IN tst_flush\n");
+ fflush(stdout);
+#endif
+
+ /*
+ * Print out last line if in NOPASS mode.
+ */
+ if (Buffered == TRUE && T_mode == NOPASS) {
+ tst_print(Last_tcid, Last_num, Last_type, Last_mesg);
+ Buffered = FALSE;
+ }
+
+ fflush(T_out);
+}
+
+
+/*
+ * tst_print() - Print a line to the output stream.
+ */
+static void tst_print(char *tcid, int tnum, int ttype, char *tmesg)
+{
+ /*
+ * avoid unintended side effects from failures with fprintf when
+ * calling write(2), et all.
+ */
+ int err = errno;
+ const char *type;
+ int ttype_result = TTYPE_RESULT(ttype);
+
+#ifdef GARRETT_IS_A_PEDANTIC_BASTARD
+ /* Don't execute these APIs unless you have the same pid as main! */
+ if (spawned_program_pid != 0) {
+ /*
+ * Die quickly and noisily so people get the cluebat that the
+ * test needs to be fixed. These APIs should _not_ be called
+ * from forked processes because of the fact that it can confuse
+ * end-users with printouts, cleanup will potentially blow away
+ * directories and/or files still in use introducing
+ * non-determinism, etc.
+ *
+ * assert will not return (by design in accordance with POSIX
+ * 1003.1) if the assertion fails. Read abort(3) for more
+ * details. So don't worry about saving / restoring the signal
+ * handler, unless you have a buggy OS that you've hacked 15
+ * different ways to Sunday.
+ */
+ assert(spawned_program_pid == getpid());
+ }
+#endif
+
+#if DEBUG
+ printf("IN tst_print: tnum = %d, ttype = %d, tmesg = %s\n",
+ tnum, ttype, tmesg);
+ fflush(stdout);
+#endif
+
+ /*
+ * Save the test result type by ORing ttype into the current exit value
+ * (used by tst_exit()). This is already done in tst_res(), but is
+ * also done here to catch internal warnings. For internal warnings,
+ * tst_print() is called directly with a case of TWARN.
+ */
+ T_exitval |= ttype_result;
+
+ /*
+ * If output mode is DISCARD, or if the output mode is NOPASS and this
+ * result is not one of FAIL, BROK, or WARN, just return. This check
+ * is necessary even though we check for DISCARD mode inside of
+ * tst_res(), since occasionally we get to this point without going
+ * through tst_res() (e.g. internal TWARN messages).
+ */
+ if (T_mode == DISCARD || (T_mode == NOPASS && ttype_result != TFAIL &&
+ ttype_result != TBROK && ttype_result != TWARN))
+ return;
+
+ /*
+ * Build the result line and print it.
+ */
+ type = strttype(ttype);
+ if (T_mode == VERBOSE) {
+ fprintf(T_out, "%-8s %4d %s : %s", tcid, tnum, type, tmesg);
+ } else {
+ fprintf(T_out, "%-8s %4d %s : %s",
+ tcid, tnum, type, tmesg);
+ }
+ if (ttype & TERRNO) {
+ fprintf(T_out, ": errno=%s(%i): %s", strerrnodef(err),
+ err, strerror(err));
+ }
+ if (ttype & TTERRNO) {
+ fprintf(T_out, ": TEST_ERRNO=%s(%i): %s",
+ strerrnodef(TEST_ERRNO), (int)TEST_ERRNO,
+ strerror(TEST_ERRNO));
+ }
+ fprintf(T_out, "\n");
+
+ /*
+ * If tst_res() was called with a file, append file contents to the
+ * end of last printed result.
+ */
+ if (File != NULL)
+ cat_file(File);
+
+ File = NULL;
+}
+
+
+/*
+ * check_env() - Check the value of the environment variable TOUTPUT and
+ * set the global variable T_mode. The TOUTPUT environment
+ * variable should be set to "VERBOSE", "NOPASS", or "DISCARD".
+ * If TOUTPUT does not exist or is not set to a valid value, the
+ * default is "VERBOSE".
+ */
+static void check_env(void)
+{
+ static int first_time = 1;
+ char *value;
+
+#if DEBUG
+ printf("IN check_env\n");
+ fflush(stdout);
+#endif
+
+ if (!first_time)
+ return;
+
+ first_time = 0;
+
+ /* BTOUTPUT not defined, use default */
+ if ((value = getenv(TOUTPUT)) == NULL) {
+ T_mode = VERBOSE;
+ return;
+ }
+
+ if (strcmp(value, TOUT_NOPASS_S) == 0) {
+ T_mode = NOPASS;
+ return;
+ }
+
+ if (strcmp(value, TOUT_DISCARD_S) == 0) {
+ T_mode = DISCARD;
+ return;
+ }
+
+ /* default */
+ T_mode = VERBOSE;
+ return;
+}
+
+
+/*
+ * tst_exit() - Call exit() with the value T_exitval, set up by
+ * tst_res(). T_exitval has a bit set for most of the
+ * result types that were seen (including TPASS, TFAIL,
+ * TBROK, TWARN, TCONF). Also, print the last result (if
+ * necessary) before exiting.
+ */
+void tst_exit(void)
+{
+#if DEBUG
+ printf("IN tst_exit\n"); fflush(stdout);
+ fflush(stdout);
+#endif
+
+ /* Call tst_flush() flush any output in the buffer. */
+ tst_flush();
+
+ /* Mask out TRETR, TINFO, and TCONF results from the exit status. */
+ exit(T_exitval & ~(TRETR | TINFO | TCONF));
+}
+
+
+/*
+ * tst_environ() - Preserve the tst_res() output location, despite any
+ * changes to stdout.
+ */
+int tst_environ(void)
+{
+ if ((T_out = fdopen(dup(fileno(stdout)), "w")) == NULL)
+ return -1;
+ else
+ return 0;
+}
+
+
+/*
+ * Make tst_brk reentrant so that one can call the SAFE_* macros from within
+ * user-defined cleanup functions.
+ */
+static int tst_brk_entered = 0;
+
+/*
+ * tst_brk() - Fail or break current test case, and break the remaining
+ * tests cases.
+ */
+void tst_brk(int ttype, char *fname, void (*func)(void), char *arg_fmt, ...)
+{
+ char tmesg[USERMESG];
+ int ttype_result = TTYPE_RESULT(ttype);
+
+#if DEBUG
+ printf("IN tst_brk\n"); fflush(stdout);
+ fflush(stdout);
+#endif
+
+ EXPAND_VAR_ARGS(tmesg, arg_fmt, USERMESG);
+
+ /*
+ * Only FAIL, BROK, CONF, and RETR are supported by tst_brk().
+ */
+ if (ttype_result != TFAIL && ttype_result != TBROK &&
+ ttype_result != TCONF && ttype_result != TRETR) {
+ sprintf(Warn_mesg, "%s: Invalid Type: %d. Using TBROK",
+ __func__, ttype_result);
+ tst_print(TCID, 0, TWARN, Warn_mesg);
+ /* Keep TERRNO, TTERRNO, etc. */
+ ttype = (ttype & ~ttype_result) | TBROK;
+ }
+
+ tst_res(ttype, fname, "%s", tmesg);
+ if (tst_brk_entered == 0) {
+ if (ttype_result == TCONF)
+ tst_res(ttype, NULL,
+ "Remaining cases not appropriate for "
+ "configuration");
+ else if (ttype_result == TRETR)
+ tst_res(ttype, NULL, "Remaining cases retired");
+ else if (ttype_result == TBROK)
+ tst_res(TBROK, NULL, "Remaining cases broken");
+ }
+
+ /*
+ * If no cleanup function was specified, just return to the caller.
+ * Otherwise call the specified function.
+ */
+ if (func != NULL) {
+ tst_brk_entered++;
+ (*func)();
+ tst_brk_entered--;
+ }
+ if (tst_brk_entered == 0)
+ tst_exit();
+
+}
+
+/*
+ * tst_resm() - Interface to tst_res(), with no filename.
+ */
+void tst_resm(int ttype, char *arg_fmt, ...)
+{
+ char tmesg[USERMESG];
+
+#if DEBUG
+ printf("IN tst_resm\n"); fflush(stdout);
+ fflush(stdout);
+#endif
+
+ EXPAND_VAR_ARGS(tmesg, arg_fmt, USERMESG);
+
+ tst_res(ttype, NULL, "%s", tmesg);
+}
+
+
+/*
+ * tst_brkm() - Interface to tst_brk(), with no filename.
+ */
+void tst_brkm(int ttype, void (*func)(void), char *arg_fmt, ...)
+{
+ char tmesg[USERMESG];
+
+#if DEBUG
+ printf("IN tst_brkm\n"); fflush(stdout);
+ fflush(stdout);
+#endif
+
+ EXPAND_VAR_ARGS(tmesg, arg_fmt, USERMESG);
+
+ tst_brk(ttype, NULL, func, "%s", tmesg);
+}
+
+
+/*
+ * tst_require_root() - Test for root permissions and abort if not.
+ */
+void tst_require_root(void (*func)(void))
+{
+ if (geteuid() != 0)
+ tst_brkm(TCONF, func, "Test needs to be run as root");
+}
+
+
+/*
+ * cat_file() - Print the contents of a file to standard out.
+ */
+static void cat_file(char *filename)
+{
+ FILE *fp;
+ int b_read, b_written;
+ char buffer[BUFSIZ];
+
+#if DEBUG
+ printf("IN cat_file\n"); fflush(stdout);
+#endif
+
+ if ((fp = fopen(filename, "r")) == NULL) {
+ sprintf(Warn_mesg,
+ "tst_res(): fopen(%s, \"r\") failed; errno = %d: %s",
+ filename, errno, strerror(errno));
+ tst_print(TCID, 0, TWARN, Warn_mesg);
+ return;
+ }
+
+ errno = 0;
+
+ while ((b_read = fread(buffer, 1, BUFSIZ, fp)) != 0) {
+ if ((b_written = fwrite(buffer, 1, b_read, T_out)) != b_read) {
+ sprintf(Warn_mesg,
+ "tst_res(): While trying to cat \"%s\", "
+ "fwrite() wrote only %d of %d bytes",
+ filename, b_written, b_read);
+ tst_print(TCID, 0, TWARN, Warn_mesg);
+ break;
+ }
+ }
+
+ if (!feof(fp)) {
+ sprintf(Warn_mesg,
+ "tst_res(): While trying to cat \"%s\", fread() "
+ "failed, errno = %d: %s",
+ filename, errno, strerror(errno));
+ tst_print(TCID, 0, TWARN, Warn_mesg);
+ }
+
+ if (fclose(fp) != 0) {
+ sprintf(Warn_mesg,
+ "tst_res(): While trying to cat \"%s\", fclose() "
+ "failed, errno = %d: %s",
+ filename, errno, strerror(errno));
+ tst_print(TCID, 0, TWARN, Warn_mesg);
+ }
+}
+
+
+#ifdef UNIT_TEST
+/****************************************************************************
+ * Unit test code: Takes input from stdin and can make the following
+ * calls: tst_res(), tst_resm(), tst_brk(), tst_brkm(),
+ * tst_flush_buf(), tst_exit().
+ ****************************************************************************/
+int TST_TOTAL = 10;
+char *TCID = "TESTTCID";
+
+#define RES "tst_res.c UNIT TEST message; ttype = %d; contents of \"%s\":"
+#define RESM "tst_res.c UNIT TEST message; ttype = %d"
+
+int main(void)
+{
+ int ttype;
+ char chr;
+ char fname[MAXMESG];
+
+ printf("UNIT TEST of tst_res.c. Options for ttype:\n\
+ -1 : call tst_exit()\n\
+ -2 : call tst_flush()\n\
+ -3 : call tst_brk()\n\
+ -4 : call tst_res()\n\
+ %2i : call tst_res(TPASS, ...)\n\
+ %2i : call tst_res(TFAIL, ...)\n\
+ %2i : call tst_res(TBROK, ...)\n\
+ %2i : call tst_res(TWARN, ...)\n\
+ %2i : call tst_res(TRETR, ...)\n\
+ %2i : call tst_res(TINFO, ...)\n\
+ %2i : call tst_res(TCONF, ...)\n\n",
+ TPASS, TFAIL, TBROK, TWARN, TRETR, TINFO, TCONF);
+
+ while (1) {
+ printf("Enter ttype (-5,-4,-3,-2,-1,%i,%i,%i,%i,%i,%i,%i): ",
+ TPASS, TFAIL, TBROK, TWARN, TRETR, TINFO, TCONF);
+ scanf("%d%c", &ttype, &chr);
+
+ switch (ttype) {
+ case -1:
+ tst_exit();
+ break;
+
+ case -2:
+ tst_flush();
+ break;
+
+ case -3:
+ printf("Enter the current type (%i=FAIL, %i=BROK, %i=RETR, %i=CONF): ",
+ TFAIL, TBROK, TRETR, TCONF);
+ scanf("%d%c", &ttype, &chr);
+ printf("Enter file name (<cr> for none): ");
+ gets(fname);
+ if (strcmp(fname, "") == 0)
+ tst_brkm(ttype, tst_exit, RESM, ttype);
+ else
+ tst_brk(ttype, fname, tst_exit, RES, ttype, fname);
+ break;
+
+ case -4:
+ printf("Enter the current type (%i,%i,%i,%i,%i,%i,%i): ",
+ TPASS, TFAIL, TBROK, TWARN, TRETR, TINFO, TCONF);
+ scanf("%d%c", &ttype, &chr);
+ default:
+ printf("Enter file name (<cr> for none): ");
+ gets(fname);
+
+ if (strcmp(fname, "") == 0)
+ tst_resm(ttype, RESM, ttype);
+ else
+ tst_res(ttype, fname, RES, ttype, fname);
+ break;
+ }
+
+ }
+}
+
+#endif /* UNIT_TEST */
diff --git a/ltp_framework/lib/tst_sig.c b/ltp_framework/lib/tst_sig.c
new file mode 100644
index 0000000..53181bf
--- /dev/null
+++ b/ltp_framework/lib/tst_sig.c
@@ -0,0 +1,271 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+
+/* $Id: tst_sig.c,v 1.13 2009/08/28 09:29:01 vapier Exp $ */
+
+/*****************************************************************************
+ OS Testing - Silicon Graphics, Inc.
+
+ FUNCTION IDENTIFIER : tst_sig Set up for unexpected signals.
+
+ AUTHOR : David D. Fenner
+
+ CO-PILOT : Bill Roske
+
+ DATE STARTED : 06/06/90
+
+ This module may be linked with c-modules requiring unexpected
+ signal handling. The parameters to tst_sig are as follows:
+
+ fork_flag - set to FORK or NOFORK depending upon whether the
+ calling program executes a fork() system call. It
+ is normally the case that the calling program treats
+ SIGCLD as an expected signal if fork() is being used.
+
+ handler - a pointer to the unexpected signal handler to
+ be executed after an unexpected signal has been
+ detected. If handler is set to DEF_HANDLER, a
+ default handler is used. This routine should be
+ declared as function returning an int.
+
+ cleanup - a pointer to a cleanup routine to be executed
+ by the unexpected signal handler before tst_exit is
+ called. This parameter is set to NULL if no cleanup
+ routine is required. An external variable, T_cleanup
+ is set so that other user-defined handlers have
+ access to the cleanup routine. This routine should be
+ declared as returning type void.
+
+***************************************************************************/
+
+#include <errno.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+#include "test.h"
+
+#define MAXMESG 150 /* size of mesg string sent to tst_res */
+
+void (*T_cleanup) (); /* pointer to cleanup function */
+
+/****************************************************************************
+ * STD_COPIES is defined in parse_opts.c but is externed here in order to
+ * test whether SIGCHILD should be ignored or not.
+ ***************************************************************************/
+extern int STD_COPIES;
+
+static void def_handler(); /* default signal handler */
+static void (*tst_setup_signal(int, void (*)(int))) (int);
+
+/****************************************************************************
+ * tst_sig() : set-up to catch unexpected signals. fork_flag is set to NOFORK
+ * if SIGCLD is to be an "unexpected signal", otherwise it is set to
+ * FORK. cleanup points to a cleanup routine to be executed before
+ * tst_exit is called (cleanup is set to NULL if no cleanup is desired).
+ * handler is a pointer to the signal handling routine (if handler is
+ * set to NULL, a default handler is used).
+ ***************************************************************************/
+
+void tst_sig(int fork_flag, void (*handler) (), void (*cleanup) ())
+{
+ int sig;
+#ifdef _SC_SIGRT_MIN
+ long sigrtmin, sigrtmax;
+#endif
+
+ /*
+ * save T_cleanup and handler function pointers
+ */
+ T_cleanup = cleanup; /* used by default handler */
+
+ if (handler == DEF_HANDLER) {
+ /* use default handler */
+ handler = def_handler;
+ }
+#ifdef _SC_SIGRT_MIN
+ sigrtmin = sysconf(_SC_SIGRT_MIN);
+ sigrtmax = sysconf(_SC_SIGRT_MAX);
+#endif
+
+ /*
+ * now loop through all signals and set the handlers
+ */
+
+ for (sig = 1; sig < NSIG; sig++) {
+ /*
+ * SIGKILL is never unexpected.
+ * SIGCLD is only unexpected when
+ * no forking is being done.
+ * SIGINFO is used for file quotas and should be expected
+ */
+
+#ifdef _SC_SIGRT_MIN
+ if (sig >= sigrtmin && sig <= sigrtmax)
+ continue;
+#endif
+
+ switch (sig) {
+ case SIGKILL:
+ case SIGSTOP:
+ case SIGCONT:
+#if !defined(_SC_SIGRT_MIN) && defined(__SIGRTMIN) && defined(__SIGRTMAX)
+ /* Ignore all real-time signals */
+ case __SIGRTMIN:
+ case __SIGRTMIN + 1:
+ case __SIGRTMIN + 2:
+ case __SIGRTMIN + 3:
+ case __SIGRTMIN + 4:
+ case __SIGRTMIN + 5:
+ case __SIGRTMIN + 6:
+ case __SIGRTMIN + 7:
+ case __SIGRTMIN + 8:
+ case __SIGRTMIN + 9:
+ case __SIGRTMIN + 10:
+ case __SIGRTMIN + 11:
+ case __SIGRTMIN + 12:
+ case __SIGRTMIN + 13:
+ case __SIGRTMIN + 14:
+ case __SIGRTMIN + 15:
+/* __SIGRTMIN is 37 on HPPA rather than 32 *
+ * as on i386, etc. */
+#if !defined(__hppa__)
+ case __SIGRTMAX - 15:
+ case __SIGRTMAX - 14:
+ case __SIGRTMAX - 13:
+ case __SIGRTMAX - 12:
+ case __SIGRTMAX - 11:
+#endif
+ case __SIGRTMAX - 10:
+ case __SIGRTMAX - 9:
+ case __SIGRTMAX - 8:
+ case __SIGRTMAX - 7:
+ case __SIGRTMAX - 6:
+ case __SIGRTMAX - 5:
+ case __SIGRTMAX - 4:
+ case __SIGRTMAX - 3:
+ case __SIGRTMAX - 2:
+ case __SIGRTMAX - 1:
+ case __SIGRTMAX:
+#endif
+#ifdef CRAY
+ case SIGINFO:
+ case SIGRECOVERY: /* allow chkpnt/restart */
+#endif /* CRAY */
+
+#ifdef SIGSWAP
+ case SIGSWAP:
+#endif /* SIGSWAP */
+
+#ifdef SIGCKPT
+ case SIGCKPT:
+#endif
+#ifdef SIGRESTART
+ case SIGRESTART:
+#endif
+ /*
+ * pthread-private signals SIGPTINTR and SIGPTRESCHED.
+ * Setting a handler for these signals is disallowed when
+ * the binary is linked against libpthread.
+ */
+#ifdef SIGPTINTR
+ case SIGPTINTR:
+#endif /* SIGPTINTR */
+#ifdef SIGPTRESCHED
+ case SIGPTRESCHED:
+#endif /* SIGPTRESCHED */
+#ifdef _SIGRESERVE
+ case _SIGRESERVE:
+#endif
+#ifdef _SIGDIL
+ case _SIGDIL:
+#endif
+#ifdef _SIGCANCEL
+ case _SIGCANCEL:
+#endif
+#ifdef _SIGGFAULT
+ case _SIGGFAULT:
+#endif
+ break;
+
+ case SIGCLD:
+ if (fork_flag == FORK || STD_COPIES > 1)
+ continue;
+
+ default:
+ if (tst_setup_signal(sig, handler) == SIG_ERR)
+ tst_resm(TWARN|TERRNO,
+ "signal failed for signal %d", sig);
+ break;
+ }
+#ifdef __sgi
+ /* On irix (07/96), signal() fails when signo is 33 or higher */
+ if (sig + 1 >= 33)
+ break;
+#endif /* __sgi */
+
+ } /* endfor */
+}
+
+/****************************************************************************
+ * def_handler() : default signal handler that is invoked when
+ * an unexpected signal is caught.
+ ***************************************************************************/
+
+static void def_handler(int sig)
+{
+ /*
+ * Break remaining test cases, do any cleanup, then exit
+ */
+ tst_brkm(TBROK, T_cleanup,
+ "unexpected signal %d received (pid = %d).", sig, getpid());
+}
+
+/*
+ * tst_setup_signal - A function like signal(), but we have
+ * control over its personality.
+ */
+static void (*tst_setup_signal(int sig, void (*handler) (int))) (int)
+{
+ struct sigaction my_act, old_act;
+ int ret;
+
+ my_act.sa_handler = handler;
+ my_act.sa_flags = SA_RESTART;
+ sigemptyset(&my_act.sa_mask);
+
+ ret = sigaction(sig, &my_act, &old_act);
+
+ if (ret == 0)
+ return old_act.sa_handler;
+ else
+ return SIG_ERR;
+} \ No newline at end of file
diff --git a/ltp_framework/lib/tst_tmpdir.c b/ltp_framework/lib/tst_tmpdir.c
new file mode 100644
index 0000000..d112e3e
--- /dev/null
+++ b/ltp_framework/lib/tst_tmpdir.c
@@ -0,0 +1,405 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+
+/* $Id: tst_tmpdir.c,v 1.14 2009/07/20 10:59:32 vapier Exp $ */
+
+/**********************************************************
+ *
+ * OS Testing - Silicon Graphics, Inc.
+ *
+ * FUNCTION NAME : tst_tmpdir, tst_rmdir
+ *
+ * FUNCTION TITLE : Create/remove a testing temp dir
+ *
+ * SYNOPSIS:
+ * void tst_tmpdir();
+ * void tst_rmdir();
+ *
+ * AUTHOR : Dave Fenner
+ *
+ * INITIAL RELEASE : UNICOS 8.0
+ *
+ * DESCRIPTION
+ * tst_tmpdir() is used to create a unique, temporary testing
+ * directory, and make it the current working directory.
+ * tst_rmdir() is used to remove the directory created by
+ * tst_tmpdir().
+ *
+ * Setting the env variable "TDIRECTORY" will override the creation
+ * of a new temp dir. The directory specified by TDIRECTORY will
+ * be used as the temporary directory, and no removal will be done
+ * in tst_rmdir().
+ *
+ * RETURN VALUE
+ * Neither tst_tmpdir() or tst_rmdir() has a return value.
+ *
+ *#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**/
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <assert.h>
+#include <errno.h>
+#include <libgen.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include "test.h"
+#include "rmobj.h"
+
+/*
+ * Define some useful macros.
+ */
+#define DIR_MODE (S_IRWXU|S_IRWXG|S_IRWXO)
+
+#ifndef PATH_MAX
+#ifdef MAXPATHLEN
+#define PATH_MAX MAXPATHLEN
+#else
+#define PATH_MAX 1024
+#endif
+#endif
+
+/*
+ * Define function prototypes.
+ */
+static void tmpdir_cleanup(void);
+
+/*
+ * Define global variables.
+ */
+extern char *TCID; /* defined/initialized in main() */
+static char *TESTDIR = NULL; /* the directory created */
+
+/*
+ * Return a copy of the test temp directory as seen by LTP. This is for
+ * path-oriented tests like chroot, etc, that may munge the path a bit.
+ *
+ * FREE VARIABLE AFTER USE IF IT IS REUSED!
+ */
+char *
+get_tst_tmpdir(void)
+{
+ /* Smack the user for calling things out of order. */
+ if (TESTDIR == NULL)
+ tst_brkm(TBROK, NULL, "you must call tst_tmpdir() first");
+ return strdup(TESTDIR);
+}
+
+/*
+ * tst_tmpdir() - Create a unique temporary directory and chdir() to it.
+ * It expects the caller to have defined/initialized the
+ * TCID/TST_TOTAL global variables. The TESTDIR global
+ * variable will be set to the directory that gets used
+ * as the testing directory.
+ *
+ * NOTE: This function must be called BEFORE any activity
+ * that would require CLEANUP. If tst_tmpdir() fails, it
+ * cleans up afer itself and calls tst_exit() (i.e. does
+ * not return).
+ */
+void tst_tmpdir(void)
+{
+ char template[PATH_MAX];
+ int no_cleanup = 0; /* !0 means TDIRECTORY env var was set */
+ char *env_tmpdir; /* temporary storage for TMPDIR env var */
+ /* This is an AWFUL hack to figure out if mkdtemp() is available */
+#if defined(__GLIBC_PREREQ) && __GLIBC_PREREQ(2,2)
+#define HAVE_MKDTEMP
+#endif
+
+ /*
+ * If the TDIRECTORY env variable is not set, a temp dir will be
+ * created.
+ */
+ if ((TESTDIR = getenv(TDIRECTORY)) != NULL) {
+ /*
+ * The TDIRECTORY env. variable is set, so no temp dir is created.
+ */
+ if (mkdir(TESTDIR, DIR_MODE) == -1 && errno != EEXIST) {
+ tst_brkm(TBROK, NULL, "mkdir(%s, %o) failed",
+ TESTDIR, DIR_MODE);
+ }
+ /*
+ * Try to create the directory if it does not exist already;
+ * user might forget to create one before exporting TDIRECTORY.
+ */
+ no_cleanup++;
+#if UNIT_TEST
+ printf("TDIRECTORY env var is set\n");
+#endif
+ } else {
+ /*
+ * Create a template for the temporary directory. Use the
+ * environment variable TMPDIR if it is available, otherwise
+ * use our default TEMPDIR.
+ */
+ if ((env_tmpdir = getenv("TMPDIR"))) {
+ snprintf(template, PATH_MAX, "%s/%.3sXXXXXX", env_tmpdir, TCID);
+ } else {
+ snprintf(template, PATH_MAX, "%s/%.3sXXXXXX", TEMPDIR, TCID);
+ }
+
+#ifdef HAVE_MKDTEMP
+ /* Make the temporary directory in one shot using mkdtemp. */
+ if (mkdtemp(template) == NULL)
+ tst_brkm(TBROK|TERRNO, tmpdir_cleanup,
+ "%s: mkdtemp(%s) failed", __func__, template);
+ if ((TESTDIR = strdup(template)) == NULL) {
+ tst_brkm(TBROK|TERRNO, tmpdir_cleanup,
+ "%s: strdup(%s) failed", __func__, template);
+ }
+#else
+ int tfd;
+
+ /* Make the template name, then the directory */
+ if ((tfd = mkstemp(template)) == -1)
+ tst_brkm(TBROK|TERRNO, tmpdir_cleanup,
+ "%s: mkstemp(%s) failed", __func__, template);
+ if (close(tfd) == -1) {
+ tst_brkm(TBROK|TERRNO, tmpdir_cleanup,
+ "%s: close() failed", __func__);
+ }
+ if (unlink(template) == -1) {
+ tst_brkm(TBROK|TERRNO, tmpdir_cleanup,
+ "%s: unlink(%s) failed", __func__, template);
+ }
+ if ((TESTDIR = strdup(template)) == NULL) {
+ tst_brkm(TBROK|TERRNO, tmpdir_cleanup,
+ "%s: strdup(%s) failed", __func__, template);
+ }
+ if (mkdir(TESTDIR, DIR_MODE)) {
+ /*
+ * If we start failing with EEXIST, wrap this section in
+ * a loop so we can try again.
+ *
+ * XXX (garrcoop): why? Hacking around broken
+ * filesystems should not be done.
+ */
+ tst_brkm(TBROK|TERRNO, tmpdir_cleanup,
+ "%s: mkdir(%s, %#o) failed",
+ __func__, TESTDIR, DIR_MODE);
+ }
+#endif
+
+ if (chown(TESTDIR, -1, getgid()) == -1)
+ tst_brkm(TBROK|TERRNO, tmpdir_cleanup,
+ "chown(%s, -1, %d) failed", TESTDIR, getgid());
+ if (chmod(TESTDIR, DIR_MODE) == -1)
+ tst_brkm(TBROK|TERRNO, tmpdir_cleanup,
+ "chmod(%s, %#o) failed", TESTDIR, DIR_MODE);
+ }
+
+#if UNIT_TEST
+ printf("TESTDIR = %s\n", TESTDIR);
+#endif
+
+ /*
+ * Change to the temporary directory. If the chdir() fails, issue
+ * TBROK messages for all test cases, attempt to remove the
+ * directory (if it was created), and exit. If the removal also
+ * fails, also issue a TWARN message.
+ */
+ if (chdir(TESTDIR) == -1) {
+ tst_brkm(TBROK|TERRNO, NULL, "%s: chdir(%s) failed",
+ __func__, TESTDIR);
+
+ /* Try to remove the directory */
+ if (!no_cleanup && rmdir(TESTDIR) == -1) {
+ tst_resm(TWARN|TERRNO, "%s: rmdir(%s) failed",
+ __func__, TESTDIR);
+ }
+
+ tmpdir_cleanup();
+ }
+
+#if UNIT_TEST
+ printf("CWD is %s\n", getcwd(NULL, PATH_MAX));
+#endif
+
+} /* tst_tmpdir() */
+
+
+/*
+ *
+ * tst_rmdir() - Recursively remove the temporary directory created by
+ * tst_tmpdir(). This function is intended ONLY as a
+ * companion to tst_tmpdir(). If the TDIRECTORY
+ * environment variable is set, no cleanup will be
+ * attempted.
+ */
+void tst_rmdir(void)
+{
+ struct stat buf1;
+ struct stat buf2;
+ char current_dir[PATH_MAX];
+ char *errmsg;
+ char *parent_dir;
+ char *tdirectory;
+
+ /*
+ * If the TDIRECTORY env variable is set, this indicates that no
+ * temp dir was created by tst_tmpdir(). Thus no cleanup will be
+ * necessary.
+ */
+ if ((tdirectory = getenv(TDIRECTORY)) != NULL) {
+#if UNIT_TEST
+ printf("\"TDIRECORY\" env variable is set; no cleanup was performed\n");
+#endif
+ return;
+ }
+
+ /*
+ * Check that TESTDIR is not NULL.
+ */
+ if (TESTDIR == NULL) {
+ tst_resm(TWARN,
+ "%s: TESTDIR was NULL; no removal attempted", __func__);
+ return;
+ }
+
+ if ((parent_dir = malloc(PATH_MAX)) == NULL) {
+ /* Make sure that we exit quickly and noisily. */
+ tst_brkm(TBROK|TERRNO, NULL,
+ "%s: malloc(%d) failed", __func__, PATH_MAX);
+ }
+
+ /*
+ * Check that the value of TESTDIR is not "*" or "/". These could
+ * have disastrous effects in a test run by root.
+ */
+ /* XXX: a temp directory that's '/' seems stupid and dangerous anyways. */
+ if (stat(TESTDIR, &buf1) == 0 && stat("/", &buf2) == 0 &&
+ buf1.st_ino == buf2.st_ino) {
+ tst_resm(TWARN, "%s: will not remove /", __func__);
+ return;
+ }
+
+ /*
+ * XXX: this just reeks of bad programming; all shell characters should
+ * be escaped in invocations of rm(1)/rmdir(1).
+ */
+ if (strchr(TESTDIR, '*') != NULL) {
+ tst_resm(TWARN, "%s: will not remove *", __func__);
+ return;
+ }
+
+ /*
+ * Get the directory name of TESTDIR. If TESTDIR is a relative path,
+ * get full path.
+ */
+ if (TESTDIR[0] != '/') {
+ if (getcwd(current_dir, PATH_MAX) == NULL)
+ strncpy(parent_dir, TESTDIR, sizeof(parent_dir));
+ else
+ sprintf(parent_dir, "%s/%s", current_dir, TESTDIR);
+ } else {
+ strcpy(parent_dir, TESTDIR);
+ }
+ if ((parent_dir = dirname(parent_dir)) == NULL) {
+ tst_resm(TWARN|TERRNO, "%s: dirname failed", __func__);
+ return;
+ }
+
+ /*
+ * Change directory to parent_dir (The dir above TESTDIR).
+ */
+ if (chdir(parent_dir) != 0) {
+ tst_resm(TWARN|TERRNO,
+ "%s: chdir(%s) failed\nAttempting to remove temp dir "
+ "anyway",
+ __func__, parent_dir);
+ }
+
+ /*
+ * Attempt to remove the "TESTDIR" directory, using rmobj().
+ */
+ if (rmobj(TESTDIR, &errmsg) == -1)
+ tst_resm(TWARN, "%s: rmobj(%s) failed: %s",
+ __func__, TESTDIR, errmsg);
+
+} /* tst_rmdir() */
+
+
+/*
+ * tmpdir_cleanup(void) - This function is used when tst_tmpdir()
+ * encounters an error, and must cleanup and exit.
+ * It prints a warning message via tst_resm(), and
+ * then calls tst_exit().
+ */
+static void
+tmpdir_cleanup(void)
+{
+ tst_brkm(TWARN, NULL,
+ "%s: no user cleanup function called before exiting", __func__);
+}
+
+
+#ifdef UNIT_TEST
+/****************************************************************************
+ * Unit test code: Takes input from stdin and can make the following
+ * calls: tst_tmpdir(), tst_rmdir().
+ ****************************************************************************/
+extern int TST_TOTAL; /* defined/initialized in main() */
+
+int TST_TOTAL = 10;
+char *TCID = "TESTTCID";
+
+main()
+{
+ int option;
+ char *chrptr;
+
+ printf("UNIT TEST of tst_tmpdir.c. Options to try:\n\
+ -1 : call tst_exit()\n\
+ 0 : call tst_tmpdir()\n\
+ 1 : call tst_rmdir()\n\n");
+
+ while (1) {
+ printf("Enter options (-1, 0, 1): ");
+ (void)scanf("%d%c", &option, &chrptr);
+
+ switch (option) {
+ case -1:
+ tst_exit();
+ break;
+
+ case 0:
+ tst_tmpdir();
+ break;
+
+ case 1:
+ tst_rmdir();
+ break;
+ } /* switch() */
+ } /* while () */
+}
+#endif /* UNIT_TEST */
diff --git a/ltp_framework/lib/write_log.c b/ltp_framework/lib/write_log.c
new file mode 100644
index 0000000..ef560e7
--- /dev/null
+++ b/ltp_framework/lib/write_log.c
@@ -0,0 +1,503 @@
+/*
+ * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it would be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ *
+ * Further, this software is distributed without any warranty that it is
+ * free of the rightful claim of any third person regarding infringement
+ * or the like. Any license provided herein, whether implied or
+ * otherwise, applies only to this software file. Patent licenses, if
+ * any, provided herein do not apply to combinations of this program with
+ * other software, or any other product whatsoever.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write the Free Software Foundation, Inc., 59
+ * Temple Place - Suite 330, Boston MA 02111-1307, USA.
+ *
+ * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
+ * Mountain View, CA 94043, or:
+ *
+ * http://www.sgi.com
+ *
+ * For further information regarding this notice, see:
+ *
+ * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
+ */
+/*
+ * This module contains code for logging writes to files, and for
+ * perusing the resultant logfile. The main intent of all this is
+ * to provide a 'write history' of a file which can be examined to
+ * judge the state of a file (ie. whether it is corrupted or not) based
+ * on the write activity.
+ *
+ * The main abstractions available to the user are the wlog_file, and
+ * the wlog_rec. A wlog_file is a handle encapsulating a write logfile.
+ * It is initialized with the wlog_open() function. This handle is
+ * then passed to the various wlog_xxx() functions to provide transparent
+ * access to the write logfile.
+ *
+ * The wlog_rec datatype is a structure which contains all the information
+ * about a file write. Examples include the file name, offset, length,
+ * pattern, etc. In addition there is a bit which is cleared/set based
+ * on whether or not the write has been confirmed as complete. This
+ * allows the write logfile to contain information on writes which have
+ * been initiated, but not yet completed (as in async io).
+ *
+ * There is also a function to scan a write logfile in reverse order.
+ *
+ * NOTE: For target file analysis based on a write logfile, the
+ * assumption is made that the file being written to is
+ * locked from simultaneous access, so that the order of
+ * write completion is predictable. This is an issue when
+ * more than 1 process is trying to write data to the same
+ * target file simultaneously.
+ *
+ * The history file created is a collection of variable length records
+ * described by scruct wlog_rec_disk in write_log.h. See that module for
+ * the layout of the data on disk.
+ */
+
+#include <stdio.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include "write_log.h"
+
+#ifndef BSIZE
+#ifdef DEV_BSIZE
+#define BSIZE DEV_BSIZE
+#else
+#define BSIZE BBSIZE
+#endif
+#endif
+
+#ifndef PATH_MAX
+#define PATH_MAX 255
+/*#define PATH_MAX pathconf("/", _PC_PATH_MAX)*/
+#endif
+
+char Wlog_Error_String[256];
+
+#if __STDC__
+static int wlog_rec_pack(struct wlog_rec *wrec, char *buf, int flag);
+static int wlog_rec_unpack(struct wlog_rec *wrec, char *buf);
+#else
+static int wlog_rec_pack();
+static int wlog_rec_unpack();
+#endif
+
+/*
+ * Initialize a write logfile. wfile is a wlog_file structure that has
+ * the w_file field filled in. The rest of the information in the
+ * structure is initialized by the routine.
+ *
+ * The trunc flag is used to indicate whether or not the logfile should
+ * be truncated if it currently exists. If it is non-zero, the file will
+ * be truncated, otherwise it will be appended to.
+ *
+ * The mode argument is the [absolute] mode which the file will be
+ * given if it does not exist. This mode is not affected by your process
+ * umask.
+ */
+
+int
+wlog_open(wfile, trunc, mode)
+struct wlog_file *wfile;
+int trunc;
+int mode;
+{
+ int omask, oflags;
+
+ if (trunc)
+ trunc = O_TRUNC;
+
+ omask = umask(0);
+
+ /*
+ * Open 1 file descriptor as O_APPEND
+ */
+
+ oflags = O_WRONLY | O_APPEND | O_CREAT | trunc;
+ wfile->w_afd =
+ open(wfile->w_file, oflags, mode);
+ umask(omask);
+
+ if (wfile->w_afd == -1) {
+ sprintf(Wlog_Error_String,
+ "Could not open write_log - open(%s, %#o, %#o) failed: %s\n",
+ wfile->w_file, oflags, mode, strerror(errno));
+ return -1;
+ }
+
+ /*
+ * Open the next fd as a random access descriptor
+ */
+
+ oflags = O_RDWR;
+ if ((wfile->w_rfd = open(wfile->w_file, oflags)) == -1) {
+ sprintf(Wlog_Error_String,
+ "Could not open write log - open(%s, %#o) failed: %s\n",
+ wfile->w_file, oflags, strerror(errno));
+ close(wfile->w_afd);
+ wfile->w_afd = -1;
+ return -1;
+ }
+
+ return 0;
+}
+
+/*
+ * Release all resources associated with a wlog_file structure allocated
+ * with the wlog_open() call.
+ */
+
+int
+wlog_close(wfile)
+struct wlog_file *wfile;
+{
+ close(wfile->w_afd);
+ close(wfile->w_rfd);
+ return 0;
+}
+
+/*
+ * Write a wlog_rec structure to a write logfile. Offset is used to
+ * control where the record will be written. If offset is < 0, the
+ * record will be appended to the end of the logfile. Otherwise, the
+ * record which exists at the indicated offset will be overlayed. This
+ * is so that we can record writes which are outstanding (with the w_done
+ * bit in wrec cleared), but not completed, and then later update the
+ * logfile when the write request completes (as with async io). When
+ * offset is >= 0, only the fixed length portion of the record is
+ * rewritten. See text in write_log.h for details on the format of an
+ * on-disk record.
+ *
+ * The return value of the function is the byte offset in the logfile
+ * where the record begins.
+ *
+ * Note: It is the callers responsibility to make sure that the offset
+ * parameter 'points' to a valid record location when a record is to be
+ * overlayed. This is guarenteed by saving the return value of a previous
+ * call to wlog_record_write() which wrote the record to be overlayed.
+ *
+ * Note2: The on-disk version of the wlog_rec is MUCH different than
+ * the user version. Don't expect to od the logfile and see data formatted
+ * as it is in the wlog_rec structure. Considerable data packing takes
+ * place before the record is written.
+ */
+
+int
+wlog_record_write(wfile, wrec, offset)
+struct wlog_file *wfile;
+struct wlog_rec *wrec;
+long offset;
+{
+ int reclen;
+ char wbuf[WLOG_REC_MAX_SIZE + 2];
+
+ /*
+ * If offset is -1, we append the record at the end of file
+ *
+ * Otherwise, we overlay wrec at the file offset indicated and assume
+ * that the caller passed us the correct offset. We do not record the
+ * fname in this case.
+ */
+
+ reclen = wlog_rec_pack(wrec, wbuf, (offset < 0));
+
+ if (offset < 0) {
+ /*
+ * Since we're writing a complete new record, we must also tack
+ * its length onto the end so that wlog_scan_backward() will work.
+ * Length is asumed to fit into 2 bytes.
+ */
+
+ wbuf[reclen] = reclen / 256;
+ wbuf[reclen+1] = reclen % 256;
+ reclen += 2;
+
+ if (write(wfile->w_afd, wbuf, reclen) == -1) {
+ sprintf(Wlog_Error_String,
+ "Could not write log - write(%s, %s, %d) failed: %s\n",
+ wfile->w_file, wbuf, reclen, strerror(errno));
+ return -1;
+ } else {
+ offset = lseek(wfile->w_afd, 0, SEEK_CUR) - reclen;
+ if (offset == -1) {
+ sprintf(Wlog_Error_String,
+ "Could not reposition file pointer - lseek(%s, 0, SEEK_CUR) failed: %s\n",
+ wfile->w_file, strerror(errno));
+ return -1;
+ }
+ }
+ } else {
+ if ((lseek(wfile->w_rfd, offset, SEEK_SET)) == -1) {
+ sprintf(Wlog_Error_String,
+ "Could not reposition file pointer - lseek(%s, %ld, SEEK_SET) failed: %s\n",
+ wfile->w_file, offset, strerror(errno));
+ return -1;
+ } else {
+ if ((write(wfile->w_rfd, wbuf, reclen)) == -1) {
+ sprintf(Wlog_Error_String,
+ "Could not write log - write(%s, %s, %d) failed: %s\n",
+ wfile->w_file, wbuf, reclen, strerror(errno));
+ return -1;
+ }
+ }
+ }
+
+ return offset;
+}
+
+/*
+ * Function to scan a logfile in reverse order. Wfile is a valid
+ * wlog_file structure initialized by wlog_open(). nrecs is the number
+ * of records to scan (all records are scanned if nrecs is 0). func is
+ * a user-supplied function to call for each record found. The function
+ * will be passed a single parameter - a wlog_rec structure .
+ */
+
+int
+wlog_scan_backward(wfile, nrecs, func, data)
+struct wlog_file *wfile;
+int nrecs;
+int (*func)();
+long data;
+{
+ int fd, leftover, nbytes, offset, recnum, reclen, rval;
+ char buf[BSIZE*32], *bufend, *cp, *bufstart;
+ char albuf[WLOG_REC_MAX_SIZE];
+ struct wlog_rec wrec;
+
+ fd = wfile->w_rfd;
+
+ /*
+ * Move to EOF. offset will always hold the current file offset
+ */
+
+ if ((lseek(fd, 0, SEEK_END)) == -1) {
+ sprintf(Wlog_Error_String,
+ "Could not reposition file pointer - lseek(%s, 0, SEEK_END) failed: %s\n",
+ wfile->w_file, strerror(errno));
+ return -1;
+ }
+ offset = lseek(fd, 0, SEEK_CUR);
+ if ((offset == -1)) {
+ sprintf(Wlog_Error_String,
+ "Could not reposition file pointer - lseek(%s, 0, SEEK_CUR) failed: %s\n",
+ wfile->w_file, strerror(errno));
+ return -1;
+ }
+
+ bufend = buf + sizeof(buf);
+ bufstart = buf;
+
+ recnum = 0;
+ leftover = 0;
+ while ((!nrecs || recnum < nrecs) && offset > 0) {
+ /*
+ * Check for beginning of file - if there aren't enough bytes
+ * remaining to fill buf, adjust bufstart.
+ */
+
+ if ((unsigned int)offset + leftover < sizeof(buf)) {
+ bufstart = bufend - (offset + leftover);
+ offset = 0;
+ } else {
+ offset -= sizeof(buf) - leftover;
+ }
+
+ /*
+ * Move to the proper file offset, and read into buf
+ */
+ if ((lseek(fd, offset, SEEK_SET)) ==-1) {
+ sprintf(Wlog_Error_String,
+ "Could not reposition file pointer - lseek(%s, %d, SEEK_SET) failed: %s\n",
+ wfile->w_file, offset, strerror(errno));
+ return -1;
+ }
+
+ nbytes = read(fd, bufstart, bufend - bufstart - leftover);
+
+ if (nbytes == -1) {
+ sprintf(Wlog_Error_String,
+ "Could not read history file at offset %d - read(%d, %p, %d) failed: %s\n",
+ offset, fd, bufstart,
+ (int)(bufend - bufstart - leftover), strerror(errno));
+ return -1;
+ }
+
+ cp = bufend;
+ leftover = 0;
+
+ while (cp >= bufstart) {
+
+ /*
+ * If cp-bufstart is not large enough to hold a piece
+ * of record length information, copy remainder to end
+ * of buf and continue reading the file.
+ */
+
+ if (cp - bufstart < 2) {
+ leftover = cp - bufstart;
+ memcpy(bufend - leftover, bufstart, leftover);
+ break;
+ }
+
+ /*
+ * Extract the record length. We must do it this way
+ * instead of casting cp to an int because cp might
+ * not be word aligned.
+ */
+
+ reclen = (*(cp-2) * 256) + *(cp -1);
+
+ /*
+ * If cp-bufstart isn't large enough to hold a
+ * complete record, plus the length information, copy
+ * the leftover bytes to the end of buf and continue
+ * reading.
+ */
+
+ if (cp - bufstart < reclen + 2) {
+ leftover = cp - bufstart;
+ memcpy(bufend - leftover, bufstart, leftover);
+ break;
+ }
+
+ /*
+ * Adjust cp to point at the start of the record.
+ * Copy the record into wbuf so that it is word
+ * aligned and pass the record to the user supplied
+ * function.
+ */
+
+ cp -= reclen + 2;
+ memcpy(albuf, cp, reclen);
+
+ wlog_rec_unpack(&wrec, albuf);
+
+ /*
+ * Call the user supplied function -
+ * stop if instructed to.
+ */
+
+ if ((rval = (*func)(&wrec, data)) == WLOG_STOP_SCAN) {
+ break;
+ }
+
+ recnum++;
+
+ if (nrecs && recnum >= nrecs)
+ break;
+ }
+ }
+
+ return 0;
+}
+
+/*
+ * The following 2 routines are used to pack and unpack the user
+ * visible wlog_rec structure to/from a character buffer which is
+ * stored or read from the write logfile. Any changes to either of
+ * these routines must be reflected in the other.
+ */
+
+static int
+wlog_rec_pack(wrec, buf, flag)
+struct wlog_rec *wrec;
+char *buf;
+int flag;
+{
+ char *file, *host, *pattern;
+ struct wlog_rec_disk *wrecd;
+
+ wrecd = (struct wlog_rec_disk *)buf;
+
+ wrecd->w_pid = (uint)wrec->w_pid;
+ wrecd->w_offset = (uint)wrec->w_offset;
+ wrecd->w_nbytes = (uint)wrec->w_nbytes;
+ wrecd->w_oflags = (uint)wrec->w_oflags;
+ wrecd->w_done = (uint)wrec->w_done;
+ wrecd->w_async = (uint)wrec->w_async;
+
+ wrecd->w_pathlen = (wrec->w_pathlen > 0) ? (uint)wrec->w_pathlen : 0;
+ wrecd->w_hostlen = (wrec->w_hostlen > 0) ? (uint)wrec->w_hostlen : 0;
+ wrecd->w_patternlen = (wrec->w_patternlen > 0) ? (uint)wrec->w_patternlen : 0;
+
+ /*
+ * If flag is true, we should also pack the variable length parts
+ * of the wlog_rec. By default, we only pack the fixed length
+ * parts.
+ */
+
+ if (flag) {
+ file = buf + sizeof(struct wlog_rec_disk);
+ host = file + wrecd->w_pathlen;
+ pattern = host + wrecd->w_hostlen;
+
+ if (wrecd->w_pathlen > 0)
+ memcpy(file, wrec->w_path, wrecd->w_pathlen);
+
+ if (wrecd->w_hostlen > 0)
+ memcpy(host, wrec->w_host, wrecd->w_hostlen);
+
+ if (wrecd->w_patternlen > 0)
+ memcpy(pattern, wrec->w_pattern, wrecd->w_patternlen);
+
+ return (sizeof(struct wlog_rec_disk) +
+ wrecd->w_pathlen + wrecd->w_hostlen + wrecd->w_patternlen);
+ } else {
+ return sizeof(struct wlog_rec_disk);
+ }
+}
+
+static int
+wlog_rec_unpack(wrec, buf)
+struct wlog_rec *wrec;
+char *buf;
+{
+ char *file, *host, *pattern;
+ struct wlog_rec_disk *wrecd;
+
+ memset((char *)wrec, 0x00, sizeof(struct wlog_rec));
+ wrecd = (struct wlog_rec_disk *)buf;
+
+ wrec->w_pid = wrecd->w_pid;
+ wrec->w_offset = wrecd->w_offset;
+ wrec->w_nbytes = wrecd->w_nbytes;
+ wrec->w_oflags = wrecd->w_oflags;
+ wrec->w_hostlen = wrecd->w_hostlen;
+ wrec->w_pathlen = wrecd->w_pathlen;
+ wrec->w_patternlen = wrecd->w_patternlen;
+ wrec->w_done = wrecd->w_done;
+ wrec->w_async = wrecd->w_async;
+
+ if (wrec->w_pathlen > 0) {
+ file = buf + sizeof(struct wlog_rec_disk);
+ memcpy(wrec->w_path, file, wrec->w_pathlen);
+ }
+
+ if (wrec->w_hostlen > 0) {
+ host = buf + sizeof(struct wlog_rec_disk) + wrec->w_pathlen;
+ memcpy(wrec->w_host, host, wrec->w_hostlen);
+ }
+
+ if (wrec->w_patternlen > 0) {
+ pattern = buf + sizeof(struct wlog_rec_disk) +
+ wrec->w_pathlen + wrec->w_hostlen;
+ memcpy(wrec->w_pattern, pattern, wrec->w_patternlen);
+ }
+
+ return 0;
+} \ No newline at end of file