file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/48574474.c | /*
ITS240-01
Lab 08
ch9p462pe5
03/29/2017
Daniel Kuckuck
Write a C function named chartype() that determines the ASCII type of any integer in the range 0 to 127. If the number represents a printable ascii character, print the character with one of the following appropriate messages.
The ASCII character is a lowercase letter.
The ASCII character is an uppercase letter.
The ASCII character is a digit.
The ASCII character is a punctuation mark.
The ASCII character is a space.
If the ASCII character is a nonprintable character, display its ASCII code in decimal format and the message The ASCII character is a nonprintable character.
Write a simple main() function to test the function written above. The main() function should generate 20 random numbers in the range 0 to 127 and call chartype() for each generated number.
*/
#include <stdio.h>
#include <ctype.h>
#include <time.h>
int main()
{
void chartype(char);
char usrInput;
int count = 127;
/* Part a
printf("\nPlease enter a character -->");
scanf("%c", &usrInput);
/ end of part a begin part b */
for (int i = 0; i < count; ++i)
{
srand(time(NULL));
usrInput = rand() % 127 +i;
printf("\n%d", usrInput);
chartype(usrInput);
}
return 0;
}
void chartype(char passedValue)
{
if (isalpha(passedValue) != 0)
{
if (isupper(passedValue) != 0)
{
printf("\nThe ASCII character is an uppercase letter, %c", passedValue);
}
else
{
printf("\nThe ASCII character is a lowercase letter, %c", passedValue);
}
}
else if (isdigit(passedValue) != 0)
{
printf("\nThe ASCII character is a digit, %c", passedValue);
}
else if (ispunct(passedValue) != 0)
{
printf("\nThe ASCII character is a punctuation mark, %c", passedValue);
}
else if (isspace(passedValue) != 0)
{
printf("\nThe ASCII character is a space, %c", passedValue);
}
else
printf("\nThe ASCII character is a nonprintable character, %c", passedValue);
} |
the_stack_data/123269.c | #include<stdio.h>
int fun(int x)
{
if(x>9)
{
fun(27/9);
printf("%d ",x-1);
fun(27/3);
}
else
{
printf("%d ",x-2);
}
}
int main()
{
int x=27;
fun(x);
return 0;
}
//o/p
//1 26 7
|
the_stack_data/65954.c | int main() {
myfunc();
return 0;
}
|
the_stack_data/165767879.c | /*
* Write a program that reads input until encountering the # character and then
* reports the number of spaces read, the number of newline characters read, and
* the number of all other characters read
*/
#include <stdio.h>
int main (void)
{
char c;
unsigned int spaces = 0, newlines = 0, other = 0;
while ((c = getchar()) != '#')
{
if (c == ' ')
spaces++;
else if (c == '\n')
newlines++;
else
other++;
}
printf("Read %d spaces, %d newlines, %d other characters\n", spaces, newlines, other);
return 0;
}
|
the_stack_data/1055245.c | int i, a = 0, j;
void main()
{
for (i = 0, j = 2; i < 10; i++)
{
printid(a);
a += j + i;
}
printid(a);
}
|
the_stack_data/154967.c | #include <stdlib.h>
extern int __VERIFIER_nondet_int(void);
int test_fun(int x, int y)
{
int* x_ref = alloca(sizeof(int));
int* y_ref = alloca(sizeof(int));
int* c = alloca(sizeof(int));
*x_ref = x;
*y_ref = y;
*c = 0;
while (!(*x_ref == *y_ref)) {
if(*x_ref > *y_ref) {
*y_ref = *y_ref + 1;
} else {
*x_ref = *x_ref + 1;
}
*c = *c + 1;
}
return *c;
}
int main() {
return test_fun(__VERIFIER_nondet_int(),__VERIFIER_nondet_int());
}
|
the_stack_data/828071.c | //
// Created by jimmy on 2016/11/26.
//
#include <malloc.h>
#define ABS(a) ((a)<(0)?(-a):(a))
#define MAX(a, b) ((a)>(b)?(a):(b))
#define MIN(a, b) ((a)<(b)?(a):(b))
/*************************************************
Function: StackBlur
Description: Using stack way blurred image pixels
Calls: malloc
Table Accessed: NULL
Table Updated: NULL
Input: Collection of pixels, wide image, image is high, the blur radius
Output: After return to fuzzy collection of pixels
Return: After return to fuzzy collection of pixels
Others: NULL
*************************************************/
int *blur_ARGB_8888(int *pix, int w, int h, int radius) {
int wm = w - 1;
int hm = h - 1;
int wh = w * h;
int div = radius + radius + 1;
short *r = (short *) malloc(wh * sizeof(short));
short *g = (short *) malloc(wh * sizeof(short));
short *b = (short *) malloc(wh * sizeof(short));
int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
int *vmin = (int *) malloc(MAX(w, h) * sizeof(int));
int divsum = (div + 1) >> 1;
divsum *= divsum;
short *dv = (short *) malloc(256 * divsum * sizeof(short));
for (i = 0; i < 256 * divsum; i++) {
dv[i] = (short) (i / divsum);
}
yw = yi = 0;
int(*stack)[3] = (int (*)[3]) malloc(div * 3 * sizeof(int));
int stackpointer;
int stackstart;
int *sir;
int rbs;
int r1 = radius + 1;
int routsum, goutsum, boutsum;
int rinsum, ginsum, binsum;
for (y = 0; y < h; y++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
for (i = -radius; i <= radius; i++) {
p = pix[yi + (MIN(wm, MAX(i, 0)))];
sir = stack[i + radius];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rbs = r1 - ABS(i);
rsum += sir[0] * rbs;
gsum += sir[1] * rbs;
bsum += sir[2] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
}
else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
}
stackpointer = radius;
for (x = 0; x < w; x++) {
r[yi] = dv[rsum];
g[yi] = dv[gsum];
b[yi] = dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (y == 0) {
vmin[x] = MIN(x + radius + 1, wm);
}
p = pix[yw + vmin[x]];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[(stackpointer) % div];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi++;
}
yw += w;
}
for (x = 0; x < w; x++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
yp = -radius * w;
for (i = -radius; i <= radius; i++) {
yi = MAX(0, yp) + x;
sir = stack[i + radius];
sir[0] = r[yi];
sir[1] = g[yi];
sir[2] = b[yi];
rbs = r1 - ABS(i);
rsum += r[yi] * rbs;
gsum += g[yi] * rbs;
bsum += b[yi] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
}
else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
if (i < hm) {
yp += w;
}
}
yi = x;
stackpointer = radius;
for (y = 0; y < h; y++) {
// Preserve alpha channel: ( 0xff000000 & pix[yi] )
pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (x == 0) {
vmin[y] = MIN(y + r1, hm) * w;
}
p = x + vmin[y];
sir[0] = r[p];
sir[1] = g[p];
sir[2] = b[p];
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[stackpointer];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi += w;
}
}
free(r);
free(g);
free(b);
free(vmin);
free(dv);
free(stack);
return (pix);
}
short *blur_RGB_565(short *pix, int w, int h, int radius) {
int wm = w - 1;
int hm = h - 1;
int wh = w * h;
int div = radius + radius + 1;
short *r = (short *) malloc(wh * sizeof(short));
short *g = (short *) malloc(wh * sizeof(short));
short *b = (short *) malloc(wh * sizeof(short));
int rsum, gsum, bsum, x, y, p, i, yp, yi, yw;
int *vmin = (int *) malloc(MAX(w, h) * sizeof(int));
int divsum = (div + 1) >> 1;
divsum *= divsum;
short *dv = (short *) malloc(256 * divsum * sizeof(short));
for (i = 0; i < 256 * divsum; i++) {
dv[i] = (short) (i / divsum);
}
yw = yi = 0;
int(*stack)[3] = (int (*)[3]) malloc(div * 3 * sizeof(int));
int stackpointer;
int stackstart;
int *sir;
int rbs;
int r1 = radius + 1;
int routsum, goutsum, boutsum;
int rinsum, ginsum, binsum;
for (y = 0; y < h; y++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
for (i = -radius; i <= radius; i++) {
p = pix[yi + (MIN(wm, MAX(i, 0)))];
sir = stack[i + radius];
sir[0] = (((p) & 0xF800) >> 11) << 3;
sir[1] = (((p) & 0x7E0) >> 5) << 2;
sir[2] = ((p) & 0x1F) << 3;
rbs = r1 - ABS(i);
rsum += sir[0] * rbs;
gsum += sir[1] * rbs;
bsum += sir[2] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
}
else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
}
stackpointer = radius;
for (x = 0; x < w; x++) {
r[yi] = dv[rsum];
g[yi] = dv[gsum];
b[yi] = dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (y == 0) {
vmin[x] = MIN(x + radius + 1, wm);
}
p = pix[yw + vmin[x]];
sir[0] = (((p) & 0xF800) >> 11) << 3;
sir[1] = (((p) & 0x7E0) >> 5) << 2;
sir[2] = ((p) & 0x1F) << 3;
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[(stackpointer) % div];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi++;
}
yw += w;
}
for (x = 0; x < w; x++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
yp = -radius * w;
for (i = -radius; i <= radius; i++) {
yi = MAX(0, yp) + x;
sir = stack[i + radius];
sir[0] = r[yi];
sir[1] = g[yi];
sir[2] = b[yi];
rbs = r1 - ABS(i);
rsum += r[yi] * rbs;
gsum += g[yi] * rbs;
bsum += b[yi] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
}
else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
if (i < hm) {
yp += w;
}
}
yi = x;
stackpointer = radius;
for (y = 0; y < h; y++) {
// Not have alpha channel
pix[yi] = ((((dv[rsum]) >> 3) << 11) | (((dv[gsum]) >> 2) << 5) | ((dv[bsum]) >> 3));
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (x == 0) {
vmin[y] = MIN(y + r1, hm) * w;
}
p = x + vmin[y];
sir[0] = r[p];
sir[1] = g[p];
sir[2] = b[p];
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[stackpointer];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi += w;
}
}
free(r);
free(g);
free(b);
free(vmin);
free(dv);
free(stack);
return (pix);
}
|
the_stack_data/34694.c | #include <stdio.h>
int main(void) {
const char baseDigits[16] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
int convertedNumber[64];
long int numberToConvert;
int nextDigit, base, index = 0;
// get the number and the base
printf ( "Number to be converted? ");
scanf ( "%ld", &numberToConvert);
printf ( "Base? ");
scanf ( "%i", &base);
// convert to the indicated base
do {
convertedNumber[index] = numberToConvert % base;
++index;
numberToConvert = numberToConvert / base;
}
while ( numberToConvert != 0);
// display the results in reverse order
printf ( "Converted number = ");
for ( --index; index >= 0; --index ) {
nextDigit = convertedNumber[index];
printf ( "%c", baseDigits[nextDigit] );
}
printf ( "\n" );
return 0;
}
|
the_stack_data/87638179.c | #include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <poll.h>
#include <unistd.h>
#include <getopt.h>
#include <time.h>
#include <linux/serial.h>
#include <errno.h>
// command line args
int _cl_baud = 0;
char *_cl_port = NULL;
int _cl_divisor = 0;
int _cl_rx_dump = 0;
int _cl_rx_dump_ascii = 0;
int _cl_tx_detailed = 0;
int _cl_stats = 0;
int _cl_stop_on_error = 0;
int _cl_single_byte = -1;
int _cl_another_byte = -1;
int _cl_rts_cts = 0;
int _cl_2_stop_bit = 0;
int _cl_parity = 0;
int _cl_odd_parity = 0;
int _cl_stick_parity = 0;
int _cl_dump_err = 0;
int _cl_no_rx = 0;
int _cl_no_tx = 0;
int _cl_rx_delay = 0;
int _cl_tx_delay = 0;
int _cl_tx_bytes = 0;
int _cl_rs485_delay = -1;
int _cl_tx_time = 0;
int _cl_rx_time = 0;
// Module variables
unsigned char _write_count_value = 0;
unsigned char _read_count_value = 0;
int _fd = -1;
unsigned char * _write_data;
ssize_t _write_size;
// keep our own counts for cases where the driver stats don't work
int _write_count = 0;
int _read_count = 0;
int _error_count = 0;
void dump_data(unsigned char * b, int count) {
printf("%i bytes: ", count);
int i;
for (i=0; i < count; i++) {
printf("%02x ", b[i]);
}
printf("\n");
}
void dump_data_ascii(unsigned char * b, int count) {
int i;
for (i=0; i < count; i++) {
printf("%c", b[i]);
}
}
void set_baud_divisor(int speed)
{
// default baud was not found, so try to set a custom divisor
struct serial_struct ss;
if (ioctl(_fd, TIOCGSERIAL, &ss) != 0) {
printf("TIOCGSERIAL failed\n");
exit(1);
}
ss.flags = (ss.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST;
ss.custom_divisor = (ss.baud_base + (speed/2)) / speed;
int closest_speed = ss.baud_base / ss.custom_divisor;
if (closest_speed < speed * 98 / 100 || closest_speed > speed * 102 / 100) {
printf("Cannot set speed to %d, closest is %d\n", speed, closest_speed);
exit(1);
}
printf("closest baud = %i, base = %i, divisor = %i\n", closest_speed, ss.baud_base,
ss.custom_divisor);
if (ioctl(_fd, TIOCSSERIAL, &ss) < 0) {
printf("TIOCSSERIAL failed\n");
exit(1);
}
}
// converts integer baud to Linux define
int get_baud(int baud)
{
switch (baud) {
case 9600:
return B9600;
case 19200:
return B19200;
case 38400:
return B38400;
case 57600:
return B57600;
case 115200:
return B115200;
case 230400:
return B230400;
case 460800:
return B460800;
case 500000:
return B500000;
case 576000:
return B576000;
case 921600:
return B921600;
case 1000000:
return B1000000;
case 1152000:
return B1152000;
case 1500000:
return B1500000;
case 2000000:
return B2000000;
case 2500000:
return B2500000;
case 3000000:
return B3000000;
case 3500000:
return B3500000;
case 4000000:
return B4000000;
default:
return -1;
}
}
void display_help()
{
printf("Usage: linux-serial-test [OPTION]\n"
"\n"
" -h, --help\n"
" -b, --baud Baud rate, 115200, etc (115200 is default)\n"
" -p, --port Port (/dev/ttyS0, etc) (must be specified)\n"
" -d, --divisor UART Baud rate divisor (can be used to set custom baud rates)\n"
" -R, --rx_dump Dump Rx data (ascii, raw)\n"
" -T, --detailed_tx Detailed Tx data\n"
" -s, --stats Dump serial port stats every 5s\n"
" -S, --stop-on-err Stop program if we encounter an error\n"
" -y, --single-byte Send specified byte to the serial port\n"
" -z, --second-byte Send another specified byte to the serial port\n"
" -c, --rts-cts Enable RTS/CTS flow control\n"
" -B, --2-stop-bit Use two stop bits per character\n"
" -P, --parity Use parity bit (odd, even, mark, space)\n"
" -e, --dump-err Display errors\n"
" -r, --no-rx Don't receive data (can be used to test flow control)\n"
" when serial driver buffer is full\n"
" -t, --no-tx Don't transmit data\n"
" -l, --rx-delay Delay between reading data (ms) (can be used to test flow control)\n"
" -a, --tx-delay Delay between writing data (ms)\n"
" -w, --tx-bytes Number of bytes for each write (default is to repeatedly write 1024 bytes\n"
" until no more are accepted)\n"
" -q, --rs485 Enable RS485 direction control on port, and set delay\n"
" from when TX is finished and RS485 driver enable is\n"
" de-asserted. Delay is specified in bit times.\n"
" -o, --tx-time Number of seconds to transmit for (defaults to 0, meaning no limit)\n"
" -i, --rx-time Number of seconds to receive for (defaults to 0, meaning no limit)\n"
"\n"
);
exit(0);
}
void process_options(int argc, char * argv[])
{
for (;;) {
int option_index = 0;
static const char *short_options = "hb:p:d:R:TsSy:z:cBertq:l:a:w:o:i:P:";
static const struct option long_options[] = {
{"help", no_argument, 0, 0},
{"baud", required_argument, 0, 'b'},
{"port", required_argument, 0, 'p'},
{"divisor", required_argument, 0, 'd'},
{"rx_dump", required_argument, 0, 'R'},
{"detailed_tx", no_argument, 0, 'T'},
{"stats", no_argument, 0, 's'},
{"stop-on-err", no_argument, 0, 'S'},
{"single-byte", no_argument, 0, 'y'},
{"second-byte", no_argument, 0, 'z'},
{"rts-cts", no_argument, 0, 'c'},
{"2-stop-bit", no_argument, 0, 'B'},
{"parity", required_argument, 0, 'P'},
{"dump-err", no_argument, 0, 'e'},
{"no-rx", no_argument, 0, 'r'},
{"no-tx", no_argument, 0, 't'},
{"rx-delay", required_argument, 0, 'l'},
{"tx-delay", required_argument, 0, 'a'},
{"tx-bytes", required_argument, 0, 'w'},
{"rs485", required_argument, 0, 'q'},
{"tx-time", required_argument, 0, 'o'},
{"rx-time", required_argument, 0, 'i'},
{0,0,0,0},
};
int c = getopt_long(argc, argv, short_options,
long_options, &option_index);
if (c == EOF) {
break;
}
switch (c) {
case 0:
display_help();
break;
case 'h':
display_help();
break;
case 'b':
_cl_baud = atoi(optarg);
break;
case 'p':
_cl_port = strdup(optarg);
break;
case 'd':
_cl_divisor = atoi(optarg);
break;
case 'R':
_cl_rx_dump = 1;
_cl_rx_dump_ascii = !strcmp(optarg, "ascii");
break;
case 'T':
_cl_tx_detailed = 1;
break;
case 's':
_cl_stats = 1;
break;
case 'S':
_cl_stop_on_error = 1;
break;
case 'y': {
char * endptr;
_cl_single_byte = strtol(optarg, &endptr, 0);
break;
}
case 'z': {
char * endptr;
_cl_another_byte = strtol(optarg, &endptr, 0);
break;
}
case 'c':
_cl_rts_cts = 1;
break;
case 'B':
_cl_2_stop_bit = 1;
break;
case 'P':
_cl_parity = 1;
_cl_odd_parity = (!strcmp(optarg, "mark")||!strcmp(optarg, "odd"));
_cl_stick_parity = (!strcmp(optarg, "mark")||!strcmp(optarg, "space"));
break;
case 'e':
_cl_dump_err = 1;
break;
case 'r':
_cl_no_rx = 1;
break;
case 't':
_cl_no_tx = 1;
break;
case 'l': {
char *endptr;
_cl_rx_delay = strtol(optarg, &endptr, 0);
break;
}
case 'a': {
char *endptr;
_cl_tx_delay = strtol(optarg, &endptr, 0);
break;
}
case 'w': {
char *endptr;
_cl_tx_bytes = strtol(optarg, &endptr, 0);
break;
}
case 'q': {
char *endptr;
_cl_rs485_delay = strtol(optarg, &endptr, 0);
break;
}
case 'o': {
char *endptr;
_cl_tx_time = strtol(optarg, &endptr, 0);
break;
}
case 'i': {
char *endptr;
_cl_rx_time = strtol(optarg, &endptr, 0);
break;
}
}
}
}
void dump_serial_port_stats()
{
struct serial_icounter_struct icount = { 0 };
printf("%s: count for this session: rx=%i, tx=%i, rx err=%i\n", _cl_port, _read_count, _write_count, _error_count);
int ret = ioctl(_fd, TIOCGICOUNT, &icount);
if (ret != -1) {
printf("%s: TIOCGICOUNT: ret=%i, rx=%i, tx=%i, frame = %i, overrun = %i, parity = %i, brk = %i, buf_overrun = %i\n",
_cl_port, ret, icount.rx, icount.tx, icount.frame, icount.overrun, icount.parity, icount.brk,
icount.buf_overrun);
}
}
void process_read_data()
{
unsigned char rb[1024];
int c = read(_fd, &rb, sizeof(rb));
if (c > 0) {
if (_cl_rx_dump) {
if (_cl_rx_dump_ascii)
dump_data_ascii(rb, c);
else
dump_data(rb, c);
}
// verify read count is incrementing
int i;
for (i = 0; i < c; i++) {
if (rb[i] != _read_count_value) {
if (_cl_dump_err) {
printf("Error, count: %i, expected %02x, got %02x\n",
_read_count + i, _read_count_value, rb[i]);
}
_error_count++;
if (_cl_stop_on_error) {
dump_serial_port_stats();
exit(1);
}
_read_count_value = rb[i];
}
_read_count_value++;
}
_read_count += c;
}
}
void process_write_data()
{
ssize_t count = 0;
int repeat = (_cl_tx_bytes == 0);
do
{
ssize_t i;
for (i = 0; i < _write_size; i++) {
_write_data[i] = _write_count_value;
_write_count_value++;
}
ssize_t c = write(_fd, _write_data, _write_size);
if (c < 0) {
printf("write failed (%d)\n", errno);
c = 0;
}
count += c;
if (c < _write_size) {
_write_count_value -= _write_size - c;
repeat = 0;
}
} while (repeat);
_write_count += count;
if (_cl_tx_detailed)
printf("wrote %zd bytes\n", count);
}
void setup_serial_port(int baud)
{
struct termios newtio;
_fd = open(_cl_port, O_RDWR | O_NONBLOCK);
if (_fd < 0) {
printf("Error opening serial port \n");
free(_cl_port);
exit(1);
}
bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */
/* man termios get more info on below settings */
newtio.c_cflag = baud | CS8 | CLOCAL | CREAD;
if (_cl_rts_cts) {
newtio.c_cflag |= CRTSCTS;
}
if (_cl_2_stop_bit) {
newtio.c_cflag |= CSTOPB;
}
if (_cl_parity) {
newtio.c_cflag |= PARENB;
if (_cl_odd_parity) {
newtio.c_cflag |= PARODD;
}
if (_cl_stick_parity) {
newtio.c_cflag |= CMSPAR;
}
}
newtio.c_iflag = 0;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
// block for up till 128 characters
newtio.c_cc[VMIN] = 128;
// 0.5 seconds read timeout
newtio.c_cc[VTIME] = 5;
/* now clean the modem line and activate the settings for the port */
tcflush(_fd, TCIOFLUSH);
tcsetattr(_fd,TCSANOW,&newtio);
/* enable rs485 direction control */
if (_cl_rs485_delay >= 0) {
struct serial_rs485 rs485;
if(ioctl(_fd, TIOCGRS485, &rs485) < 0) {
printf("Error getting rs485 mode\n");
} else {
rs485.flags |= SER_RS485_ENABLED | SER_RS485_RTS_ON_SEND | SER_RS485_RTS_AFTER_SEND;
rs485.delay_rts_after_send = _cl_rs485_delay;
rs485.delay_rts_before_send = 0;
if(ioctl(_fd, TIOCSRS485, &rs485) < 0) {
printf("Error setting rs485 mode\n");
}
}
}
}
int diff_ms(const struct timespec *t1, const struct timespec *t2)
{
struct timespec diff;
diff.tv_sec = t1->tv_sec - t2->tv_sec;
diff.tv_nsec = t1->tv_nsec - t2->tv_nsec;
if (diff.tv_nsec < 0) {
diff.tv_sec--;
diff.tv_nsec += 1000000000;
}
return (diff.tv_sec * 1000 + diff.tv_nsec/1000000);
}
int main(int argc, char * argv[])
{
printf("Linux serial test app\n");
process_options(argc, argv);
if (!_cl_port) {
printf("ERROR: Port argument required\n");
display_help();
}
int baud = B115200;
if (_cl_baud)
baud = get_baud(_cl_baud);
if (baud <= 0) {
printf("NOTE: non standard baud rate, trying custom divisor\n");
baud = B38400;
setup_serial_port(B38400);
set_baud_divisor(_cl_baud);
} else {
setup_serial_port(baud);
}
if (_cl_single_byte >= 0) {
unsigned char data[2];
data[0] = (unsigned char)_cl_single_byte;
if (_cl_another_byte < 0) {
write(_fd, &data, 1);
} else {
data[1] = _cl_another_byte;
write(_fd, &data, 2);
}
return 0;
}
_write_size = (_cl_tx_bytes == 0) ? 1024 : _cl_tx_bytes;
_write_data = malloc(_write_size);
if (_write_data == NULL) {
printf("ERROR: Memory allocation failed\n");
}
struct pollfd serial_poll;
serial_poll.fd = _fd;
if (!_cl_no_rx) {
serial_poll.events |= POLLIN;
} else {
serial_poll.events &= ~POLLIN;
}
if (!_cl_no_tx) {
serial_poll.events |= POLLOUT;
} else {
serial_poll.events &= ~POLLOUT;
}
struct timespec start_time, last_stat;
struct timespec last_read = { .tv_sec = 0, .tv_nsec = 0 };
struct timespec last_write = { .tv_sec = 0, .tv_nsec = 0 };
clock_gettime(CLOCK_MONOTONIC, &start_time);
last_stat = start_time;
while (!(_cl_no_rx && _cl_no_tx)) {
int retval = poll(&serial_poll, 1, 1000);
if (retval == -1) {
perror("poll()");
} else if (retval) {
if (serial_poll.revents & POLLIN) {
if (_cl_rx_delay) {
// only read if it has been rx-delay ms
// since the last read
struct timespec current;
clock_gettime(CLOCK_MONOTONIC, ¤t);
if (diff_ms(¤t, &last_read) > _cl_rx_delay) {
process_read_data();
last_read = current;
}
} else {
process_read_data();
}
}
if (serial_poll.revents & POLLOUT) {
if (_cl_tx_delay) {
// only write if it has been tx-delay ms
// since the last write
struct timespec current;
clock_gettime(CLOCK_MONOTONIC, ¤t);
if (diff_ms(¤t, &last_write) > _cl_tx_delay) {
process_write_data();
last_write = current;
}
} else {
process_write_data();
}
}
} else if (!(_cl_no_tx && _write_count != 0 && _write_count == _read_count)) {
// No data. We report this unless we are no longer
// transmitting and the receive count equals the
// transmit count, suggesting a loopback test that has
// finished.
printf("No data within one second.\n");
}
if (_cl_stats || _cl_tx_time || _cl_rx_time) {
struct timespec current;
clock_gettime(CLOCK_MONOTONIC, ¤t);
if (_cl_stats) {
if (current.tv_sec - last_stat.tv_sec > 5) {
dump_serial_port_stats();
last_stat = current;
}
}
if (_cl_tx_time) {
if (current.tv_sec - start_time.tv_sec >= _cl_tx_time) {
_cl_tx_time = 0;
_cl_no_tx = 1;
serial_poll.events &= ~POLLOUT;
printf("Stopped transmitting.\n");
}
}
if (_cl_rx_time) {
if (current.tv_sec - start_time.tv_sec >= _cl_rx_time) {
_cl_rx_time = 0;
_cl_no_rx = 1;
serial_poll.events &= ~POLLIN;
printf("Stopped receiving.\n");
}
}
}
}
dump_serial_port_stats();
tcflush(_fd, TCIOFLUSH);
free(_cl_port);
int result = abs(_write_count - _read_count) + _error_count;
return (result > 255) ? 255 : result;
}
|
the_stack_data/6387309.c | //
// main.c
// my
//
// Created by Nat! on 05.11.17.
// Copyright © 2017 Mulle kybernetiK. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
return 0;
}
|
the_stack_data/43888877.c | #include <errno.h>
#include <sys/types.h>
#include "syscall.h"
int fchmod(int fd, mode_t mode)
{
int ret = __syscall(91, fd, mode, 0, 0, 0, 0);
if (ret < 0) {
errno = -ret;
return -1;
}
return 0;
}
|
the_stack_data/6082.c | int k=43234;
|
the_stack_data/3262592.c | /*Exercise 2 - Selection
Write a program to calculate the amount to be paid for a rented vehicle.
• Input the distance the van has travelled
• The first 30 km is at a rate of 50/= per km.
• The remaining distance is calculated at the rate of 40/= per km.
e.g.
Distance -> 20
Amount = 20 x 50 = 1000
Distance -> 50
Amount = 30 x 50 + (50-30) x 40 = 2300*/
#include <stdio.h>
int main() {
int distance;
float amount;
printf("Distance -> ");
scanf("%d", &distance);
if (distance <= 30)
{
amount = distance * 50;
}
else
{
distance = distance - 30;
amount = (30 * 50) + (distance * 40);
}
printf("Amount = %.2f\n", amount);
return 0;
}
|
the_stack_data/243893739.c | /* Density of Binary Tree = Size / Height */
#include<stdio.h> //For standard input / output operations
#include<stdlib.h> //For dynamic declaration of Node using malloc
struct Node { //Struct for a Node in the tree
int data; //Data stored in this node
struct Node *left, *right; //Pointer to left and right child
};
struct Node* newNode(int data) { //Function for defining a New Node
struct Node* node = malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL; //Initialize left and right child as 0
return node;
}
int heightAndSize(struct Node* node, int *size) {
if (node==NULL) //Left node
return 0;
int left_child_height = heightAndSize(node->left, size); //Recursively calls of the function for its left child
int right_child_height = heightAndSize(node->right, size); //Recursively calls of the function for its right child
*size=*size+1; //Increments size by 1 on traversal of each node
return (left_child_height > right_child_height) ? left_child_height + 1 : right_child_height + 1; //Returns the larger height among it's left and right child and adds 1 to account for itself
}
float density(struct Node* root){ //Function to calculate density by passing root of tree
if (root == NULL) //Incase root is Null , tree will be empty and hence density is 0
return 0;
int size, tree_height;
size = 0; //Initialize size of the tree as 0
tree_height = heightAndSize(root, &size); //Calls function to find height and size of the tree (returns height and increments size by address of parameter)
return (float)size/tree_height;
}
int main(){
struct Node* root = newNode(1); //Root of tree
root->left = newNode(2); //Child Node
root->right = newNode(3); //Child Node
root->right->left = newNode(4); //Child Node
// For current example, height = 3 and size = 4 hence density should be 1.3333
printf("Density of given binary tree is %f", density(root)); //Prints density
return 0;
} |
the_stack_data/154828617.c | /**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the mingw-w64 runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
#define SPECIAL_CRTEXE
#include <fcntl.h>
#include <stdlib.h>
|
the_stack_data/776784.c | /**************************************************************************//**
* @file startup_em355x.c
* @brief Startup file for GCC compilers
* Should be used with GCC 'GNU Tools ARM Embedded'
* @version 5.8.3
******************************************************************************
* @section License
* <b>(C) Copyright 2018 Silicon Labs, www.silabs.com</b>
*******************************************************************************
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
* DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Silicon Labs has no
* obligation to support this Software. Silicon Labs is providing the
* Software "AS IS", with no express or implied warranties of any kind,
* including, but not limited to, any implied warranties of merchantability
* or fitness for any particular purpose or warranties against infringement
* of any proprietary rights of a third party.
*
* Silicon Labs will not be liable for any consequential, incidental, or
* special damages, or any other relief, or for any claim by any third party,
* arising from your use of this Software.
*
******************************************************************************/
#include <stdint.h>
#include <stdbool.h>
/*----------------------------------------------------------------------------
* Linker generated Symbols
*----------------------------------------------------------------------------*/
extern uint32_t __etext;
extern uint32_t __data_start__;
extern uint32_t __data_end__;
extern uint32_t __copy_table_start__;
extern uint32_t __copy_table_end__;
extern uint32_t __zero_table_start__;
extern uint32_t __zero_table_end__;
extern uint32_t __bss_start__;
extern uint32_t __bss_end__;
extern uint32_t __StackTop;
/*----------------------------------------------------------------------------
* Exception / Interrupt Handler Function Prototype
*----------------------------------------------------------------------------*/
typedef union {
void (*pFunc)(void);
void *topOfStack;
} tVectorEntry;
/*----------------------------------------------------------------------------
* External References
*----------------------------------------------------------------------------*/
#ifndef __START
extern void _start(void) __attribute__((noreturn)); /* Pre Main (C library entry point) */
#else
extern int __START(void) __attribute__((noreturn)); /* main entry point */
#endif
#ifndef __NO_SYSTEM_INIT
extern void SystemInit(void); /* CMSIS System Initialization */
#endif
/*----------------------------------------------------------------------------
* Internal References
*----------------------------------------------------------------------------*/
void Default_Handler(void); /* Default empty handler */
void Reset_Handler(void); /* Reset Handler */
/*----------------------------------------------------------------------------
* User Initial Stack & Heap
*----------------------------------------------------------------------------*/
#ifndef __STACK_SIZE
#define __STACK_SIZE 0x00000400
#endif
static uint8_t stack[__STACK_SIZE] __attribute__ ((aligned(8), used, section(".stack")));
#ifndef __HEAP_SIZE
#define __HEAP_SIZE 0x00000C00
#endif
#if __HEAP_SIZE > 0
static uint8_t heap[__HEAP_SIZE] __attribute__ ((aligned(8), used, section(".heap")));
#endif
/*----------------------------------------------------------------------------
* Exception / Interrupt Handler
*----------------------------------------------------------------------------*/
/* Cortex-M Processor Exceptions */
void NMI_Handler(void) __attribute__ ((weak, alias("Default_Handler")));
void HardFault_Handler(void) __attribute__ ((weak, alias("Default_Handler")));
void MemManage_Handler(void) __attribute__ ((weak, alias("Default_Handler")));
void BusFault_Handler(void) __attribute__ ((weak, alias("Default_Handler")));
void UsageFault_Handler(void) __attribute__ ((weak, alias("Default_Handler")));
void DebugMon_Handler(void) __attribute__ ((weak, alias("Default_Handler")));
void SVC_Handler(void) __attribute__ ((weak, alias("Default_Handler")));
void PendSV_Handler(void) __attribute__ ((weak, alias("Default_Handler")));
void SysTick_Handler(void) __attribute__ ((weak, alias("Default_Handler")));
/* Part Specific Interrupts */
void TIM1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void TIM2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void MGMT_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void BB_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void SLEEPTMR_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void SC1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void SC2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void AESCCM_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void MACTMR_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void MACTX_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void MACRX_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void ADC_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void IRQA_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void IRQB_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void IRQC_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void IRQD_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void DEBUG_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void SC3_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void SC4_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
void USB_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler")));
/*----------------------------------------------------------------------------
* Exception / Interrupt Vector table
*----------------------------------------------------------------------------*/
#if defined (__ICCARM__)
#pragma data_alignment=256
#endif
extern const tVectorEntry __Vectors[];
const tVectorEntry __Vectors[] __attribute__ ((section(".vectors"))) = {
/* Cortex-M Exception Handlers */
{ .topOfStack = &__StackTop }, /* Initial Stack Pointer */
{ Reset_Handler }, /* Reset Handler */
{ NMI_Handler }, /* NMI Handler */
{ HardFault_Handler }, /* Hard Fault Handler */
{ MemManage_Handler }, /* MPU Fault Handler */
{ BusFault_Handler }, /* Bus Fault Handler */
{ UsageFault_Handler }, /* Usage Fault Handler */
{ Default_Handler }, /* Reserved */
{ Default_Handler }, /* Reserved */
{ Default_Handler }, /* Reserved */
{ Default_Handler }, /* Reserved */
{ SVC_Handler }, /* SVCall Handler */
{ DebugMon_Handler }, /* Debug Monitor Handler */
{ Default_Handler }, /* Reserved */
{ PendSV_Handler }, /* PendSV Handler */
{ SysTick_Handler }, /* SysTick Handler */
/* External interrupts */
{ TIM1_IRQHandler }, /*0 - TIM1 */
{ TIM2_IRQHandler }, /*1 - TIM2 */
{ MGMT_IRQHandler }, /*2 - MGMT */
{ BB_IRQHandler }, /*3 - BB */
{ SLEEPTMR_IRQHandler }, /*4 - SLEEPTMR */
{ SC1_IRQHandler }, /*5 - SC1 */
{ SC2_IRQHandler }, /*6 - SC2 */
{ AESCCM_IRQHandler }, /*7 - AESCCM */
{ MACTMR_IRQHandler }, /*8 - MACTMR */
{ MACTX_IRQHandler }, /*9 - MACTX */
{ MACRX_IRQHandler }, /*10 - MACRX */
{ ADC_IRQHandler }, /*11 - ADC */
{ IRQA_IRQHandler }, /*12 - IRQA */
{ IRQB_IRQHandler }, /*13 - IRQB */
{ IRQC_IRQHandler }, /*14 - IRQC */
{ IRQD_IRQHandler }, /*15 - IRQD */
{ DEBUG_IRQHandler }, /*16 - DEBUG */
{ SC3_IRQHandler }, /*17 - SC3 */
{ SC4_IRQHandler }, /*18 - SC4 */
{ USB_IRQHandler }, /*19 - USB */
};
//
// Start Handler called by SystemInit to start the main program running.
// Since IAR and GCC have very different semantics for this, they are
// wrapped in this function that can be called by common code without
// worrying about which compiler is being used.
//
void Start_Handler(void)
{
uint32_t *pSrc, *pDest;
uint32_t *pTable __attribute__((unused));
/* Firstly it copies data from read only memory to RAM. There are two schemes
* to copy. One can copy more than one sections. Another can only copy
* one section. The former scheme needs more instructions and read-only
* data to implement than the latter.
* Macro __STARTUP_COPY_MULTIPLE is used to choose between two schemes. */
#ifdef __STARTUP_COPY_MULTIPLE
/* Multiple sections scheme.
*
* Between symbol address __copy_table_start__ and __copy_table_end__,
* there are array of triplets, each of which specify:
* offset 0: LMA of start of a section to copy from
* offset 4: VMA of start of a section to copy to
* offset 8: size of the section to copy. Must be multiply of 4
*
* All addresses must be aligned to 4 bytes boundary.
*/
pTable = &__copy_table_start__;
for (; pTable < &__copy_table_end__; pTable = pTable + 3) {
pSrc = (uint32_t *) *(pTable + 0);
pDest = (uint32_t *) *(pTable + 1);
for (; pDest < (uint32_t *) (*(pTable + 1) + *(pTable + 2)); ) {
*pDest++ = *pSrc++;
}
}
#else
/* Single section scheme.
*
* The ranges of copy from/to are specified by following symbols
* __etext: LMA of start of the section to copy from. Usually end of text
* __data_start__: VMA of start of the section to copy to
* __data_end__: VMA of end of the section to copy to
*
* All addresses must be aligned to 4 bytes boundary.
*/
pSrc = &__etext;
pDest = &__data_start__;
for (; pDest < &__data_end__; ) {
*pDest++ = *pSrc++;
}
#endif /*__STARTUP_COPY_MULTIPLE */
/* This part of work usually is done in C library startup code. Otherwise,
* define this macro to enable it in this startup.
*
* There are two schemes too. One can clear multiple BSS sections. Another
* can only clear one section. The former is more size expensive than the
* latter.
*
* Define macro __STARTUP_CLEAR_BSS_MULTIPLE to choose the former.
* Otherwise efine macro __STARTUP_CLEAR_BSS to choose the later.
*/
#ifdef __STARTUP_CLEAR_BSS_MULTIPLE
/* Multiple sections scheme.
*
* Between symbol address __copy_table_start__ and __copy_table_end__,
* there are array of tuples specifying:
* offset 0: Start of a BSS section
* offset 4: Size of this BSS section. Must be multiply of 4
*/
pTable = &__zero_table_start__;
for (; pTable < &__zero_table_end__; pTable = pTable + 2) {
pDest = (uint32_t *) *(pTable + 0);
for (; pDest < (uint32_t *) (*(pTable + 0) + *(pTable + 1)); ) {
*pDest++ = 0UL;
}
}
#elif defined (__STARTUP_CLEAR_BSS)
/* Single BSS section scheme.
*
* The BSS section is specified by following symbols
* __bss_start__: start of the BSS section.
* __bss_end__: end of the BSS section.
*
* Both addresses must be aligned to 4 bytes boundary.
*/
pDest = &__bss_start__;
for (; pDest < &__bss_end__; ) {
*pDest++ = 0UL;
}
#endif /* __STARTUP_CLEAR_BSS_MULTIPLE || __STARTUP_CLEAR_BSS */
#ifndef __START
#define __START _start
#endif
__START();
}
/*----------------------------------------------------------------------------
* Reset Handler called on controller reset
*----------------------------------------------------------------------------*/
void Reset_Handler(void)
{
#ifndef __NO_SYSTEM_INIT
SystemInit();
#else
Start_Handler();
#endif
}
/*----------------------------------------------------------------------------
* Default Handler for Exceptions / Interrupts
*----------------------------------------------------------------------------*/
void Default_Handler(void)
{
// The Default_Handler is for unimplemented handlers. Trap execution.
while (true) {
}
}
/*----------------------------------------------------------------------------
* Exit function, in case main ever accidentally returns.
*
* A GCC compilation that uses more than "nosys.specs" needs an exit() function.
* Ideally once START passes control to main, the code should never return.
*----------------------------------------------------------------------------*/
void exit(int status)
{
// Trap execution in case main accidentally returns.
while (true) {
}
}
|
the_stack_data/1246284.c | #ifdef _WIN32
#include <windows.h>
#include <stdarg.h>
#include <stdio.h>
#include <errno.h>
#ifndef FOREGROUND_MASK
# define FOREGROUND_MASK (FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_INTENSITY)
#endif
#ifndef BACKGROUND_MASK
# define BACKGROUND_MASK (BACKGROUND_RED|BACKGROUND_BLUE|BACKGROUND_GREEN|BACKGROUND_INTENSITY)
#endif
int
__write_w32(FILE* fp, const char* buf) {
static WORD attr_olds[2] = {-1, -1}, attr_old;
static int first = 1;
int type;
HANDLE handle = INVALID_HANDLE_VALUE;
WORD attr;
DWORD written, csize;
CONSOLE_CURSOR_INFO cci;
CONSOLE_SCREEN_BUFFER_INFO csbi;
COORD coord;
const char *ptr = buf;
if (fp == stdout) {
type = 0;
} else if (fp == stderr) {
type = 1;
} else {
type = 0;
}
handle = (HANDLE) _get_osfhandle(fileno(fp));
GetConsoleScreenBufferInfo(handle, &csbi);
attr = csbi.wAttributes;
if (attr_olds[type] == (WORD) -1) {
attr_olds[type] = attr;
}
attr_old = attr;
while (*ptr) {
if (*ptr == '\033') {
unsigned char c;
int i, n = 0, m, v[6], w, h;
for (i = 0; i < 6; i++) v[i] = -1;
ptr++;
retry:
if ((c = *ptr++) == 0) break;
if (isdigit(c)) {
if (v[n] == -1) v[n] = c - '0';
else v[n] = v[n] * 10 + c - '0';
goto retry;
}
if (c == '[') {
goto retry;
}
if (c == ';') {
if (++n == 6) break;
goto retry;
}
if (c == '>' || c == '?') {
m = c;
goto retry;
}
switch (c) {
case 'h':
if (m == '?') {
for (i = 0; i <= n; i++) {
switch (v[i]) {
case 3:
GetConsoleScreenBufferInfo(handle, &csbi);
w = csbi.dwSize.X;
h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
csize = w * (h + 1);
coord.X = 0;
coord.Y = csbi.srWindow.Top;
FillConsoleOutputCharacter(handle, ' ', csize, coord, &written);
FillConsoleOutputAttribute(handle, csbi.wAttributes, csize, coord, &written);
SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
csbi.dwSize.X = 132;
SetConsoleScreenBufferSize(handle, csbi.dwSize);
csbi.srWindow.Right = csbi.srWindow.Left + 131;
SetConsoleWindowInfo(handle, TRUE, &csbi.srWindow);
break;
case 5:
attr =
((attr & FOREGROUND_MASK) << 4) |
((attr & BACKGROUND_MASK) >> 4);
SetConsoleTextAttribute(handle, attr);
break;
case 9:
break;
case 25:
GetConsoleCursorInfo(handle, &cci);
cci.bVisible = TRUE;
SetConsoleCursorInfo(handle, &cci);
break;
case 47:
coord.X = 0;
coord.Y = 0;
SetConsoleCursorPosition(handle, coord);
break;
default:
break;
}
}
} else if (m == '>' && v[0] == 5) {
GetConsoleCursorInfo(handle, &cci);
cci.bVisible = FALSE;
SetConsoleCursorInfo(handle, &cci);
}
break;
case 'l':
if (m == '?') {
for (i = 0; i <= n; i++) {
switch (v[i]) {
case 3:
GetConsoleScreenBufferInfo(handle, &csbi);
w = csbi.dwSize.X;
h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
csize = w * (h + 1);
coord.X = 0;
coord.Y = csbi.srWindow.Top;
FillConsoleOutputCharacter(handle, ' ', csize, coord, &written);
FillConsoleOutputAttribute(handle, csbi.wAttributes, csize, coord, &written);
SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
csbi.srWindow.Right = csbi.srWindow.Left + 79;
SetConsoleWindowInfo(handle, TRUE, &csbi.srWindow);
csbi.dwSize.X = 80;
SetConsoleScreenBufferSize(handle, csbi.dwSize);
break;
case 5:
attr =
((attr & FOREGROUND_MASK) << 4) |
((attr & BACKGROUND_MASK) >> 4);
SetConsoleTextAttribute(handle, attr);
break;
case 25:
GetConsoleCursorInfo(handle, &cci);
cci.bVisible = FALSE;
SetConsoleCursorInfo(handle, &cci);
break;
default:
break;
}
}
}
else if (m == '>' && v[0] == 5) {
GetConsoleCursorInfo(handle, &cci);
cci.bVisible = TRUE;
SetConsoleCursorInfo(handle, &cci);
}
break;
case 'm':
attr = attr_old;
for (i = 0; i <= n; i++) {
if (v[i] == -1 || v[i] == 0)
attr = attr_olds[type];
else if (v[i] == 1)
attr |= FOREGROUND_INTENSITY;
else if (v[i] == 4)
attr |= FOREGROUND_INTENSITY;
else if (v[i] == 5)
attr |= FOREGROUND_INTENSITY;
else if (v[i] == 7)
attr =
((attr & FOREGROUND_MASK) << 4) |
((attr & BACKGROUND_MASK) >> 4);
else if (v[i] == 10)
; // symbol on
else if (v[i] == 11)
; // symbol off
else if (v[i] == 22)
attr &= ~FOREGROUND_INTENSITY;
else if (v[i] == 24)
attr &= ~FOREGROUND_INTENSITY;
else if (v[i] == 25)
attr &= ~FOREGROUND_INTENSITY;
else if (v[i] == 27)
attr =
((attr & FOREGROUND_MASK) << 4) |
((attr & BACKGROUND_MASK) >> 4);
else if (v[i] >= 30 && v[i] <= 37) {
attr = (attr & BACKGROUND_MASK);
if ((v[i] - 30) & 1)
attr |= FOREGROUND_RED;
if ((v[i] - 30) & 2)
attr |= FOREGROUND_GREEN;
if ((v[i] - 30) & 4)
attr |= FOREGROUND_BLUE;
}
//else if (v[i] == 39)
//attr = (~attr & BACKGROUND_MASK);
else if (v[i] >= 40 && v[i] <= 47) {
attr = (attr & FOREGROUND_MASK);
if ((v[i] - 40) & 1)
attr |= BACKGROUND_RED;
if ((v[i] - 40) & 2)
attr |= BACKGROUND_GREEN;
if ((v[i] - 40) & 4)
attr |= BACKGROUND_BLUE;
}
else if (v[i] >= 90 && v[i] <= 97) {
attr = (attr & BACKGROUND_MASK) | FOREGROUND_INTENSITY;
if ((v[i] - 90) & 1)
attr |= FOREGROUND_RED;
if ((v[i] - 90) & 2)
attr |= FOREGROUND_GREEN;
if ((v[i] - 90) & 4)
attr |= FOREGROUND_BLUE;
}
else if (v[i] >= 100 && v[i] <= 107) {
attr = (attr & FOREGROUND_MASK) | BACKGROUND_INTENSITY;
if ((v[i] - 100) & 1)
attr |= BACKGROUND_RED;
if ((v[i] - 100) & 2)
attr |= BACKGROUND_GREEN;
if ((v[i] - 100) & 4)
attr |= BACKGROUND_BLUE;
}
//else if (v[i] == 49)
//attr = (~attr & FOREGROUND_MASK);
else if (v[i] == 100)
attr = attr_old;
}
SetConsoleTextAttribute(handle, attr);
break;
case 'K':
GetConsoleScreenBufferInfo(handle, &csbi);
coord = csbi.dwCursorPosition;
switch (v[0]) {
default:
case 0:
csize = csbi.dwSize.X - coord.X;
break;
case 1:
csize = coord.X;
coord.X = 0;
break;
case 2:
csize = csbi.dwSize.X;
coord.X = 0;
break;
}
FillConsoleOutputCharacter(handle, ' ', csize, coord, &written);
FillConsoleOutputAttribute(handle, csbi.wAttributes, csize, coord, &written);
SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
break;
case 'J':
GetConsoleScreenBufferInfo(handle, &csbi);
w = csbi.dwSize.X;
h = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
coord = csbi.dwCursorPosition;
switch (v[0]) {
default:
case 0:
csize = w * (h - coord.Y) - coord.X;
coord.X = 0;
break;
case 1:
csize = w * coord.Y + coord.X;
coord.X = 0;
coord.Y = csbi.srWindow.Top;
break;
case 2:
csize = w * (h + 1);
coord.X = 0;
coord.Y = csbi.srWindow.Top;
break;
}
FillConsoleOutputCharacter(handle, ' ', csize, coord, &written);
FillConsoleOutputAttribute(handle, csbi.wAttributes, csize, coord, &written);
SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
break;
case 'H':
GetConsoleScreenBufferInfo(handle, &csbi);
coord = csbi.dwCursorPosition;
if (v[0] != -1) {
if (v[1] != -1) {
coord.Y = csbi.srWindow.Top + v[0] - 1;
coord.X = v[1] - 1;
} else
coord.X = v[0] - 1;
} else {
coord.X = 0;
coord.Y = csbi.srWindow.Top;
}
if (coord.X < csbi.srWindow.Left)
coord.X = csbi.srWindow.Left;
else if (coord.X > csbi.srWindow.Right)
coord.X = csbi.srWindow.Right;
if (coord.Y < csbi.srWindow.Top)
coord.Y = csbi.srWindow.Top;
else if (coord.Y > csbi.srWindow.Bottom)
coord.Y = csbi.srWindow.Bottom;
SetConsoleCursorPosition(handle, coord);
break;
case 'A': // Move up
GetConsoleScreenBufferInfo(handle, &csbi);
coord = csbi.dwCursorPosition;
if (v[0] != -1) coord.Y = coord.Y - v[0];
if (coord.Y < csbi.srWindow.Top) coord.Y = csbi.srWindow.Top;
SetConsoleCursorPosition(handle, coord);
break;
case 'B': // Move down
GetConsoleScreenBufferInfo(handle, &csbi);
coord = csbi.dwCursorPosition;
if (v[0] != -1) coord.Y = coord.Y + v[0];
if (coord.Y > csbi.srWindow.Bottom) coord.Y = csbi.srWindow.Bottom;
SetConsoleCursorPosition(handle, coord);
break;
case 'C': // Move forward / right
GetConsoleScreenBufferInfo(handle, &csbi);
coord = csbi.dwCursorPosition;
if (v[0] != -1) coord.X = coord.X + v[0];
if (coord.X > csbi.srWindow.Right) coord.X = csbi.srWindow.Right;
SetConsoleCursorPosition(handle, coord);
break;
case 'D': // Move backward / left
GetConsoleScreenBufferInfo(handle, &csbi);
coord = csbi.dwCursorPosition;
if (v[0] != -1) coord.X = coord.X - v[0];
if (coord.X < csbi.srWindow.Left) coord.X = csbi.srWindow.Left;
SetConsoleCursorPosition(handle, coord);
break;
default:
break;
}
} else {
putchar(*ptr);
ptr++;
}
}
return ptr - buf;
}
int
_fprintf_w32(FILE* fp, const char* format, ...) {
va_list args;
int r;
char *buf = NULL;
va_start(args, format);
r = vasprintf(&buf, format, args);
va_end(args);
if (r != -1)
r = __write_w32(fp, buf);
if (buf) free(buf);
return r;
}
int
_fputs_w32(FILE* fp, const char* s) {
int r = __write_w32(fp, s);
r += __write_w32(fp, "\n");
return r;
}
#else
#include <stdio.h>
#endif
|
the_stack_data/865026.c | #include <stdio.h>
main()
{
printf("hola mundo");
} |
the_stack_data/62638576.c | // WARNING: kobject bug in ib_register_device
// https://syzkaller.appspot.com/bug?id=805ad726feb6910e35088ae7bbe61f4125e573b7
// status:open
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <netinet/in.h>
#include <sched.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <linux/capability.h>
#include <linux/genetlink.h>
#include <linux/if_addr.h>
#include <linux/if_ether.h>
#include <linux/if_link.h>
#include <linux/if_tun.h>
#include <linux/in6.h>
#include <linux/ip.h>
#include <linux/neighbour.h>
#include <linux/net.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/tcp.h>
#include <linux/veth.h>
unsigned long long procid;
static bool write_file(const char* file, const char* what, ...)
{
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
int err = errno;
close(fd);
errno = err;
return false;
}
close(fd);
return true;
}
struct nlmsg {
char* pos;
int nesting;
struct nlattr* nested[8];
char buf[1024];
};
static struct nlmsg nlmsg;
static void netlink_init(struct nlmsg* nlmsg, int typ, int flags,
const void* data, int size)
{
memset(nlmsg, 0, sizeof(*nlmsg));
struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf;
hdr->nlmsg_type = typ;
hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
memcpy(hdr + 1, data, size);
nlmsg->pos = (char*)(hdr + 1) + NLMSG_ALIGN(size);
}
static void netlink_attr(struct nlmsg* nlmsg, int typ, const void* data,
int size)
{
struct nlattr* attr = (struct nlattr*)nlmsg->pos;
attr->nla_len = sizeof(*attr) + size;
attr->nla_type = typ;
memcpy(attr + 1, data, size);
nlmsg->pos += NLMSG_ALIGN(attr->nla_len);
}
static void netlink_nest(struct nlmsg* nlmsg, int typ)
{
struct nlattr* attr = (struct nlattr*)nlmsg->pos;
attr->nla_type = typ;
nlmsg->pos += sizeof(*attr);
nlmsg->nested[nlmsg->nesting++] = attr;
}
static void netlink_done(struct nlmsg* nlmsg)
{
struct nlattr* attr = nlmsg->nested[--nlmsg->nesting];
attr->nla_len = nlmsg->pos - (char*)attr;
}
static int netlink_send_ext(struct nlmsg* nlmsg, int sock, uint16_t reply_type,
int* reply_len)
{
if (nlmsg->pos > nlmsg->buf + sizeof(nlmsg->buf) || nlmsg->nesting)
exit(1);
struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf;
hdr->nlmsg_len = nlmsg->pos - nlmsg->buf;
struct sockaddr_nl addr;
memset(&addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
unsigned n = sendto(sock, nlmsg->buf, hdr->nlmsg_len, 0,
(struct sockaddr*)&addr, sizeof(addr));
if (n != hdr->nlmsg_len)
exit(1);
n = recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0);
if (hdr->nlmsg_type == NLMSG_DONE) {
*reply_len = 0;
return 0;
}
if (n < sizeof(struct nlmsghdr))
exit(1);
if (reply_len && hdr->nlmsg_type == reply_type) {
*reply_len = n;
return 0;
}
if (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr))
exit(1);
if (hdr->nlmsg_type != NLMSG_ERROR)
exit(1);
return -((struct nlmsgerr*)(hdr + 1))->error;
}
static int netlink_send(struct nlmsg* nlmsg, int sock)
{
return netlink_send_ext(nlmsg, sock, 0, NULL);
}
static int netlink_next_msg(struct nlmsg* nlmsg, unsigned int offset,
unsigned int total_len)
{
struct nlmsghdr* hdr = (struct nlmsghdr*)(nlmsg->buf + offset);
if (offset == total_len || offset + hdr->nlmsg_len > total_len)
return -1;
return hdr->nlmsg_len;
}
static void netlink_add_device_impl(struct nlmsg* nlmsg, const char* type,
const char* name)
{
struct ifinfomsg hdr;
memset(&hdr, 0, sizeof(hdr));
netlink_init(nlmsg, RTM_NEWLINK, NLM_F_EXCL | NLM_F_CREATE, &hdr,
sizeof(hdr));
if (name)
netlink_attr(nlmsg, IFLA_IFNAME, name, strlen(name));
netlink_nest(nlmsg, IFLA_LINKINFO);
netlink_attr(nlmsg, IFLA_INFO_KIND, type, strlen(type));
}
static void netlink_add_device(struct nlmsg* nlmsg, int sock, const char* type,
const char* name)
{
netlink_add_device_impl(nlmsg, type, name);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_veth(struct nlmsg* nlmsg, int sock, const char* name,
const char* peer)
{
netlink_add_device_impl(nlmsg, "veth", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_nest(nlmsg, VETH_INFO_PEER);
nlmsg->pos += sizeof(struct ifinfomsg);
netlink_attr(nlmsg, IFLA_IFNAME, peer, strlen(peer));
netlink_done(nlmsg);
netlink_done(nlmsg);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_hsr(struct nlmsg* nlmsg, int sock, const char* name,
const char* slave1, const char* slave2)
{
netlink_add_device_impl(nlmsg, "hsr", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
int ifindex1 = if_nametoindex(slave1);
netlink_attr(nlmsg, IFLA_HSR_SLAVE1, &ifindex1, sizeof(ifindex1));
int ifindex2 = if_nametoindex(slave2);
netlink_attr(nlmsg, IFLA_HSR_SLAVE2, &ifindex2, sizeof(ifindex2));
netlink_done(nlmsg);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_linked(struct nlmsg* nlmsg, int sock, const char* type,
const char* name, const char* link)
{
netlink_add_device_impl(nlmsg, type, name);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_vlan(struct nlmsg* nlmsg, int sock, const char* name,
const char* link, uint16_t id, uint16_t proto)
{
netlink_add_device_impl(nlmsg, "vlan", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_attr(nlmsg, IFLA_VLAN_ID, &id, sizeof(id));
netlink_attr(nlmsg, IFLA_VLAN_PROTOCOL, &proto, sizeof(proto));
netlink_done(nlmsg);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_macvlan(struct nlmsg* nlmsg, int sock, const char* name,
const char* link)
{
netlink_add_device_impl(nlmsg, "macvlan", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
uint32_t mode = MACVLAN_MODE_BRIDGE;
netlink_attr(nlmsg, IFLA_MACVLAN_MODE, &mode, sizeof(mode));
netlink_done(nlmsg);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_geneve(struct nlmsg* nlmsg, int sock, const char* name,
uint32_t vni, struct in_addr* addr4,
struct in6_addr* addr6)
{
netlink_add_device_impl(nlmsg, "geneve", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_attr(nlmsg, IFLA_GENEVE_ID, &vni, sizeof(vni));
if (addr4)
netlink_attr(nlmsg, IFLA_GENEVE_REMOTE, addr4, sizeof(*addr4));
if (addr6)
netlink_attr(nlmsg, IFLA_GENEVE_REMOTE6, addr6, sizeof(*addr6));
netlink_done(nlmsg);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
#define IFLA_IPVLAN_FLAGS 2
#define IPVLAN_MODE_L3S 2
#undef IPVLAN_F_VEPA
#define IPVLAN_F_VEPA 2
static void netlink_add_ipvlan(struct nlmsg* nlmsg, int sock, const char* name,
const char* link, uint16_t mode, uint16_t flags)
{
netlink_add_device_impl(nlmsg, "ipvlan", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_attr(nlmsg, IFLA_IPVLAN_MODE, &mode, sizeof(mode));
netlink_attr(nlmsg, IFLA_IPVLAN_FLAGS, &flags, sizeof(flags));
netlink_done(nlmsg);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_device_change(struct nlmsg* nlmsg, int sock,
const char* name, bool up, const char* master,
const void* mac, int macsize,
const char* new_name)
{
struct ifinfomsg hdr;
memset(&hdr, 0, sizeof(hdr));
if (up)
hdr.ifi_flags = hdr.ifi_change = IFF_UP;
hdr.ifi_index = if_nametoindex(name);
netlink_init(nlmsg, RTM_NEWLINK, 0, &hdr, sizeof(hdr));
if (new_name)
netlink_attr(nlmsg, IFLA_IFNAME, new_name, strlen(new_name));
if (master) {
int ifindex = if_nametoindex(master);
netlink_attr(nlmsg, IFLA_MASTER, &ifindex, sizeof(ifindex));
}
if (macsize)
netlink_attr(nlmsg, IFLA_ADDRESS, mac, macsize);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static int netlink_add_addr(struct nlmsg* nlmsg, int sock, const char* dev,
const void* addr, int addrsize)
{
struct ifaddrmsg hdr;
memset(&hdr, 0, sizeof(hdr));
hdr.ifa_family = addrsize == 4 ? AF_INET : AF_INET6;
hdr.ifa_prefixlen = addrsize == 4 ? 24 : 120;
hdr.ifa_scope = RT_SCOPE_UNIVERSE;
hdr.ifa_index = if_nametoindex(dev);
netlink_init(nlmsg, RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, &hdr,
sizeof(hdr));
netlink_attr(nlmsg, IFA_LOCAL, addr, addrsize);
netlink_attr(nlmsg, IFA_ADDRESS, addr, addrsize);
return netlink_send(nlmsg, sock);
}
static void netlink_add_addr4(struct nlmsg* nlmsg, int sock, const char* dev,
const char* addr)
{
struct in_addr in_addr;
inet_pton(AF_INET, addr, &in_addr);
int err = netlink_add_addr(nlmsg, sock, dev, &in_addr, sizeof(in_addr));
(void)err;
}
static void netlink_add_addr6(struct nlmsg* nlmsg, int sock, const char* dev,
const char* addr)
{
struct in6_addr in6_addr;
inet_pton(AF_INET6, addr, &in6_addr);
int err = netlink_add_addr(nlmsg, sock, dev, &in6_addr, sizeof(in6_addr));
(void)err;
}
#define DEVLINK_FAMILY_NAME "devlink"
#define DEVLINK_CMD_PORT_GET 5
#define DEVLINK_ATTR_BUS_NAME 1
#define DEVLINK_ATTR_DEV_NAME 2
#define DEVLINK_ATTR_NETDEV_NAME 7
static int netlink_devlink_id_get(struct nlmsg* nlmsg, int sock)
{
struct genlmsghdr genlhdr;
struct nlattr* attr;
int err, n;
uint16_t id = 0;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = CTRL_CMD_GETFAMILY;
netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, DEVLINK_FAMILY_NAME,
strlen(DEVLINK_FAMILY_NAME) + 1);
err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n);
if (err) {
return -1;
}
attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg->buf + n;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == CTRL_ATTR_FAMILY_ID) {
id = *(uint16_t*)(attr + 1);
break;
}
}
if (!id) {
return -1;
}
recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); /* recv ack */
return id;
}
static struct nlmsg nlmsg2;
static void initialize_devlink_ports(const char* bus_name, const char* dev_name,
const char* netdev_prefix)
{
struct genlmsghdr genlhdr;
int len, total_len, id, err, offset;
uint16_t netdev_index;
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (sock == -1)
exit(1);
int rtsock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (rtsock == -1)
exit(1);
id = netlink_devlink_id_get(&nlmsg, sock);
if (id == -1)
goto error;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = DEVLINK_CMD_PORT_GET;
netlink_init(&nlmsg, id, NLM_F_DUMP, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1);
netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1);
err = netlink_send_ext(&nlmsg, sock, id, &total_len);
if (err) {
goto error;
}
offset = 0;
netdev_index = 0;
while ((len = netlink_next_msg(&nlmsg, offset, total_len)) != -1) {
struct nlattr* attr = (struct nlattr*)(nlmsg.buf + offset + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg.buf + offset + len;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == DEVLINK_ATTR_NETDEV_NAME) {
char* port_name;
char netdev_name[IFNAMSIZ];
port_name = (char*)(attr + 1);
snprintf(netdev_name, sizeof(netdev_name), "%s%d", netdev_prefix,
netdev_index);
netlink_device_change(&nlmsg2, rtsock, port_name, true, 0, 0, 0,
netdev_name);
break;
}
}
offset += len;
netdev_index++;
}
error:
close(rtsock);
close(sock);
}
#define DEV_IPV4 "172.20.20.%d"
#define DEV_IPV6 "fe80::%02x"
#define DEV_MAC 0x00aaaaaaaaaa
static void netdevsim_add(unsigned int addr, unsigned int port_count)
{
char buf[16];
sprintf(buf, "%u %u", addr, port_count);
if (write_file("/sys/bus/netdevsim/new_device", buf)) {
snprintf(buf, sizeof(buf), "netdevsim%d", addr);
initialize_devlink_ports("netdevsim", buf, "netdevsim");
}
}
#define WG_GENL_NAME "wireguard"
enum wg_cmd {
WG_CMD_GET_DEVICE,
WG_CMD_SET_DEVICE,
};
enum wgdevice_attribute {
WGDEVICE_A_UNSPEC,
WGDEVICE_A_IFINDEX,
WGDEVICE_A_IFNAME,
WGDEVICE_A_PRIVATE_KEY,
WGDEVICE_A_PUBLIC_KEY,
WGDEVICE_A_FLAGS,
WGDEVICE_A_LISTEN_PORT,
WGDEVICE_A_FWMARK,
WGDEVICE_A_PEERS,
};
enum wgpeer_attribute {
WGPEER_A_UNSPEC,
WGPEER_A_PUBLIC_KEY,
WGPEER_A_PRESHARED_KEY,
WGPEER_A_FLAGS,
WGPEER_A_ENDPOINT,
WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
WGPEER_A_LAST_HANDSHAKE_TIME,
WGPEER_A_RX_BYTES,
WGPEER_A_TX_BYTES,
WGPEER_A_ALLOWEDIPS,
WGPEER_A_PROTOCOL_VERSION,
};
enum wgallowedip_attribute {
WGALLOWEDIP_A_UNSPEC,
WGALLOWEDIP_A_FAMILY,
WGALLOWEDIP_A_IPADDR,
WGALLOWEDIP_A_CIDR_MASK,
};
static int netlink_wireguard_id_get(struct nlmsg* nlmsg, int sock)
{
struct genlmsghdr genlhdr;
struct nlattr* attr;
int err, n;
uint16_t id = 0;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = CTRL_CMD_GETFAMILY;
netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, WG_GENL_NAME,
strlen(WG_GENL_NAME) + 1);
err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n);
if (err) {
return -1;
}
attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg->buf + n;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == CTRL_ATTR_FAMILY_ID) {
id = *(uint16_t*)(attr + 1);
break;
}
}
if (!id) {
return -1;
}
recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); /* recv ack */
return id;
}
static void netlink_wireguard_setup(void)
{
const char ifname_a[] = "wg0";
const char ifname_b[] = "wg1";
const char ifname_c[] = "wg2";
const char private_a[] = "\xa0\x5c\xa8\x4f\x6c\x9c\x8e\x38\x53\xe2\xfd\x7a"
"\x70\xae\x0f\xb2\x0f\xa1\x52\x60\x0c\xb0\x08\x45"
"\x17\x4f\x08\x07\x6f\x8d\x78\x43";
const char private_b[] = "\xb0\x80\x73\xe8\xd4\x4e\x91\xe3\xda\x92\x2c\x22"
"\x43\x82\x44\xbb\x88\x5c\x69\xe2\x69\xc8\xe9\xd8"
"\x35\xb1\x14\x29\x3a\x4d\xdc\x6e";
const char private_c[] = "\xa0\xcb\x87\x9a\x47\xf5\xbc\x64\x4c\x0e\x69\x3f"
"\xa6\xd0\x31\xc7\x4a\x15\x53\xb6\xe9\x01\xb9\xff"
"\x2f\x51\x8c\x78\x04\x2f\xb5\x42";
const char public_a[] = "\x97\x5c\x9d\x81\xc9\x83\xc8\x20\x9e\xe7\x81\x25\x4b"
"\x89\x9f\x8e\xd9\x25\xae\x9f\x09\x23\xc2\x3c\x62\xf5"
"\x3c\x57\xcd\xbf\x69\x1c";
const char public_b[] = "\xd1\x73\x28\x99\xf6\x11\xcd\x89\x94\x03\x4d\x7f\x41"
"\x3d\xc9\x57\x63\x0e\x54\x93\xc2\x85\xac\xa4\x00\x65"
"\xcb\x63\x11\xbe\x69\x6b";
const char public_c[] = "\xf4\x4d\xa3\x67\xa8\x8e\xe6\x56\x4f\x02\x02\x11\x45"
"\x67\x27\x08\x2f\x5c\xeb\xee\x8b\x1b\xf5\xeb\x73\x37"
"\x34\x1b\x45\x9b\x39\x22";
const uint16_t listen_a = 20001;
const uint16_t listen_b = 20002;
const uint16_t listen_c = 20003;
const uint16_t af_inet = AF_INET;
const uint16_t af_inet6 = AF_INET6;
/* Unused, but useful in case we change this:
const struct sockaddr_in endpoint_a_v4 = {
.sin_family = AF_INET,
.sin_port = htons(listen_a),
.sin_addr = {htonl(INADDR_LOOPBACK)}};*/
const struct sockaddr_in endpoint_b_v4 = {
.sin_family = AF_INET,
.sin_port = htons(listen_b),
.sin_addr = {htonl(INADDR_LOOPBACK)}};
const struct sockaddr_in endpoint_c_v4 = {
.sin_family = AF_INET,
.sin_port = htons(listen_c),
.sin_addr = {htonl(INADDR_LOOPBACK)}};
struct sockaddr_in6 endpoint_a_v6 = {.sin6_family = AF_INET6,
.sin6_port = htons(listen_a)};
endpoint_a_v6.sin6_addr = in6addr_loopback;
/* Unused, but useful in case we change this:
const struct sockaddr_in6 endpoint_b_v6 = {
.sin6_family = AF_INET6,
.sin6_port = htons(listen_b)};
endpoint_b_v6.sin6_addr = in6addr_loopback; */
struct sockaddr_in6 endpoint_c_v6 = {.sin6_family = AF_INET6,
.sin6_port = htons(listen_c)};
endpoint_c_v6.sin6_addr = in6addr_loopback;
const struct in_addr first_half_v4 = {0};
const struct in_addr second_half_v4 = {htonl(128 << 24)};
const struct in6_addr first_half_v6 = {{{0}}};
const struct in6_addr second_half_v6 = {{{0x80}}};
const uint8_t half_cidr = 1;
const uint16_t persistent_keepalives[] = {1, 3, 7, 9, 14, 19};
struct genlmsghdr genlhdr = {.cmd = WG_CMD_SET_DEVICE, .version = 1};
int sock;
int id, err;
sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (sock == -1)
exit(1);
id = netlink_wireguard_id_get(&nlmsg, sock);
if (id == -1)
goto error;
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_a, strlen(ifname_a) + 1);
netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_a, 32);
netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_a, 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_b, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_b_v4,
sizeof(endpoint_b_v4));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[0], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4,
sizeof(first_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6,
sizeof(first_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_c, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_c_v6,
sizeof(endpoint_c_v6));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[1], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4,
sizeof(second_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6,
sizeof(second_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
err = netlink_send(&nlmsg, sock);
if (err) {
}
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_b, strlen(ifname_b) + 1);
netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_b, 32);
netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_b, 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_a, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_a_v6,
sizeof(endpoint_a_v6));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[2], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4,
sizeof(first_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6,
sizeof(first_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_c, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_c_v4,
sizeof(endpoint_c_v4));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[3], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4,
sizeof(second_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6,
sizeof(second_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
err = netlink_send(&nlmsg, sock);
if (err) {
}
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_c, strlen(ifname_c) + 1);
netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_c, 32);
netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_c, 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_a, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_a_v6,
sizeof(endpoint_a_v6));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[4], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4,
sizeof(first_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6,
sizeof(first_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_b, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_b_v4,
sizeof(endpoint_b_v4));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[5], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4,
sizeof(second_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6,
sizeof(second_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
err = netlink_send(&nlmsg, sock);
if (err) {
}
error:
close(sock);
}
static void initialize_netdevices(void)
{
char netdevsim[16];
sprintf(netdevsim, "netdevsim%d", (int)procid);
struct {
const char* type;
const char* dev;
} devtypes[] = {
{"ip6gretap", "ip6gretap0"}, {"bridge", "bridge0"},
{"vcan", "vcan0"}, {"bond", "bond0"},
{"team", "team0"}, {"dummy", "dummy0"},
{"nlmon", "nlmon0"}, {"caif", "caif0"},
{"batadv", "batadv0"}, {"vxcan", "vxcan1"},
{"netdevsim", netdevsim}, {"veth", 0},
{"xfrm", "xfrm0"}, {"wireguard", "wg0"},
{"wireguard", "wg1"}, {"wireguard", "wg2"},
};
const char* devmasters[] = {"bridge", "bond", "team", "batadv"};
struct {
const char* name;
int macsize;
bool noipv6;
} devices[] = {
{"lo", ETH_ALEN},
{"sit0", 0},
{"bridge0", ETH_ALEN},
{"vcan0", 0, true},
{"tunl0", 0},
{"gre0", 0},
{"gretap0", ETH_ALEN},
{"ip_vti0", 0},
{"ip6_vti0", 0},
{"ip6tnl0", 0},
{"ip6gre0", 0},
{"ip6gretap0", ETH_ALEN},
{"erspan0", ETH_ALEN},
{"bond0", ETH_ALEN},
{"veth0", ETH_ALEN},
{"veth1", ETH_ALEN},
{"team0", ETH_ALEN},
{"veth0_to_bridge", ETH_ALEN},
{"veth1_to_bridge", ETH_ALEN},
{"veth0_to_bond", ETH_ALEN},
{"veth1_to_bond", ETH_ALEN},
{"veth0_to_team", ETH_ALEN},
{"veth1_to_team", ETH_ALEN},
{"veth0_to_hsr", ETH_ALEN},
{"veth1_to_hsr", ETH_ALEN},
{"hsr0", 0},
{"dummy0", ETH_ALEN},
{"nlmon0", 0},
{"vxcan0", 0, true},
{"vxcan1", 0, true},
{"caif0", ETH_ALEN},
{"batadv0", ETH_ALEN},
{netdevsim, ETH_ALEN},
{"xfrm0", ETH_ALEN},
{"veth0_virt_wifi", ETH_ALEN},
{"veth1_virt_wifi", ETH_ALEN},
{"virt_wifi0", ETH_ALEN},
{"veth0_vlan", ETH_ALEN},
{"veth1_vlan", ETH_ALEN},
{"vlan0", ETH_ALEN},
{"vlan1", ETH_ALEN},
{"macvlan0", ETH_ALEN},
{"macvlan1", ETH_ALEN},
{"ipvlan0", ETH_ALEN},
{"ipvlan1", ETH_ALEN},
{"veth0_macvtap", ETH_ALEN},
{"veth1_macvtap", ETH_ALEN},
{"macvtap0", ETH_ALEN},
{"macsec0", ETH_ALEN},
{"veth0_to_batadv", ETH_ALEN},
{"veth1_to_batadv", ETH_ALEN},
{"batadv_slave_0", ETH_ALEN},
{"batadv_slave_1", ETH_ALEN},
{"geneve0", ETH_ALEN},
{"geneve1", ETH_ALEN},
{"wg0", 0},
{"wg1", 0},
{"wg2", 0},
};
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock == -1)
exit(1);
unsigned i;
for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++)
netlink_add_device(&nlmsg, sock, devtypes[i].type, devtypes[i].dev);
for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) {
char master[32], slave0[32], veth0[32], slave1[32], veth1[32];
sprintf(slave0, "%s_slave_0", devmasters[i]);
sprintf(veth0, "veth0_to_%s", devmasters[i]);
netlink_add_veth(&nlmsg, sock, slave0, veth0);
sprintf(slave1, "%s_slave_1", devmasters[i]);
sprintf(veth1, "veth1_to_%s", devmasters[i]);
netlink_add_veth(&nlmsg, sock, slave1, veth1);
sprintf(master, "%s0", devmasters[i]);
netlink_device_change(&nlmsg, sock, slave0, false, master, 0, 0, NULL);
netlink_device_change(&nlmsg, sock, slave1, false, master, 0, 0, NULL);
}
netlink_device_change(&nlmsg, sock, "bridge_slave_0", true, 0, 0, 0, NULL);
netlink_device_change(&nlmsg, sock, "bridge_slave_1", true, 0, 0, 0, NULL);
netlink_add_veth(&nlmsg, sock, "hsr_slave_0", "veth0_to_hsr");
netlink_add_veth(&nlmsg, sock, "hsr_slave_1", "veth1_to_hsr");
netlink_add_hsr(&nlmsg, sock, "hsr0", "hsr_slave_0", "hsr_slave_1");
netlink_device_change(&nlmsg, sock, "hsr_slave_0", true, 0, 0, 0, NULL);
netlink_device_change(&nlmsg, sock, "hsr_slave_1", true, 0, 0, 0, NULL);
netlink_add_veth(&nlmsg, sock, "veth0_virt_wifi", "veth1_virt_wifi");
netlink_add_linked(&nlmsg, sock, "virt_wifi", "virt_wifi0",
"veth1_virt_wifi");
netlink_add_veth(&nlmsg, sock, "veth0_vlan", "veth1_vlan");
netlink_add_vlan(&nlmsg, sock, "vlan0", "veth0_vlan", 0, htons(ETH_P_8021Q));
netlink_add_vlan(&nlmsg, sock, "vlan1", "veth0_vlan", 1, htons(ETH_P_8021AD));
netlink_add_macvlan(&nlmsg, sock, "macvlan0", "veth1_vlan");
netlink_add_macvlan(&nlmsg, sock, "macvlan1", "veth1_vlan");
netlink_add_ipvlan(&nlmsg, sock, "ipvlan0", "veth0_vlan", IPVLAN_MODE_L2, 0);
netlink_add_ipvlan(&nlmsg, sock, "ipvlan1", "veth0_vlan", IPVLAN_MODE_L3S,
IPVLAN_F_VEPA);
netlink_add_veth(&nlmsg, sock, "veth0_macvtap", "veth1_macvtap");
netlink_add_linked(&nlmsg, sock, "macvtap", "macvtap0", "veth0_macvtap");
netlink_add_linked(&nlmsg, sock, "macsec", "macsec0", "veth1_macvtap");
char addr[32];
sprintf(addr, DEV_IPV4, 14 + 10);
struct in_addr geneve_addr4;
if (inet_pton(AF_INET, addr, &geneve_addr4) <= 0)
exit(1);
struct in6_addr geneve_addr6;
if (inet_pton(AF_INET6, "fc00::01", &geneve_addr6) <= 0)
exit(1);
netlink_add_geneve(&nlmsg, sock, "geneve0", 0, &geneve_addr4, 0);
netlink_add_geneve(&nlmsg, sock, "geneve1", 1, 0, &geneve_addr6);
netdevsim_add((int)procid, 4);
netlink_wireguard_setup();
for (i = 0; i < sizeof(devices) / (sizeof(devices[0])); i++) {
char addr[32];
sprintf(addr, DEV_IPV4, i + 10);
netlink_add_addr4(&nlmsg, sock, devices[i].name, addr);
if (!devices[i].noipv6) {
sprintf(addr, DEV_IPV6, i + 10);
netlink_add_addr6(&nlmsg, sock, devices[i].name, addr);
}
uint64_t macaddr = DEV_MAC + ((i + 10ull) << 40);
netlink_device_change(&nlmsg, sock, devices[i].name, true, 0, &macaddr,
devices[i].macsize, NULL);
}
close(sock);
}
static void initialize_netdevices_init(void)
{
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock == -1)
exit(1);
struct {
const char* type;
int macsize;
bool noipv6;
bool noup;
} devtypes[] = {
{"nr", 7, true}, {"rose", 5, true, true},
};
unsigned i;
for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) {
char dev[32], addr[32];
sprintf(dev, "%s%d", devtypes[i].type, (int)procid);
sprintf(addr, "172.30.%d.%d", i, (int)procid + 1);
netlink_add_addr4(&nlmsg, sock, dev, addr);
if (!devtypes[i].noipv6) {
sprintf(addr, "fe88::%02x:%02x", i, (int)procid + 1);
netlink_add_addr6(&nlmsg, sock, dev, addr);
}
int macsize = devtypes[i].macsize;
uint64_t macaddr = 0xbbbbbb +
((unsigned long long)i << (8 * (macsize - 2))) +
(procid << (8 * (macsize - 1)));
netlink_device_change(&nlmsg, sock, dev, !devtypes[i].noup, 0, &macaddr,
macsize, NULL);
}
close(sock);
}
static void setup_common()
{
if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) {
}
}
static void loop();
static void sandbox_common()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
setsid();
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = (200 << 20);
setrlimit(RLIMIT_AS, &rlim);
rlim.rlim_cur = rlim.rlim_max = 32 << 20;
setrlimit(RLIMIT_MEMLOCK, &rlim);
rlim.rlim_cur = rlim.rlim_max = 136 << 20;
setrlimit(RLIMIT_FSIZE, &rlim);
rlim.rlim_cur = rlim.rlim_max = 1 << 20;
setrlimit(RLIMIT_STACK, &rlim);
rlim.rlim_cur = rlim.rlim_max = 0;
setrlimit(RLIMIT_CORE, &rlim);
rlim.rlim_cur = rlim.rlim_max = 256;
setrlimit(RLIMIT_NOFILE, &rlim);
if (unshare(CLONE_NEWNS)) {
}
if (unshare(CLONE_NEWIPC)) {
}
if (unshare(0x02000000)) {
}
if (unshare(CLONE_NEWUTS)) {
}
if (unshare(CLONE_SYSVSEM)) {
}
typedef struct {
const char* name;
const char* value;
} sysctl_t;
static const sysctl_t sysctls[] = {
{"/proc/sys/kernel/shmmax", "16777216"},
{"/proc/sys/kernel/shmall", "536870912"},
{"/proc/sys/kernel/shmmni", "1024"},
{"/proc/sys/kernel/msgmax", "8192"},
{"/proc/sys/kernel/msgmni", "1024"},
{"/proc/sys/kernel/msgmnb", "1024"},
{"/proc/sys/kernel/sem", "1024 1048576 500 1024"},
};
unsigned i;
for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++)
write_file(sysctls[i].name, sysctls[i].value);
}
int wait_for_loop(int pid)
{
if (pid < 0)
exit(1);
int status = 0;
while (waitpid(-1, &status, __WALL) != pid) {
}
return WEXITSTATUS(status);
}
static void drop_caps(void)
{
struct __user_cap_header_struct cap_hdr = {};
struct __user_cap_data_struct cap_data[2] = {};
cap_hdr.version = _LINUX_CAPABILITY_VERSION_3;
cap_hdr.pid = getpid();
if (syscall(SYS_capget, &cap_hdr, &cap_data))
exit(1);
const int drop = (1 << CAP_SYS_PTRACE) | (1 << CAP_SYS_NICE);
cap_data[0].effective &= ~drop;
cap_data[0].permitted &= ~drop;
cap_data[0].inheritable &= ~drop;
if (syscall(SYS_capset, &cap_hdr, &cap_data))
exit(1);
}
static int do_sandbox_none(void)
{
if (unshare(CLONE_NEWPID)) {
}
int pid = fork();
if (pid != 0)
return wait_for_loop(pid);
setup_common();
sandbox_common();
drop_caps();
initialize_netdevices_init();
if (unshare(CLONE_NEWNET)) {
}
initialize_netdevices();
loop();
exit(1);
}
uint64_t r[1] = {0xffffffffffffffff};
void loop(void)
{
intptr_t res = 0;
res = syscall(__NR_socket, 0x10ul, 3ul, 0x14ul);
if (res != -1)
r[0] = res;
*(uint64_t*)0x20000000 = 0;
*(uint32_t*)0x20000008 = 0;
*(uint64_t*)0x20000010 = 0x200000c0;
*(uint64_t*)0x200000c0 = 0x20000100;
memcpy((void*)0x20000100, "\x38\x00\x00\x00\x03\x14\x01\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x09\x00\x02\x40\x00\x00\x00\x00"
"\x00\x00\x00\x00\x08\x00\x41\x00\x72\x78\x65\x00"
"\x14\x00\x33\x00\x76\x6c\x61\x6e\x30\x00\x00\x00"
"\x00\x00\x08\x00\x00\x00\x00\x00",
56);
*(uint64_t*)0x200000c8 = 0x38;
*(uint64_t*)0x20000018 = 1;
*(uint64_t*)0x20000020 = 0;
*(uint64_t*)0x20000028 = 0;
*(uint32_t*)0x20000030 = 0;
syscall(__NR_sendmsg, r[0], 0x20000000ul, 0ul);
}
int main(void)
{
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 3ul, 0x32ul, -1, 0);
do_sandbox_none();
return 0;
}
|
the_stack_data/99385.c | int printf();
void* malloc();
int main() {
int a=100;;
printf("%d\n", a += 2);
printf("%d\n", a -= 2);
printf("%d\n", a *= 2);
printf("%d\n", a /= 2);
int* b = malloc(16);
b[0]=1;
b[1]=2;
b[2]=3;
b[3]=4;
b += 2;
printf("%d\n", b[0]);
b -= 1;
printf("%d\n", b[0]);
return 0;
}
|
the_stack_data/119930.c | // Check the basic reporting/warning and the application of constraints.
// RUN: %clang_analyze_cc1 %s \
// RUN: -analyzer-checker=core \
// RUN: -analyzer-checker=apiModeling.StdCLibraryFunctions \
// RUN: -analyzer-checker=apiModeling.StdCLibraryFunctionArgs \
// RUN: -analyzer-checker=debug.StdCLibraryFunctionsTester \
// RUN: -analyzer-checker=debug.ExprInspection \
// RUN: -triple x86_64-unknown-linux-gnu \
// RUN: -verify=report
// Check the bugpath related to the reports.
// RUN: %clang_analyze_cc1 %s \
// RUN: -analyzer-checker=core \
// RUN: -analyzer-checker=apiModeling.StdCLibraryFunctions \
// RUN: -analyzer-checker=apiModeling.StdCLibraryFunctionArgs \
// RUN: -analyzer-checker=debug.StdCLibraryFunctionsTester \
// RUN: -analyzer-checker=debug.ExprInspection \
// RUN: -triple x86_64-unknown-linux-gnu \
// RUN: -analyzer-output=text \
// RUN: -verify=bugpath
void clang_analyzer_eval(int);
int glob;
#define EOF -1
int isalnum(int);
void test_alnum_concrete(int v) {
int ret = isalnum(256); // \
// report-warning{{Function argument constraint is not satisfied}} \
// bugpath-warning{{Function argument constraint is not satisfied}} \
// bugpath-note{{Function argument constraint is not satisfied}}
(void)ret;
}
void test_alnum_symbolic(int x) {
int ret = isalnum(x);
(void)ret;
clang_analyzer_eval(EOF <= x && x <= 255); // \
// report-warning{{TRUE}} \
// bugpath-warning{{TRUE}} \
// bugpath-note{{TRUE}} \
// bugpath-note{{Left side of '&&' is true}} \
// bugpath-note{{'x' is <= 255}}
}
void test_alnum_symbolic2(int x) {
if (x > 255) { // \
// bugpath-note{{Assuming 'x' is > 255}} \
// bugpath-note{{Taking true branch}}
int ret = isalnum(x); // \
// report-warning{{Function argument constraint is not satisfied}} \
// bugpath-warning{{Function argument constraint is not satisfied}} \
// bugpath-note{{Function argument constraint is not satisfied}}
(void)ret;
}
}
typedef struct FILE FILE;
typedef typeof(sizeof(int)) size_t;
size_t fread(void *restrict, size_t, size_t, FILE *);
void test_notnull_concrete(FILE *fp) {
fread(0, sizeof(int), 10, fp); // \
// report-warning{{Function argument constraint is not satisfied}} \
// bugpath-warning{{Function argument constraint is not satisfied}} \
// bugpath-note{{Function argument constraint is not satisfied}}
}
void test_notnull_symbolic(FILE *fp, int *buf) {
fread(buf, sizeof(int), 10, fp);
clang_analyzer_eval(buf != 0); // \
// report-warning{{TRUE}} \
// bugpath-warning{{TRUE}} \
// bugpath-note{{TRUE}} \
// bugpath-note{{'buf' is not equal to null}}
}
void test_notnull_symbolic2(FILE *fp, int *buf) {
if (!buf) // bugpath-note{{Assuming 'buf' is null}} \
// bugpath-note{{Taking true branch}}
fread(buf, sizeof(int), 10, fp); // \
// report-warning{{Function argument constraint is not satisfied}} \
// bugpath-warning{{Function argument constraint is not satisfied}} \
// bugpath-note{{Function argument constraint is not satisfied}}
}
int __two_constrained_args(int, int);
void test_constraints_on_multiple_args(int x, int y) {
// State split should not happen here. I.e. x == 1 should not be evaluated
// FALSE.
__two_constrained_args(x, y);
clang_analyzer_eval(x == 1); // \
// report-warning{{TRUE}} \
// bugpath-warning{{TRUE}} \
// bugpath-note{{TRUE}}
clang_analyzer_eval(y == 1); // \
// report-warning{{TRUE}} \
// bugpath-warning{{TRUE}} \
// bugpath-note{{TRUE}}
}
int __arg_constrained_twice(int);
void test_multiple_constraints_on_same_arg(int x) {
__arg_constrained_twice(x);
// Check that both constraints are applied and only one branch is there.
clang_analyzer_eval(x < 1 || x > 2); // \
// report-warning{{TRUE}} \
// bugpath-warning{{TRUE}} \
// bugpath-note{{TRUE}} \
// bugpath-note{{Assuming 'x' is < 1}} \
// bugpath-note{{Left side of '||' is true}}
}
int __variadic(void *stream, const char *format, ...);
void test_arg_constraint_on_variadic_fun() {
__variadic(0, "%d%d", 1, 2); // \
// report-warning{{Function argument constraint is not satisfied}} \
// bugpath-warning{{Function argument constraint is not satisfied}} \
// bugpath-note{{Function argument constraint is not satisfied}}
}
|
the_stack_data/32949941.c | #include <stdio.h>
void writefile();
void readfile();
void readfullfile();
int main()
{
// writefile ();
//readfile ();
readfullfile();
return 0;
}
//fgetc fputc
//function description
void readfullfile()
{
FILE *ptr;
char c;
ptr = fopen("sample.txt", "r");
c = fgetc(ptr);
while (c != EOF) //EOF Not Working in my compiler
{
printf("%c", c);
c = fgetc(ptr);
}
fclose(ptr);
}
void readfile()
{
FILE *ptr; //create pointer to file
int num, num2;
//open file in read format
ptr = fopen("sample.txt", "r");
//inside sample.txt >[22 23]
if (ptr == NULL)
{
printf("File Does Not exist\n"); //FILE NOT EXIST
}
else
{ //read file
fscanf(ptr, "%d", &num); //inside file first value
fscanf(ptr, "%d", &num2); //inside file second value
fclose(ptr); //close the file
printf("The Value of Num is %d\n", num); //22
printf("The Value of Num2 is %d\n", num2); //23
}
}
void writefile()
{
FILE *ptr;
int num = 20;
ptr = fopen("sample.txt", "w");
fprintf(ptr, "Inside File number is %d", num);
fclose(ptr);
} |
the_stack_data/528712.c | //Program to display a two digit number in words
#include<stdio.h>
int main()
{
int a;
printf("Enter a two digit number\n");
scanf("%d",&a);
int b=a/10;
int c=a%10;
printf("The two digit integer %d in words is ",a);
switch (b)
{
case 1:
{
switch (c)
{
case 0: printf("Ten");
break;
case 1: printf("Eleven");
break;
case 2: printf("Twelve");
break;
case 3: printf("Thirteen");
break;
case 4: printf("Fourteen");
break;
case 5: printf("Fifteen");
break;
case 6: printf("Sixteen");
break;
case 7: printf("Seventeen");
break;
case 8: printf("Eighteen");
break;
case 9: printf("Nineteen");
break;
}
}
break;
case 2: printf("Twenty");
break;
case 3: printf("Thirty");
break;
case 4: printf("Forty");
break;
case 5: printf("Fifty");
break;
case 6: printf("Sixty");
break;
case 7: printf("Seventy");
break;
case 8: printf("Eighty");
break;
case 9: printf("Ninety");
break;
}
if(b>=2 && b<=9)
{
switch (c)
{
case 1: printf(" One");
break;
case 2: printf(" Two");
break;
case 3: printf(" Three");
break;
case 4: printf(" Four");
break;
case 5: printf(" Five");
break;
case 6: printf(" Six");
break;
case 7: printf(" Seven");
break;
case 8: printf(" Eight");
break;
case 9: printf(" Nine");
break;
}
}
else
{
;
}
return 0;
} |
the_stack_data/1136521.c | #include <stdio.h>
#if defined(__is_libk)
#include <kernel/TTY.h>
#endif
int putchar(int ic) {
#if defined(__is_libk)
char c = (char) ic;
terminal_write(&c, sizeof(c));
#else
// TODO: Implement stdio and the write system call.
#endif
return ic;
}
|
the_stack_data/28903.c | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern float strtof(char const *str , char const *endptr ) ;
extern void signal(int sig , void *func ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void RandomFunc(unsigned int input[1] , unsigned int output[1] )
{
unsigned int state[1] ;
unsigned int local1 ;
unsigned short copy11 ;
unsigned short copy13 ;
{
state[0UL] = (input[0UL] & 914778474UL) << 7U;
local1 = 0UL;
while (local1 < 1UL) {
if (state[0UL] > local1) {
copy11 = *((unsigned short *)(& state[local1]) + 1);
*((unsigned short *)(& state[local1]) + 1) = *((unsigned short *)(& state[local1]) + 0);
*((unsigned short *)(& state[local1]) + 0) = copy11;
}
if (state[0UL] > local1) {
copy13 = *((unsigned short *)(& state[0UL]) + 1);
*((unsigned short *)(& state[0UL]) + 1) = *((unsigned short *)(& state[0UL]) + 0);
*((unsigned short *)(& state[0UL]) + 0) = copy13;
copy13 = *((unsigned short *)(& state[0UL]) + 0);
*((unsigned short *)(& state[0UL]) + 0) = *((unsigned short *)(& state[0UL]) + 1);
*((unsigned short *)(& state[0UL]) + 1) = copy13;
} else {
state[local1] >>= ((state[local1] >> 3U) & 7U) | 1UL;
}
local1 ++;
}
output[0UL] = (state[0UL] << 1U) ^ 1048569772U;
}
}
void megaInit(void)
{
{
}
}
int main(int argc , char *argv[] )
{
unsigned int input[1] ;
unsigned int output[1] ;
int randomFuns_i5 ;
unsigned int randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 377481100U) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
|
the_stack_data/87141.c | // RUN: %debug_check %s
typedef void V;
V *p;
V *a[1];
const void *x1;
const V *x2;
V fn(V)
{
}
int main()
{
*(int *)0 = 0;
}
|
the_stack_data/149578.c | /*-
* Copyright (c) 1995
* The President and Fellows of Harvard University
*
* This code is derived from software contributed to Harvard by
* Jeremy Rassen.
*
* 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS 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.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)hash_debug.c 8.4 (Berkeley) 11/7/95";
#endif /* LIBC_SCCS and not lint */
#ifdef DEBUG
/*
* PACKAGE: hashing
*
* DESCRIPTION:
* Debug routines.
*
* ROUTINES:
*
* External
* __dump_bucket
*/
#include <stdio.h>
#include <db.h>
#include "hash.h"
#include "page.h"
#include "extern.h"
#include "compat.h"
void
__dump_bucket(hashp, bucket)
HTAB *hashp;
u_int32_t bucket;
{
CURSOR cursor;
DBT key, val;
ITEM_INFO item_info;
int var;
char *cp;
cursor.pagep = NULL;
item_info.seek_size = 0;
item_info.seek_found_page = 0;
__get_item_reset(hashp, &cursor);
cursor.bucket = bucket;
for (;;) {
__get_item_next(hashp, &cursor, &key, &val, &item_info);
if (item_info.status == ITEM_ERROR) {
(void)printf("get_item_next returned error\n");
break;
} else if (item_info.status == ITEM_NO_MORE)
break;
if (item_info.key_off == BIGPAIR) {
if (__big_keydata(hashp, cursor.pagep, &key, &val,
item_info.pgndx)) {
(void)printf("__big_keydata returned error\n");
break;
}
}
if (key.size == sizeof(int)) {
memcpy(&var, key.data, sizeof(int));
(void)printf("%d\n", var);
} else {
for (cp = (char *)key.data; key.size--; cp++)
(void)printf("%c", *cp);
(void)printf("\n");
}
}
__get_item_done(hashp, &cursor);
}
#endif /* DEBUG */
|
the_stack_data/661535.c | #include <stdint.h>
#include <stdio.h>
#include <stdlib.h> // <-- malloc is in stdlib.h
#define KIBI 1024L
#define MEGA (KIBI*KIBI)
#define SIZE 1024*8
/*
* malloc: Memory ALLOCate, in number of bytes
* free: deallocate the memory
* takes the pointer returned by malloc
*
* Memory still needs to be initialized!
*/
uint8_t * get_board() {
void * allocated = malloc(sizeof(uint8_t) * SIZE * SIZE);
if (allocated == NULL) {
printf("Error: Out of memory!\n");
abort();
}
return allocated;
}
int main() {
uint8_t (*board)[SIZE] = NULL;
size_t total_size = sizeof(uint8_t) * SIZE * SIZE;
board = (uint8_t (*)[SIZE])get_board();
// board = malloc(total_size);
for (size_t row = 0; row < SIZE; row++) {
for (size_t col = 0; col < SIZE; col++) {
board[row][col] = rand() % 26 + 'A';
}
}
for (size_t row = 0; row < SIZE; row++) {
for (size_t col = 0; col < SIZE; col++) {
printf("%c", (char) board[row][col]);
}
printf("\n");
}
printf("board is %zu mebibytes!\n", total_size/MEGA);
free(board);
for (size_t row = 0; row < SIZE; row++) {
for (size_t col = 0; col < SIZE; col++) {
printf("%c", (char) board[row][col]);
}
printf("\n");
}
}
|
the_stack_data/25138999.c | #include <stdio.h>
double fun (int i) {
volatile double d[1] = {3.14};
volatile long int a[2];
a[i] = 1073741824;
return d[0];
}
int main(int argc, char const *argv[]) {
printf("%f\n%f\n%f\n", fun(0), fun(1), fun(2));
printf("%f\n", fun(3));
printf("%f\n", fun(4));
return 0;
}
// 3.140000
// 3.140000
// 3.139999
// 0.000000
// 3.140000 存储保护错
// -----------------
// EBP | EBP 的旧值 |
// | d7 d6 d5 d4 |
// | d3 d2 d1 d0 |
// | a[1] |
// ESP | a[0] | |
the_stack_data/153267883.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2012-2017 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
enum EE
{
VALUE = 1
};
struct x
{
unsigned char before;
enum EE e;
unsigned char after;
};
int
call_me (struct x param)
{
return param.e;
}
int
main (void)
{
struct x val;
val.before = 0xff;
val.e = VALUE;
val.after = 0xff;
call_me (val);
return 0;
}
|
the_stack_data/168892507.c | /*****************************************************************************
* Name: case.c
*
* Summary: Demo of the case switch statement. Also see Vim imap CsW
*
* Created: Sun Feb 29 10:15:40 2004 (Bob Heckel)
*****************************************************************************
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
///int ch;
char* ch;
switch ( argc ) {
case 1:
puts("no arg passed in");
break; // don't fall-thru
case 2:
ch = argv[1];
if ( strncmp(argv[1], "h", 1) == 0 ) {
fprintf(stderr, "Found an h: %s\n", *argv);
exit(EXIT_SUCCESS);
} else {
printf("one arg passed in NOT AN H: %s %d\n", ch, strncmp(argv[1],"h",1));
}
break;
default:
puts("Sorry, only one char at a time.");
exit(EXIT_SUCCESS);
break;
}
return 0;
}
|
the_stack_data/226391.c | /* CAUTION: This is the ANSI C (only) version of the Numerical Recipes
utility file nrutil.c. Do not confuse this file with the same-named
file nrutil.c that is supplied in the same subdirectory or archive
as the header file nrutil.h. *That* file contains both ANSI and
traditional K&R versions, along with #ifdef macros to select the
correct version. *This* file contains only ANSI C. */
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#define NR_END 1
#define FREE_ARG char*
void nrerror(char error_text[])
/* Numerical Recipes standard error handler */
{
fprintf(stderr,"Numerical Recipes run-time error...\n");
fprintf(stderr,"%s\n",error_text);
fprintf(stderr,"...now exiting to system...\n");
exit(1);
}
float *vector(long nl, long nh)
/* allocate a float vector with subscript range v[nl..nh] */
{
float *v;
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
if (!v) nrerror("allocation failure in vector()");
return v-nl+NR_END;
}
long *ivector(long nl, long nh)
/* allocate an long vector with subscript range v[nl..nh] */
{
long *v;
v=(long *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(long)));
if (!v) nrerror("allocation failure in ivector()");
return v-nl+NR_END;
}
unsigned char *cvector(long nl, long nh)
/* allocate an unsigned char vector with subscript range v[nl..nh] */
{
unsigned char *v;
v=(unsigned char *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(unsigned char)));
if (!v) nrerror("allocation failure in cvector()");
return v-nl+NR_END;
}
unsigned long *lvector(long nl, long nh)
/* allocate an unsigned long vector with subscript range v[nl..nh] */
{
unsigned long *v;
v=(unsigned long *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(long)));
if (!v) nrerror("allocation failure in lvector()");
return v-nl+NR_END;
}
double *dvector(long nl, long nh)
/* allocate a double vector with subscript range v[nl..nh] */
{
double *v;
v=(double *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(double)));
if (!v) nrerror("allocation failure in dvector()");
return v-nl+NR_END;
}
float **matrix(long nrl, long nrh, long ncl, long nch)
/* allocate a float matrix with subscript range m[nrl..nrh][ncl..nch] */
{
long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
float **m;
/* allocate pointers to rows */
m=(float **) malloc((size_t)((nrow+NR_END)*sizeof(float*)));
if (!m) nrerror("allocation failure 1 in matrix()");
m += NR_END;
m -= nrl;
/* allocate rows and set pointers to them */
m[nrl]=(float *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(float)));
if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
m[nrl] += NR_END;
m[nrl] -= ncl;
for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
double **dmatrix(long nrl, long nrh, long ncl, long nch)
/* allocate a double matrix with subscript range m[nrl..nrh][ncl..nch] */
{
long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
double **m;
/* allocate pointers to rows */
m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
if (!m) nrerror("allocation failure 1 in matrix()");
m += NR_END;
m -= nrl;
/* allocate rows and set pointers to them */
m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
m[nrl] += NR_END;
m[nrl] -= ncl;
for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
long **imatrix(long nrl, long nrh, long ncl, long nch)
/* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
{
long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
long **m;
/* allocate pointers to rows */
m=(long **) malloc((size_t)((nrow+NR_END)*sizeof(long*)));
if (!m) nrerror("allocation failure 1 in matrix()");
m += NR_END;
m -= nrl;
/* allocate rows and set pointers to them */
m[nrl]=(long *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(long)));
if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
m[nrl] += NR_END;
m[nrl] -= ncl;
for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
float **submatrix(float **a, long oldrl, long oldrh, long oldcl, long oldch,
long newrl, long newcl)
/* point a submatrix [newrl..][newcl..] to a[oldrl..oldrh][oldcl..oldch] */
{
long i,j,nrow=oldrh-oldrl+1,ncol=oldcl-newcl;
float **m;
/* allocate array of pointers to rows */
m=(float **) malloc((size_t) ((nrow+NR_END)*sizeof(float*)));
if (!m) nrerror("allocation failure in submatrix()");
m += NR_END;
m -= newrl;
/* set pointers to rows */
for(i=oldrl,j=newrl;i<=oldrh;i++,j++) m[j]=a[i]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
float **convert_matrix(float *a, long nrl, long nrh, long ncl, long nch)
/* allocate a float matrix m[nrl..nrh][ncl..nch] that points to the matrix
declared in the standard C manner as a[nrow][ncol], where nrow=nrh-nrl+1
and ncol=nch-ncl+1. The routine should be called with the address
&a[0][0] as the first argument. */
{
long i,j,nrow=nrh-nrl+1,ncol=nch-ncl+1;
float **m;
/* allocate pointers to rows */
m=(float **) malloc((size_t) ((nrow+NR_END)*sizeof(float*)));
if (!m) nrerror("allocation failure in convert_matrix()");
m += NR_END;
m -= nrl;
/* set pointers to rows */
m[nrl]=a-ncl;
for(i=1,j=nrl+1;i<nrow;i++,j++) m[j]=m[j-1]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
float ***f3tensor(long nrl, long nrh, long ncl, long nch, long ndl, long ndh)
/* allocate a float 3tensor with range t[nrl..nrh][ncl..nch][ndl..ndh] */
{
long i,j,nrow=nrh-nrl+1,ncol=nch-ncl+1,ndep=ndh-ndl+1;
float ***t;
/* allocate pointers to pointers to rows */
t=(float ***) malloc((size_t)((nrow+NR_END)*sizeof(float**)));
if (!t) nrerror("allocation failure 1 in f3tensor()");
t += NR_END;
t -= nrl;
/* allocate pointers to rows and set pointers to them */
t[nrl]=(float **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(float*)));
if (!t[nrl]) nrerror("allocation failure 2 in f3tensor()");
t[nrl] += NR_END;
t[nrl] -= ncl;
/* allocate rows and set pointers to them */
t[nrl][ncl]=(float *) malloc((size_t)((nrow*ncol*ndep+NR_END)*sizeof(float)));
if (!t[nrl][ncl]) nrerror("allocation failure 3 in f3tensor()");
t[nrl][ncl] += NR_END;
t[nrl][ncl] -= ndl;
for(j=ncl+1;j<=nch;j++) t[nrl][j]=t[nrl][j-1]+ndep;
for(i=nrl+1;i<=nrh;i++) {
t[i]=t[i-1]+ncol;
t[i][ncl]=t[i-1][ncl]+ncol*ndep;
for(j=ncl+1;j<=nch;j++) t[i][j]=t[i][j-1]+ndep;
}
/* return pointer to array of pointers to rows */
return t;
}
void free_vector(float *v, long nl, long nh)
/* free a float vector allocated with vector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_ivector(long *v, long nl, long nh)
/* free an long vector allocated with ivector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_cvector(unsigned char *v, long nl, long nh)
/* free an unsigned char vector allocated with cvector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_lvector(unsigned long *v, long nl, long nh)
/* free an unsigned long vector allocated with lvector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_dvector(double *v, long nl, long nh)
/* free a double vector allocated with dvector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_matrix(float **m, long nrl, long nrh, long ncl, long nch)
/* free a float matrix allocated by matrix() */
{
free((FREE_ARG) (m[nrl]+ncl-NR_END));
free((FREE_ARG) (m+nrl-NR_END));
}
void free_dmatrix(double **m, long nrl, long nrh, long ncl, long nch)
/* free a double matrix allocated by dmatrix() */
{
free((FREE_ARG) (m[nrl]+ncl-NR_END));
free((FREE_ARG) (m+nrl-NR_END));
}
void free_imatrix(long **m, long nrl, long nrh, long ncl, long nch)
/* free an long matrix allocated by imatrix() */
{
free((FREE_ARG) (m[nrl]+ncl-NR_END));
free((FREE_ARG) (m+nrl-NR_END));
}
void free_submatrix(float **b, long nrl, long nrh, long ncl, long nch)
/* free a submatrix allocated by submatrix() */
{
free((FREE_ARG) (b+nrl-NR_END));
}
void free_convert_matrix(float **b, long nrl, long nrh, long ncl, long nch)
/* free a matrix allocated by convert_matrix() */
{
free((FREE_ARG) (b+nrl-NR_END));
}
void free_f3tensor(float ***t, long nrl, long nrh, long ncl, long nch,
long ndl, long ndh)
/* free a float f3tensor allocated by f3tensor() */
{
free((FREE_ARG) (t[nrl][ncl]+ndl-NR_END));
free((FREE_ARG) (t[nrl]+ncl-NR_END));
free((FREE_ARG) (t+nrl-NR_END));
}
unsigned char **cmatrix(long nrl, long nrh, long ncl, long nch)
/* allocate a unsigned char matrix with subscript range m[nrl..nrh][ncl..nch] */
{
long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
unsigned char **m;
/* allocate pointers to rows */
m=(unsigned char **) malloc((size_t)((nrow+NR_END)*sizeof(unsigned char*)));
if (!m) nrerror("allocation failure 1 in matrix()");
m += NR_END;
m -= nrl;
/* allocate rows and set pointers to them */
m[nrl]=(unsigned char *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(unsigned char)));
if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
m[nrl] += NR_END;
m[nrl] -= ncl;
for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
|
the_stack_data/40341.c | #include <stdio.h>
main(){
int vetor [1000];
int n=0,i=0,j=0,qn=0, result;
printf ("%d", result);
scanf ("%d", &n);
result=0;
for (i=0; i<n;i++){
scanf ("%d", &qn);
vetor[i]=qn;
}
for (j=0; j<vetor[j]; j++) {
if (j==0){
if (vetor[j]>vetor[j+1]*2){
result++;
}
}
else if ((vetor[j]>vetor[j+1]*2) && (vetor[j]>vetor[j-1]*2)) {
result++;
}
}
printf("%d", result);
}
|
the_stack_data/67407.c | #include <x86intrin.h>
__m256d local_sum;
int main(int argc, char *argv[]){
}
|
the_stack_data/31388871.c | #include <stdio.h>
#include <limits.h>
#include <math.h>
int main(int argc, char const *argv[])
{
int a[] = {0, 1, -3, -1, -2};
int n = sizeof(a)/sizeof(a[0]);
int max = INT_MIN;
for (int i = 0; i < n; i++)
{
if(a[i] > max)
max = a[i];
}
printf("max is %i\n", max);
return 0;
} |
the_stack_data/22014017.c | extern int * g;
extern int rand();
void f(int * p) {
int x;
if(rand())
g = p;
else
g = &x;
}
|
the_stack_data/153268895.c | /* $Id$ */
/*
* %GPL_START_LICENSE%
* ---------------------------------------------------------------------
* Copyright 2010-2018, Pittsburgh Supercomputing Center
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License contained in the file
* `COPYING-GPL' at the top of this distribution or at
* https://www.gnu.org/licenses/gpl-2.0.html for more details.
* ---------------------------------------------------------------------
* %END_LICENSE%
*/
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define FILE_SIZE 4978
int
main(int argc, char *argv[])
{
char ch;
char *map;
int i, fd, ret, choice = 0;
char *filename = "mmap-test.dat";
if (argc == 2)
choice = atoi(argv[1]);
fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, 0600);
if (fd == -1)
err(1, "Error opening file %s for writing.", filename);
ret = lseek(fd, FILE_SIZE - 1, SEEK_SET);
if (ret == -1)
err(1, "Error lseeking to the end of the file.");
ch = 0x30;
ret = write(fd, &ch, 1);
if (ret != 1)
err(1, "Error writing last byte of the file.");
if (choice) {
/*
* This should fail because we turn on direct_io on SLASH2.
*/
printf("Using shared mapping\n");
map = mmap(0, FILE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
} else {
printf("Using private mapping\n");
map = mmap(0, FILE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
}
if (map == MAP_FAILED)
err(1, "Error mmapping the file.");
for (i = 0; i < FILE_SIZE; i++) {
map[i] = (i % 10) + 0x30;
}
if (munmap(map, FILE_SIZE) == -1)
err(1, "Error un-mmapping the file.");
close(fd);
exit(0);
}
|
the_stack_data/621827.c | /*numPass=5, numTotal=8
Verdict:ACCEPTED, Visibility:1, Input:"1004", ExpOutput:"Leap Year", Output:"Leap Year"
Verdict:ACCEPTED, Visibility:1, Input:"2009", ExpOutput:"Not Leap Year", Output:"Not Leap Year"
Verdict:ACCEPTED, Visibility:1, Input:"2012", ExpOutput:"Leap Year", Output:"Leap Year"
Verdict:ACCEPTED, Visibility:1, Input:"2115", ExpOutput:"Not Leap Year", Output:"Not Leap Year"
Verdict:WRONG_ANSWER, Visibility:0, Input:"1000", ExpOutput:"Not Leap Year", Output:"Leap Year"
Verdict:WRONG_ANSWER, Visibility:0, Input:"1700", ExpOutput:"Not Leap Year", Output:"Leap Year"
Verdict:WRONG_ANSWER, Visibility:0, Input:"1900", ExpOutput:"Not Leap Year", Output:"Leap Year"
Verdict:ACCEPTED, Visibility:0, Input:"2000", ExpOutput:"Leap Year", Output:"Leap Year"
*/
#include<stdio.h>
int main()
{
int y;//y as year
scanf("%d",&y);
if (y%100==0 && y%400==0)//Leap Year,if y divisible by 100 & 400 both
printf("Leap Year");
else
if (y%4==0)//Leap Year,if y divisible just by 4
printf("Leap Year");
else
printf("Not Leap Year");
return 0;
} |
the_stack_data/61074299.c | #include "math.h"
double exp(double n) {
return 0.0;
}
|
the_stack_data/111079390.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_memset.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ioleinik <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/11 19:55:57 by ioleinik #+# #+# */
/* Updated: 2021/05/11 20:27:36 by ioleinik ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
void *ft_memset(void *str, int ch, size_t length)
{
size_t i;
i = 0;
while (i < length)
{
((unsigned char *)str)[i] = ch;
i++;
}
return (str);
}
|
the_stack_data/31387867.c | #include<stdio.h>
int main(void)
{
char a[50],b[50];
int i,j,n,st=0;
printf("Array size : ");
scanf("%d",&n);
printf("Elements to array :");
for(i=0;i<n;i++)
scanf(" %c",&a[i]);
printf("Elements to array :");
for(i=0;i<n;i++)
scanf(" %c",&b[i]);
printf("----Output----\n");
for(i=0;i<n;i++)
{
if(a[i]!=b[i])
{
for(j=i;a[j]!=b[j] && j<n;j++)
printf("%c",a[j]);
printf(" , ");
for(;i<j;i++)
printf("%c",b[i]);
printf("\n");
}
}
return 0;
}
|
the_stack_data/68411.c | #include <stdio.h>
void board(char arr[3][3]);
int checkWin(char arr[3][3]);
int main(){
//initializes temporary values for the 2D array
char arr[3][3] = {{' ', ' ',' '}, {' ', ' ', ' '}, {' ', ' ', ' '}};
int win=0, moves, player=1, row, col, i;
board(arr);
for(i=0; i<9; i++){
if(player==1){
printf("X's turn");
do{
printf("\nRow: ");
scanf("%i", &row);
}while(row < 0 || row >3);
do{
printf("Column: ");
scanf("%i", &col);
}while(col < 0 || col > 3);
if(arr[row-1][col-1] == 'X' || arr[row-1][col-1] =='O'){
i -= 1;
printf("\n(%i, %i)\nOccupied!\n", row-1, col-1);
}else{
arr[row-1][col-1] = 'X';
player = 0;
}
board(arr);
if(checkWin(arr) == 1){
win = 1;
i = 10;
}
}else{
printf("O's turn");
do{
printf("\nRow: ");
scanf("%i", &row);
}while(row < 0 || row >3);
do{
printf("Column: ");
scanf("%i", &col);
}while(col < 0 || col > 3);
if(arr[row-1][col-1] == 'X' || arr[row-1][col-1] =='O'){
i -= 1;
printf("\n(%i, %i)\nOccupied!\n", row-1, col-1);
}else{
arr[row-1][col-1] = 'O';
player=1;
}
board(arr);
if(checkWin(arr) == 1){
win = 2;
i = 10;
}
}
}
//prints who the winner is
if(i==9 && win==0){
printf("Its a tie!");
}else if(win == 1){
printf("X wins!");
}else if(win == 2){
printf("O wins!");
}
}
//the board
void board(char arr[3][3]){
printf(" %c | %c | %c \n", arr[0][0], arr[0][1], arr[0][2]);
printf("---+---+---\n");
printf(" %c | %c | %c \n", arr[1][0], arr[1][1], arr[1][2]);
printf("---+---+---\n");
printf(" %c | %c | %c \n", arr[2][0], arr[2][1], arr[2][2]);
}
//checks the winner
int checkWin(char arr[3][3]){
if((arr[0][0] != ' ' || arr[0][1] != ' ' || arr[0][2] != ' ') && arr[0][0] == arr[0][1] && arr[0][1] == arr[0][2]){ //First Row X
return 1;
}else if((arr[1][0] != ' ' || arr[1][1] != ' ' || arr[1][2] != ' ') && arr[1][0] == arr[1][1] && arr[1][1] == arr[1][2]){ //Second Row X
return 1;
}else if((arr[2][0] != ' ' || arr[2][1] != ' ' || arr[2][2] != ' ') && arr[2][0] == arr[2][1] && arr[2][1] == arr[2][2]){ //Third Row X
return 1;
}else if((arr[0][0] != ' ' || arr[1][0] != ' ' || arr[2][0] != ' ') && arr[0][0] == arr[1][0] && arr[1][0] == arr[2][0]){ //First Column X
return 1;
}else if((arr[0][1] != ' ' || arr[1][1] != ' ' || arr[2][1] != ' ') && arr[0][1] == arr[1][1] && arr[1][1] == arr[2][1]){ //Second Column X
return 1;
}else if((arr[0][2] != ' ' || arr[1][2] != ' ' || arr[2][2] != ' ') && arr[0][2] == arr[1][2] && arr[1][2] == arr[2][2]){ //Third Column X
return 1;
}else if((arr[0][0] != ' ' || arr[1][1] != ' ' || arr[2][2] != ' ') && arr[0][0] == arr[1][1] && arr[1][1] == arr[2][2]){ //Diagonal L-R X
return 1;
}else if((arr[0][2] != ' ' || arr[1][1] != ' ' || arr[2][0] != ' ') && arr[0][2] == arr[1][1] && arr[1][1] == arr[2][0]){ //Diagonal R-L X
return 1;
}else{
return 0;
}
}
|
the_stack_data/1176833.c | #ifdef INTERFACE
CLASS(NexuizCharmap) EXTENDS(Image)
METHOD(NexuizCharmap, configureNexuizCharmap, void(entity, entity))
METHOD(NexuizCharmap, mousePress, float(entity, vector))
METHOD(NexuizCharmap, mouseRelease, float(entity, vector))
METHOD(NexuizCharmap, mouseMove, float(entity, vector))
METHOD(NexuizCharmap, mouseDrag, float(entity, vector))
METHOD(NexuizCharmap, keyDown, float(entity, float, float, float))
METHOD(NexuizCharmap, focusLeave, void(entity))
METHOD(NexuizCharmap, draw, void(entity))
ATTRIB(NexuizCharmap, controlledTextbox, entity, NULL)
ATTRIB(NexuizCharmap, image, string, SKINGFX_CHARMAP)
ATTRIB(NexuizCharmap, image2, string, SKINGFX_CHARMAP_SELECTED)
ATTRIB(NexuizCharmap, focusable, float, 1)
ATTRIB(NexuizCharmap, previouslySelectedCharacterCell, float, -1)
ATTRIB(NexuizCharmap, selectedCharacterCell, float, 0)
ATTRIB(NexuizCharmap, mouseSelectedCharacterCell, float, -1)
ENDCLASS(NexuizCharmap)
entity makeNexuizCharmap(entity theTextbox);
#endif
#ifdef IMPLEMENTATION
entity makeNexuizCharmap(entity theTextbox)
{
entity me;
me = spawnNexuizCharmap();
me.configureNexuizCharmap(me, theTextbox);
return me;
}
string CharMap_CellToChar(float c)
{
var u = 0xE000 * CVAR(utf8_enable);
if(c == 13)
return chr(127 + u);
else if(c < 32)
return chr(c + u);
else
return chr(c + 96 + u);
}
void configureNexuizCharmapNexuizCharmap(entity me, entity theTextbox)
{
me.controlledTextbox = theTextbox;
me.configureImage(me, me.image);
}
float mouseMoveNexuizCharmap(entity me, vector coords)
{
float x, y, c;
x = floor(coords_x * 16);
y = floor(coords_y * 10);
if(x < 0 || y < 0 || x >= 16 || y >= 10)
{
me.mouseSelectedCharacterCell = -1;
return 0;
}
c = y * 16 + x;
if(c != me.mouseSelectedCharacterCell)
me.mouseSelectedCharacterCell = me.selectedCharacterCell = c;
return 1;
}
float mouseDragNexuizCharmap(entity me, vector coords)
{
return me.mouseMove(me, coords);
}
float mousePressNexuizCharmap(entity me, vector coords)
{
me.mouseMove(me, coords);
if(me.mouseSelectedCharacterCell >= 0)
{
me.pressed = 1;
me.previouslySelectedCharacterCell = me.selectedCharacterCell;
}
return 1;
}
float mouseReleaseNexuizCharmap(entity me, vector coords)
{
if(!me.pressed)
return 0;
me.mouseMove(me, coords);
if(me.selectedCharacterCell == me.previouslySelectedCharacterCell)
me.controlledTextbox.enterText(me.controlledTextbox, CharMap_CellToChar(me.selectedCharacterCell));
me.pressed = 0;
return 1;
}
float keyDownNexuizCharmap(entity me, float key, float ascii, float shift)
{
switch(key)
{
case K_LEFTARROW:
me.selectedCharacterCell = mod(me.selectedCharacterCell + 159, 160);
return 1;
case K_RIGHTARROW:
me.selectedCharacterCell = mod(me.selectedCharacterCell + 1, 160);
return 1;
case K_UPARROW:
me.selectedCharacterCell = mod(me.selectedCharacterCell + 144, 160);
return 1;
case K_DOWNARROW:
me.selectedCharacterCell = mod(me.selectedCharacterCell + 16, 160);
return 1;
case K_HOME:
me.selectedCharacterCell = 0;
return 1;
case K_END:
me.selectedCharacterCell = 159;
return 1;
case K_SPACE:
case K_ENTER:
case K_INS:
me.controlledTextbox.enterText(me.controlledTextbox, CharMap_CellToChar(me.selectedCharacterCell));
return 1;
default:
return me.controlledTextbox.keyDown(me.controlledTextbox, key, ascii, shift);
}
}
void focusLeaveNexuizCharmap(entity me)
{
me.controlledTextbox.saveCvars(me.controlledTextbox);
}
void drawNexuizCharmap(entity me)
{
if(me.focused)
{
if(!me.pressed || (me.selectedCharacterCell == me.previouslySelectedCharacterCell))
{
vector c;
c = eX * (mod(me.selectedCharacterCell, 16) / 16.0);
c += eY * (floor(me.selectedCharacterCell / 16.0) / 10.0);
draw_Picture(c, me.image2, '0.0625 0.1 0', '1 1 1', 1);
}
}
drawImage(me);
}
#endif
|
the_stack_data/237642213.c | #include <stdio.h>
int rotate_left();
int rotate_right();
int rotate_180();
int flip_vertical();
int flip_horizontal();
int quit();
int s[3][3] = {1, 2, 3,
4, 5, 6,
7, 8, 9};
int main(void)
{
printf("1 2 3\n");
printf("4 5 6\n");
printf("7 8 9\n\n");
printf("Enter the operation of your choise:\n");
printf("A. Rotate left B. Rotate right\n");
printf("C. Rotate 180 D. Flip vertical\n");
printf("E. Flip horizontal Q. Quit\n");
char a;
scanf("%c", &a);
while (a != 'q')
{
if (a == 'a' || a == 'b' || a == 'c' || a == 'd' || a == 'e')
{
switch (a)
{
case 'a':
rotate_left();
break;
case 'b':
rotate_right();
break;
case 'c':
rotate_180();
break;
case 'd':
flip_vertical();
break;
case 'e':
flip_horizontal();
break;
}
}
scanf("%c", &a);
}
return 0;
}
int flip_vertical()
{
int t_arr[3][3] = {1, 2, 3,
4, 5, 6,
7, 8, 9};
int t;
for (int i = 0; i < 3; ++i)
{
t = t_arr[0][i];
t_arr[0][i] = t_arr[2][i];
t_arr[2][i] = t;
}
printf("\n%d %d %d\n%d %d %d\n%d %d %d\n\n", t_arr[0][0], t_arr[0][1], t_arr[0][2], t_arr[1][0], t_arr[1][1], t_arr[1][2], t_arr[2][0], t_arr[2][1], t_arr[2][2]);
}
int flip_horizontal()
{
int t_arr[3][3] = {1, 2, 3,
4, 5, 6,
7, 8, 9};
int t;
for (int i = 0; i < 3; ++i)
{
t = t_arr[i][0];
t_arr[i][0] = t_arr[i][2];
t_arr[i][2] = t;
}
printf("\n%d %d %d\n%d %d %d\n%d %d %d\n\n", t_arr[0][0], t_arr[0][1], t_arr[0][2], t_arr[1][0], t_arr[1][1], t_arr[1][2], t_arr[2][0], t_arr[2][1], t_arr[2][2]);
}
int rotate_left()
{
int t_arr[3][3];
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
t_arr[2 - j][i] = s[i][j];
}
}
printf("\n%d %d %d\n%d %d %d\n%d %d %d\n\n", t_arr[0][0], t_arr[0][1], t_arr[0][2], t_arr[1][0], t_arr[1][1], t_arr[1][2], t_arr[2][0], t_arr[2][1], t_arr[2][2]);
}
int rotate_right()
{
int t_arr[3][3]; //rotate left
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
t_arr[2 - j][i] = s[i][j];
}
}
int h = 0; // flip horizontal
for (int i = 0; i < 3; ++i)
{
h = t_arr[i][0];
t_arr[i][0] = t_arr[i][2];
t_arr[i][2] = h;
}
int t[3]; // flip vertical
for (int i = 0; i < 3; i++)
{
t[i] = t_arr[0][i];
}
for (int i = 0; i < 3; i++)
{
t_arr[0][i] = t_arr[2][i];
}
for (int i = 0; i < 3; i++)
{
t_arr[2][i] = t[i];
}
printf("\n%d %d %d\n%d %d %d\n%d %d %d\n\n", t_arr[0][0], t_arr[0][1], t_arr[0][2], t_arr[1][0], t_arr[1][1], t_arr[1][2], t_arr[2][0], t_arr[2][1], t_arr[2][2]);
}
int rotate_180()
{
int t_arr[3][3] = {1, 2, 3,
4, 5, 6,
7, 8, 9};
int h = 0; // flip horizontal
for (int i = 0; i < 3; ++i)
{
h = t_arr[i][0];
t_arr[i][0] = t_arr[i][2];
t_arr[i][2] = h;
}
int t[3]; // flip vertical
for (int i = 0; i < 3; i++)
{
t[i] = t_arr[0][i];
}
for (int i = 0; i < 3; i++)
{
t_arr[0][i] = t_arr[2][i];
}
for (int i = 0; i < 3; i++)
{
t_arr[2][i] = t[i];
}
printf("\n%d %d %d\n%d %d %d\n%d %d %d\n\n", t_arr[0][0], t_arr[0][1], t_arr[0][2], t_arr[1][0], t_arr[1][1], t_arr[1][2], t_arr[2][0], t_arr[2][1], t_arr[2][2]);
} |
the_stack_data/175142214.c | /*
* ========================================================================
* Copyright 2006-2007 University of Washington
* Copyright 2013-2016 Eduardo Chappa
*
* Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
*
* ========================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct helplist {
char *name;
struct helplist *next;
} HELPLIST_S;
HELPLIST_S *help_list;
void preamble(FILE *ofp);
void body(FILE *ifp, FILE *ofp);
char *quote_clean(char *rawline);
int only_tags(char *line);
int append_to_help_list(HELPLIST_S **, char *new);
void print_help_list(HELPLIST_S *, FILE *fp);
int
main(int argc, char **argv)
{
preamble(stdout);
body(stdin, stdout);
exit(0);
}
void
preamble(FILE *ofp)
{
fprintf(ofp, "\n\t\t/*\n");
fprintf(ofp, "\t\t * AUTMATICALLY GENERATED FILE!\n");
fprintf(ofp, "\t\t * DO NOT EDIT!!\n");
fprintf(ofp, "\t\t * See help_c_gen.c.\n\t\t */\n\n\n");
fprintf(ofp, "#include <stdio.h>\n#include \"headers.h\"\n#include \"helptext.h\"\n\n");
}
void
body(FILE *ifp, FILE *ofp)
{
char rawline[10000];
char *line;
#define SPACE ' '
char *p, *helpname;
int in_text = 0, new_topic = 0, first_one = 1, justtags;
while(fgets(rawline, sizeof(rawline), ifp) != NULL){
if(rawline[0] == '#')
continue;
line = quote_clean(rawline);
if(!line){
/*
* Put errors in result so that it will cause a compile
* error and be noticed.
*/
fprintf(ofp, "Error: quote_clean returns NULL for help line\n %s\n", rawline);
exit(-1);
}
justtags = 0;
if(!strncmp(line, "====", 4)){
p = line;
/* skip to first space */
while(*p && *p != SPACE)
p++;
if(!*p){
fprintf(ofp, "Error: help input line\n %s\n No space after ====\n", rawline);
exit(-1);
}
/* skip spaces */
while(*p && *p == SPACE)
p++;
if(!*p){
fprintf(ofp, "Error: help input line\n %s\n Missing helpname after ====\n", rawline);
exit(-1);
}
helpname = p;
/* skip to next space */
while(*p && *p != SPACE)
p++;
*p = '\0'; /* tie off helpname */
/* finish previous one */
if(in_text)
fprintf(ofp, "NULL\n};\n\n\n");
in_text = new_topic = 1;
fprintf(ofp, "char *%s[] = {\n", helpname);
if(append_to_help_list(&help_list, helpname) < 0){
fprintf(ofp, "Error: Can't allocate memory for help_list after line\n %s\n", rawline);
exit(-1);
}
}
else if(line[0] == '\0'){
if(in_text)
fprintf(ofp, "\" \",\n"); /* why the space? */
}
else if(only_tags(line)){
if(in_text){
fprintf(ofp, "\"%s\",\n", line);
justtags = 1;
}
}
if(line[0] && line[0] != '='){
if(in_text && !justtags){
if(first_one){
first_one = 0;
fprintf(ofp, "/*\n");
fprintf(ofp, "TRANSLATORS: The translation strings for pith/helptext.c\n");
fprintf(ofp, "are automatically generated by a script from the help\n");
fprintf(ofp, "text in pith/pine.hlp. This means that the translation job for\n");
fprintf(ofp, "the help text is particularly difficult.\n");
fprintf(ofp, "This is HTML source so please leave the text inside HTML tags untranslated.\n");
fprintf(ofp, "HTML tags like <LI> or <TITLE> should, of course, be left untranslated.\n");
fprintf(ofp, "Special HTML characters like < (less than character) should be left alone.\n");
fprintf(ofp, "Alpine option names are short phrases with the words separated by\n");
fprintf(ofp, "dashes. An example of an option name is Quell-Extra-Post-Prompt.\n");
fprintf(ofp, "Option names should not be translated.\n");
fprintf(ofp, "The file pith/helptext.c contains many separate help topics.\n");
fprintf(ofp, "Some of them are very short and some are long. If left unsorted the\n");
fprintf(ofp, "text for a single topic is together in the translation file. The start\n");
fprintf(ofp, "of each new topic is marked by the comment\n");
fprintf(ofp, "TRANSLATORS: Start of new help topic.\n");
fprintf(ofp, "*/\n");
}
else if(new_topic){
new_topic = 0;
fprintf(ofp, "/* TRANSLATORS: Start of new help topic. */\n");
}
fprintf(ofp, "N_(\"%s\"),\n", line);
}
else{
; /* skip leading cruft */
}
}
}
if(in_text)
fprintf(ofp, "NULL\n};\n\n\n");
print_help_list(help_list, ofp);
}
char *
quote_clean(char *rawline)
{
char *p, *q, *cleaned = NULL;
size_t len;
if(rawline){
len = strlen(rawline);
cleaned = (char *) malloc((2*len+1) * sizeof(char));
if(cleaned){
p = rawline;
q = cleaned;
while(*p && *p != '\n'){
if(*p == '"' && !(p > rawline && *(p-1) == '\\'))
*q++ = '\\';
*q++ = *p++;
}
*q = '\0';
}
}
return cleaned;
}
int
only_tags(char *line)
{
char *p;
int is_tags = 1; /* only tags seen so far */
if(!line)
return 0;
p = line;
while(is_tags && *p){
/* leading space before a tag */
while(*p && isspace(*p))
p++;
if(*p == '<'){
p++;
/* skip through interior of tag */
while(*p && *p != '<' && *p != '>')
p++;
if(*p == '>'){
p++;
/* trailing space after tag */
while(*p && isspace(*p))
p++;
}
else
is_tags = 0;
}
else if(*p)
is_tags = 0;
}
return is_tags;
}
int
append_to_help_list(HELPLIST_S **head, char *name)
{
HELPLIST_S *new, *h;
size_t len;
if(!(name && *name && head))
return 0;
new = (HELPLIST_S *) malloc(sizeof(*new));
if(!new)
return -1;
memset(new, 0, sizeof(*new));
len = strlen(name);
new->name = (char *) malloc((len+1) * sizeof(char));
strncpy(new->name, name, len);
new->name[len] = '\0';
if(*head){
for(h = *head; h->next; h = h->next)
;
h->next = new;
}
else
*head = new;
return 0;
}
void
print_help_list(HELPLIST_S *head, FILE *fp)
{
HELPLIST_S *h;
if(head){
fprintf(fp, "struct help_texts h_texts[] = {\n");
for(h = head; h; h = h->next)
if(h->name && h->name[0])
fprintf(fp, "{%s,\"%s\"},\n", h->name, h->name);
fprintf(fp, "{NO_HELP, NULL}\n};\n");
}
}
|
the_stack_data/740210.c | /*
* Copyright (c) 2006-2020, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2020/12/31 Bernard Add license info
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("hello rt-thread\n");
return 0;
}
|
the_stack_data/649265.c | #include <stdio.h>
int main() {
int n, elem, aux, seq, maior=0;
scanf("%d",&n);
scanf("%d",&elem);
seq = 1;
maior = 1;
n--;
while(n--) {
aux = elem;
scanf("%d",&elem);
if(aux < elem)
seq++;
else seq =1;
if(seq>maior)
maior = seq;
}
printf("O comprimento do segmento crescente maximo e: %d\n",maior);
return 0;
} |
the_stack_data/69799.c | /* Make sure timers don't return early
* by: john stultz ([email protected])
* John Stultz ([email protected])
* (C) Copyright IBM 2012
* (C) Copyright Linaro 2013 2015
* Licensed under the GPLv2
*
* To build:
* $ gcc nanosleep.c -o nanosleep -lrt
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <sys/timex.h>
#include <string.h>
#include <signal.h>
#ifdef KTEST
#include "../kselftest.h"
#else
static inline int ksft_exit_pass(void)
{
exit(0);
}
static inline int ksft_exit_fail(void)
{
exit(1);
}
#endif
#define NSEC_PER_SEC 1000000000ULL
#define CLOCK_REALTIME 0
#define CLOCK_MONOTONIC 1
#define CLOCK_PROCESS_CPUTIME_ID 2
#define CLOCK_THREAD_CPUTIME_ID 3
#define CLOCK_MONOTONIC_RAW 4
#define CLOCK_REALTIME_COARSE 5
#define CLOCK_MONOTONIC_COARSE 6
#define CLOCK_BOOTTIME 7
#define CLOCK_REALTIME_ALARM 8
#define CLOCK_BOOTTIME_ALARM 9
#define CLOCK_HWSPECIFIC 10
#define CLOCK_TAI 11
#define NR_CLOCKIDS 12
#define UNSUPPORTED 0xf00f
char *clockstring(int clockid)
{
switch (clockid) {
case CLOCK_REALTIME:
return "CLOCK_REALTIME";
case CLOCK_MONOTONIC:
return "CLOCK_MONOTONIC";
case CLOCK_PROCESS_CPUTIME_ID:
return "CLOCK_PROCESS_CPUTIME_ID";
case CLOCK_THREAD_CPUTIME_ID:
return "CLOCK_THREAD_CPUTIME_ID";
case CLOCK_MONOTONIC_RAW:
return "CLOCK_MONOTONIC_RAW";
case CLOCK_REALTIME_COARSE:
return "CLOCK_REALTIME_COARSE";
case CLOCK_MONOTONIC_COARSE:
return "CLOCK_MONOTONIC_COARSE";
case CLOCK_BOOTTIME:
return "CLOCK_BOOTTIME";
case CLOCK_REALTIME_ALARM:
return "CLOCK_REALTIME_ALARM";
case CLOCK_BOOTTIME_ALARM:
return "CLOCK_BOOTTIME_ALARM";
case CLOCK_TAI:
return "CLOCK_TAI";
};
return "UNKNOWN_CLOCKID";
}
/* returns 1 if a <= b, 0 otherwise */
static inline int in_order(struct timespec a, struct timespec b)
{
if (a.tv_sec < b.tv_sec)
return 1;
if (a.tv_sec > b.tv_sec)
return 0;
if (a.tv_nsec > b.tv_nsec)
return 0;
return 1;
}
struct timespec timespec_add(struct timespec ts, unsigned long long ns)
{
ts.tv_nsec += ns;
while (ts.tv_nsec >= NSEC_PER_SEC) {
ts.tv_nsec -= NSEC_PER_SEC;
ts.tv_sec++;
}
return ts;
}
int nanosleep_test(int clockid, long long ns)
{
struct timespec now, target, rel;
/* First check abs time */
if (clock_gettime(clockid, &now))
return UNSUPPORTED;
target = timespec_add(now, ns);
if (clock_nanosleep(clockid, TIMER_ABSTIME, &target, NULL))
return UNSUPPORTED;
clock_gettime(clockid, &now);
if (!in_order(target, now))
return -1;
/* Second check reltime */
clock_gettime(clockid, &now);
rel.tv_sec = 0;
rel.tv_nsec = 0;
rel = timespec_add(rel, ns);
target = timespec_add(now, ns);
clock_nanosleep(clockid, 0, &rel, NULL);
clock_gettime(clockid, &now);
if (!in_order(target, now))
return -1;
return 0;
}
int main(int argc, char **argv)
{
long long length;
int clockid, ret;
for (clockid = CLOCK_REALTIME; clockid < NR_CLOCKIDS; clockid++) {
/* Skip cputime clockids since nanosleep won't increment cputime */
if (clockid == CLOCK_PROCESS_CPUTIME_ID ||
clockid == CLOCK_THREAD_CPUTIME_ID ||
clockid == CLOCK_HWSPECIFIC)
continue;
printf("Nanosleep %-31s ", clockstring(clockid));
length = 10;
while (length <= (NSEC_PER_SEC * 10)) {
ret = nanosleep_test(clockid, length);
if (ret == UNSUPPORTED) {
printf("[UNSUPPORTED]\n");
goto next;
}
if (ret < 0) {
printf("[FAILED]\n");
return ksft_exit_fail();
}
length *= 100;
}
printf("[OK]\n");
next:
ret = 0;
}
return ksft_exit_pass();
}
|
the_stack_data/88157.c | #include <stdio.h>
int ac()
{
static int a = 0; // 静态变量只会初始化一次
a++;
return a;
}
int acp = 10;
int main()
{
int b;
for (int a=0;a<10;a++) {
int b = ac();
}
printf("ac: %d\n",b);
register int cup_s = 10; // 寄存器变量
printf("cpu: %d\n",cup_s);
printf("acp: %d\n",acp);
return 0;
} |
the_stack_data/27915.c | // RUN: %llvmgcc %s -emit-llvm -O0 -c -o %t1.bc
// RUN: rm -rf %t.klee-out
// RUN: %klee --output-dir=%t.klee-out --libc=klee --exit-on-error %t1.bc
#include <arpa/inet.h>
#include <assert.h>
int main() {
uint32_t n = 0;
klee_make_symbolic(&n, sizeof(n));
uint32_t h = ntohl(n);
assert(htonl(h) == n);
return 0;
}
|
the_stack_data/111078018.c | #include <stdio.h>
int fatorial(int n) {
if(n == 0){
return 1;
} else{
return n * fatorial(n-1);
}
}
void divisor(int n) {
if(n == 0) {
printf("nao ha divisores para 0");
} else {
printf("%d é divisor de %d\n", n, n);
for(int i = (n/2); i > 0; i--){
if(n%i == 0) {
printf("%d é divisor de %d\n", i, n);
}
}
}
}
int main() {
int n = 10;
printf("Fatorial de %d é %d\n", n, fatorial(n));
divisor(n);
return 0;
}
|
the_stack_data/61075111.c |
#include <stdio.h>
void scilab_rt_plot3d_i2d2d2d0d0s0i2d2_(int in00, int in01, int matrixin0[in00][in01],
int in10, int in11, double matrixin1[in10][in11],
int in20, int in21, double matrixin2[in20][in21],
double scalarin0,
double scalarin1,
char* scalarin2,
int in30, int in31, int matrixin3[in30][in31],
int in40, int in41, double matrixin4[in40][in41])
{
int i;
int j;
int val0 = 0;
double val1 = 0;
double val2 = 0;
int val3 = 0;
double val4 = 0;
for (i = 0; i < in00; ++i) {
for (j = 0; j < in01; ++j) {
val0 += matrixin0[i][j];
}
}
printf("%d", val0);
for (i = 0; i < in10; ++i) {
for (j = 0; j < in11; ++j) {
val1 += matrixin1[i][j];
}
}
printf("%f", val1);
for (i = 0; i < in20; ++i) {
for (j = 0; j < in21; ++j) {
val2 += matrixin2[i][j];
}
}
printf("%f", val2);
printf("%f", scalarin0);
printf("%f", scalarin1);
printf("%s", scalarin2);
for (i = 0; i < in30; ++i) {
for (j = 0; j < in31; ++j) {
val3 += matrixin3[i][j];
}
}
printf("%d", val3);
for (i = 0; i < in40; ++i) {
for (j = 0; j < in41; ++j) {
val4 += matrixin4[i][j];
}
}
printf("%f", val4);
}
|
the_stack_data/184516898.c | #include <stdio.h>
extern int add2(int a, int b);
int main(int argc, char *argv[]) {
printf("The result is: %d\n", add2(1, 2));
return 0;
}
|
the_stack_data/167331284.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int r,dice1,dice2,dice3;
/* seed the randomizer */
srand( (unsigned)time(NULL) );
puts("Roll them bones!");
r = rand() % 6;
r += 1;
dice1 = r;
r = rand() % 6;
r += 1;
dice2 = r;
r = rand() % 6;
r += 1;
dice3 = r;
printf("You rolled %d - %d - %d\n",dice1,dice2,dice3);
return(0);
}
|
the_stack_data/132951959.c | #include<stdlib.h>
#include<stdio.h>
#include<locale.h>
void main(){
//Para utilizar acentos.
setlocale(LC_ALL, "");
/*Crie um algoritmo que informe se o valor lido é primo ou não.*/
//Definindo variáveis.
int i, valor, aux;
printf("Digite um valor para saber se ele é primo: ");
scanf("%d", &valor);
for(i = 1; i <= valor; i++){
//Conferindo quantas vezes houve divisibilidade.
if(valor % i == 0){
aux++;
}
}
if(aux == 2){
printf("\nO número é primo!\n");
}else{
printf("\nO número não é primo! Pois ele tem %d divisores\n", aux);
}
} |
the_stack_data/154827601.c | #include <stdio.h>
void hello() {
printf("%s: hello world\n",__FILE__);
}
|
the_stack_data/116926.c | /*
* Copyright 2019 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* 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.
*/
#include <stdio.h>
#define N 1024
int main(int argc, char **argv)
{
float x[N], y[N];
int i;
#pragma acc parallel loop
for (i=0; i<N; i++)
{
y[i] = 0.0f;
x[i] = (float)(i+1);
}
#pragma acc parallel loop
for (i=0; i<N; i++)
{
y[i] = 2.0f * x[i] + y[i];
}
printf("%f %f\n",y[0],y[N-1]);
return 0;
}
|
the_stack_data/96393.c | // general protection fault in path_openat
// https://syzkaller.appspot.com/bug?id=a1cf806fac1e4401d8d151efefa31f969e3868b6
// status:open
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <dirent.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <linux/futex.h>
#include <linux/loop.h>
unsigned long long procid;
static __thread int skip_segv;
static __thread jmp_buf segv_env;
static void segv_handler(int sig, siginfo_t* info, void* ctx)
{
uintptr_t addr = (uintptr_t)info->si_addr;
const uintptr_t prog_start = 1 << 20;
const uintptr_t prog_end = 100 << 20;
if (__atomic_load_n(&skip_segv, __ATOMIC_RELAXED) &&
(addr < prog_start || addr > prog_end)) {
_longjmp(segv_env, 1);
}
exit(sig);
}
static void install_segv_handler(void)
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8);
syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8);
memset(&sa, 0, sizeof(sa));
sa.sa_sigaction = segv_handler;
sa.sa_flags = SA_NODEFER | SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);
sigaction(SIGBUS, &sa, NULL);
}
#define NONFAILING(...) \
{ \
__atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \
if (_setjmp(segv_env) == 0) { \
__VA_ARGS__; \
} \
__atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \
}
static void sleep_ms(uint64_t ms)
{
usleep(ms * 1000);
}
static uint64_t current_time_ms(void)
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
exit(1);
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
static void use_temporary_dir(void)
{
char tmpdir_template[] = "./syzkaller.XXXXXX";
char* tmpdir = mkdtemp(tmpdir_template);
if (!tmpdir)
exit(1);
if (chmod(tmpdir, 0777))
exit(1);
if (chdir(tmpdir))
exit(1);
}
static void thread_start(void* (*fn)(void*), void* arg)
{
pthread_t th;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 128 << 10);
int i;
for (i = 0; i < 100; i++) {
if (pthread_create(&th, &attr, fn, arg) == 0) {
pthread_attr_destroy(&attr);
return;
}
if (errno == EAGAIN) {
usleep(50);
continue;
}
break;
}
exit(1);
}
typedef struct {
int state;
} event_t;
static void event_init(event_t* ev)
{
ev->state = 0;
}
static void event_reset(event_t* ev)
{
ev->state = 0;
}
static void event_set(event_t* ev)
{
if (ev->state)
exit(1);
__atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE);
syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1000000);
}
static void event_wait(event_t* ev)
{
while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0);
}
static int event_isset(event_t* ev)
{
return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE);
}
static int event_timedwait(event_t* ev, uint64_t timeout)
{
uint64_t start = current_time_ms();
uint64_t now = start;
for (;;) {
uint64_t remain = timeout - (now - start);
struct timespec ts;
ts.tv_sec = remain / 1000;
ts.tv_nsec = (remain % 1000) * 1000 * 1000;
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts);
if (__atomic_load_n(&ev->state, __ATOMIC_RELAXED))
return 1;
now = current_time_ms();
if (now - start > timeout)
return 0;
}
}
static bool write_file(const char* file, const char* what, ...)
{
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
int err = errno;
close(fd);
errno = err;
return false;
}
close(fd);
return true;
}
struct fs_image_segment {
void* data;
uintptr_t size;
uintptr_t offset;
};
#define IMAGE_MAX_SEGMENTS 4096
#define IMAGE_MAX_SIZE (129 << 20)
#define sys_memfd_create 319
static unsigned long fs_image_segment_check(unsigned long size,
unsigned long nsegs, long segments)
{
unsigned long i;
struct fs_image_segment* segs = (struct fs_image_segment*)segments;
if (nsegs > IMAGE_MAX_SEGMENTS)
nsegs = IMAGE_MAX_SEGMENTS;
for (i = 0; i < nsegs; i++) {
if (segs[i].size > IMAGE_MAX_SIZE)
segs[i].size = IMAGE_MAX_SIZE;
segs[i].offset %= IMAGE_MAX_SIZE;
if (segs[i].offset > IMAGE_MAX_SIZE - segs[i].size)
segs[i].offset = IMAGE_MAX_SIZE - segs[i].size;
if (size < segs[i].offset + segs[i].offset)
size = segs[i].offset + segs[i].offset;
}
if (size > IMAGE_MAX_SIZE)
size = IMAGE_MAX_SIZE;
return size;
}
static long syz_mount_image(volatile long fsarg, volatile long dir,
volatile unsigned long size,
volatile unsigned long nsegs,
volatile long segments, volatile long flags,
volatile long optsarg)
{
char loopname[64], fs[32], opts[256];
int loopfd, err = 0, res = -1;
unsigned long i;
NONFAILING(size = fs_image_segment_check(size, nsegs, segments));
int memfd = syscall(sys_memfd_create, "syz_mount_image", 0);
if (memfd == -1) {
err = errno;
goto error;
}
if (ftruncate(memfd, size)) {
err = errno;
goto error_close_memfd;
}
for (i = 0; i < nsegs; i++) {
struct fs_image_segment* segs = (struct fs_image_segment*)segments;
int res1 = 0;
NONFAILING(res1 =
pwrite(memfd, segs[i].data, segs[i].size, segs[i].offset));
if (res1 < 0) {
}
}
snprintf(loopname, sizeof(loopname), "/dev/loop%llu", procid);
loopfd = open(loopname, O_RDWR);
if (loopfd == -1) {
err = errno;
goto error_close_memfd;
}
if (ioctl(loopfd, LOOP_SET_FD, memfd)) {
if (errno != EBUSY) {
err = errno;
goto error_close_loop;
}
ioctl(loopfd, LOOP_CLR_FD, 0);
usleep(1000);
if (ioctl(loopfd, LOOP_SET_FD, memfd)) {
err = errno;
goto error_close_loop;
}
}
mkdir((char*)dir, 0777);
memset(fs, 0, sizeof(fs));
NONFAILING(strncpy(fs, (char*)fsarg, sizeof(fs) - 1));
memset(opts, 0, sizeof(opts));
NONFAILING(strncpy(opts, (char*)optsarg, sizeof(opts) - 32));
if (strcmp(fs, "iso9660") == 0) {
flags |= MS_RDONLY;
} else if (strncmp(fs, "ext", 3) == 0) {
if (strstr(opts, "errors=panic") || strstr(opts, "errors=remount-ro") == 0)
strcat(opts, ",errors=continue");
} else if (strcmp(fs, "xfs") == 0) {
strcat(opts, ",nouuid");
}
if (mount(loopname, (char*)dir, fs, flags, opts)) {
err = errno;
goto error_clear_loop;
}
res = 0;
error_clear_loop:
ioctl(loopfd, LOOP_CLR_FD, 0);
error_close_loop:
close(loopfd);
error_close_memfd:
close(memfd);
error:
errno = err;
return res;
}
#define FS_IOC_SETFLAGS _IOW('f', 2, long)
static void remove_dir(const char* dir)
{
DIR* dp;
struct dirent* ep;
int iter = 0;
retry:
while (umount2(dir, MNT_DETACH) == 0) {
}
dp = opendir(dir);
if (dp == NULL) {
if (errno == EMFILE) {
exit(1);
}
exit(1);
}
while ((ep = readdir(dp))) {
if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0)
continue;
char filename[FILENAME_MAX];
snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name);
while (umount2(filename, MNT_DETACH) == 0) {
}
struct stat st;
if (lstat(filename, &st))
exit(1);
if (S_ISDIR(st.st_mode)) {
remove_dir(filename);
continue;
}
int i;
for (i = 0;; i++) {
if (unlink(filename) == 0)
break;
if (errno == EPERM) {
int fd = open(filename, O_RDONLY);
if (fd != -1) {
long flags = 0;
if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) {
}
close(fd);
continue;
}
}
if (errno == EROFS) {
break;
}
if (errno != EBUSY || i > 100)
exit(1);
if (umount2(filename, MNT_DETACH))
exit(1);
}
}
closedir(dp);
int i;
for (i = 0;; i++) {
if (rmdir(dir) == 0)
break;
if (i < 100) {
if (errno == EPERM) {
int fd = open(dir, O_RDONLY);
if (fd != -1) {
long flags = 0;
if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) {
}
close(fd);
continue;
}
}
if (errno == EROFS) {
break;
}
if (errno == EBUSY) {
if (umount2(dir, MNT_DETACH))
exit(1);
continue;
}
if (errno == ENOTEMPTY) {
if (iter < 100) {
iter++;
goto retry;
}
}
}
exit(1);
}
}
static void kill_and_wait(int pid, int* status)
{
kill(-pid, SIGKILL);
kill(pid, SIGKILL);
int i;
for (i = 0; i < 100; i++) {
if (waitpid(-1, status, WNOHANG | __WALL) == pid)
return;
usleep(1000);
}
DIR* dir = opendir("/sys/fs/fuse/connections");
if (dir) {
for (;;) {
struct dirent* ent = readdir(dir);
if (!ent)
break;
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
char abort[300];
snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort",
ent->d_name);
int fd = open(abort, O_WRONLY);
if (fd == -1) {
continue;
}
if (write(fd, abort, 1) < 0) {
}
close(fd);
}
closedir(dir);
} else {
}
while (waitpid(-1, status, __WALL) != pid) {
}
}
static void reset_loop()
{
char buf[64];
snprintf(buf, sizeof(buf), "/dev/loop%llu", procid);
int loopfd = open(buf, O_RDWR);
if (loopfd != -1) {
ioctl(loopfd, LOOP_CLR_FD, 0);
close(loopfd);
}
}
static void setup_test()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
write_file("/proc/self/oom_score_adj", "1000");
}
struct thread_t {
int created, call;
event_t ready, done;
};
static struct thread_t threads[16];
static void execute_call(int call);
static int running;
static void* thr(void* arg)
{
struct thread_t* th = (struct thread_t*)arg;
for (;;) {
event_wait(&th->ready);
event_reset(&th->ready);
execute_call(th->call);
__atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED);
event_set(&th->done);
}
return 0;
}
static void execute_one(void)
{
int i, call, thread;
for (call = 0; call < 3; call++) {
for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0]));
thread++) {
struct thread_t* th = &threads[thread];
if (!th->created) {
th->created = 1;
event_init(&th->ready);
event_init(&th->done);
event_set(&th->done);
thread_start(thr, th);
}
if (!event_isset(&th->done))
continue;
event_reset(&th->done);
th->call = call;
__atomic_fetch_add(&running, 1, __ATOMIC_RELAXED);
event_set(&th->ready);
event_timedwait(&th->done, 45 + (call == 2 ? 100 : 0));
break;
}
}
for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++)
sleep_ms(1);
}
static void execute_one(void);
#define WAIT_FLAGS __WALL
static void loop(void)
{
int iter;
for (iter = 0;; iter++) {
char cwdbuf[32];
sprintf(cwdbuf, "./%d", iter);
if (mkdir(cwdbuf, 0777))
exit(1);
reset_loop();
int pid = fork();
if (pid < 0)
exit(1);
if (pid == 0) {
if (chdir(cwdbuf))
exit(1);
setup_test();
execute_one();
exit(0);
}
int status = 0;
uint64_t start = current_time_ms();
for (;;) {
if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid)
break;
sleep_ms(1);
if (current_time_ms() - start < 5 * 1000)
continue;
kill_and_wait(pid, &status);
break;
}
remove_dir(cwdbuf);
}
}
void execute_call(int call)
{
switch (call) {
case 0:
NONFAILING(memcpy((void*)0x200000c0, "./file0\000", 8));
syscall(__NR_open, 0x200000c0ul, 0x204c2ul, 0ul);
break;
case 1:
NONFAILING(memcpy((void*)0x20001340, "./file0", 7));
NONFAILING(memcpy((void*)0x20000180, "./file0\000", 8));
syscall(__NR_mount, 0x20001340ul, 0x20000180ul, 0ul, 0x30c5004ul, 0ul);
break;
case 2:
NONFAILING(memcpy((void*)0x20000080, "./file0\000", 8));
syz_mount_image(0, 0x20000080, 0, 0, 0, 0x38028b8, 0);
break;
}
}
int main(void)
{
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 3ul, 0x32ul, -1, 0);
install_segv_handler();
for (procid = 0; procid < 6; procid++) {
if (fork() == 0) {
use_temporary_dir();
loop();
}
}
sleep(1000000);
return 0;
}
|
the_stack_data/62637560.c | #include <stdio.h>//都是一个函数,(偷懒
int main()
{
char a[1000]={0};
scanf("%[^\n]",a);
int i=0,j;
while(a[i]!=0||a[i+1]!=0)
{
i+=1;
}
for(j=0;j<i;j++)
{
a[j]=255-a[j];
}
for(j=i-1;j>=0;j--)
{
printf("%c",a[j]);//简陋的反着打印
}
return 0;
} |
the_stack_data/40762891.c | # 1 "/scratch/local/tmp.soPlafqy6w/_sds/vhls/encrypt/solution/.autopilot/db/aes.pragma.1.c"
# 1 "/scratch/local/tmp.soPlafqy6w/_sds/vhls/encrypt/solution/.autopilot/db/aes.pragma.1.c" 1
# 1 "<built-in>" 1
# 1 "<built-in>" 3
# 146 "<built-in>" 3
# 1 "<command line>" 1
# 30 "<command line>"
# 1 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/common/technology/autopilot/etc/autopilot_ssdm_op.h" 1
/* autopilot_ssdm_op.h*/
/*
#- (c) Copyright 2011-2017 Xilinx, Inc. All rights reserved.
#-
#- This file contains confidential and proprietary information
#- of Xilinx, Inc. and is protected under U.S. and
#- international copyright and other intellectual property
#- laws.
#-
#- DISCLAIMER
#- This disclaimer is not a license and does not grant any
#- rights to the materials distributed herewith. Except as
#- otherwise provided in a valid license issued to you by
#- Xilinx, and to the maximum extent permitted by applicable
#- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
#- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
#- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
#- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
#- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
#- (2) Xilinx shall not be liable (whether in contract or tort,
#- including negligence, or under any other theory of
#- liability) for any loss or damage of any kind or nature
#- related to, arising under or in connection with these
#- materials, including for any direct, or any indirect,
#- special, incidental, or consequential loss or damage
#- (including loss of data, profits, goodwill, or any type of
#- loss or damage suffered as a result of any action brought
#- by a third party) even if such damage or loss was
#- reasonably foreseeable or Xilinx had been advised of the
#- possibility of the same.
#-
#- CRITICAL APPLICATIONS
#- Xilinx products are not designed or intended to be fail-
#- safe, or for use in any application requiring fail-safe
#- performance, such as life-support or safety devices or
#- systems, Class III medical devices, nuclear facilities,
#- applications related to the deployment of airbags, or any
#- other applications that could lead to death, personal
#- injury, or severe property or environmental damage
#- (individually and collectively, "Critical
#- Applications"). Customer assumes the sole risk and
#- liability of any use of Xilinx products in Critical
#- Applications, subject only to applicable laws and
#- regulations governing limitations on product liability.
#-
#- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
#- PART OF THIS FILE AT ALL TIMES.
#- ************************************************************************
*
* $Id$
*/
# 289 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/common/technology/autopilot/etc/autopilot_ssdm_op.h"
/*#define AP_SPEC_ATTR __attribute__ ((pure))*/
/****** SSDM Intrinsics: OPERATIONS ***/
// Interface operations
//typedef unsigned int __attribute__ ((bitwidth(1))) _uint1_;
void _ssdm_op_IfRead() __attribute__ ((nothrow));
void _ssdm_op_IfWrite() __attribute__ ((nothrow));
//_uint1_ _ssdm_op_IfNbRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_op_IfNbWrite() SSDM_OP_ATTR;
//_uint1_ _ssdm_op_IfCanRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_op_IfCanWrite() SSDM_OP_ATTR;
// Stream Intrinsics
void _ssdm_StreamRead() __attribute__ ((nothrow));
void _ssdm_StreamWrite() __attribute__ ((nothrow));
//_uint1_ _ssdm_StreamNbRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_StreamNbWrite() SSDM_OP_ATTR;
//_uint1_ _ssdm_StreamCanRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_StreamCanWrite() SSDM_OP_ATTR;
// Misc
void _ssdm_op_MemShiftRead() __attribute__ ((nothrow));
void _ssdm_op_Wait() __attribute__ ((nothrow));
void _ssdm_op_Poll() __attribute__ ((nothrow));
void _ssdm_op_Return() __attribute__ ((nothrow));
/* SSDM Intrinsics: SPECIFICATIONS */
void _ssdm_op_SpecSynModule() __attribute__ ((nothrow));
void _ssdm_op_SpecTopModule() __attribute__ ((nothrow));
void _ssdm_op_SpecProcessDecl() __attribute__ ((nothrow));
void _ssdm_op_SpecProcessDef() __attribute__ ((nothrow));
void _ssdm_op_SpecPort() __attribute__ ((nothrow));
void _ssdm_op_SpecConnection() __attribute__ ((nothrow));
void _ssdm_op_SpecChannel() __attribute__ ((nothrow));
void _ssdm_op_SpecSensitive() __attribute__ ((nothrow));
void _ssdm_op_SpecModuleInst() __attribute__ ((nothrow));
void _ssdm_op_SpecPortMap() __attribute__ ((nothrow));
void _ssdm_op_SpecReset() __attribute__ ((nothrow));
void _ssdm_op_SpecPlatform() __attribute__ ((nothrow));
void _ssdm_op_SpecClockDomain() __attribute__ ((nothrow));
void _ssdm_op_SpecPowerDomain() __attribute__ ((nothrow));
int _ssdm_op_SpecRegionBegin() __attribute__ ((nothrow));
int _ssdm_op_SpecRegionEnd() __attribute__ ((nothrow));
void _ssdm_op_SpecLoopName() __attribute__ ((nothrow));
void _ssdm_op_SpecLoopTripCount() __attribute__ ((nothrow));
int _ssdm_op_SpecStateBegin() __attribute__ ((nothrow));
int _ssdm_op_SpecStateEnd() __attribute__ ((nothrow));
void _ssdm_op_SpecInterface() __attribute__ ((nothrow));
void _ssdm_op_SpecPipeline() __attribute__ ((nothrow));
void _ssdm_op_SpecDataflowPipeline() __attribute__ ((nothrow));
void _ssdm_op_SpecLatency() __attribute__ ((nothrow));
void _ssdm_op_SpecParallel() __attribute__ ((nothrow));
void _ssdm_op_SpecProtocol() __attribute__ ((nothrow));
void _ssdm_op_SpecOccurrence() __attribute__ ((nothrow));
void _ssdm_op_SpecResource() __attribute__ ((nothrow));
void _ssdm_op_SpecResourceLimit() __attribute__ ((nothrow));
void _ssdm_op_SpecCHCore() __attribute__ ((nothrow));
void _ssdm_op_SpecFUCore() __attribute__ ((nothrow));
void _ssdm_op_SpecIFCore() __attribute__ ((nothrow));
void _ssdm_op_SpecIPCore() __attribute__ ((nothrow));
void _ssdm_op_SpecKeepValue() __attribute__ ((nothrow));
void _ssdm_op_SpecMemCore() __attribute__ ((nothrow));
void _ssdm_op_SpecExt() __attribute__ ((nothrow));
/*void* _ssdm_op_SpecProcess() SSDM_SPEC_ATTR;
void* _ssdm_op_SpecEdge() SSDM_SPEC_ATTR; */
/* Presynthesis directive functions */
void _ssdm_SpecArrayDimSize() __attribute__ ((nothrow));
void _ssdm_RegionBegin() __attribute__ ((nothrow));
void _ssdm_RegionEnd() __attribute__ ((nothrow));
void _ssdm_Unroll() __attribute__ ((nothrow));
void _ssdm_UnrollRegion() __attribute__ ((nothrow));
void _ssdm_InlineAll() __attribute__ ((nothrow));
void _ssdm_InlineLoop() __attribute__ ((nothrow));
void _ssdm_Inline() __attribute__ ((nothrow));
void _ssdm_InlineSelf() __attribute__ ((nothrow));
void _ssdm_InlineRegion() __attribute__ ((nothrow));
void _ssdm_SpecArrayMap() __attribute__ ((nothrow));
void _ssdm_SpecArrayPartition() __attribute__ ((nothrow));
void _ssdm_SpecArrayReshape() __attribute__ ((nothrow));
void _ssdm_SpecStream() __attribute__ ((nothrow));
void _ssdm_SpecExpr() __attribute__ ((nothrow));
void _ssdm_SpecExprBalance() __attribute__ ((nothrow));
void _ssdm_SpecDependence() __attribute__ ((nothrow));
void _ssdm_SpecLoopMerge() __attribute__ ((nothrow));
void _ssdm_SpecLoopFlatten() __attribute__ ((nothrow));
void _ssdm_SpecLoopRewind() __attribute__ ((nothrow));
void _ssdm_SpecFuncInstantiation() __attribute__ ((nothrow));
void _ssdm_SpecFuncBuffer() __attribute__ ((nothrow));
void _ssdm_SpecFuncExtract() __attribute__ ((nothrow));
void _ssdm_SpecConstant() __attribute__ ((nothrow));
void _ssdm_DataPack() __attribute__ ((nothrow));
void _ssdm_SpecDataPack() __attribute__ ((nothrow));
void _ssdm_op_SpecBitsMap() __attribute__ ((nothrow));
void _ssdm_op_SpecLicense() __attribute__ ((nothrow));
/*#define _ssdm_op_WaitUntil(X) while (!(X)) _ssdm_op_Wait(1);
#define _ssdm_op_Delayed(X) X */
# 427 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/common/technology/autopilot/etc/autopilot_ssdm_op.h"
// 67d7842dbbe25473c3c32b93c0da8047785f30d78e8a024de1b57352245f9689
# 31 "<command line>" 2
# 1 "<built-in>" 2
# 1 "/scratch/local/tmp.soPlafqy6w/_sds/vhls/encrypt/solution/.autopilot/db/aes.pragma.1.c" 2
# 1 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.c"
# 1 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.c" 1
# 1 "<built-in>" 1
# 1 "<built-in>" 3
# 146 "<built-in>" 3
# 1 "<command line>" 1
# 30 "<command line>"
# 1 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/common/technology/autopilot/etc/autopilot_ssdm_op.h" 1
/* autopilot_ssdm_op.h*/
/*
#- (c) Copyright 2011-2017 Xilinx, Inc. All rights reserved.
#-
#- This file contains confidential and proprietary information
#- of Xilinx, Inc. and is protected under U.S. and
#- international copyright and other intellectual property
#- laws.
#-
#- DISCLAIMER
#- This disclaimer is not a license and does not grant any
#- rights to the materials distributed herewith. Except as
#- otherwise provided in a valid license issued to you by
#- Xilinx, and to the maximum extent permitted by applicable
#- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
#- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
#- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
#- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
#- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
#- (2) Xilinx shall not be liable (whether in contract or tort,
#- including negligence, or under any other theory of
#- liability) for any loss or damage of any kind or nature
#- related to, arising under or in connection with these
#- materials, including for any direct, or any indirect,
#- special, incidental, or consequential loss or damage
#- (including loss of data, profits, goodwill, or any type of
#- loss or damage suffered as a result of any action brought
#- by a third party) even if such damage or loss was
#- reasonably foreseeable or Xilinx had been advised of the
#- possibility of the same.
#-
#- CRITICAL APPLICATIONS
#- Xilinx products are not designed or intended to be fail-
#- safe, or for use in any application requiring fail-safe
#- performance, such as life-support or safety devices or
#- systems, Class III medical devices, nuclear facilities,
#- applications related to the deployment of airbags, or any
#- other applications that could lead to death, personal
#- injury, or severe property or environmental damage
#- (individually and collectively, "Critical
#- Applications"). Customer assumes the sole risk and
#- liability of any use of Xilinx products in Critical
#- Applications, subject only to applicable laws and
#- regulations governing limitations on product liability.
#-
#- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
#- PART OF THIS FILE AT ALL TIMES.
#- ************************************************************************
*
* $Id$
*/
# 289 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/common/technology/autopilot/etc/autopilot_ssdm_op.h"
/*#define AP_SPEC_ATTR __attribute__ ((pure))*/
/****** SSDM Intrinsics: OPERATIONS ***/
// Interface operations
//typedef unsigned int __attribute__ ((bitwidth(1))) _uint1_;
void _ssdm_op_IfRead() __attribute__ ((nothrow));
void _ssdm_op_IfWrite() __attribute__ ((nothrow));
//_uint1_ _ssdm_op_IfNbRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_op_IfNbWrite() SSDM_OP_ATTR;
//_uint1_ _ssdm_op_IfCanRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_op_IfCanWrite() SSDM_OP_ATTR;
// Stream Intrinsics
void _ssdm_StreamRead() __attribute__ ((nothrow));
void _ssdm_StreamWrite() __attribute__ ((nothrow));
//_uint1_ _ssdm_StreamNbRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_StreamNbWrite() SSDM_OP_ATTR;
//_uint1_ _ssdm_StreamCanRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_StreamCanWrite() SSDM_OP_ATTR;
// Misc
void _ssdm_op_MemShiftRead() __attribute__ ((nothrow));
void _ssdm_op_Wait() __attribute__ ((nothrow));
void _ssdm_op_Poll() __attribute__ ((nothrow));
void _ssdm_op_Return() __attribute__ ((nothrow));
/* SSDM Intrinsics: SPECIFICATIONS */
void _ssdm_op_SpecSynModule() __attribute__ ((nothrow));
void _ssdm_op_SpecTopModule() __attribute__ ((nothrow));
void _ssdm_op_SpecProcessDecl() __attribute__ ((nothrow));
void _ssdm_op_SpecProcessDef() __attribute__ ((nothrow));
void _ssdm_op_SpecPort() __attribute__ ((nothrow));
void _ssdm_op_SpecConnection() __attribute__ ((nothrow));
void _ssdm_op_SpecChannel() __attribute__ ((nothrow));
void _ssdm_op_SpecSensitive() __attribute__ ((nothrow));
void _ssdm_op_SpecModuleInst() __attribute__ ((nothrow));
void _ssdm_op_SpecPortMap() __attribute__ ((nothrow));
void _ssdm_op_SpecReset() __attribute__ ((nothrow));
void _ssdm_op_SpecPlatform() __attribute__ ((nothrow));
void _ssdm_op_SpecClockDomain() __attribute__ ((nothrow));
void _ssdm_op_SpecPowerDomain() __attribute__ ((nothrow));
int _ssdm_op_SpecRegionBegin() __attribute__ ((nothrow));
int _ssdm_op_SpecRegionEnd() __attribute__ ((nothrow));
void _ssdm_op_SpecLoopName() __attribute__ ((nothrow));
void _ssdm_op_SpecLoopTripCount() __attribute__ ((nothrow));
int _ssdm_op_SpecStateBegin() __attribute__ ((nothrow));
int _ssdm_op_SpecStateEnd() __attribute__ ((nothrow));
void _ssdm_op_SpecInterface() __attribute__ ((nothrow));
void _ssdm_op_SpecPipeline() __attribute__ ((nothrow));
void _ssdm_op_SpecDataflowPipeline() __attribute__ ((nothrow));
void _ssdm_op_SpecLatency() __attribute__ ((nothrow));
void _ssdm_op_SpecParallel() __attribute__ ((nothrow));
void _ssdm_op_SpecProtocol() __attribute__ ((nothrow));
void _ssdm_op_SpecOccurrence() __attribute__ ((nothrow));
void _ssdm_op_SpecResource() __attribute__ ((nothrow));
void _ssdm_op_SpecResourceLimit() __attribute__ ((nothrow));
void _ssdm_op_SpecCHCore() __attribute__ ((nothrow));
void _ssdm_op_SpecFUCore() __attribute__ ((nothrow));
void _ssdm_op_SpecIFCore() __attribute__ ((nothrow));
void _ssdm_op_SpecIPCore() __attribute__ ((nothrow));
void _ssdm_op_SpecKeepValue() __attribute__ ((nothrow));
void _ssdm_op_SpecMemCore() __attribute__ ((nothrow));
void _ssdm_op_SpecExt() __attribute__ ((nothrow));
/*void* _ssdm_op_SpecProcess() SSDM_SPEC_ATTR;
void* _ssdm_op_SpecEdge() SSDM_SPEC_ATTR; */
/* Presynthesis directive functions */
void _ssdm_SpecArrayDimSize() __attribute__ ((nothrow));
void _ssdm_RegionBegin() __attribute__ ((nothrow));
void _ssdm_RegionEnd() __attribute__ ((nothrow));
void _ssdm_Unroll() __attribute__ ((nothrow));
void _ssdm_UnrollRegion() __attribute__ ((nothrow));
void _ssdm_InlineAll() __attribute__ ((nothrow));
void _ssdm_InlineLoop() __attribute__ ((nothrow));
void _ssdm_Inline() __attribute__ ((nothrow));
void _ssdm_InlineSelf() __attribute__ ((nothrow));
void _ssdm_InlineRegion() __attribute__ ((nothrow));
void _ssdm_SpecArrayMap() __attribute__ ((nothrow));
void _ssdm_SpecArrayPartition() __attribute__ ((nothrow));
void _ssdm_SpecArrayReshape() __attribute__ ((nothrow));
void _ssdm_SpecStream() __attribute__ ((nothrow));
void _ssdm_SpecExpr() __attribute__ ((nothrow));
void _ssdm_SpecExprBalance() __attribute__ ((nothrow));
void _ssdm_SpecDependence() __attribute__ ((nothrow));
void _ssdm_SpecLoopMerge() __attribute__ ((nothrow));
void _ssdm_SpecLoopFlatten() __attribute__ ((nothrow));
void _ssdm_SpecLoopRewind() __attribute__ ((nothrow));
void _ssdm_SpecFuncInstantiation() __attribute__ ((nothrow));
void _ssdm_SpecFuncBuffer() __attribute__ ((nothrow));
void _ssdm_SpecFuncExtract() __attribute__ ((nothrow));
void _ssdm_SpecConstant() __attribute__ ((nothrow));
void _ssdm_DataPack() __attribute__ ((nothrow));
void _ssdm_SpecDataPack() __attribute__ ((nothrow));
void _ssdm_op_SpecBitsMap() __attribute__ ((nothrow));
void _ssdm_op_SpecLicense() __attribute__ ((nothrow));
/*#define _ssdm_op_WaitUntil(X) while (!(X)) _ssdm_op_Wait(1);
#define _ssdm_op_Delayed(X) X */
# 427 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/common/technology/autopilot/etc/autopilot_ssdm_op.h"
// 67d7842dbbe25473c3c32b93c0da8047785f30d78e8a024de1b57352245f9689
# 31 "<command line>" 2
# 1 "<built-in>" 2
# 1 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.c" 2
/*
* Byte-oriented AES-256 implementation.
* All lookup tables replaced with 'on the fly' calculations.
*/
# 1 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.h" 1
/*
* Byte-oriented AES-256 implementation.
* All lookup tables replaced with 'on the fly' calculations.
*/
# 1 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/common/support.h" 1
# 1 "/usr/include/stdlib.h" 1 3 4
/* Copyright (C) 1991-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/*
* ISO C99 Standard: 7.20 General utilities <stdlib.h>
*/
# 1 "/usr/include/features.h" 1 3 4
/* Copyright (C) 1991-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* These are defined by the user (or the compiler)
to specify the desired environment:
__STRICT_ANSI__ ISO Standard C.
_ISOC99_SOURCE Extensions to ISO C89 from ISO C99.
_ISOC11_SOURCE Extensions to ISO C99 from ISO C11.
_POSIX_SOURCE IEEE Std 1003.1.
_POSIX_C_SOURCE If ==1, like _POSIX_SOURCE; if >=2 add IEEE Std 1003.2;
if >=199309L, add IEEE Std 1003.1b-1993;
if >=199506L, add IEEE Std 1003.1c-1995;
if >=200112L, all of IEEE 1003.1-2004
if >=200809L, all of IEEE 1003.1-2008
_XOPEN_SOURCE Includes POSIX and XPG things. Set to 500 if
Single Unix conformance is wanted, to 600 for the
sixth revision, to 700 for the seventh revision.
_XOPEN_SOURCE_EXTENDED XPG things and X/Open Unix extensions.
_LARGEFILE_SOURCE Some more functions for correct standard I/O.
_LARGEFILE64_SOURCE Additional functionality from LFS for large files.
_FILE_OFFSET_BITS=N Select default filesystem interface.
_ATFILE_SOURCE Additional *at interfaces.
_GNU_SOURCE All of the above, plus GNU extensions.
_DEFAULT_SOURCE The default set of features (taking precedence over
__STRICT_ANSI__).
_REENTRANT Select additionally reentrant object.
_THREAD_SAFE Same as _REENTRANT, often used by other systems.
_FORTIFY_SOURCE If set to numeric value > 0 additional security
measures are defined, according to level.
The `-ansi' switch to the GNU C compiler, and standards conformance
options such as `-std=c99', define __STRICT_ANSI__. If none of
these are defined, or if _DEFAULT_SOURCE is defined, the default is
to have _POSIX_SOURCE set to one and _POSIX_C_SOURCE set to
200809L, as well as enabling miscellaneous functions from BSD and
SVID. If more than one of these are defined, they accumulate. For
example __STRICT_ANSI__, _POSIX_SOURCE and _POSIX_C_SOURCE together
give you ISO C, 1003.1, and 1003.2, but nothing else.
These are defined by this file and are used by the
header files to decide what to declare or define:
__USE_ISOC11 Define ISO C11 things.
__USE_ISOC99 Define ISO C99 things.
__USE_ISOC95 Define ISO C90 AMD1 (C95) things.
__USE_POSIX Define IEEE Std 1003.1 things.
__USE_POSIX2 Define IEEE Std 1003.2 things.
__USE_POSIX199309 Define IEEE Std 1003.1, and .1b things.
__USE_POSIX199506 Define IEEE Std 1003.1, .1b, .1c and .1i things.
__USE_XOPEN Define XPG things.
__USE_XOPEN_EXTENDED Define X/Open Unix things.
__USE_UNIX98 Define Single Unix V2 things.
__USE_XOPEN2K Define XPG6 things.
__USE_XOPEN2KXSI Define XPG6 XSI things.
__USE_XOPEN2K8 Define XPG7 things.
__USE_XOPEN2K8XSI Define XPG7 XSI things.
__USE_LARGEFILE Define correct standard I/O things.
__USE_LARGEFILE64 Define LFS things with separate names.
__USE_FILE_OFFSET64 Define 64bit interface as default.
__USE_MISC Define things from 4.3BSD or System V Unix.
__USE_ATFILE Define *at interfaces and AT_* constants for them.
__USE_GNU Define GNU extensions.
__USE_REENTRANT Define reentrant/thread-safe *_r functions.
__USE_FORTIFY_LEVEL Additional security measures used, according to level.
The macros `__GNU_LIBRARY__', `__GLIBC__', and `__GLIBC_MINOR__' are
defined by this file unconditionally. `__GNU_LIBRARY__' is provided
only for compatibility. All new code should use the other symbols
to test for features.
All macros listed above as possibly being defined by this file are
explicitly undefined if they are not explicitly defined.
Feature-test macros that are not defined by the user or compiler
but are implied by the other feature-test macros defined (or by the
lack of any definitions) are defined by the file. */
/* Undefine everything, so we get a clean slate. */
# 122 "/usr/include/features.h" 3 4
/* Suppress kernel-name space pollution unless user expressedly asks
for it. */
/* Convenience macros to test the versions of glibc and gcc.
Use them like this:
#if __GNUC_PREREQ (2,8)
... code requiring gcc 2.8 or later ...
#endif
Note - they won't work for gcc1 or glibc1, since the _MINOR macros
were not defined then. */
/* _BSD_SOURCE and _SVID_SOURCE are deprecated aliases for
_DEFAULT_SOURCE. If _DEFAULT_SOURCE is present we do not
issue a warning; the expectation is that the source is being
transitioned to use the new macro. */
/* If _GNU_SOURCE was defined by the user, turn on all the other features. */
# 177 "/usr/include/features.h" 3 4
/* If nothing (other than _GNU_SOURCE and _DEFAULT_SOURCE) is defined,
define _DEFAULT_SOURCE. */
# 188 "/usr/include/features.h" 3 4
/* This is to enable the ISO C11 extension. */
/* This is to enable the ISO C99 extension. */
/* This is to enable the ISO C90 Amendment 1:1995 extension. */
/* This is to enable compatibility for ISO C++11.
So far g++ does not provide a macro. Check the temporary macro for
now, too. */
/* If none of the ANSI/POSIX macros are defined, or if _DEFAULT_SOURCE
is defined, use POSIX.1-2008 (or another version depending on
_XOPEN_SOURCE). */
# 341 "/usr/include/features.h" 3 4
/* Get definitions of __STDC_* predefined macros, if the compiler has
not preincluded this header automatically. */
# 1 "/usr/include/stdc-predef.h" 1 3 4
/* Copyright (C) 1991-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
# 52 "/usr/include/stdc-predef.h" 3 4
/* wchar_t uses Unicode 7.0.0. Version 7.0 of the Unicode Standard is
synchronized with ISO/IEC 10646:2012, plus Amendments 1 (published
on April, 2013) and 2 (not yet published as of February, 2015).
Additionally, it includes the accelerated publication of U+20BD
RUBLE SIGN. Therefore Unicode 7.0.0 is between 10646:2012 and
10646:2014, and so we use the date ISO/IEC 10646:2012 Amd.1 was
published. */
/* We do not support C11 <threads.h>. */
# 344 "/usr/include/features.h" 2 3 4
/* This macro indicates that the installed library is the GNU C Library.
For historic reasons the value now is 6 and this will stay from now
on. The use of this variable is deprecated. Use __GLIBC__ and
__GLIBC_MINOR__ now (see below) when you want to test for a specific
GNU C library version and use the values in <gnu/lib-names.h> to get
the sonames of the shared libraries. */
/* Major and minor version number of the GNU C library package. Use
these macros to test for features in specific releases. */
/* This is here only because every header file already includes this one. */
# 1 "/usr/include/sys/cdefs.h" 1 3 4
/* Copyright (C) 1992-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* We are almost always included from features.h. */
/* The GNU libc does not support any K&R compilers or the traditional mode
of ISO C compilers anymore. Check for some of the combinations not
anymore supported. */
/* Some user header file might have defined this before. */
/* All functions, except those with callbacks or those that
synchronize memory, are leaf functions. */
# 49 "/usr/include/sys/cdefs.h" 3 4
/* GCC can always grok prototypes. For C++ programs we add throw()
to help it optimize the function calls. But this works only with
gcc 2.8.x and egcs. For gcc 3.2 and up we even mark C functions
as non-throwing using a function attribute since programs can use
the -fexceptions options for C code as well. */
# 80 "/usr/include/sys/cdefs.h" 3 4
/* These two macros are not used in glibc anymore. They are kept here
only because some other projects expect the macros to be defined. */
/* For these things, GCC behaves the ANSI way normally,
and the non-ANSI way under -traditional. */
/* This is not a typedef so `const __ptr_t' does the right thing. */
/* C++ needs to know that types and declarations are C, not C++. */
# 106 "/usr/include/sys/cdefs.h" 3 4
/* The standard library needs the functions from the ISO C90 standard
in the std namespace. At the same time we want to be safe for
future changes and we include the ISO C99 code in the non-standard
namespace __c99. The C++ wrapper header take case of adding the
definitions to the global namespace. */
# 119 "/usr/include/sys/cdefs.h" 3 4
/* For compatibility we do not add the declarations into any
namespace. They will end up in the global namespace which is what
old code expects. */
# 131 "/usr/include/sys/cdefs.h" 3 4
/* Fortify support. */
# 147 "/usr/include/sys/cdefs.h" 3 4
/* Support for flexible arrays. */
/* GCC 2.97 supports C99 flexible array members. */
# 165 "/usr/include/sys/cdefs.h" 3 4
/* __asm__ ("xyz") is used throughout the headers to rename functions
at the assembly language level. This is wrapped by the __REDIRECT
macro, in order to support compilers that can do this some other
way. When compilers don't support asm-names at all, we have to do
preprocessor tricks instead (which don't have exactly the right
semantics, but it's the best we can do).
Example:
int __REDIRECT(setpgrp, (__pid_t pid, __pid_t pgrp), setpgid); */
# 192 "/usr/include/sys/cdefs.h" 3 4
/*
#elif __SOME_OTHER_COMPILER__
# define __REDIRECT(name, proto, alias) name proto; \
_Pragma("let " #name " = " #alias)
*/
/* GCC has various useful declarations that can be made with the
`__attribute__' syntax. All of the ways we use this do fine if
they are omitted for compilers that don't understand it. */
/* At some point during the gcc 2.96 development the `malloc' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings. */
/* Tell the compiler which arguments to an allocation function
indicate the size of the allocation. */
/* At some point during the gcc 2.96 development the `pure' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings. */
/* This declaration tells the compiler that the value is constant. */
/* At some point during the gcc 3.1 development the `used' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings. */
# 252 "/usr/include/sys/cdefs.h" 3 4
/* gcc allows marking deprecated functions. */
/* At some point during the gcc 2.8 development the `format_arg' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings.
If several `format_arg' attributes are given for the same function, in
gcc-3.0 and older, all but the last one are ignored. In newer gccs,
all designated arguments are considered. */
/* At some point during the gcc 2.97 development the `strfmon' format
attribute for functions was introduced. We don't want to use it
unconditionally (although this would be possible) since it
generates warnings. */
/* The nonull function attribute allows to mark pointer parameters which
must not be NULL. */
/* If fortification mode, we warn about unused results of certain
function calls which can lead to problems. */
# 305 "/usr/include/sys/cdefs.h" 3 4
/* Forces a function to be always inlined. */
/* Associate error messages with the source location of the call site rather
than with the source location inside the function. */
/* GCC 4.3 and above with -std=c99 or -std=gnu99 implements ISO C99
inline semantics, unless -fgnu89-inline is used. Using __GNUC_STDC_INLINE__
or __GNUC_GNU_INLINE is not a good enough check for gcc because gcc versions
older than 4.3 may define these macros and still not guarantee GNU inlining
semantics.
clang++ identifies itself as gcc-4.2, but has support for GNU inlining
semantics, that can be checked fot by using the __GNUC_STDC_INLINE_ and
__GNUC_GNU_INLINE__ macro definitions. */
# 346 "/usr/include/sys/cdefs.h" 3 4
/* GCC 4.3 and above allow passing all anonymous arguments of an
__extern_always_inline function to some other vararg function. */
/* It is possible to compile containing GCC extensions even if GCC is
run in pedantic mode if the uses are carefully marked using the
`__extension__' keyword. But this is not generally available before
version 2.8. */
/* __restrict is known in EGCS 1.2 and above. */
/* ISO C99 also allows to declare arrays as non-overlapping. The syntax is
array_name[restrict]
GCC 3.1 supports this. */
# 410 "/usr/include/sys/cdefs.h" 3 4
# 1 "/usr/include/bits/wordsize.h" 1 3 4
/* Determine the wordsize from the preprocessor defines. */
# 411 "/usr/include/sys/cdefs.h" 2 3 4
# 366 "/usr/include/features.h" 2 3 4
/* If we don't have __REDIRECT, prototypes will be missing if
__USE_FILE_OFFSET64 but not __USE_LARGEFILE[64]. */
/* Decide whether we can define 'extern inline' functions in headers. */
/* This is here only because every header file already includes this one.
Get the definitions of all the appropriate `__stub_FUNCTION' symbols.
<gnu/stubs.h> contains `#define __stub_FUNCTION' when FUNCTION is a stub
that will always return failure (and set errno to ENOSYS). */
# 1 "/usr/include/gnu/stubs.h" 1 3 4
/* This file is automatically generated.
This file selects the right generated file of `__stub_FUNCTION' macros
based on the architecture being compiled for. */
# 1 "/usr/include/gnu/stubs-32.h" 1 3 4
/* This file is automatically generated.
It defines a symbol `__stub_FUNCTION' for each function
in the C library which is a stub, meaning it will fail
every time called, usually setting errno to ENOSYS. */
# 8 "/usr/include/gnu/stubs.h" 2 3 4
# 390 "/usr/include/features.h" 2 3 4
# 25 "/usr/include/stdlib.h" 2 3 4
/* Get size_t, wchar_t and NULL from <stddef.h>. */
# 1 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/lnx64/tools/clang/bin/../lib/clang/3.1/include/stddef.h" 1 3 4
/*===---- stddef.h - Basic type definitions --------------------------------===
*
* Copyright (c) 2008 Eli Friedman
*
* 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.
*
*===-----------------------------------------------------------------------===
*/
typedef __typeof__(((int*)0)-((int*)0)) ptrdiff_t;
typedef __typeof__(sizeof(int)) size_t;
typedef int wchar_t;
# 56 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/lnx64/tools/clang/bin/../lib/clang/3.1/include/stddef.h" 3 4
/* Some C libraries expect to see a wint_t here. Others (notably MinGW) will use
__WINT_TYPE__ directly; accommodate both by requiring __need_wint_t */
# 33 "/usr/include/stdlib.h" 2 3 4
/* XPG requires a few symbols from <sys/wait.h> being defined. */
# 1 "/usr/include/bits/waitflags.h" 1 3 4
/* Definitions of flag bits for `waitpid' et al.
Copyright (C) 1992-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* Bits in the third argument to `waitpid'. */
/* Bits in the fourth argument to `waitid'. */
# 42 "/usr/include/stdlib.h" 2 3 4
# 1 "/usr/include/bits/waitstatus.h" 1 3 4
/* Definitions of status bits for `wait' et al.
Copyright (C) 1992-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* Everything extant so far uses these same bits. */
/* If WIFEXITED(STATUS), the low-order 8 bits of the status. */
/* If WIFSIGNALED(STATUS), the terminating signal. */
/* If WIFSTOPPED(STATUS), the signal that stopped the child. */
/* Nonzero if STATUS indicates normal termination. */
/* Nonzero if STATUS indicates termination by a signal. */
/* Nonzero if STATUS indicates the child is stopped. */
/* Nonzero if STATUS indicates the child continued after a stop. We only
define this if <bits/waitflags.h> provides the WCONTINUED flag bit. */
/* Nonzero if STATUS indicates the child dumped core. */
/* Macros for constructing status values. */
# 64 "/usr/include/bits/waitstatus.h" 3 4
# 1 "/usr/include/endian.h" 1 3 4
/* Copyright (C) 1992-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* Definitions for byte order, according to significance of bytes,
from low addresses to high addresses. The value is what you get by
putting '4' in the most significant byte, '3' in the second most
significant byte, '2' in the second least significant byte, and '1'
in the least significant byte, and then writing down one digit for
each byte, starting with the byte at the lowest address at the left,
and proceeding to the byte with the highest address at the right. */
/* This file defines `__BYTE_ORDER' for the particular machine. */
# 1 "/usr/include/bits/endian.h" 1 3 4
/* i386/x86_64 are little-endian. */
# 37 "/usr/include/endian.h" 2 3 4
/* Some machines may need to use a different endianness for floating point
values. */
# 59 "/usr/include/endian.h" 3 4
/* Conversion interfaces. */
# 1 "/usr/include/bits/byteswap.h" 1 3 4
/* Macros to swap the order of bytes in integer values.
Copyright (C) 1997-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
# 27 "/usr/include/bits/byteswap.h" 3 4
# 1 "/usr/include/bits/types.h" 1 3 4
/* bits/types.h -- definitions of __*_t types underlying *_t types.
Copyright (C) 2002-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/*
* Never include this file directly; use <sys/types.h> instead.
*/
# 1 "/usr/include/bits/wordsize.h" 1 3 4
/* Determine the wordsize from the preprocessor defines. */
# 28 "/usr/include/bits/types.h" 2 3 4
/* Convenience types. */
typedef unsigned char __u_char;
typedef unsigned short int __u_short;
typedef unsigned int __u_int;
typedef unsigned long int __u_long;
/* Fixed-size types, underlying types depend on word size and compiler. */
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;
__extension__ typedef signed long long int __int64_t;
__extension__ typedef unsigned long long int __uint64_t;
/* quad_t is also 64 bits. */
__extension__ typedef long long int __quad_t;
__extension__ typedef unsigned long long int __u_quad_t;
/* The machine-dependent file <bits/typesizes.h> defines __*_T_TYPE
macros for each of the OS types we define below. The definitions
of those macros must use the following macros for underlying types.
We define __S<SIZE>_TYPE and __U<SIZE>_TYPE for the signed and unsigned
variants of each of the following integer types on this machine.
16 -- "natural" 16-bit type (always short)
32 -- "natural" 32-bit type (always int)
64 -- "natural" 64-bit type (long or long long)
LONG32 -- 32-bit type, traditionally long
QUAD -- 64-bit type, always long long
WORD -- natural type of __WORDSIZE bits (int or long)
LONGWORD -- type of __WORDSIZE bits, traditionally long
We distinguish WORD/LONGWORD, 32/LONG32, and 64/QUAD so that the
conventional uses of `long' or `long long' type modifiers match the
types we define, even when a less-adorned type would be the same size.
This matters for (somewhat) portably writing printf/scanf formats for
these types, where using the appropriate l or ll format modifiers can
make the typedefs and the formats match up across all GNU platforms. If
we used `long' when it's 64 bits where `long long' is expected, then the
compiler would warn about the formats not matching the argument types,
and the programmer changing them to shut up the compiler would break the
program's portability.
Here we assume what is presently the case in all the GCC configurations
we support: long long is always 64 bits, long is always word/address size,
and int is always 32 bits. */
# 104 "/usr/include/bits/types.h" 3 4
/* We want __extension__ before typedef's that use nonstandard base types
such as `long long' in C89 mode. */
# 121 "/usr/include/bits/types.h" 3 4
# 1 "/usr/include/bits/typesizes.h" 1 3 4
/* bits/typesizes.h -- underlying types for *_t. Linux/x86-64 version.
Copyright (C) 2012-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
# 26 "/usr/include/bits/typesizes.h" 3 4
/* See <bits/types.h> for the meaning of these macros. This file exists so
that <bits/types.h> need not vary across different GNU platforms. */
/* X32 kernel interface is 64-bit. */
# 85 "/usr/include/bits/typesizes.h" 3 4
/* Number of descriptors that can fit in an `fd_set'. */
# 122 "/usr/include/bits/types.h" 2 3 4
__extension__ typedef __u_quad_t __dev_t; /* Type of device numbers. */
__extension__ typedef unsigned int __uid_t; /* Type of user identifications. */
__extension__ typedef unsigned int __gid_t; /* Type of group identifications. */
__extension__ typedef unsigned long int __ino_t; /* Type of file serial numbers. */
__extension__ typedef __u_quad_t __ino64_t; /* Type of file serial numbers (LFS).*/
__extension__ typedef unsigned int __mode_t; /* Type of file attribute bitmasks. */
__extension__ typedef unsigned int __nlink_t; /* Type of file link counts. */
__extension__ typedef long int __off_t; /* Type of file sizes and offsets. */
__extension__ typedef __quad_t __off64_t; /* Type of file sizes and offsets (LFS). */
__extension__ typedef int __pid_t; /* Type of process identifications. */
__extension__ typedef struct { int __val[2]; } __fsid_t; /* Type of file system IDs. */
__extension__ typedef long int __clock_t; /* Type of CPU usage counts. */
__extension__ typedef unsigned long int __rlim_t; /* Type for resource measurement. */
__extension__ typedef __u_quad_t __rlim64_t; /* Type for resource measurement (LFS). */
__extension__ typedef unsigned int __id_t; /* General type for IDs. */
__extension__ typedef long int __time_t; /* Seconds since the Epoch. */
__extension__ typedef unsigned int __useconds_t; /* Count of microseconds. */
__extension__ typedef long int __suseconds_t; /* Signed count of microseconds. */
__extension__ typedef int __daddr_t; /* The type of a disk address. */
__extension__ typedef int __key_t; /* Type of an IPC key. */
/* Clock ID used in clock and timer functions. */
__extension__ typedef int __clockid_t;
/* Timer ID returned by `timer_create'. */
__extension__ typedef void * __timer_t;
/* Type to represent block size. */
__extension__ typedef long int __blksize_t;
/* Types from the Large File Support interface. */
/* Type to count number of disk blocks. */
__extension__ typedef long int __blkcnt_t;
__extension__ typedef __quad_t __blkcnt64_t;
/* Type to count file system blocks. */
__extension__ typedef unsigned long int __fsblkcnt_t;
__extension__ typedef __u_quad_t __fsblkcnt64_t;
/* Type to count file system nodes. */
__extension__ typedef unsigned long int __fsfilcnt_t;
__extension__ typedef __u_quad_t __fsfilcnt64_t;
/* Type of miscellaneous file system fields. */
__extension__ typedef int __fsword_t;
__extension__ typedef int __ssize_t; /* Type of a byte count, or error. */
/* Signed long type used in system calls. */
__extension__ typedef long int __syscall_slong_t;
/* Unsigned long type used in system calls. */
__extension__ typedef unsigned long int __syscall_ulong_t;
/* These few don't really vary by system, they always correspond
to one of the other defined types. */
typedef __off64_t __loff_t; /* Type of file sizes and offsets (LFS). */
typedef __quad_t *__qaddr_t;
typedef char *__caddr_t;
/* Duplicates info from stdint.h but this is used in unistd.h. */
__extension__ typedef int __intptr_t;
/* Duplicate info from sys/socket.h. */
__extension__ typedef unsigned int __socklen_t;
# 28 "/usr/include/bits/byteswap.h" 2 3 4
# 1 "/usr/include/bits/wordsize.h" 1 3 4
/* Determine the wordsize from the preprocessor defines. */
# 29 "/usr/include/bits/byteswap.h" 2 3 4
/* Swap bytes in 16 bit value. */
/* Get __bswap_16. */
# 1 "/usr/include/bits/byteswap-16.h" 1 3 4
/* Macros to swap the order of bytes in 16-bit integer values.
Copyright (C) 2012-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
# 36 "/usr/include/bits/byteswap.h" 2 3 4
/* Swap bytes in 32 bit value. */
# 56 "/usr/include/bits/byteswap.h" 3 4
/* To swap the bytes in a word the i486 processors and up provide the
`bswap' opcode. On i386 we have to use three instructions. */
# 96 "/usr/include/bits/byteswap.h" 3 4
/* Swap bytes in 64 bit value. */
# 61 "/usr/include/endian.h" 2 3 4
# 65 "/usr/include/bits/waitstatus.h" 2 3 4
union wait
{
int w_status;
struct
{
unsigned int __w_termsig:7; /* Terminating signal. */
unsigned int __w_coredump:1; /* Set if dumped core. */
unsigned int __w_retcode:8; /* Return code if exited normally. */
unsigned int:16;
} __wait_terminated;
struct
{
unsigned int __w_stopval:8; /* W_STOPPED if stopped. */
unsigned int __w_stopsig:8; /* Stopping signal. */
unsigned int:16;
} __wait_stopped;
};
# 43 "/usr/include/stdlib.h" 2 3 4
/* Lots of hair to allow traditional BSD use of `union wait'
as well as POSIX.1 use of `int' for the status word. */
# 57 "/usr/include/stdlib.h" 3 4
/* This is the type of the argument to `wait'. The funky union
causes redeclarations with either `int *' or `union wait *' to be
allowed without complaint. __WAIT_STATUS_DEFN is the type used in
the actual function definitions. */
/* This works in GCC 2.6.1 and later. */
typedef union
{
union wait *__uptr;
int *__iptr;
} __WAIT_STATUS __attribute__ ((__transparent_union__));
# 83 "/usr/include/stdlib.h" 3 4
/* Define the macros <sys/wait.h> also would define this way. */
# 96 "/usr/include/stdlib.h" 3 4
/* Returned by `div'. */
typedef struct
{
int quot; /* Quotient. */
int rem; /* Remainder. */
} div_t;
/* Returned by `ldiv'. */
typedef struct
{
long int quot; /* Quotient. */
long int rem; /* Remainder. */
} ldiv_t;
/* Returned by `lldiv'. */
__extension__ typedef struct
{
long long int quot; /* Quotient. */
long long int rem; /* Remainder. */
} lldiv_t;
/* The largest number rand will return (same as INT_MAX). */
/* We define these the same for all machines.
Changes from this to the outside world should be done in `_exit'. */
/* Maximum length of a multibyte character in the current locale. */
extern size_t __ctype_get_mb_cur_max (void) __attribute__ ((__nothrow__ )) /* Ignore */;
/* Convert a string to a floating-point number. */
extern double atof (const char *__nptr)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) /* Ignore */;
/* Convert a string to an integer. */
extern int atoi (const char *__nptr)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) /* Ignore */;
/* Convert a string to a long integer. */
extern long int atol (const char *__nptr)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) /* Ignore */;
/* Convert a string to a long long integer. */
__extension__ extern long long int atoll (const char *__nptr)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) /* Ignore */;
/* Convert a string to a floating-point number. */
extern double strtod (const char *__restrict __nptr,
char **__restrict __endptr)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Likewise for `float' and `long double' sizes of floating-point numbers. */
extern float strtof (const char *__restrict __nptr,
char **__restrict __endptr) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern long double strtold (const char *__restrict __nptr,
char **__restrict __endptr)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Convert a string to a long integer. */
extern long int strtol (const char *__restrict __nptr,
char **__restrict __endptr, int __base)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Convert a string to an unsigned long integer. */
extern unsigned long int strtoul (const char *__restrict __nptr,
char **__restrict __endptr, int __base)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Convert a string to a quadword integer. */
__extension__
extern long long int strtoq (const char *__restrict __nptr,
char **__restrict __endptr, int __base)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Convert a string to an unsigned quadword integer. */
__extension__
extern unsigned long long int strtouq (const char *__restrict __nptr,
char **__restrict __endptr, int __base)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Convert a string to a quadword integer. */
__extension__
extern long long int strtoll (const char *__restrict __nptr,
char **__restrict __endptr, int __base)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Convert a string to an unsigned quadword integer. */
__extension__
extern unsigned long long int strtoull (const char *__restrict __nptr,
char **__restrict __endptr, int __base)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
# 302 "/usr/include/stdlib.h" 3 4
/* Convert N to base 64 using the digits "./0-9A-Za-z", least-significant
digit first. Returns a pointer to static storage overwritten by the
next call. */
extern char *l64a (long int __n) __attribute__ ((__nothrow__ )) /* Ignore */;
/* Read a number from a string S in base 64 as above. */
extern long int a64l (const char *__s)
__attribute__ ((__nothrow__ )) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) /* Ignore */;
# 1 "/usr/include/sys/types.h" 1 3 4
/* Copyright (C) 1991-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/*
* POSIX Standard: 2.6 Primitive System Data Types <sys/types.h>
*/
# 33 "/usr/include/sys/types.h" 3 4
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;
# 60 "/usr/include/sys/types.h" 3 4
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;
# 98 "/usr/include/sys/types.h" 3 4
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;
# 132 "/usr/include/sys/types.h" 3 4
# 1 "/usr/include/time.h" 1 3 4
/* Copyright (C) 1991-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/*
* ISO C99 Standard: 7.23 Date and time <time.h>
*/
# 58 "/usr/include/time.h" 3 4
/* Returned by `clock'. */
typedef __clock_t clock_t;
# 74 "/usr/include/time.h" 3 4
/* Returned by `time'. */
typedef __time_t time_t;
# 90 "/usr/include/time.h" 3 4
/* Clock ID used in clock and timer functions. */
typedef __clockid_t clockid_t;
# 102 "/usr/include/time.h" 3 4
/* Timer ID returned by `timer_create'. */
typedef __timer_t timer_t;
# 133 "/usr/include/sys/types.h" 2 3 4
# 146 "/usr/include/sys/types.h" 3 4
# 1 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/lnx64/tools/clang/bin/../lib/clang/3.1/include/stddef.h" 1 3 4
/*===---- stddef.h - Basic type definitions --------------------------------===
*
* Copyright (c) 2008 Eli Friedman
*
* 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.
*
*===-----------------------------------------------------------------------===
*/
# 56 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/lnx64/tools/clang/bin/../lib/clang/3.1/include/stddef.h" 3 4
/* Some C libraries expect to see a wint_t here. Others (notably MinGW) will use
__WINT_TYPE__ directly; accommodate both by requiring __need_wint_t */
# 147 "/usr/include/sys/types.h" 2 3 4
/* Old compatibility names for C types. */
typedef unsigned long int ulong;
typedef unsigned short int ushort;
typedef unsigned int uint;
/* These size-specific names are used by some of the inet code. */
# 186 "/usr/include/sys/types.h" 3 4
/* For GCC 2.7 and later, we can use specific type-size attributes. */
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__)));
/* Some code from BIND tests this macro to see if the types above are
defined. */
/* In BSD <sys/types.h> is expected to define BYTE_ORDER. */
/* It also defines `fd_set' and the FD_* macros for `select'. */
# 1 "/usr/include/sys/select.h" 1 3 4
/* `fd_set' type and related macros, and `select'/`pselect' declarations.
Copyright (C) 1996-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* POSIX 1003.1g: 6.2 Select from File Descriptor Sets <sys/select.h> */
/* Get definition of needed basic types. */
/* Get __FD_* definitions. */
# 1 "/usr/include/bits/select.h" 1 3 4
/* Copyright (C) 1997-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
# 1 "/usr/include/bits/wordsize.h" 1 3 4
/* Determine the wordsize from the preprocessor defines. */
# 23 "/usr/include/bits/select.h" 2 3 4
# 31 "/usr/include/sys/select.h" 2 3 4
/* Get __sigset_t. */
# 1 "/usr/include/bits/sigset.h" 1 3 4
/* __sig_atomic_t, __sigset_t, and related definitions. Linux version.
Copyright (C) 1991-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
typedef int __sig_atomic_t;
/* A `sigset_t' has a bit for each signal. */
typedef struct
{
unsigned long int __val[(1024 / (8 * sizeof (unsigned long int)))];
} __sigset_t;
/* We only want to define these functions if <signal.h> was actually
included; otherwise we were included just to define the types. Since we
are namespace-clean, it wouldn't hurt to define extra macros. But
trouble can be caused by functions being defined (e.g., any global
register vars declared later will cause compilation errors). */
# 34 "/usr/include/sys/select.h" 2 3 4
typedef __sigset_t sigset_t;
/* Get definition of timer specification structures. */
# 1 "/usr/include/time.h" 1 3 4
/* Copyright (C) 1991-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/*
* ISO C99 Standard: 7.23 Date and time <time.h>
*/
# 118 "/usr/include/time.h" 3 4
/* POSIX.1b structure for a time value. This is like a `struct timeval' but
has nanoseconds instead of microseconds. */
struct timespec
{
__time_t tv_sec; /* Seconds. */
__syscall_slong_t tv_nsec; /* Nanoseconds. */
};
# 44 "/usr/include/sys/select.h" 2 3 4
# 1 "/usr/include/bits/time.h" 1 3 4
/* System-dependent timing definitions. Linux version.
Copyright (C) 1996-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/*
* Never include this file directly; use <time.h> instead.
*/
/* A time value that is accurate to the nearest
microsecond but also has a range of years. */
struct timeval
{
__time_t tv_sec; /* Seconds. */
__suseconds_t tv_usec; /* Microseconds. */
};
# 46 "/usr/include/sys/select.h" 2 3 4
typedef __suseconds_t suseconds_t;
/* The fd_set member is required to be an array of longs. */
typedef long int __fd_mask;
/* Some versions of <linux/posix_types.h> define this macros. */
/* It's easier to assume 8-bit bytes than to get CHAR_BIT. */
/* fd_set for select and pselect. */
typedef struct
{
/* XPG4.2 requires this member name. Otherwise avoid the name
from the global namespace. */
__fd_mask __fds_bits[1024 / (8 * (int) sizeof (__fd_mask))];
} fd_set;
/* Maximum number of file descriptors in `fd_set'. */
/* Sometimes the fd_set member is assumed to have this type. */
typedef __fd_mask fd_mask;
/* Number of bits per word of `fd_set' (some code assumes this is 32). */
/* Access macros for `fd_set'. */
# 98 "/usr/include/sys/select.h" 3 4
/* Check the first NFDS descriptors each in READFDS (if not NULL) for read
readiness, in WRITEFDS (if not NULL) for write readiness, and in EXCEPTFDS
(if not NULL) for exceptional conditions. If TIMEOUT is not NULL, time out
after waiting the interval specified therein. Returns the number of ready
descriptors, or -1 for errors.
This function is a cancellation point and therefore not marked with
__THROW. */
extern int select (int __nfds, fd_set *__restrict __readfds,
fd_set *__restrict __writefds,
fd_set *__restrict __exceptfds,
struct timeval *__restrict __timeout);
/* Same as above only that the TIMEOUT value is given with higher
resolution and a sigmask which is been set temporarily. This version
should be used.
This function is a cancellation point and therefore not marked with
__THROW. */
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);
/* Define some inlines helping to catch common problems. */
# 220 "/usr/include/sys/types.h" 2 3 4
/* BSD defines these symbols, so we follow. */
# 1 "/usr/include/sys/sysmacros.h" 1 3 4
/* Definitions of macros to access `dev_t' values.
Copyright (C) 1996-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
# 26 "/usr/include/sys/sysmacros.h" 3 4
__extension__
extern unsigned int gnu_dev_major (unsigned long long int __dev)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__));
__extension__
extern unsigned int gnu_dev_minor (unsigned long long int __dev)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__));
__extension__
extern unsigned long long int gnu_dev_makedev (unsigned int __major,
unsigned int __minor)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__));
# 60 "/usr/include/sys/sysmacros.h" 3 4
/* Access the functions with their traditional names. */
# 223 "/usr/include/sys/types.h" 2 3 4
typedef __blksize_t blksize_t;
/* Types from the Large File Support interface. */
typedef __blkcnt_t blkcnt_t; /* Type to count number of disk blocks. */
typedef __fsblkcnt_t fsblkcnt_t; /* Type to count file system blocks. */
typedef __fsfilcnt_t fsfilcnt_t; /* Type to count file system inodes. */
# 268 "/usr/include/sys/types.h" 3 4
/* Now add the thread types. */
# 1 "/usr/include/bits/pthreadtypes.h" 1 3 4
/* Copyright (C) 2002-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
# 1 "/usr/include/bits/wordsize.h" 1 3 4
/* Determine the wordsize from the preprocessor defines. */
# 22 "/usr/include/bits/pthreadtypes.h" 2 3 4
# 58 "/usr/include/bits/pthreadtypes.h" 3 4
/* Thread identifiers. The structure of the attribute type is not
exposed on purpose. */
typedef unsigned long int pthread_t;
union pthread_attr_t
{
char __size[36];
long int __align;
};
typedef union pthread_attr_t pthread_attr_t;
# 81 "/usr/include/bits/pthreadtypes.h" 3 4
typedef struct __pthread_internal_slist
{
struct __pthread_internal_slist *__next;
} __pthread_slist_t;
/* Data structures for mutex handling. The structure of the attribute
type is not exposed on purpose. */
typedef union
{
struct __pthread_mutex_s
{
int __lock;
unsigned int __count;
int __owner;
/* KIND must stay at this position in the structure to maintain
binary compatibility. */
int __kind;
# 111 "/usr/include/bits/pthreadtypes.h" 3 4
unsigned int __nusers;
__extension__ union
{
struct
{
short __espins;
short __elision;
} __elision_data;
__pthread_slist_t __list;
};
} __data;
char __size[24];
long int __align;
} pthread_mutex_t;
typedef union
{
char __size[4];
int __align;
} pthread_mutexattr_t;
/* Data structure for conditional variable handling. The structure of
the attribute type is not exposed on purpose. */
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;
/* Keys for thread-specific data */
typedef unsigned int pthread_key_t;
/* Once-only execution */
typedef int pthread_once_t;
/* Data structure for read-write lock variable handling. The
structure of the attribute type is not exposed on purpose. */
typedef union
{
# 202 "/usr/include/bits/pthreadtypes.h" 3 4
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;
/* FLAGS must stay at this position in the structure to maintain
binary compatibility. */
unsigned char __flags;
unsigned char __shared;
signed char __rwelision;
unsigned char __pad2;
int __writer;
} __data;
char __size[32];
long int __align;
} pthread_rwlock_t;
typedef union
{
char __size[8];
long int __align;
} pthread_rwlockattr_t;
/* POSIX spinlock data type. */
typedef volatile int pthread_spinlock_t;
/* POSIX barriers data type. The structure of the type is
deliberately not exposed. */
typedef union
{
char __size[20];
long int __align;
} pthread_barrier_t;
typedef union
{
char __size[4];
int __align;
} pthread_barrierattr_t;
/* Extra attributes for the cleanup functions. */
# 271 "/usr/include/sys/types.h" 2 3 4
# 315 "/usr/include/stdlib.h" 2 3 4
/* These are the functions that actually do things. The `random', `srandom',
`initstate' and `setstate' functions are those from BSD Unices.
The `rand' and `srand' functions are required by the ANSI standard.
We provide both interfaces to the same random number generator. */
/* Return a random long integer between 0 and RAND_MAX inclusive. */
extern long int random (void) __attribute__ ((__nothrow__ ));
/* Seed the random number generator with the given number. */
extern void srandom (unsigned int __seed) __attribute__ ((__nothrow__ ));
/* Initialize the random number generator to use state buffer STATEBUF,
of length STATELEN, and seed it with SEED. Optimal lengths are 8, 16,
32, 64, 128 and 256, the bigger the better; values less than 8 will
cause an error and values greater than 256 will be rounded down. */
extern char *initstate (unsigned int __seed, char *__statebuf,
size_t __statelen) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2)));
/* Switch the random number generator to state buffer STATEBUF,
which should have been previously initialized by `initstate'. */
extern char *setstate (char *__statebuf) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Reentrant versions of the `random' family of functions.
These functions all use the following data structure to contain
state, rather than global state variables. */
struct random_data
{
int32_t *fptr; /* Front pointer. */
int32_t *rptr; /* Rear pointer. */
int32_t *state; /* Array of state values. */
int rand_type; /* Type of random number generator. */
int rand_deg; /* Degree of random number generator. */
int rand_sep; /* Distance between front and rear. */
int32_t *end_ptr; /* Pointer behind state table. */
};
extern int random_r (struct random_data *__restrict __buf,
int32_t *__restrict __result) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int srandom_r (unsigned int __seed, struct random_data *__buf)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2)));
extern int initstate_r (unsigned int __seed, char *__restrict __statebuf,
size_t __statelen,
struct random_data *__restrict __buf)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2, 4)));
extern int setstate_r (char *__restrict __statebuf,
struct random_data *__restrict __buf)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
/* Return a random integer between 0 and RAND_MAX inclusive. */
extern int rand (void) __attribute__ ((__nothrow__ ));
/* Seed the random number generator with the given number. */
extern void srand (unsigned int __seed) __attribute__ ((__nothrow__ ));
/* Reentrant interface according to POSIX.1. */
extern int rand_r (unsigned int *__seed) __attribute__ ((__nothrow__ ));
/* System V style 48-bit random number generator functions. */
/* Return non-negative, double-precision floating-point value in [0.0,1.0). */
extern double drand48 (void) __attribute__ ((__nothrow__ ));
extern double erand48 (unsigned short int __xsubi[3]) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Return non-negative, long integer in [0,2^31). */
extern long int lrand48 (void) __attribute__ ((__nothrow__ ));
extern long int nrand48 (unsigned short int __xsubi[3])
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Return signed, long integers in [-2^31,2^31). */
extern long int mrand48 (void) __attribute__ ((__nothrow__ ));
extern long int jrand48 (unsigned short int __xsubi[3])
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Seed random number generator. */
extern void srand48 (long int __seedval) __attribute__ ((__nothrow__ ));
extern unsigned short int *seed48 (unsigned short int __seed16v[3])
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
extern void lcong48 (unsigned short int __param[7]) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Data structure for communication with thread safe versions. This
type is to be regarded as opaque. It's only exported because users
have to allocate objects of this type. */
struct drand48_data
{
unsigned short int __x[3]; /* Current state. */
unsigned short int __old_x[3]; /* Old state. */
unsigned short int __c; /* Additive const. in congruential formula. */
unsigned short int __init; /* Flag for initializing. */
__extension__ unsigned long long int __a; /* Factor in congruential
formula. */
};
/* Return non-negative, double-precision floating-point value in [0.0,1.0). */
extern int drand48_r (struct drand48_data *__restrict __buffer,
double *__restrict __result) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int erand48_r (unsigned short int __xsubi[3],
struct drand48_data *__restrict __buffer,
double *__restrict __result) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
/* Return non-negative, long integer in [0,2^31). */
extern int lrand48_r (struct drand48_data *__restrict __buffer,
long int *__restrict __result)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int nrand48_r (unsigned short int __xsubi[3],
struct drand48_data *__restrict __buffer,
long int *__restrict __result)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
/* Return signed, long integers in [-2^31,2^31). */
extern int mrand48_r (struct drand48_data *__restrict __buffer,
long int *__restrict __result)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int jrand48_r (unsigned short int __xsubi[3],
struct drand48_data *__restrict __buffer,
long int *__restrict __result)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
/* Seed random number generator. */
extern int srand48_r (long int __seedval, struct drand48_data *__buffer)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2)));
extern int seed48_r (unsigned short int __seed16v[3],
struct drand48_data *__buffer) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
extern int lcong48_r (unsigned short int __param[7],
struct drand48_data *__buffer)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2)));
# 465 "/usr/include/stdlib.h" 3 4
/* Allocate SIZE bytes of memory. */
extern void *malloc (size_t __size) __attribute__ ((__nothrow__ )) __attribute__ ((__malloc__)) /* Ignore */;
/* Allocate NMEMB elements of SIZE bytes each, all initialized to 0. */
extern void *calloc (size_t __nmemb, size_t __size)
__attribute__ ((__nothrow__ )) __attribute__ ((__malloc__)) /* Ignore */;
/* Re-allocate the previously allocated block
in PTR, making the new block SIZE bytes long. */
/* __attribute_malloc__ is not used, because if realloc returns
the same pointer that was passed to it, aliasing needs to be allowed
between objects pointed by the old and new pointers. */
extern void *realloc (void *__ptr, size_t __size)
__attribute__ ((__nothrow__ )) __attribute__ ((__warn_unused_result__));
/* Free a block allocated by `malloc', `realloc' or `calloc'. */
extern void free (void *__ptr) __attribute__ ((__nothrow__ ));
/* Free a block. An alias for `free'. (Sun Unices). */
extern void cfree (void *__ptr) __attribute__ ((__nothrow__ ));
# 1 "/usr/include/alloca.h" 1 3 4
/* Copyright (C) 1992-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
# 25 "/usr/include/alloca.h" 3 4
# 1 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/lnx64/tools/clang/bin/../lib/clang/3.1/include/stddef.h" 1 3 4
/*===---- stddef.h - Basic type definitions --------------------------------===
*
* Copyright (c) 2008 Eli Friedman
*
* 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.
*
*===-----------------------------------------------------------------------===
*/
# 56 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/lnx64/tools/clang/bin/../lib/clang/3.1/include/stddef.h" 3 4
/* Some C libraries expect to see a wint_t here. Others (notably MinGW) will use
__WINT_TYPE__ directly; accommodate both by requiring __need_wint_t */
# 25 "/usr/include/alloca.h" 2 3 4
/* Remove any previous definitions. */
/* Allocate a block that will be freed when the calling function exits. */
extern void *alloca (size_t __size) __attribute__ ((__nothrow__ ));
# 493 "/usr/include/stdlib.h" 2 3 4
/* Allocate SIZE bytes on a page boundary. The storage cannot be freed. */
extern void *valloc (size_t __size) __attribute__ ((__nothrow__ )) __attribute__ ((__malloc__)) /* Ignore */;
/* Allocate memory of SIZE bytes with an alignment of ALIGNMENT. */
extern int posix_memalign (void **__memptr, size_t __alignment, size_t __size)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1))) /* Ignore */;
# 514 "/usr/include/stdlib.h" 3 4
/* Abort execution and generate a core-dump. */
extern void abort (void) __attribute__ ((__nothrow__ )) __attribute__ ((__noreturn__));
/* Register a function to be called when `exit' is called. */
extern int atexit (void (*__func) (void)) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
# 533 "/usr/include/stdlib.h" 3 4
/* Register a function to be called with the status
given to `exit' and the given argument. */
extern int on_exit (void (*__func) (int __status, void *__arg), void *__arg)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Call all functions registered with `atexit' and `on_exit',
in the reverse of the order in which they were registered,
perform stdio cleanup, and terminate program execution with STATUS. */
extern void exit (int __status) __attribute__ ((__nothrow__ )) __attribute__ ((__noreturn__));
# 555 "/usr/include/stdlib.h" 3 4
/* Terminate the program with STATUS without calling any of the
functions registered with `atexit' or `on_exit'. */
extern void _Exit (int __status) __attribute__ ((__nothrow__ )) __attribute__ ((__noreturn__));
/* Return the value of envariable NAME, or NULL if it doesn't exist. */
extern char *getenv (const char *__name) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1))) /* Ignore */;
# 575 "/usr/include/stdlib.h" 3 4
/* The SVID says this is in <stdio.h>, but this seems a better place. */
/* Put STRING, which is of the form "NAME=VALUE", in the environment.
If there is no `=', remove NAME from the environment. */
extern int putenv (char *__string) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Set NAME to VALUE in the environment.
If REPLACE is nonzero, overwrite an existing value. */
extern int setenv (const char *__name, const char *__value, int __replace)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (2)));
/* Remove the variable NAME from the environment. */
extern int unsetenv (const char *__name) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* The `clearenv' was planned to be added to POSIX.1 but probably
never made it. Nevertheless the POSIX.9 standard (POSIX bindings
for Fortran 77) requires this function. */
extern int clearenv (void) __attribute__ ((__nothrow__ ));
/* Generate a unique temporary file name from TEMPLATE.
The last six characters of TEMPLATE must be "XXXXXX";
they are replaced with a string that makes the file name unique.
Always returns TEMPLATE, it's either a temporary file name or a null
string if it cannot get a unique file name. */
extern char *mktemp (char *__template) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
/* Generate a unique temporary file name from TEMPLATE.
The last six characters of TEMPLATE must be "XXXXXX";
they are replaced with a string that makes the filename unique.
Returns a file descriptor open on the file for reading and writing,
or -1 if it cannot create a uniquely-named file.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int mkstemp (char *__template) __attribute__ ((__nonnull__ (1))) /* Ignore */;
# 634 "/usr/include/stdlib.h" 3 4
/* Similar to mkstemp, but the template can have a suffix after the
XXXXXX. The length of the suffix is specified in the second
parameter.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int mkstemps (char *__template, int __suffixlen) __attribute__ ((__nonnull__ (1))) /* Ignore */;
# 657 "/usr/include/stdlib.h" 3 4
/* Create a unique temporary directory from TEMPLATE.
The last six characters of TEMPLATE must be "XXXXXX";
they are replaced with a string that makes the directory name unique.
Returns TEMPLATE, or a null pointer if it cannot get a unique name.
The directory is created mode 700. */
extern char *mkdtemp (char *__template) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1))) /* Ignore */;
# 712 "/usr/include/stdlib.h" 3 4
/* Execute the given line as a shell command.
This function is a cancellation point and therefore not marked with
__THROW. */
extern int system (const char *__command) /* Ignore */;
# 728 "/usr/include/stdlib.h" 3 4
/* Return the canonical absolute name of file NAME. If RESOLVED is
null, the result is malloc'd; otherwise, if the canonical name is
PATH_MAX chars or more, returns null with `errno' set to
ENAMETOOLONG; if the name fits in fewer than PATH_MAX chars,
returns the name in RESOLVED. */
extern char *realpath (const char *__restrict __name,
char *__restrict __resolved) __attribute__ ((__nothrow__ )) /* Ignore */;
/* Shorthand for type of comparison functions. */
typedef int (*__compar_fn_t) (const void *, const void *);
# 752 "/usr/include/stdlib.h" 3 4
/* Do a binary search for KEY in BASE, which consists of NMEMB elements
of SIZE bytes each, using COMPAR to perform the comparisons. */
extern void *bsearch (const void *__key, const void *__base,
size_t __nmemb, size_t __size, __compar_fn_t __compar)
__attribute__ ((__nonnull__ (1, 2, 5))) /* Ignore */;
/* Sort NMEMB elements of BASE, of SIZE bytes each,
using COMPAR to perform the comparisons. */
extern void qsort (void *__base, size_t __nmemb, size_t __size,
__compar_fn_t __compar) __attribute__ ((__nonnull__ (1, 4)));
/* Return the absolute value of X. */
extern int abs (int __x) __attribute__ ((__nothrow__ )) __attribute__ ((__const__)) /* Ignore */;
extern long int labs (long int __x) __attribute__ ((__nothrow__ )) __attribute__ ((__const__)) /* Ignore */;
__extension__ extern long long int llabs (long long int __x)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__)) /* Ignore */;
/* Return the `div_t', `ldiv_t' or `lldiv_t' representation
of the value of NUMER over DENOM. */
/* GCC may have built-ins for these someday. */
extern div_t div (int __numer, int __denom)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__)) /* Ignore */;
extern ldiv_t ldiv (long int __numer, long int __denom)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__)) /* Ignore */;
__extension__ extern lldiv_t lldiv (long long int __numer,
long long int __denom)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__)) /* Ignore */;
/* Convert floating point numbers to strings. The returned values are
valid only until another call to the same function. */
/* Convert VALUE to a string with NDIGIT digits and return a pointer to
this. Set *DECPT with the position of the decimal character and *SIGN
with the sign of the number. */
extern char *ecvt (double __value, int __ndigit, int *__restrict __decpt,
int *__restrict __sign) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4))) /* Ignore */;
/* Convert VALUE to a string rounded to NDIGIT decimal digits. Set *DECPT
with the position of the decimal character and *SIGN with the sign of
the number. */
extern char *fcvt (double __value, int __ndigit, int *__restrict __decpt,
int *__restrict __sign) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4))) /* Ignore */;
/* If possible convert VALUE to a string with NDIGIT significant digits.
Otherwise use exponential representation. The resulting string will
be written to BUF. */
extern char *gcvt (double __value, int __ndigit, char *__buf)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3))) /* Ignore */;
/* Long double versions of above functions. */
extern char *qecvt (long double __value, int __ndigit,
int *__restrict __decpt, int *__restrict __sign)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4))) /* Ignore */;
extern char *qfcvt (long double __value, int __ndigit,
int *__restrict __decpt, int *__restrict __sign)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4))) /* Ignore */;
extern char *qgcvt (long double __value, int __ndigit, char *__buf)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3))) /* Ignore */;
/* Reentrant version of the functions above which provide their own
buffers. */
extern int ecvt_r (double __value, int __ndigit, int *__restrict __decpt,
int *__restrict __sign, char *__restrict __buf,
size_t __len) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4, 5)));
extern int fcvt_r (double __value, int __ndigit, int *__restrict __decpt,
int *__restrict __sign, char *__restrict __buf,
size_t __len) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4, 5)));
extern int qecvt_r (long double __value, int __ndigit,
int *__restrict __decpt, int *__restrict __sign,
char *__restrict __buf, size_t __len)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4, 5)));
extern int qfcvt_r (long double __value, int __ndigit,
int *__restrict __decpt, int *__restrict __sign,
char *__restrict __buf, size_t __len)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (3, 4, 5)));
/* Return the length of the multibyte character
in S, which is no longer than N. */
extern int mblen (const char *__s, size_t __n) __attribute__ ((__nothrow__ ));
/* Return the length of the given multibyte character,
putting its `wchar_t' representation in *PWC. */
extern int mbtowc (wchar_t *__restrict __pwc,
const char *__restrict __s, size_t __n) __attribute__ ((__nothrow__ ));
/* Put the multibyte character represented
by WCHAR in S, returning its length. */
extern int wctomb (char *__s, wchar_t __wchar) __attribute__ ((__nothrow__ ));
/* Convert a multibyte string to a wide char string. */
extern size_t mbstowcs (wchar_t *__restrict __pwcs,
const char *__restrict __s, size_t __n) __attribute__ ((__nothrow__ ));
/* Convert a wide char string to multibyte string. */
extern size_t wcstombs (char *__restrict __s,
const wchar_t *__restrict __pwcs, size_t __n)
__attribute__ ((__nothrow__ ));
/* Determine whether the string value of RESPONSE matches the affirmation
or negative response expression as specified by the LC_MESSAGES category
in the program's current locale. Returns 1 if affirmative, 0 if
negative, and -1 if not matching. */
extern int rpmatch (const char *__response) __attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1))) /* Ignore */;
/* Parse comma separated suboption from *OPTIONP and match against
strings in TOKENS. If found return index and set *VALUEP to
optional value introduced by an equal sign. If the suboption is
not part of TOKENS return in *VALUEP beginning of unknown
suboption. On exit *OPTIONP is set to the beginning of the next
token or at the terminating NUL character. */
extern int getsubopt (char **__restrict __optionp,
char *const *__restrict __tokens,
char **__restrict __valuep)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1, 2, 3))) /* Ignore */;
# 911 "/usr/include/stdlib.h" 3 4
/* X/Open pseudo terminal handling. */
# 947 "/usr/include/stdlib.h" 3 4
/* Put the 1 minute, 5 minute and 15 minute load averages into the first
NELEM elements of LOADAVG. Return the number written (never more than
three, but may be less than NELEM), or -1 if an error occurred. */
extern int getloadavg (double __loadavg[], int __nelem)
__attribute__ ((__nothrow__ )) __attribute__ ((__nonnull__ (1)));
# 1 "/usr/include/bits/stdlib-float.h" 1 3 4
/* Floating-point inline functions for stdlib.h.
Copyright (C) 2012-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
# 955 "/usr/include/stdlib.h" 2 3 4
/* Define some macros helping to catch buffer overflows. */
# 2 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/common/support.h" 2
# 1 "/usr/include/inttypes.h" 1 3 4
/* Copyright (C) 1997-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/*
* ISO C99: 7.8 Format conversion of integer types <inttypes.h>
*/
/* Get the type definitions. */
# 1 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/lnx64/tools/clang/bin/../lib/clang/3.1/include/stdint.h" 1 3 4
/*===---- stdint.h - Standard header for sized integer types --------------===*\
*
* Copyright (c) 2009 Chris Lattner
*
* 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.
*
\*===----------------------------------------------------------------------===*/
/* If we're hosted, fall back to the system's stdint.h, which might have
* additional definitions.
*/
# 1 "/usr/include/stdint.h" 1 3 4
/* Copyright (C) 1997-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/*
* ISO C99: 7.18 Integer types <stdint.h>
*/
# 1 "/usr/include/bits/wchar.h" 1 3 4
/* wchar_t type related definitions.
Copyright (C) 2000-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* The fallback definitions, for when __WCHAR_MAX__ or __WCHAR_MIN__
are not defined, give the right value and type as long as both int
and wchar_t are 32-bit types. Adding L'\0' to a constant value
ensures that the type is correct; it is necessary to use (L'\0' +
0) rather than just L'\0' so that the type in C++ is the promoted
version of wchar_t rather than the distinct wchar_t type itself.
Because wchar_t in preprocessor #if expressions is treated as
intmax_t or uintmax_t, the expression (L'\0' - 1) would have the
wrong value for WCHAR_MAX in such expressions and so cannot be used
to define __WCHAR_MAX in the unsigned case. */
# 27 "/usr/include/stdint.h" 2 3 4
# 1 "/usr/include/bits/wordsize.h" 1 3 4
/* Determine the wordsize from the preprocessor defines. */
# 28 "/usr/include/stdint.h" 2 3 4
/* Exact integral types. */
/* Signed. */
/* There is some amount of overlap with <sys/types.h> as known by inet code */
# 47 "/usr/include/stdint.h" 3 4
/* Unsigned. */
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;
typedef unsigned int uint32_t;
__extension__
typedef unsigned long long int uint64_t;
/* Small types. */
/* Signed. */
typedef signed char int_least8_t;
typedef short int int_least16_t;
typedef int int_least32_t;
__extension__
typedef long long int int_least64_t;
/* Unsigned. */
typedef unsigned char uint_least8_t;
typedef unsigned short int uint_least16_t;
typedef unsigned int uint_least32_t;
__extension__
typedef unsigned long long int uint_least64_t;
/* Fast types. */
/* Signed. */
typedef signed char int_fast8_t;
typedef int int_fast16_t;
typedef int int_fast32_t;
__extension__
typedef long long int int_fast64_t;
/* Unsigned. */
typedef unsigned char uint_fast8_t;
typedef unsigned int uint_fast16_t;
typedef unsigned int uint_fast32_t;
__extension__
typedef unsigned long long int uint_fast64_t;
/* Types for `void *' pointers. */
# 125 "/usr/include/stdint.h" 3 4
typedef int intptr_t;
typedef unsigned int uintptr_t;
/* Largest integral types. */
__extension__
typedef long long int intmax_t;
__extension__
typedef unsigned long long int uintmax_t;
# 152 "/usr/include/stdint.h" 3 4
/* Limits of integral types. */
/* Minimum of signed integral types. */
/* Maximum of signed integral types. */
/* Maximum of unsigned integral types. */
/* Minimum of signed integral types having a minimum size. */
/* Maximum of signed integral types having a minimum size. */
/* Maximum of unsigned integral types having a minimum size. */
/* Minimum of fast signed integral types having a minimum size. */
# 200 "/usr/include/stdint.h" 3 4
/* Maximum of fast signed integral types having a minimum size. */
# 211 "/usr/include/stdint.h" 3 4
/* Maximum of fast unsigned integral types having a minimum size. */
# 223 "/usr/include/stdint.h" 3 4
/* Values to test for integral types holding `void *' pointer. */
# 235 "/usr/include/stdint.h" 3 4
/* Minimum for largest signed integral type. */
/* Maximum for largest signed integral type. */
/* Maximum for largest unsigned integral type. */
/* Limits of other integer types. */
/* Limits of `ptrdiff_t' type. */
# 255 "/usr/include/stdint.h" 3 4
/* Limits of `sig_atomic_t'. */
/* Limit of `size_t' type. */
# 270 "/usr/include/stdint.h" 3 4
/* Limits of `wchar_t'. */
/* These constants might also be defined in <wchar.h>. */
/* Limits of `wint_t'. */
/* Signed. */
# 291 "/usr/include/stdint.h" 3 4
/* Unsigned. */
# 301 "/usr/include/stdint.h" 3 4
/* Maximal type. */
# 34 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/lnx64/tools/clang/bin/../lib/clang/3.1/include/stdint.h" 2 3 4
# 28 "/usr/include/inttypes.h" 2 3 4
/* Get a definition for wchar_t. But we must not define wchar_t itself. */
typedef int __gwchar_t;
# 51 "/usr/include/inttypes.h" 3 4
/* Macros for printing format specifiers. */
/* Decimal notation. */
# 85 "/usr/include/inttypes.h" 3 4
/* Octal notation. */
# 101 "/usr/include/inttypes.h" 3 4
/* Unsigned integers. */
# 117 "/usr/include/inttypes.h" 3 4
/* lowercase hexadecimal notation. */
# 133 "/usr/include/inttypes.h" 3 4
/* UPPERCASE hexadecimal notation. */
# 150 "/usr/include/inttypes.h" 3 4
/* Macros for printing `intmax_t' and `uintmax_t'. */
# 159 "/usr/include/inttypes.h" 3 4
/* Macros for printing `intptr_t' and `uintptr_t'. */
# 168 "/usr/include/inttypes.h" 3 4
/* Macros for scanning format specifiers. */
/* Signed decimal notation. */
# 186 "/usr/include/inttypes.h" 3 4
/* Signed decimal notation. */
# 202 "/usr/include/inttypes.h" 3 4
/* Unsigned decimal notation. */
# 218 "/usr/include/inttypes.h" 3 4
/* Octal notation. */
# 234 "/usr/include/inttypes.h" 3 4
/* Hexadecimal notation. */
# 251 "/usr/include/inttypes.h" 3 4
/* Macros for scanning `intmax_t' and `uintmax_t'. */
/* Macros for scaning `intptr_t' and `uintptr_t'. */
# 279 "/usr/include/inttypes.h" 3 4
/* We have to define the `uintmax_t' type using `lldiv_t'. */
typedef struct
{
__extension__ long long int quot; /* Quotient. */
__extension__ long long int rem; /* Remainder. */
} imaxdiv_t;
/* Compute absolute value of N. */
extern intmax_t imaxabs (intmax_t __n) __attribute__ ((__nothrow__ )) __attribute__ ((__const__));
/* Return the `imaxdiv_t' representation of the value of NUMER over DENOM. */
extern imaxdiv_t imaxdiv (intmax_t __numer, intmax_t __denom)
__attribute__ ((__nothrow__ )) __attribute__ ((__const__));
/* Like `strtol' but convert to `intmax_t'. */
extern intmax_t strtoimax (const char *__restrict __nptr,
char **__restrict __endptr, int __base) __attribute__ ((__nothrow__ ));
/* Like `strtoul' but convert to `uintmax_t'. */
extern uintmax_t strtoumax (const char *__restrict __nptr,
char ** __restrict __endptr, int __base) __attribute__ ((__nothrow__ ));
/* Like `wcstol' but convert to `intmax_t'. */
extern intmax_t wcstoimax (const __gwchar_t *__restrict __nptr,
__gwchar_t **__restrict __endptr, int __base)
__attribute__ ((__nothrow__ ));
/* Like `wcstoul' but convert to `uintmax_t'. */
extern uintmax_t wcstoumax (const __gwchar_t *__restrict __nptr,
__gwchar_t ** __restrict __endptr, int __base)
__attribute__ ((__nothrow__ ));
# 3 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/common/support.h" 2
///// File and section functions
char *readfile(int fd);
char *find_section_start(char *s, int n);
///// Array read functions
int parse_string(char *s, char *arr, int n); // n==-1 : %%-terminated
int parse_uint8_t_array(char *s, uint8_t *arr, int n);
int parse_uint16_t_array(char *s, uint16_t *arr, int n);
int parse_uint32_t_array(char *s, uint32_t *arr, int n);
int parse_uint64_t_array(char *s, uint64_t *arr, int n);
int parse_int8_t_array(char *s, int8_t *arr, int n);
int parse_int16_t_array(char *s, int16_t *arr, int n);
int parse_int32_t_array(char *s, int32_t *arr, int n);
int parse_int64_t_array(char *s, int64_t *arr, int n);
int parse_float_array(char *s, float *arr, int n);
int parse_double_array(char *s, double *arr, int n);
///// Array write functions
int write_string(int fd, char *arr, int n);
int write_uint8_t_array(int fd, uint8_t *arr, int n);
int write_uint16_t_array(int fd, uint16_t *arr, int n);
int write_uint32_t_array(int fd, uint32_t *arr, int n);
int write_uint64_t_array(int fd, uint64_t *arr, int n);
int write_int8_t_array(int fd, int8_t *arr, int n);
int write_int16_t_array(int fd, int16_t *arr, int n);
int write_int32_t_array(int fd, int32_t *arr, int n);
int write_int64_t_array(int fd, int64_t *arr, int n);
int write_float_array(int fd, float *arr, int n);
int write_double_array(int fd, double *arr, int n);
int write_section_header(int fd);
///// Per-benchmark files
void run_benchmark( void *vargs );
void input_to_data(int fd, void *vdata);
void data_to_input(int fd, void *vdata);
void output_to_data(int fd, void *vdata);
void data_to_output(int fd, void *vdata);
int check_data(void *vdata, void *vref);
extern int INPUT_SIZE;
///// TYPE macros
// Macro trick to automatically expand TYPE into the appropriate function
// (S)et (T)ype (A)nd (C)oncatenate
// Invoke like this:
// #define TYPE int32_t
// STAC(write_,TYPE,_array)(fd, array, n);
// where array is of type (TYPE *)
// This translates to:
// write_int32_t_array(fd, array, n);
/**** PRNG library. Available at https://github.com/rdadolf/prng. *****/
# 1 "/usr/include/stdio.h" 1 3 4
/* Define ISO C stdio on top of C++ iostreams.
Copyright (C) 1991-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/*
* ISO C99 Standard: 7.19 Input/output <stdio.h>
*/
# 33 "/usr/include/stdio.h" 3 4
# 1 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/lnx64/tools/clang/bin/../lib/clang/3.1/include/stddef.h" 1 3 4
/*===---- stddef.h - Basic type definitions --------------------------------===
*
* Copyright (c) 2008 Eli Friedman
*
* 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.
*
*===-----------------------------------------------------------------------===
*/
# 56 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/lnx64/tools/clang/bin/../lib/clang/3.1/include/stddef.h" 3 4
/* Some C libraries expect to see a wint_t here. Others (notably MinGW) will use
__WINT_TYPE__ directly; accommodate both by requiring __need_wint_t */
# 34 "/usr/include/stdio.h" 2 3 4
# 43 "/usr/include/stdio.h" 3 4
/* Define outside of namespace so the C++ is happy. */
struct _IO_FILE;
/* The opaque type of streams. This is the definition used elsewhere. */
typedef struct _IO_FILE FILE;
# 63 "/usr/include/stdio.h" 3 4
/* The opaque type of streams. This is the definition used elsewhere. */
typedef struct _IO_FILE __FILE;
# 74 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/libio.h" 1 3 4
/* Copyright (C) 1991-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Written by Per Bothner <[email protected]>.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>.
As a special exception, if you link the code in this file with
files compiled with a GNU compiler to produce an executable,
that does not cause the resulting executable to be covered by
the GNU Lesser General Public License. This exception does not
however invalidate any other reasons why the executable file
might be covered by the GNU Lesser General Public License.
This exception applies to code released by its copyright holders
in files containing the exception. */
# 1 "/usr/include/_G_config.h" 1 3 4
/* This file is needed by libio to define various configuration parameters.
These are always the same in the GNU C library. */
/* Define types for libio in terms of the standard internal type names. */
# 16 "/usr/include/_G_config.h" 3 4
# 1 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/lnx64/tools/clang/bin/../lib/clang/3.1/include/stddef.h" 1 3 4
/*===---- stddef.h - Basic type definitions --------------------------------===
*
* Copyright (c) 2008 Eli Friedman
*
* 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.
*
*===-----------------------------------------------------------------------===
*/
# 56 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/lnx64/tools/clang/bin/../lib/clang/3.1/include/stddef.h" 3 4
/* Some C libraries expect to see a wint_t here. Others (notably MinGW) will use
__WINT_TYPE__ directly; accommodate both by requiring __need_wint_t */
# 16 "/usr/include/_G_config.h" 2 3 4
# 1 "/usr/include/wchar.h" 1 3 4
/* Copyright (C) 1995-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/*
* ISO C99 Standard: 7.24
* Extended multibyte and wide character utilities <wchar.h>
*/
# 81 "/usr/include/wchar.h" 3 4
/* Conversion state information. */
typedef struct
{
int __count;
union
{
unsigned int __wch;
char __wchb[4];
} __value; /* Value so far. */
} __mbstate_t;
/* The rest of the file is only used if used if __need_mbstate_t is not
defined. */
# 899 "/usr/include/wchar.h" 3 4
/* Undefine all __need_* constants in case we are included to get those
constants but the whole file was already read. */
# 21 "/usr/include/_G_config.h" 2 3 4
typedef struct
{
__off_t __pos;
__mbstate_t __state;
} _G_fpos_t;
typedef struct
{
__off64_t __pos;
__mbstate_t __state;
} _G_fpos64_t;
# 45 "/usr/include/_G_config.h" 3 4
/* These library features are always available in the GNU C library. */
/* This is defined by <bits/stat.h> if `st_blksize' exists. */
# 32 "/usr/include/libio.h" 2 3 4
/* ALL of these should be defined in _G_config.h */
# 47 "/usr/include/libio.h" 3 4
/* This define avoids name pollution if we're using GNU stdarg.h */
# 1 "/mnt/icgridio2/safe/SDSoC/SDx/2017.1/Vivado_HLS/lnx64/tools/clang/bin/../lib/clang/3.1/include/stdarg.h" 1 3 4
/*===---- stdarg.h - Variable argument handling ----------------------------===
*
* Copyright (c) 2008 Eli Friedman
*
* 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.
*
*===-----------------------------------------------------------------------===
*/
typedef __builtin_va_list va_list;
/* GCC always defines __va_copy, but does not define va_copy unless in c99 mode
* or -ansi is not specified, since it was not part of C90.
*/
/* Hack required to make standard headers work, at least on Ubuntu */
typedef __builtin_va_list __gnuc_va_list;
# 50 "/usr/include/libio.h" 2 3 4
# 86 "/usr/include/libio.h" 3 4
/* Magic numbers and bits for the _flags field.
The magic numbers use the high-order bits of _flags;
the remaining bits are available for variable flags.
Note: The magic numbers must all be negative if stdio
emulation is desired. */
# 124 "/usr/include/libio.h" 3 4
/* These are "formatting flags" matching the iostream fmtflags enum values. */
# 144 "/usr/include/libio.h" 3 4
struct _IO_jump_t; struct _IO_FILE;
/* Handle lock. */
typedef void _IO_lock_t;
/* A streammarker remembers a position in a buffer. */
struct _IO_marker {
struct _IO_marker *_next;
struct _IO_FILE *_sbuf;
/* If _pos >= 0
it points to _buf->Gbase()+_pos. FIXME comment */
/* if _pos < 0, it points to _buf->eBptr()+_pos. FIXME comment */
int _pos;
# 177 "/usr/include/libio.h" 3 4
};
/* This is the structure from the libstdc++ codecvt class. */
enum __codecvt_result
{
__codecvt_ok,
__codecvt_partial,
__codecvt_error,
__codecvt_noconv
};
# 245 "/usr/include/libio.h" 3 4
struct _IO_FILE {
int _flags; /* High-order word is _IO_MAGIC; rest is flags. */
/* The following pointers correspond to the C++ streambuf protocol. */
/* Note: Tk uses the _IO_read_ptr and _IO_read_end fields directly. */
char* _IO_read_ptr; /* Current read pointer */
char* _IO_read_end; /* End of get area. */
char* _IO_read_base; /* Start of putback+get area. */
char* _IO_write_base; /* Start of put area. */
char* _IO_write_ptr; /* Current put pointer. */
char* _IO_write_end; /* End of put area. */
char* _IO_buf_base; /* Start of reserve area. */
char* _IO_buf_end; /* End of reserve area. */
/* The following fields are used to support backing up and undo. */
char *_IO_save_base; /* Pointer to start of non-current get area. */
char *_IO_backup_base; /* Pointer to first valid character of backup area */
char *_IO_save_end; /* Pointer to end of non-current get area. */
struct _IO_marker *_markers;
struct _IO_FILE *_chain;
int _fileno;
int _flags2;
__off_t _old_offset; /* This used to be _offset but it's too small. */
/* 1+column number of pbase(); 0 is unknown. */
unsigned short _cur_column;
signed char _vtable_offset;
char _shortbuf[1];
/* char* _save_gptr; char* _save_egptr; */
_IO_lock_t *_lock;
# 293 "/usr/include/libio.h" 3 4
__off64_t _offset;
# 302 "/usr/include/libio.h" 3 4
void *__pad1;
void *__pad2;
void *__pad3;
void *__pad4;
size_t __pad5;
int _mode;
/* Make sure we don't get into trouble again. */
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_;
# 334 "/usr/include/libio.h" 3 4
/* Functions to do I/O and file management for a stream. */
/* Read NBYTES bytes from COOKIE into a buffer pointed to by BUF.
Return number of bytes read. */
typedef __ssize_t __io_read_fn (void *__cookie, char *__buf, size_t __nbytes);
/* Write N bytes pointed to by BUF to COOKIE. Write all N bytes
unless there is an error. Return number of bytes written. If
there is an error, return 0 and do not write anything. If the file
has been opened for append (__mode.__append set), then set the file
pointer to the end of the file and then do the write; if not, just
write at the current file pointer. */
typedef __ssize_t __io_write_fn (void *__cookie, const char *__buf,
size_t __n);
/* Move COOKIE's file position to *POS bytes from the
beginning of the file (if W is SEEK_SET),
the current position (if W is SEEK_CUR),
or the end of the file (if W is SEEK_END).
Set *POS to the new file position.
Returns zero if successful, nonzero if not. */
typedef int __io_seek_fn (void *__cookie, __off64_t *__pos, int __w);
/* Close COOKIE. */
typedef int __io_close_fn (void *__cookie);
# 390 "/usr/include/libio.h" 3 4
extern int __underflow (_IO_FILE *);
extern int __uflow (_IO_FILE *);
extern int __overflow (_IO_FILE *, int);
# 434 "/usr/include/libio.h" 3 4
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__ ));
extern int _IO_ferror (_IO_FILE *__fp) __attribute__ ((__nothrow__ ));
extern int _IO_peekc_locked (_IO_FILE *__fp);
/* This one is for Emacs. */
extern void _IO_flockfile (_IO_FILE *) __attribute__ ((__nothrow__ ));
extern void _IO_funlockfile (_IO_FILE *) __attribute__ ((__nothrow__ ));
extern int _IO_ftrylockfile (_IO_FILE *) __attribute__ ((__nothrow__ ));
# 464 "/usr/include/libio.h" 3 4
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__ ));
# 75 "/usr/include/stdio.h" 2 3 4
typedef __gnuc_va_list va_list;
# 107 "/usr/include/stdio.h" 3 4
/* The type of the second argument to `fgetpos' and `fsetpos'. */
typedef _G_fpos_t fpos_t;
# 119 "/usr/include/stdio.h" 3 4
/* The possibilities for the third argument to `setvbuf'. */
/* Default buffer size. */
/* End of file character.
Some things throughout the library rely on this being -1. */
/* The possibilities for the third argument to `fseek'.
These values should not be changed. */
# 150 "/usr/include/stdio.h" 3 4
/* Default path prefix for `tempnam' and `tmpnam'. */
/* Get the values:
L_tmpnam How long an array of chars must be to be passed to `tmpnam'.
TMP_MAX The minimum number of unique filenames generated by tmpnam
(and tempnam when it uses tmpnam's name space),
or tempnam (the two are separate).
L_ctermid How long an array to pass to `ctermid'.
L_cuserid How long an array to pass to `cuserid'.
FOPEN_MAX Minimum number of files that can be open at once.
FILENAME_MAX Maximum length of a filename. */
# 1 "/usr/include/bits/stdio_lim.h" 1 3 4
/* Copyright (C) 1994-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
# 165 "/usr/include/stdio.h" 2 3 4
/* Standard streams. */
extern struct _IO_FILE *stdin; /* Standard input stream. */
extern struct _IO_FILE *stdout; /* Standard output stream. */
extern struct _IO_FILE *stderr; /* Standard error output stream. */
/* C89/C99 say they're macros. Make them happy. */
/* Remove file FILENAME. */
extern int remove (const char *__filename) __attribute__ ((__nothrow__ ));
/* Rename file OLD to NEW. */
extern int rename (const char *__old, const char *__new) __attribute__ ((__nothrow__ ));
/* Rename file OLD relative to OLDFD to NEW relative to NEWFD. */
extern int renameat (int __oldfd, const char *__old, int __newfd,
const char *__new) __attribute__ ((__nothrow__ ));
/* Create a temporary file and open it read/write.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern FILE *tmpfile (void) /* Ignore */;
# 208 "/usr/include/stdio.h" 3 4
/* Generate a temporary filename. */
extern char *tmpnam (char *__s) __attribute__ ((__nothrow__ )) /* Ignore */;
/* This is the reentrant variant of `tmpnam'. The only difference is
that it does not allow S to be NULL. */
extern char *tmpnam_r (char *__s) __attribute__ ((__nothrow__ )) /* Ignore */;
/* Generate a unique temporary filename using up to five characters of PFX
if it is not NULL. The directory to put this file in is searched for
as follows: First the environment variable "TMPDIR" is checked.
If it contains the name of a writable directory, that directory is used.
If not and if DIR is not NULL, that value is checked. If that fails,
P_tmpdir is tried and finally "/tmp". The storage for the filename
is allocated by `malloc'. */
extern char *tempnam (const char *__dir, const char *__pfx)
__attribute__ ((__nothrow__ )) __attribute__ ((__malloc__)) /* Ignore */;
/* Close STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int fclose (FILE *__stream);
/* Flush STREAM, or all streams if STREAM is NULL.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int fflush (FILE *__stream);
/* Faster versions when locking is not required.
This function is not part of POSIX and therefore no official
cancellation point. But due to similarity with an POSIX interface
or due to the implementation it is a cancellation point and
therefore not marked with __THROW. */
extern int fflush_unlocked (FILE *__stream);
# 268 "/usr/include/stdio.h" 3 4
/* Open a file and create a new stream for it.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern FILE *fopen (const char *__restrict __filename,
const char *__restrict __modes) /* Ignore */;
/* Open a file, replacing an existing stream with it.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern FILE *freopen (const char *__restrict __filename,
const char *__restrict __modes,
FILE *__restrict __stream) /* Ignore */;
# 305 "/usr/include/stdio.h" 3 4
/* Create a new stream that refers to an existing system file descriptor. */
extern FILE *fdopen (int __fd, const char *__modes) __attribute__ ((__nothrow__ )) /* Ignore */;
# 318 "/usr/include/stdio.h" 3 4
/* Create a new stream that refers to a memory buffer. */
extern FILE *fmemopen (void *__s, size_t __len, const char *__modes)
__attribute__ ((__nothrow__ )) /* Ignore */;
/* Open a stream that writes into a malloc'd buffer that is expanded as
necessary. *BUFLOC and *SIZELOC are updated with the buffer's location
and the number of characters written on fflush or fclose. */
extern FILE *open_memstream (char **__bufloc, size_t *__sizeloc) __attribute__ ((__nothrow__ )) /* Ignore */;
/* If BUF is NULL, make STREAM unbuffered.
Else make it use buffer BUF, of size BUFSIZ. */
extern void setbuf (FILE *__restrict __stream, char *__restrict __buf) __attribute__ ((__nothrow__ ));
/* Make STREAM use buffering mode MODE.
If BUF is not NULL, use N bytes of it for buffering;
else allocate an internal buffer N bytes long. */
extern int setvbuf (FILE *__restrict __stream, char *__restrict __buf,
int __modes, size_t __n) __attribute__ ((__nothrow__ ));
/* If BUF is NULL, make STREAM unbuffered.
Else make it use SIZE bytes of BUF for buffering. */
extern void setbuffer (FILE *__restrict __stream, char *__restrict __buf,
size_t __size) __attribute__ ((__nothrow__ ));
/* Make STREAM line-buffered. */
extern void setlinebuf (FILE *__stream) __attribute__ ((__nothrow__ ));
/* Write formatted output to STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int fprintf (FILE *__restrict __stream,
const char *__restrict __format, ...);
/* Write formatted output to stdout.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int printf (const char *__restrict __format, ...);
/* Write formatted output to S. */
extern int sprintf (char *__restrict __s,
const char *__restrict __format, ...) __attribute__ ((__nothrow__));
/* Write formatted output to S from argument list ARG.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int vfprintf (FILE *__restrict __s, const char *__restrict __format,
__gnuc_va_list __arg);
/* Write formatted output to stdout from argument list ARG.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int vprintf (const char *__restrict __format, __gnuc_va_list __arg);
/* Write formatted output to S from argument list ARG. */
extern int vsprintf (char *__restrict __s, const char *__restrict __format,
__gnuc_va_list __arg) __attribute__ ((__nothrow__));
/* Maximum chars of output to write in MAXLEN. */
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)));
# 411 "/usr/include/stdio.h" 3 4
/* Write formatted output to a file descriptor. */
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)));
/* Read formatted input from STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int fscanf (FILE *__restrict __stream,
const char *__restrict __format, ...) /* Ignore */;
/* Read formatted input from stdin.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int scanf (const char *__restrict __format, ...) /* Ignore */;
/* Read formatted input from S. */
extern int sscanf (const char *__restrict __s,
const char *__restrict __format, ...) __attribute__ ((__nothrow__ ));
/* For strict ISO C99 or POSIX compliance disallow %as, %aS and %a[
GNU extension which conflicts with valid %a followed by letter
s, S or [. */
extern int fscanf (FILE *__restrict __stream, const char *__restrict __format, ...) __asm__ ("" "__isoc99_fscanf") /* Ignore */;
extern int scanf (const char *__restrict __format, ...) __asm__ ("" "__isoc99_scanf") /* Ignore */;
extern int sscanf (const char *__restrict __s, const char *__restrict __format, ...) __asm__ ("" "__isoc99_sscanf") __attribute__ ((__nothrow__ ));
# 467 "/usr/include/stdio.h" 3 4
/* Read formatted input from S into argument list ARG.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int vfscanf (FILE *__restrict __s, const char *__restrict __format,
__gnuc_va_list __arg)
__attribute__ ((__format__ (__scanf__, 2, 0))) /* Ignore */;
/* Read formatted input from stdin into argument list ARG.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int vscanf (const char *__restrict __format, __gnuc_va_list __arg)
__attribute__ ((__format__ (__scanf__, 1, 0))) /* Ignore */;
/* Read formatted input from S into argument list ARG. */
extern int vsscanf (const char *__restrict __s,
const char *__restrict __format, __gnuc_va_list __arg)
__attribute__ ((__nothrow__ )) __attribute__ ((__format__ (__scanf__, 2, 0)));
/* For strict ISO C99 or POSIX compliance disallow %as, %aS and %a[
GNU extension which conflicts with valid %a followed by letter
s, S or [. */
extern int vfscanf (FILE *__restrict __s, const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vfscanf")
__attribute__ ((__format__ (__scanf__, 2, 0))) /* Ignore */;
extern int vscanf (const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vscanf")
__attribute__ ((__format__ (__scanf__, 1, 0))) /* Ignore */;
extern int vsscanf (const char *__restrict __s, const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vsscanf") __attribute__ ((__nothrow__ ))
__attribute__ ((__format__ (__scanf__, 2, 0)));
# 527 "/usr/include/stdio.h" 3 4
/* Read a character from STREAM.
These functions are possible cancellation points and therefore not
marked with __THROW. */
extern int fgetc (FILE *__stream);
extern int getc (FILE *__stream);
/* Read a character from stdin.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int getchar (void);
/* The C standard explicitly says this is a macro, so we always do the
optimization for it. */
/* These are defined in POSIX.1:1996.
These functions are possible cancellation points and therefore not
marked with __THROW. */
extern int getc_unlocked (FILE *__stream);
extern int getchar_unlocked (void);
/* Faster version when locking is not necessary.
This function is not part of POSIX and therefore no official
cancellation point. But due to similarity with an POSIX interface
or due to the implementation it is a cancellation point and
therefore not marked with __THROW. */
extern int fgetc_unlocked (FILE *__stream);
/* Write a character to STREAM.
These functions are possible cancellation points and therefore not
marked with __THROW.
These functions is a possible cancellation point and therefore not
marked with __THROW. */
extern int fputc (int __c, FILE *__stream);
extern int putc (int __c, FILE *__stream);
/* Write a character to stdout.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int putchar (int __c);
/* The C standard explicitly says this can be a macro,
so we always do the optimization for it. */
/* Faster version when locking is not necessary.
This function is not part of POSIX and therefore no official
cancellation point. But due to similarity with an POSIX interface
or due to the implementation it is a cancellation point and
therefore not marked with __THROW. */
extern int fputc_unlocked (int __c, FILE *__stream);
/* These are defined in POSIX.1:1996.
These functions are possible cancellation points and therefore not
marked with __THROW. */
extern int putc_unlocked (int __c, FILE *__stream);
extern int putchar_unlocked (int __c);
/* Get a word (int) from STREAM. */
extern int getw (FILE *__stream);
/* Write a word (int) to STREAM. */
extern int putw (int __w, FILE *__stream);
/* Get a newline-terminated string of finite length from STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern char *fgets (char *__restrict __s, int __n, FILE *__restrict __stream)
/* Ignore */;
/* Get a newline-terminated string from stdin, removing the newline.
DO NOT USE THIS FUNCTION!! There is no limit on how much it will read.
The function has been officially removed in ISO C11. This opportunity
is used to also remove it from the GNU feature list. It is now only
available when explicitly using an old ISO C, Unix, or POSIX standard.
GCC defines _GNU_SOURCE when building C++ code and the function is still
in C++11, so it is also available for C++.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern char *gets (char *__s) /* Ignore */ __attribute__ ((__deprecated__));
# 655 "/usr/include/stdio.h" 3 4
/* Read up to (and including) a DELIMITER from STREAM into *LINEPTR
(and null-terminate it). *LINEPTR is a pointer returned from malloc (or
NULL), pointing to *N characters of space. It is realloc'd as
necessary. Returns the number of characters read (not including the
null terminator), or -1 on error or EOF.
These functions are not part of POSIX and therefore no official
cancellation point. But due to similarity with an POSIX interface
or due to the implementation they are cancellation points and
therefore not marked with __THROW. */
extern __ssize_t __getdelim (char **__restrict __lineptr,
size_t *__restrict __n, int __delimiter,
FILE *__restrict __stream) /* Ignore */;
extern __ssize_t getdelim (char **__restrict __lineptr,
size_t *__restrict __n, int __delimiter,
FILE *__restrict __stream) /* Ignore */;
/* Like `getdelim', but reads up to a newline.
This function is not part of POSIX and therefore no official
cancellation point. But due to similarity with an POSIX interface
or due to the implementation it is a cancellation point and
therefore not marked with __THROW. */
extern __ssize_t getline (char **__restrict __lineptr,
size_t *__restrict __n,
FILE *__restrict __stream) /* Ignore */;
/* Write a string to STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int fputs (const char *__restrict __s, FILE *__restrict __stream);
/* Write a string, followed by a newline, to stdout.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int puts (const char *__s);
/* Push a character back onto the input buffer of STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int ungetc (int __c, FILE *__stream);
/* Read chunks of generic data from STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern size_t fread (void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream) /* Ignore */;
/* Write chunks of generic data to STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern size_t fwrite (const void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __s);
# 731 "/usr/include/stdio.h" 3 4
/* Faster versions when locking is not necessary.
These functions are not part of POSIX and therefore no official
cancellation point. But due to similarity with an POSIX interface
or due to the implementation they are cancellation points and
therefore not marked with __THROW. */
extern size_t fread_unlocked (void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream) /* Ignore */;
extern size_t fwrite_unlocked (const void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream);
/* Seek to a certain position on STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int fseek (FILE *__stream, long int __off, int __whence);
/* Return the current position of STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern long int ftell (FILE *__stream) /* Ignore */;
/* Rewind to the beginning of STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern void rewind (FILE *__stream);
/* The Single Unix Specification, Version 2, specifies an alternative,
more adequate interface for the two functions above which deal with
file offset. `long int' is not the right type. These definitions
are originally defined in the Large File Support API. */
/* Seek to a certain position on STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
/* Return the current position of STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern __off_t ftello (FILE *__stream) /* Ignore */;
# 794 "/usr/include/stdio.h" 3 4
/* Get STREAM's position.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int fgetpos (FILE *__restrict __stream, fpos_t *__restrict __pos);
/* Set STREAM's position.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int fsetpos (FILE *__stream, const fpos_t *__pos);
# 825 "/usr/include/stdio.h" 3 4
/* Clear the error and EOF indicators for STREAM. */
extern void clearerr (FILE *__stream) __attribute__ ((__nothrow__ ));
/* Return the EOF indicator for STREAM. */
extern int feof (FILE *__stream) __attribute__ ((__nothrow__ )) /* Ignore */;
/* Return the error indicator for STREAM. */
extern int ferror (FILE *__stream) __attribute__ ((__nothrow__ )) /* Ignore */;
/* Faster versions when locking is not required. */
extern void clearerr_unlocked (FILE *__stream) __attribute__ ((__nothrow__ ));
extern int feof_unlocked (FILE *__stream) __attribute__ ((__nothrow__ )) /* Ignore */;
extern int ferror_unlocked (FILE *__stream) __attribute__ ((__nothrow__ )) /* Ignore */;
/* Print a message describing the meaning of the value of errno.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern void perror (const char *__s);
/* Provide the declarations for `sys_errlist' and `sys_nerr' if they
are available on this system. Even if available, these variables
should not be used directly. The `strerror' function provides
all the necessary functionality. */
# 1 "/usr/include/bits/sys_errlist.h" 1 3 4
/* Declare sys_errlist and sys_nerr, or don't. Compatibility (do) version.
Copyright (C) 2002-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* sys_errlist and sys_nerr are deprecated. Use strerror instead. */
extern int sys_nerr;
extern const char *const sys_errlist[];
# 854 "/usr/include/stdio.h" 2 3 4
/* Return the system file descriptor for STREAM. */
extern int fileno (FILE *__stream) __attribute__ ((__nothrow__ )) /* Ignore */;
/* Faster version when locking is not required. */
extern int fileno_unlocked (FILE *__stream) __attribute__ ((__nothrow__ )) /* Ignore */;
/* Create a new stream connected to a pipe running the given command.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern FILE *popen (const char *__command, const char *__modes) /* Ignore */;
/* Close a stream opened by popen and return the status of its child.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int pclose (FILE *__stream);
/* Return the name of the controlling terminal. */
extern char *ctermid (char *__s) __attribute__ ((__nothrow__ ));
# 909 "/usr/include/stdio.h" 3 4
/* These are defined in POSIX.1:1996. */
/* Acquire ownership of STREAM. */
extern void flockfile (FILE *__stream) __attribute__ ((__nothrow__ ));
/* Try to acquire ownership of STREAM but do not block if it is not
possible. */
extern int ftrylockfile (FILE *__stream) __attribute__ ((__nothrow__ )) /* Ignore */;
/* Relinquish the ownership granted for STREAM. */
extern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__ ));
# 930 "/usr/include/stdio.h" 3 4
/* If we are compiling with optimizing read this file. It contains
several optimizing inline functions and macros. */
# 66 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/common/support.h" 2
// 10x is a heuristic, it just needs to be large enough to remove correlation
struct prng_rand_t {
uint64_t s[((1)<<6)]; // Lags
uint_fast16_t i; // Location of the current lag
uint_fast16_t c; // Exhaustion count
};
static inline uint64_t prng_rand(struct prng_rand_t *state) {
uint_fast16_t i;
uint_fast16_t r, new_rands=0;
if( !state->c ) { // Randomness exhausted, run forward to refill
new_rands += (((55)*10)-(55))+1;
state->c = (55)-1;
} else {
new_rands = 1;
state->c--;
}
for( r=0; r<new_rands; r++ ) {
i = state->i;
state->s[i&(((1)<<6)-1)] = state->s[(i+((1)<<6)-(24))&(((1)<<6)-1)]
+ state->s[(i+((1)<<6)-(55))&(((1)<<6)-1)];
state->i++;
}
return state->s[i&(((1)<<6)-1)];
}
static inline void prng_srand(uint64_t seed, struct prng_rand_t *state) {
uint_fast16_t i;
// Naive seed
state->c = (55);
state->i = 0;
state->s[0] = seed;
for(i=1; i<((1)<<6); i++) {
// Arbitrary magic, mostly to eliminate the effect of low-value seeds.
// Probably could be better, but the run-up obviates any real need to.
state->s[i] = i*(2147483647ULL) + seed;
}
// Run forward 10,000 numbers
for(i=0; i<10000; i++) {
prng_rand(state);
}
}
// Clean up our macros
// PRNG_RAND_MAX is exported
# 6 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.h" 2
typedef struct {
uint8_t key[32];
uint8_t enckey[32];
uint8_t deckey[32];
} aes256_context;
void encrypt(uint8_t ctx_key[32], uint8_t ctx_enckey[32],
uint8_t ctx_deckey[32], uint8_t k[32], uint8_t buf[16]);
////////////////////////////////////////////////////////////////////////////////
// Test harness interface code.
struct bench_args_t {
aes256_context ctx;
uint8_t k[32];
uint8_t buf[16];
};
# 6 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.c" 2
# 66 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.c"
const unsigned pipeline_ii_sub = 11;
const unsigned pipeline_ii_addkey = 8;
const unsigned pipeline_ii_cpkey = 6;
const unsigned pipeline_ii_mix = 1;
const unsigned pipeline_ii_exp1 = 1;
const unsigned pipeline_ii_exp2 = 2;
const unsigned pipeline_ii_ecb1 = 16;
const unsigned pipeline_ii_ecb2 = 6;
const unsigned pipeline_ii_ecb3 = 12;
const unsigned unroll_factor_sub = 14;
const unsigned unroll_factor_addkey = 9;
const unsigned unroll_factor_cpkey = 4;
const unsigned unroll_factor_mix = 4;
const unsigned unroll_factor_exp1 = 2;
const unsigned unroll_factor_exp2 = 1;
const unsigned unroll_factor_ecb1 = 32;
const unsigned unroll_factor_ecb2 = 4;
const unsigned unroll_factor_ecb3 = 7;
const uint8_t sbox[256] = {
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,
0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc,
0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a,
0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,
0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17,
0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88,
0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9,
0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6,
0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94,
0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68,
0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
};
# 171 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.c"
/* -------------------------------------------------------------------------- */
uint8_t rj_xtime(uint8_t x)
{
return (x & 0x80) ? ((x << 1) ^ 0x1b) : (x << 1);
} /* rj_xtime */
/* -------------------------------------------------------------------------- */
void aes_subBytes(uint8_t *buf)
{
register uint8_t i = 16;
sub : while (i--)
{
_ssdm_Unroll(1, 0, unroll_factor_sub, "");
buf[i] = sbox[(buf[i])];
}
} /* aes_subBytes */
/* -------------------------------------------------------------------------- */
void aes_addRoundKey(uint8_t *buf, uint8_t *key)
{
register uint8_t i = 16;
addkey : while (i--)
{
_ssdm_Unroll(1, 0, unroll_factor_addkey, "");
buf[i] ^= key[i];
}
} /* aes_addRoundKey */
/* -------------------------------------------------------------------------- */
void aes_addRoundKey_cpy(uint8_t *buf, uint8_t *key, uint8_t *cpk)
{
register uint8_t i = 16;
cpkey : while (i--)
{
_ssdm_Unroll(1, 0, unroll_factor_cpkey, "");
buf[i] ^= (cpk[i] = key[i]), cpk[16+i] = key[16 + i];
}
} /* aes_addRoundKey_cpy */
/* -------------------------------------------------------------------------- */
void aes_shiftRows(uint8_t *buf)
{
register uint8_t i, j; /* to make it potentially parallelable :) */
i = buf[1]; buf[1] = buf[5]; buf[5] = buf[9]; buf[9] = buf[13]; buf[13] = i;
i = buf[10]; buf[10] = buf[2]; buf[2] = i;
j = buf[3]; buf[3] = buf[15]; buf[15] = buf[11]; buf[11] = buf[7]; buf[7] = j;
j = buf[14]; buf[14] = buf[6]; buf[6] = j;
} /* aes_shiftRows */
/* -------------------------------------------------------------------------- */
void aes_mixColumns(uint8_t *buf)
{
register uint8_t i, a, b, c, d, e;
mix : for (i = 0; i < 16; i += 4)
{
_ssdm_op_SpecPipeline(pipeline_ii_mix, 1, 1, 0, "");
a = buf[i]; b = buf[i + 1]; c = buf[i + 2]; d = buf[i + 3];
e = a ^ b ^ c ^ d;
buf[i] ^= e ^ rj_xtime(a^b); buf[i+1] ^= e ^ rj_xtime(b^c);
buf[i+2] ^= e ^ rj_xtime(c^d); buf[i+3] ^= e ^ rj_xtime(d^a);
}
} /* aes_mixColumns */
/* -------------------------------------------------------------------------- */
void aes_expandEncKey(uint8_t *k, uint8_t *rc)
{
register uint8_t i;
k[0] ^= sbox[(k[29])] ^ (*rc);
k[1] ^= sbox[(k[30])];
k[2] ^= sbox[(k[31])];
k[3] ^= sbox[(k[28])];
*rc = (((*rc)<<1) ^ ((((*rc)>>7) & 1) * 0x1b));
exp1 : for(i = 4; i < 16; i += 4)
{
_ssdm_op_SpecPipeline(pipeline_ii_exp1, 1, 1, 0, "");
k[i] ^= k[i-4], k[i+1] ^= k[i-3],
k[i+2] ^= k[i-2], k[i+3] ^= k[i-1];
}
k[16] ^= sbox[(k[12])];
k[17] ^= sbox[(k[13])];
k[18] ^= sbox[(k[14])];
k[19] ^= sbox[(k[15])];
exp2 : for(i = 20; i < 32; i += 4)
{
_ssdm_op_SpecPipeline(pipeline_ii_exp2, 1, 1, 0, "");
k[i] ^= k[i-4], k[i+1] ^= k[i-3],
k[i+2] ^= k[i-2], k[i+3] ^= k[i-1];
}
} /* aes_expandEncKey */
/* -------------------------------------------------------------------------- */
#pragma SDS data zero_copy(ctx_key)
#pragma SDS data zero_copy(ctx_enckey)
#pragma SDS data zero_copy(ctx_deckey)
#pragma SDS data zero_copy(buf)
void encrypt(uint8_t ctx_key[32], uint8_t ctx_enckey[32],
uint8_t ctx_deckey[32], uint8_t k[32], uint8_t buf[16])
{_ssdm_SpecArrayDimSize(ctx_enckey,32);_ssdm_SpecArrayDimSize(buf,16);_ssdm_SpecArrayDimSize(ctx_key,32);_ssdm_SpecArrayDimSize(k,32);_ssdm_SpecArrayDimSize(ctx_deckey,32);
_ssdm_op_SpecLatency(1, 65535, "");
# 303 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.c"
_ssdm_op_SpecResource(k, "", "RAM_1P", "", -1, "", "", "", "", "");
# 303 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.c"
_ssdm_op_SpecInterface(k, "bram", 0, 0, "", 0, 0, "", "", "", 0, 0, 0, 0, "", "");
# 303 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.c"
_ssdm_op_SpecInterface(ctx_deckey, "m_axi", 0, 0, "", 0, 0, "ctx_deckey", "direct", "", 16, 16, 16, 16, "", "");
# 303 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.c"
_ssdm_op_SpecInterface(ctx_enckey, "m_axi", 0, 0, "", 0, 0, "ctx_enckey", "direct", "", 16, 16, 16, 16, "", "");
# 303 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.c"
_ssdm_op_SpecInterface(ctx_key, "m_axi", 0, 0, "", 0, 0, "ctx_key", "direct", "", 16, 16, 16, 16, "", "");
# 303 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.c"
_ssdm_op_SpecInterface(buf, "m_axi", 0, 0, "", 0, 0, "buf", "direct", "", 16, 16, 16, 16, "", "");
# 303 "/mnt/icgridio2/safe/giesen/HLS_tuner/1/TestApps/MachSuite/aes/Sources/aes.c"
//INIT
uint8_t rcon = 1;
uint8_t i;
ecb1 : for (i = 0; i < 32; i++){
_ssdm_Unroll(1, 0, unroll_factor_ecb1, "");
ctx_enckey[i] = ctx_deckey[i] = k[i];
}
ecb2 : for (i = 8;--i;){
_ssdm_op_SpecPipeline(pipeline_ii_ecb2, 1, 1, 0, "");
aes_expandEncKey(ctx_deckey, &rcon);
}
//DEC
aes_addRoundKey_cpy(buf, ctx_enckey, ctx_key);
ecb3 : for(i = 1, rcon = 1; i < 14; ++i)
{
_ssdm_Unroll(1, 0, unroll_factor_ecb3, "");
aes_subBytes(buf);
aes_shiftRows(buf);
aes_mixColumns(buf);
if( i & 1 ) aes_addRoundKey( buf, ctx_key + 16);
else aes_expandEncKey(ctx_key, &rcon), aes_addRoundKey(buf, ctx_key);
}
aes_subBytes(buf);
aes_shiftRows(buf);
aes_expandEncKey(ctx_key, &rcon);
aes_addRoundKey(buf, ctx_key);
} /* aes256_encrypt */
|
the_stack_data/51193.c | #include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;
};
typedef struct node Node;
int main(int argc, char* argv[])
{
Node * first = (Node*) malloc (sizeof(Node));
Node * second = (Node*) malloc (sizeof(Node));
Node * third = (Node*) malloc (sizeof(Node));
Node * fourth = (Node*) malloc (sizeof(Node));
first->data = 12;
first->next = second;
second->data = 13;
second->next = third;
third->data = 14;
third->next = fourth;
fourth->data = 15;
fourth->next = NULL
;
Node* node1 = first;
while(node1!=NULL){
printf("%d\n",node1->data);
node1 = node1->next;
}
free(fourth);
free(third);
free(second);
free(first);
return 0;
}
|
the_stack_data/170452676.c | void memstore(void *dest,void *src,int sz)
{
my_memcpy(dest,src,sz);
}
void caram()
{
int j[4],k[4];
while(1) {
j[0]=1;
my_memcpy(&k[0],&j[0],4*sizeof(int));
memstore(&j[0],&k[0],4*sizeof(int));
}
}
|
the_stack_data/9094.c | #include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAX_BIT 16 /* required for accommodating precision 4 decimal */
#define ERROR_FLOAT -1.0
void process_file(FILE *);
float get_number(FILE *);
char *bin_enc(float);
char *spacer(char *);
int debug;
int count;
char *prog;
int main(int argc, char *argv[])
{
prog = argv[0];
debug = getenv("DEBUG")? 1: 0;
if(argc == 1) {
process_file(stdin);
} else {
FILE *fp;
while(1) {
if(argc == 1) break;
argc--; argv++; /* Skip argv[0] */
if(debug) printf("Processing File %d: %s\n", argc, *argv);
if(!(fp = fopen(*argv, "r"))) {
fprintf(stderr, "%s: error: %s: ", prog, *argv);
perror("");
return 1;
}
count = 0;
process_file(fp);
fclose(fp);
}
}
printf("\n");
return 0;
}
void process_file(FILE *fp)
{
float U;
char *s;
if(debug) printf("Binary Points:\n");
while((U = get_number(fp)) != ERROR_FLOAT) {
if(debug) {
s = bin_enc(U);
printf("\t%3d. %+6.4f = %c %.3s %.4s %.4s %.4s\n", count, U, s[0], &s[1], &s[4], &s[8], &s[12]);
} else {
printf("%s", spacer(bin_enc(U)));
}
}
if(debug) printf("Number of Points: %d\n", count);
return;
}
float get_number(FILE *fp)
{
register int c = 0;
float f;
while(!feof(fp) && isspace(c = fgetc(fp))); /* Skip spaces */
if(!feof(fp))
ungetc(c, fp);
else
return ERROR_FLOAT;
if(isdigit(c) || c == '+' || c == '-' || c == '.') {
c = fscanf(fp, "%f", &f);
if(feof(fp) || c == 0 || f < -0.5 || f > 0.5) return ERROR_FLOAT;
} else return ERROR_FLOAT;
count++;
return f;
}
char *bin_enc(float f)
{
int i;
short unsigned int n;
char *b = (char *) malloc((MAX_BIT + 1) * sizeof(char));
b[0] = f < 0? '1': '0'; /* Store the sign bit */
b[MAX_BIT] = '\0'; /* NULL terminated binary string */
f = f < 0? -f: f; /* take the absolute value */
n = (int) (10000 * f);
for(i = MAX_BIT - 1; i > 0; i--) {
b[i] = '0' + (n & 0x1);
n >>= 1;
}
return b;
}
char *spacer(char *s)
{
int i, len;
char *ss;
if(!s) return (char *)NULL;
len = strlen(s);
ss = (char *) malloc((2 * len + 1) * sizeof(char));
ss[2*len] = '\0';
for(i = 0; i < len; i++) {
ss[2*i] = s[i];
ss[2*i + 1] = ' ';
}
return ss;
}
|
the_stack_data/38859.c | // Ogg Vorbis audio decoder - v1.17 - public domain
// http://nothings.org/stb_vorbis/
//
// Original version written by Sean Barrett in 2007.
//
// Originally sponsored by RAD Game Tools. Seeking implementation
// sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker,
// Elias Software, Aras Pranckevicius, and Sean Barrett.
//
// LICENSE
//
// See end of file for license information.
//
// Limitations:
//
// - floor 0 not supported (used in old ogg vorbis files pre-2004)
// - lossless sample-truncation at beginning ignored
// - cannot concatenate multiple vorbis streams
// - sample positions are 32-bit, limiting seekable 192Khz
// files to around 6 hours (Ogg supports 64-bit)
//
// Feature contributors:
// Dougall Johnson (sample-exact seeking)
//
// Bugfix/warning contributors:
// Terje Mathisen Niklas Frykholm Andy Hill
// Casey Muratori John Bolton Gargaj
// Laurent Gomila Marc LeBlanc Ronny Chevalier
// Bernhard Wodo Evan Balster alxprd@github
// Tom Beaumont Ingo Leitgeb Nicolas Guillemot
// Phillip Bennefall Rohit Thiago Goulart
// manxorist@github saga musix github:infatum
// Timur Gagiev Maxwell Koo
//
// Partial history:
// 1.17 - 2019-07-08 - fix CVE-2019-13217..CVE-2019-13223 (by ForAllSecure)
// 1.16 - 2019-03-04 - fix warnings
// 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found
// 1.14 - 2018-02-11 - delete bogus dealloca usage
// 1.13 - 2018-01-29 - fix truncation of last frame (hopefully)
// 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files
// 1.11 - 2017-07-23 - fix MinGW compilation
// 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory
// 1.09 - 2016-04-04 - back out 'truncation of last frame' fix from previous version
// 1.08 - 2016-04-02 - warnings; setup memory leaks; truncation of last frame
// 1.07 - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const
// 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson)
// some crash fixes when out of memory or with corrupt files
// fix some inappropriately signed shifts
// 1.05 - 2015-04-19 - don't define __forceinline if it's redundant
// 1.04 - 2014-08-27 - fix missing const-correct case in API
// 1.03 - 2014-08-07 - warning fixes
// 1.02 - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows
// 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct)
// 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel;
// (API change) report sample rate for decode-full-file funcs
//
// See end of file for full version history.
//////////////////////////////////////////////////////////////////////////////
//
// HEADER BEGINS HERE
//
#ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H
#define STB_VORBIS_INCLUDE_STB_VORBIS_H
#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
#define STB_VORBIS_NO_STDIO 1
#endif
#ifndef STB_VORBIS_NO_STDIO
#include <stdio.h>
#endif
#ifdef __clang__
#pragma clang diagnostic ignored "-Wcomma"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/////////// THREAD SAFETY
// Individual stb_vorbis* handles are not thread-safe; you cannot decode from
// them from multiple threads at the same time. However, you can have multiple
// stb_vorbis* handles and decode from them independently in multiple thrads.
/////////// MEMORY ALLOCATION
// normally stb_vorbis uses malloc() to allocate memory at startup,
// and alloca() to allocate temporary memory during a frame on the
// stack. (Memory consumption will depend on the amount of setup
// data in the file and how you set the compile flags for speed
// vs. size. In my test files the maximal-size usage is ~150KB.)
//
// You can modify the wrapper functions in the source (setup_malloc,
// setup_temp_malloc, temp_malloc) to change this behavior, or you
// can use a simpler allocation model: you pass in a buffer from
// which stb_vorbis will allocate _all_ its memory (including the
// temp memory). "open" may fail with a VORBIS_outofmem if you
// do not pass in enough data; there is no way to determine how
// much you do need except to succeed (at which point you can
// query get_info to find the exact amount required. yes I know
// this is lame).
//
// If you pass in a non-NULL buffer of the type below, allocation
// will occur from it as described above. Otherwise just pass NULL
// to use malloc()/alloca()
typedef struct
{
char *alloc_buffer;
int alloc_buffer_length_in_bytes;
} stb_vorbis_alloc;
/////////// FUNCTIONS USEABLE WITH ALL INPUT MODES
typedef struct stb_vorbis stb_vorbis;
typedef struct
{
unsigned int sample_rate;
int channels;
unsigned int setup_memory_required;
unsigned int setup_temp_memory_required;
unsigned int temp_memory_required;
int max_frame_size;
} stb_vorbis_info;
// get general information about the file
extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f);
// get the last error detected (clears it, too)
extern int stb_vorbis_get_error(stb_vorbis *f);
// close an ogg vorbis file and free all memory in use
extern void stb_vorbis_close(stb_vorbis *f);
// this function returns the offset (in samples) from the beginning of the
// file that will be returned by the next decode, if it is known, or -1
// otherwise. after a flush_pushdata() call, this may take a while before
// it becomes valid again.
// NOT WORKING YET after a seek with PULLDATA API
extern int stb_vorbis_get_sample_offset(stb_vorbis *f);
// returns the current seek point within the file, or offset from the beginning
// of the memory buffer. In pushdata mode it returns 0.
extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f);
/////////// PUSHDATA API
#ifndef STB_VORBIS_NO_PUSHDATA_API
// this API allows you to get blocks of data from any source and hand
// them to stb_vorbis. you have to buffer them; stb_vorbis will tell
// you how much it used, and you have to give it the rest next time;
// and stb_vorbis may not have enough data to work with and you will
// need to give it the same data again PLUS more. Note that the Vorbis
// specification does not bound the size of an individual frame.
extern stb_vorbis *stb_vorbis_open_pushdata(
const unsigned char * datablock, int datablock_length_in_bytes,
int *datablock_memory_consumed_in_bytes,
int *error,
const stb_vorbis_alloc *alloc_buffer);
// create a vorbis decoder by passing in the initial data block containing
// the ogg&vorbis headers (you don't need to do parse them, just provide
// the first N bytes of the file--you're told if it's not enough, see below)
// on success, returns an stb_vorbis *, does not set error, returns the amount of
// data parsed/consumed on this call in *datablock_memory_consumed_in_bytes;
// on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed
// if returns NULL and *error is VORBIS_need_more_data, then the input block was
// incomplete and you need to pass in a larger block from the start of the file
extern int stb_vorbis_decode_frame_pushdata(
stb_vorbis *f,
const unsigned char *datablock, int datablock_length_in_bytes,
int *channels, // place to write number of float * buffers
float ***output, // place to write float ** array of float * buffers
int *samples // place to write number of output samples
);
// decode a frame of audio sample data if possible from the passed-in data block
//
// return value: number of bytes we used from datablock
//
// possible cases:
// 0 bytes used, 0 samples output (need more data)
// N bytes used, 0 samples output (resynching the stream, keep going)
// N bytes used, M samples output (one frame of data)
// note that after opening a file, you will ALWAYS get one N-bytes,0-sample
// frame, because Vorbis always "discards" the first frame.
//
// Note that on resynch, stb_vorbis will rarely consume all of the buffer,
// instead only datablock_length_in_bytes-3 or less. This is because it wants
// to avoid missing parts of a page header if they cross a datablock boundary,
// without writing state-machiney code to record a partial detection.
//
// The number of channels returned are stored in *channels (which can be
// NULL--it is always the same as the number of channels reported by
// get_info). *output will contain an array of float* buffers, one per
// channel. In other words, (*output)[0][0] contains the first sample from
// the first channel, and (*output)[1][0] contains the first sample from
// the second channel.
extern void stb_vorbis_flush_pushdata(stb_vorbis *f);
// inform stb_vorbis that your next datablock will not be contiguous with
// previous ones (e.g. you've seeked in the data); future attempts to decode
// frames will cause stb_vorbis to resynchronize (as noted above), and
// once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it
// will begin decoding the _next_ frame.
//
// if you want to seek using pushdata, you need to seek in your file, then
// call stb_vorbis_flush_pushdata(), then start calling decoding, then once
// decoding is returning you data, call stb_vorbis_get_sample_offset, and
// if you don't like the result, seek your file again and repeat.
#endif
////////// PULLING INPUT API
#ifndef STB_VORBIS_NO_PULLDATA_API
// This API assumes stb_vorbis is allowed to pull data from a source--
// either a block of memory containing the _entire_ vorbis stream, or a
// FILE * that you or it create, or possibly some other reading mechanism
// if you go modify the source to replace the FILE * case with some kind
// of callback to your code. (But if you don't support seeking, you may
// just want to go ahead and use pushdata.)
#if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output);
#endif
#if !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output);
#endif
// decode an entire file and output the data interleaved into a malloc()ed
// buffer stored in *output. The return value is the number of samples
// decoded, or -1 if the file could not be opened or was not an ogg vorbis file.
// When you're done with it, just free() the pointer returned in *output.
extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len,
int *error, const stb_vorbis_alloc *alloc_buffer);
// create an ogg vorbis decoder from an ogg vorbis stream in memory (note
// this must be the entire stream!). on failure, returns NULL and sets *error
#ifndef STB_VORBIS_NO_STDIO
extern stb_vorbis * stb_vorbis_open_filename(const char *filename,
int *error, const stb_vorbis_alloc *alloc_buffer);
// create an ogg vorbis decoder from a filename via fopen(). on failure,
// returns NULL and sets *error (possibly to VORBIS_file_open_failure).
extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close,
int *error, const stb_vorbis_alloc *alloc_buffer);
// create an ogg vorbis decoder from an open FILE *, looking for a stream at
// the _current_ seek point (ftell). on failure, returns NULL and sets *error.
// note that stb_vorbis must "own" this stream; if you seek it in between
// calls to stb_vorbis, it will become confused. Moreover, if you attempt to
// perform stb_vorbis_seek_*() operations on this file, it will assume it
// owns the _entire_ rest of the file after the start point. Use the next
// function, stb_vorbis_open_file_section(), to limit it.
extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close,
int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len);
// create an ogg vorbis decoder from an open FILE *, looking for a stream at
// the _current_ seek point (ftell); the stream will be of length 'len' bytes.
// on failure, returns NULL and sets *error. note that stb_vorbis must "own"
// this stream; if you seek it in between calls to stb_vorbis, it will become
// confused.
#endif
extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number);
extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number);
// these functions seek in the Vorbis file to (approximately) 'sample_number'.
// after calling seek_frame(), the next call to get_frame_*() will include
// the specified sample. after calling stb_vorbis_seek(), the next call to
// stb_vorbis_get_samples_* will start with the specified sample. If you
// do not need to seek to EXACTLY the target sample when using get_samples_*,
// you can also use seek_frame().
extern int stb_vorbis_seek_start(stb_vorbis *f);
// this function is equivalent to stb_vorbis_seek(f,0)
extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f);
extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f);
// these functions return the total length of the vorbis stream
extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output);
// decode the next frame and return the number of samples. the number of
// channels returned are stored in *channels (which can be NULL--it is always
// the same as the number of channels reported by get_info). *output will
// contain an array of float* buffers, one per channel. These outputs will
// be overwritten on the next call to stb_vorbis_get_frame_*.
//
// You generally should not intermix calls to stb_vorbis_get_frame_*()
// and stb_vorbis_get_samples_*(), since the latter calls the former.
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts);
extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples);
#endif
// decode the next frame and return the number of *samples* per channel.
// Note that for interleaved data, you pass in the number of shorts (the
// size of your array), but the return value is the number of samples per
// channel, not the total number of samples.
//
// The data is coerced to the number of channels you request according to the
// channel coercion rules (see below). You must pass in the size of your
// buffer(s) so that stb_vorbis will not overwrite the end of the buffer.
// The maximum buffer size needed can be gotten from get_info(); however,
// the Vorbis I specification implies an absolute maximum of 4096 samples
// per channel.
// Channel coercion rules:
// Let M be the number of channels requested, and N the number of channels present,
// and Cn be the nth channel; let stereo L be the sum of all L and center channels,
// and stereo R be the sum of all R and center channels (channel assignment from the
// vorbis spec).
// M N output
// 1 k sum(Ck) for all k
// 2 * stereo L, stereo R
// k l k > l, the first l channels, then 0s
// k l k <= l, the first k channels
// Note that this is not _good_ surround etc. mixing at all! It's just so
// you get something useful.
extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats);
extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples);
// gets num_samples samples, not necessarily on a frame boundary--this requires
// buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES.
// Returns the number of samples stored per channel; it may be less than requested
// at the end of the file. If there are no more samples in the file, returns 0.
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts);
extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples);
#endif
// gets num_samples samples, not necessarily on a frame boundary--this requires
// buffering so you have to supply the buffers. Applies the coercion rules above
// to produce 'channels' channels. Returns the number of samples stored per channel;
// it may be less than requested at the end of the file. If there are no more
// samples in the file, returns 0.
#endif
//////// ERROR CODES
enum STBVorbisError
{
VORBIS__no_error,
VORBIS_need_more_data=1, // not a real error
VORBIS_invalid_api_mixing, // can't mix API modes
VORBIS_outofmem, // not enough memory
VORBIS_feature_not_supported, // uses floor 0
VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small
VORBIS_file_open_failure, // fopen() failed
VORBIS_seek_without_length, // can't seek in unknown-length file
VORBIS_unexpected_eof=10, // file is truncated?
VORBIS_seek_invalid, // seek past EOF
// decoding errors (corrupt/invalid stream) -- you probably
// don't care about the exact details of these
// vorbis errors:
VORBIS_invalid_setup=20,
VORBIS_invalid_stream,
// ogg errors:
VORBIS_missing_capture_pattern=30,
VORBIS_invalid_stream_structure_version,
VORBIS_continued_packet_flag_invalid,
VORBIS_incorrect_stream_serial_number,
VORBIS_invalid_first_page,
VORBIS_bad_packet_type,
VORBIS_cant_find_last_page,
VORBIS_seek_failed,
VORBIS_ogg_skeleton_not_supported
};
#ifdef __cplusplus
}
#endif
#endif // STB_VORBIS_INCLUDE_STB_VORBIS_H
//
// HEADER ENDS HERE
//
//////////////////////////////////////////////////////////////////////////////
#ifndef STB_VORBIS_HEADER_ONLY
// global configuration settings (e.g. set these in the project/makefile),
// or just set them in this file at the top (although ideally the first few
// should be visible when the header file is compiled too, although it's not
// crucial)
// STB_VORBIS_NO_PUSHDATA_API
// does not compile the code for the various stb_vorbis_*_pushdata()
// functions
// #define STB_VORBIS_NO_PUSHDATA_API
// STB_VORBIS_NO_PULLDATA_API
// does not compile the code for the non-pushdata APIs
// #define STB_VORBIS_NO_PULLDATA_API
// STB_VORBIS_NO_STDIO
// does not compile the code for the APIs that use FILE *s internally
// or externally (implied by STB_VORBIS_NO_PULLDATA_API)
// #define STB_VORBIS_NO_STDIO
// STB_VORBIS_NO_INTEGER_CONVERSION
// does not compile the code for converting audio sample data from
// float to integer (implied by STB_VORBIS_NO_PULLDATA_API)
// #define STB_VORBIS_NO_INTEGER_CONVERSION
// STB_VORBIS_NO_FAST_SCALED_FLOAT
// does not use a fast float-to-int trick to accelerate float-to-int on
// most platforms which requires endianness be defined correctly.
//#define STB_VORBIS_NO_FAST_SCALED_FLOAT
// STB_VORBIS_MAX_CHANNELS [number]
// globally define this to the maximum number of channels you need.
// The spec does not put a restriction on channels except that
// the count is stored in a byte, so 255 is the hard limit.
// Reducing this saves about 16 bytes per value, so using 16 saves
// (255-16)*16 or around 4KB. Plus anything other memory usage
// I forgot to account for. Can probably go as low as 8 (7.1 audio),
// 6 (5.1 audio), or 2 (stereo only).
#ifndef STB_VORBIS_MAX_CHANNELS
#define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone?
#endif
// STB_VORBIS_PUSHDATA_CRC_COUNT [number]
// after a flush_pushdata(), stb_vorbis begins scanning for the
// next valid page, without backtracking. when it finds something
// that looks like a page, it streams through it and verifies its
// CRC32. Should that validation fail, it keeps scanning. But it's
// possible that _while_ streaming through to check the CRC32 of
// one candidate page, it sees another candidate page. This #define
// determines how many "overlapping" candidate pages it can search
// at once. Note that "real" pages are typically ~4KB to ~8KB, whereas
// garbage pages could be as big as 64KB, but probably average ~16KB.
// So don't hose ourselves by scanning an apparent 64KB page and
// missing a ton of real ones in the interim; so minimum of 2
#ifndef STB_VORBIS_PUSHDATA_CRC_COUNT
#define STB_VORBIS_PUSHDATA_CRC_COUNT 4
#endif
// STB_VORBIS_FAST_HUFFMAN_LENGTH [number]
// sets the log size of the huffman-acceleration table. Maximum
// supported value is 24. with larger numbers, more decodings are O(1),
// but the table size is larger so worse cache missing, so you'll have
// to probe (and try multiple ogg vorbis files) to find the sweet spot.
#ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH
#define STB_VORBIS_FAST_HUFFMAN_LENGTH 10
#endif
// STB_VORBIS_FAST_BINARY_LENGTH [number]
// sets the log size of the binary-search acceleration table. this
// is used in similar fashion to the fast-huffman size to set initial
// parameters for the binary search
// STB_VORBIS_FAST_HUFFMAN_INT
// The fast huffman tables are much more efficient if they can be
// stored as 16-bit results instead of 32-bit results. This restricts
// the codebooks to having only 65535 possible outcomes, though.
// (At least, accelerated by the huffman table.)
#ifndef STB_VORBIS_FAST_HUFFMAN_INT
#define STB_VORBIS_FAST_HUFFMAN_SHORT
#endif
// STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
// If the 'fast huffman' search doesn't succeed, then stb_vorbis falls
// back on binary searching for the correct one. This requires storing
// extra tables with the huffman codes in sorted order. Defining this
// symbol trades off space for speed by forcing a linear search in the
// non-fast case, except for "sparse" codebooks.
// #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
// STB_VORBIS_DIVIDES_IN_RESIDUE
// stb_vorbis precomputes the result of the scalar residue decoding
// that would otherwise require a divide per chunk. you can trade off
// space for time by defining this symbol.
// #define STB_VORBIS_DIVIDES_IN_RESIDUE
// STB_VORBIS_DIVIDES_IN_CODEBOOK
// vorbis VQ codebooks can be encoded two ways: with every case explicitly
// stored, or with all elements being chosen from a small range of values,
// and all values possible in all elements. By default, stb_vorbis expands
// this latter kind out to look like the former kind for ease of decoding,
// because otherwise an integer divide-per-vector-element is required to
// unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can
// trade off storage for speed.
//#define STB_VORBIS_DIVIDES_IN_CODEBOOK
#ifdef STB_VORBIS_CODEBOOK_SHORTS
#error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats"
#endif
// STB_VORBIS_DIVIDE_TABLE
// this replaces small integer divides in the floor decode loop with
// table lookups. made less than 1% difference, so disabled by default.
// STB_VORBIS_NO_INLINE_DECODE
// disables the inlining of the scalar codebook fast-huffman decode.
// might save a little codespace; useful for debugging
// #define STB_VORBIS_NO_INLINE_DECODE
// STB_VORBIS_NO_DEFER_FLOOR
// Normally we only decode the floor without synthesizing the actual
// full curve. We can instead synthesize the curve immediately. This
// requires more memory and is very likely slower, so I don't think
// you'd ever want to do it except for debugging.
// #define STB_VORBIS_NO_DEFER_FLOOR
//////////////////////////////////////////////////////////////////////////////
#ifdef STB_VORBIS_NO_PULLDATA_API
#define STB_VORBIS_NO_INTEGER_CONVERSION
#define STB_VORBIS_NO_STDIO
#endif
#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
#define STB_VORBIS_NO_STDIO 1
#endif
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
// only need endianness for fast-float-to-int, which we don't
// use for pushdata
#ifndef STB_VORBIS_BIG_ENDIAN
#define STB_VORBIS_ENDIAN 0
#else
#define STB_VORBIS_ENDIAN 1
#endif
#endif
#endif
#ifndef STB_VORBIS_NO_STDIO
#include <stdio.h>
#endif
#ifndef STB_VORBIS_NO_CRT
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>
// find definition of alloca if it's not in stdlib.h:
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <malloc.h>
#endif
#if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__)
#include <alloca.h>
#endif
#else // STB_VORBIS_NO_CRT
#define NULL 0
#define malloc(s) 0
#define free(s) ((void) 0)
#define realloc(s) 0
#endif // STB_VORBIS_NO_CRT
#include <limits.h>
#ifdef __MINGW32__
// eff you mingw:
// "fixed":
// http://sourceforge.net/p/mingw-w64/mailman/message/32882927/
// "no that broke the build, reverted, who cares about C":
// http://sourceforge.net/p/mingw-w64/mailman/message/32890381/
#ifdef __forceinline
#undef __forceinline
#endif
#define __forceinline
#define alloca __builtin_alloca
#elif !defined(_MSC_VER)
#if __GNUC__
#define __forceinline inline
#else
#define __forceinline
#endif
#endif
#ifdef __FreeBSD__
#ifdef alloca
#undef alloca
#endif
#define alloca allocm
#endif
#if STB_VORBIS_MAX_CHANNELS > 256
#error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range"
#endif
#if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24
#error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range"
#endif
#if 0
#include <crtdbg.h>
#define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1])
#else
#define CHECK(f) ((void) 0)
#endif
#define MAX_BLOCKSIZE_LOG 13 // from specification
#define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG)
typedef unsigned char uint8;
typedef signed char int8;
typedef unsigned short uint16;
typedef signed short int16;
typedef unsigned int uint32;
typedef signed int int32;
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
typedef float codetype;
// @NOTE
//
// Some arrays below are tagged "//varies", which means it's actually
// a variable-sized piece of data, but rather than malloc I assume it's
// small enough it's better to just allocate it all together with the
// main thing
//
// Most of the variables are specified with the smallest size I could pack
// them into. It might give better performance to make them all full-sized
// integers. It should be safe to freely rearrange the structures or change
// the sizes larger--nothing relies on silently truncating etc., nor the
// order of variables.
#define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)
#define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1)
typedef struct
{
int dimensions, entries;
uint8 *codeword_lengths;
float minimum_value;
float delta_value;
uint8 value_bits;
uint8 lookup_type;
uint8 sequence_p;
uint8 sparse;
uint32 lookup_values;
codetype *multiplicands;
uint32 *codewords;
#ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
#else
int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
#endif
uint32 *sorted_codewords;
int *sorted_values;
int sorted_entries;
} Codebook;
typedef struct
{
uint8 order;
uint16 rate;
uint16 bark_map_size;
uint8 amplitude_bits;
uint8 amplitude_offset;
uint8 number_of_books;
uint8 book_list[16]; // varies
} Floor0;
typedef struct
{
uint8 partitions;
uint8 partition_class_list[32]; // varies
uint8 class_dimensions[16]; // varies
uint8 class_subclasses[16]; // varies
uint8 class_masterbooks[16]; // varies
int16 subclass_books[16][8]; // varies
uint16 Xlist[31*8+2]; // varies
uint8 sorted_order[31*8+2];
uint8 neighbors[31*8+2][2];
uint8 floor1_multiplier;
uint8 rangebits;
int values;
} Floor1;
typedef union
{
Floor0 floor0;
Floor1 floor1;
} Floor;
typedef struct
{
uint32 begin, end;
uint32 part_size;
uint8 classifications;
uint8 classbook;
uint8 **classdata;
int16 (*residue_books)[8];
} Residue;
typedef struct
{
uint8 magnitude;
uint8 angle;
uint8 mux;
} MappingChannel;
typedef struct
{
uint16 coupling_steps;
MappingChannel *chan;
uint8 submaps;
uint8 submap_floor[15]; // varies
uint8 submap_residue[15]; // varies
} Mapping;
typedef struct
{
uint8 blockflag;
uint8 mapping;
uint16 windowtype;
uint16 transformtype;
} Mode;
typedef struct
{
uint32 goal_crc; // expected crc if match
int bytes_left; // bytes left in packet
uint32 crc_so_far; // running crc
int bytes_done; // bytes processed in _current_ chunk
uint32 sample_loc; // granule pos encoded in page
} CRCscan;
typedef struct
{
uint32 page_start, page_end;
uint32 last_decoded_sample;
} ProbedPage;
struct stb_vorbis
{
// user-accessible info
unsigned int sample_rate;
int channels;
unsigned int setup_memory_required;
unsigned int temp_memory_required;
unsigned int setup_temp_memory_required;
// input config
#ifndef STB_VORBIS_NO_STDIO
FILE *f;
uint32 f_start;
int close_on_free;
#endif
uint8 *stream;
uint8 *stream_start;
uint8 *stream_end;
uint32 stream_len;
uint8 push_mode;
uint32 first_audio_page_offset;
ProbedPage p_first, p_last;
// memory management
stb_vorbis_alloc alloc;
int setup_offset;
int temp_offset;
// run-time results
int eof;
enum STBVorbisError error;
// user-useful data
// header info
int blocksize[2];
int blocksize_0, blocksize_1;
int codebook_count;
Codebook *codebooks;
int floor_count;
uint16 floor_types[64]; // varies
Floor *floor_config;
int residue_count;
uint16 residue_types[64]; // varies
Residue *residue_config;
int mapping_count;
Mapping *mapping;
int mode_count;
Mode mode_config[64]; // varies
uint32 total_samples;
// decode buffer
float *channel_buffers[STB_VORBIS_MAX_CHANNELS];
float *outputs [STB_VORBIS_MAX_CHANNELS];
float *previous_window[STB_VORBIS_MAX_CHANNELS];
int previous_length;
#ifndef STB_VORBIS_NO_DEFER_FLOOR
int16 *finalY[STB_VORBIS_MAX_CHANNELS];
#else
float *floor_buffers[STB_VORBIS_MAX_CHANNELS];
#endif
uint32 current_loc; // sample location of next frame to decode
int current_loc_valid;
// per-blocksize precomputed data
// twiddle factors
float *A[2],*B[2],*C[2];
float *window[2];
uint16 *bit_reverse[2];
// current page/packet/segment streaming info
uint32 serial; // stream serial number for verification
int last_page;
int segment_count;
uint8 segments[255];
uint8 page_flag;
uint8 bytes_in_seg;
uint8 first_decode;
int next_seg;
int last_seg; // flag that we're on the last segment
int last_seg_which; // what was the segment number of the last seg?
uint32 acc;
int valid_bits;
int packet_bytes;
int end_seg_with_known_loc;
uint32 known_loc_for_packet;
int discard_samples_deferred;
uint32 samples_output;
// push mode scanning
int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching
#ifndef STB_VORBIS_NO_PUSHDATA_API
CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT];
#endif
// sample-access
int channel_buffer_start;
int channel_buffer_end;
};
#if defined(STB_VORBIS_NO_PUSHDATA_API)
#define IS_PUSH_MODE(f) FALSE
#elif defined(STB_VORBIS_NO_PULLDATA_API)
#define IS_PUSH_MODE(f) TRUE
#else
#define IS_PUSH_MODE(f) ((f)->push_mode)
#endif
typedef struct stb_vorbis vorb;
static int error(vorb *f, enum STBVorbisError e)
{
f->error = e;
if (!f->eof && e != VORBIS_need_more_data) {
f->error=e; // breakpoint for debugging
}
return 0;
}
// these functions are used for allocating temporary memory
// while decoding. if you can afford the stack space, use
// alloca(); otherwise, provide a temp buffer and it will
// allocate out of those.
#define array_size_required(count,size) (count*(sizeof(void *)+(size)))
#define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size))
#define temp_free(f,p) 0
#define temp_alloc_save(f) ((f)->temp_offset)
#define temp_alloc_restore(f,p) ((f)->temp_offset = (p))
#define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size)
// given a sufficiently large block of memory, make an array of pointers to subblocks of it
static void *make_block_array(void *mem, int count, int size)
{
int i;
void ** p = (void **) mem;
char *q = (char *) (p + count);
for (i=0; i < count; ++i) {
p[i] = q;
q += size;
}
return p;
}
static void *setup_malloc(vorb *f, int sz)
{
sz = (sz+3) & ~3;
f->setup_memory_required += sz;
if (f->alloc.alloc_buffer) {
void *p = (char *) f->alloc.alloc_buffer + f->setup_offset;
if (f->setup_offset + sz > f->temp_offset) return NULL;
f->setup_offset += sz;
return p;
}
return sz ? malloc(sz) : NULL;
}
static void setup_free(vorb *f, void *p)
{
if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack
free(p);
}
static void *setup_temp_malloc(vorb *f, int sz)
{
sz = (sz+3) & ~3;
if (f->alloc.alloc_buffer) {
if (f->temp_offset - sz < f->setup_offset) return NULL;
f->temp_offset -= sz;
return (char *) f->alloc.alloc_buffer + f->temp_offset;
}
return malloc(sz);
}
static void setup_temp_free(vorb *f, void *p, int sz)
{
if (f->alloc.alloc_buffer) {
f->temp_offset += (sz+3)&~3;
return;
}
free(p);
}
#define CRC32_POLY 0x04c11db7 // from spec
static uint32 crc_table[256];
static void crc32_init(void)
{
int i,j;
uint32 s;
for(i=0; i < 256; i++) {
for (s=(uint32) i << 24, j=0; j < 8; ++j)
s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0);
crc_table[i] = s;
}
}
static __forceinline uint32 crc32_update(uint32 crc, uint8 byte)
{
return (crc << 8) ^ crc_table[byte ^ (crc >> 24)];
}
// used in setup, and for huffman that doesn't go fast path
static unsigned int bit_reverse(unsigned int n)
{
n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);
n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);
n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);
return (n >> 16) | (n << 16);
}
static float square(float x)
{
return x*x;
}
// this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3
// as required by the specification. fast(?) implementation from stb.h
// @OPTIMIZE: called multiple times per-packet with "constants"; move to setup
static int ilog(int32 n)
{
static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };
if (n < 0) return 0; // signed n returns 0
// 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)
if (n < (1 << 14))
if (n < (1 << 4)) return 0 + log2_4[n ];
else if (n < (1 << 9)) return 5 + log2_4[n >> 5];
else return 10 + log2_4[n >> 10];
else if (n < (1 << 24))
if (n < (1 << 19)) return 15 + log2_4[n >> 15];
else return 20 + log2_4[n >> 20];
else if (n < (1 << 29)) return 25 + log2_4[n >> 25];
else return 30 + log2_4[n >> 30];
}
#ifndef M_PI
#define M_PI 3.14159265358979323846264f // from CRC
#endif
// code length assigned to a value with no huffman encoding
#define NO_CODE 255
/////////////////////// LEAF SETUP FUNCTIONS //////////////////////////
//
// these functions are only called at setup, and only a few times
// per file
static float float32_unpack(uint32 x)
{
// from the specification
uint32 mantissa = x & 0x1fffff;
uint32 sign = x & 0x80000000;
uint32 exp = (x & 0x7fe00000) >> 21;
double res = sign ? -(double)mantissa : (double)mantissa;
return (float) ldexp((float)res, exp-788);
}
// zlib & jpeg huffman tables assume that the output symbols
// can either be arbitrarily arranged, or have monotonically
// increasing frequencies--they rely on the lengths being sorted;
// this makes for a very simple generation algorithm.
// vorbis allows a huffman table with non-sorted lengths. This
// requires a more sophisticated construction, since symbols in
// order do not map to huffman codes "in order".
static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values)
{
if (!c->sparse) {
c->codewords [symbol] = huff_code;
} else {
c->codewords [count] = huff_code;
c->codeword_lengths[count] = len;
values [count] = symbol;
}
}
static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values)
{
int i,k,m=0;
uint32 available[32];
memset(available, 0, sizeof(available));
// find the first entry
for (k=0; k < n; ++k) if (len[k] < NO_CODE) break;
if (k == n) { assert(c->sorted_entries == 0); return TRUE; }
// add to the list
add_entry(c, 0, k, m++, len[k], values);
// add all available leaves
for (i=1; i <= len[k]; ++i)
available[i] = 1U << (32-i);
// note that the above code treats the first case specially,
// but it's really the same as the following code, so they
// could probably be combined (except the initial code is 0,
// and I use 0 in available[] to mean 'empty')
for (i=k+1; i < n; ++i) {
uint32 res;
int z = len[i], y;
if (z == NO_CODE) continue;
// find lowest available leaf (should always be earliest,
// which is what the specification calls for)
// note that this property, and the fact we can never have
// more than one free leaf at a given level, isn't totally
// trivial to prove, but it seems true and the assert never
// fires, so!
while (z > 0 && !available[z]) --z;
if (z == 0) { return FALSE; }
res = available[z];
assert(z >= 0 && z < 32);
available[z] = 0;
add_entry(c, bit_reverse(res), i, m++, len[i], values);
// propagate availability up the tree
if (z != len[i]) {
assert(len[i] >= 0 && len[i] < 32);
for (y=len[i]; y > z; --y) {
assert(available[y] == 0);
available[y] = res + (1 << (32-y));
}
}
}
return TRUE;
}
// accelerated huffman table allows fast O(1) match of all symbols
// of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH
static void compute_accelerated_huffman(Codebook *c)
{
int i, len;
for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i)
c->fast_huffman[i] = -1;
len = c->sparse ? c->sorted_entries : c->entries;
#ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
if (len > 32767) len = 32767; // largest possible value we can encode!
#endif
for (i=0; i < len; ++i) {
if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i];
// set table entries for all bit combinations in the higher bits
while (z < FAST_HUFFMAN_TABLE_SIZE) {
c->fast_huffman[z] = i;
z += 1 << c->codeword_lengths[i];
}
}
}
}
#ifdef _MSC_VER
#define STBV_CDECL __cdecl
#else
#define STBV_CDECL
#endif
static int STBV_CDECL uint32_compare(const void *p, const void *q)
{
uint32 x = * (uint32 *) p;
uint32 y = * (uint32 *) q;
return x < y ? -1 : x > y;
}
static int include_in_sort(Codebook *c, uint8 len)
{
if (c->sparse) { assert(len != NO_CODE); return TRUE; }
if (len == NO_CODE) return FALSE;
if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE;
return FALSE;
}
// if the fast table above doesn't work, we want to binary
// search them... need to reverse the bits
static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values)
{
int i, len;
// build a list of all the entries
// OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.
// this is kind of a frivolous optimization--I don't see any performance improvement,
// but it's like 4 extra lines of code, so.
if (!c->sparse) {
int k = 0;
for (i=0; i < c->entries; ++i)
if (include_in_sort(c, lengths[i]))
c->sorted_codewords[k++] = bit_reverse(c->codewords[i]);
assert(k == c->sorted_entries);
} else {
for (i=0; i < c->sorted_entries; ++i)
c->sorted_codewords[i] = bit_reverse(c->codewords[i]);
}
qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare);
c->sorted_codewords[c->sorted_entries] = 0xffffffff;
len = c->sparse ? c->sorted_entries : c->entries;
// now we need to indicate how they correspond; we could either
// #1: sort a different data structure that says who they correspond to
// #2: for each sorted entry, search the original list to find who corresponds
// #3: for each original entry, find the sorted entry
// #1 requires extra storage, #2 is slow, #3 can use binary search!
for (i=0; i < len; ++i) {
int huff_len = c->sparse ? lengths[values[i]] : lengths[i];
if (include_in_sort(c,huff_len)) {
uint32 code = bit_reverse(c->codewords[i]);
int x=0, n=c->sorted_entries;
while (n > 1) {
// invariant: sc[x] <= code < sc[x+n]
int m = x + (n >> 1);
if (c->sorted_codewords[m] <= code) {
x = m;
n -= (n>>1);
} else {
n >>= 1;
}
}
assert(c->sorted_codewords[x] == code);
if (c->sparse) {
c->sorted_values[x] = values[i];
c->codeword_lengths[x] = huff_len;
} else {
c->sorted_values[x] = i;
}
}
}
}
// only run while parsing the header (3 times)
static int vorbis_validate(uint8 *data)
{
static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };
return memcmp(data, vorbis, 6) == 0;
}
// called from setup only, once per code book
// (formula implied by specification)
static int lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
if (pow((float) r+1, dim) <= entries)
return -1;
if ((int) floor(pow((float) r, dim)) > entries)
return -1;
return r;
}
// called twice per file
static void compute_twiddle_factors(int n, float *A, float *B, float *C)
{
int n4 = n >> 2, n8 = n >> 3;
int k,k2;
for (k=k2=0; k < n4; ++k,k2+=2) {
A[k2 ] = (float) cos(4*k*M_PI/n);
A[k2+1] = (float) -sin(4*k*M_PI/n);
B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f;
B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f;
}
for (k=k2=0; k < n8; ++k,k2+=2) {
C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
}
}
static void compute_window(int n, float *window)
{
int n2 = n >> 1, i;
for (i=0; i < n2; ++i)
window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));
}
static void compute_bitreverse(int n, uint16 *rev)
{
int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
int i, n8 = n >> 3;
for (i=0; i < n8; ++i)
rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2;
}
static int init_blocksize(vorb *f, int b, int n)
{
int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;
f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2);
f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2);
f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4);
if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem);
compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);
f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2);
if (!f->window[b]) return error(f, VORBIS_outofmem);
compute_window(n, f->window[b]);
f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8);
if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem);
compute_bitreverse(n, f->bit_reverse[b]);
return TRUE;
}
static void neighbors(uint16 *x, int n, int *plow, int *phigh)
{
int low = -1;
int high = 65536;
int i;
for (i=0; i < n; ++i) {
if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; }
if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }
}
}
// this has been repurposed so y is now the original index instead of y
typedef struct
{
uint16 x,id;
} stbv__floor_ordering;
static int STBV_CDECL point_compare(const void *p, const void *q)
{
stbv__floor_ordering *a = (stbv__floor_ordering *) p;
stbv__floor_ordering *b = (stbv__floor_ordering *) q;
return a->x < b->x ? -1 : a->x > b->x;
}
//
/////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////
#if defined(STB_VORBIS_NO_STDIO)
#define USE_MEMORY(z) TRUE
#else
#define USE_MEMORY(z) ((z)->stream)
#endif
static uint8 get8(vorb *z)
{
if (USE_MEMORY(z)) {
if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; }
return *z->stream++;
}
#ifndef STB_VORBIS_NO_STDIO
{
int c = fgetc(z->f);
if (c == EOF) { z->eof = TRUE; return 0; }
return c;
}
#endif
}
static uint32 get32(vorb *f)
{
uint32 x;
x = get8(f);
x += get8(f) << 8;
x += get8(f) << 16;
x += (uint32) get8(f) << 24;
return x;
}
static int getn(vorb *z, uint8 *data, int n)
{
if (USE_MEMORY(z)) {
if (z->stream+n > z->stream_end) { z->eof = 1; return 0; }
memcpy(data, z->stream, n);
z->stream += n;
return 1;
}
#ifndef STB_VORBIS_NO_STDIO
if (fread(data, n, 1, z->f) == 1)
return 1;
else {
z->eof = 1;
return 0;
}
#endif
}
static void skip(vorb *z, int n)
{
if (USE_MEMORY(z)) {
z->stream += n;
if (z->stream >= z->stream_end) z->eof = 1;
return;
}
#ifndef STB_VORBIS_NO_STDIO
{
long x = ftell(z->f);
fseek(z->f, x+n, SEEK_SET);
}
#endif
}
static int set_file_offset(stb_vorbis *f, unsigned int loc)
{
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (f->push_mode) return 0;
#endif
f->eof = 0;
if (USE_MEMORY(f)) {
if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) {
f->stream = f->stream_end;
f->eof = 1;
return 0;
} else {
f->stream = f->stream_start + loc;
return 1;
}
}
#ifndef STB_VORBIS_NO_STDIO
if (loc + f->f_start < loc || loc >= 0x80000000) {
loc = 0x7fffffff;
f->eof = 1;
} else {
loc += f->f_start;
}
if (!fseek(f->f, loc, SEEK_SET))
return 1;
f->eof = 1;
fseek(f->f, f->f_start, SEEK_END);
return 0;
#endif
}
static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 };
static int capture_pattern(vorb *f)
{
if (0x4f != get8(f)) return FALSE;
if (0x67 != get8(f)) return FALSE;
if (0x67 != get8(f)) return FALSE;
if (0x53 != get8(f)) return FALSE;
return TRUE;
}
#define PAGEFLAG_continued_packet 1
#define PAGEFLAG_first_page 2
#define PAGEFLAG_last_page 4
static int start_page_no_capturepattern(vorb *f)
{
uint32 loc0,loc1,n;
// stream structure version
if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version);
// header flag
f->page_flag = get8(f);
// absolute granule position
loc0 = get32(f);
loc1 = get32(f);
// @TODO: validate loc0,loc1 as valid positions?
// stream serial number -- vorbis doesn't interleave, so discard
get32(f);
//if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number);
// page sequence number
n = get32(f);
f->last_page = n;
// CRC32
get32(f);
// page_segments
f->segment_count = get8(f);
if (!getn(f, f->segments, f->segment_count))
return error(f, VORBIS_unexpected_eof);
// assume we _don't_ know any the sample position of any segments
f->end_seg_with_known_loc = -2;
if (loc0 != ~0U || loc1 != ~0U) {
int i;
// determine which packet is the last one that will complete
for (i=f->segment_count-1; i >= 0; --i)
if (f->segments[i] < 255)
break;
// 'i' is now the index of the _last_ segment of a packet that ends
if (i >= 0) {
f->end_seg_with_known_loc = i;
f->known_loc_for_packet = loc0;
}
}
if (f->first_decode) {
int i,len;
ProbedPage p;
len = 0;
for (i=0; i < f->segment_count; ++i)
len += f->segments[i];
len += 27 + f->segment_count;
p.page_start = f->first_audio_page_offset;
p.page_end = p.page_start + len;
p.last_decoded_sample = loc0;
f->p_first = p;
}
f->next_seg = 0;
return TRUE;
}
static int start_page(vorb *f)
{
if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern);
return start_page_no_capturepattern(f);
}
static int start_packet(vorb *f)
{
while (f->next_seg == -1) {
if (!start_page(f)) return FALSE;
if (f->page_flag & PAGEFLAG_continued_packet)
return error(f, VORBIS_continued_packet_flag_invalid);
}
f->last_seg = FALSE;
f->valid_bits = 0;
f->packet_bytes = 0;
f->bytes_in_seg = 0;
// f->next_seg is now valid
return TRUE;
}
static int maybe_start_packet(vorb *f)
{
if (f->next_seg == -1) {
int x = get8(f);
if (f->eof) return FALSE; // EOF at page boundary is not an error!
if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern);
if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
if (!start_page_no_capturepattern(f)) return FALSE;
if (f->page_flag & PAGEFLAG_continued_packet) {
// set up enough state that we can read this packet if we want,
// e.g. during recovery
f->last_seg = FALSE;
f->bytes_in_seg = 0;
return error(f, VORBIS_continued_packet_flag_invalid);
}
}
return start_packet(f);
}
static int next_segment(vorb *f)
{
int len;
if (f->last_seg) return 0;
if (f->next_seg == -1) {
f->last_seg_which = f->segment_count-1; // in case start_page fails
if (!start_page(f)) { f->last_seg = 1; return 0; }
if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid);
}
len = f->segments[f->next_seg++];
if (len < 255) {
f->last_seg = TRUE;
f->last_seg_which = f->next_seg-1;
}
if (f->next_seg >= f->segment_count)
f->next_seg = -1;
assert(f->bytes_in_seg == 0);
f->bytes_in_seg = len;
return len;
}
#define EOP (-1)
#define INVALID_BITS (-1)
static int get8_packet_raw(vorb *f)
{
if (!f->bytes_in_seg) { // CLANG!
if (f->last_seg) return EOP;
else if (!next_segment(f)) return EOP;
}
assert(f->bytes_in_seg > 0);
--f->bytes_in_seg;
++f->packet_bytes;
return get8(f);
}
static int get8_packet(vorb *f)
{
int x = get8_packet_raw(f);
f->valid_bits = 0;
return x;
}
static void flush_packet(vorb *f)
{
while (get8_packet_raw(f) != EOP);
}
// @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important
// as the huffman decoder?
static uint32 get_bits(vorb *f, int n)
{
uint32 z;
if (f->valid_bits < 0) return 0;
if (f->valid_bits < n) {
if (n > 24) {
// the accumulator technique below would not work correctly in this case
z = get_bits(f, 24);
z += get_bits(f, n-24) << 24;
return z;
}
if (f->valid_bits == 0) f->acc = 0;
while (f->valid_bits < n) {
int z = get8_packet_raw(f);
if (z == EOP) {
f->valid_bits = INVALID_BITS;
return 0;
}
f->acc += z << f->valid_bits;
f->valid_bits += 8;
}
}
if (f->valid_bits < 0) return 0;
z = f->acc & ((1 << n)-1);
f->acc >>= n;
f->valid_bits -= n;
return z;
}
// @OPTIMIZE: primary accumulator for huffman
// expand the buffer to as many bits as possible without reading off end of packet
// it might be nice to allow f->valid_bits and f->acc to be stored in registers,
// e.g. cache them locally and decode locally
static __forceinline void prep_huffman(vorb *f)
{
if (f->valid_bits <= 24) {
if (f->valid_bits == 0) f->acc = 0;
do {
int z;
if (f->last_seg && !f->bytes_in_seg) return;
z = get8_packet_raw(f);
if (z == EOP) return;
f->acc += (unsigned) z << f->valid_bits;
f->valid_bits += 8;
} while (f->valid_bits <= 24);
}
}
enum
{
VORBIS_packet_id = 1,
VORBIS_packet_comment = 3,
VORBIS_packet_setup = 5
};
static int codebook_decode_scalar_raw(vorb *f, Codebook *c)
{
int i;
prep_huffman(f);
if (c->codewords == NULL && c->sorted_codewords == NULL)
return -1;
// cases to use binary search: sorted_codewords && !c->codewords
// sorted_codewords && c->entries > 8
if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) {
// binary search
uint32 code = bit_reverse(f->acc);
int x=0, n=c->sorted_entries, len;
while (n > 1) {
// invariant: sc[x] <= code < sc[x+n]
int m = x + (n >> 1);
if (c->sorted_codewords[m] <= code) {
x = m;
n -= (n>>1);
} else {
n >>= 1;
}
}
// x is now the sorted index
if (!c->sparse) x = c->sorted_values[x];
// x is now sorted index if sparse, or symbol otherwise
len = c->codeword_lengths[x];
if (f->valid_bits >= len) {
f->acc >>= len;
f->valid_bits -= len;
return x;
}
f->valid_bits = 0;
return -1;
}
// if small, linear search
assert(!c->sparse);
for (i=0; i < c->entries; ++i) {
if (c->codeword_lengths[i] == NO_CODE) continue;
if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) {
if (f->valid_bits >= c->codeword_lengths[i]) {
f->acc >>= c->codeword_lengths[i];
f->valid_bits -= c->codeword_lengths[i];
return i;
}
f->valid_bits = 0;
return -1;
}
}
error(f, VORBIS_invalid_stream);
f->valid_bits = 0;
return -1;
}
#ifndef STB_VORBIS_NO_INLINE_DECODE
#define DECODE_RAW(var, f,c) \
if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \
prep_huffman(f); \
var = f->acc & FAST_HUFFMAN_TABLE_MASK; \
var = c->fast_huffman[var]; \
if (var >= 0) { \
int n = c->codeword_lengths[var]; \
f->acc >>= n; \
f->valid_bits -= n; \
if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \
} else { \
var = codebook_decode_scalar_raw(f,c); \
}
#else
static int codebook_decode_scalar(vorb *f, Codebook *c)
{
int i;
if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH)
prep_huffman(f);
// fast huffman table lookup
i = f->acc & FAST_HUFFMAN_TABLE_MASK;
i = c->fast_huffman[i];
if (i >= 0) {
f->acc >>= c->codeword_lengths[i];
f->valid_bits -= c->codeword_lengths[i];
if (f->valid_bits < 0) { f->valid_bits = 0; return -1; }
return i;
}
return codebook_decode_scalar_raw(f,c);
}
#define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c);
#endif
#define DECODE(var,f,c) \
DECODE_RAW(var,f,c) \
if (c->sparse) var = c->sorted_values[var];
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
#define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c)
#else
#define DECODE_VQ(var,f,c) DECODE(var,f,c)
#endif
// CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case
// where we avoid one addition
#define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off])
#define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off])
#define CODEBOOK_ELEMENT_BASE(c) (0)
static int codebook_decode_start(vorb *f, Codebook *c)
{
int z = -1;
// type 0 is only legal in a scalar context
if (c->lookup_type == 0)
error(f, VORBIS_invalid_stream);
else {
DECODE_VQ(z,f,c);
if (c->sparse) assert(z < c->sorted_entries);
if (z < 0) { // check for EOP
if (!f->bytes_in_seg)
if (f->last_seg)
return z;
error(f, VORBIS_invalid_stream);
}
}
return z;
}
static int codebook_decode(vorb *f, Codebook *c, float *output, int len)
{
int i,z = codebook_decode_start(f,c);
if (z < 0) return FALSE;
if (len > c->dimensions) len = c->dimensions;
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
float last = CODEBOOK_ELEMENT_BASE(c);
int div = 1;
for (i=0; i < len; ++i) {
int off = (z / div) % c->lookup_values;
float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
output[i] += val;
if (c->sequence_p) last = val + c->minimum_value;
div *= c->lookup_values;
}
return TRUE;
}
#endif
z *= c->dimensions;
if (c->sequence_p) {
float last = CODEBOOK_ELEMENT_BASE(c);
for (i=0; i < len; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
output[i] += val;
last = val + c->minimum_value;
}
} else {
float last = CODEBOOK_ELEMENT_BASE(c);
for (i=0; i < len; ++i) {
output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;
}
}
return TRUE;
}
static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step)
{
int i,z = codebook_decode_start(f,c);
float last = CODEBOOK_ELEMENT_BASE(c);
if (z < 0) return FALSE;
if (len > c->dimensions) len = c->dimensions;
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int div = 1;
for (i=0; i < len; ++i) {
int off = (z / div) % c->lookup_values;
float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
output[i*step] += val;
if (c->sequence_p) last = val;
div *= c->lookup_values;
}
return TRUE;
}
#endif
z *= c->dimensions;
for (i=0; i < len; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
output[i*step] += val;
if (c->sequence_p) last = val;
}
return TRUE;
}
static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode)
{
int c_inter = *c_inter_p;
int p_inter = *p_inter_p;
int i,z, effective = c->dimensions;
// type 0 is only legal in a scalar context
if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);
while (total_decode > 0) {
float last = CODEBOOK_ELEMENT_BASE(c);
DECODE_VQ(z,f,c);
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
assert(!c->sparse || z < c->sorted_entries);
#endif
if (z < 0) {
if (!f->bytes_in_seg)
if (f->last_seg) return FALSE;
return error(f, VORBIS_invalid_stream);
}
// if this will take us off the end of the buffers, stop short!
// we check by computing the length of the virtual interleaved
// buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),
// and the length we'll be using (effective)
if (c_inter + p_inter*ch + effective > len * ch) {
effective = len*ch - (p_inter*ch - c_inter);
}
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int div = 1;
for (i=0; i < effective; ++i) {
int off = (z / div) % c->lookup_values;
float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
if (outputs[c_inter])
outputs[c_inter][p_inter] += val;
if (++c_inter == ch) { c_inter = 0; ++p_inter; }
if (c->sequence_p) last = val;
div *= c->lookup_values;
}
} else
#endif
{
z *= c->dimensions;
if (c->sequence_p) {
for (i=0; i < effective; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
if (outputs[c_inter])
outputs[c_inter][p_inter] += val;
if (++c_inter == ch) { c_inter = 0; ++p_inter; }
last = val;
}
} else {
for (i=0; i < effective; ++i) {
float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
if (outputs[c_inter])
outputs[c_inter][p_inter] += val;
if (++c_inter == ch) { c_inter = 0; ++p_inter; }
}
}
}
total_decode -= effective;
}
*c_inter_p = c_inter;
*p_inter_p = p_inter;
return TRUE;
}
static int predict_point(int x, int x0, int x1, int y0, int y1)
{
int dy = y1 - y0;
int adx = x1 - x0;
// @OPTIMIZE: force int division to round in the right direction... is this necessary on x86?
int err = abs(dy) * (x - x0);
int off = err / adx;
return dy < 0 ? y0 - off : y0 + off;
}
// the following table is block-copied from the specification
static float inverse_db_table[256] =
{
1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f,
1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f,
1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f,
2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f,
2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f,
3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f,
4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f,
6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f,
7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f,
1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f,
1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f,
1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f,
2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f,
2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f,
3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f,
4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f,
5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f,
7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f,
9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f,
1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f,
1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f,
2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f,
2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f,
3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f,
4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f,
5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f,
7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f,
9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f,
0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f,
0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f,
0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f,
0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f,
0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f,
0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f,
0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f,
0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f,
0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f,
0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f,
0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f,
0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f,
0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f,
0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f,
0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f,
0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f,
0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f,
0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f,
0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f,
0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f,
0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f,
0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f,
0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f,
0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f,
0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f,
0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f,
0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f,
0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f,
0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f,
0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f,
0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f,
0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f,
0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f,
0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f,
0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f,
0.82788260f, 0.88168307f, 0.9389798f, 1.0f
};
// @OPTIMIZE: if you want to replace this bresenham line-drawing routine,
// note that you must produce bit-identical output to decode correctly;
// this specific sequence of operations is specified in the spec (it's
// drawing integer-quantized frequency-space lines that the encoder
// expects to be exactly the same)
// ... also, isn't the whole point of Bresenham's algorithm to NOT
// have to divide in the setup? sigh.
#ifndef STB_VORBIS_NO_DEFER_FLOOR
#define LINE_OP(a,b) a *= b
#else
#define LINE_OP(a,b) a = b
#endif
#ifdef STB_VORBIS_DIVIDE_TABLE
#define DIVTAB_NUMER 32
#define DIVTAB_DENOM 64
int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB
#endif
static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
{
int dy = y1 - y0;
int adx = x1 - x0;
int ady = abs(dy);
int base;
int x=x0,y=y0;
int err = 0;
int sy;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
if (dy < 0) {
base = -integer_divide_table[ady][adx];
sy = base-1;
} else {
base = integer_divide_table[ady][adx];
sy = base+1;
}
} else {
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
}
#else
base = dy / adx;
if (dy < 0)
sy = base - 1;
else
sy = base+1;
#endif
ady -= abs(base) * adx;
if (x1 > n) x1 = n;
if (x < x1) {
LINE_OP(output[x], inverse_db_table[y&255]);
for (++x; x < x1; ++x) {
err += ady;
if (err >= adx) {
err -= adx;
y += sy;
} else
y += base;
LINE_OP(output[x], inverse_db_table[y&255]);
}
}
}
static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype)
{
int k;
if (rtype == 0) {
int step = n / book->dimensions;
for (k=0; k < step; ++k)
if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step))
return FALSE;
} else {
for (k=0; k < n; ) {
if (!codebook_decode(f, book, target+offset, n-k))
return FALSE;
k += book->dimensions;
offset += book->dimensions;
}
}
return TRUE;
}
// n is 1/2 of the blocksize --
// specification: "Correct per-vector decode length is [n]/2"
static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode)
{
int i,j,pass;
Residue *r = f->residue_config + rn;
int rtype = f->residue_types[rn];
int c = r->classbook;
int classwords = f->codebooks[c].dimensions;
unsigned int actual_size = rtype == 2 ? n*2 : n;
unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size);
unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size);
int n_read = limit_r_end - limit_r_begin;
int part_read = n_read / r->part_size;
int temp_alloc_point = temp_alloc_save(f);
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata));
#else
int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications));
#endif
CHECK(f);
for (i=0; i < ch; ++i)
if (!do_not_decode[i])
memset(residue_buffers[i], 0, sizeof(float) * n);
if (rtype == 2 && ch != 1) {
for (j=0; j < ch; ++j)
if (!do_not_decode[j])
break;
if (j == ch)
goto done;
for (pass=0; pass < 8; ++pass) {
int pcount = 0, class_set = 0;
if (ch == 2) {
while (pcount < part_read) {
int z = r->begin + pcount*r->part_size;
int c_inter = (z & 1), p_inter = z>>1;
if (pass == 0) {
Codebook *c = f->codebooks+r->classbook;
int q;
DECODE(q,f,c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[0][i+pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount*r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
Codebook *book = f->codebooks + b;
#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
#else
// saves 1%
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
#endif
} else {
z += r->part_size;
c_inter = z & 1;
p_inter = z >> 1;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
} else if (ch == 1) {
while (pcount < part_read) {
int z = r->begin + pcount*r->part_size;
int c_inter = 0, p_inter = z;
if (pass == 0) {
Codebook *c = f->codebooks+r->classbook;
int q;
DECODE(q,f,c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[0][i+pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount*r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
Codebook *book = f->codebooks + b;
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
} else {
z += r->part_size;
c_inter = 0;
p_inter = z;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
} else {
while (pcount < part_read) {
int z = r->begin + pcount*r->part_size;
int c_inter = z % ch, p_inter = z/ch;
if (pass == 0) {
Codebook *c = f->codebooks+r->classbook;
int q;
DECODE(q,f,c);
if (q == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[0][class_set] = r->classdata[q];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[0][i+pcount] = q % r->classifications;
q /= r->classifications;
}
#endif
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
int z = r->begin + pcount*r->part_size;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[0][class_set][i];
#else
int c = classifications[0][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
Codebook *book = f->codebooks + b;
if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
goto done;
} else {
z += r->part_size;
c_inter = z % ch;
p_inter = z / ch;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
}
}
goto done;
}
CHECK(f);
for (pass=0; pass < 8; ++pass) {
int pcount = 0, class_set=0;
while (pcount < part_read) {
if (pass == 0) {
for (j=0; j < ch; ++j) {
if (!do_not_decode[j]) {
Codebook *c = f->codebooks+r->classbook;
int temp;
DECODE(temp,f,c);
if (temp == EOP) goto done;
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
part_classdata[j][class_set] = r->classdata[temp];
#else
for (i=classwords-1; i >= 0; --i) {
classifications[j][i+pcount] = temp % r->classifications;
temp /= r->classifications;
}
#endif
}
}
}
for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
for (j=0; j < ch; ++j) {
if (!do_not_decode[j]) {
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
int c = part_classdata[j][class_set][i];
#else
int c = classifications[j][pcount];
#endif
int b = r->residue_books[c][pass];
if (b >= 0) {
float *target = residue_buffers[j];
int offset = r->begin + pcount * r->part_size;
int n = r->part_size;
Codebook *book = f->codebooks + b;
if (!residue_decode(f, book, target, offset, n, rtype))
goto done;
}
}
}
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
++class_set;
#endif
}
}
done:
CHECK(f);
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
temp_free(f,part_classdata);
#else
temp_free(f,classifications);
#endif
temp_alloc_restore(f,temp_alloc_point);
}
#if 0
// slow way for debugging
void inverse_mdct_slow(float *buffer, int n)
{
int i,j;
int n2 = n >> 1;
float *x = (float *) malloc(sizeof(*x) * n2);
memcpy(x, buffer, sizeof(*x) * n2);
for (i=0; i < n; ++i) {
float acc = 0;
for (j=0; j < n2; ++j)
// formula from paper:
//acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
// formula from wikipedia
//acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
// these are equivalent, except the formula from the paper inverts the multiplier!
// however, what actually works is NO MULTIPLIER!?!
//acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
buffer[i] = acc;
}
free(x);
}
#elif 0
// same as above, but just barely able to run in real time on modern machines
void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
{
float mcos[16384];
int i,j;
int n2 = n >> 1, nmask = (n << 2) -1;
float *x = (float *) malloc(sizeof(*x) * n2);
memcpy(x, buffer, sizeof(*x) * n2);
for (i=0; i < 4*n; ++i)
mcos[i] = (float) cos(M_PI / 2 * i / n);
for (i=0; i < n; ++i) {
float acc = 0;
for (j=0; j < n2; ++j)
acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask];
buffer[i] = acc;
}
free(x);
}
#elif 0
// transform to use a slow dct-iv; this is STILL basically trivial,
// but only requires half as many ops
void dct_iv_slow(float *buffer, int n)
{
float mcos[16384];
float x[2048];
int i,j;
int n2 = n >> 1, nmask = (n << 3) - 1;
memcpy(x, buffer, sizeof(*x) * n);
for (i=0; i < 8*n; ++i)
mcos[i] = (float) cos(M_PI / 4 * i / n);
for (i=0; i < n; ++i) {
float acc = 0;
for (j=0; j < n; ++j)
acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask];
buffer[i] = acc;
}
}
void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
{
int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4;
float temp[4096];
memcpy(temp, buffer, n2 * sizeof(float));
dct_iv_slow(temp, n2); // returns -c'-d, a-b'
for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b'
for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d'
for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d
}
#endif
#ifndef LIBVORBIS_MDCT
#define LIBVORBIS_MDCT 0
#endif
#if LIBVORBIS_MDCT
// directly call the vorbis MDCT using an interface documented
// by Jeff Roberts... useful for performance comparison
typedef struct
{
int n;
int log2n;
float *trig;
int *bitrev;
float scale;
} mdct_lookup;
extern void mdct_init(mdct_lookup *lookup, int n);
extern void mdct_clear(mdct_lookup *l);
extern void mdct_backward(mdct_lookup *init, float *in, float *out);
mdct_lookup M1,M2;
void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
{
mdct_lookup *M;
if (M1.n == n) M = &M1;
else if (M2.n == n) M = &M2;
else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; }
else {
if (M2.n) __asm int 3;
mdct_init(&M2, n);
M = &M2;
}
mdct_backward(M, buffer, buffer);
}
#endif
// the following were split out into separate functions while optimizing;
// they could be pushed back up but eh. __forceinline showed no change;
// they're probably already being inlined.
static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A)
{
float *ee0 = e + i_off;
float *ee2 = ee0 + k_off;
int i;
assert((n & 3) == 0);
for (i=(n>>2); i > 0; --i) {
float k00_20, k01_21;
k00_20 = ee0[ 0] - ee2[ 0];
k01_21 = ee0[-1] - ee2[-1];
ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0];
ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1];
ee2[ 0] = k00_20 * A[0] - k01_21 * A[1];
ee2[-1] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
k00_20 = ee0[-2] - ee2[-2];
k01_21 = ee0[-3] - ee2[-3];
ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2];
ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3];
ee2[-2] = k00_20 * A[0] - k01_21 * A[1];
ee2[-3] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
k00_20 = ee0[-4] - ee2[-4];
k01_21 = ee0[-5] - ee2[-5];
ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4];
ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5];
ee2[-4] = k00_20 * A[0] - k01_21 * A[1];
ee2[-5] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
k00_20 = ee0[-6] - ee2[-6];
k01_21 = ee0[-7] - ee2[-7];
ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6];
ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7];
ee2[-6] = k00_20 * A[0] - k01_21 * A[1];
ee2[-7] = k01_21 * A[0] + k00_20 * A[1];
A += 8;
ee0 -= 8;
ee2 -= 8;
}
}
static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1)
{
int i;
float k00_20, k01_21;
float *e0 = e + d0;
float *e2 = e0 + k_off;
for (i=lim >> 2; i > 0; --i) {
k00_20 = e0[-0] - e2[-0];
k01_21 = e0[-1] - e2[-1];
e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0];
e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1];
e2[-0] = (k00_20)*A[0] - (k01_21) * A[1];
e2[-1] = (k01_21)*A[0] + (k00_20) * A[1];
A += k1;
k00_20 = e0[-2] - e2[-2];
k01_21 = e0[-3] - e2[-3];
e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2];
e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3];
e2[-2] = (k00_20)*A[0] - (k01_21) * A[1];
e2[-3] = (k01_21)*A[0] + (k00_20) * A[1];
A += k1;
k00_20 = e0[-4] - e2[-4];
k01_21 = e0[-5] - e2[-5];
e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4];
e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5];
e2[-4] = (k00_20)*A[0] - (k01_21) * A[1];
e2[-5] = (k01_21)*A[0] + (k00_20) * A[1];
A += k1;
k00_20 = e0[-6] - e2[-6];
k01_21 = e0[-7] - e2[-7];
e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6];
e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7];
e2[-6] = (k00_20)*A[0] - (k01_21) * A[1];
e2[-7] = (k01_21)*A[0] + (k00_20) * A[1];
e0 -= 8;
e2 -= 8;
A += k1;
}
}
static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0)
{
int i;
float A0 = A[0];
float A1 = A[0+1];
float A2 = A[0+a_off];
float A3 = A[0+a_off+1];
float A4 = A[0+a_off*2+0];
float A5 = A[0+a_off*2+1];
float A6 = A[0+a_off*3+0];
float A7 = A[0+a_off*3+1];
float k00,k11;
float *ee0 = e +i_off;
float *ee2 = ee0+k_off;
for (i=n; i > 0; --i) {
k00 = ee0[ 0] - ee2[ 0];
k11 = ee0[-1] - ee2[-1];
ee0[ 0] = ee0[ 0] + ee2[ 0];
ee0[-1] = ee0[-1] + ee2[-1];
ee2[ 0] = (k00) * A0 - (k11) * A1;
ee2[-1] = (k11) * A0 + (k00) * A1;
k00 = ee0[-2] - ee2[-2];
k11 = ee0[-3] - ee2[-3];
ee0[-2] = ee0[-2] + ee2[-2];
ee0[-3] = ee0[-3] + ee2[-3];
ee2[-2] = (k00) * A2 - (k11) * A3;
ee2[-3] = (k11) * A2 + (k00) * A3;
k00 = ee0[-4] - ee2[-4];
k11 = ee0[-5] - ee2[-5];
ee0[-4] = ee0[-4] + ee2[-4];
ee0[-5] = ee0[-5] + ee2[-5];
ee2[-4] = (k00) * A4 - (k11) * A5;
ee2[-5] = (k11) * A4 + (k00) * A5;
k00 = ee0[-6] - ee2[-6];
k11 = ee0[-7] - ee2[-7];
ee0[-6] = ee0[-6] + ee2[-6];
ee0[-7] = ee0[-7] + ee2[-7];
ee2[-6] = (k00) * A6 - (k11) * A7;
ee2[-7] = (k11) * A6 + (k00) * A7;
ee0 -= k0;
ee2 -= k0;
}
}
static __forceinline void iter_54(float *z)
{
float k00,k11,k22,k33;
float y0,y1,y2,y3;
k00 = z[ 0] - z[-4];
y0 = z[ 0] + z[-4];
y2 = z[-2] + z[-6];
k22 = z[-2] - z[-6];
z[-0] = y0 + y2; // z0 + z4 + z2 + z6
z[-2] = y0 - y2; // z0 + z4 - z2 - z6
// done with y0,y2
k33 = z[-3] - z[-7];
z[-4] = k00 + k33; // z0 - z4 + z3 - z7
z[-6] = k00 - k33; // z0 - z4 - z3 + z7
// done with k33
k11 = z[-1] - z[-5];
y1 = z[-1] + z[-5];
y3 = z[-3] + z[-7];
z[-1] = y1 + y3; // z1 + z5 + z3 + z7
z[-3] = y1 - y3; // z1 + z5 - z3 - z7
z[-5] = k11 - k22; // z1 - z5 + z2 - z6
z[-7] = k11 + k22; // z1 - z5 - z2 + z6
}
static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n)
{
int a_off = base_n >> 3;
float A2 = A[0+a_off];
float *z = e + i_off;
float *base = z - 16 * n;
while (z > base) {
float k00,k11;
k00 = z[-0] - z[-8];
k11 = z[-1] - z[-9];
z[-0] = z[-0] + z[-8];
z[-1] = z[-1] + z[-9];
z[-8] = k00;
z[-9] = k11 ;
k00 = z[ -2] - z[-10];
k11 = z[ -3] - z[-11];
z[ -2] = z[ -2] + z[-10];
z[ -3] = z[ -3] + z[-11];
z[-10] = (k00+k11) * A2;
z[-11] = (k11-k00) * A2;
k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation
k11 = z[ -5] - z[-13];
z[ -4] = z[ -4] + z[-12];
z[ -5] = z[ -5] + z[-13];
z[-12] = k11;
z[-13] = k00;
k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation
k11 = z[ -7] - z[-15];
z[ -6] = z[ -6] + z[-14];
z[ -7] = z[ -7] + z[-15];
z[-14] = (k00+k11) * A2;
z[-15] = (k00-k11) * A2;
iter_54(z);
iter_54(z-8);
z -= 16;
}
}
static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
{
int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
int ld;
// @OPTIMIZE: reduce register pressure by using fewer variables?
int save_point = temp_alloc_save(f);
float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2));
float *u=NULL,*v=NULL;
// twiddle factors
float *A = f->A[blocktype];
// IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
// See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function.
// kernel from paper
// merged:
// copy and reflect spectral data
// step 0
// note that it turns out that the items added together during
// this step are, in fact, being added to themselves (as reflected
// by step 0). inexplicable inefficiency! this became obvious
// once I combined the passes.
// so there's a missing 'times 2' here (for adding X to itself).
// this propagates through linearly to the end, where the numbers
// are 1/2 too small, and need to be compensated for.
{
float *d,*e, *AA, *e_stop;
d = &buf2[n2-2];
AA = A;
e = &buffer[0];
e_stop = &buffer[n2];
while (e != e_stop) {
d[1] = (e[0] * AA[0] - e[2]*AA[1]);
d[0] = (e[0] * AA[1] + e[2]*AA[0]);
d -= 2;
AA += 2;
e += 4;
}
e = &buffer[n2-3];
while (d >= buf2) {
d[1] = (-e[2] * AA[0] - -e[0]*AA[1]);
d[0] = (-e[2] * AA[1] + -e[0]*AA[0]);
d -= 2;
AA += 2;
e -= 4;
}
}
// now we use symbolic names for these, so that we can
// possibly swap their meaning as we change which operations
// are in place
u = buffer;
v = buf2;
// step 2 (paper output is w, now u)
// this could be in place, but the data ends up in the wrong
// place... _somebody_'s got to swap it, so this is nominated
{
float *AA = &A[n2-8];
float *d0,*d1, *e0, *e1;
e0 = &v[n4];
e1 = &v[0];
d0 = &u[n4];
d1 = &u[0];
while (AA >= A) {
float v40_20, v41_21;
v41_21 = e0[1] - e1[1];
v40_20 = e0[0] - e1[0];
d0[1] = e0[1] + e1[1];
d0[0] = e0[0] + e1[0];
d1[1] = v41_21*AA[4] - v40_20*AA[5];
d1[0] = v40_20*AA[4] + v41_21*AA[5];
v41_21 = e0[3] - e1[3];
v40_20 = e0[2] - e1[2];
d0[3] = e0[3] + e1[3];
d0[2] = e0[2] + e1[2];
d1[3] = v41_21*AA[0] - v40_20*AA[1];
d1[2] = v40_20*AA[0] + v41_21*AA[1];
AA -= 8;
d0 += 4;
d1 += 4;
e0 += 4;
e1 += 4;
}
}
// step 3
ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
// optimized step 3:
// the original step3 loop can be nested r inside s or s inside r;
// it's written originally as s inside r, but this is dumb when r
// iterates many times, and s few. So I have two copies of it and
// switch between them halfway.
// this is iteration 0 of step 3
imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A);
imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A);
// this is iteration 1 of step 3
imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16);
imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16);
imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16);
imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16);
l=2;
for (; l < (ld-3)>>1; ++l) {
int k0 = n >> (l+2), k0_2 = k0>>1;
int lim = 1 << (l+1);
int i;
for (i=0; i < lim; ++i)
imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3));
}
for (; l < ld-6; ++l) {
int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1;
int rlim = n >> (l+6), r;
int lim = 1 << (l+1);
int i_off;
float *A0 = A;
i_off = n2-1;
for (r=rlim; r > 0; --r) {
imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0);
A0 += k1*4;
i_off -= 8;
}
}
// iterations with count:
// ld-6,-5,-4 all interleaved together
// the big win comes from getting rid of needless flops
// due to the constants on pass 5 & 4 being all 1 and 0;
// combining them to be simultaneous to improve cache made little difference
imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n);
// output is u
// step 4, 5, and 6
// cannot be in-place because of step 5
{
uint16 *bitrev = f->bit_reverse[blocktype];
// weirdly, I'd have thought reading sequentially and writing
// erratically would have been better than vice-versa, but in
// fact that's not what my testing showed. (That is, with
// j = bitreverse(i), do you read i and write j, or read j and write i.)
float *d0 = &v[n4-4];
float *d1 = &v[n2-4];
while (d0 >= v) {
int k4;
k4 = bitrev[0];
d1[3] = u[k4+0];
d1[2] = u[k4+1];
d0[3] = u[k4+2];
d0[2] = u[k4+3];
k4 = bitrev[1];
d1[1] = u[k4+0];
d1[0] = u[k4+1];
d0[1] = u[k4+2];
d0[0] = u[k4+3];
d0 -= 4;
d1 -= 4;
bitrev += 2;
}
}
// (paper output is u, now v)
// data must be in buf2
assert(v == buf2);
// step 7 (paper output is v, now v)
// this is now in place
{
float *C = f->C[blocktype];
float *d, *e;
d = v;
e = v + n2 - 4;
while (d < e) {
float a02,a11,b0,b1,b2,b3;
a02 = d[0] - e[2];
a11 = d[1] + e[3];
b0 = C[1]*a02 + C[0]*a11;
b1 = C[1]*a11 - C[0]*a02;
b2 = d[0] + e[ 2];
b3 = d[1] - e[ 3];
d[0] = b2 + b0;
d[1] = b3 + b1;
e[2] = b2 - b0;
e[3] = b1 - b3;
a02 = d[2] - e[0];
a11 = d[3] + e[1];
b0 = C[3]*a02 + C[2]*a11;
b1 = C[3]*a11 - C[2]*a02;
b2 = d[2] + e[ 0];
b3 = d[3] - e[ 1];
d[2] = b2 + b0;
d[3] = b3 + b1;
e[0] = b2 - b0;
e[1] = b1 - b3;
C += 4;
d += 4;
e -= 4;
}
}
// data must be in buf2
// step 8+decode (paper output is X, now buffer)
// this generates pairs of data a la 8 and pushes them directly through
// the decode kernel (pushing rather than pulling) to avoid having
// to make another pass later
// this cannot POSSIBLY be in place, so we refer to the buffers directly
{
float *d0,*d1,*d2,*d3;
float *B = f->B[blocktype] + n2 - 8;
float *e = buf2 + n2 - 8;
d0 = &buffer[0];
d1 = &buffer[n2-4];
d2 = &buffer[n2];
d3 = &buffer[n-4];
while (e >= v) {
float p0,p1,p2,p3;
p3 = e[6]*B[7] - e[7]*B[6];
p2 = -e[6]*B[6] - e[7]*B[7];
d0[0] = p3;
d1[3] = - p3;
d2[0] = p2;
d3[3] = p2;
p1 = e[4]*B[5] - e[5]*B[4];
p0 = -e[4]*B[4] - e[5]*B[5];
d0[1] = p1;
d1[2] = - p1;
d2[1] = p0;
d3[2] = p0;
p3 = e[2]*B[3] - e[3]*B[2];
p2 = -e[2]*B[2] - e[3]*B[3];
d0[2] = p3;
d1[1] = - p3;
d2[2] = p2;
d3[1] = p2;
p1 = e[0]*B[1] - e[1]*B[0];
p0 = -e[0]*B[0] - e[1]*B[1];
d0[3] = p1;
d1[0] = - p1;
d2[3] = p0;
d3[0] = p0;
B -= 8;
e -= 8;
d0 += 4;
d2 += 4;
d1 -= 4;
d3 -= 4;
}
}
temp_free(f,buf2);
temp_alloc_restore(f,save_point);
}
#if 0
// this is the original version of the above code, if you want to optimize it from scratch
void inverse_mdct_naive(float *buffer, int n)
{
float s;
float A[1 << 12], B[1 << 12], C[1 << 11];
int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
int n3_4 = n - n4, ld;
// how can they claim this only uses N words?!
// oh, because they're only used sparsely, whoops
float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13];
// set up twiddle factors
for (k=k2=0; k < n4; ++k,k2+=2) {
A[k2 ] = (float) cos(4*k*M_PI/n);
A[k2+1] = (float) -sin(4*k*M_PI/n);
B[k2 ] = (float) cos((k2+1)*M_PI/n/2);
B[k2+1] = (float) sin((k2+1)*M_PI/n/2);
}
for (k=k2=0; k < n8; ++k,k2+=2) {
C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
}
// IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
// Note there are bugs in that pseudocode, presumably due to them attempting
// to rename the arrays nicely rather than representing the way their actual
// implementation bounces buffers back and forth. As a result, even in the
// "some formulars corrected" version, a direct implementation fails. These
// are noted below as "paper bug".
// copy and reflect spectral data
for (k=0; k < n2; ++k) u[k] = buffer[k];
for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1];
// kernel from paper
// step 1
for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) {
v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1];
v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2];
}
// step 2
for (k=k4=0; k < n8; k+=1, k4+=4) {
w[n2+3+k4] = v[n2+3+k4] + v[k4+3];
w[n2+1+k4] = v[n2+1+k4] + v[k4+1];
w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4];
w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4];
}
// step 3
ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
for (l=0; l < ld-3; ++l) {
int k0 = n >> (l+2), k1 = 1 << (l+3);
int rlim = n >> (l+4), r4, r;
int s2lim = 1 << (l+2), s2;
for (r=r4=0; r < rlim; r4+=4,++r) {
for (s2=0; s2 < s2lim; s2+=2) {
u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4];
u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4];
u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1]
- (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1];
u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1]
+ (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1];
}
}
if (l+1 < ld-3) {
// paper bug: ping-ponging of u&w here is omitted
memcpy(w, u, sizeof(u));
}
}
// step 4
for (i=0; i < n8; ++i) {
int j = bit_reverse(i) >> (32-ld+3);
assert(j < n8);
if (i == j) {
// paper bug: original code probably swapped in place; if copying,
// need to directly copy in this case
int i8 = i << 3;
v[i8+1] = u[i8+1];
v[i8+3] = u[i8+3];
v[i8+5] = u[i8+5];
v[i8+7] = u[i8+7];
} else if (i < j) {
int i8 = i << 3, j8 = j << 3;
v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1];
v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3];
v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5];
v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7];
}
}
// step 5
for (k=0; k < n2; ++k) {
w[k] = v[k*2+1];
}
// step 6
for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) {
u[n-1-k2] = w[k4];
u[n-2-k2] = w[k4+1];
u[n3_4 - 1 - k2] = w[k4+2];
u[n3_4 - 2 - k2] = w[k4+3];
}
// step 7
for (k=k2=0; k < n8; ++k, k2 += 2) {
v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
}
// step 8
for (k=k2=0; k < n4; ++k,k2 += 2) {
X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1];
X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ];
}
// decode kernel to output
// determined the following value experimentally
// (by first figuring out what made inverse_mdct_slow work); then matching that here
// (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?)
s = 0.5; // theoretically would be n4
// [[[ note! the s value of 0.5 is compensated for by the B[] in the current code,
// so it needs to use the "old" B values to behave correctly, or else
// set s to 1.0 ]]]
for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4];
for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1];
for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4];
}
#endif
static float *get_window(vorb *f, int len)
{
len <<= 1;
if (len == f->blocksize_0) return f->window[0];
if (len == f->blocksize_1) return f->window[1];
return NULL;
}
#ifndef STB_VORBIS_NO_DEFER_FLOOR
typedef int16 YTYPE;
#else
typedef int YTYPE;
#endif
static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag)
{
int n2 = n >> 1;
int s = map->chan[i].mux, floor;
floor = map->submap_floor[s];
if (f->floor_types[floor] == 0) {
return error(f, VORBIS_invalid_stream);
} else {
Floor1 *g = &f->floor_config[floor].floor1;
int j,q;
int lx = 0, ly = finalY[0] * g->floor1_multiplier;
for (q=1; q < g->values; ++q) {
j = g->sorted_order[q];
#ifndef STB_VORBIS_NO_DEFER_FLOOR
if (finalY[j] >= 0)
#else
if (step2_flag[j])
#endif
{
int hy = finalY[j] * g->floor1_multiplier;
int hx = g->Xlist[j];
if (lx != hx)
draw_line(target, lx,ly, hx,hy, n2);
CHECK(f);
lx = hx, ly = hy;
}
}
if (lx < n2) {
// optimization of: draw_line(target, lx,ly, n,ly, n2);
for (j=lx; j < n2; ++j)
LINE_OP(target[j], inverse_db_table[ly]);
CHECK(f);
}
}
return TRUE;
}
// The meaning of "left" and "right"
//
// For a given frame:
// we compute samples from 0..n
// window_center is n/2
// we'll window and mix the samples from left_start to left_end with data from the previous frame
// all of the samples from left_end to right_start can be output without mixing; however,
// this interval is 0-length except when transitioning between short and long frames
// all of the samples from right_start to right_end need to be mixed with the next frame,
// which we don't have, so those get saved in a buffer
// frame N's right_end-right_start, the number of samples to mix with the next frame,
// has to be the same as frame N+1's left_end-left_start (which they are by
// construction)
static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
{
Mode *m;
int i, n, prev, next, window_center;
f->channel_buffer_start = f->channel_buffer_end = 0;
retry:
if (f->eof) return FALSE;
if (!maybe_start_packet(f))
return FALSE;
// check packet type
if (get_bits(f,1) != 0) {
if (IS_PUSH_MODE(f))
return error(f,VORBIS_bad_packet_type);
while (EOP != get8_packet(f));
goto retry;
}
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
i = get_bits(f, ilog(f->mode_count-1));
if (i == EOP) return FALSE;
if (i >= f->mode_count) return FALSE;
*mode = i;
m = f->mode_config + i;
if (m->blockflag) {
n = f->blocksize_1;
prev = get_bits(f,1);
next = get_bits(f,1);
} else {
prev = next = 0;
n = f->blocksize_0;
}
// WINDOWING
window_center = n >> 1;
if (m->blockflag && !prev) {
*p_left_start = (n - f->blocksize_0) >> 2;
*p_left_end = (n + f->blocksize_0) >> 2;
} else {
*p_left_start = 0;
*p_left_end = window_center;
}
if (m->blockflag && !next) {
*p_right_start = (n*3 - f->blocksize_0) >> 2;
*p_right_end = (n*3 + f->blocksize_0) >> 2;
} else {
*p_right_start = window_center;
*p_right_end = n;
}
return TRUE;
}
static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left)
{
Mapping *map;
int i,j,k,n,n2;
int zero_channel[256];
int really_zero_channel[256];
// WINDOWING
n = f->blocksize[m->blockflag];
map = &f->mapping[m->mapping];
// FLOORS
n2 = n >> 1;
CHECK(f);
for (i=0; i < f->channels; ++i) {
int s = map->chan[i].mux, floor;
zero_channel[i] = FALSE;
floor = map->submap_floor[s];
if (f->floor_types[floor] == 0) {
return error(f, VORBIS_invalid_stream);
} else {
Floor1 *g = &f->floor_config[floor].floor1;
if (get_bits(f, 1)) {
short *finalY;
uint8 step2_flag[256];
static int range_list[4] = { 256, 128, 86, 64 };
int range = range_list[g->floor1_multiplier-1];
int offset = 2;
finalY = f->finalY[i];
finalY[0] = get_bits(f, ilog(range)-1);
finalY[1] = get_bits(f, ilog(range)-1);
for (j=0; j < g->partitions; ++j) {
int pclass = g->partition_class_list[j];
int cdim = g->class_dimensions[pclass];
int cbits = g->class_subclasses[pclass];
int csub = (1 << cbits)-1;
int cval = 0;
if (cbits) {
Codebook *c = f->codebooks + g->class_masterbooks[pclass];
DECODE(cval,f,c);
}
for (k=0; k < cdim; ++k) {
int book = g->subclass_books[pclass][cval & csub];
cval = cval >> cbits;
if (book >= 0) {
int temp;
Codebook *c = f->codebooks + book;
DECODE(temp,f,c);
finalY[offset++] = temp;
} else
finalY[offset++] = 0;
}
}
if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec
step2_flag[0] = step2_flag[1] = 1;
for (j=2; j < g->values; ++j) {
int low, high, pred, highroom, lowroom, room, val;
low = g->neighbors[j][0];
high = g->neighbors[j][1];
//neighbors(g->Xlist, j, &low, &high);
pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]);
val = finalY[j];
highroom = range - pred;
lowroom = pred;
if (highroom < lowroom)
room = highroom * 2;
else
room = lowroom * 2;
if (val) {
step2_flag[low] = step2_flag[high] = 1;
step2_flag[j] = 1;
if (val >= room)
if (highroom > lowroom)
finalY[j] = val - lowroom + pred;
else
finalY[j] = pred - val + highroom - 1;
else
if (val & 1)
finalY[j] = pred - ((val+1)>>1);
else
finalY[j] = pred + (val>>1);
} else {
step2_flag[j] = 0;
finalY[j] = pred;
}
}
#ifdef STB_VORBIS_NO_DEFER_FLOOR
do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag);
#else
// defer final floor computation until _after_ residue
for (j=0; j < g->values; ++j) {
if (!step2_flag[j])
finalY[j] = -1;
}
#endif
} else {
error:
zero_channel[i] = TRUE;
}
// So we just defer everything else to later
// at this point we've decoded the floor into buffer
}
}
CHECK(f);
// at this point we've decoded all floors
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
// re-enable coupled channels if necessary
memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels);
for (i=0; i < map->coupling_steps; ++i)
if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) {
zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE;
}
CHECK(f);
// RESIDUE DECODE
for (i=0; i < map->submaps; ++i) {
float *residue_buffers[STB_VORBIS_MAX_CHANNELS];
int r;
uint8 do_not_decode[256];
int ch = 0;
for (j=0; j < f->channels; ++j) {
if (map->chan[j].mux == i) {
if (zero_channel[j]) {
do_not_decode[ch] = TRUE;
residue_buffers[ch] = NULL;
} else {
do_not_decode[ch] = FALSE;
residue_buffers[ch] = f->channel_buffers[j];
}
++ch;
}
}
r = map->submap_residue[i];
decode_residue(f, residue_buffers, ch, n2, r, do_not_decode);
}
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
CHECK(f);
// INVERSE COUPLING
for (i = map->coupling_steps-1; i >= 0; --i) {
int n2 = n >> 1;
float *m = f->channel_buffers[map->chan[i].magnitude];
float *a = f->channel_buffers[map->chan[i].angle ];
for (j=0; j < n2; ++j) {
float a2,m2;
if (m[j] > 0)
if (a[j] > 0)
m2 = m[j], a2 = m[j] - a[j];
else
a2 = m[j], m2 = m[j] + a[j];
else
if (a[j] > 0)
m2 = m[j], a2 = m[j] + a[j];
else
a2 = m[j], m2 = m[j] - a[j];
m[j] = m2;
a[j] = a2;
}
}
CHECK(f);
// finish decoding the floors
#ifndef STB_VORBIS_NO_DEFER_FLOOR
for (i=0; i < f->channels; ++i) {
if (really_zero_channel[i]) {
memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
} else {
do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL);
}
}
#else
for (i=0; i < f->channels; ++i) {
if (really_zero_channel[i]) {
memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
} else {
for (j=0; j < n2; ++j)
f->channel_buffers[i][j] *= f->floor_buffers[i][j];
}
}
#endif
// INVERSE MDCT
CHECK(f);
for (i=0; i < f->channels; ++i)
inverse_mdct(f->channel_buffers[i], n, f, m->blockflag);
CHECK(f);
// this shouldn't be necessary, unless we exited on an error
// and want to flush to get to the next packet
flush_packet(f);
if (f->first_decode) {
// assume we start so first non-discarded sample is sample 0
// this isn't to spec, but spec would require us to read ahead
// and decode the size of all current frames--could be done,
// but presumably it's not a commonly used feature
f->current_loc = -n2; // start of first frame is positioned for discard
// we might have to discard samples "from" the next frame too,
// if we're lapping a large block then a small at the start?
f->discard_samples_deferred = n - right_end;
f->current_loc_valid = TRUE;
f->first_decode = FALSE;
} else if (f->discard_samples_deferred) {
if (f->discard_samples_deferred >= right_start - left_start) {
f->discard_samples_deferred -= (right_start - left_start);
left_start = right_start;
*p_left = left_start;
} else {
left_start += f->discard_samples_deferred;
*p_left = left_start;
f->discard_samples_deferred = 0;
}
} else if (f->previous_length == 0 && f->current_loc_valid) {
// we're recovering from a seek... that means we're going to discard
// the samples from this packet even though we know our position from
// the last page header, so we need to update the position based on
// the discarded samples here
// but wait, the code below is going to add this in itself even
// on a discard, so we don't need to do it here...
}
// check if we have ogg information about the sample # for this packet
if (f->last_seg_which == f->end_seg_with_known_loc) {
// if we have a valid current loc, and this is final:
if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) {
uint32 current_end = f->known_loc_for_packet;
// then let's infer the size of the (probably) short final frame
if (current_end < f->current_loc + (right_end-left_start)) {
if (current_end < f->current_loc) {
// negative truncation, that's impossible!
*len = 0;
} else {
*len = current_end - f->current_loc;
}
*len += left_start; // this doesn't seem right, but has no ill effect on my test files
if (*len > right_end) *len = right_end; // this should never happen
f->current_loc += *len;
return TRUE;
}
}
// otherwise, just set our sample loc
// guess that the ogg granule pos refers to the _middle_ of the
// last frame?
// set f->current_loc to the position of left_start
f->current_loc = f->known_loc_for_packet - (n2-left_start);
f->current_loc_valid = TRUE;
}
if (f->current_loc_valid)
f->current_loc += (right_start - left_start);
if (f->alloc.alloc_buffer)
assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
*len = right_end; // ignore samples after the window goes to 0
CHECK(f);
return TRUE;
}
static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right)
{
int mode, left_end, right_end;
if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0;
return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left);
}
static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)
{
int prev,i,j;
// we use right&left (the start of the right- and left-window sin()-regions)
// to determine how much to return, rather than inferring from the rules
// (same result, clearer code); 'left' indicates where our sin() window
// starts, therefore where the previous window's right edge starts, and
// therefore where to start mixing from the previous buffer. 'right'
// indicates where our sin() ending-window starts, therefore that's where
// we start saving, and where our returned-data ends.
// mixin from previous window
if (f->previous_length) {
int i,j, n = f->previous_length;
float *w = get_window(f, n);
if (w == NULL) return 0;
for (i=0; i < f->channels; ++i) {
for (j=0; j < n; ++j)
f->channel_buffers[i][left+j] =
f->channel_buffers[i][left+j]*w[ j] +
f->previous_window[i][ j]*w[n-1-j];
}
}
prev = f->previous_length;
// last half of this data becomes previous window
f->previous_length = len - right;
// @OPTIMIZE: could avoid this copy by double-buffering the
// output (flipping previous_window with channel_buffers), but
// then previous_window would have to be 2x as large, and
// channel_buffers couldn't be temp mem (although they're NOT
// currently temp mem, they could be (unless we want to level
// performance by spreading out the computation))
for (i=0; i < f->channels; ++i)
for (j=0; right+j < len; ++j)
f->previous_window[i][j] = f->channel_buffers[i][right+j];
if (!prev)
// there was no previous packet, so this data isn't valid...
// this isn't entirely true, only the would-have-overlapped data
// isn't valid, but this seems to be what the spec requires
return 0;
// truncate a short frame
if (len < right) right = len;
f->samples_output += right-left;
return right - left;
}
static int vorbis_pump_first_frame(stb_vorbis *f)
{
int len, right, left, res;
res = vorbis_decode_packet(f, &len, &left, &right);
if (res)
vorbis_finish_frame(f, len, left, right);
return res;
}
#ifndef STB_VORBIS_NO_PUSHDATA_API
static int is_whole_packet_present(stb_vorbis *f, int end_page)
{
// make sure that we have the packet available before continuing...
// this requires a full ogg parse, but we know we can fetch from f->stream
// instead of coding this out explicitly, we could save the current read state,
// read the next packet with get8() until end-of-packet, check f->eof, then
// reset the state? but that would be slower, esp. since we'd have over 256 bytes
// of state to restore (primarily the page segment table)
int s = f->next_seg, first = TRUE;
uint8 *p = f->stream;
if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag
for (; s < f->segment_count; ++s) {
p += f->segments[s];
if (f->segments[s] < 255) // stop at first short segment
break;
}
// either this continues, or it ends it...
if (end_page)
if (s < f->segment_count-1) return error(f, VORBIS_invalid_stream);
if (s == f->segment_count)
s = -1; // set 'crosses page' flag
if (p > f->stream_end) return error(f, VORBIS_need_more_data);
first = FALSE;
}
for (; s == -1;) {
uint8 *q;
int n;
// check that we have the page header ready
if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data);
// validate the page
if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream);
if (p[4] != 0) return error(f, VORBIS_invalid_stream);
if (first) { // the first segment must NOT have 'continued_packet', later ones MUST
if (f->previous_length)
if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
// if no previous length, we're resynching, so we can come in on a continued-packet,
// which we'll just drop
} else {
if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
}
n = p[26]; // segment counts
q = p+27; // q points to segment table
p = q + n; // advance past header
// make sure we've read the segment table
if (p > f->stream_end) return error(f, VORBIS_need_more_data);
for (s=0; s < n; ++s) {
p += q[s];
if (q[s] < 255)
break;
}
if (end_page)
if (s < n-1) return error(f, VORBIS_invalid_stream);
if (s == n)
s = -1; // set 'crosses page' flag
if (p > f->stream_end) return error(f, VORBIS_need_more_data);
first = FALSE;
}
return TRUE;
}
#endif // !STB_VORBIS_NO_PUSHDATA_API
static int start_decoder(vorb *f)
{
uint8 header[6], x,y;
int len,i,j,k, max_submaps = 0;
int longest_floorlist=0;
// first page, first packet
if (!start_page(f)) return FALSE;
// validate page flag
if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);
// check for expected packet length
if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
if (f->segments[0] != 30) {
// check for the Ogg skeleton fishead identifying header to refine our error
if (f->segments[0] == 64 &&
getn(f, header, 6) &&
header[0] == 'f' &&
header[1] == 'i' &&
header[2] == 's' &&
header[3] == 'h' &&
header[4] == 'e' &&
header[5] == 'a' &&
get8(f) == 'd' &&
get8(f) == '\0') return error(f, VORBIS_ogg_skeleton_not_supported);
else
return error(f, VORBIS_invalid_first_page);
}
// read packet
// check packet header
if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
// vorbis_version
if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);
if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);
f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
get32(f); // bitrate_maximum
get32(f); // bitrate_nominal
get32(f); // bitrate_minimum
x = get8(f);
{
int log0,log1;
log0 = x & 15;
log1 = x >> 4;
f->blocksize_0 = 1 << log0;
f->blocksize_1 = 1 << log1;
if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
if (log0 > log1) return error(f, VORBIS_invalid_setup);
}
// framing_flag
x = get8(f);
if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
// second packet!
if (!start_page(f)) return FALSE;
if (!start_packet(f)) return FALSE;
do {
len = next_segment(f);
skip(f, len);
f->bytes_in_seg = 0;
} while (len);
// third packet!
if (!start_packet(f)) return FALSE;
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (IS_PUSH_MODE(f)) {
if (!is_whole_packet_present(f, TRUE)) {
// convert error in ogg header to write type
if (f->error == VORBIS_invalid_stream)
f->error = VORBIS_invalid_setup;
return FALSE;
}
}
#endif
crc32_init(); // always init it, to avoid multithread race conditions
if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);
for (i=0; i < 6; ++i) header[i] = get8_packet(f);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
// codebooks
f->codebook_count = get_bits(f,8) + 1;
f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
for (i=0; i < f->codebook_count; ++i) {
uint32 *values;
int ordered, sorted_count;
int total=0;
uint8 *lengths;
Codebook *c = f->codebooks+i;
CHECK(f);
x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8);
c->dimensions = (get_bits(f, 8)<<8) + x;
x = get_bits(f, 8);
y = get_bits(f, 8);
c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;
ordered = get_bits(f,1);
c->sparse = ordered ? 0 : get_bits(f,1);
if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup);
if (c->sparse)
lengths = (uint8 *) setup_temp_malloc(f, c->entries);
else
lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (!lengths) return error(f, VORBIS_outofmem);
if (ordered) {
int current_entry = 0;
int current_length = get_bits(f,5) + 1;
while (current_entry < c->entries) {
int limit = c->entries - current_entry;
int n = get_bits(f, ilog(limit));
if (current_length >= 32) return error(f, VORBIS_invalid_setup);
if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }
memset(lengths + current_entry, current_length, n);
current_entry += n;
++current_length;
}
} else {
for (j=0; j < c->entries; ++j) {
int present = c->sparse ? get_bits(f,1) : 1;
if (present) {
lengths[j] = get_bits(f, 5) + 1;
++total;
if (lengths[j] == 32)
return error(f, VORBIS_invalid_setup);
} else {
lengths[j] = NO_CODE;
}
}
}
if (c->sparse && total >= c->entries >> 2) {
// convert sparse items to non-sparse!
if (c->entries > (int) f->setup_temp_memory_required)
f->setup_temp_memory_required = c->entries;
c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem);
memcpy(c->codeword_lengths, lengths, c->entries);
setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!
lengths = c->codeword_lengths;
c->sparse = 0;
}
// compute the size of the sorted tables
if (c->sparse) {
sorted_count = total;
} else {
sorted_count = 0;
#ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
for (j=0; j < c->entries; ++j)
if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
++sorted_count;
#endif
}
c->sorted_entries = sorted_count;
values = NULL;
CHECK(f);
if (!c->sparse) {
c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
} else {
unsigned int size;
if (c->sorted_entries) {
c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);
if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
if (!values) return error(f, VORBIS_outofmem);
}
size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
if (size > f->setup_temp_memory_required)
f->setup_temp_memory_required = size;
}
if (!compute_codewords(c, lengths, c->entries, values)) {
if (c->sparse) setup_temp_free(f, values, 0);
return error(f, VORBIS_invalid_setup);
}
if (c->sorted_entries) {
// allocate an extra slot for sentinels
c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem);
// allocate an extra slot at the front so that c->sorted_values[-1] is defined
// so that we can catch that case without an extra if
c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
if (c->sorted_values == NULL) return error(f, VORBIS_outofmem);
++c->sorted_values;
c->sorted_values[-1] = -1;
compute_sorted_huffman(c, lengths, values);
}
if (c->sparse) {
setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
setup_temp_free(f, lengths, c->entries);
c->codewords = NULL;
}
compute_accelerated_huffman(c);
CHECK(f);
c->lookup_type = get_bits(f, 4);
if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
if (c->lookup_type > 0) {
uint16 *mults;
c->minimum_value = float32_unpack(get_bits(f, 32));
c->delta_value = float32_unpack(get_bits(f, 32));
c->value_bits = get_bits(f, 4)+1;
c->sequence_p = get_bits(f,1);
if (c->lookup_type == 1) {
int values = lookup1_values(c->entries, c->dimensions);
if (values < 0) return error(f, VORBIS_invalid_setup);
c->lookup_values = (uint32) values;
} else {
c->lookup_values = c->entries * c->dimensions;
}
if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup);
mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
if (mults == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < (int) c->lookup_values; ++j) {
int q = get_bits(f, c->value_bits);
if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }
mults[j] = q;
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int len, sparse = c->sparse;
float last=0;
// pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop
if (sparse) {
if (c->sorted_entries == 0) goto skip;
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
} else
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
len = sparse ? c->sorted_entries : c->entries;
for (j=0; j < len; ++j) {
unsigned int z = sparse ? c->sorted_values[j] : j;
unsigned int div=1;
for (k=0; k < c->dimensions; ++k) {
int off = (z / div) % c->lookup_values;
float val = mults[off];
val = mults[off]*c->delta_value + c->minimum_value + last;
c->multiplicands[j*c->dimensions + k] = val;
if (c->sequence_p)
last = val;
if (k+1 < c->dimensions) {
if (div > UINT_MAX / (unsigned int) c->lookup_values) {
setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
return error(f, VORBIS_invalid_setup);
}
div *= c->lookup_values;
}
}
}
c->lookup_type = 2;
}
else
#endif
{
float last=0;
CHECK(f);
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
for (j=0; j < (int) c->lookup_values; ++j) {
float val = mults[j] * c->delta_value + c->minimum_value + last;
c->multiplicands[j] = val;
if (c->sequence_p)
last = val;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
skip:;
#endif
setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values);
CHECK(f);
}
CHECK(f);
}
// time domain transfers (notused)
x = get_bits(f, 6) + 1;
for (i=0; i < x; ++i) {
uint32 z = get_bits(f, 16);
if (z != 0) return error(f, VORBIS_invalid_setup);
}
// Floors
f->floor_count = get_bits(f, 6)+1;
f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
if (f->floor_config == NULL) return error(f, VORBIS_outofmem);
for (i=0; i < f->floor_count; ++i) {
f->floor_types[i] = get_bits(f, 16);
if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
if (f->floor_types[i] == 0) {
Floor0 *g = &f->floor_config[i].floor0;
g->order = get_bits(f,8);
g->rate = get_bits(f,16);
g->bark_map_size = get_bits(f,16);
g->amplitude_bits = get_bits(f,6);
g->amplitude_offset = get_bits(f,8);
g->number_of_books = get_bits(f,4) + 1;
for (j=0; j < g->number_of_books; ++j)
g->book_list[j] = get_bits(f,8);
return error(f, VORBIS_feature_not_supported);
} else {
stbv__floor_ordering p[31*8+2];
Floor1 *g = &f->floor_config[i].floor1;
int max_class = -1;
g->partitions = get_bits(f, 5);
for (j=0; j < g->partitions; ++j) {
g->partition_class_list[j] = get_bits(f, 4);
if (g->partition_class_list[j] > max_class)
max_class = g->partition_class_list[j];
}
for (j=0; j <= max_class; ++j) {
g->class_dimensions[j] = get_bits(f, 3)+1;
g->class_subclasses[j] = get_bits(f, 2);
if (g->class_subclasses[j]) {
g->class_masterbooks[j] = get_bits(f, 8);
if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
g->subclass_books[j][k] = get_bits(f,8)-1;
if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
}
g->floor1_multiplier = get_bits(f,2)+1;
g->rangebits = get_bits(f,4);
g->Xlist[0] = 0;
g->Xlist[1] = 1 << g->rangebits;
g->values = 2;
for (j=0; j < g->partitions; ++j) {
int c = g->partition_class_list[j];
for (k=0; k < g->class_dimensions[c]; ++k) {
g->Xlist[g->values] = get_bits(f, g->rangebits);
++g->values;
}
}
// precompute the sorting
for (j=0; j < g->values; ++j) {
p[j].x = g->Xlist[j];
p[j].id = j;
}
qsort(p, g->values, sizeof(p[0]), point_compare);
for (j=0; j < g->values-1; ++j)
if (p[j].x == p[j+1].x)
return error(f, VORBIS_invalid_setup);
for (j=0; j < g->values; ++j)
g->sorted_order[j] = (uint8) p[j].id;
// precompute the neighbors
for (j=2; j < g->values; ++j) {
int low,hi;
neighbors(g->Xlist, j, &low,&hi);
g->neighbors[j][0] = low;
g->neighbors[j][1] = hi;
}
if (g->values > longest_floorlist)
longest_floorlist = g->values;
}
}
// Residue
f->residue_count = get_bits(f, 6)+1;
f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0]));
if (f->residue_config == NULL) return error(f, VORBIS_outofmem);
memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0]));
for (i=0; i < f->residue_count; ++i) {
uint8 residue_cascade[64];
Residue *r = f->residue_config+i;
f->residue_types[i] = get_bits(f, 16);
if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
r->begin = get_bits(f, 24);
r->end = get_bits(f, 24);
if (r->end < r->begin) return error(f, VORBIS_invalid_setup);
r->part_size = get_bits(f,24)+1;
r->classifications = get_bits(f,6)+1;
r->classbook = get_bits(f,8);
if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup);
for (j=0; j < r->classifications; ++j) {
uint8 high_bits=0;
uint8 low_bits=get_bits(f,3);
if (get_bits(f,1))
high_bits = get_bits(f,5);
residue_cascade[j] = high_bits*8 + low_bits;
}
r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
if (r->residue_books == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < r->classifications; ++j) {
for (k=0; k < 8; ++k) {
if (residue_cascade[j] & (1 << k)) {
r->residue_books[j][k] = get_bits(f, 8);
if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
} else {
r->residue_books[j][k] = -1;
}
}
}
// precompute the classifications[] array to avoid inner-loop mod/divide
// call it 'classdata' since we already have r->classifications
r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
if (!r->classdata) return error(f, VORBIS_outofmem);
memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
int classwords = f->codebooks[r->classbook].dimensions;
int temp = j;
r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem);
for (k=classwords-1; k >= 0; --k) {
r->classdata[j][k] = temp % r->classifications;
temp /= r->classifications;
}
}
}
f->mapping_count = get_bits(f,6)+1;
f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
if (f->mapping == NULL) return error(f, VORBIS_outofmem);
memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping));
for (i=0; i < f->mapping_count; ++i) {
Mapping *m = f->mapping + i;
int mapping_type = get_bits(f,16);
if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));
if (m->chan == NULL) return error(f, VORBIS_outofmem);
if (get_bits(f,1))
m->submaps = get_bits(f,4)+1;
else
m->submaps = 1;
if (m->submaps > max_submaps)
max_submaps = m->submaps;
if (get_bits(f,1)) {
m->coupling_steps = get_bits(f,8)+1;
if (m->coupling_steps > f->channels) return error(f, VORBIS_invalid_setup);
for (k=0; k < m->coupling_steps; ++k) {
m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));
m->chan[k].angle = get_bits(f, ilog(f->channels-1));
if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);
}
} else
m->coupling_steps = 0;
// reserved field
if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);
if (m->submaps > 1) {
for (j=0; j < f->channels; ++j) {
m->chan[j].mux = get_bits(f, 4);
if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
}
} else
// @SPECIFICATION: this case is missing from the spec
for (j=0; j < f->channels; ++j)
m->chan[j].mux = 0;
for (j=0; j < m->submaps; ++j) {
get_bits(f,8); // discard
m->submap_floor[j] = get_bits(f,8);
m->submap_residue[j] = get_bits(f,8);
if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);
if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);
}
}
// Modes
f->mode_count = get_bits(f, 6)+1;
for (i=0; i < f->mode_count; ++i) {
Mode *m = f->mode_config+i;
m->blockflag = get_bits(f,1);
m->windowtype = get_bits(f,16);
m->transformtype = get_bits(f,16);
m->mapping = get_bits(f,8);
if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
}
flush_packet(f);
f->previous_length = 0;
for (i=0; i < f->channels; ++i) {
f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);
f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);
if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem);
memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1);
#ifdef STB_VORBIS_NO_DEFER_FLOOR
f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem);
#endif
}
if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
f->blocksize[0] = f->blocksize_0;
f->blocksize[1] = f->blocksize_1;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (integer_divide_table[1][1]==0)
for (i=0; i < DIVTAB_NUMER; ++i)
for (j=1; j < DIVTAB_DENOM; ++j)
integer_divide_table[i][j] = i / j;
#endif
// compute how much temporary memory is needed
// 1.
{
uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
uint32 classify_mem;
int i,max_part_read=0;
for (i=0; i < f->residue_count; ++i) {
Residue *r = f->residue_config + i;
unsigned int actual_size = f->blocksize_1 / 2;
unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size;
unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size;
int n_read = limit_r_end - limit_r_begin;
int part_read = n_read / r->part_size;
if (part_read > max_part_read)
max_part_read = part_read;
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));
#else
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
#endif
// maximum reasonable partition size is f->blocksize_1
f->temp_memory_required = classify_mem;
if (imdct_mem > f->temp_memory_required)
f->temp_memory_required = imdct_mem;
}
f->first_decode = TRUE;
if (f->alloc.alloc_buffer) {
assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
// check if there's enough temp memory so we don't error later
if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
return error(f, VORBIS_outofmem);
}
f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
return TRUE;
}
static void vorbis_deinit(stb_vorbis *p)
{
int i,j;
if (p->residue_config) {
for (i=0; i < p->residue_count; ++i) {
Residue *r = p->residue_config+i;
if (r->classdata) {
for (j=0; j < p->codebooks[r->classbook].entries; ++j)
setup_free(p, r->classdata[j]);
setup_free(p, r->classdata);
}
setup_free(p, r->residue_books);
}
}
if (p->codebooks) {
CHECK(p);
for (i=0; i < p->codebook_count; ++i) {
Codebook *c = p->codebooks + i;
setup_free(p, c->codeword_lengths);
setup_free(p, c->multiplicands);
setup_free(p, c->codewords);
setup_free(p, c->sorted_codewords);
// c->sorted_values[-1] is the first entry in the array
setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL);
}
setup_free(p, p->codebooks);
}
setup_free(p, p->floor_config);
setup_free(p, p->residue_config);
if (p->mapping) {
for (i=0; i < p->mapping_count; ++i)
setup_free(p, p->mapping[i].chan);
setup_free(p, p->mapping);
}
CHECK(p);
for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) {
setup_free(p, p->channel_buffers[i]);
setup_free(p, p->previous_window[i]);
#ifdef STB_VORBIS_NO_DEFER_FLOOR
setup_free(p, p->floor_buffers[i]);
#endif
setup_free(p, p->finalY[i]);
}
for (i=0; i < 2; ++i) {
setup_free(p, p->A[i]);
setup_free(p, p->B[i]);
setup_free(p, p->C[i]);
setup_free(p, p->window[i]);
setup_free(p, p->bit_reverse[i]);
}
#ifndef STB_VORBIS_NO_STDIO
if (p->close_on_free) fclose(p->f);
#endif
}
void stb_vorbis_close(stb_vorbis *p)
{
if (p == NULL) return;
vorbis_deinit(p);
setup_free(p,p);
}
static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z)
{
memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start
if (z) {
p->alloc = *z;
p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3;
p->temp_offset = p->alloc.alloc_buffer_length_in_bytes;
}
p->eof = 0;
p->error = VORBIS__no_error;
p->stream = NULL;
p->codebooks = NULL;
p->page_crc_tests = -1;
#ifndef STB_VORBIS_NO_STDIO
p->close_on_free = FALSE;
p->f = NULL;
#endif
}
int stb_vorbis_get_sample_offset(stb_vorbis *f)
{
if (f->current_loc_valid)
return f->current_loc;
else
return -1;
}
stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f)
{
stb_vorbis_info d;
d.channels = f->channels;
d.sample_rate = f->sample_rate;
d.setup_memory_required = f->setup_memory_required;
d.setup_temp_memory_required = f->setup_temp_memory_required;
d.temp_memory_required = f->temp_memory_required;
d.max_frame_size = f->blocksize_1 >> 1;
return d;
}
int stb_vorbis_get_error(stb_vorbis *f)
{
int e = f->error;
f->error = VORBIS__no_error;
return e;
}
static stb_vorbis * vorbis_alloc(stb_vorbis *f)
{
stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p));
return p;
}
#ifndef STB_VORBIS_NO_PUSHDATA_API
void stb_vorbis_flush_pushdata(stb_vorbis *f)
{
f->previous_length = 0;
f->page_crc_tests = 0;
f->discard_samples_deferred = 0;
f->current_loc_valid = FALSE;
f->first_decode = FALSE;
f->samples_output = 0;
f->channel_buffer_start = 0;
f->channel_buffer_end = 0;
}
static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len)
{
int i,n;
for (i=0; i < f->page_crc_tests; ++i)
f->scan[i].bytes_done = 0;
// if we have room for more scans, search for them first, because
// they may cause us to stop early if their header is incomplete
if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) {
if (data_len < 4) return 0;
data_len -= 3; // need to look for 4-byte sequence, so don't miss
// one that straddles a boundary
for (i=0; i < data_len; ++i) {
if (data[i] == 0x4f) {
if (0==memcmp(data+i, ogg_page_header, 4)) {
int j,len;
uint32 crc;
// make sure we have the whole page header
if (i+26 >= data_len || i+27+data[i+26] >= data_len) {
// only read up to this page start, so hopefully we'll
// have the whole page header start next time
data_len = i;
break;
}
// ok, we have it all; compute the length of the page
len = 27 + data[i+26];
for (j=0; j < data[i+26]; ++j)
len += data[i+27+j];
// scan everything up to the embedded crc (which we must 0)
crc = 0;
for (j=0; j < 22; ++j)
crc = crc32_update(crc, data[i+j]);
// now process 4 0-bytes
for ( ; j < 26; ++j)
crc = crc32_update(crc, 0);
// len is the total number of bytes we need to scan
n = f->page_crc_tests++;
f->scan[n].bytes_left = len-j;
f->scan[n].crc_so_far = crc;
f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24);
// if the last frame on a page is continued to the next, then
// we can't recover the sample_loc immediately
if (data[i+27+data[i+26]-1] == 255)
f->scan[n].sample_loc = ~0;
else
f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24);
f->scan[n].bytes_done = i+j;
if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT)
break;
// keep going if we still have room for more
}
}
}
}
for (i=0; i < f->page_crc_tests;) {
uint32 crc;
int j;
int n = f->scan[i].bytes_done;
int m = f->scan[i].bytes_left;
if (m > data_len - n) m = data_len - n;
// m is the bytes to scan in the current chunk
crc = f->scan[i].crc_so_far;
for (j=0; j < m; ++j)
crc = crc32_update(crc, data[n+j]);
f->scan[i].bytes_left -= m;
f->scan[i].crc_so_far = crc;
if (f->scan[i].bytes_left == 0) {
// does it match?
if (f->scan[i].crc_so_far == f->scan[i].goal_crc) {
// Houston, we have page
data_len = n+m; // consumption amount is wherever that scan ended
f->page_crc_tests = -1; // drop out of page scan mode
f->previous_length = 0; // decode-but-don't-output one frame
f->next_seg = -1; // start a new page
f->current_loc = f->scan[i].sample_loc; // set the current sample location
// to the amount we'd have decoded had we decoded this page
f->current_loc_valid = f->current_loc != ~0U;
return data_len;
}
// delete entry
f->scan[i] = f->scan[--f->page_crc_tests];
} else {
++i;
}
}
return data_len;
}
// return value: number of bytes we used
int stb_vorbis_decode_frame_pushdata(
stb_vorbis *f, // the file we're decoding
const uint8 *data, int data_len, // the memory available for decoding
int *channels, // place to write number of float * buffers
float ***output, // place to write float ** array of float * buffers
int *samples // place to write number of output samples
)
{
int i;
int len,right,left;
if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
if (f->page_crc_tests >= 0) {
*samples = 0;
return vorbis_search_for_page_pushdata(f, (uint8 *) data, data_len);
}
f->stream = (uint8 *) data;
f->stream_end = (uint8 *) data + data_len;
f->error = VORBIS__no_error;
// check that we have the entire packet in memory
if (!is_whole_packet_present(f, FALSE)) {
*samples = 0;
return 0;
}
if (!vorbis_decode_packet(f, &len, &left, &right)) {
// save the actual error we encountered
enum STBVorbisError error = f->error;
if (error == VORBIS_bad_packet_type) {
// flush and resynch
f->error = VORBIS__no_error;
while (get8_packet(f) != EOP)
if (f->eof) break;
*samples = 0;
return (int) (f->stream - data);
}
if (error == VORBIS_continued_packet_flag_invalid) {
if (f->previous_length == 0) {
// we may be resynching, in which case it's ok to hit one
// of these; just discard the packet
f->error = VORBIS__no_error;
while (get8_packet(f) != EOP)
if (f->eof) break;
*samples = 0;
return (int) (f->stream - data);
}
}
// if we get an error while parsing, what to do?
// well, it DEFINITELY won't work to continue from where we are!
stb_vorbis_flush_pushdata(f);
// restore the error that actually made us bail
f->error = error;
*samples = 0;
return 1;
}
// success!
len = vorbis_finish_frame(f, len, left, right);
for (i=0; i < f->channels; ++i)
f->outputs[i] = f->channel_buffers[i] + left;
if (channels) *channels = f->channels;
*samples = len;
*output = f->outputs;
return (int) (f->stream - data);
}
stb_vorbis *stb_vorbis_open_pushdata(
const unsigned char *data, int data_len, // the memory available for decoding
int *data_used, // only defined if result is not NULL
int *error, const stb_vorbis_alloc *alloc)
{
stb_vorbis *f, p;
vorbis_init(&p, alloc);
p.stream = (uint8 *) data;
p.stream_end = (uint8 *) data + data_len;
p.push_mode = TRUE;
if (!start_decoder(&p)) {
if (p.eof)
*error = VORBIS_need_more_data;
else
*error = p.error;
return NULL;
}
f = vorbis_alloc(&p);
if (f) {
*f = p;
*data_used = (int) (f->stream - data);
*error = 0;
return f;
} else {
vorbis_deinit(&p);
return NULL;
}
}
#endif // STB_VORBIS_NO_PUSHDATA_API
unsigned int stb_vorbis_get_file_offset(stb_vorbis *f)
{
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (f->push_mode) return 0;
#endif
if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start);
#ifndef STB_VORBIS_NO_STDIO
return (unsigned int) (ftell(f->f) - f->f_start);
#endif
}
#ifndef STB_VORBIS_NO_PULLDATA_API
//
// DATA-PULLING API
//
static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last)
{
for(;;) {
int n;
if (f->eof) return 0;
n = get8(f);
if (n == 0x4f) { // page header candidate
unsigned int retry_loc = stb_vorbis_get_file_offset(f);
int i;
// check if we're off the end of a file_section stream
if (retry_loc - 25 > f->stream_len)
return 0;
// check the rest of the header
for (i=1; i < 4; ++i)
if (get8(f) != ogg_page_header[i])
break;
if (f->eof) return 0;
if (i == 4) {
uint8 header[27];
uint32 i, crc, goal, len;
for (i=0; i < 4; ++i)
header[i] = ogg_page_header[i];
for (; i < 27; ++i)
header[i] = get8(f);
if (f->eof) return 0;
if (header[4] != 0) goto invalid;
goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24);
for (i=22; i < 26; ++i)
header[i] = 0;
crc = 0;
for (i=0; i < 27; ++i)
crc = crc32_update(crc, header[i]);
len = 0;
for (i=0; i < header[26]; ++i) {
int s = get8(f);
crc = crc32_update(crc, s);
len += s;
}
if (len && f->eof) return 0;
for (i=0; i < len; ++i)
crc = crc32_update(crc, get8(f));
// finished parsing probable page
if (crc == goal) {
// we could now check that it's either got the last
// page flag set, OR it's followed by the capture
// pattern, but I guess TECHNICALLY you could have
// a file with garbage between each ogg page and recover
// from it automatically? So even though that paranoia
// might decrease the chance of an invalid decode by
// another 2^32, not worth it since it would hose those
// invalid-but-useful files?
if (end)
*end = stb_vorbis_get_file_offset(f);
if (last) {
if (header[5] & 0x04)
*last = 1;
else
*last = 0;
}
set_file_offset(f, retry_loc-1);
return 1;
}
}
invalid:
// not a valid page, so rewind and look for next one
set_file_offset(f, retry_loc);
}
}
}
#define SAMPLE_unknown 0xffffffff
// seeking is implemented with a binary search, which narrows down the range to
// 64K, before using a linear search (because finding the synchronization
// pattern can be expensive, and the chance we'd find the end page again is
// relatively high for small ranges)
//
// two initial interpolation-style probes are used at the start of the search
// to try to bound either side of the binary search sensibly, while still
// working in O(log n) time if they fail.
static int get_seek_page_info(stb_vorbis *f, ProbedPage *z)
{
uint8 header[27], lacing[255];
int i,len;
// record where the page starts
z->page_start = stb_vorbis_get_file_offset(f);
// parse the header
getn(f, header, 27);
if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S')
return 0;
getn(f, lacing, header[26]);
// determine the length of the payload
len = 0;
for (i=0; i < header[26]; ++i)
len += lacing[i];
// this implies where the page ends
z->page_end = z->page_start + 27 + header[26] + len;
// read the last-decoded sample out of the data
z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24);
// restore file state to where we were
set_file_offset(f, z->page_start);
return 1;
}
// rarely used function to seek back to the preceding page while finding the
// start of a packet
static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset)
{
unsigned int previous_safe, end;
// now we want to seek back 64K from the limit
if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset)
previous_safe = limit_offset - 65536;
else
previous_safe = f->first_audio_page_offset;
set_file_offset(f, previous_safe);
while (vorbis_find_page(f, &end, NULL)) {
if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset)
return 1;
set_file_offset(f, end);
}
return 0;
}
#ifdef __clang__
#pragma clang diagnostic ignored "-Wconditional-uninitialized"
#endif
// implements the search logic for finding a page and starting decoding. if
// the function succeeds, current_loc_valid will be true and current_loc will
// be less than or equal to the provided sample number (the closer the
// better).
static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number)
{
ProbedPage left, right, mid;
int i, start_seg_with_known_loc, end_pos, page_start;
uint32 delta, stream_length, padding;
double offset, bytes_per_sample;
int probe = 0;
// find the last page and validate the target sample
stream_length = stb_vorbis_stream_length_in_samples(f);
if (stream_length == 0) return error(f, VORBIS_seek_without_length);
if (sample_number > stream_length) return error(f, VORBIS_seek_invalid);
// this is the maximum difference between the window-center (which is the
// actual granule position value), and the right-start (which the spec
// indicates should be the granule position (give or take one)).
padding = ((f->blocksize_1 - f->blocksize_0) >> 2);
if (sample_number < padding)
sample_number = 0;
else
sample_number -= padding;
left = f->p_first;
while (left.last_decoded_sample == ~0U) {
// (untested) the first page does not have a 'last_decoded_sample'
set_file_offset(f, left.page_end);
if (!get_seek_page_info(f, &left)) goto error;
}
right = f->p_last;
assert(right.last_decoded_sample != ~0U);
// starting from the start is handled differently
if (sample_number <= left.last_decoded_sample) {
if (stb_vorbis_seek_start(f))
return 1;
return 0;
}
while (left.page_end != right.page_start) {
assert(left.page_end < right.page_start);
// search range in bytes
delta = right.page_start - left.page_end;
if (delta <= 65536) {
// there's only 64K left to search - handle it linearly
set_file_offset(f, left.page_end);
} else {
if (probe < 2) {
if (probe == 0) {
// first probe (interpolate)
double data_bytes = right.page_end - left.page_start;
bytes_per_sample = data_bytes / right.last_decoded_sample;
offset = left.page_start + bytes_per_sample * (sample_number - left.last_decoded_sample);
} else {
// second probe (try to bound the other side)
double error = ((double) sample_number - mid.last_decoded_sample) * bytes_per_sample;
if (error >= 0 && error < 8000) error = 8000;
if (error < 0 && error > -8000) error = -8000;
offset += error * 2;
}
// ensure the offset is valid
if (offset < left.page_end)
offset = left.page_end;
if (offset > right.page_start - 65536)
offset = right.page_start - 65536;
set_file_offset(f, (unsigned int) offset);
} else {
// binary search for large ranges (offset by 32K to ensure
// we don't hit the right page)
set_file_offset(f, left.page_end + (delta / 2) - 32768);
}
if (!vorbis_find_page(f, NULL, NULL)) goto error;
}
for (;;) {
if (!get_seek_page_info(f, &mid)) goto error;
if (mid.last_decoded_sample != ~0U) break;
// (untested) no frames end on this page
set_file_offset(f, mid.page_end);
assert(mid.page_start < right.page_start);
}
// if we've just found the last page again then we're in a tricky file,
// and we're close enough.
if (mid.page_start == right.page_start)
break;
if (sample_number < mid.last_decoded_sample)
right = mid;
else
left = mid;
++probe;
}
// seek back to start of the last packet
page_start = left.page_start;
set_file_offset(f, page_start);
if (!start_page(f)) return error(f, VORBIS_seek_failed);
end_pos = f->end_seg_with_known_loc;
assert(end_pos >= 0);
for (;;) {
for (i = end_pos; i > 0; --i)
if (f->segments[i-1] != 255)
break;
start_seg_with_known_loc = i;
if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet))
break;
// (untested) the final packet begins on an earlier page
if (!go_to_page_before(f, page_start))
goto error;
page_start = stb_vorbis_get_file_offset(f);
if (!start_page(f)) goto error;
end_pos = f->segment_count - 1;
}
// prepare to start decoding
f->current_loc_valid = FALSE;
f->last_seg = FALSE;
f->valid_bits = 0;
f->packet_bytes = 0;
f->bytes_in_seg = 0;
f->previous_length = 0;
f->next_seg = start_seg_with_known_loc;
for (i = 0; i < start_seg_with_known_loc; i++)
skip(f, f->segments[i]);
// start decoding (optimizable - this frame is generally discarded)
if (!vorbis_pump_first_frame(f))
return 0;
if (f->current_loc > sample_number)
return error(f, VORBIS_seek_failed);
return 1;
error:
// try to restore the file to a valid state
stb_vorbis_seek_start(f);
return error(f, VORBIS_seek_failed);
}
// the same as vorbis_decode_initial, but without advancing
static int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
{
int bits_read, bytes_read;
if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode))
return 0;
// either 1 or 2 bytes were read, figure out which so we can rewind
bits_read = 1 + ilog(f->mode_count-1);
if (f->mode_config[*mode].blockflag)
bits_read += 2;
bytes_read = (bits_read + 7) / 8;
f->bytes_in_seg += bytes_read;
f->packet_bytes -= bytes_read;
skip(f, -bytes_read);
if (f->next_seg == -1)
f->next_seg = f->segment_count - 1;
else
f->next_seg--;
f->valid_bits = 0;
return 1;
}
int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number)
{
uint32 max_frame_samples;
if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
// fast page-level search
if (!seek_to_sample_coarse(f, sample_number))
return 0;
assert(f->current_loc_valid);
assert(f->current_loc <= sample_number);
// linear search for the relevant packet
max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2;
while (f->current_loc < sample_number) {
int left_start, left_end, right_start, right_end, mode, frame_samples;
if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode))
return error(f, VORBIS_seek_failed);
// calculate the number of samples returned by the next frame
frame_samples = right_start - left_start;
if (f->current_loc + frame_samples > sample_number) {
return 1; // the next frame will contain the sample
} else if (f->current_loc + frame_samples + max_frame_samples > sample_number) {
// there's a chance the frame after this could contain the sample
vorbis_pump_first_frame(f);
} else {
// this frame is too early to be relevant
f->current_loc += frame_samples;
f->previous_length = 0;
maybe_start_packet(f);
flush_packet(f);
}
}
// the next frame will start with the sample
assert(f->current_loc == sample_number);
return 1;
}
int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number)
{
if (!stb_vorbis_seek_frame(f, sample_number))
return 0;
if (sample_number != f->current_loc) {
int n;
uint32 frame_start = f->current_loc;
stb_vorbis_get_frame_float(f, &n, NULL);
assert(sample_number > frame_start);
assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end);
f->channel_buffer_start += (sample_number - frame_start);
}
return 1;
}
int stb_vorbis_seek_start(stb_vorbis *f)
{
if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); }
set_file_offset(f, f->first_audio_page_offset);
f->previous_length = 0;
f->first_decode = TRUE;
f->next_seg = -1;
return vorbis_pump_first_frame(f);
}
unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f)
{
unsigned int restore_offset, previous_safe;
unsigned int end, last_page_loc;
if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
if (!f->total_samples) {
unsigned int last;
uint32 lo,hi;
char header[6];
// first, store the current decode position so we can restore it
restore_offset = stb_vorbis_get_file_offset(f);
// now we want to seek back 64K from the end (the last page must
// be at most a little less than 64K, but let's allow a little slop)
if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset)
previous_safe = f->stream_len - 65536;
else
previous_safe = f->first_audio_page_offset;
set_file_offset(f, previous_safe);
// previous_safe is now our candidate 'earliest known place that seeking
// to will lead to the final page'
if (!vorbis_find_page(f, &end, &last)) {
// if we can't find a page, we're hosed!
f->error = VORBIS_cant_find_last_page;
f->total_samples = 0xffffffff;
goto done;
}
// check if there are more pages
last_page_loc = stb_vorbis_get_file_offset(f);
// stop when the last_page flag is set, not when we reach eof;
// this allows us to stop short of a 'file_section' end without
// explicitly checking the length of the section
while (!last) {
set_file_offset(f, end);
if (!vorbis_find_page(f, &end, &last)) {
// the last page we found didn't have the 'last page' flag
// set. whoops!
break;
}
previous_safe = last_page_loc+1;
last_page_loc = stb_vorbis_get_file_offset(f);
}
set_file_offset(f, last_page_loc);
// parse the header
getn(f, (unsigned char *)header, 6);
// extract the absolute granule position
lo = get32(f);
hi = get32(f);
if (lo == 0xffffffff && hi == 0xffffffff) {
f->error = VORBIS_cant_find_last_page;
f->total_samples = SAMPLE_unknown;
goto done;
}
if (hi)
lo = 0xfffffffe; // saturate
f->total_samples = lo;
f->p_last.page_start = last_page_loc;
f->p_last.page_end = end;
f->p_last.last_decoded_sample = lo;
done:
set_file_offset(f, restore_offset);
}
return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples;
}
float stb_vorbis_stream_length_in_seconds(stb_vorbis *f)
{
return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate;
}
int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output)
{
int len, right,left,i;
if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
if (!vorbis_decode_packet(f, &len, &left, &right)) {
f->channel_buffer_start = f->channel_buffer_end = 0;
return 0;
}
len = vorbis_finish_frame(f, len, left, right);
for (i=0; i < f->channels; ++i)
f->outputs[i] = f->channel_buffers[i] + left;
f->channel_buffer_start = left;
f->channel_buffer_end = left+len;
if (channels) *channels = f->channels;
if (output) *output = f->outputs;
return len;
}
#ifndef STB_VORBIS_NO_STDIO
stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length)
{
stb_vorbis *f, p;
vorbis_init(&p, alloc);
p.f = file;
p.f_start = (uint32) ftell(file);
p.stream_len = length;
p.close_on_free = close_on_free;
if (start_decoder(&p)) {
f = vorbis_alloc(&p);
if (f) {
*f = p;
vorbis_pump_first_frame(f);
return f;
}
}
if (error) *error = p.error;
vorbis_deinit(&p);
return NULL;
}
stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc)
{
unsigned int len, start;
start = (unsigned int) ftell(file);
fseek(file, 0, SEEK_END);
len = (unsigned int) (ftell(file) - start);
fseek(file, start, SEEK_SET);
return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len);
}
stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc)
{
FILE *f;
#if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__)
if (0 != fopen_s(&f, filename, "rb"))
f = NULL;
#else
f = fopen(filename, "rb");
#endif
if (f)
return stb_vorbis_open_file(f, TRUE, error, alloc);
if (error) *error = VORBIS_file_open_failure;
return NULL;
}
#endif // STB_VORBIS_NO_STDIO
stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc)
{
stb_vorbis *f, p;
if (data == NULL) return NULL;
vorbis_init(&p, alloc);
p.stream = (uint8 *) data;
p.stream_end = (uint8 *) data + len;
p.stream_start = (uint8 *) p.stream;
p.stream_len = len;
p.push_mode = FALSE;
if (start_decoder(&p)) {
f = vorbis_alloc(&p);
if (f) {
*f = p;
vorbis_pump_first_frame(f);
if (error) *error = VORBIS__no_error;
return f;
}
}
if (error) *error = p.error;
vorbis_deinit(&p);
return NULL;
}
#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
#define PLAYBACK_MONO 1
#define PLAYBACK_LEFT 2
#define PLAYBACK_RIGHT 4
#define L (PLAYBACK_LEFT | PLAYBACK_MONO)
#define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO)
#define R (PLAYBACK_RIGHT | PLAYBACK_MONO)
static int8 channel_position[7][6] =
{
{ 0 },
{ C },
{ L, R },
{ L, C, R },
{ L, R, L, R },
{ L, C, R, L, R },
{ L, C, R, L, R, C },
};
#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
typedef union {
float f;
int i;
} float_conv;
typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4];
#define FASTDEF(x) float_conv x
// add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round
#define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT))
#define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22))
#define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s))
#define check_endianness()
#else
#define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s))))
#define check_endianness()
#define FASTDEF(x)
#endif
static void copy_samples(short *dest, float *src, int len)
{
int i;
check_endianness();
for (i=0; i < len; ++i) {
FASTDEF(temp);
int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15);
if ((unsigned int) (v + 32768) > 65535)
v = v < 0 ? -32768 : 32767;
dest[i] = v;
}
}
static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len)
{
#define BUFFER_SIZE 32
float buffer[BUFFER_SIZE];
int i,j,o,n = BUFFER_SIZE;
check_endianness();
for (o = 0; o < len; o += BUFFER_SIZE) {
memset(buffer, 0, sizeof(buffer));
if (o + n > len) n = len - o;
for (j=0; j < num_c; ++j) {
if (channel_position[num_c][j] & mask) {
for (i=0; i < n; ++i)
buffer[i] += data[j][d_offset+o+i];
}
}
for (i=0; i < n; ++i) {
FASTDEF(temp);
int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
if ((unsigned int) (v + 32768) > 65535)
v = v < 0 ? -32768 : 32767;
output[o+i] = v;
}
}
}
static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len)
{
#define BUFFER_SIZE 32
float buffer[BUFFER_SIZE];
int i,j,o,n = BUFFER_SIZE >> 1;
// o is the offset in the source data
check_endianness();
for (o = 0; o < len; o += BUFFER_SIZE >> 1) {
// o2 is the offset in the output data
int o2 = o << 1;
memset(buffer, 0, sizeof(buffer));
if (o + n > len) n = len - o;
for (j=0; j < num_c; ++j) {
int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT);
if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) {
for (i=0; i < n; ++i) {
buffer[i*2+0] += data[j][d_offset+o+i];
buffer[i*2+1] += data[j][d_offset+o+i];
}
} else if (m == PLAYBACK_LEFT) {
for (i=0; i < n; ++i) {
buffer[i*2+0] += data[j][d_offset+o+i];
}
} else if (m == PLAYBACK_RIGHT) {
for (i=0; i < n; ++i) {
buffer[i*2+1] += data[j][d_offset+o+i];
}
}
}
for (i=0; i < (n<<1); ++i) {
FASTDEF(temp);
int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
if ((unsigned int) (v + 32768) > 65535)
v = v < 0 ? -32768 : 32767;
output[o2+i] = v;
}
}
}
static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples)
{
int i;
if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} };
for (i=0; i < buf_c; ++i)
compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples);
} else {
int limit = buf_c < data_c ? buf_c : data_c;
for (i=0; i < limit; ++i)
copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples);
for ( ; i < buf_c; ++i)
memset(buffer[i]+b_offset, 0, sizeof(short) * samples);
}
}
int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples)
{
float **output;
int len = stb_vorbis_get_frame_float(f, NULL, &output);
if (len > num_samples) len = num_samples;
if (len)
convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len);
return len;
}
static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len)
{
int i;
check_endianness();
if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
assert(buf_c == 2);
for (i=0; i < buf_c; ++i)
compute_stereo_samples(buffer, data_c, data, d_offset, len);
} else {
int limit = buf_c < data_c ? buf_c : data_c;
int j;
for (j=0; j < len; ++j) {
for (i=0; i < limit; ++i) {
FASTDEF(temp);
float f = data[i][d_offset+j];
int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15);
if ((unsigned int) (v + 32768) > 65535)
v = v < 0 ? -32768 : 32767;
*buffer++ = v;
}
for ( ; i < buf_c; ++i)
*buffer++ = 0;
}
}
}
int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts)
{
float **output;
int len;
if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts);
len = stb_vorbis_get_frame_float(f, NULL, &output);
if (len) {
if (len*num_c > num_shorts) len = num_shorts / num_c;
convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len);
}
return len;
}
int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts)
{
float **outputs;
int len = num_shorts / channels;
int n=0;
int z = f->channels;
if (z > channels) z = channels;
while (n < len) {
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n+k >= len) k = len - n;
if (k)
convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k);
buffer += k*channels;
n += k;
f->channel_buffer_start += k;
if (n == len) break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
}
return n;
}
int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len)
{
float **outputs;
int n=0;
int z = f->channels;
if (z > channels) z = channels;
while (n < len) {
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n+k >= len) k = len - n;
if (k)
convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k);
n += k;
f->channel_buffer_start += k;
if (n == len) break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
}
return n;
}
#ifndef STB_VORBIS_NO_STDIO
int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output)
{
int data_len, offset, total, limit, error;
short *data;
stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL);
if (v == NULL) return -1;
limit = v->channels * 4096;
*channels = v->channels;
if (sample_rate)
*sample_rate = v->sample_rate;
offset = data_len = 0;
total = limit;
data = (short *) malloc(total * sizeof(*data));
if (data == NULL) {
stb_vorbis_close(v);
return -2;
}
for (;;) {
int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
if (n == 0) break;
data_len += n;
offset += n * v->channels;
if (offset + limit > total) {
short *data2;
total *= 2;
data2 = (short *) realloc(data, total * sizeof(*data));
if (data2 == NULL) {
free(data);
stb_vorbis_close(v);
return -2;
}
data = data2;
}
}
*output = data;
stb_vorbis_close(v);
return data_len;
}
#endif // NO_STDIO
int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output)
{
int data_len, offset, total, limit, error;
short *data;
stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL);
if (v == NULL) return -1;
limit = v->channels * 4096;
*channels = v->channels;
if (sample_rate)
*sample_rate = v->sample_rate;
offset = data_len = 0;
total = limit;
data = (short *) malloc(total * sizeof(*data));
if (data == NULL) {
stb_vorbis_close(v);
return -2;
}
for (;;) {
int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
if (n == 0) break;
data_len += n;
offset += n * v->channels;
if (offset + limit > total) {
short *data2;
total *= 2;
data2 = (short *) realloc(data, total * sizeof(*data));
if (data2 == NULL) {
free(data);
stb_vorbis_close(v);
return -2;
}
data = data2;
}
}
*output = data;
stb_vorbis_close(v);
return data_len;
}
#endif // STB_VORBIS_NO_INTEGER_CONVERSION
int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats)
{
float **outputs;
int len = num_floats / channels;
int n=0;
int z = f->channels;
if (z > channels) z = channels;
while (n < len) {
int i,j;
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n+k >= len) k = len - n;
for (j=0; j < k; ++j) {
for (i=0; i < z; ++i)
*buffer++ = f->channel_buffers[i][f->channel_buffer_start+j];
for ( ; i < channels; ++i)
*buffer++ = 0;
}
n += k;
f->channel_buffer_start += k;
if (n == len)
break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs))
break;
}
return n;
}
int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples)
{
float **outputs;
int n=0;
int z = f->channels;
if (z > channels) z = channels;
while (n < num_samples) {
int i;
int k = f->channel_buffer_end - f->channel_buffer_start;
if (n+k >= num_samples) k = num_samples - n;
if (k) {
for (i=0; i < z; ++i)
memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k);
for ( ; i < channels; ++i)
memset(buffer[i]+n, 0, sizeof(float) * k);
}
n += k;
f->channel_buffer_start += k;
if (n == num_samples)
break;
if (!stb_vorbis_get_frame_float(f, NULL, &outputs))
break;
}
return n;
}
#endif // STB_VORBIS_NO_PULLDATA_API
/* Version history
1.17 - 2019-07-08 - fix CVE-2019-13217, -13218, -13219, -13220, -13221, -13222, -13223
found with Mayhem by ForAllSecure
1.16 - 2019-03-04 - fix warnings
1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found
1.14 - 2018-02-11 - delete bogus dealloca usage
1.13 - 2018-01-29 - fix truncation of last frame (hopefully)
1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files
1.11 - 2017-07-23 - fix MinGW compilation
1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory
1.09 - 2016-04-04 - back out 'avoid discarding last frame' fix from previous version
1.08 - 2016-04-02 - fixed multiple warnings; fix setup memory leaks;
avoid discarding last frame of audio data
1.07 - 2015-01-16 - fixed some warnings, fix mingw, const-correct API
some more crash fixes when out of memory or with corrupt files
1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson)
some crash fixes when out of memory or with corrupt files
1.05 - 2015-04-19 - don't define __forceinline if it's redundant
1.04 - 2014-08-27 - fix missing const-correct case in API
1.03 - 2014-08-07 - Warning fixes
1.02 - 2014-07-09 - Declare qsort compare function _cdecl on windows
1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float
1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in multichannel
(API change) report sample rate for decode-full-file funcs
0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila
0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem
0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence
0.99993 - remove assert that fired on legal files with empty tables
0.99992 - rewind-to-start
0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo
0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++
0.9998 - add a full-decode function with a memory source
0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition
0.9996 - query length of vorbis stream in samples/seconds
0.9995 - bugfix to another optimization that only happened in certain files
0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors
0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation
0.9992 - performance improvement of IMDCT; now performs close to reference implementation
0.9991 - performance improvement of IMDCT
0.999 - (should have been 0.9990) performance improvement of IMDCT
0.998 - no-CRT support from Casey Muratori
0.997 - bugfixes for bugs found by Terje Mathisen
0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen
0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen
0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen
0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen
0.992 - fixes for MinGW warning
0.991 - turn fast-float-conversion on by default
0.990 - fix push-mode seek recovery if you seek into the headers
0.98b - fix to bad release of 0.98
0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode
0.97 - builds under c++ (typecasting, don't use 'class' keyword)
0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code
0.95 - clamping code for 16-bit functions
0.94 - not publically released
0.93 - fixed all-zero-floor case (was decoding garbage)
0.92 - fixed a memory leak
0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION
0.90 - first public release
*/
#endif // STB_VORBIS_HEADER_ONLY
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
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.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
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 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.
------------------------------------------------------------------------------
*/
|
the_stack_data/43887861.c | // RUN: %ucc -fsyntax-only %s
enum A
{
A
};
/* this ensures alignof() on an enum works - previously it
* would cause a segfault because it was accessing the enum
* part of a identifiers .bits union */
_Static_assert(__alignof__(A) == sizeof(A), "");
|
the_stack_data/133333.c | #include<stdio.h>
int main()
{
int m,i,j,temp,n;
printf("enter order of array");
scanf("%d%d",&m,&n);
int arr[m][n];
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&arr[i][j]);
}
for(i=0;i<m;i++)
{
for(j=0;j<n-1;j++)
{
if(arr[i][j]>arr[i][j+1])
{
temp=arr[i][j];
arr[i][j]=arr[i][j+1];
arr[i][j+1]=temp;
}
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("new array is %d\n",arr[i][j]);
}
}
|
the_stack_data/114475.c | #include <stdio.h>
static struct sss{
char * f;
long double a[10];
} sss;
#define _offsetof(st,f) ((char *)&((st *) 16)->f - (char *) 16)
int main (void) {
printf ("++++Array of longdouble in struct starting with pointer:\n");
printf ("size=%d,align=%d\n",
sizeof (sss), __alignof__ (sss));
printf ("offset-pointer=%d,offset-arrayof-longdouble=%d,\nalign-pointer=%d,align-arrayof-longdouble=%d\n",
_offsetof (struct sss, f), _offsetof (struct sss, a),
__alignof__ (sss.f), __alignof__ (sss.a));
printf ("offset-longdouble-a[5]=%d,align-longdouble-a[5]=%d\n",
_offsetof (struct sss, a[5]),
__alignof__ (sss.a[5]));
return 0;
}
|
the_stack_data/150141020.c | #include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, const char *argv[]){
pid_t pid = fork();
int status;
int execRet;
if (pid < 0)
perror("Fork failed.");
else if (pid == 0) {
execRet = execlp("ls", "ls", "-l", NULL);
if (execRet == -1) {
printf("execl failed\n");
_exit(1);
}
}
else {
wait(&status);
printf("\nChild executed with exit code: %d\n", WEXITSTATUS(status));
}
return 0;
}
|
the_stack_data/64200569.c | #include <stdio.h>
int gcd( int a, int b );
int main () {
int x, y;
scanf("%d %d", &x, &y);
printf("%d\n", gcd( x, y ));
return 0;
}
int gcd( int a, int b ) {
if ( (b <= a) && ((a % b) == 0) ) {
return b;
}
else if (a < b) {
return gcd(b, a);
}
else {
return gcd(b, a % b);
}
}
|
the_stack_data/6389097.c | /* { dg-skip-if "ptxas runs out of memory" { nvptx-*-* } { "*" } { "" } } */
/* { dg-require-effective-target int32plus } */
/* Inspired by the test case for PR middle-end/52640. */
typedef struct
{
char *value;
} REFERENCE;
/* Add a few "extern int Xxxxxx ();" declarations. */
#undef DEF
#undef LIM1
#undef LIM2
#undef LIM3
#undef LIM4
#undef LIM5
#undef LIM6
#define DEF(x) extern int x ()
#define LIM1(x) DEF(x##0); DEF(x##1); DEF(x##2); DEF(x##3); DEF(x##4); \
DEF(x##5); DEF(x##6); DEF(x##7); DEF(x##8); DEF(x##9);
#define LIM2(x) LIM1(x##0) LIM1(x##1) LIM1(x##2) LIM1(x##3) LIM1(x##4) \
LIM1(x##5) LIM1(x##6) LIM1(x##7) LIM1(x##8) LIM1(x##9)
#define LIM3(x) LIM2(x##0) LIM2(x##1) LIM2(x##2) LIM2(x##3) LIM2(x##4) \
LIM2(x##5) LIM2(x##6) LIM2(x##7) LIM2(x##8) LIM2(x##9)
#define LIM4(x) LIM3(x##0) LIM3(x##1) LIM3(x##2) LIM3(x##3) LIM3(x##4) \
LIM3(x##5) LIM3(x##6) LIM3(x##7) LIM3(x##8) LIM3(x##9)
#define LIM5(x) LIM4(x##0) LIM4(x##1) LIM4(x##2) LIM4(x##3) LIM4(x##4) \
LIM4(x##5) LIM4(x##6) LIM4(x##7) LIM4(x##8) LIM4(x##9)
#define LIM6(x) LIM5(x##0) LIM5(x##1) LIM5(x##2) LIM5(x##3) LIM5(x##4) \
LIM5(x##5) LIM5(x##6) LIM5(x##7) LIM5(x##8) LIM5(x##9)
LIM5 (X);
/* Add references to them, or GCC will simply ignore the extern decls. */
#undef DEF
#undef LIM1
#undef LIM2
#undef LIM3
#undef LIM4
#undef LIM5
#undef LIM6
#define DEF(x) (char *) x
#define LIM1(x) DEF(x##0), DEF(x##1), DEF(x##2), DEF(x##3), DEF(x##4), \
DEF(x##5), DEF(x##6), DEF(x##7), DEF(x##8), DEF(x##9),
#define LIM2(x) LIM1(x##0) LIM1(x##1) LIM1(x##2) LIM1(x##3) LIM1(x##4) \
LIM1(x##5) LIM1(x##6) LIM1(x##7) LIM1(x##8) LIM1(x##9)
#define LIM3(x) LIM2(x##0) LIM2(x##1) LIM2(x##2) LIM2(x##3) LIM2(x##4) \
LIM2(x##5) LIM2(x##6) LIM2(x##7) LIM2(x##8) LIM2(x##9)
#define LIM4(x) LIM3(x##0) LIM3(x##1) LIM3(x##2) LIM3(x##3) LIM3(x##4) \
LIM3(x##5) LIM3(x##6) LIM3(x##7) LIM3(x##8) LIM3(x##9)
#define LIM5(x) LIM4(x##0) LIM4(x##1) LIM4(x##2) LIM4(x##3) LIM4(x##4) \
LIM4(x##5) LIM4(x##6) LIM4(x##7) LIM4(x##8) LIM4(x##9)
#define LIM6(x) LIM5(x##0) LIM5(x##1) LIM5(x##2) LIM5(x##3) LIM5(x##4) \
LIM5(x##5) LIM5(x##6) LIM5(x##7) LIM5(x##8) LIM5(x##9)
REFERENCE references[] = {
LIM5 (X)
0
};
|
the_stack_data/574597.c | // wcsrtombs_s_ex.c : wcsrtombs_s() example
// -------------------------------------------------------------
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h> // errno_t wcsrtombs_s(size_t * restrict retval,
// char * restrict dest,
// rsize_t destmax,
// const wchar_t ** restrict src,
// rsize_t n,
// mbstate_t * restrict state);
#include <locale.h>
#include <stdio.h>
int main()
{
if( setlocale(LC_ALL, "") == NULL)
fputs("Unable to set the locale.\n", stderr);
wchar_t widestr[] = L"A wide-character string ...";
const wchar_t *wcptr = widestr; // A pointer to a wide character.
char mbstr[100] = ""; // For the multibyte string.
size_t mblen = 0;
mbstate_t mbstate = {0}; // Conversion state.
if( wcsrtombs_s( &mblen, mbstr, sizeof(mbstr),
&wcptr, 3, &mbstate) == 0)
{
printf("Multibyte length: %zu; character codes: [", mblen);
for( size_t i = 0; i < mblen; ++i)
printf(" %X", (unsigned char)mbstr[i]);
puts(" ]");
if( wcptr != NULL)
printf("Wide characters remaining: \"%ls\"\n", wcptr);
}
return 0;
}
|
the_stack_data/132952782.c | /* Copyright (c) 2017, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#include <openssl/crypto.h>
// This file exists in order to give the fipsmodule target, in non-FIPS mode,
// something to compile.
int FIPS_mode(void) {
#if defined(BORINGSSL_FIPS) && !defined(OPENSSL_ASAN)
return 1;
#else
return 0;
#endif
}
|
the_stack_data/23576100.c | //---------pipetest_first.c----------
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
int main(unsigned int argc, unsigned char** argv)
{
int pipe_fd[2];
pid_t pid;
char r_buf[100];
char w_buf[4];
int r_num;
int cmd;
memset(r_buf, 0, sizeof(r_buf));
memset(w_buf, 0, sizeof(r_buf));
//匿名管道(unnamed pipe):只能用于同一个祖先的进程组通信
//有名管道(named fifo):不相关的进程也可以使用来通信
//unnamed pipe:int pipe(int filedes[2]); fildes[0]:用于从管道中读取数据; fildes[1]:用于将数据写入管道(不需要open,直接read/write,等系统调用,系统自动删除,进程不需要考虑。)
//named pipe: int mkfifo(const char* pathname, mode_t mode);
if (pipe(pipe_fd) < 0)
{
printf("FILE: %s,LINE: %d.pipe create error\n", __FILE__, __LINE__);
return -1;
}
if ((pid = fork()) == 0) //child process
{
printf("####################\n");
close(pipe_fd[1]); //close writer
sleep(3); //ensure the writer has closed
r_num = read(pipe_fd[0], r_buf, 100);
printf("child read num is %d, the data read from the pipe is %d\n", r_num, atoi(r_buf));
close(pipe_fd[0]); //close reader
//exit(0);
}
else if (pid > 0) //parent process
{
close(pipe_fd[0]); //close reader
strcpy(w_buf, "111");
if (write(pipe_fd[1], w_buf, 4) != -1)
{
printf("parent write over\n");
}
close(pipe_fd[1]); //close writer
printf("parent close fd[1]-write over\n");
sleep(3);
}
return 0;
} |
the_stack_data/713083.c |
n_basis_M1 = 3;
n_basis_M2 = 3;
n_basis_DQ = 3;
|
the_stack_data/827067.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, Z. Vasicek, L. Sekanina, H. Jiang and J. Han, "Scalable Construction of Approximate Multipliers With Formally Guaranteed Worst Case Error" in IEEE Transactions on Very Large Scale Integration (VLSI) Systems, vol. 26, no. 11, pp. 2572-2576, Nov. 2018. doi: 10.1109/TVLSI.2018.2856362
* This file contains a circuit from a sub-set of pareto optimal circuits with respect to the pwr and mae parameters
***/
// MAE% = 0.0018 %
// MAE = 1.2
// WCE% = 0.0076 %
// WCE = 5.0
// WCRE% = 500.00 %
// EP% = 50.00 %
// MRE% = 0.28 %
// MSE = 3.8
// PDK45_PWR = 0.422 mW
// PDK45_AREA = 711.0 um2
// PDK45_DELAY = 1.48 ns
#include <stdint.h>
#include <stdlib.h>
int16_t mul8s_1KVA(int8_t A, int8_t B)
{
int16_t P, P_;
uint8_t tmp, C_1_1,C_1_2,C_1_3,C_1_4,C_1_5,C_1_6,C_1_7,C_2_0,C_2_1,C_2_2,C_2_3,C_2_4,C_2_5,C_2_6,C_2_7,C_3_0,C_3_1,C_3_2,C_3_3,C_3_4,C_3_5,C_3_6,C_3_7,C_4_0,C_4_1,C_4_2,C_4_3,C_4_4,C_4_5,C_4_6,C_4_7,C_5_0,C_5_1,C_5_2,C_5_3,C_5_4,C_5_5,C_5_6,C_5_7,C_6_0,C_6_1,C_6_2,C_6_3,C_6_4,C_6_5,C_6_6,C_6_7,C_7_0,C_7_1,C_7_2,C_7_3,C_7_4,C_7_5,C_7_6,C_7_7,C_8_0,C_8_1,C_8_2,C_8_3,C_8_4,C_8_5,C_8_6,C_8_7,S_0_2,S_0_3,S_0_4,S_0_5,S_0_6,S_0_7,S_1_1,S_1_2,S_1_3,S_1_4,S_1_5,S_1_6,S_1_7,S_2_0,S_2_1,S_2_2,S_2_3,S_2_4,S_2_5,S_2_6,S_2_7,S_3_0,S_3_1,S_3_2,S_3_3,S_3_4,S_3_5,S_3_6,S_3_7,S_4_0,S_4_1,S_4_2,S_4_3,S_4_4,S_4_5,S_4_6,S_4_7,S_5_0,S_5_1,S_5_2,S_5_3,S_5_4,S_5_5,S_5_6,S_5_7,S_6_0,S_6_1,S_6_2,S_6_3,S_6_4,S_6_5,S_6_6,S_6_7,S_7_0,S_7_1,S_7_2,S_7_3,S_7_4,S_7_5,S_7_6,S_7_7,S_8_0,S_8_1,S_8_2,S_8_3,S_8_4,S_8_5,S_8_6,S_8_7;
S_0_2 = (((A>>0)&1) & ((B>>2)&1));
S_0_3 = (((A>>0)&1) & ((B>>3)&1));
S_0_4 = (((A>>0)&1) & ((B>>4)&1));
S_0_5 = (((A>>0)&1) & ((B>>5)&1));
S_0_6 = (((A>>0)&1) & ((B>>6)&1));
S_0_7 = (((((A>>0)&1) & ((B>>7)&1)))^1);
S_1_1 = S_0_2^(((A>>1)&1) & ((B>>1)&1));
C_1_1 = S_0_2&(((A>>1)&1) & ((B>>1)&1));
S_1_2 = S_0_3^(((A>>1)&1) & ((B>>2)&1));
C_1_2 = S_0_3&(((A>>1)&1) & ((B>>2)&1));
S_1_3 = S_0_4^(((A>>1)&1) & ((B>>3)&1));
C_1_3 = S_0_4&(((A>>1)&1) & ((B>>3)&1));
S_1_4 = S_0_5^(((A>>1)&1) & ((B>>4)&1));
C_1_4 = S_0_5&(((A>>1)&1) & ((B>>4)&1));
S_1_5 = S_0_6^(((A>>1)&1) & ((B>>5)&1));
C_1_5 = S_0_6&(((A>>1)&1) & ((B>>5)&1));
S_1_6 = S_0_7^(((A>>1)&1) & ((B>>6)&1));
C_1_6 = S_0_7&(((A>>1)&1) & ((B>>6)&1));
S_1_7 = 1^(((((A>>1)&1) & ((B>>7)&1)))^1);
C_1_7 = 1&(((((A>>1)&1) & ((B>>7)&1)))^1);
S_2_0 = S_1_1^(((A>>2)&1) & ((B>>0)&1));
C_2_0 = S_1_1&(((A>>2)&1) & ((B>>0)&1));
tmp = S_1_2^C_1_1;
S_2_1 = tmp^(((A>>2)&1) & ((B>>1)&1));
C_2_1 = (tmp&(((A>>2)&1) & ((B>>1)&1)))|(S_1_2&C_1_1);
tmp = S_1_3^C_1_2;
S_2_2 = tmp^(((A>>2)&1) & ((B>>2)&1));
C_2_2 = (tmp&(((A>>2)&1) & ((B>>2)&1)))|(S_1_3&C_1_2);
tmp = S_1_4^C_1_3;
S_2_3 = tmp^(((A>>2)&1) & ((B>>3)&1));
C_2_3 = (tmp&(((A>>2)&1) & ((B>>3)&1)))|(S_1_4&C_1_3);
tmp = S_1_5^C_1_4;
S_2_4 = tmp^(((A>>2)&1) & ((B>>4)&1));
C_2_4 = (tmp&(((A>>2)&1) & ((B>>4)&1)))|(S_1_5&C_1_4);
tmp = S_1_6^C_1_5;
S_2_5 = tmp^(((A>>2)&1) & ((B>>5)&1));
C_2_5 = (tmp&(((A>>2)&1) & ((B>>5)&1)))|(S_1_6&C_1_5);
tmp = S_1_7^C_1_6;
S_2_6 = tmp^(((A>>2)&1) & ((B>>6)&1));
C_2_6 = (tmp&(((A>>2)&1) & ((B>>6)&1)))|(S_1_7&C_1_6);
S_2_7 = C_1_7^(((((A>>2)&1) & ((B>>7)&1)))^1);
C_2_7 = C_1_7&(((((A>>2)&1) & ((B>>7)&1)))^1);
tmp = S_2_1^C_2_0;
S_3_0 = tmp^(((A>>3)&1) & ((B>>0)&1));
C_3_0 = (tmp&(((A>>3)&1) & ((B>>0)&1)))|(S_2_1&C_2_0);
tmp = S_2_2^C_2_1;
S_3_1 = tmp^(((A>>3)&1) & ((B>>1)&1));
C_3_1 = (tmp&(((A>>3)&1) & ((B>>1)&1)))|(S_2_2&C_2_1);
tmp = S_2_3^C_2_2;
S_3_2 = tmp^(((A>>3)&1) & ((B>>2)&1));
C_3_2 = (tmp&(((A>>3)&1) & ((B>>2)&1)))|(S_2_3&C_2_2);
tmp = S_2_4^C_2_3;
S_3_3 = tmp^(((A>>3)&1) & ((B>>3)&1));
C_3_3 = (tmp&(((A>>3)&1) & ((B>>3)&1)))|(S_2_4&C_2_3);
tmp = S_2_5^C_2_4;
S_3_4 = tmp^(((A>>3)&1) & ((B>>4)&1));
C_3_4 = (tmp&(((A>>3)&1) & ((B>>4)&1)))|(S_2_5&C_2_4);
tmp = S_2_6^C_2_5;
S_3_5 = tmp^(((A>>3)&1) & ((B>>5)&1));
C_3_5 = (tmp&(((A>>3)&1) & ((B>>5)&1)))|(S_2_6&C_2_5);
tmp = S_2_7^C_2_6;
S_3_6 = tmp^(((A>>3)&1) & ((B>>6)&1));
C_3_6 = (tmp&(((A>>3)&1) & ((B>>6)&1)))|(S_2_7&C_2_6);
S_3_7 = C_2_7^(((((A>>3)&1) & ((B>>7)&1)))^1);
C_3_7 = C_2_7&(((((A>>3)&1) & ((B>>7)&1)))^1);
tmp = S_3_1^C_3_0;
S_4_0 = tmp^(((A>>4)&1) & ((B>>0)&1));
C_4_0 = (tmp&(((A>>4)&1) & ((B>>0)&1)))|(S_3_1&C_3_0);
tmp = S_3_2^C_3_1;
S_4_1 = tmp^(((A>>4)&1) & ((B>>1)&1));
C_4_1 = (tmp&(((A>>4)&1) & ((B>>1)&1)))|(S_3_2&C_3_1);
tmp = S_3_3^C_3_2;
S_4_2 = tmp^(((A>>4)&1) & ((B>>2)&1));
C_4_2 = (tmp&(((A>>4)&1) & ((B>>2)&1)))|(S_3_3&C_3_2);
tmp = S_3_4^C_3_3;
S_4_3 = tmp^(((A>>4)&1) & ((B>>3)&1));
C_4_3 = (tmp&(((A>>4)&1) & ((B>>3)&1)))|(S_3_4&C_3_3);
tmp = S_3_5^C_3_4;
S_4_4 = tmp^(((A>>4)&1) & ((B>>4)&1));
C_4_4 = (tmp&(((A>>4)&1) & ((B>>4)&1)))|(S_3_5&C_3_4);
tmp = S_3_6^C_3_5;
S_4_5 = tmp^(((A>>4)&1) & ((B>>5)&1));
C_4_5 = (tmp&(((A>>4)&1) & ((B>>5)&1)))|(S_3_6&C_3_5);
tmp = S_3_7^C_3_6;
S_4_6 = tmp^(((A>>4)&1) & ((B>>6)&1));
C_4_6 = (tmp&(((A>>4)&1) & ((B>>6)&1)))|(S_3_7&C_3_6);
S_4_7 = C_3_7^(((((A>>4)&1) & ((B>>7)&1)))^1);
C_4_7 = C_3_7&(((((A>>4)&1) & ((B>>7)&1)))^1);
tmp = S_4_1^C_4_0;
S_5_0 = tmp^(((A>>5)&1) & ((B>>0)&1));
C_5_0 = (tmp&(((A>>5)&1) & ((B>>0)&1)))|(S_4_1&C_4_0);
tmp = S_4_2^C_4_1;
S_5_1 = tmp^(((A>>5)&1) & ((B>>1)&1));
C_5_1 = (tmp&(((A>>5)&1) & ((B>>1)&1)))|(S_4_2&C_4_1);
tmp = S_4_3^C_4_2;
S_5_2 = tmp^(((A>>5)&1) & ((B>>2)&1));
C_5_2 = (tmp&(((A>>5)&1) & ((B>>2)&1)))|(S_4_3&C_4_2);
tmp = S_4_4^C_4_3;
S_5_3 = tmp^(((A>>5)&1) & ((B>>3)&1));
C_5_3 = (tmp&(((A>>5)&1) & ((B>>3)&1)))|(S_4_4&C_4_3);
tmp = S_4_5^C_4_4;
S_5_4 = tmp^(((A>>5)&1) & ((B>>4)&1));
C_5_4 = (tmp&(((A>>5)&1) & ((B>>4)&1)))|(S_4_5&C_4_4);
tmp = S_4_6^C_4_5;
S_5_5 = tmp^(((A>>5)&1) & ((B>>5)&1));
C_5_5 = (tmp&(((A>>5)&1) & ((B>>5)&1)))|(S_4_6&C_4_5);
tmp = S_4_7^C_4_6;
S_5_6 = tmp^(((A>>5)&1) & ((B>>6)&1));
C_5_6 = (tmp&(((A>>5)&1) & ((B>>6)&1)))|(S_4_7&C_4_6);
S_5_7 = C_4_7^(((((A>>5)&1) & ((B>>7)&1)))^1);
C_5_7 = C_4_7&(((((A>>5)&1) & ((B>>7)&1)))^1);
tmp = S_5_1^C_5_0;
S_6_0 = tmp^(((A>>6)&1) & ((B>>0)&1));
C_6_0 = (tmp&(((A>>6)&1) & ((B>>0)&1)))|(S_5_1&C_5_0);
tmp = S_5_2^C_5_1;
S_6_1 = tmp^(((A>>6)&1) & ((B>>1)&1));
C_6_1 = (tmp&(((A>>6)&1) & ((B>>1)&1)))|(S_5_2&C_5_1);
tmp = S_5_3^C_5_2;
S_6_2 = tmp^(((A>>6)&1) & ((B>>2)&1));
C_6_2 = (tmp&(((A>>6)&1) & ((B>>2)&1)))|(S_5_3&C_5_2);
tmp = S_5_4^C_5_3;
S_6_3 = tmp^(((A>>6)&1) & ((B>>3)&1));
C_6_3 = (tmp&(((A>>6)&1) & ((B>>3)&1)))|(S_5_4&C_5_3);
tmp = S_5_5^C_5_4;
S_6_4 = tmp^(((A>>6)&1) & ((B>>4)&1));
C_6_4 = (tmp&(((A>>6)&1) & ((B>>4)&1)))|(S_5_5&C_5_4);
tmp = S_5_6^C_5_5;
S_6_5 = tmp^(((A>>6)&1) & ((B>>5)&1));
C_6_5 = (tmp&(((A>>6)&1) & ((B>>5)&1)))|(S_5_6&C_5_5);
tmp = S_5_7^C_5_6;
S_6_6 = tmp^(((A>>6)&1) & ((B>>6)&1));
C_6_6 = (tmp&(((A>>6)&1) & ((B>>6)&1)))|(S_5_7&C_5_6);
S_6_7 = C_5_7^(((((A>>6)&1) & ((B>>7)&1)))^1);
C_6_7 = C_5_7&(((((A>>6)&1) & ((B>>7)&1)))^1);
tmp = S_6_1^C_6_0;
S_7_0 = tmp^(((((A>>7)&1) & ((B>>0)&1)))^1);
C_7_0 = (tmp&(((((A>>7)&1) & ((B>>0)&1)))^1))|(S_6_1&C_6_0);
tmp = S_6_2^C_6_1;
S_7_1 = tmp^(((((A>>7)&1) & ((B>>1)&1)))^1);
C_7_1 = (tmp&(((((A>>7)&1) & ((B>>1)&1)))^1))|(S_6_2&C_6_1);
tmp = S_6_3^C_6_2;
S_7_2 = tmp^(((((A>>7)&1) & ((B>>2)&1)))^1);
C_7_2 = (tmp&(((((A>>7)&1) & ((B>>2)&1)))^1))|(S_6_3&C_6_2);
tmp = S_6_4^C_6_3;
S_7_3 = tmp^(((((A>>7)&1) & ((B>>3)&1)))^1);
C_7_3 = (tmp&(((((A>>7)&1) & ((B>>3)&1)))^1))|(S_6_4&C_6_3);
tmp = S_6_5^C_6_4;
S_7_4 = tmp^(((((A>>7)&1) & ((B>>4)&1)))^1);
C_7_4 = (tmp&(((((A>>7)&1) & ((B>>4)&1)))^1))|(S_6_5&C_6_4);
tmp = S_6_6^C_6_5;
S_7_5 = tmp^(((((A>>7)&1) & ((B>>5)&1)))^1);
C_7_5 = (tmp&(((((A>>7)&1) & ((B>>5)&1)))^1))|(S_6_6&C_6_5);
tmp = S_6_7^C_6_6;
S_7_6 = tmp^(((((A>>7)&1) & ((B>>6)&1)))^1);
C_7_6 = (tmp&(((((A>>7)&1) & ((B>>6)&1)))^1))|(S_6_7&C_6_6);
S_7_7 = C_6_7^(((A>>7)&1) & ((B>>7)&1));
C_7_7 = C_6_7&(((A>>7)&1) & ((B>>7)&1));
S_8_0 = S_7_1^C_7_0;
C_8_0 = S_7_1&C_7_0;
tmp = S_7_2^C_8_0;
S_8_1 = tmp^C_7_1;
C_8_1 = (tmp&C_7_1)|(S_7_2&C_8_0);
tmp = S_7_3^C_8_1;
S_8_2 = tmp^C_7_2;
C_8_2 = (tmp&C_7_2)|(S_7_3&C_8_1);
tmp = S_7_4^C_8_2;
S_8_3 = tmp^C_7_3;
C_8_3 = (tmp&C_7_3)|(S_7_4&C_8_2);
tmp = S_7_5^C_8_3;
S_8_4 = tmp^C_7_4;
C_8_4 = (tmp&C_7_4)|(S_7_5&C_8_3);
tmp = S_7_6^C_8_4;
S_8_5 = tmp^C_7_5;
C_8_5 = (tmp&C_7_5)|(S_7_6&C_8_4);
tmp = S_7_7^C_8_5;
S_8_6 = tmp^C_7_6;
C_8_6 = (tmp&C_7_6)|(S_7_7&C_8_5);
tmp = 1^C_8_6;
S_8_7 = tmp^C_7_7;
C_8_7 = (tmp&C_7_7)|(1&C_8_6);
P = 0;
P |= (S_2_0 & 1) << 2;
P |= (S_3_0 & 1) << 3;
P |= (S_4_0 & 1) << 4;
P |= (S_5_0 & 1) << 5;
P |= (S_6_0 & 1) << 6;
P |= (S_7_0 & 1) << 7;
P |= (S_8_0 & 1) << 8;
P |= (S_8_1 & 1) << 9;
P |= (S_8_2 & 1) << 10;
P |= (S_8_3 & 1) << 11;
P |= (S_8_4 & 1) << 12;
P |= (S_8_5 & 1) << 13;
P |= (S_8_6 & 1) << 14;
P |= (S_8_7 & 1) << 15;
return P;
}
|
the_stack_data/178264663.c | /*
Copyright (c) 2013, Alexey Frunze
All rights reserved.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
/*****************************************************************************/
/* */
/* MIPS ELF to RetroBSD a.out convertor with support for MIPS icache */
/* */
/*****************************************************************************/
#include <limits.h>
#include <stdarg.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char uchar, uint8;
typedef signed char schar, int8;
typedef unsigned short ushort, uint16;
typedef short int16;
#if UINT_MAX >= 0xFFFFFFFF
typedef unsigned uint32;
typedef int int32;
#else
typedef unsigned long uint32;
typedef long int32;
#endif
typedef unsigned uint;
typedef unsigned long ulong;
typedef long long longlong;
typedef unsigned long long ulonglong;
#if ULONG_MAX >= 0xFFFFFFFFFFFFFFFFULL
typedef unsigned long uint64;
typedef long int64;
#else
typedef unsigned long long uint64;
typedef long long int64;
#endif
#define C_ASSERT(expr) extern char CAssertExtern[(expr)?1:-1]
C_ASSERT(CHAR_BIT == 8);
C_ASSERT(sizeof(uint16) == 2);
C_ASSERT(sizeof(uint32) == 4);
C_ASSERT(sizeof(uint64) == 8);
C_ASSERT(sizeof(size_t) >= 4);
#pragma pack(push,1)
typedef struct
{
uint8 e_ident[16];
uint16 e_type;
uint16 e_machine;
uint32 e_version;
uint32 e_entry;
uint32 e_phoff;
uint32 e_shoff;
uint32 e_flags;
uint16 e_ehsize;
uint16 e_phentsize;
uint16 e_phnum;
uint16 e_shentsize;
uint16 e_shnum;
uint16 e_shstrndx;
} Elf32Hdr;
typedef struct
{
uint32 sh_name;
uint32 sh_type;
uint32 sh_flags;
uint32 sh_addr;
uint32 sh_offset;
uint32 sh_size;
uint32 sh_link;
uint32 sh_info;
uint32 sh_addralign;
uint32 sh_entsize;
} Elf32SectHdr;
typedef struct
{
uint32 a_magic; /* magic number */
#define OMAGIC 0407 /* old impure format */
uint32 a_text; /* size of text segment */
uint32 a_data; /* size of initialized data */
uint32 a_bss; /* size of uninitialized data */
uint32 a_reltext; /* size of text relocation info */
uint32 a_reldata; /* size of data relocation info */
uint32 a_syms; /* size of symbol table */
uint32 a_entry; /* entry point */
} AoutHdr;
#pragma pack(pop)
C_ASSERT(sizeof(Elf32Hdr) == 52);
C_ASSERT(sizeof(Elf32SectHdr) == 40);
C_ASSERT(sizeof(AoutHdr) == 32);
typedef struct
{
const char* Name;
uint32 FileOffs;
uint32 Addr;
uint32 Size;
uint32 Flags;
uint32 Flags2;
} tSection;
tSection* Sections = NULL;
uint SectionCnt = 0;
char* SectNames = NULL;
uint32 EntryPointAddr = 0;
FILE* ElfFile = NULL;
FILE* AoutFile = NULL;
const char* AoutName = NULL;
void error(char* format, ...)
{
va_list vl;
va_start(vl, format);
if (ElfFile)
fclose(ElfFile);
if (AoutFile)
fclose(AoutFile);
if (AoutName != NULL)
remove(AoutName);
puts("");
vprintf(format, vl);
va_end(vl);
exit(-1);
}
int SectAddrCompare(const void* pa, const void* pb)
{
const tSection *p1 = pa, *p2 = pb;
if (p1->Addr < p2->Addr)
return -1;
else if (p1->Addr > p2->Addr)
return +1;
return 0;
}
void WriteZeroes(FILE* f, uint32 size)
{
static const char zeroes[1024];
while (size)
{
uint32 sz;
if (size > sizeof zeroes)
sz = sizeof zeroes;
else
sz = size;
if (fwrite(zeroes, 1, sz, f) != sz)
error("Can't write file\n");
size -= sz;
}
}
void CopyFileData(FILE* fto, FILE* ffrom, uint32 size)
{
char buf[1024];
while (size)
{
uint32 sz;
if (size > sizeof buf)
sz = sizeof buf;
else
sz = size;
if (fread(buf, 1, sz, ffrom) != sz)
error("Can't read file\n");
if (fwrite(buf, 1, sz, fto) != sz)
error("Can't write file\n");
size -= sz;
}
}
int main(int argc, char** argv)
{
Elf32Hdr elfHdr;
Elf32SectHdr sectHdr;
uint idx;
int unsupported = 0;
int verbose = 0;
AoutHdr aoutHdr;
uint32 addr;
uint32 endAddr = 0, codeEndAddr, bssStartAddr;
if (argc > 1 && !strcmp(argv[1], "-v"))
{
verbose = 1;
argc--;
argv++;
}
if (argc != 3 ||
!(ElfFile = fopen(argv[1], "rb")) ||
!(AoutFile = fopen(AoutName = argv[2], "wb")))
error("Usage:\n ice2aout [-v] <mips32 elf executable> <RetroBSD mips32 a.out executable>\n");
if (fread(&elfHdr, 1, sizeof elfHdr, ElfFile) != sizeof elfHdr)
error("Can't read file\n");
if (memcmp(elfHdr.e_ident, "\x7F""ELF", 4))
error("Not an ELF file\n");
if (elfHdr.e_ident[6] != 1)
error("Not a v1 ELF file\n");
if (elfHdr.e_ehsize != sizeof elfHdr)
error("Unexpected ELF header size\n");
if (elfHdr.e_shentsize != sizeof sectHdr)
error("Unexpected ELF section size\n");
if (elfHdr.e_ident[4] != 1)
error("Not a 32-bit file\n");
if (elfHdr.e_ident[5] != 1)
error("Not a little-endian file\n");
if (elfHdr.e_type != 2)
error("Not an executable file\n");
if (elfHdr.e_machine != 8)
error("Not a MIPS executable\n");
if (fseek(ElfFile, elfHdr.e_shoff + elfHdr.e_shstrndx * sizeof sectHdr, SEEK_SET))
error("Can't read file\n");
if (fread(§Hdr, 1, sizeof sectHdr, ElfFile) != sizeof sectHdr)
error("Can't read file\n");
if ((SectNames = malloc(sectHdr.sh_size)) == NULL)
error("Out of memory\n");
if (fseek(ElfFile, sectHdr.sh_offset, SEEK_SET))
error("Can't read file\n");
if (fread(SectNames, 1, sectHdr.sh_size, ElfFile) != sectHdr.sh_size)
error("Can't read file\n");
if ((Sections = calloc(1, (elfHdr.e_shnum + 1) * sizeof(tSection))) == NULL)
error("Out of memory\n");
for (idx = 0; idx < elfHdr.e_shnum; idx++)
{
const char* name = "";
if (fseek(ElfFile, elfHdr.e_shoff + idx * sizeof sectHdr, SEEK_SET))
error("Can't read file\n");
if (fread(§Hdr, 1, sizeof sectHdr, ElfFile) != sizeof sectHdr)
error("Can't read file\n");
if (sectHdr.sh_type == 0)
memset(§Hdr, 0, sizeof sectHdr);
if (sectHdr.sh_name)
name = SectNames + sectHdr.sh_name;
unsupported |=
(!strcmp(name, ".dynsym") ||
!strcmp(name, ".dynstr") ||
!strcmp(name, ".dynamic") ||
!strcmp(name, ".hash") ||
!strcmp(name, ".got") ||
!strcmp(name, ".plt") ||
sectHdr.sh_type == 5 || // SHT_HASH
sectHdr.sh_type == 6 || // SHT_DYNAMIC
sectHdr.sh_type == 11); // SHT_DYNSYM
// Keep only allocatable sections of non-zero size
if ((sectHdr.sh_flags & 2) && sectHdr.sh_size) // SHF_ALLOC and size > 0
{
Sections[SectionCnt].FileOffs = 0;
Sections[SectionCnt].Name = name;
Sections[SectionCnt].Addr = sectHdr.sh_addr;
Sections[SectionCnt].Size = sectHdr.sh_size;
Sections[SectionCnt].Flags = (sectHdr.sh_flags & 1) | ((sectHdr.sh_flags & 4) >> 1); // bit0=Writable,bit1=eXecutable
if (sectHdr.sh_type == 1) // SHT_PROGBITS
{
Sections[SectionCnt].FileOffs = sectHdr.sh_offset;
}
SectionCnt++;
}
}
EntryPointAddr = elfHdr.e_entry;
// Sort sections by address as we'll need them in order
// and without gaps inbetween
qsort(Sections, SectionCnt, sizeof Sections[0], &SectAddrCompare);
if (verbose)
{
printf(" # XAW VirtAddr FileOffs Size Name\n");
for (idx = 0; idx < SectionCnt; idx++)
{
tSection* p = &Sections[idx];
printf("%2u %c%c%c 0x%08lX 0x%08lX %10lu %s\n",
idx,
"-X"[(p->Flags / 2) & 1],
"-A"[1],
"-W"[(p->Flags / 1) & 1],
(ulong)p->Addr,
(ulong)p->FileOffs,
(ulong)p->Size,
p->Name);
}
printf("Entry: 0x%08lX\n", (ulong)EntryPointAddr);
puts("");
}
if (unsupported)
error("Dynamically linked or unsupported type of executable\n");
// Write an empty a.out header at first, it will be updated later
memset(&aoutHdr, 0, sizeof aoutHdr);
if (fwrite(&aoutHdr, 1, sizeof aoutHdr, AoutFile) != sizeof aoutHdr)
error("Can't write file\n");
#define USER_DATA_START 0x7F008000
#define MAXMEM (96*1024)
#define USER_DATA_END (USER_DATA_START + MAXMEM)
if (verbose)
printf("Phase 1: Processing sections in the range 0x%08lX ... 0x%08lX ...\n",
(ulong)USER_DATA_START, (ulong)USER_DATA_END - 1);
addr = USER_DATA_START;
// Copy non-cached sections
for (idx = 0; idx < SectionCnt; idx++)
{
tSection* p = &Sections[idx];
if (p->Addr + p->Size >= p->Addr &&
p->Addr >= USER_DATA_START &&
p->Addr + p->Size <= USER_DATA_END)
{
if (verbose)
printf("Copying %s ...\n", p->Name);
if (idx && (Sections[idx - 1].Flags2 & 1))
{
if (p->Addr < Sections[idx - 1].Addr + Sections[idx - 1].Size)
error("Sections must not intersect in memory\n");
if ((p->Flags & 2) && !(Sections[idx - 1].Flags & 2)) // executable after non-executable
error("Code sections must precede data sections in memory\n");
}
if ((p->Flags & 2) && !p->FileOffs) // executable and initialized to all zeroes
error("Code sections must not be initialized to all zeroes\n");
// If this section has code/data in it, if it's not initialized to all zeroes...
if (p->FileOffs)
{
// Fill inter-section gaps (and .bss-like sections that aren't at the end)
// with zeroes. This lets me order sections more flexibly and yet make
// sure they all are properly initialized.
if (addr < p->Addr)
{
WriteZeroes(AoutFile, p->Addr - addr);
addr = p->Addr;
}
// Copy section
if (fseek(ElfFile, p->FileOffs, SEEK_SET))
error("Can't read file\n");
CopyFileData(AoutFile, ElfFile, p->Size);
addr += p->Size;
}
p->Flags2 |= 1; // section has been processed
endAddr = p->Addr + p->Size;
}
else
{
if (verbose)
printf("Skipping %s ...\n", p->Name);
}
}
if (endAddr == 0)
error("There are no copiable sections in this range\n");
if (verbose)
printf("Phase 2: Processing sections outside the range 0x%08lX ... 0x%08lX ...\n",
(ulong)USER_DATA_START, (ulong)USER_DATA_END - 1);
// Append cached section(s)
for (idx = 0; idx < SectionCnt; idx++)
{
tSection* p = &Sections[idx];
if (p->Addr + p->Size >= p->Addr &&
(p->Addr >= USER_DATA_END ||
p->Addr + p->Size <= USER_DATA_START))
{
if (verbose)
printf("Copying %s ...\n", p->Name);
// Copy section
if (p->FileOffs)
{
if (fseek(ElfFile, p->FileOffs, SEEK_SET))
error("Can't read file\n");
CopyFileData(AoutFile, ElfFile, p->Size);
}
p->Flags2 |= 1; // section has been processed
}
}
// Make sure no section has been left unprocessed
for (idx = 0; idx < SectionCnt; idx++)
{
tSection* p = &Sections[idx];
if (!(p->Flags2 & 1))
error("Not all sections have been processed, e.g. %s hasn't\n", p->Name);
}
// Update a.out header
aoutHdr.a_magic = OMAGIC;
aoutHdr.a_entry = EntryPointAddr;
codeEndAddr = endAddr;
for (idx = SectionCnt - 1; idx != (uint)-1; idx--)
{
tSection* p = &Sections[idx];
if (p->Addr + p->Size >= p->Addr &&
p->Addr >= USER_DATA_START &&
p->Addr + p->Size <= USER_DATA_END)
{
// While not executable, keep going, executable sections are first
if (!(p->Flags & 2))
codeEndAddr = p->Addr;
else
break;
}
}
bssStartAddr = endAddr;
for (idx = SectionCnt - 1; idx != (uint)-1; idx--)
{
tSection* p = &Sections[idx];
if (p->Addr + p->Size >= p->Addr &&
p->Addr >= USER_DATA_START &&
p->Addr + p->Size <= USER_DATA_END)
{
// While initialized to all zeroes, keep going
if (!p->FileOffs)
bssStartAddr = p->Addr;
else
break;
}
}
aoutHdr.a_text = codeEndAddr - USER_DATA_START;
aoutHdr.a_data = bssStartAddr - codeEndAddr;
aoutHdr.a_bss = endAddr - bssStartAddr;
if (fseek(AoutFile, 0, SEEK_SET))
error("Can't write file\n");
if (fwrite(&aoutHdr, 1, sizeof aoutHdr, AoutFile) != sizeof aoutHdr)
error("Can't write file\n");
if (fclose(AoutFile))
error("Can't write file\n");
fclose(ElfFile);
if (verbose)
{
printf("a.out header:\n"
" text size: %lu\n"
" data size: %lu\n"
" bss size: %lu\n",
(ulong)aoutHdr.a_text,
(ulong)aoutHdr.a_data,
(ulong)aoutHdr.a_bss);
printf("Done\n");
}
return 0;
}
|
the_stack_data/45450210.c |
// sparse matrix vector multiply (SpMV) for CSR format
void spMVMul_csr(int n, int* rowptr, int* col, double* val, double *x, double *y)
{
int i,k, tmp;
for (i=0; i<n; i++) {
tmp = y[i];
for(k=rowptr[i]; k<rowptr[i+1]; k++){
y[i] = tmp + val[k]*x[col[k]];
}
}
}
|
the_stack_data/25446.c | /* { dg-do run } */
/* { dg-skip-if "" { *-*-* } { "*" } { "-O2" } } */
/* { dg-options "-fsanitize=undefined" } */
/* Test PARM_DECLs and RESULT_DECLs. */
struct T { char d[8]; int e; };
struct T t = { "abcdefg", 1 };
#ifdef __cplusplus
struct C { C () : d("abcdefg"), e(1) {} C (const C &x) { __builtin_memcpy (d, x.d, 8); e = x.e; } ~C () {} char d[8]; int e; };
#endif
struct U { int a : 5; int b : 19; int c : 8; };
struct S { struct U d[10]; };
struct S s __attribute__ ((aligned(4096)));
int
f1 (struct T x, int i)
{
char *p = x.d;
p += i;
return *p;
}
/* { dg-output "load of address \[^\n\r]* with insufficient space for an object of type 'char'\[^\n\r]*(\n|\r\n|\r)" } */
/* { dg-output "\[^\n\r]*note: pointer points here\[^\n\r]*(\n|\r\n|\r)" } */
/* { dg-output "\[^\n\r]*\[^\n\r]*(\n|\r\n|\r)" } */
/* { dg-output "\[^\n\r]*\\^\[^\n\r]*(\n|\r\n|\r)" } */
#ifdef __cplusplus
static struct C
f2 (int i)
{
struct C x;
x.d[i] = 'z';
return x;
}
/* { dg-output "\[^\n\r]*index 12 out of bounds for type 'char \\\[8\\\]'\[^\n\r]*(\n|\r\n|\r)" { target { c++ } } } */
/* { dg-output "\[^\n\r]*store to address \[^\n\r]* with insufficient space for an object of type 'char'\[^\n\r]*(\n|\r\n|\r)" { target { c++ } } } */
/* { dg-output "\[^\n\r]*note: pointer points here\[^\n\r]*(\n|\r\n|\r)" { target { c++ } } } */
/* { dg-output "\[^\n\r]*\[^\n\r]*(\n|\r\n|\r)" { target { c++ } } } */
/* { dg-output "\[^\n\r]*\\^\[^\n\r]*(\n|\r\n|\r)" { target { c++ } } } */
static struct C
f3 (int i)
{
struct C x;
char *p = x.d;
p += i;
*p = 'z';
return x;
}
/* { dg-output "\[^\n\r]*store to address \[^\n\r]* with insufficient space for an object of type 'char'\[^\n\r]*(\n|\r\n|\r)" { target { c++ } } } */
/* { dg-output "\[^\n\r]*note: pointer points here\[^\n\r]*(\n|\r\n|\r)" { target { c++ } } } */
/* { dg-output "\[^\n\r]*\[^\n\r]*(\n|\r\n|\r)" { target { c++ } } } */
/* { dg-output "\[^\n\r]*\\^\[^\n\r]*(\n|\r\n|\r)" { target { c++ } } } */
#endif
int
f4 (int i)
{
return s.d[i].b;
}
/* { dg-output "\[^\n\r]*index 12 out of bounds for type 'U \\\[10\\\]'\[^\n\r]*(\n|\r\n|\r)" } */
/* { dg-output "\[^\n\r]*load of address \[^\n\r]* with insufficient space for an object of type 'unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */
/* { dg-output "\[^\n\r]*note: pointer points here\[^\n\r]*(\n|\r\n|\r)" } */
/* { dg-output "\[^\n\r]*\[^\n\r]*(\n|\r\n|\r)" } */
/* { dg-output "\[^\n\r]*\\^\[^\n\r]*(\n|\r\n|\r)" } */
int
f5 (int i)
{
struct U *u = s.d;
u += i;
return u->b;
}
/* { dg-output "\[^\n\r]*load of address \[^\n\r]* with insufficient space for an object of type 'unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */
/* { dg-output "\[^\n\r]*note: pointer points here\[^\n\r]*(\n|\r\n|\r)" } */
/* { dg-output "\[^\n\r]*\[^\n\r]*(\n|\r\n|\r)" } */
/* { dg-output "\[^\n\r]*\\^" } */
int
main (void)
{
f1 (t, 12);
#ifdef __cplusplus
f2 (12);
f3 (12);
#endif
f4 (12);
f5 (12);
#ifdef __cplusplus
/* Stack may be smashed by f2/f3 above. */
__builtin_exit (0);
#endif
return 0;
}
|
the_stack_data/45451198.c | /*
This program is part of the TACLeBench benchmark suite.
Version V 2.0
Name: fft
Author: Juan Martinez Velarde
Function: benchmarking of an integer stage scaling FFT
To avoid errors caused by overflow and bit growth,
the input data is scaled. Bit growth occurs potentially
at butterfly operations, which involve a complex
multiplication, a complex addition and a complex
subtraction. Maximal bit growth from butterfly input
to butterfly output is two bits.
The input data includes enough extra sign bits, called
guard bits, to ensure that bit growth never results in
overflow (Rabiner and Gold, 1975). Data can grow by a
maximum factor of 2.4 from butterfly input to output
(two bits of grow). However, a data value cannot grow by
maximum amount in two consecutive stages.
The number of guard bits necessary to compensate the
maximum bit growth in an N-point FFT is (log_2 (N))+1).
In a 16-point FFT (requires 4 stages), each of the
input samples should contain 5 guard bits. The input
data is then restricted to 10 bits, one sign bit and
nine magnitude bits, in order to prevent an
overflow from the integer multiplication with the
precalculed twiddle coefficients.
Another method to compensate bit growth is to scale the
outputs down by a factor of two unconditionally after
each stage. This approach is called unconditional scaling
Initially, 2 guard bits are included in the input data to
accomodate the maximum overflow in the first stage.
In each butterfly of a stage calculation, the data can
grow into the guard bits. To prevent overflow in the next
stage, the guard bits are replaced before the next stage is
executed by shifting the entire block of data one bit
to the right.
Input data should not be restricted to a 1.9 format.
Input data can be represented in a 1.13 format,that is
14 significant bits, one sign and 13 magnitude bits. In
the FFT calculation, the data loses a total of (log2 N) -1
bits because of shifting. Unconditional scaling results
in the same number of bits lost as in the input data scaling.
However, it produces more precise results because the
FFT starts with more precise input data. The tradeoff is
a slower FFT calculation because of the extra cycles needed
to shift the output of each stage.
Source: DSP-Stone
http://www.ice.rwth-aachen.de/research/tools-projects/entry/detail/dspstone/
Original name: fft_1024_13
(merged main1024_bit_reduct and fft_bit_reduct from DSP-Stone)
Changes: no major functional changes
License: may be used, modified, and re-distributed freely
*/
#define N_FFT 1024
#define NUMBER_OF_BITS 13 /* fract format 1.NUMBER_OF_BITS = 1.13 */
#define BITS_PER_TWID 13 /* bits per twiddle coefficient */
#define SHIFT BITS_PER_TWID /* fractional shift after each multiplication */
/*
Forward declaration of functions
*/
float fft_exp2f( float x );
float fft_modff( float x, float *intpart );
int fft_convert( float value );
void fft_bit_reduct( register int *int_pointer );
void fft_pin_down( int input_data[] );
void fft_init( void );
void fft_main( void );
int fft_return(void);
int main(void);
/*
Forward declaration of global variables
*/
int fft_input_data[2 * N_FFT];
/* precalculated twiddle factors
for an integer 1024 point FFT
in format 1.13 => table twidtable[2*(N_FFT-1)] ; */
extern int fft_twidtable[2046];
/* 1024 real values as input data in float format */
extern float fft_input[1024];
/* will hold the transformed data */
int fft_inputfract[N_FFT];
/*
Algorithm core function
*/
void fft_bit_reduct( register int *int_pointer )
{
register int i, j = 0 ;
register int tmpr, max = 2, m, n = N_FFT << 1 ;
/* do the bit reversal scramble of the input data */
_Pragma( "loopbound min 1024 max 1024" )
for ( i = 0; i < ( n - 1 ) ; i += 2 ) {
if ( j > i ) {
tmpr = *( int_pointer + j ) ;
*( int_pointer + j ) = *( int_pointer + i ) ;
*( int_pointer + i ) = tmpr ;
tmpr = *( int_pointer + j + 1 ) ;
*( int_pointer + j + 1 ) = *( int_pointer + i + 1 ) ;
*( int_pointer + i + 1 ) = tmpr ;
}
m = N_FFT;
_Pragma( "loopbound min 0 max 10" )
while ( m >= 2 && j >= m ) {
j -= m ;
m >>= 1;
}
j += m ;
}
{
register int *data_pointer = &fft_twidtable[0] ;
register int *p, *q ;
register int tmpi, fr = 0, level, k, l ;
_Pragma( "loopbound min 10 max 10" )
while ( n > max ) {
level = max << 1;
_Pragma( "loopbound min 1 max 512" )
for ( m = 1; m < max; m += 2 ) {
l = *( data_pointer + fr );
k = *( data_pointer + fr + 1 ) ;
fr += 2 ;
_Pragma( "loopbound min 1 max 512" )
for ( i = m; i <= n; i += level ) {
j = i + max;
p = int_pointer + j;
q = int_pointer + i;
tmpr = l * *( p - 1 );
tmpr -= ( k * *p );
tmpi = l * *p;
tmpi += ( k * *( p - 1 ) );
tmpr = tmpr >> SHIFT ;
tmpi = tmpi >> SHIFT ;
*( p - 1 ) = *( q - 1 ) - tmpr ;
*p = *q - tmpi ;
*( q - 1 ) += tmpr ;
*q += tmpi ;
}
}
/* implement unconditional bit reduction */
{
register int f;
p = int_pointer;
_Pragma( "loopbound min 2048 max 2048" )
for ( f = 0 ; f < 2 * N_FFT; f++ ) {
*p = *p >> 1;
p++;
}
}
max = level;
}
}
}
/*
Initialization- and return-value-related functions
*/
/* conversion function to 1.NUMBER_OF_BITS format */
float fft_exp2f( float x )
{
int i;
float ret = 2.0f;
_Pragma( "loopbound min 13 max 13" )
for ( i = 1; i < x; ++i )
ret *= 2.0f;
return ret;
}
float fft_modff( float x, float *intpart )
{
if ( intpart ) {
*intpart = ( int )x;
return x - *intpart;
} else
return x;
}
/* conversion function to 1.NUMBER_OF_BITS format */
int fft_convert( float value )
{
float man, t_val, frac, m, exponent = NUMBER_OF_BITS;
int rnd_val;
unsigned long int_val;
unsigned long pm_val;
m = fft_exp2f( exponent + 1 ) - 1;
t_val = value * m ;
frac = fft_modff( t_val, &man );
if ( frac < 0.0f ) {
rnd_val = ( -1 );
if ( frac > -0.5f ) rnd_val = 0;
} else {
rnd_val = 1;
if ( frac < 0.5f ) rnd_val = 0;
}
int_val = man + rnd_val;
pm_val = int_val ;
return ( ( int ) ( pm_val ) ) ;
}
void fft_float2fract(void)
{
float f ;
int j, i ;
_Pragma( "loopbound min 1024 max 1024" )
for ( j = 0 ; j < N_FFT ; j++ ) {
f = fft_input[j];
i = fft_convert( f );
fft_inputfract[j] = i;
}
}
void fft_pin_down( int input_data[] )
{
/* conversion from input to a 1.13 format */
fft_float2fract() ;
int *pd, *ps, f;
pd = &input_data[0];
ps = &fft_inputfract[0];
_Pragma( "loopbound min 1024 max 1024" )
for ( f = 0; f < N_FFT; f++ ) {
*pd++ = *ps++ ; /* fill in with real data */
*pd++ = 0 ; /* imaginary data is equal zero */
}
}
void fft_init( void )
{
int i;
volatile int x = 0;
fft_pin_down( &fft_input_data[0] );
/* avoid constant propagation of input values */
for ( i = 0; i < 2*N_FFT; i++) {
fft_input_data[i] += x;
fft_twidtable[i] += x;
}
}
int fft_return(void)
{
int check_sum = 0;
int i = 0;
for(i = 0; i < 2*N_FFT; ++i){
check_sum += fft_input_data[i];
}
return check_sum != 3968;
}
/*
Main functions
*/
void _Pragma( "entrypoint" ) fft_main( void )
{
fft_bit_reduct( &fft_input_data[0] );
}
int main( void )
{
fft_init();
fft_main();
return fft_return();
}
|
the_stack_data/146425.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
void insertSort(int arr[], int size) {
// Begin at second element
for(int i = 1; i < size - 1; ++i) {
int value = arr[i];
int k = i;
// While k > 0 and the previous value is larger than
// the current to be sorted in value
while(k > 0 && (arr[k - 1] > value)) {
// Switch current with previous value
int tmp = arr[k];
arr[k] = arr[k - 1];
arr[k - 1] = tmp;
--k;
}
// Set value in correct order
arr[k] = value;
}
}
void printList(int arr[], int size) {
printf("\n");
for(int i = 0; i < size; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
srand(time(NULL));
int size;
printf("\nWie gross soll die Liste sein?\n");
scanf("%d", &size);
int arr[size];
for(int i = 0; i < size; ++i) {
int rnd = (rand() % 50) + 1;
arr[i] = rnd;
}
printList(arr, size);
insertSort(arr, size);
printList(arr, size);
return 0;
}
|
the_stack_data/306677.c | #include <stdio.h>
#include <math.h>
int main(int argc, char ** argv) {
double d1 = 3.14;
double d2 = 2.0;
double dr;
dr = d1 * d2;
printf("hello %lf * %lf = %lf\n", d1, d2, dr);
dr = sin(d1);
printf("hello sin(%lf) = %lf\n", d1, dr);
return 0;
}
|
the_stack_data/111078153.c | /* { dg-do compile } */
/* PR c/16531 */
/* { dg-options "-O2 -fdelete-null-pointer-checks -Wnull-dereference" } */
/* { dg-skip-if "" keeps_null_pointer_checks } */
#ifndef __cplusplus
#define NULL (void *)0
#else
#define NULL nullptr
#endif
struct t
{
int bar;
};
struct t2
{
struct t *s;
};
void test1 ()
{
struct t *s = NULL;
s->bar = 1; /* { dg-warning "null" } */
}
void test2 (struct t *s)
{
if (s == NULL && s->bar > 2) /* { dg-warning "null" } */
return;
s->bar = 3;
}
void test3 (struct t *s)
{
if (s != NULL || s->bar > 2) /* { dg-warning "null" } */
return;
s->bar = 3; /* { dg-warning "null" } */
}
int test4 (struct t *s)
{
if (s != NULL && s->bar > 2) /* { dg-bogus "null" } */
return 1;
return 0;
}
int test5 (struct t *s)
{
if (s == NULL || s->bar > 2) /* { dg-bogus "null" } */
return 1;
return 0;
}
int test6 (struct t2 *s)
{
if (s->s == 0 && s->s->bar == 0) /* { dg-warning "null" } */
return 1;
return 0;
}
int test7 (struct t *s)
{
s = 0;
return s->bar; /* { dg-warning "null" } */
}
int test8 ()
{
return ((struct t *)0)->bar; /* { dg-warning "null" } */
}
void test9 (struct t **s)
{
if (s == 0)
*s = 0; /* { dg-warning "null" } */
}
|
the_stack_data/20451420.c | // Modifies the volume of an audio file
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// Define some important structures
typedef uint8_t BYTE;
typedef int16_t TWO_BYTES;
// Number of bytes in .wav header
const int HEADER_SIZE = 44;
int main(int argc, char *argv[])
{
// Check command-line arguments
if (argc != 4)
{
printf("Usage: ./volume input.wav output.wav factor\n");
return 1;
}
// Open files
FILE *input = fopeny(argv[1], "r");
if (input == NULL)
{
printf("Could not open file.\n");
return 1;
}
FILE *output = fopen(argv[2], "w");
if (output == NULL)
{
printf("Could not open file.\n");
return 1;
}
float factor = atof(argv[3]);
BYTE Header[HEADER_SIZE];
// TODO: Copy header from input file to output file
fread(Header, sizeof(BYTE), HEADER_SIZE, input);
fwrite(Header, sizeof(BYTE), HEADER_SIZE, output);
// TODO: Read samples from input file and write updated data to output file
TWO_BYTES buffer;
while (fread(&buffer, sizeof(TWO_BYTES), 1, input) == 1)
{
buffer = buffer * factor;
fwrite(&buffer, sizeof(TWO_BYTES), 1, output);
}
// Close files
fclose(input);
fclose(output);
}
|
the_stack_data/237642358.c | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
int lonelyinteger(int a_size, int* a) {
int i;
int res=0;
for(i = 0; i < a_size; i++){
res = res ^ a[i];
}
return res;
}
int main() {
int res;
int _a_size, _a_i;
scanf("%d", &_a_size);
int _a[_a_size];
for(_a_i = 0; _a_i < _a_size; _a_i++) {
int _a_item;
scanf("%d", &_a_item);
_a[_a_i] = _a_item;
}
res = lonelyinteger(_a_size, _a);
printf("%d", res);
return 0;
} |
the_stack_data/109921.c | /* ISC license. */
#include <unistd.h>
int main (void)
{
_exit(0) ;
}
|
the_stack_data/89394.c | // Punch a module into the kernel with brute force.
// This code assumes that you have total trust into the
// module file because you're about to load it into the
// kernel, so it doesn't protect against maliciously
// crafted or broken ELFs.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sys/klog.h>
#include <string.h>
#include <elf.h>
#define VERMAGIC_NEEDLE_1 ": version magic '"
#define VERMAGIC_NEEDLE_2 "' should be '"
#define Elf_Ehdr Elf32_Ehdr
#define Elf_Shdr Elf32_Shdr
// WTF is up with the init_module(2) manpage? two args, and one of them
// is a totally weird struct? gah.
extern long init_module(void *, unsigned long, const char *);
/* Find a module section: 0 means not found. */
static unsigned int find_sec(Elf_Ehdr *hdr, Elf_Shdr *sechdrs, char *secstrings, const char *name) {
unsigned int i;
for (i = 1; i < hdr->e_shnum; i++) {
Elf_Shdr *shdr = &sechdrs[i];
/* Alloc bit cleared means "ignore it." */
if ((shdr->sh_flags & SHF_ALLOC)
&& strcmp(secstrings + shdr->sh_name, name) == 0)
return i;
}
return 0;
}
static int punch(void *data, off_t *orig_len, char *new_vermagic) {
Elf_Ehdr *hdr = data;
// find .modinfo section
Elf_Shdr *sechdrs = (void *)hdr + hdr->e_shoff;
char *secstrings = (void *)hdr + sechdrs[hdr->e_shstrndx].sh_offset;
unsigned int modinfo_sec_i = find_sec(hdr, sechdrs, secstrings, ".modinfo");
if (modinfo_sec_i == 0) return 1;
Elf_Shdr *modinfo_sec_hdr = &sechdrs[modinfo_sec_i];
char *modinfo_text = data + modinfo_sec_hdr->sh_offset;
// clone section
int modinfo_len = modinfo_sec_hdr->sh_size;
char *new_modinfo = data + *orig_len; /* just append to the end of the elf file */
char *new_modinfo_end = new_modinfo + modinfo_len;
memcpy(new_modinfo, modinfo_text, modinfo_len);
// wipe old vermagic
char *modinfo_vermagic;
if (memcmp(new_modinfo, "vermagic=", 9) == 0) {
modinfo_vermagic = new_modinfo;
} else {
modinfo_vermagic = memmem(new_modinfo, modinfo_len, "\0vermagic=", 10)+1;
}
if (modinfo_vermagic != NULL+1) {
int vermagic_len = strlen(modinfo_vermagic)+1;
printf("deleting %i bytes of old vermagic ('%s') from copied modinfo section\n", vermagic_len, modinfo_vermagic);
char *vermagic_end = modinfo_vermagic+vermagic_len;
memmove(modinfo_vermagic, vermagic_end, new_modinfo_end - vermagic_end);
modinfo_len -= vermagic_len;
new_modinfo_end -= vermagic_len;
} else {
printf("warning: no old modinfo found!\n");
}
// append new vermagic
strcpy(new_modinfo_end, "vermagic=");
strcpy(new_modinfo_end+9, new_vermagic);
modinfo_len += 9+strlen(new_vermagic)+1;
// update pointer for new section
modinfo_sec_hdr->sh_offset = *orig_len;
modinfo_sec_hdr->sh_size = modinfo_len;
*orig_len += modinfo_len;
// At this point, I thought: "Oh damn, what do I do about sh_addr? How can I find
// a free memory location? Oh nooooes!!!"
// Turns out the first thing the kernel does with that field is to overwrite it. :/
modinfo_sec_hdr->sh_addr = 0; // crash if I'm wrong
return 0;
}
int extract_vermagic(char *buf, size_t len, char **result, size_t *result_len) {
char *ptr = buf, *end = buf+len;
while (1) {
char *lineend = memchr(ptr, '\0', end-ptr);
if (lineend == NULL) break;
char *needle1_pos = memmem(ptr, lineend-ptr, VERMAGIC_NEEDLE_1, strlen(VERMAGIC_NEEDLE_1));
if (needle1_pos == NULL) goto next;
char *needle2_pos = memmem(needle1_pos, lineend-needle1_pos, VERMAGIC_NEEDLE_2, strlen(VERMAGIC_NEEDLE_2));
if (needle2_pos == NULL) goto next;
// wheee, found it!
*result = needle2_pos + strlen(VERMAGIC_NEEDLE_2);
char *vermagic_end = strchr(*result, '\'');
if (vermagic_end == NULL) goto next;
*result_len = vermagic_end - *result;
return 0;
next:
ptr = lineend+1;
}
return 1;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("call with two args (path, options [yes, as one argument!]), please!\n");
exit(1);
}
int fd = open(argv[1], O_RDONLY);
if (fd < 0) {
printf("can't open file: %s\n", strerror(errno));
exit(1);
}
struct stat st;
if (fstat(fd, &st)) {
printf("can't stat opened file: %s\n", strerror(errno));
exit(1);
}
void *data = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd, 0);
if (!init_module(data, st.st_size, argv[2])) {
// whoah, everything went fine? exact vermagic match,
// no need to punch? :( - I want to punch!
exit(0);
}
if (errno != ENOEXEC) {
printf("init_module syscall failed with error (might be VERY misleading): %s\n", strerror(errno));
exit(1);
}
// we'll just guess it's because of a vermagic mismatch for now.
printf("no luck the friendly way, going to try it with a punch...\n");
// extract needed vermagic
char dmesg_buf[10001];
klogctl(3, dmesg_buf, sizeof(dmesg_buf)-1);
char *needed_vermagic;
size_t vermagic_length;
if (extract_vermagic(dmesg_buf, sizeof(dmesg_buf), &needed_vermagic, &vermagic_length)) {
printf("module loading attempt failed with ENOEXEC and there's no vermagic mismatch in the syslog; aborting.\n");
exit(1);
}
needed_vermagic[vermagic_length] = '\0';
printf("needed vermagic: %s\n", needed_vermagic);
// hairy part: fix the vermagic!
char *old_data = data;
data = malloc(st.st_size + 1024 /* just assume modinfo is smaller than this */);
memcpy(data, old_data, st.st_size);
munmap(old_data, st.st_size);
if (punch(data, &st.st_size, needed_vermagic)) {
printf("internal punching failure - did you supply a valid ELF?\n");
exit(1);
}
// debug code
/*
int outfd = open("/tmp/punchdebug.ko", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
write(outfd, data, st.st_size);
close(outfd);
*/
// now try loading this
if (init_module(data, st.st_size, argv[2])) {
printf("init_module syscall failed with error (might be VERY misleading): %s\n", strerror(errno));
return 1;
} else {
printf("successfully punched the small bitblob into almighty bitblob! :)\n");
return 0;
}
}
|
the_stack_data/852771.c | /* cache_info.c: this program gets the standard information:
level, type (data, instruction, or unified)
line_size
sets
associativity
cache_size
about the caches (L1-instruction/data and L2) on a linux system
by reading the system files under the directory:
/sys/devices/system/cpu/cpu0/cache/index[012]/
it then displays the information on the screen. Note that normally
index=0 is L1-cache data, index=1 is L1-cache instruction, and
index=2 is the L2-cache (unified).
It assumes the standard breakdown of an address into,
for example:
----------------------------------------------------
| tag | set or index (10) | byte number (6) |
----------------------------------------------------
If also checks the parameters for consistency, since it
SHOULD be the case that
line_size * sets * associativity = cache_size */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <signal.h>
#include <math.h>
#include <sys/resource.h>
#include <errno.h>
#define CA_DIRECTORY "/sys/devices/system/cpu/cpu0/cache/"
#define CA_LINE_SIZE "coherency_line_size"
#define CA_SETS "number_of_sets"
#define CA_ASSOCIATIVITY "ways_of_associativity"
#define CA_SIZE "size"
#define CA_TYPE "type"
#define CA_LEVEL "level"
/* ---------------------------------------------------------------- */
int main(int argc, char *argv[], char *envp[])
{
char pathname[256];
int num, ret;
FILE *ftemp;
int pagesize; /* usually 4K-8K */
int line_size; /* number of bytes in a cache line */
int sets; /* number of rows in the cache; "set"
is sometimes called "index" */
int pages_per_block; /* (line_size * sets)/pagesize */
int level; /* 1, 2, or 3 (if present) */
int associativity; /* set way associativity */
int cache_size; /* total bytes needed for the cache */
char type[256]; /* instruction, data, or unified */
int temp1, temp2;
char cache_mult; /* 'K' or 'M' */
pagesize = getpagesize(); /* get the page size */
/* go through each cache */
for (num = 0 ; num <= 3 ; num++)
{
/* ---------------------------- .../index[012]/level */
sprintf(pathname, "%sindex%d/%s",
CA_DIRECTORY, num, CA_LEVEL);
ftemp = fopen(pathname, "r");
if (ftemp == (FILE *)NULL)
{
fflush(stdout); fprintf(stderr,
"\n *** fatal error: no such file: %s",
pathname);
return(-1);
}
else
{
ret = fscanf(ftemp, "%d", &level);
if (ret != 1)
{
fflush(stdout); fprintf(stderr,
"\n *** fatal error: read failed on: %s",
pathname);
fclose(ftemp);
return(-1);
}
fclose(ftemp);
}
/* ---------------------------- .../index[012]/type */
sprintf(pathname, "%sindex%d/%s",
CA_DIRECTORY, num, CA_TYPE);
ftemp = fopen(pathname, "r");
if (ftemp == (FILE *)NULL)
{
fflush(stdout); fprintf(stderr,
"\n *** fatal error: no such file: %s",
pathname);
return(-1);
}
else
{
ret = fscanf(ftemp, "%s", type);
if (ret != 1)
{
fflush(stdout); fprintf(stderr,
"\n *** fatal error: read failed on: %s",
pathname);
fclose(ftemp);
return(-1);
}
fclose(ftemp);
}
/* ---------------------------- .../index[012]/coherency_line_size */
sprintf(pathname, "%sindex%d/%s",
CA_DIRECTORY, num, CA_LINE_SIZE);
ftemp = fopen(pathname, "r");
if (ftemp == (FILE *)NULL)
{
fflush(stdout); fprintf(stderr,
"\n *** fatal error: no such file: %s",
pathname);
return(-1);
}
else
{
ret = fscanf(ftemp, "%d", &line_size);
if (ret != 1)
{
fflush(stdout); fprintf(stderr,
"\n *** fatal error: read failed on: %s",
pathname);
fclose(ftemp);
return(-1);
}
fclose(ftemp);
}
/* ---------------------------- .../index[012]/number_of_sets */
sprintf(pathname, "%sindex%d/%s",
CA_DIRECTORY, num, CA_SETS);
ftemp = fopen(pathname, "r");
if (ftemp == (FILE *)NULL)
{
fflush(stdout); fprintf(stderr,
"\n *** fatal error: no such file: %s",
pathname);
return(-1);
}
else
{
ret = fscanf(ftemp, "%d", &sets);
if (ret != 1)
{
fflush(stdout); fprintf(stderr,
"\n *** fatal error: read failed on: %s",
pathname);
fclose(ftemp);
return(-1);
}
fclose(ftemp);
}
/* ---------------------------- .../index[012]/ways_of_associativity */
sprintf(pathname, "%sindex%d/%s",
CA_DIRECTORY, num, CA_ASSOCIATIVITY);
ftemp = fopen(pathname, "r");
if (ftemp == (FILE *)NULL)
{
fflush(stdout); fprintf(stderr,
"\n *** fatal error: no such file: %s",
pathname);
return(-1);
}
else
{
ret = fscanf(ftemp, "%d", &associativity);
if (ret != 1)
{
fflush(stdout); fprintf(stderr,
"\n *** fatal error: read failed on: %s",
pathname);
fclose(ftemp);
return(-1);
}
fclose(ftemp);
}
/* ---------------------------- .../index[012]/size */
sprintf(pathname, "%sindex%d/%s",
CA_DIRECTORY, num, CA_SIZE);
ftemp = fopen(pathname, "r");
if (ftemp == (FILE *)NULL)
{
fflush(stdout); fprintf(stderr,
"\n *** fatal error: no such file: %s",
pathname);
return(-1);
}
else
{
ret = fscanf(ftemp, "%d%c", &cache_size,
&cache_mult);
if (ret != 2)
{
fflush(stdout); fprintf(stderr,
"\n *** fatal error: read failed on: %s",
pathname);
fclose(ftemp);
return(-1);
}
fclose(ftemp);
}
/* now print out info */
pages_per_block = (line_size * sets)/pagesize;
printf("\nParameters for the L%d cache (%s):",
level, type);
printf("\n");
printf("\n line_size= %8d ", line_size);
printf("\n sets= %8d ", sets);
printf("\n pages per block= %8d (pagesize= %8d)",
pages_per_block, pagesize);
printf("\n associativity= %8d-way set associative",
associativity);
printf("\n cache_size= %8d%c bytes total", cache_size,
cache_mult);
/* check consistency of size */
temp1 = line_size * sets * associativity;
if (cache_mult == 'K')
temp2 = cache_size * 1024;
else if (cache_mult == 'M')
temp2 = cache_size * 1024 * 1024;
else
goto no_test;
if (temp1 != temp2)
printf("\n *** warning: sizes differ %d %d ***",
temp1, temp2);
no_test:
printf("\n");
}
printf("\n\n");
return(0); /* successful */
} /* end of main */
|
the_stack_data/86074956.c | // RUN: %clang_builtins %s %librt -fnested-functions -o %t && %run %t
/* ===-- trampoline_setup_test.c - Test __trampoline_setup -----------------===
*
* The LLVM Compiler Infrastructure
*
* This file is dual licensed under the MIT and the University of Illinois Open
* Source Licenses. See LICENSE.TXT for details.
*
* ===----------------------------------------------------------------------===
*/
#include <stdio.h>
#include <string.h>
#include <stdint.h>
/*
* Tests nested functions
* The ppc compiler generates a call to __trampoline_setup
* The i386 and x86_64 compilers generate a call to ___enable_execute_stack
*/
/*
* Note that, nested functions are not ISO C and are not supported in Clang.
*/
#if !defined(__clang__)
typedef int (*nested_func_t)(int x);
nested_func_t proc;
int main() {
/* Some locals */
int c = 10;
int d = 7;
/* Define a nested function: */
int bar(int x) { return x*5 + c*d; };
/* Assign global to point to nested function
* (really points to trampoline). */
proc = bar;
/* Invoke nested function: */
c = 4;
if ( (*proc)(3) != 43 )
return 1;
d = 5;
if ( (*proc)(4) != 40 )
return 1;
/* Success. */
return 0;
}
#else
int main() {
printf("skipped\n");
return 0;
}
#endif
|
the_stack_data/728919.c | extern unsigned int _DATA_ROM_START;
extern unsigned int _DATA_RAM_START;
extern unsigned int _DATA_RAM_END;
extern unsigned int _BSS_START;
extern unsigned int _BSS_END;
#define STACK_TOP 0x20008000
// Predefine startup function
void startup();
/**
* Define vector table
*/
unsigned int *vectorTable[2] __attribute__((section("vectors"))) = {
(unsigned int *)STACK_TOP, // Stack pointer
(unsigned int *)(&startup) // Reset vector
};
void main();
void startup()
{
// Create pointers for sections
unsigned int *data_rom_start_p = &_DATA_ROM_START;
unsigned int *data_ram_start_p = &_DATA_RAM_START;
unsigned int *data_ram_end_p = &_DATA_RAM_END;
unsigned int *_bss_start_p = &_BSS_START;
unsigned int *_bss_end_p = &_BSS_END;
// Copy .data from ROM to RAM
while (data_ram_start_p != data_ram_end_p)
{
*data_ram_start_p = *data_rom_start_p;
data_ram_start_p++;
data_rom_start_p++;
}
// Initialize .bss with nulls
while (_bss_start_p != _bss_end_p)
{
*_bss_start_p = 0;
_bss_start_p++;
}
// Call main function
main();
} |
the_stack_data/962286.c | #include <stdio.h>
#include <string.h>
int* hop(int *elem);
int is_in_bound(int *arr, int size, int *ptr);
int main()
{
int arr[50],h=0,i=0;
int *ptr;
while(scanf("%d",&arr[i]) != EOF && i<50)
{
i=i+1;
}
ptr=&arr[0];
//printf("%d\n",*ptr);
do{
if (*ptr==0)
{
printf("1\n");
break;
}
ptr=hop(ptr);
h++;
//printf("\n %d",*ptr);
if (is_in_bound(arr,i,ptr)==0 || h>49)
{
printf("0\n");
break;
}
//printf("\nj=%d",j);
}while(1);
printf("%d\n",h);
return 0;
}
int * hop(int *elem)
{
elem=elem+ *elem;
return(elem);
}
int is_in_bound(int *arr, int size, int *ptr)
{
if((ptr - arr < 0) || (ptr - arr >size))
{
return 0;
}
return 1;
}
|
the_stack_data/671524.c | main()
{ int i, j,k ,r;
i =3 ;
j=4 ;
k=8 ;
printf (i) ;
r=(i+j)*(i+k/j) ;
printf ( r ) ;
} |
the_stack_data/38912.c | #define _GNU_SOURCE
#include <unistd.h>
#include <sys/mman.h>
/**
* Boilerplate to create an in-memory shared file.
*
* Link with `-lrt`.
*/
int create_shm_file(off_t size) {
int fd = memfd_create("shm", MFD_CLOEXEC | MFD_ALLOW_SEALING);
if (fd < 0) {
return fd;
}
if (ftruncate(fd, size) < 0) {
close(fd);
return -1;
}
return fd;
}
|
the_stack_data/97150.c | #include<stdio.h>
#include<stdlib.h>
int power(int m, int n){
if(n == 0){
return 1;
}
return power(m, n-1) * m;
}
int effPower(int m, int n){
if(n == 0){
return 1;
}
else if(n%2 == 0){
return effPower(m*m, n/2);
}
return effPower(m*m, (n-1)/2) * m;
}
int main() {
printf("%d\nMore efficient function: %d", power(2, 9), effPower(2, 9));
return 0;
}
|
the_stack_data/1248051.c | #include <pwd.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
void substitute_home_directory(char * working_directory, const char* home_directory)
{
char * home_directory_ptr = strstr(working_directory, home_directory);
if (home_directory_ptr != NULL)
{
strcpy(working_directory+1,working_directory+strlen(home_directory));
working_directory[0] = '~';
}
}
bool is_whitespace(char c)
{
return c == ' ' || c == '\t' || c == '\n';
}
unsigned int count_args(char * command)
{
unsigned int num_args = 0;
unsigned int i = 0;
// Get to first argument
while (is_whitespace(command[i]))
{
i++;
}
// While not at the end
while(command[i] != '\0')
{
// Parse one argument
while(!is_whitespace(command[i]) && command[i] != '\0')
{
i++;
}
num_args++;
// Get to the next argument
while (is_whitespace(command[i]))
{
i++;
}
}
return num_args;
}
char ** parse_command_args(char * command, ssize_t command_length, unsigned int * num_args_ptr)
{
*num_args_ptr = count_args(command);
// Add one because the last arg must be NULL
char ** args = (char**) malloc(*num_args_ptr*sizeof(char*)+1);
unsigned int i = 0;
// Create a copy because strtok destroys command
char * command_copy = strdup(command);
char* token = strtok(command_copy, " ");
// && i < num_args because strtok will pick up a trailing space
while (token != NULL && i < *num_args_ptr) {
args[i] = token;
token = strtok(NULL, " ");
i++;
}
// Set last arg to NULL
args[i] = NULL;
return args;
}
unsigned int is_child(pid_t pid)
{
if (pid == 0) { return 1; }
else { return 0; }
}
// Execute the command with execvp
void execute_command(char ** args)
{
execvp(args[0], args);
}
#define MAX_WORKING_DIRECTORY_SIZE 256
#define MAX_HOSTNAME_SIZE 256
// ANSI Color Codes
#define BLACK "\x1b[30m"
#define RED "\x1b[31m"
#define GREEN "\x1b[32m"
#define LIGHT_GREEN "\x1b[92m"
#define YELLOW "\x1b[33m"
#define BLUE "\x1b[34m"
#define LIGHT_BLUE "\x1b[94m"
#define MAGENTA "\x1b[35m"
#define CYAN "\x1b[36m"
#define WHITE "\x1b[37m"
#define RESET "\x1b[0m"
int main()
{
char * command = NULL;
size_t command_allocated_size = 0;
bool running = true;
char * username = getlogin();
char hostname[MAX_HOSTNAME_SIZE];
gethostname(hostname, MAX_HOSTNAME_SIZE);
uid_t user_uid = getuid();
struct passwd *user_passwd = getpwuid(user_uid);
const char *home_directory = user_passwd->pw_dir;
char working_directory[MAX_WORKING_DIRECTORY_SIZE];
while (running)
{
getcwd(working_directory, MAX_WORKING_DIRECTORY_SIZE);
substitute_home_directory(working_directory, home_directory);
printf(LIGHT_GREEN "%s@%s" WHITE ":" LIGHT_BLUE "%s" WHITE "$ " RESET, username, hostname, working_directory);
ssize_t num_characters_read = getline(&command, &command_allocated_size, stdin);
// Remove the trailing newline from the command
command[strlen(command)-1] = '\0';
unsigned int num_args = -1;
char ** args = parse_command_args(command, num_characters_read, &num_args);
pid_t child = fork();
if (is_child(child))
{
execute_command(args);
}
else
{
int child_exit_status;
waitpid(child, &child_exit_status, 0);
}
}
} |
the_stack_data/167330047.c | #include <signal.h>
int sigrelse(int sig)
{
sigset_t mask;
sigemptyset(&mask);
if (sigaddset(&mask, sig) < 0) return -1;
return sigprocmask(SIG_UNBLOCK, &mask, 0);
}
|
the_stack_data/8257.c | #include <stdio.h>
#include <stdlib.h>
#define size 4
typedef struct pile
{
int top;
int possibleTeacher[size];
} class;
int initPile(class *pile)
{
(*pile).top = -1;
return 0;
}
int check(class *pile)
{
if ((*pile).top == -1)
return 0; /* pilha vazia */
else
{
if ((*pile).top == size - 1)
return 1; /* pilha cheia */
else
return 2; /* pilha não vazia com capacidade de armazenamento */
}
}
int push(class *pile, int possibleTeacher)
{
int feedback = check(pile);
if ((feedback == 0) || (feedback == 2))
{
(*pile).top++;
(*pile).possibleTeacher[(*pile).top] = possibleTeacher;
return 0;
}
else
return feedback;
}
char pop(class *pile)
{
int feedback = check(pile);
if (feedback != 0)
{
int remove = pile->possibleTeacher[pile->top];
pile->top--;
//printf("\nPOP %d", remove);
return remove;
}
else
return feedback;
}
int listPile(class pile)
{
int feedback = check(&pile);
if ((feedback == 1) || (feedback == 2))
{
printf("\n -----|TOPO|-----\n");
for (int i = pile.top; i >= 0; i--)
{
printf("\t%d\n", (&pile)->possibleTeacher[i]);
}
printf(" -----|BASE|-----\n\n");
system("pause");
return 0;
}
else
return feedback; /* nao possivel listar pois a pilha vazia */
}
/* ----------------------------
------------FUNÇÕES------------
-----------------------------*/
int addData(int nPessoas, int matriz[][size], class *pile)
{
printf("\nDigite 1 para SIM e 0 para NAO\n\n");
for (int linha = 0; linha < nPessoas; linha++)
push(pile, linha);
for (int linha = 0; linha < nPessoas; linha++)
{
printf("\n----- | PESSOA %d | -----\n", pile->possibleTeacher[linha]);
for (int coluna = 0; coluna < nPessoas; coluna++)
{
if (linha != coluna)
{
printf("\nReconhece pessoa %d ? : ", pile->possibleTeacher[coluna]);
scanf("%d", &matriz[linha][coluna]);
}
else
matriz[linha][coluna] = 0;
}
printf("\n\n");
}
}
int listData(int nPessoas, int matriz[][size])
{
printf("\n\t ----- | MATRIZ | -----\n\n");
// printf("------");
// for (int coluna = 0; coluna < nPessoas; coluna++)
// {
// printf("\t| %d |", coluna);
// }
printf("\n");
for (int linha = 0; linha < nPessoas; linha++)
{
printf(" | %d | ", linha);
for (int coluna = 0; coluna < nPessoas; coluna++)
{
printf("\t%d", matriz[linha][coluna]);
}
printf("\n\n");
}
system("pause");
}
int analyzeData(int nPessoas, int matriz[][size], class *pile)
{
while (pile->top != 0)
{
int peopleToCompare[2];
peopleToCompare[0] = pop(pile); // 3
peopleToCompare[1] = pop(pile); // 4
// printf("\nPOP %d", peopleToCompare[0]);
//printf("\nPOP %d", peopleToCompare[1]);
//Se A reconhece B, então A não pode ser o professor e B volta para a pilha
if (matriz[peopleToCompare[0]][peopleToCompare[1]] == 1)
{
// printf("\n%d nao pode ser professor, reconheceu %d ", peopleToCompare[0], peopleToCompare[1]);
//printf("\nPUSH %d", peopleToCompare[1]);
push(pile, peopleToCompare[1]);
}
//Se A não reconhece B, então B não pode o professor e A volta para a pilha.
else
{
//printf("\n%d nao pode ser professor, nao foi reconhecido por %d ", peopleToCompare[1], peopleToCompare[0]);
// printf("\nPUSH %d", peopleToCompare[0]);
push(pile, peopleToCompare[0]);
}
printf("\n\n");
}
int flag = 1;
int possibleTeacher = pop(pile);
for (int i = 0; i < size; i++)
{
if (i != possibleTeacher && matriz[possibleTeacher][i] == 1)
{
flag = 0;
}
}
for (int i = 0; i < size; i++)
{
if (i != possibleTeacher && matriz[i][possibleTeacher] == 0)
{
flag = 0;
}
}
if (flag == 1)
{
printf("\nProfessor = %d\n\n", possibleTeacher);
}
else
{
printf("\nProfessor = professor nao esta na sala");
}
system("pause");
}
/* ----------------------------
-------------MAIN--------------
-----------------------------*/
int main(void)
{
int q;
int nPessoas = size;
int matriz[size][size];
class pile;
initPile(&pile);
do
{
system("cls");
printf("1 -> Adicionar dados\n");
printf("2 -> Listar dados\n");
printf("3 -> Analisar dados\n");
printf("4 -> Listar pilha\n");
printf("\nOpcao: ");
scanf("%d", &q);
switch (q)
{
case 1:
addData(nPessoas, matriz, &pile);
break;
case 2:
listData(nPessoas, matriz);
break;
case 3:
analyzeData(nPessoas, matriz, &pile);
break;
case 4:
listPile(pile);
break;
case 9:
break;
default:
printf("\n\n Opcao invalida\n");
break;
}
getchar();
} while ((q != 9));
return 0;
}
|
the_stack_data/50350.c | /*
* Kubos Linux
* Copyright (C) 2017 Kubos Corporation
*
* Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* 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.
*/
#include <stdio.h>
int main(void)
{
printf("Hello World!\n");
return 0;
}
|
the_stack_data/77416.c | #define _XOPEN_SOURCE 500
#include <limits.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static struct {
const char *argv0;
char end;
} opt;
static int do_dynamic_readlink(const char *path)
{
char *buf;
size_t len;
ssize_t ret;
len = PATH_MAX * 2;
for (;;) {
buf = malloc(len);
if (!buf) {
fprintf(stderr, "%s: unable to allocate: %s\n",
opt.argv0, strerror(errno));
return -1;
}
ret = readlink(path, buf, sizeof(buf));
if (ret < 0) {
fprintf(stderr, "%s: %s: %s\n",
opt.argv0, path, strerror(errno));
return -1;
}
if (ret == sizeof(buf)) {
free(buf);
len += PATH_MAX;
continue;
}
buf[ret] = '\0';
printf("%s%c", buf, opt.end);
free(buf);
return 0;
}
return 0;
}
static int do_readlink(const char *path)
{
char buf[PATH_MAX];
ssize_t ret;
ret = readlink(path, buf, sizeof(buf));
if (ret < 0) {
fprintf(stderr, "%s: %s: %s\n",
opt.argv0, path, strerror(errno));
return -1;
}
if (ret == sizeof(buf))
return do_dynamic_readlink(path);
buf[ret] = '\0';
printf("%s%c", buf, opt.end);
return 0;
}
/* Usage: readlink [-n] [PATH...] */
int main(int argc, const char *argv[])
{
int i, ret;
opt.argv0 = argv[0];
opt.end = '\n';
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-') {
break;
} else if (!strcmp(argv[i], "-n")) {
opt.end = '\0';
} else {
fprintf(stderr, "%s: invalid argument: %s\n",
argv[0], argv[i]);
return 1;
}
}
if (i == argc) {
fprintf(stderr, "%s: missing operand\n", argv[0]);
return 1;
}
ret = 0;
for (; i < argc; i++) {
if (do_readlink(argv[i]))
ret = 1;
}
return ret;
}
|
the_stack_data/132951812.c | /**************************************************
* MATRIX MULTIPLICATION: Steps from C to Assembly *
**************************************************/
#include <stdio.h>
void print1D(int *array, int rows, int cols) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j)
printf("%d ", array[i*cols + j]);
printf("\n");
}
printf("\n\n");
}
void zero1D(int *array, int size) {
for (int i = 0; i < size; ++i)
array[i] = 0;
}
int main(void) {
int i, j, k;
int r1 = 2, c1 = 3, r2 = 3, c2 = 4;
/********************************************************************
** 2D Arrays
********************************************************************/
int a1[2][3] = { {1, 2, 3}, {4, 5, 6} };
int b1[3][4] = { {1, 2, 3, 4}, {4, 4, 3, 2}, {9, 7, 6, 4 } };
int result1[2][4] = { 0 };
for (i = 0; i < r1; ++i)
for (j = 0; j < c2; ++j)
for (k = 0; k < c1; ++k)
result1[i][j] += a1[i][k] * b1[k][j];
for (i = 0; i < r1; ++i) {
for (j = 0; j < c2; ++j)
printf("%d ", result1[i][j]);
printf("\n");
}
printf("\n\n");
/********************************************************************
** 1D Arrays representing 2D Arrays
********************************************************************/
int a2[2*3] = { 1, 2, 3, 4, 5, 6 };
int b2[3*4] = { 1, 2, 3, 4, 4, 4, 3, 2, 9, 7, 6, 4 };
int result2[2*4] = { 0 };
for (i = 0; i < r1; ++i)
for (j = 0; j < c2; ++j)
for (k = 0; k < c1; ++k)
result2[i*c2 + j] += a2[i*c1 + k] * b2[k*c2 + j];
print1D(result2, r1, c2);
zero1D(result2, r1*c2);
/********************************************************************
** GoTo instead of for-loops
********************************************************************/
int aa, bb;
int *ptrA = a2;
int *ptrB = b2;
int *res = result2;
int x, y, xytmp, xy;
i = 0;
outer1:
j = 0;
middle1:
k = 0;
inner1:
x = *(ptrA + i*c1 + k);
y = *(ptrB + k*c2 + j);
xy = x*y;
xytmp = *(res + i*c2 + j);
*(res + i*c2 + j) = xytmp + xy;
k++;
if (k < c1) goto inner1;
j++;
if (j < c2) goto middle1;
i++;
if (i < r1) goto outer1;
print1D(result2, r1, c2);
zero1D(result2, r1*c2);
/********************************************************************
** pointer/label arithmetic instead of array[i*cols + j]
********************************************************************/
i = 0;
outer2:
j = 0;
middle2:
k = 0;
inner2:
x = *ptrA;
y = *ptrB;
xy = x * y;
*res += xy;
k++;
ptrA++;
ptrB += c2;
if (k < c1) goto inner2;
j++;
ptrA -= k;
ptrB = b2 + j;
res++;
if (j < c2) goto middle2;
i++;
ptrA += c1;
ptrB = b2;
res += c2 - j;
if (i < r1) goto outer2;
print1D(result2, r1, c2);
/********************************************************************
** CEAL code in matrix_mult_o.sca
********************************************************************/
return 0;
}
|
the_stack_data/98573951.c | /* jsmin.c
2013-03-29
Copyright (c) 2002 Douglas Crockford (www.crockford.com)
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 shall be used for Good, not Evil.
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.
*/
#include <stdlib.h>
#include <stdio.h>
FILE *jsmin_in = NULL;
FILE *jsmin_out = NULL;
static int theA;
static int theB;
static int theLookahead = EOF;
static int theX = EOF;
static int theY = EOF;
static void
error(const char* s)
{
fputs("JSMIN Error: ", stderr);
fputs(s, stderr);
fputc('\n', stderr);
exit(1);
}
/* isAlphanum -- return true if the character is a letter, digit, underscore,
dollar sign, or non-ASCII character.
*/
static int
isAlphanum(int c)
{
return ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'Z') || c == '_' || c == '$' || c == '\\' ||
c > 126);
}
/* get -- return the next character from stdin. Watch out for lookahead. If
the character is a control character, translate it to a space or
linefeed.
*/
static int
get()
{
int c = theLookahead;
theLookahead = EOF;
if (c == EOF) {
c = getc(jsmin_in);
}
if (c >= ' ' || c == '\n' || c == EOF) {
return c;
}
if (c == '\r') {
return '\n';
}
return ' ';
}
/* peek -- get the next character without getting it.
*/
static int
peek()
{
theLookahead = get();
return theLookahead;
}
/* next -- get the next character, excluding comments. peek() is used to see
if a '/' is followed by a '/' or '*'.
*/
static int
next()
{
int c = get();
if (c == '/') {
switch (peek()) {
case '/':
for (;;) {
c = get();
if (c <= '\n') {
break;
}
}
break;
case '*':
get();
while (c != ' ') {
switch (get()) {
case '*':
if (peek() == '/') {
get();
c = ' ';
}
break;
case EOF:
error("Unterminated comment.");
}
}
break;
}
}
theY = theX;
theX = c;
return c;
}
/* action -- do something! What you do is determined by the argument:
1 Output A. Copy B to A. Get the next B.
2 Copy B to A. Get the next B. (Delete A).
3 Get the next B. (Delete B).
action treats a string as a single character. Wow!
action recognizes a regular expression if it is preceded by ( or , or =.
*/
static void
action(int d)
{
switch (d) {
case 1:
putc(theA, jsmin_out);
if (
(theY == '\n' || theY == ' ') &&
(theA == '+' || theA == '-' || theA == '*' || theA == '/') &&
(theB == '+' || theB == '-' || theB == '*' || theB == '/')
) {
putc(theY, jsmin_out);
}
case 2:
theA = theB;
if (theA == '\'' || theA == '"' || theA == '`') {
for (;;) {
putc(theA, jsmin_out);
theA = get();
if (theA == theB) {
break;
}
if (theA == '\\') {
putc(theA, jsmin_out);
theA = get();
}
if (theA == EOF) {
error("Unterminated string literal.");
}
}
}
case 3:
theB = next();
if (theB == '/' && (
theA == '(' || theA == ',' || theA == '=' || theA == ':' ||
theA == '[' || theA == '!' || theA == '&' || theA == '|' ||
theA == '?' || theA == '+' || theA == '-' || theA == '~' ||
theA == '*' || theA == '/' || theA == '{' || theA == '\n'
)) {
putc(theA, jsmin_out);
if (theA == '/' || theA == '*') {
putc(' ', jsmin_out);
}
putc(theB, jsmin_out);
for (;;) {
theA = get();
if (theA == '[') {
for (;;) {
putc(theA, jsmin_out);
theA = get();
if (theA == ']') {
break;
}
if (theA == '\\') {
putc(theA, jsmin_out);
theA = get();
}
if (theA == EOF) {
error("Unterminated set in Regular Expression literal.");
}
}
} else if (theA == '/') {
switch (peek()) {
case '/':
case '*':
error("Unterminated set in Regular Expression literal.");
}
break;
} else if (theA =='\\') {
putc(theA, jsmin_out);
theA = get();
}
if (theA == EOF) {
error("Unterminated Regular Expression literal.");
}
putc(theA, jsmin_out);
}
theB = next();
}
}
}
/* jsmin -- Copy the input to the output, deleting the characters which are
insignificant to JavaScript. Comments will be removed. Tabs will be
replaced with spaces. Carriage returns will be replaced with linefeeds.
Most spaces and linefeeds will be removed.
*/
void
jsmin(void)
{
if (peek() == 0xEF) {
get();
get();
get();
}
theA = '\n';
action(3);
while (theA != EOF) {
switch (theA) {
case ' ':
action(isAlphanum(theB) ? 1 : 2);
break;
case '\n':
switch (theB) {
case '{':
case '[':
case '(':
case '+':
case '-':
case '!':
case '~':
action(1);
break;
case ' ':
action(3);
break;
default:
action(isAlphanum(theB) ? 1 : 2);
}
break;
default:
switch (theB) {
case ' ':
action(isAlphanum(theA) ? 1 : 3);
break;
case '\n':
switch (theA) {
case '}':
case ']':
case ')':
case '+':
case '-':
case '"':
case '\'':
case '`':
action(1);
break;
default:
action(isAlphanum(theA) ? 1 : 3);
}
break;
default:
action(1);
break;
}
}
}
}
|
Subsets and Splits