ASM Long
Collection
Neural Long Context Assembly Transpilation
•
19 items
•
Updated
file
stringlengths 18
26
| data
stringlengths 4
1.03M
|
---|---|
the_stack_data/211081048.c | //array1.c
// arrays example
#include <stdio.h>
int a1 [] = {16, 2, 77, 40, 13};
int sum = 0;
int n;
int main ()
{
for (n=0 ; n<5 ; n++ )
{
sum += a1[n];
}
printf("%d \n", sum);
return 0;
}
|
the_stack_data/145452848.c | struct Base {
int type;
void *internal;
};
struct Something {
int data;
};
int main() {
struct Something something = {.data = 13};
struct Base base = {.type = 0, .internal = &something};
printf("%d\n", ((struct Something *)(base.internal))->data);
return 0;
}
|
the_stack_data/546887.c | #include <time.h>
char *ctime_r(const time_t *t, char *buf)
{
struct tm tm;
localtime_r(t, &tm);
return asctime_r(&tm, buf);
}
|
the_stack_data/46696.c | /*
* C Program to Input Few Numbers & Perform Merge Sort on them using Recursion
*/
#include <stdio.h>
void mergeSort(int [], int, int, int);
void partition(int [],int, int);
int main()
{
int list[50];
int i, size;
printf("Enter total number of elements:");
scanf("%d", &size);
printf("Enter the elements:\n");
for(i = 0; i < size; i++)
{
scanf("%d", &list[i]);
}
partition(list, 0, size - 1);
printf("After merge sort:\n");
for(i = 0;i < size; i++)
{
printf("%d ",list[i]);
}
return 0;
}
void partition(int list[],int low,int high)
{
int mid;
if(low < high)
{
mid = (low + high) / 2;
partition(list, low, mid);
partition(list, mid + 1, high);
mergeSort(list, low, mid, high);
}
}
void mergeSort(int list[],int low,int mid,int high)
{
int i, mi, k, lo, temp[50];
lo = low;
i = low;
mi = mid + 1;
while ((lo <= mid) && (mi <= high))
{
if (list[lo] <= list[mi])
{
temp[i] = list[lo];
lo++;
}
else
{
temp[i] = list[mi];
mi++;
}
i++;
}
if (lo > mid)
{
for (k = mi; k <= high; k++)
{
temp[i] = list[k];
i++;
}
}
else
{
for (k = lo; k <= mid; k++)
{
temp[i] = list[k];
i++;
}
}
for (k = low; k <= high; k++)
{
list[k] = temp[k];
}
}
/*
Enter total number of elements:5
Enter the elements:
5
45
15
35
75
After merge sort:
5 15 35 45 75
--------------------------------
Process exited after 17.42 seconds with return value 0
Press any key to continue . . .
*/
|
the_stack_data/100140965.c | #include <stdio.h>
int main(int argc, char **argv, char **envp)
{
char **p = envp;
do
{
printf("%s\n", *p);
}
while (*(++p));
return 0;
}
|
the_stack_data/126703273.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#define ULONG uint32_t
#define USHORT uint16_t
#define UCHAR uint8_t
ULONG isdata[1000000]; /* each bit defines one byte as: code=0, data=1 */
extern void dis_asm(ULONG off, ULONG val, char *stg);
int static inline le2int(unsigned char* buf)
{
int32_t res = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0];
return res;
}
int main(int argc, char **argv)
{
FILE *in, *out;
char *ptr, stg[256];
unsigned char buf[4];
ULONG pos, sz, val, loop;
int offset, offset1;
USHORT regid;
if(argc == 1 || strcmp(argv[1], "--help") == 0)
{ printf("Usage: arm_disass [input file]\n");
printf(" disassembles input file to 'disasm.txt'\n");
exit(-1);
}
in = fopen(argv[1], "rb");
if(in == NULL)
{ printf("Cannot open %s", argv[1]);
exit(-1);
}
out = fopen("disasm.txt", "w");
if(out == NULL) exit(-1);
fseek(in, 0, SEEK_END);
sz = ftell(in);
/* first loop only sets data/code tags */
for(loop=0; loop<2; loop++)
{
for(pos=0; pos<sz; pos+=4)
{
/* clear disassembler string start */
memset(stg, 0, 40);
/* read next code dword */
fseek(in, pos, SEEK_SET);
fread(buf, 1, 4, in);
val = le2int(buf);
/* check for data tag set: if 1 byte out of 4 is marked => assume data */
if((isdata[pos>>5] & (0xf << (pos & 31))) || (val & 0xffff0000) == 0)
{
sprintf(stg, "%6x: %08x", pos, val);
}
else
{
dis_asm(pos, val, stg);
/* check for instant mov operation */
if(memcmp(stg+17, "mov ", 4) == 0 && (ptr=strstr(stg, "0x")) != NULL)
{
regid = *(USHORT*)(stg+22);
sscanf(ptr+2, "%x", &offset);
if(ptr[-1] == '-')
offset = -offset;
}
else
/* check for add/sub operation */
if((ptr=strstr(stg, "0x")) != NULL
&& (memcmp(stg+17, "add ", 4) == 0 || memcmp(stg+17, "sub ", 4) == 0))
{
if(regid == *(USHORT*)(stg+22) && regid == *(USHORT*)(stg+26))
{
sscanf(ptr+2, "%x", &offset1);
if(ptr[-1] == '-')
offset1 = -offset1;
if(memcmp(stg+17, "add ", 4) == 0) offset += offset1;
else offset -= offset1;
/* add result to disassembler string */
sprintf(stg+strlen(stg), " <- 0x%x", offset);
}
else
regid = 0;
}
else
regid = 0;
/* check for const data */
if(memcmp(stg+26, "[pc, ", 5) == 0 && (ptr=strstr(stg, "0x")) != NULL)
{
sscanf(ptr+2, "%x", &offset);
if(ptr[-1] == '-')
offset = -offset;
/* add data tag */
isdata[(pos+offset+8)>>5] |= 1 << ((pos+offset+8) & 31);
/* add const data to disassembler string */
fseek(in, pos+offset+8, SEEK_SET);
fread(&buf, 1, 4, in);
offset = le2int(buf);
sprintf(stg+strlen(stg), " <- 0x%x", offset);
}
}
/* remove trailing spaces */
while(stg[strlen(stg)-1] == 32)
stg[strlen(stg)-1] = 0;
if(loop == 1)
fprintf(out, "%s\n", stg);
}
}
fclose(in);
return 0;
}
|
the_stack_data/92324907.c | #include <stdio.h>
int g(int n);
int main(void) {
int n = 100000;
printf("%d\n", g(n));
return 0;
}
int g(int n) {
if (n == 0) {
return 1;
}
else {
return g(n - 1);
}
}
|
the_stack_data/243894166.c | /*
* Run a set of tests, reporting results.
*
* Test suite driver that runs a set of tests implementing a subset of the
* Test Anything Protocol (TAP) and reports the results.
*
* Any bug reports, bug fixes, and improvements are very much welcome and
* should be sent to the e-mail address below. This program is part of C TAP
* Harness <https://www.eyrie.org/~eagle/software/c-tap-harness/>.
*
* Copyright 2000-2001, 2004, 2006-2018 Russ Allbery <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* SPDX-License-Identifier: MIT
*/
/*
* Usage:
*
* runtests [-hv] [-b <build-dir>] [-s <source-dir>] -l <test-list>
* runtests [-hv] [-b <build-dir>] [-s <source-dir>] <test> [<test> ...]
* runtests -o [-h] [-b <build-dir>] [-s <source-dir>] <test>
*
* In the first case, expects a list of executables located in the given file,
* one line per executable, possibly followed by a space-separated list of
* options. For each one, runs it as part of a test suite, reporting results.
* In the second case, use the same infrastructure, but run only the tests
* listed on the command line.
*
* Test output should start with a line containing the number of tests
* (numbered from 1 to this number), optionally preceded by "1..", although
* that line may be given anywhere in the output. Each additional line should
* be in the following format:
*
* ok <number>
* not ok <number>
* ok <number> # skip
* not ok <number> # todo
*
* where <number> is the number of the test. An optional comment is permitted
* after the number if preceded by whitespace. ok indicates success, not ok
* indicates failure. "# skip" and "# todo" are a special cases of a comment,
* and must start with exactly that formatting. They indicate the test was
* skipped for some reason (maybe because it doesn't apply to this platform)
* or is testing something known to currently fail. The text following either
* "# skip" or "# todo" and whitespace is the reason.
*
* As a special case, the first line of the output may be in the form:
*
* 1..0 # skip some reason
*
* which indicates that this entire test case should be skipped and gives a
* reason.
*
* Any other lines are ignored, although for compliance with the TAP protocol
* all lines other than the ones in the above format should be sent to
* standard error rather than standard output and start with #.
*
* This is a subset of TAP as documented in Test::Harness::TAP or
* TAP::Parser::Grammar, which comes with Perl.
*
* If the -o option is given, instead run a single test and display all of its
* output. This is intended for use with failing tests so that the person
* running the test suite can get more details about what failed.
*
* If built with the C preprocessor symbols C_TAP_SOURCE and C_TAP_BUILD
* defined, C TAP Harness will export those values in the environment so that
* tests can find the source and build directory and will look for tests under
* both directories. These paths can also be set with the -b and -s
* command-line options, which will override anything set at build time.
*
* If the -v option is given, or the C_TAP_VERBOSE environment variable is set,
* display the full output of each test as it runs rather than showing a
* summary of the results of each test.
*/
/* Required for fdopen(), getopt(), and putenv(). */
#if defined(__STRICT_ANSI__) || defined(PEDANTIC)
# ifndef _XOPEN_SOURCE
# define _XOPEN_SOURCE 500
# endif
#endif
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
/* sys/time.h must be included before sys/resource.h on some platforms. */
#include <sys/resource.h>
/* AIX 6.1 (and possibly later) doesn't have WCOREDUMP. */
#ifndef WCOREDUMP
# define WCOREDUMP(status) ((unsigned)(status) & 0x80)
#endif
/*
* POSIX requires that these be defined in <unistd.h>, but they're not always
* available. If one of them has been defined, all the rest almost certainly
* have.
*/
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
# define STDOUT_FILENO 1
# define STDERR_FILENO 2
#endif
/*
* Used for iterating through arrays. Returns the number of elements in the
* array (useful for a < upper bound in a for loop).
*/
#define ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
/*
* The source and build versions of the tests directory. This is used to set
* the C_TAP_SOURCE and C_TAP_BUILD environment variables (and the SOURCE and
* BUILD environment variables set for backward compatibility) and find test
* programs, if set. Normally, this should be set as part of the build
* process to the test subdirectories of $(abs_top_srcdir) and
* $(abs_top_builddir) respectively.
*/
#ifndef C_TAP_SOURCE
# define C_TAP_SOURCE NULL
#endif
#ifndef C_TAP_BUILD
# define C_TAP_BUILD NULL
#endif
/* Test status codes. */
enum test_status {
TEST_FAIL,
TEST_PASS,
TEST_SKIP,
TEST_INVALID
};
/* Really, just a boolean, but this is more self-documenting. */
enum test_verbose {
CONCISE = 0,
VERBOSE = 1
};
/* Indicates the state of our plan. */
enum plan_status {
PLAN_INIT, /* Nothing seen yet. */
PLAN_FIRST, /* Plan seen before any tests. */
PLAN_PENDING, /* Test seen and no plan yet. */
PLAN_FINAL /* Plan seen after some tests. */
};
/* Error exit statuses for test processes. */
#define CHILDERR_DUP 100 /* Couldn't redirect stderr or stdout. */
#define CHILDERR_EXEC 101 /* Couldn't exec child process. */
#define CHILDERR_STDIN 102 /* Couldn't open stdin file. */
#define CHILDERR_STDERR 103 /* Couldn't open stderr file. */
/* Structure to hold data for a set of tests. */
struct testset {
char *file; /* The file name of the test. */
char **command; /* The argv vector to run the command. */
enum plan_status plan; /* The status of our plan. */
unsigned long count; /* Expected count of tests. */
unsigned long current; /* The last seen test number. */
unsigned int length; /* The length of the last status message. */
unsigned long passed; /* Count of passing tests. */
unsigned long failed; /* Count of failing lists. */
unsigned long skipped; /* Count of skipped tests (passed). */
unsigned long allocated; /* The size of the results table. */
enum test_status *results; /* Table of results by test number. */
unsigned int aborted; /* Whether the set was aborted. */
unsigned int reported; /* Whether the results were reported. */
int status; /* The exit status of the test. */
unsigned int all_skipped; /* Whether all tests were skipped. */
char *reason; /* Why all tests were skipped. */
};
/* Structure to hold a linked list of test sets. */
struct testlist {
struct testset *ts;
struct testlist *next;
};
/*
* Usage message. Should be used as a printf format with four arguments: the
* path to runtests, given three times, and the usage_description. This is
* split into variables to satisfy the pedantic ISO C90 limit on strings.
*/
static const char usage_message[] = "\
Usage: %s [-hv] [-b <build-dir>] [-s <source-dir>] <test> ...\n\
%s [-hv] [-b <build-dir>] [-s <source-dir>] -l <test-list>\n\
%s -o [-h] [-b <build-dir>] [-s <source-dir>] <test>\n\
\n\
Options:\n\
-b <build-dir> Set the build directory to <build-dir>\n\
%s";
static const char usage_extra[] = "\
-l <list> Take the list of tests to run from <test-list>\n\
-o Run a single test rather than a list of tests\n\
-s <source-dir> Set the source directory to <source-dir>\n\
-v Show the full output of each test\n\
\n\
runtests normally runs each test listed on the command line. With the -l\n\
option, it instead runs every test listed in a file. With the -o option,\n\
it instead runs a single test and shows its complete output.\n";
/*
* Header used for test output. %s is replaced by the file name of the list
* of tests.
*/
static const char banner[] = "\n\
Running all tests listed in %s. If any tests fail, run the failing\n\
test program with runtests -o to see more details.\n\n";
/* Header for reports of failed tests. */
static const char header[] = "\n\
Failed Set Fail/Total (%) Skip Stat Failing Tests\n\
-------------------------- -------------- ---- ---- ------------------------";
/* Include the file name and line number in malloc failures. */
#define xcalloc(n, size) x_calloc((n), (size), __FILE__, __LINE__)
#define xmalloc(size) x_malloc((size), __FILE__, __LINE__)
#define xstrdup(p) x_strdup((p), __FILE__, __LINE__)
#define xstrndup(p, size) x_strndup((p), (size), __FILE__, __LINE__)
#define xreallocarray(p, n, size) \
x_reallocarray((p), (n), (size), __FILE__, __LINE__)
/*
* __attribute__ is available in gcc 2.5 and later, but only with gcc 2.7
* could you use the __format__ form of the attributes, which is what we use
* (to avoid confusion with other macros).
*/
#ifndef __attribute__
# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
# define __attribute__(spec) /* empty */
# endif
#endif
/*
* We use __alloc_size__, but it was only available in fairly recent versions
* of GCC. Suppress warnings about the unknown attribute if GCC is too old.
* We know that we're GCC at this point, so we can use the GCC variadic macro
* extension, which will still work with versions of GCC too old to have C99
* variadic macro support.
*/
#if !defined(__attribute__) && !defined(__alloc_size__)
# if defined(__GNUC__) && !defined(__clang__)
# if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 3)
# define __alloc_size__(spec, args...) /* empty */
# endif
# endif
#endif
/*
* LLVM and Clang pretend to be GCC but don't support all of the __attribute__
* settings that GCC does. For them, suppress warnings about unknown
* attributes on declarations. This unfortunately will affect the entire
* compilation context, but there's no push and pop available.
*/
#if !defined(__attribute__) && (defined(__llvm__) || defined(__clang__))
# pragma GCC diagnostic ignored "-Wattributes"
#endif
/* Declare internal functions that benefit from compiler attributes. */
static void die(const char *, ...)
__attribute__((__nonnull__, __noreturn__, __format__(printf, 1, 2)));
static void sysdie(const char *, ...)
__attribute__((__nonnull__, __noreturn__, __format__(printf, 1, 2)));
static void *x_calloc(size_t, size_t, const char *, int)
__attribute__((__alloc_size__(1, 2), __malloc__, __nonnull__));
static void *x_malloc(size_t, const char *, int)
__attribute__((__alloc_size__(1), __malloc__, __nonnull__));
static void *x_reallocarray(void *, size_t, size_t, const char *, int)
__attribute__((__alloc_size__(2, 3), __malloc__, __nonnull__(4)));
static char *x_strdup(const char *, const char *, int)
__attribute__((__malloc__, __nonnull__));
static char *x_strndup(const char *, size_t, const char *, int)
__attribute__((__malloc__, __nonnull__));
/*
* Report a fatal error and exit.
*/
static void
die(const char *format, ...)
{
va_list args;
fflush(stdout);
fprintf(stderr, "runtests: ");
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
fprintf(stderr, "\n");
exit(1);
}
/*
* Report a fatal error, including the results of strerror, and exit.
*/
static void
sysdie(const char *format, ...)
{
int oerrno;
va_list args;
oerrno = errno;
fflush(stdout);
fprintf(stderr, "runtests: ");
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
fprintf(stderr, ": %s\n", strerror(oerrno));
exit(1);
}
/*
* Allocate zeroed memory, reporting a fatal error and exiting on failure.
*/
static void *
x_calloc(size_t n, size_t size, const char *file, int line)
{
void *p;
n = (n > 0) ? n : 1;
size = (size > 0) ? size : 1;
p = calloc(n, size);
if (p == NULL)
sysdie("failed to calloc %lu bytes at %s line %d",
(unsigned long) size, file, line);
return p;
}
/*
* Allocate memory, reporting a fatal error and exiting on failure.
*/
static void *
x_malloc(size_t size, const char *file, int line)
{
void *p;
p = malloc(size);
if (p == NULL)
sysdie("failed to malloc %lu bytes at %s line %d",
(unsigned long) size, file, line);
return p;
}
/*
* Reallocate memory, reporting a fatal error and exiting on failure.
*
* We should technically use SIZE_MAX here for the overflow check, but
* SIZE_MAX is C99 and we're only assuming C89 + SUSv3, which does not
* guarantee that it exists. They do guarantee that UINT_MAX exists, and we
* can assume that UINT_MAX <= SIZE_MAX. And we should not be allocating
* anything anywhere near that large.
*
* (In theory, C89 and C99 permit size_t to be smaller than unsigned int, but
* I disbelieve in the existence of such systems and they will have to cope
* without overflow checks.)
*/
static void *
x_reallocarray(void *p, size_t n, size_t size, const char *file, int line)
{
if (n > 0 && UINT_MAX / n <= size)
sysdie("realloc too large at %s line %d", file, line);
p = realloc(p, n * size);
if (p == NULL)
sysdie("failed to realloc %lu bytes at %s line %d",
(unsigned long) (n * size), file, line);
return p;
}
/*
* Copy a string, reporting a fatal error and exiting on failure.
*/
static char *
x_strdup(const char *s, const char *file, int line)
{
char *p;
size_t len;
len = strlen(s) + 1;
p = malloc(len);
if (p == NULL)
sysdie("failed to strdup %lu bytes at %s line %d",
(unsigned long) len, file, line);
memcpy(p, s, len);
return p;
}
/*
* Copy the first n characters of a string, reporting a fatal error and
* existing on failure.
*
* Avoid using the system strndup function since it may not exist (on Mac OS
* X, for example), and there's no need to introduce another portability
* requirement.
*/
char *
x_strndup(const char *s, size_t size, const char *file, int line)
{
const char *p;
size_t len;
char *copy;
/* Don't assume that the source string is nul-terminated. */
for (p = s; (size_t) (p - s) < size && *p != '\0'; p++)
;
len = (size_t) (p - s);
copy = malloc(len + 1);
if (copy == NULL)
sysdie("failed to strndup %lu bytes at %s line %d",
(unsigned long) len, file, line);
memcpy(copy, s, len);
copy[len] = '\0';
return copy;
}
/*
* Form a new string by concatenating multiple strings. The arguments must be
* terminated by (const char *) 0.
*
* This function only exists because we can't assume asprintf. We can't
* simulate asprintf with snprintf because we're only assuming SUSv3, which
* does not require that snprintf with a NULL buffer return the required
* length. When those constraints are relaxed, this should be ripped out and
* replaced with asprintf or a more trivial replacement with snprintf.
*/
static char *
concat(const char *first, ...)
{
va_list args;
char *result;
const char *string;
size_t offset;
size_t length = 0;
/*
* Find the total memory required. Ensure we don't overflow length. We
* aren't guaranteed to have SIZE_MAX, so use UINT_MAX as an acceptable
* substitute (see the x_nrealloc comments).
*/
va_start(args, first);
for (string = first; string != NULL; string = va_arg(args, const char *)) {
if (length >= UINT_MAX - strlen(string)) {
errno = EINVAL;
sysdie("strings too long in concat");
}
length += strlen(string);
}
va_end(args);
length++;
/* Create the string. */
result = xmalloc(length);
va_start(args, first);
offset = 0;
for (string = first; string != NULL; string = va_arg(args, const char *)) {
memcpy(result + offset, string, strlen(string));
offset += strlen(string);
}
va_end(args);
result[offset] = '\0';
return result;
}
/*
* Given a struct timeval, return the number of seconds it represents as a
* double. Use difftime() to convert a time_t to a double.
*/
static double
tv_seconds(const struct timeval *tv)
{
return difftime(tv->tv_sec, 0) + (double) tv->tv_usec * 1e-6;
}
/*
* Given two struct timevals, return the difference in seconds.
*/
static double
tv_diff(const struct timeval *tv1, const struct timeval *tv0)
{
return tv_seconds(tv1) - tv_seconds(tv0);
}
/*
* Given two struct timevals, return the sum in seconds as a double.
*/
static double
tv_sum(const struct timeval *tv1, const struct timeval *tv2)
{
return tv_seconds(tv1) + tv_seconds(tv2);
}
/*
* Given a pointer to a string, skip any leading whitespace and return a
* pointer to the first non-whitespace character.
*/
static const char *
skip_whitespace(const char *p)
{
while (isspace((unsigned char)(*p)))
p++;
return p;
}
/*
* Given a pointer to a string, skip any non-whitespace characters and return
* a pointer to the first whitespace character, or to the end of the string.
*/
static const char *
skip_non_whitespace(const char *p)
{
while (*p != '\0' && !isspace((unsigned char)(*p)))
p++;
return p;
}
/*
* Start a program, connecting its stdout to a pipe on our end and its stderr
* to /dev/null, and storing the file descriptor to read from in the two
* argument. Returns the PID of the new process. Errors are fatal.
*/
static pid_t
test_start(char *const *command, int *fd)
{
int fds[2], infd, errfd;
pid_t child;
/* Create a pipe used to capture the output from the test program. */
if (pipe(fds) == -1) {
puts("ABORTED");
fflush(stdout);
sysdie("can't create pipe");
}
/* Fork a child process, massage the file descriptors, and exec. */
child = fork();
switch (child) {
case -1:
puts("ABORTED");
fflush(stdout);
sysdie("can't fork");
/* In the child. Set up our standard output. */
case 0:
close(fds[0]);
close(STDOUT_FILENO);
if (dup2(fds[1], STDOUT_FILENO) < 0)
_exit(CHILDERR_DUP);
close(fds[1]);
/* Point standard input at /dev/null. */
close(STDIN_FILENO);
infd = open("/dev/null", O_RDONLY);
if (infd < 0)
_exit(CHILDERR_STDIN);
if (infd != STDIN_FILENO) {
if (dup2(infd, STDIN_FILENO) < 0)
_exit(CHILDERR_DUP);
close(infd);
}
/* Point standard error at /dev/null. */
close(STDERR_FILENO);
errfd = open("/dev/null", O_WRONLY);
if (errfd < 0)
_exit(CHILDERR_STDERR);
if (errfd != STDERR_FILENO) {
if (dup2(errfd, STDERR_FILENO) < 0)
_exit(CHILDERR_DUP);
close(errfd);
}
/* Now, exec our process. */
if (execv(command[0], command) == -1)
_exit(CHILDERR_EXEC);
break;
/* In parent. Close the extra file descriptor. */
default:
close(fds[1]);
break;
}
*fd = fds[0];
return child;
}
/*
* Back up over the output saying what test we were executing.
*/
static void
test_backspace(struct testset *ts)
{
unsigned int i;
if (!isatty(STDOUT_FILENO))
return;
for (i = 0; i < ts->length; i++)
putchar('\b');
for (i = 0; i < ts->length; i++)
putchar(' ');
for (i = 0; i < ts->length; i++)
putchar('\b');
ts->length = 0;
}
/*
* Allocate or resize the array of test results to be large enough to contain
* the test number in.
*/
static void
resize_results(struct testset *ts, unsigned long n)
{
unsigned long i;
size_t s;
/* If there's already enough space, return quickly. */
if (n <= ts->allocated)
return;
/*
* If no space has been allocated, do the initial allocation. Otherwise,
* resize. Start with 32 test cases and then add 1024 with each resize to
* try to reduce the number of reallocations.
*/
if (ts->allocated == 0) {
s = (n > 32) ? n : 32;
ts->results = xcalloc(s, sizeof(enum test_status));
} else {
s = (n > ts->allocated + 1024) ? n : ts->allocated + 1024;
ts->results = xreallocarray(ts->results, s, sizeof(enum test_status));
}
/* Set the results for the newly-allocated test array. */
for (i = ts->allocated; i < s; i++)
ts->results[i] = TEST_INVALID;
ts->allocated = s;
}
/*
* Report an invalid test number and set the appropriate flags. Pulled into a
* separate function since we do this in several places.
*/
static void
invalid_test_number(struct testset *ts, long n, enum test_verbose verbose)
{
if (!verbose)
test_backspace(ts);
printf("ABORTED (invalid test number %ld)\n", n);
ts->aborted = 1;
ts->reported = 1;
}
/*
* Read the plan line of test output, which should contain the range of test
* numbers. We may initialize the testset structure here if we haven't yet
* seen a test. Return true if initialization succeeded and the test should
* continue, false otherwise.
*/
static int
test_plan(const char *line, struct testset *ts, enum test_verbose verbose)
{
long n;
/*
* Accept a plan without the leading 1.. for compatibility with older
* versions of runtests. This will only be allowed if we've not yet seen
* a test result.
*/
line = skip_whitespace(line);
if (strncmp(line, "1..", 3) == 0)
line += 3;
/*
* Get the count and check it for validity.
*
* If we have something of the form "1..0 # skip foo", the whole file was
* skipped; record that. If we do skip the whole file, zero out all of
* our statistics, since they're no longer relevant.
*
* strtol is called with a second argument to advance the line pointer
* past the count to make it simpler to detect the # skip case.
*/
n = strtol(line, (char **) &line, 10);
if (n == 0) {
line = skip_whitespace(line);
if (*line == '#') {
line = skip_whitespace(line + 1);
if (strncasecmp(line, "skip", 4) == 0) {
line = skip_whitespace(line + 4);
if (*line != '\0') {
ts->reason = xstrdup(line);
ts->reason[strlen(ts->reason) - 1] = '\0';
}
ts->all_skipped = 1;
ts->aborted = 1;
ts->count = 0;
ts->passed = 0;
ts->skipped = 0;
ts->failed = 0;
return 0;
}
}
}
if (n <= 0) {
puts("ABORTED (invalid test count)");
ts->aborted = 1;
ts->reported = 1;
return 0;
}
/*
* If we are doing lazy planning, check the plan against the largest test
* number that we saw and fail now if we saw a check outside the plan
* range.
*/
if (ts->plan == PLAN_PENDING && (unsigned long) n < ts->count) {
invalid_test_number(ts, (long) ts->count, verbose);
return 0;
}
/*
* Otherwise, allocated or resize the results if needed and update count,
* and then record that we've seen a plan.
*/
resize_results(ts, (unsigned long) n);
ts->count = (unsigned long) n;
if (ts->plan == PLAN_INIT)
ts->plan = PLAN_FIRST;
else if (ts->plan == PLAN_PENDING)
ts->plan = PLAN_FINAL;
return 1;
}
/*
* Given a single line of output from a test, parse it and return the success
* status of that test. Anything printed to stdout not matching the form
* /^(not )?ok \d+/ is ignored. Sets ts->current to the test number that just
* reported status.
*/
static void
test_checkline(const char *line, struct testset *ts,
enum test_verbose verbose)
{
enum test_status status = TEST_PASS;
const char *bail;
char *end;
long number;
unsigned long current;
int outlen;
/* Before anything, check for a test abort. */
bail = strstr(line, "Bail out!");
if (bail != NULL) {
bail = skip_whitespace(bail + strlen("Bail out!"));
if (*bail != '\0') {
size_t length;
length = strlen(bail);
if (bail[length - 1] == '\n')
length--;
if (!verbose)
test_backspace(ts);
printf("ABORTED (%.*s)\n", (int) length, bail);
ts->reported = 1;
}
ts->aborted = 1;
return;
}
/*
* If the given line isn't newline-terminated, it was too big for an
* fgets(), which means ignore it.
*/
if (line[strlen(line) - 1] != '\n')
return;
/* If the line begins with a hash mark, ignore it. */
if (line[0] == '#')
return;
/* If we haven't yet seen a plan, look for one. */
if (ts->plan == PLAN_INIT && isdigit((unsigned char)(*line))) {
if (!test_plan(line, ts, verbose))
return;
} else if (strncmp(line, "1..", 3) == 0) {
if (ts->plan == PLAN_PENDING) {
if (!test_plan(line, ts, verbose))
return;
} else {
if (!verbose)
test_backspace(ts);
puts("ABORTED (multiple plans)");
ts->aborted = 1;
ts->reported = 1;
return;
}
}
/* Parse the line, ignoring something we can't parse. */
if (strncmp(line, "not ", 4) == 0) {
status = TEST_FAIL;
line += 4;
}
if (strncmp(line, "ok", 2) != 0)
return;
line = skip_whitespace(line + 2);
errno = 0;
number = strtol(line, &end, 10);
if (errno != 0 || end == line)
current = ts->current + 1;
else if (number <= 0) {
invalid_test_number(ts, number, verbose);
return;
} else
current = (unsigned long) number;
if (current > ts->count && ts->plan == PLAN_FIRST) {
invalid_test_number(ts, (long) current, verbose);
return;
}
/* We have a valid test result. Tweak the results array if needed. */
if (ts->plan == PLAN_INIT || ts->plan == PLAN_PENDING) {
ts->plan = PLAN_PENDING;
resize_results(ts, current);
if (current > ts->count)
ts->count = current;
}
/*
* Handle directives. We should probably do something more interesting
* with unexpected passes of todo tests.
*/
while (isdigit((unsigned char)(*line)))
line++;
line = skip_whitespace(line);
if (*line == '#') {
line = skip_whitespace(line + 1);
if (strncasecmp(line, "skip", 4) == 0)
status = TEST_SKIP;
if (strncasecmp(line, "todo", 4) == 0)
status = (status == TEST_FAIL) ? TEST_SKIP : TEST_FAIL;
}
/* Make sure that the test number is in range and not a duplicate. */
if (ts->results[current - 1] != TEST_INVALID) {
if (!verbose)
test_backspace(ts);
printf("ABORTED (duplicate test number %lu)\n", current);
ts->aborted = 1;
ts->reported = 1;
return;
}
/* Good results. Increment our various counters. */
switch (status) {
case TEST_PASS: ts->passed++; break;
case TEST_FAIL: ts->failed++; break;
case TEST_SKIP: ts->skipped++; break;
case TEST_INVALID: break;
}
ts->current = current;
ts->results[current - 1] = status;
if (!verbose && isatty(STDOUT_FILENO)) {
test_backspace(ts);
if (ts->plan == PLAN_PENDING)
outlen = printf("%lu/?", current);
else
outlen = printf("%lu/%lu", current, ts->count);
ts->length = (outlen >= 0) ? (unsigned int) outlen : 0;
fflush(stdout);
}
}
/*
* Print out a range of test numbers, returning the number of characters it
* took up. Takes the first number, the last number, the number of characters
* already printed on the line, and the limit of number of characters the line
* can hold. Add a comma and a space before the range if chars indicates that
* something has already been printed on the line, and print ... instead if
* chars plus the space needed would go over the limit (use a limit of 0 to
* disable this).
*/
static unsigned int
test_print_range(unsigned long first, unsigned long last, unsigned long chars,
unsigned int limit)
{
unsigned int needed = 0;
unsigned long n;
for (n = first; n > 0; n /= 10)
needed++;
if (last > first) {
for (n = last; n > 0; n /= 10)
needed++;
needed++;
}
if (chars > 0)
needed += 2;
if (limit > 0 && chars + needed > limit) {
needed = 0;
if (chars <= limit) {
if (chars > 0) {
printf(", ");
needed += 2;
}
printf("...");
needed += 3;
}
} else {
if (chars > 0)
printf(", ");
if (last > first)
printf("%lu-", first);
printf("%lu", last);
}
return needed;
}
/*
* Summarize a single test set. The second argument is 0 if the set exited
* cleanly, a positive integer representing the exit status if it exited
* with a non-zero status, and a negative integer representing the signal
* that terminated it if it was killed by a signal.
*/
static void
test_summarize(struct testset *ts, int status)
{
unsigned long i;
unsigned long missing = 0;
unsigned long failed = 0;
unsigned long first = 0;
unsigned long last = 0;
if (ts->aborted) {
fputs("ABORTED", stdout);
if (ts->count > 0)
printf(" (passed %lu/%lu)", ts->passed, ts->count - ts->skipped);
} else {
for (i = 0; i < ts->count; i++) {
if (ts->results[i] == TEST_INVALID) {
if (missing == 0)
fputs("MISSED ", stdout);
if (first && i == last)
last = i + 1;
else {
if (first)
test_print_range(first, last, missing - 1, 0);
missing++;
first = i + 1;
last = i + 1;
}
}
}
if (first)
test_print_range(first, last, missing - 1, 0);
first = 0;
last = 0;
for (i = 0; i < ts->count; i++) {
if (ts->results[i] == TEST_FAIL) {
if (missing && !failed)
fputs("; ", stdout);
if (failed == 0)
fputs("FAILED ", stdout);
if (first && i == last)
last = i + 1;
else {
if (first)
test_print_range(first, last, failed - 1, 0);
failed++;
first = i + 1;
last = i + 1;
}
}
}
if (first)
test_print_range(first, last, failed - 1, 0);
if (!missing && !failed) {
fputs(!status ? "ok" : "dubious", stdout);
if (ts->skipped > 0) {
if (ts->skipped == 1)
printf(" (skipped %lu test)", ts->skipped);
else
printf(" (skipped %lu tests)", ts->skipped);
}
}
}
if (status > 0)
printf(" (exit status %d)", status);
else if (status < 0)
printf(" (killed by signal %d%s)", -status,
WCOREDUMP(ts->status) ? ", core dumped" : "");
putchar('\n');
}
/*
* Given a test set, analyze the results, classify the exit status, handle a
* few special error messages, and then pass it along to test_summarize() for
* the regular output. Returns true if the test set ran successfully and all
* tests passed or were skipped, false otherwise.
*/
static int
test_analyze(struct testset *ts)
{
if (ts->reported)
return 0;
if (ts->all_skipped) {
if (ts->reason == NULL)
puts("skipped");
else
printf("skipped (%s)\n", ts->reason);
return 1;
} else if (WIFEXITED(ts->status) && WEXITSTATUS(ts->status) != 0) {
switch (WEXITSTATUS(ts->status)) {
case CHILDERR_DUP:
if (!ts->reported)
puts("ABORTED (can't dup file descriptors)");
break;
case CHILDERR_EXEC:
if (!ts->reported)
puts("ABORTED (execution failed -- not found?)");
break;
case CHILDERR_STDIN:
case CHILDERR_STDERR:
if (!ts->reported)
puts("ABORTED (can't open /dev/null)");
break;
default:
test_summarize(ts, WEXITSTATUS(ts->status));
break;
}
return 0;
} else if (WIFSIGNALED(ts->status)) {
test_summarize(ts, -WTERMSIG(ts->status));
return 0;
} else if (ts->plan != PLAN_FIRST && ts->plan != PLAN_FINAL) {
puts("ABORTED (no valid test plan)");
ts->aborted = 1;
return 0;
} else {
test_summarize(ts, 0);
return (ts->failed == 0);
}
}
/*
* Runs a single test set, accumulating and then reporting the results.
* Returns true if the test set was successfully run and all tests passed,
* false otherwise.
*/
static int
test_run(struct testset *ts, enum test_verbose verbose)
{
pid_t testpid, child;
int outfd, status;
unsigned long i;
FILE *output;
char buffer[BUFSIZ];
/* Run the test program. */
testpid = test_start(ts->command, &outfd);
output = fdopen(outfd, "r");
if (!output) {
puts("ABORTED");
fflush(stdout);
sysdie("fdopen failed");
}
/*
* Pass each line of output to test_checkline(), and print the line if
* verbosity is requested.
*/
while (!ts->aborted && fgets(buffer, sizeof(buffer), output)) {
if (verbose)
printf("%s", buffer);
test_checkline(buffer, ts, verbose);
}
if (ferror(output) || ts->plan == PLAN_INIT)
ts->aborted = 1;
if (!verbose)
test_backspace(ts);
/*
* Consume the rest of the test output, close the output descriptor,
* retrieve the exit status, and pass that information to test_analyze()
* for eventual output.
*/
while (fgets(buffer, sizeof(buffer), output))
if (verbose)
printf("%s", buffer);
fclose(output);
child = waitpid(testpid, &ts->status, 0);
if (child == (pid_t) -1) {
if (!ts->reported) {
puts("ABORTED");
fflush(stdout);
}
sysdie("waitpid for %u failed", (unsigned int) testpid);
}
if (ts->all_skipped)
ts->aborted = 0;
status = test_analyze(ts);
/* Convert missing tests to failed tests. */
for (i = 0; i < ts->count; i++) {
if (ts->results[i] == TEST_INVALID) {
ts->failed++;
ts->results[i] = TEST_FAIL;
status = 0;
}
}
return status;
}
/* Summarize a list of test failures. */
static void
test_fail_summary(const struct testlist *fails)
{
struct testset *ts;
unsigned int chars;
unsigned long i, first, last, total;
double failed;
puts(header);
/* Failed Set Fail/Total (%) Skip Stat Failing (25)
-------------------------- -------------- ---- ---- -------------- */
for (; fails; fails = fails->next) {
ts = fails->ts;
total = ts->count - ts->skipped;
failed = (double) ts->failed;
printf("%-26.26s %4lu/%-4lu %3.0f%% %4lu ", ts->file, ts->failed,
total, total ? (failed * 100.0) / (double) total : 0,
ts->skipped);
if (WIFEXITED(ts->status))
printf("%4d ", WEXITSTATUS(ts->status));
else
printf(" -- ");
if (ts->aborted) {
puts("aborted");
continue;
}
chars = 0;
first = 0;
last = 0;
for (i = 0; i < ts->count; i++) {
if (ts->results[i] == TEST_FAIL) {
if (first != 0 && i == last)
last = i + 1;
else {
if (first != 0)
chars += test_print_range(first, last, chars, 19);
first = i + 1;
last = i + 1;
}
}
}
if (first != 0)
test_print_range(first, last, chars, 19);
putchar('\n');
}
}
/*
* Check whether a given file path is a valid test. Currently, this checks
* whether it is executable and is a regular file. Returns true or false.
*/
static int
is_valid_test(const char *path)
{
struct stat st;
if (access(path, X_OK) < 0)
return 0;
if (stat(path, &st) < 0)
return 0;
if (!S_ISREG(st.st_mode))
return 0;
return 1;
}
/*
* Given the name of a test, a pointer to the testset struct, and the source
* and build directories, find the test. We try first relative to the current
* directory, then in the build directory (if not NULL), then in the source
* directory. In each of those directories, we first try a "-t" extension and
* then a ".t" extension. When we find an executable program, we return the
* path to that program. If none of those paths are executable, just fill in
* the name of the test as is.
*
* The caller is responsible for freeing the path member of the testset
* struct.
*/
static char *
find_test(const char *name, const char *source, const char *build)
{
char *path = NULL;
const char *bases[3], *suffix, *base;
unsigned int i, j;
const char *suffixes[3] = { "-t", ".t", "" };
/* Possible base directories. */
bases[0] = ".";
bases[1] = build;
bases[2] = source;
/* Try each suffix with each base. */
for (i = 0; i < ARRAY_SIZE(suffixes); i++) {
suffix = suffixes[i];
for (j = 0; j < ARRAY_SIZE(bases); j++) {
base = bases[j];
if (base == NULL)
continue;
path = concat(base, "/", name, suffix, (const char *) 0);
if (is_valid_test(path))
return path;
free(path);
path = NULL;
}
}
if (path == NULL)
path = xstrdup(name);
return path;
}
/*
* Parse a single line of a test list and store the test name and command to
* execute it in the given testset struct.
*
* Normally, each line is just the name of the test, which is located in the
* test directory and turned into a command to run. However, each line may
* have whitespace-separated options, which change the command that's run.
* Current supported options are:
*
* valgrind
* Run the test under valgrind if C_TAP_VALGRIND is set. The contents
* of that environment variable are taken as the valgrind command (with
* options) to run. The command is parsed with a simple split on
* whitespace and no quoting is supported.
*
* libtool
* If running under valgrind, use libtool to invoke valgrind. This avoids
* running valgrind on the wrapper shell script generated by libtool. If
* set, C_TAP_LIBTOOL must be set to the full path to the libtool program
* to use to run valgrind and thus the test. Ignored if the test isn't
* being run under valgrind.
*/
static void
parse_test_list_line(const char *line, struct testset *ts, const char *source,
const char *build)
{
const char *p, *end, *option, *libtool;
const char *valgrind = NULL;
unsigned int use_libtool = 0;
unsigned int use_valgrind = 0;
size_t len, i;
/* Determine the name of the test. */
p = skip_non_whitespace(line);
ts->file = xstrndup(line, p - line);
/* Check if any test options are set. */
p = skip_whitespace(p);
while (*p != '\0') {
end = skip_non_whitespace(p);
if (strncmp(p, "libtool", end - p) == 0) {
use_libtool = 1;
p = end;
} else if (strncmp(p, "valgrind", end - p) == 0) {
valgrind = getenv("C_TAP_VALGRIND");
use_valgrind = (valgrind != NULL);
p = end;
} else {
option = xstrndup(p, end - p);
die("unknown test list option %s", option);
}
p = skip_whitespace(end);
}
/* Construct the argv to run the test. First, find the length. */
len = 1;
if (use_valgrind && valgrind != NULL) {
p = skip_whitespace(valgrind);
while (*p != '\0') {
len++;
p = skip_whitespace(skip_non_whitespace(p));
}
if (use_libtool)
len += 2;
}
/* Now, build the command. */
ts->command = xcalloc(len + 1, sizeof(char *));
i = 0;
if (use_valgrind && valgrind != NULL) {
if (use_libtool) {
libtool = getenv("C_TAP_LIBTOOL");
if (libtool == NULL)
die("valgrind with libtool requested, but C_TAP_LIBTOOL is not"
" set");
ts->command[i++] = xstrdup(libtool);
ts->command[i++] = xstrdup("--mode=execute");
}
p = skip_whitespace(valgrind);
while (*p != '\0') {
end = skip_non_whitespace(p);
ts->command[i++] = xstrndup(p, end - p);
p = skip_whitespace(end);
}
}
if (i != len - 1)
die("internal error while constructing command line");
ts->command[i++] = find_test(ts->file, source, build);
ts->command[i] = NULL;
}
/*
* Read a list of tests from a file, returning the list of tests as a struct
* testlist, or NULL if there were no tests (such as a file containing only
* comments). Reports an error to standard error and exits if the list of
* tests cannot be read.
*/
static struct testlist *
read_test_list(const char *filename, const char *source, const char *build)
{
FILE *file;
unsigned int line;
size_t length;
char buffer[BUFSIZ];
const char *start;
struct testlist *listhead, *current;
/* Create the initial container list that will hold our results. */
listhead = xcalloc(1, sizeof(struct testlist));
current = NULL;
/*
* Open our file of tests to run and read it line by line, creating a new
* struct testlist and struct testset for each line.
*/
file = fopen(filename, "r");
if (file == NULL)
sysdie("can't open %s", filename);
line = 0;
while (fgets(buffer, sizeof(buffer), file)) {
line++;
length = strlen(buffer) - 1;
if (buffer[length] != '\n') {
fprintf(stderr, "%s:%u: line too long\n", filename, line);
exit(1);
}
buffer[length] = '\0';
/* Skip comments, leading spaces, and blank lines. */
start = skip_whitespace(buffer);
if (strlen(start) == 0)
continue;
if (start[0] == '#')
continue;
/* Allocate the new testset structure. */
if (current == NULL)
current = listhead;
else {
current->next = xcalloc(1, sizeof(struct testlist));
current = current->next;
}
current->ts = xcalloc(1, sizeof(struct testset));
current->ts->plan = PLAN_INIT;
/* Parse the line and store the results in the testset struct. */
parse_test_list_line(start, current->ts, source, build);
}
fclose(file);
/* If there were no tests, current is still NULL. */
if (current == NULL) {
free(listhead);
return NULL;
}
/* Return the results. */
return listhead;
}
/*
* Build a list of tests from command line arguments. Takes the argv and argc
* representing the command line arguments and returns a newly allocated test
* list, or NULL if there were no tests. The caller is responsible for
* freeing.
*/
static struct testlist *
build_test_list(char *argv[], int argc, const char *source, const char *build)
{
int i;
struct testlist *listhead, *current;
/* Create the initial container list that will hold our results. */
listhead = xcalloc(1, sizeof(struct testlist));
current = NULL;
/* Walk the list of arguments and create test sets for them. */
for (i = 0; i < argc; i++) {
if (current == NULL)
current = listhead;
else {
current->next = xcalloc(1, sizeof(struct testlist));
current = current->next;
}
current->ts = xcalloc(1, sizeof(struct testset));
current->ts->plan = PLAN_INIT;
current->ts->file = xstrdup(argv[i]);
current->ts->command = xcalloc(2, sizeof(char *));
current->ts->command[0] = find_test(current->ts->file, source, build);
current->ts->command[1] = NULL;
}
/* If there were no tests, current is still NULL. */
if (current == NULL) {
free(listhead);
return NULL;
}
/* Return the results. */
return listhead;
}
/* Free a struct testset. */
static void
free_testset(struct testset *ts)
{
size_t i;
free(ts->file);
for (i = 0; ts->command[i] != NULL; i++)
free(ts->command[i]);
free(ts->command);
free(ts->results);
free(ts->reason);
free(ts);
}
/*
* Run a batch of tests. Takes two additional parameters: the root of the
* source directory and the root of the build directory. Test programs will
* be first searched for in the current directory, then the build directory,
* then the source directory. Returns true iff all tests passed, and always
* frees the test list that's passed in.
*/
static int
test_batch(struct testlist *tests, enum test_verbose verbose)
{
size_t length, i;
size_t longest = 0;
unsigned int count = 0;
struct testset *ts;
struct timeval start, end;
struct rusage stats;
struct testlist *failhead = NULL;
struct testlist *failtail = NULL;
struct testlist *current, *next;
int succeeded;
unsigned long total = 0;
unsigned long passed = 0;
unsigned long skipped = 0;
unsigned long failed = 0;
unsigned long aborted = 0;
/* Walk the list of tests to find the longest name. */
for (current = tests; current != NULL; current = current->next) {
length = strlen(current->ts->file);
if (length > longest)
longest = length;
}
/*
* Add two to longest and round up to the nearest tab stop. This is how
* wide the column for printing the current test name will be.
*/
longest += 2;
if (longest % 8)
longest += 8 - (longest % 8);
/* Start the wall clock timer. */
gettimeofday(&start, NULL);
/* Now, plow through our tests again, running each one. */
for (current = tests; current != NULL; current = current->next) {
ts = current->ts;
/* Print out the name of the test file. */
fputs(ts->file, stdout);
if (verbose)
fputs("\n\n", stdout);
else
for (i = strlen(ts->file); i < longest; i++)
putchar('.');
if (isatty(STDOUT_FILENO))
fflush(stdout);
/* Run the test. */
succeeded = test_run(ts, verbose);
fflush(stdout);
if (verbose)
putchar('\n');
/* Record cumulative statistics. */
aborted += ts->aborted;
total += ts->count + ts->all_skipped;
passed += ts->passed;
skipped += ts->skipped + ts->all_skipped;
failed += ts->failed;
count++;
/* If the test fails, we shuffle it over to the fail list. */
if (!succeeded) {
if (failhead == NULL) {
failhead = xmalloc(sizeof(struct testset));
failtail = failhead;
} else {
failtail->next = xmalloc(sizeof(struct testset));
failtail = failtail->next;
}
failtail->ts = ts;
failtail->next = NULL;
}
}
total -= skipped;
/* Stop the timer and get our child resource statistics. */
gettimeofday(&end, NULL);
getrusage(RUSAGE_CHILDREN, &stats);
/* Summarize the failures and free the failure list. */
if (failhead != NULL) {
test_fail_summary(failhead);
while (failhead != NULL) {
next = failhead->next;
free(failhead);
failhead = next;
}
}
/* Free the memory used by the test lists. */
while (tests != NULL) {
next = tests->next;
free_testset(tests->ts);
free(tests);
tests = next;
}
/* Print out the final test summary. */
putchar('\n');
if (aborted != 0) {
if (aborted == 1)
printf("Aborted %lu test set", aborted);
else
printf("Aborted %lu test sets", aborted);
printf(", passed %lu/%lu tests", passed, total);
}
else if (failed == 0)
fputs("All tests successful", stdout);
else
printf("Failed %lu/%lu tests, %.2f%% okay", failed, total,
(double) (total - failed) * 100.0 / (double) total);
if (skipped != 0) {
if (skipped == 1)
printf(", %lu test skipped", skipped);
else
printf(", %lu tests skipped", skipped);
}
puts(".");
printf("Files=%u, Tests=%lu", count, total);
printf(", %.2f seconds", tv_diff(&end, &start));
printf(" (%.2f usr + %.2f sys = %.2f CPU)\n",
tv_seconds(&stats.ru_utime), tv_seconds(&stats.ru_stime),
tv_sum(&stats.ru_utime, &stats.ru_stime));
return (failed == 0 && aborted == 0);
}
/*
* Run a single test case. This involves just running the test program after
* having done the environment setup and finding the test program.
*/
static void
test_single(const char *program, const char *source, const char *build)
{
char *path;
path = find_test(program, source, build);
if (execl(path, path, (char *) 0) == -1)
sysdie("cannot exec %s", path);
}
/*
* Main routine. Set the C_TAP_SOURCE, C_TAP_BUILD, SOURCE, and BUILD
* environment variables and then, given a file listing tests, run each test
* listed.
*/
int
main(int argc, char *argv[])
{
int option;
int status = 0;
int single = 0;
enum test_verbose verbose = CONCISE;
char *c_tap_source_env = NULL;
char *c_tap_build_env = NULL;
char *source_env = NULL;
char *build_env = NULL;
const char *program;
const char *shortlist;
const char *list = NULL;
const char *source = C_TAP_SOURCE;
const char *build = C_TAP_BUILD;
struct testlist *tests;
program = argv[0];
while ((option = getopt(argc, argv, "b:hl:os:v")) != EOF) {
switch (option) {
case 'b':
build = optarg;
break;
case 'h':
printf(usage_message, program, program, program, usage_extra);
exit(0);
case 'l':
list = optarg;
break;
case 'o':
single = 1;
break;
case 's':
source = optarg;
break;
case 'v':
verbose = VERBOSE;
break;
default:
exit(1);
}
}
argv += optind;
argc -= optind;
if ((list == NULL && argc < 1) || (list != NULL && argc > 0)) {
fprintf(stderr, usage_message, program, program, program, usage_extra);
exit(1);
}
/*
* If C_TAP_VERBOSE is set in the environment, that also turns on verbose
* mode.
*/
if (getenv("C_TAP_VERBOSE") != NULL)
verbose = VERBOSE;
/*
* Set C_TAP_SOURCE and C_TAP_BUILD environment variables. Also set
* SOURCE and BUILD for backward compatibility, although we're trying to
* migrate to the ones with a C_TAP_* prefix.
*/
if (source != NULL) {
c_tap_source_env = concat("C_TAP_SOURCE=", source, (const char *) 0);
if (putenv(c_tap_source_env) != 0)
sysdie("cannot set C_TAP_SOURCE in the environment");
source_env = concat("SOURCE=", source, (const char *) 0);
if (putenv(source_env) != 0)
sysdie("cannot set SOURCE in the environment");
}
if (build != NULL) {
c_tap_build_env = concat("C_TAP_BUILD=", build, (const char *) 0);
if (putenv(c_tap_build_env) != 0)
sysdie("cannot set C_TAP_BUILD in the environment");
build_env = concat("BUILD=", build, (const char *) 0);
if (putenv(build_env) != 0)
sysdie("cannot set BUILD in the environment");
}
/* Run the tests as instructed. */
if (single)
test_single(argv[0], source, build);
else if (list != NULL) {
shortlist = strrchr(list, '/');
if (shortlist == NULL)
shortlist = list;
else
shortlist++;
printf(banner, shortlist);
tests = read_test_list(list, source, build);
status = test_batch(tests, verbose) ? 0 : 1;
} else {
tests = build_test_list(argv, argc, source, build);
status = test_batch(tests, verbose) ? 0 : 1;
}
/* For valgrind cleanliness, free all our memory. */
if (source_env != NULL) {
putenv((char *) "C_TAP_SOURCE=");
putenv((char *) "SOURCE=");
free(c_tap_source_env);
free(source_env);
}
if (build_env != NULL) {
putenv((char *) "C_TAP_BUILD=");
putenv((char *) "BUILD=");
free(c_tap_build_env);
free(build_env);
}
exit(status);
}
|
the_stack_data/54826282.c |
typedef unsigned char __u_char;
typedef unsigned short int __u_short;
typedef unsigned int __u_int;
typedef unsigned long int __u_long;
typedef signed char __int8_t;
typedef unsigned char __uint8_t;
typedef signed short int __int16_t;
typedef unsigned short int __uint16_t;
typedef signed int __int32_t;
typedef unsigned int __uint32_t;
typedef signed long int __int64_t;
typedef unsigned long int __uint64_t;
typedef long int __quad_t;
typedef unsigned long int __u_quad_t;
typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;
typedef int __pid_t;
typedef struct {
int __val[2];
} __fsid_t;
typedef long int __clock_t;
typedef unsigned long int __rlim_t;
typedef unsigned long int __rlim64_t;
typedef unsigned int __id_t;
typedef long int __time_t;
typedef unsigned int __useconds_t;
typedef long int __suseconds_t;
typedef int __daddr_t;
typedef int __key_t;
typedef int __clockid_t;
typedef void * __timer_t;
typedef long int __blksize_t;
typedef long int __blkcnt_t;
typedef long int __blkcnt64_t;
typedef unsigned long int __fsblkcnt_t;
typedef unsigned long int __fsblkcnt64_t;
typedef unsigned long int __fsfilcnt_t;
typedef unsigned long int __fsfilcnt64_t;
typedef long int __fsword_t;
typedef long int __ssize_t;
typedef long int __syscall_slong_t;
typedef unsigned long int __syscall_ulong_t;
typedef __off64_t __loff_t;
typedef __quad_t *__qaddr_t;
typedef char *__caddr_t;
typedef long int __intptr_t;
typedef unsigned int __socklen_t;
typedef __u_char u_char;
typedef __u_short u_short;
typedef __u_int u_int;
typedef __u_long u_long;
typedef __quad_t quad_t;
typedef __u_quad_t u_quad_t;
typedef __fsid_t fsid_t;
typedef __loff_t loff_t;
typedef __ino_t ino_t;
typedef __dev_t dev_t;
typedef __gid_t gid_t;
typedef __mode_t mode_t;
typedef __nlink_t nlink_t;
typedef __uid_t uid_t;
typedef __off_t off_t;
typedef __pid_t pid_t;
typedef __id_t id_t;
typedef __ssize_t ssize_t;
typedef __daddr_t daddr_t;
typedef __caddr_t caddr_t;
typedef __key_t key_t;
typedef __clock_t clock_t;
typedef __time_t time_t;
typedef __clockid_t clockid_t;
typedef __timer_t timer_t;
typedef long unsigned int size_t;
typedef unsigned long int ulong;
typedef unsigned short int ushort;
typedef unsigned int uint;
typedef int int8_t __attribute__ ((__mode__ (__QI__)));
typedef int int16_t __attribute__ ((__mode__ (__HI__)));
typedef int int32_t __attribute__ ((__mode__ (__SI__)));
typedef int int64_t __attribute__ ((__mode__ (__DI__)));
typedef unsigned int u_int8_t __attribute__ ((__mode__ (__QI__)));
typedef unsigned int u_int16_t __attribute__ ((__mode__ (__HI__)));
typedef unsigned int u_int32_t __attribute__ ((__mode__ (__SI__)));
typedef unsigned int u_int64_t __attribute__ ((__mode__ (__DI__)));
typedef int register_t __attribute__ ((__mode__ (__word__)));
static __inline unsigned int
__bswap_32 (unsigned int __bsx)
{
return __builtin_bswap32 (__bsx);
}
static __inline __uint64_t
__bswap_64 (__uint64_t __bsx)
{
return __builtin_bswap64 (__bsx);
}
typedef int __sig_atomic_t;
typedef struct
{
unsigned long int __val[(1024 / (8 * sizeof (unsigned long int)))];
} __sigset_t;
typedef __sigset_t sigset_t;
struct timespec
{
__time_t tv_sec;
__syscall_slong_t tv_nsec;
};
struct timeval
{
__time_t tv_sec;
__suseconds_t tv_usec;
};
typedef __suseconds_t suseconds_t;
typedef long int __fd_mask;
typedef struct
{
__fd_mask __fds_bits[1024 / (8 * (int) sizeof (__fd_mask))];
} fd_set;
typedef __fd_mask fd_mask;
extern int select (int __nfds, fd_set *__restrict __readfds,
fd_set *__restrict __writefds,
fd_set *__restrict __exceptfds,
struct timeval *__restrict __timeout);
extern int pselect (int __nfds, fd_set *__restrict __readfds,
fd_set *__restrict __writefds,
fd_set *__restrict __exceptfds,
const struct timespec *__restrict __timeout,
const __sigset_t *__restrict __sigmask);
__extension__
extern unsigned int gnu_dev_major (unsigned long long int __dev)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
__extension__
extern unsigned int gnu_dev_minor (unsigned long long int __dev)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
__extension__
extern unsigned long long int gnu_dev_makedev (unsigned int __major,
unsigned int __minor)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
typedef __blksize_t blksize_t;
typedef __blkcnt_t blkcnt_t;
typedef __fsblkcnt_t fsblkcnt_t;
typedef __fsfilcnt_t fsfilcnt_t;
typedef unsigned long int pthread_t;
union pthread_attr_t
{
char __size[56];
long int __align;
};
typedef union pthread_attr_t pthread_attr_t;
typedef struct __pthread_internal_list
{
struct __pthread_internal_list *__prev;
struct __pthread_internal_list *__next;
} __pthread_list_t;
typedef union
{
struct __pthread_mutex_s
{
int __lock;
unsigned int __count;
int __owner;
unsigned int __nusers;
int __kind;
short __spins;
short __elision;
__pthread_list_t __list;
} __data;
char __size[40];
long int __align;
} pthread_mutex_t;
typedef union
{
char __size[4];
int __align;
} pthread_mutexattr_t;
typedef union
{
struct
{
int __lock;
unsigned int __futex;
__extension__ unsigned long long int __total_seq;
__extension__ unsigned long long int __wakeup_seq;
__extension__ unsigned long long int __woken_seq;
void *__mutex;
unsigned int __nwaiters;
unsigned int __broadcast_seq;
} __data;
char __size[48];
__extension__ long long int __align;
} pthread_cond_t;
typedef union
{
char __size[4];
int __align;
} pthread_condattr_t;
typedef unsigned int pthread_key_t;
typedef int pthread_once_t;
typedef union
{
struct
{
int __lock;
unsigned int __nr_readers;
unsigned int __readers_wakeup;
unsigned int __writer_wakeup;
unsigned int __nr_readers_queued;
unsigned int __nr_writers_queued;
int __writer;
int __shared;
unsigned long int __pad1;
unsigned long int __pad2;
unsigned int __flags;
} __data;
char __size[56];
long int __align;
} pthread_rwlock_t;
typedef union
{
char __size[8];
long int __align;
} pthread_rwlockattr_t;
typedef volatile int pthread_spinlock_t;
typedef union
{
char __size[32];
long int __align;
} pthread_barrier_t;
typedef union
{
char __size[4];
int __align;
} pthread_barrierattr_t;
struct iovec
{
void *iov_base;
size_t iov_len;
};
extern ssize_t readv (int __fd, const struct iovec *__iovec, int __count)
;
extern ssize_t writev (int __fd, const struct iovec *__iovec, int __count)
;
extern ssize_t preadv (int __fd, const struct iovec *__iovec, int __count,
__off_t __offset) ;
extern ssize_t pwritev (int __fd, const struct iovec *__iovec, int __count,
__off_t __offset) ;
typedef __socklen_t socklen_t;
enum __socket_type
{
SOCK_STREAM = 1,
SOCK_DGRAM = 2,
SOCK_RAW = 3,
SOCK_RDM = 4,
SOCK_SEQPACKET = 5,
SOCK_DCCP = 6,
SOCK_PACKET = 10,
SOCK_CLOEXEC = 02000000,
SOCK_NONBLOCK = 00004000
};
typedef unsigned short int sa_family_t;
struct sockaddr
{
sa_family_t sa_family;
char sa_data[14];
};
struct sockaddr_storage
{
sa_family_t ss_family;
unsigned long int __ss_align;
char __ss_padding[(128 - (2 * sizeof (unsigned long int)))];
};
enum
{
MSG_OOB = 0x01,
MSG_PEEK = 0x02,
MSG_DONTROUTE = 0x04,
MSG_CTRUNC = 0x08,
MSG_PROXY = 0x10,
MSG_TRUNC = 0x20,
MSG_DONTWAIT = 0x40,
MSG_EOR = 0x80,
MSG_WAITALL = 0x100,
MSG_FIN = 0x200,
MSG_SYN = 0x400,
MSG_CONFIRM = 0x800,
MSG_RST = 0x1000,
MSG_ERRQUEUE = 0x2000,
MSG_NOSIGNAL = 0x4000,
MSG_MORE = 0x8000,
MSG_WAITFORONE = 0x10000,
MSG_FASTOPEN = 0x20000000,
MSG_CMSG_CLOEXEC = 0x40000000
};
struct msghdr
{
void *msg_name;
socklen_t msg_namelen;
struct iovec *msg_iov;
size_t msg_iovlen;
void *msg_control;
size_t msg_controllen;
int msg_flags;
};
struct cmsghdr
{
size_t cmsg_len;
int cmsg_level;
int cmsg_type;
__extension__ unsigned char __cmsg_data [];
};
extern struct cmsghdr *__cmsg_nxthdr (struct msghdr *__mhdr,
struct cmsghdr *__cmsg) __attribute__ ((__nothrow__ , __leaf__));
enum
{
SCM_RIGHTS = 0x01
};
struct linger
{
int l_onoff;
int l_linger;
};
struct osockaddr
{
unsigned short int sa_family;
unsigned char sa_data[14];
};
enum
{
SHUT_RD = 0,
SHUT_WR,
SHUT_RDWR
};
extern int socket (int __domain, int __type, int __protocol) __attribute__ ((__nothrow__ , __leaf__));
extern int socketpair (int __domain, int __type, int __protocol,
int __fds[2]) __attribute__ ((__nothrow__ , __leaf__));
extern int bind (int __fd, const struct sockaddr * __addr, socklen_t __len)
__attribute__ ((__nothrow__ , __leaf__));
extern int getsockname (int __fd, struct sockaddr *__restrict __addr,
socklen_t *__restrict __len) __attribute__ ((__nothrow__ , __leaf__));
extern int connect (int __fd, const struct sockaddr * __addr, socklen_t __len);
extern int getpeername (int __fd, struct sockaddr *__restrict __addr,
socklen_t *__restrict __len) __attribute__ ((__nothrow__ , __leaf__));
extern ssize_t send (int __fd, const void *__buf, size_t __n, int __flags);
extern ssize_t recv (int __fd, void *__buf, size_t __n, int __flags);
extern ssize_t sendto (int __fd, const void *__buf, size_t __n,
int __flags, const struct sockaddr * __addr,
socklen_t __addr_len);
extern ssize_t recvfrom (int __fd, void *__restrict __buf, size_t __n,
int __flags, struct sockaddr *__restrict __addr,
socklen_t *__restrict __addr_len);
extern ssize_t sendmsg (int __fd, const struct msghdr *__message,
int __flags);
extern ssize_t recvmsg (int __fd, struct msghdr *__message, int __flags);
extern int getsockopt (int __fd, int __level, int __optname,
void *__restrict __optval,
socklen_t *__restrict __optlen) __attribute__ ((__nothrow__ , __leaf__));
extern int setsockopt (int __fd, int __level, int __optname,
const void *__optval, socklen_t __optlen) __attribute__ ((__nothrow__ , __leaf__));
extern int listen (int __fd, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int accept (int __fd, struct sockaddr *__restrict __addr,
socklen_t *__restrict __addr_len);
extern int shutdown (int __fd, int __how) __attribute__ ((__nothrow__ , __leaf__));
extern int sockatmark (int __fd) __attribute__ ((__nothrow__ , __leaf__));
extern int isfdtype (int __fd, int __fdtype) __attribute__ ((__nothrow__ , __leaf__));
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long int uint64_t;
typedef signed char int_least8_t;
typedef short int int_least16_t;
typedef int int_least32_t;
typedef long int int_least64_t;
typedef unsigned char uint_least8_t;
typedef unsigned short int uint_least16_t;
typedef unsigned int uint_least32_t;
typedef unsigned long int uint_least64_t;
typedef signed char int_fast8_t;
typedef long int int_fast16_t;
typedef long int int_fast32_t;
typedef long int int_fast64_t;
typedef unsigned char uint_fast8_t;
typedef unsigned long int uint_fast16_t;
typedef unsigned long int uint_fast32_t;
typedef unsigned long int uint_fast64_t;
typedef long int intptr_t;
typedef unsigned long int uintptr_t;
typedef long int intmax_t;
typedef unsigned long int uintmax_t;
enum
{
IPPROTO_IP = 0,
IPPROTO_HOPOPTS = 0,
IPPROTO_ICMP = 1,
IPPROTO_IGMP = 2,
IPPROTO_IPIP = 4,
IPPROTO_TCP = 6,
IPPROTO_EGP = 8,
IPPROTO_PUP = 12,
IPPROTO_UDP = 17,
IPPROTO_IDP = 22,
IPPROTO_TP = 29,
IPPROTO_DCCP = 33,
IPPROTO_IPV6 = 41,
IPPROTO_ROUTING = 43,
IPPROTO_FRAGMENT = 44,
IPPROTO_RSVP = 46,
IPPROTO_GRE = 47,
IPPROTO_ESP = 50,
IPPROTO_AH = 51,
IPPROTO_ICMPV6 = 58,
IPPROTO_NONE = 59,
IPPROTO_DSTOPTS = 60,
IPPROTO_MTP = 92,
IPPROTO_ENCAP = 98,
IPPROTO_PIM = 103,
IPPROTO_COMP = 108,
IPPROTO_SCTP = 132,
IPPROTO_UDPLITE = 136,
IPPROTO_RAW = 255,
IPPROTO_MAX
};
typedef uint16_t in_port_t;
enum
{
IPPORT_ECHO = 7,
IPPORT_DISCARD = 9,
IPPORT_SYSTAT = 11,
IPPORT_DAYTIME = 13,
IPPORT_NETSTAT = 15,
IPPORT_FTP = 21,
IPPORT_TELNET = 23,
IPPORT_SMTP = 25,
IPPORT_TIMESERVER = 37,
IPPORT_NAMESERVER = 42,
IPPORT_WHOIS = 43,
IPPORT_MTP = 57,
IPPORT_TFTP = 69,
IPPORT_RJE = 77,
IPPORT_FINGER = 79,
IPPORT_TTYLINK = 87,
IPPORT_SUPDUP = 95,
IPPORT_EXECSERVER = 512,
IPPORT_LOGINSERVER = 513,
IPPORT_CMDSERVER = 514,
IPPORT_EFSSERVER = 520,
IPPORT_BIFFUDP = 512,
IPPORT_WHOSERVER = 513,
IPPORT_ROUTESERVER = 520,
IPPORT_RESERVED = 1024,
IPPORT_USERRESERVED = 5000
};
typedef uint32_t in_addr_t;
struct in_addr
{
in_addr_t s_addr;
};
struct in6_addr
{
union
{
uint8_t __u6_addr8[16];
uint16_t __u6_addr16[8];
uint32_t __u6_addr32[4];
} __in6_u;
};
extern const struct in6_addr in6addr_any;
extern const struct in6_addr in6addr_loopback;
struct sockaddr_in
{
sa_family_t sin_family;
in_port_t sin_port;
struct in_addr sin_addr;
unsigned char sin_zero[sizeof (struct sockaddr) -
(sizeof (unsigned short int)) -
sizeof (in_port_t) -
sizeof (struct in_addr)];
};
struct sockaddr_in6
{
sa_family_t sin6_family;
in_port_t sin6_port;
uint32_t sin6_flowinfo;
struct in6_addr sin6_addr;
uint32_t sin6_scope_id;
};
struct ip_mreq
{
struct in_addr imr_multiaddr;
struct in_addr imr_interface;
};
struct ip_mreq_source
{
struct in_addr imr_multiaddr;
struct in_addr imr_interface;
struct in_addr imr_sourceaddr;
};
struct ipv6_mreq
{
struct in6_addr ipv6mr_multiaddr;
unsigned int ipv6mr_interface;
};
struct group_req
{
uint32_t gr_interface;
struct sockaddr_storage gr_group;
};
struct group_source_req
{
uint32_t gsr_interface;
struct sockaddr_storage gsr_group;
struct sockaddr_storage gsr_source;
};
struct ip_msfilter
{
struct in_addr imsf_multiaddr;
struct in_addr imsf_interface;
uint32_t imsf_fmode;
uint32_t imsf_numsrc;
struct in_addr imsf_slist[1];
};
struct group_filter
{
uint32_t gf_interface;
struct sockaddr_storage gf_group;
uint32_t gf_fmode;
uint32_t gf_numsrc;
struct sockaddr_storage gf_slist[1];
};
struct ip_opts
{
struct in_addr ip_dst;
char ip_opts[40];
};
struct ip_mreqn
{
struct in_addr imr_multiaddr;
struct in_addr imr_address;
int imr_ifindex;
};
struct in_pktinfo
{
int ipi_ifindex;
struct in_addr ipi_spec_dst;
struct in_addr ipi_addr;
};
extern uint32_t ntohl (uint32_t __netlong) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern uint16_t ntohs (uint16_t __netshort)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern uint32_t htonl (uint32_t __hostlong)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern uint16_t htons (uint16_t __hostshort)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int bindresvport (int __sockfd, struct sockaddr_in *__sock_in) __attribute__ ((__nothrow__ , __leaf__));
extern int bindresvport6 (int __sockfd, struct sockaddr_in6 *__sock_in)
__attribute__ ((__nothrow__ , __leaf__));
typedef __builtin_va_list __gnuc_va_list;
extern void warn (const char *__format, ...)
__attribute__ ((__format__ (__printf__, 1, 2)));
extern void vwarn (const char *__format, __gnuc_va_list)
__attribute__ ((__format__ (__printf__, 1, 0)));
extern void warnx (const char *__format, ...)
__attribute__ ((__format__ (__printf__, 1, 2)));
extern void vwarnx (const char *__format, __gnuc_va_list)
__attribute__ ((__format__ (__printf__, 1, 0)));
extern void err (int __status, const char *__format, ...)
__attribute__ ((__noreturn__, __format__ (__printf__, 2, 3)));
extern void verr (int __status, const char *__format, __gnuc_va_list)
__attribute__ ((__noreturn__, __format__ (__printf__, 2, 0)));
extern void errx (int __status, const char *__format, ...)
__attribute__ ((__noreturn__, __format__ (__printf__, 2, 3)));
extern void verrx (int __status, const char *, __gnuc_va_list)
__attribute__ ((__noreturn__, __format__ (__printf__, 2, 0)));
extern void *memcpy (void *__restrict __dest, const void *__restrict __src,
size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memmove (void *__dest, const void *__src, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memccpy (void *__restrict __dest, const void *__restrict __src,
int __c, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memset (void *__s, int __c, size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int memcmp (const void *__s1, const void *__s2, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memchr (const void *__s, int __c, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strncpy (char *__restrict __dest,
const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strcat (char *__restrict __dest, const char *__restrict __src)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strncat (char *__restrict __dest, const char *__restrict __src,
size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strcmp (const char *__s1, const char *__s2)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strncmp (const char *__s1, const char *__s2, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strcoll (const char *__s1, const char *__s2)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern size_t strxfrm (char *__restrict __dest,
const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
typedef struct __locale_struct
{
struct __locale_data *__locales[13];
const unsigned short int *__ctype_b;
const int *__ctype_tolower;
const int *__ctype_toupper;
const char *__names[13];
} *__locale_t;
typedef __locale_t locale_t;
extern int strcoll_l (const char *__s1, const char *__s2, __locale_t __l)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2, 3)));
extern size_t strxfrm_l (char *__dest, const char *__src, size_t __n,
__locale_t __l) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 4)));
extern char *strdup (const char *__s)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__nonnull__ (1)));
extern char *strndup (const char *__string, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__nonnull__ (1)));
extern char *strchr (const char *__s, int __c)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *strrchr (const char *__s, int __c)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern size_t strcspn (const char *__s, const char *__reject)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern size_t strspn (const char *__s, const char *__accept)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strpbrk (const char *__s, const char *__accept)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strstr (const char *__haystack, const char *__needle)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strtok (char *__restrict __s, const char *__restrict __delim)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern char *__strtok_r (char *__restrict __s,
const char *__restrict __delim,
char **__restrict __save_ptr)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3)));
extern char *strtok_r (char *__restrict __s, const char *__restrict __delim,
char **__restrict __save_ptr)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3)));
extern size_t strlen (const char *__s)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern size_t strnlen (const char *__string, size_t __maxlen)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *strerror (int __errnum) __attribute__ ((__nothrow__ , __leaf__));
extern int strerror_r (int __errnum, char *__buf, size_t __buflen) __asm__ ("" "__xpg_strerror_r") __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__nonnull__ (2)));
extern char *strerror_l (int __errnum, __locale_t __l) __attribute__ ((__nothrow__ , __leaf__));
extern void __bzero (void *__s, size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern void bcopy (const void *__src, void *__dest, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void bzero (void *__s, size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int bcmp (const void *__s1, const void *__s2, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *index (const char *__s, int __c)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *rindex (const char *__s, int __c)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern int ffs (int __i) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int strcasecmp (const char *__s1, const char *__s2)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strncasecmp (const char *__s1, const char *__s2, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strsep (char **__restrict __stringp,
const char *__restrict __delim)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strsignal (int __sig) __attribute__ ((__nothrow__ , __leaf__));
extern char *__stpcpy (char *__restrict __dest, const char *__restrict __src)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *stpcpy (char *__restrict __dest, const char *__restrict __src)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *__stpncpy (char *__restrict __dest,
const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *stpncpy (char *__restrict __dest,
const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
typedef __gnuc_va_list va_list;
struct _IO_FILE;
typedef struct _IO_FILE FILE;
typedef struct _IO_FILE __FILE;
typedef struct
{
int __count;
union
{
unsigned int __wch;
char __wchb[4];
} __value;
} __mbstate_t;
typedef struct
{
__off_t __pos;
__mbstate_t __state;
} _G_fpos_t;
typedef struct
{
__off64_t __pos;
__mbstate_t __state;
} _G_fpos64_t;
struct _IO_jump_t;
struct _IO_FILE;
typedef void _IO_lock_t;
struct _IO_marker {
struct _IO_marker *_next;
struct _IO_FILE *_sbuf;
int _pos;
};
enum __codecvt_result
{
__codecvt_ok,
__codecvt_partial,
__codecvt_error,
__codecvt_noconv
};
struct _IO_FILE {
int _flags;
char* _IO_read_ptr;
char* _IO_read_end;
char* _IO_read_base;
char* _IO_write_base;
char* _IO_write_ptr;
char* _IO_write_end;
char* _IO_buf_base;
char* _IO_buf_end;
char *_IO_save_base;
char *_IO_backup_base;
char *_IO_save_end;
struct _IO_marker *_markers;
struct _IO_FILE *_chain;
int _fileno;
int _flags2;
__off_t _old_offset;
unsigned short _cur_column;
signed char _vtable_offset;
char _shortbuf[1];
_IO_lock_t *_lock;
__off64_t _offset;
void *__pad1;
void *__pad2;
void *__pad3;
void *__pad4;
size_t __pad5;
int _mode;
char _unused2[15 * sizeof (int) - 4 * sizeof (void *) - sizeof (size_t)];
};
typedef struct _IO_FILE _IO_FILE;
struct _IO_FILE_plus;
extern struct _IO_FILE_plus _IO_2_1_stdin_;
extern struct _IO_FILE_plus _IO_2_1_stdout_;
extern struct _IO_FILE_plus _IO_2_1_stderr_;
typedef __ssize_t __io_read_fn (void *__cookie, char *__buf, size_t __nbytes);
typedef __ssize_t __io_write_fn (void *__cookie, const char *__buf,
size_t __n);
typedef int __io_seek_fn (void *__cookie, __off64_t *__pos, int __w);
typedef int __io_close_fn (void *__cookie);
extern int __underflow (_IO_FILE *);
extern int __uflow (_IO_FILE *);
extern int __overflow (_IO_FILE *, int);
extern int _IO_getc (_IO_FILE *__fp);
extern int _IO_putc (int __c, _IO_FILE *__fp);
extern int _IO_feof (_IO_FILE *__fp) __attribute__ ((__nothrow__ , __leaf__));
extern int _IO_ferror (_IO_FILE *__fp) __attribute__ ((__nothrow__ , __leaf__));
extern int _IO_peekc_locked (_IO_FILE *__fp);
extern void _IO_flockfile (_IO_FILE *) __attribute__ ((__nothrow__ , __leaf__));
extern void _IO_funlockfile (_IO_FILE *) __attribute__ ((__nothrow__ , __leaf__));
extern int _IO_ftrylockfile (_IO_FILE *) __attribute__ ((__nothrow__ , __leaf__));
extern int _IO_vfscanf (_IO_FILE * __restrict, const char * __restrict,
__gnuc_va_list, int *__restrict);
extern int _IO_vfprintf (_IO_FILE *__restrict, const char *__restrict,
__gnuc_va_list);
extern __ssize_t _IO_padn (_IO_FILE *, int, __ssize_t);
extern size_t _IO_sgetn (_IO_FILE *, void *, size_t);
extern __off64_t _IO_seekoff (_IO_FILE *, __off64_t, int, int);
extern __off64_t _IO_seekpos (_IO_FILE *, __off64_t, int);
extern void _IO_free_backup_area (_IO_FILE *) __attribute__ ((__nothrow__ , __leaf__));
typedef _G_fpos_t fpos_t;
extern struct _IO_FILE *stdin;
extern struct _IO_FILE *stdout;
extern struct _IO_FILE *stderr;
extern int remove (const char *__filename) __attribute__ ((__nothrow__ , __leaf__));
extern int rename (const char *__old, const char *__new) __attribute__ ((__nothrow__ , __leaf__));
extern int renameat (int __oldfd, const char *__old, int __newfd,
const char *__new) __attribute__ ((__nothrow__ , __leaf__));
extern FILE *tmpfile (void) ;
extern char *tmpnam (char *__s) __attribute__ ((__nothrow__ , __leaf__)) ;
extern char *tmpnam_r (char *__s) __attribute__ ((__nothrow__ , __leaf__)) ;
extern char *tempnam (const char *__dir, const char *__pfx)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) ;
extern int fclose (FILE *__stream);
extern int fflush (FILE *__stream);
extern int fflush_unlocked (FILE *__stream);
extern FILE *fopen (const char *__restrict __filename,
const char *__restrict __modes) ;
extern FILE *freopen (const char *__restrict __filename,
const char *__restrict __modes,
FILE *__restrict __stream) ;
extern FILE *fdopen (int __fd, const char *__modes) __attribute__ ((__nothrow__ , __leaf__)) ;
extern FILE *fmemopen (void *__s, size_t __len, const char *__modes)
__attribute__ ((__nothrow__ , __leaf__)) ;
extern FILE *open_memstream (char **__bufloc, size_t *__sizeloc) __attribute__ ((__nothrow__ , __leaf__)) ;
extern void setbuf (FILE *__restrict __stream, char *__restrict __buf) __attribute__ ((__nothrow__ , __leaf__));
extern int setvbuf (FILE *__restrict __stream, char *__restrict __buf,
int __modes, size_t __n) __attribute__ ((__nothrow__ , __leaf__));
extern void setbuffer (FILE *__restrict __stream, char *__restrict __buf,
size_t __size) __attribute__ ((__nothrow__ , __leaf__));
extern void setlinebuf (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int fprintf (FILE *__restrict __stream,
const char *__restrict __format, ...);
extern int printf (const char *__restrict __format, ...);
extern int sprintf (char *__restrict __s,
const char *__restrict __format, ...) __attribute__ ((__nothrow__));
extern int vfprintf (FILE *__restrict __s, const char *__restrict __format,
__gnuc_va_list __arg);
extern int vprintf (const char *__restrict __format, __gnuc_va_list __arg);
extern int vsprintf (char *__restrict __s, const char *__restrict __format,
__gnuc_va_list __arg) __attribute__ ((__nothrow__));
extern int snprintf (char *__restrict __s, size_t __maxlen,
const char *__restrict __format, ...)
__attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 3, 4)));
extern int vsnprintf (char *__restrict __s, size_t __maxlen,
const char *__restrict __format, __gnuc_va_list __arg)
__attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 3, 0)));
extern int vdprintf (int __fd, const char *__restrict __fmt,
__gnuc_va_list __arg)
__attribute__ ((__format__ (__printf__, 2, 0)));
extern int dprintf (int __fd, const char *__restrict __fmt, ...)
__attribute__ ((__format__ (__printf__, 2, 3)));
extern int fscanf (FILE *__restrict __stream,
const char *__restrict __format, ...) ;
extern int scanf (const char *__restrict __format, ...) ;
extern int sscanf (const char *__restrict __s,
const char *__restrict __format, ...) __attribute__ ((__nothrow__ , __leaf__));
extern int fscanf (FILE *__restrict __stream, const char *__restrict __format, ...) __asm__ ("" "__isoc99_fscanf")
;
extern int scanf (const char *__restrict __format, ...) __asm__ ("" "__isoc99_scanf")
;
extern int sscanf (const char *__restrict __s, const char *__restrict __format, ...) __asm__ ("" "__isoc99_sscanf") __attribute__ ((__nothrow__ , __leaf__))
;
extern int vfscanf (FILE *__restrict __s, const char *__restrict __format,
__gnuc_va_list __arg)
__attribute__ ((__format__ (__scanf__, 2, 0))) ;
extern int vscanf (const char *__restrict __format, __gnuc_va_list __arg)
__attribute__ ((__format__ (__scanf__, 1, 0))) ;
extern int vsscanf (const char *__restrict __s,
const char *__restrict __format, __gnuc_va_list __arg)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__format__ (__scanf__, 2, 0)));
extern int vfscanf (FILE *__restrict __s, const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vfscanf")
__attribute__ ((__format__ (__scanf__, 2, 0))) ;
extern int vscanf (const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vscanf")
__attribute__ ((__format__ (__scanf__, 1, 0))) ;
extern int vsscanf (const char *__restrict __s, const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vsscanf") __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__format__ (__scanf__, 2, 0)));
extern int fgetc (FILE *__stream);
extern int getc (FILE *__stream);
extern int getchar (void);
extern int getc_unlocked (FILE *__stream);
extern int getchar_unlocked (void);
extern int fgetc_unlocked (FILE *__stream);
extern int fputc (int __c, FILE *__stream);
extern int putc (int __c, FILE *__stream);
extern int putchar (int __c);
extern int fputc_unlocked (int __c, FILE *__stream);
extern int putc_unlocked (int __c, FILE *__stream);
extern int putchar_unlocked (int __c);
extern int getw (FILE *__stream);
extern int putw (int __w, FILE *__stream);
extern char *fgets (char *__restrict __s, int __n, FILE *__restrict __stream)
;
extern char *gets (char *__s) __attribute__ ((__deprecated__));
extern __ssize_t __getdelim (char **__restrict __lineptr,
size_t *__restrict __n, int __delimiter,
FILE *__restrict __stream) ;
extern __ssize_t getdelim (char **__restrict __lineptr,
size_t *__restrict __n, int __delimiter,
FILE *__restrict __stream) ;
extern __ssize_t getline (char **__restrict __lineptr,
size_t *__restrict __n,
FILE *__restrict __stream) ;
extern int fputs (const char *__restrict __s, FILE *__restrict __stream);
extern int puts (const char *__s);
extern int ungetc (int __c, FILE *__stream);
extern size_t fread (void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream) ;
extern size_t fwrite (const void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __s);
extern size_t fread_unlocked (void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream) ;
extern size_t fwrite_unlocked (const void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream);
extern int fseek (FILE *__stream, long int __off, int __whence);
extern long int ftell (FILE *__stream) ;
extern void rewind (FILE *__stream);
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;
extern int fgetpos (FILE *__restrict __stream, fpos_t *__restrict __pos);
extern int fsetpos (FILE *__stream, const fpos_t *__pos);
extern void clearerr (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int feof (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int ferror (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern void clearerr_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int feof_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int ferror_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern void perror (const char *__s);
extern int sys_nerr;
extern const char *const sys_errlist[];
extern int fileno (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int fileno_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern FILE *popen (const char *__command, const char *__modes) ;
extern int pclose (FILE *__stream);
extern char *ctermid (char *__s) __attribute__ ((__nothrow__ , __leaf__));
extern void flockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int ftrylockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
typedef struct HAllocator_ {
void* (*alloc)(struct HAllocator_* allocator, size_t size);
void* (*realloc)(struct HAllocator_* allocator, void* ptr, size_t size);
void (*free)(struct HAllocator_* allocator, void* ptr);
} HAllocator;
typedef struct HArena_ HArena ;
HArena *h_new_arena(HAllocator* allocator, size_t block_size);
void* h_arena_malloc(HArena *arena, size_t count) __attribute__(( malloc, alloc_size(2) ));
void h_arena_free(HArena *arena, void* ptr);
void h_delete_arena(HArena *arena);
typedef struct {
size_t used;
size_t wasted;
} HArenaStats;
void h_allocator_stats(HArena *arena, HArenaStats *stats);
typedef int bool;
typedef struct HParseState_ HParseState;
typedef enum HParserBackend_ {
PB_MIN = 0,
PB_PACKRAT = PB_MIN,
PB_REGULAR,
PB_LLk,
PB_LALR,
PB_GLR,
PB_MAX = PB_GLR
} HParserBackend;
typedef enum HTokenType_ {
TT_NONE = 1,
TT_BYTES = 2,
TT_SINT = 4,
TT_UINT = 8,
TT_SEQUENCE = 16,
TT_RESERVED_1,
TT_ERR = 32,
TT_USER = 64,
TT_MAX
} HTokenType;
typedef struct HCountedArray_ {
size_t capacity;
size_t used;
HArena * arena;
struct HParsedToken_ **elements;
} HCountedArray;
typedef struct HBytes_ {
const uint8_t *token;
size_t len;
} HBytes;
typedef struct HParsedToken_ {
HTokenType token_type;
union {
HBytes bytes;
int64_t sint;
uint64_t uint;
double dbl;
float flt;
HCountedArray *seq;
void *user;
};
size_t index;
char bit_offset;
} HParsedToken;
typedef struct HParseResult_ {
const HParsedToken *ast;
int64_t bit_length;
HArena * arena;
} HParseResult;
typedef struct HBitWriter_ HBitWriter;
typedef HParsedToken* (*HAction)(const HParseResult *p, void* user_data);
typedef bool (*HPredicate)(HParseResult *p, void* user_data);
typedef struct HCFChoice_ HCFChoice;
typedef struct HRVMProg_ HRVMProg;
typedef struct HParserVtable_ HParserVtable;
typedef struct HParser_ {
const HParserVtable *vtable;
HParserBackend backend;
void* backend_data;
void *env;
HCFChoice *desugared;
const char *name;
} HParser;
typedef struct HParserTestcase_ {
unsigned char* input;
size_t length;
char* output_unambiguous;
} HParserTestcase;
typedef struct HCaseResult_ {
bool success;
union {
const char* actual_results;
size_t parse_time;
};
} HCaseResult;
typedef struct HBackendResults_ {
HParserBackend backend;
bool compile_success;
size_t n_testcases;
size_t failed_testcases;
HCaseResult *cases;
} HBackendResults;
typedef struct HBenchmarkResults_ {
size_t len;
HBackendResults *results;
} HBenchmarkResults;
HParseResult* h_parse(const HParser* parser, const uint8_t* input, size_t length);
HParseResult* h_parse__m(HAllocator* mm__, const HParser* parser, const uint8_t* input, size_t length);
HParseResult* h_parse_error(const HParser *parser, const uint8_t* input, size_t length, FILE *error_fd);
HParseResult* h_parse_error__m(HAllocator* mm__, const HParser *parser, const uint8_t* input, size_t length, FILE *error_fd);
HParser* h_token(const uint8_t *str, const size_t len);
HParser* h_token__m(HAllocator* mm__, const uint8_t *str, const size_t len);
HParser* h_ch(const uint8_t c);
HParser* h_ch__m(HAllocator* mm__, const uint8_t c);
HParser* h_ch_range(const uint8_t lower, const uint8_t upper);
HParser* h_ch_range__m(HAllocator* mm__, const uint8_t lower, const uint8_t upper);
HParser* h_int_range(const HParser *p, const int64_t lower, const int64_t upper);
HParser* h_int_range__m(HAllocator* mm__, const HParser *p, const int64_t lower, const int64_t upper);
HParser * h_strint(const int signed);
HParser * h_strint__m(HAllocator* mm__, const int signed);
HParser* h_bits(size_t len, bool sign);
HParser* h_bits__m(HAllocator* mm__, size_t len, bool sign);
HParser* h_int64(void);
HParser* h_int64__m(HAllocator* mm__);
HParser* h_int32(void);
HParser* h_int32__m(HAllocator* mm__);
HParser* h_int16(void);
HParser* h_int16__m(HAllocator* mm__);
HParser* h_int8(void);
HParser* h_int8__m(HAllocator* mm__);
HParser* h_uint64(void);
HParser* h_uint64__m(HAllocator* mm__);
HParser* h_uint32(void);
HParser* h_uint32__m(HAllocator* mm__);
HParser* h_uint16(void);
HParser* h_uint16__m(HAllocator* mm__);
HParser* h_uint8(void);
HParser* h_uint8__m(HAllocator* mm__);
HParser* h_whitespace(const HParser* p);
HParser* h_whitespace__m(HAllocator* mm__, const HParser* p);
HParser* h_left(const HParser* p, const HParser* q);
HParser* h_left__m(HAllocator* mm__, const HParser* p, const HParser* q);
HParser* h_right(const HParser* p, const HParser* q);
HParser* h_right__m(HAllocator* mm__, const HParser* p, const HParser* q);
HParser* h_middle(const HParser* p, const HParser* x, const HParser* q);
HParser* h_middle__m(HAllocator* mm__, const HParser* p, const HParser* x, const HParser* q);
HParser* h_action(const HParser* p, const HAction a, void* user_data);
HParser* h_action__m(HAllocator* mm__, const HParser* p, const HAction a, void* user_data);
HParser* h_in(const uint8_t *charset, size_t length);
HParser* h_in__m(HAllocator* mm__, const uint8_t *charset, size_t length);
HParser* h_not_in(const uint8_t *charset, size_t length);
HParser* h_not_in__m(HAllocator* mm__, const uint8_t *charset, size_t length);
HParser* h_end_p(void);
HParser* h_end_p__m(HAllocator* mm__);
HParser* h_nothing_p(void);
HParser* h_nothing_p__m(HAllocator* mm__);
HParser* h_sequence(HParser* p, ...) __attribute__((sentinel));
HParser* h_sequence__m(HAllocator* mm__, HParser* p, ...) __attribute__((sentinel));
HParser* h_sequence__mv(HAllocator* mm__, HParser* p, va_list ap);
HParser* h_sequence__v(HParser* p, va_list ap);
HParser* h_sequence__a(void *args[]);
HParser* h_sequence__ma(HAllocator *mm__, void *args[]);
HParser* h_choice(HParser* p, ...) __attribute__((sentinel));
HParser* h_choice__m(HAllocator* mm__, HParser* p, ...) __attribute__((sentinel));
HParser* h_choice__mv(HAllocator* mm__, HParser* p, va_list ap);
HParser* h_choice__v(HParser* p, va_list ap);
HParser* h_choice__a(void *args[]);
HParser* h_choice__ma(HAllocator *mm__, void *args[]);
HParser* h_butnot(const HParser* p1, const HParser* p2);
HParser* h_butnot__m(HAllocator* mm__, const HParser* p1, const HParser* p2);
HParser* h_difference(const HParser* p1, const HParser* p2);
HParser* h_difference__m(HAllocator* mm__, const HParser* p1, const HParser* p2);
HParser* h_xor(const HParser* p1, const HParser* p2);
HParser* h_xor__m(HAllocator* mm__, const HParser* p1, const HParser* p2);
HParser* h_many(const HParser* p);
HParser* h_many__m(HAllocator* mm__, const HParser* p);
HParser* h_many1(const HParser* p);
HParser* h_many1__m(HAllocator* mm__, const HParser* p);
HParser* h_repeat_n(const HParser* p, const size_t n);
HParser* h_repeat_n__m(HAllocator* mm__, const HParser* p, const size_t n);
HParser* h_optional(const HParser* p);
HParser* h_optional__m(HAllocator* mm__, const HParser* p);
HParser* h_ignore(const HParser* p);
HParser* h_ignore__m(HAllocator* mm__, const HParser* p);
HParser* h_sepBy(const HParser* p, const HParser* sep);
HParser* h_sepBy__m(HAllocator* mm__, const HParser* p, const HParser* sep);
HParser* h_sepBy1(const HParser* p, const HParser* sep);
HParser* h_sepBy1__m(HAllocator* mm__, const HParser* p, const HParser* sep);
HParser* h_epsilon_p(void);
HParser* h_epsilon_p__m(HAllocator* mm__);
HParser* h_length_value(const HParser* length, const HParser* value);
HParser* h_length_value__m(HAllocator* mm__, const HParser* length, const HParser* value);
HParser* h_attr_bool(const HParser* p, HPredicate pred, void* user_data);
HParser* h_attr_bool__m(HAllocator* mm__, const HParser* p, HPredicate pred, void* user_data);
HParser* h_and(const HParser* p);
HParser* h_and__m(HAllocator* mm__, const HParser* p);
HParser* h_not(const HParser* p);
HParser* h_not__m(HAllocator* mm__, const HParser* p);
HParser* h_indirect(void);
HParser* h_indirect__m(HAllocator* mm__);
void h_bind_indirect(HParser* indirect, const HParser* inner);
void h_bind_indirect__m(HAllocator* mm__, HParser* indirect, const HParser* inner);
void h_parse_result_free(HParseResult *result);
void h_parse_result_free__m(HAllocator* mm__, HParseResult *result);
char* h_write_result_unamb(const HParsedToken* tok);
void h_pprint(FILE* stream, const HParsedToken* tok, int indent, int delta);
HParser * h_name(const char *name, HParser *p);
HParser * h_trace(FILE *file, const char*prefix,HParser *p);
HParser * h_trace__m(HAllocator* mm__, FILE *file, const char*prefix,HParser *p);
int h_compile(HParser* parser, HParserBackend backend, const void* params);
int h_compile__m(HAllocator* mm__, HParser* parser, HParserBackend backend, const void* params);
HBitWriter *h_bit_writer_new(HAllocator* mm__);
void h_bit_writer_put(HBitWriter* w, uint64_t data, size_t nbits);
const uint8_t* h_bit_writer_get_buffer(HBitWriter* w, size_t *len);
void h_bit_writer_free(HBitWriter* w);
HParsedToken *h_act_first(const HParseResult *p, void* userdata);
HParsedToken *h_act_second(const HParseResult *p, void* userdata);
HParsedToken *h_act_last(const HParseResult *p, void* userdata);
HParsedToken *h_act_flatten(const HParseResult *p, void* userdata);
HParsedToken *h_act_ignore(const HParseResult *p, void* userdata);
HBenchmarkResults * h_benchmark(HParser* parser, HParserTestcase* testcases);
HBenchmarkResults * h_benchmark__m(HAllocator* mm__, HParser* parser, HParserTestcase* testcases);
void h_benchmark_report(FILE* stream, HBenchmarkResults* results);
int h_allocate_token_type(const char* name);
int h_get_token_type_number(const char* name);
const char* h_get_token_type_name(int token_type);
|
the_stack_data/125141602.c | /* selection sort */
void selection_sort(int * arr, int n) {
int min, pos, temp;
for ( int i=0; i<n-1; i++ ) {
min=arr[i];
for ( int j=i+1; j<n; j++ ) {
if ( arr[j]<min ) {
min=arr[j];
pos=j;
}
}
temp=arr[i];
arr[i]=arr[pos];
arr[pos]=temp;
}
}
|
the_stack_data/139829.c | // File: 8.19-Tao.c
// Author: TaoKY
#include <stdio.h>
#define SIZE 100000
char memoryPoll[SIZE];
char *pos = memoryPoll;
// Well, @iBug is too angry at this problem...
// In fact, K&R's book has the solution to the problem.
// But Tan's ambiguous words really make the problem very confusing.
void *new(int n);
void free(void *p);
int main(){
// nothing to do
return 0;
}
void *new(int n){
if (n >= 0 && pos + n <= memoryPoll + SIZE){
char *res = pos;
pos += n;
return (void *)res;
}
else
return NULL;
}
void free(void *p){
if ((char *)p >= memoryPoll && (char *)p < memoryPoll + SIZE)
pos = (char *)p;
}
|
the_stack_data/3264045.c | /*
* Warning - this relies heavily on the TLI implementation in PTX 2.X and will
* probably not work under PTX 4.
*
* Author: Tim Wright, Sequent Computer Systems Ltd., UK.
*
* Modified slightly to conform to the new internal interfaces - Wietse
*/
#ifndef lint
static char sccsid[] = "@(#) tli-sequent.c 1.1 94/12/28 17:42:51";
#endif
#ifdef TLI_SEQUENT
/* System libraries. */
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/tiuser.h>
#include <sys/stream.h>
#include <sys/stropts.h>
#include <sys/tihdr.h>
#include <sys/timod.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <syslog.h>
#include <errno.h>
#include <string.h>
extern int errno;
extern char *sys_errlist[];
extern int sys_nerr;
extern int t_errno;
extern char *t_errlist[];
extern int t_nerr;
/* Local stuff. */
#include "tcpd.h"
#include "tli-sequent.h"
/* Forward declarations. */
static char *tli_error();
static void tli_sink();
/* tli_host - determine endpoint info */
int tli_host(request)
struct request_info *request;
{
static struct sockaddr_in client;
static struct sockaddr_in server;
struct _ti_user *tli_state_ptr;
union T_primitives *TSI_prim_ptr;
struct strpeek peek;
int len;
/*
* Use DNS and socket routines for name and address conversions.
*/
sock_methods(request);
/*
* Find out the client address using getpeerinaddr(). This call is the
* TLI equivalent to getpeername() under Dynix/ptx.
*/
len = sizeof(client);
t_sync(request->fd);
if (getpeerinaddr(request->fd, &client, len) < 0) {
tcpd_warn("can't get client address: %s", tli_error());
return;
}
request->client->sin = &client;
/* Call TLI utility routine to get information on endpoint */
if ((tli_state_ptr = _t_checkfd(request->fd)) == NULL)
return;
if (tli_state_ptr->ti_servtype == T_CLTS) {
/* UDP - may need to get address the hard way */
if (client.sin_addr.s_addr == 0) {
/* The UDP endpoint is not connected so we didn't get the */
/* remote address - get it the hard way ! */
/* Look at the control part of the top message on the stream */
/* we don't want to remove it from the stream so we use I_PEEK */
peek.ctlbuf.maxlen = tli_state_ptr->ti_ctlsize;
peek.ctlbuf.len = 0;
peek.ctlbuf.buf = tli_state_ptr->ti_ctlbuf;
/* Don't even look at the data */
peek.databuf.maxlen = -1;
peek.databuf.len = 0;
peek.databuf.buf = 0;
peek.flags = 0;
switch (ioctl(request->fd, I_PEEK, &peek)) {
case -1:
tcpd_warn("can't peek at endpoint: %s", tli_error());
return;
case 0:
/* No control part - we're hosed */
tcpd_warn("can't get UDP info: %s", tli_error());
return;
default:
/* FALL THROUGH */
;
}
/* Can we even check the PRIM_type ? */
if (peek.ctlbuf.len < sizeof(long)) {
tcpd_warn("UDP control info garbage");
return;
}
TSI_prim_ptr = (union T_primitives *) peek.ctlbuf.buf;
if (TSI_prim_ptr->type != T_UNITDATA_IND) {
tcpd_warn("wrong type for UDP control info");
return;
}
/* Validate returned unitdata indication packet */
if ((peek.ctlbuf.len < sizeof(struct T_unitdata_ind)) ||
((TSI_prim_ptr->unitdata_ind.OPT_length != 0) &&
(peek.ctlbuf.len <
TSI_prim_ptr->unitdata_ind.OPT_length +
TSI_prim_ptr->unitdata_ind.OPT_offset))) {
tcpd_warn("UDP control info garbaged");
return;
}
/* Extract the address */
memcpy(&client,
peek.ctlbuf.buf + TSI_prim_ptr->unitdata_ind.SRC_offset,
TSI_prim_ptr->unitdata_ind.SRC_length);
}
request->sink = tli_sink;
}
if (getmyinaddr(request->fd, &server, len) < 0)
tcpd_warn("can't get local address: %s", tli_error());
else
request->server->sin = &server;
}
/* tli_error - convert tli error number to text */
static char *tli_error()
{
static char buf[40];
if (t_errno != TSYSERR) {
if (t_errno < 0 || t_errno >= t_nerr) {
sprintf(buf, "Unknown TLI error %d", t_errno);
return (buf);
} else {
return (t_errlist[t_errno]);
}
} else {
if (errno < 0 || errno >= sys_nerr) {
sprintf(buf, "Unknown UNIX error %d", errno);
return (buf);
} else {
return (sys_errlist[errno]);
}
}
}
/* tli_sink - absorb unreceived datagram */
static void tli_sink(fd)
int fd;
{
struct t_unitdata *unit;
int flags;
/*
* Something went wrong. Absorb the datagram to keep inetd from looping.
* Allocate storage for address, control and data. If that fails, sleep
* for a couple of seconds in an attempt to keep inetd from looping too
* fast.
*/
if ((unit = (struct t_unitdata *) t_alloc(fd, T_UNITDATA, T_ALL)) == 0) {
tcpd_warn("t_alloc: %s", tli_error());
sleep(5);
} else {
(void) t_rcvudata(fd, unit, &flags);
t_free((void *) unit, T_UNITDATA);
}
}
#endif /* TLI_SEQUENT */
|
the_stack_data/95450821.c | #include <stdio.h>
int main(void)
/*(*/
{
/*int n, int n2, int n3;*/
int n, n2, n3;
n = 5;
n2 = n * n;
/*n3 = n2 * n2;*/
n3 = n2 * n;
/*printf("n = %d, n squared = %d, n cubed = %d\n", n, n2, n3);*/
printf("n = %d, n squared = %d, n cubed = %d\n", n, n2, n3);
return 0;
/*)*/
} |
the_stack_data/58452.c | #include <stdio.h>
// 尼克彻斯定理
// 任何一个大于 2 的整数的立方都可以表示成一串连续奇数的和,这些奇数一定是要连续的
//
// 首项: first = num*num-num+1
// 第n项: An = first + n*2
// 多项和: Sn = n*first + n*(n-1)*2/2
int main(){
int num,end;
_Bool turn = 1;
int an,sn=0;
int i=0,g;
int anlist[100];
printf("input: ");
scanf("%d",&num);
end = num*num*num;
while( turn ){
an = (num*num-num+1) + i*2;
sn += an;
anlist[i++] = an;
if( end == sn ){
break;
}
}
if(i<=3){
printf("%d = %d + %d + %d",end,anlist[0],anlist[1],anlist[2]);
}
else if(i>3){
printf("%d = %d + %d ... + %d",end,anlist[0],anlist[1],anlist[i-1]);
}
return 0;
}
|
the_stack_data/29826388.c |
/* stringtest.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <malloc.h>
#include <stdbool.h>
void chartest(char *str, int i)
{
printf("Char: %c \n", str[i]);
}
void test(char *str)
{
printf("Char: %c \n", *str+3);
}
/* Token */
typedef struct {
char *toktype ;
char value[20];
} Token;
Token *maketok(char *str, char val[20])
{
Token *atok;
atok = (Token *) malloc(sizeof(Token));
atok->toktype = str;
memcpy(atok->value, val, 20);
return atok;
}
void printtok(Token *tok)
{
printf("Token type: %s \n", tok->toktype) ;
printf("Token value: %s \n", tok->value);
}
int main()
{
char *str = "012345678" ;
chartest(str, 0);
chartest(str, 4);
test(str);
char *str2 = "keyword" ;
char arr[] = {"select"};
Token *t ;
t = maketok(str2, arr);
printtok(t);
printf("arr[0] %c \n", arr[0]);
printf("arr[1] %c \n", arr[1]);
printf("arr[2] %c \n", arr[2]);
free(t);
return 0;
}
|
the_stack_data/770253.c | #include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAXSIZE 254
#define DIMENTION 15
#define NUMOFFILE 100
#define FNAME_OUTPUT "./output001.txt"
#define TEMP_NUM 11
#define MITI_NUM 21
typedef struct {
char name[20];
char onso[50];
int flame;
double mcepdata[MAXSIZE][DIMENTION];
} mcepdata_t;
int main(void)
{
int h0, h, i, j, k;
FILE *fp_temp, *fp_miti, *fp_output;
mcepdata_t city_temp, city_miti;
char ch0[200];
double d[MAXSIZE][MAXSIZE];
double g[MAXSIZE][MAXSIZE];
double tangokankyori[NUMOFFILE];
double tangokankyori_min;
int num_matchfname = 0;
int count = 0;
printf("city%03dとcity%03dの認識実験を行います\n", TEMP_NUM, MITI_NUM);
for(h0 = 0; h0 < NUMOFFILE; h0++)
{
sprintf(ch0, "./city%03d/city%03d_%03d.txt", TEMP_NUM, TEMP_NUM, h0 + 1);
if((fp_temp = fopen(ch0, "r")) == NULL)
{
printf("temp file open error!\n");
exit(EXIT_FAILURE);
}
fgets(city_temp.name, sizeof(city_temp.name), fp_temp);
fgets(city_temp.onso, sizeof(city_temp.onso), fp_temp);
fgets(ch0, sizeof(ch0), fp_temp);
city_temp.flame = atoi(ch0);
for(i = 0; i < city_temp.flame; i++)
{
for(j = 0; j < DIMENTION; j++)
{
fscanf(fp_temp, "%lf", &city_temp.mcepdata[i][j]);
}
}
for(h = 0; h < NUMOFFILE; h++)
{
sprintf(ch0, "./city%03d/city%03d_%03d.txt", MITI_NUM, MITI_NUM, h + 1);
if((fp_miti = fopen(ch0, "r")) == NULL)
{
printf("miti file open error!!\n");
exit(EXIT_FAILURE);
}
fgets(city_miti.name, sizeof(city_miti.name), fp_miti);
fgets(city_miti.onso, sizeof(city_miti.onso), fp_miti);
fgets(ch0, sizeof(ch0), fp_miti);
city_miti.flame = atoi(ch0);
for(i = 0; i < city_miti.flame; i++)
{
for(j = 0; j < DIMENTION; i++)
{
fscanf(fp_miti, "%lf", &city_miti.mcepdata[i][j]);
}
}
for(i = 0; i < city_temp.flame; i++)
{
for(j = 0; j < city_miti.flame; j++)
{
d[i][j] = 0;
for(int k = 0; k < DIMENTION; k++)
{
d[i][j] += (city_temp.mcepdata[i][k] - city_miti.mcepdata[j][k]) * (city_temp.mcepdata[i][k] - city_miti.mcepdata[j][k]);
}
sqrtl(d[i][j]);
}
}
g[0][0] = d[0][0];
for(i = 1; i < city_temp.flame; i++)
{
g[i][0] = g[i - 1][0] + d[i][0];
}
for(j = 1; j < city_miti.flame; j++)
{
g[0][j] = g[0][j - 1] + d[0][j];
}
for(i = 1; i < city_temp.flame; i++)
{
for(j = 1; j < city_miti.flame; j++)
{
double a = g[i][j - 1] + d[i][j];
double b = g[i - 1][j - 1] + 2 * d[i][j];
double c = g[i - 1][j] + d[i][j];
g[i][j] = a;
if(b < g[i][j])
{
g[i][j] = b;
}
if(c < g[i][j])
{
g[i][j] = c;
}
}
}
tangokankyori[h] = g[city_temp.flame - 1][city_miti.flame - 1] / (city_temp.flame + city_miti.flame);
fclose(fp_miti);
}
tangokankyori_min = tangokankyori[0];
num_matchfname = 0;
for(h = 1; h < NUMOFFILE; h++)
{
if(tangokankyori_min > tangokankyori[h])
{
tangokankyori_min = tangokankyori[h];
num_matchfname = h;
}
}
fclose(fp_temp);
if(num_matchfname == h0)
{
count++;
}
if(num_matchfname != h0)
{
printf("----------Result NOT Matching----------\n");
printf("city_temp : city%03d/city%03d_%03d.txt\n", TEMP_NUM, TEMP_NUM, h0 + 1);
printf("city_miti : city%03d_city%03d_%03d.txt\n", MITI_NUM, MITI_NUM, num_matchfname + 1);
printf("tangokankyori : %f\n", tangokankyori_min);
}
}
sprintf(ch0, FNAME_OUTPUT);
if((fp_output = fopen(ch0, "a")) == NULL)
{
printf("output file open error!!\n");
exit(EXIT_FAILURE);
}
fprintf(fp_output, "正解率%d%%です\n", count);
printf("\nファイルを作成しました\n");
printf("正答率 %d%% です\n", count);
fclose(fp_output);
return 0;
}
|
the_stack_data/17956.c | #include <stdio.h>
#define N 10
void quicksort(int a[], int *low, int *high);
int *split(int a[], int *low, int *high);
int main(void) {
int a[N], i;
printf("Enter %d numbers to be sorted: ", N);
for (i = 0; i < N; i++)
scanf("%d", &a[i]);
quicksort(a, a, a + N - 1);
printf("In sorted order: ");
for (i = 0; i < N; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
void quicksort(int a[], int *low, int *high) {
int *middle;
if (low >= high) return;
middle = split(a, low, high);
quicksort(a, low, middle - 1);
quicksort(a, middle + 1, high);
}
int *split(int a[], int *low, int *high) {
int part_element = *low;
for (;;) {
while (low < high && part_element <= *high)
high--;
if (low >= high) break;
*low++ = *high;
while (low < high && *low <= part_element)
low++;
if (low >= high) break;
*high-- = *low;
}
*high = part_element;
return high;
}
|
the_stack_data/496836.c | /*-
* Copyright (c) 2012 Simon W. Moore
* All rights reserved.
*
* This software was developed by SRI International and the University of
* Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
* ("CTSRD"), as part of the DARPA CRASH research programme.
*
* @BERI_LICENSE_HEADER_START@
*
* Licensed to BERI Open Systems C.I.C. (BERI) under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. BERI licenses this
* file to you under the BERI Hardware-Software License, Version 1.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.beri-open-systems.org/legal/license-1-0.txt
*
* Unless required by applicable law or agreed to in writing, Work distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* @BERI_LICENSE_HEADER_END@
*/
/*****************************************************************************
* This program reads SREC format memory images and writes them to Intel
* NOR flash memory. This has been tested on FreeBSD on the CHERI processor
* for the Terasic DE4 FPGA board.
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <err.h>
#include <stdbool.h>
#include <sys/mman.h>
#include <string.h>
/*****************************************************************************
* read data files
*****************************************************************************/
static u_int8_t* read_data;
static int read_data_len = -1;
static int read_data_base_addr8b = -1;
inline
int hex2dec(int c)
{
if(c>='A')
return c - 'A' + 10;
else
return c - '0';
}
inline
int twohex(int c0, int c1)
{
return hex2dec(c0)<<4 | hex2dec(c1);
}
void
readsrec(char* fn, int savedata)
{
FILE* fp = fopen(fn,"r");
char c = 'S';
int format,len,addr;
int nextaddr = -1;
int lenmarker = 1024*1024;
int j, sum;
int b[256];
char line[600];
int linelen, linepos;
if(savedata==true)
printf("Reading from file %s\n",fn);
else
printf("Reading from file %s and not saving data\n",fn);
if(fp==NULL)
errx(1, "Failed to read %s", fn);
read_data_base_addr8b = -1;
read_data_len = 0;
while(c=='S') {
if(fgets(line, 600, fp) == NULL) {
c = ' ';
linelen = 0;
} else {
c = line[0];
linelen = strlen(line);
}
if((c=='S') && (linelen>8)) {
format = line[1] - ((int) '0');
len = twohex(line[2], line[3]);
// N.B. code would support format=1 but not tested so not enabled
if(!((format==2) || (format==3)))
errx(1, "SREC format %d not supported", format);
// collect bytes
for(j=0, linepos=4; (j<len) && (linepos<(linelen-1)) ; j++) {
b[j] = twohex(line[linepos], line[linepos+1]);
linepos += 2;
}
if(line[linepos]!='\n')
errx(1, "End of line missing, e.g. due to wrong length (len=%1d)", len);
// address according to format (big endian)
for(j=addr=0; j<=format; j++)
addr = (addr<<8) | b[j];
if(read_data_base_addr8b < 0)
read_data_base_addr8b = addr;
if((nextaddr>=0) && (addr!=nextaddr))
errx(1, "none contiguous SREC file");
nextaddr = addr+((len-1) - (format+1));
// calculate checksum including sum of checksum
for(j=0, sum=len; j<len; j++)
sum += b[j];
sum = (~sum) & 0xff;
if(sum!=0)
errx(1, "SREC checksum fail");
if(savedata==true)
for(j=format+1; j<len-1; j++) {
read_data[read_data_len] = b[j];
read_data_len++;
}
if(read_data_len > lenmarker) {
printf("Read %1d MiB\n", lenmarker>>20);
lenmarker += 1024*1024;
}
/*
printf("c=%c, format=%1d, len=%2d, addr=0x%08x",c,format,len,addr);
for(j=format+1; j<len-1; j++)
printf(" %02x", b[j]);
putchar('\n');
*/
}
}
fclose(fp);
}
/*****************************************************************************/
static int flashfd;
volatile static u_int16_t *flashmem16;
inline u_int16_t
byteswap(u_int16_t w)
{
return ((w>>8) & 0xff) | ((w & 0xff)<<8);
}
void
flash_write(u_int64_t offset, u_int16_t d)
{
flashmem16[offset] = byteswap(d);
}
u_int16_t
flash_read(u_int64_t offset)
{
return byteswap(flashmem16[offset]);
}
int
flash_read_status(int offset)
{
flash_write(offset,0x70);
return flash_read(offset);
}
void
flash_clear_status(int offset)
{
flash_write(offset,0x50);
}
void
flash_read_mode(int offset)
{
flash_write(offset,0xff);
}
void unlock_block_for_writes(int offset)
{
flash_write(offset,0x60); // lock block setup
flash_write(offset,0xd0); // unlock block
}
void lock_block_to_prevent_writes(int offset)
{
flash_write(offset,0x60); // lock block setup
flash_write(offset,0x01); // lock block
}
void
single_write(int offset, int data)
{
int j;
int status;
unlock_block_for_writes(offset);
flash_write(offset,0x40); // send write command
flash_write(offset,data);
status = flash_read_status(offset);
for(j=0; ((status & 0x80)==0) && (j<0xfff); j++)
status = flash_read_status(offset);
if((status & 0x80)==0)
warnx("ERROR on write - flash is busy even after 0x%x checks\n",j);
status = flash_read_status(offset);
if((status & (1<<3))!=0)
warnx("Vpp voltage droop error during write, aborted, status=0x%02x\n", status);
if((status & (3<<4))!=0)
warnx("Command sequence error during write, aborted, status=0x%02x\n", status);
if((status & (1<<1))!=0)
warnx("Block locked during write process, aborted, status=0x%02x\n", status);
if((status & (1<<5))!=0)
warnx("write failed at offset 0x%08x, status=0x%02x\n", offset<<1, status);
lock_block_to_prevent_writes(offset);
flash_read_mode(offset);
}
void
block_write(int addr16b, int* data) // assumes data is block of length 0x20
{
int j, f, status;
unlock_block_for_writes(addr16b);
flash_write(addr16b,0xe8); // send block write command
if((flash_read(addr16b) & 0x80)==0)
warnx("block_write to flash failed - block write not supported by device?");
flash_write(addr16b,0x1f); // write 0x20 words into buffer
for(j=0; j<0x20; j++) // write 32 words of data into buffer
flash_write(addr16b+j,data[j]);
flash_write(addr16b,0xd0); // confirm write
status = flash_read(addr16b);
for(j=0; ((status & 0x80)==0) && (j<0xfff); j++)
status = flash_read(addr16b);
if((status & 0x80)==0)
warnx("ERROR on block-write - flash is busy even after 0x%x checks\n",j);
status = flash_read_status(addr16b);
if((status & (1<<3))!=0)
warnx("Vpp voltage droop error during block-write, aborted, status=0x%02x\n", status);
if((status & (3<<4))!=0)
warnx("Command sequence error during block-write, aborted, status=0x%02x\n", status);
if((status & (1<<1))!=0)
warnx("Block locked during block-write process, aborted, status=0x%02x\n", status);
if((status & (1<<5))!=0)
warnx("Block-write failed at offset 0x%08x, status=0x%02x\n", addr16b<<1, status);
lock_block_to_prevent_writes(addr16b);
flash_read_mode(addr16b);
/*
// read check done at end so it doesn't need to be done here unless we're debugging
for(j=0; j<0x20; j++) {
f = flash_read(addr16b+j);
if(f != data[j])
warnx("Block-write failed to write[0x%08x] 0x%04x, read back 0x%04x",
(addr16b+j)<<1, data[j], f);
}
*/
}
void erase_block(int addr16b)
{
int j, status;
unlock_block_for_writes(addr16b);
flash_clear_status(addr16b);
flash_write(addr16b,0x20);
flash_write(addr16b,0xD0);
status = flash_read(addr16b);
for(j=0; ((status & 0x80)==0) && (j<10000000); j++)
status = flash_read(addr16b);
if((status & 0x80)==0)
warnx("Error on erase - flash is busy even after %1d status checks, status=0x%02x\n", j, status);
status = flash_read_status(addr16b);
if((status & (1<<3))!=0)
warnx("Vpp voltage droop error during erease, aborted, status=0x%02x\n", status);
if((status & (3<<4))!=0)
warnx("Command sequence error during erase, aborted, status=0x%02x\n", status);
if((status & (1<<1))!=0)
warnx("Block locked during erase process, aborted, status=0x%02x\n", status);
if((status & (1<<5))!=0)
warnx("Erase failed at addr16b 0x%08x, status=0x%02x\n", addr16b<<1, status);
lock_block_to_prevent_writes(addr16b);
flash_clear_status(addr16b);
flash_read_mode(addr16b);
flash_read_mode(addr16b);
j = flash_read(addr16b);
if(j!=0xffff)
warnx("Erase appears to have happened but read back 0x%04x but expecting 0xffff",j);
}
void display_device_info()
{
int j;
int r;
printf("Flash device information:\n");
flash_write(0, 0x90); // write command
printf(" manufacturer code: 0x%04x\n",flash_read(0x00));
printf(" device id code: 0x%04x\n",flash_read(0x01));
printf(" block lock config 0: 0x%04x\n",flash_read(0x02));
printf(" block lock config 1: 0x%04x\n",flash_read(0x03));
printf(" block lock config 2: 0x%04x\n",flash_read(0x04));
printf(" configuration register: 0x%04x\n",flash_read(0x05));
printf(" lock register 0: 0x%04x\n",flash_read(0x80));
printf(" lock register 1: 0x%04x\n",flash_read(0x89));
printf(" 64-bit factory program protection: 0x%04x 0x%04x 0x%04x 0x%04x\n"
,flash_read(0x84)
,flash_read(0x83)
,flash_read(0x82)
,flash_read(0x81));
printf(" 64-bit user program protection: 0x%04x 0x%04x 0x%04x 0x%04x\n"
,flash_read(0x88)
,flash_read(0x87)
,flash_read(0x86)
,flash_read(0x85));
printf(" 128-bit user program protection: 0x%04x 0x%04x 0x%04x 0x%04x\n"
,flash_read(0x88)
,flash_read(0x87)
,flash_read(0x86)
,flash_read(0x85));
for(j=0x84; j<=0x109; j+=8) {
printf("128-bit user program prot. reg[0x%04x]:",(j-0x84)/8);
for(r=7; r>0; r--)
printf(" 0x%04x",flash_read((j+r)));
putchar('\n');
}
}
int
check_memory(int report)
{
int offset16b;
for(offset16b = 0; offset16b < (read_data_len>>1); offset16b++) {
int w = read_data[offset16b<<1] | (read_data[(offset16b<<1)+1]<<8);
int addr16b = offset16b + (read_data_base_addr8b>>1);
int f = flash_read(addr16b);
if(w != f) {
if(report)
printf("memory check fail: addr=0x%08x from file: 0x%04x from flash: 0x%04x\n",
addr16b<<1, w, f);
return false;
}
}
return true;
}
// erase blocks that need to be erased
void
erase_sweep(void)
{
int offset16b;
int markpoint = 1024*1024 - 1;
int mb = 0;
printf("Beginning erase sweep\n");
for(offset16b = 0; offset16b<(read_data_len>>1); offset16b++) {
int w = read_data[offset16b<<1] | (read_data[(offset16b<<1)+1]<<8);
int addr16b = offset16b+(read_data_base_addr8b>>1);
int f = flash_read(addr16b);
if((w & f) != w) {
erase_block(addr16b);
if(flash_read(addr16b) != 0xffff)
warnx( "Flash erase doesn't appear to have erased a block");
}
if(offset16b>=markpoint) {
mb++;
markpoint += 1024*1024/2;
printf("Erase sweep passed %d MiB\n",mb);
}
}
}
void
write_sweep(void)
{
int offset16b;
int markpoint = (1024*1024/2)-1;
int mb = 0;
printf("Beginning write sweep\n");
for(offset16b = 0; offset16b<(read_data_len>>1); ) {
int addr16b = offset16b + (read_data_base_addr8b>>1);
if(((addr16b & 0x1f) == 0) && ((offset16b+0x1f)<(read_data_len>>1))) {
// write a block
int w[32];
int j, correct;
for(j=0, correct=true; (j<0x20); j++) {
int k = (offset16b+j);
w[j] = read_data[k<<1] | (read_data[(k<<1)+1]<<8);
correct &= w[j] == flash_read(addr16b+j);
}
if(!correct)
block_write(addr16b,w);
offset16b += 0x20;
} else {
// do single writes
int w = read_data[offset16b<<1] | (read_data[(offset16b<<1)+1]<<8);
int f = flash_read(addr16b);
if(w != f)
single_write(addr16b, w);
offset16b++;
}
if(offset16b>=markpoint) {
mb++;
markpoint += 1024*1024/2;
printf("Write sweep passed %d MiB\n",mb);
}
}
}
int
main(int argc, char *argv[])
{
if(argc!=2)
errx(0,"Usage: %s file.srec",argv[0]);
flashfd = open("/dev/de4flash", O_RDWR | O_NONBLOCK);
if(flashfd < 0)
err(1, "open flash");
flashmem16 = mmap(NULL, 64*1024*1024, PROT_READ | PROT_WRITE, MAP_SHARED, flashfd, 0);
if (flashmem16 == MAP_FAILED)
err(1, "mmap flash");
display_device_info();
flash_read_mode(0);
printf("flash status = 0x%02x\n", flash_read_status(0x20000));
flash_clear_status(0x20000);
printf("flash status after clear = 0x%02x\n", flash_read_status(0x20000));
flash_read_mode(0);
// could parse the file first to see what buffer size is needed but this is too slow
// readsrec(argv[1], false);
// hack - allocate more than enough memory to hold the data to be read
read_data = (u_int8_t*) malloc(64*1024*1024 * sizeof(u_int8_t));
readsrec(argv[1], true);
if(read_data_len<1)
err(1, "readsrec - read no SREC data");
printf("srec file start address=0x%08x length=0x%08x\n",
read_data_base_addr8b, read_data_len);
if(check_memory(false) == true)
printf("Memory already holds the right data - exiting...\n");
else {
erase_sweep();
write_sweep();
if(check_memory(true) == true)
printf("Flash writes complete\n");
else
errx(1,"FAILED TO WRITE DATA CORRECTLY\n");
}
return 0;
}
|
the_stack_data/206392402.c | /**
* @file
*
* @brief
*
* Copyright (c) 2013-2015 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \asf_license_stop
*/
#if (defined ENABLE_TFA) || (defined TFA_BAT_MON)
/* === INCLUDES ============================================================ */
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include "pal.h"
#include "return_val.h"
#include "tal.h"
#include "ieee_const.h"
#include "tal_constants.h"
#include "at86rf232.h"
#include "tal_internal.h"
#include "tfa.h"
/* === TYPES =============================================================== */
/* === MACROS ============================================================== */
/* Constant define for the ED scaling: register value at -35dBm */
#define CLIP_VALUE_REG (56)
/* === GLOBALS ============================================================= */
#ifdef ENABLE_TFA
/**
* TFA PIB attribute to reduce the Rx sensitivity.
* Represents the Rx sensitivity value in dBm; example: -52
*/
static int8_t tfa_pib_rx_sens;
#endif
/* === PROTOTYPES ========================================================== */
#ifdef ENABLE_TFA
static void init_tfa_pib(void);
static void write_all_tfa_pibs_to_trx(void);
#endif
/* === IMPLEMENTATION ====================================================== */
#ifdef ENABLE_TFA
/*
* \brief Gets a TFA PIB attribute
*
* This function is called to retrieve the transceiver information base
* attributes.
*
* \param[in] tfa_pib_attribute TAL infobase attribute ID
* \param[out] value TFA infobase attribute value
*
* \return MAC_UNSUPPORTED_ATTRIBUTE if the TFA infobase attribute is not found
* MAC_SUCCESS otherwise
*/
retval_t tfa_pib_get(tfa_pib_t tfa_pib_attribute, void *value)
{
switch (tfa_pib_attribute) {
case TFA_PIB_RX_SENS:
*(uint8_t *)value = tfa_pib_rx_sens;
break;
default:
/* Invalid attribute id */
return MAC_UNSUPPORTED_ATTRIBUTE;
}
return MAC_SUCCESS;
}
#endif
#ifdef ENABLE_TFA
/*
* \brief Sets a TFA PIB attribute
*
* This function is called to set the transceiver information base
* attributes.
*
* \param[in] tfa_pib_attribute TFA infobase attribute ID
* \param[in] value TFA infobase attribute value to be set
*
* \return MAC_UNSUPPORTED_ATTRIBUTE if the TFA info base attribute is not found
* TAL_BUSY if the TAL is not in TAL_IDLE state.
* MAC_SUCCESS if the attempt to set the PIB attribute was successful
*/
retval_t tfa_pib_set(tfa_pib_t tfa_pib_attribute, void *value)
{
switch (tfa_pib_attribute) {
case TFA_PIB_RX_SENS:
{
uint8_t reg_val;
tfa_pib_rx_sens = *((int8_t *)value);
if (tfa_pib_rx_sens > -49) {
reg_val = 0xF;
tfa_pib_rx_sens = -49;
} else if (tfa_pib_rx_sens <= RSSI_BASE_VAL_DBM) {
reg_val = 0x0;
tfa_pib_rx_sens = RSSI_BASE_VAL_DBM;
} else {
reg_val
= ((tfa_pib_rx_sens -
(RSSI_BASE_VAL_DBM)) / 3) + 1;
}
trx_bit_write(SR_RX_PDT_LEVEL, reg_val);
}
break;
default:
/* Invalid attribute id */
return MAC_UNSUPPORTED_ATTRIBUTE;
}
return MAC_SUCCESS;
}
#endif
#ifdef ENABLE_TFA
/*
* \brief Initializes the TFA
*
* This function is called to initialize the TFA.
*
* \return MAC_SUCCESS if everything went correct;
* FAILURE otherwise
*/
retval_t tfa_init(void)
{
init_tfa_pib();
write_all_tfa_pibs_to_trx();
return MAC_SUCCESS;
}
#endif
#ifdef ENABLE_TFA
/*
* \brief Reset the TFA
*
* This function is called to reset the TFA.
*
* \param set_default_pib Defines whether PIB values need to be set
* to its default values
*/
void tfa_reset(bool set_default_pib)
{
if (set_default_pib) {
init_tfa_pib();
}
write_all_tfa_pibs_to_trx();
}
#endif
#ifdef ENABLE_TFA
/*
* \brief Perform a CCA
*
* This function performs a CCA request.
*
* \return phy_enum_t PHY_IDLE or PHY_BUSY
*/
phy_enum_t tfa_cca_perform(void)
{
tal_trx_status_t trx_status;
uint8_t cca_status;
uint8_t cca_done;
/* Ensure that trx is not in SLEEP for register access */
do {
trx_status = set_trx_state(CMD_TRX_OFF);
} while (trx_status != TRX_OFF);
/* no interest in receiving frames while doing CCA */
trx_bit_write(SR_RX_PDT_DIS, RX_DISABLE); /* disable frame reception
* indication */
/* Set trx to rx mode. */
do {
trx_status = set_trx_state(CMD_RX_ON);
} while (trx_status != RX_ON);
/* Start CCA */
trx_bit_write(SR_CCA_REQUEST, CCA_START);
/* wait until CCA is done */
pal_timer_delay(TAL_CONVERT_SYMBOLS_TO_US(CCA_DURATION_SYM));
do {
/* poll until CCA is really done */
cca_done = trx_bit_read(SR_CCA_DONE);
} while (cca_done != CCA_COMPLETED);
set_trx_state(CMD_TRX_OFF);
/* Check if channel was idle or busy. */
if (trx_bit_read(SR_CCA_STATUS) == CCA_CH_IDLE) {
cca_status = PHY_IDLE;
} else {
cca_status = PHY_BUSY;
}
/* Enable frame reception again. */
trx_bit_write(SR_RX_PDT_DIS, RX_ENABLE);
return (phy_enum_t)cca_status;
}
#endif
#ifdef ENABLE_TFA
/*
* \brief Perform a single ED measurement
*
* \return ed_value Result of the measurement
* If the build switch TRX_REG_RAW_VALUE is defined, the transceiver's
* register value is returned.
*/
uint8_t tfa_ed_sample(void)
{
trx_irq_reason_t trx_irq_cause;
uint8_t ed_value;
tal_trx_status_t trx_status;
/* Make sure that receiver is switched on. */
do {
trx_status = set_trx_state(CMD_RX_ON);
} while (trx_status != RX_ON);
/*
* Disable the transceiver interrupts to prevent frame reception
* while performing ED scan.
*/
trx_bit_write(SR_RX_PDT_DIS, RX_DISABLE);
/* Write dummy value to start measurement. */
trx_reg_write(RG_PHY_ED_LEVEL, 0xFF);
/* Wait for ED measurement completion. */
pal_timer_delay(TAL_CONVERT_SYMBOLS_TO_US(ED_SAMPLE_DURATION_SYM));
do {
trx_irq_cause = (trx_irq_reason_t)trx_reg_read(RG_IRQ_STATUS);
} while ((trx_irq_cause & TRX_IRQ_4_CCA_ED_DONE) !=
TRX_IRQ_4_CCA_ED_DONE);
/* Read the ED Value. */
ed_value = trx_reg_read(RG_PHY_ED_LEVEL);
/* Clear IRQ register */
trx_reg_read(RG_IRQ_STATUS);
/* Enable reception agian */
trx_bit_write(SR_RX_PDT_DIS, RX_ENABLE);
/* Switch receiver off again */
set_trx_state(CMD_TRX_OFF);
#ifndef TRX_REG_RAW_VALUE
/*
* Scale ED result.
* Clip values to 0xFF if > -35dBm
*/
if (ed_value > CLIP_VALUE_REG) {
ed_value = 0xFF;
} else {
ed_value
= (uint8_t)(((uint16_t)ed_value *
0xFF) / CLIP_VALUE_REG);
}
#endif
return ed_value;
}
#endif
#if (defined ENABLE_TFA) || (defined TFA_BAT_MON)
/*
* \brief Get the transceiver's supply voltage
*
* \return mv Milli Volt; 0 if below threshold, 0xFFFF if above threshold
*/
uint16_t tfa_get_batmon_voltage(void)
{
tal_trx_status_t previous_trx_status;
uint8_t vth_val;
uint16_t mv = 1; /* 1 used as indicator flag */
bool range;
previous_trx_status = tal_trx_status;
if (tal_trx_status == TRX_SLEEP) {
set_trx_state(CMD_TRX_OFF);
}
/*
* Disable all trx interrupts.
* This needs to be done AFTER the transceiver has been woken up.
*/
pal_trx_irq_dis();
/* Check if supply voltage is within upper or lower range. */
trx_bit_write(SR_BATMON_HR, BATMON_HR_HIGH);
trx_bit_write(SR_BATMON_VTH, 0x00);
pal_timer_delay(5); /* Wait until Batmon has been settled. */
/* Check if supply voltage is within lower range */
if (trx_bit_read(SR_BATMON_OK) == BATMON_NOT_VALID) {
/* Lower range */
/* Check if supply voltage is below lower limit */
trx_bit_write(SR_BATMON_HR, BATMON_HR_LOW);
pal_timer_delay(2); /* Wait until Batmon has been settled. */
if (trx_bit_read(SR_BATMON_OK) == BATMON_NOT_VALID) {
/* below lower limit */
mv = SUPPLY_VOLTAGE_BELOW_LOWER_LIMIT;
}
range = LOW;
} else {
/* Higher range */
/* Check if supply voltage is above upper limit */
trx_bit_write(SR_BATMON_VTH, 0x0F);
pal_timer_delay(5); /* Wait until Batmon has been settled. */
if (trx_bit_read(SR_BATMON_OK) == BATMON_VALID) {
/* above upper limit */
mv = SUPPLY_VOLTAGE_ABOVE_UPPER_LIMIT;
}
range = HIGH;
}
/* Scan through the current range for the matching threshold. */
if (mv == 1) { /* 1 = indicates that voltage is within supported range
**/
vth_val = 0x0F;
for (uint8_t i = 0; i < 16; i++) {
trx_bit_write(SR_BATMON_VTH, vth_val);
pal_timer_delay(2); /* Wait until Batmon has been
* settled. */
if (trx_bit_read(SR_BATMON_OK) == BATMON_VALID) {
break;
}
vth_val--;
}
/* Calculate voltage based on register value and range. */
if (range == HIGH) {
mv = 2550 + (75 * vth_val);
} else {
mv = 1700 + (50 * vth_val);
}
}
trx_reg_read(RG_IRQ_STATUS);
/*
* Enable all trx interrupts.
* This needs to be done BEFORE putting the transceiver back to slee.
*/
pal_trx_irq_en();
if (previous_trx_status == TRX_SLEEP) {
set_trx_state(CMD_SLEEP);
}
return mv;
}
#endif /* #if (defined ENABLE_TFA) || (defined TFA_BAT_MON) */
#ifdef ENABLE_TFA
/**
* \brief Initialize the TFA PIB
*
* This function initializes the TFA information base attributes
* to their default values.
* \ingroup group_tfa
*/
static void init_tfa_pib(void)
{
tfa_pib_rx_sens = TFA_PIB_RX_SENS_DEF;
}
#endif
#ifdef ENABLE_TFA
/**
* \brief Write all shadow PIB variables to the transceiver
*
* This function writes all shadow PIB variables to the transceiver.
* It is assumed that the radio does not sleep.
* \ingroup group_tfa
*/
static void write_all_tfa_pibs_to_trx(void)
{
tfa_pib_set(TFA_PIB_RX_SENS, (void *)&tfa_pib_rx_sens);
}
#endif
#ifdef ENABLE_TFA
/*
* \brief Starts continuous transmission on current channel
*
* \param tx_mode Mode of continuous transmission (CW or PRBS)
* \param random_content Use random content if true
*/
void tfa_continuous_tx_start(continuous_tx_mode_t tx_mode, bool random_content)
{
uint8_t txcwdata[128];
trx_bit_write(SR_TX_AUTO_CRC_ON, TX_AUTO_CRC_DISABLE);
trx_reg_write(RG_TRX_STATE, CMD_TRX_OFF);
trx_bit_write(SR_TST_CTRL_DIG, TST_CONT_TX);
/* Here: use 2MBPS mode for PSD measurements.
* Omit the two following lines, if 250k mode is desired for PRBS mode.
**/
trx_reg_write(RG_TRX_CTRL_2, 0x03);
trx_reg_write(RG_RX_CTRL, 0x37);
if (tx_mode == CW_MODE) {
txcwdata[0] = 1; /* length */
/* Step 12 - frame buffer write access */
txcwdata[1] = 0x00; /* f=fch-0.5 MHz; set value to 0xFF for
* f=fch+0.5MHz */
trx_frame_write(txcwdata, 2);
} else { /* PRBS mode */
txcwdata[0] = 127; /* = max length */
for (uint8_t i = 1; i < 128; i++) {
if (random_content) {
txcwdata[i] = (uint8_t)rand();
} else {
txcwdata[i] = 0;
}
}
trx_frame_write(txcwdata, 128);
}
trx_reg_write(RG_PART_NUM, 0x54);
trx_reg_write(RG_PART_NUM, 0x46);
set_trx_state(CMD_PLL_ON);
TRX_SLP_TR_HIGH();
TRX_SLP_TR_LOW();
}
#endif
#ifdef ENABLE_TFA
/*
* \brief Stops continuous transmission
*/
void tfa_continuous_tx_stop(void)
{
tal_reset(false);
}
#endif
#endif /* #if (defined ENABLE_TFA) || (defined TFA_BAT_MON) */
/* EOF */
|
the_stack_data/20449278.c | #include<unistd.h>
void mx_printchar(char c){
write(1, &c, 1);
}
|
the_stack_data/1028251.c | #include <stdio.h>
#include <stdlib.h>
long factorial(int n) {
if(n == 0) {
// exit condition
return 1;
} else {
// recursion
return n * factorial(n-1);
}
}
long iterative_factorial(int n) {
int i = 1;
long result = 1;
while(i <= n) {
result *= i; // result = result * i
i++;
}
return result;
}
long tail_fact(int n, int iterator, long result) {
int i = iterator;
long res = result;
if(i <= n) {
res *= i;
i++;
return tail_fact(n, i, res);
}
return res;
}
int main() {
int a;
printf("Insert the number you want to evaluate the factorial of: ");
scanf("%d", &a);
long result = factorial(a);
long iterRes = iterative_factorial(a);
long tailRes = tail_fact(a, 1, 1);
printf("The factorial of %d is %ld\n", a, result);
printf("The factorial of %d is %ld\n", a, iterRes);
printf("The factorial of %d is %ld\n", a, tailRes);
return 0;
}
// cd recursion/math-es
// gcc -o fact factorial.c && ./fact
/*
Evaluates the factorial of a given number.
The return type of the funcions is 'long' since the result could be very huge.
While the user input is an int, since it could be very difficult to evaluate
the factorial of a 'long' number.
*/ |
the_stack_data/18889083.c | /* Exercise 1.23
*
* Program to remove comments from a C Program.
*
* Program should echo quotes and character constants properly
* C comments do not nest
*
*/
#include<stdio.h>
void rcomment(int c);
void incomment(void);
void echo_quote(int c);
int main(void)
{
int c,d;
printf(" To Check /* Quoted String */ \n");
while((c=getchar())!=EOF)
rcomment(c);
return 0;
}
void rcomment(int c)
{
int d;
if( c == '/')
{
if((d=getchar())=='*')
incomment();
else if( d == '/')
{
putchar(c);
rcomment(d);
}
else
{
putchar(c);
putchar(d);
}
}
else if( c == '\''|| c == '"')
echo_quote(c);
else
putchar(c);
}
void incomment()
{
int c,d;
c = getchar();
d = getchar();
while(c!='*' || d !='/')
{
c =d;
d = getchar();
}
}
void echo_quote(int c)
{
int d;
putchar(c);
while((d=getchar())!=c)
{
putchar(d);
if(d == '\\')
putchar(getchar());
}
putchar(d);
}
|
the_stack_data/18940.c | #include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <stdlib.h>
#define STUDENT 5
#define LOCATE 30
main()
{
int error=0;
int i;
char name_locater[LOCATE];
char stuname[STUDENT][LOCATE] = { "John Smith", "Paul Walker",
"Vin Diesel", "Cian Healy", "Derek Higgins"};
printf("Enter surname of the student are you looking for:\n");
scanf("%29s", name_locater);
for (i = 0; i < STUDENT; i++)
{
if (strstr(stuname[i], name_locater) != NULL)//searching for string that is the same as entered
{
printf("Found %s in our student records\n", stuname[i]);
error=1;
}//end if
}//end for
if(error==0)
{
printf("No name found try somewhere else");
}//end if printing error message
flushall();
getchar();
}//end main |
the_stack_data/90644.c | /* ACM 324 Factorial Frequencies
* mythnc
* 2011/11/18 09:13:32
* run time: 0.012
*/
#include <stdio.h>
#define MAXD 781
void init(int *, int);
int mul(int *, int);
void countdec(int *, int, int *);
void print(int, int *);
int main(void)
{
int n, count;
int seq[MAXD];
int dec[10];
while (scanf("%d", &n) && n != 0) {
init(seq, MAXD);
init(dec, 10);
count = mul(seq, n);
countdec(seq, count, dec);
print(n, dec);
}
return 0;
}
/* init: initialized s to zero */
void init(int *s, int n)
{
int i;
for (i = 0; i < n; i++)
s[i] = 0;
}
/* mul: calculate n!,
* return its digit number */
int mul(int *s, int n)
{
int i, j;
for (s[0] = 1, i = 2; i < n + 1; i++) {
for (j = 0; j < MAXD; j++)
s[j] *= i;
/* carry */
for (j = 0; j < MAXD; j++)
if (s[j] > 9) {
s[j + 1] += s[j] / 10;
s[j] %= 10;
}
}
for (i = MAXD - 1; s[i] == 0; i--)
;
return i + 1;
}
/* countdec: count 0~9 times */
void countdec(int *s, int n, int *d)
{
int i;
for (i = 0; i < n; i++)
d[s[i]]++;
}
/* print: print out result */
void print(int n, int *d)
{
int i;
printf("%d! --\n", n);
for (i = 0; i < 10; i++) {
if (i == 5)
printf("\n");
if (i != 0 && i != 5)
printf(" ");
printf(" (%d)%5d", i, d[i]);
}
printf("\n");
}
|
the_stack_data/676230.c | #include <unistd.h>
char *ft_strcpy(char *dest, char *src)
{
int s;
s = 0;
while (src[s] != '\0')
{
dest[s] = src[s];
s++;
}
dest[s] = '\0';
return (dest);
}
|
the_stack_data/36075832.c | #if defined(__linux__)
#include <stddef.h>
#include <string.h>
// NOTE!! This file must be compiled with gcc lto disabled
// using memcpy adds a dependency to glibc 2.14. instead, we want to depend on glibc 2.2.5
// to use this, add -Wl,--wrap=memcpy when linking with gcc. this will tell gcc to use __wrap_memcpy instead of memcpy
// -flto does not seem to work with this hack. must disable when compiling this source file
void* __wrap_memcpy(void* restrict to, const void* restrict from, size_t size);
__asm__(".symver memcpy, memcpy@GLIBC_2.2.5");
void* __attribute__((used)) __wrap_memcpy(void* restrict to, const void* restrict from, size_t size) {
return memcpy(to, from, size);
}
#else
// this is here to get rid of a warning for "an empty translation unit"
typedef int compilerWarningFix;
#endif
|
the_stack_data/57444.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
int days, qtdDaysWithTempLowerThenAverage;
days = 365;
float temperatureVector[days];
float higherTemperature, lowerTemperature, averageTemperature, sum;
for(int i = 0; i < days; i++) {
printf("Type the temperature of the day: ");
scanf("%f",&temperatureVector[i]);
if(i == 0) {
higherTemperature = temperatureVector[i];
lowerTemperature = temperatureVector[i];
sum = temperatureVector[i];
}
else {
if(temperatureVector[i] > higherTemperature) {
higherTemperature = temperatureVector[i];
}
if(temperatureVector[i] < lowerTemperature) {
lowerTemperature = temperatureVector[i];
}
sum = sum + temperatureVector[i];
}
}
averageTemperature = sum / days;
for(int i = 0; i < days; i++) {
if(temperatureVector[i] < averageTemperature) {
qtdDaysWithTempLowerThenAverage = qtdDaysWithTempLowerThenAverage + 1;
}
}
printf("\nLower temperature of the year: %f \n", lowerTemperature);
printf("Higher temperature of the year: %f \n", higherTemperature);
printf("Average temperature of the year: %f \n", averageTemperature);
printf("Number of Days with temperature lower then average: %i \n", qtdDaysWithTempLowerThenAverage);
}
|
the_stack_data/70302.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, S. S. Sarwar, L. Sekanina, Z. Vasicek and K. Roy, "Design of power-efficient approximate multipliers for approximate artificial neural networks," 2016 IEEE/ACM International Conference on Computer-Aided Design (ICCAD), Austin, TX, 2016, pp. 1-7. doi: 10.1145/2966986.2967021
* This file contains a circuit from a sub-set of pareto optimal circuits with respect to the pwr and ep parameters
***/
// MAE% = 0.10 %
// MAE = 4294
// WCE% = 0.20 %
// WCE = 8369
// WCRE% = 220.00 %
// EP% = 98.28 %
// MRE% = 1.84 %
// MSE = 28977.591e3
// PDK45_PWR = 0.834 mW
// PDK45_AREA = 1222.5 um2
// PDK45_DELAY = 2.08 ns
#include <stdint.h>
#include <stdlib.h>
uint64_t mul11u_0AG(uint64_t a, uint64_t b) {
int wa[11];
int wb[11];
uint64_t y = 0;
wa[0] = (a >> 0) & 0x01;
wb[0] = (b >> 0) & 0x01;
wa[1] = (a >> 1) & 0x01;
wb[1] = (b >> 1) & 0x01;
wa[2] = (a >> 2) & 0x01;
wb[2] = (b >> 2) & 0x01;
wa[3] = (a >> 3) & 0x01;
wb[3] = (b >> 3) & 0x01;
wa[4] = (a >> 4) & 0x01;
wb[4] = (b >> 4) & 0x01;
wa[5] = (a >> 5) & 0x01;
wb[5] = (b >> 5) & 0x01;
wa[6] = (a >> 6) & 0x01;
wb[6] = (b >> 6) & 0x01;
wa[7] = (a >> 7) & 0x01;
wb[7] = (b >> 7) & 0x01;
wa[8] = (a >> 8) & 0x01;
wb[8] = (b >> 8) & 0x01;
wa[9] = (a >> 9) & 0x01;
wb[9] = (b >> 9) & 0x01;
wa[10] = (a >> 10) & 0x01;
wb[10] = (b >> 10) & 0x01;
int sig_22 = wa[9] & wb[4];
int sig_27 = ~(wa[1] | wb[0]);
int sig_28 = wa[6] & wb[0];
int sig_29 = wa[7] & wb[0];
int sig_30 = wa[8] & wb[0];
int sig_31 = wa[9] & wb[0];
int sig_32 = wa[10] & wb[0];
int sig_37 = wa[4] & wb[1];
int sig_38 = wa[5] & wb[1];
int sig_39 = wa[6] & wb[1];
int sig_40 = wa[7] & wb[1];
int sig_41 = wa[8] & wb[1];
int sig_42 = wa[9] & wb[1];
int sig_43 = wa[10] & wb[1];
int sig_52 = wb[10] ^ wa[8];
int sig_53 = sig_27 & sig_37;
int sig_54 = sig_28 ^ sig_38;
int sig_55 = sig_28 & sig_38;
int sig_56 = sig_29 ^ sig_39;
int sig_57 = sig_29 & sig_39;
int sig_58 = sig_30 ^ sig_40;
int sig_59 = sig_30 & sig_40;
int sig_60 = sig_31 ^ sig_41;
int sig_61 = sig_31 & sig_41;
int sig_62 = sig_32 ^ sig_42;
int sig_63 = wb[1] & wb[3];
int sig_67 = wa[3] & wa[8];
int sig_68 = wa[4] & wb[2];
int sig_69 = wa[5] & wb[2];
int sig_70 = wa[6] & wb[2];
int sig_71 = wa[7] & wb[2];
int sig_72 = wa[8] & wb[2];
int sig_73 = wa[9] & wb[2];
int sig_74 = wa[10] & wb[2];
int sig_91 = sig_52 & sig_67;
int sig_94 = sig_91 & wb[0];
int sig_95 = sig_54 ^ sig_68;
int sig_96 = sig_54 & sig_68;
int sig_98 = sig_95 ^ sig_53;
int sig_99 = sig_96;
int sig_100 = sig_56 ^ sig_69;
int sig_101 = sig_56 & sig_69;
int sig_102 = sig_100 & sig_55;
int sig_103 = sig_100 ^ sig_55;
int sig_104 = sig_101 | sig_102;
int sig_105 = sig_58 ^ sig_70;
int sig_106 = sig_58 & sig_70;
int sig_107 = sig_105 & sig_57;
int sig_108 = sig_105 ^ sig_57;
int sig_109 = sig_106 | sig_107;
int sig_110 = sig_60 ^ sig_71;
int sig_111 = sig_60 & sig_71;
int sig_112 = wa[10] & sig_59;
int sig_113 = sig_110 ^ sig_59;
int sig_114 = sig_111 ^ sig_112;
int sig_115 = sig_62 ^ sig_72;
int sig_116 = sig_62 & sig_72;
int sig_117 = sig_115 & sig_61;
int sig_118 = sig_115 ^ sig_61;
int sig_119 = sig_116 | sig_117;
int sig_120 = sig_43 ^ sig_73;
int sig_123 = sig_120 & sig_63;
int sig_128 = wa[3] & wb[3];
int sig_129 = wa[4] & wb[3];
int sig_130 = wa[5] & wb[3];
int sig_131 = wa[6] & wb[3];
int sig_132 = wa[7] & wb[3];
int sig_133 = wa[8] & wb[3];
int sig_134 = wa[9] & wb[3];
int sig_135 = wa[10] & wb[3];
int sig_149 = wa[4] ^ wb[2];
int sig_151 = sig_98 & sig_128;
int sig_152 = sig_98 & sig_128;
int sig_154 = sig_151 ^ sig_94;
int sig_155 = sig_152;
int sig_156 = sig_103 ^ sig_129;
int sig_157 = sig_103 & sig_129;
int sig_158 = sig_156 & sig_99;
int sig_159 = sig_156 ^ sig_99;
int sig_160 = sig_157 ^ sig_158;
int sig_161 = sig_108 ^ sig_130;
int sig_162 = sig_108 & sig_130;
int sig_163 = sig_161 & sig_104;
int sig_164 = sig_161 ^ sig_104;
int sig_165 = sig_162 | sig_163;
int sig_166 = sig_113 ^ sig_131;
int sig_167 = sig_113 & sig_131;
int sig_168 = sig_166 & sig_109;
int sig_169 = sig_166 ^ sig_109;
int sig_170 = sig_167 | sig_168;
int sig_171 = sig_118 ^ sig_132;
int sig_172 = sig_118 & sig_132;
int sig_173 = wb[3] & sig_114;
int sig_174 = sig_171 ^ sig_114;
int sig_175 = sig_172 | sig_173;
int sig_176 = sig_123 ^ sig_133;
int sig_177 = sig_123 & sig_133;
int sig_178 = sig_176 & sig_119;
int sig_179 = sig_176 ^ sig_119;
int sig_180 = sig_177 | sig_178;
int sig_181 = sig_74 ^ sig_134;
int sig_182 = sig_74 & sig_134;
int sig_184 = sig_181;
int sig_185 = sig_182;
int sig_187 = wa[1] & wb[4];
int sig_188 = wa[2] & wb[4];
int sig_189 = wa[3] & wb[4];
int sig_190 = wa[4] & wb[4];
int sig_191 = wa[5] & wb[4];
int sig_192 = wa[6] & wb[4];
int sig_193 = wa[7] & wb[4];
int sig_194 = wa[8] & wb[4];
int sig_195 = wa[9] & wb[4];
int sig_196 = wa[10] & wb[4];
int sig_203 = sig_149 & sig_187;
int sig_205 = wa[0] & wa[0];
int sig_206 = sig_203;
int sig_207 = sig_154 ^ sig_188;
int sig_208 = sig_154 & sig_188;
int sig_210 = sig_207;
int sig_211 = sig_208;
int sig_212 = sig_159 ^ sig_189;
int sig_213 = sig_159 & sig_189;
int sig_215 = sig_212 ^ sig_155;
int sig_216 = sig_213;
int sig_217 = sig_164 ^ sig_190;
int sig_218 = sig_164 & sig_190;
int sig_219 = sig_217 & sig_160;
int sig_220 = sig_217 ^ sig_160;
int sig_221 = sig_218 ^ sig_219;
int sig_222 = sig_169 ^ sig_191;
int sig_223 = sig_169 & sig_191;
int sig_224 = sig_222 & sig_165;
int sig_225 = sig_222 ^ sig_165;
int sig_226 = sig_223 | sig_224;
int sig_227 = sig_174 ^ sig_192;
int sig_228 = sig_174 & sig_192;
int sig_229 = sig_227 & sig_170;
int sig_230 = sig_227 ^ sig_170;
int sig_231 = sig_228 ^ sig_229;
int sig_232 = sig_179 ^ sig_193;
int sig_233 = sig_179 & sig_193;
int sig_234 = sig_232 & sig_175;
int sig_235 = sig_232 ^ sig_175;
int sig_236 = sig_233 | sig_234;
int sig_237 = sig_184 | sig_194;
int sig_238 = sig_184 & wa[1];
int sig_239 = sig_237 | sig_180;
int sig_240 = sig_237 ^ sig_180;
int sig_241 = sig_238 | sig_239;
int sig_242 = sig_135 ^ sig_195;
int sig_243 = sig_135 & sig_195;
int sig_244 = wb[2] & sig_185;
int sig_245 = sig_242 ^ sig_185;
int sig_246 = sig_243 | sig_244;
int sig_248 = wa[1] & wb[5];
int sig_249 = wa[2] & wb[5];
int sig_250 = wa[3] & wb[5];
int sig_251 = wa[4] & wb[5];
int sig_252 = wa[5] & wb[5];
int sig_253 = wa[6] & wb[5];
int sig_254 = wa[7] & wb[5];
int sig_255 = wa[8] & wb[5];
int sig_256 = wa[9] & wb[5];
int sig_257 = wa[10] & wb[5];
int sig_259 = sig_205;
int sig_260 = wa[0] ^ wb[10];
int sig_262 = sig_259 | sig_260;
int sig_263 = sig_210 ^ sig_248;
int sig_264 = sig_210 & sig_248;
int sig_265 = sig_263 & sig_206;
int sig_266 = sig_263 ^ sig_206;
int sig_267 = sig_264 | sig_265;
int sig_268 = sig_215 ^ sig_249;
int sig_269 = sig_215 & sig_249;
int sig_271 = sig_268 ^ sig_211;
int sig_272 = sig_269;
int sig_273 = sig_220 ^ sig_250;
int sig_274 = sig_220 & sig_250;
int sig_275 = sig_273 & sig_216;
int sig_276 = sig_273 ^ sig_216;
int sig_277 = sig_274 ^ sig_275;
int sig_278 = sig_225 ^ sig_251;
int sig_279 = sig_225 & sig_251;
int sig_280 = sig_278 & sig_221;
int sig_281 = sig_278 ^ sig_221;
int sig_282 = sig_279 | sig_280;
int sig_283 = sig_230 ^ sig_252;
int sig_284 = sig_230 & sig_252;
int sig_285 = sig_283 & sig_226;
int sig_286 = sig_283 ^ sig_226;
int sig_287 = sig_284 ^ sig_285;
int sig_288 = sig_235 ^ sig_253;
int sig_289 = sig_235 & sig_253;
int sig_290 = sig_288 & sig_231;
int sig_291 = sig_288 ^ sig_231;
int sig_292 = sig_289 | sig_290;
int sig_293 = sig_240 ^ sig_254;
int sig_294 = wa[7] & sig_254;
int sig_295 = sig_293 & sig_236;
int sig_296 = sig_293 ^ sig_236;
int sig_297 = sig_294 | sig_295;
int sig_298 = sig_245 ^ sig_255;
int sig_299 = sig_245 & sig_255;
int sig_300 = sig_298 & sig_241;
int sig_301 = sig_298 ^ sig_241;
int sig_302 = sig_299 ^ sig_300;
int sig_303 = sig_196 ^ sig_256;
int sig_304 = sig_196 & sig_256;
int sig_305 = sig_303 & sig_246;
int sig_306 = sig_303 ^ sig_246;
int sig_307 = sig_304 | sig_305;
int sig_308 = wa[0] & wb[6];
int sig_309 = wa[1] & wb[6];
int sig_310 = wa[2] & wb[6];
int sig_311 = wa[3] & wb[6];
int sig_312 = wa[4] & wb[6];
int sig_313 = wa[5] & wb[6];
int sig_314 = wa[6] & wb[6];
int sig_315 = wa[7] & wb[6];
int sig_316 = wa[8] & wb[6];
int sig_317 = wa[9] & wb[6];
int sig_318 = wa[10] & wb[6];
int sig_319 = sig_266 ^ sig_308;
int sig_320 = sig_266 ^ sig_308;
int sig_321 = sig_319 & sig_262;
int sig_322 = sig_319 & wb[10];
int sig_323 = sig_320 ^ sig_321;
int sig_324 = sig_271 ^ sig_309;
int sig_325 = sig_271 & sig_309;
int sig_326 = sig_324 & sig_267;
int sig_327 = sig_324 ^ sig_267;
int sig_328 = sig_325 | sig_326;
int sig_329 = sig_276 ^ sig_310;
int sig_330 = sig_276 & sig_310;
int sig_332 = sig_329 ^ sig_272;
int sig_333 = sig_330;
int sig_334 = sig_281 ^ sig_311;
int sig_335 = sig_281 & sig_311;
int sig_336 = sig_334 & sig_277;
int sig_337 = sig_334 ^ sig_277;
int sig_338 = sig_335 | sig_336;
int sig_339 = sig_286 ^ sig_312;
int sig_340 = sig_286 & sig_312;
int sig_341 = sig_339 & sig_282;
int sig_342 = sig_339 ^ sig_282;
int sig_343 = sig_340 | sig_341;
int sig_344 = sig_291 ^ sig_313;
int sig_345 = sig_291 & sig_313;
int sig_346 = sig_344 & sig_287;
int sig_347 = sig_344 ^ sig_287;
int sig_348 = sig_345 | sig_346;
int sig_349 = sig_296 ^ sig_314;
int sig_350 = sig_296 & sig_314;
int sig_351 = sig_349 & sig_292;
int sig_352 = sig_349 ^ sig_292;
int sig_353 = sig_350 | sig_351;
int sig_354 = sig_301 ^ sig_315;
int sig_355 = sig_301 & sig_315;
int sig_356 = sig_354 & sig_297;
int sig_357 = sig_354 ^ sig_297;
int sig_358 = sig_355 | sig_356;
int sig_359 = sig_306 ^ sig_316;
int sig_360 = sig_306 & sig_316;
int sig_361 = sig_359 & sig_302;
int sig_362 = sig_359 ^ sig_302;
int sig_363 = sig_360 ^ sig_361;
int sig_364 = sig_257 ^ sig_317;
int sig_365 = sig_257 & sig_317;
int sig_366 = sig_364 & sig_307;
int sig_367 = sig_364 ^ sig_307;
int sig_368 = sig_365 | sig_366;
int sig_369 = wa[0] & wb[6];
int sig_370 = wa[1] & wb[7];
int sig_371 = wa[2] & wb[7];
int sig_372 = wa[3] & wb[7];
int sig_373 = wa[4] & wb[7];
int sig_374 = wa[5] & wb[7];
int sig_375 = wa[6] & wb[7];
int sig_376 = wa[7] & wb[7];
int sig_377 = wa[8] & wb[7];
int sig_378 = wa[9] & wb[7];
int sig_379 = wa[10] & wb[7];
int sig_380 = sig_327 ^ sig_369;
int sig_381 = sig_327 & sig_369;
int sig_382 = sig_380 & sig_323;
int sig_383 = sig_380 ^ sig_323;
int sig_384 = sig_381 | sig_382;
int sig_385 = sig_332 ^ sig_370;
int sig_386 = sig_332 & sig_370;
int sig_387 = sig_385 & sig_328;
int sig_388 = sig_385 ^ sig_328;
int sig_389 = sig_386 | sig_387;
int sig_390 = sig_337 ^ sig_371;
int sig_391 = sig_337 & sig_371;
int sig_392 = sig_390 & sig_333;
int sig_393 = sig_390 ^ sig_333;
int sig_394 = sig_391 | sig_392;
int sig_395 = sig_342 ^ sig_372;
int sig_396 = sig_342 & sig_372;
int sig_397 = sig_395 & sig_338;
int sig_398 = sig_395 ^ sig_338;
int sig_399 = sig_396 | sig_397;
int sig_400 = sig_347 ^ sig_373;
int sig_401 = sig_347 & sig_373;
int sig_402 = sig_400 & sig_343;
int sig_403 = sig_400 ^ sig_343;
int sig_404 = sig_401 ^ sig_402;
int sig_405 = sig_352 ^ sig_374;
int sig_406 = sig_352 & sig_374;
int sig_407 = sig_405 & sig_348;
int sig_408 = sig_405 ^ sig_348;
int sig_409 = sig_406 | sig_407;
int sig_410 = sig_357 ^ sig_375;
int sig_411 = sig_357 & sig_375;
int sig_412 = sig_410 & sig_353;
int sig_413 = sig_410 ^ sig_353;
int sig_414 = sig_411 | sig_412;
int sig_415 = sig_362 ^ sig_376;
int sig_416 = sig_362 & sig_376;
int sig_417 = sig_415 & sig_358;
int sig_418 = sig_415 ^ sig_358;
int sig_419 = sig_416 ^ sig_417;
int sig_420 = sig_367 ^ sig_377;
int sig_421 = sig_367 & sig_377;
int sig_422 = sig_420 & sig_363;
int sig_423 = sig_420 ^ sig_363;
int sig_424 = sig_421 ^ sig_422;
int sig_425 = sig_318 ^ sig_378;
int sig_426 = sig_318 & sig_378;
int sig_427 = sig_425 & sig_368;
int sig_428 = sig_425 ^ sig_368;
int sig_429 = sig_426 | sig_427;
int sig_430 = wa[0] & wb[8];
int sig_431 = wa[1] & wb[8];
int sig_432 = wa[2] & wb[8];
int sig_433 = wa[3] & wb[8];
int sig_434 = wa[4] & wb[8];
int sig_435 = wa[5] & wb[8];
int sig_436 = wa[6] & wb[8];
int sig_437 = wa[7] & wb[8];
int sig_438 = wa[8] & wb[8];
int sig_439 = wa[9] & wb[8];
int sig_440 = wa[10] & wb[8];
int sig_441 = sig_388 ^ sig_430;
int sig_442 = sig_388 & sig_430;
int sig_443 = sig_441 & sig_384;
int sig_444 = sig_441 ^ sig_384;
int sig_445 = sig_442 ^ sig_443;
int sig_446 = sig_393 ^ sig_431;
int sig_447 = sig_393 & sig_431;
int sig_448 = sig_446 & sig_389;
int sig_449 = sig_446 ^ sig_389;
int sig_450 = sig_447 ^ sig_448;
int sig_451 = sig_398 ^ sig_432;
int sig_452 = sig_398 & sig_432;
int sig_453 = sig_451 & sig_394;
int sig_454 = sig_451 ^ sig_394;
int sig_455 = sig_452 | sig_453;
int sig_456 = sig_403 ^ sig_433;
int sig_457 = sig_403 & sig_433;
int sig_458 = sig_456 & sig_399;
int sig_459 = sig_456 ^ sig_399;
int sig_460 = sig_457 | sig_458;
int sig_461 = sig_408 ^ sig_434;
int sig_462 = sig_408 & sig_434;
int sig_463 = sig_461 & sig_404;
int sig_464 = sig_461 ^ sig_404;
int sig_465 = sig_462 | sig_463;
int sig_466 = sig_413 ^ sig_435;
int sig_467 = sig_413 & sig_435;
int sig_468 = sig_466 & sig_409;
int sig_469 = sig_466 ^ sig_409;
int sig_470 = sig_467 | sig_468;
int sig_471 = sig_418 ^ sig_436;
int sig_472 = sig_418 & sig_436;
int sig_473 = sig_471 & sig_414;
int sig_474 = sig_471 ^ sig_414;
int sig_475 = sig_472 | sig_473;
int sig_476 = sig_423 ^ sig_437;
int sig_477 = sig_423 & sig_437;
int sig_478 = sig_476 & sig_419;
int sig_479 = sig_476 ^ sig_419;
int sig_480 = sig_477 | sig_478;
int sig_481 = sig_428 ^ sig_438;
int sig_482 = sig_428 & sig_438;
int sig_483 = sig_481 & sig_424;
int sig_484 = sig_481 ^ sig_424;
int sig_485 = sig_482 | sig_483;
int sig_486 = sig_379 ^ sig_439;
int sig_487 = sig_379 & sig_439;
int sig_488 = sig_486 & sig_429;
int sig_489 = sig_486 ^ sig_429;
int sig_490 = sig_487 | sig_488;
int sig_491 = wa[0] & wb[9];
int sig_492 = wa[1] & wb[9];
int sig_493 = wa[2] & wb[9];
int sig_494 = wa[3] & wb[9];
int sig_495 = wa[4] & wb[9];
int sig_496 = wa[5] & wb[9];
int sig_497 = wa[6] & wb[9];
int sig_498 = wa[7] & wb[9];
int sig_499 = wa[8] & wb[9];
int sig_500 = wa[9] & wb[9];
int sig_501 = wa[10] & wb[9];
int sig_502 = sig_449 ^ sig_491;
int sig_503 = sig_449 & sig_491;
int sig_504 = sig_502 & sig_445;
int sig_505 = sig_502 ^ sig_445;
int sig_506 = sig_503 ^ sig_504;
int sig_507 = sig_454 ^ sig_492;
int sig_508 = sig_454 & sig_492;
int sig_509 = sig_507 & sig_450;
int sig_510 = sig_507 ^ sig_450;
int sig_511 = sig_508 ^ sig_509;
int sig_512 = sig_459 ^ sig_493;
int sig_513 = sig_459 & sig_493;
int sig_514 = sig_512 & sig_455;
int sig_515 = sig_512 ^ sig_455;
int sig_516 = sig_513 | sig_514;
int sig_517 = sig_464 ^ sig_494;
int sig_518 = sig_464 & sig_494;
int sig_519 = sig_517 & sig_460;
int sig_520 = sig_517 ^ sig_460;
int sig_521 = sig_518 ^ sig_519;
int sig_522 = sig_469 ^ sig_495;
int sig_523 = sig_469 & sig_495;
int sig_524 = sig_522 & sig_465;
int sig_525 = sig_522 ^ sig_465;
int sig_526 = sig_523 | sig_524;
int sig_527 = sig_474 ^ sig_496;
int sig_528 = sig_474 & sig_496;
int sig_529 = sig_527 & sig_470;
int sig_530 = sig_527 ^ sig_470;
int sig_531 = sig_528 | sig_529;
int sig_532 = sig_479 ^ sig_497;
int sig_533 = sig_479 & sig_497;
int sig_534 = sig_532 & sig_475;
int sig_535 = sig_532 ^ sig_475;
int sig_536 = sig_533 | sig_534;
int sig_537 = sig_484 ^ sig_498;
int sig_538 = sig_484 & sig_498;
int sig_539 = sig_537 & sig_480;
int sig_540 = sig_537 ^ sig_480;
int sig_541 = sig_538 | sig_539;
int sig_542 = sig_489 ^ sig_499;
int sig_543 = sig_489 & sig_499;
int sig_544 = sig_542 & sig_485;
int sig_545 = sig_542 ^ sig_485;
int sig_546 = sig_543 | sig_544;
int sig_547 = sig_440 ^ sig_500;
int sig_548 = sig_440 & sig_500;
int sig_549 = sig_547 & sig_490;
int sig_550 = sig_547 ^ sig_490;
int sig_551 = sig_548 | sig_549;
int sig_552 = wa[0] & wb[10];
int sig_553 = wa[1] & wb[10];
int sig_554 = wa[2] & wb[10];
int sig_555 = wa[3] & wb[10];
int sig_556 = wa[4] & wb[10];
int sig_557 = wa[5] & wb[10];
int sig_558 = wa[6] & wb[10];
int sig_559 = wa[7] & wb[10];
int sig_560 = wa[8] & wb[10];
int sig_561 = wa[9] & wb[10];
int sig_562 = wa[10] & wb[10];
int sig_563 = sig_510 ^ sig_552;
int sig_564 = sig_510 & sig_552;
int sig_565 = sig_563 & sig_506;
int sig_566 = sig_563 ^ sig_506;
int sig_567 = sig_564 | sig_565;
int sig_568 = sig_515 ^ sig_553;
int sig_569 = sig_515 & sig_553;
int sig_570 = sig_568 & sig_511;
int sig_571 = sig_568 ^ sig_511;
int sig_572 = sig_569 | sig_570;
int sig_573 = sig_520 ^ sig_554;
int sig_574 = sig_520 & sig_554;
int sig_575 = sig_573 & sig_516;
int sig_576 = sig_573 ^ sig_516;
int sig_577 = sig_574 | sig_575;
int sig_578 = sig_525 ^ sig_555;
int sig_579 = sig_525 & sig_555;
int sig_580 = sig_578 & sig_521;
int sig_581 = sig_578 ^ sig_521;
int sig_582 = sig_579 | sig_580;
int sig_583 = sig_530 ^ sig_556;
int sig_584 = sig_530 & sig_556;
int sig_585 = sig_583 & sig_526;
int sig_586 = sig_583 ^ sig_526;
int sig_587 = sig_584 | sig_585;
int sig_588 = sig_535 ^ sig_557;
int sig_589 = sig_535 & sig_557;
int sig_590 = sig_588 & sig_531;
int sig_591 = sig_588 ^ sig_531;
int sig_592 = sig_589 ^ sig_590;
int sig_593 = sig_540 ^ sig_558;
int sig_594 = sig_540 & sig_558;
int sig_595 = sig_593 & sig_536;
int sig_596 = sig_593 ^ sig_536;
int sig_597 = sig_594 | sig_595;
int sig_598 = sig_545 ^ sig_559;
int sig_599 = sig_545 & sig_559;
int sig_600 = sig_598 & sig_541;
int sig_601 = sig_598 ^ sig_541;
int sig_602 = sig_599 | sig_600;
int sig_603 = sig_550 ^ sig_560;
int sig_604 = sig_550 & sig_560;
int sig_605 = sig_603 & sig_546;
int sig_606 = sig_603 ^ sig_546;
int sig_607 = sig_604 ^ sig_605;
int sig_608 = sig_501 ^ sig_561;
int sig_609 = sig_501 & sig_561;
int sig_610 = sig_608 & sig_551;
int sig_611 = sig_608 ^ sig_551;
int sig_612 = sig_609 | sig_610;
int sig_613 = sig_571 ^ sig_567;
int sig_614 = sig_571 & sig_567;
int sig_615 = sig_576 ^ sig_572;
int sig_616 = sig_576 & sig_572;
int sig_617 = sig_615 & sig_614;
int sig_618 = sig_615 ^ sig_614;
int sig_619 = sig_616 ^ sig_617;
int sig_620 = sig_581 ^ sig_577;
int sig_621 = sig_581 & sig_577;
int sig_622 = sig_620 & sig_619;
int sig_623 = sig_620 ^ sig_619;
int sig_624 = sig_621 | sig_622;
int sig_625 = sig_586 ^ sig_582;
int sig_626 = sig_586 & sig_582;
int sig_627 = sig_625 & sig_624;
int sig_628 = sig_625 ^ sig_624;
int sig_629 = sig_626 ^ sig_627;
int sig_630 = sig_591 ^ sig_587;
int sig_631 = sig_591 & sig_587;
int sig_632 = sig_630 & sig_629;
int sig_633 = sig_630 ^ sig_629;
int sig_634 = sig_631 | sig_632;
int sig_635 = sig_596 ^ sig_592;
int sig_636 = sig_596 & sig_592;
int sig_637 = sig_635 & sig_634;
int sig_638 = sig_635 ^ sig_634;
int sig_639 = sig_636 | sig_637;
int sig_640 = sig_601 ^ sig_597;
int sig_641 = sig_601 & sig_597;
int sig_642 = sig_640 & sig_639;
int sig_643 = sig_640 ^ sig_639;
int sig_644 = sig_641 | sig_642;
int sig_645 = sig_606 ^ sig_602;
int sig_646 = sig_606 & sig_602;
int sig_647 = sig_645 & sig_644;
int sig_648 = sig_645 ^ sig_644;
int sig_649 = sig_646 | sig_647;
int sig_650 = sig_611 ^ sig_607;
int sig_651 = sig_611 & sig_607;
int sig_652 = sig_650 & sig_649;
int sig_653 = sig_650 ^ sig_649;
int sig_654 = sig_651 | sig_652;
int sig_655 = sig_562 ^ sig_612;
int sig_656 = sig_562 & sig_612;
int sig_657 = sig_655 & sig_654;
int sig_658 = sig_655 ^ sig_654;
int sig_659 = sig_656 | sig_657;
y |= (sig_22 & 0x01) << 0; // default output
y |= (sig_305 & 0x01) << 1; // default output
y |= (sig_98 & 0x01) << 2; // default output
y |= (sig_189 & 0x01) << 3; // default output
y |= (sig_250 & 0x01) << 4; // default output
y |= (sig_130 & 0x01) << 5; // default output
y |= (sig_322 & 0x01) << 6; // default output
y |= (sig_383 & 0x01) << 7; // default output
y |= (sig_444 & 0x01) << 8; // default output
y |= (sig_505 & 0x01) << 9; // default output
y |= (sig_566 & 0x01) << 10; // default output
y |= (sig_613 & 0x01) << 11; // default output
y |= (sig_618 & 0x01) << 12; // default output
y |= (sig_623 & 0x01) << 13; // default output
y |= (sig_628 & 0x01) << 14; // default output
y |= (sig_633 & 0x01) << 15; // default output
y |= (sig_638 & 0x01) << 16; // default output
y |= (sig_643 & 0x01) << 17; // default output
y |= (sig_648 & 0x01) << 18; // default output
y |= (sig_653 & 0x01) << 19; // default output
y |= (sig_658 & 0x01) << 20; // default output
y |= (sig_659 & 0x01) << 21; // default output
return y;
}
|
the_stack_data/274.c | #include <unistd.h>
#include "syscall.h"
pid_t getpgid(pid_t pid)
{
return syscall(SYS_getpgid, pid);
}
|
the_stack_data/549891.c | #include<stdio.h>
int main(){
int num;
printf("Enter number whose multiplication table you wish to see:\n");
scanf("%d",&num);
printf("\n");
for(int i=0;i<=10;i++)
printf("%d * %d = %d\n",num,i,num*i);
}
|
the_stack_data/1250609.c | // RUN: %cml %s -o %t && %t | FileCheck %s
#include <stdio.h>
int main() {
int a = 3;
int b = 5;
if (a >= 3)
a++;
for (int i = 0; i < 10; i++) {
a = a + 3;
if (b < 300) {
for (int j = 0; j < 10; j++) {
b = b + 5;
}
}
}
printf("%d %d\n", a, b); // CHECK: 34 305
return 0;
}
|
the_stack_data/892265.c | /*
* my_getopt.c - my re-implementation of getopt.
* Copyright 1997, 2000, 2001, 2002, 2006, Benjamin Sittler
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifdef WIN32
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "my_getopt.h"
int optind=1, opterr=1, optopt=0;
char *optarg=0;
/* reset argument parser to start-up values */
int getopt_reset(void)
{
optind = 1;
opterr = 1;
optopt = 0;
optarg = 0;
return 0;
}
/* this is the plain old UNIX getopt, with GNU-style extensions. */
/* if you're porting some piece of UNIX software, this is all you need. */
/* this supports GNU-style permution and optional arguments */
static int _getopt(int argc, char * argv[], const char *opts)
{
static int charind=0;
const char *s;
char mode, colon_mode;
int off = 0, opt = -1;
if(getenv("POSIXLY_CORRECT")) colon_mode = mode = '+';
else {
if((colon_mode = *opts) == ':') off ++;
if(((mode = opts[off]) == '+') || (mode == '-')) {
off++;
if((colon_mode != ':') && ((colon_mode = opts[off]) == ':'))
off ++;
}
}
optarg = 0;
if(charind) {
optopt = argv[optind][charind];
for(s=opts+off; *s; s++) if(optopt == *s) {
charind++;
if((*(++s) == ':') || ((optopt == 'W') && (*s == ';'))) {
if(argv[optind][charind]) {
optarg = &(argv[optind++][charind]);
charind = 0;
} else if(*(++s) != ':') {
charind = 0;
if(++optind >= argc) {
if(opterr) fprintf(stderr,
"%s: option requires an argument -- %c\n",
argv[0], optopt);
opt = (colon_mode == ':') ? ':' : '?';
goto my_getopt_ok;
}
optarg = argv[optind++];
}
}
opt = optopt;
goto my_getopt_ok;
}
if(opterr) fprintf(stderr,
"%s: illegal option -- %c\n",
argv[0], optopt);
opt = '?';
if(argv[optind][++charind] == '\0') {
optind++;
charind = 0;
}
my_getopt_ok:
if(charind && ! argv[optind][charind]) {
optind++;
charind = 0;
}
} else if((optind >= argc) ||
((argv[optind][0] == '-') &&
(argv[optind][1] == '-') &&
(argv[optind][2] == '\0'))) {
optind++;
opt = -1;
} else if((argv[optind][0] != '-') ||
(argv[optind][1] == '\0')) {
char *tmp;
int i, j, k;
if(mode == '+') opt = -1;
else if(mode == '-') {
optarg = argv[optind++];
charind = 0;
opt = 1;
} else {
for(i=j=optind; i<argc; i++) if((argv[i][0] == '-') &&
(argv[i][1] != '\0')) {
optind=i;
opt=_getopt(argc, argv, opts);
while(i > j) {
tmp=argv[--i];
for(k=i; k+1<optind; k++) argv[k]=argv[k+1];
argv[--optind]=tmp;
}
break;
}
if(i == argc) opt = -1;
}
} else {
charind++;
opt = _getopt(argc, argv, opts);
}
if (optind > argc) optind = argc;
return opt;
}
/* this is the extended getopt_long{,_only}, with some GNU-like
* extensions. Implements _getopt_internal in case any programs
* expecting GNU libc getopt call it.
*/
int _getopt_internal(int argc, char * argv[], const char *shortopts,
const struct option *longopts, int *longind,
int long_only)
{
char mode, colon_mode = *shortopts;
int shortoff = 0, opt = -1;
if(getenv("POSIXLY_CORRECT")) colon_mode = mode = '+';
else {
if((colon_mode = *shortopts) == ':') shortoff ++;
if(((mode = shortopts[shortoff]) == '+') || (mode == '-')) {
shortoff++;
if((colon_mode != ':') && ((colon_mode = shortopts[shortoff]) == ':'))
shortoff ++;
}
}
optarg = 0;
if((optind >= argc) ||
((argv[optind][0] == '-') &&
(argv[optind][1] == '-') &&
(argv[optind][2] == '\0'))) {
optind++;
opt = -1;
} else if((argv[optind][0] != '-') ||
(argv[optind][1] == '\0')) {
char *tmp;
int i, j, k;
opt = -1;
if(mode == '+') return -1;
else if(mode == '-') {
optarg = argv[optind++];
return 1;
}
for(i=j=optind; i<argc; i++) if((argv[i][0] == '-') &&
(argv[i][1] != '\0')) {
optind=i;
opt=_getopt_internal(argc, argv, shortopts,
longopts, longind,
long_only);
while(i > j) {
tmp=argv[--i];
for(k=i; k+1<optind; k++)
argv[k]=argv[k+1];
argv[--optind]=tmp;
}
break;
}
} else if((!long_only) && (argv[optind][1] != '-'))
opt = _getopt(argc, argv, shortopts);
else {
int charind, offset;
int found = 0, ind, hits = 0;
if(((optopt = argv[optind][1]) != '-') && ! argv[optind][2]) {
int c;
ind = shortoff;
while((c = shortopts[ind++])) {
if(((shortopts[ind] == ':') ||
((c == 'W') && (shortopts[ind] == ';'))) &&
(shortopts[++ind] == ':'))
ind ++;
if(optopt == c) return _getopt(argc, argv, shortopts);
}
}
offset = 2 - (argv[optind][1] != '-');
for(charind = offset;
(argv[optind][charind] != '\0') &&
(argv[optind][charind] != '=');
charind++);
for(ind = 0; longopts[ind].name && !hits; ind++)
if((strlen(longopts[ind].name) == (size_t) (charind - offset)) &&
(strncmp(longopts[ind].name,
argv[optind] + offset, charind - offset) == 0))
found = ind, hits++;
if(!hits) for(ind = 0; longopts[ind].name; ind++)
if(strncmp(longopts[ind].name,
argv[optind] + offset, charind - offset) == 0)
found = ind, hits++;
if(hits == 1) {
opt = 0;
if(argv[optind][charind] == '=') {
if(longopts[found].has_arg == 0) {
opt = '?';
if(opterr) fprintf(stderr,
"%s: option `--%s' doesn't allow an argument\n",
argv[0], longopts[found].name);
} else {
optarg = argv[optind] + ++charind;
charind = 0;
}
} else if(longopts[found].has_arg == 1) {
if(++optind >= argc) {
opt = (colon_mode == ':') ? ':' : '?';
if(opterr) fprintf(stderr,
"%s: option `--%s' requires an argument\n",
argv[0], longopts[found].name);
} else optarg = argv[optind];
}
if(!opt) {
if (longind) *longind = found;
if(!longopts[found].flag) opt = longopts[found].val;
else *(longopts[found].flag) = longopts[found].val;
}
optind++;
} else if(!hits) {
if(offset == 1) opt = _getopt(argc, argv, shortopts);
else {
opt = '?';
if(opterr) fprintf(stderr,
"%s: unrecognized option `%s'\n",
argv[0], argv[optind++]);
}
} else {
opt = '?';
if(opterr) fprintf(stderr,
"%s: option `%s' is ambiguous\n",
argv[0], argv[optind++]);
}
}
if (optind > argc) optind = argc;
return opt;
}
/* This function is kinda problematic because most getopt() nowadays
seem to use char * const argv[] (they DON'T permute the options list),
but this one does. So we remove it as long as HAVE_GETOPT is define, so
people can use the version from their platform instead */
#ifndef HAVE_GETOPT
int getopt(int argc, char * argv[], const char *opts)
{
return _getopt(argc, argv, opts);
}
#endif /* HAVE_GETOPT */
int getopt_long(int argc, char * argv[], const char *shortopts,
const struct option *longopts, int *longind)
{
return _getopt_internal(argc, argv, shortopts, longopts, longind, 0);
}
int getopt_long_only(int argc, char * argv[], const char *shortopts,
const struct option *longopts, int *longind)
{
return _getopt_internal(argc, argv, shortopts, longopts, longind, 1);
}
#endif
|