file
stringlengths
18
26
data
stringlengths
2
1.05M
the_stack_data/485591.c
/* BAREOS® - Backup Archiving REcovery Open Sourced Copyright (C) 2009-2011 Free Software Foundation Europe e.V. This program is Free Software; you can redistribute it and/or modify it under the terms of version three of the GNU Affero General Public License as published by the Free Software Foundation and included in the file LICENSE. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * Program to test Ingres DB routines * * Stefan Reddig, February 2010 * * reusing code by * Eric Bollengier, August 2009 */ #ifdef needed #include "bareos.h" #include "cats/cats.h" #include "cats/sql_glue.h" /* Local variables */ static B_DB *db; static const char *file = "COPYRIGHT"; //static DBId_t fnid=0; static const char *db_name = "bareos"; static const char *db_user = "bareos"; static const char *db_password = ""; static const char *db_host = NULL; static void usage() { fprintf(stderr, _( PROG_COPYRIGHT "\nVersion: %s (%s)\n" " -d <nn> set debug level to <nn>\n" " -dt print timestamp in debug output\n" " -n <name> specify the database name (default bareos)\n" " -u <user> specify database user name (default bareos)\n" " -P <password specify database password (default none)\n" " -h <host> specify database host (default NULL)\n" " -w <working> specify working directory\n" " -j <jobids> specify jobids\n" " -p <path> specify path\n" " -f <file> specify file\n" " -l <limit> maximum tuple to fetch\n" " -T truncate cache table before starting\n" " -v verbose\n" " -? print this message\n\n"), 2001, VERSION, BDATE); exit(1); } /* * simple handler for debug output of CRUD example */ static int test_handler(void *ctx, int num_fields, char **row) { Pmsg2(0, " Values are %d, %s\n", str_to_int64(row[0]), row[1]); return 0; } /* * string handler for debug output of simple SELECT tests */ static int string_handler(void *ctx, int num_fields, char **row) { Pmsg1(0, " Value is >>%s<<\n", row[0]); return 0; } /* number of thread started */ int main (int argc, char *argv[]) { int ch; char *jobids = (char *)"1"; char *path=NULL, *client=NULL; uint64_t limit=0; bool clean=false; setlocale(LC_ALL, ""); bindtextdomain("bareos", LOCALEDIR); textdomain("bareos"); init_stack_dump(); Dmsg0(0, "Starting ing_test tool\n"); my_name_is(argc, argv, "ing_test"); init_msg(NULL, NULL); OSDependentInit(); while ((ch = getopt(argc, argv, "h:c:l:d:n:P:Su:vf:w:?j:p:f:T")) != -1) { switch (ch) { case 'd': /* debug level */ if (*optarg == 't') { dbg_timestamp = true; } else { debug_level = atoi(optarg); if (debug_level <= 0) { debug_level = 1; } } break; case 'l': limit = str_to_int64(optarg); break; case 'c': client = optarg; break; case 'h': db_host = optarg; break; case 'n': db_name = optarg; break; case 'w': working_directory = optarg; break; case 'u': db_user = optarg; break; case 'P': db_password = optarg; break; case 'v': verbose++; break; case 'p': path = optarg; break; case 'f': file = optarg; break; case 'j': jobids = optarg; break; case 'T': clean = true; break; case '?': default: usage(); } } argc -= optind; argv += optind; if (argc != 0) { Pmsg0(0, _("Wrong number of arguments: \n")); usage(); } if ((db = db_init_database(NULL, "ingres", db_name, db_user, db_password, db_host, 0, NULL)) == NULL) { Emsg0(M_ERROR_TERM, 0, _("Could not init Bareos database\n")); } Dmsg1(0, "db_type=%s\n", db_get_type(db)); if (!db_open_database(NULL, db)) { Emsg0(M_ERROR_TERM, 0, db_strerror(db)); } Dmsg0(200, "Database opened\n"); if (verbose) { Pmsg2(000, _("Using Database: %s, User: %s\n"), db_name, db_user); } /* * simple CRUD test including create/drop table */ Pmsg0(0, "\nsimple CRUD test...\n\n"); const char *stmt1[8] = { "CREATE TABLE t1 ( c1 integer, c2 varchar(29))", "INSERT INTO t1 VALUES (1, 'foo')", "SELECT c1,c2 FROM t1", "UPDATE t1 SET c2='bar' WHERE c1=1", "SELECT * FROM t1", "DELETE FROM t1 WHERE c2 LIKE '\%r'", "SELECT * FROM t1", "DROP TABLE t1" }; int (*hndl1[8])(void*,int,char**) = { NULL, NULL, test_handler, NULL, test_handler, NULL, test_handler, NULL }; for (int i=0; i<8; ++i) { Pmsg1(0, "DB-Statement: %s\n",stmt1[i]); if (!db_sql_query(db, stmt1[i], hndl1[i], NULL)) { Emsg0(M_ERROR_TERM, 0, _("Stmt went wrong\n")); } } /* * simple SELECT tests without tables */ Pmsg0(0, "\nsimple SELECT tests without tables...\n\n"); const char *stmt2[8] = { "SELECT 'Test of simple SELECT!'", "SELECT 'Test of simple SELECT!' as Text", "SELECT VARCHAR(LENGTH('Test of simple SELECT!'))", "SELECT DBMSINFO('_version')", "SELECT 'This is a ''quoting'' test with single quotes'", "SELECT 'This is a \"quoting\" test with double quotes'", "SELECT null", "SELECT ''" }; int (*hndl2[8])(void*,int,char**) = { string_handler, string_handler, string_handler, string_handler, string_handler, string_handler, string_handler, string_handler }; for (int i=0; i<8; ++i) { Pmsg1(0, "DB-Statement: %s\n",stmt2[i]); if (!db_sql_query(db, stmt2[i], hndl2[i], NULL)) { Emsg0(M_ERROR_TERM, 0, _("Stmt went wrong\n")); } } /* * testing aggregates like avg, max, sum */ Pmsg0(0, "\ntesting aggregates...\n\n"); const char *stmt[11] = { "CREATE TABLE t1 (c1 integer, c2 varchar(29))", "INSERT INTO t1 VALUES (1,'foo')", "INSERT INTO t1 VALUES (2,'bar')", "INSERT INTO t1 VALUES (3,'fun')", "INSERT INTO t1 VALUES (4,'egg')", "SELECT max(c1) from t1", "SELECT sum(c1) from t1", "INSERT INTO t1 VALUES (5,NULL)", "SELECT count(*) from t1", "SELECT count(c2) from t1", "DROP TABLE t1" }; int (*hndl[11])(void*,int,char**) = { NULL, NULL, NULL, NULL, NULL, string_handler, string_handler, NULL, string_handler, string_handler, NULL }; for (int i=0; i<11; ++i) { Pmsg1(0, "DB-Statement: %s\n",stmt[i]); if (!db_sql_query(db, stmt[i], hndl[i], NULL)) { Emsg0(M_ERROR_TERM, 0, _("Stmt went wrong\n")); } } /* * datatypes test */ Pmsg0(0, "\ndatatypes test... (TODO)\n\n"); Dmsg0(200, "DB-Statement: CREATE TABLE for datatypes\n"); if (!db_sql_query(db, "CREATE TABLE t2 (" "c1 integer," "c2 varchar(255)," "c3 char(255)" /* some more datatypes... "c4 ," */ ")" , NULL, NULL)) { Emsg0(M_ERROR_TERM, 0, _("CREATE-Stmt went wrong\n")); } Dmsg0(200, "DB-Statement: DROP TABLE for datatypes\n"); if (!db_sql_query(db, "DROP TABLE t2", NULL, NULL)) { Emsg0(M_ERROR_TERM, 0, _("DROP-Stmt went wrong\n")); } db_close_database(NULL, db); db_flush_backends(); Dmsg0(200, "Database closed\n"); return 0; } #else /* needed */ int main (int argc, char *argv[]) { return 1; } #endif /* needed */
the_stack_data/11075870.c
#include <stdio.h> #define SIZE 4 #define MONTHS 12 void pnt_add(); void day_month3(); int main(void) { pnt_add(); day_month3(); return 0; } void pnt_add() { short dates[SIZE]; short * pti; short index; double bills[SIZE]; double * ptf; pti = dates; ptf = bills; printf("%23s %15s \n", "short", "double"); for (index = 0; index < SIZE; index++) printf("pointers + %d: %10p %10p \n", index, pti + index, ptf + index); } void day_month3() { int days[MONTHS] = {31,28,31,30,31,30,31,31,30,31,30,31}; int index; for (index = 0; index < MONTHS; index++) printf("Month %2d has %2d days. \n", index+1, *(days+index)); }
the_stack_data/151707078.c
/** * BOJ 11654번 C언어 소스 코드 * 작성자 : 동동매니저 (DDManager) * * ※ 실행 결과 * 사용 메모리 : 1,116 KB / 262,144 KB * 소요 시간 : 0 ms / 1,000 ms * * Copyright 2019. DDManager all rights reserved. */ #include <stdio.h> int main(void){ char c; scanf("%c",&c); printf("%d\n",c); return 0; }
the_stack_data/198581478.c
/* Signal Handlers that Return Copyright (C) 1991-2015 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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, if not, see <http://www.gnu.org/licenses/>. */ #include <signal.h> #include <stdio.h> #include <stdlib.h> /* This flag controls termination of the main loop. */ volatile sig_atomic_t keep_going = 1; /* The signal handler just clears the flag and re-enables itself. */ void catch_alarm (int sig) { keep_going = 0; signal (sig, catch_alarm); } void do_stuff (void) { puts ("Doing stuff while waiting for alarm...."); } int main (void) { /* Establish a handler for SIGALRM signals. */ signal (SIGALRM, catch_alarm); /* Set an alarm to go off in a little while. */ alarm (2); /* Check the flag once in a while to see when to quit. */ while (keep_going) do_stuff (); return EXIT_SUCCESS; }
the_stack_data/182952603.c
#include <stdio.h> int main() { int i, j, rows, cols; printf("Enter rows: "); scanf("%d", &rows); printf("Enter cols: "); scanf("%d", &cols); for(i=1; i<=rows; i++) { for(j=1; j<i; j++) { printf(" "); } for(j=1; j<=cols; j++) { if(i==1 || i==rows || j==1 || j==cols) { printf("*"); } else { printf(" "); } } printf("\n"); } return 0; }
the_stack_data/181393733.c
#include <stdio.h> int main() { int a, b, c = 0, d, e = 0; printf("Enter integer : "); scanf("%d", &a); printf("\nDecimal number(s) between 1 and %d : ", a); for (b = 2; b <= a; b++) { for (d = 1; d <= b; d++) { if (b % d == 0) e++; } if (e == 2) { printf("%d ", b); c++; } e = 0; } printf("\nCount of decimal number(s) between 1 and %d : %d\n", a, c); return 0; }
the_stack_data/93888060.c
/* Check logical operators on enum variables * * No information available for b7 because transformers are not * computed in context */ #include <stdio.h> #include <stdlib.h> typedef enum { false, true } bool; bool alea(void) { // rand() >=0 // 0 <= ((>=0) % 2) <= 1 return rand()%2; } int main(void) { bool b1, b2, b3, b4, b5, b6, b7; b1 = true; b2 = false; // b3 in 0..1 because of type? %2? b3 = alea(); // b4 in 0..1 because logical b4 = b1 && b3; // b5 in 0..1 because logical b5 = b1 || b3; // b6 in 0..1 because logical b6 = !b3; // b7 ??? b7 = b1 ^ b2; fprintf(stdout, "b1=%d b2=%d b3=%d b4=%d b5=%d b6=%d b7=%d\n", b1, b2, b3, b4, b5, b6, b7); }
the_stack_data/141117.c
/* uncompr.c -- decompress a memory buffer * Copyright (C) 1995-2003, 2010 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #define ZLIB_INTERNAL #include "zlib.h" /* =========================================================================== Decompresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the compressed buffer. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted. */ int ZEXPORT uncompress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen) { z_stream stream; int err; stream.next_in = (Bytef*)source; stream.avail_in = (uInt)sourceLen; /* Check for source > 64K on 16-bit machine: */ if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; stream.next_out = dest; stream.avail_out = (uInt)*destLen; if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; err = inflateInit(&stream); if (err != Z_OK) return err; err = inflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { inflateEnd(&stream); if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) return Z_DATA_ERROR; return err; } *destLen = stream.total_out; err = inflateEnd(&stream); return err; }
the_stack_data/934874.c
#include <assert.h> enum my_enum { first, second, third, fourth, fifth }; int main() { enum my_enum ev1; enum my_enum ev2; ev1 = first; ev2 = fifth; assert(__CPROVER_enum_is_in_range(ev1, ev2)); return 0; }
the_stack_data/200141946.c
/* This test program is part of GDB, the GNU debugger. Copyright 1997-2020 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/>. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <limits.h> int global_i = 100; int main (int argc, char ** argv) { int local_j = global_i + 1; int local_k = local_j + 1; char prog[PATH_MAX]; int len; printf ("foll-exec is about to execlp(execd-prog)...\n"); strcpy (prog, argv[0]); len = strlen (prog); /* Replace "foll-exec" with "execd-prog". */ memcpy (prog + len - 9, "execd-prog", 10); prog[len + 1] = 0; execlp (prog, /* tbreak-execlp */ prog, "execlp arg1 from foll-exec", (char *) 0); printf ("foll-exec is about to execl(execd-prog)...\n"); execl (prog, /* tbreak-execl */ prog, "execl arg1 from foll-exec", "execl arg2 from foll-exec", (char *) 0); { static char * argv[] = { (char *) "", (char *) "execv arg1 from foll-exec", (char *) 0}; argv[0] = prog; printf ("foll-exec is about to execv(execd-prog)...\n"); execv (prog, argv); /* tbreak-execv */ } }
the_stack_data/70124.c
#include <stdio.h> #include <string.h> /* Use for strcmp() */ #include <stdlib.h> /* atoi() */ int main(int argc, char* argv[]){ if(argc < 1){ printf("Not enough arguments passed in to calculate a combination. \n"); printf("USAGE: \n"); printf(" combination-calculator <n> <r> <--latex> \n"); printf(" <n>: total number of terms \n"); printf(" <r>: number of terms to choose \n"); printf(" <--latex>: add to print out code for insertion to LaTeX"); return 1; } /* nCr = n! / r!(n - r)! */ long numerator = 1, denominator = 1; int n = atoi( argv[1] ); int r = atoi( argv[2] ); if(r > n){ printf("r must be less than n"); return 2; } if(r <= 0 && n <= 0){ printf("RESULT: 0"); return 2; } for(int i = 1; i <= n; i++){ numerator = numerator * i; // printf("numerator: %ld \n", numerator); } for(int i = 1; i <= r; i++){ denominator = denominator * i; if(i == n - r){ denominator *= i; } // printf("denominator: %ld \n", denominator); } long result = numerator / denominator; printf("NUMERATOR: %ld\n", numerator); printf("DENOMINATOR: %ld\n", denominator); printf("RESULT: %ld \n", result); if(argc > 2){ if(strcmp(argv[3], "--latex") == 0){ printf("$ \\binom{%d}{%d} = \\frac{%d!}{%d!(%d - %d)} = %ld $", n, r, n, r, n, r, result); } } return 0; }
the_stack_data/170454187.c
/* * COPYRIGHT * * gaussrv.c * Copyright (C) 2014 Exstrom Laboratories LLC * * 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. * * A copy of the GNU General Public License is available on the internet at: * http://www.gnu.org/copyleft/gpl.html * * or you can write to: * * The Free Software Foundation, Inc. * 675 Mass Ave * Cambridge, MA 02139, USA * * Exstrom Laboratories LLC contact: * stefan(AT)exstrom.com * * Exstrom Laboratories LLC * Longmont, CO 80503, USA * */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <time.h> //TcheL: As a patch // Compile: gcc -lm -o gaussrv gaussrv.c int main( int argc, char *argv[] ) { if( argc < 4 ) { printf("usage: %s n m a seed\n", argv[0]); printf(" Generates n gaussian random numbers with mean=m, stdev=a\n"); printf(" seed = optional random number seed\n"); exit( -1 ); } unsigned long i, n = strtoul(argv[1], NULL, 10); double m = strtod(argv[2], NULL); double a = strtod(argv[3], NULL); unsigned int seed; double z1, z2, r, d; seed = argc > 4 ? strtoul(argv[4], NULL, 10) : time(NULL); srand(seed); for(i=0; i<n; ++i){ do{ z1 = 2.0*rand()/RAND_MAX - 1.0; z2 = 2.0*rand()/RAND_MAX - 1.0; r = z1 * z1 + z2 * z2;} while(r >= 1.0); d = a * sqrt(-2.0 * log(r) / r); printf("%lf\n", m + d * z1);} return(0); }
the_stack_data/57662.c
// Future home of the exec builtin
the_stack_data/176706194.c
// creation of library for zip zip int main() { //go forward move_relative_position(0,1450,1400); move_relative_position(3,1250,1400); block_motor_done(0); block_motor_done(3); enable_servos(); //open arm servo 1 set_servo_position(1,50); set_servo_position(0,1350); // give time for arm to open msleep(1000); //go forward move_relative_position(0,1500,1200); move_relative_position(3,1250,1200); block_motor_done(0); block_motor_done(3); //close arm servo 1 set_servo_position(1,900); // give time for arm to close msleep(1000); //go forward move_relative_position(0,1500,2150); move_relative_position(3,1250,2150); block_motor_done(0); block_motor_done(3); //turn right move_relative_position(3, 800, -700); move_relative_position(0, 800, 700); block_motor_done(3); block_motor_done(0); //go forward move_relative_position(0,1050,1850); move_relative_position(3,1000,1850); block_motor_done(0); block_motor_done(3); //turn right move_relative_position(3, 800, -400); move_relative_position(0, 800,400); block_motor_done(2); block_motor_done(0); enable_servos(); //open arm servo 0 set_servo_position(0,2147); // give time for arm to open msleep(1000); //go back set_servo_position(1,50); move_relative_position(0,1200,4400); move_relative_position(3,1150,4400); block_motor_done(0); block_motor_done(3); enable_servos(); //open arm servo 1 set_servo_position(1,900); // give time for arm to open msleep(1000); //go forward to right move_relative_position(0,1200,-4700); move_relative_position(3,1150,-4700); block_motor_done(0); block_motor_done(3); //close arm servo 1 set_servo_position(1,900); // give time for arm to close msleep(1000); printf("Baby it's cold outside!\n"); set_servo_position(0,1400); // Backing up #1 move_relative_position(0,-1200,2000); move_relative_position(3,-1150,2000); // Backing up #2 move_relative_position(0,-1200,2000); move_relative_position(3,-1150,2000); block_motor_done(0); block_motor_done(3); return 0; }
the_stack_data/206392624.c
/** * * File Name: libc/ctype/tolower.c * Title : Simple Standard C Library * Project : PINE64 ROCK64 Bare-Metal * Author : Copyright (C) 2021 Johannes Krottmayer <[email protected]> * Created : 2021-01-16 * Modified : * Revised : * Version : 0.1.0.0 * License : ISC (see LICENSE.txt) * * NOTE: This code is currently below version 1.0, and therefore is considered * to be lacking in some functionality or documentation, or may not be fully * tested. Nonetheless, you can expect most functions to work. * */ int tolower(const int c) { if (!((c >= 'A') && (c <= 'Z'))) return c; return (c + ('a' - 'A')); }
the_stack_data/90462.c
int main(void) { int i = 22; __gcov_flush(); i = 42; asm("int $3"); i = 84; return 0; }
the_stack_data/215767095.c
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <dirent.h> #include <unistd.h> int main(int argc, char **argv){ struct dirent *pDirent; DIR *pDir; if (argc < 2) { printf ("Usage: ./opendir <dirname>\n"); return 1; } pDir = opendir (argv[1]); if (pDir == NULL) { printf ("Cannot open directory '%s'\n", argv[1]); return 1; } while ((pDirent = readdir(pDir)) != NULL) { printf ("name: %s inode: %d\n", pDirent->d_name,(int)pDirent->d_ino); } closedir (pDir); return 0; }
the_stack_data/137991.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2017-2020 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/>. */ #include <stdlib.h> #include <unistd.h> /* GDB reads this to figure out the child's PID. */ pid_t child_pid; void marker (void) { } int main () { alarm (60); child_pid = fork (); if (child_pid == -1) return 1; while (1) { marker (); usleep (1000); } return 0; }
the_stack_data/1240575.c
/* * Minimal BPF debugger * * Minimal BPF debugger that mimics the kernel's engine (w/o extensions) * and allows for single stepping through selected packets from a pcap * with a provided user filter in order to facilitate verification of a * BPF program. Besides others, this is useful to verify BPF programs * before attaching to a live system, and can be used in socket filters, * cls_bpf, xt_bpf, team driver and e.g. PTP code; in particular when a * single more complex BPF program is being used. Reasons for a more * complex BPF program are likely primarily to optimize execution time * for making a verdict when multiple simple BPF programs are combined * into one in order to prevent parsing same headers multiple times. * * More on how to debug BPF opcodes see Documentation/networking/filter.txt * which is the main document on BPF. Mini howto for getting started: * * 1) `./bpf_dbg` to enter the shell (shell cmds denoted with '>'): * 2) > load bpf 6,40 0 0 12,21 0 3 20... (output from `bpf_asm` or * `tcpdump -iem1 -ddd port 22 | tr '\n' ','` to load as filter) * 3) > load pcap foo.pcap * 4) > run <n>/disassemble/dump/quit (self-explanatory) * 5) > breakpoint 2 (sets bp at loaded BPF insns 2, do `run` then; * multiple bps can be set, of course, a call to `breakpoint` * w/o args shows currently loaded bps, `breakpoint reset` for * resetting all breakpoints) * 6) > select 3 (`run` etc will start from the 3rd packet in the pcap) * 7) > step [-<n>, +<n>] (performs single stepping through the BPF) * * Copyright 2013 Daniel Borkmann <[email protected]> * Licensed under the GNU General Public License, version 2.0 (GPLv2) */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <ctype.h> #include <stdbool.h> #include <stdarg.h> #include <setjmp.h> #include <linux/filter.h> #include <linux/if_packet.h> #include <readline/readline.h> #include <readline/history.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <errno.h> #include <signal.h> #include <arpa/inet.h> #include <net/ethernet.h> #define TCPDUMP_MAGIC 0xa1b2c3d4 #define BPF_LDX_B (BPF_LDX | BPF_B) #define BPF_LDX_W (BPF_LDX | BPF_W) #define BPF_JMP_JA (BPF_JMP | BPF_JA) #define BPF_JMP_JEQ (BPF_JMP | BPF_JEQ) #define BPF_JMP_JGT (BPF_JMP | BPF_JGT) #define BPF_JMP_JGE (BPF_JMP | BPF_JGE) #define BPF_JMP_JSET (BPF_JMP | BPF_JSET) #define BPF_ALU_ADD (BPF_ALU | BPF_ADD) #define BPF_ALU_SUB (BPF_ALU | BPF_SUB) #define BPF_ALU_MUL (BPF_ALU | BPF_MUL) #define BPF_ALU_DIV (BPF_ALU | BPF_DIV) #define BPF_ALU_MOD (BPF_ALU | BPF_MOD) #define BPF_ALU_NEG (BPF_ALU | BPF_NEG) #define BPF_ALU_AND (BPF_ALU | BPF_AND) #define BPF_ALU_OR (BPF_ALU | BPF_OR) #define BPF_ALU_XOR (BPF_ALU | BPF_XOR) #define BPF_ALU_LSH (BPF_ALU | BPF_LSH) #define BPF_ALU_RSH (BPF_ALU | BPF_RSH) #define BPF_MISC_TAX (BPF_MISC | BPF_TAX) #define BPF_MISC_TXA (BPF_MISC | BPF_TXA) #define BPF_LD_B (BPF_LD | BPF_B) #define BPF_LD_H (BPF_LD | BPF_H) #define BPF_LD_W (BPF_LD | BPF_W) #ifndef array_size # define array_size(x) (sizeof(x) / sizeof((x)[0])) #endif #ifndef __check_format_printf # define __check_format_printf(pos_fmtstr, pos_fmtargs) \ __attribute__ ((format (printf, (pos_fmtstr), (pos_fmtargs)))) #endif #define CMD(_name, _func) { .name = _name, .func = _func, } #define OP(_op, _name) [_op] = _name enum { CMD_OK, CMD_ERR, CMD_EX, }; struct shell_cmd { const char *name; int (*func)(char *args); }; struct pcap_filehdr { uint32_t magic; uint16_t version_major; uint16_t version_minor; int32_t thiszone; uint32_t sigfigs; uint32_t snaplen; uint32_t linktype; }; struct pcap_timeval { int32_t tv_sec; int32_t tv_usec; }; struct pcap_pkthdr { struct pcap_timeval ts; uint32_t caplen; uint32_t len; }; struct bpf_regs { uint32_t A; uint32_t X; uint32_t M[BPF_MEMWORDS]; uint32_t R; bool Rs; uint16_t Pc; }; static struct sock_filter bpf_image[BPF_MAXINSNS + 1]; static unsigned int bpf_prog_len = 0; static int bpf_breakpoints[64]; static struct bpf_regs bpf_regs[BPF_MAXINSNS + 1]; static struct bpf_regs bpf_curr; static unsigned int bpf_regs_len = 0; static int pcap_fd = -1; static unsigned int pcap_packet = 0; static size_t pcap_map_size = 0; static char *pcap_ptr_va_start, *pcap_ptr_va_curr; static const char * const op_table[] = { OP(BPF_ST, "st"), OP(BPF_STX, "stx"), OP(BPF_LD_B, "ldb"), OP(BPF_LD_H, "ldh"), OP(BPF_LD_W, "ld"), OP(BPF_LDX, "ldx"), OP(BPF_LDX_B, "ldxb"), OP(BPF_JMP_JA, "ja"), OP(BPF_JMP_JEQ, "jeq"), OP(BPF_JMP_JGT, "jgt"), OP(BPF_JMP_JGE, "jge"), OP(BPF_JMP_JSET, "jset"), OP(BPF_ALU_ADD, "add"), OP(BPF_ALU_SUB, "sub"), OP(BPF_ALU_MUL, "mul"), OP(BPF_ALU_DIV, "div"), OP(BPF_ALU_MOD, "mod"), OP(BPF_ALU_NEG, "neg"), OP(BPF_ALU_AND, "and"), OP(BPF_ALU_OR, "or"), OP(BPF_ALU_XOR, "xor"), OP(BPF_ALU_LSH, "lsh"), OP(BPF_ALU_RSH, "rsh"), OP(BPF_MISC_TAX, "tax"), OP(BPF_MISC_TXA, "txa"), OP(BPF_RET, "ret"), }; static __check_format_printf(1, 2) int rl_printf(const char *fmt, ...) { int ret; va_list vl; va_start(vl, fmt); ret = vfprintf(rl_outstream, fmt, vl); va_end(vl); return ret; } static int matches(const char *cmd, const char *pattern) { int len = strlen(cmd); if (len > strlen(pattern)) return -1; return memcmp(pattern, cmd, len); } static void hex_dump(const uint8_t *buf, size_t len) { int i; rl_printf("%3u: ", 0); for (i = 0; i < len; i++) { if (i && !(i % 16)) rl_printf("\n%3u: ", i); rl_printf("%02x ", buf[i]); } rl_printf("\n"); } static bool bpf_prog_loaded(void) { if (bpf_prog_len == 0) rl_printf("no bpf program loaded!\n"); return bpf_prog_len > 0; } static void bpf_disasm(const struct sock_filter f, unsigned int i) { const char *op, *fmt; int val = f.k; char buf[256]; switch (f.code) { case BPF_RET | BPF_K: op = op_table[BPF_RET]; fmt = "#%#x"; break; case BPF_RET | BPF_A: op = op_table[BPF_RET]; fmt = "a"; break; case BPF_RET | BPF_X: op = op_table[BPF_RET]; fmt = "x"; break; case BPF_MISC_TAX: op = op_table[BPF_MISC_TAX]; fmt = ""; break; case BPF_MISC_TXA: op = op_table[BPF_MISC_TXA]; fmt = ""; break; case BPF_ST: op = op_table[BPF_ST]; fmt = "M[%d]"; break; case BPF_STX: op = op_table[BPF_STX]; fmt = "M[%d]"; break; case BPF_LD_W | BPF_ABS: op = op_table[BPF_LD_W]; fmt = "[%d]"; break; case BPF_LD_H | BPF_ABS: op = op_table[BPF_LD_H]; fmt = "[%d]"; break; case BPF_LD_B | BPF_ABS: op = op_table[BPF_LD_B]; fmt = "[%d]"; break; case BPF_LD_W | BPF_LEN: op = op_table[BPF_LD_W]; fmt = "#len"; break; case BPF_LD_W | BPF_IND: op = op_table[BPF_LD_W]; fmt = "[x+%d]"; break; case BPF_LD_H | BPF_IND: op = op_table[BPF_LD_H]; fmt = "[x+%d]"; break; case BPF_LD_B | BPF_IND: op = op_table[BPF_LD_B]; fmt = "[x+%d]"; break; case BPF_LD | BPF_IMM: op = op_table[BPF_LD_W]; fmt = "#%#x"; break; case BPF_LDX | BPF_IMM: op = op_table[BPF_LDX]; fmt = "#%#x"; break; case BPF_LDX_B | BPF_MSH: op = op_table[BPF_LDX_B]; fmt = "4*([%d]&0xf)"; break; case BPF_LD | BPF_MEM: op = op_table[BPF_LD_W]; fmt = "M[%d]"; break; case BPF_LDX | BPF_MEM: op = op_table[BPF_LDX]; fmt = "M[%d]"; break; case BPF_JMP_JA: op = op_table[BPF_JMP_JA]; fmt = "%d"; val = i + 1 + f.k; break; case BPF_JMP_JGT | BPF_X: op = op_table[BPF_JMP_JGT]; fmt = "x"; break; case BPF_JMP_JGT | BPF_K: op = op_table[BPF_JMP_JGT]; fmt = "#%#x"; break; case BPF_JMP_JGE | BPF_X: op = op_table[BPF_JMP_JGE]; fmt = "x"; break; case BPF_JMP_JGE | BPF_K: op = op_table[BPF_JMP_JGE]; fmt = "#%#x"; break; case BPF_JMP_JEQ | BPF_X: op = op_table[BPF_JMP_JEQ]; fmt = "x"; break; case BPF_JMP_JEQ | BPF_K: op = op_table[BPF_JMP_JEQ]; fmt = "#%#x"; break; case BPF_JMP_JSET | BPF_X: op = op_table[BPF_JMP_JSET]; fmt = "x"; break; case BPF_JMP_JSET | BPF_K: op = op_table[BPF_JMP_JSET]; fmt = "#%#x"; break; case BPF_ALU_NEG: op = op_table[BPF_ALU_NEG]; fmt = ""; break; case BPF_ALU_LSH | BPF_X: op = op_table[BPF_ALU_LSH]; fmt = "x"; break; case BPF_ALU_LSH | BPF_K: op = op_table[BPF_ALU_LSH]; fmt = "#%d"; break; case BPF_ALU_RSH | BPF_X: op = op_table[BPF_ALU_RSH]; fmt = "x"; break; case BPF_ALU_RSH | BPF_K: op = op_table[BPF_ALU_RSH]; fmt = "#%d"; break; case BPF_ALU_ADD | BPF_X: op = op_table[BPF_ALU_ADD]; fmt = "x"; break; case BPF_ALU_ADD | BPF_K: op = op_table[BPF_ALU_ADD]; fmt = "#%d"; break; case BPF_ALU_SUB | BPF_X: op = op_table[BPF_ALU_SUB]; fmt = "x"; break; case BPF_ALU_SUB | BPF_K: op = op_table[BPF_ALU_SUB]; fmt = "#%d"; break; case BPF_ALU_MUL | BPF_X: op = op_table[BPF_ALU_MUL]; fmt = "x"; break; case BPF_ALU_MUL | BPF_K: op = op_table[BPF_ALU_MUL]; fmt = "#%d"; break; case BPF_ALU_DIV | BPF_X: op = op_table[BPF_ALU_DIV]; fmt = "x"; break; case BPF_ALU_DIV | BPF_K: op = op_table[BPF_ALU_DIV]; fmt = "#%d"; break; case BPF_ALU_MOD | BPF_X: op = op_table[BPF_ALU_MOD]; fmt = "x"; break; case BPF_ALU_MOD | BPF_K: op = op_table[BPF_ALU_MOD]; fmt = "#%d"; break; case BPF_ALU_AND | BPF_X: op = op_table[BPF_ALU_AND]; fmt = "x"; break; case BPF_ALU_AND | BPF_K: op = op_table[BPF_ALU_AND]; fmt = "#%#x"; break; case BPF_ALU_OR | BPF_X: op = op_table[BPF_ALU_OR]; fmt = "x"; break; case BPF_ALU_OR | BPF_K: op = op_table[BPF_ALU_OR]; fmt = "#%#x"; break; case BPF_ALU_XOR | BPF_X: op = op_table[BPF_ALU_XOR]; fmt = "x"; break; case BPF_ALU_XOR | BPF_K: op = op_table[BPF_ALU_XOR]; fmt = "#%#x"; break; default: op = "nosup"; fmt = "%#x"; val = f.code; break; } memset(buf, 0, sizeof(buf)); snprintf(buf, sizeof(buf), fmt, val); buf[sizeof(buf) - 1] = 0; if ((BPF_CLASS(f.code) == BPF_JMP && BPF_OP(f.code) != BPF_JA)) rl_printf("l%d:\t%s %s, l%d, l%d\n", i, op, buf, i + 1 + f.jt, i + 1 + f.jf); else rl_printf("l%d:\t%s %s\n", i, op, buf); } static void bpf_dump_curr(struct bpf_regs *r, struct sock_filter *f) { int i, m = 0; rl_printf("pc: [%u]\n", r->Pc); rl_printf("code: [%u] jt[%u] jf[%u] k[%u]\n", f->code, f->jt, f->jf, f->k); rl_printf("curr: "); bpf_disasm(*f, r->Pc); if (f->jt || f->jf) { rl_printf("jt: "); bpf_disasm(*(f + f->jt + 1), r->Pc + f->jt + 1); rl_printf("jf: "); bpf_disasm(*(f + f->jf + 1), r->Pc + f->jf + 1); } rl_printf("A: [%#08x][%u]\n", r->A, r->A); rl_printf("X: [%#08x][%u]\n", r->X, r->X); if (r->Rs) rl_printf("ret: [%#08x][%u]!\n", r->R, r->R); for (i = 0; i < BPF_MEMWORDS; i++) { if (r->M[i]) { m++; rl_printf("M[%d]: [%#08x][%u]\n", i, r->M[i], r->M[i]); } } if (m == 0) rl_printf("M[0,%d]: [%#08x][%u]\n", BPF_MEMWORDS - 1, 0, 0); } static void bpf_dump_pkt(uint8_t *pkt, uint32_t pkt_caplen, uint32_t pkt_len) { if (pkt_caplen != pkt_len) rl_printf("cap: %u, len: %u\n", pkt_caplen, pkt_len); else rl_printf("len: %u\n", pkt_len); hex_dump(pkt, pkt_caplen); } static void bpf_disasm_all(const struct sock_filter *f, unsigned int len) { unsigned int i; for (i = 0; i < len; i++) bpf_disasm(f[i], i); } static void bpf_dump_all(const struct sock_filter *f, unsigned int len) { unsigned int i; rl_printf("/* { op, jt, jf, k }, */\n"); for (i = 0; i < len; i++) rl_printf("{ %#04x, %2u, %2u, %#010x },\n", f[i].code, f[i].jt, f[i].jf, f[i].k); } static bool bpf_runnable(struct sock_filter *f, unsigned int len) { int sock, ret, i; struct sock_fprog bpf = { .filter = f, .len = len, }; sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { rl_printf("cannot open socket!\n"); return false; } ret = setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf)); close(sock); if (ret < 0) { rl_printf("program not allowed to run by kernel!\n"); return false; } for (i = 0; i < len; i++) { if (BPF_CLASS(f[i].code) == BPF_LD && f[i].k > SKF_AD_OFF) { rl_printf("extensions currently not supported!\n"); return false; } } return true; } static void bpf_reset_breakpoints(void) { int i; for (i = 0; i < array_size(bpf_breakpoints); i++) bpf_breakpoints[i] = -1; } static void bpf_set_breakpoints(unsigned int where) { int i; bool set = false; for (i = 0; i < array_size(bpf_breakpoints); i++) { if (bpf_breakpoints[i] == (int) where) { rl_printf("breakpoint already set!\n"); set = true; break; } if (bpf_breakpoints[i] == -1 && set == false) { bpf_breakpoints[i] = where; set = true; } } if (!set) rl_printf("too many breakpoints set, reset first!\n"); } static void bpf_dump_breakpoints(void) { int i; rl_printf("breakpoints: "); for (i = 0; i < array_size(bpf_breakpoints); i++) { if (bpf_breakpoints[i] < 0) continue; rl_printf("%d ", bpf_breakpoints[i]); } rl_printf("\n"); } static void bpf_reset(void) { bpf_regs_len = 0; memset(bpf_regs, 0, sizeof(bpf_regs)); memset(&bpf_curr, 0, sizeof(bpf_curr)); } static void bpf_safe_regs(void) { memcpy(&bpf_regs[bpf_regs_len++], &bpf_curr, sizeof(bpf_curr)); } static bool bpf_restore_regs(int off) { unsigned int index = bpf_regs_len - 1 + off; if (index == 0) { bpf_reset(); return true; } else if (index < bpf_regs_len) { memcpy(&bpf_curr, &bpf_regs[index], sizeof(bpf_curr)); bpf_regs_len = index; return true; } else { rl_printf("reached bottom of register history stack!\n"); return false; } } static uint32_t extract_u32(uint8_t *pkt, uint32_t off) { uint32_t r; memcpy(&r, &pkt[off], sizeof(r)); return ntohl(r); } static uint16_t extract_u16(uint8_t *pkt, uint32_t off) { uint16_t r; memcpy(&r, &pkt[off], sizeof(r)); return ntohs(r); } static uint8_t extract_u8(uint8_t *pkt, uint32_t off) { return pkt[off]; } static void set_return(struct bpf_regs *r) { r->R = 0; r->Rs = true; } static void bpf_single_step(struct bpf_regs *r, struct sock_filter *f, uint8_t *pkt, uint32_t pkt_caplen, uint32_t pkt_len) { uint32_t K = f->k; int d; switch (f->code) { case BPF_RET | BPF_K: r->R = K; r->Rs = true; break; case BPF_RET | BPF_A: r->R = r->A; r->Rs = true; break; case BPF_RET | BPF_X: r->R = r->X; r->Rs = true; break; case BPF_MISC_TAX: r->X = r->A; break; case BPF_MISC_TXA: r->A = r->X; break; case BPF_ST: r->M[K] = r->A; break; case BPF_STX: r->M[K] = r->X; break; case BPF_LD_W | BPF_ABS: d = pkt_caplen - K; if (d >= sizeof(uint32_t)) r->A = extract_u32(pkt, K); else set_return(r); break; case BPF_LD_H | BPF_ABS: d = pkt_caplen - K; if (d >= sizeof(uint16_t)) r->A = extract_u16(pkt, K); else set_return(r); break; case BPF_LD_B | BPF_ABS: d = pkt_caplen - K; if (d >= sizeof(uint8_t)) r->A = extract_u8(pkt, K); else set_return(r); break; case BPF_LD_W | BPF_IND: d = pkt_caplen - (r->X + K); if (d >= sizeof(uint32_t)) r->A = extract_u32(pkt, r->X + K); break; case BPF_LD_H | BPF_IND: d = pkt_caplen - (r->X + K); if (d >= sizeof(uint16_t)) r->A = extract_u16(pkt, r->X + K); else set_return(r); break; case BPF_LD_B | BPF_IND: d = pkt_caplen - (r->X + K); if (d >= sizeof(uint8_t)) r->A = extract_u8(pkt, r->X + K); else set_return(r); break; case BPF_LDX_B | BPF_MSH: d = pkt_caplen - K; if (d >= sizeof(uint8_t)) { r->X = extract_u8(pkt, K); r->X = (r->X & 0xf) << 2; } else set_return(r); break; case BPF_LD_W | BPF_LEN: r->A = pkt_len; break; case BPF_LDX_W | BPF_LEN: r->A = pkt_len; break; case BPF_LD | BPF_IMM: r->A = K; break; case BPF_LDX | BPF_IMM: r->X = K; break; case BPF_LD | BPF_MEM: r->A = r->M[K]; break; case BPF_LDX | BPF_MEM: r->X = r->M[K]; break; case BPF_JMP_JA: r->Pc += K; break; case BPF_JMP_JGT | BPF_X: r->Pc += r->A > r->X ? f->jt : f->jf; break; case BPF_JMP_JGT | BPF_K: r->Pc += r->A > K ? f->jt : f->jf; break; case BPF_JMP_JGE | BPF_X: r->Pc += r->A >= r->X ? f->jt : f->jf; break; case BPF_JMP_JGE | BPF_K: r->Pc += r->A >= K ? f->jt : f->jf; break; case BPF_JMP_JEQ | BPF_X: r->Pc += r->A == r->X ? f->jt : f->jf; break; case BPF_JMP_JEQ | BPF_K: r->Pc += r->A == K ? f->jt : f->jf; break; case BPF_JMP_JSET | BPF_X: r->Pc += r->A & r->X ? f->jt : f->jf; break; case BPF_JMP_JSET | BPF_K: r->Pc += r->A & K ? f->jt : f->jf; break; case BPF_ALU_NEG: r->A = -r->A; break; case BPF_ALU_LSH | BPF_X: r->A <<= r->X; break; case BPF_ALU_LSH | BPF_K: r->A <<= K; break; case BPF_ALU_RSH | BPF_X: r->A >>= r->X; break; case BPF_ALU_RSH | BPF_K: r->A >>= K; break; case BPF_ALU_ADD | BPF_X: r->A += r->X; break; case BPF_ALU_ADD | BPF_K: r->A += K; break; case BPF_ALU_SUB | BPF_X: r->A -= r->X; break; case BPF_ALU_SUB | BPF_K: r->A -= K; break; case BPF_ALU_MUL | BPF_X: r->A *= r->X; break; case BPF_ALU_MUL | BPF_K: r->A *= K; break; case BPF_ALU_DIV | BPF_X: case BPF_ALU_MOD | BPF_X: if (r->X == 0) { set_return(r); break; } goto do_div; case BPF_ALU_DIV | BPF_K: case BPF_ALU_MOD | BPF_K: if (K == 0) { set_return(r); break; } do_div: switch (f->code) { case BPF_ALU_DIV | BPF_X: r->A /= r->X; break; case BPF_ALU_DIV | BPF_K: r->A /= K; break; case BPF_ALU_MOD | BPF_X: r->A %= r->X; break; case BPF_ALU_MOD | BPF_K: r->A %= K; break; } break; case BPF_ALU_AND | BPF_X: r->A &= r->X; break; case BPF_ALU_AND | BPF_K: r->A &= r->X; break; case BPF_ALU_OR | BPF_X: r->A |= r->X; break; case BPF_ALU_OR | BPF_K: r->A |= K; break; case BPF_ALU_XOR | BPF_X: r->A ^= r->X; break; case BPF_ALU_XOR | BPF_K: r->A ^= K; break; } } static bool bpf_pc_has_breakpoint(uint16_t pc) { int i; for (i = 0; i < array_size(bpf_breakpoints); i++) { if (bpf_breakpoints[i] < 0) continue; if (bpf_breakpoints[i] == pc) return true; } return false; } static bool bpf_handle_breakpoint(struct bpf_regs *r, struct sock_filter *f, uint8_t *pkt, uint32_t pkt_caplen, uint32_t pkt_len) { rl_printf("-- register dump --\n"); bpf_dump_curr(r, &f[r->Pc]); rl_printf("-- packet dump --\n"); bpf_dump_pkt(pkt, pkt_caplen, pkt_len); rl_printf("(breakpoint)\n"); return true; } static int bpf_run_all(struct sock_filter *f, uint16_t bpf_len, uint8_t *pkt, uint32_t pkt_caplen, uint32_t pkt_len) { bool stop = false; while (bpf_curr.Rs == false && stop == false) { bpf_safe_regs(); if (bpf_pc_has_breakpoint(bpf_curr.Pc)) stop = bpf_handle_breakpoint(&bpf_curr, f, pkt, pkt_caplen, pkt_len); bpf_single_step(&bpf_curr, &f[bpf_curr.Pc], pkt, pkt_caplen, pkt_len); bpf_curr.Pc++; } return stop ? -1 : bpf_curr.R; } static int bpf_run_stepping(struct sock_filter *f, uint16_t bpf_len, uint8_t *pkt, uint32_t pkt_caplen, uint32_t pkt_len, int next) { bool stop = false; int i = 1; while (bpf_curr.Rs == false && stop == false) { bpf_safe_regs(); if (i++ == next) stop = bpf_handle_breakpoint(&bpf_curr, f, pkt, pkt_caplen, pkt_len); bpf_single_step(&bpf_curr, &f[bpf_curr.Pc], pkt, pkt_caplen, pkt_len); bpf_curr.Pc++; } return stop ? -1 : bpf_curr.R; } static bool pcap_loaded(void) { if (pcap_fd < 0) rl_printf("no pcap file loaded!\n"); return pcap_fd >= 0; } static struct pcap_pkthdr *pcap_curr_pkt(void) { return (void *) pcap_ptr_va_curr; } static bool pcap_next_pkt(void) { struct pcap_pkthdr *hdr = pcap_curr_pkt(); if (pcap_ptr_va_curr + sizeof(*hdr) - pcap_ptr_va_start >= pcap_map_size) return false; if (hdr->caplen == 0 || hdr->len == 0 || hdr->caplen > hdr->len) return false; if (pcap_ptr_va_curr + sizeof(*hdr) + hdr->caplen - pcap_ptr_va_start >= pcap_map_size) return false; pcap_ptr_va_curr += (sizeof(*hdr) + hdr->caplen); return true; } static void pcap_reset_pkt(void) { pcap_ptr_va_curr = pcap_ptr_va_start + sizeof(struct pcap_filehdr); } static int try_load_pcap(const char *file) { struct pcap_filehdr *hdr; struct stat sb; int ret; pcap_fd = open(file, O_RDONLY); if (pcap_fd < 0) { rl_printf("cannot open pcap [%s]!\n", strerror(errno)); return CMD_ERR; } ret = fstat(pcap_fd, &sb); if (ret < 0) { rl_printf("cannot fstat pcap file!\n"); return CMD_ERR; } if (!S_ISREG(sb.st_mode)) { rl_printf("not a regular pcap file, duh!\n"); return CMD_ERR; } pcap_map_size = sb.st_size; if (pcap_map_size <= sizeof(struct pcap_filehdr)) { rl_printf("pcap file too small!\n"); return CMD_ERR; } pcap_ptr_va_start = mmap(NULL, pcap_map_size, PROT_READ, MAP_SHARED | MAP_LOCKED, pcap_fd, 0); if (pcap_ptr_va_start == MAP_FAILED) { rl_printf("mmap of file failed!"); return CMD_ERR; } hdr = (void *) pcap_ptr_va_start; if (hdr->magic != TCPDUMP_MAGIC) { rl_printf("wrong pcap magic!\n"); return CMD_ERR; } pcap_reset_pkt(); return CMD_OK; } static void try_close_pcap(void) { if (pcap_fd >= 0) { munmap(pcap_ptr_va_start, pcap_map_size); close(pcap_fd); pcap_ptr_va_start = pcap_ptr_va_curr = NULL; pcap_map_size = 0; pcap_packet = 0; pcap_fd = -1; } } static int cmd_load_bpf(char *bpf_string) { char sp, *token, separator = ','; unsigned short bpf_len, i = 0; struct sock_filter tmp; bpf_prog_len = 0; memset(bpf_image, 0, sizeof(bpf_image)); if (sscanf(bpf_string, "%hu%c", &bpf_len, &sp) != 2 || sp != separator || bpf_len > BPF_MAXINSNS || bpf_len == 0) { rl_printf("syntax error in head length encoding!\n"); return CMD_ERR; } token = bpf_string; while ((token = strchr(token, separator)) && (++token)[0]) { if (i >= bpf_len) { rl_printf("program exceeds encoded length!\n"); return CMD_ERR; } if (sscanf(token, "%hu %hhu %hhu %u,", &tmp.code, &tmp.jt, &tmp.jf, &tmp.k) != 4) { rl_printf("syntax error at instruction %d!\n", i); return CMD_ERR; } bpf_image[i].code = tmp.code; bpf_image[i].jt = tmp.jt; bpf_image[i].jf = tmp.jf; bpf_image[i].k = tmp.k; i++; } if (i != bpf_len) { rl_printf("syntax error exceeding encoded length!\n"); return CMD_ERR; } else bpf_prog_len = bpf_len; if (!bpf_runnable(bpf_image, bpf_prog_len)) bpf_prog_len = 0; return CMD_OK; } static int cmd_load_pcap(char *file) { char *file_trim, *tmp; file_trim = strtok_r(file, " ", &tmp); if (file_trim == NULL) return CMD_ERR; try_close_pcap(); return try_load_pcap(file_trim); } static int cmd_load(char *arg) { char *subcmd, *cont, *tmp = strdup(arg); int ret = CMD_OK; subcmd = strtok_r(tmp, " ", &cont); if (subcmd == NULL) goto out; if (matches(subcmd, "bpf") == 0) { bpf_reset(); bpf_reset_breakpoints(); ret = cmd_load_bpf(cont); } else if (matches(subcmd, "pcap") == 0) { ret = cmd_load_pcap(cont); } else { out: rl_printf("bpf <code>: load bpf code\n"); rl_printf("pcap <file>: load pcap file\n"); ret = CMD_ERR; } free(tmp); return ret; } static int cmd_step(char *num) { struct pcap_pkthdr *hdr; int steps, ret; if (!bpf_prog_loaded() || !pcap_loaded()) return CMD_ERR; steps = strtol(num, NULL, 10); if (steps == 0 || strlen(num) == 0) steps = 1; if (steps < 0) { if (!bpf_restore_regs(steps)) return CMD_ERR; steps = 1; } hdr = pcap_curr_pkt(); ret = bpf_run_stepping(bpf_image, bpf_prog_len, (uint8_t *) hdr + sizeof(*hdr), hdr->caplen, hdr->len, steps); if (ret >= 0 || bpf_curr.Rs) { bpf_reset(); if (!pcap_next_pkt()) { rl_printf("(going back to first packet)\n"); pcap_reset_pkt(); } else { rl_printf("(next packet)\n"); } } return CMD_OK; } static int cmd_select(char *num) { unsigned int which, i; struct pcap_pkthdr *hdr; bool have_next = true; if (!pcap_loaded() || strlen(num) == 0) return CMD_ERR; which = strtoul(num, NULL, 10); if (which == 0) { rl_printf("packet count starts with 1, clamping!\n"); which = 1; } pcap_reset_pkt(); bpf_reset(); for (i = 0; i < which && (have_next = pcap_next_pkt()); i++) /* noop */; if (!have_next || (hdr = pcap_curr_pkt()) == NULL) { rl_printf("no packet #%u available!\n", which); pcap_reset_pkt(); return CMD_ERR; } return CMD_OK; } static int cmd_breakpoint(char *subcmd) { if (!bpf_prog_loaded()) return CMD_ERR; if (strlen(subcmd) == 0) bpf_dump_breakpoints(); else if (matches(subcmd, "reset") == 0) bpf_reset_breakpoints(); else { unsigned int where = strtoul(subcmd, NULL, 10); if (where < bpf_prog_len) { bpf_set_breakpoints(where); rl_printf("breakpoint at: "); bpf_disasm(bpf_image[where], where); } } return CMD_OK; } static int cmd_run(char *num) { static uint32_t pass = 0, fail = 0; struct pcap_pkthdr *hdr; bool has_limit = true; int ret, pkts = 0, i = 0; if (!bpf_prog_loaded() || !pcap_loaded()) return CMD_ERR; pkts = strtol(num, NULL, 10); if (pkts == 0 || strlen(num) == 0) has_limit = false; do { hdr = pcap_curr_pkt(); ret = bpf_run_all(bpf_image, bpf_prog_len, (uint8_t *) hdr + sizeof(*hdr), hdr->caplen, hdr->len); if (ret > 0) pass++; else if (ret == 0) fail++; else return CMD_OK; bpf_reset(); } while (pcap_next_pkt() && (!has_limit || (has_limit && ++i < pkts))); rl_printf("bpf passes:%u fails:%u\n", pass, fail); pcap_reset_pkt(); bpf_reset(); pass = fail = 0; return CMD_OK; } static int cmd_disassemble(char *line_string) { bool single_line = false; unsigned long line; if (!bpf_prog_loaded()) return CMD_ERR; if (strlen(line_string) > 0 && (line = strtoul(line_string, NULL, 10)) < bpf_prog_len) single_line = true; if (single_line) bpf_disasm(bpf_image[line], line); else bpf_disasm_all(bpf_image, bpf_prog_len); return CMD_OK; } static int cmd_dump(char *dontcare) { if (!bpf_prog_loaded()) return CMD_ERR; bpf_dump_all(bpf_image, bpf_prog_len); return CMD_OK; } static int cmd_quit(char *dontcare) { return CMD_EX; } static const struct shell_cmd cmds[] = { CMD("load", cmd_load), CMD("select", cmd_select), CMD("step", cmd_step), CMD("run", cmd_run), CMD("breakpoint", cmd_breakpoint), CMD("disassemble", cmd_disassemble), CMD("dump", cmd_dump), CMD("quit", cmd_quit), }; static int execf(char *arg) { char *cmd, *cont, *tmp = strdup(arg); int i, ret = 0, len; cmd = strtok_r(tmp, " ", &cont); if (cmd == NULL) goto out; len = strlen(cmd); for (i = 0; i < array_size(cmds); i++) { if (len != strlen(cmds[i].name)) continue; if (strncmp(cmds[i].name, cmd, len) == 0) { ret = cmds[i].func(cont); break; } } out: free(tmp); return ret; } static char *shell_comp_gen(const char *buf, int state) { static int list_index, len; const char *name; if (!state) { list_index = 0; len = strlen(buf); } for (; list_index < array_size(cmds); ) { name = cmds[list_index].name; list_index++; if (strncmp(name, buf, len) == 0) return strdup(name); } return NULL; } static char **shell_completion(const char *buf, int start, int end) { char **matches = NULL; if (start == 0) matches = rl_completion_matches(buf, shell_comp_gen); return matches; } static void intr_shell(int sig) { if (rl_end) rl_kill_line(-1, 0); rl_crlf(); rl_refresh_line(0, 0); rl_free_line_state(); } static void init_shell(FILE *fin, FILE *fout) { char file[128]; memset(file, 0, sizeof(file)); snprintf(file, sizeof(file) - 1, "%s/.bpf_dbg_history", getenv("HOME")); read_history(file); memset(file, 0, sizeof(file)); snprintf(file, sizeof(file) - 1, "%s/.bpf_dbg_init", getenv("HOME")); rl_instream = fin; rl_outstream = fout; rl_readline_name = "bpf_dbg"; rl_terminal_name = getenv("TERM"); rl_catch_signals = 0; rl_catch_sigwinch = 1; rl_attempted_completion_function = shell_completion; rl_bind_key('\t', rl_complete); rl_bind_key_in_map('\t', rl_complete, emacs_meta_keymap); rl_bind_key_in_map('\033', rl_complete, emacs_meta_keymap); rl_read_init_file(file); rl_prep_terminal(0); rl_set_signals(); signal(SIGINT, intr_shell); } static void exit_shell(void) { char file[128]; memset(file, 0, sizeof(file)); snprintf(file, sizeof(file) - 1, "%s/.bpf_dbg_history", getenv("HOME")); write_history(file); clear_history(); rl_deprep_terminal(); try_close_pcap(); } static int run_shell_loop(FILE *fin, FILE *fout) { char *buf; int ret; init_shell(fin, fout); while ((buf = readline("> ")) != NULL) { ret = execf(buf); if (ret == CMD_EX) break; if (ret == CMD_OK && strlen(buf) > 0) add_history(buf); free(buf); } exit_shell(); return 0; } int main(int argc, char **argv) { FILE *fin = NULL, *fout = NULL; if (argc >= 2) fin = fopen(argv[1], "r"); if (argc >= 3) fout = fopen(argv[2], "w"); return run_shell_loop(fin ? : stdin, fout ? : stdout); }
the_stack_data/844091.c
// This is a test code that is infinitely recursive and which can be found in the CentOS version of exim C application. // A slightly different version of this has been identified and is in test2012_04.c // extern int recvmmsg (int __fd, struct mmsghdr *__vmessages, unsigned int __vlen, int __flags, __const struct timespec *__tmo); // int recvmmsg (int __fd, struct mmsghdr *__vmessages ); // void recvmmsg (struct mmsghdr *x ); void foo (struct X *abc);
the_stack_data/76700348.c
//inner list file //create by inner-trans #ifdef _MG_ENABLE_LICENSE //include files extern unsigned char __mg_splash_dat_00_minigui_data[]; //00_minigui.dat.c extern unsigned char __mg_splash_dat_01_fmsoft_data[]; //01_fmsoft.dat.c extern unsigned char __mg_splash_dat_02_feiman_data[]; //02_feiman.dat.c extern unsigned char __mg_splash_dat_03_progressbar_data[]; //03_progressbar.dat.c extern unsigned char __mg_splash_dat_04_progressbar_bk_data[]; //04_progressbar-bk.dat.c //declear arrays static INNER_RES __mg_splash_splash_inner_res[]={ { 0x1562B2, (void*)__mg_splash_dat_00_minigui_data, 18067, "dat"}, //00_minigui.dat.c { 0xCD582, (void*)__mg_splash_dat_01_fmsoft_data, 3806, "dat"}, //01_fmsoft.dat.c { 0xC8712, (void*)__mg_splash_dat_02_feiman_data, 10032, "dat"}, //02_feiman.dat.c { 0x536B0E, (void*)__mg_splash_dat_03_progressbar_data, 2863, "dat"}, //03_progressbar.dat.c { 0xC97F8E, (void*)__mg_splash_dat_04_progressbar_bk_data, 2932, "dat"}, //04_progressbar-bk.dat.c }; #endif // _MG_ENABLE_LICENSE
the_stack_data/138987.c
int main(void) { char c; c = 'at'; return 0; }
the_stack_data/215768083.c
/*- * Copyright (c) 1988 Terry Donahue * 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 AUTHOR 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 AUTHOR 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. */ #ifdef MULTI_SYNC #define NEED_REPLIES #define NEED_EVENTS #ifndef __GNUC__ #define UNIXCPP #endif #include <X11/Xlibint.h> extern _XQEvent *_qfree; /* * Synchronize multiple displays with errors and events, optionally * discarding pending events. */ void XMultiSync(Display *dpys[], int num_dpys, int discard) { register Display *dpy; xGetInputFocusReply rep; register xReq *req; register int i; for (i = 0; i < num_dpys; ++i) { dpy = dpys[i]; LockDisplay(dpy); } /* Send out all the input focus requests at once */ for (i = 0; i < num_dpys; ++i) { dpy = dpys[i]; GetEmptyReq(GetInputFocus, req); _XFlush(dpy); } /* Wait for all the replies to come back in */ for (i = 0; i < num_dpys; ++i) { dpy = dpys[i]; (void) _XReply(dpy, (xReply *) & rep, 0, xTrue); } if (discard) { for (i = 0; i < num_dpys; ++i) { dpy = dpys[i]; if (dpy->head) { ((_XQEvent *) dpy->tail)->next = _qfree; _qfree = (_XQEvent *) dpy->head; dpy->head = dpy->tail = NULL; dpy->qlen = 0; } } } for (i = 0; i < num_dpys; ++i) { dpy = dpys[i]; UnlockDisplay(dpy); } } #endif /* MULTI_SYNC */
the_stack_data/243894340.c
#include <stdio.h> int main (){ //Ler as notas da 1a. e 2a. avaliações de um aluno. Calcular a média aritmética simples e escrever //uma mensagem que diga se o aluno foi ou não aprovado (considerar que nota igual ou maior que 6 o //aluno é aprovado). Escrever também a média calculada. double nota1; double nota2; double media; printf("Digite sua primeira nota:"); scanf("%lf",&nota1); printf("Digite sua segunda nota:"); scanf("%lf",&nota2); media=(nota1+nota2)/2; if(media >=6 ){ printf("Aprovado media=%0.2lf",media); } else{ printf("Não foi aprovado media=%0.2lf",media); } }
the_stack_data/58674.c
// SPDX-FileCopyrightText: Copyright (c) 2019-2021 Virginia Tech // SPDX-License-Identifier: Apache-2.0 #ifdef TS_NVM_IS_PMDK #include <libpmemobj.h> #include "util.h" #include "debug.h" #include "port.h" #include "nvm.h" static PMEMobjpool *__g_pop; #define POOL_PATH "/mnt/pmem/ts" #define POOL_SIZE 25ul * 1024ul * 1024ul * 1024ul ts_nvm_root_obj_t *nvm_load_heap(const char *path, size_t sz, int *is_created) { PMEMoid root; ts_nvm_root_obj_t *root_obj; /* You should not init twice. */ ts_assert(__g_pop == NULL); /* Open a nvm heap */ if (access(POOL_PATH, F_OK) != 0) { __g_pop = pmemobj_create(POOL_PATH, POBJ_LAYOUT_NAME(nvlog), POOL_SIZE, 0666); if (unlikely(!__g_pop)) { ts_trace(TS_ERROR, "failed to create pool\n"); return NULL; } *is_created = 1; } else { if ((__g_pop = pmemobj_open(POOL_PATH, POBJ_LAYOUT_NAME(nvlog))) == NULL) { ts_trace(TS_ERROR, "failed to open the exsisting pool\n"); return NULL; } *is_created = 0; } /* Allocate a root in the nvmem pool, here on root_obj * will be the entry point to nv pool for all log allocations*/ root = pmemobj_root(__g_pop, sizeof(ts_nvm_root_obj_t)); root_obj = pmemobj_direct(root); if (!root_obj) { return NULL; } if (*is_created) { memset(root_obj, 0, sizeof(*root_obj)); } return root_obj; } void nvm_heap_destroy(void) { PMEMoid root; ts_nvm_root_obj_t *root_obj; /* set the root_obj->next to null to signify safe termination*/ root = pmemobj_root(__g_pop, sizeof(ts_nvm_root_obj_t)); root_obj = pmemobj_direct(root); root_obj->next = NULL; flush_to_nvm(root_obj, sizeof(*root_obj)); smp_wmb(); pmemobj_close(__g_pop); __g_pop = NULL; } void *nvm_alloc(size_t size) { int ret; PMEMoid master_obj; ret = pmemobj_alloc(__g_pop, &master_obj, size, 0, NULL, NULL); /* TODO: need to link each object for recovery */ if (ret) { ts_trace(TS_ERROR, "master_obj allocation failed\n"); return NULL; } return pmemobj_direct(master_obj); } void *nvm_aligned_alloc(size_t alignment, size_t size) { /* TODO: need to implement aligned alloc */ return nvm_alloc(size); } void nvm_free(void *ptr) { PMEMoid _ptr; _ptr = pmemobj_oid(ptr); pmemobj_free(&_ptr); } #endif /* TS_NVM_IS_PMDK */
the_stack_data/678388.c
/* unused */ /* crypto/bn/expspeed.c */ /* Copyright (C) 1995-1998 Eric Young ([email protected]) * All rights reserved. * * This package is an SSL implementation written * by Eric Young ([email protected]). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson ([email protected]). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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 cryptographic software written by * Eric Young ([email protected])" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson ([email protected])" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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 licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* most of this code has been pilfered from my libdes speed.c program */ #define BASENUM 5000 #define NUM_START 0 /* determine timings for modexp, modmul, modsqr, gcd, Kronecker symbol, * modular inverse, or modular square roots */ #define TEST_EXP #undef TEST_MUL #undef TEST_SQR #undef TEST_GCD #undef TEST_KRON #undef TEST_INV #undef TEST_SQRT #define P_MOD_64 9 /* least significant 6 bits for prime to be used for BN_sqrt timings */ #if defined(TEST_EXP) + defined(TEST_MUL) + defined(TEST_SQR) + defined(TEST_GCD) + defined(TEST_KRON) + defined(TEST_INV) +defined(TEST_SQRT) != 1 # error "choose one test" #endif #if defined(TEST_INV) || defined(TEST_SQRT) # define C_PRIME static void genprime_cb(int p, int n, void *arg); #endif #undef PROG #define PROG bnspeed_main #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <string.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/rand.h> #if !defined(OPENSSL_SYS_MSDOS) && (!defined(OPENSSL_SYS_VMS) || defined(__DECC)) && !defined(OPENSSL_SYS_MACOSX) #define TIMES #endif #ifndef _IRIX #include <time.h> #endif #ifdef TIMES #include <sys/types.h> #include <sys/times.h> #endif /* Depending on the VMS version, the tms structure is perhaps defined. The __TMS macro will show if it was. If it wasn't defined, we should undefine TIMES, since that tells the rest of the program how things should be handled. -- Richard Levitte */ #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__TMS) #undef TIMES #endif #ifndef TIMES #include <sys/timeb.h> #endif #if defined(sun) || defined(__ultrix) #define _POSIX_SOURCE #include <limits.h> #include <sys/param.h> #endif #include <openssl/bn.h> #include <openssl/x509.h> /* The following if from times(3) man page. It may need to be changed */ #ifndef HZ # ifndef CLK_TCK # ifndef _BSD_CLK_TCK_ /* FreeBSD hack */ # define HZ 100.0 # else /* _BSD_CLK_TCK_ */ # define HZ ((double)_BSD_CLK_TCK_) # endif # else /* CLK_TCK */ # define HZ ((double)CLK_TCK) # endif #endif #undef BUFSIZE #define BUFSIZE ((long)1024*8) int run=0; static double Time_F(int s); #define START 0 #define STOP 1 static double Time_F(int s) { double ret; #ifdef TIMES static struct tms tstart,tend; if (s == START) { times(&tstart); return(0); } else { times(&tend); ret=((double)(tend.tms_utime-tstart.tms_utime))/HZ; return((ret < 1e-3)?1e-3:ret); } #else /* !times() */ static struct timeb tstart,tend; long i; if (s == START) { ftime(&tstart); return(0); } else { ftime(&tend); i=(long)tend.millitm-(long)tstart.millitm; ret=((double)(tend.time-tstart.time))+((double)i)/1000.0; return((ret < 0.001)?0.001:ret); } #endif } #define NUM_SIZES 7 #if NUM_START > NUM_SIZES # error "NUM_START > NUM_SIZES" #endif static int sizes[NUM_SIZES]={128,256,512,1024,2048,4096,8192}; static int mul_c[NUM_SIZES]={8*8*8*8*8*8,8*8*8*8*8,8*8*8*8,8*8*8,8*8,8,1}; /*static int sizes[NUM_SIZES]={59,179,299,419,539}; */ #define RAND_SEED(string) { const char str[] = string; RAND_seed(string, sizeof str); } void do_mul_exp(BIGNUM *r,BIGNUM *a,BIGNUM *b,BIGNUM *c,BN_CTX *ctx); int main(int argc, char **argv) { BN_CTX *ctx; BIGNUM *a,*b,*c,*r; #if 1 if (!CRYPTO_set_mem_debug_functions(0,0,0,0,0)) abort(); #endif ctx=BN_CTX_new(); a=BN_new(); b=BN_new(); c=BN_new(); r=BN_new(); while (!RAND_status()) /* not enough bits */ RAND_SEED("I demand a manual recount!"); do_mul_exp(r,a,b,c,ctx); return 0; } void do_mul_exp(BIGNUM *r, BIGNUM *a, BIGNUM *b, BIGNUM *c, BN_CTX *ctx) { int i,k; double tm; long num; num=BASENUM; for (i=NUM_START; i<NUM_SIZES; i++) { #ifdef C_PRIME # ifdef TEST_SQRT if (!BN_set_word(a, 64)) goto err; if (!BN_set_word(b, P_MOD_64)) goto err; # define ADD a # define REM b # else # define ADD NULL # define REM NULL # endif if (!BN_generate_prime(c,sizes[i],0,ADD,REM,genprime_cb,NULL)) goto err; putc('\n', stderr); fflush(stderr); #endif for (k=0; k<num; k++) { if (k%50 == 0) /* Average over num/50 different choices of random numbers. */ { if (!BN_pseudo_rand(a,sizes[i],1,0)) goto err; if (!BN_pseudo_rand(b,sizes[i],1,0)) goto err; #ifndef C_PRIME if (!BN_pseudo_rand(c,sizes[i],1,1)) goto err; #endif #ifdef TEST_SQRT if (!BN_mod_sqr(a,a,c,ctx)) goto err; if (!BN_mod_sqr(b,b,c,ctx)) goto err; #else if (!BN_nnmod(a,a,c,ctx)) goto err; if (!BN_nnmod(b,b,c,ctx)) goto err; #endif if (k == 0) Time_F(START); } #if defined(TEST_EXP) if (!BN_mod_exp(r,a,b,c,ctx)) goto err; #elif defined(TEST_MUL) { int i = 0; for (i = 0; i < 50; i++) if (!BN_mod_mul(r,a,b,c,ctx)) goto err; } #elif defined(TEST_SQR) { int i = 0; for (i = 0; i < 50; i++) { if (!BN_mod_sqr(r,a,c,ctx)) goto err; if (!BN_mod_sqr(r,b,c,ctx)) goto err; } } #elif defined(TEST_GCD) if (!BN_gcd(r,a,b,ctx)) goto err; if (!BN_gcd(r,b,c,ctx)) goto err; if (!BN_gcd(r,c,a,ctx)) goto err; #elif defined(TEST_KRON) if (-2 == BN_kronecker(a,b,ctx)) goto err; if (-2 == BN_kronecker(b,c,ctx)) goto err; if (-2 == BN_kronecker(c,a,ctx)) goto err; #elif defined(TEST_INV) if (!BN_mod_inverse(r,a,c,ctx)) goto err; if (!BN_mod_inverse(r,b,c,ctx)) goto err; #else /* TEST_SQRT */ if (!BN_mod_sqrt(r,a,c,ctx)) goto err; if (!BN_mod_sqrt(r,b,c,ctx)) goto err; #endif } tm=Time_F(STOP); printf( #if defined(TEST_EXP) "modexp %4d ^ %4d %% %4d" #elif defined(TEST_MUL) "50*modmul %4d %4d %4d" #elif defined(TEST_SQR) "100*modsqr %4d %4d %4d" #elif defined(TEST_GCD) "3*gcd %4d %4d %4d" #elif defined(TEST_KRON) "3*kronecker %4d %4d %4d" #elif defined(TEST_INV) "2*inv %4d %4d mod %4d" #else /* TEST_SQRT */ "2*sqrt [prime == %d (mod 64)] %4d %4d mod %4d" #endif " -> %8.6fms %5.1f (%ld)\n", #ifdef TEST_SQRT P_MOD_64, #endif sizes[i],sizes[i],sizes[i],tm*1000.0/num,tm*mul_c[i]/num, num); num/=7; if (num <= 0) num=1; } return; err: ERR_print_errors_fp(stderr); } #ifdef C_PRIME static void genprime_cb(int p, int n, void *arg) { char c='*'; if (p == 0) c='.'; if (p == 1) c='+'; if (p == 2) c='*'; if (p == 3) c='\n'; putc(c, stderr); fflush(stderr); (void)n; (void)arg; } #endif
the_stack_data/497998.c
/* Glidix Runtime Copyright (c) 2014-2017, Madd Games. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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 HOLDER 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. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> void abort() { raise(SIGABRT); exit(-SIGABRT); // if SIGABRT was caught };
the_stack_data/125141424.c
// Empty source file! Beautiful!!
the_stack_data/80538.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2013-2020 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/>. */ /* This program is intended to be started outside of gdb, and then attached to by gdb. It loops for a while, but not forever. */ #include <unistd.h> static void foo1 (void) { sleep (100); } static void foo2 (void) { foo1 (); } static void foo3 (void) { foo2 (); } int main (void) { foo3 (); return 0; }
the_stack_data/1158892.c
typedef struct S1 { int x; } T1; struct S3 { int x; }; typedef struct { int x; struct S3 s3; } T4; typedef union U5 { int x; double y; } T5; typedef struct S6 { struct { int x; }; union { int y; int z; }; } T6; typedef struct S7 { struct { int x; } y; union { int w; } z; } T7; int main() {}
the_stack_data/126703055.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define min(a,b) (((a)<(b))?(a):(b)) #define max(a,b) (((a)>(b))?(a):(b)) #define SOME_ABSURDLY_HIGH_NUMBER 2147483647 #define TEXT_BLOCK_SIZE 8 #define CHANGE 'c' #define PRINT 'p' #define DELETE 'd' #define QUIT 'q' #define UNDO 'u' #define REDO 'r' #define SKIP 0 /* ===================================================================== */ /* typedefs */ typedef struct edit{ char code; int location, size, setlen; char **lines; }edit_t; typedef struct state{ edit_t *undo, *redo; }state_t; typedef struct snpsht{ int time; int size; char **lines; }snapshot_t; /* ===================================================================== */ /* Function declarations */ void AdjustCapacity(int required_lines); void SetTextCapacity(int capacity); void SetTextLength(int length); void SetLine(int location, char **content); void UpdateHistory(); void FreeStateContent(int index); edit_t *GetStateEdit(char which); void SetupEdit(edit_t *e, char code, int loc, int setl, int size); void AddLineToEdit(edit_t *e, char **lineContent); void OnQuit(); void OnPrint(int from, int to); void OnChange(int from, int to); void OnDelete(int from, int to); void OnUndo(int steps); void OnRedo(int steps); void QueueUndos(int amount); void QueueRedos(int amount); void RestoreEdits(); void UpdateSnapshots(); snapshot_t TakeSnapshot(); int FindClosestSnapshot(int to); void RestoreSnapshot(int snap); /* ===================================================================== */ /* Globals */ char **text; int t_cap = 0; // Text capacity int t_len = 0; // Text length char *in_buf = NULL; size_t in_size = 0; ssize_t in_len = 0; char status = 0; state_t *history; int stateCount = 0; // Max time int currentState = 0; // Current time int actions_to_restore = 0; snapshot_t *album = NULL; int album_len = 0, *album_pages = NULL; /* ===================================================================== */ /* Main */ int main(int argc, char* argv[]){ // Init text SetTextCapacity(TEXT_BLOCK_SIZE); // Init history (count = 1, current = 0) UpdateHistory(); UpdateSnapshots(); int arg1, arg2; while(status != QUIT){ // Get input in_buf = NULL; in_len = getline(&in_buf, &in_size, stdin); // Execute input switch (status = in_buf[in_len - 2]){ case PRINT: RestoreEdits(); sscanf(in_buf, "%d,%dp", &arg1, &arg2); OnPrint(arg1, arg2); break; case CHANGE: RestoreEdits(); sscanf(in_buf, "%d,%dc", &arg1, &arg2); OnChange(arg1, arg2); break; case DELETE: RestoreEdits(); sscanf(in_buf, "%d,%dd", &arg1, &arg2); OnDelete(arg1, arg2); break; case UNDO: sscanf(in_buf, "%du", &arg1); // OnUndo(arg1); QueueUndos(arg1); break; case REDO: sscanf(in_buf, "%dr", &arg1); // OnRedo(arg1); QueueRedos(arg1); break; } } return 0; } /* ===================================================================== */ /* Text support */ void SetTextCapacity(int capacity){ t_cap = capacity; text = (char**)realloc(text, t_cap * sizeof(char*)); } void AdjustTextCapacity(int required_lines) { int capacity = t_cap; if(required_lines < capacity) { // Decrease capacity to trim out any non required text space while(capacity - TEXT_BLOCK_SIZE >= required_lines) capacity -= TEXT_BLOCK_SIZE; } else { // Increase capacity to fit the required text size while(required_lines > capacity) capacity += TEXT_BLOCK_SIZE; } SetTextCapacity(capacity); } void SetTextLength(int length){ t_len = length; AdjustTextCapacity(t_len); } void SetLine(int location, char** content){ text[location-1] = (*content); } /* ===================================================================== */ /* History support */ void UpdateHistory(){ // Making changes in the present if(stateCount == 0 || currentState == stateCount-1){ // Increase count by one state and reallocate memory stateCount++; } // Making changes in the past else { // Deallocate old states for(int i = currentState + 1; i < stateCount; i++){ FreeStateContent(i); } // Set new size and reallocate stateCount = currentState + 2; } // Resize history space history = (state_t*)realloc(history, stateCount * sizeof(state_t)); // Initialize new state history[stateCount - 1].undo = NULL; history[stateCount - 1].redo = NULL; } void FreeStateContent(int index){ edit_t *e = history[index].undo; if(e != NULL){ free(e); history[index].undo = NULL; } e = history[index].redo; if(e != NULL){ free(e); history[index].redo = NULL; } } edit_t* GetStateEdit(char which){ if(which == UNDO){ // If empty, generate (could do realloc/calloc but is it necessary?) if(history[currentState + 1].undo == NULL) { history[currentState + 1].undo = (edit_t*)malloc(sizeof(edit_t)); history[currentState + 1].undo->code = 0; history[currentState + 1].undo->location = 0; history[currentState + 1].undo->size = 0; history[currentState + 1].undo->setlen = 0; history[currentState + 1].undo->lines = NULL; } return history[currentState+1].undo; } // If empty, generate (could do realloc/calloc but is it necessary?) if(history[currentState].redo == NULL){ history[currentState].redo = (edit_t*)malloc(sizeof(edit_t)); history[currentState].redo->code = 0; history[currentState].redo->location = 0; history[currentState].redo->size = 0; history[currentState].redo->setlen = 0; history[currentState].redo->lines = NULL; } return history[currentState].redo; } void SetupEdit(edit_t *e, char code, int loc, int setl, int size){ e->code = code; e->location = loc; e->setlen = setl; e->size = size; e->lines = NULL; } void AddLineToEdit(edit_t *e, char **lineContent){ e->size++; e->lines = (char**)realloc(e->lines, e->size * sizeof(char*)); e->lines[e->size-1] = (*lineContent); } /* ===================================================================== */ /* Command events */ void OnPrint(int from, int to){ for(int i = from; i <= to; i++){ if(i > 0 && i <= t_len) printf("%s", text[i-1]); else printf(".\n"); } } void OnChange(int from, int to){ int prevLen = t_len; // Expand/Trim text to fit SetTextLength(max(to, prevLen)); UpdateHistory(); // count = current + 2, current+1 is the undo's state edit_t *undo = GetStateEdit(UNDO); SetupEdit(undo, CHANGE, from, prevLen, 0); edit_t *redo = GetStateEdit(REDO); SetupEdit(redo, CHANGE, from, t_len, 0); for(int i = from; i <= to; i++){ // Get input in_buf = NULL; in_len = getline(&in_buf, &in_size, stdin); // If line is being overwritten if(i <= prevLen) { AddLineToEdit(undo, &text[i-1]); } SetLine(i, &in_buf); AddLineToEdit(redo, &in_buf); } currentState++; } void OnDelete(int from, int to){ if(from > t_len || to < 1) { UpdateHistory(); edit_t *undo = GetStateEdit(UNDO); SetupEdit(undo, SKIP, 0, 0, 0); edit_t *redo = GetStateEdit(REDO); SetupEdit(redo, SKIP, 0, 0, 0); currentState++; return; } int lastToRemove = min(to, t_len); int offset = lastToRemove - from + 1; UpdateHistory(); edit_t *undo = GetStateEdit(UNDO); SetupEdit(undo, DELETE, from, t_len, 0); edit_t *redo = GetStateEdit(REDO); SetupEdit(redo, DELETE, from, t_len-offset, offset); UpdateSnapshots(); int cursor = from - 1; while(cursor < t_len){ if(cursor < lastToRemove){ AddLineToEdit(undo, &text[cursor]); } if(cursor + offset < t_len){ text[cursor] = text[cursor+offset]; text[cursor + offset] = NULL; } cursor++; } SetTextLength(t_len-offset); currentState++; } void OnUndo(int steps){ edit_t *undo; while(currentState > 0 && steps > 0){ undo = history[currentState].undo; switch (undo->code){ case CHANGE: /* Undo Change ------------------ */ { SetTextLength(undo->setlen); for(int i = 0; i < undo->size; i++){ SetLine(undo->location + i, &undo->lines[i]); } } break; case DELETE: /* Undo Delete (do insert) ------ */ { SetTextLength(undo->setlen); int cursor = t_len; while(cursor >= undo->location){ // Inserting at the end if(t_len - undo->size == undo->location - 1){ SetLine(cursor, &undo->lines[cursor-undo->location]); } // Inserting in the middle else { if(cursor-undo->size > 0) text[cursor - 1] = text[cursor-undo->size - 1]; if(cursor <= undo->location + undo->size - 1) SetLine(cursor, &undo->lines[cursor-undo->location]); } cursor--; } } break; } steps--; currentState--; } } void OnRedo(int steps){ edit_t *redo; while(currentState < stateCount - 1 && steps > 0){ redo = history[currentState].redo; switch (redo->code){ case CHANGE: /* Redo Change ------------------ */ { SetTextLength(redo->setlen); for(int i = 0; i < redo->size; i++){ SetLine(redo->location + i, &redo->lines[i]); } } break; case DELETE: /* Redo Delete ------------------ */ { int cursor = redo->location - 1; while(cursor < t_len){ if(cursor + redo->size < t_len){ text[cursor] = text[cursor+redo->size]; text[cursor + redo->size] = NULL; } cursor++; } SetTextLength(redo->setlen); } break; } steps--; currentState++; } } void QueueUndos(int amount){ actions_to_restore -= amount; if(currentState + actions_to_restore < 0) actions_to_restore = -currentState; } void QueueRedos(int amount){ actions_to_restore += amount; if(actions_to_restore + currentState > stateCount - 1) actions_to_restore = stateCount - 1 - currentState; } void RestoreEdits(){ int target = currentState + actions_to_restore; int snapshot = FindClosestSnapshot(target); if(abs(target - album[snapshot].time) < abs(target-currentState)){ RestoreSnapshot(snapshot); actions_to_restore = target - album[snapshot].time; } if(actions_to_restore > 0) OnRedo(actions_to_restore); else if (actions_to_restore < 0) OnUndo(-actions_to_restore); actions_to_restore = 0; } void UpdateSnapshots(){ if(album_len == 0){ album_len++; album = malloc(sizeof(snapshot_t)); } else if(currentState == stateCount - 1){ album_len++; album=realloc(album, album_len * sizeof(snapshot_t)); } else { int counter; for(counter = 0; counter < album_len; counter++){ if(album[counter].time > currentState) break; } album_len = counter+1; album = realloc(album, album_len * sizeof(snapshot_t)); } album[album_len-1] = TakeSnapshot(); } snapshot_t TakeSnapshot(){ snapshot_t s; s.time = currentState; s.size = t_len; s.lines=(char**)malloc(t_len * sizeof(char*)); for(int i = 0; i < t_len; i++){ s.lines[i] = strdup(text[i]); } return s; } int FindClosestSnapshot(int to){ int currentCloser = 0; for(int i = 1; i < album_len; i++){ if(abs(to - album[i].time) < abs(to - currentCloser)) currentCloser = i; } return currentCloser; } void RestoreSnapshot(int snap){ snapshot_t s = album[snap]; SetTextLength(s.size); for(int i = 0; i < t_len; i++) text[i] = s.lines[i]; currentState = s.time; }
the_stack_data/187643197.c
struct S$TU2; union S$TU1; struct S$TU2 { int x; };
the_stack_data/154830322.c
/** ****************************************************************************** * @file stm32l0xx_ll_adc.c * @author MCD Application Team * @brief ADC LL module driver ****************************************************************************** * @attention * * <h2><center>&copy; Copyright(c) 2016 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32l0xx_ll_adc.h" #include "stm32l0xx_ll_bus.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /** @addtogroup STM32L0xx_LL_Driver * @{ */ #if defined (ADC1) /** @addtogroup ADC_LL ADC * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @addtogroup ADC_LL_Private_Constants * @{ */ /* Definitions of ADC hardware constraints delays */ /* Note: Only ADC peripheral HW delays are defined in ADC LL driver driver, */ /* not timeout values: */ /* Timeout values for ADC operations are dependent to device clock */ /* configuration (system clock versus ADC clock), */ /* and therefore must be defined in user application. */ /* Refer to @ref ADC_LL_EC_HW_DELAYS for description of ADC timeout */ /* values definition. */ /* Note: ADC timeout values are defined here in CPU cycles to be independent */ /* of device clock setting. */ /* In user application, ADC timeout values should be defined with */ /* temporal values, in function of device clock settings. */ /* Highest ratio CPU clock frequency vs ADC clock frequency: */ /* - ADC clock from synchronous clock with AHB prescaler 512, */ /* APB prescaler 16, ADC prescaler 4. */ /* - ADC clock from asynchronous clock (HSI) with prescaler 1, */ /* with highest ratio CPU clock frequency vs HSI clock frequency: */ /* CPU clock frequency max 32MHz, HSI frequency 16MHz: ratio 2. */ /* Unit: CPU cycles. */ #define ADC_CLOCK_RATIO_VS_CPU_HIGHEST ((uint32_t) 512U * 16U * 4U) #define ADC_TIMEOUT_DISABLE_CPU_CYCLES (ADC_CLOCK_RATIO_VS_CPU_HIGHEST * 1U) #define ADC_TIMEOUT_STOP_CONVERSION_CPU_CYCLES (ADC_CLOCK_RATIO_VS_CPU_HIGHEST * 1U) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup ADC_LL_Private_Macros * @{ */ /* Check of parameters for configuration of ADC hierarchical scope: */ /* common to several ADC instances. */ #define IS_LL_ADC_COMMON_CLOCK(__CLOCK__) \ ( ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV1) \ || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV2) \ || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV4) \ || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV6) \ || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV8) \ || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV10) \ || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV12) \ || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV16) \ || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV32) \ || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV64) \ || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV128) \ || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC_DIV256) \ ) #define IS_LL_ADC_CLOCK_FREQ_MODE(__CLOCK_FREQ_MODE__) \ ( ((__CLOCK_FREQ_MODE__) == LL_ADC_CLOCK_FREQ_MODE_HIGH) \ || ((__CLOCK_FREQ_MODE__) == LL_ADC_CLOCK_FREQ_MODE_LOW) \ ) /* Check of parameters for configuration of ADC hierarchical scope: */ /* ADC instance. */ #define IS_LL_ADC_CLOCK(__CLOCK__) \ ( ((__CLOCK__) == LL_ADC_CLOCK_SYNC_PCLK_DIV4) \ || ((__CLOCK__) == LL_ADC_CLOCK_SYNC_PCLK_DIV2) \ || ((__CLOCK__) == LL_ADC_CLOCK_SYNC_PCLK_DIV1) \ || ((__CLOCK__) == LL_ADC_CLOCK_ASYNC) \ ) #define IS_LL_ADC_RESOLUTION(__RESOLUTION__) \ ( ((__RESOLUTION__) == LL_ADC_RESOLUTION_12B) \ || ((__RESOLUTION__) == LL_ADC_RESOLUTION_10B) \ || ((__RESOLUTION__) == LL_ADC_RESOLUTION_8B) \ || ((__RESOLUTION__) == LL_ADC_RESOLUTION_6B) \ ) #define IS_LL_ADC_DATA_ALIGN(__DATA_ALIGN__) \ ( ((__DATA_ALIGN__) == LL_ADC_DATA_ALIGN_RIGHT) \ || ((__DATA_ALIGN__) == LL_ADC_DATA_ALIGN_LEFT) \ ) #define IS_LL_ADC_LOW_POWER(__LOW_POWER__) \ ( ((__LOW_POWER__) == LL_ADC_LP_MODE_NONE) \ || ((__LOW_POWER__) == LL_ADC_LP_AUTOWAIT) \ || ((__LOW_POWER__) == LL_ADC_LP_AUTOPOWEROFF) \ || ((__LOW_POWER__) == LL_ADC_LP_AUTOWAIT_AUTOPOWEROFF) \ ) /* Check of parameters for configuration of ADC hierarchical scope: */ /* ADC group regular */ /* ADC group regular external trigger TIM2_CC3 available only on */ /* STM32L0 devices categories: Cat.1, Cat.2, Cat.5 */ #if defined (STM32L011xx) || defined (STM32L021xx) || \ defined (STM32L031xx) || defined (STM32L041xx) || \ defined (STM32L071xx) || defined (STM32L072xx) || defined (STM32L073xx) || \ defined (STM32L081xx) || defined (STM32L082xx) || defined (STM32L083xx) #define IS_LL_ADC_REG_TRIG_SOURCE(__REG_TRIG_SOURCE__) \ ( ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM6_TRGO) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM21_CH2) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_TRGO) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH4) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM22_TRGO) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH3) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_TRGO) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \ ) #else #define IS_LL_ADC_REG_TRIG_SOURCE(__REG_TRIG_SOURCE__) \ ( ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_SOFTWARE) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM6_TRGO) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM21_CH2) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_TRGO) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM2_CH4) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM22_TRGO) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_TIM3_TRGO) \ || ((__REG_TRIG_SOURCE__) == LL_ADC_REG_TRIG_EXT_EXTI_LINE11) \ ) #endif #define IS_LL_ADC_REG_CONTINUOUS_MODE(__REG_CONTINUOUS_MODE__) \ ( ((__REG_CONTINUOUS_MODE__) == LL_ADC_REG_CONV_SINGLE) \ || ((__REG_CONTINUOUS_MODE__) == LL_ADC_REG_CONV_CONTINUOUS) \ ) #define IS_LL_ADC_REG_DMA_TRANSFER(__REG_DMA_TRANSFER__) \ ( ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_NONE) \ || ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_LIMITED) \ || ((__REG_DMA_TRANSFER__) == LL_ADC_REG_DMA_TRANSFER_UNLIMITED) \ ) #define IS_LL_ADC_REG_OVR_DATA_BEHAVIOR(__REG_OVR_DATA_BEHAVIOR__) \ ( ((__REG_OVR_DATA_BEHAVIOR__) == LL_ADC_REG_OVR_DATA_PRESERVED) \ || ((__REG_OVR_DATA_BEHAVIOR__) == LL_ADC_REG_OVR_DATA_OVERWRITTEN) \ ) #define IS_LL_ADC_REG_SEQ_SCAN_DISCONT_MODE(__REG_SEQ_DISCONT_MODE__) \ ( ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_DISABLE) \ || ((__REG_SEQ_DISCONT_MODE__) == LL_ADC_REG_SEQ_DISCONT_1RANK) \ ) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup ADC_LL_Exported_Functions * @{ */ /** @addtogroup ADC_LL_EF_Init * @{ */ /** * @brief De-initialize registers of all ADC instances belonging to * the same ADC common instance to their default reset values. * @note This function is performing a hard reset, using high level * clock source RCC ADC reset. * @param ADCxy_COMMON ADC common instance * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) * @retval An ErrorStatus enumeration value: * - SUCCESS: ADC common registers are de-initialized * - ERROR: not applicable */ ErrorStatus LL_ADC_CommonDeInit(ADC_Common_TypeDef *ADCxy_COMMON) { /* Check the parameters */ assert_param(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON)); /* Force reset of ADC clock (core clock) */ LL_APB2_GRP1_ForceReset(LL_APB2_GRP1_PERIPH_ADC1); /* Release reset of ADC clock (core clock) */ LL_APB2_GRP1_ReleaseReset(LL_APB2_GRP1_PERIPH_ADC1); return SUCCESS; } /** * @brief Initialize some features of ADC common parameters * (all ADC instances belonging to the same ADC common instance) * and multimode (for devices with several ADC instances available). * @note The setting of ADC common parameters is conditioned to * ADC instances state: * All ADC instances belonging to the same ADC common instance * must be disabled. * @param ADCxy_COMMON ADC common instance * (can be set directly from CMSIS definition or by using helper macro @ref __LL_ADC_COMMON_INSTANCE() ) * @param ADC_CommonInitStruct Pointer to a @ref LL_ADC_CommonInitTypeDef structure * @retval An ErrorStatus enumeration value: * - SUCCESS: ADC common registers are initialized * - ERROR: ADC common registers are not initialized */ ErrorStatus LL_ADC_CommonInit(ADC_Common_TypeDef *ADCxy_COMMON, LL_ADC_CommonInitTypeDef *ADC_CommonInitStruct) { ErrorStatus status = SUCCESS; /* Check the parameters */ assert_param(IS_ADC_COMMON_INSTANCE(ADCxy_COMMON)); assert_param(IS_LL_ADC_COMMON_CLOCK(ADC_CommonInitStruct->CommonClock)); /* Note: Hardware constraint (refer to description of functions */ /* "LL_ADC_SetCommonXXX()": */ /* On this STM32 serie, setting of these features is conditioned to */ /* ADC state: */ /* All ADC instances of the ADC common group must be disabled. */ if(__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE(ADCxy_COMMON) == 0U) { /* Configuration of ADC hierarchical scope: */ /* - common to several ADC */ /* (all ADC instances belonging to the same ADC common instance) */ /* - Set ADC clock (conversion clock) */ LL_ADC_SetCommonClock(ADCxy_COMMON, ADC_CommonInitStruct->CommonClock); } else { /* Initialization error: One or several ADC instances belonging to */ /* the same ADC common instance are not disabled. */ status = ERROR; } return status; } /** * @brief Set each @ref LL_ADC_CommonInitTypeDef field to default value. * @param ADC_CommonInitStruct Pointer to a @ref LL_ADC_CommonInitTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_ADC_CommonStructInit(LL_ADC_CommonInitTypeDef *ADC_CommonInitStruct) { /* Set ADC_CommonInitStruct fields to default values */ /* Set fields of ADC common */ /* (all ADC instances belonging to the same ADC common instance) */ ADC_CommonInitStruct->CommonClock = LL_ADC_CLOCK_ASYNC_DIV2; } /** * @brief De-initialize registers of the selected ADC instance * to their default reset values. * @note To reset all ADC instances quickly (perform a hard reset), * use function @ref LL_ADC_CommonDeInit(). * @note If this functions returns error status, it means that ADC instance * is in an unknown state. * In this case, perform a hard reset using high level * clock source RCC ADC reset. * Refer to function @ref LL_ADC_CommonDeInit(). * @param ADCx ADC instance * @retval An ErrorStatus enumeration value: * - SUCCESS: ADC registers are de-initialized * - ERROR: ADC registers are not de-initialized */ ErrorStatus LL_ADC_DeInit(ADC_TypeDef *ADCx) { ErrorStatus status = SUCCESS; __IO uint32_t timeout_cpu_cycles = 0U; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(ADCx)); /* Disable ADC instance if not already disabled. */ if(LL_ADC_IsEnabled(ADCx) == 1U) { /* Set ADC group regular trigger source to SW start to ensure to not */ /* have an external trigger event occurring during the conversion stop */ /* ADC disable process. */ LL_ADC_REG_SetTriggerSource(ADCx, LL_ADC_REG_TRIG_SOFTWARE); /* Stop potential ADC conversion on going on ADC group regular. */ if(LL_ADC_REG_IsConversionOngoing(ADCx) != 0U) { if(LL_ADC_REG_IsStopConversionOngoing(ADCx) == 0U) { LL_ADC_REG_StopConversion(ADCx); } } /* Wait for ADC conversions are effectively stopped */ timeout_cpu_cycles = ADC_TIMEOUT_STOP_CONVERSION_CPU_CYCLES; while (LL_ADC_REG_IsStopConversionOngoing(ADCx) == 1U) { if(timeout_cpu_cycles-- == 0U) { /* Time-out error */ status = ERROR; } } /* Disable the ADC instance */ LL_ADC_Disable(ADCx); /* Wait for ADC instance is effectively disabled */ timeout_cpu_cycles = ADC_TIMEOUT_DISABLE_CPU_CYCLES; while (LL_ADC_IsDisableOngoing(ADCx) == 1U) { if(timeout_cpu_cycles-- == 0U) { /* Time-out error */ status = ERROR; } } } /* Check whether ADC state is compliant with expected state */ if(READ_BIT(ADCx->CR, ( ADC_CR_ADSTP | ADC_CR_ADSTART | ADC_CR_ADDIS | ADC_CR_ADEN ) ) == 0U) { /* ========== Reset ADC registers ========== */ /* Reset register IER */ CLEAR_BIT(ADCx->IER, ( LL_ADC_IT_ADRDY | LL_ADC_IT_EOC | LL_ADC_IT_EOS | LL_ADC_IT_OVR | LL_ADC_IT_EOSMP | LL_ADC_IT_AWD1 ) ); /* Reset register ISR */ SET_BIT(ADCx->ISR, ( LL_ADC_FLAG_ADRDY | LL_ADC_FLAG_EOC | LL_ADC_FLAG_EOS | LL_ADC_FLAG_OVR | LL_ADC_FLAG_EOSMP | LL_ADC_FLAG_AWD1 ) ); /* Reset register CR */ /* Bits ADC_CR_ADCAL, ADC_CR_ADSTP, ADC_CR_ADSTART are in access mode */ /* "read-set": no direct reset applicable. */ CLEAR_BIT(ADCx->CR, ADC_CR_ADVREGEN); /* Reset register CFGR1 */ CLEAR_BIT(ADCx->CFGR1, ( ADC_CFGR1_AWDCH | ADC_CFGR1_AWDEN | ADC_CFGR1_AWDSGL | ADC_CFGR1_DISCEN | ADC_CFGR1_AUTOFF | ADC_CFGR1_WAIT | ADC_CFGR1_CONT | ADC_CFGR1_OVRMOD | ADC_CFGR1_EXTEN | ADC_CFGR1_EXTSEL | ADC_CFGR1_ALIGN | ADC_CFGR1_RES | ADC_CFGR1_SCANDIR | ADC_CFGR1_DMACFG | ADC_CFGR1_DMAEN ) ); /* Reset register CFGR2 */ /* Note: Update of ADC clock mode is conditioned to ADC state disabled: */ /* already done above. */ CLEAR_BIT(ADCx->CFGR2, ( ADC_CFGR2_CKMODE | ADC_CFGR2_TOVS | ADC_CFGR2_OVSS | ADC_CFGR2_OVSR | ADC_CFGR2_OVSE | ADC_CFGR2_CKMODE ) ); /* Reset register SMPR */ CLEAR_BIT(ADCx->SMPR, ADC_SMPR_SMP); /* Reset register TR */ MODIFY_REG(ADCx->TR, ADC_TR_HT | ADC_TR_LT, ADC_TR_HT); /* Reset register CHSELR */ #if defined(ADC_CCR_VLCDEN) CLEAR_BIT(ADCx->CHSELR, ( ADC_CHSELR_CHSEL18 | ADC_CHSELR_CHSEL17 | ADC_CHSELR_CHSEL16 | ADC_CHSELR_CHSEL15 | ADC_CHSELR_CHSEL14 | ADC_CHSELR_CHSEL13 | ADC_CHSELR_CHSEL12 | ADC_CHSELR_CHSEL11 | ADC_CHSELR_CHSEL10 | ADC_CHSELR_CHSEL9 | ADC_CHSELR_CHSEL8 | ADC_CHSELR_CHSEL7 | ADC_CHSELR_CHSEL6 | ADC_CHSELR_CHSEL5 | ADC_CHSELR_CHSEL4 | ADC_CHSELR_CHSEL3 | ADC_CHSELR_CHSEL2 | ADC_CHSELR_CHSEL1 | ADC_CHSELR_CHSEL0 ) ); #else CLEAR_BIT(ADCx->CHSELR, ( ADC_CHSELR_CHSEL18 | ADC_CHSELR_CHSEL17 | ADC_CHSELR_CHSEL15 | ADC_CHSELR_CHSEL14 | ADC_CHSELR_CHSEL13 | ADC_CHSELR_CHSEL12 | ADC_CHSELR_CHSEL11 | ADC_CHSELR_CHSEL10 | ADC_CHSELR_CHSEL9 | ADC_CHSELR_CHSEL8 | ADC_CHSELR_CHSEL7 | ADC_CHSELR_CHSEL6 | ADC_CHSELR_CHSEL5 | ADC_CHSELR_CHSEL4 | ADC_CHSELR_CHSEL3 | ADC_CHSELR_CHSEL2 | ADC_CHSELR_CHSEL1 | ADC_CHSELR_CHSEL0 ) ); #endif /* Reset register DR */ /* bits in access mode read only, no direct reset applicable */ /* Reset register CALFACT */ CLEAR_BIT(ADCx->CALFACT, ADC_CALFACT_CALFACT); } else { /* ADC instance is in an unknown state */ /* Need to performing a hard reset of ADC instance, using high level */ /* clock source RCC ADC reset. */ /* Caution: On this STM32 serie, if several ADC instances are available */ /* on the selected device, RCC ADC reset will reset */ /* all ADC instances belonging to the common ADC instance. */ status = ERROR; } return status; } /** * @brief Initialize some features of ADC instance. * @note These parameters have an impact on ADC scope: ADC instance. * Refer to corresponding unitary functions into * @ref ADC_LL_EF_Configuration_ADC_Instance . * @note The setting of these parameters by function @ref LL_ADC_Init() * is conditioned to ADC state: * ADC instance must be disabled. * This condition is applied to all ADC features, for efficiency * and compatibility over all STM32 families. However, the different * features can be set under different ADC state conditions * (setting possible with ADC enabled without conversion on going, * ADC enabled with conversion on going, ...) * Each feature can be updated afterwards with a unitary function * and potentially with ADC in a different state than disabled, * refer to description of each function for setting * conditioned to ADC state. * @note After using this function, some other features must be configured * using LL unitary functions. * The minimum configuration remaining to be done is: * - Set ADC group regular sequencer: * map channel on rank corresponding to channel number. * Refer to function @ref LL_ADC_REG_SetSequencerChannels(); * - Set ADC channel sampling time * Refer to function LL_ADC_SetChannelSamplingTime(); * @param ADCx ADC instance * @param ADC_InitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure * @retval An ErrorStatus enumeration value: * - SUCCESS: ADC registers are initialized * - ERROR: ADC registers are not initialized */ ErrorStatus LL_ADC_Init(ADC_TypeDef *ADCx, LL_ADC_InitTypeDef *ADC_InitStruct) { ErrorStatus status = SUCCESS; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(ADCx)); assert_param(IS_LL_ADC_CLOCK(ADC_InitStruct->Clock)); assert_param(IS_LL_ADC_RESOLUTION(ADC_InitStruct->Resolution)); assert_param(IS_LL_ADC_DATA_ALIGN(ADC_InitStruct->DataAlignment)); assert_param(IS_LL_ADC_LOW_POWER(ADC_InitStruct->LowPowerMode)); /* Note: Hardware constraint (refer to description of this function): */ /* ADC instance must be disabled. */ if(LL_ADC_IsEnabled(ADCx) == 0U) { /* Configuration of ADC hierarchical scope: */ /* - ADC instance */ /* - Set ADC data resolution */ /* - Set ADC conversion data alignment */ /* - Set ADC low power mode */ MODIFY_REG(ADCx->CFGR1, ADC_CFGR1_RES | ADC_CFGR1_ALIGN | ADC_CFGR1_WAIT | ADC_CFGR1_AUTOFF , ADC_InitStruct->Resolution | ADC_InitStruct->DataAlignment | ADC_InitStruct->LowPowerMode ); MODIFY_REG(ADCx->CFGR2, ADC_CFGR2_CKMODE , ADC_InitStruct->Clock ); } else { /* Initialization error: ADC instance is not disabled. */ status = ERROR; } return status; } /** * @brief Set each @ref LL_ADC_InitTypeDef field to default value. * @param ADC_InitStruct Pointer to a @ref LL_ADC_InitTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_ADC_StructInit(LL_ADC_InitTypeDef *ADC_InitStruct) { /* Set ADC_InitStruct fields to default values */ /* Set fields of ADC instance */ ADC_InitStruct->Clock = LL_ADC_CLOCK_SYNC_PCLK_DIV2; ADC_InitStruct->Resolution = LL_ADC_RESOLUTION_12B; ADC_InitStruct->DataAlignment = LL_ADC_DATA_ALIGN_RIGHT; ADC_InitStruct->LowPowerMode = LL_ADC_LP_MODE_NONE; } /** * @brief Initialize some features of ADC group regular. * @note These parameters have an impact on ADC scope: ADC group regular. * Refer to corresponding unitary functions into * @ref ADC_LL_EF_Configuration_ADC_Group_Regular * (functions with prefix "REG"). * @note The setting of these parameters by function @ref LL_ADC_Init() * is conditioned to ADC state: * ADC instance must be disabled. * This condition is applied to all ADC features, for efficiency * and compatibility over all STM32 families. However, the different * features can be set under different ADC state conditions * (setting possible with ADC enabled without conversion on going, * ADC enabled with conversion on going, ...) * Each feature can be updated afterwards with a unitary function * and potentially with ADC in a different state than disabled, * refer to description of each function for setting * conditioned to ADC state. * @note After using this function, other features must be configured * using LL unitary functions. * The minimum configuration remaining to be done is: * - Set ADC group regular sequencer: * map channel on rank corresponding to channel number. * Refer to function @ref LL_ADC_REG_SetSequencerChannels(); * - Set ADC channel sampling time * Refer to function LL_ADC_SetChannelSamplingTime(); * @param ADCx ADC instance * @param ADC_REG_InitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure * @retval An ErrorStatus enumeration value: * - SUCCESS: ADC registers are initialized * - ERROR: ADC registers are not initialized */ ErrorStatus LL_ADC_REG_Init(ADC_TypeDef *ADCx, LL_ADC_REG_InitTypeDef *ADC_REG_InitStruct) { ErrorStatus status = SUCCESS; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(ADCx)); assert_param(IS_LL_ADC_REG_TRIG_SOURCE(ADC_REG_InitStruct->TriggerSource)); assert_param(IS_LL_ADC_REG_SEQ_SCAN_DISCONT_MODE(ADC_REG_InitStruct->SequencerDiscont)); assert_param(IS_LL_ADC_REG_CONTINUOUS_MODE(ADC_REG_InitStruct->ContinuousMode)); assert_param(IS_LL_ADC_REG_DMA_TRANSFER(ADC_REG_InitStruct->DMATransfer)); assert_param(IS_LL_ADC_REG_OVR_DATA_BEHAVIOR(ADC_REG_InitStruct->Overrun)); /* Note: Hardware constraint (refer to description of this function): */ /* ADC instance must be disabled. */ if(LL_ADC_IsEnabled(ADCx) == 0U) { /* Configuration of ADC hierarchical scope: */ /* - ADC group regular */ /* - Set ADC group regular trigger source */ /* - Set ADC group regular sequencer discontinuous mode */ /* - Set ADC group regular continuous mode */ /* - Set ADC group regular conversion data transfer: no transfer or */ /* transfer by DMA, and DMA requests mode */ /* - Set ADC group regular overrun behavior */ /* Note: On this STM32 serie, ADC trigger edge is set to value 0x0 by */ /* setting of trigger source to SW start. */ MODIFY_REG(ADCx->CFGR1, ADC_CFGR1_EXTSEL | ADC_CFGR1_EXTEN | ADC_CFGR1_DISCEN | ADC_CFGR1_CONT | ADC_CFGR1_DMAEN | ADC_CFGR1_DMACFG | ADC_CFGR1_OVRMOD , ADC_REG_InitStruct->TriggerSource | ADC_REG_InitStruct->SequencerDiscont | ADC_REG_InitStruct->ContinuousMode | ADC_REG_InitStruct->DMATransfer | ADC_REG_InitStruct->Overrun ); } else { /* Initialization error: ADC instance is not disabled. */ status = ERROR; } return status; } /** * @brief Set each @ref LL_ADC_REG_InitTypeDef field to default value. * @param ADC_REG_InitStruct Pointer to a @ref LL_ADC_REG_InitTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_ADC_REG_StructInit(LL_ADC_REG_InitTypeDef *ADC_REG_InitStruct) { /* Set ADC_REG_InitStruct fields to default values */ /* Set fields of ADC group regular */ /* Note: On this STM32 serie, ADC trigger edge is set to value 0x0 by */ /* setting of trigger source to SW start. */ ADC_REG_InitStruct->TriggerSource = LL_ADC_REG_TRIG_SOFTWARE; ADC_REG_InitStruct->SequencerDiscont = LL_ADC_REG_SEQ_DISCONT_DISABLE; ADC_REG_InitStruct->ContinuousMode = LL_ADC_REG_CONV_SINGLE; ADC_REG_InitStruct->DMATransfer = LL_ADC_REG_DMA_TRANSFER_NONE; ADC_REG_InitStruct->Overrun = LL_ADC_REG_OVR_DATA_OVERWRITTEN; } /** * @} */ /** * @} */ /** * @} */ #endif /* ADC1 */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/93887076.c
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> static void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; } static void dfs(int *nums, int size, int start, int **results, int *count) { int i; if (start == size) { results[*count] = malloc(size * sizeof(int)); memcpy(results[*count], nums, size * sizeof(int)); (*count)++; } else { for (i = start; i < size; i++) { swap(nums + start, nums + i); dfs(nums, size, start + 1, results, count); swap(nums + start, nums + i); } } } /** ** Return an array of arrays of size *returnSize. ** Note: The returned array must be malloced, assume caller calls free(). **/ static int **permute(int* nums, int numsSize, int* returnSize) { int count = 0, cap = 5000; int **results = malloc(cap * sizeof(int *)); *returnSize = 0; dfs(nums, numsSize, 0, results, returnSize); return results; } int main(int argc, char **argv) { if (argc <= 1) { fprintf(stderr, "Usage: ./test ...\n"); exit(-1); } int i, j, count = argc - 1; int *nums = malloc(count * sizeof(int)); for (i = 0; i < count; i++) { nums[i] = atoi(argv[i + 1]); } int **lists = permute(nums, argc - 1, &count); for (i = 0; i < count; i++) { for (j = 0; j < argc - 1; j++) { printf("%d", lists[i][j]); } putchar('\n'); } return 0; }
the_stack_data/115766290.c
/* * Compute forces and accumulate the virial and the potential */ extern double epot, vir; void forces(int npart, double x[], double f[], double side, double rcoff){ int i; vir = 0.0; epot = 0.0; #pragma omp parallel for default(none) shared(f,x,npart,side,rcoff) reduction(+:epot,vir) schedule(static,32) for (i=0; i<npart*3; i+=3) { // zero force components on particle i double fxi = 0.0; double fyi = 0.0; double fzi = 0.0; int j; // loop over all particles with index > i for (j=i+3; j<npart*3; j+=3) { // compute distance between particles i and j allowing for wraparound double xx = x[i]-x[j]; double yy = x[i+1]-x[j+1]; double zz = x[i+2]-x[j+2]; if (xx< (-0.5*side) ) xx += side; if (xx> (0.5*side) ) xx -= side; if (yy< (-0.5*side) ) yy += side; if (yy> (0.5*side) ) yy -= side; if (zz< (-0.5*side) ) zz += side; if (zz> (0.5*side) ) zz -= side; double rd = xx*xx+yy*yy+zz*zz; // if distance is inside cutoff radius compute forces // and contributions to pot. energy and virial if (rd<=rcoff*rcoff) { double rrd = 1.0/rd; double rrd3 = rrd*rrd*rrd; double rrd4 = rrd3*rrd; double r148 = rrd4*(rrd3 - 0.5); epot += rrd3*(rrd3-1.0); vir -= rd*r148; fxi += xx*r148; fyi += yy*r148; fzi += zz*r148; #pragma omp atomic f[j] -= xx*r148; #pragma omp atomic f[j+1] -= yy*r148; #pragma omp atomic f[j+2] -= zz*r148; } } // update forces on particle i #pragma omp atomic f[i] += fxi; #pragma omp atomic f[i+1] += fyi; #pragma omp atomic f[i+2] += fzi; } }
the_stack_data/547929.c
// Scrivere un programma che legga da tastiera una sequenza di // n interi ordinati e li inserisca in una lista bidirezionale. // Il programma entra poi in un ciclo nel quale legge un intero // i da tastiera e lo cerca nella lista. Se i si trova nella lista, // stampa la sua posizione (contando da 0), altrimenti stampa -1. // Ogni elemento della lista mantiene anche un contatore che ricorda // quante volte `e stata cercata la corrispondente chiave. // Tutti i contatori sono inizialmente settati a 0. Dopo ogni // ricerca si deve garantire che gli elementi della lista siano // ordinati in ordine non-crescente di contatore. #include <stdio.h> #include <stdlib.h> //List structure: struct elemento { int info; int cont; struct elemento *next; struct elemento *prec; }; typedef struct elemento ElementoDiLista; typedef ElementoDiLista *ListaDiElementi; ListaDiElementi readList(); //Function to print all the elements of the list: void printList(ListaDiElementi lis) { printf("("); while(lis!=NULL){ printf("%d ", lis->info); lis=lis->next; } printf(")\n"); } void sposta(ListaDiElementi *lis,int x){ ListaDiElementi cor=*lis,pre=cor->prec,aux; while(cor->info!=x){ // faccio puntare cor all'elemento che pre=cor; // sto cercando e pre a quello precedente cor=cor->next; } cor->cont=cor->cont+1; //aggiorno il contatore if(pre!=NULL){ while(pre!=NULL && cor->cont>pre->cont){ cor->prec=pre->prec; if(pre->prec!=NULL){ aux=pre->prec; aux->next=cor; } pre->next=cor->next; if(cor->next!=NULL){ aux=cor->next; aux->prec=pre; } pre->prec=cor; cor->next=pre; pre=cor->prec; } if(cor->prec==NULL) // se prima di cor non c'è un elemento *lis=cor; // aggiorno la testa perchè è cambiata } } int prese(ListaDiElementi lis,int x){ // controllo che x è presente nella lista int ok=0,count=0; // e restituisco il suo indice ListaDiElementi aux=lis; while(aux!=NULL&&!ok){ if(aux->info==x) ok=1; else{ aux=aux->next; count++; } } if(!ok) count=-1; return count; } int main() { ListaDiElementi l; l= readList(); int x=l->info,m=0; while(m!=-1){ scanf("%d",&x); m=prese(l,x); if(m!=-1) sposta(&l,x); printf("%d\n",m); } return 0; } //Function to acquire a list of integers: ListaDiElementi readList() { ListaDiElementi head = NULL; ListaDiElementi previous = NULL; ListaDiElementi item; int n,x; scanf("%d", &n); while(n>0) { n--; scanf("%d", &x); item = (ListaDiElementi) malloc(sizeof(ElementoDiLista)); item->info = x; item->cont = 0; item->next = NULL; item->prec = NULL; if(previous == NULL) { //Item is the first element: head = item; previous=head; } else { //Item is not the first element: previous->next = item; item->prec=previous; previous = item; } } return head; }
the_stack_data/234516894.c
float foo(float X) { #pragma spf transform propagate float Y; float Z; Y = X; Z = X; return Y + Z; } //CHECK:
the_stack_data/47738.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <pthread.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> //----------------------------------------------------------------------------*/ /* 전처리기 선언 //----------------------------------------------------------------------------*/ #ifndef true #define true (1) #endif #ifndef false #define false (0) #endif #define SEVERITY_SUCCESS (0) #define SEVERITY_ERROR (1) #define THREAD_COUNT_MAX (2) #define PORT_NUMBER (3600) #define PACKET_LENGTH_MAX (1024) //----------------------------------------------------------------------------*/ /* 전역 변수 / 함수 선언 //----------------------------------------------------------------------------*/ void* ThreadFunction(void* Data); //----------------------------------------------------------------------------*/ /* 엔트리 포인트 //----------------------------------------------------------------------------*/ int main(int argc, char** argv) { // 소켓 생성 int ListenFD = socket(AF_INET, SOCK_STREAM, 0); if(ListenFD < 0) { printf("Socket create error!\n"); return SEVERITY_ERROR; } printf("Socket create success.\n"); // 소켓 바인딩 struct sockaddr_in ServerAddress; memset(&ServerAddress, 0x00, sizeof(ServerAddress)); ServerAddress.sin_family = AF_INET; ServerAddress.sin_addr.s_addr = inet_addr("127.0.0.1"); ServerAddress.sin_port = htons(PORT_NUMBER); int BindResult = bind(ListenFD, (struct sockaddr*)&ServerAddress, sizeof(ServerAddress)); if(BindResult == -1) { printf("Socket bind error!\n"); return SEVERITY_ERROR; } printf("Socket bind success.\n"); // 소켓 수신 준비 int ListenResut = listen(ListenFD, 5); if(ListenResut == -1) { printf("Socket listen error!\n"); return SEVERITY_ERROR; } printf("Socket listen success.\n"); // 클라이언트 소켓 int ClientFD = 0; struct sockaddr_in ClientAddress; socklen_t ClientAddressLength = 0; char Buffer[PACKET_LENGTH_MAX] = { 0 }; pthread_t ThreadID = 0; while(true) { ClientAddressLength = sizeof(ClientAddress); ClientFD = accept(ListenFD, (struct sockaddr*)&ClientAddress, &ClientAddressLength); if(ClientFD == -1) { printf("Accept error!\n"); } else { int ThreadResult = pthread_create(&ThreadID, NULL, &ThreadFunction, (void*)&ClientFD); pthread_detach(ThreadID); } } return SEVERITY_SUCCESS; } //----------------------------------------------------------------------------*/ void* ThreadFunction(void* Data) { int SocketFD = *((int*)Data); struct sockaddr_in ClientAddress; memset(&ClientAddress, 0x00, sizeof(ClientAddress)); socklen_t ClientAddressLength = sizeof(ClientAddress); int GetPeerResult = getpeername(SocketFD, (struct sockaddr*)&ClientAddress, &ClientAddressLength); if(GetPeerResult != 0) { printf("Get peer name is failed! : %d\n", GetPeerResult); } printf("Accept success! Client socket FD : %d\n", SocketFD); char Buffer[PACKET_LENGTH_MAX] = { 0 }; int ReadCount = 0; int ReadResult = read(SocketFD, Buffer, sizeof(char) * PACKET_LENGTH_MAX); while(ReadResult > 0) { printf("Read data %s(%d) : %s\n", inet_ntoa(ClientAddress.sin_addr), ntohs(ClientAddress.sin_port), Buffer); write(SocketFD, Buffer, strlen(Buffer)); memset(Buffer, 0x00, sizeof(Buffer)); } close(SocketFD); printf("Worker thread end\n"); return NULL; }
the_stack_data/1117596.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern void signal(int sig , void *func ) ; extern float strtof(char const *str , char const *endptr ) ; 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 char input[1] , unsigned char 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 , ...) ; int main(int argc , char *argv[] ) { unsigned char input[1] ; unsigned char output[1] ; int randomFuns_i5 ; unsigned char 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 char )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 3) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } } void RandomFunc(unsigned char input[1] , unsigned char output[1] ) { unsigned char state[1] ; unsigned char local1 ; { state[0UL] = input[0UL] + (unsigned char)69; local1 = 0UL; while (local1 < input[1UL]) { if (state[0UL] > local1) { if (state[0UL] > local1) { state[local1] -= state[0UL]; } else { state[local1] = state[0UL] + state[0UL]; } } else if (state[0UL] == local1) { state[local1] += state[0UL]; } else { state[local1] *= state[local1]; } local1 += 2UL; } output[0UL] = state[0UL] + (unsigned char)133; } } void megaInit(void) { { } }
the_stack_data/125598.c
#include <stdio.h> #include <string.h> long hash(char *word); int main() { char word[200]; int i, p = 0, hashv = 42; scanf ("%s", word); i = strlen(word); for (; p<i; p++) { hashv= hashv + hash(&word[p]); } printf ("%d", hashv); return 0; } long hash (char *word) { int result; static int counter = 0; counter ++; result = *word * counter; return result; }
the_stack_data/90762086.c
/** ** Digit Change Program ** Ahasanul Basher Hamza ** Date: 23/02/18 ***/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <strings.h> #include <math.h> #include <ctype.h> int main() { int i,j,n; scanf("%d",&n); for(i = 0;i < n;i++) { char *s = malloc(sizeof(char) * 100); scanf("%s",s); for(j = 0;j < strlen(s);j++) { if(s[j] % 2 == 0) { s[j]++; } else { s[j]--; } } int key = atoi(s); printf("%d\n",key); } return 0; }
the_stack_data/232955276.c
//Problem-4 What is the smallest number that is evenly divisble by all nos from 1 to 20 #include<stdio.h> int main(){ long int num,i=1,j,chk; while(1){ num =20*(i); for (j=2;j<=20;j++){ if((num%j)==0) chk=1; else{ chk=0; break;} } if(chk){ break;} i++; } printf("\nThe Number Evenly divisible by numbers from 1 to 20 is %ld",num); return 0; }
the_stack_data/162643598.c
/* PR c/21536 */ /* { dg-do run } */ /* { dg-options "-O2 -Wuninitialized" } */ typedef __SIZE_TYPE__ size_t; extern void *malloc (size_t); extern void free (void *); void * foo (int x, int y) { void *d = malloc (x * y * sizeof (double)); double (*e)[x][y] = d; x += 10; y += 10; if (x > 18) (*e)[x - 12][y - 12] = 0.0; else (*e)[x - 11][y - 11] = 1.0; return d; } void * bar (int x, int y) { void *d = malloc (x * y * sizeof (double)); struct S { double (*e)[x][y]; double (*f)[x][y]; } s; s.e = d; s.f = d; x += 10; y += 10; if (x > 18) (*s.e)[x - 12][y - 12] = 0.0; else (*s.e)[x - 11][y - 11] = 1.0; if (x > 16) (*s.f)[x - 13][y - 13] = 0.0; else (*s.f)[x - 14][y - 14] = 1.0; return d; } int main () { void *d1 = foo (10, 10); void *d2 = bar (10, 10); free (d1); free (d2); return 0; }
the_stack_data/122016869.c
// KASAN: stack-out-of-bounds Read in string // https://syzkaller.appspot.com/bug?id=c9618f06df4c2cff0ce71dd96887aa419f053e50 // status:fixed // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <endian.h> #include <errno.h> #include <fcntl.h> #include <setjmp.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mount.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> #include <linux/usb/ch9.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 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); } #define USB_MAX_EP_NUM 32 struct usb_device_index { struct usb_device_descriptor* dev; struct usb_config_descriptor* config; unsigned config_length; struct usb_interface_descriptor* iface; struct usb_endpoint_descriptor* eps[USB_MAX_EP_NUM]; unsigned eps_num; }; static bool parse_usb_descriptor(char* buffer, size_t length, struct usb_device_index* index) { if (length < sizeof(*index->dev) + sizeof(*index->config) + sizeof(*index->iface)) return false; index->dev = (struct usb_device_descriptor*)buffer; index->config = (struct usb_config_descriptor*)(buffer + sizeof(*index->dev)); index->config_length = length - sizeof(*index->dev); index->iface = (struct usb_interface_descriptor*)(buffer + sizeof(*index->dev) + sizeof(*index->config)); index->eps_num = 0; size_t offset = 0; while (true) { if (offset == length) break; if (offset + 1 < length) break; uint8_t length = buffer[offset]; uint8_t type = buffer[offset + 1]; if (type == USB_DT_ENDPOINT) { index->eps[index->eps_num] = (struct usb_endpoint_descriptor*)(buffer + offset); index->eps_num++; } if (index->eps_num == USB_MAX_EP_NUM) break; offset += length; } return true; } enum usb_fuzzer_event_type { USB_FUZZER_EVENT_INVALID, USB_FUZZER_EVENT_CONNECT, USB_FUZZER_EVENT_DISCONNECT, USB_FUZZER_EVENT_SUSPEND, USB_FUZZER_EVENT_RESUME, USB_FUZZER_EVENT_CONTROL, }; struct usb_fuzzer_event { uint32_t type; uint32_t length; char data[0]; }; struct usb_fuzzer_init { uint64_t speed; const char* driver_name; const char* device_name; }; struct usb_fuzzer_ep_io { uint16_t ep; uint16_t flags; uint32_t length; char data[0]; }; #define USB_FUZZER_IOCTL_INIT _IOW('U', 0, struct usb_fuzzer_init) #define USB_FUZZER_IOCTL_RUN _IO('U', 1) #define USB_FUZZER_IOCTL_EP0_READ _IOWR('U', 2, struct usb_fuzzer_event) #define USB_FUZZER_IOCTL_EP0_WRITE _IOW('U', 3, struct usb_fuzzer_ep_io) #define USB_FUZZER_IOCTL_EP_ENABLE _IOW('U', 4, struct usb_endpoint_descriptor) #define USB_FUZZER_IOCTL_EP_WRITE _IOW('U', 6, struct usb_fuzzer_ep_io) #define USB_FUZZER_IOCTL_CONFIGURE _IO('U', 8) #define USB_FUZZER_IOCTL_VBUS_DRAW _IOW('U', 9, uint32_t) int usb_fuzzer_open() { return open("/sys/kernel/debug/usb-fuzzer", O_RDWR); } int usb_fuzzer_init(int fd, uint32_t speed, const char* driver, const char* device) { struct usb_fuzzer_init arg; arg.speed = speed; arg.driver_name = driver; arg.device_name = device; return ioctl(fd, USB_FUZZER_IOCTL_INIT, &arg); } int usb_fuzzer_run(int fd) { return ioctl(fd, USB_FUZZER_IOCTL_RUN, 0); } int usb_fuzzer_ep0_read(int fd, struct usb_fuzzer_event* event) { return ioctl(fd, USB_FUZZER_IOCTL_EP0_READ, event); } int usb_fuzzer_ep0_write(int fd, struct usb_fuzzer_ep_io* io) { return ioctl(fd, USB_FUZZER_IOCTL_EP0_WRITE, io); } int usb_fuzzer_ep_write(int fd, struct usb_fuzzer_ep_io* io) { return ioctl(fd, USB_FUZZER_IOCTL_EP_WRITE, io); } int usb_fuzzer_ep_enable(int fd, struct usb_endpoint_descriptor* desc) { return ioctl(fd, USB_FUZZER_IOCTL_EP_ENABLE, desc); } int usb_fuzzer_configure(int fd) { return ioctl(fd, USB_FUZZER_IOCTL_CONFIGURE, 0); } int usb_fuzzer_vbus_draw(int fd, uint32_t power) { return ioctl(fd, USB_FUZZER_IOCTL_VBUS_DRAW, power); } #define USB_MAX_PACKET_SIZE 1024 struct usb_fuzzer_control_event { struct usb_fuzzer_event inner; struct usb_ctrlrequest ctrl; }; struct usb_fuzzer_ep_io_data { struct usb_fuzzer_ep_io inner; char data[USB_MAX_PACKET_SIZE]; }; struct vusb_connect_string_descriptor { uint32_t len; char* str; } __attribute__((packed)); struct vusb_connect_descriptors { uint32_t qual_len; char* qual; uint32_t bos_len; char* bos; uint32_t strs_len; struct vusb_connect_string_descriptor strs[0]; } __attribute__((packed)); static volatile long syz_usb_connect(volatile long a0, volatile long a1, volatile long a2, volatile long a3) { int64_t speed = a0; int64_t dev_len = a1; char* dev = (char*)a2; struct vusb_connect_descriptors* conn_descs = (struct vusb_connect_descriptors*)a3; if (!dev) return -1; struct usb_device_index index; memset(&index, 0, sizeof(index)); int rv = parse_usb_descriptor(dev, dev_len, &index); if (!rv) return -1; int fd = usb_fuzzer_open(); if (fd < 0) return -1; char device[32]; sprintf(&device[0], "dummy_udc.%llu", procid); rv = usb_fuzzer_init(fd, speed, "dummy_udc", &device[0]); if (rv < 0) return -1; rv = usb_fuzzer_run(fd); if (rv < 0) return -1; bool done = false; while (!done) { char* response_data = NULL; uint32_t response_length = 0; unsigned ep; uint8_t str_idx; struct usb_fuzzer_control_event event; event.inner.type = 0; event.inner.length = sizeof(event.ctrl); rv = usb_fuzzer_ep0_read(fd, (struct usb_fuzzer_event*)&event); if (rv < 0) return -1; if (event.inner.type != USB_FUZZER_EVENT_CONTROL) continue; switch (event.ctrl.bRequestType & USB_TYPE_MASK) { case USB_TYPE_STANDARD: switch (event.ctrl.bRequest) { case USB_REQ_GET_DESCRIPTOR: switch (event.ctrl.wValue >> 8) { case USB_DT_DEVICE: response_data = (char*)index.dev; response_length = sizeof(*index.dev); goto reply; case USB_DT_CONFIG: response_data = (char*)index.config; response_length = index.config_length; goto reply; case USB_DT_STRING: str_idx = (uint8_t)event.ctrl.wValue; if (str_idx >= conn_descs->strs_len) goto reply; response_data = conn_descs->strs[str_idx].str; response_length = conn_descs->strs[str_idx].len; goto reply; case USB_DT_BOS: response_data = conn_descs->bos; response_length = conn_descs->bos_len; goto reply; case USB_DT_DEVICE_QUALIFIER: response_data = conn_descs->qual; response_length = conn_descs->qual_len; goto reply; default: exit(1); continue; } break; case USB_REQ_SET_CONFIGURATION: rv = usb_fuzzer_vbus_draw(fd, index.config->bMaxPower); if (rv < 0) return -1; rv = usb_fuzzer_configure(fd); if (rv < 0) return -1; for (ep = 0; ep < index.eps_num; ep++) { rv = usb_fuzzer_ep_enable(fd, index.eps[ep]); if (rv < 0) exit(1); } done = true; goto reply; default: exit(1); continue; } break; default: exit(1); continue; } struct usb_fuzzer_ep_io_data response; reply: response.inner.ep = 0; response.inner.flags = 0; if (response_length > sizeof(response.data)) response_length = 0; response.inner.length = response_length; if (response_data) memcpy(&response.data[0], response_data, response_length); if (event.ctrl.wLength < response.inner.length) response.inner.length = event.ctrl.wLength; usb_fuzzer_ep0_write(fd, (struct usb_fuzzer_ep_io*)&response); } sleep_ms(200); return fd; } int main(void) { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); install_segv_handler(); use_temporary_dir(); NONFAILING(*(uint8_t*)0x20000040 = 0x12); NONFAILING(*(uint8_t*)0x20000041 = 1); NONFAILING(*(uint16_t*)0x20000042 = 0); NONFAILING(*(uint8_t*)0x20000044 = 0xea); NONFAILING(*(uint8_t*)0x20000045 = 0x89); NONFAILING(*(uint8_t*)0x20000046 = 0x7a); NONFAILING(*(uint8_t*)0x20000047 = 0x40); NONFAILING(*(uint16_t*)0x20000048 = 0x424); NONFAILING(*(uint16_t*)0x2000004a = 0x12c); NONFAILING(*(uint16_t*)0x2000004c = 0x1a78); NONFAILING(*(uint8_t*)0x2000004e = 0); NONFAILING(*(uint8_t*)0x2000004f = 0); NONFAILING(*(uint8_t*)0x20000050 = 0); NONFAILING(*(uint8_t*)0x20000051 = 1); NONFAILING(*(uint8_t*)0x20000052 = 9); NONFAILING(*(uint8_t*)0x20000053 = 2); NONFAILING(*(uint16_t*)0x20000054 = 0x1b); NONFAILING(*(uint8_t*)0x20000056 = 1); NONFAILING(*(uint8_t*)0x20000057 = 0); NONFAILING(*(uint8_t*)0x20000058 = 0); NONFAILING(*(uint8_t*)0x20000059 = 0); NONFAILING(*(uint8_t*)0x2000005a = 0); NONFAILING(*(uint8_t*)0x2000005b = 9); NONFAILING(*(uint8_t*)0x2000005c = 4); NONFAILING(*(uint8_t*)0x2000005d = 0x9e); NONFAILING(*(uint8_t*)0x2000005e = 0); NONFAILING(*(uint8_t*)0x2000005f = 1); NONFAILING(*(uint8_t*)0x20000060 = 0xb4); NONFAILING(*(uint8_t*)0x20000061 = 0x11); NONFAILING(*(uint8_t*)0x20000062 = 0xd1); NONFAILING(*(uint8_t*)0x20000063 = 0); NONFAILING(*(uint8_t*)0x20000064 = 7); NONFAILING(*(uint8_t*)0x20000065 = 5); NONFAILING(*(uint8_t*)0x20000066 = 0x8c); NONFAILING(*(uint8_t*)0x20000067 = 0); NONFAILING(*(uint16_t*)0x20000068 = 0); NONFAILING(*(uint8_t*)0x2000006a = 0); NONFAILING(*(uint8_t*)0x2000006b = 0); NONFAILING(*(uint8_t*)0x2000006c = 0); syz_usb_connect(4, 0x2d, 0x20000040, 0); return 0; }
the_stack_data/103156.c
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_10__ TYPE_4__ ; typedef struct TYPE_9__ TYPE_3__ ; typedef struct TYPE_8__ TYPE_2__ ; typedef struct TYPE_7__ TYPE_1__ ; /* Type definitions */ typedef int /*<<< orphan*/ uint64_t ; typedef int /*<<< orphan*/ uint32_t ; typedef int /*<<< orphan*/ uint16_t ; struct retro_keybind {int /*<<< orphan*/ joyaxis; int /*<<< orphan*/ joykey; } ; struct TYPE_8__ {float axis_threshold; int /*<<< orphan*/ joy_idx; TYPE_1__* auto_binds; } ; typedef TYPE_2__ rarch_joypad_info_t ; typedef int int16_t ; struct TYPE_9__ {TYPE_4__* joypad; } ; typedef TYPE_3__ ctr_input_t ; struct TYPE_10__ {int /*<<< orphan*/ (* axis ) (int /*<<< orphan*/ ,int /*<<< orphan*/ const) ;int /*<<< orphan*/ (* button ) (int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;} ; struct TYPE_7__ {int /*<<< orphan*/ joyaxis; int /*<<< orphan*/ joykey; } ; /* Variables and functions */ int /*<<< orphan*/ AXIS_NONE ; int /*<<< orphan*/ NO_BTN ; unsigned int RARCH_FIRST_CUSTOM_BIND ; #define RETRO_DEVICE_ANALOG 129 unsigned int RETRO_DEVICE_ID_JOYPAD_MASK ; #define RETRO_DEVICE_JOYPAD 128 scalar_t__ abs (int /*<<< orphan*/ ) ; int input_joypad_analog (TYPE_4__*,TYPE_2__,unsigned int,unsigned int,unsigned int,struct retro_keybind const*) ; int /*<<< orphan*/ stub1 (int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; int /*<<< orphan*/ stub2 (int /*<<< orphan*/ ,int /*<<< orphan*/ const) ; int /*<<< orphan*/ stub3 (int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; int /*<<< orphan*/ stub4 (int /*<<< orphan*/ ,int /*<<< orphan*/ const) ; __attribute__((used)) static int16_t ctr_input_state(void *data, rarch_joypad_info_t joypad_info, const struct retro_keybind **binds, unsigned port, unsigned device, unsigned idx, unsigned id) { ctr_input_t *ctr = (ctr_input_t*)data; if (port > 0) return 0; switch (device) { case RETRO_DEVICE_JOYPAD: if (id == RETRO_DEVICE_ID_JOYPAD_MASK) { unsigned i; int16_t ret = 0; for (i = 0; i < RARCH_FIRST_CUSTOM_BIND; i++) { /* Auto-binds are per joypad, not per user. */ const uint64_t joykey = (binds[port][i].joykey != NO_BTN) ? binds[port][i].joykey : joypad_info.auto_binds[i].joykey; const uint32_t joyaxis = (binds[port][i].joyaxis != AXIS_NONE) ? binds[port][i].joyaxis : joypad_info.auto_binds[i].joyaxis; if ((uint16_t)joykey != NO_BTN && ctr->joypad->button(joypad_info.joy_idx, (uint16_t)joykey)) { ret |= (1 << i); continue; } if (((float)abs(ctr->joypad->axis(joypad_info.joy_idx, joyaxis)) / 0x8000) > joypad_info.axis_threshold) { ret |= (1 << i); continue; } } return ret; } else { /* Auto-binds are per joypad, not per user. */ const uint64_t joykey = (binds[port][id].joykey != NO_BTN) ? binds[port][id].joykey : joypad_info.auto_binds[id].joykey; const uint32_t joyaxis = (binds[port][id].joyaxis != AXIS_NONE) ? binds[port][id].joyaxis : joypad_info.auto_binds[id].joyaxis; if ((uint16_t)joykey != NO_BTN && ctr->joypad->button(joypad_info.joy_idx, (uint16_t)joykey)) return true; if (((float)abs(ctr->joypad->axis(joypad_info.joy_idx, joyaxis)) / 0x8000) > joypad_info.axis_threshold) return true; } break; case RETRO_DEVICE_ANALOG: if (binds[port]) return input_joypad_analog(ctr->joypad, joypad_info, port, idx, id, binds[port]); break; } return 0; }
the_stack_data/162642610.c
#include <stdio.h> int main() { puts("Hello, World!"); return 0; }
the_stack_data/107953812.c
/* P R O F W I N . C */ #ifdef HYBRID #define REALWINCALLS #include "word.h" #include "debug.h" #include "lmem.h" #include "sdmdefs.h" #include "sdmver.h" #include "sdm.h" /* %%Function:FillWindowPR %%Owner:BRADV */ NATIVE void FillWindowPR(P1,P2,P3,P4) /* WINIGNORE - PROFILE only */ HWND P1; HWND P2; HDC P3; HBRUSH P4; { FillWindow(P1,P2,P3,P4); } /* %%Function:BeginPaintPR %%Owner:BRADV */ NATIVE HDC BeginPaintPR(P1,P2) /* WINIGNORE - PROFILE only */ HWND P1; LPPAINTSTRUCT P2; { return BeginPaint(P1,P2); } /* %%Function:BitBltPR %%Owner:BRADV */ NATIVE BOOL BitBltPR(P1,P2,P3,P4,P5,P6,P7,P8,P9) /* WINIGNORE - PROFILE only */ HDC P1; short P2; short P3; short P4; short P5; HDC P6; short P7; short P8; DWORD P9; { return BitBlt(P1,P2,P3,P4,P5,P6,P7,P8,P9); } /* %%Function:CallWindowProcPR %%Owner:BRADV */ NATIVE long CallWindowProcPR(P1,P2,P3,P4,P5) /* WINIGNORE - PROFILE only */ FARPROC P1; HWND P2; unsigned P3; WORD P4; LONG P5; { return CallWindowProc(P1,P2,P3,P4,P5); } /* %%Function:ChangeMenuPR %%Owner:BRADV */ NATIVE BOOL ChangeMenuPR(P1,P2,P3,P4,P5) /* WINIGNORE - PROFILE only */ HMENU P1; WORD P2; LPSTR P3; WORD P4; WORD P5; { return ChangeMenu(P1,P2,P3,P4,P5); } /* %%Function:CheckDlgButtonPR %%Owner:BRADV */ NATIVE void CheckDlgButtonPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ HWND P1; int P2; WORD P3; { CheckDlgButton(P1,P2,P3); } /* %%Function:CheckMenuItemPR %%Owner:BRADV */ NATIVE BOOL CheckMenuItemPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ HMENU P1; WORD P2; WORD P3; { return CheckMenuItem(P1,P2,P3); } /* %%Function:CheckRadioButtonPR %%Owner:BRADV */ NATIVE void CheckRadioButtonPR(P1,P2,P3,P4) /* WINIGNORE - PROFILE only */ HWND P1; int P2; int P3; int P4; { CheckRadioButton(P1,P2,P3,P4); } /* %%Function:CloseClipboardPR %%Owner:BRADV */ NATIVE BOOL CloseClipboardPR() /* WINIGNORE - PROFILE only */ { return CloseClipboard(); } /* %%Function:CreateBitmapPR %%Owner:BRADV */ NATIVE HBITMAP CreateBitmapPR(P1,P2,P3,P4,P5) /* WINIGNORE - PROFILE only */ short P1; short P2; BYTE P3; BYTE P4; LPSTR P5; { return CreateBitmap(P1,P2,P3,P4,P5); } /* %%Function:CreateBMIndirectPR %%Owner:BRADV */ NATIVE HBITMAP CreateBMIndirectPR(P1) /* WINIGNORE - PROFILE only */ BITMAP FAR * P1; { return CreateBitmapIndirect(P1); } /* %%Function:CreateCaretPR %%Owner:BRADV */ NATIVE void CreateCaretPR(P1,P2,P3,P4) /* WINIGNORE - PROFILE only */ HWND P1; HBITMAP P2; int P3; int P4; { CreateCaret(P1,P2,P3,P4); } /* %%Function:CreateComBitmapPR %%Owner:BRADV */ NATIVE HBITMAP CreateComBitmapPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ HDC P1; short P2; short P3; { return CreateCompatibleBitmap(P1,P2,P3); } /* %%Function:CreateComDCPR %%Owner:BRADV */ NATIVE HDC CreateComDCPR(P1) /* WINIGNORE - PROFILE only */ HDC P1; { return CreateCompatibleDC(P1); } /* %%Function:CreateDCPR %%Owner:BRADV */ NATIVE HDC CreateDCPR(P1,P2,P3,P4) /* WINIGNORE - PROFILE only */ LPSTR P1; LPSTR P2; LPSTR P3; LPSTR P4; { return CreateDC(P1,P2,P3,P4); } /* %%Function:CreateFontIndirectPR %%Owner:BRADV */ NATIVE HFONT CreateFontIndirectPR(P1) /* WINIGNORE - PROFILE only */ LOGFONT FAR * P1; { return CreateFontIndirect(P1); } /* %%Function:CreateICPR %%Owner:BRADV */ NATIVE HDC CreateICPR(P1,P2,P3,P4) /* WINIGNORE - PROFILE only */ LPSTR P1; LPSTR P2; LPSTR P3; LPSTR P4; { return CreateIC(P1,P2,P3,P4); } /* %%Function:CreatePatternBrushPR %%Owner:BRADV */ NATIVE HBRUSH CreatePatternBrushPR(P1) /* WINIGNORE - PROFILE only */ HBITMAP P1; { return CreatePatternBrush(P1); } /* %%Function:CreateSolidBrushPR %%Owner:BRADV */ NATIVE HBRUSH CreateSolidBrushPR(P1) /* WINIGNORE - PROFILE only */ DWORD P1; { return CreateSolidBrush(P1); } /* %%Function:CreateWindowPR %%Owner:BRADV */ NATIVE HWND CreateWindowPR(P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11) /* WINIGNORE - PROFILE only */ LPSTR P1; LPSTR P2; DWORD P3; int P4; int P5; int P6; int P7; HWND P8; HMENU P9; HANDLE P10; LPSTR P11; { return CreateWindow(P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11); } /* %%Function:DeleteDCPR %%Owner:BRADV */ NATIVE BOOL DeleteDCPR(P1) /* WINIGNORE - PROFILE only */ HDC P1; { return DeleteDC(P1); } /* %%Function:DeleteObjectPR %%Owner:BRADV */ NATIVE BOOL DeleteObjectPR(P1) /* WINIGNORE - PROFILE only */ HANDLE P1; { return DeleteObject(P1); } /* %%Function:DestroyCaretPR %%Owner:BRADV */ NATIVE void DestroyCaretPR() /* WINIGNORE - PROFILE only */ { DestroyCaret(); } /* %%Function:DrawTextPR %%Owner:BRADV */ NATIVE void DrawTextPR(P1,P2,P3,P4,P5) /* WINIGNORE - PROFILE only */ HDC P1; LPSTR P2; int P3; LPRECT P4; WORD P5; { DrawText(P1,P2,P3,P4,P5); } /* %%Function:EmptyClipboardPR %%Owner:BRADV */ NATIVE BOOL EmptyClipboardPR() /* WINIGNORE - PROFILE only */ { return EmptyClipboard(); } /* %%Function:EnableWindowPR %%Owner:BRADV */ NATIVE BOOL EnableWindowPR(P1,P2) /* WINIGNORE - PROFILE only */ HWND P1; BOOL P2; { return EnableWindow(P1,P2); } /* %%Function:EndPaintPR %%Owner:BRADV */ NATIVE void EndPaintPR(P1,P2) /* WINIGNORE - PROFILE only */ HWND P1; LPPAINTSTRUCT P2; { EndPaint(P1,P2); } /* %%Function:EscapePR %%Owner:BRADV */ NATIVE short EscapePR(P1,P2,P3,P4,P5) /* WINIGNORE - PROFILE only */ HDC P1; short P2; short P3; LPSTR P4; LPSTR P5; { return Escape(P1,P2,P3,P4,P5); } /* %%Function:FillRectPR %%Owner:BRADV */ NATIVE int FillRectPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ HDC P1; LPRECT P2; HBRUSH P3; { return FillRect(P1,P2,P3); } /* %%Function:FillRgnPR %%Owner:BRADV */ NATIVE BOOL FillRgnPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ HDC P1; HRGN P2; HBRUSH P3; { return FillRgn(P1,P2,P3); } /* %%Function:GetClipboardDataPR %%Owner:BRADV */ NATIVE HANDLE GetClipboardDataPR(P1) /* WINIGNORE - PROFILE only */ WORD P1; { return GetClipboardData(P1); } /* %%Function:GetDCPR %%Owner:BRADV */ NATIVE HDC GetDCPR(P1) /* WINIGNORE - PROFILE only */ HWND P1; { return GetDC(P1); } /* %%Function:GetMenuPR %%Owner:BRADV */ NATIVE HMENU GetMenuPR(P1) /* WINIGNORE - PROFILE only */ HWND P1; { return GetMenu(P1); } /* %%Function:GetMenuStringPR %%Owner:BRADV */ NATIVE int GetMenuStringPR(P1,P2,P3,P4,P5) /* WINIGNORE - PROFILE only */ HMENU P1; WORD P2; LPSTR P3; int P4; WORD P5; { return GetMenuString(P1,P2,P3,P4,P5); } /* %%Function:GetMessagePR %%Owner:BRADV */ NATIVE BOOL GetMessagePR(P1,P2,P3,P4) /* WINIGNORE - PROFILE only */ LPMSG P1; HWND P2; unsigned P3; unsigned P4; { return GetMessage(P1,P2,P3,P4); } /* %%Function:GetProfileIntPR %%Owner:BRADV */ NATIVE int GetProfileIntPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ LPSTR P1; LPSTR P2; int P3; { return GetProfileInt(P1,P2,P3); } /* %%Function:GetProfileStringPR %%Owner:BRADV */ NATIVE int GetProfileStringPR(P1,P2,P3,P4,P5) /* WINIGNORE - PROFILE only */ LPSTR P1; LPSTR P2; LPSTR P3; LPSTR P4; int P5; { return GetProfileString(P1,P2,P3,P4,P5); } /* %%Function:GetStockObjectPR %%Owner:BRADV */ NATIVE HANDLE GetStockObjectPR(P1) /* WINIGNORE - PROFILE only */ short P1; { return GetStockObject(P1); } /* %%Function:GetTempFileNamePR %%Owner:BRADV */ NATIVE int GetTempFileNamePR(P1,P2,P3,P4) /* WINIGNORE - PROFILE only */ BYTE P1; LPSTR P2; WORD P3; LPSTR P4; { return GetTempFileName(P1,P2,P3,P4); } /* %%Function:GetTextExtentPR %%Owner:BRADV */ NATIVE DWORD GetTextExtentPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ HDC P1; LPSTR P2; short P3; { return GetTextExtent(P1,P2,P3); } /* %%Function:GetUpdateRectPR %%Owner:BRADV */ NATIVE BOOL GetUpdateRectPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ HWND P1; LPRECT P2; BOOL P3; { return GetUpdateRect(P1,P2,P3); } /* %%Function:GlblAllocPR %%Owner:BRADV */ NATIVE HANDLE GlblAllocPR(P1,P2) /* WINIGNORE - PROFILE only */ WORD P1; DWORD P2; { return GlobalAlloc(P1,P2); } /* %%Function:GlobalFreePR %%Owner:BRADV */ NATIVE HANDLE GlobalFreePR(P1) /* WINIGNORE - PROFILE only */ HANDLE P1; { return GlobalFree(P1); } /* %%Function:GlobalLockPR %%Owner:BRADV */ NATIVE LPSTR GlobalLockPR(P1) /* WINIGNORE - PROFILE only */ HANDLE P1; { return GlobalLock(P1); } /* %%Function:GlobalReAllocPR %%Owner:BRADV */ NATIVE HANDLE GlobalReAllocPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ HANDLE P1; DWORD P2; WORD P3; { return GlobalReAlloc(P1,P2,P3); } /* %%Function:GlobalSizePR %%Owner:BRADV */ NATIVE DWORD GlobalSizePR(P1) /* WINIGNORE - PROFILE only */ HANDLE P1; { return GlobalSize(P1); } /* %%Function:GlobalUnlockPR %%Owner:BRADV */ NATIVE BOOL GlobalUnlockPR(P1) /* WINIGNORE - PROFILE only */ HANDLE P1; { return GlobalUnlock(P1); } /* %%Function:GrayStringPR %%Owner:BRADV */ NATIVE BOOL GrayStringPR(P1,P2,P3,P4,P5,P6,P7,P8,P9) /* WINIGNORE - PROFILE only */ HDC P1; HBRUSH P2; FARPROC P3; DWORD P4; int P5; int P6; int P7; int P8; int P9; { return GrayString(P1,P2,P3,P4,P5,P6,P7,P8,P9); } /* %%Function:HideCaretPR %%Owner:BRADV */ NATIVE void HideCaretPR(P1) /* WINIGNORE - PROFILE only */ HWND P1; { HideCaret(P1); } /* %%Function:InvalidateRectPR %%Owner:BRADV */ NATIVE void InvalidateRectPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ HWND P1; LPRECT P2; BOOL P3; { InvalidateRect(P1,P2,P3); } /* %%Function:InvertRectPR %%Owner:BRADV */ NATIVE int InvertRectPR(P1,P2) /* WINIGNORE - PROFILE only */ HDC P1; LPRECT P2; { return InvertRect(P1,P2); } /* %%Function:LineToPR %%Owner:BRADV */ NATIVE BOOL LineToPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ HDC P1; short P2; short P3; { return LineTo(P1,P2,P3); } /* %%Function:MsgBeepPR %%Owner:BRADV */ NATIVE BOOL MsgBeepPR(P1) /* WINIGNORE - PROFILE only */ WORD P1; { return MessageBeep(P1); } /* %%Function:MessageBoxPR %%Owner:BRADV */ NATIVE int MessageBoxPR(P1,P2,P3,P4) /* WINIGNORE - PROFILE only */ HWND P1; LPSTR P2; LPSTR P3; WORD P4; { return MessageBox(P1,P2,P3,P4); } /* %%Function:MoveToPR %%Owner:BRADV */ NATIVE DWORD MoveToPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ HDC P1; short P2; short P3; { return MoveTo(P1,P2,P3); } /* %%Function:OpenClipboardPR %%Owner:BRADV */ NATIVE BOOL OpenClipboardPR(P1) /* WINIGNORE - PROFILE only */ HWND P1; { return OpenClipboard(P1); } /* %%Function:OpenFilePR %%Owner:BRADV */ NATIVE int OpenFilePR(P1,P2,P3) /* WINIGNORE - PROFILE only */ LPSTR P1; LPOFSTRUCT P2; WORD P3; { return OpenFile(P1,P2,P3); } /* %%Function:PatBltPR %%Owner:BRADV */ NATIVE BOOL PatBltPR(P1,P2,P3,P4,P5,P6) /* WINIGNORE - PROFILE only */ HDC P1; short P2; short P3; short P4; short P5; DWORD P6; { return PatBlt(P1,P2,P3,P4,P5,P6); } /* %%Function:PeekMsgPR %%Owner:BRADV */ NATIVE BOOL PeekMsgPR(P1,P2,P3,P4,P5) /* WINIGNORE - PROFILE only */ LPMSG P1; HWND P2; unsigned P3; WORD P4; BOOL P5; { return PeekMessage(P1,P2,P3,P4,P5); } /* %%Function:PostMsgPR %%Owner:BRADV */ NATIVE BOOL PostMsgPR(P1,P2,P3,P4) /* WINIGNORE - PROFILE only */ HWND P1; unsigned P2; WORD P3; LONG P4; { return PostMessage(P1,P2,P3,P4); } /* %%Function:ReleaseCapturePR %%Owner:BRADV */ NATIVE void ReleaseCapturePR() /* WINIGNORE - PROFILE only */ { ReleaseCapture(); } /* %%Function:RestoreDCPR %%Owner:BRADV */ NATIVE int RestoreDCPR(P1,P2) /* WINIGNORE - PROFILE only */ HDC P1; short P2; { return RestoreDC(P1,P2); } /* %%Function:SaveDCPR %%Owner:BRADV */ NATIVE short SaveDCPR(P1) /* WINIGNORE - PROFILE only */ HDC P1; { return SaveDC(P1); } /* %%Function:ScrollWindowPR %%Owner:BRADV */ NATIVE void ScrollWindowPR(P1,P2,P3,P4,P5) /* WINIGNORE - PROFILE only */ HWND P1; int P2; int P3; LPRECT P4; LPRECT P5; { ScrollWindow(P1,P2,P3,P4,P5); } /* %%Function:SelectObjectPR %%Owner:BRADV */ NATIVE HANDLE SelectObjectPR(P1,P2) /* WINIGNORE - PROFILE only */ HDC P1; HANDLE P2; { return SelectObject(P1,P2); } /* %%Function:SendMsgPR %%Owner:BRADV */ NATIVE long SendMsgPR(P1,P2,P3,P4) /* WINIGNORE - PROFILE only */ HWND P1; unsigned P2; WORD P3; LONG P4; { return SendMessage(P1,P2,P3,P4); } /* %%Function:SetActiveWindowPR %%Owner:BRADV */ NATIVE HWND SetActiveWindowPR(P1) /* WINIGNORE - PROFILE only */ HWND P1; { return SetActiveWindow(P1); } /* %%Function:SetCapturePR %%Owner:BRADV */ NATIVE HWND SetCapturePR(P1) /* WINIGNORE - PROFILE only */ HWND P1; { return SetCapture(P1); } /* %%Function:SetClipboardDataPR %%Owner:BRADV */ NATIVE HANDLE SetClipboardDataPR(P1,P2) /* WINIGNORE - PROFILE only */ WORD P1; HANDLE P2; { return SetClipboardData(P1,P2); } /* %%Function:SetCursorPR %%Owner:BRADV */ NATIVE HCURSOR SetCursorPR(P1) /* WINIGNORE - PROFILE only */ HCURSOR P1; { return SetCursor(P1); } /* %%Function:SetFocusPR %%Owner:BRADV */ NATIVE HWND SetFocusPR(P1) /* WINIGNORE - PROFILE only */ HWND P1; { return SetFocus(P1); } /* %%Function:ShowCaretPR %%Owner:BRADV */ NATIVE void ShowCaretPR(P1) /* WINIGNORE - PROFILE only */ HWND P1; { ShowCaret(P1); } /* %%Function:ShowCursorPR %%Owner:BRADV */ NATIVE int ShowCursorPR(P1) /* WINIGNORE - PROFILE only */ BOOL P1; { return ShowCursor(P1); } /* %%Function:ShowWindowPR %%Owner:BRADV */ NATIVE BOOL ShowWindowPR(P1,P2) /* WINIGNORE - PROFILE only */ HWND P1; int P2; { return ShowWindow(P1,P2); } /* %%Function:StretchBltPR %%Owner:BRADV */ NATIVE BOOL StretchBltPR(P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11) /* WINIGNORE - PROFILE only */ HDC P1; short P2; short P3; short P4; short P5; HDC P6; short P7; short P8; short P9; short P10; DWORD P11; { return StretchBlt(P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11); } /* %%Function:TextOutPR %%Owner:BRADV */ NATIVE BOOL TextOutPR(P1,P2,P3,P4,P5) /* WINIGNORE - PROFILE only */ HDC P1; short P2; short P3; LPSTR P4; short P5; { return TextOut(P1,P2,P3,P4,P5); } /* %%Function:TranslateMessagePR %%Owner:BRADV */ NATIVE BOOL TranslateMessagePR(P1) /* WINIGNORE - PROFILE only */ LPMSG P1; { return TranslateMessage(P1); } /* %%Function:UpdateWindowPR %%Owner:BRADV */ NATIVE void UpdateWindowPR(P1) /* WINIGNORE - PROFILE only */ HWND P1; { UpdateWindow(P1); } /* %%Function:ValidateRectPR %%Owner:BRADV */ NATIVE void ValidateRectPR(P1,P2) /* WINIGNORE - PROFILE only */ HWND P1; LPRECT P2; { ValidateRect(P1,P2); } /* %%Function:WriteProfileStringPR %%Owner:BRADV */ NATIVE BOOL WriteProfileStringPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ LPSTR P1; LPSTR P2; LPSTR P3; { return WriteProfileString(P1,P2,P3); } /* %%Function:SelectClipRgnPR %%Owner:BRADV */ NATIVE int SelectClipRgnPR(P1,P2) /* WINIGNORE - PROFILE only */ HDC P1; HRGN P2; { return SelectClipRgn(P1,P2); } /* %%Function:CreateRectRgnIndirectPR %%Owner:BRADV */ NATIVE HRGN CreateRectRgnIndirectPR(P1) /* WINIGNORE - PROFILE only */ LPRECT P1; { return CreateRectRgnIndirect(P1); } /* %%Function:BringWindowToTopPR %%Owner:BRADV */ NATIVE void BringWindowToTopPR(P1) /* WINIGNORE - PROFILE only */ HWND P1; { BringWindowToTop(P1); } /* %%Function:LoadLibraryPR %%Owner:BRADV */ NATIVE HANDLE LoadLibraryPR(P1) /* WINIGNORE - PROFILE only */ LPSTR P1; { return LoadLibrary(P1); } /* %%Function:ExcludeClipRectPR %%Owner:BRADV */ NATIVE ExcludeClipRectPR(P1,P2,P3,P4,P5) /* WINIGNORE - PROFILE only */ HDC P1; short P2; short P3; short P4; short P5; { return ExcludeClipRect(P1,P2,P3,P4,P5); } /* %%Function:GlobalCompactPR %%Owner:BRADV */ NATIVE DWORD GlobalCompactPR(P1) /* WINIGNORE - PROFILE only */ DWORD P1; { return GlobalCompact(P1); } /* %%Function:CreatePenIndirectPR %%Owner:BRADV */ NATIVE HPEN CreatePenIndirectPR(P1) /* WINIGNORE - PROFILE only */ LPLOGPEN P1; { return CreatePenIndirect(P1); } /* %%Function:SetMenuPR %%Owner:BRADV */ NATIVE BOOL SetMenuPR(P1,P2) /* WINIGNORE - PROFILE only */ HWND P1; HMENU P2; { return SetMenu(P1,P2); } /* %%Function:ScrollDCPR %%Owner:BRADV */ NATIVE BOOL ScrollDCPR(P1,P2,P3,P4,P5,P6,P7) /* WINIGNORE - PROFILE only */ HDC P1; int P2; int P3; LPRECT P4; LPRECT P5; HRGN P6; LPRECT P7; { return ScrollDC(P1,P2,P3,P4,P5,P6,P7); } /* %%Function:CreatePenPR %%Owner:BRADV */ NATIVE HPEN CreatePenPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ short P1; short P2; DWORD P3; { return CreatePen(P1,P2,P3); } /* %%Function:CreateMenuPR %%Owner:BRADV */ NATIVE HMENU CreateMenuPR() /* WINIGNORE - PROFILE only */ { return CreateMenu(); } /* %%Function:GetMenuItemCountPR %%Owner:BRADV */ NATIVE WORD GetMenuItemCountPR(P1) /* WINIGNORE - PROFILE only */ HMENU P1; { return GetMenuItemCount(P1); } /* %%Function:GetMenuItemIdPR %%Owner:BRADV */ NATIVE WORD GetMenuItemIdPR(P1,P2) /* WINIGNORE - PROFILE only */ HMENU P1; WORD P2; { return GetMenuItemId(P1,P2); } /* %%Function:GetInputStatePR %%Owner:BRADV */ NATIVE BOOL GetInputStatePR() /* WINIGNORE - PROFILE only */ { return GetInputState(); } /* %%Function:ExtTextOutPR %%Owner:BRADV */ NATIVE BOOL ExtTextOutPR(P1,P2,P3,P4,P5,P6,P7,P8) /* WINIGNORE - PROFILE only */ HDC P1; int P2; int P3; WORD P4; LPRECT P5; LPSTR P6; int P7; LPSTR P8; { return ExtTextOut(P1,P2,P3,P4,P5,P6,P7,P8); } /* %%Function:GetEnvironmentPR %%Owner:BRADV */ NATIVE short GetEnvironmentPR(P1,P2,P3) /* WINIGNORE - PROFILE only */ LPSTR P1; LPSTR P2; int P3; { return GetEnvironment(P1,P2,P3); } /* %%Function:GetMenuStatePR %%Owner:BRADV */ NATIVE WORD GetMenuStatePR(P1,P2,P3) /* WINIGNORE - PROFILE only */ HMENU P1; WORD P2; WORD P3; { return GetMenuState(P1,P2,P3); } #endif /* HYBRID */
the_stack_data/124610.c
#include <stdlib.h> #include <stdio.h> /// Main function used during tests to check if the file produced is /// the same as the input int main() { extern const char myfile[]; extern const size_t myfile_len; fwrite(myfile, 1, myfile_len, stdout); return 0; }
the_stack_data/73575730.c
#include <stdio.h> #include <stdlib.h> int main() { int a; // goes into the stack int *p; // goes into the stack p = (int *)malloc(sizeof(int)); // malloc returns a void*; so we need typecasting *p = 10; free(p); p = (int *)malloc(20 * sizeof(int)); p[0] = 999; // this is a valid way to assign value to array *(p + 1) = 123; // this is also a valid way to assign values to array printf("%d\n", p[0]); printf("%d\n", *p); printf("%d\n", p[1]); printf("%d\n", *(p + 1)); }
the_stack_data/231394346.c
#include <stdio.h> typedef struct complex { float real; float imag; } complex; complex add(complex n1, complex n2); int main() { complex n1, n2, temp; printf("For 1st complex number \n"); printf("Enter real and imaginary part respectively:\n"); scanf("%f %f", &n1.real, &n1.imag); printf("\nFor 2nd complex number \n"); printf("Enter real and imaginary part respectively:\n"); scanf("%f %f", &n2.real, &n2.imag); temp = add(n1, n2); printf("Sum = %.1f + %.1fi", temp.real, temp.imag); return 0; } complex add(complex n1, complex n2) { complex temp; temp.real = n1.real + n2.real; temp.imag = n1.imag + n2.imag; return (temp); }
the_stack_data/15623.c
#ifdef STM32L0xx #include "stm32l0xx_hal_comp_ex.c" #endif
the_stack_data/1183505.c
int main() { int i = 0, j=9; do { i++; } while (i!=10); print ("i 10"); printid(i); do j++; while (i!=10); print ("j 10"); printid(j); i=8; j=0; do { j++; i--; if (i % 2 == 0) continue; j++; if (i == 1) break; } while (i!=10); print ("j 11"); printid(j); print ("i 1"); printid(i); return 0; }
the_stack_data/32165.c
/*team members: Ganesh Gajavelli*/ #include <stdio.h> void printString(char *input); void readString(char *line); void readSector(char *buffer, int sector); void handleInterrupt21(int ax, int bx, int cx, int dx); void main(){ char line[80]; // Hint: this line needs to be at the top of main // in ansi C declarations must be at the start of a function char* printToLine = "\nDisplay a string to the console using printString!\n"; char buffer[512]; /*print "Hello World" using raw memory commands*/ putInMemory(0xB000, 0x8140, 'H'); putInMemory(0xB000, 0x8141, 0x7); putInMemory(0xB000, 0x8142, 'e'); putInMemory(0xB000, 0x8143, 0x7); putInMemory(0xB000, 0x8144, 'l'); putInMemory(0xB000, 0x8145, 0x7); putInMemory(0xB000, 0x8146, 'l'); putInMemory(0xB000, 0x8147, 0x7); putInMemory(0xB000, 0x8148, 'o'); putInMemory(0xB000, 0x8149, 0x7); putInMemory(0xB000, 0x814A, ' '); putInMemory(0xB000, 0x814B, 0x7); putInMemory(0xB000, 0x814C, 'W'); putInMemory(0xB000, 0x814D, 0x7); putInMemory(0xB000, 0x814E, 'o'); putInMemory(0xB000, 0x814F, 0x7); putInMemory(0xB000, 0x8150, 'r'); putInMemory(0xB000, 0x8151, 0x7); putInMemory(0xB000, 0x8152, 'l'); putInMemory(0xB000, 0x8153, 0x7); putInMemory(0xB000, 0x8154, 'd'); putInMemory(0xB000, 0x8155, 0x7); /*interrupt(0x10, 0xe*256+'Q', 0, 0, 0);*/ makeInterrupt21(); interrupt(0x21,0,printToLine,0,0); printToLine = "Enter a line: \0"; makeInterrupt21(); interrupt(0x21,0,printToLine,0,0); makeInterrupt21(); interrupt(0x21,1,line,0,0); interrupt(0x21,0,line,0,0); makeInterrupt21(); interrupt(0x21,2,buffer,30,0); interrupt(0x21,0,buffer,0,0); /* makeInterrupt21(); interrupt(0x21, 0, 0, 0, 0); char line[80]; makeInterrupt21(); interrupt(0x21,1,line,0,0); interrupt(0x21,0,line,0,0); */ while(1); /* never forget this */ } void printString(char *input){ int i = 0; while (input[i] != '\0'){ interrupt(0x10, 0xe*256+input[i], 0, 0, 0); i++; } } /* Reads a line from the console using Interrupt 0x16. */ void readString(char *line){ int i, lineLength, ax; char charRead, backSpace, enter; lineLength = 80; i = 0; ax = 0; backSpace = 0x8; enter = 0xd; charRead = interrupt(0x16, ax, 0, 0, 0); while (charRead != enter && i < lineLength-2) { if (charRead != backSpace) { interrupt(0x10, 0xe*256+charRead, 0, 0, 0); line[i] = charRead; i++; } else { i--; if (i >= 0) { interrupt(0x10, 0xe*256+charRead, 0, 0, 0); interrupt(0x10, 0xe*256+'\0', 0, 0, 0); interrupt(0x10, 0xe*256+backSpace, 0, 0, 0); } else { i = 0; } } charRead = interrupt(0x16, ax, 0, 0, 0); } line[i] = 0xa; line[i+1] = 0x0; /* correctly prints a newline */ printString("\r\n"); return; } int mod(int a, int b) { int temp; temp = a; while (temp >= b) { temp = temp-b; } return temp; } int div(int a, int b) { int quotient; quotient = 0; while ((quotient + 1) * b <= a) { quotient++; } return quotient; } void readSector(char *buffer, int sector){ /* */ int ah = 2; int al = 1; int ax = (ah * 256) + al; int bx = buffer; int ch = div(sector,36); int cl = mod(sector,18)+1; int cx = (ch * 256) + cl; int dh0 = div(sector,18); int dh = mod(dh0,2); int dl = 0; int dx = (dh * 256) + dl; interrupt(0x13,ax,buffer,cx,dx); /* interrupt(0x13,513,&buffer,((sector/36)*256)+(mod(sector,18)+1),(mod(div(sector,18),2)*256));*/ } void handleInterrupt21(int ax, int bx, int cx, int dx){ /*printString("Hello World");*/ if (ax == 0){ char* printer = bx; printString(printer); } else if (ax == 1){ char* reader = bx; readString(reader); } else if (ax == 2){ char* buffer = bx; int sectorNum = cx; readSector(buffer,sectorNum); } else{ printString("error message! Invalid first parameter"); } }
the_stack_data/89200468.c
// Compile with: // // // To specify the number of bodies in the world, the program optionally accepts // an integer as its first command line argument. #include <time.h> #include <sys/times.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <X11/Xlib.h> #include <unistd.h> #include "omp.h" #define WIDTH 1024 #define HEIGHT 768 // default number of bodies #define DEF_NUM_BODIES 2000 // gravitational constant #define GRAV 10.0 // initial velocities are scaled by this value #define V_SCALAR 20.0 // initial masses are scaled by this value #define M_SCALAR 5.0 // radius scalar #define R_SCALAR 3 // coefficient of restitution determines the elasticity of a collision: C_REST = [0,1] // if C_REST = 0 -> perfectly inelastic (particles stick together) // if C_REST = 1 -> perfectly elastic (no loss of speed) #define C_REST 0.5 // set the iteration times #define iteration_times 100 // Must set 0 if run on Pi #define NOT_RUN_ON_PI 1 #define TREERATIO 3 struct body { double x, y; // position double vx, vy; // velocity double ax, ay; //accelerate double m; // mass double r; // radius of the particle }; struct world { struct body *bodies; int num_bodies; }; clock_t total_time = 0; //total_time.sec = 0; //total_time.usec = 0; double max (double a, double b) {return (a > b ? a : b);} double min (double a, double b) {return (a < b ? a : b);} struct node { struct body * bodyp; struct node * q1; struct node * q2; struct node * q3; struct node * q4; double totalmass; double centerx, centery; double xmin, xmax; double ymin, ymax; double diag; }; enum quadrant { q1, q2, q3, q4 }; enum quadrant getquadrant(double x, double y, double xmin, double xmax, double ymin, double ymax) //makes a rectangle with bounds of xmin,xmax,ymin,ymax, and returns the quadrant that (x,y) is in { double midx, midy; midx = xmin + 0.5*(xmax - xmin); midy = ymin + 0.5*(ymax - ymin); if(y > midy) { if(x > midx) return q1; else return q2; } else { if(x > midx) return q4; else return q3; } } struct node * createnode(struct body * bodyp, double xmin, double xmax, double ymin, double ymax) //creates a leaf node to insert into the tree { struct node * rootnode; if(!(rootnode=malloc(sizeof(struct node)))) { printf("Unable to allocate node, exit"); return 0; } rootnode->totalmass = bodyp->m; rootnode->centerx = bodyp->x; rootnode->centery = bodyp->y; rootnode->xmin = xmin; rootnode->xmax = xmax; rootnode->ymin = ymin; rootnode->ymax = ymax; rootnode->diag = sqrt(( pow(xmax - xmin, 2) + pow(ymax - ymin, 2) )); rootnode->bodyp = bodyp; rootnode->q1 = NULL; rootnode->q2 = NULL; rootnode->q3 = NULL; rootnode->q4 = NULL; return rootnode; } void updatecenterofmass(struct node * nodep, struct body * bodyp) //updates the center of mass after inserting a point into a branch { nodep->centerx = (nodep->totalmass*nodep->centerx + bodyp->m*bodyp->x)/(nodep->totalmass + bodyp->m); nodep->centery = (nodep->totalmass*nodep->centery + bodyp->m*bodyp->y)/(nodep->totalmass + bodyp->m); nodep->totalmass += bodyp->m; return; } void insertbody(struct body * insbody, struct node * nodep) //inserts a body into the tree, converting leaf nodes into branches if necessary { enum quadrant existingquad, newquad; double xmid, ymid; xmid = nodep->xmin + 0.5*(nodep->xmax - nodep->xmin); ymid = nodep->ymin + 0.5*(nodep->ymax - nodep->ymin); if(nodep->bodyp != NULL) //if the node is a leaf convert to a branch by inserting the leaf point into one of its subquadrants { existingquad = getquadrant(nodep->bodyp->x, nodep->bodyp->y, nodep->xmin, nodep->xmax, nodep->ymin, nodep->ymax); switch (existingquad) { case q1: nodep->q1 = createnode(nodep->bodyp, xmid, nodep->xmax, ymid, nodep->ymax); break; case q2: nodep->q2 = createnode(nodep->bodyp, nodep->xmin, xmid, ymid, nodep->ymax); break; case q3: nodep->q3 = createnode(nodep->bodyp, nodep->xmin, xmid, nodep->ymin, ymid); break; case q4: nodep->q4 = createnode(nodep->bodyp, xmid, nodep->xmax, nodep->ymin, ymid); break; } nodep->bodyp = NULL; } newquad = getquadrant(insbody->x, insbody->y, nodep->xmin, nodep->xmax, nodep->ymin, nodep->ymax); updatecenterofmass(nodep,insbody); switch (newquad) //insert the new point into one of the quadrants if empty, otherwise recurse deeper into tree { case q1: if(nodep->q1 == NULL) { nodep->q1 = createnode(insbody, xmid, nodep->xmax, ymid, nodep->ymax); } else { insertbody(insbody,nodep->q1); } break; case q2: if(nodep->q2 == NULL) { nodep->q2 = createnode(insbody, nodep->xmin, xmid, ymid, nodep->ymax); } else { insertbody(insbody,nodep->q2); } break; case q3: if(nodep->q3 == NULL) { nodep->q3 = createnode(insbody, nodep->xmin, xmid, nodep->ymin, ymid); } else { insertbody(insbody,nodep->q3); } break; case q4: if(nodep->q4 == NULL) { nodep->q4 = createnode(insbody, xmid, nodep->xmax, nodep->ymin, ymid); } else { insertbody(insbody,nodep->q4); } break; } } void treesum(struct node * nodep, struct body * bodyp, double ratiothreshold ) //sum the forces on body bodyp from points in tree with root node nodep { double dx, dy, r, rsqr; //x distance, y distance, distance, distance^2 double accel; double a_over_r; dx = nodep->centerx - bodyp->x; dy = nodep->centery - bodyp->y; rsqr = pow(dx,2) + pow(dy,2); r = sqrt(rsqr); if(r < 25){ r = 25; } if( (((r/nodep->diag) > ratiothreshold) || (nodep->bodyp))&&(nodep->bodyp!=bodyp) ) { accel = (10.0) * nodep->totalmass / r/r/r; bodyp->ax += accel*dx; bodyp->ay += accel*dy; } else { if(nodep->q1) { treesum(nodep->q1, bodyp, ratiothreshold); } if(nodep->q2) { treesum(nodep->q2, bodyp, ratiothreshold); } if(nodep->q3) { treesum(nodep->q3, bodyp, ratiothreshold); } if(nodep->q4) { treesum(nodep->q4, bodyp, ratiothreshold); } } return; } void destroytree(struct node * nodep) { if(nodep != NULL) { if(nodep->q1 != NULL) { destroytree(nodep->q1); } if(nodep->q2 != NULL) { destroytree(nodep->q2); } if(nodep->q3 != NULL) { destroytree(nodep->q3); } if(nodep->q4 != NULL) { destroytree(nodep->q4); } free(nodep); } } /* This function initializes each particle's mass, velocity and position */ struct world* create_world(int num_bodies) { struct world *world = malloc(sizeof(struct world)); world->num_bodies = num_bodies; world->bodies = malloc(sizeof(struct body)*num_bodies); int i = 0; double x; double y; double rc; int min_dim = (WIDTH < HEIGHT) ? WIDTH : HEIGHT; while (i<num_bodies) { x = drand48() * WIDTH; y = drand48() * HEIGHT; rc = sqrt((WIDTH/2-x)*(WIDTH/2-x) + (y-HEIGHT/2)*(y-HEIGHT/2)); if (rc <= min_dim/2) { world->bodies[i].x = x; world->bodies[i].y = y; world->bodies[i].vx = V_SCALAR * (y-HEIGHT/2) / rc; world->bodies[i].vy = V_SCALAR * (WIDTH/2-x) / rc; world->bodies[i].ax = 0; world->bodies[i].ay = 0; world->bodies[i].m = (1 / (0.025 + drand48())) * M_SCALAR; world->bodies[i].r = sqrt(world->bodies[i].m / M_PI) * R_SCALAR; i++; } } return world; } // set the foreground color given RGB values between 0..255. void set_color(Display *disp, GC gc, int r, int g, int b){ unsigned long int p ; if (r < 0) r = 0; else if (r > 255) r = 255; if (g < 0) g = 0; else if (g > 255) g = 255; if (b < 0) b = 0; else if (b > 255) b = 255; p = (r << 16) | (g << 8) | (b) ; XSetForeground(disp, gc, p) ; } /* This function updates the screen with the new positions of each particle */ void draw_world(Display *disp, Pixmap back_buf, GC gc, struct world *world) { int i; double x, y, r, r2; // we turn off aliasing for faster draws set_color(disp, gc, 255, 255, 255); XFillRectangle(disp, back_buf, gc, 0, 0, WIDTH, HEIGHT); for (i = 0; i < world->num_bodies; i++) { r = world->bodies[i].r; x = world->bodies[i].x - r; y = world->bodies[i].y - r; r2 = r + r; // draw body set_color(disp, gc, 255*7/10, 255*7/10, 255*7/10); XFillArc(disp, back_buf, gc, x, y, r2, r2, 0, 360*64); set_color(disp, gc, 0, 0, 0); XDrawArc(disp, back_buf, gc, x, y, r2, r2, 0, 360*64); } } void collision_step(struct world *world) { int a, b; double r, x, y, vx, vy; // Impose screen boundaries by reversing direction if body is off screen for (a = 0; a < world->num_bodies; a++) { r = world->bodies[a].r; x = world->bodies[a].x; y = world->bodies[a].y; vx = world->bodies[a].vx; vy = world->bodies[a].vy; if (x-r < 0) { // left edge if (vx < 0) { world->bodies[a].vx = -C_REST * vx; } world->bodies[a].x = r; } else if (x+r > WIDTH) { // right edge if (vx > 0) { world->bodies[a].vx = -C_REST * vx; } world->bodies[a].x = WIDTH - r; } if (y-r < 0) { // bottom edge if (vy < 0) { world->bodies[a].vy = -C_REST * vy; } world->bodies[a].y = r; } else if (y+r > HEIGHT) { // top edge if (vy > 0) { world->bodies[a].vy = -C_REST * vy; } world->bodies[a].y = HEIGHT - r; } } } void position_step(struct world *world, double time_res){ struct node * rootnode; //struct body * bodies = world->bodies; //int nbodies = world->num_bodies; double xmin, xmax, ymin, ymax; xmin = 0.0; xmax = 0.0; ymin = 0.0; ymax = 0.0; for(int i = 0; i < world->num_bodies; i++) //reset accel { world->bodies[i].ax = 0.0; world->bodies[i].ay = 0.0; xmin=min(xmin,world->bodies[i].x); xmax=max(xmax,world->bodies[i].x); ymin=min(ymin,world->bodies[i].y); ymax=max(ymax,world->bodies[i].y); } rootnode = createnode(world->bodies+0,xmin,xmax,ymin,ymax); //rootnode = createnode(bodies+0,0,WIDTH,0,HEIGHT); for(int i = 1; i < world->num_bodies; i++) { insertbody(world->bodies+i, rootnode); } //#pragma omp parallel { //#pragma omp for for(int i = 0; i < world->num_bodies; i++) //sum accel { treesum(rootnode, world->bodies+i, TREERATIO); } //#pragma omp for for(int i = 0; i < world->num_bodies; i++) { //Update velocities world->bodies[i].vx += world->bodies[i].ax * time_res; world->bodies[i].vy += world->bodies[i].ay * time_res; //Update positions world->bodies[i].x += world->bodies[i].vx * time_res; world->bodies[i].y += world->bodies[i].vy * time_res; } } destroytree(rootnode); } void step_world(struct world *world, double time_res) { struct tms ttt; clock_t start, end; start = times(&ttt); position_step(world, time_res); end = times(&ttt); total_time += end - start; collision_step(world); } /* Main method runs initialize() and update() */ int main(int argc, char **argv) { //total_time.tv_sec = 0; //total_time.tv_usec = 0; /* get num bodies from the command line */ int num_bodies; num_bodies = (argc == 2) ? atoi(argv[1]) : DEF_NUM_BODIES; printf("Universe has %d bodies.\n", num_bodies); //omp_set_num_threads(8); /* set up the universe */ time_t cur_time; time(&cur_time); srand48((long)cur_time); // seed the RNG used in create_world struct world *world = create_world(num_bodies); /* set up graphics using Xlib */ #if NOT_RUN_ON_PI Display *disp = XOpenDisplay(NULL); int scr = DefaultScreen(disp); Window win = XCreateSimpleWindow( disp, RootWindow(disp, scr), 0, 0, WIDTH, HEIGHT, 0, BlackPixel(disp, scr), WhitePixel(disp, scr)); XStoreName(disp, win, "N-Body Simulator"); Pixmap back_buf = XCreatePixmap(disp, RootWindow(disp, scr), WIDTH, HEIGHT, DefaultDepth(disp, scr)); GC gc = XCreateGC(disp, back_buf, 0, 0); // Make sure we're only looking for messages about closing the window Atom del_window = XInternAtom(disp, "WM_DELETE_WINDOW", 0); XSetWMProtocols(disp, win, &del_window, 1); XSelectInput(disp, win, StructureNotifyMask); XMapWindow(disp, win); XEvent event; // wait until window is mapped while (1) { XNextEvent(disp, &event); if (event.type == MapNotify) { break; } } #endif struct timespec delay={0, 1000000000 / 60}; // for 60 FPS struct timespec remaining; double delta_t = 0.1; int ii; for(ii = 0; ii < iteration_times; ii++){ // check if the window has been closed #if NOT_RUN_ON_PI if (XCheckTypedEvent(disp, ClientMessage, &event)) { break; } // we first draw to the back buffer then copy it to the front (`win`) draw_world(disp, back_buf, gc, world); XCopyArea(disp, back_buf, win, gc, 0, 0, WIDTH, HEIGHT, 0, 0); #endif step_world(world, delta_t); //if you want to watch the process in 60 FPS //nanosleep(&delay, &remaining); } // printf("Total Time = %f\n", (double)total_time.tv_sec + (double)total_time.tv_usec/1000000); printf("Nbody Position Calculation Time = :%lf s\n",(double)total_time / (sysconf(_SC_CLK_TCK))); #if NOT_RUN_ON_PI XFreeGC(disp, gc); XFreePixmap(disp, back_buf); XDestroyWindow(disp, win); XCloseDisplay(disp); #endif return 0; }
the_stack_data/75137164.c
double factorial(int n) { double result = 1.0; if (n > 1) { for (int i = n; i < n; i++) { result *= n; } } return result; } int flip(int n) { return -n; } int abs(int n) { if (n < 0) { return -n; } else { return n; } } float absf(float n) { if (n < 0) { return -n; } else { return n; } } double sqrt(double square) { double root = square / 3; int i; if (square <= 0) return 0; for (i = 0; i < 32; i++) root = (root + square / root) / 2; return root; } int pow(int x, int n) { int r = x; for (int i = 0; i < n - 1; i++) { r *= x; } return r; } int ceil(float num) { int inum = (int) num; if (num == (float) inum) { return inum; } return inum + 1; } void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } /** * @brief rounds up number if it's not zero * * @param[in] x the number to round up * * @return the rounded number */ int roundup(int x, int y) { if ((x % y) == 0) { return x / y; } return (x / y) + 1; }
the_stack_data/1242826.c
#include <stdio.h> #include <stdlib.h> #include <inttypes.h> uint64_t minimum(uint64_t a, uint64_t b); uint64_t distance(int a, int b, uint64_t s[], int length); uint64_t find_farthest_houses(uint64_t s[],int length); int main(){ int houses; scanf("%d", &houses); uint64_t* sum = (uint64_t*) malloc(houses * (sizeof(uint64_t))); for(int i = 0; i < houses; i++){ // uint64_t s; scanf("%" SCNu64,&sum[i]); if(i != 0) sum[i] += sum[i-1]; } printf("%" SCNu64 "\n", find_farthest_houses(sum,houses)); free(sum); } uint64_t minimum(uint64_t a, uint64_t b){ if(a < b){ return a; }else return b; } uint64_t distance(int a, int b,uint64_t s[], int length){ if(a == 1){ return minimum(s[b-2], (s[length - 1] - s[b-2])); } else if (a == 2){ return minimum(s[b-2] - s[a-2], (s[length - 1] - s[b-2] + s[a-2])); }else return minimum(s[b-2] - s[a-2], (s[length - 1] - s[b-2] + s[a-2])); } uint64_t find_farthest_houses(uint64_t s[],int length){ // caterpillar method uint64_t max = 0; // max path between two houses int start = 0; /* int end = 1; // start&end of subsequences uint64_t dst = distance(start+1, end+1, s, length); */ int endptr = 1; while(start < endptr && endptr < length){ uint64_t left,right; if(start != 0){ left = s[endptr-1] - s[start-1]; right = s[length-1] - s[endptr-1] + s[start-1]; }else{ left = s[endptr-1]; right = s[length-1] - s[endptr-1]; } if( left > right ){ if( right > max ) max = right; start++; }else{ if( left > max ) max = left; endptr++; } }/* for(int i = 0; i < length-1; i++){ if(end <= i){ end = i+1; } uint64_t dst1 = distance(i+1,end+1,s,length); if(dst1 > dst){ end--; } while (end < length && (dst = distance(i+1,end+1,s,length)) >= max){ printf("while: i: %d, end: %d, dst: %"SCNu64 "\n",i,end, dst); max = dst; end++; } if(end == length) end--; printf("for: i: %d, end: %d, dst: %"SCNu64 "\n",i,end, dst); } */ /* BruteForce for(int i = 0; i<length-1; i++){ for(int j = i+1; j<length; j++){ dst = distance(i+1,j+1,s,length); if (dst > max) { max = dst; } } } */ /*while(start < length){ dst = distance(start+1,end+1,s,length); while (end < length && dst >= max){ max = dst; dst = distance(start+1, end+1, s, length); end++; } if(dst > max) max = dst; end--; start++; }*/ return max; }
the_stack_data/34512696.c
//EXERCICIO 5 #include <stdio.h> #include <string.h> int main() { char str1[] = "Oi"; char str2[] = "Bom dia"; int N = strlen(str2); strcpy(str1, str2); for (int cont = 0; cont < N; cont++) { strcat(str1[cont], str2[cont]); printf("%s", str1[cont]); } return 0; }
the_stack_data/634057.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strlcpy.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lgavalda <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/06 13:38:36 by lgavalda #+# #+# */ /* Updated: 2019/07/07 21:51:32 by lgavalda ### ########.fr */ /* */ /* ************************************************************************** */ unsigned int ft_strlcpy(char *dest, char *src, unsigned int size) { char *src_save; src_save = src; while (*src && size > 1) { *dest++ = *src++; size--; } if (size > 0) { *dest = '\0'; } size = 0; while (*src_save++) { size++; } return (size); }
the_stack_data/792860.c
/* Test program to: + Ignore a few signals + Block a few signals + Exec whatever the test runner asked for */ #include <stdlib.h> #include <signal.h> #include <unistd.h> int main(int argc, char *argv[]) { // Signals to ignore signal(SIGTTOU, SIG_IGN); // This one should still be in SigIgn (Tini touches it to ignore it, and should restore it) signal(SIGSEGV, SIG_IGN); // This one should still be in SigIgn (Tini shouldn't touch it) signal(SIGINT, SIG_IGN); // This one should still be in SigIgn (Tini should block it to forward it, and restore it) // Signals to block sigset_t set; sigemptyset(&set); sigaddset(&set, SIGTTIN); // This one should still be in SigIgn (Tini touches it to ignore it, and should restore it) sigaddset(&set, SIGILL); // This one should still be in SigIgn (Tini shouldn't touch it) sigaddset(&set, SIGTERM); // This one should still be in SigIgn (Tini should block it to forward it, and restore it) sigprocmask(SIG_BLOCK, &set, NULL); // Run whatever we were asked to run execvp(argv[1], argv+1); }
the_stack_data/354471.c
// RUN: c-index-test -index-file %s | FileCheck %s // rdar://10941790 // Check that we don't get stack overflow trying to index a huge number of // logical operators. // UBSan increses stack usage. // REQUIRES: not_ubsan // CHECK: [indexDeclaration]: kind: function | name: foo int foo(int x) { return x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x && x; }
the_stack_data/946806.c
#include <fcntl.h> #include <stdio.h> #include <sys/mman.h> #include <sys/stat.h> int main(int argc, char const *argv[]) { return 0; }
the_stack_data/6388149.c
#include <stdio.h> double IMC(double weight, double height){ return (weight)/(height*height); } char* descriptionByIMC(double imc){ if (imc < 17) return "Muito abaixo do peso"; if (imc < 18.5) return "Abaixo do peso"; if (imc < 25) return "Peso normal"; if (imc < 30) return "Acima do peso"; if (imc < 35) return "Obesidade I"; if (imc < 40) return "Obesidade II (severa)"; else return "Obesidade III (mórbida)"; } int main(){ double weight, height; printf("Peso (em kg): "); scanf(" %lf", &weight); printf("Altura (em m): "); scanf(" %lf", &height); double imc = IMC(weight, height); printf("IMC: %lf (%s)\n", imc, descriptionByIMC(imc)); return 0; }
the_stack_data/87637339.c
/* _ _ ** _ __ ___ ___ __| | ___ ___| | mod_ssl ** | '_ ` _ \ / _ \ / _` | / __/ __| | Apache Interface to OpenSSL ** | | | | | | (_) | (_| | \__ \__ \ | www.modssl.org ** |_| |_| |_|\___/ \__,_|___|___/___/_| ftp.modssl.org ** |_____| ** ssl_engine_compat.c ** Backward Compatibility */ /* ==================================================================== * Copyright (c) 1998-2003 Ralf S. Engelschall. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by * Ralf S. Engelschall <[email protected]> for use in the * mod_ssl project (http://www.modssl.org/)." * * 4. The names "mod_ssl" must not be used to endorse or promote * products derived from this software without prior written * permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "mod_ssl" * nor may "mod_ssl" appear in their names without prior * written permission of Ralf S. Engelschall. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by * Ralf S. Engelschall <[email protected]> for use in the * mod_ssl project (http://www.modssl.org/)." * * THIS SOFTWARE IS PROVIDED BY RALF S. ENGELSCHALL ``AS IS'' AND ANY * EXPRESSED 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 RALF S. ENGELSCHALL OR * HIS 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. * ==================================================================== */ /* ``Backward compatibility is for users who don't want to live on the bleeding edge.'' -- Unknown */ #ifdef SSL_COMPAT #include "mod_ssl.h" /* _________________________________________________________________ ** ** Backward Compatibility ** _________________________________________________________________ */ /* * The mapping of obsolete directives to official ones... */ static char *ssl_compat_RequireSSL(pool *, const char *, const char *, const char *); static char *ssl_compat_SSLSessionLockFile(pool *, const char *, const char *, const char *); static char *ssl_compat_SSLCacheDisable(pool *, const char *, const char *, const char *); static char *ssl_compat_SSLRequireCipher(pool *, const char *, const char *, const char *); static char *ssl_compat_SSLBanCipher(pool *, const char *, const char *, const char *); static char *ssl_compat_SSL_SessionDir(pool *, const char *, const char *, const char *); static char *ssl_compat_words2list(pool *, const char *); #define CRM_BEGIN /* nop */ #define CRM_ENTRY(what,action) { what, action }, #define CRM_END { NULL, NULL, NULL, NULL, NULL, NULL } #define CRM_CMD(cmd) cmd, NULL, NULL #define CRM_STR(str) NULL, str, NULL #define CRM_PAT(cmd) NULL, NULL, pat #define CRM_LOG(msg) msg, NULL, NULL #define CRM_SUB(new) NULL, new, NULL #define CRM_CAL(fct) NULL, NULL, fct static struct { char *cpCommand; char *cpSubstring; char *cpPattern; char *cpMessage; char *cpSubst; char *(*fpSubst)(pool *, const char *, const char *, const char *); } ssl_cmd_rewrite_map[] = { CRM_BEGIN /* * Apache-SSL 1.x & mod_ssl 2.0.x backward compatibility */ CRM_ENTRY( CRM_CMD("SSLEnable"), CRM_SUB("SSLEngine on") ) CRM_ENTRY( CRM_CMD("SSLDisable"), CRM_SUB("SSLEngine off") ) CRM_ENTRY( CRM_CMD("SSLLogFile"), CRM_SUB("SSLLog") ) CRM_ENTRY( CRM_CMD("SSLRequiredCiphers"), CRM_SUB("SSLCipherSuite") ) CRM_ENTRY( CRM_CMD("SSLRequireCipher"), CRM_CAL(ssl_compat_SSLRequireCipher) ) CRM_ENTRY( CRM_CMD("SSLBanCipher"), CRM_CAL(ssl_compat_SSLBanCipher) ) CRM_ENTRY( CRM_CMD("SSLFakeBasicAuth"), CRM_SUB("SSLOptions +FakeBasicAuth") ) CRM_ENTRY( CRM_CMD("SSLCacheServerPath"), CRM_LOG("Use SSLSessionCache instead") ) CRM_ENTRY( CRM_CMD("SSLCacheServerPort"), CRM_LOG("Use SSLSessionCache instead") ) /* * Apache-SSL 1.x backward compatibility */ CRM_ENTRY( CRM_CMD("SSLExportClientCertificates"), CRM_SUB("SSLOptions +ExportCertData") ) CRM_ENTRY( CRM_CMD("SSLCacheServerRunDir"), CRM_LOG("Not needed for mod_ssl") ) /* * Sioux 1.x backward compatibility */ CRM_ENTRY( CRM_CMD("SSL_CertFile"), CRM_SUB("SSLCertificateFile") ) CRM_ENTRY( CRM_CMD("SSL_KeyFile"), CRM_SUB("SSLCertificateKeyFile") ) CRM_ENTRY( CRM_CMD("SSL_CipherSuite"), CRM_SUB("SSLCipherSuite") ) CRM_ENTRY( CRM_CMD("SSL_X509VerifyDir"), CRM_SUB("SSLCACertificatePath") ) CRM_ENTRY( CRM_CMD("SSL_Log"), CRM_SUB("SSLLogFile") ) CRM_ENTRY( CRM_CMD("SSL_Connect"), CRM_SUB("SSLEngine") ) CRM_ENTRY( CRM_CMD("SSL_ClientAuth"), CRM_SUB("SSLVerifyClient") ) CRM_ENTRY( CRM_CMD("SSL_X509VerifyDepth"), CRM_SUB("SSLVerifyDepth") ) CRM_ENTRY( CRM_CMD("SSL_FetchKeyPhraseFrom"), CRM_LOG("Use SSLPassPhraseDialog instead") ) CRM_ENTRY( CRM_CMD("SSL_SessionDir"), CRM_CAL(ssl_compat_SSL_SessionDir) ) CRM_ENTRY( CRM_CMD("SSL_Require"), CRM_LOG("Use SSLRequire instead (Syntax!)")) CRM_ENTRY( CRM_CMD("SSL_CertFileType"), CRM_LOG("Not supported by mod_ssl") ) CRM_ENTRY( CRM_CMD("SSL_KeyFileType"), CRM_LOG("Not supported by mod_ssl") ) CRM_ENTRY( CRM_CMD("SSL_X509VerifyPolicy"), CRM_LOG("Not supported by mod_ssl") ) CRM_ENTRY( CRM_CMD("SSL_LogX509Attributes"), CRM_LOG("Not supported by mod_ssl") ) /* * Stronghold 2.x backward compatibility */ CRM_ENTRY( CRM_CMD("StrongholdAccelerator"), CRM_LOG("Not supported by mod_ssl") ) CRM_ENTRY( CRM_CMD("StrongholdKey"), CRM_LOG("Not supported by mod_ssl") ) CRM_ENTRY( CRM_CMD("StrongholdLicenseFile"), CRM_LOG("Not supported by mod_ssl") ) CRM_ENTRY( CRM_CMD("SSLFlag"), CRM_SUB("SSLEngine") ) CRM_ENTRY( CRM_CMD("SSLClientCAfile"), CRM_SUB("SSLCACertificateFile") ) CRM_ENTRY( CRM_CMD("SSLSessionLockFile"), CRM_CAL(ssl_compat_SSLSessionLockFile) ) CRM_ENTRY( CRM_CMD("SSLCacheDisable"), CRM_CAL(ssl_compat_SSLCacheDisable) ) CRM_ENTRY( CRM_CMD("RequireSSL"), CRM_CAL(ssl_compat_RequireSSL) ) CRM_ENTRY( CRM_CMD("SSLCipherList"), CRM_SUB("SSLCipherSuite") ) CRM_ENTRY( CRM_CMD("SSLErrorFile"), CRM_LOG("Not needed for mod_ssl") ) CRM_ENTRY( CRM_CMD("SSLRoot"), CRM_LOG("Not supported by mod_ssl") ) CRM_ENTRY( CRM_CMD("SSL_CertificateLogDir"), CRM_LOG("Not supported by mod_ssl") ) CRM_ENTRY( CRM_CMD("AuthCertDir"), CRM_LOG("Not supported by mod_ssl") ) CRM_ENTRY( CRM_CMD("SSL_Group"), CRM_LOG("Not supported by mod_ssl") ) #ifndef SSL_EXPERIMENTAL_PROXY CRM_ENTRY( CRM_CMD("SSLProxyMachineCertPath"), CRM_LOG("Not supported by mod_ssl") ) CRM_ENTRY( CRM_CMD("SSLProxyMachineCertFile"), CRM_LOG("Not supported by mod_ssl") ) CRM_ENTRY( CRM_CMD("SSLProxyCACertificatePath"), CRM_LOG("Not supported by mod_ssl") ) CRM_ENTRY( CRM_CMD("SSLProxyCACertificateFile"), CRM_LOG("Not supported by mod_ssl") ) CRM_ENTRY( CRM_CMD("SSLProxyVerifyDepth"), CRM_LOG("Not supported by mod_ssl") ) CRM_ENTRY( CRM_CMD("SSLProxyCipherList"), CRM_LOG("Not supported by mod_ssl") ) #else CRM_ENTRY( CRM_CMD("SSLProxyCipherList"), CRM_SUB("SSLProxyCipherSuite") ) #endif CRM_END }; static char *ssl_compat_RequireSSL( pool *p, const char *oline, const char *cmd, const char *args) { char *cp; for (cp = (char *)args; ap_isspace(*cp); cp++) ; if (strcEQ(cp, "on")) return "SSLRequireSSL"; return ""; } static char *ssl_compat_SSLSessionLockFile( pool *p, const char *oline, const char *cmd, const char *args) { char *cp; for (cp = (char *)args; ap_isspace(*cp); cp++) ; return ap_pstrcat(p, "SSLMutex file:", cp, NULL); } static char *ssl_compat_SSLCacheDisable( pool *p, const char *oline, const char *cmd, const char *args) { char *cp; for (cp = (char *)args; ap_isspace(*cp); cp++) ; if (strcEQ(cp, "on")) return "SSLSessionCache none"; return ""; } static char *ssl_compat_SSLRequireCipher(pool *p, const char *oline, const char *cmd, const char *args) { return ap_pstrcat(p, "SSLRequire %{SSL_CIPHER} in {", ssl_compat_words2list(p, args), "}", NULL); } static char *ssl_compat_SSLBanCipher(pool *p, const char *oline, const char *cmd, const char *args) { return ap_pstrcat(p, "SSLRequire not (%{SSL_CIPHER} in {", ssl_compat_words2list(p, args), "})", NULL); } static char *ssl_compat_SSL_SessionDir( pool *p, const char *oline, const char *cmd, const char *args) { char *cp; for (cp = (char *)args; ap_isspace(*cp); cp++) ; return ap_pstrcat(p, "SSLSessionCache dir:", cp, NULL); } static char *ssl_compat_words2list(pool *p, const char *oline) { char *line; char *cpB; char *cpE; char *cpI; char *cpO; char n; /* * Step 1: Determine borders */ cpB = (char *)oline; while (*cpB == ' ' || *cpB == '\t') cpB++; cpE = cpB+strlen(cpB); while (cpE > cpB && (*(cpE-1) == ' ' || *(cpE-1) == '\t')) cpE--; /* * Step 2: Determine final size and allocate buffer */ for (cpI = cpB, n = 1; cpI < cpE; cpI++) if ((*cpI == ' ' || *cpI == '\t') && (cpI > cpB && *(cpI-1) != ' ' && *(cpI-1) != '\t')) n++; line = ap_palloc(p, (cpE-cpB)+(n*2)+n+1); cpI = cpB; cpO = line; while (cpI < cpE) { if ( (*cpI != ' ' && *cpI != '\t') && ( cpI == cpB || ( cpI > cpB && (*(cpI-1) == ' ' || *(cpI-1) == '\t')))) { *cpO++ = '"'; *cpO++ = *cpI++; } else if ( (*cpI == ' ' || *cpI == '\t') && ( cpI > cpB && (*(cpI-1) != ' ' && *(cpI-1) != '\t'))) { *cpO++ = '"'; *cpO++ = ','; *cpO++ = *cpI++; } else { *cpO++ = *cpI++; } } if (cpI > cpB && (*(cpI-1) != ' ' && *(cpI-1) != '\t')) *cpO++ = '"'; *cpO++ = NUL; return line; } char *ssl_compat_directive(server_rec *s, pool *p, const char *oline) { int i; char *line; char *cp; char caCmd[1024]; char *cpArgs; int match; /* * Skip comment lines */ cp = (char *)oline; while ((*cp == ' ' || *cp == '\t' || *cp == '\n') && (*cp != NUL)) cp++; if (*cp == '#' || *cp == NUL) return NULL; /* * Extract directive name */ cp = (char *)oline; for (i = 0; *cp != ' ' && *cp != '\t' && *cp != NUL && i < sizeof(caCmd) - 1; ) caCmd[i++] = *cp++; caCmd[i] = NUL; cpArgs = cp; /* * Apply rewriting map */ line = NULL; for (i = 0; !(ssl_cmd_rewrite_map[i].cpCommand == NULL && ssl_cmd_rewrite_map[i].cpPattern == NULL ); i++) { /* * Matching */ match = FALSE; if (ssl_cmd_rewrite_map[i].cpCommand != NULL) { if (strcEQ(ssl_cmd_rewrite_map[i].cpCommand, caCmd)) match = TRUE; } else if (ssl_cmd_rewrite_map[i].cpSubstring != NULL) { if (strstr(oline, ssl_cmd_rewrite_map[i].cpSubstring) != NULL) match = TRUE; } else if (ssl_cmd_rewrite_map[i].cpPattern != NULL) { if (ap_fnmatch(ssl_cmd_rewrite_map[i].cpPattern, oline, 0)) match = TRUE; } /* * Action Processing */ if (match) { if (ssl_cmd_rewrite_map[i].cpMessage != NULL) { ap_log_error(APLOG_MARK, APLOG_WARNING|APLOG_NOERRNO, s, "mod_ssl:Compat: OBSOLETE '%s' => %s", oline, ssl_cmd_rewrite_map[i].cpMessage); line = ""; break; } else if (ssl_cmd_rewrite_map[i].cpSubst != NULL) { if (ssl_cmd_rewrite_map[i].cpCommand != NULL) line = ap_pstrcat(p, ssl_cmd_rewrite_map[i].cpSubst, cpArgs, NULL); else if (ssl_cmd_rewrite_map[i].cpSubstring != NULL) line = ssl_util_ptxtsub(p, oline, ssl_cmd_rewrite_map[i].cpSubstring, ssl_cmd_rewrite_map[i].cpSubst); else line = ssl_cmd_rewrite_map[i].cpSubst; break; } else if (ssl_cmd_rewrite_map[i].fpSubst != NULL) { line = ((char *(*)(pool *, const char *, const char *, const char *)) (ssl_cmd_rewrite_map[i].fpSubst))(p, oline, caCmd, cpArgs); break; } } } if (line != NULL && line[0] != NUL) ap_log_error(APLOG_MARK, APLOG_INFO|APLOG_NOERRNO, s, "mod_ssl:Compat: MAPPED '%s' => '%s'", oline, line); return line; } /* * The mapping of obsolete environment variables to official ones... */ #define VRM_BEGIN /* nop */ #define VRM_ENTRY(var,action) { var, action }, #define VRM_END { NULL, NULL, NULL } #define VRM_VAR(old) old #define VRM_SUB(new) new, NULL #define VRM_LOG(msg) NULL, msg static struct { char *cpOld; char *cpNew; char *cpMsg; } ssl_var_rewrite_map[] = { VRM_BEGIN /* * Apache-SSL 1.x, mod_ssl 2.0.x, Sioux 1.x * and Stronghold 2.x backward compatibility */ VRM_ENTRY( VRM_VAR("SSL_PROTOCOL_VERSION"), VRM_SUB("SSL_PROTOCOL") ) VRM_ENTRY( VRM_VAR("SSLEAY_VERSION"), VRM_SUB("SSL_VERSION_LIBRARY") ) VRM_ENTRY( VRM_VAR("HTTPS_SECRETKEYSIZE"), VRM_SUB("SSL_CIPHER_USEKEYSIZE") ) VRM_ENTRY( VRM_VAR("HTTPS_KEYSIZE"), VRM_SUB("SSL_CIPHER_ALGKEYSIZE") ) VRM_ENTRY( VRM_VAR("HTTPS_CIPHER"), VRM_SUB("SSL_CIPHER") ) VRM_ENTRY( VRM_VAR("HTTPS_EXPORT"), VRM_SUB("SSL_CIPHER_EXPORT") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_KEY_SIZE"), VRM_SUB("SSL_CIPHER_ALGKEYSIZE") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_CERTIFICATE"), VRM_SUB("SSL_SERVER_CERT") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_CERT_START"), VRM_SUB("SSL_SERVER_V_START") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_CERT_END"), VRM_SUB("SSL_SERVER_V_END") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_CERT_SERIAL"), VRM_SUB("SSL_SERVER_M_SERIAL") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_SIGNATURE_ALGORITHM"),VRM_SUB("SSL_SERVER_A_SIG") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_DN"), VRM_SUB("SSL_SERVER_S_DN") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_CN"), VRM_SUB("SSL_SERVER_S_DN_CN") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_EMAIL"), VRM_SUB("SSL_SERVER_S_DN_Email") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_O"), VRM_SUB("SSL_SERVER_S_DN_O") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_OU"), VRM_SUB("SSL_SERVER_S_DN_OU") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_C"), VRM_SUB("SSL_SERVER_S_DN_C") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_SP"), VRM_SUB("SSL_SERVER_S_DN_SP") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_L"), VRM_SUB("SSL_SERVER_S_DN_L") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_IDN"), VRM_SUB("SSL_SERVER_I_DN") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_ICN"), VRM_SUB("SSL_SERVER_I_DN_CN") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_IEMAIL"), VRM_SUB("SSL_SERVER_I_DN_Email") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_IO"), VRM_SUB("SSL_SERVER_I_DN_O") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_IOU"), VRM_SUB("SSL_SERVER_I_DN_OU") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_IC"), VRM_SUB("SSL_SERVER_I_DN_C") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_ISP"), VRM_SUB("SSL_SERVER_I_DN_SP") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_IL"), VRM_SUB("SSL_SERVER_I_DN_L") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_CERTIFICATE"), VRM_SUB("SSL_CLIENT_CERT") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_CERT_START"), VRM_SUB("SSL_CLIENT_V_START") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_CERT_END"), VRM_SUB("SSL_CLIENT_V_END") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_CERT_SERIAL"), VRM_SUB("SSL_CLIENT_M_SERIAL") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_SIGNATURE_ALGORITHM"),VRM_SUB("SSL_CLIENT_A_SIG") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_DN"), VRM_SUB("SSL_CLIENT_S_DN") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_CN"), VRM_SUB("SSL_CLIENT_S_DN_CN") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_EMAIL"), VRM_SUB("SSL_CLIENT_S_DN_Email") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_O"), VRM_SUB("SSL_CLIENT_S_DN_O") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_OU"), VRM_SUB("SSL_CLIENT_S_DN_OU") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_C"), VRM_SUB("SSL_CLIENT_S_DN_C") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_SP"), VRM_SUB("SSL_CLIENT_S_DN_SP") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_L"), VRM_SUB("SSL_CLIENT_S_DN_L") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_IDN"), VRM_SUB("SSL_CLIENT_I_DN") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_ICN"), VRM_SUB("SSL_CLIENT_I_DN_CN") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_IEMAIL"), VRM_SUB("SSL_CLIENT_I_DN_Email") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_IO"), VRM_SUB("SSL_CLIENT_I_DN_O") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_IOU"), VRM_SUB("SSL_CLIENT_I_DN_OU") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_IC"), VRM_SUB("SSL_CLIENT_I_DN_C") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_ISP"), VRM_SUB("SSL_CLIENT_I_DN_SP") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_IL"), VRM_SUB("SSL_CLIENT_I_DN_L") ) VRM_ENTRY( VRM_VAR("SSL_EXPORT"), VRM_SUB("SSL_CIPHER_EXPORT") ) VRM_ENTRY( VRM_VAR("SSL_KEYSIZE"), VRM_SUB("SSL_CIPHER_ALGKEYSIZE") ) VRM_ENTRY( VRM_VAR("SSL_SECRETKEYSIZE"), VRM_SUB("SSL_CIPHER_USEKEYSIZE") ) VRM_ENTRY( VRM_VAR("SSL_SSLEAY_VERSION"), VRM_SUB("SSL_VERSION_LIBRARY") ) VRM_ENTRY( VRM_VAR("SSL_STRONG_CRYPTO"), VRM_LOG("Not supported by mod_ssl") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_KEY_EXP"), VRM_LOG("Not supported by mod_ssl") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_KEY_SIZE"), VRM_LOG("Not supported by mod_ssl") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_KEY_ALGORITHM"), VRM_LOG("Not supported by mod_ssl") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_SESSIONDIR"), VRM_LOG("Not supported by mod_ssl") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_CERTIFICATELOGDIR"), VRM_LOG("Not supported by mod_ssl") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_CERTFILE"), VRM_LOG("Not supported by mod_ssl") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_KEYFILE"), VRM_LOG("Not supported by mod_ssl") ) VRM_ENTRY( VRM_VAR("SSL_SERVER_KEYFILETYPE"), VRM_LOG("Not supported by mod_ssl") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_KEY_EXP"), VRM_LOG("Not supported by mod_ssl") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_KEY_ALGORITHM"), VRM_LOG("Not supported by mod_ssl") ) VRM_ENTRY( VRM_VAR("SSL_CLIENT_KEY_SIZE"), VRM_LOG("Not supported by mod_ssl") ) VRM_END }; void ssl_compat_variables(request_rec *r) { char *cpOld; char *cpNew; char *cpMsg; char *cpVal; int i; for (i = 0; ssl_var_rewrite_map[i].cpOld != NULL; i++) { cpOld = ssl_var_rewrite_map[i].cpOld; cpMsg = ssl_var_rewrite_map[i].cpMsg; cpNew = ssl_var_rewrite_map[i].cpNew; if (cpNew != NULL) { cpVal = ssl_var_lookup(r->pool, r->server, r->connection, r, cpNew); if (!strIsEmpty(cpVal)) ap_table_set(r->subprocess_env, cpOld, cpVal); } else if (cpMsg != NULL) { #ifdef SSL_VENDOR /* * something that isn't provided by mod_ssl, so at least * let vendor extensions provide a reasonable value first. */ cpVal = NULL; ap_hook_use("ap::mod_ssl::vendor::compat_variables_lookup", AP_HOOK_SIG3(ptr,ptr,ptr), AP_HOOK_DECLINE(NULL), &cpVal, r, cpOld); if (cpVal != NULL) { ap_table_set(r->subprocess_env, cpOld, cpVal); continue; } #endif /* * we cannot print a message, so we set at least * the variables content to the compat message */ ap_table_set(r->subprocess_env, cpOld, cpMsg); } } return; } #endif /* SSL_COMPAT */
the_stack_data/133165.c
#include<stdio.h> int main() { int a[50],n,i,j,pr=0,prime[50],t=0; printf("how many numbers you want to enter"); scanf("%d",&n); printf("enter the numbers"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=0;i<n;i++) { pr=0; for(j=2;j<a[i];j++) { if(a[i]%j==0) { pr=1; break; } } if(pr==0) { prime[t]=a[i]; t++; } } printf("prime numbers are\n"); for(i=0;i<t;i++) printf("%d\n",prime[i]); }
the_stack_data/114623.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> void *hola(void *arg) { char *msg = "Hola"; int i; for ( i = 0 ; i < strlen (msg) ; i++ ) { printf (" %c", msg[i]); fflush (stdout ); usleep (1000000) ; } return NULL; } void *mundo(void *arg ) { char *msg = " mundo "; int i; for ( i = 0 ; i < strlen (msg) ; i++ ) { printf (" %c", msg[i]); fflush (stdout ); usleep (1000000) ; } return NULL; } int main(int argc , char *argv []) { pthread_t h1; pthread_t h2; pthread_create(&h1, NULL , hola , NULL); pthread_create(&h2, NULL , mundo , NULL); printf ("Fin\n"); }
the_stack_data/150141276.c
int def(void); void use(int); static void foo(int a, int b) { int c; if (a) c = 1; else c = def(); if (c) use(1); else use(0); } /* * check-name: kill-phi-ttsbb * check-description: * Verify if OP_PHI usage is adjusted after successful try_to_simplify_bb() * check-command: test-linearize $file * check-output-ignore * * check-output-excludes: phi\\. * check-output-excludes: phisrc\\. */
the_stack_data/393671.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2009-2020 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/>. */ #include <stdlib.h> #include <unistd.h> short hglob = 1; short glob = 92; void bar() { if (glob == 0) exit(1); } int commonfun() { bar(); return 0; } /* from hello */ int hello(int x) { x *= 2; return x + 45; } static void hello_loop (void) { } int main() { int tmpx; alarm (240); bar(); tmpx = hello(glob); commonfun(); glob = tmpx; commonfun(); while (1) { hello_loop (); usleep (20); } }
the_stack_data/179830895.c
// RUN: %check %s void *malloc(unsigned long); main() { int *p = malloc(3 * sizeof(int)); // CHECK: !/warn.*assignment.*malloc/ char *a = malloc(sizeof(*p)); // CHECK: warning: malloc assignment with different types 'char *' and 'int *' char *b = malloc(sizeof(*b)); // CHECK: !/warn.*assignment.*malloc/ void *v = malloc(sizeof(int)); // CHECK: !/warn.*assignment.*malloc/ }
the_stack_data/1063587.c
#include <assert.h> #include <stddef.h> #include <stdio.h> #include <string.h> int main(const int argc, const char* const argv[]) { // Getting away with no error checking throughout because CodeEval makes some // strong guarantees about our runtime environment. No need to pay when we're // being benchmarked. Don't forget to define NDEBUG prior to submitting! assert(argc >= 2 && "Expecting at least one command-line argument."); static char stdoutBuffer[512] = ""; // Turn on full output buffering for stdout. setvbuf(stdout, stdoutBuffer, _IOFBF, sizeof stdoutBuffer); FILE* inputStream = fopen(argv[1], "r"); assert(inputStream && "Failed to open input stream."); for(char lineBuffer[512] = ""; fgets(lineBuffer, sizeof lineBuffer, inputStream);) { // Indices start after the pipe separator. char* c = strchr(lineBuffer, '|'); assert(c); // Eat leading whitespace. for(++c; *c && *c == ' '; ++c); // Reuse the input buffer for output. char* result = c, * write = c; for(size_t index = 0;; ++c) { if(*c >= '0' && *c <= '9') index = (index * 10) + (*c - '0'); // Term boundary. else if(*c == ' ' || !*c) { // Supplied indices are 1-based. assert(index); *write++ = lineBuffer[index - 1]; index = 0; if(!*c) { *write = '\0'; break; } } } puts(result); } // The CRT takes care of cleanup. }
the_stack_data/23576356.c
extern void abort(void); unsigned int c = 0x80000000; int main() { if (c - 0x80000000L < 0) abort(); return 0; }
the_stack_data/178264435.c
void nop() { return; } int main(void) { nop(); return 42; }
the_stack_data/463570.c
/* { dg-lto-do run } */ int first = 0; void abort (void); void c (void); void b (void); int second = 0; void callmealias (void) { if (!first || !second) abort (); } void callmefirst (void) { if (first) abort(); first = 1; } void callmesecond (void) { if (!first) abort(); if (second) abort(); second = 1; } int main() { c(); b(); return 0; }
the_stack_data/24598.c
//Lista de adj #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <stdbool.h> typedef struct node *link; static int count, aux[1000]; struct node{ int v; link prox; int c; }; typedef struct{ int v; int w; } Edge; Edge EDGE(int v, int w){ Edge EDGE; EDGE.v = v; EDGE.w = w; return EDGE; }; typedef struct graph *Graph; struct graph{ int V; int E; link *adj; }; link NEW(int v, link prox, int c){ link m = malloc(sizeof*m); m->v=v; m->prox=prox; m-> c = c; return m; } Graph GRAPHinit(int v){ Graph G=malloc(sizeof(*G)); G->V=v; G->E=0; G->adj=malloc(v*sizeof(link)); for(int i=0; i<v;i++){ G->adj[i] = NULL; } return G; } void GRAPHInsertE(Graph G, Edge e, int c){ int v = e.v; int w=e.w; G->adj[v] = NEW(w,G->adj[v],c); G->adj[w]= NEW(v,G->adj[w],c); G->E++; } int GRAPHEdges(Edge a[], Graph G){ int v,E=0; link t; for(v=0;v<G->V;v++){ for(t=G->adj[v]; t!=NULL; t=t->prox){ if(v<t->v){ a[E++]=EDGE(v, t->v); } } } return E; } //busca em profundidade //recursao ou pilha //Edge e é a aresta que queremos começar a percorrer o grafo void dfsR(Graph G, Edge e){ int t, w=e.w; link l; aux[w] = count++; for(l=G->adj[w]; l!=NULL; l=l->prox){ t = l->v; if(aux[t]==-1){ dfsR(G,EDGE(w,t)); } } } //versao ingenua void GRAPHcptD1(Graph G, int s, int *pa, int *dist){ bool mature[1000]; for(int v = 0; v < G->V; v++){ pa[v]=-1; mature[v]=false; dist[v]=INT_MAX; } pa[s] = 1; dist[s]=0; while(true){ int min = INT_MAX; int y; for(int z = 0; z < G->V; z++){ if(mature[z]) continue; if(dist[z] < min){ min = dist[z]; y = z; } } if(min == INT_MAX) break; for(link a = G->adj[y]; a!=NULL; a=a->prox){ if(mature[a->v]) continue; if(dist[y] + a->c < dist[a->v]){ dist[a->v] = dist[y] + a->c; pa[a->v] = y; } } mature[y] = true; } } int main(){ int N,M,S,T,B; scanf("%d %d", &N, &M); Graph PONTES = GRAPHinit(N+2); int *pa = malloc(sizeof(int)*N+2); int *dist = malloc(sizeof(int)*N+2); for(int i = 0; i<M; i++){ scanf("%d %d %d", &S, &T, &B); GRAPHInsertE(PONTES, EDGE(S, T), B); } GRAPHcptD1(PONTES, 0, pa, dist); printf("%d\n", dist[N+1]); return 0; }
the_stack_data/45450046.c
#ifdef STM32F0xx #include "stm32f0xx_hal_crc_ex.c" #elif STM32F3xx #include "stm32f3xx_hal_crc_ex.c" #elif STM32F7xx #include "stm32f7xx_hal_crc_ex.c" #elif STM32G0xx #include "stm32g0xx_hal_crc_ex.c" #elif STM32G4xx #include "stm32g4xx_hal_crc_ex.c" #elif STM32H7xx #include "stm32h7xx_hal_crc_ex.c" #elif STM32L0xx #include "stm32l0xx_hal_crc_ex.c" #elif STM32L4xx #include "stm32l4xx_hal_crc_ex.c" #elif STM32L5xx #include "stm32l5xx_hal_crc_ex.c" #elif STM32MP1xx #include "stm32mp1xx_hal_crc_ex.c" #elif STM32WBxx #include "stm32wbxx_hal_crc_ex.c" #endif
the_stack_data/25610.c
/* These stubs are provided so that autoconf can check library * versions using C symbols only */ extern void libvamphostsdk_v_2_9_present(void) { } extern void libvamphostsdk_v_2_8_present(void) { } extern void libvamphostsdk_v_2_7_1_present(void) { } extern void libvamphostsdk_v_2_7_present(void) { } extern void libvamphostsdk_v_2_6_present(void) { } extern void libvamphostsdk_v_2_5_present(void) { } extern void libvamphostsdk_v_2_4_present(void) { } extern void libvamphostsdk_v_2_3_1_present(void) { } extern void libvamphostsdk_v_2_3_present(void) { } extern void libvamphostsdk_v_2_2_1_present(void) { } extern void libvamphostsdk_v_2_2_present(void) { } extern void libvamphostsdk_v_2_1_present(void) { } extern void libvamphostsdk_v_2_0_present(void) { }
the_stack_data/787246.c
typedef signed char __int8_t; typedef unsigned char __uint8_t; typedef short int __int16_t; typedef short unsigned int __uint16_t; typedef long int __int32_t; typedef long unsigned int __uint32_t; typedef long long int __int64_t; typedef long long unsigned int __uint64_t; typedef signed char __int_least8_t; typedef unsigned char __uint_least8_t; typedef short int __int_least16_t; typedef short unsigned int __uint_least16_t; typedef long int __int_least32_t; typedef long unsigned int __uint_least32_t; typedef long long int __int_least64_t; typedef long long unsigned int __uint_least64_t; typedef int __intptr_t; typedef unsigned int __uintptr_t; typedef unsigned int size_t; typedef int ptrdiff_t; typedef unsigned int wchar_t; typedef struct { long long __max_align_ll __attribute__((__aligned__(__alignof__(long long)))); long double __max_align_ld __attribute__((__aligned__(__alignof__(long double)))); } max_align_t; typedef __builtin_va_list __gnuc_va_list; typedef __gnuc_va_list va_list; typedef int _LOCK_T; typedef int _LOCK_RECURSIVE_T; typedef long __blkcnt_t; typedef long __blksize_t; typedef __uint64_t __fsblkcnt_t; typedef __uint32_t __fsfilcnt_t; typedef long _off_t; typedef int __pid_t; typedef short __dev_t; typedef unsigned short __uid_t; typedef unsigned short __gid_t; typedef __uint32_t __id_t; typedef unsigned short __ino_t; typedef __uint32_t __mode_t; __extension__ typedef long long _off64_t; typedef _off_t __off_t; typedef _off64_t __loff_t; typedef long __key_t; typedef long _fpos_t; typedef unsigned int __size_t; typedef signed int _ssize_t; typedef _ssize_t __ssize_t; typedef unsigned int wint_t; typedef struct { int __count; union { wint_t __wch; unsigned char __wchb[4]; } __value; } _mbstate_t; typedef _LOCK_RECURSIVE_T _flock_t; typedef void *_iconv_t; typedef unsigned long __clock_t; typedef long __time_t; typedef unsigned long __clockid_t; typedef unsigned long __timer_t; typedef __uint8_t __sa_family_t; typedef __uint32_t __socklen_t; typedef unsigned short __nlink_t; typedef long __suseconds_t; typedef unsigned long __useconds_t; typedef __builtin_va_list __va_list; typedef unsigned long __ULong; struct _reent; struct __locale_t; struct _Bigint { struct _Bigint *_next; int _k, _maxwds, _sign, _wds; __ULong _x[1]; }; struct __tm { int __tm_sec; int __tm_min; int __tm_hour; int __tm_mday; int __tm_mon; int __tm_year; int __tm_wday; int __tm_yday; int __tm_isdst; }; struct _on_exit_args { void * _fnargs[32]; void * _dso_handle[32]; __ULong _fntypes; __ULong _is_cxa; }; struct _atexit { struct _atexit *_next; int _ind; void (*_fns[32])(void); struct _on_exit_args _on_exit_args; }; struct __sbuf { unsigned char *_base; int _size; }; struct __sFILE { unsigned char *_p; int _r; int _w; short _flags; short _file; struct __sbuf _bf; int _lbfsize; void * _cookie; int (* _read) (struct _reent *, void *, char *, int) ; int (* _write) (struct _reent *, void *, const char *, int) ; _fpos_t (* _seek) (struct _reent *, void *, _fpos_t, int); int (* _close) (struct _reent *, void *); struct __sbuf _ub; unsigned char *_up; int _ur; unsigned char _ubuf[3]; unsigned char _nbuf[1]; struct __sbuf _lb; int _blksize; _off_t _offset; struct _reent *_data; _flock_t _lock; _mbstate_t _mbstate; int _flags2; }; typedef struct __sFILE __FILE; struct _glue { struct _glue *_next; int _niobs; __FILE *_iobs; }; struct _rand48 { unsigned short _seed[3]; unsigned short _mult[3]; unsigned short _add; }; struct _reent { int _errno; __FILE *_stdin, *_stdout, *_stderr; int _inc; char _emergency[25]; int _unspecified_locale_info; struct __locale_t *_locale; int __sdidinit; void (* __cleanup) (struct _reent *); struct _Bigint *_result; int _result_k; struct _Bigint *_p5s; struct _Bigint **_freelist; int _cvtlen; char *_cvtbuf; union { struct { unsigned int _unused_rand; char * _strtok_last; char _asctime_buf[26]; struct __tm _localtime_buf; int _gamma_signgam; __extension__ unsigned long long _rand_next; struct _rand48 _r48; _mbstate_t _mblen_state; _mbstate_t _mbtowc_state; _mbstate_t _wctomb_state; char _l64a_buf[8]; char _signal_buf[24]; int _getdate_err; _mbstate_t _mbrlen_state; _mbstate_t _mbrtowc_state; _mbstate_t _mbsrtowcs_state; _mbstate_t _wcrtomb_state; _mbstate_t _wcsrtombs_state; int _h_errno; } _reent; struct { unsigned char * _nextf[30]; unsigned int _nmalloc[30]; } _unused; } _new; struct _atexit *_atexit; struct _atexit _atexit0; void (**(_sig_func))(int); struct _glue __sglue; __FILE __sf[3]; }; extern struct _reent *_impure_ptr ; extern struct _reent *const _global_impure_ptr ; void _reclaim_reent (struct _reent *); typedef __uint8_t u_int8_t; typedef __uint16_t u_int16_t; typedef __uint32_t u_int32_t; typedef __uint64_t u_int64_t; typedef int register_t; typedef __int8_t int8_t ; typedef __uint8_t uint8_t ; typedef __int16_t int16_t ; typedef __uint16_t uint16_t ; typedef __int32_t int32_t ; typedef __uint32_t uint32_t ; typedef __int64_t int64_t ; typedef __uint64_t uint64_t ; typedef __intptr_t intptr_t; typedef __uintptr_t uintptr_t; typedef unsigned long __sigset_t; typedef __suseconds_t suseconds_t; typedef long time_t; struct timeval { time_t tv_sec; suseconds_t tv_usec; }; struct timespec { time_t tv_sec; long tv_nsec; }; struct itimerspec { struct timespec it_interval; struct timespec it_value; }; typedef __sigset_t sigset_t; typedef unsigned long fd_mask; typedef struct _types_fd_set { fd_mask fds_bits[(((64)+(((sizeof (fd_mask) * 8))-1))/((sizeof (fd_mask) * 8)))]; } _types_fd_set; int select (int __n, _types_fd_set *__readfds, _types_fd_set *__writefds, _types_fd_set *__exceptfds, struct timeval *__timeout) ; int pselect (int __n, _types_fd_set *__readfds, _types_fd_set *__writefds, _types_fd_set *__exceptfds, const struct timespec *__timeout, const sigset_t *__set) ; typedef __uint32_t in_addr_t; typedef __uint16_t in_port_t; typedef unsigned char u_char; typedef unsigned short u_short; typedef unsigned int u_int; typedef unsigned long u_long; typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long ulong; typedef __blkcnt_t blkcnt_t; typedef __blksize_t blksize_t; typedef unsigned long clock_t; typedef long daddr_t; typedef char * caddr_t; typedef __fsblkcnt_t fsblkcnt_t; typedef __fsfilcnt_t fsfilcnt_t; typedef __id_t id_t; typedef __ino_t ino_t; typedef __off_t off_t; typedef __dev_t dev_t; typedef __uid_t uid_t; typedef __gid_t gid_t; typedef __pid_t pid_t; typedef __key_t key_t; typedef _ssize_t ssize_t; typedef __mode_t mode_t; typedef __nlink_t nlink_t; typedef __clockid_t clockid_t; typedef __timer_t timer_t; typedef __useconds_t useconds_t; typedef __int64_t sbintime_t; typedef __FILE FILE; typedef _fpos_t fpos_t; char * ctermid (char *); FILE * tmpfile (void); char * tmpnam (char *); char * tempnam (const char *, const char *); int fclose (FILE *); int fflush (FILE *); FILE * freopen (const char *restrict, const char *restrict, FILE *restrict); void setbuf (FILE *restrict, char *restrict); int setvbuf (FILE *restrict, char *restrict, int, size_t); int fprintf (FILE *restrict, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; int fscanf (FILE *restrict, const char *restrict, ...) __attribute__ ((__format__ (__scanf__, 2, 3))) ; int printf (const char *restrict, ...) __attribute__ ((__format__ (__printf__, 1, 2))) ; int scanf (const char *restrict, ...) __attribute__ ((__format__ (__scanf__, 1, 2))) ; int sscanf (const char *restrict, const char *restrict, ...) __attribute__ ((__format__ (__scanf__, 2, 3))) ; int vfprintf (FILE *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int vprintf (const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 1, 0))) ; int vsprintf (char *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int fgetc (FILE *); char * fgets (char *restrict, int, FILE *restrict); int fputc (int, FILE *); int fputs (const char *restrict, FILE *restrict); int getc (FILE *); int getchar (void); char * gets (char *); int putc (int, FILE *); int putchar (int); int puts (const char *); int ungetc (int, FILE *); size_t fread (void * restrict, size_t _size, size_t _n, FILE *restrict); size_t fwrite (const void * restrict , size_t _size, size_t _n, FILE *); int fgetpos (FILE *restrict, fpos_t *restrict); int fseek (FILE *, long, int); int fsetpos (FILE *, const fpos_t *); long ftell ( FILE *); void rewind (FILE *); void clearerr (FILE *); int feof (FILE *); int ferror (FILE *); void perror (const char *); FILE * fopen (const char *restrict _name, const char *restrict _type); int sprintf (char *restrict, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; int remove (const char *); int rename (const char *, const char *); int fseeko (FILE *, off_t, int); off_t ftello ( FILE *); int snprintf (char *restrict, size_t, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int vsnprintf (char *restrict, size_t, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int vfscanf (FILE *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 2, 0))) ; int vscanf (const char *, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 1, 0))) ; int vsscanf (const char *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 2, 0))) ; int asiprintf (char **, const char *, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; char * asniprintf (char *, size_t *, const char *, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; char * asnprintf (char *restrict, size_t *restrict, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int diprintf (int, const char *, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; int fiprintf (FILE *, const char *, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; int fiscanf (FILE *, const char *, ...) __attribute__ ((__format__ (__scanf__, 2, 3))) ; int iprintf (const char *, ...) __attribute__ ((__format__ (__printf__, 1, 2))) ; int iscanf (const char *, ...) __attribute__ ((__format__ (__scanf__, 1, 2))) ; int siprintf (char *, const char *, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; int siscanf (const char *, const char *, ...) __attribute__ ((__format__ (__scanf__, 2, 3))) ; int sniprintf (char *, size_t, const char *, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int vasiprintf (char **, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; char * vasniprintf (char *, size_t *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; char * vasnprintf (char *, size_t *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int vdiprintf (int, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int vfiprintf (FILE *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int vfiscanf (FILE *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 2, 0))) ; int viprintf (const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 1, 0))) ; int viscanf (const char *, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 1, 0))) ; int vsiprintf (char *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int vsiscanf (const char *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 2, 0))) ; int vsniprintf (char *, size_t, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; FILE * fdopen (int, const char *); int fileno (FILE *); int pclose (FILE *); FILE * popen (const char *, const char *); void setbuffer (FILE *, char *, int); int setlinebuf (FILE *); int getw (FILE *); int putw (int, FILE *); int getc_unlocked (FILE *); int getchar_unlocked (void); void flockfile (FILE *); int ftrylockfile (FILE *); void funlockfile (FILE *); int putc_unlocked (int, FILE *); int putchar_unlocked (int); int dprintf (int, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; FILE * fmemopen (void *restrict, size_t, const char *restrict); FILE * open_memstream (char **, size_t *); int vdprintf (int, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int renameat (int, const char *, int, const char *); int _asiprintf_r (struct _reent *, char **, const char *, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; char * _asniprintf_r (struct _reent *, char *, size_t *, const char *, ...) __attribute__ ((__format__ (__printf__, 4, 5))) ; char * _asnprintf_r (struct _reent *, char *restrict, size_t *restrict, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 4, 5))) ; int _asprintf_r (struct _reent *, char **restrict, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int _diprintf_r (struct _reent *, int, const char *, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int _dprintf_r (struct _reent *, int, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int _fclose_r (struct _reent *, FILE *); int _fcloseall_r (struct _reent *); FILE * _fdopen_r (struct _reent *, int, const char *); int _fflush_r (struct _reent *, FILE *); int _fgetc_r (struct _reent *, FILE *); int _fgetc_unlocked_r (struct _reent *, FILE *); char * _fgets_r (struct _reent *, char *restrict, int, FILE *restrict); char * _fgets_unlocked_r (struct _reent *, char *restrict, int, FILE *restrict); int _fgetpos_r (struct _reent *, FILE *, fpos_t *); int _fsetpos_r (struct _reent *, FILE *, const fpos_t *); int _fiprintf_r (struct _reent *, FILE *, const char *, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int _fiscanf_r (struct _reent *, FILE *, const char *, ...) __attribute__ ((__format__ (__scanf__, 3, 4))) ; FILE * _fmemopen_r (struct _reent *, void *restrict, size_t, const char *restrict); FILE * _fopen_r (struct _reent *, const char *restrict, const char *restrict); FILE * _freopen_r (struct _reent *, const char *restrict, const char *restrict, FILE *restrict); int _fprintf_r (struct _reent *, FILE *restrict, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int _fpurge_r (struct _reent *, FILE *); int _fputc_r (struct _reent *, int, FILE *); int _fputc_unlocked_r (struct _reent *, int, FILE *); int _fputs_r (struct _reent *, const char *restrict, FILE *restrict); int _fputs_unlocked_r (struct _reent *, const char *restrict, FILE *restrict); size_t _fread_r (struct _reent *, void * restrict, size_t _size, size_t _n, FILE *restrict); size_t _fread_unlocked_r (struct _reent *, void * restrict, size_t _size, size_t _n, FILE *restrict); int _fscanf_r (struct _reent *, FILE *restrict, const char *restrict, ...) __attribute__ ((__format__ (__scanf__, 3, 4))) ; int _fseek_r (struct _reent *, FILE *, long, int); int _fseeko_r (struct _reent *, FILE *, _off_t, int); long _ftell_r (struct _reent *, FILE *); _off_t _ftello_r (struct _reent *, FILE *); void _rewind_r (struct _reent *, FILE *); size_t _fwrite_r (struct _reent *, const void * restrict, size_t _size, size_t _n, FILE *restrict); size_t _fwrite_unlocked_r (struct _reent *, const void * restrict, size_t _size, size_t _n, FILE *restrict); int _getc_r (struct _reent *, FILE *); int _getc_unlocked_r (struct _reent *, FILE *); int _getchar_r (struct _reent *); int _getchar_unlocked_r (struct _reent *); char * _gets_r (struct _reent *, char *); int _iprintf_r (struct _reent *, const char *, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; int _iscanf_r (struct _reent *, const char *, ...) __attribute__ ((__format__ (__scanf__, 2, 3))) ; FILE * _open_memstream_r (struct _reent *, char **, size_t *); void _perror_r (struct _reent *, const char *); int _printf_r (struct _reent *, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; int _putc_r (struct _reent *, int, FILE *); int _putc_unlocked_r (struct _reent *, int, FILE *); int _putchar_unlocked_r (struct _reent *, int); int _putchar_r (struct _reent *, int); int _puts_r (struct _reent *, const char *); int _remove_r (struct _reent *, const char *); int _rename_r (struct _reent *, const char *_old, const char *_new) ; int _scanf_r (struct _reent *, const char *restrict, ...) __attribute__ ((__format__ (__scanf__, 2, 3))) ; int _siprintf_r (struct _reent *, char *, const char *, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int _siscanf_r (struct _reent *, const char *, const char *, ...) __attribute__ ((__format__ (__scanf__, 3, 4))) ; int _sniprintf_r (struct _reent *, char *, size_t, const char *, ...) __attribute__ ((__format__ (__printf__, 4, 5))) ; int _snprintf_r (struct _reent *, char *restrict, size_t, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 4, 5))) ; int _sprintf_r (struct _reent *, char *restrict, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int _sscanf_r (struct _reent *, const char *restrict, const char *restrict, ...) __attribute__ ((__format__ (__scanf__, 3, 4))) ; char * _tempnam_r (struct _reent *, const char *, const char *); FILE * _tmpfile_r (struct _reent *); char * _tmpnam_r (struct _reent *, char *); int _ungetc_r (struct _reent *, int, FILE *); int _vasiprintf_r (struct _reent *, char **, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; char * _vasniprintf_r (struct _reent*, char *, size_t *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 4, 0))) ; char * _vasnprintf_r (struct _reent*, char *, size_t *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 4, 0))) ; int _vasprintf_r (struct _reent *, char **, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int _vdiprintf_r (struct _reent *, int, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int _vdprintf_r (struct _reent *, int, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int _vfiprintf_r (struct _reent *, FILE *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int _vfiscanf_r (struct _reent *, FILE *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 3, 0))) ; int _vfprintf_r (struct _reent *, FILE *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int _vfscanf_r (struct _reent *, FILE *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 3, 0))) ; int _viprintf_r (struct _reent *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int _viscanf_r (struct _reent *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 2, 0))) ; int _vprintf_r (struct _reent *, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int _vscanf_r (struct _reent *, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 2, 0))) ; int _vsiprintf_r (struct _reent *, char *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int _vsiscanf_r (struct _reent *, const char *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 3, 0))) ; int _vsniprintf_r (struct _reent *, char *, size_t, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 4, 0))) ; int _vsnprintf_r (struct _reent *, char *restrict, size_t, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 4, 0))) ; int _vsprintf_r (struct _reent *, char *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int _vsscanf_r (struct _reent *, const char *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 3, 0))) ; int fpurge (FILE *); ssize_t __getdelim (char **, size_t *, int, FILE *); ssize_t __getline (char **, size_t *, FILE *); void clearerr_unlocked (FILE *); int feof_unlocked (FILE *); int ferror_unlocked (FILE *); int fileno_unlocked (FILE *); int fflush_unlocked (FILE *); int fgetc_unlocked (FILE *); int fputc_unlocked (int, FILE *); size_t fread_unlocked (void * restrict, size_t _size, size_t _n, FILE *restrict); size_t fwrite_unlocked (const void * restrict , size_t _size, size_t _n, FILE *); int __srget_r (struct _reent *, FILE *); int __swbuf_r (struct _reent *, int, FILE *); FILE *funopen (const void * __cookie, int (*__readfn)(void * __cookie, char *__buf, int __n), int (*__writefn)(void * __cookie, const char *__buf, int __n), fpos_t (*__seekfn)(void * __cookie, fpos_t __off, int __whence), int (*__closefn)(void * __cookie)) ; FILE *_funopen_r (struct _reent *, const void * __cookie, int (*__readfn)(void * __cookie, char *__buf, int __n), int (*__writefn)(void * __cookie, const char *__buf, int __n), fpos_t (*__seekfn)(void * __cookie, fpos_t __off, int __whence), int (*__closefn)(void * __cookie)) ; static __inline__ int __sputc_r(struct _reent *_ptr, int _c, FILE *_p) { if (--_p->_w >= 0 || (_p->_w >= _p->_lbfsize && (char)_c != '\n')) return (*_p->_p++ = _c); else return (__swbuf_r(_ptr, _c, _p)); } uint32_t sd_nvic_SystemReset(void); void hal_reboot(void) { printf("reboot!\n"); sd_nvic_SystemReset(); }
the_stack_data/286993.c
#include<stdio.h> #include<stdlib.h> /* Link list node */ struct Node { int data; struct Node* next; }; /* function to insert a new_node in a list. Note that this function expects a pointer to head_ref as this can modify the head of the input linked list (similar to push())*/ void sortedInsert(struct Node** head_ref, struct Node* new_node) { struct Node* current; /* Special case for the head end */ if (*head_ref == NULL || (*head_ref)->data >= new_node->data) { new_node->next = *head_ref; *head_ref = new_node; } else { /* Locate the node before the point of insertion */ current = *head_ref; while (current->next!=NULL && current->next->data < new_node->data) { current = current->next; } new_node->next = current->next; current->next = new_node; } } /* BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert */ /* A utility function to create a new node */ struct Node *newNode(int new_data) { /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; new_node->next = NULL; return new_node; } /* Function to print linked list */ void printList(struct Node *head) { struct Node *temp = head; while(temp != NULL) { printf("%d ", temp->data); temp = temp->next; } } /* Drier program to test count function*/ int main() { /* Start with the empty list */ struct Node* head = NULL; struct Node *new_node = newNode(5); sortedInsert(&head, new_node); new_node = newNode(10); sortedInsert(&head, new_node); new_node = newNode(7); sortedInsert(&head, new_node); new_node = newNode(3); sortedInsert(&head, new_node); new_node = newNode(1); sortedInsert(&head, new_node); new_node = newNode(9); sortedInsert(&head, new_node); printf("\n Created Linked List\n"); printList(head); return 0; }
the_stack_data/184517946.c
/* * Copyright (c) [2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <limits.h> __attribute__((count("len", 2))) void test1(int len, int *p) { for (int i = 0; i < len + 5; ++i) { printf("%d\n", p[i]); } } int main() { return 0; }
the_stack_data/89089.c
#define _POSIX_C_SOURCE 200809L #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <stdint.h> #include <time.h> #define DEFAULT_BUFFER_SIZE 0xff #ifndef SHOW_PROGRESS #define SHOW_PROGRESS 1 #include <pthread.h> #endif void gen_binary(size_t min, size_t max, size_t bufsiz, FILE *output, float *progress); void binary_to_csv(FILE* in, FILE* out, size_t bufsiz, float *progress); void *progress_func(void *args); const size_t max = 1000; int main(int argc, char *argv[]) { /* Options: * argv[1] = mode */ float progress = 0.f; int status = EXIT_SUCCESS; #if SHOW_PROGRESS == 1 pthread_t p_thread; #endif if (strcmp(argv[1], "g") == 0) { FILE *out; if (strcmp("-", argv[2]) == 0) { out = stdout; } else { out = fopen(argv[2], "w"); } if (out != NULL) { size_t min, max; if (sscanf(argv[3], "%zu", &min) == 1 && sscanf(argv[4], "%zu", &max) == 1) { size_t bufsiz = DEFAULT_BUFFER_SIZE; if (argc == 6) { if (sscanf(argv[5], "%zu", &bufsiz) != 1) { fprintf(stderr, "%s: Failed to parse bufsiz: %s", argv[0], strerror(errno)); return EXIT_FAILURE; } } #if SHOW_PROGRESS == 1 if (pthread_create(&p_thread, NULL, progress_func, &progress) != 0) { fprintf(stderr, "%s: Failed to create pthread: %s", argv[0], strerror(errno)); status = EXIT_FAILURE; } #endif if (status == EXIT_SUCCESS) { gen_binary(min, max, bufsiz, out, &progress); progress = 2.f; pthread_join(p_thread, NULL); } } else { fprintf(stderr, "%s: Failed to parse min or max: %s\n", argv[0], strerror(errno)); status = EXIT_FAILURE; } fclose(out); } else { fprintf(stderr, "%s: %s: %s\n", argv[0], argv[1], strerror(errno)); status = EXIT_FAILURE; } } else if (strcmp(argv[1], "c") == 0) { FILE *in; if (strcmp("-", argv[2]) == 0) { in = stdin; } else { in = fopen(argv[2], "r"); } if (in != NULL) { FILE *out; if (strcmp("-", argv[3]) == 0) { out = stdout; } else { out = fopen(argv[3], "w"); } if (out != NULL) { size_t bufsiz = DEFAULT_BUFFER_SIZE; if (argc > 4 && sscanf(argv[4], "%zu", &bufsiz) != 1) { fprintf(stderr, "%s: Failed to parse min: %s", argv[0], strerror(errno)); status = EXIT_FAILURE; } #if SHOW_PROGRESS == 1 if (pthread_create(&p_thread, NULL, progress_func, &progress) != 0) { fprintf(stderr, "%s: Failed to create pthread: %s", argv[0], strerror(errno)); status = EXIT_FAILURE; } #endif if (status == EXIT_SUCCESS) { binary_to_csv(in, out, bufsiz, &progress); progress = 2.f; pthread_join(p_thread, NULL); } fclose(out); } else { fprintf(stderr, "%s: %s: %s", argv[0], argv[3], strerror(errno)); } fclose(in); } else { fprintf(stderr, "%s: %s: %s", argv[0], argv[1], strerror(errno)); } } else { fprintf(stderr, "%s: Invalid usage", argv[0]); } return status; } void *progress_func(void *args) { float *progress = args; while (*progress != 2.f) { printf("%.2f %%\n", *progress * 100); struct timespec a = { .tv_sec = 0, .tv_nsec = 100000000 }; nanosleep(&a, NULL); } return NULL; } void binary_to_csv(FILE* in, FILE* out, size_t bufsiz, float *progress) { size_t min = 0, max = 0; size_t *buffer = NULL; buffer = calloc(bufsiz, sizeof(size_t)); if (buffer == NULL) { perror("Failed to allocate buffer"); return; } /* Read header. */ fread(&min, sizeof(size_t), 1, in); fread(&max, sizeof(size_t), 1, in); while (min < max) { /* Update progress. */ *progress = (float)min / max; if (max - min >= bufsiz) { /* What's left. */ fread(buffer, sizeof(size_t), bufsiz, in); for (size_t i = 0; i < bufsiz; ++i) { fprintf(out, "%zu,%zu\n", min + i, buffer[i]); } min += bufsiz; } else { fread(buffer, sizeof(size_t), max - min, in); /* Read the rest. */ for (size_t i = 0; i < max - min; ++i) { fprintf(out, "%zu,%zu\n", min + i, buffer[i]); } min += max - min; } } /* Final progress. */ *progress = 1.f; free(buffer); } void gen_binary(size_t min, size_t max, size_t bufsiz, FILE *output, float *progress) { size_t n = 0; /* The current index. */ size_t s = 0; /* Steps. */ size_t *buffer = NULL; size_t buffree = 0; /* Free index in buffer. */ buffer = calloc(bufsiz, sizeof(size_t)); if (buffer == NULL) { perror("Failed to allocate buffer in gen_binary"); return; } /* Write header in binary file. */ fwrite(&min, sizeof(size_t), 1, output); fwrite(&max, sizeof(size_t), 1, output); /* Go through min to max, excluding max. */ while ((n = min++) < max) { s = 0; /* Logic. */ while (n > 1) { if ((n & 1) == 0) { /* even */ n >>= 1; /* Divide by 2. */ ++s; } else { /* odd */ n = (n * 3 + 1) >> 1; /* (3 * n + 1) / 2 */ s += 2; } } /* Save logic. */ buffer[buffree++] = s; if (buffree >= bufsiz) { fwrite(buffer, sizeof(size_t), buffree, output); buffree = 0; } /* Update progress. */ *progress = (float)min / max; } /* Print if anything is left. */ if (buffree > 0) { fwrite(buffer, sizeof(size_t), buffree, output); buffree = 0; } /* Final progress. */ *progress = 1.f; free(buffer); }
the_stack_data/68647.c
/* * ===================================================================================== * * Filename: pathconfig.c * * Description: 运行时限定值 * pathconfig:获取路径一些限定信息 * sysconf:获得与文件目录无关限定值 * fpathconf:文件相关限定 * * Version: 1.0 * Created: 03/01/2018 11:41:30 AM * Revision: none * Compiler: gcc * * Author: Hang Cao (Melvin), [email protected] * Organization: * * ===================================================================================== */ #include <stdlib.h> #include <unistd.h> int main(void) { char pathname[256] = "/home"; printf("%s:\n", pathname); printf("NAME_MAX=%d\n", pathconf(pathname, _PC_NAME_MAX)); printf("PATH_MAX=%d\n", pathconf(pathname, _PC_PATH_MAX)); printf("LINK_MAX=%d\n", pathconf(pathname, _PC_LINK_MAX)); printf("MAX_INPUT=%d\n", pathconf(pathname, _PC_MAX_INPUT)); printf("PIPE_BUF=%d\n", pathconf(pathname, _PC_PIPE_BUF)); return 0; }
the_stack_data/25136851.c
#include <string.h> #include <stdio.h> void main(int argc, char *argv[]) { char buffer[300]; strcpy(buffer, argv[1]); printf("\n\nI'm sorry, my responses are limited. You must ask the right questions.\n\n"); }
the_stack_data/237642045.c
int main() { return 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10; }
the_stack_data/175142042.c
int f(int x) { return x+42; } int main(int argc, char ** argv) { int x = 100; int y; int i; while (x) { y = f(x); y = y + 6; y = x + y + 5; for (i=0; i < y; i++) { x = x + 2; } } return x; }
the_stack_data/767700.c
/* S/MIME detached data decrypt example: rarely done but * should the need arise this is an example.... */ #include <openssl/pem.h> #include <openssl/cms.h> #include <openssl/err.h> int main(int argc, char **argv) { BIO *in = NULL, *out = NULL, *tbio = NULL, *dcont = NULL; X509 *rcert = NULL; EVP_PKEY *rkey = NULL; CMS_ContentInfo *cms = NULL; int ret = 1; OpenSSL_add_all_algorithms(); ERR_load_crypto_strings(); /* Read in recipient certificate and private key */ tbio = BIO_new_file("signer.pem", "r"); if (!tbio) goto err; rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL); BIO_reset(tbio); rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL); if (!rcert || !rkey) goto err; /* Open PEM file containing enveloped data */ in = BIO_new_file("smencr.pem", "r"); if (!in) goto err; /* Parse PEM content */ cms = PEM_read_bio_CMS(in, NULL, 0, NULL); if (!cms) goto err; /* Open file containing detached content */ dcont = BIO_new_file("smencr.out", "rb"); if (!in) goto err; out = BIO_new_file("encrout.txt", "w"); if (!out) goto err; /* Decrypt S/MIME message */ if (!CMS_decrypt(cms, rkey, rcert, dcont, out, 0)) goto err; ret = 0; err: if (ret) { fprintf(stderr, "Error Decrypting Data\n"); ERR_print_errors_fp(stderr); } if (cms) CMS_ContentInfo_free(cms); if (rcert) X509_free(rcert); if (rkey) EVP_PKEY_free(rkey); if (in) BIO_free(in); if (out) BIO_free(out); if (tbio) BIO_free(tbio); if (dcont) BIO_free(dcont); return ret; }
the_stack_data/1257200.c
/* * Copyright (c) 2005-2017 National Technology & Engineering Solutions * of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with * NTESS, the U.S. Government retains certain rights in this software. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * 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. * * * Neither the name of NTESS 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 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. * */ #include <stdio.h> #include <string.h> /* Debug break point. */ void checkpnt(char *tag) { int affirm(char *prompt); void bail(char *msg, int status); if (tag != NULL && (int)strlen(tag) > 0) { printf("%s: ", tag); } if (!affirm("continue")) { bail(NULL, 0); } }
the_stack_data/649033.c
// SPDX-License-Identifier: GPL-2.0-only /* * Minimal BPF debugger * * Minimal BPF debugger that mimics the kernel's engine (w/o extensions) * and allows for single stepping through selected packets from a pcap * with a provided user filter in order to facilitate verification of a * BPF program. Besides others, this is useful to verify BPF programs * before attaching to a live system, and can be used in socket filters, * cls_bpf, xt_bpf, team driver and e.g. PTP code; in particular when a * single more complex BPF program is being used. Reasons for a more * complex BPF program are likely primarily to optimize execution time * for making a verdict when multiple simple BPF programs are combined * into one in order to prevent parsing same headers multiple times. * * More on how to debug BPF opcodes see Documentation/networking/filter.rst * which is the main document on BPF. Mini howto for getting started: * * 1) `./bpf_dbg` to enter the shell (shell cmds denoted with '>'): * 2) > load bpf 6,40 0 0 12,21 0 3 20... (output from `bpf_asm` or * `tcpdump -iem1 -ddd port 22 | tr '\n' ','` to load as filter) * 3) > load pcap foo.pcap * 4) > run <n>/disassemble/dump/quit (self-explanatory) * 5) > breakpoint 2 (sets bp at loaded BPF insns 2, do `run` then; * multiple bps can be set, of course, a call to `breakpoint` * w/o args shows currently loaded bps, `breakpoint reset` for * resetting all breakpoints) * 6) > select 3 (`run` etc will start from the 3rd packet in the pcap) * 7) > step [-<n>, +<n>] (performs single stepping through the BPF) * * Copyright 2013 Daniel Borkmann <[email protected]> */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <ctype.h> #include <stdbool.h> #include <stdarg.h> #include <setjmp.h> #include <linux/filter.h> #include <linux/if_packet.h> #include <readline/readline.h> #include <readline/history.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <errno.h> #include <signal.h> #include <arpa/inet.h> #include <net/ethernet.h> #define TCPDUMP_MAGIC 0xa1b2c3d4 #define BPF_LDX_B (BPF_LDX | BPF_B) #define BPF_LDX_W (BPF_LDX | BPF_W) #define BPF_JMP_JA (BPF_JMP | BPF_JA) #define BPF_JMP_JEQ (BPF_JMP | BPF_JEQ) #define BPF_JMP_JGT (BPF_JMP | BPF_JGT) #define BPF_JMP_JGE (BPF_JMP | BPF_JGE) #define BPF_JMP_JSET (BPF_JMP | BPF_JSET) #define BPF_ALU_ADD (BPF_ALU | BPF_ADD) #define BPF_ALU_SUB (BPF_ALU | BPF_SUB) #define BPF_ALU_MUL (BPF_ALU | BPF_MUL) #define BPF_ALU_DIV (BPF_ALU | BPF_DIV) #define BPF_ALU_MOD (BPF_ALU | BPF_MOD) #define BPF_ALU_NEG (BPF_ALU | BPF_NEG) #define BPF_ALU_AND (BPF_ALU | BPF_AND) #define BPF_ALU_OR (BPF_ALU | BPF_OR) #define BPF_ALU_XOR (BPF_ALU | BPF_XOR) #define BPF_ALU_LSH (BPF_ALU | BPF_LSH) #define BPF_ALU_RSH (BPF_ALU | BPF_RSH) #define BPF_MISC_TAX (BPF_MISC | BPF_TAX) #define BPF_MISC_TXA (BPF_MISC | BPF_TXA) #define BPF_LD_B (BPF_LD | BPF_B) #define BPF_LD_H (BPF_LD | BPF_H) #define BPF_LD_W (BPF_LD | BPF_W) #ifndef array_size # define array_size(x) (sizeof(x) / sizeof((x)[0])) #endif #ifndef __check_format_printf # define __check_format_printf(pos_fmtstr, pos_fmtargs) \ __attribute__ ((format (printf, (pos_fmtstr), (pos_fmtargs)))) #endif enum { CMD_OK, CMD_ERR, CMD_EX, }; struct shell_cmd { const char *name; int (*func)(char *args); }; struct pcap_filehdr { uint32_t magic; uint16_t version_major; uint16_t version_minor; int32_t thiszone; uint32_t sigfigs; uint32_t snaplen; uint32_t linktype; }; struct pcap_timeval { int32_t tv_sec; int32_t tv_usec; }; struct pcap_pkthdr { struct pcap_timeval ts; uint32_t caplen; uint32_t len; }; struct bpf_regs { uint32_t A; uint32_t X; uint32_t M[BPF_MEMWORDS]; uint32_t R; bool Rs; uint16_t Pc; }; static struct sock_filter bpf_image[BPF_MAXINSNS + 1]; static unsigned int bpf_prog_len; static int bpf_breakpoints[64]; static struct bpf_regs bpf_regs[BPF_MAXINSNS + 1]; static struct bpf_regs bpf_curr; static unsigned int bpf_regs_len; static int pcap_fd = -1; static unsigned int pcap_packet; static size_t pcap_map_size; static char *pcap_ptr_va_start, *pcap_ptr_va_curr; static const char * const op_table[] = { [BPF_ST] = "st", [BPF_STX] = "stx", [BPF_LD_B] = "ldb", [BPF_LD_H] = "ldh", [BPF_LD_W] = "ld", [BPF_LDX] = "ldx", [BPF_LDX_B] = "ldxb", [BPF_JMP_JA] = "ja", [BPF_JMP_JEQ] = "jeq", [BPF_JMP_JGT] = "jgt", [BPF_JMP_JGE] = "jge", [BPF_JMP_JSET] = "jset", [BPF_ALU_ADD] = "add", [BPF_ALU_SUB] = "sub", [BPF_ALU_MUL] = "mul", [BPF_ALU_DIV] = "div", [BPF_ALU_MOD] = "mod", [BPF_ALU_NEG] = "neg", [BPF_ALU_AND] = "and", [BPF_ALU_OR] = "or", [BPF_ALU_XOR] = "xor", [BPF_ALU_LSH] = "lsh", [BPF_ALU_RSH] = "rsh", [BPF_MISC_TAX] = "tax", [BPF_MISC_TXA] = "txa", [BPF_RET] = "ret", }; static __check_format_printf(1, 2) int rl_printf(const char *fmt, ...) { int ret; va_list vl; va_start(vl, fmt); ret = vfprintf(rl_outstream, fmt, vl); va_end(vl); return ret; } static int matches(const char *cmd, const char *pattern) { int len = strlen(cmd); if (len > strlen(pattern)) return -1; return memcmp(pattern, cmd, len); } static void hex_dump(const uint8_t *buf, size_t len) { int i; rl_printf("%3u: ", 0); for (i = 0; i < len; i++) { if (i && !(i % 16)) rl_printf("\n%3u: ", i); rl_printf("%02x ", buf[i]); } rl_printf("\n"); } static bool bpf_prog_loaded(void) { if (bpf_prog_len == 0) rl_printf("no bpf program loaded!\n"); return bpf_prog_len > 0; } static void bpf_disasm(const struct sock_filter f, unsigned int i) { const char *op, *fmt; int val = f.k; char buf[256]; switch (f.code) { case BPF_RET | BPF_K: op = op_table[BPF_RET]; fmt = "#%#x"; break; case BPF_RET | BPF_A: op = op_table[BPF_RET]; fmt = "a"; break; case BPF_RET | BPF_X: op = op_table[BPF_RET]; fmt = "x"; break; case BPF_MISC_TAX: op = op_table[BPF_MISC_TAX]; fmt = ""; break; case BPF_MISC_TXA: op = op_table[BPF_MISC_TXA]; fmt = ""; break; case BPF_ST: op = op_table[BPF_ST]; fmt = "M[%d]"; break; case BPF_STX: op = op_table[BPF_STX]; fmt = "M[%d]"; break; case BPF_LD_W | BPF_ABS: op = op_table[BPF_LD_W]; fmt = "[%d]"; break; case BPF_LD_H | BPF_ABS: op = op_table[BPF_LD_H]; fmt = "[%d]"; break; case BPF_LD_B | BPF_ABS: op = op_table[BPF_LD_B]; fmt = "[%d]"; break; case BPF_LD_W | BPF_LEN: op = op_table[BPF_LD_W]; fmt = "#len"; break; case BPF_LD_W | BPF_IND: op = op_table[BPF_LD_W]; fmt = "[x+%d]"; break; case BPF_LD_H | BPF_IND: op = op_table[BPF_LD_H]; fmt = "[x+%d]"; break; case BPF_LD_B | BPF_IND: op = op_table[BPF_LD_B]; fmt = "[x+%d]"; break; case BPF_LD | BPF_IMM: op = op_table[BPF_LD_W]; fmt = "#%#x"; break; case BPF_LDX | BPF_IMM: op = op_table[BPF_LDX]; fmt = "#%#x"; break; case BPF_LDX_B | BPF_MSH: op = op_table[BPF_LDX_B]; fmt = "4*([%d]&0xf)"; break; case BPF_LD | BPF_MEM: op = op_table[BPF_LD_W]; fmt = "M[%d]"; break; case BPF_LDX | BPF_MEM: op = op_table[BPF_LDX]; fmt = "M[%d]"; break; case BPF_JMP_JA: op = op_table[BPF_JMP_JA]; fmt = "%d"; val = i + 1 + f.k; break; case BPF_JMP_JGT | BPF_X: op = op_table[BPF_JMP_JGT]; fmt = "x"; break; case BPF_JMP_JGT | BPF_K: op = op_table[BPF_JMP_JGT]; fmt = "#%#x"; break; case BPF_JMP_JGE | BPF_X: op = op_table[BPF_JMP_JGE]; fmt = "x"; break; case BPF_JMP_JGE | BPF_K: op = op_table[BPF_JMP_JGE]; fmt = "#%#x"; break; case BPF_JMP_JEQ | BPF_X: op = op_table[BPF_JMP_JEQ]; fmt = "x"; break; case BPF_JMP_JEQ | BPF_K: op = op_table[BPF_JMP_JEQ]; fmt = "#%#x"; break; case BPF_JMP_JSET | BPF_X: op = op_table[BPF_JMP_JSET]; fmt = "x"; break; case BPF_JMP_JSET | BPF_K: op = op_table[BPF_JMP_JSET]; fmt = "#%#x"; break; case BPF_ALU_NEG: op = op_table[BPF_ALU_NEG]; fmt = ""; break; case BPF_ALU_LSH | BPF_X: op = op_table[BPF_ALU_LSH]; fmt = "x"; break; case BPF_ALU_LSH | BPF_K: op = op_table[BPF_ALU_LSH]; fmt = "#%d"; break; case BPF_ALU_RSH | BPF_X: op = op_table[BPF_ALU_RSH]; fmt = "x"; break; case BPF_ALU_RSH | BPF_K: op = op_table[BPF_ALU_RSH]; fmt = "#%d"; break; case BPF_ALU_ADD | BPF_X: op = op_table[BPF_ALU_ADD]; fmt = "x"; break; case BPF_ALU_ADD | BPF_K: op = op_table[BPF_ALU_ADD]; fmt = "#%d"; break; case BPF_ALU_SUB | BPF_X: op = op_table[BPF_ALU_SUB]; fmt = "x"; break; case BPF_ALU_SUB | BPF_K: op = op_table[BPF_ALU_SUB]; fmt = "#%d"; break; case BPF_ALU_MUL | BPF_X: op = op_table[BPF_ALU_MUL]; fmt = "x"; break; case BPF_ALU_MUL | BPF_K: op = op_table[BPF_ALU_MUL]; fmt = "#%d"; break; case BPF_ALU_DIV | BPF_X: op = op_table[BPF_ALU_DIV]; fmt = "x"; break; case BPF_ALU_DIV | BPF_K: op = op_table[BPF_ALU_DIV]; fmt = "#%d"; break; case BPF_ALU_MOD | BPF_X: op = op_table[BPF_ALU_MOD]; fmt = "x"; break; case BPF_ALU_MOD | BPF_K: op = op_table[BPF_ALU_MOD]; fmt = "#%d"; break; case BPF_ALU_AND | BPF_X: op = op_table[BPF_ALU_AND]; fmt = "x"; break; case BPF_ALU_AND | BPF_K: op = op_table[BPF_ALU_AND]; fmt = "#%#x"; break; case BPF_ALU_OR | BPF_X: op = op_table[BPF_ALU_OR]; fmt = "x"; break; case BPF_ALU_OR | BPF_K: op = op_table[BPF_ALU_OR]; fmt = "#%#x"; break; case BPF_ALU_XOR | BPF_X: op = op_table[BPF_ALU_XOR]; fmt = "x"; break; case BPF_ALU_XOR | BPF_K: op = op_table[BPF_ALU_XOR]; fmt = "#%#x"; break; default: op = "nosup"; fmt = "%#x"; val = f.code; break; } memset(buf, 0, sizeof(buf)); snprintf(buf, sizeof(buf), fmt, val); buf[sizeof(buf) - 1] = 0; if ((BPF_CLASS(f.code) == BPF_JMP && BPF_OP(f.code) != BPF_JA)) rl_printf("l%d:\t%s %s, l%d, l%d\n", i, op, buf, i + 1 + f.jt, i + 1 + f.jf); else rl_printf("l%d:\t%s %s\n", i, op, buf); } static void bpf_dump_curr(struct bpf_regs *r, struct sock_filter *f) { int i, m = 0; rl_printf("pc: [%u]\n", r->Pc); rl_printf("code: [%u] jt[%u] jf[%u] k[%u]\n", f->code, f->jt, f->jf, f->k); rl_printf("curr: "); bpf_disasm(*f, r->Pc); if (f->jt || f->jf) { rl_printf("jt: "); bpf_disasm(*(f + f->jt + 1), r->Pc + f->jt + 1); rl_printf("jf: "); bpf_disasm(*(f + f->jf + 1), r->Pc + f->jf + 1); } rl_printf("A: [%#08x][%u]\n", r->A, r->A); rl_printf("X: [%#08x][%u]\n", r->X, r->X); if (r->Rs) rl_printf("ret: [%#08x][%u]!\n", r->R, r->R); for (i = 0; i < BPF_MEMWORDS; i++) { if (r->M[i]) { m++; rl_printf("M[%d]: [%#08x][%u]\n", i, r->M[i], r->M[i]); } } if (m == 0) rl_printf("M[0,%d]: [%#08x][%u]\n", BPF_MEMWORDS - 1, 0, 0); } static void bpf_dump_pkt(uint8_t *pkt, uint32_t pkt_caplen, uint32_t pkt_len) { if (pkt_caplen != pkt_len) rl_printf("cap: %u, len: %u\n", pkt_caplen, pkt_len); else rl_printf("len: %u\n", pkt_len); hex_dump(pkt, pkt_caplen); } static void bpf_disasm_all(const struct sock_filter *f, unsigned int len) { unsigned int i; for (i = 0; i < len; i++) bpf_disasm(f[i], i); } static void bpf_dump_all(const struct sock_filter *f, unsigned int len) { unsigned int i; rl_printf("/* { op, jt, jf, k }, */\n"); for (i = 0; i < len; i++) rl_printf("{ %#04x, %2u, %2u, %#010x },\n", f[i].code, f[i].jt, f[i].jf, f[i].k); } static bool bpf_runnable(struct sock_filter *f, unsigned int len) { int sock, ret, i; struct sock_fprog bpf = { .filter = f, .len = len, }; sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { rl_printf("cannot open socket!\n"); return false; } ret = setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf)); close(sock); if (ret < 0) { rl_printf("program not allowed to run by kernel!\n"); return false; } for (i = 0; i < len; i++) { if (BPF_CLASS(f[i].code) == BPF_LD && f[i].k > SKF_AD_OFF) { rl_printf("extensions currently not supported!\n"); return false; } } return true; } static void bpf_reset_breakpoints(void) { int i; for (i = 0; i < array_size(bpf_breakpoints); i++) bpf_breakpoints[i] = -1; } static void bpf_set_breakpoints(unsigned int where) { int i; bool set = false; for (i = 0; i < array_size(bpf_breakpoints); i++) { if (bpf_breakpoints[i] == (int) where) { rl_printf("breakpoint already set!\n"); set = true; break; } if (bpf_breakpoints[i] == -1 && set == false) { bpf_breakpoints[i] = where; set = true; } } if (!set) rl_printf("too many breakpoints set, reset first!\n"); } static void bpf_dump_breakpoints(void) { int i; rl_printf("breakpoints: "); for (i = 0; i < array_size(bpf_breakpoints); i++) { if (bpf_breakpoints[i] < 0) continue; rl_printf("%d ", bpf_breakpoints[i]); } rl_printf("\n"); } static void bpf_reset(void) { bpf_regs_len = 0; memset(bpf_regs, 0, sizeof(bpf_regs)); memset(&bpf_curr, 0, sizeof(bpf_curr)); } static void bpf_safe_regs(void) { memcpy(&bpf_regs[bpf_regs_len++], &bpf_curr, sizeof(bpf_curr)); } static bool bpf_restore_regs(int off) { unsigned int index = bpf_regs_len - 1 + off; if (index == 0) { bpf_reset(); return true; } else if (index < bpf_regs_len) { memcpy(&bpf_curr, &bpf_regs[index], sizeof(bpf_curr)); bpf_regs_len = index; return true; } else { rl_printf("reached bottom of register history stack!\n"); return false; } } static uint32_t extract_u32(uint8_t *pkt, uint32_t off) { uint32_t r; memcpy(&r, &pkt[off], sizeof(r)); return ntohl(r); } static uint16_t extract_u16(uint8_t *pkt, uint32_t off) { uint16_t r; memcpy(&r, &pkt[off], sizeof(r)); return ntohs(r); } static uint8_t extract_u8(uint8_t *pkt, uint32_t off) { return pkt[off]; } static void set_return(struct bpf_regs *r) { r->R = 0; r->Rs = true; } static void bpf_single_step(struct bpf_regs *r, struct sock_filter *f, uint8_t *pkt, uint32_t pkt_caplen, uint32_t pkt_len) { uint32_t K = f->k; int d; switch (f->code) { case BPF_RET | BPF_K: r->R = K; r->Rs = true; break; case BPF_RET | BPF_A: r->R = r->A; r->Rs = true; break; case BPF_RET | BPF_X: r->R = r->X; r->Rs = true; break; case BPF_MISC_TAX: r->X = r->A; break; case BPF_MISC_TXA: r->A = r->X; break; case BPF_ST: r->M[K] = r->A; break; case BPF_STX: r->M[K] = r->X; break; case BPF_LD_W | BPF_ABS: d = pkt_caplen - K; if (d >= sizeof(uint32_t)) r->A = extract_u32(pkt, K); else set_return(r); break; case BPF_LD_H | BPF_ABS: d = pkt_caplen - K; if (d >= sizeof(uint16_t)) r->A = extract_u16(pkt, K); else set_return(r); break; case BPF_LD_B | BPF_ABS: d = pkt_caplen - K; if (d >= sizeof(uint8_t)) r->A = extract_u8(pkt, K); else set_return(r); break; case BPF_LD_W | BPF_IND: d = pkt_caplen - (r->X + K); if (d >= sizeof(uint32_t)) r->A = extract_u32(pkt, r->X + K); break; case BPF_LD_H | BPF_IND: d = pkt_caplen - (r->X + K); if (d >= sizeof(uint16_t)) r->A = extract_u16(pkt, r->X + K); else set_return(r); break; case BPF_LD_B | BPF_IND: d = pkt_caplen - (r->X + K); if (d >= sizeof(uint8_t)) r->A = extract_u8(pkt, r->X + K); else set_return(r); break; case BPF_LDX_B | BPF_MSH: d = pkt_caplen - K; if (d >= sizeof(uint8_t)) { r->X = extract_u8(pkt, K); r->X = (r->X & 0xf) << 2; } else set_return(r); break; case BPF_LD_W | BPF_LEN: r->A = pkt_len; break; case BPF_LDX_W | BPF_LEN: r->A = pkt_len; break; case BPF_LD | BPF_IMM: r->A = K; break; case BPF_LDX | BPF_IMM: r->X = K; break; case BPF_LD | BPF_MEM: r->A = r->M[K]; break; case BPF_LDX | BPF_MEM: r->X = r->M[K]; break; case BPF_JMP_JA: r->Pc += K; break; case BPF_JMP_JGT | BPF_X: r->Pc += r->A > r->X ? f->jt : f->jf; break; case BPF_JMP_JGT | BPF_K: r->Pc += r->A > K ? f->jt : f->jf; break; case BPF_JMP_JGE | BPF_X: r->Pc += r->A >= r->X ? f->jt : f->jf; break; case BPF_JMP_JGE | BPF_K: r->Pc += r->A >= K ? f->jt : f->jf; break; case BPF_JMP_JEQ | BPF_X: r->Pc += r->A == r->X ? f->jt : f->jf; break; case BPF_JMP_JEQ | BPF_K: r->Pc += r->A == K ? f->jt : f->jf; break; case BPF_JMP_JSET | BPF_X: r->Pc += r->A & r->X ? f->jt : f->jf; break; case BPF_JMP_JSET | BPF_K: r->Pc += r->A & K ? f->jt : f->jf; break; case BPF_ALU_NEG: r->A = -r->A; break; case BPF_ALU_LSH | BPF_X: r->A <<= r->X; break; case BPF_ALU_LSH | BPF_K: r->A <<= K; break; case BPF_ALU_RSH | BPF_X: r->A >>= r->X; break; case BPF_ALU_RSH | BPF_K: r->A >>= K; break; case BPF_ALU_ADD | BPF_X: r->A += r->X; break; case BPF_ALU_ADD | BPF_K: r->A += K; break; case BPF_ALU_SUB | BPF_X: r->A -= r->X; break; case BPF_ALU_SUB | BPF_K: r->A -= K; break; case BPF_ALU_MUL | BPF_X: r->A *= r->X; break; case BPF_ALU_MUL | BPF_K: r->A *= K; break; case BPF_ALU_DIV | BPF_X: case BPF_ALU_MOD | BPF_X: if (r->X == 0) { set_return(r); break; } goto do_div; case BPF_ALU_DIV | BPF_K: case BPF_ALU_MOD | BPF_K: if (K == 0) { set_return(r); break; } do_div: switch (f->code) { case BPF_ALU_DIV | BPF_X: r->A /= r->X; break; case BPF_ALU_DIV | BPF_K: r->A /= K; break; case BPF_ALU_MOD | BPF_X: r->A %= r->X; break; case BPF_ALU_MOD | BPF_K: r->A %= K; break; } break; case BPF_ALU_AND | BPF_X: r->A &= r->X; break; case BPF_ALU_AND | BPF_K: r->A &= K; break; case BPF_ALU_OR | BPF_X: r->A |= r->X; break; case BPF_ALU_OR | BPF_K: r->A |= K; break; case BPF_ALU_XOR | BPF_X: r->A ^= r->X; break; case BPF_ALU_XOR | BPF_K: r->A ^= K; break; } } static bool bpf_pc_has_breakpoint(uint16_t pc) { int i; for (i = 0; i < array_size(bpf_breakpoints); i++) { if (bpf_breakpoints[i] < 0) continue; if (bpf_breakpoints[i] == pc) return true; } return false; } static bool bpf_handle_breakpoint(struct bpf_regs *r, struct sock_filter *f, uint8_t *pkt, uint32_t pkt_caplen, uint32_t pkt_len) { rl_printf("-- register dump --\n"); bpf_dump_curr(r, &f[r->Pc]); rl_printf("-- packet dump --\n"); bpf_dump_pkt(pkt, pkt_caplen, pkt_len); rl_printf("(breakpoint)\n"); return true; } static int bpf_run_all(struct sock_filter *f, uint16_t bpf_len, uint8_t *pkt, uint32_t pkt_caplen, uint32_t pkt_len) { bool stop = false; while (bpf_curr.Rs == false && stop == false) { bpf_safe_regs(); if (bpf_pc_has_breakpoint(bpf_curr.Pc)) stop = bpf_handle_breakpoint(&bpf_curr, f, pkt, pkt_caplen, pkt_len); bpf_single_step(&bpf_curr, &f[bpf_curr.Pc], pkt, pkt_caplen, pkt_len); bpf_curr.Pc++; } return stop ? -1 : bpf_curr.R; } static int bpf_run_stepping(struct sock_filter *f, uint16_t bpf_len, uint8_t *pkt, uint32_t pkt_caplen, uint32_t pkt_len, int next) { bool stop = false; int i = 1; while (!bpf_curr.Rs && !stop) { bpf_safe_regs(); if (i++ == next) stop = bpf_handle_breakpoint(&bpf_curr, f, pkt, pkt_caplen, pkt_len); bpf_single_step(&bpf_curr, &f[bpf_curr.Pc], pkt, pkt_caplen, pkt_len); bpf_curr.Pc++; } return stop ? -1 : bpf_curr.R; } static bool pcap_loaded(void) { if (pcap_fd < 0) rl_printf("no pcap file loaded!\n"); return pcap_fd >= 0; } static struct pcap_pkthdr *pcap_curr_pkt(void) { return (void *) pcap_ptr_va_curr; } static bool pcap_next_pkt(void) { struct pcap_pkthdr *hdr = pcap_curr_pkt(); if (pcap_ptr_va_curr + sizeof(*hdr) - pcap_ptr_va_start >= pcap_map_size) return false; if (hdr->caplen == 0 || hdr->len == 0 || hdr->caplen > hdr->len) return false; if (pcap_ptr_va_curr + sizeof(*hdr) + hdr->caplen - pcap_ptr_va_start >= pcap_map_size) return false; pcap_ptr_va_curr += (sizeof(*hdr) + hdr->caplen); return true; } static void pcap_reset_pkt(void) { pcap_ptr_va_curr = pcap_ptr_va_start + sizeof(struct pcap_filehdr); } static int try_load_pcap(const char *file) { struct pcap_filehdr *hdr; struct stat sb; int ret; pcap_fd = open(file, O_RDONLY); if (pcap_fd < 0) { rl_printf("cannot open pcap [%s]!\n", strerror(errno)); return CMD_ERR; } ret = fstat(pcap_fd, &sb); if (ret < 0) { rl_printf("cannot fstat pcap file!\n"); return CMD_ERR; } if (!S_ISREG(sb.st_mode)) { rl_printf("not a regular pcap file, duh!\n"); return CMD_ERR; } pcap_map_size = sb.st_size; if (pcap_map_size <= sizeof(struct pcap_filehdr)) { rl_printf("pcap file too small!\n"); return CMD_ERR; } pcap_ptr_va_start = mmap(NULL, pcap_map_size, PROT_READ, MAP_SHARED | MAP_LOCKED, pcap_fd, 0); if (pcap_ptr_va_start == MAP_FAILED) { rl_printf("mmap of file failed!"); return CMD_ERR; } hdr = (void *) pcap_ptr_va_start; if (hdr->magic != TCPDUMP_MAGIC) { rl_printf("wrong pcap magic!\n"); return CMD_ERR; } pcap_reset_pkt(); return CMD_OK; } static void try_close_pcap(void) { if (pcap_fd >= 0) { munmap(pcap_ptr_va_start, pcap_map_size); close(pcap_fd); pcap_ptr_va_start = pcap_ptr_va_curr = NULL; pcap_map_size = 0; pcap_packet = 0; pcap_fd = -1; } } static int cmd_load_bpf(char *bpf_string) { char sp, *token, separator = ','; unsigned short bpf_len, i = 0; struct sock_filter tmp; bpf_prog_len = 0; memset(bpf_image, 0, sizeof(bpf_image)); if (sscanf(bpf_string, "%hu%c", &bpf_len, &sp) != 2 || sp != separator || bpf_len > BPF_MAXINSNS || bpf_len == 0) { rl_printf("syntax error in head length encoding!\n"); return CMD_ERR; } token = bpf_string; while ((token = strchr(token, separator)) && (++token)[0]) { if (i >= bpf_len) { rl_printf("program exceeds encoded length!\n"); return CMD_ERR; } if (sscanf(token, "%hu %hhu %hhu %u,", &tmp.code, &tmp.jt, &tmp.jf, &tmp.k) != 4) { rl_printf("syntax error at instruction %d!\n", i); return CMD_ERR; } bpf_image[i].code = tmp.code; bpf_image[i].jt = tmp.jt; bpf_image[i].jf = tmp.jf; bpf_image[i].k = tmp.k; i++; } if (i != bpf_len) { rl_printf("syntax error exceeding encoded length!\n"); return CMD_ERR; } else bpf_prog_len = bpf_len; if (!bpf_runnable(bpf_image, bpf_prog_len)) bpf_prog_len = 0; return CMD_OK; } static int cmd_load_pcap(char *file) { char *file_trim, *tmp; file_trim = strtok_r(file, " ", &tmp); if (file_trim == NULL) return CMD_ERR; try_close_pcap(); return try_load_pcap(file_trim); } static int cmd_load(char *arg) { char *subcmd, *cont = NULL, *tmp = strdup(arg); int ret = CMD_OK; subcmd = strtok_r(tmp, " ", &cont); if (subcmd == NULL) goto out; if (matches(subcmd, "bpf") == 0) { bpf_reset(); bpf_reset_breakpoints(); if (!cont) ret = CMD_ERR; else ret = cmd_load_bpf(cont); } else if (matches(subcmd, "pcap") == 0) { ret = cmd_load_pcap(cont); } else { out: rl_printf("bpf <code>: load bpf code\n"); rl_printf("pcap <file>: load pcap file\n"); ret = CMD_ERR; } free(tmp); return ret; } static int cmd_step(char *num) { struct pcap_pkthdr *hdr; int steps, ret; if (!bpf_prog_loaded() || !pcap_loaded()) return CMD_ERR; steps = strtol(num, NULL, 10); if (steps == 0 || strlen(num) == 0) steps = 1; if (steps < 0) { if (!bpf_restore_regs(steps)) return CMD_ERR; steps = 1; } hdr = pcap_curr_pkt(); ret = bpf_run_stepping(bpf_image, bpf_prog_len, (uint8_t *) hdr + sizeof(*hdr), hdr->caplen, hdr->len, steps); if (ret >= 0 || bpf_curr.Rs) { bpf_reset(); if (!pcap_next_pkt()) { rl_printf("(going back to first packet)\n"); pcap_reset_pkt(); } else { rl_printf("(next packet)\n"); } } return CMD_OK; } static int cmd_select(char *num) { unsigned int which, i; bool have_next = true; if (!pcap_loaded() || strlen(num) == 0) return CMD_ERR; which = strtoul(num, NULL, 10); if (which == 0) { rl_printf("packet count starts with 1, clamping!\n"); which = 1; } pcap_reset_pkt(); bpf_reset(); for (i = 0; i < which && (have_next = pcap_next_pkt()); i++) /* noop */; if (!have_next || pcap_curr_pkt() == NULL) { rl_printf("no packet #%u available!\n", which); pcap_reset_pkt(); return CMD_ERR; } return CMD_OK; } static int cmd_breakpoint(char *subcmd) { if (!bpf_prog_loaded()) return CMD_ERR; if (strlen(subcmd) == 0) bpf_dump_breakpoints(); else if (matches(subcmd, "reset") == 0) bpf_reset_breakpoints(); else { unsigned int where = strtoul(subcmd, NULL, 10); if (where < bpf_prog_len) { bpf_set_breakpoints(where); rl_printf("breakpoint at: "); bpf_disasm(bpf_image[where], where); } } return CMD_OK; } static int cmd_run(char *num) { static uint32_t pass, fail; bool has_limit = true; int pkts = 0, i = 0; if (!bpf_prog_loaded() || !pcap_loaded()) return CMD_ERR; pkts = strtol(num, NULL, 10); if (pkts == 0 || strlen(num) == 0) has_limit = false; do { struct pcap_pkthdr *hdr = pcap_curr_pkt(); int ret = bpf_run_all(bpf_image, bpf_prog_len, (uint8_t *) hdr + sizeof(*hdr), hdr->caplen, hdr->len); if (ret > 0) pass++; else if (ret == 0) fail++; else return CMD_OK; bpf_reset(); } while (pcap_next_pkt() && (!has_limit || (++i < pkts))); rl_printf("bpf passes:%u fails:%u\n", pass, fail); pcap_reset_pkt(); bpf_reset(); pass = fail = 0; return CMD_OK; } static int cmd_disassemble(char *line_string) { bool single_line = false; unsigned long line; if (!bpf_prog_loaded()) return CMD_ERR; if (strlen(line_string) > 0 && (line = strtoul(line_string, NULL, 10)) < bpf_prog_len) single_line = true; if (single_line) bpf_disasm(bpf_image[line], line); else bpf_disasm_all(bpf_image, bpf_prog_len); return CMD_OK; } static int cmd_dump(char *dontcare) { if (!bpf_prog_loaded()) return CMD_ERR; bpf_dump_all(bpf_image, bpf_prog_len); return CMD_OK; } static int cmd_quit(char *dontcare) { return CMD_EX; } static const struct shell_cmd cmds[] = { { .name = "load", .func = cmd_load }, { .name = "select", .func = cmd_select }, { .name = "step", .func = cmd_step }, { .name = "run", .func = cmd_run }, { .name = "breakpoint", .func = cmd_breakpoint }, { .name = "disassemble", .func = cmd_disassemble }, { .name = "dump", .func = cmd_dump }, { .name = "quit", .func = cmd_quit }, }; static int execf(char *arg) { char *cmd, *cont, *tmp = strdup(arg); int i, ret = 0, len; cmd = strtok_r(tmp, " ", &cont); if (cmd == NULL) goto out; len = strlen(cmd); for (i = 0; i < array_size(cmds); i++) { if (len != strlen(cmds[i].name)) continue; if (strncmp(cmds[i].name, cmd, len) == 0) { ret = cmds[i].func(cont); break; } } out: free(tmp); return ret; } static char *shell_comp_gen(const char *buf, int state) { static int list_index, len; if (!state) { list_index = 0; len = strlen(buf); } for (; list_index < array_size(cmds); ) { const char *name = cmds[list_index].name; list_index++; if (strncmp(name, buf, len) == 0) return strdup(name); } return NULL; } static char **shell_completion(const char *buf, int start, int end) { char **matches = NULL; if (start == 0) matches = rl_completion_matches(buf, shell_comp_gen); return matches; } static void intr_shell(int sig) { if (rl_end) rl_kill_line(-1, 0); rl_crlf(); rl_refresh_line(0, 0); rl_free_line_state(); } static void init_shell(FILE *fin, FILE *fout) { char file[128]; snprintf(file, sizeof(file), "%s/.bpf_dbg_history", getenv("HOME")); read_history(file); rl_instream = fin; rl_outstream = fout; rl_readline_name = "bpf_dbg"; rl_terminal_name = getenv("TERM"); rl_catch_signals = 0; rl_catch_sigwinch = 1; rl_attempted_completion_function = shell_completion; rl_bind_key('\t', rl_complete); rl_bind_key_in_map('\t', rl_complete, emacs_meta_keymap); rl_bind_key_in_map('\033', rl_complete, emacs_meta_keymap); snprintf(file, sizeof(file), "%s/.bpf_dbg_init", getenv("HOME")); rl_read_init_file(file); rl_prep_terminal(0); rl_set_signals(); signal(SIGINT, intr_shell); } static void exit_shell(FILE *fin, FILE *fout) { char file[128]; snprintf(file, sizeof(file), "%s/.bpf_dbg_history", getenv("HOME")); write_history(file); clear_history(); rl_deprep_terminal(); try_close_pcap(); if (fin != stdin) fclose(fin); if (fout != stdout) fclose(fout); } static int run_shell_loop(FILE *fin, FILE *fout) { char *buf; init_shell(fin, fout); while ((buf = readline("> ")) != NULL) { int ret = execf(buf); if (ret == CMD_EX) break; if (ret == CMD_OK && strlen(buf) > 0) add_history(buf); free(buf); } exit_shell(fin, fout); return 0; } int main(int argc, char **argv) { FILE *fin = NULL, *fout = NULL; if (argc >= 2) fin = fopen(argv[1], "r"); if (argc >= 3) fout = fopen(argv[2], "w"); return run_shell_loop(fin ? : stdin, fout ? : stdout); }
the_stack_data/146738.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t ready = PTHREAD_COND_INITIALIZER; int traveler_cond = 0; void *traveler_arrive(void *name){ printf("traveler %s need a taxi now\n", (char *)name); pthread_mutex_lock(&lock); traveler_cond++; pthread_cond_wait(&ready, &lock); pthread_mutex_unlock(&lock); printf("traveler %s now got a taxi\n", (char *)name); pthread_exit((void *)0); } void *taxi_arrived(void *name){ printf("taxi %s arrives\n", (char *)name); while(1){ pthread_mutex_lock(&lock); if(traveler_cond > 0){ pthread_cond_signal(&ready); pthread_mutex_unlock(&lock); break; } pthread_mutex_unlock(&lock); } pthread_exit((void *)0); } int main(){ pthread_t tids[3]; int iRet = pthread_create(&tids[0], NULL, taxi_arrived, (void *)("Jack")); if(iRet){ printf("pthread_create error : iRet = %d\n", iRet); return iRet; } printf("time passing by\n"); sleep(1); iRet = pthread_create(&tids[1], NULL, traveler_arrive, (void *)("Susan")); if(iRet){ printf("pthread_create error : iRet = %d\n", iRet); return iRet; } printf("time passing by\n"); sleep(1); iRet = pthread_create(&tids[0], NULL, taxi_arrived, (void *)("Mike")); if(iRet){ printf("pthread_create error : iRet = %d\n", iRet); return iRet; } printf("time passing by\n"); sleep(1); void *retval; for(int i = 0; i < 3; i++){ iRet = pthread_join(tids[i], &retval); if(iRet){ printf("pthread_join error : iRet = %d\n", iRet); return iRet; } printf("retval = %ld\n", (long)retval); } return 0; }
the_stack_data/61075347.c
/* * Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2019] EMBL-European Bioinformatics Institute * * 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. */ /* A program for calculating linkage disequilibrium stats */ /* Copyright 2005 Daniel Rios & Tim Cutts */ #include <stdio.h> #include <strings.h> #include <stdlib.h> #include <math.h> #include <inttypes.h> #define SIZE 150 #define WINDOW_SIZE 100000 #define INITIAL_LIST_SIZE 256 #define USER_ERROR 1 #define SYSTEM_ERROR 2 /* Macros for fetching particular haplotypes from the allele_counters */ #define AABB allele_counters[0x0000] #define AABb allele_counters[0x0001] #define AAbb allele_counters[0x0003] #define AaBB allele_counters[0x0004] #define AaBb allele_counters[0x0005] #define Aabb allele_counters[0x0007] #define aaBB allele_counters[0x000c] #define aaBb allele_counters[0x000d] #define aabb allele_counters[0x000f] /* Macro which turns pairs of characters into a two bit integer */ #define genotype2int(g) (((g[0] & 0x20) >> 4) | ((g[1] & 0x20) >> 5)) typedef struct { int person_id; uint8_t genotype; } Genotype; typedef struct{ int locus; int position; int variation_feature_id; int seq_region_end; int population_id; int number_genotypes; Genotype genotypes[SIZE]; } Locus_info; typedef struct{ double D; double r2; double theta; int N; double d_prime; int people; } Stats; typedef struct { int head; int tail; int sz; Locus_info *locus; } Locus_list; typedef struct{ int number_haplotypes; uint8_t haplotype[SIZE]; } Haplotype; void init_locus_list(Locus_list *l) { l->sz = INITIAL_LIST_SIZE; l->tail = -1; l->head = 0; l->locus = malloc(INITIAL_LIST_SIZE*sizeof(Locus_info)); if (l->locus == NULL) { perror("Could not allocate memory"); exit(SYSTEM_ERROR); } } void reallocate_locus_list(Locus_list *l) { Locus_info *t; l->sz *= 2; if (( t = realloc(l->locus, l->sz * sizeof(Locus_info))) == NULL) { perror("Out of memory reallocating locus list"); exit(SYSTEM_ERROR); } l->locus = t; } /* dequeue is so simple, it's just a macro */ #define dequeue(ll) ll.head++ void enqueue(Locus_list *ll, int locus, int pos, int var_ft_id, int seq_reg_end, int pop_id, int personid, uint8_t genotype) { Locus_info *l; ll->tail++; if (ll->tail == ll->sz) reallocate_locus_list(ll); l = &ll->locus[ll->tail]; l->locus = locus; l->position = pos; l->variation_feature_id = var_ft_id; l->seq_region_end = seq_reg_end; l->population_id = pop_id; l->genotypes[0].person_id = personid; l->genotypes[0].genotype = genotype; l->number_genotypes = 1; } void major_freqs(const Haplotype * haplotypes, double *f_A, double *f_B){ int f_a = 0, f_b = 0; int f_A_tmp = 0, f_B_tmp = 0; int total = 0; int i; int tmp; uint8_t h; for (i=0;i<haplotypes->number_haplotypes;i++){ h = haplotypes->haplotype[i]; tmp = ((h & 0x8) >> 3) + ((h & 0x4) >> 2); f_a += tmp; f_A_tmp += (2 - tmp); tmp = ((h & 0x2) >> 1) + (h & 0x1); f_b += tmp; f_B_tmp += (2 - tmp); total = total + 2; } if (total == 0) { *f_A = 0.0; *f_B = 0.0; return; } if (f_a > f_A_tmp){ tmp = f_a; f_a = f_A_tmp; f_A_tmp = tmp; } if (f_b > f_B_tmp){ tmp = f_b; f_b = f_B_tmp; f_B_tmp = f_b; } *f_A = ((double)f_A_tmp / (double)total); *f_B = ((double)f_B_tmp / (double)total); return; } int by_person_id(const void *v1, const void *v2){ Genotype * data1 = (Genotype *)v1; Genotype * data2 = (Genotype *)v2; if (data1->person_id > data2->person_id) return 1; if (data1->person_id == data2->person_id) return 0; if (data1->person_id < data2->person_id) return -1; return 0; } void calculate_pairwise_stats(Locus_info *first, Locus_info *second, Stats *s){ int allele_counters[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; int nAB = 0, nab = 0, nAb = 0, naB = 0; int N; double theta = 0.5; double thetaprev = 2.0; double tmp; double f_A, f_B; double D,r2, Dmax = 0.0, d_prime; int i; int j; Genotype *genotype; uint8_t haplotype; Haplotype haplotypes; /*sort the arrays with the person_id numbers*/ qsort(first->genotypes,first->number_genotypes,sizeof(Genotype),by_person_id); qsort(second->genotypes,second->number_genotypes,sizeof(Genotype),by_person_id); for (i=0;i< first->number_genotypes;i++){ for (j=i;j<second->number_genotypes;j++){ if (first->genotypes[i].person_id == second->genotypes[j].person_id){ genotype = &second->genotypes[j]; /*the second locus has the same person_id*/ haplotype = first->genotypes[i].genotype << 2; haplotype |= genotype->genotype; allele_counters[haplotype]++; haplotypes.haplotype[i] = haplotype; haplotypes.number_haplotypes = i+1; break; } else{ /*they have different, */ if (first->genotypes[i].person_id < second->genotypes[j].person_id){ break; } /* fprintf(stderr, "Could not find %hd in locus %d\n",first->genotypes[i].person_id,second->locus);*/ } } } nAB = 2*AABB + AaBB + AABb; nab = 2*aabb + Aabb + aaBb; nAb = 2*AAbb + Aabb + AABb; naB = 2*aaBB + AaBB + aaBb; N = nAB + nab + nAb + naB + 2*AaBb; /* Initialise stats variable */ bzero(s, sizeof(Stats)); if (N < 40){ /*not enough individuals, return */ s->N = N; return; } while(fabs(theta-thetaprev) > 0.0001){ thetaprev = theta; tmp = ((nAB + (1-theta)*AaBb)*(nab + (1-theta)*AaBb) + (nAb + theta*AaBb)*(naB + theta*AaBb)); theta = (tmp==0) ? 0.5 : ((nAb + theta*AaBb)*(naB + theta*AaBb))/ tmp; } /*now calculate stats*/ major_freqs(&haplotypes,&f_A,&f_B); D = (nAB+(1-theta)*AaBb) / N - (f_A*f_B); tmp = (f_A*f_B*(1-f_A)*(1-f_B)); r2 = (tmp==0) ? 0 : D*D/tmp; if (D < 0){ if (f_A*f_B < ((1-f_A)*(1-f_B))) Dmax = f_A*f_B; if (f_A*f_B >= ((1-f_A)*(1-f_B))) Dmax = (1-f_A)*(1-f_B); } if (D >0){ if (f_A*(1-f_B) < (1-f_A)*f_B) Dmax = f_A*(1-f_B); if (f_A*(1-f_B) >= (1-f_A)*f_B) Dmax = (1-f_A)*f_B; } s->D = D; s->r2 = r2; s->theta = theta; s->N = N; s->d_prime = (Dmax == 0) ? 0.0 : D/Dmax; s->people = haplotypes.number_haplotypes; } void calculate_ld(const Locus_list *ll, int seq_region_id, FILE *fh){ Locus_info *next, *head; Stats stats; /* Doesn't look like it, but sets head and next to the first and second entries - I love C, sometimes */ next = &ll->locus[ll->head]; head = next++; int i; for (i = ll->head; i < ll->tail; i++, next++) { calculate_pairwise_stats(head, next, &stats); if (stats.r2 < 0.05 || stats.N < 40 || stats.r2 > 1) continue; fprintf(fh, "%d\t%d\t%hd\t%d\t%d\t%d\t%f\t%f\t%d\n", head->variation_feature_id, next->variation_feature_id, head->population_id, seq_region_id, head->position, next->position, stats.r2, fabs(stats.d_prime), stats.N); } } int main(int argc, char *argv[]) { FILE *fh; FILE *in; int seq_region_id_previous = -1; int locus; int position; int personid; int variation_feature_id; int seq_region_id; int seq_region_end; int population_id; char genotype[2]; Locus_list locus_list; Locus_info* l_tmp; int last_position = -1; int file_line = 1; int fields; /* Check the command line parameters */ if ((argc != 3) && (argc != 1)) { fprintf(stderr, "Usage: %s [input_file output_file]\n", argv[0]); return USER_ERROR; } if (argc > 1) { if ((in = fopen(argv[1],"r"))==NULL) { perror("Could not open input file"); return USER_ERROR; } if ((fh = fopen(argv[2],"w"))==NULL) { perror("Could not open output file"); return USER_ERROR; } } else { in = stdin; fh = stdout; } init_locus_list(&locus_list); loop: while (!feof( in )){ if (8 != (fields = fscanf(in, "%d%d%d\t%2c\t%d%d%d%d", &locus, &position, &personid, genotype, &variation_feature_id, &seq_region_id, &seq_region_end, &population_id))) { if (fields == EOF) break; fprintf(stderr, "Input parse failure at line %d got %d fields\n", file_line, fields); return USER_ERROR; } file_line++; /* Check both are 'a' or 'A' */ if ((genotype[0] | genotype[1] | 0x20) != 'a') { fprintf(stderr, "Genotype must be AA, Aa or aa, not %s\n",genotype); return USER_ERROR; } /* Make all hets the same order */ if (genotype[0] == 'a' && genotype[1] == 'A') { genotype[0] = 'A'; genotype[1] = 'a'; } /*new region, calculate the ld information for the remaining markers*/ if (seq_region_id != seq_region_id_previous){ while (locus_list.tail >= locus_list.head){ calculate_ld(&locus_list, seq_region_id_previous, fh); dequeue(locus_list); } seq_region_id_previous = seq_region_id; last_position = -1; /* Can reset the queue to the beginning */ locus_list.head = 0; locus_list.tail = -1; } /*still the same marker, add the genotypes to the array and get next one*/ if (position == last_position){ l_tmp = &locus_list.locus[locus_list.tail]; l_tmp->genotypes[l_tmp->number_genotypes].person_id = personid; l_tmp->genotypes[l_tmp->number_genotypes].genotype = genotype2int(genotype); l_tmp->number_genotypes++; if (l_tmp->number_genotypes == SIZE) { fprintf(stderr, "Number of genotypes supported by the program (%d) exceeded\n", SIZE); return SYSTEM_ERROR; } goto loop; } /*check if the new position is farther than the limit.*/ /*if so, calculate the ld information for the values in the array*/ while ((locus_list.tail >= locus_list.head) && (abs(locus_list.locus[locus_list.head].position - position) > WINDOW_SIZE)){ calculate_ld(&locus_list, seq_region_id_previous, fh); dequeue(locus_list); } if (locus_list.tail < locus_list.head) { /* Can reset the queue to the beginning */ locus_list.head = 0; locus_list.tail = -1; } /*new marker*/ last_position = position; enqueue(&locus_list, locus, position, variation_feature_id, seq_region_end, population_id, personid, genotype2int(genotype)); } if (in != stdin) fclose(in); while(locus_list.tail >= locus_list.head){ calculate_ld(&locus_list, seq_region_id_previous, fh); dequeue(locus_list); } if (fh != stdout) fclose(fh); return 0; }
the_stack_data/88301.c
/* { dg-do compile } */ /* { dg-options "-O -fdump-tree-cddce1" } */ __SIZE_TYPE__ fx (char *a, __SIZE_TYPE__ sz) { char *b = a + sz; /* The first forwprop pass should optimize this to return sz; */ return b - a; } /* { dg-final { scan-tree-dump "return sz" "cddce1" } } */
the_stack_data/206394383.c
/* * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. * * 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> #include <stdlib.h> void dot(int *A, int *B, int *C, int m, int n) { for( int i = 0; i < m; i++ ) { C[i] = 0; for( int j = 0; j < n; j++ ) { C[i] += A[i*n+j] * B[i*n+j]; } } }
the_stack_data/154827457.c
#include <stdio.h> /* * ----------------------------------- * | Pedro Daniel Jardim | * | UFV | * | 01/03/2020 | * ---------------------------------- * */ int main(int argc, char **argv) { char c; int i, n, x; long long ans = 0; scanf("%d%*c", &n); for (i = 0; i < n; ++i) { scanf("%c %d%*c", &c, &x); if (c == 'G') ans -= x; else ans += x; } if (ans >= 0) puts("A greve vai parar."); else puts("NAO VAI TER CORTE, VAI TER LUTA!"); return 0; }
the_stack_data/39987.c
/* * testInotify.c: a demo for use inotify to watch the change of file in linux * * Authors: * mardyu<[email protected]> * * Copyright 2016 mardyu<[email protected]> * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdbool.h> #include <sys/inotify.h> void GetMask(int32_t mask); int main(int argc, char **args) { if (argc <= 1) { printf("no folder to watch!\n"); return 1; } int fd = inotify_init(); if (-1 == fd) { perror("init error\n"); return 2; } int i; int ret; int32_t mask = IN_ACCESS | IN_ATTRIB | IN_CLOSE_WRITE | IN_CLOSE_NOWRITE | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO | IN_OPEN; for (i = 0; i < argc; i++) { ret = inotify_add_watch(fd, args[i], IN_ALL_EVENTS); if (-1 == ret) { perror("add_watch error\n"); return 3; } } struct inotify_event *ev; char buff[1024]; while (true) { memset(buff, 0, sizeof(buff)); ret = read(fd, buff, sizeof(buff)); if (-1 == ret) { perror("read error\n"); return 4; } buff[ret] = '\0'; ev = (struct inotify_event *)&buff; printf("filename: %d\n", ev->len); GetMask(ev->mask); printf("watch fd: %d, mask: %d, cookie: %d, name: %s\n" , ev->wd, ev->mask, ev->cookie, ev->name); } return 0; } void GetMask(int32_t mask) { if (mask & IN_ACCESS) { printf("IN_ACCESS\n"); } if (mask & IN_ATTRIB) { printf("IN_ATTRIB\n"); } if (mask & IN_CLOSE_WRITE) { printf("IN_CLOSE_WRITE\n"); } if (mask & IN_CLOSE_NOWRITE) { printf("IN_CLOSE_NOWRITE\n"); } if (mask & IN_CREATE) { printf("IN_CREATE\n"); } if (mask & IN_DELETE) { printf("IN_DELETE\n"); } if (mask & IN_DELETE_SELF) { printf("IN_DELETE_SELF\n"); } if (mask & IN_MODIFY) { printf("IN_MODIFY\n"); } if (mask & IN_MOVE_SELF) { printf("IN_MOVE_SELF\n"); } if (mask & IN_MOVED_FROM) { printf("IN_MOVED_FROM\n"); } if (mask & IN_MOVED_TO) { printf("IN_MOVED_TO\n"); } if (mask & IN_OPEN) { printf("IN_OPEN\n"); } }
the_stack_data/62637736.c
#include<stdio.h> int main(){ int kvartal; scanf("%d",&kvartal); switch(kvartal){ case 0:printf("zero\n"); break; case 1:printf("one\n"); break; case 2:printf("two\n"); break; case 3:printf("three\n"); break; case 4:printf("four\n"); break; case 5:printf("five\n"); break; case 6:printf("six\n"); break; case 7:printf("seven\n"); break; case 8:printf("eight\n"); break; case 9:printf("nine\n"); break; } return 0; }
the_stack_data/356922.c
/* { dg-do run } */ /* { dg-additional-options "-O2" } */ #include <stdio.h> #define N (32*32*32+17) int main () { int ix; int ondev = 0; int t = 0, h = 0; #pragma acc parallel num_workers(32) vector_length(32) copy(ondev) { #pragma acc loop worker vector reduction (+:t) for (unsigned ix = 0; ix < N; ix++) { int val = ix; if (__builtin_acc_on_device (5)) { int g = 0, w = 0, v = 0; __asm__ volatile ("mov.u32 %0,%%ctaid.x;" : "=r" (g)); __asm__ volatile ("mov.u32 %0,%%tid.y;" : "=r" (w)); __asm__ volatile ("mov.u32 %0,%%tid.x;" : "=r" (v)); val = (g << 16) | (w << 8) | v; ondev = 1; } t += val; } } for (ix = 0; ix < N; ix++) { int val = ix; if(ondev) { int g = 0; int w = (ix / 32) % 32; int v = ix % 32; val = (g << 16) | (w << 8) | v; } h += val; } if (t != h) { printf ("t=%x expected %x\n", t, h); return 1; } return 0; }
the_stack_data/76483.c
#include <stdio.h> #include <sys/stat.h> #include <stdbool.h> #include <stdlib.h> #include <dirent.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> static int num_dirs, num_regular; bool is_dir(const char* path) { /* * Use the stat() function (try "man 2 stat") to determine if the file * referenced by path is a directory or not. Call stat, and then use * S_ISDIR to see if the file is a directory. Make sure you check the * return value from stat in case there is a problem, e.g., maybe the * the file doesn't actually exist. */ struct stat *buf = malloc(sizeof(struct stat)); bool x; if (stat(path, buf)) { free(buf); printf("Didnt work\n"); return false; }else { x = S_ISDIR(buf->st_mode); free(buf); return x; } } /* * I needed this because the multiple recursion means there's no way to * order them so that the definitions all precede the cause. */ void process_path(const char*); void process_directory(const char* path) { /* * Update the number of directories seen, use opendir() to open the * directory, and then use readdir() to loop through the entries * and process them. You have to be careful not to process the * "." and ".." directory entries, or you'll end up spinning in * (infinite) loops. Also make sure you closedir() when you're done. * * You'll also want to use chdir() to move into this new directory, * with a matching call to chdir() to move back out of it when you're * done. */ //char* y; //getcwd(y, 1024); chdir(path); DIR *dr = opendir("."); num_dirs += 1; struct dirent *x; while ((x = readdir(dr)) != NULL){ if(strcmp(x->d_name, ".") && strcmp(x->d_name, "..")) process_path(x->d_name); } closedir(dr); free(x); chdir(".."); } void process_file(const char* path) { /* * Update the number of regular files. */ num_regular += 1; } void process_path(const char* path) { if (is_dir(path)) { process_directory(path); } else { process_file(path); } } int main (int argc, char *argv[]) { // Ensure an argument was provided. if (argc != 2) { printf ("Usage: %s <path>\n", argv[0]); printf (" where <path> is the file or root of the tree you want to summarize.\n"); return 1; } num_dirs = 0; num_regular = 0; process_path(argv[1]); printf("There were %d directories.\n", num_dirs); printf("There were %d regular files.\n", num_regular); return 0; }
the_stack_data/170452420.c
#include <stdio.h> /* Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. */ int fibSum(int n) { int sum = 0; int cur = 2; int past = 1; int aux = 0; while (cur < n) { if (cur % 2 == 0) { sum += cur; } aux = cur; cur = past + cur; past = aux; } return sum; } int main() { int sum = fibSum(4000000); printf("Sum fib: %d", sum); return 0; }
the_stack_data/1007108.c
#ifndef IN_GENERATED_CCODE #define IN_GENERATED_CCODE #define U_DISABLE_RENAMING 1 #include "unicode/umachine.h" #endif U_CDECL_BEGIN const struct { double bogus; uint8_t bytes[3552]; } icudt57l_ibm_858_P100_1997_cnv={ 0.0, { 128,0,218,39,20,0,0,0,0,0,2,0,99,110,118,116, 6,2,0,0,57,1,0,0,32,67,111,112,121,114,105,103, 104,116,32,40,67,41,32,50,48,49,54,44,32,73,110,116, 101,114,110,97,116,105,111,110,97,108,32,66,117,115,105,110, 101,115,115,32,77,97,99,104,105,110,101,115,32,67,111,114, 112,111,114,97,116,105,111,110,32,97,110,100,32,111,116,104, 101,114,115,46,32,65,108,108,32,82,105,103,104,116,115,32, 82,101,115,101,114,118,101,100,46,32,0,0,0,0,0,0, 100,0,0,0,105,98,109,45,56,53,56,95,80,49,48,48, 45,49,57,57,55,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 90,3,0,0,0,2,1,1,127,0,0,0,1,0,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,4,4,31,0,1,0,0,0,0,0,0,0, 32,4,0,0,32,4,0,0,204,6,0,0,0,0,0,0, 40,6,0,0,0,0,0,128,1,0,0,128,2,0,0,128, 3,0,0,128,4,0,0,128,5,0,0,128,6,0,0,128, 7,0,0,128,8,0,0,128,9,0,0,128,10,0,0,128, 11,0,0,128,12,0,0,128,13,0,0,128,14,0,0,128, 15,0,0,128,16,0,0,128,17,0,0,128,18,0,0,128, 19,0,0,128,20,0,0,128,21,0,0,128,22,0,0,128, 23,0,0,128,24,0,0,128,25,0,0,128,28,0,0,128, 27,0,0,128,127,0,0,128,29,0,0,128,30,0,0,128, 31,0,0,128,32,0,0,128,33,0,0,128,34,0,0,128, 35,0,0,128,36,0,0,128,37,0,0,128,38,0,0,128, 39,0,0,128,40,0,0,128,41,0,0,128,42,0,0,128, 43,0,0,128,44,0,0,128,45,0,0,128,46,0,0,128, 47,0,0,128,48,0,0,128,49,0,0,128,50,0,0,128, 51,0,0,128,52,0,0,128,53,0,0,128,54,0,0,128, 55,0,0,128,56,0,0,128,57,0,0,128,58,0,0,128, 59,0,0,128,60,0,0,128,61,0,0,128,62,0,0,128, 63,0,0,128,64,0,0,128,65,0,0,128,66,0,0,128, 67,0,0,128,68,0,0,128,69,0,0,128,70,0,0,128, 71,0,0,128,72,0,0,128,73,0,0,128,74,0,0,128, 75,0,0,128,76,0,0,128,77,0,0,128,78,0,0,128, 79,0,0,128,80,0,0,128,81,0,0,128,82,0,0,128, 83,0,0,128,84,0,0,128,85,0,0,128,86,0,0,128, 87,0,0,128,88,0,0,128,89,0,0,128,90,0,0,128, 91,0,0,128,92,0,0,128,93,0,0,128,94,0,0,128, 95,0,0,128,96,0,0,128,97,0,0,128,98,0,0,128, 99,0,0,128,100,0,0,128,101,0,0,128,102,0,0,128, 103,0,0,128,104,0,0,128,105,0,0,128,106,0,0,128, 107,0,0,128,108,0,0,128,109,0,0,128,110,0,0,128, 111,0,0,128,112,0,0,128,113,0,0,128,114,0,0,128, 115,0,0,128,116,0,0,128,117,0,0,128,118,0,0,128, 119,0,0,128,120,0,0,128,121,0,0,128,122,0,0,128, 123,0,0,128,124,0,0,128,125,0,0,128,126,0,0,128, 26,0,0,128,199,0,0,128,252,0,0,128,233,0,0,128, 226,0,0,128,228,0,0,128,224,0,0,128,229,0,0,128, 231,0,0,128,234,0,0,128,235,0,0,128,232,0,0,128, 239,0,0,128,238,0,0,128,236,0,0,128,196,0,0,128, 197,0,0,128,201,0,0,128,230,0,0,128,198,0,0,128, 244,0,0,128,246,0,0,128,242,0,0,128,251,0,0,128, 249,0,0,128,255,0,0,128,214,0,0,128,220,0,0,128, 248,0,0,128,163,0,0,128,216,0,0,128,215,0,0,128, 146,1,0,128,225,0,0,128,237,0,0,128,243,0,0,128, 250,0,0,128,241,0,0,128,209,0,0,128,170,0,0,128, 186,0,0,128,191,0,0,128,174,0,0,128,172,0,0,128, 189,0,0,128,188,0,0,128,161,0,0,128,171,0,0,128, 187,0,0,128,145,37,0,128,146,37,0,128,147,37,0,128, 2,37,0,128,36,37,0,128,193,0,0,128,194,0,0,128, 192,0,0,128,169,0,0,128,99,37,0,128,81,37,0,128, 87,37,0,128,93,37,0,128,162,0,0,128,165,0,0,128, 16,37,0,128,20,37,0,128,52,37,0,128,44,37,0,128, 28,37,0,128,0,37,0,128,60,37,0,128,227,0,0,128, 195,0,0,128,90,37,0,128,84,37,0,128,105,37,0,128, 102,37,0,128,96,37,0,128,80,37,0,128,108,37,0,128, 164,0,0,128,240,0,0,128,208,0,0,128,202,0,0,128, 203,0,0,128,200,0,0,128,172,32,0,128,205,0,0,128, 206,0,0,128,207,0,0,128,24,37,0,128,12,37,0,128, 136,37,0,128,132,37,0,128,166,0,0,128,204,0,0,128, 128,37,0,128,211,0,0,128,223,0,0,128,212,0,0,128, 210,0,0,128,245,0,0,128,213,0,0,128,181,0,0,128, 254,0,0,128,222,0,0,128,218,0,0,128,219,0,0,128, 217,0,0,128,253,0,0,128,221,0,0,128,175,0,0,128, 180,0,0,128,173,0,0,128,177,0,0,128,23,32,0,128, 190,0,0,128,182,0,0,128,167,0,0,128,247,0,0,128, 184,0,0,128,176,0,0,128,168,0,0,128,183,0,0,128, 185,0,0,128,179,0,0,128,178,0,0,128,160,37,0,128, 160,0,0,128,128,0,64,0,64,0,64,0,64,0,64,0, 64,0,64,0,191,0,239,0,64,0,64,0,64,0,64,0, 64,0,64,0,64,0,64,0,64,0,64,0,64,0,64,0, 64,0,64,0,64,0,64,0,64,0,64,0,64,0,64,0, 64,0,64,0,64,0,64,0,64,0,64,0,64,0,64,0, 64,0,64,0,64,0,64,0,64,0,64,0,64,0,64,0, 64,0,64,0,64,0,64,0,64,0,64,0,64,0,64,0, 64,0,64,0,64,0,64,0,64,0,64,0,64,0,64,0, 64,0,22,1,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,64,0,80,0,96,0,112,0,128,0,144,0, 160,0,176,0,192,0,208,0,224,0,240,0,0,1,16,1, 32,1,48,1,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,64,1,80,1,96,1,112,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,121,1,135,1,139,1,0,0,0,0,0,0, 0,0,0,0,0,0,154,1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,170,1,178,1,0,0,0,0,0,0,0,0, 0,0,0,0,187,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,203,1,219,1,232,1,245,1,0,0,5,2,21,2, 0,0,37,2,52,2,68,2,82,2,95,2,107,2,0,0, 0,0,0,0,0,0,0,0,117,2,133,2,0,0,149,2, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 164,2,180,2,196,2,212,2,228,2,244,2,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,15,1,15,2,15,3,15,4,15,5,15,6,15,7,15, 8,15,9,15,10,15,11,15,12,15,13,15,14,15,15,15, 16,15,17,15,18,15,19,15,20,15,21,15,22,15,23,15, 24,15,25,15,127,15,27,15,26,15,29,15,30,15,31,15, 32,15,33,15,34,15,35,15,36,15,37,15,38,15,39,15, 40,15,41,15,42,15,43,15,44,15,45,15,46,15,47,15, 48,15,49,15,50,15,51,15,52,15,53,15,54,15,55,15, 56,15,57,15,58,15,59,15,60,15,61,15,62,15,63,15, 64,15,65,15,66,15,67,15,68,15,69,15,70,15,71,15, 72,15,73,15,74,15,75,15,76,15,77,15,78,15,79,15, 80,15,81,15,82,15,83,15,84,15,85,15,86,15,87,15, 88,15,89,15,90,15,91,15,92,15,93,15,94,15,95,15, 96,15,97,15,98,15,99,15,100,15,101,15,102,15,103,15, 104,15,105,15,106,15,107,15,108,15,109,15,110,15,111,15, 112,15,113,15,114,15,115,15,116,15,117,15,118,15,119,15, 120,15,121,15,122,15,123,15,124,15,125,15,126,15,28,15, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 255,15,173,15,189,15,156,15,207,15,190,15,221,15,245,15, 249,15,184,15,166,15,174,15,170,15,240,15,169,15,238,15, 248,15,241,15,253,15,252,15,239,15,230,15,244,15,250,15, 247,15,251,15,167,15,175,15,172,15,171,15,243,15,168,15, 183,15,181,15,182,15,199,15,142,15,143,15,146,15,128,15, 212,15,144,15,210,15,211,15,222,15,214,15,215,15,216,15, 209,15,165,15,227,15,224,15,226,15,229,15,153,15,158,15, 157,15,235,15,233,15,234,15,154,15,237,15,232,15,225,15, 133,15,160,15,131,15,198,15,132,15,134,15,145,15,135,15, 138,15,130,15,136,15,137,15,141,15,161,15,140,15,139,15, 208,15,164,15,149,15,162,15,147,15,228,15,148,15,246,15, 155,15,151,15,163,15,150,15,129,15,236,15,231,15,152,15, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,159,15,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 242,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,7,8,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,19,8, 0,0,238,8,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,213,15,0,0, 0,0,0,0,27,8,24,8,26,8,25,8,29,8,18,8, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,23,8,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,28,8,196,15,0,0,179,15,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,218,15, 0,0,0,0,0,0,191,15,0,0,0,0,0,0,192,15, 0,0,0,0,0,0,217,15,0,0,0,0,0,0,195,15, 0,0,0,0,0,0,0,0,180,15,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,194,15,0,0,0,0,0,0, 0,0,193,15,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,197,15,0,0,0,0,0,0,205,15,186,15,0,0, 0,0,201,15,0,0,0,0,187,15,0,0,0,0,200,15, 0,0,0,0,188,15,0,0,0,0,204,15,0,0,0,0, 185,15,0,0,0,0,203,15,0,0,0,0,202,15,0,0, 0,0,206,15,0,0,0,0,0,0,223,15,0,0,0,0, 0,0,220,15,0,0,0,0,0,0,219,15,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,176,15,177,15,178,15, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,254,15,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 22,8,0,0,0,0,0,0,30,8,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,16,8,0,0,31,8,0,0, 0,0,0,0,0,0,17,8,0,0,0,0,0,0,0,0, 0,0,0,0,9,8,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,8,8,10,8,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,8, 2,8,15,8,0,0,0,0,0,0,12,8,0,0,11,8, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,6,8,0,0,0,0, 5,8,0,0,3,8,4,8,0,0,0,0,0,0,13,8, 0,0,14,8,0,0,0,0,0,0,33,8,34,8,35,8, 36,8,37,8,38,8,39,8,40,8,41,8,42,8,43,8, 44,8,45,8,46,8,47,8,48,8,49,8,50,8,51,8, 52,8,53,8,54,8,55,8,56,8,57,8,58,8,59,8, 60,8,61,8,62,8,63,8,64,8,65,8,66,8,67,8, 68,8,69,8,70,8,71,8,72,8,73,8,74,8,75,8, 76,8,77,8,78,8,79,8,80,8,81,8,82,8,83,8, 84,8,85,8,86,8,87,8,88,8,89,8,90,8,91,8, 92,8,93,8,94,8,95,8,96,8,97,8,98,8,99,8, 100,8,101,8,102,8,103,8,104,8,105,8,106,8,107,8, 108,8,109,8,110,8,111,8,112,8,113,8,114,8,115,8, 116,8,117,8,118,8,119,8,120,8,121,8,122,8,123,8, 124,8,125,8,126,8,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,179,8,27,8,24,8,26,8,25,8, 254,8,9,8,0,0,0,0,170,170,170,170,170,170,170,170 } }; U_CDECL_END
the_stack_data/97012954.c
#include<stdio.h> #include<string.h> #include<stdlib.h> struct entry { char *name; char *val; }; enum { MAX_RECORDS = 0x20 }; enum { MAX_LEN = 0x400 }; char tag[MAX_LEN]; int tag_index; struct entry record[MAX_RECORDS]; int records; char *rtrim(char *buf) { char *p = buf + strlen(buf); while(p > buf && (!*p || *p == ' ' || *p == '\t')) { *p = 0; --p; } return buf; } void flush_record(void) { int i = 0; if(!*tag) { return; } printf(" [0x%08x]={\n", tag_index); printf(" .tag_%s={\n", tag); printf(" .tag_base.op=&op_%s,\n", tag); for(i = 0; i < records; ++i) { if(!strcmp("name", record[i].name) || !strcmp("byte_size", record[i].name)) { printf(" .tag_base.%s=%s,\n", record[i].name, rtrim(record[i].val)); } else { printf(" .%s=%s,\n", record[i].name, rtrim(record[i].val)); } free(record[i].name); free(record[i].val); } printf(" },\n"); printf(" },\n"); memset(record, 0, sizeof record); records = 0; tag_index = 0; tag[0] = 0; } char *tagdup(char *pc) { char *DW_AT_ = "DW_AT_"; int strlen_DW_AT_ = strlen(DW_AT_); char *b = strstr(pc, DW_AT_) + strlen_DW_AT_; char *e = strchr(b, ' '); char *tag = calloc(1, e - b + 1); char *t = tag; while(b != e) { *t++ = *b++; } return tag; } char *quotedup(char *pc) { char *trimmed = rtrim(pc); int len = strlen(trimmed) + 3; char *ret = calloc(len, 1); snprintf(ret, len, "\"%s\"", trimmed); return ret; } int parse_line(char *line) { { struct fmts { char *ofmt; char *ifmt; }; struct fmts fmts[] = { {"%d", " <%x> DW_AT_artificial : %d",}, {"%d", " <%x> DW_AT_bit_offset : %d",}, {"%d", " <%x> DW_AT_data_member_location : %d",}, {"%d", " <%x> DW_AT_bit_size : %d",}, {"%d", " <%x> DW_AT_byte_size : %d",}, {"%d", " <%x> DW_AT_const_value : %d",}, {"%d", " <%x> DW_AT_decl_file : %d",}, {"%d", " <%x> DW_AT_decl_line : %d",}, {"%d", " <%x> DW_AT_external : %d",}, {"%d", " <%x> DW_AT_prototyped : %d",}, {"%d", " <%x> DW_AT_upper_bound : %d",}, {"0x%08x", " <%x> DW_AT_high_pc : %x ",}, {"0x%08x", " <%x> DW_AT_low_pc : %x ",}, {"0x%08x", " <%x> DW_AT_stmt_list : %x ",}, {"0x%08x", " <%x> DW_AT_sibling : <0x%x> ",}, {"0x%08x", " <%x> DW_AT_type : <0x%x> ",}, }; int i = 0; for(i = 0; i < sizeof(fmts) / sizeof(fmts[0]); ++i) { unsigned int u = 0; unsigned int val = 0; char *ifmt = fmts[i].ifmt; char *ofmt = fmts[i].ofmt; if(2 == sscanf(line, ifmt, &u, &val)) { char n[0x20] = ""; struct entry *entry = record + records++; snprintf(n, (int)sizeof(n) - 1, ofmt, val); entry->val = strdup(n); entry->name = tagdup(ifmt); return 1; } } } { char buf[MAX_LEN] = ""; unsigned int u0; unsigned int u1; char *fmts[] = { " <%x> DW_AT_comp_dir : (indirect string, offset: 0x%x): %[^\n]", " <%x> DW_AT_name : (indirect string, offset: 0x%x): %[^\n]", }; int i = 0; for(i = 0; i < sizeof(fmts) / sizeof(fmts[0]); ++i) { char *fmt = fmts[i]; if(3 == sscanf(line, fmt, &u0, &u1, buf)) { struct entry *entry = record + records++; entry->val = quotedup(buf); entry->name = tagdup(fmt); return 1; } } } { unsigned int u; unsigned int val; char buf[MAX_LEN] = ""; char *fmt = " <%x> DW_AT_encoding : %d (%s)"; if(3 == sscanf(line, fmt, &u, &val, buf)) { char n[0x20] = ""; struct entry *entry = record + records++; snprintf(n, (int)sizeof(n) - 1, "%d", val); entry->val = strdup(n); entry->name = tagdup(fmt); return 1; } } { unsigned int u; char buf[MAX_LEN] = ""; char *fmt = " <%x> DW_AT_name : %s"; if(2 == sscanf(line, fmt, &u, buf)) { struct entry *entry = record + records++; entry->val = quotedup(buf); entry->name = tagdup(fmt); return 1; } } return 0; } int main() { int trig = 0; printf("union tag tags[]={\n"); for(;;) { char line[MAX_LEN]; memset(line, 0, sizeof line); if(!fgets(line, (int)sizeof(line) - 1, stdin)) { break; } else if(!trig && strstr(line, "Contents of the .debug_info section")) { trig = 1; continue; } else if(!trig) { continue; } else if(trig && strstr(line, "Contents of the .debug_abbrev section")) { break; } else if(!strchr(line, '<')) { continue; } else { int found = 0; int i = 0; char *ignore[] = { "DW_AT_language", "DW_AT_location", "DW_AT_producer", "DW_AT_frame_base", }; for(i = 0; i < sizeof(ignore) / sizeof(ignore[0]); ++i) { if(strstr(line, ignore[i])) { found = 1; break; } } if(found) { continue; } } if(parse_line(line)) { continue; } { char buf[MAX_LEN] = ""; unsigned int u0; unsigned int val; int i0; if(4 == sscanf(line, " <%x><%x>: Abbrev Number: %d (DW_TAG_%[^)]", &u0, &val, &i0, buf)) { flush_record(); tag_index = val; strcpy(tag, buf); } } } flush_record(); printf("};\n"); printf("struct taglim taglim = {\n"); printf(" .base=tags,\n"); printf(" .nelem=sizeof tags/sizeof tags[0],\n"); printf("};\n"); return 0; }
the_stack_data/659169.c
#include <curses.h> void curses_init() { initscr(); start_color(); init_pair(1, COLOR_WHITE, COLOR_BLACK); init_pair(2, COLOR_BLUE, COLOR_BLACK); init_pair(3, COLOR_GREEN, COLOR_BLACK); init_pair(4, COLOR_RED, COLOR_BLACK); refresh(); keypad(stdscr,TRUE); nonl(); cbreak(); noecho(); curs_set(0); clear(); bkgd(COLOR_PAIR(2)); } void curses_exit() { clear(); endwin(); } void curses_clear_screen() { clear(); } void curses_refresh() { refresh(); } void curses_show_char(int y, int x, int ch) { mvaddch(y, x, ch); }
the_stack_data/79495.c
#include <stdio.h> int main(void) { int count; for (count=1; count<10; count++) { if (count % 15 == 0) printf("FizzBuzz"); else if (count % 3 == 0) printf("Fizz"); else if (count % 5 == 0) printf("Buzz"); else printf("%d", count); if (count<10) printf(", ", count); } printf("\r\n"); return 0; }