file
stringlengths
18
26
data
stringlengths
4
1.03M
the_stack_data/14199182.c
#include <stdio.h> int main(int argc, char *argv[] ) { char *line = NULL; size_t size; // get input from stdin while (getline(&line, &size, stdin) != -1) { if (*argv[1] == 'a'){ // append to the file provided FILE *file = fopen(argv[argc-1], "a"); fprintf(file,line); fprintf(stdout,line); fclose(file); } if(argv[2]){ // write to the file provided FILE *file1 = fopen(argv[argc-1], "w"); fprintf(file1,line); fprintf(stdout,line); fclose(file1); } } } // 3) In general, this worked fairly well for me once I understood what was actually going on. I guess one thing I want to do in the future is not be so intimidated by the language and the man pages. I also kind of assume that hardcoding for the argument placement would not actually work in a function that would be used "in real life". I was shocked in that my code worked the first time I tested it, but I had a bit of trouble figuring out how to read the input buffer, and had to consult a few stack overflow pages. // 4) I was shocked by how long the professional code was. Essentially, I noticed a lot of extra checks and accounting for all sorts of edge cases which I didn't think about or take into account. They also included all sorts of fancy warnings and pointer things which I don't know how to use or work with yet.
the_stack_data/41847.c
/*------------------------------------------------------------------------- * * pg_id.c-- * Print the user ID for the login name passed as argument, * or the real user ID of the caller if no argument. If the * login name doesn't exist, print "NOUSER" and exit 1. * * Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * $Header: /usr/local/cvsroot/postgres95/src/bin/pg_id/pg_id.c,v 1.1.1.1 1996/07/09 06:22:14 scrappy Exp $ * *------------------------------------------------------------------------- */ #include <sys/types.h> #include <pwd.h> #include <stdio.h> int main(int argc, char **argv) { struct passwd *pw; int ch; extern int optind; while ((ch = getopt(argc, argv, "")) != EOF) switch (ch) { case '?': default: fprintf(stderr, "usage: pg_id [login]\n"); exit(1); } argc -= optind; argv += optind; if (argc > 0) { if (argc > 1) { fprintf(stderr, "usage: pg_id [login]\n"); exit(1); } if ((pw = getpwnam(argv[0])) == NULL) { printf("NOUSER\n"); exit(1); } printf("%d\n", pw->pw_uid); } else { printf("%d\n", getuid()); } exit(0); }
the_stack_data/25138117.c
/* ----------------------------------------------------------------------- * * * Copyright (C) 2009 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * H. Peter Anvin <[email protected]> * * ----------------------------------------------------------------------- */ /* * Compute the desired load offset from a compressed program; outputs * a small assembly wrapper with the appropriate symbols defined. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> static uint32_t getle32(const void *p) { const uint8_t *cp = p; return (uint32_t)cp[0] + ((uint32_t)cp[1] << 8) + ((uint32_t)cp[2] << 16) + ((uint32_t)cp[3] << 24); } int main(int argc, char *argv[]) { uint32_t olen; long ilen; unsigned long offs; FILE *f; if (argc < 2) { fprintf(stderr, "Usage: %s compressed_file\n", argv[0]); return 1; } /* Get the information for the compressed kernel image first */ f = fopen(argv[1], "r"); if (!f) { perror(argv[1]); return 1; } if (fseek(f, -4L, SEEK_END)) { perror(argv[1]); } fread(&olen, sizeof olen, 1, f); ilen = ftell(f); olen = getle32(&olen); fclose(f); /* * Now we have the input (compressed) and output (uncompressed) * sizes, compute the necessary decompression offset... */ offs = (olen > ilen) ? olen - ilen : 0; offs += olen >> 12; /* Add 8 bytes for each 32K block */ offs += 32*1024 + 18; /* Add 32K + 18 bytes slack */ offs = (offs+4095) & ~4095; /* Round to a 4K boundary */ printf(".section \".rodata.compressed\",\"a\",@progbits\n"); printf(".globl z_input_len\n"); printf("z_input_len = %lu\n", ilen); printf(".globl z_output_len\n"); printf("z_output_len = %lu\n", (unsigned long)olen); printf(".globl z_extract_offset\n"); printf("z_extract_offset = 0x%lx\n", offs); /* z_extract_offset_negative allows simplification of head_32.S */ printf(".globl z_extract_offset_negative\n"); printf("z_extract_offset_negative = -0x%lx\n", offs); printf(".globl input_data, input_data_end\n"); printf("input_data:\n"); printf(".incbin \"%s\"\n", argv[1]); printf("input_data_end:\n"); return 0; }
the_stack_data/1178323.c
/* * /src/NTP/REPOSITORY/ntp4-dev/libparse/clk_trimtsip.c,v 4.19 2009/11/01 10:47:49 kardel RELEASE_20091101_A * * clk_trimtsip.c,v 4.19 2009/11/01 10:47:49 kardel RELEASE_20091101_A * * Trimble TSIP support * Thanks to Sven Dietrich for providing test hardware * * Copyright (c) 1995-2009 by Frank Kardel <kardel <AT> ntp.org> * Copyright (c) 1989-1994 by Frank Kardel, Friedrich-Alexander Universitaet Erlangen-Nuernberg, Germany * * 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. Neither the name of the author 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 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 HAVE_CONFIG_H # include <config.h> #endif #if defined(REFCLOCK) && defined(CLOCK_PARSE) && defined(CLOCK_TRIMTSIP) #include "ntp_syslog.h" #include "ntp_types.h" #include "ntp_fp.h" #include "timevalops.h" #include "ntp_calendar.h" #include "ntp_machine.h" #include "ntp_stdlib.h" #include "parse.h" #ifndef PARSESTREAM # include <stdio.h> #else # include "sys/parsestreams.h" #endif #include "ascii.h" #include "binio.h" #include "ieee754io.h" #include "trimble.h" /* * Trimble low level TSIP parser / time converter * * The receiver uses a serial message protocol called Trimble Standard * Interface Protocol (it can support others but this driver only supports * TSIP). Messages in this protocol have the following form: * * <DLE><id> ... <data> ... <DLE><ETX> * * Any bytes within the <data> portion of value 10 hex (<DLE>) are doubled * on transmission and compressed back to one on reception. Otherwise * the values of data bytes can be anything. The serial interface is RS-422 * asynchronous using 9600 baud, 8 data bits with odd party (**note** 9 bits * in total!), and 1 stop bit. The protocol supports byte, integer, single, * and double datatypes. Integers are two bytes, sent most significant first. * Singles are IEEE754 single precision floating point numbers (4 byte) sent * sign & exponent first. Doubles are IEEE754 double precision floating point * numbers (8 byte) sent sign & exponent first. * The receiver supports a large set of messages, only a very small subset of * which is used here. * * From this module the following are recognised: * * ID Description * * 41 GPS Time * 46 Receiver health * 4F UTC correction data (used to get leap second warnings) * * All others are accepted but ignored for time conversion - they are passed up to higher layers. * */ static offsets_t trim_offsets = { 0, 1, 2, 3, 4, 5, 6, 7 }; struct trimble { u_char t_in_pkt; /* first DLE received */ u_char t_dle; /* subsequent DLE received */ u_short t_week; /* GPS week */ u_short t_weekleap; /* GPS week of next/last week */ u_short t_dayleap; /* day in week */ u_short t_gpsutc; /* GPS - UTC offset */ u_short t_gpsutcleap; /* offset at next/last leap */ u_char t_operable; /* receiver feels OK */ u_char t_mode; /* actual operating mode */ u_char t_leap; /* possible leap warning */ u_char t_utcknown; /* utc offset known */ }; #define STATUS_BAD 0 /* BAD or UNINITIALIZED receiver status */ #define STATUS_UNSAFE 1 /* not enough receivers for full precision */ #define STATUS_SYNC 2 /* enough information for good operation */ static unsigned long inp_tsip (parse_t *, char, timestamp_t *); static unsigned long cvt_trimtsip (unsigned char *, int, struct format *, clocktime_t *, void *); struct clockformat clock_trimtsip = { inp_tsip, /* Trimble TSIP input handler */ cvt_trimtsip, /* Trimble TSIP conversion */ pps_one, /* easy PPS monitoring */ 0, /* no configuration data */ "Trimble TSIP", 400, /* input buffer */ sizeof(struct trimble) /* private data */ }; #define ADDSECOND 0x01 #define DELSECOND 0x02 static unsigned long inp_tsip( parse_t *parseio, char ch, timestamp_t *tstamp ) { struct trimble *t = (struct trimble *)parseio->parse_pdata; if (!t) return PARSE_INP_SKIP; /* local data not allocated - sigh! */ if (!t->t_in_pkt && ch != DLE) { /* wait for start of packet */ return PARSE_INP_SKIP; } if ((parseio->parse_index >= (parseio->parse_dsize - 2)) || (parseio->parse_dtime.parse_msglen >= (sizeof(parseio->parse_dtime.parse_msg) - 2))) { /* OVERFLOW - DROP! */ t->t_in_pkt = t->t_dle = 0; parseio->parse_index = 0; parseio->parse_dtime.parse_msglen = 0; return PARSE_INP_SKIP; } switch (ch) { case DLE: if (!t->t_in_pkt) { t->t_dle = 0; t->t_in_pkt = 1; parseio->parse_index = 0; parseio->parse_data[parseio->parse_index++] = ch; parseio->parse_dtime.parse_msglen = 0; parseio->parse_dtime.parse_msg[parseio->parse_dtime.parse_msglen++] = ch; parseio->parse_dtime.parse_stime = *tstamp; /* pick up time stamp at packet start */ } else if (t->t_dle) { /* Double DLE -> insert a DLE */ t->t_dle = 0; parseio->parse_data[parseio->parse_index++] = DLE; parseio->parse_dtime.parse_msg[parseio->parse_dtime.parse_msglen++] = DLE; } else t->t_dle = 1; break; case ETX: if (t->t_dle) { /* DLE,ETX -> end of packet */ parseio->parse_data[parseio->parse_index++] = DLE; parseio->parse_data[parseio->parse_index] = ch; parseio->parse_ldsize = (u_short) (parseio->parse_index + 1); memcpy(parseio->parse_ldata, parseio->parse_data, parseio->parse_ldsize); parseio->parse_dtime.parse_msg[parseio->parse_dtime.parse_msglen++] = DLE; parseio->parse_dtime.parse_msg[parseio->parse_dtime.parse_msglen++] = ch; t->t_in_pkt = t->t_dle = 0; return PARSE_INP_TIME|PARSE_INP_DATA; } /*FALLTHROUGH*/ default: /* collect data */ t->t_dle = 0; parseio->parse_data[parseio->parse_index++] = ch; parseio->parse_dtime.parse_msg[parseio->parse_dtime.parse_msglen++] = ch; } return PARSE_INP_SKIP; } static short getshort( unsigned char *p ) { return (short) get_msb_short(&p); } /* * cvt_trimtsip * * convert TSIP type format */ static unsigned long cvt_trimtsip( unsigned char *buffer, int size, struct format *format, clocktime_t *clock_time, void *local ) { register struct trimble *t = (struct trimble *)local; /* get local data space */ #define mb(_X_) (buffer[2+(_X_)]) /* shortcut for buffer access */ register u_char cmd; clock_time->flags = 0; if (!t) { return CVT_NONE; /* local data not allocated - sigh! */ } if ((size < 4) || (buffer[0] != DLE) || (buffer[size-1] != ETX) || (buffer[size-2] != DLE)) { printf("TRIMBLE BAD packet, size %d:\n", size); return CVT_NONE; } else { unsigned char *bp; cmd = buffer[1]; switch(cmd) { case CMD_RCURTIME: { /* GPS time */ l_fp secs; u_int week = getshort((unsigned char *)&mb(4)); l_fp utcoffset; l_fp gpstime; bp = &mb(0); if (fetch_ieee754(&bp, IEEE_SINGLE, &secs, trim_offsets) != IEEE_OK) return CVT_FAIL|CVT_BADFMT; if ((secs.l_i <= 0) || (t->t_utcknown == 0)) { clock_time->flags = PARSEB_POWERUP; return CVT_OK; } week = basedate_expand_gpsweek(week); /* time OK */ /* fetch UTC offset */ bp = &mb(6); if (fetch_ieee754(&bp, IEEE_SINGLE, &utcoffset, trim_offsets) != IEEE_OK) return CVT_FAIL|CVT_BADFMT; L_SUB(&secs, &utcoffset); /* adjust GPS time to UTC time */ gpstolfp((unsigned short)week, (unsigned short)0, secs.l_ui, &gpstime); gpstime.l_uf = secs.l_uf; clock_time->utctime = gpstime.l_ui - JAN_1970; TSFTOTVU(gpstime.l_uf, clock_time->usecond); if (t->t_leap == ADDSECOND) clock_time->flags |= PARSEB_LEAPADD; if (t->t_leap == DELSECOND) clock_time->flags |= PARSEB_LEAPDEL; switch (t->t_operable) { case STATUS_SYNC: clock_time->flags &= ~(PARSEB_POWERUP|PARSEB_NOSYNC); break; case STATUS_UNSAFE: clock_time->flags |= PARSEB_NOSYNC; break; case STATUS_BAD: clock_time->flags |= PARSEB_NOSYNC|PARSEB_POWERUP; break; } if (t->t_mode == 0) clock_time->flags |= PARSEB_POSITION; clock_time->flags |= PARSEB_S_LEAP|PARSEB_S_POSITION; return CVT_OK; } /* case 0x41 */ case CMD_RRECVHEALTH: { /* TRIMBLE health */ u_char status = mb(0); switch (status) { case 0x00: /* position fixes */ t->t_operable = STATUS_SYNC; break; case 0x09: /* 1 satellite */ case 0x0A: /* 2 satellites */ case 0x0B: /* 3 satellites */ t->t_operable = STATUS_UNSAFE; break; default: t->t_operable = STATUS_BAD; break; } t->t_mode = status; } break; case CMD_RUTCPARAM: { l_fp t0t; unsigned char *lbp; /* UTC correction data - derive a leap warning */ int tls = t->t_gpsutc = (u_short) getshort((unsigned char *)&mb(12)); /* current leap correction (GPS-UTC) */ int tlsf = t->t_gpsutcleap = (u_short) getshort((unsigned char *)&mb(24)); /* new leap correction */ t->t_weekleap = basedate_expand_gpsweek( (u_short) getshort((unsigned char *)&mb(20))); /* week no of leap correction */ t->t_dayleap = (u_short) getshort((unsigned char *)&mb(22)); /* day in week of leap correction */ t->t_week = basedate_expand_gpsweek( (u_short) getshort((unsigned char *)&mb(18))); /* current week no */ lbp = (unsigned char *)&mb(14); /* last update time */ if (fetch_ieee754(&lbp, IEEE_SINGLE, &t0t, trim_offsets) != IEEE_OK) return CVT_FAIL|CVT_BADFMT; t->t_utcknown = t0t.l_ui != 0; if ((t->t_utcknown) && /* got UTC information */ (tlsf != tls) && /* something will change */ ((t->t_weekleap - t->t_week) < 5)) /* and close in the future */ { /* generate a leap warning */ if (tlsf > tls) t->t_leap = ADDSECOND; else t->t_leap = DELSECOND; } else { t->t_leap = 0; } } break; default: /* it's validly formed, but we don't care about it! */ break; } } return CVT_SKIP; } #else /* not (REFCLOCK && CLOCK_PARSE && CLOCK_TRIMTSIP && !PARSESTREAM) */ int clk_trimtsip_bs; #endif /* not (REFCLOCK && CLOCK_PARSE && CLOCK_TRIMTSIP && !PARSESTREAM) */ /* * History: * * clk_trimtsip.c,v * Revision 4.19 2009/11/01 10:47:49 kardel * de-P() * * Revision 4.18 2009/11/01 08:46:46 kardel * clarify case FALLTHROUGH * * Revision 4.17 2005/04/16 17:32:10 kardel * update copyright * * Revision 4.16 2004/11/14 15:29:41 kardel * support PPSAPI, upgrade Copyright to Berkeley style * * Revision 4.13 1999/11/28 09:13:51 kardel * RECON_4_0_98F * * Revision 4.12 1999/02/28 13:00:08 kardel * *** empty log message *** * * Revision 4.11 1999/02/28 11:47:54 kardel * (struct trimble): new member t_utcknown * (cvt_trimtsip): fixed status monitoring, bad receiver states are * now recognized * * Revision 4.10 1999/02/27 15:57:15 kardel * use mmemcpy instead of bcopy * * Revision 4.9 1999/02/21 12:17:42 kardel * 4.91f reconcilation * * Revision 4.8 1998/11/15 20:27:58 kardel * Release 4.0.73e13 reconcilation * * Revision 4.7 1998/08/16 18:49:20 kardel * (cvt_trimtsip): initial kernel capable version (no more floats) * (clock_trimtsip =): new format name * * Revision 4.6 1998/08/09 22:26:05 kardel * Trimble TSIP support * * Revision 4.5 1998/08/02 10:37:05 kardel * working TSIP parser * * Revision 4.4 1998/06/28 16:50:40 kardel * (getflt): fixed ENDIAN issue * (getdbl): fixed ENDIAN issue * (getint): use get_msb_short() * (cvt_trimtsip): use gpstolfp() for conversion * * Revision 4.3 1998/06/13 12:07:31 kardel * fix SYSV clock name clash * * Revision 4.2 1998/06/12 15:22:30 kardel * fix prototypes * * Revision 4.1 1998/05/24 09:39:54 kardel * implementation of the new IO handling model * * Revision 4.0 1998/04/10 19:45:32 kardel * Start 4.0 release version numbering * * from V3 1.8 loginfo deleted 1998/04/11 kardel */
the_stack_data/95449434.c
/* * Example C code from TA. * Your interpreter & debuger should be able to handle this example code. */ int avg(int count, int *value) { int i, total; total = 0; for(i = 0; i < count; i++) { total = total + value[i]; } return (total / count); } int main(void) { int student_number, count, i, sum; int mark[4]; float average; count = 4; sum = 0; for(i = 0; i < count; i++) { mark[i] = i * 30; sum = sum + mark[i]; average = avg(i + 1, mark); if(average > 40) { printf("%f\n", average); } } }
the_stack_data/111077880.c
/* * Write a program that uses one printf() call to print your first name and * last name on one line, uses a second printf() call to print your first and * last names on two separate lines, and uses a pair of printf() calls to print * your first and last names on one line. The output should look something like this * * Ken Goettler * Ken * Goettler * Ken Goettler * */ #include <stdio.h> #define FIRST_NAME "Ken" #define LAST_NAME "Goettler" int main (void) { printf("%s %s\n", FIRST_NAME, LAST_NAME); printf("%s\n%s\n", FIRST_NAME, LAST_NAME); printf("%s", FIRST_NAME); printf(" %s\n", LAST_NAME); }
the_stack_data/184519000.c
/* { dg-do compile } */ /* { dg-options "-O" } */ /* { dg-final { scan-assembler "fs:16" } } */ /* { dg-final { scan-assembler "gs:16" } } */ int test(void) { int __seg_fs *f = (int __seg_fs *)16; int __seg_gs *g = (int __seg_gs *)16; return *f + *g; }
the_stack_data/76699182.c
#include <stdio.h> int main() { int a[20],freq[20],i,j,n=10,count; for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n;i++) { count=1; for(j=i+1;j<n;j++) { if(a[i]==a[j]) { count++; freq[j]=0; } } if(freq[i]!=0) a[i]=count; } for(i=0;i<n;i++) { if(freq[i]!=0) { printf("%d occurs %d times\n",a[i],freq[i]); } } }
the_stack_data/701404.c
// Test from Gopan - SAS07 // Cited by Gulwani in Control-flow refinement and Progress invariants for Bound // Analysis - PLDI'09 // #include <stdio.h> int main() { int x,y,z,k; x=0; y=0; while (y>=0) { while(y>=0 && x<=50) { x++; y++; } while (y>=0 && x>50) { y--; x++; } } if(x==103) printf("property verified\n"); }
the_stack_data/541656.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> /* Trabalho de Grupo * Docente: Mário Simões * Alunos: Gustavo Campos 47576 * Tiago Cebola 47594 * * Build: gcc -std=c99 exe4.c -o exe4 */ #define MAX_WORDS 5 #define MAX_NAME_COUNT 50 #define MAX_NAME_SIZE 255 /*Máximo de caracteres por linha pré-definido */ /*Função que verifica se a palavra em nameWord é idêntica a alguma * das strings indicadas pelos ponteiros do array lowerWords*/ int verify(char *nameWord, char *lowerWords[], int numWords ) { int size = strlen(nameWord); for ( int i = 0; i < size ; i++ ) { /* Ciclo inicial que coloca a string toda em minúsculo */ nameWord[i] = tolower(nameWord[i]); } int result; /* Váriavel que guarda o retorno da função */ for (int i = 0; i < numWords; i++ ) { result = strcmp(nameWord, lowerWords[i]); if ( result == 0 ) return 1; } return 0; } /*Função que em nameWord converte-a para a forma padrão: a primeira * letra em maiúscula e as restantes para minúscula; exceção – se a * palavra existir nas strings indicadas por lowerWords, deve ficar * toda em minúsculas. Deve utilizar a função anterior.*/ void upper_first(char *nameWord, char *lowerWords[], int numWords ) { int i = 0; int save; save = verify( nameWord, lowerWords, numWords); if ( save == 0 ) nameWord[i] = toupper(nameWord[i]); } /*Função que recebendo em name um nome formado por várias palavras, * separadas, antecedidas ou sucedidas por um ou vários espaços ou * Tabs, reproduz a string com as palavras convertidas para a forma * padrão e separadas por um espaço, sem espaços no início nem no fim.*/ void unifyName(char *name, char *lowerWords[], int numWords ) { char *aux; int size = strlen(name) - 1; char save_string[size]; /* Array auxiliar para guardar tokens */ int i = 0; aux = strtok(name, " \t"); /* Utilização da função strtok e os seus delimitadores (Espaço e Tab) */ while ( aux != NULL ) { /* Ciclo que percorre os restantes nomes e faz uso da função upper_first para deixar no formato correto */ upper_first(aux, lowerWords, numWords ); for( int j = 0; aux[j] != 0; j++){ save_string[i] = aux[j]; i++; } save_string[i] = ' '; /* Adiciona espaços entre nomes */ i++; aux = strtok(NULL, " \t"); } save_string[--i] = '\0'; /* Terminador da String */ strcpy(name, save_string); /* Guarda a string correta em name */ } /*que lê, a partir da stream indicada, um nome, o qual uniformiza e armazena na string indicada apor name. Para ler, deve usar a função fgets da biblioteca normalizada; para uniformizar o nome, deve utilizar as funções do exercício anterior. Retorna: 1, em caso de sucesso; 0, se ocorreu end-of-file na leitura. */ int fillName(char *name, FILE *stream ) { char *lowerWords[MAX_WORDS]; /* Um array de ponteiros que contém as lowerWords pré-definidas */ lowerWords[0] = "dos"; lowerWords[1] = "do"; lowerWords[2] = "da"; lowerWords[3] = "de"; lowerWords[4] = "e"; char line_feed[] = "\n"; do { if ( fgets(name, MAX_NAME_SIZE, stream) == NULL ) return 0; } while ( strcmp(name, line_feed) == 0 ); name[strlen(name) - 1] = 0; unifyName(name, lowerWords, MAX_WORDS ); return 1; } int cmpchar ( const void *name1, const void *name2 ) { int x = strcmp( (char*)name1, (char*)name2 ); return x; } /*que ordena o array name, por ordem alfabética crescente. O parâmetro count é o número de elementos preenchidos no array. Para ordenar o array, deve utilizar a função qsort da biblioteca normalizada. É necessário escrever uma função de comparação que identifica a ordem relativa entre duas strings. Esta função é passada por parâmetro à função qsort. */ void sortNames( char name[][MAX_NAME_SIZE], int count ) { qsort( (void*)name, count, sizeof *name, cmpchar ); printf("Array de nomes ordenados:\n"); for ( int i = 0; i < count; i++) { printf("%s\n", name[i] ); } } int main () { char names[MAX_NAME_COUNT][MAX_NAME_SIZE]; int i = 0; printf("Introduza uma sequencia de nomes: "); while ( fillName(names[i], stdin) ) i++; sortNames(names, i); return 0; }
the_stack_data/97013004.c
// Generate random passwords #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <time.h> #define ALPHABET_LENGTH 26 #define NUMBERS_LENGTH 10 #define SPECIAL_CHARS_LENGTH 7 int main(int argc, char *argv[]) { // Ensure proper usage if (argc > 2) { printf("Usage: You must provide only one argument\n"); return 1; } else if (argc < 2) { printf("Usage: You must provide an argument\n"); return 1; } char *argument = argv[1]; // Ensure argument is a digit if (!isdigit(*argument)) { printf("Usage: The argument must be a number\n"); return 1; } int pass_length = atoi(argument); // A few more usage checks if (pass_length < 4) { printf("Usage: The minimum length has to be 4\n"); return 1; } else if (pass_length >90) { printf("Usage: The maximum length has to be 90\n"); return 1; } const char alphabet[ALPHABET_LENGTH] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; const char numbers[NUMBERS_LENGTH] = {'0','1','2','3','4','5','6','7','8','9'}; const char special_characters[SPECIAL_CHARS_LENGTH] = {'!','@','#','$','%','&','*'}; char pass_arr[pass_length]; srand(time(0)); // Get a random letter from alphabet, convert to uppercase and insert in pass_arr int random_1 = rand() % ALPHABET_LENGTH; char letter = alphabet[random_1]; char upper_letter = toupper(letter); pass_arr[0] = upper_letter; // Get a random special character and insert in pass_arr int random_2 = rand() % SPECIAL_CHARS_LENGTH; char special = special_characters[random_2]; pass_arr[1] = special; // Get a random number and insert in pass_arr int random_3 = rand() % NUMBERS_LENGTH; char number = numbers[random_3]; pass_arr[2] = number; // Get random letters from alphabet and insert in pass_arr for (int i = 3; i < pass_length; i++) { int random = rand() % 26; char item = alphabet[random]; pass_arr[i] = item; } // Print generated password for (int i = 0; i < pass_length; i++) { printf("%c", pass_arr[i]); } printf("\n"); return 0; }
the_stack_data/36349.c
#include <stdio.h> void PrintPrime(int n) { int i; for (i = 2; i<= n; i=i+2) { if ((i == 2 || i == 3) || (i == 5 || i == 7)) { printf("%d ", i); if (i == 2) { i = 1; } } else if ((i % 3 == 0 || i % 5 == 0) || i % 7 == 0) { continue; } else { printf("%d ", i); } } } int main() { int n; printf("Enter the last number : "); scanf("%d", &n); PrintPrime(n); return 0; }
the_stack_data/72011958.c
int SIZE = 50000001; int __VERIFIER_nondet_int(); extern void __VERIFIER_error(void); extern void __VERIFIER_assume(int); void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; } int main() { int i,j; i = 0; j=0; while(i<SIZE){ if(__VERIFIER_nondet_int()) i = i + 8; else i = i + 4; } j = i/4 ; __VERIFIER_assert( (j * 4) == i); return 0; }
the_stack_data/242331768.c
// KMSAN: uninit-value in packet_set_ring // https://syzkaller.appspot.com/bug?id=92ec3093576975e2b3e68a0c377e060a81c655e4 // status:fixed // autogenerated by syzkaller (http://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <dirent.h> #include <endian.h> #include <errno.h> #include <errno.h> #include <errno.h> #include <errno.h> #include <fcntl.h> #include <fcntl.h> #include <linux/capability.h> #include <linux/futex.h> #include <linux/if.h> #include <linux/if_ether.h> #include <linux/if_tun.h> #include <linux/ip.h> #include <linux/net.h> #include <linux/tcp.h> #include <net/if_arp.h> #include <netinet/in.h> #include <pthread.h> #include <sched.h> #include <signal.h> #include <signal.h> #include <stdarg.h> #include <stdarg.h> #include <stdarg.h> #include <stdbool.h> #include <stdbool.h> #include <stdio.h> #include <stdio.h> #include <stdio.h> #include <stdlib.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <sys/mount.h> #include <sys/mount.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/wait.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> __attribute__((noreturn)) static void doexit(int status) { volatile unsigned i; syscall(__NR_exit_group, status); for (i = 0;; i++) { } } #include <errno.h> #include <setjmp.h> #include <signal.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string.h> #include <sys/stat.h> const int kFailStatus = 67; const int kRetryStatus = 69; static void fail(const char* msg, ...) { int e = errno; va_list args; va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, " (errno %d)\n", e); doexit((e == ENOMEM || e == EAGAIN) ? kRetryStatus : kFailStatus); } static void exitf(const char* msg, ...) { int e = errno; va_list args; va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, " (errno %d)\n", e); doexit(kRetryStatus); } static __thread int skip_segv; static __thread jmp_buf segv_env; static void segv_handler(int sig, siginfo_t* info, void* uctx) { 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); } doexit(sig); } static void install_segv_handler() { 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 uint64_t current_time_ms() { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) fail("clock_gettime failed"); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static void use_temporary_dir() { char tmpdir_template[] = "./syzkaller.XXXXXX"; char* tmpdir = mkdtemp(tmpdir_template); if (!tmpdir) fail("failed to mkdtemp"); if (chmod(tmpdir, 0777)) fail("failed to chmod"); if (chdir(tmpdir)) fail("failed to chdir"); } static void vsnprintf_check(char* str, size_t size, const char* format, va_list args) { int rv; rv = vsnprintf(str, size, format, args); if (rv < 0) fail("tun: snprintf failed"); if ((size_t)rv >= size) fail("tun: string '%s...' doesn't fit into buffer", str); } static void snprintf_check(char* str, size_t size, const char* format, ...) { va_list args; va_start(args, format); vsnprintf_check(str, size, format, args); va_end(args); } #define COMMAND_MAX_LEN 128 #define PATH_PREFIX \ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin " #define PATH_PREFIX_LEN (sizeof(PATH_PREFIX) - 1) static void execute_command(bool panic, const char* format, ...) { va_list args; char command[PATH_PREFIX_LEN + COMMAND_MAX_LEN]; int rv; va_start(args, format); memcpy(command, PATH_PREFIX, PATH_PREFIX_LEN); vsnprintf_check(command + PATH_PREFIX_LEN, COMMAND_MAX_LEN, format, args); va_end(args); rv = system(command); if (rv) { if (panic) fail("command '%s' failed: %d", &command[0], rv); } } static int tunfd = -1; static int tun_frags_enabled; #define SYZ_TUN_MAX_PACKET_SIZE 1000 #define TUN_IFACE "syz_tun" #define LOCAL_MAC "aa:aa:aa:aa:aa:aa" #define REMOTE_MAC "aa:aa:aa:aa:aa:bb" #define LOCAL_IPV4 "172.20.20.170" #define REMOTE_IPV4 "172.20.20.187" #define LOCAL_IPV6 "fe80::aa" #define REMOTE_IPV6 "fe80::bb" #define IFF_NAPI 0x0010 #define IFF_NAPI_FRAGS 0x0020 static void initialize_tun(void) { tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK); if (tunfd == -1) { printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n"); printf("otherwise fuzzing or reproducing might not work as intended\n"); return; } const int kTunFd = 252; if (dup2(tunfd, kTunFd) < 0) fail("dup2(tunfd, kTunFd) failed"); close(tunfd); tunfd = kTunFd; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, TUN_IFACE, IFNAMSIZ); ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_NAPI | IFF_NAPI_FRAGS; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) { ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) fail("tun: ioctl(TUNSETIFF) failed"); } if (ioctl(tunfd, TUNGETIFF, (void*)&ifr) < 0) fail("tun: ioctl(TUNGETIFF) failed"); tun_frags_enabled = (ifr.ifr_flags & IFF_NAPI_FRAGS) != 0; execute_command(1, "sysctl -w net.ipv6.conf.%s.accept_dad=0", TUN_IFACE); execute_command(1, "sysctl -w net.ipv6.conf.%s.router_solicitations=0", TUN_IFACE); execute_command(1, "ip link set dev %s address %s", TUN_IFACE, LOCAL_MAC); execute_command(1, "ip addr add %s/24 dev %s", LOCAL_IPV4, TUN_IFACE); execute_command(1, "ip -6 addr add %s/120 dev %s", LOCAL_IPV6, TUN_IFACE); execute_command(1, "ip neigh add %s lladdr %s dev %s nud permanent", REMOTE_IPV4, REMOTE_MAC, TUN_IFACE); execute_command(1, "ip -6 neigh add %s lladdr %s dev %s nud permanent", REMOTE_IPV6, REMOTE_MAC, TUN_IFACE); execute_command(1, "ip link set dev %s up", TUN_IFACE); } #define DEV_IPV4 "172.20.20.%d" #define DEV_IPV6 "fe80::%02hx" #define DEV_MAC "aa:aa:aa:aa:aa:%02hx" static void initialize_netdevices(void) { unsigned i; const char* devtypes[] = {"ip6gretap", "bridge", "vcan", "bond", "team"}; const char* devnames[] = {"lo", "sit0", "bridge0", "vcan0", "tunl0", "gre0", "gretap0", "ip_vti0", "ip6_vti0", "ip6tnl0", "ip6gre0", "ip6gretap0", "erspan0", "bond0", "veth0", "veth1", "team0", "veth0_to_bridge", "veth1_to_bridge", "veth0_to_bond", "veth1_to_bond", "veth0_to_team", "veth1_to_team"}; const char* devmasters[] = {"bridge", "bond", "team"}; for (i = 0; i < sizeof(devtypes) / (sizeof(devtypes[0])); i++) execute_command(0, "ip link add dev %s0 type %s", devtypes[i], devtypes[i]); execute_command(0, "ip link add type veth"); for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) { execute_command( 0, "ip link add name %s_slave_0 type veth peer name veth0_to_%s", devmasters[i], devmasters[i]); execute_command( 0, "ip link add name %s_slave_1 type veth peer name veth1_to_%s", devmasters[i], devmasters[i]); execute_command(0, "ip link set %s_slave_0 master %s0", devmasters[i], devmasters[i]); execute_command(0, "ip link set %s_slave_1 master %s0", devmasters[i], devmasters[i]); execute_command(0, "ip link set veth0_to_%s up", devmasters[i]); execute_command(0, "ip link set veth1_to_%s up", devmasters[i]); } execute_command(0, "ip link set bridge_slave_0 up"); execute_command(0, "ip link set bridge_slave_1 up"); for (i = 0; i < sizeof(devnames) / (sizeof(devnames[0])); i++) { char addr[32]; snprintf_check(addr, sizeof(addr), DEV_IPV4, i + 10); execute_command(0, "ip -4 addr add %s/24 dev %s", addr, devnames[i]); snprintf_check(addr, sizeof(addr), DEV_IPV6, i + 10); execute_command(0, "ip -6 addr add %s/120 dev %s", addr, devnames[i]); snprintf_check(addr, sizeof(addr), DEV_MAC, i + 10); execute_command(0, "ip link set dev %s address %s", devnames[i], addr); execute_command(0, "ip link set dev %s up", devnames[i]); } } static int read_tun(char* data, int size) { if (tunfd < 0) return -1; int rv = read(tunfd, data, size); if (rv < 0) { if (errno == EAGAIN) return -1; if (errno == EBADFD) return -1; fail("tun: read failed with %d", rv); } return rv; } static void flush_tun() { char data[SYZ_TUN_MAX_PACKET_SIZE]; while (read_tun(&data[0], sizeof(data)) != -1) ; } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } static void setup_cgroups() { if (mkdir("/syzcgroup", 0777)) { } if (mkdir("/syzcgroup/unified", 0777)) { } if (mount("none", "/syzcgroup/unified", "cgroup2", 0, NULL)) { } if (chmod("/syzcgroup/unified", 0777)) { } if (!write_file("/syzcgroup/unified/cgroup.subtree_control", "+cpu +memory +io +pids +rdma")) { } if (mkdir("/syzcgroup/cpu", 0777)) { } if (mount("none", "/syzcgroup/cpu", "cgroup", 0, "cpuset,cpuacct,perf_event,hugetlb")) { } if (!write_file("/syzcgroup/cpu/cgroup.clone_children", "1")) { } if (chmod("/syzcgroup/cpu", 0777)) { } if (mkdir("/syzcgroup/net", 0777)) { } if (mount("none", "/syzcgroup/net", "cgroup", 0, "net_cls,net_prio,devices,freezer")) { } if (chmod("/syzcgroup/net", 0777)) { } } static void setup_binfmt_misc() { if (!write_file("/proc/sys/fs/binfmt_misc/register", ":syz0:M:0:syz0::./file0:")) { } if (!write_file("/proc/sys/fs/binfmt_misc/register", ":syz1:M:1:yz1::./file0:POC")) { } } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = 128 << 20; setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 8 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 32 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); if (unshare(CLONE_NEWNS)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(0x02000000)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } } static int real_uid; static int real_gid; __attribute__((aligned(64 << 10))) static char sandbox_stack[1 << 20]; static int namespace_sandbox_proc(void* arg) { sandbox_common(); write_file("/proc/self/setgroups", "deny"); if (!write_file("/proc/self/uid_map", "0 %d 1\n", real_uid)) fail("write of /proc/self/uid_map failed"); if (!write_file("/proc/self/gid_map", "0 %d 1\n", real_gid)) fail("write of /proc/self/gid_map failed"); if (unshare(CLONE_NEWNET)) fail("unshare(CLONE_NEWNET)"); initialize_tun(); initialize_netdevices(); if (mkdir("./syz-tmp", 0777)) fail("mkdir(syz-tmp) failed"); if (mount("", "./syz-tmp", "tmpfs", 0, NULL)) fail("mount(tmpfs) failed"); if (mkdir("./syz-tmp/newroot", 0777)) fail("mkdir failed"); if (mkdir("./syz-tmp/newroot/dev", 0700)) fail("mkdir failed"); unsigned mount_flags = MS_BIND | MS_REC | MS_PRIVATE; if (mount("/dev", "./syz-tmp/newroot/dev", NULL, mount_flags, NULL)) fail("mount(dev) failed"); if (mkdir("./syz-tmp/newroot/proc", 0700)) fail("mkdir failed"); if (mount(NULL, "./syz-tmp/newroot/proc", "proc", 0, NULL)) fail("mount(proc) failed"); if (mkdir("./syz-tmp/newroot/selinux", 0700)) fail("mkdir failed"); const char* selinux_path = "./syz-tmp/newroot/selinux"; if (mount("/selinux", selinux_path, NULL, mount_flags, NULL)) { if (errno != ENOENT) fail("mount(/selinux) failed"); if (mount("/sys/fs/selinux", selinux_path, NULL, mount_flags, NULL) && errno != ENOENT) fail("mount(/sys/fs/selinux) failed"); } if (mkdir("./syz-tmp/newroot/sys", 0700)) fail("mkdir failed"); if (mount(NULL, "./syz-tmp/newroot/sys", "sysfs", 0, NULL)) fail("mount(sysfs) failed"); if (mkdir("./syz-tmp/newroot/syzcgroup", 0700)) fail("mkdir failed"); if (mkdir("./syz-tmp/newroot/syzcgroup/unified", 0700)) fail("mkdir failed"); if (mkdir("./syz-tmp/newroot/syzcgroup/cpu", 0700)) fail("mkdir failed"); if (mkdir("./syz-tmp/newroot/syzcgroup/net", 0700)) fail("mkdir failed"); if (mount("/syzcgroup/unified", "./syz-tmp/newroot/syzcgroup/unified", NULL, mount_flags, NULL)) { } if (mount("/syzcgroup/cpu", "./syz-tmp/newroot/syzcgroup/cpu", NULL, mount_flags, NULL)) { } if (mount("/syzcgroup/net", "./syz-tmp/newroot/syzcgroup/net", NULL, mount_flags, NULL)) { } if (mkdir("./syz-tmp/pivot", 0777)) fail("mkdir failed"); if (syscall(SYS_pivot_root, "./syz-tmp", "./syz-tmp/pivot")) { if (chdir("./syz-tmp")) fail("chdir failed"); } else { if (chdir("/")) fail("chdir failed"); if (umount2("./pivot", MNT_DETACH)) fail("umount failed"); } if (chroot("./newroot")) fail("chroot failed"); if (chdir("/")) fail("chdir failed"); struct __user_cap_header_struct cap_hdr = {}; struct __user_cap_data_struct cap_data[2] = {}; cap_hdr.version = _LINUX_CAPABILITY_VERSION_3; cap_hdr.pid = getpid(); if (syscall(SYS_capget, &cap_hdr, &cap_data)) fail("capget failed"); cap_data[0].effective &= ~(1 << CAP_SYS_PTRACE); cap_data[0].permitted &= ~(1 << CAP_SYS_PTRACE); cap_data[0].inheritable &= ~(1 << CAP_SYS_PTRACE); if (syscall(SYS_capset, &cap_hdr, &cap_data)) fail("capset failed"); loop(); doexit(1); } static int do_sandbox_namespace(void) { int pid; setup_cgroups(); setup_binfmt_misc(); real_uid = getuid(); real_gid = getgid(); mprotect(sandbox_stack, 4096, PROT_NONE); pid = clone(namespace_sandbox_proc, &sandbox_stack[sizeof(sandbox_stack) - 64], CLONE_NEWUSER | CLONE_NEWPID, 0); if (pid < 0) fail("sandbox clone failed"); return pid; } #define XT_TABLE_SIZE 1536 #define XT_MAX_ENTRIES 10 struct xt_counters { uint64_t pcnt, bcnt; }; struct ipt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_entries; unsigned int size; }; struct ipt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct ipt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct ipt_table_desc { const char* name; struct ipt_getinfo info; struct ipt_replace replace; }; static struct ipt_table_desc ipv4_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; static struct ipt_table_desc ipv6_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; #define IPT_BASE_CTL 64 #define IPT_SO_SET_REPLACE (IPT_BASE_CTL) #define IPT_SO_GET_INFO (IPT_BASE_CTL) #define IPT_SO_GET_ENTRIES (IPT_BASE_CTL + 1) struct arpt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_entries; unsigned int size; }; struct arpt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct arpt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct arpt_table_desc { const char* name; struct arpt_getinfo info; struct arpt_replace replace; }; static struct arpt_table_desc arpt_tables[] = { {.name = "filter"}, }; #define ARPT_BASE_CTL 96 #define ARPT_SO_SET_REPLACE (ARPT_BASE_CTL) #define ARPT_SO_GET_INFO (ARPT_BASE_CTL) #define ARPT_SO_GET_ENTRIES (ARPT_BASE_CTL + 1) static void checkpoint_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { struct ipt_get_entries entries; socklen_t optlen; int fd, i; fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) fail("socket(%d, SOCK_STREAM, IPPROTO_TCP)", family); for (i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); optlen = sizeof(table->info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } fail("getsockopt(IPT_SO_GET_INFO)"); } if (table->info.size > sizeof(table->replace.entrytable)) fail("table size is too large: %u", table->info.size); if (table->info.num_entries > XT_MAX_ENTRIES) fail("too many counters: %u", table->info.num_entries); memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) fail("getsockopt(IPT_SO_GET_ENTRIES)"); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { struct xt_counters counters[XT_MAX_ENTRIES]; struct ipt_get_entries entries; struct ipt_getinfo info; socklen_t optlen; int fd, i; fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) fail("socket(%d, SOCK_STREAM, IPPROTO_TCP)", family); for (i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; if (table->info.valid_hooks == 0) continue; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); optlen = sizeof(info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &info, &optlen)) fail("getsockopt(IPT_SO_GET_INFO)"); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) fail("getsockopt(IPT_SO_GET_ENTRIES)"); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, level, IPT_SO_SET_REPLACE, &table->replace, optlen)) fail("setsockopt(IPT_SO_SET_REPLACE)"); } close(fd); } static void checkpoint_arptables(void) { struct arpt_get_entries entries; socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)"); for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); optlen = sizeof(table->info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } fail("getsockopt(ARPT_SO_GET_INFO)"); } if (table->info.size > sizeof(table->replace.entrytable)) fail("table size is too large: %u", table->info.size); if (table->info.num_entries > XT_MAX_ENTRIES) fail("too many counters: %u", table->info.num_entries); memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) fail("getsockopt(ARPT_SO_GET_ENTRIES)"); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_arptables() { struct xt_counters counters[XT_MAX_ENTRIES]; struct arpt_get_entries entries; struct arpt_getinfo info; socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)"); for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; if (table->info.valid_hooks == 0) continue; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); optlen = sizeof(info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &info, &optlen)) fail("getsockopt(ARPT_SO_GET_INFO)"); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) fail("getsockopt(ARPT_SO_GET_ENTRIES)"); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, SOL_IP, ARPT_SO_SET_REPLACE, &table->replace, optlen)) fail("setsockopt(ARPT_SO_SET_REPLACE)"); } close(fd); } #include <linux/if.h> #include <linux/netfilter_bridge/ebtables.h> struct ebt_table_desc { const char* name; struct ebt_replace replace; char entrytable[XT_TABLE_SIZE]; }; static struct ebt_table_desc ebt_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "broute"}, }; static void checkpoint_ebtables(void) { socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)"); for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; strcpy(table->replace.name, table->name); optlen = sizeof(table->replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_INFO, &table->replace, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } fail("getsockopt(EBT_SO_GET_INIT_INFO)"); } if (table->replace.entries_size > sizeof(table->entrytable)) fail("table size is too large: %u", table->replace.entries_size); table->replace.num_counters = 0; table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_ENTRIES, &table->replace, &optlen)) fail("getsockopt(EBT_SO_GET_INIT_ENTRIES)"); } close(fd); } static void reset_ebtables() { struct ebt_replace replace; char entrytable[XT_TABLE_SIZE]; socklen_t optlen; unsigned i, j, h; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)"); for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; if (table->replace.valid_hooks == 0) continue; memset(&replace, 0, sizeof(replace)); strcpy(replace.name, table->name); optlen = sizeof(replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INFO, &replace, &optlen)) fail("getsockopt(EBT_SO_GET_INFO)"); replace.num_counters = 0; table->replace.entries = 0; for (h = 0; h < NF_BR_NUMHOOKS; h++) table->replace.hook_entry[h] = 0; if (memcmp(&table->replace, &replace, sizeof(table->replace)) == 0) { memset(&entrytable, 0, sizeof(entrytable)); replace.entries = entrytable; optlen = sizeof(replace) + replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_ENTRIES, &replace, &optlen)) fail("getsockopt(EBT_SO_GET_ENTRIES)"); if (memcmp(table->entrytable, entrytable, replace.entries_size) == 0) continue; } for (j = 0, h = 0; h < NF_BR_NUMHOOKS; h++) { if (table->replace.valid_hooks & (1 << h)) { table->replace.hook_entry[h] = (struct ebt_entries*)table->entrytable + j; j++; } } table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (setsockopt(fd, SOL_IP, EBT_SO_SET_ENTRIES, &table->replace, optlen)) fail("setsockopt(EBT_SO_SET_ENTRIES)"); } close(fd); } static void checkpoint_net_namespace(void) { checkpoint_ebtables(); checkpoint_arptables(); checkpoint_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); checkpoint_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void reset_net_namespace(void) { reset_ebtables(); reset_arptables(); reset_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); reset_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void remove_dir(const char* dir) { DIR* dp; struct dirent* ep; int iter = 0; retry: while (umount2(dir, MNT_DETACH) == 0) { } dp = opendir(dir); if (dp == NULL) { if (errno == EMFILE) { exitf("opendir(%s) failed due to NOFILE, exiting", dir); } exitf("opendir(%s) failed", dir); } while ((ep = readdir(dp))) { if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) continue; char filename[FILENAME_MAX]; snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name); struct stat st; if (lstat(filename, &st)) exitf("lstat(%s) failed", filename); if (S_ISDIR(st.st_mode)) { remove_dir(filename); continue; } int i; for (i = 0;; i++) { if (unlink(filename) == 0) break; if (errno == EROFS) { break; } if (errno != EBUSY || i > 100) exitf("unlink(%s) failed", filename); if (umount2(filename, MNT_DETACH)) exitf("umount(%s) failed", filename); } } closedir(dp); int i; for (i = 0;; i++) { if (rmdir(dir) == 0) break; if (i < 100) { if (errno == EROFS) { break; } if (errno == EBUSY) { if (umount2(dir, MNT_DETACH)) exitf("umount(%s) failed", dir); continue; } if (errno == ENOTEMPTY) { if (iter < 100) { iter++; goto retry; } } } exitf("rmdir(%s) failed", dir); } } static void execute_one(); extern unsigned long long procid; static void loop() { checkpoint_net_namespace(); char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); char cgroupdir_cpu[64]; snprintf(cgroupdir_cpu, sizeof(cgroupdir_cpu), "/syzcgroup/cpu/syz%llu", procid); char cgroupdir_net[64]; snprintf(cgroupdir_net, sizeof(cgroupdir_net), "/syzcgroup/net/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } if (mkdir(cgroupdir_cpu, 0777)) { } if (mkdir(cgroupdir_net, 0777)) { } int pid = getpid(); char procs_file[128]; snprintf(procs_file, sizeof(procs_file), "%s/cgroup.procs", cgroupdir); if (!write_file(procs_file, "%d", pid)) { } snprintf(procs_file, sizeof(procs_file), "%s/cgroup.procs", cgroupdir_cpu); if (!write_file(procs_file, "%d", pid)) { } snprintf(procs_file, sizeof(procs_file), "%s/cgroup.procs", cgroupdir_net); if (!write_file(procs_file, "%d", pid)) { } int iter; for (iter = 0;; iter++) { char cwdbuf[32]; sprintf(cwdbuf, "./%d", iter); if (mkdir(cwdbuf, 0777)) fail("failed to mkdir"); int pid = fork(); if (pid < 0) fail("clone failed"); if (pid == 0) { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); if (chdir(cwdbuf)) fail("failed to chdir"); if (symlink(cgroupdir, "./cgroup")) { } if (symlink(cgroupdir_cpu, "./cgroup.cpu")) { } if (symlink(cgroupdir_net, "./cgroup.net")) { } flush_tun(); execute_one(); doexit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { int res = waitpid(-1, &status, __WALL | WNOHANG); if (res == pid) { break; } usleep(1000); if (current_time_ms() - start < 3 * 1000) continue; kill(-pid, SIGKILL); kill(pid, SIGKILL); while (waitpid(-1, &status, __WALL) != pid) { } break; } remove_dir(cwdbuf); reset_net_namespace(); } } struct thread_t { int created, running, call; pthread_t th; }; static struct thread_t threads[16]; static void execute_call(int call); static int running; static void* thr(void* arg) { struct thread_t* th = (struct thread_t*)arg; for (;;) { while (!__atomic_load_n(&th->running, __ATOMIC_ACQUIRE)) syscall(SYS_futex, &th->running, FUTEX_WAIT, 0, 0); execute_call(th->call); __atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED); __atomic_store_n(&th->running, 0, __ATOMIC_RELEASE); syscall(SYS_futex, &th->running, FUTEX_WAKE); } return 0; } static void execute(int num_calls) { int call, thread; running = 0; for (call = 0; call < num_calls; call++) { for (thread = 0; thread < sizeof(threads) / sizeof(threads[0]); thread++) { struct thread_t* th = &threads[thread]; if (!th->created) { th->created = 1; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 128 << 10); pthread_create(&th->th, &attr, thr, th); } if (!__atomic_load_n(&th->running, __ATOMIC_ACQUIRE)) { th->call = call; __atomic_fetch_add(&running, 1, __ATOMIC_RELAXED); __atomic_store_n(&th->running, 1, __ATOMIC_RELEASE); syscall(SYS_futex, &th->running, FUTEX_WAKE); struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 20 * 1000 * 1000; syscall(SYS_futex, &th->running, FUTEX_WAIT, 1, &ts); if (running) usleep((call == num_calls - 1) ? 10000 : 1000); break; } } } } uint64_t r[1] = {0xffffffffffffffff}; unsigned long long procid; void execute_call(int call) { long res; switch (call) { case 0: res = syscall(__NR_socket, 0x11, 3, 0x300); if (res != -1) r[0] = res; break; case 1: NONFAILING(*(uint32_t*)0x20210000 = 2); syscall(__NR_setsockopt, r[0], 0x107, 0xa, 0x20210000, 4); break; case 2: NONFAILING(*(uint32_t*)0x200000c0 = 0x1000); NONFAILING(*(uint32_t*)0x200000c4 = 0xffff8000); NONFAILING(*(uint32_t*)0x200000c8 = 0); NONFAILING(*(uint32_t*)0x200000cc = 0); NONFAILING(*(uint32_t*)0x200000d0 = 0); NONFAILING(*(uint32_t*)0x200000d4 = 0x15c7); NONFAILING(*(uint32_t*)0x200000d8 = 0); syscall(__NR_setsockopt, r[0], 0x107, 5, 0x200000c0, 0x1c); break; } } void execute_one() { execute(3); } int main() { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); char* cwd = get_current_dir_name(); for (procid = 0; procid < 8; procid++) { if (fork() == 0) { install_segv_handler(); for (;;) { if (chdir(cwd)) fail("failed to chdir"); use_temporary_dir(); int pid = do_sandbox_namespace(); int status = 0; while (waitpid(pid, &status, __WALL) != pid) { } } } } sleep(1000000); return 0; }
the_stack_data/1208486.c
#include <stdio.h> #include <ctype.h> int atoi_general(char s[]) { int i, n, sign; for (i = 0; isspace(s[i]); i++); sign = (s[i] == '-') ? -1: 1; if (s[i] == '+' || s[i] == '-') { i++; } for (n = 0; isdigit(s[i]); i++) { n = 10 * n + (s[i] - '0'); } return sign * n; } int main(int x, char** argc) { char* s; int result; result = atoi_general(argc[1]); printf("%d\n", result); return 0; }
the_stack_data/358064.c
/* Copyright (c) 2018, Erik Lundin. */ int xx__test_chacha20(void); int xx__test_hchacha20(void); int main(int argc, const char ** argv) { if (xx__test_chacha20() != 0) return 1; if (xx__test_hchacha20() != 0) return 2; return 0; }
the_stack_data/98883.c
#define unit(u) __attribute__((unit(u))) static double x; static double unit(m) x;
the_stack_data/118236.c
/** * This file has no copyright assigned and is placed in the Public Domain. * This file is part of the mingw-w64 runtime package. * No warranty is given; refer to the file DISCLAIMER.PD within this package. */ #include <math.h> long lrintf (float x) { long retval = 0l; #if defined(_AMD64_) || defined(__x86_64__) || defined(_X86_) || defined(__i386__) __asm__ __volatile__ ("fistpl %0" : "=m" (retval) : "t" (x) : "st"); #elif defined(__arm__) || defined(_ARM_) __asm__ __volatile__ ( "vcvtr.s32.f32 %[src], %[src]\n\t" "fmrs %[dst], %[src]\n\t" : [dst] "=r" (retval), [src] "+w" (x)); #elif defined(__aarch64__) || defined(_ARM64_) __asm__ __volatile__ ( "frintx %s1, %s1\n\t" "fcvtzs %w0, %s1\n\t" : "=r" (retval), "+w" (x)); #endif return retval; }
the_stack_data/10787.c
/* * Copyright (c) 2009-2013 Alper Akcan <[email protected]> * * This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What The Fuck You Want * To Public License, Version 2, as published by Sam Hocevar. See * http://www.wtfpl.net/ for more details. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #define size(a) ((int) (sizeof(a) / sizeof(a[0]))) int main (int argc, char *argv[]) { int rc; int i; pthread_mutex_t m[5]; (void) argc; (void) argv; for (i = 0; i < size(m); i++) { rc = pthread_mutex_init(&m[i], NULL); if (rc != 0) { fprintf(stderr, "pthread_mutex_init failed\n"); exit(-1); } } for (i = 0; i < size(m); i++) { rc = pthread_mutex_lock(&m[i]); if (rc != 0) { fprintf(stderr, "pthread_mutex_lock failed\n"); exit(-1); } } for (i = 0; i < size(m); i++) { rc = pthread_mutex_unlock(&m[i]); if (rc != 0) { fprintf(stderr, "pthread_mutex_unlock failed\n"); exit(-1); } } for (i = size(m) - 1; i >= 0; i--) { rc = pthread_mutex_lock(&m[i]); if (rc != 0) { fprintf(stderr, "pthread_mutex_lock failed\n"); exit(-1); } } for (i = size(m) - 1; i >= 0; i--) { rc = pthread_mutex_unlock(&m[i]); if (rc != 0) { fprintf(stderr, "pthread_mutex_unlock failed\n"); exit(-1); } } for (i = 0; i < size(m); i++) { rc = pthread_mutex_destroy(&m[i]); if (rc != 0) { fprintf(stderr, "pthread_mutex_destroy failed\n"); exit(-1); } } return 0; }
the_stack_data/598692.c
#include <stdio.h> /** * Temperature conversion: Fahrenheit degree to * Celsius degree. */ double fahr_to_celsius(double fahr) { return (5.0/9.0) * (fahr - 32.0); }
the_stack_data/130566.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_params.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: baslanha <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/12/14 11:11:13 by baslanha #+# #+# */ /* Updated: 2021/12/14 15:29:19 by baslanha ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> void ft_putchar(char c) { write (1, &c, 1); } int main(int argc, char *argv[]) { int i; int j; j = 1; while (j < argc) { i = 0; while (argv[j][i] != '\0') { ft_putchar(argv[j][i]); i++; } ft_putchar('\n'); j++; } return (0); }
the_stack_data/117220.c
// On souhaite modifier i de différente facon int main() { int i = 0; int *p; int j = 10; int *q; p = &i; q = &j; //on modifie i i=*q; return 0; }
the_stack_data/97895.c
/****************************************************************************** * * Copyright (C) 2009 - 2017 Xilinx, Inc. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * Use of the Software is limited solely to applications: * (a) running on a Xilinx device, or * (b) that interact with a Xilinx device through a bus or interconnect. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * XILINX BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Except as contained in this notice, the name of the Xilinx shall not be used * in advertising or otherwise to promote the sale, use or other dealings in * this Software without prior written authorization from Xilinx. * ******************************************************************************/ #if __MICROBLAZE__ #include "arch/cc.h" #include "platform.h" #include "platform_config.h" #include "xil_cache.h" #include "xparameters.h" #include "xintc.h" #include "xil_exception.h" #include "lwip/tcp.h" #ifdef TFTP_APP #include "platform_fs.h" #endif #ifdef STDOUT_IS_16550 #include "xuartns550_l.h" #endif #include "lwip/tcp.h" #if LWIP_DHCP==1 volatile int dhcp_timoutcntr = 24; void dhcp_fine_tmr(); void dhcp_coarse_tmr(); #endif volatile int TcpFastTmrFlag = 0; volatile int TcpSlowTmrFlag = 0; void timer_callback() { /* we need to call tcp_fasttmr & tcp_slowtmr at intervals specified by lwIP. * It is not important that the timing is absoluetly accurate. */ static int odd = 1; #if LWIP_DHCP==1 static int dhcp_timer = 0; #endif TcpFastTmrFlag = 1; odd = !odd; if (odd) { #if LWIP_DHCP==1 dhcp_timer++; dhcp_timoutcntr--; #endif TcpSlowTmrFlag = 1; #if LWIP_DHCP==1 dhcp_fine_tmr(); if (dhcp_timer >= 120) { dhcp_coarse_tmr(); dhcp_timer = 0; } #endif } } static XIntc intc; void platform_setup_interrupts() { XIntc *intcp; intcp = &intc; XIntc_Initialize(intcp, XPAR_INTC_0_DEVICE_ID); XIntc_Start(intcp, XIN_REAL_MODE); /* Start the interrupt controller */ XIntc_MasterEnable(XPAR_INTC_0_BASEADDR); #ifdef __MICROBLAZE__ microblaze_register_handler((XInterruptHandler)XIntc_InterruptHandler, intcp); #endif platform_setup_timer(); #ifdef XPAR_ETHERNET_MAC_IP2INTC_IRPT_MASK /* Enable timer and EMAC interrupts in the interrupt controller */ XIntc_EnableIntr(XPAR_INTC_0_BASEADDR, #ifdef __MICROBLAZE__ PLATFORM_TIMER_INTERRUPT_MASK | #endif XPAR_ETHERNET_MAC_IP2INTC_IRPT_MASK); #endif #ifdef XPAR_INTC_0_LLTEMAC_0_VEC_ID #ifdef __MICROBLAZE__ XIntc_Enable(intcp, PLATFORM_TIMER_INTERRUPT_INTR); #endif XIntc_Enable(intcp, XPAR_INTC_0_LLTEMAC_0_VEC_ID); #endif #ifdef XPAR_INTC_0_AXIETHERNET_0_VEC_ID XIntc_Enable(intcp, PLATFORM_TIMER_INTERRUPT_INTR); XIntc_Enable(intcp, XPAR_INTC_0_AXIETHERNET_0_VEC_ID); #endif #ifdef XPAR_INTC_0_EMACLITE_0_VEC_ID #ifdef __MICROBLAZE__ XIntc_Enable(intcp, PLATFORM_TIMER_INTERRUPT_INTR); #endif XIntc_Enable(intcp, XPAR_INTC_0_EMACLITE_0_VEC_ID); #endif } void enable_caches() { #ifdef __MICROBLAZE__ #ifdef XPAR_MICROBLAZE_USE_ICACHE Xil_ICacheEnable(); #endif #ifdef XPAR_MICROBLAZE_USE_DCACHE Xil_DCacheEnable(); #endif #endif } void disable_caches() { Xil_DCacheDisable(); Xil_ICacheDisable(); } void init_platform() { enable_caches(); #ifdef STDOUT_IS_16550 XUartNs550_SetBaud(STDOUT_BASEADDR, XPAR_XUARTNS550_CLOCK_HZ, 9600); XUartNs550_SetLineControlReg(STDOUT_BASEADDR, XUN_LCR_8_DATA_BITS); #endif platform_setup_interrupts(); #ifdef TFTP_APP platform_init_fs(); #endif } void cleanup_platform() { disable_caches(); } #endif
the_stack_data/212642672.c
extern int __VERIFIER_nondet_int(); extern void __VERIFIER_assume(int); int nondet_signed_int() { int r = __VERIFIER_nondet_int(); __VERIFIER_assume ((-0x7fffffff - 1) <= r && r <= 0x7fffffff); return r; } signed int main() { signed int x=nondet_signed_int(); if(x >= 1) for( ; !(x == 0) && !(x == -1); x = x - 2) while(!(!(x - 2 < (-0x7fffffff - 1) || 0x7fffffff < x - 2))); return 0; }
the_stack_data/167330982.c
/** * @Author ZhangGJ * @Date 2021/01/10 22:49 */ #include <stdio.h> int main() { int c, nb, nt, nl; nb = 0; nt = 0; nl = 0; while ((c = getchar()) != EOF) { if (c == ' ') { ++nb; } else if (c == '\t') { ++nt; } else if (c == '\n') { ++nl; } } printf("%d %d %d\n", nb, nt, nl); }
the_stack_data/597684.c
#include <stdio.h> #include <stdlib.h> #include <time.h> void array_print(int* array, size_t size) { for (int i = 0; i < size; ++i) { printf("%i ", array[i]); } printf("\n"); } void array_merge_part(int* array, size_t middle, size_t size) { int tmp[size]; size_t i, left, right; for (i = 0, left = 0, right = middle; i < size; ++i) { if (left >= middle) { tmp[i] = array[right++]; } else if (right >= size) { tmp[i] = array[left++]; } else { tmp[i] = array[left] < array[right] ? array[left++] : array[right++]; } } for (i = 0; i < size; ++i) { array[i] = tmp[i]; } } void array_sort(int* array, size_t size) { if (size < 2) return; size_t middle = size / 2; array_sort(array, middle); array_sort(array + middle, size - middle); array_merge_part(array, middle, size); } void array_init_rand(int* array, size_t size, int range) { srand(time(NULL)); for (size_t i = 0; i < size; ++i) { array[i] = rand() % range; } } int main() { size_t size = 20; int array[size]; array_init_rand(array, size, 100); array_print(array, size); array_sort(array, size); array_print(array, size); return 0; }
the_stack_data/150142675.c
/* ** 2015 February 16 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* */ #include "sqlite3.h" #if defined(SQLITE_TEST) #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) #include "sqlite3rbu.h" #include <tcl.h> #include <assert.h> /* From main.c */ extern const char *sqlite3ErrName(int); extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*); void test_rbu_delta(sqlite3_context *pCtx, int nArg, sqlite3_value **apVal){ Tcl_Interp *interp = (Tcl_Interp*)sqlite3_user_data(pCtx); Tcl_Obj *pScript; int i; pScript = Tcl_NewObj(); Tcl_IncrRefCount(pScript); Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj("rbu_delta", -1)); for(i=0; i<nArg; i++){ sqlite3_value *pIn = apVal[i]; const char *z = (const char*)sqlite3_value_text(pIn); Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(z, -1)); } if( TCL_OK==Tcl_EvalObjEx(interp, pScript, TCL_GLOBAL_ONLY) ){ const char *z = Tcl_GetStringResult(interp); sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); }else{ Tcl_BackgroundError(interp); } Tcl_DecrRefCount(pScript); } static int test_sqlite3rbu_cmd( ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ int ret = TCL_OK; sqlite3rbu *pRbu = (sqlite3rbu*)clientData; struct RbuCmd { const char *zName; int nArg; const char *zUsage; } aCmd[] = { {"step", 2, ""}, /* 0 */ {"close", 2, ""}, /* 1 */ {"create_rbu_delta", 2, ""}, /* 2 */ {"savestate", 2, ""}, /* 3 */ {"dbMain_eval", 3, "SQL"}, /* 4 */ {"bp_progress", 2, ""}, /* 5 */ {"db", 3, "RBU"}, /* 6 */ {0,0,0} }; int iCmd; if( objc<2 ){ Tcl_WrongNumArgs(interp, 1, objv, "METHOD"); return TCL_ERROR; } ret = Tcl_GetIndexFromObjStruct( interp, objv[1], aCmd, sizeof(aCmd[0]), "method", 0, &iCmd ); if( ret ) return TCL_ERROR; if( objc!=aCmd[iCmd].nArg ){ Tcl_WrongNumArgs(interp, 1, objv, aCmd[iCmd].zUsage); return TCL_ERROR; } switch( iCmd ){ case 0: /* step */ { int rc = sqlite3rbu_step(pRbu); Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); break; } case 1: /* close */ { char *zErrmsg = 0; int rc; Tcl_DeleteCommand(interp, Tcl_GetString(objv[0])); rc = sqlite3rbu_close(pRbu, &zErrmsg); if( rc==SQLITE_OK || rc==SQLITE_DONE ){ Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); assert( zErrmsg==0 ); }else{ Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); if( zErrmsg ){ Tcl_AppendResult(interp, " - ", zErrmsg, 0); sqlite3_free(zErrmsg); } ret = TCL_ERROR; } break; } case 2: /* create_rbu_delta */ { sqlite3 *db = sqlite3rbu_db(pRbu, 0); int rc = sqlite3_create_function( db, "rbu_delta", -1, SQLITE_UTF8, (void*)interp, test_rbu_delta, 0, 0 ); Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); ret = (rc==SQLITE_OK ? TCL_OK : TCL_ERROR); break; } case 3: /* savestate */ { int rc = sqlite3rbu_savestate(pRbu); Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); ret = (rc==SQLITE_OK ? TCL_OK : TCL_ERROR); break; } case 4: /* dbMain_eval */ { sqlite3 *db = sqlite3rbu_db(pRbu, 0); int rc = sqlite3_exec(db, Tcl_GetString(objv[2]), 0, 0, 0); if( rc!=SQLITE_OK ){ Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(db), -1)); ret = TCL_ERROR; } break; } case 5: /* bp_progress */ { int one, two; Tcl_Obj *pObj; sqlite3rbu_bp_progress(pRbu, &one, &two); pObj = Tcl_NewObj(); Tcl_ListObjAppendElement(interp, pObj, Tcl_NewIntObj(one)); Tcl_ListObjAppendElement(interp, pObj, Tcl_NewIntObj(two)); Tcl_SetObjResult(interp, pObj); break; } case 6: /* db */ { int bArg; if( Tcl_GetBooleanFromObj(interp, objv[2], &bArg) ){ ret = TCL_ERROR; }else{ char zBuf[50]; sqlite3 *db = sqlite3rbu_db(pRbu, bArg); if( sqlite3TestMakePointerStr(interp, zBuf, (void*)db) ){ ret = TCL_ERROR; }else{ Tcl_SetResult(interp, zBuf, TCL_VOLATILE); } } break; } default: /* seems unlikely */ assert( !"cannot happen" ); break; } return ret; } /* ** Tclcmd: sqlite3rbu CMD <target-db> <rbu-db> ?<state-db>? */ static int test_sqlite3rbu( ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ sqlite3rbu *pRbu = 0; const char *zCmd; const char *zTarget; const char *zRbu; const char *zStateDb = 0; if( objc!=4 && objc!=5 ){ Tcl_WrongNumArgs(interp, 1, objv, "NAME TARGET-DB RBU-DB ?STATE-DB?"); return TCL_ERROR; } zCmd = Tcl_GetString(objv[1]); zTarget = Tcl_GetString(objv[2]); zRbu = Tcl_GetString(objv[3]); if( objc==5 ) zStateDb = Tcl_GetString(objv[4]); pRbu = sqlite3rbu_open(zTarget, zRbu, zStateDb); Tcl_CreateObjCommand(interp, zCmd, test_sqlite3rbu_cmd, (ClientData)pRbu, 0); Tcl_SetObjResult(interp, objv[1]); return TCL_OK; } /* ** Tclcmd: sqlite3rbu_vacuum CMD <target-db> <state-db> */ static int test_sqlite3rbu_vacuum( ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ sqlite3rbu *pRbu = 0; const char *zCmd; const char *zTarget; const char *zStateDb = 0; if( objc!=4 ){ Tcl_WrongNumArgs(interp, 1, objv, "NAME TARGET-DB STATE-DB"); return TCL_ERROR; } zCmd = Tcl_GetString(objv[1]); zTarget = Tcl_GetString(objv[2]); zStateDb = Tcl_GetString(objv[3]); pRbu = sqlite3rbu_vacuum(zTarget, zStateDb); Tcl_CreateObjCommand(interp, zCmd, test_sqlite3rbu_cmd, (ClientData)pRbu, 0); Tcl_SetObjResult(interp, objv[1]); return TCL_OK; } /* ** Tclcmd: sqlite3rbu_create_vfs ?-default? NAME PARENT */ static int test_sqlite3rbu_create_vfs( ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ const char *zName; const char *zParent; int rc; if( objc!=3 && objc!=4 ){ Tcl_WrongNumArgs(interp, 1, objv, "?-default? NAME PARENT"); return TCL_ERROR; } zName = Tcl_GetString(objv[objc-2]); zParent = Tcl_GetString(objv[objc-1]); if( zParent[0]=='\0' ) zParent = 0; rc = sqlite3rbu_create_vfs(zName, zParent); if( rc!=SQLITE_OK ){ Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); return TCL_ERROR; }else if( objc==4 ){ sqlite3_vfs *pVfs = sqlite3_vfs_find(zName); sqlite3_vfs_register(pVfs, 1); } Tcl_ResetResult(interp); return TCL_OK; } /* ** Tclcmd: sqlite3rbu_destroy_vfs NAME */ static int test_sqlite3rbu_destroy_vfs( ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ const char *zName; if( objc!=2 ){ Tcl_WrongNumArgs(interp, 1, objv, "NAME"); return TCL_ERROR; } zName = Tcl_GetString(objv[1]); sqlite3rbu_destroy_vfs(zName); return TCL_OK; } /* ** Tclcmd: sqlite3rbu_internal_test */ static int test_sqlite3rbu_internal_test( ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ sqlite3 *db; if( objc!=1 ){ Tcl_WrongNumArgs(interp, 1, objv, ""); return TCL_ERROR; } db = sqlite3rbu_db(0, 0); if( db!=0 ){ Tcl_AppendResult(interp, "sqlite3rbu_db(0, 0)!=0", 0); return TCL_ERROR; } return TCL_OK; } int SqliteRbu_Init(Tcl_Interp *interp){ static struct { char *zName; Tcl_ObjCmdProc *xProc; } aObjCmd[] = { { "sqlite3rbu", test_sqlite3rbu }, { "sqlite3rbu_vacuum", test_sqlite3rbu_vacuum }, { "sqlite3rbu_create_vfs", test_sqlite3rbu_create_vfs }, { "sqlite3rbu_destroy_vfs", test_sqlite3rbu_destroy_vfs }, { "sqlite3rbu_internal_test", test_sqlite3rbu_internal_test }, }; int i; for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){ Tcl_CreateObjCommand(interp, aObjCmd[i].zName, aObjCmd[i].xProc, 0, 0); } return TCL_OK; } #else #include <tcl.h> int SqliteRbu_Init(Tcl_Interp *interp){ return TCL_OK; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */ #endif /* defined(SQLITE_TEST) */
the_stack_data/23575755.c
// Program 8.5 /* Function to find the greatest common divisor of two nonnegative integer values */ #include<stdio.h> void gcd( int u, int v ) { int temp; printf( "The gcd of %i and %i is ", u, v ); while( v != 0 ) { temp = u % v; u = v; v = temp; } printf( "%i\n", u ); } int main( void ) { gcd( 150, 35 ); gcd( 1026, 405 ); gcd( 83, 240 ); return 0; }
the_stack_data/40763397.c
// REQUIRES: native-run // RUN: %clang_builtins %s %librt -o %t && %run_nomprotect %t // REQUIRES: librt_has_enable_execute_stack #include <stdio.h> #include <string.h> #include <stdint.h> extern void __clear_cache(void* start, void* end); extern void __enable_execute_stack(void* addr); typedef int (*pfunc)(void); // Make these static to avoid ILT jumps for incremental linking on Windows. static int func1() { return 1; } static int func2() { return 2; } void *__attribute__((noinline)) memcpy_f(void *dst, const void *src, size_t n) { // ARM and MIPS nartually align functions, but use the LSB for ISA selection // (THUMB, MIPS16/uMIPS respectively). Ensure that the ISA bit is ignored in // the memcpy #if defined(__arm__) || defined(__mips__) return (void *)((uintptr_t)memcpy(dst, (void *)((uintptr_t)src & ~1), n) | ((uintptr_t)src & 1)); #else return memcpy(dst, (void *)((uintptr_t)src), n); #endif } int main() { unsigned char execution_buffer[128]; // mark stack page containing execution_buffer to be executable __enable_execute_stack(execution_buffer); // verify you can copy and execute a function pfunc f1 = (pfunc)memcpy_f(execution_buffer, func1, 128); __clear_cache(execution_buffer, &execution_buffer[128]); printf("f1: %p\n", f1); if ((*f1)() != 1) return 1; // verify you can overwrite a function with another pfunc f2 = (pfunc)memcpy_f(execution_buffer, func2, 128); __clear_cache(execution_buffer, &execution_buffer[128]); if ((*f2)() != 2) return 1; return 0; }
the_stack_data/803174.c
#include<stdio.h> #include<stdlib.h> int main() { int a,sum=0,i=0; float avr; scanf("%d",&a); do { sum=sum+a%10; i++; a=a/10; }while(a>0); avr=(float)sum/i; if(avr>7){printf("\n heavy");} else{printf("\n light");} return 0; }
the_stack_data/156391917.c
//***************************************************************************** // // startup_gcc.c - Startup code for use with GNU tools. // // Copyright (c) 2007-2013 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 10636 of the EK-LM3S2965 Firmware Package. // //***************************************************************************** //***************************************************************************** // // Forward declaration of the default fault handlers. // //***************************************************************************** void ResetISR(void); static void NmiSR(void); static void FaultISR(void); static void IntDefaultHandler(void); //***************************************************************************** // // External declarations for the interrupt handlers used by the application. // //***************************************************************************** extern void CANHandler(void); extern void SysTickIntHandler(void); //***************************************************************************** // // The entry point for the application. // //***************************************************************************** extern int main(void); //***************************************************************************** // // Reserve space for the system stack. // //***************************************************************************** static unsigned long pulStack[128]; //***************************************************************************** // // The vector table. Note that the proper constructs must be placed on this to // ensure that it ends up at physical address 0x0000.0000. // //***************************************************************************** __attribute__ ((section(".isr_vector"))) void (* const g_pfnVectors[])(void) = { (void (*)(void))((unsigned long)pulStack + sizeof(pulStack)), // The initial stack pointer ResetISR, // The reset handler NmiSR, // The NMI handler FaultISR, // The hard fault handler IntDefaultHandler, // The MPU fault handler IntDefaultHandler, // The bus fault handler IntDefaultHandler, // The usage fault handler 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved IntDefaultHandler, // SVCall handler IntDefaultHandler, // Debug monitor handler 0, // Reserved IntDefaultHandler, // The PendSV handler SysTickIntHandler, // The SysTick handler IntDefaultHandler, // GPIO Port A IntDefaultHandler, // GPIO Port B IntDefaultHandler, // GPIO Port C IntDefaultHandler, // GPIO Port D IntDefaultHandler, // GPIO Port E IntDefaultHandler, // UART0 Rx and Tx IntDefaultHandler, // UART1 Rx and Tx IntDefaultHandler, // SSI0 Rx and Tx IntDefaultHandler, // I2C0 Master and Slave IntDefaultHandler, // PWM Fault IntDefaultHandler, // PWM Generator 0 IntDefaultHandler, // PWM Generator 1 IntDefaultHandler, // PWM Generator 2 IntDefaultHandler, // Quadrature Encoder 0 IntDefaultHandler, // ADC Sequence 0 IntDefaultHandler, // ADC Sequence 1 IntDefaultHandler, // ADC Sequence 2 IntDefaultHandler, // ADC Sequence 3 IntDefaultHandler, // Watchdog timer IntDefaultHandler, // Timer 0 subtimer A IntDefaultHandler, // Timer 0 subtimer B IntDefaultHandler, // Timer 1 subtimer A IntDefaultHandler, // Timer 1 subtimer B IntDefaultHandler, // Timer 2 subtimer A IntDefaultHandler, // Timer 2 subtimer B IntDefaultHandler, // Analog Comparator 0 IntDefaultHandler, // Analog Comparator 1 IntDefaultHandler, // Analog Comparator 2 IntDefaultHandler, // System Control (PLL, OSC, BO) IntDefaultHandler, // FLASH Control IntDefaultHandler, // GPIO Port F IntDefaultHandler, // GPIO Port G IntDefaultHandler, // GPIO Port H IntDefaultHandler, // UART2 Rx and Tx IntDefaultHandler, // SSI1 Rx and Tx IntDefaultHandler, // Timer 3 subtimer A IntDefaultHandler, // Timer 3 subtimer B IntDefaultHandler, // I2C1 Master and Slave IntDefaultHandler, // Quadrature Encoder 1 CANHandler, // CAN0 IntDefaultHandler, // CAN1 IntDefaultHandler, // CAN2 IntDefaultHandler, // Ethernet IntDefaultHandler // Hibernate }; //***************************************************************************** // // The following are constructs created by the linker, indicating where the // the "data" and "bss" segments reside in memory. The initializers for the // for the "data" segment resides immediately following the "text" segment. // //***************************************************************************** extern unsigned long _etext; extern unsigned long _data; extern unsigned long _edata; extern unsigned long _bss; extern unsigned long _ebss; //***************************************************************************** // // This is the code that gets called when the processor first starts execution // following a reset event. Only the absolutely necessary set is performed, // after which the application supplied entry() routine is called. Any fancy // actions (such as making decisions based on the reset cause register, and // resetting the bits in that register) are left solely in the hands of the // application. // //***************************************************************************** void ResetISR(void) { unsigned long *pulSrc, *pulDest; // // Copy the data segment initializers from flash to SRAM. // pulSrc = &_etext; for(pulDest = &_data; pulDest < &_edata; ) { *pulDest++ = *pulSrc++; } // // Zero fill the bss segment. // __asm(" ldr r0, =_bss\n" " ldr r1, =_ebss\n" " mov r2, #0\n" " .thumb_func\n" "zero_loop:\n" " cmp r0, r1\n" " it lt\n" " strlt r2, [r0], #4\n" " blt zero_loop"); // // Call the application's entry point. // main(); } //***************************************************************************** // // This is the code that gets called when the processor receives a NMI. This // simply enters an infinite loop, preserving the system state for examination // by a debugger. // //***************************************************************************** static void NmiSR(void) { // // Enter an infinite loop. // while(1) { } } //***************************************************************************** // // This is the code that gets called when the processor receives a fault // interrupt. This simply enters an infinite loop, preserving the system state // for examination by a debugger. // //***************************************************************************** static void FaultISR(void) { // // Enter an infinite loop. // while(1) { } } //***************************************************************************** // // This is the code that gets called when the processor receives an unexpected // interrupt. This simply enters an infinite loop, preserving the system state // for examination by a debugger. // //***************************************************************************** static void IntDefaultHandler(void) { // // Go into an infinite loop. // while(1) { } }
the_stack_data/111078896.c
#include <stdio.h> #define XNAME(n) x ## n #define PRINT_XN(n) printf("x" #n " = %d\n", x ## n) int main(void) { int XNAME(1) = 14; int XNAME(2) = 20; int x3 = 30; PRINT_XN(1); PRINT_XN(2); PRINT_XN(3); return 0; }
the_stack_data/460173.c
#include <stdio.h> #include <stdlib.h> static FILE *static_fun = NULL; FILE * force_static_fun (void) { return static_fun; }
the_stack_data/25137101.c
#include<stdio.h> main() { printf("Fala sério!"); }
the_stack_data/153269393.c
/*Suppose one stack is given, where the elements are stored in sorted order with their number of occurrences i.e each stack element contains two part: element and the number of time it is occurring . Using the basic stack push() and pop() operations, implement the following insert() and delete() functions. a. Insert():- insert one new element in the stack using the push() or/and pop() operation(s) such that if the element exist then it will just increase the number of occurrences or if element doesn’t exist then it will insert the element with its occurrence as 1. After insertion of the element the stack must be sorted. b. Delete():- delete the existing element from the stack using the push() or/and pop() operation(s) such that if the element exist then it will just decrease the number of occurrences or if element doesn’t exist then it will give the underflow message.*/ #include <stdio.h> #include <stdlib.h> struct node { int data; int occur; struct node *next; }*start=NULL,*top=NULL; void push() { printf("Enter the data for the node\n"); struct node *temp,*ptr=start; temp=(struct node *)malloc(sizeof(struct node)); scanf("%d",&temp->data); temp->next=NULL; if(ptr==NULL) { ptr=temp; start=temp; top=temp; temp->occur=1; } else { while(ptr!=NULL) { if(ptr->data==temp->data) { (ptr->occur)++; free(temp); return; } ptr=ptr->next; printf("1\n"); } top->next=temp; temp->occur=1; top=temp; } } void pop() { struct node *ptr=start,*prev; if(top==NULL) { printf("Underflow\n"); return; } else { (top->occur)--; if(top->occur==0) { if(top==start && top->occur==1) { top=NULL; start=NULL; return; } while(ptr->next!=NULL) { prev=ptr; ptr=ptr->next; } prev->next=NULL; top=prev; free(ptr); } } } void display() { struct node *ptr=start; if(ptr==NULL) { printf("The stack is empty\n"); return; } while(ptr!=NULL) { printf("Element:%d Occurance:%d\n",ptr->data,ptr->occur); ptr=ptr->next; } } int main() { printf("------------Stack with occurance---------------\n"); printf("0.Exit\n"); printf("1.Insert into Stack\n"); printf("2.Delete from stack\n"); printf("3.Display the stack\n"); int ch; while(1) { printf("Enter your choice\n"); scanf("%d",&ch); switch(ch) { case 0: exit(0); case 1: push(); display(); break; case 2: pop(); display(); break; default: printf("Wrong Choice Please try again\n"); } } }
the_stack_data/26213.c
/** * Copyright (c) 2015-2017 - 2017, Nordic Semiconductor ASA * * 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, except as embedded into a Nordic * Semiconductor ASA integrated circuit in a product or a software update for * such product, 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. Neither the name of Nordic Semiconductor ASA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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 COMMISSIONING_ENABLED #include <string.h> #include "boards.h" #include "ble_hci.h" #include "nrf_soc.h" #include "app_error.h" #include "fds.h" #include "ble_advdata.h" #include "commissioning.h" #include "nordic_common.h" #include "ble_srv_common.h" #include "sdk_config.h" #define MINIMUM_ACTION_DELAY 2 /**< Delay before executing an action after the control point was written (in seconds). */ #define SEC_PARAM_BOND 0 /**< Perform bonding. */ #define SEC_PARAM_MITM 1 /**< Man In The Middle protection required (applicable when display module is detected). */ #define SEC_PARAM_IO_CAPABILITIES BLE_GAP_IO_CAPS_KEYBOARD_ONLY /**< Display I/O capabilities. */ #define SEC_PARAM_OOB 0 /**< Out Of Band data not available. */ #define SEC_PARAM_MIN_KEY_SIZE 7 /**< Minimum encryption key size. */ #define SEC_PARAM_MAX_KEY_SIZE 16 /**< Maximum encryption key size. */ #define COMM_FDS_FILE_ID 0xCAFE /**< The ID of the file that the record belongs to. */ #define COMM_FDS_RECORD_KEY 0xBEAF /**< The record key of FDS record that keeps node settings. */ #define NUMBER_OF_COMMISSIONING_TIMERS 4 #define TIMER_INDEX_DELAYED_ACTION 0 #define TIMER_INDEX_CONFIG_MODE 1 #define TIMER_INDEX_JOINING_MODE 2 #define TIMER_INDEX_IDENTITY_MODE 3 #define SEC_TO_MILLISEC(PARAM) (PARAM * 1000) static commissioning_settings_t m_node_settings; /**< All node settings as configured through the Node Configuration Service. */ static commissioning_evt_handler_t m_commissioning_evt_handler; /**< Commissioning event handler of the parent layer. */ static bool m_power_off_on_failure = false; /**< Power off on failure setting from the last NCFGS event. */ static commissioning_timer_t m_commissioning_timers[NUMBER_OF_COMMISSIONING_TIMERS]; static ipv6_medium_ble_gap_params_t m_config_mode_gap_params; /**< Advertising parameters in Config mode. */ static ipv6_medium_ble_adv_params_t m_config_mode_adv_params; /**< GAP parameters in Config mode. */ static ipv6_medium_ble_gap_params_t m_joining_mode_gap_params; /**< Advertising parameters in Joining mode. */ static ipv6_medium_ble_adv_params_t m_joining_mode_adv_params; /**< GAP parameters in Joining mode. */ static ble_uuid_t m_config_mode_adv_uuids[] = \ { {BLE_UUID_NODE_CFG_SERVICE, \ BLE_UUID_TYPE_VENDOR_BEGIN} }; /**< Config mode: List of available service UUIDs in advertisement data. */ static ble_uuid_t m_joining_mode_adv_uuids[] = \ { {BLE_UUID_IPSP_SERVICE, BLE_UUID_TYPE_BLE} }; /**< Joining mode: List of available service UUIDs in advertisement data. */ static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; /**< Handle of the active connection. */ static uint8_t m_current_mode = NODE_MODE_NONE; /**< Current mode value. */ static uint8_t m_next_mode = NODE_MODE_NONE; /**< Value of the mode the node will enter when the timeout handler of m_delayed_action_timer is triggered. */ #if (FDS_ENABLED == 1) static fds_record_desc_t m_fds_record_desc; /**< Descriptor of FDS record. */ #endif #define COMM_ENABLE_LOGS 1 /**< Set to 0 to disable debug trace in the module. */ #if COMMISSIONING_CONFIG_LOG_ENABLED #define NRF_LOG_MODULE_NAME commissioning #define NRF_LOG_LEVEL COMMISSIONING_CONFIG_LOG_LEVEL #define NRF_LOG_INFO_COLOR COMMISSIONING_CONFIG_INFO_COLOR #define NRF_LOG_DEBUG_COLOR COMMISSIONING_CONFIG_DEBUG_COLOR #include "nrf_log.h" NRF_LOG_MODULE_REGISTER(); #define COMM_TRC NRF_LOG_DEBUG /**< Used for getting trace of execution in the module. */ #define COMM_ERR NRF_LOG_ERROR /**< Used for logging errors in the module. */ #define COMM_DUMP NRF_LOG_HEXDUMP_DEBUG /**< Used for dumping octet information to get details of bond information etc. */ #define COMM_ENTRY() COMM_TRC(">> %s", __func__) #define COMM_EXIT() COMM_TRC("<< %s", __func__) #else // COMMISSIONING_CONFIG_LOG_ENABLED #define COMM_TRC(...) /**< Disables traces. */ #define COMM_DUMP(...) /**< Disables dumping of octet streams. */ #define COMM_ERR(...) /**< Disables error logs. */ #define COMM_ENTRY(...) #define COMM_EXIT(...) #endif // COMMISSIONING_CONFIG_LOG_ENABLED /**@brief Function for validating all node settings. */ static bool settings_are_valid() { uint8_t tmp = m_node_settings.poweron_mode; if (tmp == 0xFF) { return false; } else { return true; } } #if (FDS_ENABLED == 1) /**@brief Function for updating the node settings in persistent memory. */ static uint32_t persistent_settings_update(void) { uint32_t err_code; fds_find_token_t token; memset(&token, 0, sizeof(token)); fds_record_t record; memset(&record, 0, sizeof(record)); record.file_id = COMM_FDS_FILE_ID; record.key = COMM_FDS_RECORD_KEY; record.data.p_data = &m_node_settings; record.data.length_words = ALIGN_NUM(4, sizeof(commissioning_settings_t))/sizeof(uint32_t); // Try to find FDS record with node settings. err_code = fds_record_find(COMM_FDS_FILE_ID, COMM_FDS_RECORD_KEY, &m_fds_record_desc, &token); if (err_code == FDS_SUCCESS) { err_code = fds_record_update(&m_fds_record_desc, &record); } else { err_code = fds_record_write(&m_fds_record_desc, &record); } if (err_code == FDS_ERR_NO_SPACE_IN_FLASH) { // Run garbage collector to reclaim the flash space that is occupied by records that have been deleted, // or that failed to be completely written due to, for example, a power loss. err_code = fds_gc(); } return err_code; } /**@brief Function for loading node settings from the persistent memory. */ static void persistent_settings_load(void) { uint32_t err_code = FDS_SUCCESS; fds_flash_record_t record; fds_find_token_t token; memset(&token, 0, sizeof(token)); // Try to find FDS record with node settings. err_code = fds_record_find(COMM_FDS_FILE_ID, COMM_FDS_RECORD_KEY, &m_fds_record_desc, &token); if (err_code == FDS_SUCCESS) { err_code = fds_record_open(&m_fds_record_desc, &record); if (err_code == FDS_SUCCESS) { if (record.p_data) { memcpy(&m_node_settings, record.p_data, sizeof(m_node_settings)); } } } } /**@brief Function for clearing node settings from the persistent memory. */ static void persistent_settings_clear(void) { fds_record_delete(&m_fds_record_desc); } /**@brief Function for handling File Data Storage events. */ static void persistent_settings_cb(fds_evt_t const * p_evt) { if (p_evt->id == FDS_EVT_GC) { if (settings_are_valid()) { persistent_settings_update(); } } } /**@brief Function for initializing the File Data Storage module. */ static uint32_t persistent_settings_init(void) { uint32_t err_code; err_code = fds_init(); if (err_code == FDS_SUCCESS) { err_code = fds_register(persistent_settings_cb); } return err_code; } #endif /**@brief Function for setting advertisement parameters in Config mode. */ static void config_mode_adv_params_set(void) { COMM_ENTRY(); memset(&m_config_mode_adv_params, 0x00, sizeof(m_config_mode_adv_params)); m_config_mode_adv_params.advdata.name_type = BLE_ADVDATA_FULL_NAME; m_config_mode_adv_params.advdata.include_appearance = false; m_config_mode_adv_params.advdata.flags = \ BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE; m_config_mode_adv_params.advdata.uuids_complete.uuid_cnt = \ sizeof(m_config_mode_adv_uuids) / sizeof(m_config_mode_adv_uuids[0]); m_config_mode_adv_params.advdata.uuids_complete.p_uuids = m_config_mode_adv_uuids; m_config_mode_adv_params.advdata.p_manuf_specific_data = NULL; if (m_node_settings.id_data_store.identity_data_len > 0) { m_config_mode_adv_params.sr_man_specific_data.data.size = \ m_node_settings.id_data_store.identity_data_len; m_config_mode_adv_params.sr_man_specific_data.data.p_data = \ m_node_settings.id_data_store.identity_data; m_config_mode_adv_params.sr_man_specific_data.company_identifier = \ COMPANY_IDENTIFIER; m_config_mode_adv_params.srdata.p_manuf_specific_data = \ &m_config_mode_adv_params.sr_man_specific_data; } else { m_config_mode_adv_params.srdata.p_manuf_specific_data = NULL; } m_config_mode_adv_params.advparams.type = BLE_GAP_ADV_TYPE_ADV_IND; m_config_mode_adv_params.advparams.p_peer_addr = NULL; // Undirected advertisement. m_config_mode_adv_params.advparams.fp = BLE_GAP_ADV_FP_ANY; m_config_mode_adv_params.advparams.interval = CONFIG_MODE_ADV_ADV_INTERVAL; m_config_mode_adv_params.advparams.timeout = CONFIG_MODE_ADV_TIMEOUT; COMM_EXIT(); } /**@brief Function for setting GAP parameters in Config mode. */ static void config_mode_gap_params_set(void) { COMM_ENTRY(); memset(&m_config_mode_gap_params, 0x00, sizeof(m_config_mode_gap_params)); BLE_GAP_CONN_SEC_MODE_SET_OPEN(&m_config_mode_gap_params.sec_mode); m_config_mode_gap_params.p_dev_name = (const uint8_t *)CONFIG_MODE_DEVICE_NAME; m_config_mode_gap_params.dev_name_len = strlen(CONFIG_MODE_DEVICE_NAME); m_config_mode_gap_params.gap_conn_params.min_conn_interval = \ (uint16_t)CONFIG_MODE_MIN_CONN_INTERVAL; m_config_mode_gap_params.gap_conn_params.max_conn_interval = \ (uint16_t)CONFIG_MODE_MAX_CONN_INTERVAL; m_config_mode_gap_params.gap_conn_params.slave_latency = CONFIG_MODE_SLAVE_LATENCY; m_config_mode_gap_params.gap_conn_params.conn_sup_timeout = CONFIG_MODE_CONN_SUP_TIMEOUT; COMM_EXIT(); } /**@brief Function for setting advertisement parameters in Joining mode. */ static void joining_mode_adv_params_set(void) { COMM_ENTRY(); memset(&m_joining_mode_adv_params, 0x00, sizeof(m_joining_mode_adv_params)); if (m_node_settings.ssid_store.ssid_len > 0) { m_joining_mode_adv_params.adv_man_specific_data.data.size = \ m_node_settings.ssid_store.ssid_len; m_joining_mode_adv_params.adv_man_specific_data.data.p_data = \ m_node_settings.ssid_store.ssid; m_joining_mode_adv_params.adv_man_specific_data.company_identifier = \ COMPANY_IDENTIFIER; } m_joining_mode_adv_params.advdata.name_type = BLE_ADVDATA_NO_NAME; m_joining_mode_adv_params.advdata.include_appearance = false; m_joining_mode_adv_params.advdata.flags = \ BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED; m_joining_mode_adv_params.advdata.uuids_complete.uuid_cnt = \ sizeof(m_joining_mode_adv_uuids) / sizeof(m_joining_mode_adv_uuids[0]); m_joining_mode_adv_params.advdata.uuids_complete.p_uuids = m_joining_mode_adv_uuids; if (m_node_settings.ssid_store.ssid_len > 0) { m_joining_mode_adv_params.advdata.p_manuf_specific_data = \ &m_joining_mode_adv_params.adv_man_specific_data; } else { m_joining_mode_adv_params.advdata.p_manuf_specific_data = NULL; } if (m_node_settings.id_data_store.identity_data_len > 0) { m_joining_mode_adv_params.sr_man_specific_data.data.size = \ m_node_settings.id_data_store.identity_data_len; m_joining_mode_adv_params.sr_man_specific_data.data.p_data = \ m_node_settings.id_data_store.identity_data; m_joining_mode_adv_params.sr_man_specific_data.company_identifier = \ COMPANY_IDENTIFIER; m_joining_mode_adv_params.srdata.p_manuf_specific_data = \ &m_joining_mode_adv_params.sr_man_specific_data; } else { m_joining_mode_adv_params.srdata.p_manuf_specific_data = NULL; } m_joining_mode_adv_params.advparams.type = BLE_GAP_ADV_TYPE_ADV_IND; m_joining_mode_adv_params.advparams.p_peer_addr = NULL; // Undirected advertisement. m_joining_mode_adv_params.advparams.fp = BLE_GAP_ADV_FP_ANY; m_joining_mode_adv_params.advparams.interval = APP_ADV_ADV_INTERVAL; m_joining_mode_adv_params.advparams.timeout = APP_ADV_TIMEOUT; COMM_EXIT(); } /**@brief Function for setting GAP parameters in Joining mode. */ static void joining_mode_gap_params_set(void) { COMM_ENTRY(); memset(&m_joining_mode_gap_params, 0x00, sizeof(m_joining_mode_gap_params)); BLE_GAP_CONN_SEC_MODE_SET_OPEN(&m_joining_mode_gap_params.sec_mode); m_joining_mode_gap_params.appearance = BLE_APPEARANCE_UNKNOWN; m_joining_mode_gap_params.p_dev_name = (const uint8_t *)DEVICE_NAME; m_joining_mode_gap_params.dev_name_len = strlen(DEVICE_NAME); m_joining_mode_gap_params.gap_conn_params.min_conn_interval = \ (uint16_t)JOINING_MODE_MIN_CONN_INTERVAL; m_joining_mode_gap_params.gap_conn_params.max_conn_interval = \ (uint16_t)JOINING_MODE_MAX_CONN_INTERVAL; m_joining_mode_gap_params.gap_conn_params.slave_latency = JOINING_MODE_SLAVE_LATENCY; m_joining_mode_gap_params.gap_conn_params.conn_sup_timeout = JOINING_MODE_CONN_SUP_TIMEOUT; COMM_EXIT(); } /**@brief Function for starting a timer in the Commissioning module. * */ static void commissioning_timer_start(uint8_t index, uint32_t timeout_sec) { m_commissioning_timers[index].is_timer_running = true; m_commissioning_timers[index].current_value_sec = timeout_sec; } /**@brief Function for stopping and re-setting a timer in the Commissioning module. * */ static void commissioning_timer_stop_reset(uint8_t index) { m_commissioning_timers[index].is_timer_running = false; m_commissioning_timers[index].current_value_sec = 0x00; } void commissioning_node_mode_change(uint8_t new_mode) { COMM_ENTRY(); commissioning_evt_t commissioning_evt; memset(&commissioning_evt, 0x00, sizeof(commissioning_evt)); commissioning_evt.p_commissioning_settings = &m_node_settings; commissioning_evt.power_off_enable_requested = m_power_off_on_failure; commissioning_timer_stop_reset(TIMER_INDEX_DELAYED_ACTION); commissioning_timer_stop_reset(TIMER_INDEX_CONFIG_MODE); commissioning_timer_stop_reset(TIMER_INDEX_JOINING_MODE); config_mode_gap_params_set(); config_mode_adv_params_set(); joining_mode_gap_params_set(); joining_mode_adv_params_set(); m_current_mode = new_mode; switch (m_current_mode) { case NODE_MODE_CONFIG: { commissioning_evt.commissioning_evt_id = COMMISSIONING_EVT_CONFIG_MODE_ENTER; m_commissioning_evt_handler(&commissioning_evt); // Start Configuration mode timer. COMM_TRC("Config mode timeout: %ld seconds", m_node_settings.config_mode_to); commissioning_timer_start(TIMER_INDEX_CONFIG_MODE, m_node_settings.config_mode_to); break; } case NODE_MODE_JOINING: { commissioning_evt.commissioning_evt_id = COMMISSIONING_EVT_JOINING_MODE_ENTER; m_commissioning_evt_handler(&commissioning_evt); // Start Joining mode timer. COMM_TRC("Joining mode timeout: %ld seconds", m_node_settings.joining_mode_to); commissioning_timer_start(TIMER_INDEX_JOINING_MODE, m_node_settings.joining_mode_to); break; } case NODE_MODE_IDENTITY: { commissioning_evt.commissioning_evt_id = COMMISSIONING_EVT_IDENTITY_MODE_ENTER; m_commissioning_evt_handler(&commissioning_evt); // Start Identity mode timer. COMM_TRC("Identity mode timeout: %ld seconds", m_node_settings.id_mode_to); commissioning_timer_start(TIMER_INDEX_IDENTITY_MODE, m_node_settings.id_mode_to); break; } default: { break; } } COMM_EXIT(); } /**@brief Function for handling the Delayed action timer timeout. * * @details This function will be called each time the delayed action timer expires. * */ static void action_timeout_handler(void) { COMM_ENTRY(); commissioning_node_mode_change(m_next_mode); COMM_EXIT(); } /**@brief Function for handling the Config mode timer timeout. * * @details This function will be called each time the Config mode timer expires. * */ static void config_mode_timeout_handler(void) { COMM_ENTRY(); switch (m_node_settings.config_mode_failure) { case NCFGS_SOF_NO_CHANGE: // Fall-through. case NCFGS_SOF_CONFIG_MODE: { commissioning_node_mode_change(NODE_MODE_CONFIG); break; } case NCFGS_SOF_PWR_OFF: { LEDS_OFF(LEDS_MASK); // The main timer in Config mode timed out, power off. UNUSED_VARIABLE(sd_power_system_off()); break; } } COMM_EXIT(); } /**@brief Function for handling the Joining mode timer timeout. * * @details This function will be called each time the Joining mode timer expires. * */ void joining_mode_timeout_handler(void) { COMM_ENTRY(); switch (m_node_settings.joining_mode_failure) { case NCFGS_SOF_NO_CHANGE: { commissioning_node_mode_change(NODE_MODE_JOINING); break; } case NCFGS_SOF_PWR_OFF: { LEDS_OFF(LEDS_MASK); UNUSED_VARIABLE(sd_power_system_off()); break; } case NCFGS_SOF_CONFIG_MODE: { commissioning_node_mode_change(NODE_MODE_CONFIG); break; } } COMM_EXIT(); } /**@brief Function for handling the Identity mode timer timeout. * * @details This function will be called each time the Identity mode timer expires. * */ void identity_mode_timeout_handler(void) { COMM_ENTRY(); commissioning_evt_t commissioning_evt; memset(&commissioning_evt, 0x00, sizeof(commissioning_evt)); commissioning_evt.commissioning_evt_id = COMMISSIONING_EVT_IDENTITY_MODE_EXIT; m_commissioning_evt_handler(&commissioning_evt); COMM_EXIT(); } void commissioning_joining_mode_timer_ctrl( \ joining_mode_timer_ctrl_cmd_t joining_mode_timer_ctrl_cmd) { switch (joining_mode_timer_ctrl_cmd) { case JOINING_MODE_TIMER_STOP_RESET: { commissioning_timer_stop_reset(TIMER_INDEX_JOINING_MODE); break; } case JOINING_MODE_TIMER_START: { commissioning_timer_start(TIMER_INDEX_JOINING_MODE, m_node_settings.joining_mode_to); break; } } } void commissioning_gap_params_get(ipv6_medium_ble_gap_params_t ** pp_node_gap_params) { switch (m_current_mode) { case NODE_MODE_JOINING: { *pp_node_gap_params = &m_joining_mode_gap_params; break; } case NODE_MODE_IDENTITY: // Fall-through. case NODE_MODE_CONFIG: { *pp_node_gap_params = &m_config_mode_gap_params; break; } } } void commissioning_adv_params_get(ipv6_medium_ble_adv_params_t ** pp_node_adv_params) { switch (m_current_mode) { case NODE_MODE_JOINING: { *pp_node_adv_params = &m_joining_mode_adv_params; break; } case NODE_MODE_IDENTITY: // Fall-through. case NODE_MODE_CONFIG: { *pp_node_adv_params = &m_config_mode_adv_params; break; } } } /**@brief Function for reading all node settings from the persistent storage. */ static void read_node_settings(void) { memset(&m_node_settings, 0x00, sizeof(m_node_settings)); #if (FDS_ENABLED == 1) persistent_settings_load(); #endif // FDS_ENABLED if (m_node_settings.ssid_store.ssid_len > NCFGS_SSID_MAX_LEN) { m_node_settings.ssid_store.ssid_len = 0; } if (m_node_settings.keys_store.keys_len > NCFGS_KEYS_MAX_LEN) { m_node_settings.keys_store.keys_len = 0; } if (m_node_settings.id_data_store.identity_data_len > NCFGS_IDENTITY_DATA_MAX_LEN) { m_node_settings.id_data_store.identity_data_len = 0; } // The duration of each mode needs to be at least 10 second. m_node_settings.joining_mode_to = \ (m_node_settings.joining_mode_to < 10) ? 10 : m_node_settings.joining_mode_to; m_node_settings.config_mode_to = \ (m_node_settings.config_mode_to < 10) ? 10 : m_node_settings.config_mode_to; m_node_settings.id_mode_to = \ (m_node_settings.id_mode_to < 10) ? 10 : m_node_settings.id_mode_to; } #if (COMM_ENABLE_LOGS == 1) /**@brief Function for printing all node settings. */ static void print_node_settings(void) { COMM_TRC(""); COMM_TRC(" Commissioning settings in memory:"); COMM_TRC(" Start mode: %5d", m_node_settings.poweron_mode); COMM_TRC(" Mode if Joining Mode fails: %5d", m_node_settings.joining_mode_failure); COMM_TRC(" General timeout in Joining Mode: %5ld", m_node_settings.joining_mode_to); COMM_TRC(" Mode if Configuration Mode fails: %5d", m_node_settings.config_mode_failure); COMM_TRC("General timeout in Configuration Mode: %5ld", m_node_settings.config_mode_to); COMM_TRC(" Identity Mode duration: %5ld", m_node_settings.id_mode_to); COMM_TRC(" Stored Keys length: %5d", m_node_settings.keys_store.keys_len); COMM_TRC(" Stored Keys:"); uint8_t ii; for (ii=0; ii<m_node_settings.keys_store.keys_len; ++ii) { COMM_TRC("0x%02X", m_node_settings.keys_store.keys[ii]); } COMM_TRC(""); COMM_TRC(" Stored SSID length: %5d", m_node_settings.ssid_store.ssid_len); COMM_TRC(" Stored SSID:"); for (ii=0; ii<m_node_settings.ssid_store.ssid_len; ++ii) { COMM_TRC("0x%02X", m_node_settings.ssid_store.ssid[ii]); } COMM_TRC(""); COMM_TRC(" Stored Identity Data length: %5d", m_node_settings.id_data_store.identity_data_len); COMM_TRC(" Stored Identity Data:"); for (ii=0; ii<m_node_settings.id_data_store.identity_data_len; ++ii) { COMM_TRC("0x%02X", m_node_settings.id_data_store.identity_data[ii]); } COMM_TRC(""); } #endif // (COMM_ENABLE_LOGS == 1) void commissioning_settings_clear(void) { COMM_ENTRY(); memset(&m_node_settings, 0x00, sizeof(m_node_settings)); #if (FDS_ENABLED == 1) persistent_settings_clear(); #endif // FDS_ENABLED COMM_EXIT(); } void commissioning_ble_evt_handler(const ble_evt_t * p_ble_evt) { uint32_t err_code; switch (p_ble_evt->header.evt_id) { case BLE_GAP_EVT_CONNECTED: { m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle; commissioning_timer_stop_reset(TIMER_INDEX_DELAYED_ACTION); commissioning_timer_stop_reset(TIMER_INDEX_CONFIG_MODE); break; } case BLE_GAP_EVT_DISCONNECTED: { m_conn_handle = BLE_CONN_HANDLE_INVALID; if (m_current_mode == NODE_MODE_CONFIG) { commissioning_timer_start(TIMER_INDEX_CONFIG_MODE, \ m_node_settings.config_mode_to); } if (m_current_mode == NODE_MODE_JOINING) { commissioning_timer_start(TIMER_INDEX_JOINING_MODE, \ m_node_settings.joining_mode_to); } break; } case BLE_GAP_EVT_AUTH_KEY_REQUEST: { if (m_current_mode == NODE_MODE_JOINING) { // If passkey is shorter than BLE_GAP_PASSKEY_LEN, add '0' character. if (m_node_settings.keys_store.keys_len < BLE_GAP_PASSKEY_LEN) { memset(&m_node_settings.keys_store.keys[m_node_settings.keys_store.keys_len], \ '0', BLE_GAP_PASSKEY_LEN - m_node_settings.keys_store.keys_len); } // Short passkey to 6-length character. m_node_settings.keys_store.keys[BLE_GAP_PASSKEY_LEN] = 0; COMM_TRC("Stored passkey is: %s", m_node_settings.keys_store.keys); err_code = sd_ble_gap_auth_key_reply(m_conn_handle, \ BLE_GAP_AUTH_KEY_TYPE_PASSKEY, \ m_node_settings.keys_store.keys); APP_ERROR_CHECK(err_code); } break; } case BLE_GAP_EVT_AUTH_STATUS: { if (m_current_mode == NODE_MODE_JOINING) { COMM_TRC("Status of authentication: %08x", \ p_ble_evt->evt.gap_evt.params.auth_status.auth_status); } break; } case BLE_GAP_EVT_SEC_PARAMS_REQUEST: { if (m_current_mode == NODE_MODE_JOINING) { ble_gap_sec_params_t sec_param; ble_gap_sec_keyset_t keys_exchanged; memset(&sec_param, 0, sizeof(ble_gap_sec_params_t)); memset(&keys_exchanged, 0, sizeof(ble_gap_sec_keyset_t)); sec_param.bond = SEC_PARAM_BOND; sec_param.oob = SEC_PARAM_OOB; sec_param.min_key_size = SEC_PARAM_MIN_KEY_SIZE; sec_param.max_key_size = SEC_PARAM_MAX_KEY_SIZE; sec_param.mitm = SEC_PARAM_MITM; sec_param.io_caps = SEC_PARAM_IO_CAPABILITIES; err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_SUCCESS, &sec_param, &keys_exchanged); APP_ERROR_CHECK(err_code); } break; } default: { break; } } } void on_ble_ncfgs_evt(ble_ncfgs_data_t * ncfgs_data) { COMM_ENTRY(); commissioning_timer_stop_reset(TIMER_INDEX_DELAYED_ACTION); commissioning_timer_stop_reset(TIMER_INDEX_CONFIG_MODE); uint32_t mode_duration_sec; mode_duration_sec = ncfgs_data->ctrlp_value.duration_sec; mode_duration_sec = (mode_duration_sec == 0) ? 1 : mode_duration_sec; switch (ncfgs_data->ctrlp_value.opcode) { case NCFGS_OPCODE_GOTO_JOINING_MODE: { m_next_mode = NODE_MODE_JOINING; m_node_settings.joining_mode_to = mode_duration_sec; m_node_settings.joining_mode_failure = ncfgs_data->ctrlp_value.state_on_failure; /* This code will get executed in two scenarios: - if the previous mode was Config mode and now we are ready to connect to the router, or - if the previous mode was Joining mode and the state on failure was set to No Change. */ if (m_node_settings.joining_mode_failure == NCFGS_SOF_NO_CHANGE) { m_node_settings.poweron_mode = NODE_MODE_JOINING; } else { // If the state on failure is NOT No Change, start next time in Config mode. m_node_settings.poweron_mode = NODE_MODE_CONFIG; } if (m_node_settings.joining_mode_failure == NCFGS_SOF_PWR_OFF) { COMM_TRC("Will power off on failure."); m_power_off_on_failure = true; // The assert handler will power off the system. } break; } case NCFGS_OPCODE_GOTO_CONFIG_MODE: { m_next_mode = NODE_MODE_CONFIG; m_node_settings.config_mode_to = mode_duration_sec; m_node_settings.config_mode_failure = ncfgs_data->ctrlp_value.state_on_failure; /* The node is about to enter Config mode. Regardless of what the state on failure setting is (No Change or Pwr Off or Cfg Mode), the poweron_mode value should be Cfg Mode. */ m_node_settings.poweron_mode = NODE_MODE_CONFIG; if (m_node_settings.config_mode_failure == NCFGS_SOF_PWR_OFF) { COMM_TRC("Will power off on failure."); m_power_off_on_failure = true; // The assert handler will power off the system. } break; } case NCFGS_OPCODE_GOTO_IDENTITY_MODE: { m_next_mode = NODE_MODE_IDENTITY; m_node_settings.id_mode_to = mode_duration_sec; break; } default: { break; } } memcpy(&m_node_settings.ssid_store, &ncfgs_data->ssid_from_router, sizeof(ssid_store_t)); memcpy(&m_node_settings.keys_store, &ncfgs_data->keys_from_router, sizeof(keys_store_t)); memcpy(&m_node_settings.id_data_store, &ncfgs_data->id_data, sizeof(id_data_store_t)); #if (COMM_ENABLE_LOGS == 1) print_node_settings(); #endif // (COMM_ENABLE_LOGS == 1) #if (FDS_ENABLED == 1) uint32_t err_code = persistent_settings_update(); APP_ERROR_CHECK(err_code); #endif // FDS_ENABLED uint32_t action_delay_written = ncfgs_data->ctrlp_value.delay_sec; // Set the timeout value to at least MINIMUM_ACTION_DELAY second(s). // This is to make sure that storing settings in the persistent // storage completes before activating the next mode. action_delay_written = (action_delay_written < MINIMUM_ACTION_DELAY) ? \ MINIMUM_ACTION_DELAY : action_delay_written; COMM_TRC("Action delay: %ld seconds.", action_delay_written); commissioning_timer_start(TIMER_INDEX_DELAYED_ACTION, action_delay_written); COMM_EXIT(); } void commissioning_time_tick(iot_timer_time_in_ms_t wall_clock_value) { UNUSED_PARAMETER(wall_clock_value); uint8_t index; for (index=0; index<NUMBER_OF_COMMISSIONING_TIMERS; ++index) { if (m_commissioning_timers[index].is_timer_running == true) { m_commissioning_timers[index].current_value_sec -= COMMISSIONING_TICK_INTERVAL_SEC; if (m_commissioning_timers[index].current_value_sec == 0) { commissioning_timer_stop_reset(index); m_commissioning_timers[index].timeout_handler(); } } } } static void commissioning_timers_init(void) { memset(m_commissioning_timers, 0x00, sizeof(m_commissioning_timers)); m_commissioning_timers[TIMER_INDEX_DELAYED_ACTION].timeout_handler = \ action_timeout_handler; m_commissioning_timers[TIMER_INDEX_CONFIG_MODE].timeout_handler = \ config_mode_timeout_handler; m_commissioning_timers[TIMER_INDEX_JOINING_MODE].timeout_handler = \ joining_mode_timeout_handler; m_commissioning_timers[TIMER_INDEX_IDENTITY_MODE].timeout_handler = \ identity_mode_timeout_handler; } uint32_t commissioning_init(commissioning_init_params_t * p_init_param, \ uint8_t * p_poweron_state) { COMM_ENTRY(); uint32_t err_code = NRF_SUCCESS; m_commissioning_evt_handler = p_init_param->commissioning_evt_handler; m_power_off_on_failure = false; // Initialize Commissioning timers. commissioning_timers_init(); // Initialize GATT server. err_code = ble_ncfgs_init(on_ble_ncfgs_evt); if (err_code != NRF_SUCCESS) { return err_code; } #if (FDS_ENABLED == 1) err_code = persistent_settings_init(); if (err_code != NRF_SUCCESS) { return err_code; } #endif // Read application settings from persistent storage. read_node_settings(); #if (COMM_ENABLE_LOGS == 1) print_node_settings(); #endif // (COMM_ENABLE_LOGS == 1) if (!settings_are_valid()) // If the settings are invalid for any reason go to Config mode. { COMM_ERR("Invalid settings!"); commissioning_settings_clear(); memset(&m_node_settings, 0x00, sizeof(m_node_settings)); m_node_settings.config_mode_to = 300; *p_poweron_state = NODE_MODE_CONFIG; } else { if (m_node_settings.poweron_mode == NODE_MODE_JOINING) { /* This code will get executed in two scenarios: - if the previous mode was Config mode and now we are ready to connect to the router, or - if the previous mode was Joining mode and the state on failure was set to No Change. */ if ((m_node_settings.joining_mode_failure == NCFGS_SOF_PWR_OFF) || \ (m_node_settings.joining_mode_failure == NCFGS_SOF_CONFIG_MODE)) { // If the state on failure is NOT No Change, start next time in Config mode. m_node_settings.poweron_mode = NODE_MODE_CONFIG; #if (FDS_ENABLED == 1) err_code = persistent_settings_update(); APP_ERROR_CHECK(err_code); #endif // FDS_ENABLED } if (m_node_settings.joining_mode_failure == NCFGS_SOF_PWR_OFF) { COMM_TRC("Will power off on failure."); m_power_off_on_failure = true; // The assert handler will power off the system. } *p_poweron_state = NODE_MODE_JOINING; } else { /* The app is about to enter Config mode. Regardless of what the state on failure setting is (No Change or Pwr Off or Cfg Mode), the poweron_mode value should remain the same. */ if (m_node_settings.config_mode_failure == NCFGS_SOF_PWR_OFF) { COMM_TRC("Will power off on failure."); m_power_off_on_failure = true; // The assert handler will power off the system. } *p_poweron_state = NODE_MODE_CONFIG; } } // Set advertising and GAP parameters. config_mode_gap_params_set(); config_mode_adv_params_set(); joining_mode_gap_params_set(); joining_mode_adv_params_set(); COMM_EXIT(); return err_code; } #endif // COMMISSIONING_ENABLED
the_stack_data/237643915.c
// WARNING in task_participate_group_stop // https://syzkaller.appspot.com/bug?id=18436790c9573cf80e76a8676879ba155f67b89d // status:open // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <dirent.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <net/if.h> #include <net/if_arp.h> #include <netinet/in.h> #include <pthread.h> #include <sched.h> #include <setjmp.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <linux/capability.h> #include <linux/futex.h> #include <linux/genetlink.h> #include <linux/if_addr.h> #include <linux/if_ether.h> #include <linux/if_link.h> #include <linux/if_tun.h> #include <linux/in6.h> #include <linux/ip.h> #include <linux/neighbour.h> #include <linux/net.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/tcp.h> #include <linux/veth.h> unsigned long long procid; static __thread int skip_segv; static __thread jmp_buf segv_env; static void segv_handler(int sig, siginfo_t* info, void* ctx) { uintptr_t addr = (uintptr_t)info->si_addr; const uintptr_t prog_start = 1 << 20; const uintptr_t prog_end = 100 << 20; if (__atomic_load_n(&skip_segv, __ATOMIC_RELAXED) && (addr < prog_start || addr > prog_end)) { _longjmp(segv_env, 1); } exit(sig); } static void install_segv_handler(void) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_IGN; syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8); syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8); memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = segv_handler; sa.sa_flags = SA_NODEFER | SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); sigaction(SIGBUS, &sa, NULL); } #define NONFAILING(...) \ { \ __atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \ if (_setjmp(segv_env) == 0) { \ __VA_ARGS__; \ } \ __atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \ } static void sleep_ms(uint64_t ms) { usleep(ms * 1000); } static uint64_t current_time_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) exit(1); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static void use_temporary_dir(void) { char tmpdir_template[] = "./syzkaller.XXXXXX"; char* tmpdir = mkdtemp(tmpdir_template); if (!tmpdir) exit(1); if (chmod(tmpdir, 0777)) exit(1); if (chdir(tmpdir)) exit(1); } static void thread_start(void* (*fn)(void*), void* arg) { pthread_t th; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 128 << 10); int i; for (i = 0; i < 100; i++) { if (pthread_create(&th, &attr, fn, arg) == 0) { pthread_attr_destroy(&attr); return; } if (errno == EAGAIN) { usleep(50); continue; } break; } exit(1); } typedef struct { int state; } event_t; static void event_init(event_t* ev) { ev->state = 0; } static void event_reset(event_t* ev) { ev->state = 0; } static void event_set(event_t* ev) { if (ev->state) exit(1); __atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE); syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG); } static void event_wait(event_t* ev) { while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE)) syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0); } static int event_isset(event_t* ev) { return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE); } static int event_timedwait(event_t* ev, uint64_t timeout) { uint64_t start = current_time_ms(); uint64_t now = start; for (;;) { uint64_t remain = timeout - (now - start); struct timespec ts; ts.tv_sec = remain / 1000; ts.tv_nsec = (remain % 1000) * 1000 * 1000; syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts); if (__atomic_load_n(&ev->state, __ATOMIC_RELAXED)) return 1; now = current_time_ms(); if (now - start > timeout) return 0; } } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } struct nlmsg { char* pos; int nesting; struct nlattr* nested[8]; char buf[1024]; }; static struct nlmsg nlmsg; static void netlink_init(struct nlmsg* nlmsg, int typ, int flags, const void* data, int size) { memset(nlmsg, 0, sizeof(*nlmsg)); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf; hdr->nlmsg_type = typ; hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags; memcpy(hdr + 1, data, size); nlmsg->pos = (char*)(hdr + 1) + NLMSG_ALIGN(size); } static void netlink_attr(struct nlmsg* nlmsg, int typ, const void* data, int size) { struct nlattr* attr = (struct nlattr*)nlmsg->pos; attr->nla_len = sizeof(*attr) + size; attr->nla_type = typ; memcpy(attr + 1, data, size); nlmsg->pos += NLMSG_ALIGN(attr->nla_len); } static void netlink_nest(struct nlmsg* nlmsg, int typ) { struct nlattr* attr = (struct nlattr*)nlmsg->pos; attr->nla_type = typ; nlmsg->pos += sizeof(*attr); nlmsg->nested[nlmsg->nesting++] = attr; } static void netlink_done(struct nlmsg* nlmsg) { struct nlattr* attr = nlmsg->nested[--nlmsg->nesting]; attr->nla_len = nlmsg->pos - (char*)attr; } static int netlink_send_ext(struct nlmsg* nlmsg, int sock, uint16_t reply_type, int* reply_len) { if (nlmsg->pos > nlmsg->buf + sizeof(nlmsg->buf) || nlmsg->nesting) exit(1); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf; hdr->nlmsg_len = nlmsg->pos - nlmsg->buf; struct sockaddr_nl addr; memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; unsigned n = sendto(sock, nlmsg->buf, hdr->nlmsg_len, 0, (struct sockaddr*)&addr, sizeof(addr)); if (n != hdr->nlmsg_len) exit(1); n = recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); if (hdr->nlmsg_type == NLMSG_DONE) { *reply_len = 0; return 0; } if (n < sizeof(struct nlmsghdr)) exit(1); if (reply_len && hdr->nlmsg_type == reply_type) { *reply_len = n; return 0; } if (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr)) exit(1); if (hdr->nlmsg_type != NLMSG_ERROR) exit(1); return -((struct nlmsgerr*)(hdr + 1))->error; } static int netlink_send(struct nlmsg* nlmsg, int sock) { return netlink_send_ext(nlmsg, sock, 0, NULL); } static int netlink_next_msg(struct nlmsg* nlmsg, unsigned int offset, unsigned int total_len) { struct nlmsghdr* hdr = (struct nlmsghdr*)(nlmsg->buf + offset); if (offset == total_len || offset + hdr->nlmsg_len > total_len) return -1; return hdr->nlmsg_len; } static void netlink_add_device_impl(struct nlmsg* nlmsg, const char* type, const char* name) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); netlink_init(nlmsg, RTM_NEWLINK, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); if (name) netlink_attr(nlmsg, IFLA_IFNAME, name, strlen(name)); netlink_nest(nlmsg, IFLA_LINKINFO); netlink_attr(nlmsg, IFLA_INFO_KIND, type, strlen(type)); } static void netlink_add_device(struct nlmsg* nlmsg, int sock, const char* type, const char* name) { netlink_add_device_impl(nlmsg, type, name); netlink_done(nlmsg); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_add_veth(struct nlmsg* nlmsg, int sock, const char* name, const char* peer) { netlink_add_device_impl(nlmsg, "veth", name); netlink_nest(nlmsg, IFLA_INFO_DATA); netlink_nest(nlmsg, VETH_INFO_PEER); nlmsg->pos += sizeof(struct ifinfomsg); netlink_attr(nlmsg, IFLA_IFNAME, peer, strlen(peer)); netlink_done(nlmsg); netlink_done(nlmsg); netlink_done(nlmsg); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_add_hsr(struct nlmsg* nlmsg, int sock, const char* name, const char* slave1, const char* slave2) { netlink_add_device_impl(nlmsg, "hsr", name); netlink_nest(nlmsg, IFLA_INFO_DATA); int ifindex1 = if_nametoindex(slave1); netlink_attr(nlmsg, IFLA_HSR_SLAVE1, &ifindex1, sizeof(ifindex1)); int ifindex2 = if_nametoindex(slave2); netlink_attr(nlmsg, IFLA_HSR_SLAVE2, &ifindex2, sizeof(ifindex2)); netlink_done(nlmsg); netlink_done(nlmsg); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_device_change(struct nlmsg* nlmsg, int sock, const char* name, bool up, const char* master, const void* mac, int macsize, const char* new_name) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); if (up) hdr.ifi_flags = hdr.ifi_change = IFF_UP; hdr.ifi_index = if_nametoindex(name); netlink_init(nlmsg, RTM_NEWLINK, 0, &hdr, sizeof(hdr)); if (new_name) netlink_attr(nlmsg, IFLA_IFNAME, new_name, strlen(new_name)); if (master) { int ifindex = if_nametoindex(master); netlink_attr(nlmsg, IFLA_MASTER, &ifindex, sizeof(ifindex)); } if (macsize) netlink_attr(nlmsg, IFLA_ADDRESS, mac, macsize); int err = netlink_send(nlmsg, sock); (void)err; } static int netlink_add_addr(struct nlmsg* nlmsg, int sock, const char* dev, const void* addr, int addrsize) { struct ifaddrmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ifa_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ifa_prefixlen = addrsize == 4 ? 24 : 120; hdr.ifa_scope = RT_SCOPE_UNIVERSE; hdr.ifa_index = if_nametoindex(dev); netlink_init(nlmsg, RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, &hdr, sizeof(hdr)); netlink_attr(nlmsg, IFA_LOCAL, addr, addrsize); netlink_attr(nlmsg, IFA_ADDRESS, addr, addrsize); return netlink_send(nlmsg, sock); } static void netlink_add_addr4(struct nlmsg* nlmsg, int sock, const char* dev, const char* addr) { struct in_addr in_addr; inet_pton(AF_INET, addr, &in_addr); int err = netlink_add_addr(nlmsg, sock, dev, &in_addr, sizeof(in_addr)); (void)err; } static void netlink_add_addr6(struct nlmsg* nlmsg, int sock, const char* dev, const char* addr) { struct in6_addr in6_addr; inet_pton(AF_INET6, addr, &in6_addr); int err = netlink_add_addr(nlmsg, sock, dev, &in6_addr, sizeof(in6_addr)); (void)err; } static void netlink_add_neigh(struct nlmsg* nlmsg, int sock, const char* name, const void* addr, int addrsize, const void* mac, int macsize) { struct ndmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ndm_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ndm_ifindex = if_nametoindex(name); hdr.ndm_state = NUD_PERMANENT; netlink_init(nlmsg, RTM_NEWNEIGH, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); netlink_attr(nlmsg, NDA_DST, addr, addrsize); netlink_attr(nlmsg, NDA_LLADDR, mac, macsize); int err = netlink_send(nlmsg, sock); (void)err; } static int tunfd = -1; static int tun_frags_enabled; #define TUN_IFACE "syz_tun" #define LOCAL_MAC 0xaaaaaaaaaaaa #define REMOTE_MAC 0xaaaaaaaaaabb #define LOCAL_IPV4 "172.20.20.170" #define REMOTE_IPV4 "172.20.20.187" #define LOCAL_IPV6 "fe80::aa" #define REMOTE_IPV6 "fe80::bb" #define IFF_NAPI 0x0010 #define IFF_NAPI_FRAGS 0x0020 static void initialize_tun(void) { tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK); if (tunfd == -1) { printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n"); printf("otherwise fuzzing or reproducing might not work as intended\n"); return; } const int kTunFd = 240; if (dup2(tunfd, kTunFd) < 0) exit(1); close(tunfd); tunfd = kTunFd; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, TUN_IFACE, IFNAMSIZ); ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_NAPI | IFF_NAPI_FRAGS; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) { ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) exit(1); } if (ioctl(tunfd, TUNGETIFF, (void*)&ifr) < 0) exit(1); tun_frags_enabled = (ifr.ifr_flags & IFF_NAPI_FRAGS) != 0; char sysctl[64]; sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/accept_dad", TUN_IFACE); write_file(sysctl, "0"); sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/router_solicitations", TUN_IFACE); write_file(sysctl, "0"); int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); netlink_add_addr4(&nlmsg, sock, TUN_IFACE, LOCAL_IPV4); netlink_add_addr6(&nlmsg, sock, TUN_IFACE, LOCAL_IPV6); uint64_t macaddr = REMOTE_MAC; struct in_addr in_addr; inet_pton(AF_INET, REMOTE_IPV4, &in_addr); netlink_add_neigh(&nlmsg, sock, TUN_IFACE, &in_addr, sizeof(in_addr), &macaddr, ETH_ALEN); struct in6_addr in6_addr; inet_pton(AF_INET6, REMOTE_IPV6, &in6_addr); netlink_add_neigh(&nlmsg, sock, TUN_IFACE, &in6_addr, sizeof(in6_addr), &macaddr, ETH_ALEN); macaddr = LOCAL_MAC; netlink_device_change(&nlmsg, sock, TUN_IFACE, true, 0, &macaddr, ETH_ALEN, NULL); close(sock); } const int kInitNetNsFd = 239; #define DEVLINK_FAMILY_NAME "devlink" #define DEVLINK_CMD_PORT_GET 5 #define DEVLINK_CMD_RELOAD 37 #define DEVLINK_ATTR_BUS_NAME 1 #define DEVLINK_ATTR_DEV_NAME 2 #define DEVLINK_ATTR_NETDEV_NAME 7 #define DEVLINK_ATTR_NETNS_FD 138 static int netlink_devlink_id_get(struct nlmsg* nlmsg, int sock) { struct genlmsghdr genlhdr; struct nlattr* attr; int err, n; uint16_t id = 0; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = CTRL_CMD_GETFAMILY; netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, DEVLINK_FAMILY_NAME, strlen(DEVLINK_FAMILY_NAME) + 1); err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n); if (err) { return -1; } attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(genlhdr))); for (; (char*)attr < nlmsg->buf + n; attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) { if (attr->nla_type == CTRL_ATTR_FAMILY_ID) { id = *(uint16_t*)(attr + 1); break; } } if (!id) { return -1; } recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); /* recv ack */ return id; } static void netlink_devlink_netns_move(const char* bus_name, const char* dev_name, int netns_fd) { struct genlmsghdr genlhdr; int sock; int id, err; sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC); if (sock == -1) exit(1); id = netlink_devlink_id_get(&nlmsg, sock); if (id == -1) goto error; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = DEVLINK_CMD_RELOAD; netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1); netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1); netlink_attr(&nlmsg, DEVLINK_ATTR_NETNS_FD, &netns_fd, sizeof(netns_fd)); err = netlink_send(&nlmsg, sock); if (err) { } error: close(sock); } static struct nlmsg nlmsg2; static void initialize_devlink_ports(const char* bus_name, const char* dev_name, const char* netdev_prefix) { struct genlmsghdr genlhdr; int len, total_len, id, err, offset; uint16_t netdev_index; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC); if (sock == -1) exit(1); int rtsock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (rtsock == -1) exit(1); id = netlink_devlink_id_get(&nlmsg, sock); if (id == -1) goto error; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = DEVLINK_CMD_PORT_GET; netlink_init(&nlmsg, id, NLM_F_DUMP, &genlhdr, sizeof(genlhdr)); netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1); netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1); err = netlink_send_ext(&nlmsg, sock, id, &total_len); if (err) { goto error; } offset = 0; netdev_index = 0; while ((len = netlink_next_msg(&nlmsg, offset, total_len)) != -1) { struct nlattr* attr = (struct nlattr*)(nlmsg.buf + offset + NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(genlhdr))); for (; (char*)attr < nlmsg.buf + offset + len; attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) { if (attr->nla_type == DEVLINK_ATTR_NETDEV_NAME) { char* port_name; char netdev_name[IFNAMSIZ]; port_name = (char*)(attr + 1); snprintf(netdev_name, sizeof(netdev_name), "%s%d", netdev_prefix, netdev_index); netlink_device_change(&nlmsg2, rtsock, port_name, true, 0, 0, 0, netdev_name); break; } } offset += len; netdev_index++; } error: close(rtsock); close(sock); } static void initialize_devlink_pci(void) { int netns = open("/proc/self/ns/net", O_RDONLY); if (netns == -1) exit(1); int ret = setns(kInitNetNsFd, 0); if (ret == -1) exit(1); netlink_devlink_netns_move("pci", "0000:00:10.0", netns); ret = setns(netns, 0); if (ret == -1) exit(1); close(netns); initialize_devlink_ports("pci", "0000:00:10.0", "netpci"); } #define DEV_IPV4 "172.20.20.%d" #define DEV_IPV6 "fe80::%02x" #define DEV_MAC 0x00aaaaaaaaaa static void netdevsim_add(unsigned int addr, unsigned int port_count) { char buf[16]; sprintf(buf, "%u %u", addr, port_count); if (write_file("/sys/bus/netdevsim/new_device", buf)) { snprintf(buf, sizeof(buf), "netdevsim%d", addr); initialize_devlink_ports("netdevsim", buf, "netdevsim"); } } static void initialize_netdevices(void) { char netdevsim[16]; sprintf(netdevsim, "netdevsim%d", (int)procid); struct { const char* type; const char* dev; } devtypes[] = { {"ip6gretap", "ip6gretap0"}, {"bridge", "bridge0"}, {"vcan", "vcan0"}, {"bond", "bond0"}, {"team", "team0"}, {"dummy", "dummy0"}, {"nlmon", "nlmon0"}, {"caif", "caif0"}, {"batadv", "batadv0"}, {"vxcan", "vxcan1"}, {"netdevsim", netdevsim}, {"veth", 0}, }; const char* devmasters[] = {"bridge", "bond", "team"}; struct { const char* name; int macsize; bool noipv6; } devices[] = { {"lo", ETH_ALEN}, {"sit0", 0}, {"bridge0", ETH_ALEN}, {"vcan0", 0, true}, {"tunl0", 0}, {"gre0", 0}, {"gretap0", ETH_ALEN}, {"ip_vti0", 0}, {"ip6_vti0", 0}, {"ip6tnl0", 0}, {"ip6gre0", 0}, {"ip6gretap0", ETH_ALEN}, {"erspan0", ETH_ALEN}, {"bond0", ETH_ALEN}, {"veth0", ETH_ALEN}, {"veth1", ETH_ALEN}, {"team0", ETH_ALEN}, {"veth0_to_bridge", ETH_ALEN}, {"veth1_to_bridge", ETH_ALEN}, {"veth0_to_bond", ETH_ALEN}, {"veth1_to_bond", ETH_ALEN}, {"veth0_to_team", ETH_ALEN}, {"veth1_to_team", ETH_ALEN}, {"veth0_to_hsr", ETH_ALEN}, {"veth1_to_hsr", ETH_ALEN}, {"hsr0", 0}, {"dummy0", ETH_ALEN}, {"nlmon0", 0}, {"vxcan0", 0, true}, {"vxcan1", 0, true}, {"caif0", ETH_ALEN}, {"batadv0", ETH_ALEN}, {netdevsim, ETH_ALEN}, }; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) netlink_add_device(&nlmsg, sock, devtypes[i].type, devtypes[i].dev); for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) { char master[32], slave0[32], veth0[32], slave1[32], veth1[32]; sprintf(slave0, "%s_slave_0", devmasters[i]); sprintf(veth0, "veth0_to_%s", devmasters[i]); netlink_add_veth(&nlmsg, sock, slave0, veth0); sprintf(slave1, "%s_slave_1", devmasters[i]); sprintf(veth1, "veth1_to_%s", devmasters[i]); netlink_add_veth(&nlmsg, sock, slave1, veth1); sprintf(master, "%s0", devmasters[i]); netlink_device_change(&nlmsg, sock, slave0, false, master, 0, 0, NULL); netlink_device_change(&nlmsg, sock, slave1, false, master, 0, 0, NULL); } netlink_device_change(&nlmsg, sock, "bridge_slave_0", true, 0, 0, 0, NULL); netlink_device_change(&nlmsg, sock, "bridge_slave_1", true, 0, 0, 0, NULL); netlink_add_veth(&nlmsg, sock, "hsr_slave_0", "veth0_to_hsr"); netlink_add_veth(&nlmsg, sock, "hsr_slave_1", "veth1_to_hsr"); netlink_add_hsr(&nlmsg, sock, "hsr0", "hsr_slave_0", "hsr_slave_1"); netlink_device_change(&nlmsg, sock, "hsr_slave_0", true, 0, 0, 0, NULL); netlink_device_change(&nlmsg, sock, "hsr_slave_1", true, 0, 0, 0, NULL); netdevsim_add((int)procid, 4); for (i = 0; i < sizeof(devices) / (sizeof(devices[0])); i++) { char addr[32]; sprintf(addr, DEV_IPV4, i + 10); netlink_add_addr4(&nlmsg, sock, devices[i].name, addr); if (!devices[i].noipv6) { sprintf(addr, DEV_IPV6, i + 10); netlink_add_addr6(&nlmsg, sock, devices[i].name, addr); } uint64_t macaddr = DEV_MAC + ((i + 10ull) << 40); netlink_device_change(&nlmsg, sock, devices[i].name, true, 0, &macaddr, devices[i].macsize, NULL); } close(sock); } static void initialize_netdevices_init(void) { int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); struct { const char* type; int macsize; bool noipv6; bool noup; } devtypes[] = { {"nr", 7, true}, {"rose", 5, true, true}, }; unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) { char dev[32], addr[32]; sprintf(dev, "%s%d", devtypes[i].type, (int)procid); sprintf(addr, "172.30.%d.%d", i, (int)procid + 1); netlink_add_addr4(&nlmsg, sock, dev, addr); if (!devtypes[i].noipv6) { sprintf(addr, "fe88::%02x:%02x", i, (int)procid + 1); netlink_add_addr6(&nlmsg, sock, dev, addr); } int macsize = devtypes[i].macsize; uint64_t macaddr = 0xbbbbbb + ((unsigned long long)i << (8 * (macsize - 2))) + (procid << (8 * (macsize - 1))); netlink_device_change(&nlmsg, sock, dev, !devtypes[i].noup, 0, &macaddr, macsize, NULL); } close(sock); } static int read_tun(char* data, int size) { if (tunfd < 0) return -1; int rv = read(tunfd, data, size); if (rv < 0) { if (errno == EAGAIN) return -1; if (errno == EBADFD) return -1; exit(1); } return rv; } static void flush_tun() { char data[1000]; while (read_tun(&data[0], sizeof(data)) != -1) { } } #define MAX_FDS 30 #define XT_TABLE_SIZE 1536 #define XT_MAX_ENTRIES 10 struct xt_counters { uint64_t pcnt, bcnt; }; struct ipt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_entries; unsigned int size; }; struct ipt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct ipt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct ipt_table_desc { const char* name; struct ipt_getinfo info; struct ipt_replace replace; }; static struct ipt_table_desc ipv4_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; static struct ipt_table_desc ipv6_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; #define IPT_BASE_CTL 64 #define IPT_SO_SET_REPLACE (IPT_BASE_CTL) #define IPT_SO_GET_INFO (IPT_BASE_CTL) #define IPT_SO_GET_ENTRIES (IPT_BASE_CTL + 1) struct arpt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_entries; unsigned int size; }; struct arpt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct arpt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct arpt_table_desc { const char* name; struct arpt_getinfo info; struct arpt_replace replace; }; static struct arpt_table_desc arpt_tables[] = { {.name = "filter"}, }; #define ARPT_BASE_CTL 96 #define ARPT_SO_SET_REPLACE (ARPT_BASE_CTL) #define ARPT_SO_GET_INFO (ARPT_BASE_CTL) #define ARPT_SO_GET_ENTRIES (ARPT_BASE_CTL + 1) static void checkpoint_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { struct ipt_get_entries entries; socklen_t optlen; int fd, i; fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); optlen = sizeof(table->info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->info.size > sizeof(table->replace.entrytable)) exit(1); if (table->info.num_entries > XT_MAX_ENTRIES) exit(1); memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { struct xt_counters counters[XT_MAX_ENTRIES]; struct ipt_get_entries entries; struct ipt_getinfo info; socklen_t optlen; int fd, i; fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; if (table->info.valid_hooks == 0) continue; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); optlen = sizeof(info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &info, &optlen)) exit(1); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, level, IPT_SO_SET_REPLACE, &table->replace, optlen)) exit(1); } close(fd); } static void checkpoint_arptables(void) { struct arpt_get_entries entries; socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); optlen = sizeof(table->info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->info.size > sizeof(table->replace.entrytable)) exit(1); if (table->info.num_entries > XT_MAX_ENTRIES) exit(1); memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_arptables() { struct xt_counters counters[XT_MAX_ENTRIES]; struct arpt_get_entries entries; struct arpt_getinfo info; socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; if (table->info.valid_hooks == 0) continue; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); optlen = sizeof(info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &info, &optlen)) exit(1); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } else { } table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, SOL_IP, ARPT_SO_SET_REPLACE, &table->replace, optlen)) exit(1); } close(fd); } #define NF_BR_NUMHOOKS 6 #define EBT_TABLE_MAXNAMELEN 32 #define EBT_CHAIN_MAXNAMELEN 32 #define EBT_BASE_CTL 128 #define EBT_SO_SET_ENTRIES (EBT_BASE_CTL) #define EBT_SO_GET_INFO (EBT_BASE_CTL) #define EBT_SO_GET_ENTRIES (EBT_SO_GET_INFO + 1) #define EBT_SO_GET_INIT_INFO (EBT_SO_GET_ENTRIES + 1) #define EBT_SO_GET_INIT_ENTRIES (EBT_SO_GET_INIT_INFO + 1) struct ebt_replace { char name[EBT_TABLE_MAXNAMELEN]; unsigned int valid_hooks; unsigned int nentries; unsigned int entries_size; struct ebt_entries* hook_entry[NF_BR_NUMHOOKS]; unsigned int num_counters; struct ebt_counter* counters; char* entries; }; struct ebt_entries { unsigned int distinguisher; char name[EBT_CHAIN_MAXNAMELEN]; unsigned int counter_offset; int policy; unsigned int nentries; char data[0] __attribute__((aligned(__alignof__(struct ebt_replace)))); }; struct ebt_table_desc { const char* name; struct ebt_replace replace; char entrytable[XT_TABLE_SIZE]; }; static struct ebt_table_desc ebt_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "broute"}, }; static void checkpoint_ebtables(void) { socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; strcpy(table->replace.name, table->name); optlen = sizeof(table->replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_INFO, &table->replace, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->replace.entries_size > sizeof(table->entrytable)) exit(1); table->replace.num_counters = 0; table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_ENTRIES, &table->replace, &optlen)) exit(1); } close(fd); } static void reset_ebtables() { struct ebt_replace replace; char entrytable[XT_TABLE_SIZE]; socklen_t optlen; unsigned i, j, h; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; if (table->replace.valid_hooks == 0) continue; memset(&replace, 0, sizeof(replace)); strcpy(replace.name, table->name); optlen = sizeof(replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INFO, &replace, &optlen)) exit(1); replace.num_counters = 0; table->replace.entries = 0; for (h = 0; h < NF_BR_NUMHOOKS; h++) table->replace.hook_entry[h] = 0; if (memcmp(&table->replace, &replace, sizeof(table->replace)) == 0) { memset(&entrytable, 0, sizeof(entrytable)); replace.entries = entrytable; optlen = sizeof(replace) + replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_ENTRIES, &replace, &optlen)) exit(1); if (memcmp(table->entrytable, entrytable, replace.entries_size) == 0) continue; } for (j = 0, h = 0; h < NF_BR_NUMHOOKS; h++) { if (table->replace.valid_hooks & (1 << h)) { table->replace.hook_entry[h] = (struct ebt_entries*)table->entrytable + j; j++; } } table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (setsockopt(fd, SOL_IP, EBT_SO_SET_ENTRIES, &table->replace, optlen)) exit(1); } close(fd); } static void checkpoint_net_namespace(void) { checkpoint_ebtables(); checkpoint_arptables(); checkpoint_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); checkpoint_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void reset_net_namespace(void) { reset_ebtables(); reset_arptables(); reset_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); reset_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void setup_cgroups() { if (mkdir("/syzcgroup", 0777)) { } if (mkdir("/syzcgroup/unified", 0777)) { } if (mount("none", "/syzcgroup/unified", "cgroup2", 0, NULL)) { } if (chmod("/syzcgroup/unified", 0777)) { } write_file("/syzcgroup/unified/cgroup.subtree_control", "+cpu +memory +io +pids +rdma"); if (mkdir("/syzcgroup/cpu", 0777)) { } if (mount("none", "/syzcgroup/cpu", "cgroup", 0, "cpuset,cpuacct,perf_event,hugetlb")) { } write_file("/syzcgroup/cpu/cgroup.clone_children", "1"); if (chmod("/syzcgroup/cpu", 0777)) { } if (mkdir("/syzcgroup/net", 0777)) { } if (mount("none", "/syzcgroup/net", "cgroup", 0, "net_cls,net_prio,devices,freezer")) { } if (chmod("/syzcgroup/net", 0777)) { } } static void setup_cgroups_loop() { int pid = getpid(); char file[128]; char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/pids.max", cgroupdir); write_file(file, "32"); snprintf(file, sizeof(file), "%s/memory.low", cgroupdir); write_file(file, "%d", 298 << 20); snprintf(file, sizeof(file), "%s/memory.high", cgroupdir); write_file(file, "%d", 299 << 20); snprintf(file, sizeof(file), "%s/memory.max", cgroupdir); write_file(file, "%d", 300 << 20); snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); } static void setup_cgroups_test() { char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); if (symlink(cgroupdir, "./cgroup")) { } snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid); if (symlink(cgroupdir, "./cgroup.cpu")) { } snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid); if (symlink(cgroupdir, "./cgroup.net")) { } } static void setup_common() { if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) { } setup_cgroups(); } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); int netns = open("/proc/self/ns/net", O_RDONLY); if (netns == -1) exit(1); if (dup2(netns, kInitNetNsFd) < 0) exit(1); close(netns); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = (200 << 20); setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 32 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 136 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); rlim.rlim_cur = rlim.rlim_max = 256; setrlimit(RLIMIT_NOFILE, &rlim); if (unshare(CLONE_NEWNS)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(0x02000000)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } typedef struct { const char* name; const char* value; } sysctl_t; static const sysctl_t sysctls[] = { {"/proc/sys/kernel/shmmax", "16777216"}, {"/proc/sys/kernel/shmall", "536870912"}, {"/proc/sys/kernel/shmmni", "1024"}, {"/proc/sys/kernel/msgmax", "8192"}, {"/proc/sys/kernel/msgmni", "1024"}, {"/proc/sys/kernel/msgmnb", "1024"}, {"/proc/sys/kernel/sem", "1024 1048576 500 1024"}, }; unsigned i; for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++) write_file(sysctls[i].name, sysctls[i].value); } int wait_for_loop(int pid) { if (pid < 0) exit(1); int status = 0; while (waitpid(-1, &status, __WALL) != pid) { } return WEXITSTATUS(status); } static void drop_caps(void) { struct __user_cap_header_struct cap_hdr = {}; struct __user_cap_data_struct cap_data[2] = {}; cap_hdr.version = _LINUX_CAPABILITY_VERSION_3; cap_hdr.pid = getpid(); if (syscall(SYS_capget, &cap_hdr, &cap_data)) exit(1); const int drop = (1 << CAP_SYS_PTRACE) | (1 << CAP_SYS_NICE); cap_data[0].effective &= ~drop; cap_data[0].permitted &= ~drop; cap_data[0].inheritable &= ~drop; if (syscall(SYS_capset, &cap_hdr, &cap_data)) exit(1); } static int do_sandbox_none(void) { if (unshare(CLONE_NEWPID)) { } int pid = fork(); if (pid != 0) return wait_for_loop(pid); setup_common(); sandbox_common(); drop_caps(); initialize_netdevices_init(); if (unshare(CLONE_NEWNET)) { } initialize_devlink_pci(); initialize_tun(); initialize_netdevices(); loop(); exit(1); } #define FS_IOC_SETFLAGS _IOW('f', 2, long) static void remove_dir(const char* dir) { DIR* dp; struct dirent* ep; int iter = 0; retry: while (umount2(dir, MNT_DETACH) == 0) { } dp = opendir(dir); if (dp == NULL) { if (errno == EMFILE) { exit(1); } exit(1); } while ((ep = readdir(dp))) { if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) continue; char filename[FILENAME_MAX]; snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name); while (umount2(filename, MNT_DETACH) == 0) { } struct stat st; if (lstat(filename, &st)) exit(1); if (S_ISDIR(st.st_mode)) { remove_dir(filename); continue; } int i; for (i = 0;; i++) { if (unlink(filename) == 0) break; if (errno == EPERM) { int fd = open(filename, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) { } close(fd); continue; } } if (errno == EROFS) { break; } if (errno != EBUSY || i > 100) exit(1); if (umount2(filename, MNT_DETACH)) exit(1); } } closedir(dp); int i; for (i = 0;; i++) { if (rmdir(dir) == 0) break; if (i < 100) { if (errno == EPERM) { int fd = open(dir, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) { } close(fd); continue; } } if (errno == EROFS) { break; } if (errno == EBUSY) { if (umount2(dir, MNT_DETACH)) exit(1); continue; } if (errno == ENOTEMPTY) { if (iter < 100) { iter++; goto retry; } } } exit(1); } } static void kill_and_wait(int pid, int* status) { kill(-pid, SIGKILL); kill(pid, SIGKILL); int i; for (i = 0; i < 100; i++) { if (waitpid(-1, status, WNOHANG | __WALL) == pid) return; usleep(1000); } DIR* dir = opendir("/sys/fs/fuse/connections"); if (dir) { for (;;) { struct dirent* ent = readdir(dir); if (!ent) break; if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; char abort[300]; snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort", ent->d_name); int fd = open(abort, O_WRONLY); if (fd == -1) { continue; } if (write(fd, abort, 1) < 0) { } close(fd); } closedir(dir); } else { } while (waitpid(-1, status, __WALL) != pid) { } } static void setup_loop() { setup_cgroups_loop(); checkpoint_net_namespace(); } static void reset_loop() { reset_net_namespace(); } static void setup_test() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setup_cgroups_test(); write_file("/proc/self/oom_score_adj", "1000"); flush_tun(); } static void close_fds() { int fd; for (fd = 3; fd < MAX_FDS; fd++) close(fd); } static void setup_binfmt_misc() { if (mount(0, "/proc/sys/fs/binfmt_misc", "binfmt_misc", 0, 0)) { } write_file("/proc/sys/fs/binfmt_misc/register", ":syz0:M:0:\x01::./file0:"); write_file("/proc/sys/fs/binfmt_misc/register", ":syz1:M:1:\x02::./file0:POC"); } struct thread_t { int created, call; event_t ready, done; }; static struct thread_t threads[16]; static void execute_call(int call); static int running; static void* thr(void* arg) { struct thread_t* th = (struct thread_t*)arg; for (;;) { event_wait(&th->ready); event_reset(&th->ready); execute_call(th->call); __atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED); event_set(&th->done); } return 0; } static void execute_one(void) { int i, call, thread; int collide = 0; again: for (call = 0; call < 9; call++) { for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0])); thread++) { struct thread_t* th = &threads[thread]; if (!th->created) { th->created = 1; event_init(&th->ready); event_init(&th->done); event_set(&th->done); thread_start(thr, th); } if (!event_isset(&th->done)) continue; event_reset(&th->done); th->call = call; __atomic_fetch_add(&running, 1, __ATOMIC_RELAXED); event_set(&th->ready); if (collide && (call % 2) == 0) break; event_timedwait(&th->done, 45); break; } } for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++) sleep_ms(1); close_fds(); if (!collide) { collide = 1; goto again; } } static void execute_one(void); #define WAIT_FLAGS __WALL static void loop(void) { setup_loop(); int iter; for (iter = 0;; iter++) { char cwdbuf[32]; sprintf(cwdbuf, "./%d", iter); if (mkdir(cwdbuf, 0777)) exit(1); reset_loop(); int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { if (chdir(cwdbuf)) exit(1); setup_test(); execute_one(); exit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid) break; sleep_ms(1); if (current_time_ms() - start < 5 * 1000) continue; kill_and_wait(pid, &status); break; } remove_dir(cwdbuf); } } #ifndef __NR_execveat #define __NR_execveat 322 #endif #ifndef __NR_memfd_create #define __NR_memfd_create 319 #endif uint64_t r[2] = {0xffffffffffffffff, 0x0}; void execute_call(int call) { intptr_t res; switch (call) { case 0: syscall(__NR_clone, 0x200ul, 0ul, 0x9999999999999999ul, 0ul, -1ul); break; case 1: NONFAILING(memcpy( (void*)0x20000540, "\227&\211\\\320\347\312\026ZO\224:\341\001\345`iq@Nse;\250Fpj\016\004!" "\325\305YBz\224\257\023\351\322\017\302G\206Xe\361/" "V\214vS\246K&u\235X\314\r\022\021\231\347\316\256A\270-E\241\370\344~" "IS\301\004\3678\361\'\337v\220\274\321\332\210j\026\353>" "\214\241\003\363\257\375\364&a?\312G\n\345j\233}" "\306G\206\262\336Y\027yX " "$\374U\235\200dX\314\253\204\321\001_\177\364tW." "\201\n\363\v\215\022pa\221\233\214xd\006\247k\n\206\303\266\2210\362L" "\360\257\341jd\332\037\213Vrd\244\2634\374Uj\032d:#\226\371\323\034]" "ImZlU\".\030)" "\317\032m\325\340\333\334\327\216\340\243\202\354\233\373\311\201\234" "\334\267\017\335\323\327\276\211\1773\035\034@\216u\205\316s\211\225&" "3FX\261\257\246\226\242\023\037-\b\317", 249)); res = syscall(__NR_memfd_create, 0x20000540ul, 0ul); if (res != -1) r[0] = res; break; case 2: syscall(__NR_fcntl, r[0], 8ul, 0); break; case 3: NONFAILING(memcpy((void*)0x20000500, "\000", 1)); syscall(__NR_execveat, r[0], 0x20000500ul, 0ul, 0ul, 0x1000ul); break; case 4: NONFAILING(*(uint64_t*)0x20000040 = 0); NONFAILING(*(uint32_t*)0x20000048 = 0x12); NONFAILING(*(uint32_t*)0x2000004c = 0); NONFAILING(*(uint32_t*)0x20000050 = 0); syscall(__NR_timer_create, 0ul, 0x20000040ul, 0x200000c0ul); break; case 5: NONFAILING(*(uint64_t*)0x20000340 = 0); NONFAILING(*(uint64_t*)0x20000348 = 8); NONFAILING(*(uint64_t*)0x20000350 = 0); NONFAILING(*(uint64_t*)0x20000358 = 9); syscall(__NR_timer_settime, 0, 0ul, 0x20000340ul, 0ul); break; case 6: res = syscall(__NR_gettid); if (res != -1) r[1] = res; break; case 7: NONFAILING(*(uint8_t*)0x20000640 = 0x7f); NONFAILING(*(uint8_t*)0x20000641 = 0x45); NONFAILING(*(uint8_t*)0x20000642 = 0x4c); NONFAILING(*(uint8_t*)0x20000643 = 0x46); NONFAILING(*(uint8_t*)0x20000644 = 0x4c); NONFAILING(*(uint8_t*)0x20000645 = 6); NONFAILING(*(uint8_t*)0x20000646 = 2); NONFAILING(*(uint8_t*)0x20000647 = 0x1f); NONFAILING(*(uint64_t*)0x20000648 = 8); NONFAILING(*(uint16_t*)0x20000650 = 2); NONFAILING(*(uint16_t*)0x20000652 = 0x3e); NONFAILING(*(uint32_t*)0x20000654 = 5); NONFAILING(*(uint64_t*)0x20000658 = 0x324); NONFAILING(*(uint64_t*)0x20000660 = 0x40); NONFAILING(*(uint64_t*)0x20000668 = 0x10f); NONFAILING(*(uint32_t*)0x20000670 = 0x64bfb127); NONFAILING(*(uint16_t*)0x20000674 = 0x80); NONFAILING(*(uint16_t*)0x20000676 = 0x38); NONFAILING(*(uint16_t*)0x20000678 = 2); NONFAILING(*(uint16_t*)0x2000067a = 5); NONFAILING(*(uint16_t*)0x2000067c = 8); NONFAILING(*(uint16_t*)0x2000067e = 2); NONFAILING(*(uint32_t*)0x20000680 = 0x60000005); NONFAILING(*(uint32_t*)0x20000684 = 8); NONFAILING(*(uint64_t*)0x20000688 = 5); NONFAILING(*(uint64_t*)0x20000690 = 0x400); NONFAILING(*(uint64_t*)0x20000698 = 1); NONFAILING(*(uint64_t*)0x200006a0 = 5); NONFAILING(*(uint64_t*)0x200006a8 = 0x1000); NONFAILING(*(uint64_t*)0x200006b0 = 0x4a); NONFAILING(*(uint64_t*)0x200006b8 = 0); NONFAILING(*(uint64_t*)0x200006c0 = 0); NONFAILING(*(uint64_t*)0x200006c8 = 0); NONFAILING(*(uint64_t*)0x200006d0 = 0); NONFAILING(*(uint64_t*)0x200006d8 = 0); NONFAILING(*(uint64_t*)0x200006e0 = 0); NONFAILING(*(uint64_t*)0x200006e8 = 0); NONFAILING(*(uint64_t*)0x200006f0 = 0); NONFAILING(*(uint64_t*)0x200006f8 = 0); NONFAILING(*(uint64_t*)0x20000700 = 0); NONFAILING(*(uint64_t*)0x20000708 = 0); NONFAILING(*(uint64_t*)0x20000710 = 0); NONFAILING(*(uint64_t*)0x20000718 = 0); NONFAILING(*(uint64_t*)0x20000720 = 0); NONFAILING(*(uint64_t*)0x20000728 = 0); NONFAILING(*(uint64_t*)0x20000730 = 0); NONFAILING(*(uint64_t*)0x20000738 = 0); NONFAILING(*(uint64_t*)0x20000740 = 0); NONFAILING(*(uint64_t*)0x20000748 = 0); NONFAILING(*(uint64_t*)0x20000750 = 0); NONFAILING(*(uint64_t*)0x20000758 = 0); NONFAILING(*(uint64_t*)0x20000760 = 0); NONFAILING(*(uint64_t*)0x20000768 = 0); NONFAILING(*(uint64_t*)0x20000770 = 0); NONFAILING(*(uint64_t*)0x20000778 = 0); NONFAILING(*(uint64_t*)0x20000780 = 0); NONFAILING(*(uint64_t*)0x20000788 = 0); NONFAILING(*(uint64_t*)0x20000790 = 0); NONFAILING(*(uint64_t*)0x20000798 = 0); NONFAILING(*(uint64_t*)0x200007a0 = 0); NONFAILING(*(uint64_t*)0x200007a8 = 0); NONFAILING(*(uint64_t*)0x200007b0 = 0); syscall(__NR_write, r[0], 0x20000640ul, 0x178ul); break; case 8: syscall(__NR_tkill, r[1], 0x16); break; } } int main(void) { syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 3ul, 0x32ul, -1, 0); setup_binfmt_misc(); install_segv_handler(); use_temporary_dir(); do_sandbox_none(); return 0; }
the_stack_data/86074093.c
long sum(long arr[], long len) { long res = 0; for(long i = 0; i < len; i++) { res+=arr[i]; } return(res); } long sumR(long arr[], long len) { if(len <= 0) return(0); return(arr[len - 1] + sumR(arr, len - 1)); }
the_stack_data/175143912.c
/* The C Book * Example 1.1 page 3 & 4 */ #include <stdio.h> /* Tell the compiler that we intend * to use a fucntion called show_message. * It has no arguments and returns no value. * This is the "declaration". */ void show_message(void); /* Another function, but this includes the body of * the function. This is a "definition". */ int main(void) { int count; count = 0; while (count < 10){ show_message(); count = count + 1; } return 0; } /* The body of the simple function. * This is now a "definition". */ void show_message(void) { printf("Hello from tcb\n"); }
the_stack_data/67324757.c
#include <fcntl.h> #include <unistd.h> // Add imports for perror below #include <stdio.h> #include <errno.h> void main() { int fd; fd = open("file1", O_RDONLY); if (fd < 0) // output error // Output: "open: No such file or directory" perror("open"); // ... close(fd); }
the_stack_data/165769369.c
/* * Utilize the Merge Sort algorithm on an array of characters * Put in unsorted array and get back a sorted one * * Author: Ansor Kasimov * Created: March 27 2022 * Copyright (c) 2022 Ansor Kasimov */ #include <stdio.h> void mergeSort(char[], int, int); void merge(char[], int, int, int); int main() { char set[10] = {'g', 'a', 'c', 'h', 'e', 'j', 'i', 'b', 'f', 'd'}; printf("Unsorted array of characters:\n"); int i; for (i = 0; i < 10; ++i) printf("%c ", set[i]); printf("\n"); mergeSort(set, 0, 9); printf("Sorted array of characters after Merge Sort:\n"); for (i = 0; i < 10; ++i) printf("%c ", set[i]); printf("\n"); return 0; } void mergeSort(char arr[], int l, int r) { if (l < r) { int m = (l + r) / 2; mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); } } void merge(char arr[], int l, int m, int r) { int i, j, k; int lArrSize = m - l + 1; int rArrSize = r - m; int lArr[lArrSize], rArr[rArrSize]; for (i = 0; i < lArrSize; ++i) lArr[i] = arr[l + i]; for (j = 0; j < rArrSize; ++j) rArr[j] = arr[m + j + 1]; i = j = 0; k = l; while (i < lArrSize && j < rArrSize) { if (lArr[i] <= rArr[j]) arr[k++] = lArr[i++]; else arr[k++] = rArr[j++]; } while (i < lArrSize) arr[k++] = lArr[i++]; while (j < rArrSize) arr[k++] = rArr[j++]; }
the_stack_data/524151.c
/* Test we do warn about initializing variable with self in the initialization. */ /* { dg-do compile } */ /* { dg-options "-O -Wuninitialized" } */ int f() { int i = i + 1; /* { dg-warning "i" "uninitialized variable warning" } */ return i; }
the_stack_data/959392.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2013-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 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 <unistd.h> int v; int main() { /* Don't let the test case run forever. */ alarm (60); for (;;) ; }
the_stack_data/869665.c
/* * Although used for coercion on more typesafe languages, unions in C have a * more profound role: They help create both a way to destructure data, and * create sort-of polymorphism. */ #include <stdio.h> #include <stdint.h> /* Coercion example: */ union float_internal_rep { int i32; float f32; }; /* Polymorphism example: */ enum typ { INT64, DOUBLE, CHAR8 }; struct poly { enum typ poly_t; union { long i64; double f64; char c8[8]; }; }; /* Destructure example */ union data { struct { unsigned byte0:8; unsigned byte1:8; unsigned byte2:8; unsigned byte3:8; }; unsigned bytes; }; void polymorphic(struct poly *); /* SEE below */ int main() { /* coercion */ /* XXX: UB: * C standard only defines accessing the most recently modified union * field; accessing any other field is undefined but compiler writers agree * that it's best used for coercion. */ union float_internal_rep f; f.f32 = 1.2345f; printf("0x%X\n", f.i32); /* XXX: UB */ /* polymorphism */ struct poly t; t.poly_t = INT64; t.i64 = 42L; polymorphic(&t); t.poly_t = CHAR8; t.c8[0] = 'H'; t.c8[1] = 'E'; t.c8[2] = 'L'; t.c8[3] = 'L'; t.c8[4] = 'O'; polymorphic(&t); /* deconstruction */ union data word; word.bytes = 0xdeadbeef; word.byte2 = 0xcc; printf("0x%X\n", word.bytes); return 0; } void polymorphic(struct poly *S) { switch (S->poly_t) { case INT64: printf("long! %ld\n", S->i64); break; case DOUBLE: printf("double! %lf\n", S->f64); break; case CHAR8: puts("char!"); puts(S->c8); break; } }
the_stack_data/1044819.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strclr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: msiivone <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/23 01:08:45 by msiivone #+# #+# */ /* Updated: 2019/10/26 15:09:02 by msiivone ### ########.fr */ /* */ /* ************************************************************************** */ void ft_strclr(char *s) { int x; x = 0; while (s[x] != '\0') { s[x] = '\0'; x++; } }
the_stack_data/74308.c
#include <stdio.h> int main () { int i, a, b, aux; scanf("%d\n%d", &a, &b); if(a > b) { aux = a; a = b; b = aux; } for(i = a ; i <= b ; ++i) if((i % 2) != 0) printf("%d\n", i); return 0; }
the_stack_data/161080184.c
/*- * SPDX-License-Identifier: Zlib * * Copyright (c) 2009-2018 Rink Springer <[email protected]> * For conditions of distribution and use, see LICENSE file */ #include <wchar.h> #include <stdlib.h> long wcstol(const wchar_t* ptr, wchar_t** endptr, int base) { size_t len = wcstombs(NULL, ptr, 0); if (len == (size_t)-1) { if (endptr != NULL) *endptr = (wchar_t*)ptr; return 0.0; } char* buf = malloc(len + 1); if (buf == NULL) { if (endptr != NULL) *endptr = (wchar_t*)ptr; return 0.0; } wcstombs(buf, ptr, len); char* endp; long l = strtol(buf, &endp, base); if (endptr != NULL) { *endptr = (wchar_t*)ptr + (endp - buf); } free(buf); return l; }
the_stack_data/947156.c
/*Exercise 4 - Functions Implement the three functions minimum(), maximum() and multiply() below the main() function. Do not change the code given in the main() function when you are implementing your solution.*/ #include <stdio.h> int minimum(int no1,int no2); int maximum(int no1, int no2); int multiply(int no1, int no2); int main() { int no1, no2; printf("Enter a value for no 1 : "); scanf("%d", &no1); printf("Enter a value for no 2 : "); scanf("%d", &no2); printf("%d ", minimum(no1, no2)); printf("%d ", maximum(no1, no2)); printf("%d ", multiply(no1, no2)); return 0; } int minimum(int no1, int no2) { if(no1<no2) { return no1; } else { return no2; } } int maximum(int no1 ,int no2) { if(no1>no2) { return no1; } else { return no2; } } int multiply(int no1,int no2) { int x=no1*no2; return x; }
the_stack_data/132835.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); extern unsigned int __VERIFIER_nondet_uint(void); void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; } int main() { unsigned int n = __VERIFIER_nondet_uint(); unsigned int x=n, y=0, z; while(x>0) { x--; y++; } z = y; while(z>0) { x++; z--; } while(y>0) { y--; z++; } __VERIFIER_assert(z==n); return 0; }
the_stack_data/156393444.c
#include<stdio.h> int main() { char s1[20]; int i,j,c=0,v=0; printf("Enter the String:"); gets(s1); for(i=0;s1[i]!='\0';i++) { if(s1[i]=='a'||s1[i]=='e'||s1[i]=='i'||s1[i]=='o'||s1[i]=='u') c++; else v++; } printf("Vowels Count: %d\n",c); printf("Consonants Count: %d",v); return 0; }
the_stack_data/889323.c
/* * Copyright (c) 2017, 2018, Oracle and/or its affiliates. * * 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. Neither the name of the copyright holder 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 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. */ int main() { unsigned int a[10] = { 0xFFFFFFFF }; __builtin_memset(&a, 0, sizeof(a)); for (int i = 0; i < 10; i++) { if (a[i] != 0) { return 1; } } return 0; }
the_stack_data/218894294.c
int x = 0; int main() { while(1) break; while(1) { if (x == 5) { break; } x = x + 1; continue; } for (;;) { if (x == 10) { break; } x = x + 1; continue; } do { if (x == 15) { break; } x = x + 1; continue; } while(1); return x - 15; }
the_stack_data/75080.c
int main() { int a[100]; int i, j; /* Test with incomplete for: */ i = 2; for(; i <= 50; i++) for(j = 2; j < 100; j *= 2) a[j] = 2; for(i = 2; i <= 50;) { i++; for(j = 2; j < 100; j *= 2) a[j] = 2; } for(i = 2; ; i++) for(j = 2; j < 100; j *= 2) a[j] = 2; /* Unreachable from here... */ for(;;) for(j = 2; j < 100; j *= 2) a[j] = 2; return 0; }
the_stack_data/533624.c
/* * Simple Xlib application drawing a box in a window. * gcc input.c -o output -lX11 */ #include <X11/Xlib.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { Display *display; Window window; XEvent event; char *msg = "Hello, World!"; int s; /* open connection with the server */ display = XOpenDisplay(NULL); if (display == NULL) { fprintf(stderr, "Cannot open display\n"); exit(1); } s = DefaultScreen(display); /* create window */ window = XCreateSimpleWindow(display, RootWindow(display, s), 10, 10, 200, 200, 1, BlackPixel(display, s), WhitePixel(display, s)); /* select kind of events we are interested in */ XSelectInput(display, window, ExposureMask | KeyPressMask); /* map (show) the window */ XMapWindow(display, window); /* event loop */ while (1) { XNextEvent(display, &event); /* draw or redraw the window */ if (event.type == Expose) { XFillRectangle(display, window, DefaultGC(display, s), 20, 20, 10, 10); XDrawString(display, window, DefaultGC(display, s), 50, 50, msg, strlen(msg)); } /* exit on key press */ if (event.type == KeyPress) break; } /* close connection to server */ XCloseDisplay(display); return 0; }
the_stack_data/75136834.c
#include "stdio.h" #include "stdlib.h" char *integer_to_bin(long integer){ int bit_num = sizeof(long)*8; char *buffer= (char *)malloc(bit_num+1); if (buffer==NULL) { return "malloc error"; } buffer[bit_num]='\0'; for (int i = 0; i < bit_num; ++i) { buffer[i]= integer<<i>>(bit_num-1); buffer[i]= buffer[i]==0?'0':'1'; } return buffer; } char *integer_to_hex(long integer){ int bit_num=sizeof(long)*8/4; char *buffer=(char *)malloc(bit_num+3); buffer[0]='0'; buffer[1]='x'; buffer[bit_num+2]='\0'; char *tmp=&buffer[2]; for (int i = 0; i < bit_num; i++) { tmp[i]= integer<<(i*4)>>(bit_num*4-4); tmp[i]= tmp[i]>=0?tmp[i]:tmp[i]+16; tmp[i]= tmp[i]<10?(tmp[i]+48):(tmp[i]-10+'A'); } return buffer; } /* A 65 0 48 */ int main(){ printf("b(11) = %s\n", integer_to_bin(11)); printf("b(1023) = %s\n",integer_to_bin(1023) ); printf("b(23564) = %s\n",integer_to_bin(23564) ); printf("h(11) = %s\n", integer_to_hex(11)); printf("h(1023) = %s\n",integer_to_hex(1023) ); printf("h(23564) = %s\n",integer_to_hex(23564) ); printf("b(11) = %x\n", 11); printf("b(1023) = %x\n",1023 ); printf("b(23564) = %x\n",23564 ); return 0; }
the_stack_data/33835.c
/* DataToC output of file <gpencil_fx_rim_prepare_frag_glsl> */ extern int datatoc_gpencil_fx_rim_prepare_frag_glsl_size; extern char datatoc_gpencil_fx_rim_prepare_frag_glsl[]; int datatoc_gpencil_fx_rim_prepare_frag_glsl_size = 1805; char datatoc_gpencil_fx_rim_prepare_frag_glsl[] = { 117,110,105,102,111,114,109, 32,109, 97,116, 52, 32, 80,114,111,106,101, 99,116,105,111,110, 77, 97,116,114,105,120, 59, 13, 10,117,110,105,102,111,114,109, 32,109, 97,116, 52, 32, 86,105,101,119, 77, 97,116,114,105,120, 59, 13, 10, 13, 10, 47, 42, 32, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 32, 42, 47, 13, 10, 47, 42, 32, 99,114,101, 97,116,101, 32,114,105,109, 32, 97,110,100, 32,109, 97,115,107, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 42, 47, 13, 10, 47, 42, 32, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 32, 42, 47, 13, 10,117,110,105,102,111,114,109, 32,115, 97,109,112,108,101,114, 50, 68, 32,115,116,114,111,107,101, 67,111,108,111,114, 59, 13, 10,117,110,105,102,111,114,109, 32,115, 97,109,112,108,101,114, 50, 68, 32,115,116,114,111,107,101, 68,101,112,116,104, 59, 13, 10,117,110,105,102,111,114,109, 32,118,101, 99, 50, 32, 86,105,101,119,112,111,114,116, 59, 13, 10, 13, 10,117,110,105,102,111,114,109, 32,105,110,116, 32,111,102,102,115,101,116, 91, 50, 93, 59, 13, 10,117,110,105,102,111,114,109, 32,118,101, 99, 51, 32,114,105,109, 95, 99,111,108,111,114, 59, 13, 10,117,110,105,102,111,114,109, 32,118,101, 99, 51, 32,109, 97,115,107, 95, 99,111,108,111,114, 59, 13, 10, 13, 10,117,110,105,102,111,114,109, 32,118,101, 99, 51, 32,108,111, 99, 59, 13, 10,117,110,105,102,111,114,109, 32,102,108,111, 97,116, 32,112,105,120,115,105,122,101, 59, 32, 32, 32, 47, 42, 32,114,118, 51,100, 45, 62,112,105,120,115,105,122,101, 32, 42, 47, 13, 10,117,110,105,102,111,114,109, 32,102,108,111, 97,116, 32,112,105,120,102, 97, 99,116,111,114, 59, 13, 10, 13, 10,102,108,111, 97,116, 32,100,101,102, 97,117,108,116,112,105,120,115,105,122,101, 32, 61, 32,112,105,120,115,105,122,101, 32, 42, 32, 40, 49, 48, 48, 48, 46, 48, 32, 47, 32,112,105,120,102, 97, 99,116,111,114, 41, 59, 13, 10,118,101, 99, 50, 32,110,111,102,102,115,101,116, 32, 61, 32,118,101, 99, 50, 40,111,102,102,115,101,116, 91, 48, 93, 44, 32,111,102,102,115,101,116, 91, 49, 93, 41, 59, 13, 10, 13, 10,111,117,116, 32,118,101, 99, 52, 32, 70,114, 97,103, 67,111,108,111,114, 59, 13, 10, 13, 10,118,111,105,100, 32,109, 97,105,110, 40, 41, 13, 10,123, 13, 10, 9,118,101, 99, 50, 32,117,118, 32, 61, 32,118,101, 99, 50, 40,103,108, 95, 70,114, 97,103, 67,111,111,114,100, 46,120,121, 41, 59, 13, 10, 9,118,101, 99, 52, 32,110,108,111, 99, 32, 61, 32, 80,114,111,106,101, 99,116,105,111,110, 77, 97,116,114,105,120, 32, 42, 32, 86,105,101,119, 77, 97,116,114,105,120, 32, 42, 32,118,101, 99, 52, 40,108,111, 99, 46,120,121,122, 44, 32, 49, 46, 48, 41, 59, 13, 10, 13, 10, 9,102,108,111, 97,116, 32,100,120, 32, 61, 32, 40, 80,114,111,106,101, 99,116,105,111,110, 77, 97,116,114,105,120, 91, 51, 93, 91, 51, 93, 32, 61, 61, 32, 48, 46, 48, 41, 32, 63, 32, 40,110,111,102,102,115,101,116, 91, 48, 93, 32, 47, 32, 40,110,108,111, 99, 46,122, 32, 42, 32,100,101,102, 97,117,108,116,112,105,120,115,105,122,101, 41, 41, 32, 58, 32, 40,110,111,102,102,115,101,116, 91, 48, 93, 32, 47, 32,100,101,102, 97,117,108,116,112,105,120,115,105,122,101, 41, 59, 13, 10, 9,102,108,111, 97,116, 32,100,121, 32, 61, 32, 40, 80,114,111,106,101, 99,116,105,111,110, 77, 97,116,114,105,120, 91, 51, 93, 91, 51, 93, 32, 61, 61, 32, 48, 46, 48, 41, 32, 63, 32, 40,110,111,102,102,115,101,116, 91, 49, 93, 32, 47, 32, 40,110,108,111, 99, 46,122, 32, 42, 32,100,101,102, 97,117,108,116,112,105,120,115,105,122,101, 41, 41, 32, 58, 32, 40,110,111,102,102,115,101,116, 91, 49, 93, 32, 47, 32,100,101,102, 97,117,108,116,112,105,120,115,105,122,101, 41, 59, 13, 10, 13, 10, 9,102,108,111, 97,116, 32,115,116,114,111,107,101, 95,100,101,112,116,104, 32, 61, 32,116,101,120,101,108, 70,101,116, 99,104, 40,115,116,114,111,107,101, 68,101,112,116,104, 44, 32,105,118,101, 99, 50, 40,117,118, 46,120,121, 41, 44, 32, 48, 41, 46,114, 59, 13, 10, 9,118,101, 99, 52, 32,115,114, 99, 95,112,105,120,101,108, 61, 32,116,101,120,101,108, 70,101,116, 99,104, 40,115,116,114,111,107,101, 67,111,108,111,114, 44, 32,105,118,101, 99, 50, 40,117,118, 46,120,121, 41, 44, 32, 48, 41, 59, 13, 10, 9,118,101, 99, 52, 32,111,102,102,115,101,116, 95,112,105,120,101,108, 61, 32,116,101,120,101,108, 70,101,116, 99,104, 40,115,116,114,111,107,101, 67,111,108,111,114, 44, 32,105,118,101, 99, 50, 40,117,118, 46,120, 32, 45, 32,100,120, 44, 32,117,118, 46,121, 32, 45, 32,100,121, 41, 44, 32, 48, 41, 59, 13, 10, 9,118,101, 99, 52, 32,111,117,116, 99,111,108,111,114, 59, 13, 10, 13, 10, 9, 47, 42, 32,105,115, 32,116,114, 97,110,115,112, 97,114,101,110,116, 32, 42, 47, 13, 10, 9,105,102, 32, 40,115,114, 99, 95,112,105,120,101,108, 46, 97, 32, 61, 61, 32, 48, 46, 48,102, 41, 32,123, 13, 10, 9, 9,100,105,115, 99, 97,114,100, 59, 13, 10, 9,125, 13, 10, 9, 47, 42, 32, 99,104,101, 99,107, 32,105,110,115,105,100,101, 32,118,105,101,119,112,111,114,116, 32, 42, 47, 13, 10, 9,101,108,115,101, 32,105,102, 32, 40, 40,117,118, 46,120, 32, 45, 32,100,120, 32, 60, 32, 48, 41, 32,124,124, 32, 40,117,118, 46,120, 32, 45, 32,100,120, 32, 62, 32, 86,105,101,119,112,111,114,116, 91, 48, 93, 41, 41, 32,123, 13, 10, 9, 9,100,105,115, 99, 97,114,100, 59, 13, 10, 9,125, 13, 10, 9,101,108,115,101, 32,105,102, 32, 40, 40,117,118, 46,121, 32, 45, 32,100,121, 32, 60, 32, 48, 41, 32,124,124, 32, 40,117,118, 46,121, 32, 45, 32,100,121, 32, 62, 32, 86,105,101,119,112,111,114,116, 91, 49, 93, 41, 41, 32,123, 13, 10, 9, 9,100,105,115, 99, 97,114,100, 59, 13, 10, 9,125, 13, 10, 9, 47, 42, 32,112,105,120,101,108, 32,105,115, 32,101,113,117, 97,108, 32,116,111, 32,109, 97,115,107, 32, 99,111,108,111,114, 44, 32,107,101,101,112, 32, 42, 47, 13, 10, 9,101,108,115,101, 32,105,102, 32, 40,115,114, 99, 95,112,105,120,101,108, 46,114,103, 98, 32, 61, 61, 32,109, 97,115,107, 95, 99,111,108,111,114, 46,114,103, 98, 41, 32,123, 13, 10, 9, 9,100,105,115, 99, 97,114,100, 59, 13, 10, 9,125, 13, 10, 9,101,108,115,101, 32,123, 13, 10, 9, 9,105,102, 32, 40, 40,115,114, 99, 95,112,105,120,101,108, 46, 97, 32, 62, 32, 48, 41, 32, 38, 38, 32, 40,111,102,102,115,101,116, 95,112,105,120,101,108, 46, 97, 32, 62, 32, 48, 41, 41, 32,123, 13, 10, 9, 9, 9,100,105,115, 99, 97,114,100, 59, 13, 10, 9, 9,125, 13, 10, 9, 9,101,108,115,101, 32,123, 13, 10, 9, 9, 9,111,117,116, 99,111,108,111,114, 32, 61, 32,118,101, 99, 52, 40,114,105,109, 95, 99,111,108,111,114, 44, 32, 49, 46, 48, 41, 59, 13, 10, 9, 9,125, 13, 10, 9,125, 13, 10, 13, 10, 9,103,108, 95, 70,114, 97,103, 68,101,112,116,104, 32, 61, 32,115,116,114,111,107,101, 95,100,101,112,116,104, 59, 13, 10, 9, 70,114, 97,103, 67,111,108,111,114, 32, 61, 32,111,117,116, 99,111,108,111,114, 59, 13, 10,125, 13, 10,0 };
the_stack_data/29824625.c
/* * Copyright 2016 The Emscripten Authors. All rights reserved. * Emscripten is available under two separate licenses, the MIT license and the * University of Illinois/NCSA Open Source License. Both these licenses can be * found in the LICENSE file. */ #include <stdio.h> void do_call(void (*puts)(const char *), const char *str); void do_print(const char *str) { if (!str) do_call(NULL, "delusion"); if ((long)str == -1) do_print(str + 10); puts("===="); puts(str); puts("===="); } void do_call(void (*puts)(const char *), const char *str) { if (!str) do_print("confusion"); if ((long)str == -1) do_call(NULL, str - 10); (*puts)(str); } int main(int argc, char **argv) { for (int i = 0; i < argc; i++) { do_call(i != 10 ? do_print : NULL, i != 15 ? "waka waka" : NULL); } return 0; }
the_stack_data/3370.c
/* origin: FreeBSD /usr/src/lib/msun/src/e_log10.c */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunSoft, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ /* * Return the base 10 logarithm of x. See log.c for most comments. * * Reduce x to 2^k (1+f) and calculate r = log(1+f) - f + f*f/2 * as in log.c, then combine and scale in extra precision: * log10(x) = (f - f*f/2 + r)/log(10) + k*log10(2) */ #include <math.h> #include <stdint.h> static const double ivln10hi = 4.34294481878168880939e-01, /* 0x3fdbcb7b, 0x15200000 */ ivln10lo = 2.50829467116452752298e-11, /* 0x3dbb9438, 0xca9aadd5 */ log10_2hi = 3.01029995663611771306e-01, /* 0x3FD34413, 0x509F6000 */ log10_2lo = 3.69423907715893078616e-13, /* 0x3D59FEF3, 0x11F12B36 */ Lg1 = 6.666666666666735130e-01, /* 3FE55555 55555593 */ Lg2 = 3.999999999940941908e-01, /* 3FD99999 9997FA04 */ Lg3 = 2.857142874366239149e-01, /* 3FD24924 94229359 */ Lg4 = 2.222219843214978396e-01, /* 3FCC71C5 1D8E78AF */ Lg5 = 1.818357216161805012e-01, /* 3FC74664 96CB03DE */ Lg6 = 1.531383769920937332e-01, /* 3FC39A09 D078C69F */ Lg7 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ double my_log10(double x) { union {double f; uint64_t i;} u = {x}; double_t hfsq,f,s,z,R,w,t1,t2,dk,y,hi,lo,val_hi,val_lo; uint32_t hx; int k; hx = u.i>>32; k = 0; if (hx < 0x00100000 || hx>>31) { if (u.i<<1 == 0) return -1/(x*x); /* log(+-0)=-inf */ if (hx>>31) return (x-x)/0.0; /* log(-#) = NaN */ /* subnormal number, scale x up */ k -= 54; x *= 0x1p54; u.f = x; hx = u.i>>32; } else if (hx >= 0x7ff00000) { return x; } else if (hx == 0x3ff00000 && u.i<<32 == 0) return 0; /* reduce x into [sqrt(2)/2, sqrt(2)] */ hx += 0x3ff00000 - 0x3fe6a09e; k += (int)(hx>>20) - 0x3ff; hx = (hx&0x000fffff) + 0x3fe6a09e; u.i = (uint64_t)hx<<32 | (u.i&0xffffffff); x = u.f; f = x - 1.0; hfsq = 0.5*f*f; s = f/(2.0+f); z = s*s; w = z*z; t1 = w*(Lg2+w*(Lg4+w*Lg6)); t2 = z*(Lg1+w*(Lg3+w*(Lg5+w*Lg7))); R = t2 + t1; /* See log2.c for details. */ /* hi+lo = f - hfsq + s*(hfsq+R) ~ log(1+f) */ hi = f - hfsq; u.f = hi; u.i &= (uint64_t)-1<<32; hi = u.f; lo = f - hi - hfsq + s*(hfsq+R); /* val_hi+val_lo ~ log10(1+f) + k*log10(2) */ val_hi = hi*ivln10hi; dk = k; y = dk*log10_2hi; val_lo = dk*log10_2lo + (lo+hi)*ivln10lo + lo*ivln10hi; /* * Extra precision in for adding y is not strictly needed * since there is no very large cancellation near x = sqrt(2) or * x = 1/sqrt(2), but we do it anyway since it costs little on CPUs * with some parallelism and it reduces the error for many args. */ w = y + val_hi; val_lo += (y - w) + val_hi; val_hi = w; return val_lo + val_hi; }
the_stack_data/223063.c
#include <stdio.h> //income threshold #define INC_SING 17850.0 #define INC_HEAD 23900.0 #define INC_MARR 29750.0 #define INC_SEPA 14875.0 //tax rates #define TAX_BASE .15 #define TAX_EXCE .28 #define QUIT '5' int main(void) { char cat; float income, tax; float inc_base = 0; //get user tax income chathegory printf("Select from options: \n1) Single \n2) Head of HS \n3) Married \n4) Divorced \n5) Quit\n"); while ((cat = getchar()) != QUIT) { switch (cat) { case '1': inc_base = INC_SING; break; case '2': inc_base = INC_HEAD; break; case '3': inc_base = INC_MARR; break; case '4': inc_base = INC_SEPA; break; case '\n': break; default : printf("Select from 1-4, or enter 5 to quit\n"); } if (inc_base) { //get taxable income printf("Enter taxable income (q to go back): "); while (scanf("%f", &income)) { if (income < inc_base) tax = income*TAX_BASE; else tax = inc_base*TAX_BASE + (income - inc_base)*TAX_EXCE; printf("Tax due: $%.2f\n", tax); //reset inc_base to get out from loop inc_base = 0; printf("Enter taxable income (q to go back): "); } } } return 0; }
the_stack_data/104827432.c
/* { dg-do compile } */ extern volatile int g_4[1][4]; extern int g_7; void modify(int *); void func_2() { int l_46 = 4; if (g_7) modify(&l_46); else { int i; for (i = 0; i != 5; i += 1) { volatile int *vp = &g_4[0][l_46]; *vp = 0; } } }
the_stack_data/684381.c
// Test strict_string_checks option in strncmp function // RUN: %clang_asan %s -o %t // RUN: %env_asan_opts=strict_string_checks=false %run %t a 2>&1 // RUN: %env_asan_opts=strict_string_checks=true %run %t a 2>&1 // RUN: not %run %t b 2>&1 | FileCheck %s // RUN: not %run %t c 2>&1 | FileCheck %s // RUN: not %run %t d 2>&1 | FileCheck %s // RUN: not %run %t e 2>&1 | FileCheck %s // RUN: not %run %t f 2>&1 | FileCheck %s // RUN: not %run %t g 2>&1 | FileCheck %s // RUN: %env_asan_opts=strict_string_checks=false %run %t h 2>&1 // RUN: %env_asan_opts=strict_string_checks=true not %run %t h 2>&1 | FileCheck %s // RUN: %env_asan_opts=strict_string_checks=false %run %t i 2>&1 // RUN: %env_asan_opts=strict_string_checks=true not %run %t i 2>&1 | FileCheck %s // XFAIL: windows-msvc #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> int main(int argc, char **argv) { assert(argc >= 2); enum { size = 100 }; char fill = 'o'; char s1[size]; char s2[size]; memset(s1, fill, size); memset(s2, fill, size); switch (argv[1][0]) { case 'a': s1[size - 1] = 'z'; s2[size - 1] = 'x'; for (int i = 0; i <= size; ++i) assert((strncasecmp(s1, s2, i) == 0) == (i < size)); s1[size - 1] = '\0'; s2[size - 1] = '\0'; assert(strncasecmp(s1, s2, 2*size) == 0); break; case 'b': return strncasecmp(s1-1, s2, 1); case 'c': return strncasecmp(s1, s2-1, 1); case 'd': return strncasecmp(s1+size, s2, 1); case 'e': return strncasecmp(s1, s2+size, 1); case 'f': return strncasecmp(s1+1, s2, size); case 'g': return strncasecmp(s1, s2+1, size); case 'h': s1[size - 1] = '\0'; assert(strncasecmp(s1, s2, 2*size) != 0); break; case 'i': s2[size - 1] = '\0'; assert(strncasecmp(s1, s2, 2*size) != 0); break; // CHECK: {{.*}}ERROR: AddressSanitizer: stack-buffer-{{ov|und}}erflow on address } return 0; }
the_stack_data/50137753.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define max(a,b) ((a)>(b)?(a):(b)) typedef struct list_node *list; typedef struct list_node{ int value; list next; }listnode; list listinit(int *A,int n){ int i; list head=(list)malloc(sizeof(listnode)); if(NULL==head) return NULL; head->value=-1; head->next=NULL; list initlist=(list)malloc(sizeof(listnode)*n); if(NULL==initlist) return NULL; for(i=0;i<n;i++){ initlist[i].value=A[i]; initlist[i].next=NULL; } list tail; tail=head; for(i=0;i<n;i++){ tail->next=&initlist[i]; tail=&initlist[i]; } printf("List created !\n"); tail=head; while(NULL!=tail->next){ printf("%d ",tail->next->value); tail=tail->next; } printf("\n"); return head->next; } void freelist(list head){ list tmp; tmp=head; if(NULL==head) return ; if(NULL!=head->next){ tmp=head; head=head->next; free(tmp); } free(head); return ; } int addtwo(int *A,int n,int *B,int m){ list lista,listb,head,tail; int nr,cnt=0; lista=listinit(A,n); listb=listinit(B,m); head=(list)malloc(sizeof(listnode)); if(NULL==head) return 0; head->value=-1; head->next=NULL; tail=head; for(;NULL!=lista||NULL!=listb;lista=(lista==NULL?NULL:lista->next),listb=(listb==NULL?NULL:listb->next)){ nr=((NULL==lista?0:lista->value)+(NULL==listb?0:listb->value)+cnt); cnt=nr/10; nr%=10; list newnode=(list)malloc(sizeof(listnode)); if(NULL==newnode) return 0; newnode->value=nr; newnode->next=NULL; tail->next=newnode; tail=newnode; } if(cnt){ list newnode=(list)malloc(sizeof(listnode)); if(NULL==newnode) return 0; newnode->value=1; newnode->next=NULL; tail->next=newnode; } tail=head; while(NULL!=tail->next){ printf("%d ",tail->next->value); tail=tail->next; } printf("\n"); freelist(head); return 0; } int main(int argc,int **argv){ int n,m,i,j; int *A,*B; printf("Please input the 1st number:\n"); scanf("%d",&n); A=(int*)malloc(sizeof(int)*n); if(NULL==A) return 0; printf("Please input the A:\n"); for(i=0;i<n;i++){ scanf("%d",&A[i]); } printf("Please input the 2st number:\n"); scanf("%d",&m); B=(int*)malloc(sizeof(int)*m); if(NULL==B) return 0; printf("Please input the B:\n"); for(i=0;i<m;i++){ scanf("%d",&B[i]); } addtwo(A,n,B,m); free(A); free(B); A=NULL; B=NULL; return 0; }
the_stack_data/115765693.c
/** * This module is used to detect copy relocated ModuleInfos (located in .bss section). * * Copyright: Copyright Martin Nowak 2014-. * License: $(WEB www.boost.org/LICENSE_1_0.txt, Boost License 1.0). * Authors: Martin Nowak * Source: $(DRUNTIMESRC src/rt/_sections_linux.d) */ /* These symbols are defined in the linker script and bracket the * .bss, .lbss, .lrodata and .ldata sections. */ #if defined(__linux__) || defined(__FreeBSD__) // Need to use weak linkage to workaround a bug in ld.bfd (Bugzilla 13025). extern int __attribute__((weak)) __bss_start, _end; __attribute__ ((visibility ("hidden"))) void* rt_get_bss_start(); __attribute__ ((visibility ("hidden"))) void* rt_get_end(); void* rt_get_bss_start() { return (void*)&__bss_start; } void* rt_get_end() { return (void*)&_end; } #endif
the_stack_data/107952142.c
#include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node* next; }Node; typedef struct stack { Node* top; }Stack; Stack* criaPilha(); // aloca memória Node* insertInTop(Node* l, int v); // auxiliar para adicionar no topo void pushStack(Stack* p, int v); // chama a função InsereNoInicio e adiciona no topo int pop(int v); int stackNull(); Stack* createStack() { Stack* createAllocStack = (Stack*) malloc(sizeof(Stack)); createAllocStack->top = NULL; return createAllocStack; } void pushStack(Stack* p, int v){ p->top = insertInTop(p->top, v); } Node* insertInTop(Node* l, int v){ Node* newNode = (Node*) malloc(sizeof(Node)); newNode->data = v; newNode->next = l; return newNode; } int stackNull(Stack* newStack){ if (newStack->top == NULL) { return 1; } else { return 0; } } void displayStack(){ Node* p; Stack* stk; p = stk->top; while (p != NULL) { printf("%d -> ", p->data); p = p->next; } } void MaiorStack(Stack* stack){ Node* node = stack->top; Node* maior = (Node*) malloc(sizeof(Node)); maior->data = node->data; while (node != NULL) { if (node->data > maior->data) { maior->data = node->data; } node = node->next; } printf("\nMaior da Stack: < %d > ", maior->data); } int main() { Stack* newStack; Node* newNode; newStack = createStack(); pushStack(newStack, 1); pushStack(newStack, 55); pushStack(newStack, 2); pushStack(newStack, 3); displayStack(newStack); MaiorStack(newStack); return 0; }
the_stack_data/102806.c
/* * Copyright (c) 2019 Opticks Team. All Rights Reserved. * * This file is part of Opticks * (see https://bitbucket.org/simoncblyth/opticks). * * 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> #include<math.h> struct node{ int value; struct node *left; struct node *right; }; typedef struct node Node; #define STACK_SIZE 10 typedef struct stack{ int top; Node *items[STACK_SIZE]; }stack; void push(stack *ms, Node *item){ if(ms->top < STACK_SIZE-1){ ms->items[++(ms->top)] = item; } else { printf("Stack is full\n"); } } Node * pop (stack *ms){ if(ms->top > -1 ){ return ms->items[(ms->top)--]; } else{ printf("Stack is empty\n"); } return NULL ; } Node * peek(stack ms){ if(ms.top < 0){ printf("Stack empty\n"); return 0; } return ms.items[ms.top]; } int isEmpty(stack ms){ if(ms.top < 0) return 1; else return 0; } void postorderTraversalWithoutStack(Node *root){ stack ms; ms.top = -1; if(!root) return ; Node *currentNode = NULL ; push(&ms,root); Node *prev = NULL; while(!isEmpty(ms)){ currentNode = peek(ms); /* case 1. We are moving down the tree. */ if(!prev || prev->left == currentNode || prev->right == currentNode){ if(currentNode->left) push(&ms,currentNode->left); else if(currentNode->right) push(&ms,currentNode->right); else { /* If node is leaf node */ printf("%d ", currentNode->value); pop(&ms); } } /* case 2. We are moving up the tree from left child */ if(currentNode->left == prev){ if(currentNode->right) push(&ms,currentNode->right); else { printf("%d ", currentNode->value); pop(&ms); } } /* case 3. We are moving up the tree from right child */ if(currentNode->right == prev){ printf("%d ", currentNode->value); pop(&ms); } prev = currentNode; } } void postorder (Node * root){ if ( !root ) return; postorder(root->left); postorder(root->right); printf("%d ", root->value ); } Node * createNode(int value){ Node * newNode = (Node *)malloc(sizeof(Node)); newNode->value = value; newNode->right= NULL; newNode->left = NULL; return newNode; } Node * addNode(Node *node, int value){ if(!node){ return createNode(value); } else{ if (node->value > value){ node->left = addNode(node->left, value); } else{ node->right = addNode(node->right, value); } } return node; } /* Driver program for the function written above */ int main(){ Node *root = NULL; //Creating a binary tree root = addNode(root,30); root = addNode(root,20); root = addNode(root,15); root = addNode(root,25); root = addNode(root,40); root = addNode(root,37); root = addNode(root,45); postorder(root); printf("\n"); postorderTraversalWithoutStack(root); return 0; }
the_stack_data/643181.c
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <sys/types.h> #include <poll.h> #define MAX 1024 int send_int(int num, int fd) { int32_t conv = htonl(num); char *data = (char*)&conv; int left = sizeof(conv); int rc; do { rc = write(fd, data, left); if (rc < 0) { return -1; } else { data += rc; left -= rc; } } while (left > 0); return 0; } int main() { struct sockaddr_in address; socklen_t address_size; int sfd=socket(AF_INET,SOCK_STREAM,0); if(sfd==0) { printf("creation of socket failed\n"); } address.sin_family=AF_INET; address.sin_port=htons(8080); address.sin_addr.s_addr=inet_addr("127.0.0.1"); if(connect(sfd,(struct sockaddr *)&address,sizeof(address))<0) { printf("connection failed\n"); return 0; } printf("Requesting Service from server 1\n"); send_int(1,sfd); char buff[MAX]; int size; for(;;) { size = recv(sfd, buff, MAX, 0); // if(strncmp(buff,"Com",3)== 0) break; printf("%s",buff); break; } close(sfd); return 0; }
the_stack_data/92325271.c
/* { dg-do compile } */ /* { dg-options "-fopenmp -fshow-column" } */ void baz (int); void foo (int j, int k) { int i; /* Valid loops. */ #pragma omp for for (i = 0; i < 10; i++) baz (i); #pragma omp for for (i = j; i <= 10; i+=4) baz (i); #pragma omp for for (i = j; i > 0; i = i - 1) baz (j); #pragma omp for for (i = j; i >= k; i--) baz (i); /* Malformed parallel loops. */ #pragma omp for i = 0; /* { dg-error "3:for statement expected" } */ for ( ; i < 10; ) { baz (i); i++; } #pragma omp for for (i = 0; ; i--) /* { dg-error "missing controlling predicate" } */ { if (i >= 10) break; /* { dg-error "break" } */ baz (i); } #pragma omp for for (i = 0; i < 10 && j > 4; i-=3) /* { dg-error "15:invalid controlling predicate" } */ baz (i); #pragma omp for for (i = 0; i < 10; i-=3, j+=2) /* { dg-error "27:invalid increment expression" } */ baz (i); }
the_stack_data/232956675.c
/* * M/L for minimOS simulator * (c) 2015-2021 Carlos J. Santisteban * last modified 20151009-0901 */ #include <stdio.h> /* * type definitions */ typedef unsigned char byt; /* * global variables */ // memory array byt ram[49152]; // 48 kiB byt a, x, y, s, p; // 65c02 registers // zp pointers byt* endsp = &ram[2]; // *** used_z for mOS works as data stack pointer byt* a_reg = &ram[3]; byt* x_reg = &ram[4]; byt* y_reg = &ram[5]; byt* p_reg = &ram[6]; byt* s_reg = &ram[7]; byt* io_dev = &ram[8]; // *** mOS only byt* com_dev = &ram[8]; // *** for load/save byt* curs = &ram[9]; // current buffer pointer, really needed? byt* mode = &ram[10]; // choose between hex (0) and ASCII ($FF) mode byt* temp = &ram[11]; // hex-to-bin conversion byt* count = &ram[12]; // number of lines (minus 1) to dump, or bytes to load/save byt* ptr = &ram[14]; // converted values and addresses *** needs to be in zeropage *** byt* last_f = &ram[16]; // last fetch address *** should be in zeropage, may be merged with others byt* last_p = &ram[18]; // last store address *** should be in zeropage, may be merged with others byt* last_d = &ram[20]; // last dump address *** should be in zeropage, may be merged with others byt* inbuff = &ram[22]; // 40-byte buffer for keyboard input byt* stack = &ram[62]; // internal stack /* * function prototypes */ byt mos_init(void); /* * main function */ int main(void){ *endsp = 225; // full minimOS standard value // printf("%c\n", *endsp); /* * Code starts here */ *a_reg = a; // store registers *x_reg = x; *y_reg = y; *p_reg = p; // done via PHP:PLA:STA *s_reg = s; // done via TSX:STX if (mos_init()) return 0; // initialize specific stuff, abort in case of any problems x = inbuff-com_dev+1; // bytes to be cleared return 0; } /* * function definitions */ byt mos_init(void){ a = *endsp; // really gets number of available ZP bytes if (a<67) { // below minimum? printf("\n***FATAL ERROR: not enough zeropage space***\n"); return 1; // abort } // set SIGTERM handler... // open device window... *io_dev = 232; // default device placeholder return 0; // all OK }
the_stack_data/90761485.c
/* uninit.c is part of the libf2c source (libf2c.zip) in f2c available at * http://www.netlib.org/f2c/. It is used by Rad to fill memory locations * with NaN values so that uninitialized accesses of those memory locations * will throw IEEE exceptions. The libf2c source includes a Notice file * giving copyright and permission to use. The contents of this file * appear immediately below. */ /**************************************************************** Copyright 1990 - 1997 by AT&T, Lucent Technologies and Bellcore. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the names of AT&T, Bell Laboratories, Lucent or Bellcore or any of their entities not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. AT&T, Lucent and Bellcore disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall AT&T, Lucent or Bellcore be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. ****************************************************************/ #include <stdio.h> #include <string.h> /*#include "arith.h"*/ #define TYSHORT 2 #define TYLONG 3 #define TYREAL 4 #define TYDREAL 5 #define TYCOMPLEX 6 #define TYDCOMPLEX 7 #define TYINT1 11 #define TYQUAD 14 #ifndef Long #define Long long #endif #ifdef __mips #define RNAN 0xffc00000 #define DNAN0 0xfff80000 #define DNAN1 0 #endif #ifdef _PA_RISC1_1 #define RNAN 0xffc00000 #define DNAN0 0xfff80000 #define DNAN1 0 #endif #ifndef RNAN #define RNAN 0xff800001 #ifdef IEEE_MC68k #define DNAN0 0xfff00000 #define DNAN1 1 #else #define DNAN0 1 #define DNAN1 0xfff00000 #endif #endif /*RNAN*/ #ifdef KR_headers #define Void /*void*/ #define FA7UL (unsigned Long) 0xfa7a7a7aL #else #define Void void #define FA7UL 0xfa7a7a7aUL #endif #ifdef __cplusplus extern "C" { #endif static void ieee0(Void); static unsigned Long rnan = RNAN, dnan0 = DNAN0, dnan1 = DNAN1; double _0 = 0.; void #ifdef KR_headers _uninit_f2c(x, type, len) void *x; int type; long len; #else _uninit_f2c(void *x, int type, long len) #endif { static int first = 1; unsigned Long *lx, *lxe; if (first) { first = 0; ieee0(); } if (len == 1) switch(type) { case TYINT1: *(char*)x = 'Z'; return; case TYSHORT: *(unsigned short*)x = 0xfa7a; break; case TYLONG: *(unsigned Long*)x = FA7UL; return; case TYQUAD: case TYCOMPLEX: case TYDCOMPLEX: break; case TYREAL: *(unsigned Long*)x = rnan; return; case TYDREAL: lx = (unsigned Long*)x; lx[0] = dnan0; lx[1] = dnan1; return; default: printf("Surprise type %d in _uninit_f2c\n", type); } switch(type) { case TYINT1: memset(x, 'Z', len); break; case TYSHORT: *(unsigned short*)x = 0xfa7a; break; case TYQUAD: len *= 2; /* no break */ case TYLONG: lx = (unsigned Long*)x; lxe = lx + len; while(lx < lxe) *lx++ = FA7UL; break; case TYCOMPLEX: len *= 2; /* no break */ case TYREAL: lx = (unsigned Long*)x; lxe = lx + len; while(lx < lxe) *lx++ = rnan; break; case TYDCOMPLEX: len *= 2; /* no break */ case TYDREAL: lx = (unsigned Long*)x; for(lxe = lx + 2*len; lx < lxe; lx += 2) { lx[0] = dnan0; lx[1] = dnan1; } } } #ifdef __cplusplus } #endif #ifndef MSpc #ifdef MSDOS #define MSpc #else #ifdef _WIN32 #define MSpc #endif #endif #endif #ifdef MSpc #define IEEE0_done #include "float.h" #include "signal.h" static void ieee0(Void) { #ifndef __alpha _control87(EM_DENORMAL | EM_UNDERFLOW | EM_INEXACT, MCW_EM); #endif /* With MS VC++, compiling and linking with -Zi will permit */ /* clicking to invoke the MS C++ debugger, which will show */ /* the point of error -- provided SIGFPE is SIG_DFL. */ signal(SIGFPE, SIG_DFL); } #endif /* MSpc */ #ifdef __mips /* must link with -lfpe */ #define IEEE0_done /* code from Eric Grosse */ #include <stdlib.h> #include <stdio.h> #include "/usr/include/sigfpe.h" /* full pathname for lcc -N */ #include "/usr/include/sys/fpu.h" static void #ifdef KR_headers ieeeuserhand(exception, val) unsigned exception[5]; int val[2]; #else ieeeuserhand(unsigned exception[5], int val[2]) #endif { fflush(stdout); fprintf(stderr,"ieee0() aborting because of "); if(exception[0]==_OVERFL) fprintf(stderr,"overflow\n"); else if(exception[0]==_UNDERFL) fprintf(stderr,"underflow\n"); else if(exception[0]==_DIVZERO) fprintf(stderr,"divide by 0\n"); else if(exception[0]==_INVALID) fprintf(stderr,"invalid operation\n"); else fprintf(stderr,"\tunknown reason\n"); fflush(stderr); abort(); } static void #ifdef KR_headers ieeeuserhand2(j) unsigned int **j; #else ieeeuserhand2(unsigned int **j) #endif { fprintf(stderr,"ieee0() aborting because of confusion\n"); abort(); } static void ieee0(Void) { int i; for(i=1; i<=4; i++){ sigfpe_[i].count = 1000; sigfpe_[i].trace = 1; sigfpe_[i].repls = _USER_DETERMINED; } sigfpe_[1].repls = _ZERO; /* underflow */ handle_sigfpes( _ON, _EN_UNDERFL|_EN_OVERFL|_EN_DIVZERO|_EN_INVALID, ieeeuserhand,_ABORT_ON_ERROR,ieeeuserhand2); } #endif /* mips */ #ifdef __linux__ #define IEEE0_done #include "fpu_control.h" #ifdef __alpha__ #ifndef USE_setfpucw #define __setfpucw(x) __fpu_control = (x) #endif #endif #ifndef _FPU_SETCW #undef Can_use__setfpucw #define Can_use__setfpucw #endif static void ieee0(Void) { #if (defined(__mc68000__) || defined(__mc68020__) || defined(mc68020) || defined (__mc68k__)) /* Reported 20010705 by Alan Bain <[email protected]> */ /* Note that IEEE 754 IOP (illegal operation) */ /* = Signaling NAN (SNAN) + operation error (OPERR). */ #ifdef Can_use__setfpucw /* Has __setfpucw gone missing from S.u.S.E. 6.3? */ __setfpucw(_FPU_IEEE + _FPU_DOUBLE + _FPU_MASK_OPERR + _FPU_MASK_DZ + _FPU_MASK_SNAN+_FPU_MASK_OVFL); #else __fpu_control = _FPU_IEEE + _FPU_DOUBLE + _FPU_MASK_OPERR + _FPU_MASK_DZ + _FPU_MASK_SNAN+_FPU_MASK_OVFL; _FPU_SETCW(__fpu_control); #endif #elif (defined(__powerpc__)||defined(_ARCH_PPC)||defined(_ARCH_PWR)) /* !__mc68k__ */ /* Reported 20011109 by Alan Bain <[email protected]> */ #ifdef Can_use__setfpucw /* The following is NOT a mistake -- the author of the fpu_control.h for the PPC has erroneously defined IEEE mode to turn on exceptions other than Inexact! Start from default then and turn on only the ones which we want*/ __setfpucw(_FPU_DEFAULT + _FPU_MASK_IM+_FPU_MASK_OM+_FPU_MASK_UM); #else /* PPC && !Can_use__setfpucw */ __fpu_control = _FPU_DEFAULT +_FPU_MASK_OM+_FPU_MASK_IM+_FPU_MASK_UM; _FPU_SETCW(__fpu_control); #endif /*Can_use__setfpucw*/ #else /* !(mc68000||powerpc) */ #ifdef _FPU_IEEE #ifndef _FPU_EXTENDED /* e.g., ARM processor under Linux */ #define _FPU_EXTENDED 0 #endif #ifndef _FPU_DOUBLE #define _FPU_DOUBLE 0 #endif #ifdef Can_use__setfpucw /* Has __setfpucw gone missing from S.u.S.E. 6.3? */ __setfpucw(_FPU_IEEE - _FPU_EXTENDED + _FPU_DOUBLE - _FPU_MASK_IM - _FPU_MASK_ZM - _FPU_MASK_OM); #else __fpu_control = _FPU_IEEE - _FPU_EXTENDED + _FPU_DOUBLE - _FPU_MASK_IM - _FPU_MASK_ZM - _FPU_MASK_OM; _FPU_SETCW(__fpu_control); #endif #else /* !_FPU_IEEE */ fprintf(stderr, "\n%s\n%s\n%s\n%s\n", "WARNING: _uninit_f2c in libf2c does not know how", "to enable trapping on this system, so f2c's -trapuv", "option will not detect uninitialized variables unless", "you can enable trapping manually."); fflush(stderr); #endif /* _FPU_IEEE */ #endif /* __mc68k__ */ } #endif /* __linux__ */ #ifdef __alpha #ifndef IEEE0_done #define IEEE0_done #include <machine/fpu.h> static void ieee0(Void) { ieee_set_fp_control(IEEE_TRAP_ENABLE_INV); } #endif /*IEEE0_done*/ #endif /*__alpha*/ #ifdef __hpux #define IEEE0_done #define _INCLUDE_HPUX_SOURCE #include <math.h> #ifndef FP_X_INV #include <fenv.h> #define fpsetmask fesettrapenable #define FP_X_INV FE_INVALID #endif static void ieee0(Void) { fpsetmask(FP_X_INV); } #endif /*__hpux*/ #ifdef _AIX #define IEEE0_done #include <fptrap.h> static void ieee0(Void) { fp_enable(TRP_INVALID); fp_trap(FP_TRAP_SYNC); } #endif /*_AIX*/ #ifdef __sun #define IEEE0_done #include <ieeefp.h> static void ieee0(Void) { fpsetmask(FP_X_INV); } #endif /*__sparc*/ #ifndef IEEE0_done static void ieee0(Void) {} #endif
the_stack_data/100141213.c
/* Copyright (c) 2017 Dennis Wölfing * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* utils/init.c * System initialization. */ #include <err.h> #include <stdbool.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> int main(int argc, char* argv[]) { (void) argc; (void) argv; if (getpid() != 1) errx(1, "PID is not 1"); if (setenv("PATH", "/bin:/sbin", 1) < 0) err(1, "setenv"); pid_t childPid = fork(); if (childPid < 0) err(1, "fork"); if (childPid == 0) { const char* args[] = { "sh", NULL }; execv("/bin/sh", (char**) args); err(1, "execv: '/bin/sh'"); } while (true) { // Wait for any orphaned processes. int status; wait(&status); } }
the_stack_data/126702905.c
/* vi: set sw=4 ts=4: */ /* * posix_fadvise64() for ARM uClibc * http://www.opengroup.org/onlinepubs/009695399/functions/posix_fadvise.html * * Copyright (C) 2000-2006 Erik Andersen <[email protected]> * * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball. */ #include <features.h> #include <unistd.h> #include <errno.h> #include <endian.h> #include <stdint.h> #include <sys/types.h> #include <sys/syscall.h> #include <fcntl.h> #ifdef __UCLIBC_HAS_LFS__ #if defined __NR_arm_fadvise64_64 /* This is for the ARM version of fadvise64_64 which swaps the params * about to avoid having ABI compat issues */ #define __NR___syscall_arm_fadvise64_64 __NR_arm_fadvise64_64 int __libc_posix_fadvise64(int fd, __off64_t offset, __off64_t len, int advise) { INTERNAL_SYSCALL_DECL (err); int ret = INTERNAL_SYSCALL (arm_fadvise64_64, err, 6, fd, advise, __LONG_LONG_PAIR ((long)(offset >> 32), (long)offset), __LONG_LONG_PAIR ((long)(len >> 32), (long)len)); if (!INTERNAL_SYSCALL_ERROR_P (ret, err)) return 0; if (INTERNAL_SYSCALL_ERRNO (ret, err) != ENOSYS) return INTERNAL_SYSCALL_ERRNO (ret, err); return 0; } weak_alias(__libc_posix_fadvise64, posix_fadvise64); #else int posix_fadvise64(int fd, __off64_t offset, __off64_t len, int advise) { __set_errno(ENOSYS); return -1; } #endif #endif
the_stack_data/115766848.c
/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it andor modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http:www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses Unicode 10.0.0. Version 10.0 of the Unicode Standard is synchronized with ISOIEC 10646:2017, fifth edition, plus the following additions from Amendment 1 to the fifth edition: - 56 emoji characters - 285 hentaigana - 3 additional Zanabazar Square characters */ /* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: [email protected], [email protected], [email protected], [email protected], [email protected]) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https:github.comLLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. 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 disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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. */ /* Example with loop-carried data dependence at the outer level loop. But the inner level loop can be parallelized. */ #include <string.h> int main(int argc, char * argv[]) { int i; int j; double a[20][20]; int _ret_val_0; memset(a, 0, sizeof a); #pragma cetus private(i, j) #pragma loop name main#0 #pragma cetus parallel #pragma omp parallel for private(i, j) for (i=0; i<20; i ++ ) { #pragma cetus private(j) #pragma loop name main#0#0 #pragma cetus parallel #pragma omp parallel for private(j) for (j=0; j<20; j ++ ) { a[i][j]=((i*20)+j); } } #pragma cetus private(i, j) #pragma loop name main#1 for (i=0; i<(20-1); i+=1) { #pragma cetus private(j) #pragma loop name main#1#0 #pragma cetus parallel #pragma omp parallel for private(j) for (j=0; j<20; j+=1) { a[i][j]+=a[i+1][j]; } } #pragma cetus private(i, j) #pragma loop name main#2 for (i=0; i<20; i ++ ) { #pragma cetus private(j) #pragma loop name main#2#0 for (j=0; j<20; j ++ ) { printf("%lf\n", a[i][j]); } } _ret_val_0=0; return _ret_val_0; }
the_stack_data/814601.c
#include <stdio.h> #include <stdlib.h> typedef int (*Fptr)(int, int); int SameTypeFunc(int a, int b) { printf("In %s \n", __FUNCTION__); exit(0); } void DiffRetFunc(int a, int b) { printf("In %s \n", __FUNCTION__); exit(0); } int DiffArgFunc(int a, float b) { printf("In %s \n", __FUNCTION__); exit(0); } int MoreArgFunc(int a, int b, int c) { printf("In %s \n", __FUNCTION__); exit(0); } int LessArgFunc(int a) { printf("In %s \n", __FUNCTION__); exit(0); } int VoidArgFunc(void) { printf("In %s \n", __FUNCTION__); exit(0); } int VulEntryFunc(int a, int b) { __asm__ volatile("nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n"); printf("In %s\n", __FUNCTION__); exit(0); } int Foo(int a, int b) { printf("In %s\n", __FUNCTION__); exit(0); } int main(int argc, const char *argv[]) { printf("inline indirect jump test\n"); printf("\tSameTypeFunc: %p\n", (void *)SameTypeFunc); printf("\tDiffRetFunc: %p\n", (void *)DiffRetFunc); printf("\tDiffArgFunc: %p\n", (void *)DiffArgFunc); printf("\tMoreArgFunc: %p\n", (void *)MoreArgFunc); printf("\tLessArgFunc: %p\n", (void *)LessArgFunc); printf("\tVoidArgFunc: %p\n", (void *)VoidArgFunc); printf("\tnot_entry: %p\n", (void *)(VulEntryFunc + 0x10)); printf("In %s\n", __FUNCTION__); Fptr ptr = Foo; char name[8]; printf("ptr is %p\n",&ptr); printf("name is %p\n",&name); // buffer overflow printf("plz input your name:\n"); read(0, name, 0x20); asm volatile("jmp *%0" : : "m"(ptr)); return 0; }
the_stack_data/73576333.c
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/timeb.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <string.h> #include <signal.h> #define DEBUG 0 void date_time(struct timespec *ts) { clock_gettime(CLOCK_REALTIME, ts); } int main(int argc, char **argv) { pid_t child_pid; int child_status; int child_exitcode; char id_buffer[128]; struct timespec tstart, tfinish; char *reporter_id = NULL; int debug_v = DEBUG; if (getenv("QCG_PJ_WRAPPER_DEBUG") != NULL && strncmp(getenv("QCG_PJ_WRAPPER_DEBUG"), "0", 2)) debug_v = 1; if (argc < 2) { fprintf(stderr, "error: missing arguments\n"); exit(-1); } date_time(&tstart); if ((child_pid = fork()) == -1) { perror("fork error"); exit(-1); } else if (child_pid == 0) { execvp(argv[1], &argv[1]); fprintf(stderr, "error: '%s' command unknown\n", argv[1]); exit(-1); } else { char *report_path; FILE *out_fd; ssize_t written; if (waitpid(child_pid, &child_status, 0) < 0) { perror("failed to wait for a child process"); } child_exitcode = WEXITSTATUS(child_status); signal(SIGPIPE, SIG_IGN); if (debug_v) { fprintf(stderr, "child job finished with %d exit code\n", child_exitcode); } date_time(&tfinish); reporter_id = getenv("QCG_PM_RUNTIME_STATS_ID"); if (reporter_id == NULL) { snprintf(id_buffer, sizeof(id_buffer), "pid:%d", getpid()); reporter_id = id_buffer; } report_path = getenv("QCG_PM_RUNTIME_STATS_PIPE"); if (report_path == NULL) { out_fd = stderr; } else { out_fd = fopen(report_path, "w"); if (out_fd == NULL) { perror("failed to open pipe file"); exit(-2); } } if (debug_v) { fprintf(stderr, "runtime stats id: %s\n", reporter_id); fprintf(stderr, "runtime stats path: %s\n", report_path); fprintf(stderr, "%s,%lf,%lf\n", reporter_id, tstart.tv_sec + (double)tstart.tv_nsec / 1e9, tfinish.tv_sec + (double)tfinish.tv_nsec / 1e9); } written = fprintf(out_fd, "%s,%lf,%lf\n", reporter_id, tstart.tv_sec + (double)tstart.tv_nsec / 1e9, tfinish.tv_sec + (double)tfinish.tv_nsec / 1e9); if (written < 0) { perror("write data to pipe error"); } else { if (debug_v) { fprintf(stderr, "wrote %ld bytes\n", written); } } if (out_fd != stderr) { if (fclose(out_fd) != 0) { perror("failed to close write side of pipe"); } } exit(child_exitcode); } return 0; }
the_stack_data/100555.c
/* ========== Question: Imagine the case of a darshan queue at a holy temple, where the queue is divided into three levels: I, II, and III. There are three categories of darshan: i) Normal, ii) Special Darshan, and iii) Special Darshan with Puja. A devotee for normal darshan is entered into the queue of level -III. When it is found that queue level II is not full, then the devotee from front of the queue level III is removed and inserted to the queue level II. Similarly, when queue level I is not full, a devotee from the front of level II is removed and inserted to level I. However, a devotee for Special Darshan and Special darshan with puja is inserted directly in the end of queue level II and I respectively. Write a menu driven program in C / C++ to implement the above data structure and all its operations. ========== */ // Include the required header files #include<stdio.h> // Consider that the maximum number of people in each queue ca be 15 const max_size = 10; // Functions for queue operations void addDevotee(int queue[], int *front, int *rear, int *qno) { if(*rear == max_size-1) { printf("\nAll The Queues Are Full! \nPlease Try Again After Some Time!"); } else if(isEmptyQ(queue, &front, &rear) == 1) { *front=0; *rear =0; queue[*rear]=1; printf("\nCongrats! You found a place in the queue %d",*qno); } else { *rear = *rear+1; queue[*rear]=1; printf("\nCongrats! You found a place in the queue %d",*qno); } } void removeDevotee(int queue, int *front, int *rear, int *qno) { if(isEmptyQ(queue, &front, &rear) == 1) { printf("\nThe queue %d is empty", *qno); return; } else if (*front == *rear) { *front = -1; *rear = -1; } else { *front = *front + 1; } } int isEmptyQ(int queue[], int *front, int *rear) { if(*front == -1 && *rear == -1) { return 1; } else { return 0; } } int isNotFull(int queue[], int *front, int *rear, int *qno) { if(*rear == max_size-1) { return 0; } else { *qno = *qno-1; printf("\nWAIT!!! The Queue level %d is not yet full!",*qno); return 1; } } // Main Function int main() { // Declare the needed variables to solve this problem int choice,q1[max_size],q2[max_size],q3[max_size],f1=-1,f2=-1,f3=-1,r1=-1,r2=-1,r3=-1,cq; while(1) { // Menu printf("\n\n\t\t\t Managing queue at temple\n"); printf("\nChoose the category: "); printf("\n 1. Normal Devotee"); printf("\n 2. Special Devotee"); printf("\n 3. Special Devotee with puja"); printf("\nEnter your choice: "); scanf("%d",&choice); // for normal devotee if(choice == 1) { // Add the devotee to queue level 3 cq=3; addDevotee(q3,&f3,&r3,&cq); // Check for a position in queue 2 if(isNotFull(q2,&f2,&r2,&cq) == 1) { // Remove the man from queue 3 and put him in queue 2 removeDevotee(q3,&f3,&r3,&cq); addDevotee(q2,&f2,&r2,&cq); } else { printf("\nQueue level 1 and 2 are full! the devotee stays in Queue 3 for some time!"); } // Check for a position in queue 1 if(isNotFull(q1,&f1,&r1,&cq) == 1) { // Remove the man from queue 3 and put him in queue 2 removeDevotee(q2,&f2,&r2,&cq); addDevotee(q1,&f1,&r1,&cq); } else { printf("\nQueue level 1 and 2 are full! the devotee stays in Queue 3 for some time!"); } } // for special darshan devotee else if(choice == 2) { // Add the devotee to queue level 2 cq=2; addDevotee(q2,&f2,&r2,&cq); // Check for a position in queue 1 if(isNotFull(q1,&f1,&r1,&cq) == 1) { // Remove the man from queue 3 and put him in queue 2 removeDevotee(q2,&f2,&r2,&cq); addDevotee(q1,&f1,&r1,&cq); } else { printf("\nQueue level 1 is full! the devotee stays in Queue 2 for some time!"); } } // for special darshan with puja devotee else if(choice == 3) { // Add the devotee to queue level 1 cq=1; addDevotee(q1,&f1,&r1,&cq); } else { printf("\nInvalid Input"); } } }
the_stack_data/127213.c
#include <stdio.h> void main() { int a = 1; while(a != 0) { printf("Enter a number: "); scanf("%d", &a); if (a <= 0) continue; printf("%d\n", a); } }
the_stack_data/93886926.c
/* * Copyright (c) 2000 Sheldon Hearn <[email protected]>. * 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. * * $FreeBSD: src/usr.bin/truncate/truncate.c,v 1.6.2.1 2000/08/04 08:05:52 sheldonh Exp $ * $DragonFly: src/usr.bin/truncate/truncate.c,v 1.3 2003/10/04 20:36:53 hmp Exp $ */ #include <sys/stat.h> #include <ctype.h> #include <err.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> static off_t parselength(char *, off_t *); static void usage(void); static int no_create; static int do_relative; static int do_refer; static int got_size; int main(int argc, char **argv) { struct stat sb; mode_t omode; off_t oflow, rsize, sz, tsize; int ch, error, fd, oflags; char *fname, *rname; rsize = tsize = sz = 0; error = 0; rname = NULL; while ((ch = getopt(argc, argv, "cr:s:")) != -1) switch (ch) { case 'c': no_create = 1; break; case 'r': do_refer = 1; rname = optarg; break; case 's': if (parselength(optarg, &sz) == -1) errx(EXIT_FAILURE, "invalid size argument `%s'", optarg); if (*optarg == '+' || *optarg == '-') do_relative = 1; got_size = 1; break; default: usage(); /* NOTREACHED */ } argv += optind; argc -= optind; /* * Exactly one of do_refer or got_size must be specified. Since * do_relative implies got_size, do_relative and do_refer are * also mutually exclusive. See usage() for allowed invocations. */ if (do_refer + got_size != 1 || argc < 1) usage(); if (do_refer) { if (stat(rname, &sb) == -1) err(EXIT_FAILURE, "%s", rname); tsize = sb.st_size; } else if (do_relative) rsize = sz; else tsize = sz; if (no_create) oflags = O_WRONLY; else oflags = O_WRONLY | O_CREAT; omode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; while ((fname = *argv++) != NULL) { if ((fd = open(fname, oflags, omode)) == -1) { if (errno != ENOENT) { warn("%s", fname); error++; } continue; } if (do_relative) { if (fstat(fd, &sb) == -1) { warn("%s", fname); error++; continue; } oflow = sb.st_size + rsize; if (oflow < (sb.st_size + rsize)) { errno = EFBIG; warn("%s", fname); error++; continue; } tsize = oflow; } if (tsize < 0) tsize = 0; if (ftruncate(fd, tsize) == -1) { warn("%s", fname); error++; continue; } close(fd); } return error ? EXIT_FAILURE : EXIT_SUCCESS; } /* * Return the numeric value of a string given in the form [+-][0-9]+[GMK] * or -1 on format error or overflow. */ static off_t parselength(char *ls, off_t *sz) { off_t length, oflow; int lsign; length = 0; lsign = 1; switch (*ls) { case '-': lsign = -1; case '+': ls++; } #define ASSIGN_CHK_OFLOW(x, y) if (x < y) return -1; y = x /* * Calculate the value of the decimal digit string, failing * on overflow. */ while (isdigit(*ls)) { oflow = length * 10 + *ls++ - '0'; ASSIGN_CHK_OFLOW(oflow, length); } switch (*ls) { case 'G': oflow = length * 1024; ASSIGN_CHK_OFLOW(oflow, length); case 'M': oflow = length * 1024; ASSIGN_CHK_OFLOW(oflow, length); case 'K': if (ls[1] != '\0') return -1; oflow = length * 1024; ASSIGN_CHK_OFLOW(oflow, length); case '\0': break; default: return -1; } *sz = length * lsign; return 0; } static void usage(void) { fprintf(stderr, "%s\n%s\n", "usage: truncate [-c] -s [+|-]size[K|M|G] file ...", " truncate [-c] -r rfile file ..."); exit(EXIT_FAILURE); }
the_stack_data/16220.c
/* push *.h */
the_stack_data/31566.c
#include <stdio.h> int main () { int c; while ((c = getchar()) != EOF) { if (c == '\t') { putchar('\\'); putchar('t'); } else if (c == '\b') { putchar('\\'); putchar('b'); } else if (c == '\\') { putchar('\\'); putchar('\\'); } else { putchar(c); } } return 0; }
the_stack_data/247018451.c
// Exercício 06 - Escreva uma função recursiva que receba, por parâmetro, dois valores X e Z e calcula // e retorna XZ. #include <stdio.h> int main(void) { int n1, n2; printf("Base = "); scanf("%d", &n1); printf("Expoente = "); scanf("%d", &n2); printf("Resultado = %d \n", potenciacao(n1, n2)); } int potenciacao(int n1, int n2) { if (n2 == 0) { return 1; } else { return n1 * potenciacao(n1, n2 - 1); } }
the_stack_data/678950.c
/* some helpers, so our code also works with LibreSSL */ #include <openssl/opensslv.h> #include <openssl/evp.h> #if defined(LIBRESSL_VERSION_NUMBER) const EVP_CIPHER *EVP_aes_256_ocb(void){ /* dummy, so that code compiles */ return NULL; } const EVP_CIPHER *EVP_chacha20_poly1305(void){ /* dummy, so that code compiles */ return NULL; } #endif
the_stack_data/32950524.c
#ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #ifdef __MINGW32__ #define __USE_MINGW_ANSI_STDIO 1 #endif #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define XSTR(a) STR(a) #define STR(a) #a #define MAXLEN 1024 struct string_view { // Specifies the window [first, first + length). const char *first; const ptrdiff_t length; }; // Checks if [first, last) is a palindrome. static inline bool is_palindrome(const char *first, const char *last) { while (first < last) if (*first++ != *--last) return false; return true; } // Checks if the window [first, mid), or any window that may be obtained by // sliding it to the right such that its width stays the same and mid <= right, // is a palindrome. Returns the left endpoint of the first matching window, // or NULL if there is no match. static inline const char *slide_window_to_palindrome( const char *first, const char *mid, const char *const last) { for (; ; ++first, ++mid) { if (is_palindrome(first, mid)) return first; if (mid == last) return NULL; } } // Finds the first maximum-length palindrome in [first, last). static struct string_view find_longest_palindrome(const char *const first, const char *const last) { for (const char *mid = last; mid != first; --mid) { const char *const match = slide_window_to_palindrome(first, mid, last); if (match != NULL) return (struct string_view) { match, mid - first }; } assert(first == last); // nonempty worst case was a 1-character palindrome return (struct string_view) { first, 0 }; } // Prints the characters in the window denoted by the view, then a newline. static inline void print(const struct string_view view) { printf("%.*s\n", (int)view.length, view.first); } int main(void) { char buf[MAXLEN + 1] = { 0 }; int t = 0; for ((void)scanf("%d", &t); t > 0; --t) { if (scanf("%" XSTR(MAXLEN) "s", buf) != 1) abort(); print(find_longest_palindrome(buf, strchr(buf, '\0'))); } }
the_stack_data/82949218.c
#include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[], char* env[]) { int filedes_p[2]; int filedes_c[2]; int p_id; size_t size; int i = 0; int point = 0; int ex_cond = 3; char* message_list1[] = {"What is your name!?","How old are you!?","Goodbye!!!"}; char* message_list2[] = {"My name is Sandron","I'm 21","Bye!!!"}; char message[32]; if(pipe(filedes_p) < 0) { printf("Errrrrror"); exit(-1); } if(pipe(filedes_c) < 0) { printf("Errrrrror"); exit(-1); } p_id = fork (); if(p_id < 0) { printf("Errrrrror"); exit(-1); } else if(p_id > 0) { close(filedes_p[1]); close(filedes_c[0]); while(point == 0) { size = write(filedes_c[1], message_list1[i], 32); while (size = read(filedes_p[0], message, 32) < 0); printf("I tyt maloy otvetil: %s\n",message); i++; if(i >= ex_cond) point = -254; } close(filedes_p[0]); close(filedes_c[1]); } else { close(filedes_p[0]); close(filedes_c[1]); while(point == 0) { while (size = read(filedes_c[0], message, 32) < 0); printf("I tyt batya skazal: %s\n",message); size = write(filedes_p[1], message_list2[i], 32); i++; if(i >= ex_cond) point = -254; } close(filedes_p[1]); close(filedes_c[0]); } exit(0); }
the_stack_data/193891928.c
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> //Reading output from external command int main() { FILE *read_fp; char buffer[BUFSIZ + 1]; int chars_read; memset(buffer, '\0', sizeof(buffer)); read_fp = popen("ps -ax", "r"); if (read_fp != NULL) { chars_read = fread(buffer, sizeof(char), BUFSIZ, read_fp); if (chars_read > 0) { printf("Output was:-\n%s\n", buffer); } pclose(read_fp); exit(EXIT_SUCCESS); } exit(EXIT_FAILURE); }
the_stack_data/1089173.c
/* $OpenBSD: s_cacosl.c,v 1.3 2011/07/20 21:02:51 martynas Exp $ */ /* * Copyright (c) 2008 Stephen L. Moshier <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* cacosl() * * Complex circular arc cosine * * * * SYNOPSIS: * * long double complex cacosl(); * long double complex z, w; * * w = cacosl( z ); * * * * DESCRIPTION: * * * w = arccos z = PI/2 - arcsin z. * * * * * ACCURACY: * * Relative error: * arithmetic domain # trials peak rms * DEC -10,+10 5200 1.6e-15 2.8e-16 * IEEE -10,+10 30000 1.8e-14 2.2e-15 */ #include <complex.h> #include <math.h> static const long double PIO2L = 1.570796326794896619231321691639751442098585L; long double complex cacosl(long double complex z) { long double complex w; w = casinl(z); w = (PIO2L - creall(w)) - cimagl(w) * I; return (w); }
the_stack_data/450140.c
#include <setjmp.h> __attribute__((naked)) __attribute__((returns_twice)) int setjmp(jmp_buf env) { asm volatile ( "leaq 8(%%rsp), %%rax\n" /* Return address into rax */ "movq %%rax, 0(%%rdi)\n" /* jmp_buf[0] = rsp */ "movq %%rbp, 8(%%rdi)\n" /* jmp_buf[1] = rbp */ "movq (%%rsp), %%rax\n" "movq %%rax, 16(%%rdi)\n" /* jmp_buf[2] = return address */ "movq %%rbx, 24(%%rdi)\n" /* jmp_buf[3] = rbx */ "movq %%r12, 32(%%rdi)\n" /* jmp_buf[4] = r12 */ "movq %%r13, 40(%%rdi)\n" /* jmp_buf[5] = r12 */ "movq %%r14, 48(%%rdi)\n" /* jmp_buf[6] = r12 */ "movq %%r15, 56(%%rdi)\n" /* jmp_buf[7] = r12 */ "xor %%rax, %%rax\n" /* return 0 */ "retq" :::"memory" ); } __attribute__((naked)) __attribute__((noreturn)) void longjmp(jmp_buf env, int val) { asm volatile ( "movq 0(%%rdi), %%rsp\n" "movq 8(%%rdi), %%rbp\n" "movq 24(%%rdi), %%rbx\n" "movq 32(%%rdi), %%r12\n" "movq 40(%%rdi), %%r13\n" "movq 48(%%rdi), %%r14\n" "movq 56(%%rdi), %%r15\n" "movq %%rsi, %%rax\n" "jmpq *16(%%rdi)\n" :::"memory" ); }
the_stack_data/95451357.c
/* * --INFO-- * Address: 8021B708 * Size: 000020 */ void pow(void) { /* .loc_0x0: mflr r0 stw r0, 0x4(r1) stwu r1, -0x8(r1) bl -0xD64 lwz r0, 0xC(r1) addi r1, r1, 0x8 mtlr r0 blr */ }
the_stack_data/76700990.c
#include<stdio.h> #define NUMBER 5 void main(void){ FILE *fp; int age = 0; int height = 0; fp = fopen("abc.txt","r+"); if(fp == NULL){ printf("error\n"); }else{ fprintf(fp,"%d",60); while((age = fgetc(fp)) != EOF){ putchar(age); } fclose(fp); } }
the_stack_data/719367.c
#include <stdio.h> main() { int i, ncol, icol, jcol; char *value; ncol = topen("test1.tbl"); icol = tcol("fnu_25"); jcol = tcol("fnu_60"); while(tread() >= 0) printf("%s %s\n", tval(icol), tval(jcol)); tclose(); }
the_stack_data/137349.c
/* { dg-do run } */ /* { dg-options "-O2" } */ extern void abort (void); extern char *strncpy(char *, const char *, __SIZE_TYPE__); union u { struct { char vi[8]; char pi[16]; }; char all[8+16+4]; }; void __attribute__((noinline,noclone)) f(union u *u) { char vi[8+1]; __builtin_strncpy(vi, u->vi, sizeof(u->vi)); if (__builtin_object_size (u->all, 1) != -1) abort (); } int main() { union u u; f (&u); return 0; }
the_stack_data/71874.c
#include<stdio.h> int main(){ int i,j; int ans; for(i=1; i<=9; i++){ for(j=1; j<=i; j++){ // 下三角(Triange Up):(j=1; j<=i; j++) / 上三角(Triange Down):(j=i; j<=9; j++) ans = i * j; printf("%d * %d = %d\t", j, i, ans); } puts("\n"); } return 0; }
the_stack_data/478610.c
// Check that ld gets arch_multiple. // RUN: %clang -target i386-apple-darwin9 -arch i386 -arch x86_64 %s -### -o foo 2> %t.log // RUN: grep '".*ld.*" .*"-arch_multiple" "-final_output" "foo"' %t.log // Make sure we run dsymutil on source input files. // RUN: %clang -target i386-apple-darwin9 -### -g %s -o BAR 2> %t.log // RUN: grep '".*dsymutil" "-o" "BAR.dSYM" "BAR"' %t.log // RUN: %clang -target i386-apple-darwin9 -### -g -filelist FOO %s -o BAR 2> %t.log // RUN: grep '".*dsymutil" "-o" "BAR.dSYM" "BAR"' %t.log // Check linker changes that came with new linkedit format. // RUN: touch %t.o // RUN: %clang -target i386-apple-darwin9 -### -arch armv6 -miphoneos-version-min=3.0 %t.o 2> %t.log // RUN: %clang -target i386-apple-darwin9 -### -arch armv6 -miphoneos-version-min=3.0 -dynamiclib %t.o 2>> %t.log // RUN: %clang -target i386-apple-darwin9 -### -arch armv6 -miphoneos-version-min=3.0 -bundle %t.o 2>> %t.log // RUN: FileCheck -check-prefix=LINK_IPHONE_3_0 %s < %t.log // LINK_IPHONE_3_0: {{ld(.exe)?"}} // LINK_IPHONE_3_0-NOT: -lcrt1.3.1.o // LINK_IPHONE_3_0: -lcrt1.o // LINK_IPHONE_3_0: -lSystem // LINK_IPHONE_3_0: {{ld(.exe)?"}} // LINK_IPHONE_3_0: -dylib // LINK_IPHONE_3_0: -ldylib1.o // LINK_IPHONE_3_0: -lSystem // LINK_IPHONE_3_0: {{ld(.exe)?"}} // LINK_IPHONE_3_0: -lbundle1.o // LINK_IPHONE_3_0: -lSystem // RUN: %clang -target i386-apple-darwin9 -### -arch armv7 -miphoneos-version-min=3.1 %t.o 2> %t.log // RUN: %clang -target i386-apple-darwin9 -### -arch armv7 -miphoneos-version-min=3.1 -dynamiclib %t.o 2>> %t.log // RUN: %clang -target i386-apple-darwin9 -### -arch armv7 -miphoneos-version-min=3.1 -bundle %t.o 2>> %t.log // RUN: FileCheck -check-prefix=LINK_IPHONE_3_1 %s < %t.log // LINK_IPHONE_3_1: {{ld(.exe)?"}} // LINK_IPHONE_3_1-NOT: -lcrt1.o // LINK_IPHONE_3_1: -lcrt1.3.1.o // LINK_IPHONE_3_1: -lSystem // LINK_IPHONE_3_1: {{ld(.exe)?"}} // LINK_IPHONE_3_1: -dylib // LINK_IPHONE_3_1-NOT: -ldylib1.o // LINK_IPHONE_3_1: -lSystem // LINK_IPHONE_3_1: {{ld(.exe)?"}} // LINK_IPHONE_3_1-NOT: -lbundle1.o // LINK_IPHONE_3_1: -lSystem // RUN: %clang -target i386-apple-darwin9 -### -fpie %t.o 2> %t.log // RUN: FileCheck -check-prefix=LINK_EXPLICIT_PIE %s < %t.log // // LINK_EXPLICIT_PIE: {{ld(.exe)?"}} // LINK_EXPLICIT_PIE: "-pie" // RUN: %clang -target i386-apple-darwin9 -### -fno-pie %t.o 2> %t.log // RUN: FileCheck -check-prefix=LINK_EXPLICIT_NO_PIE %s < %t.log // // LINK_EXPLICIT_NO_PIE: {{ld(.exe)?"}} // LINK_EXPLICIT_NO_PIE: "-no_pie" // RUN: %clang -target x86_64-apple-darwin10 -### %t.o \ // RUN: -mlinker-version=100 2> %t.log // RUN: FileCheck -check-prefix=LINK_NEWER_DEMANGLE %s < %t.log // // LINK_NEWER_DEMANGLE: {{ld(.exe)?"}} // LINK_NEWER_DEMANGLE: "-demangle" // RUN: %clang -target x86_64-apple-darwin10 -### %t.o \ // RUN: -mlinker-version=100 -Wl,--no-demangle 2> %t.log // RUN: FileCheck -check-prefix=LINK_NEWER_NODEMANGLE %s < %t.log // // LINK_NEWER_NODEMANGLE: {{ld(.exe)?"}} // LINK_NEWER_NODEMANGLE-NOT: "-demangle" // LINK_NEWER_NODEMANGLE: "-lSystem" // RUN: %clang -target x86_64-apple-darwin10 -### %t.o \ // RUN: -mlinker-version=95 2> %t.log // RUN: FileCheck -check-prefix=LINK_OLDER_NODEMANGLE %s < %t.log // // LINK_OLDER_NODEMANGLE: {{ld(.exe)?"}} // LINK_OLDER_NODEMANGLE-NOT: "-demangle" // LINK_OLDER_NODEMANGLE: "-lSystem" // RUN: %clang -target x86_64-apple-darwin10 -### %t.o \ // RUN: -mlinker-version=117 -flto 2> %t.log // RUN: cat %t.log // RUN: FileCheck -check-prefix=LINK_OBJECT_LTO_PATH %s < %t.log // // LINK_OBJECT_LTO_PATH: {{ld(.exe)?"}} // LINK_OBJECT_LTO_PATH: "-object_path_lto" // RUN: %clang -target x86_64-apple-darwin10 -### %t.o \ // RUN: -force_load a -force_load b 2> %t.log // RUN: cat %t.log // RUN: FileCheck -check-prefix=FORCE_LOAD %s < %t.log // // FORCE_LOAD: {{ld(.exe)?"}} // FORCE_LOAD: "-force_load" "a" "-force_load" "b" // RUN: %clang -target x86_64-apple-darwin10 -### %t.o \ // RUN: -lazy_framework Framework 2> %t.log // // RUN: FileCheck -check-prefix=LINK_LAZY_FRAMEWORK %s < %t.log // LINK_LAZY_FRAMEWORK: {{ld(.exe)?"}} // LINK_LAZY_FRAMEWORK: "-lazy_framework" "Framework" // RUN: %clang -target x86_64-apple-darwin10 -### %t.o \ // RUN: -lazy_library Library 2> %t.log // // RUN: FileCheck -check-prefix=LINK_LAZY_LIBRARY %s < %t.log // LINK_LAZY_LIBRARY: {{ld(.exe)?"}} // LINK_LAZY_LIBRARY: "-lazy_library" "Library" // RUN: %clang -target x86_64-apple-darwin10 -### %t.o 2> %t.log // RUN: %clang -target x86_64-apple-macosx10.7 -### %t.o 2>> %t.log // RUN: FileCheck -check-prefix=LINK_VERSION_MIN %s < %t.log // LINK_VERSION_MIN: {{ld(.exe)?"}} // LINK_VERSION_MIN: "-macosx_version_min" "10.6.0" // LINK_VERSION_MIN: {{ld(.exe)?"}} // LINK_VERSION_MIN: "-macosx_version_min" "10.7.0" // RUN: %clang -target x86_64-apple-darwin12 -### %t.o 2> %t.log // RUN: FileCheck -check-prefix=LINK_NO_CRT1 %s < %t.log // LINK_NO_CRT1-NOT: crt // RUN: %clang -target armv7-apple-ios6.0 -miphoneos-version-min=6.0 -### %t.o 2> %t.log // RUN: FileCheck -check-prefix=LINK_NO_IOS_CRT1 %s < %t.log // LINK_NO_IOS_CRT1-NOT: crt // RUN: %clang -target i386-apple-darwin12 -pg -### %t.o 2> %t.log // RUN: FileCheck -check-prefix=LINK_PG %s < %t.log // LINK_PG: -lgcrt1.o // LINK_PG: -no_new_main
the_stack_data/248579749.c
/* ** sort_tab.c for sort_tab in /home/gwendoline/rendu/Piscine_Synthese/FASTAtools/lib ** ** Made by ** Login <[email protected]> ** ** Started on Thu Jun 25 13:20:26 2015 ** Last update Thu Jun 25 15:49:35 2015 */ void swaptab(char **tab, int i, int j) { char *str; str = tab[i]; tab[i] = tab[j]; tab[j] = str; } int len_tab(char **tab) { int i; i = 0; while (tab[i]) i++; return (i); }
the_stack_data/28263504.c
#include<stdio.h> #include<stdlib.h> #include<time.h> #define NUMBER 12 int main(){ int i, j; int *ptrToOneDArray; int **ptrToTwoDArray; int nRows = 3; int nColumns=4; srand(time(NULL)); ptrToOneDArray = (int *) calloc(NUMBER, sizeof(int)); ptrToTwoDArray = (int **) calloc(nRows, sizeof(int *)); //1D array initialization for (i = 0; i < NUMBER; ++i) ptrToOneDArray[i] = rand() % NUMBER; for (i = 0; i < NUMBER; ++i) printf("%d ", ptrToOneDArray[i]); printf("\nUse for loop to print &ptrToOneDArray[i]\n"); for (i = 0; i < NUMBER; ++i) printf("%p ", &ptrToOneDArray[i]); printf("\n"); printf("ptrToTwoDArray is %p\n", ptrToTwoDArray); // 2D array initialization for (i = 0; i < nRows; ++i) ptrToTwoDArray[i] = (int *) calloc(nColumns, sizeof(int)); printf("&ptrToTwoDArray[0]: %p\n", &ptrToTwoDArray[0]); for (i = 0; i < nRows; ++i) printf("%p ", ptrToTwoDArray[i]); printf("\n"); for (i = 0; i < nRows; ++i) { for (j = 0; j < nColumns; ++j){ ptrToTwoDArray[i][j]= rand() % 100; } } for (i = 0; i < nRows; ++i) { for (j = 0; j < nColumns; ++j){ printf("%d ", ptrToTwoDArray[i][j]); } printf("\n"); } for (i = 0; i < nRows; ++i) { for (j = 0; j < nColumns; ++j){ printf("%p ", &ptrToTwoDArray[i][j]); } printf("\n"); } printf("\n"); // let's release the allocated memory properly free(ptrToOneDArray); for (i = 0; i < nRows; ++i) free(ptrToTwoDArray[i]); free(ptrToTwoDArray); return 0; } /** output 11 11 0 6 4 10 8 8 6 8 9 10 Use for loop to print &ptrToOneDArray[i] 0x51d7040 0x51d7044 0x51d7048 0x51d704c 0x51d7050 0x51d7054 0x51d7058 0x51d705c 0x51d7060 0x51d7064 0x51d7068 0x51d706c ptrToTwoDArray is 0x51d70b0 &ptrToTwoDArray[0]: 0x51d70b0 0x51d7550 0x51d75a0 0x51d75f0 71 80 41 82 87 93 48 17 86 46 61 89 0x51d7550 0x51d7554 0x51d7558 0x51d755c 0x51d75a0 0x51d75a4 0x51d75a8 0x51d75ac 0x51d75f0 0x51d75f4 0x51d75f8 0x51d75fc **/
the_stack_data/98575533.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <libgen.h> #include <sys/stat.h> int main(int argc, char *argv[]){ if(argc == 1){ printf("Usage: touch [file name]"); }else{ int i; FILE *fPtr; for(i = 1; i <argc ; i++){ char *arg = strdup(argv[i]); char path[1024] = ""; char *ptr = strtok(dirname(argv[i]), "/"); while(ptr != NULL){ if(strcmp(path, "")) { strcat(path, "\\\\"); } strcat(path, ptr); char cmd[1024] = "mkdir "; strcat(cmd, path); struct stat sb; if(!(stat(path, &sb) == 0 && S_ISDIR(sb.st_mode))){ system(cmd); } ptr = strtok(NULL, "/"); } fPtr = fopen(arg, "w"); fputs("", fPtr); fclose(fPtr); } } }
the_stack_data/36074344.c
#include<stdio.h> int main(void) { printf("Existentialism.\n"); return 0; }
the_stack_data/247017447.c
#include <stdio.h> #include <stdlib.h> /** * swap: swaps two variables * @param x pointer to the first variable * @param y pointer to the second variable * @return void */ void swap(int* x, int* y) { int temp = *y; *y = *x; *x = temp; } /** * bubbleSort: bubble sort implementation * @param arr an array of integers * @param arrSize the size of that array * @return void */ void bubbleSort(int arr[], int arrSize) { for (int i = 0; i < arrSize - 1; i++) { for (int j = i + 1; j < arrSize; j++) { if (arr[i] > arr[j]) { swap(&arr[i], &arr[j]); } } } } /** * selectionSort: selection sort implementation * @param arr an array of integers * @param arrSize the size of that array * @return void */ void selectionSort(int arr[], int arrSize) { int minIndex; for (int i = 0; i < arrSize - 1; i++) { minIndex = i; for (int j = i + 1; j < arrSize; j++) if (arr[j] < arr[minIndex]) minIndex = j; swap(&arr[minIndex], &arr[i]); } } /** * pivot: utility function for quick sort, it splits the given array in two small subarrays and swaps elements * @param arr the array * @param arrSize length of the array * @param start starting index point of the array * @param end ending index point of the array * @return swapIndex */ int pivot(int arr[], int arrSize, int start, int end) { int pivot = arr[start]; int swapIndex = start; for (int i = start + 1; i < arrSize; i++) { if (pivot > arr[i]) { swapIndex++; // keeping track of how many elements we find so we will know the right index of the pivot swap(&arr[swapIndex], &arr[i]); } } swap(&arr[start], &arr[swapIndex]); return swapIndex; } /** * quickSort: quick sort implementation * @param arr an array of integers * @param arrSize length of the array * @param left the left index point of the array, at the first iteration this is going to be 0 * @param right the right index point of the array, athe the first iteration this is going to be arrSize - 1 * @return void */ void quickSort(int arr[], int arrSize, int left, int right) { /* NOTE: we could avoid passing the array length everytime but I was too lazy */ if (left < right) { int pivotIndex = pivot(arr, arrSize, left, right); // left quickSort(arr, arrSize, left, pivotIndex - 1); // right quickSort(arr, arrSize, pivotIndex + 1, right); } } int main() { int arr[] = {8, 3, 0, 1, 5, 4, 7, 12, 54, 21, 99}; for (int i = 0; i < 11; i++) { printf("%d ", arr[i]); } printf("\n"); quickSort(arr, 11, 0, 10); for (int i = 0; i < 11; i++) { printf("%d ", arr[i]); } printf("\n"); return 0; }
the_stack_data/111787.c
#include<stdio.h> int power(int a,int b) { if(b==0) return 1; else return a*power(a,b-1); } void decequi(int num) { int array[16]; for(int i=15;i>=0;i--) { array[i]=!(num&1); num>>=1; } num=0; for(int i=15;i>=0;i--) num+=(array[i]*power(2,15-i)); printf("HEX euivalent is %x\n",num); } void masking(int num) { int ch; printf("Choose:\n1.Bitwise AND.\n2.Bitwise XOR.\n3.Bitwise OR.\n"); scanf("%d",&ch); int mask; printf("Enter mask value: "); scanf("%d",&mask); if(ch==1) { num&=mask; printf("%x\n",num); } else if(ch==2) { num^=mask; printf("%x\n",num); } else { num|=mask; printf("%x\n",num); } } void shifting(int num) { int ch, bit; printf("Choose:\n1.Right Shift.\n2.Left Shift.\n"); scanf("%d",&ch); printf("Number of bits: "); scanf("%d",&bit); if(ch==1) num>>=bit; else num<<=bit; printf("Processed: %x\n",num); } int main() { int choice, num; while(1) { printf("Choose.\n1.HEX equivalent of 1's compliment."); printf("\n2.Masking.\n3.shifting.\n4.Exit.\n"); scanf(" %d",&choice); printf("Enter HEX value: "); scanf(" %d",&num); //printf("\n"); switch(choice) { case 1 : decequi(num); break; case 2 : masking(num); break; case 3 : shifting(num); break; case 4 : return 0; default: printf("Wrong choice!!!"); return -1; } } return 0; }
the_stack_data/199883.c
int __fp_unordered_compare (long double x, long double y){ unsigned short retval; __asm__ ( "fucom %%st(1);" "fnstsw;" : "=a" (retval) : "t" (x), "u" (y) ); return retval; }
the_stack_data/19236.c
/* { dg-do compile } */ /* { dg-options "-Wshift-count-overflow" } */ void foo() { unsigned i1 = 1U << (sizeof(unsigned) * __CHAR_BIT__); /* { dg-warning "left shift count >= width of type" } */ unsigned i2 = 1U >> (sizeof(unsigned) * __CHAR_BIT__); /* { dg-warning "right shift count >= width of type" } */ }