file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/154828864.c
static int f(void); int f(void){ return 5; } int main(void){ return f(); }
the_stack_data/28770.c
/**********************************************************************************/ #if 0 /**********************************************************************************/ #include "../ubench.h/ubench.h" #include "../dbj_matmul_common.h" #define DBJ_VARIOUS_SIMPLE_MATMULS_IMPLEMENTATION #include "simple_matmuls.h" #undef DBJ_API #define DBJ_API __attribute__((const)) static DBJ_API DBJ_MATRIX_DATA_TYPE get_one(void) { (DBJ_MATRIX_DATA_TYPE)1; } /**********************************************************************************/ enum { max_matrix_side = DBJ_SANITY_MAX_ROW_COUNT, testing_matrix_rows = DBJ_MATRIX_SIDE_DIMENSION, testing_matrix_cols = DBJ_MATRIX_SIDE_DIMENSION }; typedef struct { unsigned rows; unsigned cols; DBJ_MATRIX_DATA_TYPE* mx_data_A; DBJ_MATRIX_DATA_TYPE* mx_data_B; DBJ_MATRIX_DATA_TYPE* mx_data_M; } test_matmul_common_data; DBJ_API test_matmul_common_data TMCD_ = { .rows = testing_matrix_rows, .cols = testing_matrix_cols, .mx_data_A = NULL, .mx_data_B = NULL, .mx_data_M = NULL }; __attribute__((constructor)) DBJ_API void test_matmul_common_data_constructor(void) { TMCD_.mx_data_A = make_simple_matrix(TMCD_.rows, TMCD_.cols, get_one); TMCD_.mx_data_B = make_simple_matrix(TMCD_.rows, TMCD_.cols, get_one); TMCD_.mx_data_M = make_simple_matrix(TMCD_.cols, TMCD_.rows, get_one); } __attribute__((destructor)) DBJ_API void test_matmul_common_data_destructor(void) { if (TMCD_.mx_data_M) free(TMCD_.mx_data_M); if (TMCD_.mx_data_A) free(TMCD_.mx_data_A); if (TMCD_.mx_data_B) free(TMCD_.mx_data_B); } /* * calling direct or with table lokup makes no difference in speed */ #define UBENCH_COMMON_BODY(DBJ_MATMUL_API_FUN_ID) \ dbj_simple_matmuls_algo_table[DBJ_MATMUL_API_FUN_ID].function(\ TMCD_.rows, TMCD_.cols, TMCD_.rows, /* BUG?! */ \ TMCD_.mx_data_A , TMCD_.mx_data_B, TMCD_.mx_data_M \ ) UBENCH(simple, matmul_0) { UBENCH_COMMON_BODY(0); } UBENCH(simple, matmul_0_0) { simple_mat_mul_0_0( TMCD_.rows, TMCD_.cols, TMCD_.rows, /* BUG?! */ TMCD_.mx_data_A, TMCD_.mx_data_B, TMCD_.mx_data_M ); } UBENCH(simple, matmul_1) { UBENCH_COMMON_BODY(2); } #if __SSE__ UBENCH(simple, matmul_2_sse) { UBENCH_COMMON_BODY(3); } UBENCH(simple, matmul_7_sse) { UBENCH_COMMON_BODY(4); } #endif // __SSE__ UBENCH(simple, matmul_3) { UBENCH_COMMON_BODY(5); } UBENCH(simple, matmul_4) { UBENCH_COMMON_BODY(6); } #ifdef HAVE_CBLAS UBENCH(simple, matmul_5_cblas) { UBENCH_COMMON_BODY(7); } UBENCH(simple, matmul_6_cblas) { UBENCH_COMMON_BODY(8); } #endif // HAVE_CBLAS /**********************************************************************************/ #endif // 0 /**********************************************************************************/
the_stack_data/107587.c
#ifdef NDEBUG #undef NDEBUG #endif #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <string.h> #define XSTR(a) STR(a) #define STR(a) #a #define MAXLEN 100 static bool is_palindrome(const char *const a, ptrdiff_t n) { for (ptrdiff_t i = 0; i < --n; ++i) if (a[i] != a[n]) return false; return true; } int main(void) { int t = 0; for ((void)scanf("%d", &t); t > 0; --t) { ptrdiff_t n = 0; char buf[MAXLEN + 1] = { 0 }; (void)scanf("%td %" XSTR(MAXLEN) "s", &n, buf); assert(strlen(buf) == (size_t)n); printf("%d\n", (is_palindrome(buf, n) ? 1 : 0)); } }
the_stack_data/360093.c
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; struct node *prev; }; typedef struct node NODE; NODE *LLnode,*head,*temp,*prev; NODE* insert_at_front(NODE *); NODE* insert_at_end(NODE *); NODE* delete_at_front(NODE *); NODE* delete_at_end(NODE *); void display(NODE *); main() { int ch; head=NULL; do { printf("1--insert node at the front\n"); printf("2--insert node at the end\n"); printf("3--delete a node at the front\n"); printf("4--delete a node at the end\n"); printf("5--display the linked list\n"); printf("6--close the program\n"); printf("enter your choice\n"); scanf("%d",&ch); switch(ch) { case 1: head=insert_at_front(head); break; case 2: head=insert_at_end(head); break; case 3:head=delete_at_front(head); break; case 4: head=delete_at_end(head); break; case 5: display(head); break; case 6: exit(0);break; default:printf("Invalid choice\n"); break; } }while(ch!=6); } NODE* insert_at_front(NODE *head) { LLnode=(NODE *)malloc(sizeof(NODE)); printf("enter the data\n"); scanf("%d",&LLnode->data); if(head==NULL) { head=LLnode; head->next=NULL; head->prev=NULL; } else { LLnode->next=head; head=LLnode; head->prev=NULL; } return(head); } NODE* insert_at_end(NODE *head) { LLnode=(NODE *)malloc(sizeof(NODE)); printf("enter the data\n"); scanf("%d",&LLnode->data); LLnode->next=NULL; if(head==NULL) { head=LLnode; head->next=NULL; head->prev=NULL; } else { temp=head; while(temp->next!=NULL) { temp=temp->next; } temp->next=LLnode; LLnode->prev=temp; LLnode->next=NULL; } return(head); } NODE* delete_at_front(NODE *head) { if(head==NULL) { printf("Linked list is empty...cant delete a node\n"); } else if(head->next==NULL) { //temp=head; printf("node deleted=%d\n",head->data); free(head); head=NULL; } else { temp=head->next; printf("node deleted=%d\n",head->data); free(head); head=temp; head->prev=NULL; } return(head); } NODE* delete_at_end(NODE *head) { if(head==NULL) { printf("Linked list is empty...cant delete a node\n"); } else if(head->next==NULL) { printf("node deleted=%d\n",head->data); free(head); head=NULL; } else { temp=head; while(temp->next!=NULL) { prev=temp; temp=temp->next; } printf("node deleted=%d\n",temp->data); free(temp); prev->next=NULL; } return(head); } void display(NODE *head) { if(head==NULL) { printf("Linked list is empty\n"); } else { printf("the linked list is as below\n"); temp=head; while(temp!=NULL) { printf("%d->",temp->data); temp=temp->next; } printf("\n"); } }
the_stack_data/32949732.c
/* * Copyright (c) 2012, 2013 Jonas 'Sortie' Termansen. * * 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. * * stdio/fscanf_unlocked.c * Input format conversion. */ #include <stdarg.h> #include <stdio.h> int fscanf_unlocked(FILE* fp, const char* format, ...) { va_list ap; va_start(ap, format); flockfile(fp); int ret = vfscanf_unlocked(fp, format, ap); funlockfile(fp); va_end(ap); return ret; }
the_stack_data/528961.c
// RUN: %crabllvm --inline --lower-select --lower-unsigned-icmp --do-not-print-invariants --crab-dom=boxes --crab-check=assert %opts "%s" 2>&1 | OutputCheck -l debug %s // CHECK: ^1 Number of total safe checks$ // CHECK: ^0 Number of total error checks$ // CHECK: ^0 Number of total warning checks$ extern void __VERIFIER_error() __attribute__ ((__noreturn__)); extern char __VERIFIER_nondet_char(void); extern int __VERIFIER_nondet_int(void); extern long __VERIFIER_nondet_long(void); extern void *__VERIFIER_nondet_pointer(void); extern int __VERIFIER_nondet_int(); /* Generated by CIL v. 1.3.6 */ /* print_CIL_Input is true */ int ssl3_connect(int initial_state ) { int s__info_callback = __VERIFIER_nondet_int() ; int s__in_handshake = __VERIFIER_nondet_int() ; int s__state ; int s__new_session ; int s__server ; int s__version = __VERIFIER_nondet_int() ; int s__type ; int s__init_num ; int s__bbio = __VERIFIER_nondet_int() ; int s__wbio = __VERIFIER_nondet_int() ; int s__hit = __VERIFIER_nondet_int() ; int s__rwstate ; int s__init_buf___0 ; int s__debug = __VERIFIER_nondet_int() ; int s__shutdown ; int s__ctx__info_callback = __VERIFIER_nondet_int() ; int s__ctx__stats__sess_connect_renegotiate = __VERIFIER_nondet_int() ; int s__ctx__stats__sess_connect = __VERIFIER_nondet_int() ; int s__ctx__stats__sess_hit = __VERIFIER_nondet_int() ; int s__ctx__stats__sess_connect_good = __VERIFIER_nondet_int() ; int s__s3__change_cipher_spec ; int s__s3__flags ; int s__s3__delay_buf_pop_ret ; int s__s3__tmp__cert_req = __VERIFIER_nondet_int() ; int s__s3__tmp__new_compression = __VERIFIER_nondet_int() ; int s__s3__tmp__reuse_message = __VERIFIER_nondet_int() ; int s__s3__tmp__new_cipher = __VERIFIER_nondet_int() ; int s__s3__tmp__new_cipher__algorithms = __VERIFIER_nondet_int() ; int s__s3__tmp__next_state___0 ; int s__s3__tmp__new_compression__id = __VERIFIER_nondet_int() ; int s__session__cipher ; int s__session__compress_meth ; int buf ; unsigned long tmp ; unsigned long l ; int num1 ; int cb ; int ret ; int new_state ; int state ; int skip ; int tmp___0 ; int tmp___1 = __VERIFIER_nondet_int() ; int tmp___2 = __VERIFIER_nondet_int() ; int tmp___3 = __VERIFIER_nondet_int() ; int tmp___4 = __VERIFIER_nondet_int() ; int tmp___5 = __VERIFIER_nondet_int() ; int tmp___6 = __VERIFIER_nondet_int() ; int tmp___7 = __VERIFIER_nondet_int() ; int tmp___8 = __VERIFIER_nondet_int() ; int tmp___9 = __VERIFIER_nondet_int() ; int blastFlag ; int __cil_tmp55 ; void *__cil_tmp56 ; unsigned long __cil_tmp57 ; unsigned long __cil_tmp58 ; void *__cil_tmp59 ; unsigned long __cil_tmp60 ; unsigned long __cil_tmp61 ; unsigned long __cil_tmp62 ; unsigned long __cil_tmp63 ; unsigned long __cil_tmp64 ; long __cil_tmp65 ; long __cil_tmp66 ; long __cil_tmp67 ; long __cil_tmp68 ; long __cil_tmp69 ; long __cil_tmp70 ; long __cil_tmp71 ; long __cil_tmp72 ; long __cil_tmp73 ; long __cil_tmp74 ; { ; s__state = initial_state; blastFlag = 0; tmp = __VERIFIER_nondet_int(); cb = 0; ret = -1; skip = 0; tmp___0 = 0; if (s__info_callback != 0) { cb = s__info_callback; } else { if (s__ctx__info_callback != 0) { cb = s__ctx__info_callback; } } s__in_handshake ++; if (tmp___1 + 12288) { if (tmp___2 + 16384) { } } { while (1) { while_0_continue: /* CIL Label */ ; state = s__state; if (s__state == 12292) { goto switch_1_12292; } else { if (s__state == 16384) { goto switch_1_16384; } else { if (s__state == 4096) { goto switch_1_4096; } else { if (s__state == 20480) { goto switch_1_20480; } else { if (s__state == 4099) { goto switch_1_4099; } else { if (s__state == 4368) { goto switch_1_4368; } else { if (s__state == 4369) { goto switch_1_4369; } else { if (s__state == 4384) { goto switch_1_4384; } else { if (s__state == 4385) { goto switch_1_4385; } else { if (s__state == 4400) { goto switch_1_4400; } else { if (s__state == 4401) { goto switch_1_4401; } else { if (s__state == 4416) { goto switch_1_4416; } else { if (s__state == 4417) { goto switch_1_4417; } else { if (s__state == 4432) { goto switch_1_4432; } else { if (s__state == 4433) { goto switch_1_4433; } else { if (s__state == 4448) { goto switch_1_4448; } else { if (s__state == 4449) { goto switch_1_4449; } else { if (s__state == 4464) { goto switch_1_4464; } else { if (s__state == 4465) { goto switch_1_4465; } else { if (s__state == 4466) { goto switch_1_4466; } else { if (s__state == 4467) { goto switch_1_4467; } else { if (s__state == 4480) { goto switch_1_4480; } else { if (s__state == 4481) { goto switch_1_4481; } else { if (s__state == 4496) { goto switch_1_4496; } else { if (s__state == 4497) { goto switch_1_4497; } else { if (s__state == 4512) { goto switch_1_4512; } else { if (s__state == 4513) { goto switch_1_4513; } else { if (s__state == 4528) { goto switch_1_4528; } else { if (s__state == 4529) { goto switch_1_4529; } else { if (s__state == 4560) { goto switch_1_4560; } else { if (s__state == 4561) { goto switch_1_4561; } else { if (s__state == 4352) { goto switch_1_4352; } else { if (s__state == 3) { goto switch_1_3; } else { goto switch_1_default; if (0) { switch_1_12292: s__new_session = 1; s__state = 4096; s__ctx__stats__sess_connect_renegotiate ++; switch_1_16384: ; switch_1_4096: ; switch_1_20480: ; switch_1_4099: s__server = 0; if (cb != 0) { } { __cil_tmp55 = s__version + 65280; if (__cil_tmp55 != 768) { ret = -1; goto end; } } s__type = 4096; { __cil_tmp56 = (void *)0; __cil_tmp57 = (unsigned long )__cil_tmp56; __cil_tmp58 = (unsigned long )s__init_buf___0; if (__cil_tmp58 == __cil_tmp57) { buf = __VERIFIER_nondet_int(); { __cil_tmp59 = (void *)0; __cil_tmp60 = (unsigned long )__cil_tmp59; __cil_tmp61 = (unsigned long )buf; if (__cil_tmp61 == __cil_tmp60) { ret = -1; goto end; } } if (! tmp___3) { ret = -1; goto end; } s__init_buf___0 = buf; } } if (! tmp___4) { ret = -1; goto end; } if (! tmp___5) { ret = -1; goto end; } s__state = 4368; s__ctx__stats__sess_connect ++; s__init_num = 0; goto switch_1_break; switch_1_4368: ; switch_1_4369: s__shutdown = 0; ret = __VERIFIER_nondet_int(); if (blastFlag == 0) { blastFlag = 1; } if (ret <= 0) { goto end; } s__state = 4384; s__init_num = 0; { __cil_tmp62 = (unsigned long )s__wbio; __cil_tmp63 = (unsigned long )s__bbio; if (__cil_tmp63 != __cil_tmp62) { } } goto switch_1_break; switch_1_4384: ; switch_1_4385: ret = __VERIFIER_nondet_int(); if (blastFlag == 1) { blastFlag = 2; } else { if (blastFlag == 4) { blastFlag = 5; } } if (ret <= 0) { goto end; } if (s__hit) { s__state = 4560; } else { s__state = 4400; } s__init_num = 0; goto switch_1_break; switch_1_4400: ; switch_1_4401: ; { __cil_tmp64 = (unsigned long )s__s3__tmp__new_cipher__algorithms; if (__cil_tmp64 + 256UL) { skip = 1; } else { ret = __VERIFIER_nondet_int(); if (blastFlag == 2) { blastFlag = 3; } if (ret <= 0) { goto end; } } } s__state = 4416; s__init_num = 0; goto switch_1_break; switch_1_4416: ; switch_1_4417: ret = __VERIFIER_nondet_int(); if (blastFlag == 3) { blastFlag = 4; } if (ret <= 0) { goto end; } s__state = 4432; s__init_num = 0; if (! tmp___6) { ret = -1; goto end; } goto switch_1_break; switch_1_4432: ; switch_1_4433: ret = __VERIFIER_nondet_int(); if (blastFlag == 5) { goto ERROR; } if (ret <= 0) { goto end; } s__state = 4448; s__init_num = 0; goto switch_1_break; switch_1_4448: ; switch_1_4449: ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } if (s__s3__tmp__cert_req) { s__state = 4464; } else { s__state = 4480; } s__init_num = 0; goto switch_1_break; switch_1_4464: ; switch_1_4465: ; switch_1_4466: ; switch_1_4467: ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } s__state = 4480; s__init_num = 0; goto switch_1_break; switch_1_4480: ; switch_1_4481: ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } l = (unsigned long )s__s3__tmp__new_cipher__algorithms; if (s__s3__tmp__cert_req == 1) { s__state = 4496; } else { s__state = 4512; s__s3__change_cipher_spec = 0; } s__init_num = 0; goto switch_1_break; switch_1_4496: ; switch_1_4497: ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } s__state = 4512; s__init_num = 0; s__s3__change_cipher_spec = 0; goto switch_1_break; switch_1_4512: ; switch_1_4513: ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } s__state = 4528; s__init_num = 0; s__session__cipher = s__s3__tmp__new_cipher; if (s__s3__tmp__new_compression == 0) { s__session__compress_meth = 0; } else { s__session__compress_meth = s__s3__tmp__new_compression__id; } if (! tmp___7) { ret = -1; goto end; } if (! tmp___8) { ret = -1; goto end; } goto switch_1_break; switch_1_4528: ; switch_1_4529: ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } s__state = 4352; __cil_tmp65 = (long )s__s3__flags; __cil_tmp66 = __cil_tmp65 - 5; s__s3__flags = (int )__cil_tmp66; if (s__hit) { s__s3__tmp__next_state___0 = 3; { __cil_tmp67 = (long )s__s3__flags; if (__cil_tmp67 + 2L) { s__state = 3; __cil_tmp68 = (long )s__s3__flags; __cil_tmp69 = __cil_tmp68 * 4L; s__s3__flags = (int )__cil_tmp69; s__s3__delay_buf_pop_ret = 0; } } } else { s__s3__tmp__next_state___0 = 4560; } s__init_num = 0; goto switch_1_break; switch_1_4560: ; switch_1_4561: ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } if (s__hit) { s__state = 4512; } else { s__state = 3; } s__init_num = 0; goto switch_1_break; switch_1_4352: { __cil_tmp70 = (long )num1; if (__cil_tmp70 > 0L) { s__rwstate = 2; __cil_tmp71 = (long )tmp___9; num1 = (int )__cil_tmp71; { __cil_tmp72 = (long )num1; if (__cil_tmp72 <= 0L) { ret = -1; goto end; } } s__rwstate = 1; } } s__state = s__s3__tmp__next_state___0; goto switch_1_break; switch_1_3: if (s__init_buf___0 != 0) { s__init_buf___0 = 0; } { __cil_tmp73 = (long )s__s3__flags; __cil_tmp74 = __cil_tmp73 + 4L; if (! __cil_tmp74) { } } s__init_num = 0; s__new_session = 0; if (s__hit) { s__ctx__stats__sess_hit ++; } ret = 1; s__ctx__stats__sess_connect_good ++; if (cb != 0) { } goto end; switch_1_default: ret = -1; goto end; } else { switch_1_break: ; } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } if (! s__s3__tmp__reuse_message) { if (! skip) { if (s__debug) { ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } } if (cb != 0) { if (s__state != state) { new_state = s__state; s__state = state; s__state = new_state; } } } } skip = 0; } while_0_break: /* CIL Label */ ; } end: s__in_handshake --; if (cb != 0) { } return (ret); ERROR: __VERIFIER_error(); return (-1); } } int main(void) { int s ; { { s = 12292; ssl3_connect(s); } return (0); } }
the_stack_data/148883.c
// Conversion of time into words int main(){ int h; scanf("%d",&h); int m; scanf("%d",&m); char *hours[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve"}; char *minutes[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "ninteen", "twenty", "twenty one", "twenty two", "twenty three", "twenty four", "twenty five", "twenty six", "twenty seven", "twenty eight", "twenty nine"}; char *hour; if (m == 0) { hour = hours[h - 1]; printf("%s o' clock", hour); } else if (m == 1) { hour = hours[h - 1]; printf("one minute past %s", hour); } else if (m == 10) { hour = hours[h - 1]; printf("ten minutes past %s", hour); } else if (m == 15) { hour = hours[h - 1]; printf("quarter past %s", hour); } else if (m == 30) { hour = hours[h - 1]; printf("half past %s", hour); } else if (m == 40) { hour = hours[h]; printf("twenty minutes to %s", hour); } else if (m == 45) { hour = hours[h]; printf("quarter to %s", hour); } else if (m < 30) { hour = hours[h - 1]; printf("%s minutes past %s", minutes[m - 1], hour); } else if (m > 30) { hour = hours[h]; printf("%s minutes to %s", minutes[60 - m - 1], hour); } return 0; }
the_stack_data/90766457.c
/* create a student record having name and roll number as structure elements , take user input and display the result. */ #include <stdio.h> struct class{ int roll; char name[20]; }; int main() { struct class student[3]; for(int i=0;i<3;i++){ printf("\nEnter roll and name %d\n",i+1); scanf("%d",&student[i].roll); getchar(); gets(student[i].name); } for(int i=0;i<3;i++){ printf("\n%d\n",student[i].roll); printf(student[i].name); printf("\n"); } }
the_stack_data/31388602.c
/* Programa: lista4b_exerc4.c Autor: Pedro Mateus Melo Ormesino Lins Data: 07/01/2022 Descrição: Aplica desconto no produto de acordo com o tipo de cliente. */ #include <stdio.h> int main() { /* Declaração e inicialização das variáveis. */ float valor = -1.0, desc = 0.0; int cliente = -1; /* Menu principal e blindagem. */ while (1 == 1){ printf("De acordo com o menu abaixo, indique em qual grupo o cliente se encontra: \n\n\t(1) Cliente Comum\n\t(2) Funcionario\n\t(3) VIP\n\n"); scanf("%d", &cliente); while(getchar() != '\n'); if(cliente < 1 || cliente > 3) { printf("ERRO! Tente novamente.\n"); continue; } break; } /* Demonstração do desconto. */ switch (cliente) { case 1: printf("Desconto nao aplicavel.\n"); desc = 0.0; break; case 2: printf("Desconto de 10%% ao valor total do produto.\n"); desc = 0.1; break; case 3: printf("Desconto de 5%% ao valor total do produto."); desc = 0.05; break; } /* Inserção do valor do produto e blindagem. */ while (1 == 1) { printf("Insira o valor do produto: "); scanf("%f", &valor); while(getchar() != '\n'); if(valor < 0) { printf("ERRO! Tente novamente.\n"); continue; } /* Cálculo e impressão do valor com desconto. */ valor -= (valor*desc); printf("O valor com o desconto aplicado fica por: %.2f\n", valor); break; } return 0; }
the_stack_data/184518575.c
#include <stdio.h> #include <stdlib.h> // 没有表头的,初始节点就是head // C语言描述里面是用的这种 struct Node { int data; struct Node *next; }; typedef struct Node node; typedef struct Node *PointNode; // 头结点 在单链表的第一个结点之前附加一个结点,称为头结点。头结点的Data域可以不设任何信息,也可以记录表长等相关信息。若链表是带有头结点的,则头指针指向头结点的存储位置 // 头指针 通常使用“头指针”来标识一个链表,如单链表L,头指针为NULL的时表示一个空链表。链表非空时,头指针指向的是第一个结点的存储位置 // 如何表示一个头指针 // struct Node *PointNode // ====== 初始化空链表 头指针 == NULL // 不带头结点写法 // 初始化空链表 // 1. 传入头指针 头指针代表的是指针指向的下一个结点的存储位置 // 2. 头指针为空 则为空表 PointNode InitList(PointNode headPoint) { headPoint = NULL; return headPoint; } // ====== 初始化空链表 头指针——> 头结点 == NULL // 带头结点写法 // 初始化空链表 // 1. 传入头指针 头指针代表的是指针指向的的下一个结点的存储位置 // 2. 头指针的下一跳为头节点 头结点的 PointNode InitList2(PointNode headPoint){ headPoint = (PointNode)malloc(sizeof(struct Node)); headPoint -> next = NULL; return headPoint; } // 不带头结点写法 // 判断是否为空表 判断第一个普通节点是否为空 // 1. 传入头指针 // 2. 如果头指针为空,则表示为空表 // 空则返回0 ,不空则返回1 int IsEmpty(PointNode headPoint){ if (headPoint == NULL){ return 0; }else { return 1; } } // 带头结点写法 // 判断是否为空表 判断头结点是否为空 // 1. 传入头指针 头指针用来识别一个链表 // 2. 如果头结点是空的话,那该表为空链表 int IsEmpty2(PointNode headPoint){ PointNode head = headPoint -> next; if (head == NULL){ return 0; }else { return 1; } } // 没有头结点写法 // 创建一个单节点的表 // 1. 传入一个空链表,用头指针识别 以及 一个值 // 2. 创建一个新的节点 分配内存并且赋值 // 3. 让头指针指向新的节点,并且新的节点指向NULL // 4. 返回一个头指针类型 PointNode CreateNodeList(PointNode headPoint,int val){ PointNode newNode = (PointNode)malloc(sizeof(struct Node)); newNode -> next = NULL; newNode -> data = val; headPoint -> next = newNode; return headPoint ; } // 有头结点的写法 // 创建一个单节点的表 // 1. 传入一个空链表,用头指针识别以及一个值 // 2. 创建一个新的节点,分配内存并且赋值 // 3. 让头节点指向新的节点,并且新的节点指向NULL // 返回一个指针类型 PointNode CreateNodeList2(PointNode headPoint,int val){ // 根据头指针获取头结点 PointNode head = headPoint -> next; // 创建新的结点 PointNode newnode = (PointNode)malloc(sizeof(struct Node)); newnode -> next = NULL; newnode -> data = val; head -> next = newnode; return headPoint; } int main() { // 创建一个头结点 PointNode headPoint; PointNode hp = InitList(headPoint); int res = IsEmpty(hp); printf("%d",res); // 带头结点 PointNode headPoint2; PointNode hp2 = InitList2(headPoint2); int res2 = IsEmpty2(hp2); printf("%d",res2); }
the_stack_data/121149.c
#include <stdio.h> #include <stdlib.h> #include <assert.h> void mainQ(int y) { int x = -50; while (x < 0) { x = x + y; y++; } //%%%traces: int x, int y //assert(y > 0); } int main(int argc, char *argv[]) { mainQ(atoi(argv[1])); return 0; }
the_stack_data/1217337.c
#include<stdio.h> #include<stdlib.h> double arr1[5120][5120],arr2[5120][5120],res[5120][5120]; int main(int argc, char *argv[]){ if(argc!=2){ printf(" Usage <executable-path> Seedvalue\n"); exit(0); } srand(atoi(argv[1])); for(int i=0;i<5120;i++) for(int j=0;j<5120;j++){ arr1[i][j]= i+j+rand()%1048576+0.5; arr2[i][j]= i+j+rand() %1048576+0.5; } fprintf(stderr, "done"); int B=20; //#pragma omp parallel for for(int ii=0;ii<5120;ii+=B){//loop tiling for(int kk=0;kk<5120;kk+=B){ for(int jj=0;jj<5120;jj+=B){ for(int i=ii;i<ii+B;i++){ for(int k=kk;k<kk+B;k++){ // loop interchange for( int j=jj;j<jj+B;j+=2){//loop unrolling res[i][j]+=arr1[i][k]*arr2[k][j]; res[i][j+1]+=arr1[i][k]*arr2[k][j]; } } } } } } }//end main
the_stack_data/82951386.c
// RUN: %libomp-compile // RUN: env OMP_DISPLAY_AFFINITY=true OMP_AFFINITY_FORMAT='TESTER-ENV: tl:%L tn:%n nt:%N' OMP_NUM_THREADS=8 %libomp-run | %python %S/check.py -c 'CHECK-8' %s #include <stdio.h> #include <stdlib.h> #include <omp.h> int main(int argc, char** argv) { #pragma omp parallel { } #pragma omp parallel { } return 0; } // CHECK-8: num_threads=8 TESTER-ENV: tl:1 tn:[0-7] nt:8
the_stack_data/184517563.c
#include <assert.h> #include <stdlib.h> struct list { int x; struct list *n; }; void main() { struct list *l; struct list *nl1=malloc(sizeof(struct list)); nl1->x=-1; nl1->n=l; l=nl1; struct list *nl2=malloc(sizeof(struct list)); nl2->x=-1; nl2->n=l; l=nl2; struct list *m=l; for(int i=0; i<2; ++i) { m->x=i; m=m->n; } assert(l->n->x==0); assert(l->n->x==1); assert(l->x==2); assert(l->x==1); }
the_stack_data/31387614.c
/* ** EPITECH PROJECT, 2019 ** Memcpy ** File description: ** my_memcpy.c */ #include <stdlib.h> void *my_memcpy(void *dest, const void *src, size_t n) { char *ptr = dest; const char *tmp = src; for (; n > 0; n--) *ptr++ = *tmp++; return (dest); }
the_stack_data/109619.c
char mystring[21];
the_stack_data/178266543.c
// This file can be used to see what a native C compiler is generating for a // variety of interesting operations. // // RUN: %llvmgcc -S %s -o - | llc unsigned int udiv(unsigned int X, unsigned int Y) { return X/Y; } int sdiv(int X, int Y) { return X/Y; } unsigned int urem(unsigned int X, unsigned int Y) { return X%Y; } int srem(int X, int Y) { return X%Y; } _Bool setlt(int X, int Y) { return X < Y; } _Bool setgt(int X, int Y) { return X > Y; }
the_stack_data/147895.c
#include <pthread.h> #include <assert.h> int g = 0; // doesn't matter, gets always overwritten pthread_mutex_t C = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t D = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t E = PTHREAD_MUTEX_INITIALIZER; void *t_fun(void *arg) { pthread_mutex_lock(&C); pthread_mutex_lock(&E); g = 42; pthread_mutex_lock(&D); pthread_mutex_unlock(&E); pthread_mutex_unlock(&C); pthread_mutex_unlock(&D); return NULL; } int main(void) { pthread_t id; pthread_create(&id, NULL, t_fun, NULL); pthread_mutex_lock(&C); pthread_mutex_lock(&D); g = 2; pthread_mutex_unlock(&C); pthread_mutex_lock(&E); assert(g == 2); // TODO return 0; }
the_stack_data/25136474.c
#include <string.h> #undef memmove void * memmove(void *dst, const void *src, size_t n) { char *d = dst, *s = (char *) src; if (d < s) { while (n-- > 0) *d++ = *s++; } else { s += n-1, d += n-1; while (n-- > 0) *d-- = *s--; } return dst; }
the_stack_data/852849.c
/** \file algo/swstate/auto_generated/diagnostic/phantom_queues_diagnostic.c * * sw state functions definitions * * DO NOT EDIT THIS FILE! * This file is auto-generated. * Edits to this file will be lost when it is regenerated. */ /* * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ #ifdef BSL_LOG_MODULE #error "BSL_LOG_MODULE redefined" #endif #define BSL_LOG_MODULE BSL_LS_SWSTATEDNX_GENERAL #ifdef BCM_DNX_SUPPORT #include <soc/dnxc/swstate/dnxc_sw_state_c_includes.h> #include <bcm_int/dnx/algo/swstate/auto_generated/diagnostic/phantom_queues_diagnostic.h> #include <bcm_int/dnx/cosq/egress/phantom_queues.h> #include <soc/dnx/dnx_data/auto_generated/dnx_data_max_device.h> #if defined(DNX_SW_STATE_DIAGNOSTIC) /* * Global Variables */ extern dnx_phantom_queues_db_t * dnx_phantom_queues_db_data[SOC_MAX_NUM_DEVICES]; /* * FUNCTIONs */ /* * * dump function for the variable dnx_phantom_queues_db * AUTO-GENERATED - DO NOT MODIFY */ int dnx_phantom_queues_db_dump(int unit, dnx_sw_state_dump_filters_t filters) { DNXC_SW_STATE_INIT_FUNC_DEFS; SHR_IF_ERR_EXIT(dnx_phantom_queues_db_phantom_queues_dump(unit, -1, filters)); DNXC_SW_STATE_FUNC_RETURN; } /* * * dump function for the variable phantom_queues * AUTO-GENERATED - DO NOT MODIFY */ int dnx_phantom_queues_db_phantom_queues_dump(int unit, int phantom_queues_idx_0, dnx_sw_state_dump_filters_t filters) { int i0 = phantom_queues_idx_0, I0 = phantom_queues_idx_0 + 1; char *s0 = ""; DNXC_SW_STATE_INIT_FUNC_DEFS; if (dnx_sw_state_compare(filters.typefilter, "dnx_algo_template_t") != TRUE) { SHR_EXIT(); } if (dnx_sw_state_compare(filters.namefilter, "phantom_queues phantom_queues") != TRUE) { SHR_EXIT(); } if (filters.nocontent) { DNX_SW_STATE_PRINT(unit, "swstate phantom_queues phantom_queues\n"); } else { dnx_sw_state_dump_attach_file( unit, "dnx_phantom_queues_db/phantom_queues.txt", "dnx_phantom_queues_db[%d]->","((dnx_phantom_queues_db_t*)sw_state_roots_array[%d][PHANTOM_QUEUES_MODULE_ID])->","phantom_queues[]: "); DNX_SW_STATE_DUMP_PTR_NULL_CHECK( unit, ((dnx_phantom_queues_db_t*)sw_state_roots_array[unit][PHANTOM_QUEUES_MODULE_ID])); if (i0 == -1) { I0 = DNX_DATA_MAX_DEVICE_GENERAL_NOF_CORES; i0 = dnx_sw_state_dump_check_all_the_same(unit, ((dnx_phantom_queues_db_t*)sw_state_roots_array[unit][PHANTOM_QUEUES_MODULE_ID])->phantom_queues , sizeof(*((dnx_phantom_queues_db_t*)sw_state_roots_array[unit][PHANTOM_QUEUES_MODULE_ID])->phantom_queues), I0, &s0) ? I0 - 1 : 0; } if(i0 >= DNX_DATA_MAX_DEVICE_GENERAL_NOF_CORES) { LOG_CLI((BSL_META("dnx_phantom_queues_db[]->((dnx_phantom_queues_db_t*)sw_state_roots_array[][PHANTOM_QUEUES_MODULE_ID])->phantom_queues[]: "))); LOG_CLI((BSL_META("Invalid index: %d \n"),i0)); SHR_EXIT(); } if(DNX_DATA_MAX_DEVICE_GENERAL_NOF_CORES == 0) { SHR_EXIT(); } for(; i0 < I0; i0++) { dnx_sw_state_dump_update_current_idx(unit, i0); DNX_SW_STATE_PRINT_MONITOR( unit, "dnx_phantom_queues_db[%d]->","((dnx_phantom_queues_db_t*)sw_state_roots_array[%d][PHANTOM_QUEUES_MODULE_ID])->","phantom_queues[%s%d]: ", s0, i0); DNX_SW_STATE_PRINT_FILE( unit, "[%s%d]: ", s0, i0); DNX_ALGO_TEMP_MNGR_PRINT( unit, PHANTOM_QUEUES_MODULE_ID, &((dnx_phantom_queues_db_t*)sw_state_roots_array[unit][PHANTOM_QUEUES_MODULE_ID])->phantom_queues[i0], dnx_cosq_ohantom_queues_profile_print_cb); } dnx_sw_state_dump_end_of_stride(unit); dnx_sw_state_dump_detach_file( unit); } DNXC_SW_STATE_FUNC_RETURN; } /* * Global Variables */ dnx_sw_state_diagnostic_info_t dnx_phantom_queues_db_info[SOC_MAX_NUM_DEVICES][DNX_PHANTOM_QUEUES_DB_INFO_NOF_ENTRIES]; const char* dnx_phantom_queues_db_layout_str[DNX_PHANTOM_QUEUES_DB_INFO_NOF_ENTRIES] = { "DNX_PHANTOM_QUEUES_DB~", "DNX_PHANTOM_QUEUES_DB~PHANTOM_QUEUES~", }; #endif /* DNX_SW_STATE_DIAGNOSTIC */ #endif /* BCM_DNX_SUPPORT*/ #undef BSL_LOG_MODULE
the_stack_data/248581391.c
// // dishizhang1.c // dishizhang // // Created by mingyue on 15/10/28. // Copyright © 2015年 G. All rights reserved. // #include <stdio.h> #define MONTHS 12 int main(int argc, const char* argv[]){ int days[MONTHS] = {31,28,[4] = 31,30,31,[1] = 29}; int i; for (i = 0; i < MONTHS; i++) { printf("%2d %d\n",i + 1, days[i]); } return 0; }
the_stack_data/20450890.c
static void foo() { /* This is the second foo function, but it should not conflict with the other foo function because they are not in the same file */ ; }
the_stack_data/108591.c
// RUN: %clang_cc1 -emit-llvm -o - %s // <rdar://problem/6108358> /* For posterity, the issue here begins initial "char []" decl for * s. This is a tentative definition and so a global was being * emitted, however the mapping in GlobalDeclMap referred to a bitcast * of this global. * * The problem was that later when the correct definition for s is * emitted we were doing a RAUW on the old global which was destroying * the bitcast in the GlobalDeclMap (since it cannot be replaced * properly), leaving a dangling pointer. * * The purpose of bar is just to trigger a use of the old decl * sometime after the dangling pointer has been introduced. */ char s[]; static void bar(void *db) { eek(s); } char s[5] = "hi"; int foo(void) { bar(0); }
the_stack_data/27766.c
// determining the sum of digits #include<stdio.h> int main() { int a,b,i,j,s,num; scanf("%d %d",&a,&b); for(i=a;i<=b;i++) { num=i; s=0; while(num!=0) { j=num%10; num=num/10; s=s*10 + j; } if(i==s) // if(!(i==s))----for not palindrom----if(i!=s) printf("%d ",i); } return 0; }
the_stack_data/248580019.c
/* * ============================ ic ===================== * IC sets the initial condition * ATMS 502 / CSE 566, Spring 2016 * * Arguments: * * q1 real array IC data. Set 1..nx here; * [0],[nx+1] = ghost zones * if 1 ghost point on each side * dx real grid spacing * i1,i2 integers indices bounding array data * nx integer number of grid points * */ void ic(q,u,v,dx,dy,i1,i2,j1,j2,nx,ny,x0,y0,BC_WIDTH) int i1,i2,j1,j2,nx,ny,BC_WIDTH; float dx,dy,q[][ny],u[][ny-2*BC_WIDTH],v[][ny-2*BC_WIDTH+1],x0,y0; { #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #define xstart 0.0 #define ystart -0.05 int i,j; float x[nx-2*BC_WIDTH+1],y[ny-2*BC_WIDTH+1],d[nx][ny]; float r=0.165; for (i=0;i<=i2-i1+1;i++ ) /*x*/ { x[i]=x0+dx*(i)-dx/2; } for (j=0;j<=j2-j1+1;j++ ) /*y*/ { y[j]=y0+dy*(j)-dy/2; } for (i=0;i<=i2-i1+1;i++ ) /*u*/ for (j=0;j<j2-j1+1;j++ ) { u[i][j]=sin(5*M_PI*x[i])*sin(5*M_PI*(y[j]+dy/2)); } for (j=0;j<=j2-j1+1;j++ ) /*v*/ for (i=0;i<i2-i1+1;i++ ) { v[i][j]=cos(5*M_PI*(x[i]+dx/2))*cos(5*M_PI*y[j]); } for (i=i1;i<=i2;i++) /*q*/ { for (j=j1;j<=j2;j++) { /*d[i][j]=sqrt(pow(x[i-i1]+dx/2-xstart,2.0)+pow(y[j-j1]+dy/2-ystart,2.0)); if (d[i][j]<r) {q[i][j]=5*(1+cos(M_PI*d[i][j]/r));}*/ if (((x[i-i1]+dx/2)>=-0.020 && (x[i-i1]+dx/2)<=0.020 && (y[j-j1]+dy/2)>=-0.25 && (y[j-j1]+dy/2)<=0.25) ||\ ((x[i-i1]+dx/2)>=-0.30 && (x[i-i1]+dx/2)<=0.30 && (y[j-j1]+dy/2)>=-0.25 && (y[j-j1]+dy/2)<=-0.22) ||\ ((x[i-i1]+dx/2)>=-0.30 && (x[i-i1]+dx/2)<=0.30 && (y[j-j1]+dy/2)>=0.22 && (y[j-j1]+dy/2)<=0.25)) { q[i][j]=10.0; } else {q[i][j]=0;} } } return; }
the_stack_data/1270963.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); #include <stdio.h> #include <pthread.h> unsigned int __VERIFIER_nondet_uint(); static int top = 0; static unsigned int arr[400]; pthread_mutex_t m; _Bool flag = 0; void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { top == 0 ? 1 : 0; } int push(unsigned int *stack, int x) { if (top == 400) { printf("stack overflow\n"); return -1; } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top() == 0) { printf("stack underflow\n"); return -2; } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for (i = 0; i < 400; i++) { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint() % 400; if (push(arr, tmp) == (-1)) error(); flag = 1; pthread_mutex_unlock(&m); } } } void *t2(void *arg) { int i; for (i = 0; i < 400; i++) { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr) != (-2))) error(); } pthread_mutex_unlock(&m); } } } int main(void) { pthread_t id1; pthread_t id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
the_stack_data/131013.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> void TD_Char_Allocation(int number_of_rows, const char * format, ...) { va_list arguments; va_start(arguments, format); if (!strcmp(format, "char")) { char *** ptr = va_arg(arguments, char***); *ptr = calloc(number_of_rows, sizeof(char*)); for (int i = 0; i < number_of_rows; ++i) (*ptr)[i] = calloc(number_of_rows, ++i); } va_end(arguments); return; } int main() { char ** ptr = NULL; TD_Char_Allocation(10, "char", &ptr); printf("Freeing..\n"); for (int i = 0; i < 10; ++i) if (ptr[i]) free(ptr[i]); if (ptr) free(ptr); return 0; }
the_stack_data/116755.c
#include <stdint.h> #include <stdio.h> void main() { int64_t a; }
the_stack_data/212643307.c
void foo(void); void foo(void) { char c = 1 > 2; }
the_stack_data/154827872.c
#include <stdio.h> #include <stdlib.h> void scilab_rt_graduate_d0d0d0_d0d0d0(double scalarin0, double scalarin1, double scalarin2, double* scalarout0, double* scalarout1, double* scalarout2) { printf("%f", scalarin0); printf("%f", scalarin1); printf("%f", scalarin2); *scalarout0 = rand(); *scalarout1 = rand(); *scalarout2 = rand(); }
the_stack_data/150143300.c
/* zippo2.c -- zippo info via a pointer variable */ #include <stdio.h> int main(void) { int zippo[4][2] = { {2,4}, {6,8}, {1,3}, {5, 7} }; int (*pz)[2]; pz = zippo; printf(" pz = %p, pz + 1 = %p\n", pz, pz + 1); printf("pz[0] = %p, pz[0] + 1 = %p\n", pz[0], pz[0] + 1); printf(" *pz = %p, *pz + 1 = %p\n", *pz, *pz + 1); printf("pz[0][0] = %d\n", pz[0][0]); printf(" *pz[0] = %d\n", *pz[0]); printf(" **pz = %d\n", **pz); printf(" pz[2][1] = %d\n", pz[2][1]); printf("*(*(pz+2) + 1) = %d\n", *(*(pz+2) + 1)); return 0; }
the_stack_data/170452805.c
#include <stdio.h> int fib(int n) { if (n == 0 || n == 1) { return n; } return fib(n - 1) + fib(n - 2); } int main(void) { int a; scanf("%d", &a); int fib_number = fib(a); if (fib_number > 0) goto test; else if (fib_number == 5) goto error; test: printf("fib number is %d", fib_number); error: return -1; return 0; }
the_stack_data/23574220.c
#include <stdio.h> #include <omp.h> int main() { int chaos = 10000; int bound = 10; int i; // RNG will purposefully cause concurrency hazard // by incrementing this variable long hazard = 0; #pragma omp parallel for schedule(guided) for (i = 0; i < chaos; i++) hazard++; printf("%ld\n", hazard % bound); }
the_stack_data/150142088.c
/* Public domain. */ #include <stdio.h> #include <stdlib.h> #include <signal.h> void nope() { exit(1); } int main() { unsigned long x[4]; unsigned long y[4]; int i; int j; char c; signal(SIGILL,nope); x[0] = 0; x[1] = 0; x[2] = 0; x[3] = 0; y[0] = 0; y[1] = 0; y[2] = 0; y[3] = 0; asm volatile(".byte 15;.byte 162" : "=a"(x[0]),"=b"(x[1]),"=c"(x[3]),"=d"(x[2]) : "0"(0) ); if (!x[0]) return 0; asm volatile(".byte 15;.byte 162" : "=a"(y[0]),"=b"(y[1]),"=c"(y[2]),"=d"(y[3]) : "0"(1) ); for (i = 1;i < 4;++i) for (j = 0;j < 4;++j) { c = x[i] >> (8 * j); if (c < 32) c = 32; if (c > 126) c = 126; putchar(c); } printf("-%08lx-%08lx\n",y[0],y[3]); return 0; }
the_stack_data/40761839.c
void cambio(int*x, int*y) { int a; a=*x; *x=*y; *y=a; return; } void imprime(int a[],int n){ int i; for(i=0;i<n;i++){ printf("%d\n", a[i]); } return; } /* for(j=0;j<n-1;j++){ if(j>j+1){ } */
the_stack_data/961365.c
/* * wifi.c * Author: ITAMS - Group 9 */
the_stack_data/179831738.c
/* gcc -std=c17 -lc -lm -pthread -o ../_build/c/numeric_math_modf_1.exe ./c/numeric_math_modf_1.c && (cd ../_build/c/;./numeric_math_modf_1.exe) https://en.cppreference.com/w/c/numeric/math/modf */ #include <stdio.h> #include <math.h> #include <float.h> int main(void) { double f = 123.45; printf("Given the number %.2f or %a in hex,\n", f, f); double f3; double f2 = modf(f, &f3); printf("modf() makes %.2f + %.2f\n", f3, f2); int i; f2 = frexp(f, &i); printf("frexp() makes %f * 2^%d\n", f2, i); i = ilogb(f); printf("logb()/ilogb() make %f * %d^%d\n", f/scalbn(1.0, i), FLT_RADIX, i); // special values f2 = modf(-0.0, &f3); printf("modf(-0) makes %.2f + %.2f\n", f3, f2); f2 = modf(-INFINITY, &f3); printf("modf(-Inf) makes %.2f + %.2f\n", f3, f2); }
the_stack_data/218894469.c
#include <stdio.h> int main() { int a; int b = 12; int c; scanf("%d",&a); c = a; a = b; b = c; printf("a = %d , b = %d \n",a,b); return 0; }
the_stack_data/43887612.c
#include<stdio.h> #include<stdlib.h> int main() { int n,i=0,x; printf("Enter the total number of integers to be read : "); scanf("%d",&n); int a[n]; while(n--) { printf("Give next element as input : "); scanf("%d",&x); if(i==0) { printf("Median after first element : "); printf("%d\n",x); a[i] = x; } else { int pos=0; int lo=0,hi=i+1,mid=lo+(hi-lo)/2,j; while(lo<=hi) { mid=lo+(hi-lo)/2; if(x>a[mid]) { lo = mid+1; } else { pos=mid; hi = mid-1; } } if(a[pos]<x) pos++; for(j=i+1;j>pos;j--) { a[j]=a[j-1]; } a[pos]=x; if((i+1)%2==0) { printf("Median after first %d elements : ",i+1); printf("%.2f\n",(a[(i+1)/2] + a[(i+1)/2 - 1])/2.0); } else { printf("Median after first %d elements : ",i+1); printf("%d\n",a[(i+1)/2]); } } i++; } return 0; }
the_stack_data/220454692.c
#include<stdio.h> # define MAX 50 int main() { int i,j; int a[MAX][MAX]; int aro,acol; printf("enter rows and columns of mat a"); scanf("%d %d",&aro,&acol); printf("enter matrix a elemnts:"); for(i=0;i<aro;i++) { for(j=0;j<acol;i++) { scanf("%d",&a[i][j]); } } int b[MAX][MAX]; int bro,bcol; printf("enter rows and columns of mat b"); scanf("%d %d",&bro,&bcol); if(bro!=acol) { printf("sorry multiplication not possible"); } else{ printf("enter matrix b elemnts:"); for(i=0;i<bro;i++) { for(j=0;j<bcol;i++) { scanf("%d",&b[i][j]); } } int product[MAX][MAX]; int sum=0,k; for(i=0;i<aro;i++) { for(j=0;j<bcol;j++) { for(k=0;k<bro;k++) { sum+=a[i][k]*b[k][j]; } } } } }
the_stack_data/156392131.c
// INFO: task hung in pipe_write // https://syzkaller.appspot.com/bug?id=eb4579cce1e26940e2e1 // status:0 // 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 <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/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> static 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 bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } struct nlmsg { char* pos; int nesting; struct nlattr* nested[8]; char buf[1024]; }; static struct nlmsg nlmsg; static void netlink_init(struct nlmsg* nlmsg, int typ, int flags, const void* data, int size) { memset(nlmsg, 0, sizeof(*nlmsg)); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf; hdr->nlmsg_type = typ; hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags; memcpy(hdr + 1, data, size); nlmsg->pos = (char*)(hdr + 1) + NLMSG_ALIGN(size); } static void netlink_attr(struct nlmsg* nlmsg, int typ, const void* data, int size) { struct nlattr* attr = (struct nlattr*)nlmsg->pos; attr->nla_len = sizeof(*attr) + size; attr->nla_type = typ; memcpy(attr + 1, data, size); nlmsg->pos += NLMSG_ALIGN(attr->nla_len); } static void netlink_nest(struct nlmsg* nlmsg, int typ) { struct nlattr* attr = (struct nlattr*)nlmsg->pos; attr->nla_type = typ; nlmsg->pos += sizeof(*attr); nlmsg->nested[nlmsg->nesting++] = attr; } static void netlink_done(struct nlmsg* nlmsg) { struct nlattr* attr = nlmsg->nested[--nlmsg->nesting]; attr->nla_len = nlmsg->pos - (char*)attr; } static int netlink_send_ext(struct nlmsg* nlmsg, int sock, uint16_t reply_type, int* reply_len) { if (nlmsg->pos > nlmsg->buf + sizeof(nlmsg->buf) || nlmsg->nesting) exit(1); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf; hdr->nlmsg_len = nlmsg->pos - nlmsg->buf; struct sockaddr_nl addr; memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; unsigned n = sendto(sock, nlmsg->buf, hdr->nlmsg_len, 0, (struct sockaddr*)&addr, sizeof(addr)); if (n != hdr->nlmsg_len) exit(1); n = recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); if (hdr->nlmsg_type == NLMSG_DONE) { *reply_len = 0; return 0; } if (n < sizeof(struct nlmsghdr)) exit(1); if (reply_len && hdr->nlmsg_type == reply_type) { *reply_len = n; return 0; } if (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr)) exit(1); if (hdr->nlmsg_type != NLMSG_ERROR) exit(1); return -((struct nlmsgerr*)(hdr + 1))->error; } static int netlink_send(struct nlmsg* nlmsg, int sock) { return netlink_send_ext(nlmsg, sock, 0, NULL); } static int netlink_next_msg(struct nlmsg* nlmsg, unsigned int offset, unsigned int total_len) { struct nlmsghdr* hdr = (struct nlmsghdr*)(nlmsg->buf + offset); if (offset == total_len || offset + hdr->nlmsg_len > total_len) return -1; return hdr->nlmsg_len; } static void netlink_add_device_impl(struct nlmsg* nlmsg, const char* type, const char* name) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); netlink_init(nlmsg, RTM_NEWLINK, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); if (name) netlink_attr(nlmsg, IFLA_IFNAME, name, strlen(name)); netlink_nest(nlmsg, IFLA_LINKINFO); netlink_attr(nlmsg, IFLA_INFO_KIND, type, strlen(type)); } static void netlink_add_device(struct nlmsg* nlmsg, int sock, const char* type, const char* name) { netlink_add_device_impl(nlmsg, type, name); netlink_done(nlmsg); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_add_veth(struct nlmsg* nlmsg, int sock, const char* name, const char* peer) { netlink_add_device_impl(nlmsg, "veth", name); netlink_nest(nlmsg, IFLA_INFO_DATA); netlink_nest(nlmsg, VETH_INFO_PEER); nlmsg->pos += sizeof(struct ifinfomsg); netlink_attr(nlmsg, IFLA_IFNAME, peer, strlen(peer)); netlink_done(nlmsg); netlink_done(nlmsg); netlink_done(nlmsg); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_add_hsr(struct nlmsg* nlmsg, int sock, const char* name, const char* slave1, const char* slave2) { netlink_add_device_impl(nlmsg, "hsr", name); netlink_nest(nlmsg, IFLA_INFO_DATA); int ifindex1 = if_nametoindex(slave1); netlink_attr(nlmsg, IFLA_HSR_SLAVE1, &ifindex1, sizeof(ifindex1)); int ifindex2 = if_nametoindex(slave2); netlink_attr(nlmsg, IFLA_HSR_SLAVE2, &ifindex2, sizeof(ifindex2)); netlink_done(nlmsg); netlink_done(nlmsg); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_add_linked(struct nlmsg* nlmsg, int sock, const char* type, const char* name, const char* link) { netlink_add_device_impl(nlmsg, type, name); netlink_done(nlmsg); int ifindex = if_nametoindex(link); netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex)); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_add_vlan(struct nlmsg* nlmsg, int sock, const char* name, const char* link, uint16_t id, uint16_t proto) { netlink_add_device_impl(nlmsg, "vlan", name); netlink_nest(nlmsg, IFLA_INFO_DATA); netlink_attr(nlmsg, IFLA_VLAN_ID, &id, sizeof(id)); netlink_attr(nlmsg, IFLA_VLAN_PROTOCOL, &proto, sizeof(proto)); netlink_done(nlmsg); netlink_done(nlmsg); int ifindex = if_nametoindex(link); netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex)); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_add_macvlan(struct nlmsg* nlmsg, int sock, const char* name, const char* link) { netlink_add_device_impl(nlmsg, "macvlan", name); netlink_nest(nlmsg, IFLA_INFO_DATA); uint32_t mode = MACVLAN_MODE_BRIDGE; netlink_attr(nlmsg, IFLA_MACVLAN_MODE, &mode, sizeof(mode)); netlink_done(nlmsg); netlink_done(nlmsg); int ifindex = if_nametoindex(link); netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex)); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_add_geneve(struct nlmsg* nlmsg, int sock, const char* name, uint32_t vni, struct in_addr* addr4, struct in6_addr* addr6) { netlink_add_device_impl(nlmsg, "geneve", name); netlink_nest(nlmsg, IFLA_INFO_DATA); netlink_attr(nlmsg, IFLA_GENEVE_ID, &vni, sizeof(vni)); if (addr4) netlink_attr(nlmsg, IFLA_GENEVE_REMOTE, addr4, sizeof(*addr4)); if (addr6) netlink_attr(nlmsg, IFLA_GENEVE_REMOTE6, addr6, sizeof(*addr6)); netlink_done(nlmsg); netlink_done(nlmsg); int err = netlink_send(nlmsg, sock); (void)err; } #define IFLA_IPVLAN_FLAGS 2 #define IPVLAN_MODE_L3S 2 #undef IPVLAN_F_VEPA #define IPVLAN_F_VEPA 2 static void netlink_add_ipvlan(struct nlmsg* nlmsg, int sock, const char* name, const char* link, uint16_t mode, uint16_t flags) { netlink_add_device_impl(nlmsg, "ipvlan", name); netlink_nest(nlmsg, IFLA_INFO_DATA); netlink_attr(nlmsg, IFLA_IPVLAN_MODE, &mode, sizeof(mode)); netlink_attr(nlmsg, IFLA_IPVLAN_FLAGS, &flags, sizeof(flags)); netlink_done(nlmsg); netlink_done(nlmsg); int ifindex = if_nametoindex(link); netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex)); int err = netlink_send(nlmsg, sock); (void)err; } static void netlink_device_change(struct nlmsg* nlmsg, int sock, const char* name, bool up, const char* master, const void* mac, int macsize, const char* new_name) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); if (up) hdr.ifi_flags = hdr.ifi_change = IFF_UP; hdr.ifi_index = if_nametoindex(name); netlink_init(nlmsg, RTM_NEWLINK, 0, &hdr, sizeof(hdr)); if (new_name) netlink_attr(nlmsg, IFLA_IFNAME, new_name, strlen(new_name)); if (master) { int ifindex = if_nametoindex(master); netlink_attr(nlmsg, IFLA_MASTER, &ifindex, sizeof(ifindex)); } if (macsize) netlink_attr(nlmsg, IFLA_ADDRESS, mac, macsize); int err = netlink_send(nlmsg, sock); (void)err; } static int netlink_add_addr(struct nlmsg* nlmsg, int sock, const char* dev, const void* addr, int addrsize) { struct ifaddrmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ifa_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ifa_prefixlen = addrsize == 4 ? 24 : 120; hdr.ifa_scope = RT_SCOPE_UNIVERSE; hdr.ifa_index = if_nametoindex(dev); netlink_init(nlmsg, RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, &hdr, sizeof(hdr)); netlink_attr(nlmsg, IFA_LOCAL, addr, addrsize); netlink_attr(nlmsg, IFA_ADDRESS, addr, addrsize); return netlink_send(nlmsg, sock); } static void netlink_add_addr4(struct nlmsg* nlmsg, int sock, const char* dev, const char* addr) { struct in_addr in_addr; inet_pton(AF_INET, addr, &in_addr); int err = netlink_add_addr(nlmsg, sock, dev, &in_addr, sizeof(in_addr)); (void)err; } static void netlink_add_addr6(struct nlmsg* nlmsg, int sock, const char* dev, const char* addr) { struct in6_addr in6_addr; inet_pton(AF_INET6, addr, &in6_addr); int err = netlink_add_addr(nlmsg, sock, dev, &in6_addr, sizeof(in6_addr)); (void)err; } 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; #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 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; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) { exit(1); } 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); } #define DEVLINK_FAMILY_NAME "devlink" #define DEVLINK_CMD_PORT_GET 5 #define DEVLINK_ATTR_BUS_NAME 1 #define DEVLINK_ATTR_DEV_NAME 2 #define DEVLINK_ATTR_NETDEV_NAME 7 static int netlink_devlink_id_get(struct nlmsg* nlmsg, int sock) { struct genlmsghdr genlhdr; struct nlattr* attr; int err, n; uint16_t id = 0; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = CTRL_CMD_GETFAMILY; netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, DEVLINK_FAMILY_NAME, strlen(DEVLINK_FAMILY_NAME) + 1); err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n); if (err) { return -1; } attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(genlhdr))); for (; (char*)attr < nlmsg->buf + n; attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) { if (attr->nla_type == CTRL_ATTR_FAMILY_ID) { id = *(uint16_t*)(attr + 1); break; } } if (!id) { return -1; } recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); /* recv ack */ return id; } static struct nlmsg nlmsg2; static void initialize_devlink_ports(const char* bus_name, const char* dev_name, const char* netdev_prefix) { struct genlmsghdr genlhdr; int len, total_len, id, err, offset; uint16_t netdev_index; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC); if (sock == -1) exit(1); int rtsock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (rtsock == -1) exit(1); id = netlink_devlink_id_get(&nlmsg, sock); if (id == -1) goto error; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = DEVLINK_CMD_PORT_GET; netlink_init(&nlmsg, id, NLM_F_DUMP, &genlhdr, sizeof(genlhdr)); netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1); netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1); err = netlink_send_ext(&nlmsg, sock, id, &total_len); if (err) { goto error; } offset = 0; netdev_index = 0; while ((len = netlink_next_msg(&nlmsg, offset, total_len)) != -1) { struct nlattr* attr = (struct nlattr*)(nlmsg.buf + offset + NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(genlhdr))); for (; (char*)attr < nlmsg.buf + offset + len; attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) { if (attr->nla_type == DEVLINK_ATTR_NETDEV_NAME) { char* port_name; char netdev_name[IFNAMSIZ]; port_name = (char*)(attr + 1); snprintf(netdev_name, sizeof(netdev_name), "%s%d", netdev_prefix, netdev_index); netlink_device_change(&nlmsg2, rtsock, port_name, true, 0, 0, 0, netdev_name); break; } } offset += len; netdev_index++; } error: close(rtsock); close(sock); } #define DEV_IPV4 "172.20.20.%d" #define DEV_IPV6 "fe80::%02x" #define DEV_MAC 0x00aaaaaaaaaa static void netdevsim_add(unsigned int addr, unsigned int port_count) { char buf[16]; sprintf(buf, "%u %u", addr, port_count); if (write_file("/sys/bus/netdevsim/new_device", buf)) { snprintf(buf, sizeof(buf), "netdevsim%d", addr); initialize_devlink_ports("netdevsim", buf, "netdevsim"); } } #define WG_GENL_NAME "wireguard" enum wg_cmd { WG_CMD_GET_DEVICE, WG_CMD_SET_DEVICE, }; enum wgdevice_attribute { WGDEVICE_A_UNSPEC, WGDEVICE_A_IFINDEX, WGDEVICE_A_IFNAME, WGDEVICE_A_PRIVATE_KEY, WGDEVICE_A_PUBLIC_KEY, WGDEVICE_A_FLAGS, WGDEVICE_A_LISTEN_PORT, WGDEVICE_A_FWMARK, WGDEVICE_A_PEERS, }; enum wgpeer_attribute { WGPEER_A_UNSPEC, WGPEER_A_PUBLIC_KEY, WGPEER_A_PRESHARED_KEY, WGPEER_A_FLAGS, WGPEER_A_ENDPOINT, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, WGPEER_A_LAST_HANDSHAKE_TIME, WGPEER_A_RX_BYTES, WGPEER_A_TX_BYTES, WGPEER_A_ALLOWEDIPS, WGPEER_A_PROTOCOL_VERSION, }; enum wgallowedip_attribute { WGALLOWEDIP_A_UNSPEC, WGALLOWEDIP_A_FAMILY, WGALLOWEDIP_A_IPADDR, WGALLOWEDIP_A_CIDR_MASK, }; static int netlink_wireguard_id_get(struct nlmsg* nlmsg, int sock) { struct genlmsghdr genlhdr; struct nlattr* attr; int err, n; uint16_t id = 0; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = CTRL_CMD_GETFAMILY; netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, WG_GENL_NAME, strlen(WG_GENL_NAME) + 1); err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n); if (err) { return -1; } attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(genlhdr))); for (; (char*)attr < nlmsg->buf + n; attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) { if (attr->nla_type == CTRL_ATTR_FAMILY_ID) { id = *(uint16_t*)(attr + 1); break; } } if (!id) { return -1; } recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); /* recv ack */ return id; } static void netlink_wireguard_setup(void) { const char ifname_a[] = "wg0"; const char ifname_b[] = "wg1"; const char ifname_c[] = "wg2"; const char private_a[] = "\xa0\x5c\xa8\x4f\x6c\x9c\x8e\x38\x53\xe2\xfd\x7a\x70\xae\x0f\xb2\x0f\xa1" "\x52\x60\x0c\xb0\x08\x45\x17\x4f\x08\x07\x6f\x8d\x78\x43"; const char private_b[] = "\xb0\x80\x73\xe8\xd4\x4e\x91\xe3\xda\x92\x2c\x22\x43\x82\x44\xbb\x88\x5c" "\x69\xe2\x69\xc8\xe9\xd8\x35\xb1\x14\x29\x3a\x4d\xdc\x6e"; const char private_c[] = "\xa0\xcb\x87\x9a\x47\xf5\xbc\x64\x4c\x0e\x69\x3f\xa6\xd0\x31\xc7\x4a\x15" "\x53\xb6\xe9\x01\xb9\xff\x2f\x51\x8c\x78\x04\x2f\xb5\x42"; const char public_a[] = "\x97\x5c\x9d\x81\xc9\x83\xc8\x20\x9e\xe7\x81\x25\x4b\x89\x9f\x8e\xd9\x25" "\xae\x9f\x09\x23\xc2\x3c\x62\xf5\x3c\x57\xcd\xbf\x69\x1c"; const char public_b[] = "\xd1\x73\x28\x99\xf6\x11\xcd\x89\x94\x03\x4d\x7f\x41\x3d\xc9\x57\x63\x0e" "\x54\x93\xc2\x85\xac\xa4\x00\x65\xcb\x63\x11\xbe\x69\x6b"; const char public_c[] = "\xf4\x4d\xa3\x67\xa8\x8e\xe6\x56\x4f\x02\x02\x11\x45\x67\x27\x08\x2f\x5c" "\xeb\xee\x8b\x1b\xf5\xeb\x73\x37\x34\x1b\x45\x9b\x39\x22"; const uint16_t listen_a = 20001; const uint16_t listen_b = 20002; const uint16_t listen_c = 20003; const uint16_t af_inet = AF_INET; const uint16_t af_inet6 = AF_INET6; /* Unused, but useful in case we change this: const struct sockaddr_in endpoint_a_v4 = { .sin_family = AF_INET, .sin_port = htons(listen_a), .sin_addr = {htonl(INADDR_LOOPBACK)}};*/ const struct sockaddr_in endpoint_b_v4 = { .sin_family = AF_INET, .sin_port = htons(listen_b), .sin_addr = {htonl(INADDR_LOOPBACK)}}; const struct sockaddr_in endpoint_c_v4 = { .sin_family = AF_INET, .sin_port = htons(listen_c), .sin_addr = {htonl(INADDR_LOOPBACK)}}; struct sockaddr_in6 endpoint_a_v6 = {.sin6_family = AF_INET6, .sin6_port = htons(listen_a)}; endpoint_a_v6.sin6_addr = in6addr_loopback; /* Unused, but useful in case we change this: const struct sockaddr_in6 endpoint_b_v6 = { .sin6_family = AF_INET6, .sin6_port = htons(listen_b)}; endpoint_b_v6.sin6_addr = in6addr_loopback; */ struct sockaddr_in6 endpoint_c_v6 = {.sin6_family = AF_INET6, .sin6_port = htons(listen_c)}; endpoint_c_v6.sin6_addr = in6addr_loopback; const struct in_addr first_half_v4 = {0}; const struct in_addr second_half_v4 = {htonl(128 << 24)}; const struct in6_addr first_half_v6 = {{{0}}}; const struct in6_addr second_half_v6 = {{{0x80}}}; const uint8_t half_cidr = 1; const uint16_t persistent_keepalives[] = {1, 3, 7, 9, 14, 19}; struct genlmsghdr genlhdr = {.cmd = WG_CMD_SET_DEVICE, .version = 1}; int sock; int id, err; sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC); if (sock == -1) { return; } id = netlink_wireguard_id_get(&nlmsg, sock); if (id == -1) goto error; netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_a, strlen(ifname_a) + 1); netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_a, 32); netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_a, 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_b, 32); netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_b_v4, sizeof(endpoint_b_v4)); netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, &persistent_keepalives[0], 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4, sizeof(first_half_v4)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6, sizeof(first_half_v6)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_c, 32); netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_c_v6, sizeof(endpoint_c_v6)); netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, &persistent_keepalives[1], 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4, sizeof(second_half_v4)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6, sizeof(second_half_v6)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); err = netlink_send(&nlmsg, sock); if (err) { } netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_b, strlen(ifname_b) + 1); netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_b, 32); netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_b, 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_a, 32); netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_a_v6, sizeof(endpoint_a_v6)); netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, &persistent_keepalives[2], 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4, sizeof(first_half_v4)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6, sizeof(first_half_v6)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_c, 32); netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_c_v4, sizeof(endpoint_c_v4)); netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, &persistent_keepalives[3], 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4, sizeof(second_half_v4)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6, sizeof(second_half_v6)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); err = netlink_send(&nlmsg, sock); if (err) { } netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_c, strlen(ifname_c) + 1); netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_c, 32); netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_c, 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_a, 32); netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_a_v6, sizeof(endpoint_a_v6)); netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, &persistent_keepalives[4], 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4, sizeof(first_half_v4)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6, sizeof(first_half_v6)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_b, 32); netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_b_v4, sizeof(endpoint_b_v4)); netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, &persistent_keepalives[5], 2); netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4, sizeof(second_half_v4)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_nest(&nlmsg, NLA_F_NESTED | 0); netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2); netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6, sizeof(second_half_v6)); netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); netlink_done(&nlmsg); err = netlink_send(&nlmsg, sock); if (err) { } error: close(sock); } static void initialize_netdevices(void) { char netdevsim[16]; sprintf(netdevsim, "netdevsim%d", (int)procid); struct { const char* type; const char* dev; } devtypes[] = { {"ip6gretap", "ip6gretap0"}, {"bridge", "bridge0"}, {"vcan", "vcan0"}, {"bond", "bond0"}, {"team", "team0"}, {"dummy", "dummy0"}, {"nlmon", "nlmon0"}, {"caif", "caif0"}, {"batadv", "batadv0"}, {"vxcan", "vxcan1"}, {"netdevsim", netdevsim}, {"veth", 0}, {"xfrm", "xfrm0"}, {"wireguard", "wg0"}, {"wireguard", "wg1"}, {"wireguard", "wg2"}, }; const char* devmasters[] = {"bridge", "bond", "team", "batadv"}; struct { const char* name; int macsize; bool noipv6; } devices[] = { {"lo", ETH_ALEN}, {"sit0", 0}, {"bridge0", ETH_ALEN}, {"vcan0", 0, true}, {"tunl0", 0}, {"gre0", 0}, {"gretap0", ETH_ALEN}, {"ip_vti0", 0}, {"ip6_vti0", 0}, {"ip6tnl0", 0}, {"ip6gre0", 0}, {"ip6gretap0", ETH_ALEN}, {"erspan0", ETH_ALEN}, {"bond0", ETH_ALEN}, {"veth0", ETH_ALEN}, {"veth1", ETH_ALEN}, {"team0", ETH_ALEN}, {"veth0_to_bridge", ETH_ALEN}, {"veth1_to_bridge", ETH_ALEN}, {"veth0_to_bond", ETH_ALEN}, {"veth1_to_bond", ETH_ALEN}, {"veth0_to_team", ETH_ALEN}, {"veth1_to_team", ETH_ALEN}, {"veth0_to_hsr", ETH_ALEN}, {"veth1_to_hsr", ETH_ALEN}, {"hsr0", 0}, {"dummy0", ETH_ALEN}, {"nlmon0", 0}, {"vxcan0", 0, true}, {"vxcan1", 0, true}, {"caif0", ETH_ALEN}, {"batadv0", ETH_ALEN}, {netdevsim, ETH_ALEN}, {"xfrm0", ETH_ALEN}, {"veth0_virt_wifi", ETH_ALEN}, {"veth1_virt_wifi", ETH_ALEN}, {"virt_wifi0", ETH_ALEN}, {"veth0_vlan", ETH_ALEN}, {"veth1_vlan", ETH_ALEN}, {"vlan0", ETH_ALEN}, {"vlan1", ETH_ALEN}, {"macvlan0", ETH_ALEN}, {"macvlan1", ETH_ALEN}, {"ipvlan0", ETH_ALEN}, {"ipvlan1", ETH_ALEN}, {"veth0_macvtap", ETH_ALEN}, {"veth1_macvtap", ETH_ALEN}, {"macvtap0", ETH_ALEN}, {"macsec0", ETH_ALEN}, {"veth0_to_batadv", ETH_ALEN}, {"veth1_to_batadv", ETH_ALEN}, {"batadv_slave_0", ETH_ALEN}, {"batadv_slave_1", ETH_ALEN}, {"geneve0", ETH_ALEN}, {"geneve1", ETH_ALEN}, {"wg0", 0}, {"wg1", 0}, {"wg2", 0}, }; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) netlink_add_device(&nlmsg, sock, devtypes[i].type, devtypes[i].dev); for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) { char master[32], slave0[32], veth0[32], slave1[32], veth1[32]; sprintf(slave0, "%s_slave_0", devmasters[i]); sprintf(veth0, "veth0_to_%s", devmasters[i]); netlink_add_veth(&nlmsg, sock, slave0, veth0); sprintf(slave1, "%s_slave_1", devmasters[i]); sprintf(veth1, "veth1_to_%s", devmasters[i]); netlink_add_veth(&nlmsg, sock, slave1, veth1); sprintf(master, "%s0", devmasters[i]); netlink_device_change(&nlmsg, sock, slave0, false, master, 0, 0, NULL); netlink_device_change(&nlmsg, sock, slave1, false, master, 0, 0, NULL); } netlink_device_change(&nlmsg, sock, "bridge_slave_0", true, 0, 0, 0, NULL); netlink_device_change(&nlmsg, sock, "bridge_slave_1", true, 0, 0, 0, NULL); netlink_add_veth(&nlmsg, sock, "hsr_slave_0", "veth0_to_hsr"); netlink_add_veth(&nlmsg, sock, "hsr_slave_1", "veth1_to_hsr"); netlink_add_hsr(&nlmsg, sock, "hsr0", "hsr_slave_0", "hsr_slave_1"); netlink_device_change(&nlmsg, sock, "hsr_slave_0", true, 0, 0, 0, NULL); netlink_device_change(&nlmsg, sock, "hsr_slave_1", true, 0, 0, 0, NULL); netlink_add_veth(&nlmsg, sock, "veth0_virt_wifi", "veth1_virt_wifi"); netlink_add_linked(&nlmsg, sock, "virt_wifi", "virt_wifi0", "veth1_virt_wifi"); netlink_add_veth(&nlmsg, sock, "veth0_vlan", "veth1_vlan"); netlink_add_vlan(&nlmsg, sock, "vlan0", "veth0_vlan", 0, htons(ETH_P_8021Q)); netlink_add_vlan(&nlmsg, sock, "vlan1", "veth0_vlan", 1, htons(ETH_P_8021AD)); netlink_add_macvlan(&nlmsg, sock, "macvlan0", "veth1_vlan"); netlink_add_macvlan(&nlmsg, sock, "macvlan1", "veth1_vlan"); netlink_add_ipvlan(&nlmsg, sock, "ipvlan0", "veth0_vlan", IPVLAN_MODE_L2, 0); netlink_add_ipvlan(&nlmsg, sock, "ipvlan1", "veth0_vlan", IPVLAN_MODE_L3S, IPVLAN_F_VEPA); netlink_add_veth(&nlmsg, sock, "veth0_macvtap", "veth1_macvtap"); netlink_add_linked(&nlmsg, sock, "macvtap", "macvtap0", "veth0_macvtap"); netlink_add_linked(&nlmsg, sock, "macsec", "macsec0", "veth1_macvtap"); char addr[32]; sprintf(addr, DEV_IPV4, 14 + 10); struct in_addr geneve_addr4; if (inet_pton(AF_INET, addr, &geneve_addr4) <= 0) exit(1); struct in6_addr geneve_addr6; if (inet_pton(AF_INET6, "fc00::01", &geneve_addr6) <= 0) exit(1); netlink_add_geneve(&nlmsg, sock, "geneve0", 0, &geneve_addr4, 0); netlink_add_geneve(&nlmsg, sock, "geneve1", 1, 0, &geneve_addr6); netdevsim_add((int)procid, 4); netlink_wireguard_setup(); for (i = 0; i < sizeof(devices) / (sizeof(devices[0])); i++) { char addr[32]; sprintf(addr, DEV_IPV4, i + 10); netlink_add_addr4(&nlmsg, sock, devices[i].name, addr); if (!devices[i].noipv6) { sprintf(addr, DEV_IPV6, i + 10); netlink_add_addr6(&nlmsg, sock, devices[i].name, addr); } uint64_t macaddr = DEV_MAC + ((i + 10ull) << 40); netlink_device_change(&nlmsg, sock, devices[i].name, true, 0, &macaddr, devices[i].macsize, NULL); } close(sock); } static void initialize_netdevices_init(void) { int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); struct { const char* type; int macsize; bool noipv6; bool noup; } devtypes[] = { {"nr", 7, true}, {"rose", 5, true, true}, }; unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) { char dev[32], addr[32]; sprintf(dev, "%s%d", devtypes[i].type, (int)procid); sprintf(addr, "172.30.%d.%d", i, (int)procid + 1); netlink_add_addr4(&nlmsg, sock, dev, addr); if (!devtypes[i].noipv6) { sprintf(addr, "fe88::%02x:%02x", i, (int)procid + 1); netlink_add_addr6(&nlmsg, sock, dev, addr); } int macsize = devtypes[i].macsize; uint64_t macaddr = 0xbbbbbb + ((unsigned long long)i << (8 * (macsize - 2))) + (procid << (8 * (macsize - 1))); netlink_device_change(&nlmsg, sock, dev, !devtypes[i].noup, 0, &macaddr, macsize, NULL); } close(sock); } static int read_tun(char* data, int size) { if (tunfd < 0) return -1; int rv = read(tunfd, data, size); if (rv < 0) { if (errno == EAGAIN || 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(); 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); } static 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_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: 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); 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); } } 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) { 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"); } 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(); close_fds(); 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_userfaultfd #define __NR_userfaultfd 323 #endif uint64_t r[3] = {0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff}; void execute_one(void) { intptr_t res = 0; syscall(__NR_mmap, 0x20011000ul, 0x3000ul, 0x200000cul, 0x10032ul, -1, 0ul); res = syscall(__NR_dup2, -1, -1); if (res != -1) r[0] = res; NONFAILING(memcpy((void*)0x20000440, "./file0\000", 8)); syscall(__NR_open, 0x20000440ul, 0x110000141042ul, 0ul); syscall(__NR_clone, 0x4007fcul, 0ul, 0x9999999999999999ul, 0ul, -1ul); res = syscall(__NR_userfaultfd, 0ul); if (res != -1) r[1] = res; NONFAILING(*(uint64_t*)0x20000380 = 0xaa); NONFAILING(*(uint64_t*)0x20000388 = 0); NONFAILING(*(uint64_t*)0x20000390 = 0); syscall(__NR_ioctl, r[1], 0xc018aa3f, 0x20000380ul); syscall(__NR_ioctl, r[0], 0x80047453, 0ul); NONFAILING(*(uint64_t*)0x20000080 = 0x20909000); NONFAILING(*(uint64_t*)0x20000088 = 0x4000); NONFAILING(*(uint64_t*)0x20000090 = 1); NONFAILING(*(uint64_t*)0x20000098 = 0); syscall(__NR_ioctl, r[1], 0xc020aa00, 0x20000080ul); NONFAILING(memcpy((void*)0x200001c0, "cgroup.controllers\000", 19)); res = syscall(__NR_openat, 0xffffff9c, 0x200001c0ul, 0x275aul, 0ul); if (res != -1) r[2] = res; syscall(__NR_write, r[2], 0x20000040ul, 0x208e24bul); } int main(void) { syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul); syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul); syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul); setup_binfmt_misc(); install_segv_handler(); for (procid = 0; procid < 6; procid++) { if (fork() == 0) { use_temporary_dir(); do_sandbox_none(); } } sleep(1000000); return 0; }
the_stack_data/59512918.c
#if 0 // hbobs /* Modified for Tomato Firmware Portions, Copyright (C) 2006-2009 Jonathan Zarate */ // checkme: can remove bpalogin soon? -- zzz #include "rc.h" #include <netdb.h> #include <errno.h> #include <sys/sysinfo.h> #undef _dprintf #define _dprintf(args...) cprintf(args) // #define _dprintf(args...) do { } while(0) int start_heartbeat(int mode) { #ifdef TCONFIG_HEARTBEAT FILE *fp; int ret; char authserver[80]; char authdomain[80]; int n; if (nvram_invmatch("wan_proto", "heartbeat")) return 0; _dprintf("%s: hb_server_ip=%s wan_get_domain=%s\n", __FUNCTION__, nvram_safe_get("hb_server_ip"), nvram_safe_get("wan_get_domain")); strlcpy(authdomain, nvram_safe_get("wan_get_domain"), sizeof(authdomain)); if ((nvram_invmatch("hb_server_ip", "")) && (nvram_invmatch("hb_server_ip", "0.0.0.0"))) { strlcpy(authserver, nvram_safe_get("hb_server_ip"), sizeof(authserver)); _dprintf("trying %s\n", authserver); if (gethostbyname(authserver) == NULL) { n = strlen(authserver); snprintf(authserver + n, sizeof(authserver) - n, ".%s", authdomain); _dprintf("trying %s\n", authserver); if (gethostbyname(authserver) == NULL) { authserver[n] = 0; _dprintf("reverting to %s\n", authserver); } } } else { /* We must find out HB auth server from domain that get by dhcp if user don't input HB sever. */ snprintf(authserver, sizeof(authserver), "sm-server.%s", nvram_safe_get("wan_get_domain")); } _dprintf("%s: authserver=%s authdomain=%s\n", __FUNCTION__, authserver, authdomain); // snprintf(buf, sizeof(buf), "%s%c%s", authserver, !strcmp(authdomain, "") ? '\0' : '.', authdomain); // nvram_set("hb_server_name", buf); // _dprintf("heartbeat: Connect to server %s\n", buf); if ((fp = fopen("/tmp/bpalogin.conf", "w")) == NULL) { perror("/tmp/bpalogin.conf"); return errno; } fprintf(fp, "username %s\n", nvram_safe_get("ppp_username")); fprintf(fp, "password %s\n", nvram_safe_get("ppp_passwd")); fprintf(fp, "authserver %s\n", authserver); fprintf(fp, "authdomain %s\n", authdomain); fprintf(fp, "localport 5050\n"); fprintf(fp, "logging stdout\n"); fprintf(fp, "debuglevel 4\n"); fprintf(fp, "minheartbeatinterval 60\n"); fprintf(fp, "maxheartbeatinterval 840\n"); fprintf(fp, "connectedprog hb_connect\n"); fprintf(fp, "disconnectedprog hb_disconnect\n"); fclose(fp); mkdir("/tmp/ppp", 0777); if ((fp = fopen("/tmp/hb_connect_success", "r"))) { // ??? ret = eval("bpalogin", "-c", "/tmp/bpalogin.conf", "-t"); fclose(fp); } else ret = eval("bpalogin", "-c", "/tmp/bpalogin.conf"); if (nvram_invmatch("ppp_demand", "1")) { if (mode != REDIAL) start_redial(); } return ret; #else return 0; #endif } int stop_heartbeat(void) { #ifdef TCONFIG_HEARTBEAT unlink("/tmp/ppp/link"); killall("bpalogin", SIGTERM); killall("bpalogin", SIGKILL); #endif return 0; } // <listenport> <pid> int hb_connect_main(int argc, char **argv) { #ifdef TCONFIG_HEARTBEAT FILE *fp; char buf[254]; _dprintf("hb_connect_main: init\n"); mkdir("/tmp/ppp", 0777); if ((fp = fopen("/tmp/ppp/link", "a")) == NULL) { perror("/tmp/ppp/link"); return errno; } fprintf(fp, "%s", argv[2]); fclose(fp); start_wan_done(nvram_safe_get("wan_ifname")); snprintf(buf, sizeof(buf), "iptables -I INPUT -d %s -i %s -p udp --dport %d -j %s", nvram_safe_get("wan_ipaddr"), nvram_safe_get("wan_ifname"), 5050, "ACCEPT"); system(buf); #endif return 0; } int hb_disconnect_main(int argc, char **argv) { #ifdef TCONFIG_HEARTBEAT _dprintf("hb_disconnect_main\n"); if (check_wanup()) { stop_heartbeat(); } #endif return 0; } int hb_idle_main(int argc, char **argv) { #ifdef TCONFIG_HEARTBEAT struct sysinfo si; long target; FILE *f; char s[64]; unsigned long long now; unsigned long long last; long alive; long maxidle; if (fork() != 0) return 0; maxidle = atoi(nvram_safe_get("ppp_idletime")) * 60; if (maxidle < 60) maxidle = 60; last = 0; sysinfo(&si); alive = si.uptime; while (1) { target = si.uptime + 60; do { // _dprintf("uptime = %ld, target = %ld\n", si.uptime, target); sleep(target - si.uptime); sysinfo(&si); } while (si.uptime < target); if (check_action() != ACT_IDLE) continue; // this sucks... -- zzz if ((f = popen("iptables -xnvL FORWARD | grep wanout", "r")) == NULL) { _dprintf("hbidle: error obtaining data\n"); continue; } fgets(s, sizeof(s), f); pclose(f); if ((now = strtoull(s, NULL, 10)) == last) { if ((si.uptime - alive) > maxidle) { _dprintf("hbidle: idled for %d, stopping.\n", si.uptime - alive); stop_heartbeat(); stop_ntpc(); xstart("listen", nvram_safe_get("lan_ifname")); return 0; } } else { _dprintf("hbidle: now = %llu, last = %llu\n", now, last); last = now; alive = si.uptime; } _dprintf("hbidle: time = %ld\n", (si.uptime - alive) / 60); } #else return 0; #endif } void start_hbidle(void) { #ifdef TCONFIG_HEARTBEAT if ((nvram_match("wan_proto", "heartbeat")) && (nvram_match("ppp_demand", "1")) && (check_wanup())) { xstart("hb_idle"); } #endif } void stop_hbidle(void) { #ifdef TCONFIG_HEARTBEAT killall("hb_idle", SIGTERM); #endif } #endif // hbobs
the_stack_data/212525.c
/* * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <math.h> #include <stdlib.h> #define OFFSET(x, y, m) (((x)*(m)) + (y)) void initialize(double *restrict A, double *restrict Anew, int m, int n) { memset(A, 0, n * m * sizeof(double)); memset(Anew, 0, n * m * sizeof(double)); for(int i = 0; i < m; i++){ A[i] = 1.0; Anew[i] = 1.0; } } double calcNext(double *restrict A, double *restrict Anew, int m, int n) { double error = 0.0; #pragma acc kernels for( int j = 1; j < n-1; j++) { for( int i = 1; i < m-1; i++ ) { Anew[OFFSET(j, i, m)] = 0.25 * ( A[OFFSET(j, i+1, m)] + A[OFFSET(j, i-1, m)] + A[OFFSET(j-1, i, m)] + A[OFFSET(j+1, i, m)]); error = fmax( error, fabs(Anew[OFFSET(j, i, m)] - A[OFFSET(j, i , m)])); } } return error; } void swap(double *restrict A, double *restrict Anew, int m, int n) { #pragma acc kernels for( int j = 1; j < n-1; j++) { for( int i = 1; i < m-1; i++ ) { A[OFFSET(j, i, m)] = Anew[OFFSET(j, i, m)]; } } } void deallocate(double *restrict A, double *restrict Anew) { free(A); free(Anew); }
the_stack_data/161080779.c
/*********************************************************************** * FILE NAME: Egypt-11854.c * * PURPOSE: * * @author: Md. Arafat Hasan Jenin * EMAIL: [email protected] * * DEVELOPMENT HISTORY: * Date Change Version Description * ------------------------------------------------------------------- * 04 Aug 2016 New 1.0 Completed, Accepted ***********************************************************************/ #include<stdio.h> int main() { int b,h,o; while(scanf("%d %d %d",&b,&h,&o)==3) { if(b==0&&h==0&&o==0) break; if(b>h) { b=b+h; h=b-h; b=b-h; } if(h>o) { h=h+o; o=h-o; h=h-o; } if(b>h) { b=b+h; h=b-h; b=b-h; } if(b*b+h*h==o*o) printf("right\n"); else printf("wrong\n"); } return 0; }
the_stack_data/654009.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> int someMath(int num,int i){ num = num * num * num * i; return num; } int main(int argc, char** argv){ int nthreads, tid; int i; int num = atoi(argv[1]); int data[10000]; #pragma omp parallel { #pragma omp for for(i=0; i<10000; i++){ data[i] = someMath(num,i); } } FILE *fp; fp = fopen("data.csv","w+"); for(i=0; i<10000; i++){ fprintf(fp, "%d,",data[i]); } fprintf(fp, "\n"); for(i=0; i<10000; i++){ fprintf(fp, "%d,",data[i]); } fprintf(fp, "\n"); fclose(fp); }
the_stack_data/67325222.c
/*** * This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License. * When used, please cite the following article(s): V. Mrazek, L. Sekanina, Z. Vasicek "Libraries of Approximate Circuits: Automated Design and Application in CNN Accelerators" IEEE Journal on Emerging and Selected Topics in Circuits and Systems, Vol 10, No 4, 2020 * This file contains a circuit from a sub-set of pareto optimal circuits with respect to the pwr and mae parameters ***/ // MAE% = 44.45 % // MAE = 57 // WCE% = 100.00 % // WCE = 128 // WCRE% = 200.00 % // EP% = 99.48 % // MRE% = 99.98 % // MSE = 4551 // PDK45_PWR = 0.000 mW // PDK45_AREA = 0.0 um2 // PDK45_DELAY = 0.00 ns #include <stdint.h> #include <stdlib.h> uint64_t add8s_6HF(const uint64_t B,const uint64_t A) { uint64_t dout_61, dout_64; uint64_t O; dout_61=((B >> 3)&1)^0xFFFFFFFFFFFFFFFFU; dout_64=(dout_61&((B >> 3)&1))^0xFFFFFFFFFFFFFFFFU; O = 0; O |= (dout_64&1) << 0; O |= (dout_64&1) << 1; O |= (dout_64&1) << 2; O |= (dout_64&1) << 3; O |= (dout_64&1) << 4; O |= (dout_64&1) << 5; O |= (dout_64&1) << 6; O |= (dout_64&1) << 7; return O; }
the_stack_data/26701658.c
/** * Simple SMA16 VM in C. */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <unistd.h> #include <termios.h> #ifndef DISABLE_TIMING #define ENABLE_TIMING #endif #ifndef DISABLE_DEBUG #define ENABLE_DEBUG #endif #ifndef DISABLE_SIGINT #define ENABLE_SIGINT #endif #ifdef ENABLE_TIMING #include <time.h> #endif #ifdef ENABLE_SIGINT #include <signal.h> #endif #ifdef MEMORY_FILE const char *usage_line = "Usage: sma16vm [options]"; #else const char *usage_line = "Usage: sma16vm [options] input_memory_file"; #endif const char *version_string = "sma16 v0.1"; const char *options_string = "Options:\n" " --version\tDisplay version.\n" " --help\tDisplay this message.\n" #ifdef ENABLE_DEBUG " --debug\tDisplay debug information.\n" #endif #ifdef ENABLE_TIMING " --time\tDisplay timing information\n" #endif "\n" "Short forms can also be used as per usual."; // Workaround for missing defines #define CLOCK_PROCESS_CPUTIME_ID 2 #define SIGINT 2 #define UPPER(x) (x & 0xf000) #define INST(x) ((x >> 12) & 0xf) #define DATA(x) (x & 0xfff) #define PRESERVE_INST 0x1 #define SHIFT_INST 0x0 #define SHIFT(val, preserve_inst) ((val << 1) | (preserve_inst & 0x1)) #define NEXT_ 0xffff #define ASCII_OUT 0x00A #define SMALL_OUT 0x00B #define TERM_CONF 0x00C #define STACK_SIZE 0x00D #define RESET_VECTOR 0x000 #define FAULT_VECTOR 0x001 #define SOFTWARE_VECTOR 0x002 #define INTER_REASON 0x008 enum InterruptReason { IR_UNKNOWN = 0x0000, IR_UNSUPPORTED = 0x0ff0, }; #define INTER_RETURN 0x009 #define MEM(A, I, D) \ { \ (A & 0xffff), (((I & 0x000f) << 12) | (D & 0x0fff))}, #define MBP(A, X, Y) \ { \ (A & 0xffff), (((X & 0x00ff) << 8) | (Y & 0x00ff))}, #define DEBUG(X) \ if (debug) \ puts(X) #define START_PROGRAM const __prog_elem PROGRAM[] = { #define END_PROGRAM \ } \ ; #define CHP(x, y) ((CHP_P(x) << 6) | CHP_P(y)) #define CHP_P(x) (CHP_P_##x) #define CHP_P_A 0 #define CHP_P_B 1 #define CHP_P_C 2 #define CHP_P_D 3 #define CHP_P_E 4 #define CHP_P_F 5 #define CHP_P_G 6 #define CHP_P_H 7 #define CHP_P_I 8 #define CHP_P_J 9 #define CHP_P_K 10 #define CHP_P_L 11 #define CHP_P_M 12 #define CHP_P_N 13 #define CHP_P_O 14 #define CHP_P_P 15 #define CHP_P_Q 16 #define CHP_P_R 17 #define CHP_P_S 18 #define CHP_P_T 19 #define CHP_P_U 20 #define CHP_P_V 21 #define CHP_P_W 22 #define CHP_P_X 23 #define CHP_P_Y 24 #define CHP_P_Z 25 #define CHP_P_a 26 #define CHP_P_b 27 #define CHP_P_c 28 #define CHP_P_d 29 #define CHP_P_e 30 #define CHP_P_f 31 #define CHP_P_g 32 #define CHP_P_h 33 #define CHP_P_i 34 #define CHP_P_j 35 #define CHP_P_k 36 #define CHP_P_l 37 #define CHP_P_m 38 #define CHP_P_n 39 #define CHP_P_o 40 #define CHP_P_p 41 #define CHP_P_q 42 #define CHP_P_r 43 #define CHP_P_s 44 #define CHP_P_t 45 #define CHP_P_u 46 #define CHP_P_v 47 #define CHP_P_w 48 #define CHP_P_x 49 #define CHP_P_y 50 #define CHP_P_z 51 #define CHP_P_0 52 #define CHP_P_1 53 #define CHP_P_2 54 #define CHP_P_3 55 #define CHP_P_4 56 #define CHP_P_5 57 #define CHP_P_6 58 #define CHP_P_7 59 #define CHP_P_8 60 #define CHP_P_9 61 #define CHP_P_ CHP_P_SPACE #define CHP_P_SPACE 62 #define CHP_P__ CHP_P_NONE #define CHP_P_NONE 63 const char *HALT_STRING = "HALT"; typedef struct { uint16_t address; uint16_t data; } __prog_elem; enum Instructions { HALT = 0x0, /* 0x1 */ JUMP = 0x2, JUMPZ = 0x3, LOAD = 0x4, STORE = 0x5, LSHFT = 0x6, RSHFT = 0x7, XOR = 0x8, AND = 0x9, SFULL = 0xA, ADD = 0xB, /* 0xC */ POP = 0xD, PUSH = 0xE, NOOP = 0xF }; __attribute__((always_inline)) static inline char transform_char(uint16_t x) { if (x >= 0 && x < 26) return x + 'A'; if (x >= 26 && x < 52) return x - 26 + 'a'; if (x >= 52 && x < 62) return x - 52 + '0'; if (x == 62) return ' '; return '\0'; } static inline char get_single_char() { static struct termios old_settings, new_settings; tcgetattr(STDIN_FILENO, &old_settings); new_settings = old_settings; new_settings.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &new_settings); const char result = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &old_settings); return result; } #ifdef ENABLE_SIGINT static bool sigint_halt_flag = false; void handle_sigint(int sig) { sigint_halt_flag = true; } #endif #ifdef MEMORY_FILE #include "memory_file.s16" #endif int main(int argc, char *argv[]) { #ifdef ENABLE_SIGINT // Register signal handler signal(SIGINT, handle_sigint); #endif // Flags #ifdef ENABLE_DEBUG bool debug = false; #endif #ifdef ENABLE_TIMING bool timed = false; #endif #ifndef MEMORY_FILE int input_file_index = 0; #endif bool help = false; bool version = false; // CPU State uint16_t memory[4096] = {0}; memory[STACK_SIZE] = 0; bool halt = false; bool test = false; uint16_t accumulator = 0; uint16_t program_counter = 0; #ifdef ENABLE_TIMING // Timing struct timespec start; struct timespec end; #endif for (int arg = 0; arg < argc; arg++) { if (argv[arg][0] == '-') { if (strncmp(argv[arg], "-h", 3) == 0 || strncmp(argv[arg], "--help", 7) == 0) help = true; else if (strncmp(argv[arg], "-v", 3) == 0 || strncmp(argv[arg], "--version", 10) == 0) version = true; #ifdef ENABLE_DEBUG else if (strncmp(argv[arg], "-d", 3) == 0 || strncmp(argv[arg], "--debug", 8) == 0) debug = true; #endif #ifdef ENABLE_TIMING else if (strncmp(argv[arg], "-t", 3) == 0 || strncmp(argv[arg], "--timed", 8) == 0) timed = true; #endif } #ifndef MEMORY_FILE else if (arg != 0) { input_file_index = arg; } #endif } if (version) { puts(version_string); return 0; } if (help) { puts(usage_line); puts(options_string); return 0; } #ifdef MEMORY_FILE /* Load program */ uint16_t last_address = 0; for (uint16_t index = 0; index < (sizeof(PROGRAM) / sizeof(__prog_elem)); index++) { uint16_t address = PROGRAM[index].address; if (address == NEXT_) { address = (last_address + 1) & 0x0FFF; } address = address & 0x0fff; memory[address] = PROGRAM[index].data; last_address = address; } #else if (input_file_index == 0) { fputs("No input file.", stderr); return 1; } else { FILE *input_file = fopen(argv[input_file_index], "r"); if (NULL == input_file) { fputs("Could not open file.", stderr); return 2; } const size_t read_bytes = fread((uint8_t *)memory, 1, 8192, input_file); if (read_bytes % 2 != 0) { fputs("Warning, uneven number of bytes read from memory image.", stderr); } for (size_t word_index = 0; word_index < read_bytes / 2; word_index++) { memory[word_index] = ((memory[word_index] & 0xff) << 8) | ((memory[word_index] >> 8) & 0xff); } if (0 != fclose(input_file)) { fputs("Failed to close file.", stderr); return 3; } } #endif for (;;) { #ifdef ENABLE_DEBUG if (debug) { puts("+---------+-----+-------+--- -- -- - - -"); puts("| [ ACC ] | PC | PROG | -> OUTPUT"); puts("+---------+-----+-------+--- -- -- - - -"); } #endif #ifdef ENABLE_TIMING if (timed) clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); #endif while (!halt) { #ifdef ENABLE_DEBUG if (debug) printf("| [%01x:%03x] | %03x | %01x:%03x | -> ", INST(accumulator), DATA(accumulator), program_counter, INST(memory[program_counter]), DATA(memory[program_counter])); #endif switch (INST(memory[program_counter])) { case HALT: { #ifdef ENABLE_DEBUG if (debug) fputs(HALT_STRING, stdout); // Avoid newline else #endif puts(HALT_STRING); halt = true; program_counter++; } break; case JUMP: { program_counter = DATA(memory[program_counter]); } break; case JUMPZ: { if (test) program_counter = DATA(memory[program_counter]); else program_counter++; } break; case LOAD: { accumulator = memory[DATA(memory[program_counter])]; program_counter++; } break; case STORE: { const uint16_t address = DATA(memory[program_counter]); if (address == SMALL_OUT) { const uint16_t first_char = 0x003F & (accumulator >> 6); const uint16_t second_char = 0x003F & accumulator; if (first_char != '\0') putc(transform_char(first_char), stdout); if (second_char != '\0') putc(transform_char(second_char), stdout); } else if (address == ASCII_OUT) { const char to_print = accumulator & 0x00ff; #ifdef ENABLE_DEBUG if (debug && to_print == '\n') { putc('\\', stdout); putc('n', stdout); } else { #endif putc(to_print, stdout); #ifdef ENABLE_DEBUG } #endif } memory[address] = UPPER(memory[address]) | DATA(accumulator); program_counter++; } break; case SFULL: { const uint16_t address = DATA(memory[program_counter]); if (address == SMALL_OUT) { const uint16_t first_char = 0x003F & (accumulator >> 6); const uint16_t second_char = 0x003F & accumulator; if (first_char != '\0') putc(transform_char(first_char), stdout); if (second_char != '\0') putc(transform_char(second_char), stdout); } else if (address == ASCII_OUT) { putc(accumulator & 0x00ff, stdout); } memory[address] = accumulator; program_counter++; } break; case LSHFT: { const uint16_t shift = DATA(memory[program_counter]); const uint16_t inst = UPPER(accumulator); if (shift & 0x1) accumulator = accumulator & 0x0fff; accumulator = accumulator << (shift >> 1); if (shift & 0x1) accumulator = (accumulator & 0xfff) | inst; program_counter++; } break; case RSHFT: { const uint16_t shift = DATA(memory[program_counter]); const uint16_t inst = UPPER(accumulator); if (shift & 0x1) accumulator = accumulator & 0x0fff; accumulator = accumulator >> (shift >> 1); if (shift & 0x1) accumulator = (accumulator & 0xfff) | inst; program_counter++; } break; case XOR: { accumulator ^= DATA(memory[program_counter]); program_counter++; } break; case AND: { accumulator &= DATA(memory[program_counter]) | 0xf000; program_counter++; } break; case ADD: { const uint16_t inst = UPPER(accumulator); accumulator = inst | ((DATA(accumulator) + DATA(memory[program_counter])) & 0xfff); test = accumulator == 0; program_counter++; } break; case POP: { memory[INTER_RETURN] = program_counter + 1; program_counter = FAULT_VECTOR; memory[INTER_REASON] = IR_UNSUPPORTED + POP; } break; case PUSH: { memory[INTER_RETURN] = program_counter + 1; program_counter = FAULT_VECTOR; memory[INTER_REASON] = IR_UNSUPPORTED + PUSH; } break; case NOOP: default: { program_counter++; } break; } #ifdef ENABLE_SIGINT if (sigint_halt_flag) { halt = true; sigint_halt_flag = false; #ifdef ENABLE_DEBUG if (debug) fputs(" USER HALT", stdout); else #endif puts(" USER HALT"); } #endif #ifdef ENABLE_DEBUG if (debug) putc('\n', stdout); #endif } #ifdef ENABLE_TIMING if (timed) clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); #endif #ifdef ENABLE_DEBUG if (debug) puts("+---------+-----+-------+--- -- -- - - -"); #endif if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) { #ifdef ENABLE_TIMING if (timed) printf("System halted after %ldus.", (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000); else #endif fputs("System halted.", stdout); puts(" Press C to continue, or any other key to exit."); const char input = get_single_char(); if (input == 'C' || input == 'c') { halt = false; } else { break; } } else { puts("System halted."); break; } } return 0; }
the_stack_data/178264810.c
/*Exercise 3 - Repetition Write a C program to calculate the sum of the numbers from 1 to n. Where n is a keyboard input. e.g. n -> 100 sum = 1+2+3+....+ 99+100 = 5050 n -> 1- sum = 1+2+3+...+10 = 55 */ #include <stdio.h> int main() { int number, sum = 0 , i = 0; printf("Enter a number: "); scanf("%d",&number); for (i = 0; i <= number; i++) sum += i; printf("Sum of the numbers from 1 to %d : %d",number,sum); return 0; }
the_stack_data/165769594.c
#include<stdio.h> void main() { int i,j,u,v,w,G[20][20],V,E; printf("Enter no. of vertex and Edges : "); scanf("%d%d",&V,&E); printf("Enter source,dest and weight :\n"); for(i=1;i<=V;i++) { for(j=1;j<=V;j++) G[i][j]=99; } for(i=1;i<=E;i++) { scanf("%d%d%d",&u,&v,&w); G[u][v]=w; } printf("Reqd. MST :\n"); prims(G,V,E); } void prims(int G[][20],int V,int E) { int k=0,vis[20]={0},i,j,u,v,c=0,min; vis[1]=1; while(k<V-1) { min=99; for(i=1;i<=V;i++) { for(j=1;j<=V;j++) { if(G[i][j]<min && vis[i]==1 && vis[j]==0) { min=G[i][j]; u=i; v=j; } } } printf("\n%d %d",u,v); c+=min; vis[v]=1; k++; } }
the_stack_data/248580152.c
int fun(x, y) { asm(""); // Don't inline me, bro! int i; for (i = 0; i < 0; ++i) { } return x + y; } void main() { int i; for (i = 0; i < 200000000; i++) { fun(i, 1); } }
the_stack_data/153269425.c
#include<sys/types.h> #include<fcntl.h> #include<stdlib.h> #include<stdio.h> int main(int argc, char *argv[]) { int accmode, val; if (argc != 2) printf("the argc must equel to 2"); if ((val = fcntl(atoi(argv[1]), F_GETFL, 0)) < 0) { perror("fcntl"); exit(EXIT_FAILURE); } accmode = val & O_ACCMODE; if(accmode == O_RDONLY) printf("read only\n"); else if (accmode == O_WRONLY) printf("write only\n"); else if (accmode == O_RDWR) printf("read write\n"); else printf("unknown mode\n"); if (val & O_APPEND) printf(", append"); if (val & O_NONBLOCK) printf(", nonblocking"); return 0; }
the_stack_data/173577076.c
#include <stdio.h> int main(void) { int a[10][10], transpose[10][10], r, c, i, j; printf("Input the rows and columns of matrix: "); scanf("%d %d", &r, &c); printf("Input the elements of matrix: "); for (i=0; i<r; ++i) { for (j=0; j<c; ++j) { printf("Enter the element a[%d][%d]: ", i+1, j+1); scanf("%d", &a[i][j]); } } printf("\n Enter Matrix \n"); for (i=0; i<r; ++i) { for (j=0; j<c; ++j) { printf("%-4d", a[i][j]); if (j == c-1) printf("\n\n"); } } for (i=0; i<r; ++i) { for (j=0; j<c; ++j) { transpose[j][i] = a[i][j]; } } printf("Matrix after conversion: \n"); for (i=0; i<c; ++i) { for (j=0; j<r; ++j) { printf("%-5d", transpose[i][j]); if (j==r-1) printf("\n\n"); } } return 0; }
the_stack_data/86074725.c
#include <stdio.h> int main(void) { float f_num; int i_num; printf(" \n Enter the any integer value:"); scanf("%d",&i_num); f_num = i_num; printf(" \n the floating point variant %d = %f",i_num,f_num); // your code goes here return 0; }
the_stack_data/109752.c
#include <stdio.h> #include <stdlib.h> int main() { printf("H%dllo, w%drld!\n", 3, 0); return 0; }
the_stack_data/184517428.c
/*****************************************************************/ /* Class: Computer Programming, Fall 2019 */ /* Author: 林天佑 */ /* ID: 108820003 */ /* Date: 2019.12.08 */ /* Purpose: Be the best student. */ /* GitHub: https://github.com/Xanonymous-GitHub/main/tree/HW */ /*****************************************************************/ #include <stdio.h> int main(int argc, char *argv[]) { printf("Enter 10 numbers: "); //顯示輸出訊息 int i, ii[10], *iii = ii, iiiii = -32767, iiii = 32767; //建立變數 for (i = 0; i < 10; i++) { //跑 scanf("%d", &ii[i]); //讀 if (*(iii + i) > iiiii)iiiii = ii[i]; //比大 if (*(iii + i) < iiii)iiii = ii[i]; //比小 } printf("Largest: %d\n", iiiii); //輸出大 printf("Smallest: %d\n", iiii); //輸出小 return 0; }
the_stack_data/178266408.c
#include <sys/socket.h> int socket_family(int fd) { struct sockaddr sockaddr = {}; socklen_t len = sizeof(sockaddr); if (getsockname(fd, &sockaddr, &len) < 0) return -1; if (len < sizeof(sa_family_t)) return -1; return sockaddr.sa_family; } int socket_type(int fd) { int type = 0; socklen_t len = sizeof(type); if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &len) < 0) return -1; return type; } int socket_listening(int fd) { int accepting = 0; socklen_t len = sizeof(accepting); if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &accepting, &len) < 0) return -1; return accepting; }
the_stack_data/370082.c
//This program calculates the probability from a normal distribution //with mean "mu" and standard deviation "sigma". //If mu and sigma are not specified, they will be assumed to be 0 and 1 respectively. #include <stdlib.h> #include <stdio.h> #include <errno.h> #define MIN_SERIES_TERMS 14 #define INVERSE_SQRT_2PI 0.3989422804 #define HIGHEST_Z 3.1674 //Experimentally determined to be the bounds. #define LOWEST_Z -3.1674 double zScore(double x, double mu, double sigma) { return ((x-mu)/sigma); } double normCDF(double z) { double output = z; //starting point, computed term at n=0 int n = 0; double current_numerator = z; unsigned long denominator = 1; long denominator_piece = 1; if (z > HIGHEST_Z) { output = 1; } else if (z < LOWEST_Z) { output = 0; } else if (z == 0.0) { output = 0.5; } else { int total_terms = MIN_SERIES_TERMS; //For loop used to compute SUM((Z^(2n+1)(-1)^n)/((2n+1)(2^n)(n!))) in linear time for(n=1; n <= total_terms; n++) { current_numerator = current_numerator*z*z*(-1); denominator_piece = denominator_piece*n; //factorial term denominator_piece = denominator_piece<<1; //2^n term denominator = (2*n+1)*denominator_piece; //(2n+1) term output = output + (current_numerator / (double)denominator); } output *= INVERSE_SQRT_2PI; output += 0.5; } return output; } int main(int argc, char** argv) { //Read user input char* endptr = NULL; //This is for error checking if (argc < 3) { printf("ERROR: not enough arguments.\n"); printf("Correct usage: pnorm [low_value], [high_value], [mu, default=0], [sigma, default=1]\n"); exit(1); } double mu = 0; double sigma = 1; if (argc == 4) { mu = strtod(*(argv+3), &endptr); if (errno == ERANGE) { printf("Error: value %s for mu out of range.\n", *(argv+3)); exit(1); } } else if (argc == 5) { mu = strtod(*(argv+3), &endptr); if (errno == ERANGE) { printf("ERROR: value %s for mu out of range\n", *(argv+3)); exit(1); } sigma = strtod(*(argv+4), &endptr); if (errno == ERANGE) { printf("ERROR: value %s for sigma out of range\n", *(argv+4)); exit(1); } if (sigma <= 0) { printf("ERROR: Sigma must be a positive value.\n"); exit(1); } } double lowX = strtod(*(argv+1), &endptr); if (errno == ERANGE) { printf("ERROR: value %s for low_value out of range\n", *(argv+1)); exit(1); } double highX = strtod(*(argv+2), &endptr); if (errno == ERANGE) { printf("ERROR: value %s for high_value out of range.\n", *(argv+2)); exit(1); } if (lowX > highX) { printf("ERROR: low_value must be less than or equal to high_value.\n"); exit(1); } //actual calculations start here double output = 0; if (lowX == highX) { output = 0.0; } else { double lowZ = zScore(lowX, mu, sigma); double highZ = zScore(highX, mu, sigma); output = normCDF(highZ) - normCDF(lowZ); if (output > 1.0) { output = 1.0; } else if (output < 0.0) { output = 0.0; } } //Output result printf("P(%f < X < %f) = %f\n", lowX, highX, output); return 0; }
the_stack_data/38761.c
#include <stdio.h> #define IN 1 #define OUT 0 int wcount(char *s){ int i=0; int f=OUT; int nspace=0; while(*s){ nspace=(*s)!=32; i += !f && nspace; f = nspace; s++; } return i; } int main(int argc, char **argv){ char string [100]; gets(string); printf("%d\n", wcount((char*)string)); return 0; }
the_stack_data/117596.c
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int spawn(const char * program, char ** arg_list) { pid_t child_pid = fork(); if (child_pid != 0) return child_pid; /* This is the parent process. */ else { execvp (program, arg_list); /* Now execute PROGRAM */ fprintf (stderr, "An error occurred in execvp\n"); abort(); } } int main() { char * arg_list[] = { "ls", "-l", "/", NULL }; spawn("ls", arg_list); printf ("Main program exiting...\n"); return 0; }
the_stack_data/1047174.c
#include "stdio.h" int a = 4; int main() { int b = 3; printf("a = %d, b = %d\n", a, b); //输出 a=4, b=3 { int a = 5; printf("a = %d, b = %d\n", a, b); //输出 a=5, b=3 } printf("a = %d, b = %d\n", a, b); //输出 a=4, b=3 return 0; }
the_stack_data/710160.c
/* * Copyright (c) 1980 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ #include <sys/time.h> #include <sys/resource.h> /* * Backwards compatible nice. */ int nice(incr) int incr; { int prio; extern int errno; errno = 0; prio = getpriority(PRIO_PROCESS, 0); if (prio == -1 && errno) return (-1); return setpriority(PRIO_PROCESS, 0, prio + incr); }
the_stack_data/40763421.c
/* * * MIT License * * Copyright (c) 2020 Mirgor * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ //******************************************************************** // //! \file module.c //! //! \brief This is the [module name] module. //! //! This module implements ... //! //! \author Esteban G. Pupillo //! //! \date 19 Oct 2013 // //******************************************************************** //******************************************************************** // Include header files //******************************************************************** //******************************************************************** //! \addtogroup //! @{ //! \addtogroup //! @{ //******************************************************************** //******************************************************************** // File level pragmas //******************************************************************** //******************************************************************** // Constant and Macro Definitions using #define //******************************************************************** //******************************************************************** // Enumerations and Structures and Typedefs //******************************************************************** //******************************************************************** // Function Prototypes for Private Functions with File Level Scope //******************************************************************** //******************************************************************** // ROM Const Variables With File Level Scope //******************************************************************** //******************************************************************** // Static Variables and Const Variables With File Level Scope //******************************************************************** //******************************************************************** // Function Definitions //******************************************************************** //******************************************************************** // // Close the Doxygen group. //! @} //! @} // //******************************************************************** //******************************************************************** // // Modification Record // //******************************************************************** // // // //********************************************************************
the_stack_data/59511688.c
#include<stdio.h> int main() { int size; scanf("%d",&size); int arr[size]; int i,j,k,x,temp; for (k = 0; k<size; k++) { scanf("%d",&arr[k]); } for(i=0; i<size-1; i++) { for(j = i+1; j<size; j++) { if(arr[i]>arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } for (x=0; x<size; x++) printf("%d ",arr[x]); printf("\n"); } printf("\n"); } return 0; }
the_stack_data/1220460.c
#include <assert.h> #include <inttypes.h> #include <math.h> #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <string.h> int main(const int argc, const char* const argv[]) { // Getting away with no error checking throughout because CodeEval makes some // strong guarantees about our runtime environment. No need to pay when we're // being benchmarked. Don't forget to define NDEBUG prior to submitting! assert(argc >= 2 && "Expecting at least one command-line argument."); static char stdoutBuffer[256] = ""; // Turn on full output buffering for stdout. setvbuf(stdout, stdoutBuffer, _IOFBF, sizeof stdoutBuffer); FILE* inputStream = fopen(argv[1], "r"); assert(inputStream && "Failed to open input stream."); for(char lineBuffer[128] = ""; fgets(lineBuffer, sizeof lineBuffer, inputStream);) { // Kill trailing newline. { char* const cursor = strchr(lineBuffer, '\n'); if(cursor) *cursor = '\0'; } const size_t dataLength = strlen(lineBuffer); assert(!(dataLength & 1)); const char* const dataLeft = lineBuffer, * const dataRight = &lineBuffer[dataLength / 2]; const char* lhs = dataLeft, * rhs = dataRight; bool isValidInput = true; unsigned asteriskCount = 0; for(;lhs != dataRight; ++lhs, ++rhs) { // Wildcard pair. if((*lhs == '*') && (*rhs == '*')) ++asteriskCount; // Complete mismatch between letters. else if((*lhs != *rhs) && !(*lhs == '*' || *rhs == '*')) { isValidInput = false; break; } } if(!isValidInput) puts("0"); else { // |{A, B}| = 2. const uint_least64_t variantCount = pow(2, asteriskCount); printf("%" PRIuLEAST64 "\n", variantCount); } } // The CRT takes care of cleanup. }
the_stack_data/737626.c
//pattern 8: //1234 // 123 // 12 // 1 #include <stdio.h> void main() { int i,j,k; int n =5; //size of the pattern for(i=1;i<=n;i++) { for(k=1;k<=i;k++) printf(" "); for(j=1;j<=n-i+1;j++) printf("%d", j); printf("\n"); } }
the_stack_data/154827939.c
// Manual test to prove the C rules work. #include <stdio.h> #include <stdlib.h> #include <string.h> char kTemplate[] = "<testsuite errors=\"0\" failures=\"0\"></testsuite>"; int main(int argc, char** argv) { // The following line is legal C but not legal C++. char* buf = malloc(strlen(kTemplate) * sizeof(char) + 1); strcpy(buf, kTemplate); FILE* f = fopen("test.results", "w"); fprintf(f, "%s\n", buf); fclose(f); printf("%d %s\n", argc, argv[0]); return 0; }
the_stack_data/131158.c
int f(int a, int b) { if(a > b) b = a; return a + b; } int main() { return 0; }
the_stack_data/95270.c
#include <arpa/inet.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> int main(int argc, char **argv) { if (argc != 2) { printf("Usage: %s <port>\n", argv[0]); exit(0); } int port = atoi(argv[1]); int socketfd = 0; socketfd = socket(AF_INET, SOCK_STREAM, 0); if (socketfd == 0) { perror("Failed to create a socket!\n"); exit(EXIT_FAILURE); } char *m_buffer = NULL; struct sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr("127.0.0.1"); address.sin_port = htons(port); char r_buffer[100]; while (1) { int conn = connect(socketfd, (struct sockaddr *)&address, sizeof(address)); size_t linesize; getline(&m_buffer, &linesize, stdin); send(socketfd, m_buffer, linesize - 1, 0); recv(socketfd, r_buffer, 100, 0); printf("%s", r_buffer); sleep(1); } return EXIT_SUCCESS; }
the_stack_data/654142.c
#include <stdio.h> int main() { float x; float y; scanf("%f", &x); scanf("%f", &y); if(x == 0 && y == 0){ printf("Origem\n"); }else if(x == 0){ printf("Eixo Y\n"); }else if(y == 0){ printf("Eixo X\n"); }else if(x > 0 && y > 0){ printf("Q1\n"); }else if(x > 0 && y < 0){ printf("Q4\n"); }else if(x < 0 && y > 0){ printf("Q2\n"); }else{ printf("Q3\n"); } return 0; }
the_stack_data/161080632.c
extern void abort(void); void reach_error(){} extern unsigned int __VERIFIER_nondet_uint(void); void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: {reach_error();abort();} } return; } int main(void) { unsigned int x = __VERIFIER_nondet_uint(); while (x < 0x0fffffff) { x++; } __VERIFIER_assert(x > 0x0fffffff); }
the_stack_data/220455451.c
#include <stdio.h> #include <stdlib.h> #include <string.h> /* Kyle Thomas - U0000004031 Applied Cryptography 'Project Vigenere' Professor Navid Start Date: 05/24/2018 Finish Date: */ void encrypt(char* key); void decrypt(char* key); void encrypt(char* key) { printf("Please enter a message up to 150 characters you wish to encrypt: \n"); char m[150]; fflush(stdin); scanf("%[^\n]%*c", m); int count = strlen(m); //printf("Key: %c , %c , %c , %c , %c , %c\n", key[0], key[1], key[2], key[3], key[4], key[5]); #debugging //Make the input string upper case int c = 0; while (m[c] != '\0') { if (m[c] >= 'a' && m[c] <= 'z') { m[c] = m[c] - 32; } c++; } //Iterate through the array and add the key based on the index value for (int i = 0, j = 0 ; i < count ; i++){ if (m[i] != ' '){ m[i] = ((m[i] + key[j]) % 26) + 'A'; j = ++j %6; } } m[count] = '\0'; printf("The encrypted string is: \n%s", m); } void decrypt(char* key) { printf("Please enter a message up to 150 characters you wish to decrypt: \n"); char m[150]; fflush(stdin); scanf("%s", m); int count = strlen(m); //Make the input string upper case int c = 0; while (m[c] != '\0') { if (m[c] >= 'a' && m[c] <= 'z') { m[c] = m[c] - 32; } c++; } //Iterate through the array and subtract the key based on the index value for (int i = 0, j = 0; i < count ; i++){ if (m[i] != ' '){ m[i] = (((m[i] - key[j]) + 26) % 26) + 'A'; j = ++j % 6; } } m[count] = '\0'; printf("The original message is: \n%s", m); } int main(void) { char key[] = "THOMAS"; int rerun = 1; while(rerun == 1){ printf("\nMenu: Choose an Option:\n" "1) Encrypt a Message\n" "2) Decrypt a Message\n" "3) Change Your Key (Unavailable Feature)\n"); int *choice = malloc(sizeof(int*)); scanf("%d", choice); switch(*choice) { case 1: encrypt(key); break; case 2: decrypt(key); break; case 3: printf("Error- Feature disabled for this project.\n"); break; default: printf("Error- Invalid input. \n"); } printf("\nDo you want to run again? Enter '1' for yes: "); fflush(stdin); scanf("%d", choice); } return 0; }
the_stack_data/68888774.c
#include <math.h> #define FUNC(x) (2.0*(x)*(*funk)(aa+(x)*(x))) float midsql(float (*funk)(float), float aa, float bb, int n) { float x,tnm,sum,del,ddel,a,b; static float s; int it,j; b=sqrt(bb-aa); a=0.0; if (n == 1) { return (s=(b-a)*FUNC(0.5*(a+b))); } else { for(it=1,j=1;j<n-1;j++) it *= 3; tnm=it; del=(b-a)/(3.0*tnm); ddel=del+del; x=a+0.5*del; sum=0.0; for (j=1;j<=it;j++) { sum += FUNC(x); x += ddel; sum += FUNC(x); x += del; } s=(s+(b-a)*sum/tnm)/3.0; return s; } } #undef FUNC
the_stack_data/59512853.c
/* Concurrent access on a counter with no lock. Atomicity Violation. Data Race in line 14. Inter and Intra Region. */ #include <stdio.h> #define N 100000 int countervar = 0; int count(){ #pragma omp target map(tofrom:countervar) device(0) #pragma omp teams distribute parallel for for (int i=0; i<N; i++){ countervar++; } return 0; } int main(){ count(); printf("counter: %i expected: 100000\n ",countervar); return 0; }
the_stack_data/52070.c
# include <stdio.h> # include <math.h> int vrniDolzino (long long st) { int d = 0; while (st > 0) { st /= 10; d++; } return d; } long long potenca (long long p, long long k) { long long rezultat = 1; while (k > 0){ // Ce je potenca liha potem jo zmanjsaj za ena in pomnozi rezultat // Dobi 1 prvi bit in ga primerja z 1 kar pomenice je je liha if ((k >> 0) & 1) { k--; rezultat *= p; } // Pomnozi osnovo z sabo in zmanjas potenco za eno // Princip kvadratnega ekposniranja // 3 ^ 10 = 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 // 3 ^ 10 = (3 * 3) * (3 * 3) * (3 * 3) * (3 * 3) * (3 * 3) // 3 ^ 10 = ((3 * 3) ^ 5) // 3 ^ 10 = 9 ^ 5 // // in tako dalje p *= p; k /= 2; } return rezultat; } long long dobiPrvihNMest (long long stevilka, int mesta, int kje) { int dolzina = vrniDolzino(stevilka); // Koliko mest long long desetMesta = potenca(10, dolzina - mesta - kje); // Od kje zacnemo long long desetKje = potenca(10, dolzina - kje); // Najprej poreze do prave velikosti v desno potem pa se v levo long long vrni = (stevilka % desetKje) / desetMesta; return vrni; } int main () { long long osnova, mesta; int kjeMesta = 0, kjeOsnova = 0; scanf("%lld%lld", &osnova, &mesta); while (kjeMesta < vrniDolzino(mesta)) { int kolikoIzpisi = dobiPrvihNMest(mesta, 1, kjeMesta); printf("%lld\n", dobiPrvihNMest(osnova, kolikoIzpisi, kjeOsnova)); kjeOsnova += kolikoIzpisi; kjeMesta++; } return 0; }
the_stack_data/43887759.c
#include <pthread.h> #include <stdio.h> int i = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // Note the return type: void* void* incrementingThreadFunction(){ for (int j = 0; j < 1000000; j++) { // TODO: sync access to i pthread_mutex_lock(&mutex); i++; pthread_mutex_unlock(&mutex); } return NULL; } void* decrementingThreadFunction(){ for (int j = 0; j < 1000000; j++) { // TODO: sync access to i pthread_mutex_lock(&mutex); i--; pthread_mutex_unlock(&mutex); } return NULL; } //Mutex is used over semaphores since the resource (variable "i") should only be acsessed by one process at the time. //Therefore it would be a safer option to have a lower accessibility then in semaphores. int main(){ pthread_t incrementingThread, decrementingThread; pthread_create(&incrementingThread, NULL, incrementingThreadFunction, NULL); pthread_create(&decrementingThread, NULL, decrementingThreadFunction, NULL); pthread_join(incrementingThread, NULL); pthread_join(decrementingThread, NULL); printf("The magic number is: %d\n", i); return 0; }
the_stack_data/179831673.c
struct mutex; struct kref; typedef struct { int counter; } atomic_t; int __VERIFIER_nondet_int(void); extern void mutex_lock(struct mutex *lock); extern void mutex_lock_nested(struct mutex *lock, unsigned int subclass); extern int mutex_lock_interruptible(struct mutex *lock); extern int mutex_lock_killable(struct mutex *lock); extern int mutex_lock_interruptible_nested(struct mutex *lock, unsigned int subclass); extern int mutex_lock_killable_nested(struct mutex *lock, unsigned int subclass); static inline int mutex_is_locked(struct mutex *lock); extern int mutex_trylock(struct mutex *lock); extern void mutex_unlock(struct mutex *lock); extern int atomic_dec_and_mutex_lock(atomic_t *cnt, struct mutex *lock); static inline int kref_put_mutex(struct kref *kref, void (*release)(struct kref *kref), struct mutex *lock); static void specific_func(struct kref *kref); void ldv_check_final_state(void); void main(void) { struct mutex *mutex_1, *mutex_2, *mutex_3, *mutex_4, *mutex_5; struct kref *kref; atomic_t *counter; if (mutex_trylock(&mutex_1)) { // double trylock if (atomic_dec_and_mutex_lock(counter, &mutex_1)) { mutex_unlock(&mutex_1); } mutex_unlock(&mutex_1); } ldv_check_final_state(); }
the_stack_data/218894522.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_is_sort.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: akharrou <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/04 10:54:55 by akharrou #+# #+# */ /* Updated: 2018/11/10 21:46:13 by akharrou ### ########.fr */ /* */ /* ************************************************************************** */ int ft_is_sort(int *tab, int length, int (*f)(int, int)) { int i; i = 0; while (i + 1 < length) { if ((*f)(tab[i], tab[i + 1]) > 0) return (0); i++; } return (1); }
the_stack_data/170451795.c
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> #define s(n) scanf("%d",&n) #define sc(n) scanf("%-1c",&n) #define sl(n) scanf("%lld",&n) #define sf(n) scanf("%lf",&n) #define ss(n) scanf("%s",n) #define forall(i,a,b) for(i=a;i<b;i++) #define miN(a,b) ( (a) < (b) ? (a) : (b)) #define maX(a,b) ( (a) > (b) ? (a) : (b)) #define ll long long int #define llu long long unsigned #define ld long #define mod 1000000007 #define P(x) printf("%d\n",x) int main() { int x,y; s(x); s(y); int temp=x-y; if(temp==0 || temp==-1 || temp==1) printf("YES"); else printf("NO"); return 0; }
the_stack_data/75736.c
/* * This software is Copyright (c) 2012 Sayantan Datta <std2048 at gmail dot com> * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without modification, are permitted. * Based on Solar Designer implementation of bf_std.c in jtr-v1.7.8 */ #ifdef HAVE_OPENCL #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <math.h> #include "arch.h" #include "common.h" #include "options.h" #include "opencl_bf_std.h" #include "memdbg.h" #define INDEX [index] #define pos_S(row,col) \ _index_S + (row * 256 + col) * (CHANNEL_INTERLEAVE) #define for_each_index() \ for (index = 0; index < BF_N; index++) #define pos_P(i) \ _index_P + i static unsigned int *BF_current_S ; static unsigned int *BF_current_P ; static unsigned int *BF_init_key ; BF_binary *opencl_BF_out ; typedef struct { cl_mem salt_gpu ; cl_mem P_box_gpu ; cl_mem S_box_gpu ; cl_mem out_gpu ; cl_mem BF_current_S_gpu ; cl_mem BF_current_P_gpu ; } gpu_buffer; static cl_kernel krnl[MAX_PLATFORMS * MAX_DEVICES_PER_PLATFORM]; static gpu_buffer buffers[MAX_PLATFORMS * MAX_DEVICES_PER_PLATFORM]; #define BF_ROUND(ctx_S, ctx_P, L, R, N, tmp1, tmp2, tmp3, tmp4) \ tmp1 = L & 0xFF ; \ tmp2 = L >> 8 ; \ tmp2 &= 0xFF ; \ tmp3 = L >> 16 ; \ tmp3 &= 0xFF ; \ tmp4 = L >> 24 ; \ tmp1 = ctx_S[pos_S(3,tmp1)] ; \ tmp2 = ctx_S[pos_S(2,tmp2)] ; \ tmp3 = ctx_S[pos_S(1,tmp3)] ; \ tmp3 += ctx_S[pos_S(0,tmp4)] ; \ tmp3 ^= tmp2 ; \ R ^= ctx_P[pos_P((N + 1))] ; \ tmp3 += tmp1 ; \ R ^= tmp3 ; /* * Encrypt one block, BF_ROUNDS is hardcoded here. */ #define BF_ENCRYPT(ctx_S, ctx_P, L, R) \ L ^= ctx_P[pos_P(0)]; \ BF_ROUND(ctx_S, ctx_P, L, R, 0, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, R, L, 1, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, L, R, 2, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, R, L, 3, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, L, R, 4, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, R, L, 5, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, L, R, 6, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, R, L, 7, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, L, R, 8, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, R, L, 9, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, L, R, 10, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, R, L, 11, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, L, R, 12, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, R, L, 13, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, L, R, 14, u1, u2, u3, u4) ; \ BF_ROUND(ctx_S, ctx_P, R, L, 15, u1, u2, u3, u4) ; \ u4 = R ; \ R = L ; \ L = u4 ^ ctx_P[pos_P((BF_ROUNDS+1))] ; static void clean_gpu_buffer(gpu_buffer *pThis) { const char *errMsg = "Release Memory Object FAILED." ; HANDLE_CLERROR(clReleaseMemObject(pThis->salt_gpu), errMsg); HANDLE_CLERROR(clReleaseMemObject(pThis-> P_box_gpu), errMsg); HANDLE_CLERROR(clReleaseMemObject(pThis-> S_box_gpu), errMsg); HANDLE_CLERROR(clReleaseMemObject(pThis->out_gpu), errMsg); HANDLE_CLERROR(clReleaseMemObject(pThis->BF_current_S_gpu), errMsg); HANDLE_CLERROR(clReleaseMemObject(pThis->BF_current_P_gpu), errMsg); } void BF_clear_buffer() { clean_gpu_buffer(&buffers[gpu_id]); MEM_FREE(BF_current_S) ; MEM_FREE(BF_current_P) ; MEM_FREE(BF_init_key) ; MEM_FREE(opencl_BF_out) ; HANDLE_CLERROR(clReleaseKernel(krnl[gpu_id]), "Error releasing kernel") ; HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Error releasing Program"); } static void find_best_gws(struct fmt_main *fmt) { struct timeval start,end ; double savetime, diff ; size_t count = local_work_size; double speed = 999999 ; BF_salt random_salt ; random_salt.salt[0] = 0x12345678 ; random_salt.salt[1] = 0x87654321 ; random_salt.salt[2] = 0x21876543 ; random_salt.salt[3] = 0x98765432 ; random_salt.rounds = 5 ; random_salt.subtype = 'x' ; gettimeofday(&start,NULL) ; opencl_BF_std_crypt(&random_salt,count) ; gettimeofday(&end, NULL) ; savetime = (end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000.000; speed = ((double)count) / savetime ; do { count *= 2 ; if (count > BF_N) { count = count >> 1 ; break ; } gettimeofday(&start,NULL) ; opencl_BF_std_crypt(&random_salt,count) ; gettimeofday(&end, NULL) ; savetime = (end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000.000 ; diff = (((double)count) / savetime) / speed ; if (diff < 1) { count = count >> 1 ; break ; } diff = diff - 1 ; diff = (diff < 0)? (-diff): diff ; speed = ((double)count) / savetime ; } while (diff > 0.01) ; fmt->params.max_keys_per_crypt = global_work_size = count; } void BF_select_device(struct fmt_main *fmt) { cl_int err; const char *errMsg; const int lmem_per_th = ((1024 + 4) * sizeof(cl_uint) + 64); char buildopts[32]; BF_current_S = (unsigned int*)mem_alloc(BF_N * 1024 * sizeof(unsigned int)) ; BF_current_P = (unsigned int*)mem_alloc(BF_N * 18 * sizeof(unsigned int)) ; BF_init_key = (unsigned int*)mem_alloc(BF_N * 18 * sizeof(unsigned int)) ; opencl_BF_out = (BF_binary*)mem_alloc(BF_N * sizeof(BF_binary)) ; if (!local_work_size) local_work_size = DEFAULT_LWS; /* device max, regardless of kernel */ if (local_work_size > get_device_max_lws(gpu_id)) local_work_size = get_device_max_lws(gpu_id); /* For GPU kernel, our use of local memory sets a limit for LWS. In extreme cases we even fallback to using CPU kernel. */ if ((get_device_type(gpu_id) != CL_DEVICE_TYPE_CPU) && lmem_per_th < get_local_memory_size(gpu_id)) while (local_work_size > get_local_memory_size(gpu_id) / lmem_per_th) local_work_size >>= 1; if ((get_device_type(gpu_id) == CL_DEVICE_TYPE_CPU) || amd_vliw5(device_info[gpu_id]) || (get_local_memory_size(gpu_id) < local_work_size * lmem_per_th)) { if (CHANNEL_INTERLEAVE == 1) opencl_init("$JOHN/kernels/bf_cpu_kernel.cl", gpu_id, NULL); else { fprintf(stderr, "Please set NUM_CHANNELS and " "WAVEFRONT_SIZE to 1 in opencl_bf_std.h"); error(); } } else { snprintf(buildopts, sizeof(buildopts), "-DWORK_GROUP_SIZE="Zu, local_work_size); opencl_init("$JOHN/kernels/bf_kernel.cl", gpu_id, buildopts); } krnl[gpu_id] = clCreateKernel(program[gpu_id], "blowfish", &err) ; if (err) { fprintf(stderr, "Create Kernel blowfish FAILED\n") ; return ; } /* This time we ask about max size for this very kernel */ if (local_work_size > get_kernel_max_lws(gpu_id, krnl[gpu_id])) local_work_size = get_kernel_max_lws(gpu_id, krnl[gpu_id]); errMsg = "Create Buffer Failed" ; buffers[gpu_id].salt_gpu = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, 4 * sizeof(cl_uint), NULL, &err) ; if (buffers[gpu_id].salt_gpu == (cl_mem)0) HANDLE_CLERROR(err, errMsg) ; buffers[gpu_id].P_box_gpu = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR, sizeof(cl_uint) * 18, BF_init_state.P, &err) ; if (buffers[gpu_id].P_box_gpu == (cl_mem)0) HANDLE_CLERROR(err, errMsg) ; buffers[gpu_id].S_box_gpu = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR, sizeof(cl_uint) * 1024, BF_init_state.S, &err) ; if (buffers[gpu_id].S_box_gpu==(cl_mem)0) HANDLE_CLERROR(err, errMsg) ; buffers[gpu_id].out_gpu = clCreateBuffer(context[gpu_id], CL_MEM_READ_WRITE, BF_N * sizeof(cl_uint) * 2, NULL, &err) ; if (buffers[gpu_id].out_gpu == (cl_mem)0) HANDLE_CLERROR(err, errMsg) ; buffers[gpu_id].BF_current_S_gpu = clCreateBuffer(context[gpu_id], CL_MEM_READ_WRITE, BF_N * 1024 * sizeof(unsigned int), NULL, &err) ; if (buffers[gpu_id].BF_current_S_gpu == (cl_mem)0) HANDLE_CLERROR(err, errMsg) ; buffers[gpu_id].BF_current_P_gpu = clCreateBuffer(context[gpu_id], CL_MEM_READ_WRITE, BF_N * sizeof(unsigned int) * 18, NULL, &err) ; if (buffers[gpu_id].BF_current_P_gpu==(cl_mem)0) HANDLE_CLERROR(err, errMsg) ; HANDLE_CLERROR(clSetKernelArg(krnl[gpu_id], 0, sizeof(cl_mem), &buffers[gpu_id].salt_gpu), "Set Kernel Arg FAILED arg0") ; HANDLE_CLERROR(clSetKernelArg(krnl[gpu_id], 1, sizeof(cl_mem), &buffers[gpu_id].P_box_gpu), "Set Kernel Arg FAILED arg1") ; HANDLE_CLERROR(clSetKernelArg(krnl[gpu_id], 2, sizeof(cl_mem), &buffers[gpu_id].out_gpu), "Set Kernel Arg FAILED arg2") ; HANDLE_CLERROR(clSetKernelArg(krnl[gpu_id], 3, sizeof(cl_mem), &buffers[gpu_id].BF_current_S_gpu), "Set Kernel Arg FAILED arg3") ; HANDLE_CLERROR(clSetKernelArg(krnl[gpu_id], 4, sizeof(cl_mem), &buffers[gpu_id].BF_current_P_gpu), "Set Kernel Arg FAILED arg4"); HANDLE_CLERROR(clSetKernelArg(krnl[gpu_id], 6, sizeof(cl_mem), &buffers[gpu_id].S_box_gpu), "Set Kernel Arg FAILED arg6") ; fmt->params.min_keys_per_crypt = local_work_size; if (global_work_size) { global_work_size = global_work_size / local_work_size * local_work_size; if (global_work_size > BF_N) global_work_size = BF_N; fmt->params.max_keys_per_crypt = global_work_size; } else find_best_gws(fmt); if (options.verbosity > VERB_LEGACY) fprintf(stderr, "Local worksize (LWS) %d, Global worksize (GWS) %d\n", (int)local_work_size, (int)global_work_size); } void opencl_BF_std_set_key(char *key, int index, int sign_extension_bug) { char *ptr = key ; int i, j, _index_P = index * 18 ; BF_word tmp ; for (i = 0; i < BF_ROUNDS + 2; i++) { tmp = 0 ; for (j = 0; j < 4; j++) { tmp <<= 8 ; if (sign_extension_bug) tmp |= (int)(signed char)*ptr ; else tmp |= (unsigned char)*ptr ; if (!*ptr) ptr = key ; else ptr++ ; } BF_init_key[pos_P(i)] = BF_init_state.P[i] ^ tmp ; } } void exec_bf(cl_uint *salt_api, cl_uint *BF_out, cl_uint rounds, int n) { cl_event evnt ; cl_int err ; size_t N, M = local_work_size; double temp ; const char *errMsg ; temp = log((double)n) / log((double)2) ; n = (int)temp ; ///Make sure amount of work isn't unnecessarily doubled if ((temp - n) != 0) { if ((temp - n) < 0.00001) n = (int)pow((double)2, (double)n) ; else if ((n + 1 - temp) < 0.00001) n = (int)pow((double)2, (double)n) ; else n = (int)pow((double)2, (double)(n+1)) ; } else n = (int)pow((double)2, (double)n) ; n = (n > BF_N)? BF_N: n ; n = (n < (2*M))? 2*M: n ; if (CL_DEVICE_TYPE_CPU == get_device_type(gpu_id)) N = n/2 ; ///Two hashes per crypt call for cpu else N = n ; /* N has to be a multiple of M */ N = (N + M - 1) / M * M; errMsg = "Copy data to device: Failed" ; HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], buffers[gpu_id].salt_gpu, CL_TRUE, 0, 4 * sizeof(cl_uint), salt_api, 0, NULL, NULL ), errMsg) ; HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], buffers[gpu_id].BF_current_P_gpu, CL_TRUE, 0, BF_N*sizeof(unsigned int)*18, BF_init_key, 0, NULL, NULL ), errMsg) ; HANDLE_CLERROR(clSetKernelArg(krnl[gpu_id], 5, sizeof(cl_uint), &rounds),"Set Kernel Arg FAILED arg5"); err = clEnqueueNDRangeKernel(queue[gpu_id], krnl[gpu_id], 1, NULL, &N, &M, 0, NULL, &evnt) ; HANDLE_CLERROR(err, "Enque Kernel Failed") ; HANDLE_CLERROR(clWaitForEvents(1, &evnt), "Sync :FAILED") ; clReleaseEvent(evnt); errMsg = "Read data from device: Failed" ; HANDLE_CLERROR(clEnqueueReadBuffer(queue[gpu_id], buffers[gpu_id].out_gpu, CL_FALSE, 0, 2 * BF_N * sizeof(cl_uint), BF_out, 0, NULL, NULL), errMsg) ; HANDLE_CLERROR(clEnqueueReadBuffer(queue[gpu_id], buffers[gpu_id].BF_current_P_gpu, CL_FALSE, 0, BF_N * sizeof(unsigned int) * 18, BF_current_P, 0, NULL, NULL), errMsg) ; HANDLE_CLERROR(clEnqueueReadBuffer(queue[gpu_id], buffers[gpu_id].BF_current_S_gpu, CL_TRUE, 0, BF_N * 1024 * sizeof(unsigned int), BF_current_S, 0, NULL, NULL), errMsg) ; HANDLE_CLERROR(clFinish(queue[gpu_id]), "Finish Error") ; } void opencl_BF_std_crypt(BF_salt *salt, int n) { int index=0,j ; static unsigned int salt_api[4] ; unsigned int rounds = salt -> rounds ; static unsigned int BF_out[2*BF_N] ; salt_api[0] = salt -> salt[0] ; salt_api[1] = salt -> salt[1] ; salt_api[2] = salt -> salt[2] ; salt_api[3] = salt -> salt[3] ; exec_bf(salt_api, BF_out, rounds, n) ; for_each_index(){ j=2*index ; opencl_BF_out INDEX[0] = BF_out[j++] ; opencl_BF_out INDEX[1] = BF_out[j] ; } } void opencl_BF_std_crypt_exact(int index) { BF_word L, R; BF_word u1, u2, u3, u4; BF_word count; int i, _index_S = (index / (CHANNEL_INTERLEAVE)) * (CHANNEL_INTERLEAVE) * 1024 + index % (CHANNEL_INTERLEAVE), _index_P = index * 18 ; memcpy(&opencl_BF_out[index][2], &BF_magic_w[2], sizeof(BF_word) * 4) ; count = 64 ; do for (i = 2; i < 6; i += 2) { L = opencl_BF_out[index][i] ; R = opencl_BF_out[index][i + 1] ; BF_ENCRYPT(BF_current_S,BF_current_P, L, R) ; opencl_BF_out[index][i] = L ; opencl_BF_out[index][i + 1] = R ; } while (--count) ; /* This has to be bug-compatible with the original implementation :-) */ opencl_BF_out[index][5] &= ~(BF_word)0xFF ; } #endif /* HAVE_OPENCL */
the_stack_data/40761972.c
// echo.c -- repeat user's input #include <stdio.h> int main() { char ch; while ((ch = getchar()) != '#') putchar(ch); return 0; }
the_stack_data/1222933.c
a[]; b; c() { a[2] = a[3] = a[4] = a[5] = 5; if (b) a[0] = a[1] = a[2] = a[3] = 8; }
the_stack_data/323211.c
//***************************************************************************** // // startup_codered.c - Startup code for use with code_red tools. // // Copyright (c) 2009-2012 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 9107 of the DK-LM3S9B96 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 SysTickIntHandler(void); extern void UARTStdioIntHandler(void); extern void USB0DeviceIntHandler(void); //***************************************************************************** // // The entry point for the application. // //***************************************************************************** #if defined(__REDLIB__) #define __MAIN__ __main #else #define __MAIN__ main #endif extern int __MAIN__(void); //***************************************************************************** // // Reserve space for the system stack. // //***************************************************************************** extern unsigned long _vStackTop; //***************************************************************************** // // 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)&_vStackTop), // 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 UARTStdioIntHandler, // 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 IntDefaultHandler, // CAN0 IntDefaultHandler, // CAN1 IntDefaultHandler, // CAN2 IntDefaultHandler, // Ethernet IntDefaultHandler, // Hibernate USB0DeviceIntHandler, // USB0 IntDefaultHandler, // PWM Generator 3 IntDefaultHandler, // uDMA Software Transfer IntDefaultHandler, // uDMA Error IntDefaultHandler, // ADC1 Sequence 0 IntDefaultHandler, // ADC1 Sequence 1 IntDefaultHandler, // ADC1 Sequence 2 IntDefaultHandler, // ADC1 Sequence 3 IntDefaultHandler, // I2S0 IntDefaultHandler, // External Bus Interface 0 IntDefaultHandler // GPIO Port J }; //***************************************************************************** // // 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/304557.c
// Write a menu driven program to implement following operations on the singly linked list. Design a function create to create a link list (which is required to be called only for one time for a link list) // (a) create [ node * create() ] // (b) display [ void display(node *start) ] // (c) length [ int length (node *start) ] // (d) maximum [int maximum (node *start)] // (e) merge (to merge two link list in to the third one) [node * merge(node *start1, node *start2) // (f) sort [void sort(node *start) ] // (g) reverse [ node * reverse (node *start)] // h) Insert a node at the front of the linked list. [ node * insert_front(node *start, int no) ] // (i) Insert a node at the end of the linked list. [ node * insert_end(node *start, int no) ] // (j) Insert a node such that linked list is in ascending order.(according to info. Field) [ node * insert_sort(node *start, int no) ] // (k) Delete a first node of the linked list. [ node * delete_first(node *start) ] // (l) Delete a node before specified position. [ node * delete_before(node *start, int pos) ] // (m) Delete a node after specified position. [ node * delete_after(node *, int pos) ] // (n) No search [ int search (node*, int x) ] #include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; struct node* create(){ struct node *head = (struct node*)malloc(sizeof(struct node)); int data; printf("Enter value of head node: "); scanf("%d",&data); head->data = data; head->next = NULL; printf("Linked list created, head at %p\n\t\tValue = %d\n",head,head->data); return head; } void display(struct node* head){ while(head!=NULL){ printf("%d -> ",head->data); head = head->next; } printf("NULL\n"); } int length(struct node* head){ int counter = 0; while(head!=NULL){ counter++; head = head->next; } return counter; } int maximum(struct node* head){ int max = head->data; while(head != NULL){ if(head->data > max) max = head-> data; head = head->next; } return max; } struct node* merge(struct node* start1, struct node* start2){ if(length(start1)==0) return start2; if(length(start2)==0) return start1; struct node *loop,*head,*connector; connector = (struct node *)malloc(sizeof(struct node)); loop = (struct node *)malloc(sizeof(struct node)); loop = start1; head = start1; while(loop!=NULL){ struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); temp = loop->next; if(loop->next == NULL) connector = loop; loop = loop->next; } connector->next = start2; loop = start2; while(loop != NULL){ struct node* temp; temp = (struct node*)malloc(sizeof(struct node)); temp = loop->next; loop = loop->next; } return head; } void sort(struct node* head){ int len = length(head),i,j,temp; struct node *temp1,*temp2; // = (struct node*)malloc(sizeof(struct node)); temp1 = head; for(i=0;i<len;i++){ temp2 = temp1->next; for(j=i+1;j<len;j++){ if (temp1->data > temp2->data){ int t = temp1->data; temp1->data = temp2->data; temp2->data = t; } temp2 = temp2->next; } temp1 = temp1->next; } } int isEmpty(int top){ if(top==-1){ return 1; }else{ return 0; } } void push(int *stack, int *top, int value){ (*top)++; stack[*top] = value; } int pop(int *stack, int *top){ if(isEmpty(*top)){ printf("Stack is Empty!"); exit(0); } (*top)--; return stack[(*top)+1]; } struct node* reverse(struct node* start){ int *stack = (int*)calloc(length(start),sizeof(int)), top = 1, i = 0, j = 0; struct node *head = (struct node *)malloc(sizeof(struct node)), *temp; if(length(start)==1){ head = start; return head; } while(start!=NULL){ push(stack,&top,start->data); start = start->next; } // head->data = pop(stack,&top); temp = head; while(1){ temp->data=pop(stack,&top); if(top>1){ temp->next = (struct node *)malloc(sizeof(struct node)); temp = temp->next; } else{ temp->next = NULL; break; } } return head; } struct node* insertAtHead(struct node* head, int data){ struct node *temp = (struct node*)malloc(sizeof(struct node)); temp->data = data; temp->next = head; return temp; } struct node* insertAtTail(struct node* head, int data){ struct node *temp = head, *temp2; while(temp->next != NULL) temp = temp->next; temp2 = (struct node*)malloc(sizeof(struct node)); temp2->data = data; temp2->next = NULL; temp->next = temp2; return head; } struct node *insertSort(struct node* head, int info){ struct node *current = head,*tbi; // to be inserted = tbi tbi = (struct node*)malloc(sizeof(struct node)); tbi->data = info; if(current == NULL){ tbi->next = NULL; return tbi; } if(info < head->data){ tbi->next = head; return tbi; } while(current->next != NULL && current->next->data < tbi->data) current = current->next; tbi->next = current->next; current->next = tbi; return head; } struct node* deleteAtHead(struct node* head){ struct node* temp; temp = head; head = head->next; free(temp); return head; } struct node* deleteBefore(struct node* head, int pos){ if(pos > length(head) || pos == 1){ printf("Invalid position\n"); return head; } if(pos == 2){ head = deleteAtHead(head); return head; } struct node* temp = head,*toClr; int i; for(i=1;i<=pos-3;i++) temp = temp->next; toClr = temp->next; temp->next = temp->next->next; free(toClr); return head; } struct node* deleteAfter(struct node* head, int pos){ if(pos >= length(head)){ printf("Invalid position\n"); return head; } struct node *temp=head,*toClr; int i; for(i=1;i<=pos-1;i++) temp = temp->next; toClr = temp->next; temp->next = toClr->next; free(toClr); return head; } struct node* deleteNumber(struct node* head, int num){ struct node *temp = head,*toClr; if(head->data == num){ head = deleteAtHead(head); return head; } while(temp->next != NULL && temp->next->data != num){ temp = temp->next; } if(temp->next == NULL){ printf("Number not found\n"); return head; } toClr = temp->next; temp->next = temp->next->next; free(toClr); return head; } int search(struct node* head, int x){ while(head->data != x && head->next != NULL) head = head->next; if(head->data == x) return x; return -9999; } int main(){ int menu=0; struct node *head1,*head2,*head3; printf("Program written by enrollment number 200420107012\n1. Create\n2. Display\n3. Length\n4. Maximum\n5. Merge\n6. Sort\n7. Reverse\n8. Insert at head\n9. Insend\n10. Insord\n11. Delete head\n12. Delete before\n13. Delete After\n14. Delete number\n15. Search\n16. Exit\n"); while (menu != 16){ printf("Enter a choice: "); scanf("%d",&menu); switch(menu){ case 1: head1 = create(); break; case 2: display(head1); break; case 3:; int len; len = length(head1); printf("There are %d elements in the LL\n",len); break; case 4:; int max; max = maximum(head1); printf("Maximum value in the LL is %d\n",max); break; case 5: head2 = create(); int data2; printf("Enter value of next element for LL2: "); scanf("%d",&data2); head2 = insertAtTail(head2,data2); head3 = merge(head1,head2); display(head3); break; case 6: printf("Sorting list...\n"); sort(head1); display(head1); break; case 7:; printf("Reversing list...\n"); struct node *reverseHead = reverse(head1); display(reverseHead); break; case 8:; int dataH; printf("Enter value of node: "); scanf("%d",&dataH); head1 = insertAtHead(head1,dataH); break; case 9:; int dataT; printf("Enter value of node: "); scanf("%d",&dataT); head1 = insertAtTail(head1,dataT); break; case 10:; int dataS; printf("Enter value of node: "); scanf("%d",&dataS); head1 = insertSort(head1,dataS); display(head1); break; case 11: head1 = deleteAtHead(head1); display(head1); break; case 12:; int posB; printf("Enter position (head is 1): "); scanf("%d",&posB); head1 = deleteBefore(head1,posB); display(head1); break; case 13:; int posA; printf("Enter position (head is 1): "); scanf("%d",&posA); head1 = deleteAfter(head1,posA); display(head1); break; case 14:; int num; printf("Enter number to delete: "); scanf("%d",&num); head1 = deleteNumber(head1,num); display(head1); break; case 15:; int x,result; printf("Enter data to search: "); scanf("%d",&x); result = search(head1,x); (result == -9999) ? printf("Value not found in linked list!\n") : printf("%d found in linked list\n",result); break; case 16: return 0; default: printf("Choose correct option\n"); break; } menu=0; } return 0; }
the_stack_data/144705.c
/* * @Author: Rohit Nagraj * @Date: 2019-04-27 10:31:23 * @Last Modified by: Rohit Nagraj * @Last Modified time: 2019-04-08 21:26:22 */ /* * Question: Find Minimum Cost Spanning Tree of a given undirected graph using * Kruskal's algorithm. Give the trace of this algorithm. */ /* * Explaination: https://www.youtube.com/watch?v=4ZlRH0eK-qQ * Logic: Keep picking the shortest edges and as long as an edge is not * forming a cycle, continue till all the vertices are covered. This * implementation uses priority queue to sort * Time complexity: O(vE) = O(n^2) * Space complexity: O(n) */ #include <stdio.h> #include <time.h> struct edge { int node1; int node2; int len; } priorityQ[40], result[10]; int priorityFront = -1, priorityRear = -1, resultFront = -1, resultRear = -1; int priorityLen = 0, resultLen = 0; void priorityEnqueue(struct edge e) // Enqueue function for the priority queue { int i; if (priorityFront == -1) { priorityFront = 0; priorityRear = 0; priorityQ[priorityRear].len = e.len; priorityQ[priorityRear].node1 = e.node1; priorityQ[priorityRear].node2 = e.node2; priorityLen++; return; } for (i = priorityRear; i >= 0; i--) { if (priorityQ[i].len > e.len) { priorityQ[i + 1] = priorityQ[i]; } else { break; } } priorityQ[i + 1].len = e.len; priorityQ[i + 1].node1 = e.node1; priorityQ[i + 1].node2 = e.node2; priorityRear++; priorityLen++; } struct edge priorityDequeue() // Dequeue() for the priority queue { struct edge e; e.len = priorityQ[priorityFront].len; e.node1 = priorityQ[priorityFront].node1; e.node2 = priorityQ[priorityFront++].node2; return e; } void resultEnqueue(struct edge e) // Enqueue() for the result queue { if (resultFront == -1) { resultFront = 0; resultRear = 0; result[resultRear].len = e.len; result[resultRear].node1 = e.node1; result[resultRear].node2 = e.node2; resultLen++; return; } result[++resultRear].len = e.len; result[resultRear].node1 = e.node1; result[resultRear].node2 = e.node2; resultLen++; } struct edge resultDequeue() // Dequeue for the result queue { struct edge e; e.len = result[resultFront].len; e.node1 = result[resultFront].node1; e.node2 = result[resultFront++].node2; return e; } int cyclic(struct edge e) // to check of the edge passed as parameter creates // a cycle with the existing edges { int i, visited[10] = {0}, counter = 0; for (i = 0; i < resultLen; i++) { visited[result[i].node1] = 1; visited[result[i].node2] = 1; } visited[e.node1] = 1; visited[e.node2] = 1; for (i = 0; i < 10; i++) if (visited[i]) counter++; if (counter >= resultLen + 2) return 0; return 1; } void printResult() { int i, totalCost = 0; struct edge e; for (i = 0; i < resultLen; i++) { e = resultDequeue(); printf("Edge %d: Node %d to Node %d\n", i + 1, e.node1, e.node2); totalCost += e.len; } printf("Total cost: %d\n", totalCost); } void kruskal(int adj[][10], int n) { clock_t start = clock(); int visited[10] = {0}, i, j; struct edge e; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) // j=i+1 for undirected, j=0 for directed { if (adj[i][j]) { e.node1 = i; e.node2 = j; e.len = adj[i][j]; priorityEnqueue(e); } } } for (i = 0; i < priorityLen; i++) { e = priorityDequeue(); if (!cyclic(e)) { resultEnqueue(e); } if (resultLen == n - 1) break; } if (resultLen == n - 1) printResult(); else printf("No spanning tree could be generated\n"); printf("%f", ((double)(clock() - start)) / CLOCKS_PER_SEC); } int main() { int adj[10][10], n, i, j; printf("Enter the no. of vertices: "); scanf("%d", &n); printf("Enter the adjacency matrix:-\n"); for (i = 0; i < n; i++) for (j = 0; j < n; j++) scanf("%d", &adj[i][j]); kruskal(adj, n); return (0); }
the_stack_data/165768757.c
/* Write a program that asks a number and test the number whether it is multiple of 5 or not, divisible by 7 but not by eleven. */ #include <stdio.h> int main() { int num; printf("Enter a number:\n"); scanf("%d", &num); if (num % 5 == 0) { printf("%d is multiple of 5\n", num); } else if (num % 7 == 0 && num % 11 != 0) { printf("%d is multiple of 7 but not of 11\n", num); } else { printf("%d is not multiple of 5 and 7.\n", num); } return 0; }
the_stack_data/117328260.c
int min(int a,int b){ return a < b ? a : b; }
the_stack_data/67325369.c
int foo(int a) { int x = 10; for (; x > 0; ) { ///First pass, ///compute x as [min..max], apply the special operator after two iterations /// old range of x is [8..12], new range of x is [7..13], widening the lowerbound and the upper bound /// so we have new range of x as [min..max] ///Second pass, ///compute x as [1..max], initial range of x is [min..max] if (a) x = x + 1; else x = x -1 ; } return x; } /// Expected output /// [0..0]
the_stack_data/877317.c
// RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv5 %s | FileCheck %s -check-prefix CHECK-V5 // CHECK-V5: #define __HEXAGON_ARCH__ 5 // CHECK-V5: #define __HEXAGON_V5__ 1 // CHECK-V5-NOT: #define __HVX_LENGTH__ // CHECK-V5-NOT: #define __HVX__ 1 // CHECK-V5: #define __hexagon__ 1 // RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv55 %s | FileCheck %s -check-prefix CHECK-V55 // CHECK-V55: #define __HEXAGON_ARCH__ 55 // CHECK-V55: #define __HEXAGON_V55__ 1 // CHECK-V55-NOT: #define __HVX_LENGTH__ // CHECK-V55-NOT: #define __HVX__ 1 // CHECK-V55: #define __hexagon__ 1 // RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv60 %s | FileCheck %s -check-prefix CHECK-V60 // CHECK-V60: #define __HEXAGON_ARCH__ 60 // CHECK-V60: #define __HEXAGON_V60__ 1 // CHECK-V60-NOT: #define __HVX_LENGTH__ // CHECK-V60-NOT: #define __HVX__ 1 // CHECK-V60: #define __hexagon__ 1 // RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv62 %s | FileCheck %s -check-prefix CHECK-V62 // CHECK-V62: #define __HEXAGON_ARCH__ 62 // CHECK-V62: #define __HEXAGON_V62__ 1 // CHECK-V62-NOT: #define __HVX_LENGTH__ // CHECK-V62-NOT: #define __HVX__ 1 // CHECK-V62: #define __hexagon__ 1 // RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv65 %s | FileCheck %s -check-prefix CHECK-V65 // CHECK-V65: #define __HEXAGON_ARCH__ 65 // CHECK-V65: #define __HEXAGON_V65__ 1 // CHECK-V65-NOT: #define __HVX_LENGTH__ // CHECK-V65-NOT: #define __HVX__ 1 // CHECK-V65: #define __hexagon__ 1 // RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv66 %s | FileCheck %s -check-prefix CHECK-V66 // CHECK-V66: #define __HEXAGON_ARCH__ 66 // CHECK-V66: #define __HEXAGON_V66__ 1 // CHECK-V66-NOT: #define __HVX_LENGTH__ // CHECK-V66-NOT: #define __HVX__ 1 // CHECK-V66: #define __hexagon__ 1 // The HVX flags are explicitly defined by the driver. // For v60,v62,v65 - 64B mode is default // For v66 and future archs - 128B is default // RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv60 \ // RUN: -target-feature +hvxv60 -target-feature +hvx-length64b %s | FileCheck \ // RUN: %s -check-prefix CHECK-V60HVX-64B // CHECK-V60HVX-64B: #define __HEXAGON_ARCH__ 60 // CHECK-V60HVX-64B: #define __HEXAGON_V60__ 1 // CHECK-V60HVX-64B-NOT: #define __HVXDBL__ 1 // CHECK-V60HVX-64B: #define __HVX_ARCH__ 60 // CHECK-V60HVX-64B: #define __HVX_LENGTH__ 64 // CHECK-V60HVX-64B: #define __HVX__ 1 // CHECK-V60HVX-64B: #define __hexagon__ 1 // RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv60 \ // RUN: -target-feature +hvxv60 -target-feature +hvx-length128b %s | FileCheck \ // RUN: %s -check-prefix CHECK-V60HVX-128B // CHECK-V60HVX-128B: #define __HEXAGON_ARCH__ 60 // CHECK-V60HVX-128B: #define __HEXAGON_V60__ 1 // CHECK-V60HVX-128B: #define __HVXDBL__ 1 // CHECK-V60HVX-128B: #define __HVX_ARCH__ 60 // CHECK-V60HVX-128B: #define __HVX_LENGTH__ 128 // CHECK-V60HVX-128B: #define __HVX__ 1 // CHECK-V60HVX-128B: #define __hexagon__ 1 // RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv66 \ // RUN: -target-feature +hvxv66 -target-feature +hvx-length64b %s | FileCheck \ // RUN: %s -check-prefix CHECK-V66HVX-64B // CHECK-V66HVX-64B: #define __HEXAGON_ARCH__ 66 // CHECK-V66HVX-64B: #define __HEXAGON_V66__ 1 // CHECK-V66HVX-64B-NOT: #define __HVXDBL__ 1 // CHECK-V66HVX-64B: #define __HVX_ARCH__ 66 // CHECK-V66HVX-64B: #define __HVX_LENGTH__ 64 // CHECK-V66HVX-64B: #define __HVX__ 1 // CHECK-V66HVX-64B: #define __hexagon__ 1 // RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv66 \ // RUN: -target-feature +hvxv66 -target-feature +hvx-length128b %s | FileCheck \ // RUN: %s -check-prefix CHECK-V66HVX-128B // CHECK-V66HVX-128B: #define __HEXAGON_ARCH__ 66 // CHECK-V66HVX-128B: #define __HEXAGON_V66__ 1 // CHECK-V66HVX-128B: #define __HVXDBL__ 1 // CHECK-V66HVX-128B: #define __HVX_ARCH__ 66 // CHECK-V66HVX-128B: #define __HVX_LENGTH__ 128 // CHECK-V66HVX-128B: #define __HVX__ 1 // CHECK-V66HVX-128B: #define __hexagon__ 1 // RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv67 \ // RUN: -target-feature +hvxv67 -target-feature +hvx-length128b %s | FileCheck \ // RUN: %s -check-prefix CHECK-V67HVX-128B // CHECK-V67HVX-128B: #define __HEXAGON_ARCH__ 67 // CHECK-V67HVX-128B: #define __HEXAGON_V67__ 1 // CHECK-V67HVX-128B: #define __HVX_ARCH__ 67 // CHECK-V67HVX-128B: #define __HVX_LENGTH__ 128 // CHECK-V67HVX-128B: #define __HVX__ 1 // CHECK-V67HVX-128B: #define __hexagon__ 1 // RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv67 \ // RUN: -target-feature +hvxv67 -target-feature +hvx-length128b %s | FileCheck \ // RUN: %s -check-prefix CHECK-ELF // CHECK-ELF: #define __ELF__ 1
the_stack_data/107954353.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs // RUN: %clang_cc1 -fopenmp-enable-irbuilder -verify -fopenmp -fopenmp-version=51 -x c -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s // expected-no-diagnostics #ifndef HEADER #define HEADER // CHECK-LABEL: define {{.*}}@unroll_partial_factor( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[A_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[B_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[C_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[D_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[I:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[AGG_CAPTURED:.+]] = alloca %struct.anon, align 8 // CHECK-NEXT: %[[AGG_CAPTURED1:.+]] = alloca %struct.anon.0, align 4 // CHECK-NEXT: %[[DOTCOUNT_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: store float* %[[A:.+]], float** %[[A_ADDR]], align 8 // CHECK-NEXT: store float* %[[B:.+]], float** %[[B_ADDR]], align 8 // CHECK-NEXT: store float* %[[C:.+]], float** %[[C_ADDR]], align 8 // CHECK-NEXT: store float* %[[D:.+]], float** %[[D_ADDR]], align 8 // CHECK-NEXT: store i32 0, i32* %[[I]], align 4 // CHECK-NEXT: %[[TMP0:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[AGG_CAPTURED]], i32 0, i32 0 // CHECK-NEXT: store i32* %[[I]], i32** %[[TMP0]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[AGG_CAPTURED1]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: store i32 %[[TMP2]], i32* %[[TMP1]], align 4 // CHECK-NEXT: call void @__captured_stmt(i32* %[[DOTCOUNT_ADDR]], %struct.anon* %[[AGG_CAPTURED]]) // CHECK-NEXT: %[[DOTCOUNT:.+]] = load i32, i32* %[[DOTCOUNT_ADDR]], align 4 // CHECK-NEXT: br label %[[OMP_LOOP_PREHEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_PREHEADER]]: // CHECK-NEXT: br label %[[OMP_LOOP_HEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_HEADER]]: // CHECK-NEXT: %[[OMP_LOOP_IV:.+]] = phi i32 [ 0, %[[OMP_LOOP_PREHEADER]] ], [ %[[OMP_LOOP_NEXT:.+]], %[[OMP_LOOP_INC:.+]] ] // CHECK-NEXT: br label %[[OMP_LOOP_COND:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_COND]]: // CHECK-NEXT: %[[OMP_LOOP_CMP:.+]] = icmp ult i32 %[[OMP_LOOP_IV]], %[[DOTCOUNT]] // CHECK-NEXT: br i1 %[[OMP_LOOP_CMP]], label %[[OMP_LOOP_BODY:.+]], label %[[OMP_LOOP_EXIT:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_BODY]]: // CHECK-NEXT: call void @__captured_stmt.1(i32* %[[I]], i32 %[[OMP_LOOP_IV]], %struct.anon.0* %[[AGG_CAPTURED1]]) // CHECK-NEXT: %[[TMP3:.+]] = load float*, float** %[[B_ADDR]], align 8 // CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM:.+]] = sext i32 %[[TMP4]] to i64 // CHECK-NEXT: %[[ARRAYIDX:.+]] = getelementptr inbounds float, float* %[[TMP3]], i64 %[[IDXPROM]] // CHECK-NEXT: %[[TMP5:.+]] = load float, float* %[[ARRAYIDX]], align 4 // CHECK-NEXT: %[[TMP6:.+]] = load float*, float** %[[C_ADDR]], align 8 // CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM2:.+]] = sext i32 %[[TMP7]] to i64 // CHECK-NEXT: %[[ARRAYIDX3:.+]] = getelementptr inbounds float, float* %[[TMP6]], i64 %[[IDXPROM2]] // CHECK-NEXT: %[[TMP8:.+]] = load float, float* %[[ARRAYIDX3]], align 4 // CHECK-NEXT: %[[MUL:.+]] = fmul float %[[TMP5]], %[[TMP8]] // CHECK-NEXT: %[[TMP9:.+]] = load float*, float** %[[D_ADDR]], align 8 // CHECK-NEXT: %[[TMP10:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM4:.+]] = sext i32 %[[TMP10]] to i64 // CHECK-NEXT: %[[ARRAYIDX5:.+]] = getelementptr inbounds float, float* %[[TMP9]], i64 %[[IDXPROM4]] // CHECK-NEXT: %[[TMP11:.+]] = load float, float* %[[ARRAYIDX5]], align 4 // CHECK-NEXT: %[[MUL6:.+]] = fmul float %[[MUL]], %[[TMP11]] // CHECK-NEXT: %[[TMP12:.+]] = load float*, float** %[[A_ADDR]], align 8 // CHECK-NEXT: %[[TMP13:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM7:.+]] = sext i32 %[[TMP13]] to i64 // CHECK-NEXT: %[[ARRAYIDX8:.+]] = getelementptr inbounds float, float* %[[TMP12]], i64 %[[IDXPROM7]] // CHECK-NEXT: store float %[[MUL6]], float* %[[ARRAYIDX8]], align 4 // CHECK-NEXT: br label %[[OMP_LOOP_INC]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_INC]]: // CHECK-NEXT: %[[OMP_LOOP_NEXT]] = add nuw i32 %[[OMP_LOOP_IV]], 1 // CHECK-NEXT: br label %[[OMP_LOOP_HEADER]], !llvm.loop ![[LOOP3:[0-9]+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_EXIT]]: // CHECK-NEXT: br label %[[OMP_LOOP_AFTER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_AFTER]]: // CHECK-NEXT: ret void // CHECK-NEXT: } void unroll_partial_factor(float *a, float *b, float *c, float *d) { #pragma omp unroll partial(3) for (int i = 0; i < 2; i++) { a[i] = b[i] * c[i] * d[i]; } } #endif // HEADER // CHECK-LABEL: define {{.*}}@__captured_stmt( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[DISTANCE_ADDR:.+]] = alloca i32*, align 8 // CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon*, align 8 // CHECK-NEXT: %[[DOTSTART:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTSTOP:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTSTEP:.+]] = alloca i32, align 4 // CHECK-NEXT: store i32* %[[DISTANCE:.+]], i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store %struct.anon* %[[__CONTEXT:.+]], %struct.anon** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon*, %struct.anon** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[TMP0]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32*, i32** %[[TMP1]], align 8 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[TMP2]], align 4 // CHECK-NEXT: store i32 %[[TMP3]], i32* %[[DOTSTART]], align 4 // CHECK-NEXT: store i32 2, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: store i32 1, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[TMP5:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[CMP:.+]] = icmp slt i32 %[[TMP4]], %[[TMP5]] // CHECK-NEXT: br i1 %[[CMP]], label %[[COND_TRUE:.+]], label %[[COND_FALSE:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_TRUE]]: // CHECK-NEXT: %[[TMP6:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[SUB:.+]] = sub nsw i32 %[[TMP6]], %[[TMP7]] // CHECK-NEXT: %[[TMP8:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[SUB1:.+]] = sub i32 %[[TMP8]], 1 // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[SUB]], %[[SUB1]] // CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[DIV:.+]] = udiv i32 %[[ADD]], %[[TMP9]] // CHECK-NEXT: br label %[[COND_END:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_FALSE]]: // CHECK-NEXT: br label %[[COND_END]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_END]]: // CHECK-NEXT: %[[COND:.+]] = phi i32 [ %[[DIV]], %[[COND_TRUE]] ], [ 0, %[[COND_FALSE]] ] // CHECK-NEXT: %[[TMP10:.+]] = load i32*, i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store i32 %[[COND]], i32* %[[TMP10]], align 4 // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define {{.*}}@__captured_stmt.1( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[LOOPVAR_ADDR:.+]] = alloca i32*, align 8 // CHECK-NEXT: %[[LOGICAL_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon.0*, align 8 // CHECK-NEXT: store i32* %[[LOOPVAR:.+]], i32** %[[LOOPVAR_ADDR]], align 8 // CHECK-NEXT: store i32 %[[LOGICAL:.+]], i32* %[[LOGICAL_ADDR]], align 4 // CHECK-NEXT: store %struct.anon.0* %[[__CONTEXT:.+]], %struct.anon.0** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon.0*, %struct.anon.0** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[TMP0]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[TMP1]], align 4 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[LOGICAL_ADDR]], align 4 // CHECK-NEXT: %[[MUL:.+]] = mul i32 1, %[[TMP3]] // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[TMP2]], %[[MUL]] // CHECK-NEXT: %[[TMP4:.+]] = load i32*, i32** %[[LOOPVAR_ADDR]], align 8 // CHECK-NEXT: store i32 %[[ADD]], i32* %[[TMP4]], align 4 // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK: ![[META0:[0-9]+]] = !{i32 1, !"wchar_size", i32 4} // CHECK: ![[META1:[0-9]+]] = !{i32 7, !"openmp", i32 51} // CHECK: ![[META2:[0-9]+]] = // CHECK: ![[LOOP3]] = distinct !{![[LOOP3]], ![[LOOPPROP4:[0-9]+]], ![[LOOPPROP5:[0-9]+]]} // CHECK: ![[LOOPPROP4]] = !{!"llvm.loop.unroll.enable"} // CHECK: ![[LOOPPROP5]] = !{!"llvm.loop.unroll.count", i32 3}
the_stack_data/1112384.c
// https://leetcode.com/problems/move-zeroes/description/ void moveZeroes(int *nums, int numsSize) { int ndx = 0; int i; for (i = 0; i < numsSize; ++i) { if (nums[i] != 0) { if (i > ndx) { int t = nums[ndx]; nums[ndx] = nums[i]; nums[i] = t; } ndx++; } } }
the_stack_data/956432.c
#include <stdio.h> int main() { double x[10]; int i; double *x_d; double x1[10]; for (i = 0; i < 10; ++i) { x[i] = 1; x1[i] = 3; } x_d = x1; printf("2nd arg x1 should be equal to 3rd %p %p %p \n",x, x1, x_d); #pragma omp target enter data map(to:x) #pragma omp target map(tofrom:x_d) { x_d = x; printf("x on device : %p\n", x); } printf("1st arg x = to host x, 3rd arg = to device x %p %p %p \n",x, x1, x_d); printf("x_d %lf %lf \n",x_d[0], x_d[1]); for (i = 0; i < 10; ++i) { x[i] = 4; } printf("1st arg x should be equal to 3rd %p %p %p \n",x, x1, x_d); printf("x_d %lf should equal to %lf \n",x_d[0], x[0]); if (x_d[0] != x[0]) return 1; return 0; }
the_stack_data/231393807.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2013-2016 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* This test is just a normal return 0. */ int main (int argc, char *argv[]) { return 0; }
the_stack_data/165767741.c
#include <stdio.h> #include <stdlib.h> /* Traversing a linked list: displaying all the nodes, that is, the values stored in them. * Useful for displaying, counting, adding, sorting nodes, etc */ struct Node { int data; struct Node *next; }*first = NULL; // Creating a global pointer and initializing it to NULL // Creating a linked list void create(int A[], int n) // n is the number of elements { struct Node *t, *last; first = (struct Node *)malloc(sizeof(struct Node)); first->data = A[0]; first->next = NULL; last = first; for (int i = 1; i < n; i++) { t = (struct Node *)malloc(sizeof(struct Node)); t->data = A[i]; t->next = NULL; last->next = t; last = t; } } // Displaying a linked list: void display(struct Node *p) { // Condition to keep accessing the next values, could also be (p != NULL) or (p) while(p != 0) { printf("%d ", p->data); p = p->next; } } int main(void) { // Creating a linked list int A[] = {3, 5, 7, 10, 15}; // Creating a linked list create(A, 5); // Displaying a linked list: display(first); return 0; }
the_stack_data/117327276.c
/* Two PD getcwd() implementations. Author: Guido van Rossum, CWI Amsterdam, Jan 1991, <[email protected]>. */ #include <stdio.h> #include <errno.h> #ifdef HAVE_GETWD /* Version for BSD systems -- use getwd() */ #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #ifndef MAXPATHLEN #if defined(PATH_MAX) && PATH_MAX > 1024 #define MAXPATHLEN PATH_MAX #else #define MAXPATHLEN 1024 #endif #endif extern char *getwd(char *); char * getcwd(char *buf, int size) { char localbuf[MAXPATHLEN+1]; char *ret; if (size <= 0) { errno = EINVAL; return NULL; } ret = getwd(localbuf); if (ret != NULL && strlen(localbuf) >= (size_t)size) { errno = ERANGE; return NULL; } if (ret == NULL) { errno = EACCES; /* Most likely error */ return NULL; } strncpy(buf, localbuf, size); return buf; } #else /* !HAVE_GETWD */ /* Version for really old UNIX systems -- use pipe from pwd */ #ifndef PWD_CMD #define PWD_CMD "/bin/pwd" #endif char * getcwd(char *buf, int size) { FILE *fp; char *p; if (size <= 0) { errno = EINVAL; return NULL; } if ((fp = popen(PWD_CMD, "r")) == NULL) return NULL; if (fgets(buf, size, fp) == NULL || pclose(fp) != 0) { errno = EACCES; /* Most likely error */ return NULL; } for (p = buf; *p != '\n'; p++) { if (*p == '\0') { errno = ERANGE; return NULL; } } *p = '\0'; return buf; } #endif /* !HAVE_GETWD */
the_stack_data/1232869.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_isascii.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rlambert <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/11/04 16:04:56 by rlambert #+# #+# */ /* Updated: 2014/11/06 19:19:49 by rlambert ### ########.fr */ /* */ /* ************************************************************************** */ int ft_isascii(int c) { return (0 <= c && c <= 127); }
the_stack_data/150139400.c
// // main.c // 1.2 PrintN // // Created by SZDCMAC11 on 2019/12/5. // Copyright © 2019 SZDCMAC11. All rights reserved. // #include <stdio.h> int main(int argc, const char * argv[]) { // insert code here... printf("Hello, World!\n"); return 0; }
the_stack_data/5161.c
#include<stdio.h> long long jc(long long n) { int i; long long j=1; for(i=1;i<=n;i++){ j = i*j; } return j; } int main() { int m,n; long long c; scanf("%d%d",&m,&n); if(m==0||n>=m){ printf("1"); return 0; } c = jc(m)/(jc(n)*jc(m-n)); printf("%lld",c); return 0; }
the_stack_data/3261471.c
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "malloc.h" #include <ctype.h> const long long max_size = 2000; // max length of strings const long long N = 1; // number of closest words const long long max_w = 50; // max length of vocabulary entries int main(int argc, char **argv) { FILE *f; char st1[max_size], st2[max_size], st3[max_size], st4[max_size], bestw[N][max_size], file_name[max_size], ch; float dist, len, bestd[N], vec[max_size]; long long words, size, a, b, c, d, b1, b2, b3, threshold = 0; float *M; char *vocab; int TCN, CCN = 0, TACN = 0, CACN = 0, SECN = 0, SYCN = 0, SEAC = 0, SYAC = 0, QID = 0, TQ = 0, TQS = 0; if (argc < 2) { printf("Usage: ./compute-accuracy <FILE> <threshold>\nwhere FILE contains word projections, and threshold is used to reduce vocabulary of the model for fast approximate evaluation (0 = off, otherwise typical value is 30000)\n"); return 0; } strcpy(file_name, argv[1]); if (argc > 2) threshold = atoi(argv[2]); f = fopen(file_name, "rb"); if (f == NULL) { printf("Input file not found\n"); return -1; } fscanf(f, "%lld", &words); if (threshold) if (words > threshold) words = threshold; fscanf(f, "%lld", &size); vocab = (char *)malloc(words * max_w * sizeof(char)); M = (float *)malloc(words * size * sizeof(float)); if (M == NULL) { printf("Cannot allocate memory: %lld MB\n", words * size * sizeof(float) / 1048576); return -1; } for (b = 0; b < words; b++) { a = 0; while (1) { vocab[b * max_w + a] = fgetc(f); if (feof(f) || (vocab[b * max_w + a] == ' ')) break; if ((a < max_w) && (vocab[b * max_w + a] != '\n')) a++; } vocab[b * max_w + a] = 0; for (a = 0; a < max_w; a++) vocab[b * max_w + a] = toupper(vocab[b * max_w + a]); for (a = 0; a < size; a++) fread(&M[a + b * size], sizeof(float), 1, f); len = 0; for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size]; len = sqrt(len); for (a = 0; a < size; a++) M[a + b * size] /= len; } fclose(f); TCN = 0; while (1) { for (a = 0; a < N; a++) bestd[a] = 0; for (a = 0; a < N; a++) bestw[a][0] = 0; scanf("%s", st1); for (a = 0; a < strlen(st1); a++) st1[a] = toupper(st1[a]); if ((!strcmp(st1, ":")) || (!strcmp(st1, "EXIT")) || feof(stdin)) { if (TCN == 0) TCN = 1; if (QID != 0) { printf("ACCURACY TOP1: %.2f %% (%d / %d)\n", CCN / (float)TCN * 100, CCN, TCN); printf("Total accuracy: %.2f %% Semantic accuracy: %.2f %% Syntactic accuracy: %.2f %% \n", CACN / (float)TACN * 100, SEAC / (float)SECN * 100, SYAC / (float)SYCN * 100); } QID++; scanf("%s", st1); if (feof(stdin)) break; printf("%s:\n", st1); TCN = 0; CCN = 0; continue; } if (!strcmp(st1, "EXIT")) break; scanf("%s", st2); for (a = 0; a < strlen(st2); a++) st2[a] = toupper(st2[a]); scanf("%s", st3); for (a = 0; a<strlen(st3); a++) st3[a] = toupper(st3[a]); scanf("%s", st4); for (a = 0; a < strlen(st4); a++) st4[a] = toupper(st4[a]); for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st1)) break; b1 = b; for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st2)) break; b2 = b; for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st3)) break; b3 = b; for (a = 0; a < N; a++) bestd[a] = 0; for (a = 0; a < N; a++) bestw[a][0] = 0; TQ++; if (b1 == words) continue; if (b2 == words) continue; if (b3 == words) continue; for (b = 0; b < words; b++) if (!strcmp(&vocab[b * max_w], st4)) break; if (b == words) continue; for (a = 0; a < size; a++) vec[a] = (M[a + b2 * size] - M[a + b1 * size]) + M[a + b3 * size]; TQS++; for (c = 0; c < words; c++) { if (c == b1) continue; if (c == b2) continue; if (c == b3) continue; dist = 0; for (a = 0; a < size; a++) dist += vec[a] * M[a + c * size]; for (a = 0; a < N; a++) { if (dist > bestd[a]) { for (d = N - 1; d > a; d--) { bestd[d] = bestd[d - 1]; strcpy(bestw[d], bestw[d - 1]); } bestd[a] = dist; strcpy(bestw[a], &vocab[c * max_w]); break; } } } if (!strcmp(st4, bestw[0])) { CCN++; CACN++; if (QID <= 5) SEAC++; else SYAC++; } if (QID <= 5) SECN++; else SYCN++; TCN++; TACN++; } printf("Questions seen / total: %d %d %.2f %% \n", TQS, TQ, TQS/(float)TQ*100); return 0; }
the_stack_data/172291.c
#include<stdio.h> struct distance { int feet,inch; }d1,d2,d3; int main() { scanf("%d%d",&d1.feet,&d1.inch); scanf("%d%d",&d2.feet,&d2.inch); d3.feet=d1.feet+d2.feet; d3.inch=d1.inch+d2.inch; while(d3.inch>=12) { d3.feet++; d3.inch-=12; } printf("\n%d\t%d\n",d3.feet,d3.inch); return 0; }
the_stack_data/159515907.c
/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. * * STM32L SoC system monitor interface tool */ /* use cfmakeraw() */ #define _BSD_SOURCE #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <getopt.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <termios.h> #include <time.h> #include <unistd.h> /* Monitor command set */ #define CMD_INIT 0x7f /* Starts the monitor */ #define CMD_GETCMD 0x00 /* Gets the allowed commands */ #define CMD_GETVER 0x01 /* Gets the bootloader version */ #define CMD_GETID 0x02 /* Gets the Chip ID */ #define CMD_READMEM 0x11 /* Reads memory */ #define CMD_GO 0x21 /* Jumps to user code */ #define CMD_WRITEMEM 0x31 /* Writes memory (SRAM or Flash) */ #define CMD_ERASE 0x43 /* Erases n pages of Flash memory */ #define CMD_EXTERASE 0x44 /* Erases n pages of Flash memory */ #define CMD_WP 0x63 /* Enables write protect */ #define CMD_WU 0x73 /* Disables write protect */ #define CMD_RP 0x82 /* Enables the read protection */ #define CMD_RU 0x92 /* Disables the read protection */ #define RESP_NACK 0x1f #define RESP_ACK 0x79 /* Extended erase special parameters */ #define ERASE_ALL 0xffff #define ERASE_BANK1 0xfffe #define ERASE_BANK2 0xfffd /* known STM32 SoC parameters */ struct stm32_def { uint16_t id; const char *name; uint32_t flash_start; uint32_t flash_size; uint32_t page_size; } chip_defs[] = { {0x416, "STM32L15xxB", 0x08000000, 0x20000, 256}, {0x427, "STM32L15xxC", 0x08000000, 0x40000, 256}, {0x420, "STM32F100xx", 0x08000000, 0x20000, 1024}, {0x410, "STM32F102R8", 0x08000000, 0x10000, 1024}, {0x440, "STM32F05x", 0x08000000, 0x10000, 1024}, {0x444, "STM32F03x", 0x08000000, 0x08000, 1024}, {0x448, "STM32F07xB", 0x08000000, 0x20000, 1024}, { 0 } }; #define DEFAULT_TIMEOUT 4 /* seconds */ #define DEFAULT_BAUDRATE B38400 #define PAGE_SIZE 256 /* store custom parameters */ speed_t baudrate = DEFAULT_BAUDRATE; const char *serial_port = "/dev/ttyUSB1"; const char *input_filename; const char *output_filename; /* optional command flags */ enum { FLAG_UNPROTECT = 0x01, FLAG_ERASE = 0x02, FLAG_GO = 0x04, FLAG_READ_UNPROTECT = 0x08, }; typedef struct { int size; uint8_t *data; } payload_t; static int has_exterase; static void discard_input(int); #define MIN(a, b) ((a) < (b) ? (a) : (b)) int open_serial(const char *port) { int fd, res; struct termios cfg, cfg_copy; fd = open(port, O_RDWR | O_NOCTTY); if (fd == -1) { perror("Unable to open serial port"); return -1; } /* put the tty in "raw" mode at the defined baudrate */ res = tcgetattr(fd, &cfg); if (res == -1) { perror("Cannot read tty attributes"); close(fd); return -1; } cfmakeraw(&cfg); cfsetspeed(&cfg, baudrate); /* serial mode should be 8e1 */ cfg.c_cflag |= PARENB; /* 200 ms timeout */ cfg.c_cc[VTIME] = 2; cfg.c_cc[VMIN] = 0; memcpy(&cfg_copy, &cfg, sizeof(cfg_copy)); /* * tcsetattr() returns success if any of the modifications succeed, so * its return value of zero is not an indication of success, one needs * to check the result explicitely. */ tcsetattr(fd, TCSANOW, &cfg); if (tcgetattr(fd, &cfg)) { perror("Failed to re-read tty attributes"); close(fd); return -1; } if (memcmp(&cfg, &cfg_copy, sizeof(cfg))) { /* * On some systems the setting which does not come through is * the parity. We can try continuing without it when using * certain interfaces, let's try. */ cfg_copy.c_cflag &= ~PARENB; if (memcmp(&cfg, &cfg_copy, sizeof(cfg))) { /* * Something other than parity failed to get set, this * is an error. */ perror("Cannot set tty attributes"); close(fd); return -1; } else { fprintf(stderr, "Failed to enable parity\n"); } } discard_input(fd); /* in case were were invoked soon after reset */ return fd; } static void discard_input(int fd) { uint8_t buffer[64]; int res, i; /* eat trailing garbage */ do { res = read(fd, buffer, sizeof(buffer)); if (res > 0) { printf("Recv[%d]:", res); for (i = 0; i < res; i++) printf("%02x ", buffer[i]); printf("\n"); } } while (res > 0); } int wait_for_ack(int fd) { uint8_t resp; int res; time_t deadline = time(NULL) + DEFAULT_TIMEOUT; while (time(NULL) < deadline) { res = read(fd, &resp, 1); if ((res < 0) && (errno != EAGAIN)) { perror("Failed to read answer"); return -EIO; } if (res == 1) { if (resp == RESP_ACK) return 0; else if (resp == RESP_NACK) { fprintf(stderr, "NACK\n"); discard_input(fd); return -EINVAL; } else { fprintf(stderr, "Receive junk: %02x\n", resp); } } } fprintf(stderr, "Timeout\n"); return -ETIMEDOUT; } int send_command(int fd, uint8_t cmd, payload_t *loads, int cnt, uint8_t *resp, int resp_size) { int res, i, c; payload_t *p; int readcnt = 0; int size; uint8_t *data; uint8_t crc = 0xff ^ cmd; /* XOR checksum */ /* Send the command index */ res = write(fd, &cmd, 1); if (res <= 0) { perror("Failed to write command"); return -1; } /* Send the checksum */ res = write(fd, &crc, 1); if (res <= 0) { perror("Failed to write checksum"); return -1; } /* Wait for the ACK */ if (wait_for_ack(fd) < 0) { fprintf(stderr, "Failed to get command %02x ACK\n", cmd); return -1; } /* Send the command payloads */ for (p = loads, c = 0; c < cnt; c++, p++) { crc = 0; size = p->size; data = p->data; for (i = 0; i < size; i++) crc ^= data[i]; if (size == 1) crc = 0xff ^ crc; while (size) { res = write(fd, data, size); if (res < 0) { perror("Failed to write command payload"); return -1; } size -= res; data += res; } /* Send the checksum */ res = write(fd, &crc, 1); if (res <= 0) { perror("Failed to write checksum"); return -1; } /* Wait for the ACK */ if (wait_for_ack(fd) < 0) { fprintf(stderr, "payload %d ACK failed for CMD%02x\n", c, cmd); return -1; } } /* Read the answer payload */ if (resp) { while ((res = read(fd, resp, resp_size))) { if (res < 0) { perror("Failed to read payload"); return -1; } readcnt += res; resp += res; resp_size -= res; } } return readcnt; } struct stm32_def *command_get_id(int fd) { int res; uint8_t id[4]; uint16_t chipid; struct stm32_def *def; res = send_command(fd, CMD_GETID, NULL, 0, id, sizeof(id)); if (res > 0) { if (id[0] != 1 || id[3] != RESP_ACK) { fprintf(stderr, "unknown ID : %02x %02x %02x %02x\n", id[0], id[1], id[2], id[3]); return NULL; } chipid = (id[1] << 8) | id[2]; for (def = chip_defs; def->id; def++) if (def->id == chipid) break; if (def->id == 0) def = NULL; printf("ChipID 0x%03x : %s\n", chipid, def ? def->name : "???"); return def; } return NULL; } int init_monitor(int fd) { int res; uint8_t init = CMD_INIT; printf("Waiting for the monitor startup ..."); fflush(stdout); while (1) { /* Send the command index */ res = write(fd, &init, 1); if (res <= 0) { perror("Failed to write command"); return -1; } /* Wait for the ACK */ res = wait_for_ack(fd); if (res == 0) break; if (res == -EINVAL) { /* we got NACK'ed, the loader might be already started * let's ping it to check */ if (command_get_id(fd)) { printf("Monitor already started.\n"); return 0; } } if (res < 0 && res != -ETIMEDOUT) return -1; fflush(stdout); } printf("Done.\n"); /* read trailing chars */ discard_input(fd); return 0; } int command_get_commands(int fd) { int res, i; uint8_t cmds[64]; res = send_command(fd, CMD_GETCMD, NULL, 0, cmds, sizeof(cmds)); if (res > 0) { if ((cmds[0] > sizeof(cmds) - 2) || (cmds[cmds[0] + 2] != RESP_ACK)) { fprintf(stderr, "invalid GET answer (%02x...)\n", cmds[0]); return -1; } printf("Bootloader v%d.%d, commands : ", cmds[1] >> 4, cmds[1] & 0xf); for (i = 2; i < 2 + cmds[0]; i++) { if (cmds[i] == CMD_EXTERASE) has_exterase = 1; printf("%02x ", cmds[i]); } printf("\n"); return 0; } return -1; } static int windex; static const char wheel[] = {'|', '/', '-', '\\' }; static void draw_spinner(uint32_t remaining, uint32_t size) { int percent = (size - remaining)*100/size; printf("\r%c%3d%%", wheel[windex++], percent); windex %= sizeof(wheel); } int command_read_mem(int fd, uint32_t address, uint32_t size, uint8_t *buffer) { int res; uint32_t remaining = size; uint32_t addr_be; uint8_t cnt; payload_t loads[2] = { {4, (uint8_t *)&addr_be}, {1, &cnt} }; while (remaining) { cnt = (remaining > PAGE_SIZE) ? PAGE_SIZE - 1 : remaining - 1; addr_be = htonl(address); draw_spinner(remaining, size); fflush(stdout); res = send_command(fd, CMD_READMEM, loads, 2, buffer, cnt + 1); if (res < 0) return -EIO; buffer += cnt + 1; address += cnt + 1; remaining -= cnt + 1; } return size; } int command_write_mem(int fd, uint32_t address, uint32_t size, uint8_t *buffer) { int res; uint32_t remaining = size; uint32_t addr_be; uint32_t cnt; uint8_t outbuf[257]; payload_t loads[2] = { {4, (uint8_t *)&addr_be}, {sizeof(outbuf), outbuf} }; while (remaining) { cnt = (remaining > PAGE_SIZE) ? PAGE_SIZE : remaining; addr_be = htonl(address); outbuf[0] = cnt - 1; loads[1].size = cnt + 1; memcpy(outbuf + 1, buffer, cnt); draw_spinner(remaining, size); fflush(stdout); res = send_command(fd, CMD_WRITEMEM, loads, 2, NULL, 0); if (res < 0) return -EIO; buffer += cnt; address += cnt; remaining -= cnt; } return size; } int command_ext_erase(int fd, uint16_t count, uint16_t start) { int res; uint16_t count_be = htons(count); payload_t load = { 2, (uint8_t *)&count_be }; uint16_t *pages = NULL; if (count < 0xfff0) { int i; /* not a special value : build a list of pages */ load.size = 2 * (count + 1); pages = malloc(load.size); if (!pages) return -ENOMEM; load.data = (uint8_t *)pages; pages[0] = htons(count - 1); for (i = 0; i < count; i++) pages[i+1] = htons(start + i); } res = send_command(fd, CMD_EXTERASE, &load, 1, NULL, 0); if (res >= 0) printf("Flash erased.\n"); if (pages) free(pages); return res; } int command_erase(int fd, uint8_t count, uint8_t start) { int res; payload_t load = { 1, (uint8_t *)&count }; uint8_t *pages = NULL; if (count < 0xff) { int i; /* not a special value : build a list of pages */ load.size = count + 1; pages = malloc(load.size); if (!pages) return -ENOMEM; load.data = (uint8_t *)pages; pages[0] = count - 1; for (i = 0; i < count; i++) pages[i+1] = start + i; } res = send_command(fd, CMD_ERASE, &load, 1, NULL, 0); if (res >= 0) printf("Flash erased.\n"); if (pages) free(pages); return res; } int command_read_unprotect(int fd) { int res; res = send_command(fd, CMD_RU, NULL, 0, NULL, 0); if (res < 0) return -EIO; /* Wait for the ACK */ if (wait_for_ack(fd) < 0) { fprintf(stderr, "Failed to get read-protect ACK\n"); return -EINVAL; } printf("Flash read unprotected.\n"); /* This commands triggers a reset */ if (init_monitor(fd) < 0) { fprintf(stderr, "Cannot recover after RP reset\n"); return -EIO; } return 0; } int command_write_unprotect(int fd) { int res; res = send_command(fd, CMD_WU, NULL, 0, NULL, 0); if (res < 0) return -EIO; /* Wait for the ACK */ if (wait_for_ack(fd) < 0) { fprintf(stderr, "Failed to get write-protect ACK\n"); return -EINVAL; } printf("Flash write unprotected.\n"); /* This commands triggers a reset */ if (init_monitor(fd) < 0) { fprintf(stderr, "Cannot recover after WP reset\n"); return -EIO; } return 0; } int command_go(int fd, uint32_t address) { int res; uint32_t addr_be = htonl(address); payload_t load = { 4, (uint8_t *)&addr_be }; res = send_command(fd, CMD_GO, &load, 1, NULL, 0); if (res < 0) return -EIO; #if 0 /* this ACK should exist according to the documentation ... */ /* Wait for the ACK */ if (wait_for_ack(fd) < 0) { fprintf(stderr, "Failed to get GO ACK\n"); return -EINVAL; } #endif printf("Program started at 0x%08x.\n", address); return 0; } /* Return zero on success, a negative error value on failures. */ int read_flash(int fd, struct stm32_def *chip, const char *filename, uint32_t offset, uint32_t size) { int res; FILE *hnd; uint8_t *buffer = malloc(size); if (!buffer) { fprintf(stderr, "Cannot allocate %d bytes\n", size); return -ENOMEM; } hnd = fopen(filename, "w"); if (!hnd) { fprintf(stderr, "Cannot open file %s for writing\n", filename); free(buffer); return -EIO; } if (!size) size = chip->flash_size; offset += chip->flash_start; printf("Reading %d bytes at 0x%08x\n", size, offset); res = command_read_mem(fd, offset, size, buffer); if (res > 0) { if (fwrite(buffer, res, 1, hnd) != 1) fprintf(stderr, "Cannot write %s\n", filename); } printf("\r %d bytes read.\n", res); fclose(hnd); free(buffer); return (res < 0) ? res : 0; } /* Return zero on success, a negative error value on failures. */ int write_flash(int fd, struct stm32_def *chip, const char *filename, uint32_t offset) { int res, written; FILE *hnd; int size = chip->flash_size; uint8_t *buffer = malloc(size); if (!buffer) { fprintf(stderr, "Cannot allocate %d bytes\n", size); return -ENOMEM; } hnd = fopen(filename, "r"); if (!hnd) { fprintf(stderr, "Cannot open file %s for reading\n", filename); free(buffer); return -EIO; } res = fread(buffer, 1, size, hnd); if (res <= 0) { fprintf(stderr, "Cannot read %s\n", filename); free(buffer); return -EIO; } fclose(hnd); offset += chip->flash_start; printf("Writing %d bytes at 0x%08x\n", res, offset); written = command_write_mem(fd, offset, res, buffer); if (written != res) { fprintf(stderr, "Error writing to flash\n"); free(buffer); return -EIO; } printf("\rDone.\n"); free(buffer); return 0; } static const struct option longopts[] = { {"device", 1, 0, 'd'}, {"read", 1, 0, 'r'}, {"write", 1, 0, 'w'}, {"erase", 0, 0, 'e'}, {"go", 0, 0, 'g'}, {"help", 0, 0, 'h'}, {"unprotect", 0, 0, 'u'}, {"baudrate", 1, 0, 'b'}, {NULL, 0, 0, 0} }; void display_usage(char *program) { fprintf(stderr, "Usage: %s [-d <tty>] [-b <baudrate>] [-u] [-e] [-U]" " [-r <file>] [-w <file>] [-g]\n", program); fprintf(stderr, "--d[evice] <tty> : use <tty> as the serial port\n"); fprintf(stderr, "--b[audrate] <baudrate> : set serial port speed " "to <baudrate> bauds\n"); fprintf(stderr, "--u[nprotect] : remove flash write protect\n"); fprintf(stderr, "--U[nprotect] : remove flash read protect\n"); fprintf(stderr, "--e[rase] : erase all the flash content\n"); fprintf(stderr, "--r[ead] <file> : read the flash content and " "write it into <file>\n"); fprintf(stderr, "--w[rite] <file> : read <file> and " "write it to flash\n"); fprintf(stderr, "--g[o] : jump to execute flash entrypoint\n"); exit(2); } speed_t parse_baudrate(const char *value) { int rate = atoi(value); switch (rate) { case 9600: return B9600; case 19200: return B19200; case 38400: return B38400; case 57600: return B57600; case 115200: return B115200; default: fprintf(stderr, "Invalid baudrate %s, using %d\n", value, DEFAULT_BAUDRATE); return DEFAULT_BAUDRATE; } } int parse_parameters(int argc, char **argv) { int opt, idx; int flags = 0; while ((opt = getopt_long(argc, argv, "b:d:eghr:w:uU?", longopts, &idx)) != -1) { switch (opt) { case 'b': baudrate = parse_baudrate(optarg); break; case 'd': serial_port = optarg; break; case 'e': flags |= FLAG_ERASE; break; case 'g': flags |= FLAG_GO; break; case 'h': case '?': display_usage(argv[0]); break; case 'r': input_filename = optarg; break; case 'w': output_filename = optarg; break; case 'u': flags |= FLAG_UNPROTECT; break; case 'U': flags |= FLAG_READ_UNPROTECT; break; } } return flags; } int main(int argc, char **argv) { int ser; struct stm32_def *chip; int ret = 1; int flags; /* Parse command line options */ flags = parse_parameters(argc, argv); /* Open the serial port tty */ ser = open_serial(serial_port); if (ser < 0) return 1; /* Trigger embedded monitor detection */ if (init_monitor(ser) < 0) goto terminate; chip = command_get_id(ser); if (!chip) goto terminate; command_get_commands(ser); if (flags & FLAG_READ_UNPROTECT) command_read_unprotect(ser); if (flags & FLAG_UNPROTECT) command_write_unprotect(ser); if (flags & FLAG_ERASE || output_filename) { /* Mass erase is not supported on STM32L15xx */ /* command_ext_erase(ser, ERASE_ALL, 0); */ int i, page_count = chip->flash_size / chip->page_size; for (i = 0; i < page_count; i += 128) { int count = MIN(128, page_count - i); if (has_exterase) command_ext_erase(ser, count, i); else command_erase(ser, count, i); } } if (input_filename) { ret = read_flash(ser, chip, input_filename, 0, chip->flash_size); if (ret) goto terminate; } if (output_filename) { ret = write_flash(ser, chip, output_filename, 0); if (ret) goto terminate; } /* Run the program from flash */ if (flags & FLAG_GO) command_go(ser, chip->flash_start); /* Normal exit */ ret = 0; terminate: /* Close serial port */ close(ser); return ret; }