file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/944577.c
//Author : Sanjana Sawnt #include <stdio.h> #include <stdlib.h> struct stack_ll{ int data; struct stack_ll *next; }; typedef struct stack_ll node; node *top =NULL; node *head=NULL; char menu(); void push(); void pop(); void display(); node *getnode(); node* getnode() { node *temp; temp=(node *) malloc( sizeof(node)) ; printf("\nEnter data : "); scanf("%d", &temp -> data); temp -> next = NULL; return temp; } //Push an element to the top of the stack i.e. to the rear end of the list void push(node *newnode) { node *temp; if (newnode == NULL) { printf("\nStack underflow !!"); return ; } else { if (head == NULL) { head = newnode; top = newnode; } else { temp = head; while(temp->next != NULL) { temp = temp->next; } temp->next =newnode; top = newnode; } printf("\nData pushed onto stack"); } } //Display all the elements of the stack void display() { node *temp; if (head == NULL) printf("\nEmpty Stack"); else { temp = head ; printf("\nContents of the stack are : "); printf("\n%d", temp->data); while(temp->next != NULL) { temp = temp->next; printf("\n%d", temp->data); } } } //Pop the element at the top of the stack void pop() { node *temp; if(top == NULL) { printf("\nStack underflow"); return; } temp = head; if (head->next == NULL) { printf("\nPopped element is %d ", top -> data); head = NULL; free(top); top = NULL; } else { while(temp -> next != top) { temp = temp -> next; } temp -> next = NULL; printf("\nPopped element is %d ", top -> data); free(top); top = temp; } } char menu() { int ch; printf("\n\n-----------------------------------------------------------------"); printf("\n1. Push an element"); printf("\n2. Pop an element"); printf("\n3. Display all elements"); printf("\n4. Exit"); printf("\n\nEnter your choice (1-4): "); scanf("%d",&ch); return ch; } int main() { node *newnode; char ch; printf("\nProgram to implement stack using singly linked list \n\n"); while (1) { ch = menu(); switch (ch) { case 1: newnode = getnode(); push(newnode); break; case 2: pop(); break; case 3: display(); break; case 4: exit(0); default: printf("\nInvalid choice !!!"); } } }
the_stack_data/77729.c
/** flush_to_zero.c ***/ /* DUMMY ROUTINE - nothing to do unless on Intel machine */ void flush_to_zero(){}
the_stack_data/62637714.c
#include <stdio.h> int main(void) { int i = 100; // while i slides down to 0 while ( i -- \ //\ // \ _____//____\ \__________/ \ > 0 ) { printf("test "); } return 0; }
the_stack_data/154827475.c
#include <omp.h> #include <stdio.h> #include <math.h> int main() { int N = 4; float b[N]; float a[N]; // serial portion of the code for (int j=0; j<N; j++) { b[j] = j+1; } // parallel portion of the code #pragma omp parallel { float a[N]; // if declared here, it will go out of scope after threads join. You will fix this in lab 6 #pragma omp for for(int i=0; i<N; i++){ printf("Thread %d working on component %d\n",omp_get_thread_num(),i); a[i] = sqrt(b[i]); } } // serial portion of the code for (int j=0; j<N; j++) { printf("square root of %f is = %f\n",b[j],a[j]); } return 0; }
the_stack_data/64201495.c
/* ** EPITECH PROJECT, 2019 ** my_strncat ** File description: ** concatenate strings for few characters */ #include <string.h> #include <stdio.h> int my_strlen(char const *str); char *my_strncat(char *dest, char const *src, int nb) { int size = my_strlen(dest); int i = 0; for (i = 0; i < nb && src[i] != '\0'; i++) dest[size + i] = src[i]; dest[size + i] = '\0'; return (dest); }
the_stack_data/23576374.c
#include <stdio.h> #define MM 12 #define NN 10 void main() { int M, N; // size of matrix int A[MM][NN]; // matrix MM x NN int i,j; // loop's indexes int imin = 0, jmin = 0; // position min-elements int Z[NN]; // new inserted array printf("Input size of matrix (MxN): "); scanf("%d%d", &M, &N); printf("\nInput matrix %dx%d:\n", M, N); for (i=0; i<M; i++) for (j=0; j<N; j++) { scanf("%d", &A[i][j]); // read elements if (A[imin][jmin] > A[i][j]) { imin = i; jmin = j; /* find minimum element */ } } printf("\n Input new row (array %d elements): ", N); for (i=0; i<N; scanf("%d", &Z[i]), i++); printf("\n\n Matrix input:\n\n"); for (i=0; i<M; i++) { /* print begining matrix */ for (j=0; j<N; printf("%3d", A[i][j]), j++); printf("\n\n"); } /* print out position of first minimum value */ printf(" Minimum element A[%d][%d] = %d, which AT FIRST appears in ROW [%d].", imin+1, jmin+1, A[imin][jmin], imin+1); imin++; for (j=0; j<N; j++) { /* Change matrix */ for (i=M; i>imin; A[i][j] = A[i-1][j], i--); A[imin][j] = Z[j]; } printf("\n\n Matrix output:\n\n"); for (i=0; i<=M; i++) { for (j=0; j<N; printf("%3d", A[i][j]), j++); printf("\n\n"); } /* print out matrix after changing */ getchar(); getchar(); } /* Program VI (variant 1) */
the_stack_data/115589.c
int max(int a, int b) { return a > b ? a : b; } int genericMaxProfit(int* prices, int pricesSize, int fee) { if (pricesSize < 1) { return 0; } int result = 0; int dp[2]; dp[0] = 0; dp[1] = - prices[0]; for (int i = 1; i < pricesSize; i++) { int t0, t1; t0 = max(dp[0], dp[1] + prices[i] - fee); t1 = max(dp[1], dp[0] - prices[i]); dp[0] = t0; dp[1] = t1; } result = dp[0]; return result; } int maxProfit(int* prices, int pricesSize, int fee){ return genericMaxProfit(prices, pricesSize, fee); }
the_stack_data/59513697.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 , int); int maximum(int, int); int multiply(int,int); 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){ if(a>b) return b; else return a; } int maximum (int a, int b){ if(a>b) return a; else return b; } int multiply(int a, int b){ return a*b; }
the_stack_data/200144218.c
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct work_stuff {int static_type; scalar_t__ type_quals; int temp_start; int destructor; int constructor; } ; typedef int /*<<< orphan*/ string ; /* Variables and functions */ int /*<<< orphan*/ APPEND_BLANK (int /*<<< orphan*/ *) ; scalar_t__ ARM_DEMANGLING ; scalar_t__ AUTO_DEMANGLING ; scalar_t__ EDG_DEMANGLING ; scalar_t__ GNU_DEMANGLING ; int /*<<< orphan*/ HP_DEMANGLING ; int /*<<< orphan*/ ISDIGIT (unsigned char) ; scalar_t__ LUCID_DEMANGLING ; scalar_t__ PRINT_ARG_TYPES ; char* SCOPE_STRING (struct work_stuff*) ; scalar_t__ TYPE_UNQUALIFIED ; scalar_t__ code_for_qualifier (char const) ; int demangle_args (struct work_stuff*,char const**,int /*<<< orphan*/ *) ; int demangle_class (struct work_stuff*,char const**,int /*<<< orphan*/ *) ; int demangle_qualified (struct work_stuff*,char const**,int /*<<< orphan*/ *,int,int /*<<< orphan*/ ) ; int demangle_template (struct work_stuff*,char const**,int /*<<< orphan*/ *,int /*<<< orphan*/ *,int,int) ; int do_type (struct work_stuff*,char const**,int /*<<< orphan*/ *) ; int /*<<< orphan*/ forget_types (struct work_stuff*) ; char* qualifier_string (scalar_t__) ; int /*<<< orphan*/ remember_type (struct work_stuff*,char const*,int) ; int /*<<< orphan*/ string_append (int /*<<< orphan*/ *,char*) ; int /*<<< orphan*/ string_appends (int /*<<< orphan*/ *,int /*<<< orphan*/ *) ; int /*<<< orphan*/ string_delete (int /*<<< orphan*/ *) ; int /*<<< orphan*/ string_init (int /*<<< orphan*/ *) ; int /*<<< orphan*/ string_prepend (int /*<<< orphan*/ *,char*) ; int /*<<< orphan*/ string_prepends (int /*<<< orphan*/ *,int /*<<< orphan*/ *) ; __attribute__((used)) static int demangle_signature (struct work_stuff *work, const char **mangled, string *declp) { int success = 1; int func_done = 0; int expect_func = 0; int expect_return_type = 0; const char *oldmangled = NULL; string trawname; string tname; while (success && (**mangled != '\0')) { switch (**mangled) { case 'Q': oldmangled = *mangled; success = demangle_qualified (work, mangled, declp, 1, 0); if (success) remember_type (work, oldmangled, *mangled - oldmangled); if (AUTO_DEMANGLING || GNU_DEMANGLING) expect_func = 1; oldmangled = NULL; break; case 'K': oldmangled = *mangled; success = demangle_qualified (work, mangled, declp, 1, 0); if (AUTO_DEMANGLING || GNU_DEMANGLING) { expect_func = 1; } oldmangled = NULL; break; case 'S': /* Static member function */ if (oldmangled == NULL) { oldmangled = *mangled; } (*mangled)++; work -> static_type = 1; break; case 'C': case 'V': case 'u': work->type_quals |= code_for_qualifier (**mangled); /* a qualified member function */ if (oldmangled == NULL) oldmangled = *mangled; (*mangled)++; break; case 'L': /* Local class name follows after "Lnnn_" */ if (HP_DEMANGLING) { while (**mangled && (**mangled != '_')) (*mangled)++; if (!**mangled) success = 0; else (*mangled)++; } else success = 0; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (oldmangled == NULL) { oldmangled = *mangled; } work->temp_start = -1; /* uppermost call to demangle_class */ success = demangle_class (work, mangled, declp); if (success) { remember_type (work, oldmangled, *mangled - oldmangled); } if (AUTO_DEMANGLING || GNU_DEMANGLING || EDG_DEMANGLING) { /* EDG and others will have the "F", so we let the loop cycle if we are looking at one. */ if (**mangled != 'F') expect_func = 1; } oldmangled = NULL; break; case 'B': { string s; success = do_type (work, mangled, &s); if (success) { string_append (&s, SCOPE_STRING (work)); string_prepends (declp, &s); string_delete (&s); } oldmangled = NULL; expect_func = 1; } break; case 'F': /* Function */ /* ARM/HP style demangling includes a specific 'F' character after the class name. For GNU style, it is just implied. So we can safely just consume any 'F' at this point and be compatible with either style. */ oldmangled = NULL; func_done = 1; (*mangled)++; /* For lucid/ARM/HP style we have to forget any types we might have remembered up to this point, since they were not argument types. GNU style considers all types seen as available for back references. See comment in demangle_args() */ if (LUCID_DEMANGLING || ARM_DEMANGLING || HP_DEMANGLING || EDG_DEMANGLING) { forget_types (work); } success = demangle_args (work, mangled, declp); /* After picking off the function args, we expect to either find the function return type (preceded by an '_') or the end of the string. */ if (success && (AUTO_DEMANGLING || EDG_DEMANGLING) && **mangled == '_') { ++(*mangled); /* At this level, we do not care about the return type. */ success = do_type (work, mangled, &tname); string_delete (&tname); } break; case 't': /* G++ Template */ string_init(&trawname); string_init(&tname); if (oldmangled == NULL) { oldmangled = *mangled; } success = demangle_template (work, mangled, &tname, &trawname, 1, 1); if (success) { remember_type (work, oldmangled, *mangled - oldmangled); } string_append (&tname, SCOPE_STRING (work)); string_prepends(declp, &tname); if (work -> destructor & 1) { string_prepend (&trawname, "~"); string_appends (declp, &trawname); work->destructor -= 1; } if ((work->constructor & 1) || (work->destructor & 1)) { string_appends (declp, &trawname); work->constructor -= 1; } string_delete(&trawname); string_delete(&tname); oldmangled = NULL; expect_func = 1; break; case '_': if ((AUTO_DEMANGLING || GNU_DEMANGLING) && expect_return_type) { /* Read the return type. */ string return_type; (*mangled)++; success = do_type (work, mangled, &return_type); APPEND_BLANK (&return_type); string_prepends (declp, &return_type); string_delete (&return_type); break; } else /* At the outermost level, we cannot have a return type specified, so if we run into another '_' at this point we are dealing with a mangled name that is either bogus, or has been mangled by some algorithm we don't know how to deal with. So just reject the entire demangling. */ /* However, "_nnn" is an expected suffix for alternate entry point numbered nnn for a function, with HP aCC, so skip over that without reporting failure. pai/1997-09-04 */ if (HP_DEMANGLING) { (*mangled)++; while (**mangled && ISDIGIT ((unsigned char)**mangled)) (*mangled)++; } else success = 0; break; case 'H': if (AUTO_DEMANGLING || GNU_DEMANGLING) { /* A G++ template function. Read the template arguments. */ success = demangle_template (work, mangled, declp, 0, 0, 0); if (!(work->constructor & 1)) expect_return_type = 1; (*mangled)++; break; } else /* fall through */ {;} default: if (AUTO_DEMANGLING || GNU_DEMANGLING) { /* Assume we have stumbled onto the first outermost function argument token, and start processing args. */ func_done = 1; success = demangle_args (work, mangled, declp); } else { /* Non-GNU demanglers use a specific token to mark the start of the outermost function argument tokens. Typically 'F', for ARM/HP-demangling, for example. So if we find something we are not prepared for, it must be an error. */ success = 0; } break; } /* if (AUTO_DEMANGLING || GNU_DEMANGLING) */ { if (success && expect_func) { func_done = 1; if (LUCID_DEMANGLING || ARM_DEMANGLING || EDG_DEMANGLING) { forget_types (work); } success = demangle_args (work, mangled, declp); /* Since template include the mangling of their return types, we must set expect_func to 0 so that we don't try do demangle more arguments the next time we get here. */ expect_func = 0; } } } if (success && !func_done) { if (AUTO_DEMANGLING || GNU_DEMANGLING) { /* With GNU style demangling, bar__3foo is 'foo::bar(void)', and bar__3fooi is 'foo::bar(int)'. We get here when we find the first case, and need to ensure that the '(void)' gets added to the current declp. Note that with ARM/HP, the first case represents the name of a static data member 'foo::bar', which is in the current declp, so we leave it alone. */ success = demangle_args (work, mangled, declp); } } if (success && PRINT_ARG_TYPES) { if (work->static_type) string_append (declp, " static"); if (work->type_quals != TYPE_UNQUALIFIED) { APPEND_BLANK (declp); string_append (declp, qualifier_string (work->type_quals)); } } return (success); }
the_stack_data/150141254.c
#include <stdio.h> #include <stdlib.h> int i,n, arr[100], arr2[100], flag=0; void arrIn(){ printf("enter no.of elements in the array :\n"); scanf("%d",&n); printf("Input %d elements in the array :\n",n); for(i=0; i<n; i++){ printf("element - %d : ",i); scanf("%d", &arr[i]); } flag=1; } void CopyArr(){ if(flag == 0){ printf("First Insert Array 1!!!\n"); return; } /* Copy elements of first array into second array.*/ for(i=0; i<n; i++) arr2[i] = arr[i]; printf("Array-1 Elements have been copied to Array-2\n"); flag=1; } void PrintArr1(){ if(flag == 0){ printf("Array Is Empty!!!\n"); return; } printf("\nElements in array-1 are: "); for(i=0; i<n; i++) printf("element %d - %d : ",i,arr[i]); printf("\n"); } void PrintArr2(){ if(flag == 0){ printf("Array Is Empty!!!\n"); return; } printf("\nElements in array-2 are: "); for(i=0; i<n; i++) printf("element %d - %d : ",i,arr2[i]); printf("\n"); } void DeleteArr1(){ for(i=0; i<n; i++) arr[i] = 0; printf("Elements of Array-1 have been Deleted!\n"); } void DeleteArr2(){ for(i=0; i<n; i++) arr2[i] = 0; printf("Elements of Array-2 have been Deleted!\n"); } int main() { int c; while(1){ printf("\nArray Operations Menu:\n"); printf("-----------------------------------------\n"); printf("\n1. Input New Array:\n"); printf("\n2. Copy Array1 to Array2:\n"); printf("\n3. Print Array-1 Elements:\n"); printf("\n4. Print Array-2 Elements:\n"); printf("\n5. Delete The Array-1 Elements:\n"); printf("\n6. Delete The Array-2 Elements:\n"); printf("\n7. Exit From The Program:\n"); printf("\n\nEnter Your Choice: "); scanf("%d",&c); switch(c){ case 1: arrIn(); break; case 2: CopyArr(); break; case 3: PrintArr1(); break; case 4: PrintArr2(); break; case 5: DeleteArr1(); break; case 6: DeleteArr2(); break; case 7: exit(0); default: printf("Wrong choice!!!\n"); break; } } return 0; }
the_stack_data/373315.c
#include <stdio.h> #include <stdlib.h> int main() { int N, i, cont; double soma, media, porcentagem; printf("Quantas pessoas serao digitadas? "); scanf("%d", &N); int idades[N]; char nomes[N][50]; double alturas[N]; for(i = 0; i < N; i++){ printf("Dados da %da pessoa:\n", i + 1); printf("Nome: "); fseek(stdin, 0, SEEK_END); gets(nomes[i]); printf("Idade: "); scanf("%d", &idades[i]); printf("Altura: "); scanf("%lf", &alturas[i]); } soma = 0; for(i = 0; i < N; i++){ soma = soma + alturas[i]; } media = soma / N, printf("\nAltura media:%.2lf\n ", media); cont = 0; for(i = 0; i < N; i++){ if(idades[i] < 16){ cont++; } } porcentagem = cont * 100.0 / N; printf("Pessoas com menos de 16 anos: %.1lf %%\n", porcentagem); for(i = 0; i < N; i++){ if(idades[i] < 16){ printf("%s\n", nomes[i]); } } return 0; }
the_stack_data/114601.c
// // Created by rahul on 10/8/19. // #include <stdlib.h> #include <stdio.h> #define MAX 3 //altering this value changes size of stack created int st[MAX]; int top=-1; void push(int st[],int val); int pop(int st[]); int peek(int st[]); void display(int st[]); int main(int argc,char **argv) { int val,option; do{ printf("\n *****MAIN MENU*****"); printf("\n 1. PUSH"); printf("\n 2. POP"); printf("\n 3. PEEK"); printf("\n 4. DISPLAY"); printf("\n 5. EXIT"); printf("\n Enter your option: "); scanf("%d", &option); switch(option) { case 1: printf("enter the number to be pushed \n"); scanf("%d",&val); push(st,val); break; case 2: val=pop(st); if(val!=-1) printf("value deleted from stack is : %d",val); break; case 3: val=peek(st); if(val!=-1) printf("\n the value stored at top is %d :",val); break; case 4: display(st); break; } }while(option!=5); } void push(int st[],int val) { if(top==MAX-1) { printf("stack overflow"); } else { top++; st[top]=val; } } int pop(int st[]) { int val; if(top==-1) { printf("\n stack empty"); return -1; } else { val=st[top]; top--; return val; } } void display(int st[]) { int i; if(top==-1) printf("stack is empty"); else { for(i=top;i>=0;i--) { printf("\n %d",st[i]); printf("\n"); } } } int peek(int st[]) { if(top==-1) printf("\n stack is empty"); else return (st[top]); }
the_stack_data/133147.c
/* MDH WCET BENCHMARK SUITE. File version $Id: bsort100.c,v 1.5 2006/01/31 12:16:57 jgn Exp $ */ /* BUBBLESORT BENCHMARK PROGRAM: * This program tests the basic loop constructs, integer comparisons, * and simple array handling of compilers by sorting an array of 10 randomly * generated integers. */ /* Changes: * JG 2005/12/06: All timing code excluded (made to comments) * JG 2005/12/13: The use of memory based I/O (KNOWN_VALUE etc.) is removed * Instead unknown values should be set using annotations * JG 2005/12/20: LastIndex removed from function BubbleSort * Indented program. */ /* All output disabled for wcsim */ #define WCSIM 1 /* A read from this address will result in an known value of 1 #define KNOWN_VALUE (int)(*((char *)0x80200001)) */ /* A read from this address will result in an unknown value #define UNKNOWN_VALUE (int)(*((char *)0x80200003)) */ /* #include <sys/types.h> #include <sys/times.h> #include <stdio.h> */ #define WORSTCASE 1 #define FALSE 0 #define TRUE 1 #define NUMELEMS 20 #define MAXDIM (NUMELEMS+1) int Array[MAXDIM], Seed; int factor; void BubbleSort(int Array[]); void Initialize(int Array[]); int main(void) { Initialize(Array); BubbleSort(Array); return 0; } void Initialize(int Array[]) /* * Initializes given array with randomly generated integers. */ { int Index, fact; #ifdef WORSTCASE factor = -1; #else factor = 1; #endif fact = factor; for (Index = 1; Index <= NUMELEMS; Index ++) { Array[Index] = Index * fact/* * KNOWN_VALUE*/; } } void BubbleSort(int Array[]) /* * Sorts an array of integers of size NUMELEMS in ascending order. */ { int Sorted = FALSE; int Temp, Index, i; for (i = 1; i <= NUMELEMS - 1; /* apsim_loop 1 0 */ i++) { Sorted = TRUE; for (Index = 1; Index <= NUMELEMS - 1; /* apsim_loop 10 1 */ Index++) { if (Index > NUMELEMS - i) break; if (Array[Index] > Array[Index + 1]) { Temp = Array[Index]; Array[Index] = Array[Index + 1]; Array[Index + 1] = Temp; Sorted = FALSE; } } if (Sorted) break; } }
the_stack_data/182954386.c
#include <stdio.h> int main(){ double n; scanf("%lf",&n); if(n >= 26){ printf("1"); } else{ printf("0"); } return 0; }
the_stack_data/1194252.c
#if JS_JOBSCHED_TYPE!=JS_NONE /* * binn.[ch] as per https://github.com/liteserver/binn * * MODIFICATIONS: added pragmas to ignore -Wmaybe-uninitialized warnings AZ 21032019 * * see APACHE license in 3rd party/Binn */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <memory.h> #include "binn.h" #define UNUSED(x) (void)(x) #define round(dbl) dbl >= 0.0 ? (int)(dbl + 0.5) : ((dbl - (double)(int)dbl) <= -0.5 ? (int)dbl : (int)(dbl - 0.5)) // magic number: 0x1F 0xb1 0x22 0x1F => 0x1FB1221F or 0x1F22B11F // because the BINN_STORAGE_NOBYTES (binary 000) may not have so many sub-types (BINN_STORAGE_HAS_MORE = 0x10) #define BINN_MAGIC 0x1F22B11F #define MAX_BINN_HEADER 9 // [1:type][4:size][4:count] #define MIN_BINN_SIZE 3 // [1:type][1:size][1:count] #define CHUNK_SIZE 256 // 1024 #define BINN_STRUCT 1 #define BINN_BUFFER 2 void* (*malloc_fn)(size_t len) = 0; void* (*realloc_fn)(void *ptr, size_t len) = 0; void (*free_fn)(void *ptr) = 0; /***************************************************************************/ #if defined(__alpha__) || defined(__hppa__) || defined(__mips__) || defined(__powerpc__) || defined(__sparc__) #define BINN_ONLY_ALIGNED_ACCESS #elif ( defined(__arm__) || defined(__aarch64__) ) && !defined(__ARM_FEATURE_UNALIGNED) #define BINN_ONLY_ALIGNED_ACCESS #endif #if defined(_WIN32) #define BIG_ENDIAN 0x1000 #define LITTLE_ENDIAN 0x0001 #define BYTE_ORDER LITTLE_ENDIAN #elif defined(__APPLE__) /* macros already defined */ #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__) #include <sys/endian.h> #elif defined(_AIX) #include <sys/machine.h> #else #include <endian.h> #endif #ifndef BYTE_ORDER #error "BYTE_ORDER not defined" #endif #ifndef BIG_ENDIAN #error "BIG_ENDIAN not defined" #endif #ifndef LITTLE_ENDIAN #error "LITTLE_ENDIAN not defined" #endif #if BIG_ENDIAN == LITTLE_ENDIAN #error "BIG_ENDIAN == LITTLE_ENDIAN" #endif #if BYTE_ORDER!=BIG_ENDIAN && BYTE_ORDER!=LITTLE_ENDIAN #error "BYTE_ORDER not supported" #endif typedef unsigned short int u16; typedef unsigned int u32; typedef unsigned long long int u64; BINN_PRIVATE void copy_be16(u16 *pdest, u16 *psource) { #if BYTE_ORDER == LITTLE_ENDIAN unsigned char *source = (unsigned char *) psource; unsigned char *dest = (unsigned char *) pdest; dest[0] = source[1]; dest[1] = source[0]; #else // if BYTE_ORDER == BIG_ENDIAN #ifdef BINN_ONLY_ALIGNED_ACCESS if (psource % 2 == 0){ // address aligned to 16 bit *pdest = *psource; } else { unsigned char *source = (unsigned char *) psource; unsigned char *dest = (unsigned char *) pdest; dest[0] = source[0]; // indexes are the same dest[1] = source[1]; } #else *pdest = *psource; #endif #endif } BINN_PRIVATE void copy_be32(u32 *pdest, u32 *psource) { #if BYTE_ORDER == LITTLE_ENDIAN unsigned char *source = (unsigned char *) psource; unsigned char *dest = (unsigned char *) pdest; dest[0] = source[3]; dest[1] = source[2]; dest[2] = source[1]; dest[3] = source[0]; #else // if BYTE_ORDER == BIG_ENDIAN #ifdef BINN_ONLY_ALIGNED_ACCESS if (psource % 4 == 0){ // address aligned to 32 bit *pdest = *psource; } else { unsigned char *source = (unsigned char *) psource; unsigned char *dest = (unsigned char *) pdest; dest[0] = source[0]; // indexes are the same dest[1] = source[1]; dest[2] = source[2]; dest[3] = source[3]; } #else *pdest = *psource; #endif #endif } BINN_PRIVATE void copy_be64(u64 *pdest, u64 *psource) { #if BYTE_ORDER == LITTLE_ENDIAN unsigned char *source = (unsigned char *) psource; unsigned char *dest = (unsigned char *) pdest; int i; for (i=0; i < 8; i++) { dest[i] = source[7-i]; } #else // if BYTE_ORDER == BIG_ENDIAN #ifdef BINN_ONLY_ALIGNED_ACCESS if (psource % 8 == 0){ // address aligned to 64 bit *pdest = *psource; } else { unsigned char *source = (unsigned char *) psource; unsigned char *dest = (unsigned char *) pdest; int i; for (i=0; i < 8; i++) { dest[i] = source[i]; // indexes are the same } } #else *pdest = *psource; #endif #endif } /***************************************************************************/ #ifndef WIN32 #define stricmp strcasecmp #define strnicmp strncasecmp #endif BINN_PRIVATE BOOL IsValidBinnHeader(void *pbuf, int *ptype, int *pcount, int *psize, int *pheadersize); /***************************************************************************/ void APIENTRY binn_set_alloc_functions(void* (*new_malloc)(size_t), void* (*new_realloc)(void*,size_t), void (*new_free)(void*)) { malloc_fn = new_malloc; realloc_fn = new_realloc; free_fn = new_free; } /***************************************************************************/ BINN_PRIVATE void check_alloc_functions() { if (malloc_fn == 0) malloc_fn = &malloc; if (realloc_fn == 0) realloc_fn = &realloc; if (free_fn == 0) free_fn = &free; } /***************************************************************************/ BINN_PRIVATE void * binn_malloc(int size) { check_alloc_functions(); return malloc_fn(size); } /***************************************************************************/ BINN_PRIVATE void * binn_memdup(void *src, int size) { void *dest; if (src == NULL || size <= 0) return NULL; dest = binn_malloc(size); if (dest == NULL) return NULL; memcpy(dest, src, size); return dest; } /***************************************************************************/ BINN_PRIVATE size_t strlen2(char *str) { if (str == NULL) return 0; return strlen(str); } /***************************************************************************/ int APIENTRY binn_create_type(int storage_type, int data_type_index) { if (data_type_index < 0) return -1; if ((storage_type < BINN_STORAGE_MIN) || (storage_type > BINN_STORAGE_MAX)) return -1; if (data_type_index < 16) return storage_type | data_type_index; else if (data_type_index < 4096) { storage_type |= BINN_STORAGE_HAS_MORE; storage_type <<= 8; data_type_index >>= 4; return storage_type | data_type_index; } else return -1; } /***************************************************************************/ BOOL APIENTRY binn_get_type_info(int long_type, int *pstorage_type, int *pextra_type) { int storage_type, extra_type; BOOL retval=TRUE; again: if (long_type < 0) { goto loc_invalid; } else if (long_type <= 0xff) { storage_type = long_type & BINN_STORAGE_MASK; extra_type = long_type & BINN_TYPE_MASK; } else if (long_type <= 0xffff) { storage_type = long_type & BINN_STORAGE_MASK16; storage_type >>= 8; extra_type = long_type & BINN_TYPE_MASK16; extra_type >>= 4; } else if (long_type & BINN_STORAGE_VIRTUAL) { //storage_type = BINN_STORAGE_VIRTUAL; //extra_type = xxx; long_type &= 0xffff; goto again; } else { loc_invalid: storage_type = -1; extra_type = -1; retval = FALSE; } if (pstorage_type) *pstorage_type = storage_type; if (pextra_type) *pextra_type = extra_type; return retval; } /***************************************************************************/ BOOL APIENTRY binn_create(binn *item, int type, int size, void *pointer) { BOOL retval=FALSE; switch (type) { case BINN_LIST: case BINN_MAP: case BINN_OBJECT: break; default: goto loc_exit; } if ((item == NULL) || (size < 0)) goto loc_exit; if (size < MIN_BINN_SIZE) { if (pointer) goto loc_exit; else size = 0; } memset(item, 0, sizeof(binn)); if (pointer) { item->pre_allocated = TRUE; item->pbuf = pointer; item->alloc_size = size; } else { item->pre_allocated = FALSE; if (size == 0) size = CHUNK_SIZE; pointer = binn_malloc(size); if (pointer == 0) return INVALID_BINN; item->pbuf = pointer; item->alloc_size = size; } item->header = BINN_MAGIC; //item->allocated = FALSE; -- already zeroed item->writable = TRUE; item->used_size = MAX_BINN_HEADER; // save space for the header item->type = type; //item->count = 0; -- already zeroed item->dirty = TRUE; // the header is not written to the buffer retval = TRUE; loc_exit: return retval; } /***************************************************************************/ binn * APIENTRY binn_new(int type, int size, void *pointer) { binn *item; item = (binn*) binn_malloc(sizeof(binn)); if (binn_create(item, type, size, pointer) == FALSE) { free_fn(item); return NULL; } item->allocated = TRUE; return item; } /*************************************************************************************/ BOOL APIENTRY binn_create_list(binn *list) { return binn_create(list, BINN_LIST, 0, NULL); } /*************************************************************************************/ BOOL APIENTRY binn_create_map(binn *map) { return binn_create(map, BINN_MAP, 0, NULL); } /*************************************************************************************/ BOOL APIENTRY binn_create_object(binn *object) { return binn_create(object, BINN_OBJECT, 0, NULL); } /***************************************************************************/ binn * APIENTRY binn_list() { return binn_new(BINN_LIST, 0, 0); } /***************************************************************************/ binn * APIENTRY binn_map() { return binn_new(BINN_MAP, 0, 0); } /***************************************************************************/ binn * APIENTRY binn_object() { return binn_new(BINN_OBJECT, 0, 0); } /***************************************************************************/ binn * APIENTRY binn_copy(void *old) { int type, count, size, header_size; unsigned char *old_ptr = binn_ptr(old); binn *item; size = 0; if (!IsValidBinnHeader(old_ptr, &type, &count, &size, &header_size)) return NULL; item = binn_new(type, size - header_size + MAX_BINN_HEADER, NULL); if( item ){ unsigned char *dest; dest = ((unsigned char *) item->pbuf) + MAX_BINN_HEADER; memcpy(dest, old_ptr + header_size, size - header_size); item->used_size = MAX_BINN_HEADER + size - header_size; item->count = count; } return item; } /*************************************************************************************/ BOOL APIENTRY binn_load(void *data, binn *value) { if ((data == NULL) || (value == NULL)) return FALSE; memset(value, 0, sizeof(binn)); value->header = BINN_MAGIC; //value->allocated = FALSE; -- already zeroed //value->writable = FALSE; if (binn_is_valid(data, &value->type, &value->count, &value->size) == FALSE) return FALSE; value->ptr = data; return TRUE; } /*************************************************************************************/ binn * APIENTRY binn_open(void *data) { binn *item; item = (binn*) binn_malloc(sizeof(binn)); if (binn_load(data, item) == FALSE) { free_fn(item); return NULL; } item->allocated = TRUE; return item; } /***************************************************************************/ BINN_PRIVATE int binn_get_ptr_type(void *ptr) { if (ptr == NULL) return 0; switch (*(unsigned int *)ptr) { case BINN_MAGIC: return BINN_STRUCT; default: return BINN_BUFFER; } } /***************************************************************************/ BOOL APIENTRY binn_is_struct(void *ptr) { if (ptr == NULL) return FALSE; if ((*(unsigned int *)ptr) == BINN_MAGIC) { return TRUE; } else { return FALSE; } } /***************************************************************************/ BINN_PRIVATE int CalcAllocation(int needed_size, int alloc_size) { int calc_size; calc_size = alloc_size; while (calc_size < needed_size) { calc_size <<= 1; // same as *= 2 //calc_size += CHUNK_SIZE; -- this is slower than the above line, because there are more reallocations } return calc_size; } /***************************************************************************/ BINN_PRIVATE BOOL CheckAllocation(binn *item, int add_size) { int alloc_size; void *ptr; if (item->used_size + add_size > item->alloc_size) { if (item->pre_allocated) return FALSE; alloc_size = CalcAllocation(item->used_size + add_size, item->alloc_size); ptr = realloc_fn(item->pbuf, alloc_size); if (ptr == NULL) return FALSE; item->pbuf = ptr; item->alloc_size = alloc_size; } return TRUE; } /***************************************************************************/ #if BYTE_ORDER == BIG_ENDIAN BINN_PRIVATE int get_storage_size(int storage_type) { switch (storage_type) { case BINN_STORAGE_NOBYTES: return 0; case BINN_STORAGE_BYTE: return 1; case BINN_STORAGE_WORD: return 2; case BINN_STORAGE_DWORD: return 4; case BINN_STORAGE_QWORD: return 8; default: return 0; } } #endif /***************************************************************************/ BINN_PRIVATE unsigned char * AdvanceDataPos(unsigned char *p, unsigned char *plimit) { unsigned char byte; int storage_type, DataSize; if (p > plimit) return 0; byte = *p; p++; storage_type = byte & BINN_STORAGE_MASK; if (byte & BINN_STORAGE_HAS_MORE) p++; switch (storage_type) { case BINN_STORAGE_NOBYTES: //p += 0; break; case BINN_STORAGE_BYTE: p ++; break; case BINN_STORAGE_WORD: p += 2; break; case BINN_STORAGE_DWORD: p += 4; break; case BINN_STORAGE_QWORD: p += 8; break; case BINN_STORAGE_BLOB: if (p + sizeof(int) - 1 > plimit) return 0; copy_be32((u32*)&DataSize, (u32*)p); p += 4 + DataSize; break; case BINN_STORAGE_CONTAINER: if (p > plimit) return 0; DataSize = *((unsigned char*)p); if (DataSize & 0x80) { if (p + sizeof(int) - 1 > plimit) return 0; copy_be32((u32*)&DataSize, (u32*)p); DataSize &= 0x7FFFFFFF; } DataSize--; // remove the type byte already added before p += DataSize; break; case BINN_STORAGE_STRING: if (p > plimit) return 0; DataSize = *((unsigned char*)p); if (DataSize & 0x80) { if (p + sizeof(int) - 1 > plimit) return 0; copy_be32((u32*)&DataSize, (u32*)p); DataSize &= 0x7FFFFFFF; p+=4; } else { p++; } p += DataSize; p++; // null terminator. break; default: return 0; } if (p > plimit) return 0; return p; } /***************************************************************************/ BINN_PRIVATE unsigned char * SearchForID(unsigned char *p, int header_size, int size, int numitems, int id) { unsigned char *plimit, *base; int i, int32; base = p; plimit = p + size - 1; p += header_size; // search for the ID in all the arguments. for (i = 0; i < numitems; i++) { copy_be32((u32*)&int32, (u32*)p); p += 4; if (p > plimit) break; // Compare if the IDs are equal. if (int32 == id) return p; // xxx p = AdvanceDataPos(p, plimit); if ((p == 0) || (p < base)) break; } return NULL; } /***************************************************************************/ BINN_PRIVATE unsigned char * SearchForKey(unsigned char *p, int header_size, int size, int numitems, char *key) { unsigned char len, *plimit, *base; int i, keylen; base = p; plimit = p + size - 1; p += header_size; keylen = strlen(key); // search for the key in all the arguments. for (i = 0; i < numitems; i++) { len = *((unsigned char *)p); p++; if (p > plimit) break; // Compare if the strings are equal. if (len > 0) { if (strnicmp((char*)p, key, len) == 0) { // note that there is no null terminator here if (keylen == len) { p += len; return p; } } p += len; if (p > plimit) break; } else if (len == keylen) { // in the case of empty string: "" return p; } // xxx p = AdvanceDataPos(p, plimit); if ((p == 0) || (p < base)) break; } return NULL; } /***************************************************************************/ BINN_PRIVATE BOOL AddValue(binn *item, int type, void *pvalue, int size); /***************************************************************************/ BINN_PRIVATE BOOL binn_list_add_raw(binn *item, int type, void *pvalue, int size) { if ((item == NULL) || (item->type != BINN_LIST) || (item->writable == FALSE)) return FALSE; //if (CheckAllocation(item, 4) == FALSE) return FALSE; // 4 bytes used for data_store and data_format. if (AddValue(item, type, pvalue, size) == FALSE) return FALSE; item->count++; return TRUE; } /***************************************************************************/ BINN_PRIVATE BOOL binn_object_set_raw(binn *item, char *key, int type, void *pvalue, int size) { unsigned char *p, len; int int32; if ((item == NULL) || (item->type != BINN_OBJECT) || (item->writable == FALSE)) return FALSE; if (key == NULL) return FALSE; int32 = strlen(key); if (int32 > 255) return FALSE; // is the key already in it? p = SearchForKey(item->pbuf, MAX_BINN_HEADER, item->used_size, item->count, key); if (p) return FALSE; // start adding it if (CheckAllocation(item, 1 + int32) == FALSE) return FALSE; // bytes used for the key size and the key itself. p = ((unsigned char *) item->pbuf) + item->used_size; len = int32; *p = len; p++; memcpy(p, key, int32); int32++; // now contains the strlen + 1 byte for the len item->used_size += int32; if (AddValue(item, type, pvalue, size) == FALSE) { item->used_size -= int32; return FALSE; } item->count++; return TRUE; } /***************************************************************************/ BINN_PRIVATE BOOL binn_map_set_raw(binn *item, int id, int type, void *pvalue, int size) { unsigned char *p; if ((item == NULL) || (item->type != BINN_MAP) || (item->writable == FALSE)) return FALSE; // is the ID already in it? p = SearchForID(item->pbuf, MAX_BINN_HEADER, item->used_size, item->count, id); if (p) return FALSE; // start adding it if (CheckAllocation(item, 4) == FALSE) return FALSE; // 4 bytes used for the id. p = ((unsigned char *) item->pbuf) + item->used_size; copy_be32((u32*)p, (u32*)&id); item->used_size += 4; if (AddValue(item, type, pvalue, size) == FALSE) { item->used_size -= 4; return FALSE; } item->count++; return TRUE; } /***************************************************************************/ BINN_PRIVATE void * compress_int(int *pstorage_type, int *ptype, void *psource) { int storage_type, storage_type2, type, type2=0; int64 vint; uint64 vuint; char *pvalue; #if BYTE_ORDER == BIG_ENDIAN int size1, size2; #endif storage_type = *pstorage_type; if (storage_type == BINN_STORAGE_BYTE) return psource; type = *ptype; switch (type) { case BINN_INT64: vint = *(int64*)psource; goto loc_signed; case BINN_INT32: vint = *(int*)psource; goto loc_signed; case BINN_INT16: vint = *(short*)psource; goto loc_signed; case BINN_UINT64: vuint = *(uint64*)psource; goto loc_positive; case BINN_UINT32: vuint = *(unsigned int*)psource; goto loc_positive; case BINN_UINT16: vuint = *(unsigned short*)psource; goto loc_positive; } loc_signed: if (vint >= 0) { vuint = vint; goto loc_positive; } //loc_negative: // AZ 21032019 - suppress warning #ifdef __GNUC__ #ifndef __clang__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #endif #endif if (vint >= INT8_MIN) { type2 = BINN_INT8; } else if (vint >= INT16_MIN) { type2 = BINN_INT16; } else if (vint >= INT32_MIN) { type2 = BINN_INT32; } #ifdef __GNUC__ #ifndef __clang__ #pragma GCC diagnostic pop #endif #endif goto loc_exit; loc_positive: if (vuint <= UINT8_MAX) { type2 = BINN_UINT8; } else if (vuint <= UINT16_MAX) { type2 = BINN_UINT16; } else if (vuint <= UINT32_MAX) { type2 = BINN_UINT32; } loc_exit: pvalue = (char *) psource; if ((type2) && (type2 != type)) { *ptype = type2; storage_type2 = binn_get_write_storage(type2); *pstorage_type = storage_type2; #if BYTE_ORDER == BIG_ENDIAN size1 = get_storage_size(storage_type); size2 = get_storage_size(storage_type2); pvalue += (size1 - size2); #endif } return pvalue; } /***************************************************************************/ BINN_PRIVATE int type_family(int type); BINN_PRIVATE BOOL AddValue(binn *item, int type, void *pvalue, int size) { int int32, ArgSize, storage_type, extra_type; unsigned char *p; binn_get_type_info(type, &storage_type, &extra_type); if (pvalue == NULL) { switch (storage_type) { case BINN_STORAGE_NOBYTES: break; case BINN_STORAGE_BLOB: case BINN_STORAGE_STRING: if (size == 0) break; // the 2 above are allowed to have 0 length default: return FALSE; } } if ((type_family(type) == BINN_FAMILY_INT) && (item->disable_int_compression == FALSE)) pvalue = compress_int(&storage_type, &type, pvalue); switch (storage_type) { case BINN_STORAGE_NOBYTES: size = 0; ArgSize = size; break; case BINN_STORAGE_BYTE: size = 1; ArgSize = size; break; case BINN_STORAGE_WORD: size = 2; ArgSize = size; break; case BINN_STORAGE_DWORD: size = 4; ArgSize = size; break; case BINN_STORAGE_QWORD: size = 8; ArgSize = size; break; case BINN_STORAGE_BLOB: if (size < 0) return FALSE; //if (size == 0) ... ArgSize = size + 4; break; case BINN_STORAGE_STRING: if (size < 0) return FALSE; if (size == 0) size = strlen2( (char *) pvalue); ArgSize = size + 5; // at least this size break; case BINN_STORAGE_CONTAINER: if (size <= 0) return FALSE; ArgSize = size; break; default: return FALSE; } ArgSize += 2; // at least 2 bytes used for data_type. if (CheckAllocation(item, ArgSize) == FALSE) return FALSE; // Gets the pointer to the next place in buffer p = ((unsigned char *) item->pbuf) + item->used_size; // If the data is not a container, store the data type if (storage_type != BINN_STORAGE_CONTAINER) { if (type > 255) { u16 type16 = type; copy_be16((u16*)p, (u16*)&type16); p += 2; item->used_size += 2; } else { *p = type; p++; item->used_size++; } } switch (storage_type) { case BINN_STORAGE_NOBYTES: // Nothing to do. break; case BINN_STORAGE_BYTE: *((char *) p) = *((char *) pvalue); item->used_size += 1; break; case BINN_STORAGE_WORD: copy_be16((u16*)p, (u16*)pvalue); item->used_size += 2; break; case BINN_STORAGE_DWORD: copy_be32((u32*)p, (u32*)pvalue); item->used_size += 4; break; case BINN_STORAGE_QWORD: copy_be64((u64*)p, (u64*)pvalue); item->used_size += 8; break; case BINN_STORAGE_BLOB: copy_be32((u32*)p, (u32*)&size); p += 4; memcpy(p, pvalue, size); item->used_size += 4 + size; break; case BINN_STORAGE_STRING: if (size > 127) { int32 = size | 0x80000000; copy_be32((u32*)p, (u32*)&int32); p += 4; item->used_size += 4; } else { *((unsigned char *) p) = size; p++; item->used_size++; } memcpy(p, pvalue, size); p += size; *((char *) p) = (char) 0; size++; // null terminator item->used_size += size; break; case BINN_STORAGE_CONTAINER: memcpy(p, pvalue, size); item->used_size += size; break; } item->dirty = TRUE; return TRUE; } /***************************************************************************/ BINN_PRIVATE BOOL binn_save_header(binn *item) { unsigned char byte, *p; int int32, size; if (item == NULL) return FALSE; #ifndef BINN_DISABLE_SMALL_HEADER p = ((unsigned char *) item->pbuf) + MAX_BINN_HEADER; size = item->used_size - MAX_BINN_HEADER + 3; // at least 3 bytes for the header // write the count if (item->count > 127) { p -= 4; size += 3; int32 = item->count | 0x80000000; copy_be32((u32*)p, (u32*)&int32); } else { p--; *p = (unsigned char) item->count; } // write the size if (size > 127) { p -= 4; size += 3; int32 = size | 0x80000000; copy_be32((u32*)p, (u32*)&int32); } else { p--; *p = (unsigned char) size; } // write the type. p--; *p = (unsigned char) item->type; // set the values item->ptr = p; item->size = size; UNUSED(byte); #else p = (unsigned char *) item->pbuf; // write the type. byte = item->type; *p = byte; p++; // write the size int32 = item->used_size | 0x80000000; copy_be32((u32*)p, (u32*)&int32); p+=4; // write the count int32 = item->count | 0x80000000; copy_be32((u32*)p, (u32*)&int32); item->ptr = item->pbuf; item->size = item->used_size; #endif item->dirty = FALSE; return TRUE; } /***************************************************************************/ void APIENTRY binn_free(binn *item) { if (item == NULL) return; if ((item->writable) && (item->pre_allocated == FALSE)) { free_fn(item->pbuf); } if (item->freefn) item->freefn(item->ptr); if (item->allocated) { free_fn(item); } else { memset(item, 0, sizeof(binn)); item->header = BINN_MAGIC; } } /***************************************************************************/ // free the binn structure but keeps the binn buffer allocated, returning a pointer to it. use the free function to release the buffer later void * APIENTRY binn_release(binn *item) { void *data; if (item == NULL) return NULL; data = binn_ptr(item); if (data > item->pbuf) { memmove(item->pbuf, data, item->size); data = item->pbuf; } if (item->allocated) { free_fn(item); } else { memset(item, 0, sizeof(binn)); item->header = BINN_MAGIC; } return data; } /***************************************************************************/ BINN_PRIVATE BOOL IsValidBinnHeader(void *pbuf, int *ptype, int *pcount, int *psize, int *pheadersize) { unsigned char byte, *p, *plimit=0; int int32, type, size, count; if (pbuf == NULL) return FALSE; p = (unsigned char *) pbuf; if (psize && *psize > 0) { plimit = p + *psize - 1; } // get the type byte = *p; p++; if ((byte & BINN_STORAGE_MASK) != BINN_STORAGE_CONTAINER) return FALSE; if (byte & BINN_STORAGE_HAS_MORE) return FALSE; type = byte; switch (type) { case BINN_LIST: case BINN_MAP: case BINN_OBJECT: break; default: return FALSE; } // get the size if (plimit && p > plimit) return FALSE; int32 = *((unsigned char*)p); if (int32 & 0x80) { if (plimit && p + sizeof(int) - 1 > plimit) return FALSE; copy_be32((u32*)&int32, (u32*)p); int32 &= 0x7FFFFFFF; p+=4; } else { p++; } size = int32; // get the count if (plimit && p > plimit) return FALSE; int32 = *((unsigned char*)p); if (int32 & 0x80) { if (plimit && p + sizeof(int) - 1 > plimit) return FALSE; copy_be32((u32*)&int32, (u32*)p); int32 &= 0x7FFFFFFF; p+=4; } else { p++; } count = int32; #if 0 // get the size copy_be32((u32*)&size, (u32*)p); size &= 0x7FFFFFFF; p+=4; // get the count copy_be32((u32*)&count, (u32*)p); count &= 0x7FFFFFFF; p+=4; #endif if ((size < MIN_BINN_SIZE) || (count < 0)) return FALSE; // return the values if (ptype) *ptype = type; if (pcount) *pcount = count; if (psize && *psize==0) *psize = size; if (pheadersize) *pheadersize = (int) (p - (unsigned char*)pbuf); return TRUE; } /***************************************************************************/ BINN_PRIVATE int binn_buf_type(void *pbuf) { int type; if (!IsValidBinnHeader(pbuf, &type, NULL, NULL, NULL)) return INVALID_BINN; return type; } /***************************************************************************/ BINN_PRIVATE int binn_buf_count(void *pbuf) { int nitems; if (!IsValidBinnHeader(pbuf, NULL, &nitems, NULL, NULL)) return 0; return nitems; } /***************************************************************************/ BINN_PRIVATE int binn_buf_size(void *pbuf) { int size=0; if (!IsValidBinnHeader(pbuf, NULL, NULL, &size, NULL)) return 0; return size; } /***************************************************************************/ void * APIENTRY binn_ptr(void *ptr) { binn *item; switch (binn_get_ptr_type(ptr)) { case BINN_STRUCT: item = (binn*) ptr; if (item->writable && item->dirty) { binn_save_header(item); } return item->ptr; case BINN_BUFFER: return ptr; default: return NULL; } } /***************************************************************************/ int APIENTRY binn_size(void *ptr) { binn *item; switch (binn_get_ptr_type(ptr)) { case BINN_STRUCT: item = (binn*) ptr; if (item->writable && item->dirty) { binn_save_header(item); } return item->size; case BINN_BUFFER: return binn_buf_size(ptr); default: return 0; } } /***************************************************************************/ int APIENTRY binn_type(void *ptr) { binn *item; switch (binn_get_ptr_type(ptr)) { case BINN_STRUCT: item = (binn*) ptr; return item->type; case BINN_BUFFER: return binn_buf_type(ptr); default: return -1; } } /***************************************************************************/ int APIENTRY binn_count(void *ptr) { binn *item; switch (binn_get_ptr_type(ptr)) { case BINN_STRUCT: item = (binn*) ptr; return item->count; case BINN_BUFFER: return binn_buf_count(ptr); default: return -1; } } /***************************************************************************/ BOOL APIENTRY binn_is_valid_ex(void *ptr, int *ptype, int *pcount, int *psize) { int i, type, count, size, header_size; unsigned char *p, *plimit, *base, len; void *pbuf; pbuf = binn_ptr(ptr); if (pbuf == NULL) return FALSE; // is there an informed size? if (psize && *psize > 0) { size = *psize; } else { size = 0; } if (!IsValidBinnHeader(pbuf, &type, &count, &size, &header_size)) return FALSE; // is there an informed size? if (psize && *psize > 0) { // is it the same as the one in the buffer? if (size != *psize) return FALSE; } // is there an informed count? if (pcount && *pcount > 0) { // is it the same as the one in the buffer? if (count != *pcount) return FALSE; } // is there an informed type? if (ptype && *ptype != 0) { // is it the same as the one in the buffer? if (type != *ptype) return FALSE; } // it could compare the content size with the size informed on the header p = (unsigned char *)pbuf; base = p; plimit = p + size; p += header_size; // process all the arguments. for (i = 0; i < count; i++) { switch (type) { case BINN_OBJECT: // gets the string size (argument name) len = *p; p++; //if (len == 0) goto Invalid; // increment the used space p += len; break; case BINN_MAP: // increment the used space p += 4; break; //case BINN_LIST: // break; } // xxx p = AdvanceDataPos(p, plimit); if ((p == 0) || (p < base)) goto Invalid; } if (ptype && *ptype==0) *ptype = type; if (pcount && *pcount==0) *pcount = count; if (psize && *psize==0) *psize = size; return TRUE; Invalid: return FALSE; } /***************************************************************************/ BOOL APIENTRY binn_is_valid(void *ptr, int *ptype, int *pcount, int *psize) { if (ptype) *ptype = 0; if (pcount) *pcount = 0; if (psize) *psize = 0; return binn_is_valid_ex(ptr, ptype, pcount, psize); } /***************************************************************************/ /*** INTERNAL FUNCTIONS ****************************************************/ /***************************************************************************/ BINN_PRIVATE BOOL GetValue(unsigned char *p, binn *value) { unsigned char byte; int data_type, storage_type; //, extra_type; int DataSize; void *p2; if (value == NULL) return FALSE; memset(value, 0, sizeof(binn)); value->header = BINN_MAGIC; //value->allocated = FALSE; -- already zeroed //value->writable = FALSE; // saves for use with BINN_STORAGE_CONTAINER p2 = p; // read the data type byte = *p; p++; storage_type = byte & BINN_STORAGE_MASK; if (byte & BINN_STORAGE_HAS_MORE) { data_type = byte << 8; byte = *p; p++; data_type |= byte; //extra_type = data_type & BINN_TYPE_MASK16; } else { data_type = byte; //extra_type = byte & BINN_TYPE_MASK; } //value->storage_type = storage_type; value->type = data_type; switch (storage_type) { case BINN_STORAGE_NOBYTES: break; case BINN_STORAGE_BYTE: value->vuint8 = *((unsigned char *) p); value->ptr = p; //value->ptr = &value->vuint8; break; case BINN_STORAGE_WORD: copy_be16((u16*)&value->vint16, (u16*)p); value->ptr = &value->vint16; break; case BINN_STORAGE_DWORD: copy_be32((u32*)&value->vint32, (u32*)p); value->ptr = &value->vint32; break; case BINN_STORAGE_QWORD: copy_be64((u64*)&value->vint64, (u64*)p); value->ptr = &value->vint64; break; case BINN_STORAGE_BLOB: copy_be32((u32*)&value->size, (u32*)p); p+=4; value->ptr = p; break; case BINN_STORAGE_CONTAINER: value->ptr = p2; // <-- it returns the pointer to the container, not the data if (IsValidBinnHeader(p2, NULL, &value->count, &value->size, NULL) == FALSE) return FALSE; break; case BINN_STORAGE_STRING: DataSize = *((unsigned char*)p); if (DataSize & 0x80) { copy_be32((u32*)&DataSize, (u32*)p); DataSize &= 0x7FFFFFFF; p+=4; } else { p++; } value->size = DataSize; value->ptr = p; break; default: return FALSE; } // convert the returned value, if needed switch (value->type) { case BINN_TRUE: value->type = BINN_BOOL; value->vbool = TRUE; value->ptr = &value->vbool; break; case BINN_FALSE: value->type = BINN_BOOL; value->vbool = FALSE; value->ptr = &value->vbool; break; #ifdef BINN_EXTENDED case BINN_SINGLE_STR: value->type = BINN_SINGLE; value->vfloat = (float) atof((const char*)value->ptr); // converts from string to double, and then to float value->ptr = &value->vfloat; break; case BINN_DOUBLE_STR: value->type = BINN_DOUBLE; value->vdouble = atof((const char*)value->ptr); // converts from string to double value->ptr = &value->vdouble; break; #endif /* case BINN_DECIMAL: case BINN_CURRENCYSTR: case BINN_DATE: case BINN_DATETIME: case BINN_TIME: */ } return TRUE; } /***************************************************************************/ #if BYTE_ORDER == LITTLE_ENDIAN // on little-endian devices we store the value so we can return a pointer to integers. // it's valid only for single-threaded apps. multi-threaded apps must use the _get_ functions instead. binn local_value; BINN_PRIVATE void * store_value(binn *value) { memcpy(&local_value, value, sizeof(binn)); switch (binn_get_read_storage(value->type)) { case BINN_STORAGE_NOBYTES: // return a valid pointer case BINN_STORAGE_WORD: case BINN_STORAGE_DWORD: case BINN_STORAGE_QWORD: return &local_value.vint32; // returns the pointer to the converted value, from big-endian to little-endian } return value->ptr; // returns from the on stack value to be thread-safe (for list, map, object, string and blob) } #endif /***************************************************************************/ /*** READ FUNCTIONS ********************************************************/ /***************************************************************************/ BOOL APIENTRY binn_object_get_value(void *ptr, char *key, binn *value) { int type, count, size=0, header_size; unsigned char *p; ptr = binn_ptr(ptr); if ((ptr == 0) || (key == 0) || (value == 0)) return FALSE; // check the header if (IsValidBinnHeader(ptr, &type, &count, &size, &header_size) == FALSE) return FALSE; if (type != BINN_OBJECT) return FALSE; if (count == 0) return FALSE; p = (unsigned char *) ptr; p = SearchForKey(p, header_size, size, count, key); if (p == FALSE) return FALSE; return GetValue(p, value); } /***************************************************************************/ BOOL APIENTRY binn_map_get_value(void* ptr, int id, binn *value) { int type, count, size=0, header_size; unsigned char *p; ptr = binn_ptr(ptr); if ((ptr == 0) || (value == 0)) return FALSE; // check the header if (IsValidBinnHeader(ptr, &type, &count, &size, &header_size) == FALSE) return FALSE; if (type != BINN_MAP) return FALSE; if (count == 0) return FALSE; p = (unsigned char *) ptr; p = SearchForID(p, header_size, size, count, id); if (p == FALSE) return FALSE; return GetValue(p, value); } /***************************************************************************/ BOOL APIENTRY binn_list_get_value(void* ptr, int pos, binn *value) { int i, type, count, size=0, header_size; unsigned char *p, *plimit, *base; ptr = binn_ptr(ptr); if ((ptr == 0) || (value == 0)) return FALSE; // check the header if (IsValidBinnHeader(ptr, &type, &count, &size, &header_size) == FALSE) return FALSE; if (type != BINN_LIST) return FALSE; if (count == 0) return FALSE; if ((pos <= 0) | (pos > count)) return FALSE; pos--; // convert from base 1 to base 0 p = (unsigned char *) ptr; base = p; plimit = p + size; p += header_size; for (i = 0; i < pos; i++) { p = AdvanceDataPos(p, plimit); if ((p == 0) || (p < base)) return FALSE; } return GetValue(p, value); } /***************************************************************************/ /*** READ PAIR BY POSITION *************************************************/ /***************************************************************************/ BINN_PRIVATE BOOL binn_read_pair(int expected_type, void *ptr, int pos, int *pid, char *pkey, binn *value) { int type, count, size=0, header_size; int i, int32, id, counter=0; unsigned char *p, *plimit, *base, *key, len; ptr = binn_ptr(ptr); // check the header if (IsValidBinnHeader(ptr, &type, &count, &size, &header_size) == FALSE) return FALSE; if ((type != expected_type) || (count == 0) || (pos < 1) || (pos > count)) return FALSE; p = (unsigned char *) ptr; base = p; plimit = p + size - 1; p += header_size; for (i = 0; i < count; i++) { switch (type) { case BINN_MAP: copy_be32((u32*)&int32, (u32*)p); p += 4; if (p > plimit) return FALSE; id = int32; break; case BINN_OBJECT: len = *((unsigned char *)p); p++; if (p > plimit) return FALSE; key = p; p += len; if (p > plimit) return FALSE; break; } counter++; if (counter == pos) goto found; // p = AdvanceDataPos(p, plimit); if ((p == 0) || (p < base)) return FALSE; } return FALSE; found: switch (type) { case BINN_MAP: if (pid) *pid = id; break; case BINN_OBJECT: if (pkey) { memcpy(pkey, key, len); pkey[len] = 0; } break; } return GetValue(p, value); } /***************************************************************************/ BOOL APIENTRY binn_map_get_pair(void *ptr, int pos, int *pid, binn *value) { return binn_read_pair(BINN_MAP, ptr, pos, pid, NULL, value); } /***************************************************************************/ BOOL APIENTRY binn_object_get_pair(void *ptr, int pos, char *pkey, binn *value) { return binn_read_pair(BINN_OBJECT, ptr, pos, NULL, pkey, value); } /***************************************************************************/ binn * APIENTRY binn_map_pair(void *map, int pos, int *pid) { binn *value; value = (binn *) binn_malloc(sizeof(binn)); if (binn_read_pair(BINN_MAP, map, pos, pid, NULL, value) == FALSE) { free_fn(value); return NULL; } value->allocated = TRUE; return value; } /***************************************************************************/ binn * APIENTRY binn_object_pair(void *obj, int pos, char *pkey) { binn *value; value = (binn *) binn_malloc(sizeof(binn)); if (binn_read_pair(BINN_OBJECT, obj, pos, NULL, pkey, value) == FALSE) { free_fn(value); return NULL; } value->allocated = TRUE; return value; } /***************************************************************************/ /***************************************************************************/ void * APIENTRY binn_map_read_pair(void *ptr, int pos, int *pid, int *ptype, int *psize) { binn value; if (binn_map_get_pair(ptr, pos, pid, &value) == FALSE) return NULL; if (ptype) *ptype = value.type; if (psize) *psize = value.size; #if BYTE_ORDER == LITTLE_ENDIAN return store_value(&value); #else return value.ptr; #endif } /***************************************************************************/ void * APIENTRY binn_object_read_pair(void *ptr, int pos, char *pkey, int *ptype, int *psize) { binn value; if (binn_object_get_pair(ptr, pos, pkey, &value) == FALSE) return NULL; if (ptype) *ptype = value.type; if (psize) *psize = value.size; #if BYTE_ORDER == LITTLE_ENDIAN return store_value(&value); #else return value.ptr; #endif } /***************************************************************************/ /*** SEQUENTIAL READ FUNCTIONS *********************************************/ /***************************************************************************/ BOOL APIENTRY binn_iter_init(binn_iter *iter, void *ptr, int expected_type) { int type, count, size=0, header_size; ptr = binn_ptr(ptr); if ((ptr == 0) || (iter == 0)) return FALSE; memset(iter, 0, sizeof(binn_iter)); // check the header if (IsValidBinnHeader(ptr, &type, &count, &size, &header_size) == FALSE) return FALSE; if (type != expected_type) return FALSE; //if (count == 0) return FALSE; -- should not be used iter->plimit = (unsigned char *)ptr + size - 1; iter->pnext = (unsigned char *)ptr + header_size; iter->count = count; iter->current = 0; iter->type = type; return TRUE; } /***************************************************************************/ BOOL APIENTRY binn_list_next(binn_iter *iter, binn *value) { unsigned char *pnow; if ((iter == 0) || (iter->pnext == 0) || (iter->pnext > iter->plimit) || (iter->current > iter->count) || (iter->type != BINN_LIST)) return FALSE; iter->current++; if (iter->current > iter->count) return FALSE; pnow = iter->pnext; iter->pnext = AdvanceDataPos(pnow, iter->plimit); if (iter->pnext != 0 && iter->pnext < pnow) return FALSE; return GetValue(pnow, value); } /***************************************************************************/ BINN_PRIVATE BOOL binn_read_next_pair(int expected_type, binn_iter *iter, int *pid, char *pkey, binn *value) { int int32, id; unsigned char *p, *key; unsigned short len; if ((iter == 0) || (iter->pnext == 0) || (iter->pnext > iter->plimit) || (iter->current > iter->count) || (iter->type != expected_type)) return FALSE; iter->current++; if (iter->current > iter->count) return FALSE; p = iter->pnext; switch (expected_type) { case BINN_MAP: copy_be32((u32*)&int32, (u32*)p); p += 4; if (p > iter->plimit) return FALSE; id = int32; if (pid) *pid = id; break; case BINN_OBJECT: len = *((unsigned char *)p); p++; key = p; p += len; if (p > iter->plimit) return FALSE; if (pkey) { memcpy(pkey, key, len); pkey[len] = 0; } break; } iter->pnext = AdvanceDataPos(p, iter->plimit); if (iter->pnext != 0 && iter->pnext < p) return FALSE; return GetValue(p, value); } /***************************************************************************/ BOOL APIENTRY binn_map_next(binn_iter *iter, int *pid, binn *value) { return binn_read_next_pair(BINN_MAP, iter, pid, NULL, value); } /***************************************************************************/ BOOL APIENTRY binn_object_next(binn_iter *iter, char *pkey, binn *value) { return binn_read_next_pair(BINN_OBJECT, iter, NULL, pkey, value); } /***************************************************************************/ /***************************************************************************/ binn * APIENTRY binn_list_next_value(binn_iter *iter) { binn *value; value = (binn *) binn_malloc(sizeof(binn)); if (binn_list_next(iter, value) == FALSE) { free_fn(value); return NULL; } value->allocated = TRUE; return value; } /***************************************************************************/ binn * APIENTRY binn_map_next_value(binn_iter *iter, int *pid) { binn *value; value = (binn *) binn_malloc(sizeof(binn)); if (binn_map_next(iter, pid, value) == FALSE) { free_fn(value); return NULL; } value->allocated = TRUE; return value; } /***************************************************************************/ binn * APIENTRY binn_object_next_value(binn_iter *iter, char *pkey) { binn *value; value = (binn *) binn_malloc(sizeof(binn)); if (binn_object_next(iter, pkey, value) == FALSE) { free_fn(value); return NULL; } value->allocated = TRUE; return value; } /***************************************************************************/ /***************************************************************************/ void * APIENTRY binn_list_read_next(binn_iter *iter, int *ptype, int *psize) { binn value; if (binn_list_next(iter, &value) == FALSE) return NULL; if (ptype) *ptype = value.type; if (psize) *psize = value.size; #if BYTE_ORDER == LITTLE_ENDIAN return store_value(&value); #else return value.ptr; #endif } /***************************************************************************/ void * APIENTRY binn_map_read_next(binn_iter *iter, int *pid, int *ptype, int *psize) { binn value; if (binn_map_next(iter, pid, &value) == FALSE) return NULL; if (ptype) *ptype = value.type; if (psize) *psize = value.size; #if BYTE_ORDER == LITTLE_ENDIAN return store_value(&value); #else return value.ptr; #endif } /***************************************************************************/ void * APIENTRY binn_object_read_next(binn_iter *iter, char *pkey, int *ptype, int *psize) { binn value; if (binn_object_next(iter, pkey, &value) == FALSE) return NULL; if (ptype) *ptype = value.type; if (psize) *psize = value.size; #if BYTE_ORDER == LITTLE_ENDIAN return store_value(&value); #else return value.ptr; #endif } /*************************************************************************************/ /****** EXTENDED INTERFACE ***********************************************************/ /****** none of the functions above call the functions below *************************/ /*************************************************************************************/ int APIENTRY binn_get_write_storage(int type) { int storage_type; switch (type) { case BINN_SINGLE_STR: case BINN_DOUBLE_STR: return BINN_STORAGE_STRING; case BINN_BOOL: return BINN_STORAGE_NOBYTES; default: binn_get_type_info(type, &storage_type, NULL); return storage_type; } } /*************************************************************************************/ int APIENTRY binn_get_read_storage(int type) { int storage_type; switch (type) { #ifdef BINN_EXTENDED case BINN_SINGLE_STR: return BINN_STORAGE_DWORD; case BINN_DOUBLE_STR: return BINN_STORAGE_QWORD; #endif case BINN_BOOL: case BINN_TRUE: case BINN_FALSE: return BINN_STORAGE_DWORD; default: binn_get_type_info(type, &storage_type, NULL); return storage_type; } } /*************************************************************************************/ BINN_PRIVATE BOOL GetWriteConvertedData(int *ptype, void **ppvalue, int *psize) { int type; float f1; double d1; char pstr[128]; UNUSED(pstr); UNUSED(d1); UNUSED(f1); type = *ptype; if (*ppvalue == NULL) { switch (type) { case BINN_NULL: case BINN_TRUE: case BINN_FALSE: break; case BINN_STRING: case BINN_BLOB: if (*psize == 0) break; default: return FALSE; } } switch (type) { #ifdef BINN_EXTENDED case BINN_SINGLE: f1 = **(float**)ppvalue; d1 = f1; // convert from float (32bits) to double (64bits) type = BINN_SINGLE_STR; goto conv_double; case BINN_DOUBLE: d1 = **(double**)ppvalue; type = BINN_DOUBLE_STR; conv_double: // the '%.17e' is more precise than the '%g' snprintf(pstr, 127, "%.17e", d1); *ppvalue = pstr; *ptype = type; break; #endif case BINN_DECIMAL: case BINN_CURRENCYSTR: /* if (binn_malloc_extptr(128) == NULL) return FALSE; snprintf(sptr, 127, "%E", **ppvalue); *ppvalue = sptr; */ return TRUE; //! temporary break; case BINN_DATE: case BINN_DATETIME: case BINN_TIME: return TRUE; //! temporary break; case BINN_BOOL: if (**((BOOL**)ppvalue) == FALSE) { type = BINN_FALSE; } else { type = BINN_TRUE; } *ptype = type; break; } return TRUE; } /*************************************************************************************/ BINN_PRIVATE int type_family(int type) { switch (type) { case BINN_LIST: case BINN_MAP: case BINN_OBJECT: return BINN_FAMILY_BINN; case BINN_INT8: case BINN_INT16: case BINN_INT32: case BINN_INT64: case BINN_UINT8: case BINN_UINT16: case BINN_UINT32: case BINN_UINT64: return BINN_FAMILY_INT; case BINN_FLOAT32: case BINN_FLOAT64: //case BINN_SINGLE: case BINN_SINGLE_STR: //case BINN_DOUBLE: case BINN_DOUBLE_STR: return BINN_FAMILY_FLOAT; case BINN_STRING: case BINN_HTML: case BINN_CSS: case BINN_XML: case BINN_JSON: case BINN_JAVASCRIPT: return BINN_FAMILY_STRING; case BINN_BLOB: case BINN_JPEG: case BINN_GIF: case BINN_PNG: case BINN_BMP: return BINN_FAMILY_BLOB; case BINN_DECIMAL: case BINN_CURRENCY: case BINN_DATE: case BINN_TIME: case BINN_DATETIME: return BINN_FAMILY_STRING; case BINN_BOOL: return BINN_FAMILY_BOOL; case BINN_NULL: return BINN_FAMILY_NULL; default: // if it wasn't found return BINN_FAMILY_NONE; } } /*************************************************************************************/ BINN_PRIVATE int int_type(int type) { switch (type) { case BINN_INT8: case BINN_INT16: case BINN_INT32: case BINN_INT64: return BINN_SIGNED_INT; case BINN_UINT8: case BINN_UINT16: case BINN_UINT32: case BINN_UINT64: return BINN_UNSIGNED_INT; default: return 0; } } /*************************************************************************************/ BINN_PRIVATE BOOL copy_raw_value(void *psource, void *pdest, int data_store) { switch (data_store) { case BINN_STORAGE_NOBYTES: break; case BINN_STORAGE_BYTE: *((char *) pdest) = *(char *)psource; break; case BINN_STORAGE_WORD: *((short *) pdest) = *(short *)psource; break; case BINN_STORAGE_DWORD: *((int *) pdest) = *(int *)psource; break; case BINN_STORAGE_QWORD: *((uint64 *) pdest) = *(uint64 *)psource; break; case BINN_STORAGE_BLOB: case BINN_STORAGE_STRING: case BINN_STORAGE_CONTAINER: *((char **) pdest) = (char *)psource; break; default: return FALSE; } return TRUE; } /*************************************************************************************/ BINN_PRIVATE BOOL copy_int_value(void *psource, void *pdest, int source_type, int dest_type) { uint64 vuint64; int64 vint64; switch (source_type) { case BINN_INT8: vint64 = *(signed char *)psource; break; case BINN_INT16: vint64 = *(short *)psource; break; case BINN_INT32: vint64 = *(int *)psource; break; case BINN_INT64: vint64 = *(int64 *)psource; break; case BINN_UINT8: vuint64 = *(unsigned char *)psource; break; case BINN_UINT16: vuint64 = *(unsigned short *)psource; break; case BINN_UINT32: vuint64 = *(unsigned int *)psource; break; case BINN_UINT64: vuint64 = *(uint64 *)psource; break; default: return FALSE; } // copy from int64 to uint64, if possible if ((int_type(source_type) == BINN_UNSIGNED_INT) && (int_type(dest_type) == BINN_SIGNED_INT)) { if (vuint64 > INT64_MAX) return FALSE; vint64 = vuint64; } else if ((int_type(source_type) == BINN_SIGNED_INT) && (int_type(dest_type) == BINN_UNSIGNED_INT)) { if (vint64 < 0) return FALSE; vuint64 = vint64; } // AZ 21032019 - suppress warning #ifdef __GNUC__ #ifndef __clang__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #endif #endif switch (dest_type) { case BINN_INT8: if ((vint64 < INT8_MIN) || (vint64 > INT8_MAX)) return FALSE; *(signed char *)pdest = (signed char) vint64; break; case BINN_INT16: if ((vint64 < INT16_MIN) || (vint64 > INT16_MAX)) return FALSE; *(short *)pdest = (short) vint64; break; case BINN_INT32: if ((vint64 < INT32_MIN) || (vint64 > INT32_MAX)) return FALSE; *(int *)pdest = (int) vint64; break; case BINN_INT64: *(int64 *)pdest = vint64; break; case BINN_UINT8: if (vuint64 > UINT8_MAX) return FALSE; *(unsigned char *)pdest = (unsigned char) vuint64; break; case BINN_UINT16: if (vuint64 > UINT16_MAX) return FALSE; *(unsigned short *)pdest = (unsigned short) vuint64; break; case BINN_UINT32: if (vuint64 > UINT32_MAX) return FALSE; *(unsigned int *)pdest = (unsigned int) vuint64; break; case BINN_UINT64: *(uint64 *)pdest = vuint64; break; default: return FALSE; } #ifdef __GNUC__ #ifndef __clang__ #pragma GCC diagnostic pop #endif #endif return TRUE; } /*************************************************************************************/ BINN_PRIVATE BOOL copy_float_value(void *psource, void *pdest, int source_type, int dest_type) { switch (source_type) { case BINN_FLOAT32: *(double *)pdest = *(float *)psource; break; case BINN_FLOAT64: *(float *)pdest = (float) *(double *)psource; break; default: return FALSE; } return TRUE; } /*************************************************************************************/ BINN_PRIVATE void zero_value(void *pvalue, int type) { //int size=0; switch (binn_get_read_storage(type)) { case BINN_STORAGE_NOBYTES: break; case BINN_STORAGE_BYTE: *((char *) pvalue) = 0; //size=1; break; case BINN_STORAGE_WORD: *((short *) pvalue) = 0; //size=2; break; case BINN_STORAGE_DWORD: *((int *) pvalue) = 0; //size=4; break; case BINN_STORAGE_QWORD: *((uint64 *) pvalue) = 0; //size=8; break; case BINN_STORAGE_BLOB: case BINN_STORAGE_STRING: case BINN_STORAGE_CONTAINER: *(char **)pvalue = NULL; break; } //if (size>0) memset(pvalue, 0, size); } /*************************************************************************************/ BINN_PRIVATE BOOL copy_value(void *psource, void *pdest, int source_type, int dest_type, int data_store) { if (type_family(source_type) != type_family(dest_type)) return FALSE; if ((type_family(source_type) == BINN_FAMILY_INT) && (source_type != dest_type)) { return copy_int_value(psource, pdest, source_type, dest_type); } else if ((type_family(source_type) == BINN_FAMILY_FLOAT) && (source_type != dest_type)) { return copy_float_value(psource, pdest, source_type, dest_type); } else { return copy_raw_value(psource, pdest, data_store); } } /*************************************************************************************/ /*** WRITE FUNCTIONS *****************************************************************/ /*************************************************************************************/ BOOL APIENTRY binn_list_add(binn *list, int type, void *pvalue, int size) { if (GetWriteConvertedData(&type, &pvalue, &size) == FALSE) return FALSE; return binn_list_add_raw(list, type, pvalue, size); } /*************************************************************************************/ BOOL APIENTRY binn_map_set(binn *map, int id, int type, void *pvalue, int size) { if (GetWriteConvertedData(&type, &pvalue, &size) == FALSE) return FALSE; return binn_map_set_raw(map, id, type, pvalue, size); } /*************************************************************************************/ BOOL APIENTRY binn_object_set(binn *obj, char *key, int type, void *pvalue, int size) { if (GetWriteConvertedData(&type, &pvalue, &size) == FALSE) return FALSE; return binn_object_set_raw(obj, key, type, pvalue, size); } /*************************************************************************************/ // this function is used by the wrappers BOOL APIENTRY binn_add_value(binn *item, int binn_type, int id, char *name, int type, void *pvalue, int size) { switch (binn_type) { case BINN_LIST: return binn_list_add(item, type, pvalue, size); case BINN_MAP: return binn_map_set(item, id, type, pvalue, size); case BINN_OBJECT: return binn_object_set(item, name, type, pvalue, size); default: return FALSE; } } /*************************************************************************************/ /*************************************************************************************/ BOOL APIENTRY binn_list_add_new(binn *list, binn *value) { BOOL retval; retval = binn_list_add_value(list, value); if (value) free_fn(value); return retval; } /*************************************************************************************/ BOOL APIENTRY binn_map_set_new(binn *map, int id, binn *value) { BOOL retval; retval = binn_map_set_value(map, id, value); if (value) free_fn(value); return retval; } /*************************************************************************************/ BOOL APIENTRY binn_object_set_new(binn *obj, char *key, binn *value) { BOOL retval; retval = binn_object_set_value(obj, key, value); if (value) free_fn(value); return retval; } /*************************************************************************************/ /*** READ FUNCTIONS ******************************************************************/ /*************************************************************************************/ binn * APIENTRY binn_list_value(void *ptr, int pos) { binn *value; value = (binn *) binn_malloc(sizeof(binn)); if (binn_list_get_value(ptr, pos, value) == FALSE) { free_fn(value); return NULL; } value->allocated = TRUE; return value; } /*************************************************************************************/ binn * APIENTRY binn_map_value(void *ptr, int id) { binn *value; value = (binn *) binn_malloc(sizeof(binn)); if (binn_map_get_value(ptr, id, value) == FALSE) { free_fn(value); return NULL; } value->allocated = TRUE; return value; } /*************************************************************************************/ binn * APIENTRY binn_object_value(void *ptr, char *key) { binn *value; value = (binn *) binn_malloc(sizeof(binn)); if (binn_object_get_value(ptr, key, value) == FALSE) { free_fn(value); return NULL; } value->allocated = TRUE; return value; } /***************************************************************************/ /***************************************************************************/ void * APIENTRY binn_list_read(void *list, int pos, int *ptype, int *psize) { binn value; if (binn_list_get_value(list, pos, &value) == FALSE) return NULL; if (ptype) *ptype = value.type; if (psize) *psize = value.size; #if BYTE_ORDER == LITTLE_ENDIAN return store_value(&value); #else return value.ptr; #endif } /***************************************************************************/ void * APIENTRY binn_map_read(void *map, int id, int *ptype, int *psize) { binn value; if (binn_map_get_value(map, id, &value) == FALSE) return NULL; if (ptype) *ptype = value.type; if (psize) *psize = value.size; #if BYTE_ORDER == LITTLE_ENDIAN return store_value(&value); #else return value.ptr; #endif } /***************************************************************************/ void * APIENTRY binn_object_read(void *obj, char *key, int *ptype, int *psize) { binn value; if (binn_object_get_value(obj, key, &value) == FALSE) return NULL; if (ptype) *ptype = value.type; if (psize) *psize = value.size; #if BYTE_ORDER == LITTLE_ENDIAN return store_value(&value); #else return value.ptr; #endif } /***************************************************************************/ /***************************************************************************/ BOOL APIENTRY binn_list_get(void *ptr, int pos, int type, void *pvalue, int *psize) { binn value; int storage_type; storage_type = binn_get_read_storage(type); if ((storage_type != BINN_STORAGE_NOBYTES) && (pvalue == NULL)) return FALSE; zero_value(pvalue, type); if (binn_list_get_value(ptr, pos, &value) == FALSE) return FALSE; if (copy_value(value.ptr, pvalue, value.type, type, storage_type) == FALSE) return FALSE; if (psize) *psize = value.size; return TRUE; } /***************************************************************************/ BOOL APIENTRY binn_map_get(void *ptr, int id, int type, void *pvalue, int *psize) { binn value; int storage_type; storage_type = binn_get_read_storage(type); if ((storage_type != BINN_STORAGE_NOBYTES) && (pvalue == NULL)) return FALSE; zero_value(pvalue, type); if (binn_map_get_value(ptr, id, &value) == FALSE) return FALSE; if (copy_value(value.ptr, pvalue, value.type, type, storage_type) == FALSE) return FALSE; if (psize) *psize = value.size; return TRUE; } /***************************************************************************/ // if (binn_object_get(obj, "multiplier", BINN_INT32, &multiplier, NULL) == FALSE) xxx; BOOL APIENTRY binn_object_get(void *ptr, char *key, int type, void *pvalue, int *psize) { binn value; int storage_type; storage_type = binn_get_read_storage(type); if ((storage_type != BINN_STORAGE_NOBYTES) && (pvalue == NULL)) return FALSE; zero_value(pvalue, type); if (binn_object_get_value(ptr, key, &value) == FALSE) return FALSE; if (copy_value(value.ptr, pvalue, value.type, type, storage_type) == FALSE) return FALSE; if (psize) *psize = value.size; return TRUE; } /***************************************************************************/ /***************************************************************************/ // these functions below may not be implemented as inline functions, because // they use a lot of space, even for the variable. so they will be exported. // but what about using as static? // is there any problem with wrappers? can these wrappers implement these functions using the header? // if as static, will they be present even on modules that don't use the functions? signed char APIENTRY binn_list_int8(void *list, int pos) { signed char value; binn_list_get(list, pos, BINN_INT8, &value, NULL); return value; } short APIENTRY binn_list_int16(void *list, int pos) { short value; binn_list_get(list, pos, BINN_INT16, &value, NULL); return value; } int APIENTRY binn_list_int32(void *list, int pos) { int value; binn_list_get(list, pos, BINN_INT32, &value, NULL); return value; } int64 APIENTRY binn_list_int64(void *list, int pos) { int64 value; binn_list_get(list, pos, BINN_INT64, &value, NULL); return value; } unsigned char APIENTRY binn_list_uint8(void *list, int pos) { unsigned char value; binn_list_get(list, pos, BINN_UINT8, &value, NULL); return value; } unsigned short APIENTRY binn_list_uint16(void *list, int pos) { unsigned short value; binn_list_get(list, pos, BINN_UINT16, &value, NULL); return value; } unsigned int APIENTRY binn_list_uint32(void *list, int pos) { unsigned int value; binn_list_get(list, pos, BINN_UINT32, &value, NULL); return value; } uint64 APIENTRY binn_list_uint64(void *list, int pos) { uint64 value; binn_list_get(list, pos, BINN_UINT64, &value, NULL); return value; } float APIENTRY binn_list_float(void *list, int pos) { float value; binn_list_get(list, pos, BINN_FLOAT32, &value, NULL); return value; } double APIENTRY binn_list_double(void *list, int pos) { double value; binn_list_get(list, pos, BINN_FLOAT64, &value, NULL); return value; } BOOL APIENTRY binn_list_bool(void *list, int pos) { BOOL value; binn_list_get(list, pos, BINN_BOOL, &value, NULL); return value; } BOOL APIENTRY binn_list_null(void *list, int pos) { return binn_list_get(list, pos, BINN_NULL, NULL, NULL); } char * APIENTRY binn_list_str(void *list, int pos) { char *value; binn_list_get(list, pos, BINN_STRING, &value, NULL); return value; } void * APIENTRY binn_list_blob(void *list, int pos, int *psize) { void *value; binn_list_get(list, pos, BINN_BLOB, &value, psize); return value; } void * APIENTRY binn_list_list(void *list, int pos) { void *value; binn_list_get(list, pos, BINN_LIST, &value, NULL); return value; } void * APIENTRY binn_list_map(void *list, int pos) { void *value; binn_list_get(list, pos, BINN_MAP, &value, NULL); return value; } void * APIENTRY binn_list_object(void *list, int pos) { void *value; binn_list_get(list, pos, BINN_OBJECT, &value, NULL); return value; } /***************************************************************************/ signed char APIENTRY binn_map_int8(void *map, int id) { signed char value; binn_map_get(map, id, BINN_INT8, &value, NULL); return value; } short APIENTRY binn_map_int16(void *map, int id) { short value; binn_map_get(map, id, BINN_INT16, &value, NULL); return value; } int APIENTRY binn_map_int32(void *map, int id) { int value; binn_map_get(map, id, BINN_INT32, &value, NULL); return value; } int64 APIENTRY binn_map_int64(void *map, int id) { int64 value; binn_map_get(map, id, BINN_INT64, &value, NULL); return value; } unsigned char APIENTRY binn_map_uint8(void *map, int id) { unsigned char value; binn_map_get(map, id, BINN_UINT8, &value, NULL); return value; } unsigned short APIENTRY binn_map_uint16(void *map, int id) { unsigned short value; binn_map_get(map, id, BINN_UINT16, &value, NULL); return value; } unsigned int APIENTRY binn_map_uint32(void *map, int id) { unsigned int value; binn_map_get(map, id, BINN_UINT32, &value, NULL); return value; } uint64 APIENTRY binn_map_uint64(void *map, int id) { uint64 value; binn_map_get(map, id, BINN_UINT64, &value, NULL); return value; } float APIENTRY binn_map_float(void *map, int id) { float value; binn_map_get(map, id, BINN_FLOAT32, &value, NULL); return value; } double APIENTRY binn_map_double(void *map, int id) { double value; binn_map_get(map, id, BINN_FLOAT64, &value, NULL); return value; } BOOL APIENTRY binn_map_bool(void *map, int id) { BOOL value; binn_map_get(map, id, BINN_BOOL, &value, NULL); return value; } BOOL APIENTRY binn_map_null(void *map, int id) { return binn_map_get(map, id, BINN_NULL, NULL, NULL); } char * APIENTRY binn_map_str(void *map, int id) { char *value; binn_map_get(map, id, BINN_STRING, &value, NULL); return value; } void * APIENTRY binn_map_blob(void *map, int id, int *psize) { void *value; binn_map_get(map, id, BINN_BLOB, &value, psize); return value; } void * APIENTRY binn_map_list(void *map, int id) { void *value; binn_map_get(map, id, BINN_LIST, &value, NULL); return value; } void * APIENTRY binn_map_map(void *map, int id) { void *value; binn_map_get(map, id, BINN_MAP, &value, NULL); return value; } void * APIENTRY binn_map_object(void *map, int id) { void *value; binn_map_get(map, id, BINN_OBJECT, &value, NULL); return value; } /***************************************************************************/ signed char APIENTRY binn_object_int8(void *obj, char *key) { signed char value; binn_object_get(obj, key, BINN_INT8, &value, NULL); return value; } short APIENTRY binn_object_int16(void *obj, char *key) { short value; binn_object_get(obj, key, BINN_INT16, &value, NULL); return value; } int APIENTRY binn_object_int32(void *obj, char *key) { int value; binn_object_get(obj, key, BINN_INT32, &value, NULL); return value; } int64 APIENTRY binn_object_int64(void *obj, char *key) { int64 value; binn_object_get(obj, key, BINN_INT64, &value, NULL); return value; } unsigned char APIENTRY binn_object_uint8(void *obj, char *key) { unsigned char value; binn_object_get(obj, key, BINN_UINT8, &value, NULL); return value; } unsigned short APIENTRY binn_object_uint16(void *obj, char *key) { unsigned short value; binn_object_get(obj, key, BINN_UINT16, &value, NULL); return value; } unsigned int APIENTRY binn_object_uint32(void *obj, char *key) { unsigned int value; binn_object_get(obj, key, BINN_UINT32, &value, NULL); return value; } uint64 APIENTRY binn_object_uint64(void *obj, char *key) { uint64 value; binn_object_get(obj, key, BINN_UINT64, &value, NULL); return value; } float APIENTRY binn_object_float(void *obj, char *key) { float value; binn_object_get(obj, key, BINN_FLOAT32, &value, NULL); return value; } double APIENTRY binn_object_double(void *obj, char *key) { double value; binn_object_get(obj, key, BINN_FLOAT64, &value, NULL); return value; } BOOL APIENTRY binn_object_bool(void *obj, char *key) { BOOL value; binn_object_get(obj, key, BINN_BOOL, &value, NULL); return value; } BOOL APIENTRY binn_object_null(void *obj, char *key) { return binn_object_get(obj, key, BINN_NULL, NULL, NULL); } char * APIENTRY binn_object_str(void *obj, char *key) { char *value; binn_object_get(obj, key, BINN_STRING, &value, NULL); return value; } void * APIENTRY binn_object_blob(void *obj, char *key, int *psize) { void *value; binn_object_get(obj, key, BINN_BLOB, &value, psize); return value; } void * APIENTRY binn_object_list(void *obj, char *key) { void *value; binn_object_get(obj, key, BINN_LIST, &value, NULL); return value; } void * APIENTRY binn_object_map(void *obj, char *key) { void *value; binn_object_get(obj, key, BINN_MAP, &value, NULL); return value; } void * APIENTRY binn_object_object(void *obj, char *key) { void *value; binn_object_get(obj, key, BINN_OBJECT, &value, NULL); return value; } /*************************************************************************************/ /*************************************************************************************/ BINN_PRIVATE binn * binn_alloc_item() { binn *item; item = (binn *) binn_malloc(sizeof(binn)); if (item) { memset(item, 0, sizeof(binn)); item->header = BINN_MAGIC; item->allocated = TRUE; //item->writable = FALSE; -- already zeroed } return item; } /*************************************************************************************/ binn * APIENTRY binn_value(int type, void *pvalue, int size, binn_mem_free freefn) { int storage_type; binn *item = binn_alloc_item(); if (item) { item->type = type; binn_get_type_info(type, &storage_type, NULL); switch (storage_type) { case BINN_STORAGE_NOBYTES: break; case BINN_STORAGE_STRING: if (size == 0) size = strlen((char*)pvalue) + 1; case BINN_STORAGE_BLOB: case BINN_STORAGE_CONTAINER: if (freefn == BINN_TRANSIENT) { item->ptr = binn_memdup(pvalue, size); if (item->ptr == NULL) { free_fn(item); return NULL; } item->freefn = free_fn; if (storage_type == BINN_STORAGE_STRING) size--; } else { item->ptr = pvalue; item->freefn = freefn; } item->size = size; break; default: item->ptr = &item->vint32; copy_raw_value(pvalue, item->ptr, storage_type); } } return item; } /*************************************************************************************/ BOOL APIENTRY binn_set_string(binn *item, char *str, binn_mem_free pfree) { if (item == NULL || str == NULL) return FALSE; if (pfree == BINN_TRANSIENT) { item->ptr = binn_memdup(str, strlen(str) + 1); if (item->ptr == NULL) return FALSE; item->freefn = free_fn; } else { item->ptr = str; item->freefn = pfree; } item->type = BINN_STRING; return TRUE; } /*************************************************************************************/ BOOL APIENTRY binn_set_blob(binn *item, void *ptr, int size, binn_mem_free pfree) { if (item == NULL || ptr == NULL) return FALSE; if (pfree == BINN_TRANSIENT) { item->ptr = binn_memdup(ptr, size); if (item->ptr == NULL) return FALSE; item->freefn = free_fn; } else { item->ptr = ptr; item->freefn = pfree; } item->type = BINN_BLOB; item->size = size; return TRUE; } /*************************************************************************************/ /*** READ CONVERTED VALUE ************************************************************/ /*************************************************************************************/ #ifdef _MSC_VER #define atoi64 _atoi64 #else int64 atoi64(char *str) { int64 retval; int is_negative=0; if (*str == '-') { is_negative = 1; str++; } retval = 0; for (; *str; str++) { retval = 10 * retval + (*str - '0'); } if (is_negative) retval *= -1; return retval; } #endif /*****************************************************************************/ BINN_PRIVATE BOOL is_integer(char *p) { BOOL retval; if (p == NULL) return FALSE; if (*p == '-') p++; if (*p == 0) return FALSE; retval = TRUE; for (; *p; p++) { if ( (*p < '0') || (*p > '9') ) { retval = FALSE; } } return retval; } /*****************************************************************************/ BINN_PRIVATE BOOL is_float(char *p) { BOOL retval, number_found=FALSE; if (p == NULL) return FALSE; if (*p == '-') p++; if (*p == 0) return FALSE; retval = TRUE; for (; *p; p++) { if ((*p == '.') || (*p == ',')) { if (!number_found) retval = FALSE; } else if ( (*p >= '0') && (*p <= '9') ) { number_found = TRUE; } else { return FALSE; } } return retval; } /*************************************************************************************/ BINN_PRIVATE BOOL is_bool_str(char *str, BOOL *pbool) { int64 vint; double vdouble; if (str == NULL || pbool == NULL) return FALSE; if (stricmp(str, "true") == 0) goto loc_true; if (stricmp(str, "yes") == 0) goto loc_true; if (stricmp(str, "on") == 0) goto loc_true; //if (stricmp(str, "1") == 0) goto loc_true; if (stricmp(str, "false") == 0) goto loc_false; if (stricmp(str, "no") == 0) goto loc_false; if (stricmp(str, "off") == 0) goto loc_false; //if (stricmp(str, "0") == 0) goto loc_false; if (is_integer(str)) { vint = atoi64(str); *pbool = (vint != 0) ? TRUE : FALSE; return TRUE; } else if (is_float(str)) { vdouble = atof(str); *pbool = (vdouble != 0) ? TRUE : FALSE; return TRUE; } return FALSE; loc_true: *pbool = TRUE; return TRUE; loc_false: *pbool = FALSE; return TRUE; } /*************************************************************************************/ BOOL APIENTRY binn_get_int32(binn *value, int *pint) { if (value == NULL || pint == NULL) return FALSE; if (type_family(value->type) == BINN_FAMILY_INT) { return copy_int_value(value->ptr, pint, value->type, BINN_INT32); } switch (value->type) { case BINN_FLOAT: if ((value->vfloat < INT32_MIN) || (value->vfloat > INT32_MAX)) return FALSE; *pint = round(value->vfloat); break; case BINN_DOUBLE: if ((value->vdouble < INT32_MIN) || (value->vdouble > INT32_MAX)) return FALSE; *pint = round(value->vdouble); break; case BINN_STRING: if (is_integer((char*)value->ptr)) *pint = atoi((char*)value->ptr); else if (is_float((char*)value->ptr)) *pint = round(atof((char*)value->ptr)); else return FALSE; break; case BINN_BOOL: *pint = value->vbool; break; default: return FALSE; } return TRUE; } /*************************************************************************************/ BOOL APIENTRY binn_get_int64(binn *value, int64 *pint) { if (value == NULL || pint == NULL) return FALSE; if (type_family(value->type) == BINN_FAMILY_INT) { return copy_int_value(value->ptr, pint, value->type, BINN_INT64); } switch (value->type) { case BINN_FLOAT: if ((value->vfloat < INT64_MIN) || (value->vfloat > INT64_MAX)) return FALSE; *pint = round(value->vfloat); break; case BINN_DOUBLE: if ((value->vdouble < INT64_MIN) || (value->vdouble > INT64_MAX)) return FALSE; *pint = round(value->vdouble); break; case BINN_STRING: if (is_integer((char*)value->ptr)) *pint = atoi64((char*)value->ptr); else if (is_float((char*)value->ptr)) *pint = round(atof((char*)value->ptr)); else return FALSE; break; case BINN_BOOL: *pint = value->vbool; break; default: return FALSE; } return TRUE; } /*************************************************************************************/ BOOL APIENTRY binn_get_double(binn *value, double *pfloat) { int64 vint; if (value == NULL || pfloat == NULL) return FALSE; if (type_family(value->type) == BINN_FAMILY_INT) { if (copy_int_value(value->ptr, &vint, value->type, BINN_INT64) == FALSE) return FALSE; *pfloat = (double) vint; return TRUE; } switch (value->type) { case BINN_FLOAT: *pfloat = value->vfloat; break; case BINN_DOUBLE: *pfloat = value->vdouble; break; case BINN_STRING: if (is_integer((char*)value->ptr)) *pfloat = (double) atoi64((char*)value->ptr); else if (is_float((char*)value->ptr)) *pfloat = atof((char*)value->ptr); else return FALSE; break; case BINN_BOOL: *pfloat = value->vbool; break; default: return FALSE; } return TRUE; } /*************************************************************************************/ BOOL APIENTRY binn_get_bool(binn *value, BOOL *pbool) { int64 vint; if (value == NULL || pbool == NULL) return FALSE; if (type_family(value->type) == BINN_FAMILY_INT) { if (copy_int_value(value->ptr, &vint, value->type, BINN_INT64) == FALSE) return FALSE; *pbool = (vint != 0) ? TRUE : FALSE; return TRUE; } switch (value->type) { case BINN_BOOL: *pbool = value->vbool; break; case BINN_FLOAT: *pbool = (value->vfloat != 0) ? TRUE : FALSE; break; case BINN_DOUBLE: *pbool = (value->vdouble != 0) ? TRUE : FALSE; break; case BINN_STRING: return is_bool_str((char*)value->ptr, pbool); default: return FALSE; } return TRUE; } /*************************************************************************************/ char * APIENTRY binn_get_str(binn *value) { int64 vint; char buf[128]; if (value == NULL) return NULL; if (type_family(value->type) == BINN_FAMILY_INT) { if (copy_int_value(value->ptr, &vint, value->type, BINN_INT64) == FALSE) return NULL; sprintf(buf, "%" INT64_FORMAT, vint); goto loc_convert_value; } switch (value->type) { case BINN_FLOAT: value->vdouble = value->vfloat; case BINN_DOUBLE: sprintf(buf, "%g", value->vdouble); goto loc_convert_value; case BINN_STRING: return (char*) value->ptr; case BINN_BOOL: if (value->vbool) strcpy(buf, "true"); else strcpy(buf, "false"); goto loc_convert_value; } return NULL; loc_convert_value: //value->vint64 = 0; value->ptr = strdup(buf); if (value->ptr == NULL) return NULL; value->freefn = free; value->type = BINN_STRING; return (char*) value->ptr; } /*************************************************************************************/ /*** GENERAL FUNCTIONS ***************************************************************/ /*************************************************************************************/ BOOL APIENTRY binn_is_container(binn *item) { if (item == NULL) return FALSE; switch (item->type) { case BINN_LIST: case BINN_MAP: case BINN_OBJECT: return TRUE; default: return FALSE; } } /*************************************************************************************/ #endif
the_stack_data/25632.c
static const char* graph_json = "{\"nodes\": [{\"op\": \"null\", \"name\": \"Reshape_1\", \"inputs\": []}, {\"op\": \"null\", \"name\": \"p0\", \"inputs\": []}, {\"op\": \"tvm_op\", \"name\": \"tvmgen_default_fused_reshape_cast_subtract\", \"attrs\": {\"num_outputs\": \"1\", \"num_inputs\": \"2\", \"flatten_data\": \"0\", \"func_name\": \"tvmgen_default_fused_reshape_cast_subtract\", \"hash\": \"9d4bf10a2292c188\"}, \"inputs\": [[0, 0, 0], [1, 0, 0]]}, {\"op\": \"null\", \"name\": \"p1\", \"inputs\": []}, {\"op\": \"null\", \"name\": \"p2\", \"inputs\": []}, {\"op\": \"null\", \"name\": \"p3\", \"inputs\": []}, {\"op\": \"null\", \"name\": \"p4\", \"inputs\": []}, {\"op\": \"null\", \"name\": \"p5\", \"inputs\": []}, {\"op\": \"tvm_op\", \"name\": \"tvmgen_default_fused_nn_conv2d_add_cast_multiply_add_right_shift_cast_add_clip_cast_clip\", \"attrs\": {\"num_outputs\": \"1\", \"num_inputs\": \"6\", \"flatten_data\": \"0\", \"func_name\": \"tvmgen_default_fused_nn_conv2d_add_cast_multiply_add_right_shift_cast_add_clip_cast_clip\", \"out_layout\": \"\", \"kernel_layout\": \"HWIO\", \"data_layout\": \"NHWC\", \"hash\": \"27ee460434e6faee\"}, \"inputs\": [[2, 0, 0], [3, 0, 0], [4, 0, 0], [5, 0, 0], [6, 0, 0], [7, 0, 0]]}, {\"op\": \"null\", \"name\": \"p6\", \"inputs\": []}, {\"op\": \"tvm_op\", \"name\": \"tvmgen_default_fused_reshape_cast_subtract_1\", \"attrs\": {\"num_outputs\": \"1\", \"num_inputs\": \"2\", \"flatten_data\": \"0\", \"func_name\": \"tvmgen_default_fused_reshape_cast_subtract_1\", \"hash\": \"176bd09511aee12b\"}, \"inputs\": [[8, 0, 0], [9, 0, 0]]}, {\"op\": \"null\", \"name\": \"p7\", \"inputs\": []}, {\"op\": \"null\", \"name\": \"p8\", \"inputs\": []}, {\"op\": \"tvm_op\", \"name\": \"tvmgen_default_fused_nn_contrib_dense_pack_add_fixed_point_multiply_add_clip_cast_cast_subtract_14669711146056581479_\", \"attrs\": {\"num_outputs\": \"1\", \"num_inputs\": \"3\", \"flatten_data\": \"0\", \"func_name\": \"tvmgen_default_fused_nn_contrib_dense_pack_add_fixed_point_multiply_add_clip_cast_cast_subtract_14669711146056581479_\", \"hash\": \"a78a02f28f4677aa\"}, \"inputs\": [[10, 0, 0], [11, 0, 0], [12, 0, 0]]}, {\"op\": \"tvm_op\", \"name\": \"tvmgen_default_fused_nn_softmax\", \"attrs\": {\"num_outputs\": \"1\", \"num_inputs\": \"1\", \"flatten_data\": \"0\", \"func_name\": \"tvmgen_default_fused_nn_softmax\", \"hash\": \"e525638339182d2d\"}, \"inputs\": [[13, 0, 0]]}, {\"op\": \"tvm_op\", \"name\": \"tvmgen_default_fused_divide_add_round_cast_clip_cast\", \"attrs\": {\"num_outputs\": \"1\", \"num_inputs\": \"1\", \"flatten_data\": \"0\", \"func_name\": \"tvmgen_default_fused_divide_add_round_cast_clip_cast\", \"hash\": \"1f81d9f43de9b085\"}, \"inputs\": [[14, 0, 0]]}], \"arg_nodes\": [0, 1, 3, 4, 5, 6, 7, 9, 11, 12], \"heads\": [[15, 0, 0]], \"attrs\": {\"dltype\": [\"list_str\", [\"int8\", \"int16\", \"int16\", \"int16\", \"int32\", \"int64\", \"int64\", \"int64\", \"int8\", \"int16\", \"int16\", \"int16\", \"int32\", \"float32\", \"float32\", \"int8\"]], \"storage_id\": [\"list_int\", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 10, 11, 12, 13, 12]], \"shape\": [\"list_shape\", [[1, 1960], [], [1, 49, 40, 1], [10, 8, 1, 8], [1, 1, 1, 8], [1, 1, 1, 8], [1, 1, 1, 8], [1, 1, 1, 8], [1, 25, 20, 8], [], [1, 4000], [1, 4000, 4], [4], [1, 4], [1, 4], [1, 4]]]}, \"node_row_ptr\": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]}";
the_stack_data/45450064.c
/*- * Copyright (c) 2005, Kohsuke Ohtani * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * vsprintf.c - Format and output data to buffer */ #include <limits.h> #include <stdarg.h> #include <string.h> #include <stdio.h> #define isdigit(c) ((unsigned)((c) - '0') < 10) static int divide(long* n, int base) { int res; /* * Note: Optimized for ARM processor which does not support * divide instructions. * * res = ((unsigned long)*n) % (unsigned int)base; * *n = ((unsigned long)*n) / (unsigned int)base; */ if (base == 10) { res = (int)(((unsigned long)*n) % 10U); *n = (long)(((unsigned long)*n) / 10U); } else { res = (int)(((unsigned long)*n) % 16U); *n = (long)(((unsigned long)*n) / 16U); } return res; } static int atoi(const char** s) { int i = 0; while (isdigit((int)**s)) i = i * 10 + *((*s)++) - '0'; return i; } /* * Print formatted output - scaled down version * * Identifiers: * %d - Decimal signed int * %x - Hex integer * %u - Unsigned integer * %c - Character * %s - String * * Flags: * 0 - Zero pad */ int vsprintf(char* buf, const char* fmt, va_list args) { char *p, *str; const char* digits = "0123456789abcdef"; char pad, tmp[16]; int width, base, sign, i, size; long num; size = 0; for (p = buf; *fmt && (size < LINE_MAX); fmt++, size++) { if (*fmt != '%') { *p++ = *fmt; continue; } /* get flags */ ++fmt; pad = ' '; if (*fmt == '0') { pad = '0'; fmt++; } if (*fmt == 'l') fmt++; /* get width */ width = -1; if (isdigit((int)*fmt)) { width = atoi(&fmt); } base = 10; sign = 0; switch (*fmt) { case 'c': *p++ = (unsigned char)va_arg(args, int); continue; case 's': str = va_arg(args, char*); if (str == NULL) str = "<NULL>"; for (; *str; str++) { *p++ = *str; if (size++ >= LINE_MAX) break; } continue; case 'X': case 'x': base = 16; break; case 'd': sign = 1; break; case 'u': break; default: continue; } num = va_arg(args, long); if (sign && num < 0) { num = -num; *p++ = '-'; width--; } i = 0; if (num == 0) tmp[i++] = '0'; else while (num != 0) tmp[i++] = digits[divide(&num, base)]; width -= i; while (width-- > 0) *p++ = pad; while (i-- > 0) *p++ = tmp[i]; } *p = '\0'; return (p - buf); } int sprintf(char* buf, const char* fmt, ...) { va_list args; int i; va_start(args, fmt); i = vsprintf(buf, fmt, args); va_end(args); return i; }
the_stack_data/89199318.c
int main(int argc, char **argv, char **envp); void exit(int status); void _start (int argc, char **argv, char **envp) __attribute__ ((section (".text.boot"))); void _start (int argc, char **argv, char **envp) { int result; result=main(argc,argv,envp); exit(result); }
the_stack_data/959968.c
// KASAN: use-after-free Read in fw_load_sysfs_fallback // https://syzkaller.appspot.com/bug?id=9b91d635e2b51efd6371 // 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 <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/rfkill.h> #include <linux/rtnetlink.h> #include <linux/tcp.h> #include <linux/veth.h> static unsigned long long procid; 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 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); } 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 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_common() { if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) { } } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); 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(); loop(); 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() { checkpoint_net_namespace(); } static void reset_loop() { reset_net_namespace(); } static void setup_test() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); 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"); } static void setup_usb() { if (chmod("/dev/raw-gadget", 0666)) exit(1); } 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 < 3; call++) { for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0])); thread++) { struct thread_t* th = &threads[thread]; if (!th->created) { th->created = 1; event_init(&th->ready); event_init(&th->done); event_set(&th->done); thread_start(thr, th); } if (!event_isset(&th->done)) continue; event_reset(&th->done); th->call = call; __atomic_fetch_add(&running, 1, __ATOMIC_RELAXED); event_set(&th->ready); if (collide && (call % 2) == 0) break; event_timedwait(&th->done, 50); 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++) { reset_loop(); int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { 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; } } } uint64_t r[2] = {0xffffffffffffffff, 0x0}; void execute_call(int call) { intptr_t res = 0; switch (call) { case 0: res = syscall(__NR_socket, 0x10ul, 3ul, 0x10); if (res != -1) r[0] = res; break; case 1: memcpy((void*)0x20000080, "nl80211\000", 8); res = -1; res = syz_genetlink_get_family_id(0x20000080, -1); if (res != -1) r[1] = res; break; case 2: *(uint64_t*)0x200001c0 = 0; *(uint32_t*)0x200001c8 = 0; *(uint64_t*)0x200001d0 = 0x20000180; *(uint64_t*)0x20000180 = 0x20000140; *(uint32_t*)0x20000140 = 0x28; *(uint16_t*)0x20000144 = r[1]; *(uint16_t*)0x20000146 = 1; *(uint32_t*)0x20000148 = 0; *(uint32_t*)0x2000014c = 0; *(uint8_t*)0x20000150 = 0x7e; *(uint8_t*)0x20000151 = 0; *(uint16_t*)0x20000152 = 0; *(uint16_t*)0x20000154 = 8; *(uint16_t*)0x20000156 = 3; *(uint32_t*)0x20000158 = 0; *(uint16_t*)0x2000015c = 0xc; *(uint16_t*)0x2000015e = 0x99; *(uint32_t*)0x20000160 = 0; *(uint32_t*)0x20000164 = 0; *(uint64_t*)0x20000188 = 0x28; *(uint64_t*)0x200001d8 = 1; *(uint64_t*)0x200001e0 = 0; *(uint64_t*)0x200001e8 = 0; *(uint32_t*)0x200001f0 = 0; syscall(__NR_sendmsg, r[0], 0x200001c0ul, 0ul); 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(); setup_usb(); for (procid = 0; procid < 6; procid++) { if (fork() == 0) { do_sandbox_none(); } } sleep(1000000); return 0; }
the_stack_data/178264417.c
/** * C Object System * * * Copyright 2006+ Laurent Deniau <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <stdlib.h> static int rmlit = 0; static void echo_1(FILE *in, FILE *out) { fputc(fgetc(in), out); } static void echo_upto(FILE *in, FILE *out, int chr) { int c; while ((c = fgetc(in)) != EOF) { fputc(c, out); if (c == '\\') { echo_1(in, out); continue; } if (c == chr ) return; } } static void skip_1(FILE *in) { fgetc(in); } static void skip_upto(FILE *in, int chr) { int c; while ((c = fgetc(in)) != EOF) { if (c == '\\') { skip_1(in); continue; } if (c == chr ) return; } } static void skip_line(FILE *in) { int c; while ((c = fgetc(in)) != EOF && c != '\n') ; ungetc(c, in); } static void skip_cmt(FILE *in) { int c, p; for(p = 0; (c = fgetc(in)) != EOF; p = c) if (c == '/' && p == '*') break; ungetc(' ', in); } static void remove_cmt(FILE *in , FILE *out) { int c; while ((c = fgetc(in)) != EOF) { switch(c) { case '\'': case '"' : if (rmlit) skip_upto(in, c); else { fputc(c, out); echo_upto(in, out, c); } break; case '\\': fputc(c, out); echo_1(in, out); break; case '/' : c = fgetc(in); if (c == '/') { skip_line(in); break; } if (c == '*') { skip_cmt (in); break; } fputc('/', out); default : fputc(c , out); } } } static void help(void) { fprintf(stderr, "usage: coscmt [-h] [-l] [-o outfile] [infiles]\n"); exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { FILE *in = stdin; FILE *out = stdout; int i, o = 0; for (i = 1; i < argc; i++) { if (argv[i][0] == '-') { if (argv[i][1] == 0) continue; if (argv[i][1] == 'l') { argv[i][0] = 0; rmlit = 1; continue; } if (argv[i][1] == 'o') { argv[i][0] = 0; o = ++i; continue; } help(); } } if (o) { if (argv[o][0] == '-') out = stdout; else { out = fopen(argv[o],"w"); if (!out) { fprintf(stderr, "coscmt: unable to open file %s in write mode\n", argv[o]); exit(EXIT_FAILURE); } } argv[o][0] = 0; } for (i = 1; i < argc; i++) { if (argv[i][0] == 0) continue; if (argv[i][0] == '-') in = stdin; else { in = fopen(argv[i],"r"); if (!in) { fprintf(stderr, "coscmt: unable to open file %s in read mode\n", argv[i]); exit(EXIT_FAILURE); } } remove_cmt(in, out); if (in != stdin) fclose(in); } if (out != stdout) fclose(out); return EXIT_SUCCESS; }
the_stack_data/702025.c
#include <string.h> #include <stdio.h> #include <stdlib.h> #define INVALID (-1) int **initW(int n) { int **w = malloc(sizeof(int *) * n); int i; for (i = 0; i != n; i++) { int *p = malloc(sizeof(int) * n); int j; p[0] = i; for (j = 1; j != n; j++) { p[j] = INVALID; } w[i] = p; } return w; } void showW(int **w, int n) { int i, j; for (i = 0; i != n; i++) { printf("%2d:", i); int start = 1; for (j = 0; j != n; j++) { if (w[i][j] == INVALID) { break; } if (start) { printf(" "); start = 0; } printf(" %d", w[i][j]); } printf("\n"); } } void deinitW(int **w, int n) { for (int i = 0; i != n; i++) { free(w[i]); } free(w); } void moveOnto(int **w, int n, int a, int b) { } void moveOver(int **w, int n, int a, int b) { } void pileOnto(int **w, int n, int a, int b) { } void pileOver(int **w, int n, int a, int b) { } #define CMDLEN 32 int main() { int n; int r = scanf("%d", &n); if (r != 1) { return -1; } int **w = initW(n); showW(w, n); char cmd[CMDLEN], dec[CMDLEN]; int a, b; while ((r = scanf("%s%d%s%d", cmd, &a, dec, &b)) != 0) { if (strcmp(cmd, "quit") == 0) { break; } if (a == b) { // illegal comand continue; } printf("%s %d %s %d\n", cmd, a, dec, b); } printf("%s\n", cmd); deinitW(w, n); return 0; }
the_stack_data/48574600.c
/* * exercise1.cpp * * Created on: Jan. 23, 2020 * Author: mohpreet */ # include<stdlib.h> # include<stdio.h> int fAdd(int*pa,int*pb) { int sum =0; int a; int b; pa=&a; pb=&b; sum=a+b; return sum; } int main() { int a=3; int b=2; printf("sum is %d\n",fAdd(&a,&b)); return 0; }
the_stack_data/90764503.c
/* Copyright (c) 2007 Apple Inc. All rights reserved. @APPLE_LICENSE_HEADER_START@ This file contains Original Code and/or Modifications of Original Code as defined in and that are subject to the Apple Public Source License Version 2.0 (the 'License'). You may not use this file except in compliance with the License. Please obtain a copy of the License at http://www.opensource.apple.com/apsl/ and read it before using this file. The Original Code and all software distributed under the License are distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the specific language governing rights and limitations under the License. @APPLE_LICENSE_HEADER_END@ */ #if defined(i386) || defined(__arm__) #include <mach/kern_return.h> #include <mach/mach_time.h> #include <stdint.h> extern void spin_lock(int *); extern void spin_unlock(int *); /* deprecated function stub */ kern_return_t MKGetTimeBaseInfo( uint32_t *minAbsoluteTimeDelta, uint32_t *theAbsoluteTimeToNanosecondNumerator, uint32_t *theAbsoluteTimeToNanosecondDenominator, uint32_t *theProcessorToAbsoluteTimeNumerator, uint32_t *theProcessorToAbsoluteTimeDenominator ) { static struct mach_timebase_info mti = {0}; static int MKGetTimeBaseInfo_spin_lock = 0; if(mti.numer == 0) { kern_return_t err; spin_lock(&MKGetTimeBaseInfo_spin_lock); err = mach_timebase_info(&mti); spin_unlock(&MKGetTimeBaseInfo_spin_lock); if(err != KERN_SUCCESS) { return err; } } if(theAbsoluteTimeToNanosecondNumerator) { *theAbsoluteTimeToNanosecondNumerator = mti.numer; } if(theAbsoluteTimeToNanosecondDenominator) { *theAbsoluteTimeToNanosecondDenominator = mti.denom; } if(minAbsoluteTimeDelta) { *minAbsoluteTimeDelta = 1; } if(theProcessorToAbsoluteTimeNumerator) { *theProcessorToAbsoluteTimeNumerator = 1; } if(theProcessorToAbsoluteTimeDenominator) { *theProcessorToAbsoluteTimeDenominator = 1; } return KERN_SUCCESS; } #endif
the_stack_data/70448949.c
#include <stdio.h> #include <stdbool.h> extern const char GIT_HASH[]; extern const char GIT_BRANCH[]; extern const char GIT_TAG[]; extern const char GIT_DESCRIBE[]; extern const char GIT_SHOART_HASH[]; extern const bool GIT_IS_CLEAN; extern const bool GIT_IS_CLEAN_NO_UNTRACED_FILES; int main(int argc, char *argv[]) { printf("GIT_HASH = %s\n", GIT_HASH); printf("GIT_BRANCH = %s\n", GIT_BRANCH); printf("GIT_TAG = %s\n", GIT_TAG); printf("GIT_DESCRIBE = %s\n", GIT_DESCRIBE); printf("GIT_SHOART_HASH = %s\n", GIT_SHOART_HASH); printf("GIT_IS_CLEAN = %s\n", GIT_IS_CLEAN ? "true" : "false"); printf("GIT_IS_CLEAN_NO_UNTRACED_FILES = %s\n", GIT_IS_CLEAN_NO_UNTRACED_FILES ? "true" : "false"); return 0; }
the_stack_data/165766985.c
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Benchmark `rad2deg`. */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <sys/time.h> #define NAME "rad2deg" #define ITERATIONS 1000000 #define REPEATS 3 /** * Prints the TAP version. */ void print_version() { printf( "TAP version 13\n" ); } /** * Prints the TAP summary. * * @param total total number of tests * @param passing total number of passing tests */ void print_summary( int total, int passing ) { printf( "#\n" ); printf( "1..%d\n", total ); // TAP plan printf( "# total %d\n", total ); printf( "# pass %d\n", passing ); printf( "#\n" ); printf( "# ok\n" ); } /** * Prints benchmarks results. * * @param elapsed elapsed time in seconds */ void print_results( double elapsed ) { double rate = (double)ITERATIONS / elapsed; printf( " ---\n" ); printf( " iterations: %d\n", ITERATIONS ); printf( " elapsed: %0.9f\n", elapsed ); printf( " rate: %0.9f\n", rate ); printf( " ...\n" ); } /** * Returns a clock time. * * @return clock time */ double tic() { struct timeval now; gettimeofday( &now, NULL ); return (double)now.tv_sec + (double)now.tv_usec/1.0e6; } /** * Generates a random double on the interval [0,1]. * * @return random double */ double rand_double() { int r = rand(); return (double)r / ( (double)RAND_MAX + 1.0 ); } /** * Converts radians to degrees. * * @param x radians * @return degrees */ double rad2deg( double x ) { return x * 57.29577951308232; } /** * Runs a benchmark. * * @return elapsed time in seconds */ double benchmark() { double elapsed; double x; double y; double t; int i; t = tic(); for ( i = 0; i < ITERATIONS; i++ ) { x = ( 2.0*rand_double()*3.14 ) - 0.0; y = rad2deg( x ); if ( y != y ) { printf( "should not return NaN\n" ); break; } } elapsed = tic() - t; if ( y != y ) { printf( "should not return NaN\n" ); } return elapsed; } /** * Main execution sequence. */ int main( void ) { double elapsed; int i; // Use the current time to seed the random number generator: srand( time( NULL ) ); print_version(); for ( i = 0; i < REPEATS; i++ ) { printf( "# c::%s\n", NAME ); elapsed = benchmark(); print_results( elapsed ); printf( "ok %d benchmark finished\n", i+1 ); } print_summary( REPEATS, REPEATS ); }
the_stack_data/162644395.c
// generate a bill based on the given order #include <stdio.h> int main() { int num=0, total=0; float amt=0.0, dis=0.0; printf("Enter the number of books: "); scanf("%d", &num); if(num<=10000) { printf("No discount.\n"); amt=num*10; } else if(num>10000 && num<=15000) { printf("You've obtained 10%% discount.\n"); total=num*10; dis=0.1*total; amt=total-dis; } else if(num>15000 && num<=20000) { printf("You've obtained 20%% discount.\n"); total=num*10; dis=0.2*total; amt=total-dis; } else { printf("You can purchase upto 20000 books.\n"); return 0; } printf("The total cost = ₹%.3f\n", amt); printf("The total discount = ₹%.3f\n", dis); return 0; } /* OUTPUT_1 Enter the number of books: 17923 You've obtained 20% discount. The total cost = ₹143384.000 The total discount = ₹35846.000 OUTPUT_2 Enter the number of books: 27921 You can purchase upto 20000 books. */
the_stack_data/423840.c
int Replace(char *String, char From, char To) { int Replaced=0; if( From == '\0' ) return(Replaced); for( ; *String != '\0'; String++ ) if( *String == From ) { *String = To; Replaced++; } return(Replaced); } int Delete(char *String, char From) { int Deleted = 0; char *c; if( From == '\0' ) return(Deleted); for( ; *String != '\0'; String++ ) if( *String == From ) { c = String; for( ;; c++ ) { *c = *(c+1); if( *c == '\0' ) break; } Deleted++; String--; } return(Deleted); }
the_stack_data/383709.c
/* $NetBSD: quote_calc4.tab.c,v 1.5 2021/02/20 22:57:57 christos Exp $ */ /* original parser id follows */ /* yysccsid[] = "@(#)yaccpar 1.9 (Berkeley) 02/21/93" */ /* (use YYMAJOR/YYMINOR for ifdefs dependent on parser version) */ #define YYBYACC 1 #define YYMAJOR 2 #define YYMINOR 0 #define YYCHECK "yyyymmdd" #define YYEMPTY (-1) #define yyclearin (yychar = YYEMPTY) #define yyerrok (yyerrflag = 0) #define YYRECOVERING() (yyerrflag != 0) #define YYENOMEM (-2) #define YYEOF 0 #undef YYBTYACC #define YYBTYACC 0 #define YYDEBUGSTR YYPREFIX "debug" #ifndef yyparse #define yyparse quote_calc4_parse #endif /* yyparse */ #ifndef yylex #define yylex quote_calc4_lex #endif /* yylex */ #ifndef yyerror #define yyerror quote_calc4_error #endif /* yyerror */ #ifndef yychar #define yychar quote_calc4_char #endif /* yychar */ #ifndef yyval #define yyval quote_calc4_val #endif /* yyval */ #ifndef yylval #define yylval quote_calc4_lval #endif /* yylval */ #ifndef yydebug #define yydebug quote_calc4_debug #endif /* yydebug */ #ifndef yynerrs #define yynerrs quote_calc4_nerrs #endif /* yynerrs */ #ifndef yyerrflag #define yyerrflag quote_calc4_errflag #endif /* yyerrflag */ #ifndef yylhs #define yylhs quote_calc4_lhs #endif /* yylhs */ #ifndef yylen #define yylen quote_calc4_len #endif /* yylen */ #ifndef yydefred #define yydefred quote_calc4_defred #endif /* yydefred */ #ifndef yystos #define yystos quote_calc4_stos #endif /* yystos */ #ifndef yydgoto #define yydgoto quote_calc4_dgoto #endif /* yydgoto */ #ifndef yysindex #define yysindex quote_calc4_sindex #endif /* yysindex */ #ifndef yyrindex #define yyrindex quote_calc4_rindex #endif /* yyrindex */ #ifndef yygindex #define yygindex quote_calc4_gindex #endif /* yygindex */ #ifndef yytable #define yytable quote_calc4_table #endif /* yytable */ #ifndef yycheck #define yycheck quote_calc4_check #endif /* yycheck */ #ifndef yyname #define yyname quote_calc4_name #endif /* yyname */ #ifndef yyrule #define yyrule quote_calc4_rule #endif /* yyrule */ #if YYBTYACC #ifndef yycindex #define yycindex quote_calc4_cindex #endif /* yycindex */ #ifndef yyctable #define yyctable quote_calc4_ctable #endif /* yyctable */ #endif /* YYBTYACC */ #define YYPREFIX "quote_calc4_" #define YYPURE 0 #line 2 "quote_calc4.y" # include <stdio.h> # include <ctype.h> int regs[26]; int base; int yylex(void); static void yyerror(const char *s); #line 131 "quote_calc4.tab.c" #if ! defined(YYSTYPE) && ! defined(YYSTYPE_IS_DECLARED) /* Default: YYSTYPE is the semantic value type. */ typedef int YYSTYPE; # define YYSTYPE_IS_DECLARED 1 #endif /* compatibility with bison */ #ifdef YYPARSE_PARAM /* compatibility with FreeBSD */ # ifdef YYPARSE_PARAM_TYPE # define YYPARSE_DECL() yyparse(YYPARSE_PARAM_TYPE YYPARSE_PARAM) # else # define YYPARSE_DECL() yyparse(void *YYPARSE_PARAM) # endif #else # define YYPARSE_DECL() yyparse(void) #endif /* Parameters sent to lex. */ #ifdef YYLEX_PARAM # define YYLEX_DECL() yylex(void *YYLEX_PARAM) # define YYLEX yylex(YYLEX_PARAM) #else # define YYLEX_DECL() yylex(void) # define YYLEX yylex() #endif /* Parameters sent to yyerror. */ #ifndef YYERROR_DECL #define YYERROR_DECL() yyerror(const char *s) #endif #ifndef YYERROR_CALL #define YYERROR_CALL(msg) yyerror(msg) #endif extern int YYPARSE_DECL(); #define OP_ADD 257 #define OP_SUB 259 #define OP_MUL 261 #define OP_DIV 263 #define OP_MOD 265 #define OP_AND 267 #define DIGIT 269 #define LETTER 270 #define UMINUS 271 #define YYERRCODE 256 typedef short YYINT; static const YYINT quote_calc4_lhs[] = { -1, 0, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, }; static const YYINT quote_calc4_len[] = { 2, 0, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 1, 2, }; static const YYINT quote_calc4_defred[] = { 1, 0, 0, 0, 17, 0, 0, 0, 0, 0, 3, 15, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 18, 0, 6, 0, 0, 0, 0, 0, 0, 0, }; #if defined(YYDESTRUCT_CALL) || defined(YYSTYPE_TOSTRING) static const YYINT quote_calc4_stos[] = { 0, 273, 256, 260, 269, 270, 40, 274, 275, 276, 10, 270, 275, 61, 275, 10, 258, 260, 262, 264, 266, 268, 124, 269, 275, 41, 275, 275, 275, 275, 275, 275, 275, }; #endif /* YYDESTRUCT_CALL || YYSTYPE_TOSTRING */ static const YYINT quote_calc4_dgoto[] = { 1, 7, 8, 9, }; static const YYINT quote_calc4_sindex[] = { 0, -38, 4, -36, 0, -51, -36, 6, -121, -249, 0, 0, -243, -36, -23, 0, -36, -36, -36, -36, -36, -36, -36, 0, -121, 0, -121, -121, -121, -121, -121, -121, -243, }; static const YYINT quote_calc4_rindex[] = { 0, 0, 0, 0, 0, -9, 0, 0, 12, -10, 0, 0, -5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, -3, -2, -1, 1, 2, 3, -4, }; #if YYBTYACC static const YYINT quote_calc4_cindex[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; #endif static const YYINT quote_calc4_gindex[] = { 0, 0, 42, 0, }; #define YYTABLESIZE 259 static const YYINT quote_calc4_table[] = { 16, 15, 6, 22, 6, 14, 13, 7, 8, 9, 13, 10, 11, 12, 10, 16, 15, 17, 25, 18, 23, 19, 4, 20, 5, 21, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 14, 13, 7, 8, 9, 0, 10, 11, 12, 12, 0, 0, 14, 0, 0, 0, 0, 0, 0, 24, 0, 0, 26, 27, 28, 29, 30, 31, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 15, 0, 0, 0, 14, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 17, 0, 18, 0, 19, 0, 20, 0, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 3, 0, 0, 0, 0, 0, 0, 4, 5, 4, 11, 16, 0, 17, 0, 18, 0, 19, 0, 20, 0, 21, 0, 0, 16, 15, 16, 15, 16, 15, 16, 15, 16, 15, 16, 15, }; static const YYINT quote_calc4_check[] = { 10, 10, 40, 124, 40, 10, 10, 10, 10, 10, 61, 10, 10, 10, 10, 258, 10, 260, 41, 262, 269, 264, 10, 266, 10, 268, -1, -1, -1, -1, -1, 41, -1, -1, -1, -1, 41, 41, 41, 41, 41, -1, 41, 41, 41, 3, -1, -1, 6, -1, -1, -1, -1, -1, -1, 13, -1, -1, 16, 17, 18, 19, 20, 21, 22, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 124, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 124, 124, -1, -1, -1, 124, 124, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 258, -1, 260, -1, 262, -1, 264, -1, 266, -1, 268, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 256, -1, -1, -1, 260, -1, 260, -1, -1, -1, -1, -1, -1, 269, 270, 269, 270, 258, -1, 260, -1, 262, -1, 264, -1, 266, -1, 268, -1, -1, 258, 258, 260, 260, 262, 262, 264, 264, 266, 266, 268, 268, }; #if YYBTYACC static const YYINT quote_calc4_ctable[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; #endif #define YYFINAL 1 #ifndef YYDEBUG #define YYDEBUG 0 #endif #define YYMAXTOKEN 271 #define YYUNDFTOKEN 277 #define YYTRANSLATE(a) ((a) > YYMAXTOKEN ? YYUNDFTOKEN : (a)) #if YYDEBUG static const char *const quote_calc4_name[] = { "$end",0,0,0,0,0,0,0,0,0,"'\\n'",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,"'%'","'&'",0,"'('","')'","'*'","'+'",0,"'-'",0,"'/'",0,0,0,0,0,0,0,0,0,0, 0,0,0,"'='",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"'|'",0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,"error","OP_ADD","\"ADD-operator\"","OP_SUB","\"SUB-operator\"","OP_MUL", "\"MUL-operator\"","OP_DIV","\"DIV-operator\"","OP_MOD","\"MOD-operator\"", "OP_AND","\"AND-operator\"","DIGIT","LETTER","UMINUS","$accept","list","stat", "expr","number","illegal-symbol", }; static const char *const quote_calc4_rule[] = { "$accept : list", "list :", "list : list stat '\\n'", "list : list error '\\n'", "stat : expr", "stat : LETTER '=' expr", "expr : '(' expr ')'", "expr : expr \"ADD-operator\" expr", "expr : expr \"SUB-operator\" expr", "expr : expr \"MUL-operator\" expr", "expr : expr \"DIV-operator\" expr", "expr : expr \"MOD-operator\" expr", "expr : expr \"AND-operator\" expr", "expr : expr '|' expr", "expr : \"SUB-operator\" expr", "expr : LETTER", "expr : number", "number : DIGIT", "number : number DIGIT", }; #endif #if YYDEBUG int yydebug; #endif int yyerrflag; int yychar; YYSTYPE yyval; YYSTYPE yylval; int yynerrs; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) YYLTYPE yyloc; /* position returned by actions */ YYLTYPE yylloc; /* position from the lexer */ #endif #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) #ifndef YYLLOC_DEFAULT #define YYLLOC_DEFAULT(loc, rhs, n) \ do \ { \ if (n == 0) \ { \ (loc).first_line = YYRHSLOC(rhs, 0).last_line; \ (loc).first_column = YYRHSLOC(rhs, 0).last_column; \ (loc).last_line = YYRHSLOC(rhs, 0).last_line; \ (loc).last_column = YYRHSLOC(rhs, 0).last_column; \ } \ else \ { \ (loc).first_line = YYRHSLOC(rhs, 1).first_line; \ (loc).first_column = YYRHSLOC(rhs, 1).first_column; \ (loc).last_line = YYRHSLOC(rhs, n).last_line; \ (loc).last_column = YYRHSLOC(rhs, n).last_column; \ } \ } while (0) #endif /* YYLLOC_DEFAULT */ #endif /* defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) */ #if YYBTYACC #ifndef YYLVQUEUEGROWTH #define YYLVQUEUEGROWTH 32 #endif #endif /* YYBTYACC */ /* define the initial stack-sizes */ #ifdef YYSTACKSIZE #undef YYMAXDEPTH #define YYMAXDEPTH YYSTACKSIZE #else #ifdef YYMAXDEPTH #define YYSTACKSIZE YYMAXDEPTH #else #define YYSTACKSIZE 10000 #define YYMAXDEPTH 10000 #endif #endif #ifndef YYINITSTACKSIZE #define YYINITSTACKSIZE 200 #endif typedef struct { unsigned stacksize; YYINT *s_base; YYINT *s_mark; YYINT *s_last; YYSTYPE *l_base; YYSTYPE *l_mark; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) YYLTYPE *p_base; YYLTYPE *p_mark; #endif } YYSTACKDATA; #if YYBTYACC struct YYParseState_s { struct YYParseState_s *save; /* Previously saved parser state */ YYSTACKDATA yystack; /* saved parser stack */ int state; /* saved parser state */ int errflag; /* saved error recovery status */ int lexeme; /* saved index of the conflict lexeme in the lexical queue */ YYINT ctry; /* saved index in yyctable[] for this conflict */ }; typedef struct YYParseState_s YYParseState; #endif /* YYBTYACC */ /* variables for the parser stack */ static YYSTACKDATA yystack; #if YYBTYACC /* Current parser state */ static YYParseState *yyps = 0; /* yypath != NULL: do the full parse, starting at *yypath parser state. */ static YYParseState *yypath = 0; /* Base of the lexical value queue */ static YYSTYPE *yylvals = 0; /* Current position at lexical value queue */ static YYSTYPE *yylvp = 0; /* End position of lexical value queue */ static YYSTYPE *yylve = 0; /* The last allocated position at the lexical value queue */ static YYSTYPE *yylvlim = 0; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) /* Base of the lexical position queue */ static YYLTYPE *yylpsns = 0; /* Current position at lexical position queue */ static YYLTYPE *yylpp = 0; /* End position of lexical position queue */ static YYLTYPE *yylpe = 0; /* The last allocated position at the lexical position queue */ static YYLTYPE *yylplim = 0; #endif /* Current position at lexical token queue */ static YYINT *yylexp = 0; static YYINT *yylexemes = 0; #endif /* YYBTYACC */ #line 73 "quote_calc4.y" /* start of programs */ int main (void) { while(!feof(stdin)) { yyparse(); } return 0; } static void yyerror(const char *s) { fprintf(stderr, "%s\n", s); } int yylex(void) { /* lexical analysis routine */ /* returns LETTER for a lower case letter, yylval = 0 through 25 */ /* return DIGIT for a digit, yylval = 0 through 9 */ /* all other characters are returned immediately */ int c; while( (c=getchar()) == ' ' ) { /* skip blanks */ } /* c is now nonblank */ if( islower( c )) { yylval = c - 'a'; return ( LETTER ); } if( isdigit( c )) { yylval = c - '0'; return ( DIGIT ); } return( c ); } #line 530 "quote_calc4.tab.c" /* For use in generated program */ #define yydepth (int)(yystack.s_mark - yystack.s_base) #if YYBTYACC #define yytrial (yyps->save) #endif /* YYBTYACC */ #if YYDEBUG #include <stdio.h> /* needed for printf */ #endif #include <stdlib.h> /* needed for malloc, etc */ #include <string.h> /* needed for memset */ /* allocate initial stack or double stack size, up to YYMAXDEPTH */ static int yygrowstack(YYSTACKDATA *data) { int i; unsigned newsize; YYINT *newss; YYSTYPE *newvs; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) YYLTYPE *newps; #endif if ((newsize = data->stacksize) == 0) newsize = YYINITSTACKSIZE; else if (newsize >= YYMAXDEPTH) return YYENOMEM; else if ((newsize *= 2) > YYMAXDEPTH) newsize = YYMAXDEPTH; i = (int) (data->s_mark - data->s_base); newss = (YYINT *)realloc(data->s_base, newsize * sizeof(*newss)); if (newss == 0) return YYENOMEM; data->s_base = newss; data->s_mark = newss + i; newvs = (YYSTYPE *)realloc(data->l_base, newsize * sizeof(*newvs)); if (newvs == 0) return YYENOMEM; data->l_base = newvs; data->l_mark = newvs + i; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) newps = (YYLTYPE *)realloc(data->p_base, newsize * sizeof(*newps)); if (newps == 0) return YYENOMEM; data->p_base = newps; data->p_mark = newps + i; #endif data->stacksize = newsize; data->s_last = data->s_base + newsize - 1; #if YYDEBUG if (yydebug) fprintf(stderr, "%sdebug: stack size increased to %d\n", YYPREFIX, newsize); #endif return 0; } #if YYPURE || defined(YY_NO_LEAKS) static void yyfreestack(YYSTACKDATA *data) { free(data->s_base); free(data->l_base); #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) free(data->p_base); #endif memset(data, 0, sizeof(*data)); } #else #define yyfreestack(data) /* nothing */ #endif /* YYPURE || defined(YY_NO_LEAKS) */ #if YYBTYACC static YYParseState * yyNewState(unsigned size) { YYParseState *p = (YYParseState *) malloc(sizeof(YYParseState)); if (p == NULL) return NULL; p->yystack.stacksize = size; if (size == 0) { p->yystack.s_base = NULL; p->yystack.l_base = NULL; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) p->yystack.p_base = NULL; #endif return p; } p->yystack.s_base = (YYINT *) malloc(size * sizeof(YYINT)); if (p->yystack.s_base == NULL) return NULL; p->yystack.l_base = (YYSTYPE *) malloc(size * sizeof(YYSTYPE)); if (p->yystack.l_base == NULL) return NULL; memset(p->yystack.l_base, 0, size * sizeof(YYSTYPE)); #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) p->yystack.p_base = (YYLTYPE *) malloc(size * sizeof(YYLTYPE)); if (p->yystack.p_base == NULL) return NULL; memset(p->yystack.p_base, 0, size * sizeof(YYLTYPE)); #endif return p; } static void yyFreeState(YYParseState *p) { yyfreestack(&p->yystack); free(p); } #endif /* YYBTYACC */ #define YYABORT goto yyabort #define YYREJECT goto yyabort #define YYACCEPT goto yyaccept #define YYERROR goto yyerrlab #if YYBTYACC #define YYVALID do { if (yyps->save) goto yyvalid; } while(0) #define YYVALID_NESTED do { if (yyps->save && \ yyps->save->save == 0) goto yyvalid; } while(0) #endif /* YYBTYACC */ int YYPARSE_DECL() { int yym, yyn, yystate, yyresult; #if YYBTYACC int yynewerrflag; YYParseState *yyerrctx = NULL; #endif /* YYBTYACC */ #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) YYLTYPE yyerror_loc_range[3]; /* position of error start/end (0 unused) */ #endif #if YYDEBUG const char *yys; if ((yys = getenv("YYDEBUG")) != 0) { yyn = *yys; if (yyn >= '0' && yyn <= '9') yydebug = yyn - '0'; } if (yydebug) fprintf(stderr, "%sdebug[<# of symbols on state stack>]\n", YYPREFIX); #endif #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) memset(yyerror_loc_range, 0, sizeof(yyerror_loc_range)); #endif #if YYBTYACC yyps = yyNewState(0); if (yyps == 0) goto yyenomem; yyps->save = 0; #endif /* YYBTYACC */ yym = 0; yyn = 0; yynerrs = 0; yyerrflag = 0; yychar = YYEMPTY; yystate = 0; #if YYPURE memset(&yystack, 0, sizeof(yystack)); #endif if (yystack.s_base == NULL && yygrowstack(&yystack) == YYENOMEM) goto yyoverflow; yystack.s_mark = yystack.s_base; yystack.l_mark = yystack.l_base; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yystack.p_mark = yystack.p_base; #endif yystate = 0; *yystack.s_mark = 0; yyloop: if ((yyn = yydefred[yystate]) != 0) goto yyreduce; if (yychar < 0) { #if YYBTYACC do { if (yylvp < yylve) { /* we're currently re-reading tokens */ yylval = *yylvp++; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yylloc = *yylpp++; #endif yychar = *yylexp++; break; } if (yyps->save) { /* in trial mode; save scanner results for future parse attempts */ if (yylvp == yylvlim) { /* Enlarge lexical value queue */ size_t p = (size_t) (yylvp - yylvals); size_t s = (size_t) (yylvlim - yylvals); s += YYLVQUEUEGROWTH; if ((yylexemes = (YYINT *)realloc(yylexemes, s * sizeof(YYINT))) == NULL) goto yyenomem; if ((yylvals = (YYSTYPE *)realloc(yylvals, s * sizeof(YYSTYPE))) == NULL) goto yyenomem; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) if ((yylpsns = (YYLTYPE *)realloc(yylpsns, s * sizeof(YYLTYPE))) == NULL) goto yyenomem; #endif yylvp = yylve = yylvals + p; yylvlim = yylvals + s; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yylpp = yylpe = yylpsns + p; yylplim = yylpsns + s; #endif yylexp = yylexemes + p; } *yylexp = (YYINT) YYLEX; *yylvp++ = yylval; yylve++; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) *yylpp++ = yylloc; yylpe++; #endif yychar = *yylexp++; break; } /* normal operation, no conflict encountered */ #endif /* YYBTYACC */ yychar = YYLEX; #if YYBTYACC } while (0); #endif /* YYBTYACC */ if (yychar < 0) yychar = YYEOF; #if YYDEBUG if (yydebug) { if ((yys = yyname[YYTRANSLATE(yychar)]) == NULL) yys = yyname[YYUNDFTOKEN]; fprintf(stderr, "%s[%d]: state %d, reading token %d (%s)", YYDEBUGSTR, yydepth, yystate, yychar, yys); #ifdef YYSTYPE_TOSTRING #if YYBTYACC if (!yytrial) #endif /* YYBTYACC */ fprintf(stderr, " <%s>", YYSTYPE_TOSTRING(yychar, yylval)); #endif fputc('\n', stderr); } #endif } #if YYBTYACC /* Do we have a conflict? */ if (((yyn = yycindex[yystate]) != 0) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == (YYINT) yychar) { YYINT ctry; if (yypath) { YYParseState *save; #if YYDEBUG if (yydebug) fprintf(stderr, "%s[%d]: CONFLICT in state %d: following successful trial parse\n", YYDEBUGSTR, yydepth, yystate); #endif /* Switch to the next conflict context */ save = yypath; yypath = save->save; save->save = NULL; ctry = save->ctry; if (save->state != yystate) YYABORT; yyFreeState(save); } else { /* Unresolved conflict - start/continue trial parse */ YYParseState *save; #if YYDEBUG if (yydebug) { fprintf(stderr, "%s[%d]: CONFLICT in state %d. ", YYDEBUGSTR, yydepth, yystate); if (yyps->save) fputs("ALREADY in conflict, continuing trial parse.\n", stderr); else fputs("Starting trial parse.\n", stderr); } #endif save = yyNewState((unsigned)(yystack.s_mark - yystack.s_base + 1)); if (save == NULL) goto yyenomem; save->save = yyps->save; save->state = yystate; save->errflag = yyerrflag; save->yystack.s_mark = save->yystack.s_base + (yystack.s_mark - yystack.s_base); memcpy (save->yystack.s_base, yystack.s_base, (size_t) (yystack.s_mark - yystack.s_base + 1) * sizeof(YYINT)); save->yystack.l_mark = save->yystack.l_base + (yystack.l_mark - yystack.l_base); memcpy (save->yystack.l_base, yystack.l_base, (size_t) (yystack.l_mark - yystack.l_base + 1) * sizeof(YYSTYPE)); #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) save->yystack.p_mark = save->yystack.p_base + (yystack.p_mark - yystack.p_base); memcpy (save->yystack.p_base, yystack.p_base, (size_t) (yystack.p_mark - yystack.p_base + 1) * sizeof(YYLTYPE)); #endif ctry = yytable[yyn]; if (yyctable[ctry] == -1) { #if YYDEBUG if (yydebug && yychar >= YYEOF) fprintf(stderr, "%s[%d]: backtracking 1 token\n", YYDEBUGSTR, yydepth); #endif ctry++; } save->ctry = ctry; if (yyps->save == NULL) { /* If this is a first conflict in the stack, start saving lexemes */ if (!yylexemes) { yylexemes = (YYINT *) malloc((YYLVQUEUEGROWTH) * sizeof(YYINT)); if (yylexemes == NULL) goto yyenomem; yylvals = (YYSTYPE *) malloc((YYLVQUEUEGROWTH) * sizeof(YYSTYPE)); if (yylvals == NULL) goto yyenomem; yylvlim = yylvals + YYLVQUEUEGROWTH; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yylpsns = (YYLTYPE *) malloc((YYLVQUEUEGROWTH) * sizeof(YYLTYPE)); if (yylpsns == NULL) goto yyenomem; yylplim = yylpsns + YYLVQUEUEGROWTH; #endif } if (yylvp == yylve) { yylvp = yylve = yylvals; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yylpp = yylpe = yylpsns; #endif yylexp = yylexemes; if (yychar >= YYEOF) { *yylve++ = yylval; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) *yylpe++ = yylloc; #endif *yylexp = (YYINT) yychar; yychar = YYEMPTY; } } } if (yychar >= YYEOF) { yylvp--; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yylpp--; #endif yylexp--; yychar = YYEMPTY; } save->lexeme = (int) (yylvp - yylvals); yyps->save = save; } if (yytable[yyn] == ctry) { #if YYDEBUG if (yydebug) fprintf(stderr, "%s[%d]: state %d, shifting to state %d\n", YYDEBUGSTR, yydepth, yystate, yyctable[ctry]); #endif if (yychar < 0) { yylvp++; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yylpp++; #endif yylexp++; } if (yystack.s_mark >= yystack.s_last && yygrowstack(&yystack) == YYENOMEM) goto yyoverflow; yystate = yyctable[ctry]; *++yystack.s_mark = (YYINT) yystate; *++yystack.l_mark = yylval; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) *++yystack.p_mark = yylloc; #endif yychar = YYEMPTY; if (yyerrflag > 0) --yyerrflag; goto yyloop; } else { yyn = yyctable[ctry]; goto yyreduce; } } /* End of code dealing with conflicts */ #endif /* YYBTYACC */ if (((yyn = yysindex[yystate]) != 0) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == (YYINT) yychar) { #if YYDEBUG if (yydebug) fprintf(stderr, "%s[%d]: state %d, shifting to state %d\n", YYDEBUGSTR, yydepth, yystate, yytable[yyn]); #endif if (yystack.s_mark >= yystack.s_last && yygrowstack(&yystack) == YYENOMEM) goto yyoverflow; yystate = yytable[yyn]; *++yystack.s_mark = yytable[yyn]; *++yystack.l_mark = yylval; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) *++yystack.p_mark = yylloc; #endif yychar = YYEMPTY; if (yyerrflag > 0) --yyerrflag; goto yyloop; } if (((yyn = yyrindex[yystate]) != 0) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == (YYINT) yychar) { yyn = yytable[yyn]; goto yyreduce; } if (yyerrflag != 0) goto yyinrecovery; #if YYBTYACC yynewerrflag = 1; goto yyerrhandler; goto yyerrlab; /* redundant goto avoids 'unused label' warning */ yyerrlab: /* explicit YYERROR from an action -- pop the rhs of the rule reduced * before looking for error recovery */ yystack.s_mark -= yym; yystate = *yystack.s_mark; yystack.l_mark -= yym; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yystack.p_mark -= yym; #endif yynewerrflag = 0; yyerrhandler: while (yyps->save) { int ctry; YYParseState *save = yyps->save; #if YYDEBUG if (yydebug) fprintf(stderr, "%s[%d]: ERROR in state %d, CONFLICT BACKTRACKING to state %d, %d tokens\n", YYDEBUGSTR, yydepth, yystate, yyps->save->state, (int)(yylvp - yylvals - yyps->save->lexeme)); #endif /* Memorize most forward-looking error state in case it's really an error. */ if (yyerrctx == NULL || yyerrctx->lexeme < yylvp - yylvals) { /* Free old saved error context state */ if (yyerrctx) yyFreeState(yyerrctx); /* Create and fill out new saved error context state */ yyerrctx = yyNewState((unsigned)(yystack.s_mark - yystack.s_base + 1)); if (yyerrctx == NULL) goto yyenomem; yyerrctx->save = yyps->save; yyerrctx->state = yystate; yyerrctx->errflag = yyerrflag; yyerrctx->yystack.s_mark = yyerrctx->yystack.s_base + (yystack.s_mark - yystack.s_base); memcpy (yyerrctx->yystack.s_base, yystack.s_base, (size_t) (yystack.s_mark - yystack.s_base + 1) * sizeof(YYINT)); yyerrctx->yystack.l_mark = yyerrctx->yystack.l_base + (yystack.l_mark - yystack.l_base); memcpy (yyerrctx->yystack.l_base, yystack.l_base, (size_t) (yystack.l_mark - yystack.l_base + 1) * sizeof(YYSTYPE)); #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yyerrctx->yystack.p_mark = yyerrctx->yystack.p_base + (yystack.p_mark - yystack.p_base); memcpy (yyerrctx->yystack.p_base, yystack.p_base, (size_t) (yystack.p_mark - yystack.p_base + 1) * sizeof(YYLTYPE)); #endif yyerrctx->lexeme = (int) (yylvp - yylvals); } yylvp = yylvals + save->lexeme; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yylpp = yylpsns + save->lexeme; #endif yylexp = yylexemes + save->lexeme; yychar = YYEMPTY; yystack.s_mark = yystack.s_base + (save->yystack.s_mark - save->yystack.s_base); memcpy (yystack.s_base, save->yystack.s_base, (size_t) (yystack.s_mark - yystack.s_base + 1) * sizeof(YYINT)); yystack.l_mark = yystack.l_base + (save->yystack.l_mark - save->yystack.l_base); memcpy (yystack.l_base, save->yystack.l_base, (size_t) (yystack.l_mark - yystack.l_base + 1) * sizeof(YYSTYPE)); #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yystack.p_mark = yystack.p_base + (save->yystack.p_mark - save->yystack.p_base); memcpy (yystack.p_base, save->yystack.p_base, (size_t) (yystack.p_mark - yystack.p_base + 1) * sizeof(YYLTYPE)); #endif ctry = ++save->ctry; yystate = save->state; /* We tried shift, try reduce now */ if ((yyn = yyctable[ctry]) >= 0) goto yyreduce; yyps->save = save->save; save->save = NULL; yyFreeState(save); /* Nothing left on the stack -- error */ if (!yyps->save) { #if YYDEBUG if (yydebug) fprintf(stderr, "%sdebug[%d,trial]: trial parse FAILED, entering ERROR mode\n", YYPREFIX, yydepth); #endif /* Restore state as it was in the most forward-advanced error */ yylvp = yylvals + yyerrctx->lexeme; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yylpp = yylpsns + yyerrctx->lexeme; #endif yylexp = yylexemes + yyerrctx->lexeme; yychar = yylexp[-1]; yylval = yylvp[-1]; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yylloc = yylpp[-1]; #endif yystack.s_mark = yystack.s_base + (yyerrctx->yystack.s_mark - yyerrctx->yystack.s_base); memcpy (yystack.s_base, yyerrctx->yystack.s_base, (size_t) (yystack.s_mark - yystack.s_base + 1) * sizeof(YYINT)); yystack.l_mark = yystack.l_base + (yyerrctx->yystack.l_mark - yyerrctx->yystack.l_base); memcpy (yystack.l_base, yyerrctx->yystack.l_base, (size_t) (yystack.l_mark - yystack.l_base + 1) * sizeof(YYSTYPE)); #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yystack.p_mark = yystack.p_base + (yyerrctx->yystack.p_mark - yyerrctx->yystack.p_base); memcpy (yystack.p_base, yyerrctx->yystack.p_base, (size_t) (yystack.p_mark - yystack.p_base + 1) * sizeof(YYLTYPE)); #endif yystate = yyerrctx->state; yyFreeState(yyerrctx); yyerrctx = NULL; } yynewerrflag = 1; } if (yynewerrflag == 0) goto yyinrecovery; #endif /* YYBTYACC */ YYERROR_CALL("syntax error"); #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yyerror_loc_range[1] = yylloc; /* lookahead position is error start position */ #endif #if !YYBTYACC goto yyerrlab; /* redundant goto avoids 'unused label' warning */ yyerrlab: #endif ++yynerrs; yyinrecovery: if (yyerrflag < 3) { yyerrflag = 3; for (;;) { if (((yyn = yysindex[*yystack.s_mark]) != 0) && (yyn += YYERRCODE) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == (YYINT) YYERRCODE) { #if YYDEBUG if (yydebug) fprintf(stderr, "%s[%d]: state %d, error recovery shifting to state %d\n", YYDEBUGSTR, yydepth, *yystack.s_mark, yytable[yyn]); #endif if (yystack.s_mark >= yystack.s_last && yygrowstack(&yystack) == YYENOMEM) goto yyoverflow; yystate = yytable[yyn]; *++yystack.s_mark = yytable[yyn]; *++yystack.l_mark = yylval; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) /* lookahead position is error end position */ yyerror_loc_range[2] = yylloc; YYLLOC_DEFAULT(yyloc, yyerror_loc_range, 2); /* position of error span */ *++yystack.p_mark = yyloc; #endif goto yyloop; } else { #if YYDEBUG if (yydebug) fprintf(stderr, "%s[%d]: error recovery discarding state %d\n", YYDEBUGSTR, yydepth, *yystack.s_mark); #endif if (yystack.s_mark <= yystack.s_base) goto yyabort; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) /* the current TOS position is the error start position */ yyerror_loc_range[1] = *yystack.p_mark; #endif #if defined(YYDESTRUCT_CALL) #if YYBTYACC if (!yytrial) #endif /* YYBTYACC */ #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) YYDESTRUCT_CALL("error: discarding state", yystos[*yystack.s_mark], yystack.l_mark, yystack.p_mark); #else YYDESTRUCT_CALL("error: discarding state", yystos[*yystack.s_mark], yystack.l_mark); #endif /* defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) */ #endif /* defined(YYDESTRUCT_CALL) */ --yystack.s_mark; --yystack.l_mark; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) --yystack.p_mark; #endif } } } else { if (yychar == YYEOF) goto yyabort; #if YYDEBUG if (yydebug) { if ((yys = yyname[YYTRANSLATE(yychar)]) == NULL) yys = yyname[YYUNDFTOKEN]; fprintf(stderr, "%s[%d]: state %d, error recovery discarding token %d (%s)\n", YYDEBUGSTR, yydepth, yystate, yychar, yys); } #endif #if defined(YYDESTRUCT_CALL) #if YYBTYACC if (!yytrial) #endif /* YYBTYACC */ #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) YYDESTRUCT_CALL("error: discarding token", yychar, &yylval, &yylloc); #else YYDESTRUCT_CALL("error: discarding token", yychar, &yylval); #endif /* defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) */ #endif /* defined(YYDESTRUCT_CALL) */ yychar = YYEMPTY; goto yyloop; } yyreduce: yym = yylen[yyn]; #if YYDEBUG if (yydebug) { fprintf(stderr, "%s[%d]: state %d, reducing by rule %d (%s)", YYDEBUGSTR, yydepth, yystate, yyn, yyrule[yyn]); #ifdef YYSTYPE_TOSTRING #if YYBTYACC if (!yytrial) #endif /* YYBTYACC */ if (yym > 0) { int i; fputc('<', stderr); for (i = yym; i > 0; i--) { if (i != yym) fputs(", ", stderr); fputs(YYSTYPE_TOSTRING(yystos[yystack.s_mark[1-i]], yystack.l_mark[1-i]), stderr); } fputc('>', stderr); } #endif fputc('\n', stderr); } #endif if (yym > 0) yyval = yystack.l_mark[1-yym]; else memset(&yyval, 0, sizeof yyval); #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) /* Perform position reduction */ memset(&yyloc, 0, sizeof(yyloc)); #if YYBTYACC if (!yytrial) #endif /* YYBTYACC */ { YYLLOC_DEFAULT(yyloc, &yystack.p_mark[-yym], yym); /* just in case YYERROR is invoked within the action, save the start of the rhs as the error start position */ yyerror_loc_range[1] = yystack.p_mark[1-yym]; } #endif switch (yyn) { case 3: #line 35 "quote_calc4.y" { yyerrok ; } break; case 4: #line 39 "quote_calc4.y" { printf("%d\n",yystack.l_mark[0]);} break; case 5: #line 41 "quote_calc4.y" { regs[yystack.l_mark[-2]] = yystack.l_mark[0]; } break; case 6: #line 45 "quote_calc4.y" { yyval = yystack.l_mark[-1]; } break; case 7: #line 47 "quote_calc4.y" { yyval = yystack.l_mark[-2] + yystack.l_mark[0]; } break; case 8: #line 49 "quote_calc4.y" { yyval = yystack.l_mark[-2] - yystack.l_mark[0]; } break; case 9: #line 51 "quote_calc4.y" { yyval = yystack.l_mark[-2] * yystack.l_mark[0]; } break; case 10: #line 53 "quote_calc4.y" { yyval = yystack.l_mark[-2] / yystack.l_mark[0]; } break; case 11: #line 55 "quote_calc4.y" { yyval = yystack.l_mark[-2] % yystack.l_mark[0]; } break; case 12: #line 57 "quote_calc4.y" { yyval = yystack.l_mark[-2] & yystack.l_mark[0]; } break; case 13: #line 59 "quote_calc4.y" { yyval = yystack.l_mark[-2] | yystack.l_mark[0]; } break; case 14: #line 61 "quote_calc4.y" { yyval = - yystack.l_mark[0]; } break; case 15: #line 63 "quote_calc4.y" { yyval = regs[yystack.l_mark[0]]; } break; case 17: #line 68 "quote_calc4.y" { yyval = yystack.l_mark[0]; base = (yystack.l_mark[0]==0) ? 8 : 10; } break; case 18: #line 70 "quote_calc4.y" { yyval = base * yystack.l_mark[-1] + yystack.l_mark[0]; } break; #line 1260 "quote_calc4.tab.c" default: break; } yystack.s_mark -= yym; yystate = *yystack.s_mark; yystack.l_mark -= yym; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yystack.p_mark -= yym; #endif yym = yylhs[yyn]; if (yystate == 0 && yym == 0) { #if YYDEBUG if (yydebug) { fprintf(stderr, "%s[%d]: after reduction, ", YYDEBUGSTR, yydepth); #ifdef YYSTYPE_TOSTRING #if YYBTYACC if (!yytrial) #endif /* YYBTYACC */ fprintf(stderr, "result is <%s>, ", YYSTYPE_TOSTRING(yystos[YYFINAL], yyval)); #endif fprintf(stderr, "shifting from state 0 to final state %d\n", YYFINAL); } #endif yystate = YYFINAL; *++yystack.s_mark = YYFINAL; *++yystack.l_mark = yyval; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) *++yystack.p_mark = yyloc; #endif if (yychar < 0) { #if YYBTYACC do { if (yylvp < yylve) { /* we're currently re-reading tokens */ yylval = *yylvp++; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yylloc = *yylpp++; #endif yychar = *yylexp++; break; } if (yyps->save) { /* in trial mode; save scanner results for future parse attempts */ if (yylvp == yylvlim) { /* Enlarge lexical value queue */ size_t p = (size_t) (yylvp - yylvals); size_t s = (size_t) (yylvlim - yylvals); s += YYLVQUEUEGROWTH; if ((yylexemes = (YYINT *)realloc(yylexemes, s * sizeof(YYINT))) == NULL) goto yyenomem; if ((yylvals = (YYSTYPE *)realloc(yylvals, s * sizeof(YYSTYPE))) == NULL) goto yyenomem; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) if ((yylpsns = (YYLTYPE *)realloc(yylpsns, s * sizeof(YYLTYPE))) == NULL) goto yyenomem; #endif yylvp = yylve = yylvals + p; yylvlim = yylvals + s; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yylpp = yylpe = yylpsns + p; yylplim = yylpsns + s; #endif yylexp = yylexemes + p; } *yylexp = (YYINT) YYLEX; *yylvp++ = yylval; yylve++; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) *yylpp++ = yylloc; yylpe++; #endif yychar = *yylexp++; break; } /* normal operation, no conflict encountered */ #endif /* YYBTYACC */ yychar = YYLEX; #if YYBTYACC } while (0); #endif /* YYBTYACC */ if (yychar < 0) yychar = YYEOF; #if YYDEBUG if (yydebug) { if ((yys = yyname[YYTRANSLATE(yychar)]) == NULL) yys = yyname[YYUNDFTOKEN]; fprintf(stderr, "%s[%d]: state %d, reading token %d (%s)\n", YYDEBUGSTR, yydepth, YYFINAL, yychar, yys); } #endif } if (yychar == YYEOF) goto yyaccept; goto yyloop; } if (((yyn = yygindex[yym]) != 0) && (yyn += yystate) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == (YYINT) yystate) yystate = yytable[yyn]; else yystate = yydgoto[yym]; #if YYDEBUG if (yydebug) { fprintf(stderr, "%s[%d]: after reduction, ", YYDEBUGSTR, yydepth); #ifdef YYSTYPE_TOSTRING #if YYBTYACC if (!yytrial) #endif /* YYBTYACC */ fprintf(stderr, "result is <%s>, ", YYSTYPE_TOSTRING(yystos[yystate], yyval)); #endif fprintf(stderr, "shifting from state %d to state %d\n", *yystack.s_mark, yystate); } #endif if (yystack.s_mark >= yystack.s_last && yygrowstack(&yystack) == YYENOMEM) goto yyoverflow; *++yystack.s_mark = (YYINT) yystate; *++yystack.l_mark = yyval; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) *++yystack.p_mark = yyloc; #endif goto yyloop; #if YYBTYACC /* Reduction declares that this path is valid. Set yypath and do a full parse */ yyvalid: if (yypath) YYABORT; while (yyps->save) { YYParseState *save = yyps->save; yyps->save = save->save; save->save = yypath; yypath = save; } #if YYDEBUG if (yydebug) fprintf(stderr, "%s[%d]: state %d, CONFLICT trial successful, backtracking to state %d, %d tokens\n", YYDEBUGSTR, yydepth, yystate, yypath->state, (int)(yylvp - yylvals - yypath->lexeme)); #endif if (yyerrctx) { yyFreeState(yyerrctx); yyerrctx = NULL; } yylvp = yylvals + yypath->lexeme; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yylpp = yylpsns + yypath->lexeme; #endif yylexp = yylexemes + yypath->lexeme; yychar = YYEMPTY; yystack.s_mark = yystack.s_base + (yypath->yystack.s_mark - yypath->yystack.s_base); memcpy (yystack.s_base, yypath->yystack.s_base, (size_t) (yystack.s_mark - yystack.s_base + 1) * sizeof(YYINT)); yystack.l_mark = yystack.l_base + (yypath->yystack.l_mark - yypath->yystack.l_base); memcpy (yystack.l_base, yypath->yystack.l_base, (size_t) (yystack.l_mark - yystack.l_base + 1) * sizeof(YYSTYPE)); #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) yystack.p_mark = yystack.p_base + (yypath->yystack.p_mark - yypath->yystack.p_base); memcpy (yystack.p_base, yypath->yystack.p_base, (size_t) (yystack.p_mark - yystack.p_base + 1) * sizeof(YYLTYPE)); #endif yystate = yypath->state; goto yyloop; #endif /* YYBTYACC */ yyoverflow: YYERROR_CALL("yacc stack overflow"); #if YYBTYACC goto yyabort_nomem; yyenomem: YYERROR_CALL("memory exhausted"); yyabort_nomem: #endif /* YYBTYACC */ yyresult = 2; goto yyreturn; yyabort: yyresult = 1; goto yyreturn; yyaccept: #if YYBTYACC if (yyps->save) goto yyvalid; #endif /* YYBTYACC */ yyresult = 0; yyreturn: #if defined(YYDESTRUCT_CALL) if (yychar != YYEOF && yychar != YYEMPTY) #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) YYDESTRUCT_CALL("cleanup: discarding token", yychar, &yylval, &yylloc); #else YYDESTRUCT_CALL("cleanup: discarding token", yychar, &yylval); #endif /* defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) */ { YYSTYPE *pv; #if defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) YYLTYPE *pp; for (pv = yystack.l_base, pp = yystack.p_base; pv <= yystack.l_mark; ++pv, ++pp) YYDESTRUCT_CALL("cleanup: discarding state", yystos[*(yystack.s_base + (pv - yystack.l_base))], pv, pp); #else for (pv = yystack.l_base; pv <= yystack.l_mark; ++pv) YYDESTRUCT_CALL("cleanup: discarding state", yystos[*(yystack.s_base + (pv - yystack.l_base))], pv); #endif /* defined(YYLTYPE) || defined(YYLTYPE_IS_DECLARED) */ } #endif /* defined(YYDESTRUCT_CALL) */ #if YYBTYACC if (yyerrctx) { yyFreeState(yyerrctx); yyerrctx = NULL; } while (yyps) { YYParseState *save = yyps; yyps = save->save; save->save = NULL; yyFreeState(save); } while (yypath) { YYParseState *save = yypath; yypath = save->save; save->save = NULL; yyFreeState(save); } #endif /* YYBTYACC */ yyfreestack(&yystack); return (yyresult); }
the_stack_data/122395.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); void __VERIFIER_assert(int expression) { if (!expression) { ERROR: /* assert not proved */ /* assert not proved */ __VERIFIER_error(); }; return; } int __global_lock; void __VERIFIER_atomic_begin() { /* reachable */ /* reachable */ /* reachable */ /* reachable */ /* reachable */ __VERIFIER_assume(__global_lock==0); __global_lock=1; return; } void __VERIFIER_atomic_end() { __VERIFIER_assume(__global_lock==1); __global_lock=0; return; } #include <assert.h> #include <pthread.h> #ifndef TRUE #define TRUE (_Bool)1 #endif #ifndef FALSE #define FALSE (_Bool)0 #endif #ifndef NULL #define NULL ((void*)0) #endif #ifndef FENCE #define FENCE(x) ((void)0) #endif #ifndef IEEE_FLOAT_EQUAL #define IEEE_FLOAT_EQUAL(x,y) (x==y) #endif #ifndef IEEE_FLOAT_NOTEQUAL #define IEEE_FLOAT_NOTEQUAL(x,y) (x!=y) #endif void * P0(void *arg); void * P1(void *arg); void fence(); void isync(); void lwfence(); int __unbuffered_cnt; int __unbuffered_cnt = 0; int __unbuffered_p1_EAX; int __unbuffered_p1_EAX = 0; int __unbuffered_p1_EBX; int __unbuffered_p1_EBX = 0; _Bool main$tmp_guard0; _Bool main$tmp_guard1; int x; int x = 0; _Bool x$flush_delayed; int x$mem_tmp; _Bool x$r_buff0_thd0; _Bool x$r_buff0_thd1; _Bool x$r_buff0_thd2; _Bool x$r_buff1_thd0; _Bool x$r_buff1_thd1; _Bool x$r_buff1_thd2; _Bool x$read_delayed; int *x$read_delayed_var; int x$w_buff0; _Bool x$w_buff0_used; int x$w_buff1; _Bool x$w_buff1_used; int y; int y = 0; int z; int z = 0; _Bool weak$$choice0; _Bool weak$$choice2; void * P0(void *arg) { __VERIFIER_atomic_begin(); z = 1; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); x = 1; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); x = x$w_buff0_used && x$r_buff0_thd1 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd1 ? x$w_buff1 : x); x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd1 ? FALSE : x$w_buff0_used; x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd1 || x$w_buff1_used && x$r_buff1_thd1 ? FALSE : x$w_buff1_used; x$r_buff0_thd1 = x$w_buff0_used && x$r_buff0_thd1 ? FALSE : x$r_buff0_thd1; x$r_buff1_thd1 = x$w_buff0_used && x$r_buff0_thd1 || x$w_buff1_used && x$r_buff1_thd1 ? FALSE : x$r_buff1_thd1; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __unbuffered_cnt = __unbuffered_cnt + 1; __VERIFIER_atomic_end(); return nondet_0(); } void * P1(void *arg) { __VERIFIER_atomic_begin(); x$w_buff1 = x$w_buff0; x$w_buff0 = 2; x$w_buff1_used = x$w_buff0_used; x$w_buff0_used = TRUE; __VERIFIER_assert(!(x$w_buff1_used && x$w_buff0_used)); x$r_buff1_thd0 = x$r_buff0_thd0; x$r_buff1_thd1 = x$r_buff0_thd1; x$r_buff1_thd2 = x$r_buff0_thd2; x$r_buff0_thd2 = TRUE; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); y = 1; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __unbuffered_p1_EAX = y; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __unbuffered_p1_EBX = z; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); x = x$w_buff0_used && x$r_buff0_thd2 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd2 ? x$w_buff1 : x); x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd2 ? FALSE : x$w_buff0_used; x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd2 || x$w_buff1_used && x$r_buff1_thd2 ? FALSE : x$w_buff1_used; x$r_buff0_thd2 = x$w_buff0_used && x$r_buff0_thd2 ? FALSE : x$r_buff0_thd2; x$r_buff1_thd2 = x$w_buff0_used && x$r_buff0_thd2 || x$w_buff1_used && x$r_buff1_thd2 ? FALSE : x$r_buff1_thd2; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __unbuffered_cnt = __unbuffered_cnt + 1; __VERIFIER_atomic_end(); return nondet_0(); } void fence() { } void isync() { } void lwfence() { } int main() { pthread_create(NULL, NULL, P0, NULL); pthread_create(NULL, NULL, P1, NULL); __VERIFIER_atomic_begin(); main$tmp_guard0 = __unbuffered_cnt == 2; __VERIFIER_atomic_end(); __VERIFIER_assume(main$tmp_guard0); __VERIFIER_atomic_begin(); x = x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd0 ? x$w_buff1 : x); x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$w_buff0_used; x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd0 || x$w_buff1_used && x$r_buff1_thd0 ? FALSE : x$w_buff1_used; x$r_buff0_thd0 = x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$r_buff0_thd0; x$r_buff1_thd0 = x$w_buff0_used && x$r_buff0_thd0 || x$w_buff1_used && x$r_buff1_thd0 ? FALSE : x$r_buff1_thd0; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); /* Program proven to be relaxed for X86, model checker says YES. */ weak$$choice0 = nondet_1(); /* Program proven to be relaxed for X86, model checker says YES. */ weak$$choice2 = nondet_1(); /* Program proven to be relaxed for X86, model checker says YES. */ x$flush_delayed = weak$$choice2; /* Program proven to be relaxed for X86, model checker says YES. */ x$mem_tmp = x; /* Program proven to be relaxed for X86, model checker says YES. */ x = !x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : x$w_buff1); /* Program proven to be relaxed for X86, model checker says YES. */ x$w_buff0 = weak$$choice2 ? x$w_buff0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff0 : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : x$w_buff0)); /* Program proven to be relaxed for X86, model checker says YES. */ x$w_buff1 = weak$$choice2 ? x$w_buff1 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff1 : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff1 : x$w_buff1)); /* Program proven to be relaxed for X86, model checker says YES. */ x$w_buff0_used = weak$$choice2 ? x$w_buff0_used : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff0_used : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$w_buff0_used)); /* Program proven to be relaxed for X86, model checker says YES. */ x$w_buff1_used = weak$$choice2 ? x$w_buff1_used : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff1_used : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : FALSE)); /* Program proven to be relaxed for X86, model checker says YES. */ x$r_buff0_thd0 = weak$$choice2 ? x$r_buff0_thd0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$r_buff0_thd0 : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$r_buff0_thd0)); /* Program proven to be relaxed for X86, model checker says YES. */ x$r_buff1_thd0 = weak$$choice2 ? x$r_buff1_thd0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$r_buff1_thd0 : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : FALSE)); /* Program proven to be relaxed for X86, model checker says YES. */ main$tmp_guard1 = !(x == 2 && __unbuffered_p1_EAX == 1 && __unbuffered_p1_EBX == 0); /* Program proven to be relaxed for X86, model checker says YES. */ x = x$flush_delayed ? x$mem_tmp : x; /* Program proven to be relaxed for X86, model checker says YES. */ x$flush_delayed = FALSE; __VERIFIER_atomic_end(); /* Program proven to be relaxed for X86, model checker says YES. */ __VERIFIER_assert(main$tmp_guard1); /* reachable */ return 0; }
the_stack_data/48575588.c
// RUN: %llvmgcc -c -emit-llvm %s -o - | \ // RUN: opt -std-compile-opts | llvm-dis | not grep {declare i32.*func} // There should not be an unresolved reference to func here. Believe it or not, // the "expected result" is a function named 'func' which is internal and // referenced by bar(). // This is PR244 static int func(); void bar() { int func(); foo(func); } static int func(char** A, char ** B) {}
the_stack_data/828205.c
#include <stdio.h> #include <omp.h> int main() { int i,n=10; #pragma omp parallel shared(n) private(i) { #pragma omp for for(i=0;i<10;i++) { printf("Thread %d executes iteration %d\n",omp_get_thread_num(),i); } } printf("\n"); return 0; }
the_stack_data/615294.c
#include <stdio.h> int main() { int n, rem=0, sum =0; scanf("%d", &n); rem = n%5; if(rem>=1&& rem<=4) rem= 1; n /= 5; sum = rem + n; printf("%d", sum); }
the_stack_data/35768.c
/* ** Compile and run this standalone program in order to generate code that ** implements a function that will translate alphabetic identifiers into ** parser token codes. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <stdbool.h> /* ** A header comment placed at the beginning of generated code. */ static const char zHdr[] = "/***** This file contains automatically generated code ******\n" "**\n" "** The code in this file has been automatically generated by\n" "**\n" "** sqlite/tool/mkkeywordhash.c\n" "**\n" "** The code in this file implements a function that determines whether\n" "** or not a given identifier is really an SQL keyword. The same thing\n" "** might be implemented more directly using a hand-written hash table.\n" "** But by using this automatically generated code, the size of the code\n" "** is substantially reduced. This is important for embedded applications\n" "** on platforms with limited memory.\n" "*/\n" ; /* ** All the keywords of the SQL language are stored in a hash ** table composed of instances of the following structure. */ typedef struct Keyword Keyword; struct Keyword { char *zName; /* The keyword name */ char *zTokenType; /* Token value for this keyword */ int mask; /* Code this keyword if non-zero */ bool isReserved; /* Is this word reserved by SQL standard */ int id; /* Unique ID for this record */ int hash; /* Hash on the keyword */ int offset; /* Offset to start of name string */ int len; /* Length of this keyword, not counting final \000 */ int prefix; /* Number of characters in prefix */ int longestSuffix; /* Longest suffix that is a prefix on another word */ int iNext; /* Index in aKeywordTable[] of next with same hash */ int substrId; /* Id to another keyword this keyword is embedded in */ int substrOffset; /* Offset into substrId for start of this keyword */ char zOrigName[50]; /* Original keyword name before processing */ }; /* ** Define masks used to determine which keywords are allowed */ #define ALTER 0x00000001 #define ALWAYS 0x00000002 #ifdef SQLITE_OMIT_AUTOINCREMENT # define AUTOINCR 0 #else # define AUTOINCR 0x00000010 #endif #ifdef SQLITE_OMIT_CAST # define CAST 0 #else # define CAST 0x00000020 #endif #ifdef SQLITE_OMIT_COMPOUND_SELECT # define COMPOUND 0 #else # define COMPOUND 0x00000040 #endif #ifdef SQLITE_OMIT_CONFLICT_CLAUSE # define CONFLICT 0 #else # define CONFLICT 0x00000080 #endif #define EXPLAIN 0x00000100 #define FKEY 0x00000200 #ifdef SQLITE_OMIT_PRAGMA # define PRAGMA 0 #else # define PRAGMA 0x00000400 #endif #define SUBQUERY 0x00001000 # define TRIGGER 0x00002000 # define VIEW 0x00008000 #ifdef SQLITE_OMIT_CTE # define CTE 0 #else # define CTE 0x00040000 #endif # define RESERVED 0x00000001 /* ** These are the keywords */ static Keyword aKeywordTable[] = { { "ABORT", "TK_ABORT", CONFLICT|TRIGGER, false }, { "ACTION", "TK_ACTION", FKEY, false }, { "ADD", "TK_ADD", ALTER, false }, { "AFTER", "TK_AFTER", TRIGGER, false }, { "ALL", "TK_ALL", ALWAYS, true }, { "ALTER", "TK_ALTER", ALTER, true }, { "ANALYZE", "TK_ANALYZE", ALWAYS, true }, { "AND", "TK_AND", ALWAYS, true }, { "AS", "TK_AS", ALWAYS, true }, { "ASC", "TK_ASC", ALWAYS, true }, { "AUTOINCREMENT", "TK_AUTOINCR", AUTOINCR, false }, { "BEFORE", "TK_BEFORE", TRIGGER, false }, { "BEGIN", "TK_BEGIN", TRIGGER, true }, { "BETWEEN", "TK_BETWEEN", ALWAYS, true }, { "BY", "TK_BY", ALWAYS, true }, { "CASCADE", "TK_CASCADE", FKEY, false }, { "CASE", "TK_CASE", ALWAYS, true }, { "CAST", "TK_CAST", CAST, false }, { "CHECK", "TK_CHECK", ALWAYS, true }, { "COLLATE", "TK_COLLATE", ALWAYS, true }, /* gh-3075: Reserved until ALTER ADD COLUMN is implemeneted. * Move it back to ALTER when done. */ /* { "COLUMN", "TK_COLUMNKW", ALTER, true }, */ { "COLUMN", "TK_STANDARD", RESERVED, true }, { "COMMIT", "TK_COMMIT", ALWAYS, true }, { "CONFLICT", "TK_CONFLICT", CONFLICT, false }, { "CONSTRAINT", "TK_CONSTRAINT", ALWAYS, true }, { "CREATE", "TK_CREATE", ALWAYS, true }, { "CROSS", "TK_JOIN_KW", ALWAYS, true }, { "CURRENT_DATE", "TK_CTIME_KW", ALWAYS, true }, { "CURRENT_TIME", "TK_CTIME_KW", ALWAYS, true }, { "CURRENT_TIMESTAMP", "TK_CTIME_KW", ALWAYS, true }, { "DEFAULT", "TK_DEFAULT", ALWAYS, true }, { "DEFERRED", "TK_DEFERRED", ALWAYS, false }, { "DEFERRABLE", "TK_DEFERRABLE", FKEY, false }, { "DELETE", "TK_DELETE", ALWAYS, true }, { "DESC", "TK_DESC", ALWAYS, true }, { "DISTINCT", "TK_DISTINCT", ALWAYS, true }, { "DROP", "TK_DROP", ALWAYS, true }, { "END", "TK_END", ALWAYS, true }, { "EACH", "TK_EACH", TRIGGER, true }, { "ELSE", "TK_ELSE", ALWAYS, true }, { "ESCAPE", "TK_ESCAPE", ALWAYS, true }, { "EXCEPT", "TK_EXCEPT", COMPOUND, true }, { "EXISTS", "TK_EXISTS", ALWAYS, true }, { "EXPLAIN", "TK_EXPLAIN", EXPLAIN, true }, { "FAIL", "TK_FAIL", CONFLICT|TRIGGER, false }, { "FOR", "TK_FOR", TRIGGER, true }, { "FOREIGN", "TK_FOREIGN", FKEY, true }, { "FROM", "TK_FROM", ALWAYS, true }, { "FULL", "TK_FULL", ALWAYS, true }, { "GLOB", "TK_LIKE_KW", ALWAYS, false }, { "GROUP", "TK_GROUP", ALWAYS, true }, { "HAVING", "TK_HAVING", ALWAYS, true }, { "IF", "TK_IF", ALWAYS, true }, { "IGNORE", "TK_IGNORE", CONFLICT|TRIGGER, false }, { "IMMEDIATE", "TK_IMMEDIATE", ALWAYS, true }, { "IN", "TK_IN", ALWAYS, true }, { "INDEX", "TK_INDEX", ALWAYS, true }, { "INDEXED", "TK_INDEXED", ALWAYS, false }, { "INITIALLY", "TK_INITIALLY", FKEY, false }, { "INNER", "TK_JOIN_KW", ALWAYS, true }, { "INSERT", "TK_INSERT", ALWAYS, true }, { "INSTEAD", "TK_INSTEAD", TRIGGER, false }, { "INTERSECT", "TK_INTERSECT", COMPOUND, true }, { "INTO", "TK_INTO", ALWAYS, true }, { "IS", "TK_IS", ALWAYS, true }, { "JOIN", "TK_JOIN", ALWAYS, true }, { "KEY", "TK_KEY", ALWAYS, false }, { "LEFT", "TK_JOIN_KW", ALWAYS, true }, { "LIKE", "TK_LIKE_KW", ALWAYS, true }, { "LIMIT", "TK_LIMIT", ALWAYS, false }, { "MATCH", "TK_MATCH", ALWAYS, true }, { "NATURAL", "TK_JOIN_KW", ALWAYS, true }, { "NO", "TK_NO", FKEY, false }, { "NOT", "TK_NOT", ALWAYS, true }, { "NULL", "TK_NULL", ALWAYS, true }, { "OF", "TK_OF", ALWAYS, true }, { "OFFSET", "TK_OFFSET", ALWAYS, false }, { "ON", "TK_ON", ALWAYS, true }, { "OR", "TK_OR", ALWAYS, true }, { "ORDER", "TK_ORDER", ALWAYS, true }, { "OUTER", "TK_JOIN_KW", ALWAYS, true }, { "PARTIAL", "TK_PARTIAL", ALWAYS, true }, { "PLAN", "TK_PLAN", EXPLAIN, false }, { "PRAGMA", "TK_PRAGMA", PRAGMA, true }, { "PRIMARY", "TK_PRIMARY", ALWAYS, true }, { "QUERY", "TK_QUERY", EXPLAIN, false }, { "RAISE", "TK_RAISE", TRIGGER, false }, { "RECURSIVE", "TK_RECURSIVE", CTE, true }, { "REFERENCES", "TK_REFERENCES", FKEY, true }, { "REGEXP", "TK_LIKE_KW", ALWAYS, false }, { "RELEASE", "TK_RELEASE", ALWAYS, true }, { "RENAME", "TK_RENAME", ALTER, true }, { "REPLACE", "TK_REPLACE", CONFLICT, true }, { "RESTRICT", "TK_RESTRICT", FKEY, false }, { "RIGHT", "TK_JOIN_KW", ALWAYS, true }, { "ROLLBACK", "TK_ROLLBACK", ALWAYS, true }, { "ROW", "TK_ROW", TRIGGER, true }, { "SAVEPOINT", "TK_SAVEPOINT", ALWAYS, true }, { "SELECT", "TK_SELECT", ALWAYS, true }, { "SET", "TK_SET", ALWAYS, true }, { "SIMPLE", "TK_SIMPLE", ALWAYS, true }, { "START", "TK_START", ALWAYS, true }, { "TABLE", "TK_TABLE", ALWAYS, true }, { "THEN", "TK_THEN", ALWAYS, true }, { "TO", "TK_TO", ALWAYS, true }, { "TRANSACTION", "TK_TRANSACTION", ALWAYS, true }, { "TRIGGER", "TK_TRIGGER", TRIGGER, true }, { "UNION", "TK_UNION", COMPOUND, true }, { "UNIQUE", "TK_UNIQUE", ALWAYS, true }, { "UPDATE", "TK_UPDATE", ALWAYS, true }, { "USING", "TK_USING", ALWAYS, true }, { "VALUES", "TK_VALUES", ALWAYS, true }, { "VIEW", "TK_VIEW", VIEW, true }, { "WITH", "TK_WITH", CTE, true }, { "WHEN", "TK_WHEN", ALWAYS, true }, { "WHERE", "TK_WHERE", ALWAYS, true }, { "ANY", "TK_STANDARD", RESERVED, true }, { "ASENSITIVE", "TK_STANDARD", RESERVED, true }, { "BINARY", "TK_ID", RESERVED, true }, { "CALL", "TK_STANDARD", RESERVED, true }, { "CHAR", "TK_ID", RESERVED, true }, { "CHARACTER", "TK_ID", RESERVED, true }, { "CONDITION", "TK_STANDARD", RESERVED, true }, { "CONNECT", "TK_STANDARD", RESERVED, true }, { "CURRENT", "TK_STANDARD", RESERVED, true }, { "CURRENT_USER", "TK_STANDARD", RESERVED, true }, { "CURSOR", "TK_STANDARD", RESERVED, true }, { "DATE", "TK_ID", RESERVED, true }, { "DECIMAL", "TK_ID", RESERVED, true }, { "DECLARE", "TK_STANDARD", RESERVED, true }, { "DENSE_RANK", "TK_STANDARD", RESERVED, true }, { "DESCRIBE", "TK_STANDARD", RESERVED, true }, { "DETERMINISTIC", "TK_STANDARD", RESERVED, true }, { "DOUBLE", "TK_ID", RESERVED, true }, { "ELSEIF", "TK_STANDARD", RESERVED, true }, { "FETCH", "TK_STANDARD", RESERVED, true }, { "FLOAT", "TK_ID", RESERVED, true }, { "FUNCTION", "TK_STANDARD", RESERVED, true }, { "GET", "TK_STANDARD", RESERVED, true }, { "GRANT", "TK_STANDARD", RESERVED, true }, { "INTEGER", "TK_ID", RESERVED, true }, { "INOUT", "TK_STANDARD", RESERVED, true }, { "INSENSITIVE", "TK_STANDARD", RESERVED, true }, { "ITERATE", "TK_STANDARD", RESERVED, true }, { "LEAVE", "TK_STANDARD", RESERVED, true }, { "LOCALTIME", "TK_STANDARD", RESERVED, true }, { "LOCALTIMESTAMP", "TK_STANDARD", RESERVED, true }, { "LOOP", "TK_STANDARD", RESERVED, true }, { "OUT", "TK_STANDARD", RESERVED, true }, { "OVER", "TK_STANDARD", RESERVED, true }, { "PARTITION", "TK_STANDARD", RESERVED, true }, { "PRECISION", "TK_STANDARD", RESERVED, true }, { "PROCEDURE", "TK_STANDARD", RESERVED, true }, { "RANGE", "TK_STANDARD", RESERVED, true }, { "RANK", "TK_STANDARD", RESERVED, true }, { "READS", "TK_STANDARD", RESERVED, true }, { "REPEAT", "TK_STANDARD", RESERVED, true }, { "RESIGNAL", "TK_STANDARD", RESERVED, true }, { "RETURN", "TK_STANDARD", RESERVED, true }, { "REVOKE", "TK_STANDARD", RESERVED, true }, { "ROWS", "TK_STANDARD", RESERVED, true }, { "ROW_NUMBER", "TK_STANDARD", RESERVED, true }, { "SENSITIVE", "TK_STANDARD", RESERVED, true }, { "SIGNAL", "TK_STANDARD", RESERVED, true }, { "SMALLINT", "TK_ID", RESERVED, true }, { "SPECIFIC", "TK_STANDARD", RESERVED, true }, { "SYSTEM", "TK_STANDARD", RESERVED, true }, { "SQL", "TK_STANDARD", RESERVED, true }, { "USER", "TK_STANDARD", RESERVED, true }, { "VARCHAR", "TK_ID", RESERVED, true }, { "WHENEVER", "TK_STANDARD", RESERVED, true }, { "WHILE", "TK_STANDARD", RESERVED, true }, { "TRUNCATE", "TK_TRUNCATE", ALWAYS, true }, }; /* Number of keywords */ static int nKeyword = (sizeof(aKeywordTable)/sizeof(aKeywordTable[0])); /* Map all alphabetic characters into lower-case for hashing. This is ** only valid for alphabetics. In particular it does not work for '_' ** and so the hash cannot be on a keyword position that might be an '_'. */ #define charMap(X) (0x20|(X)) /* ** Comparision function for two Keyword records */ static int keywordCompare1(const void *a, const void *b){ const Keyword *pA = (Keyword*)a; const Keyword *pB = (Keyword*)b; int n = pA->len - pB->len; if( n==0 ){ n = strcmp(pA->zName, pB->zName); } assert( n!=0 ); return n; } static int keywordCompare2(const void *a, const void *b){ const Keyword *pA = (Keyword*)a; const Keyword *pB = (Keyword*)b; int n = pB->longestSuffix - pA->longestSuffix; if( n==0 ){ n = strcmp(pA->zName, pB->zName); } assert( n!=0 ); return n; } static int keywordCompare3(const void *a, const void *b){ const Keyword *pA = (Keyword*)a; const Keyword *pB = (Keyword*)b; int n = pA->offset - pB->offset; if( n==0 ) n = pB->id - pA->id; assert( n!=0 ); return n; } /* ** Return a KeywordTable entry with the given id */ static Keyword *findById(int id){ int i; for(i=0; i<nKeyword; i++){ if( aKeywordTable[i].id==id ) break; } return &aKeywordTable[i]; } /* ** This routine does the work. The generated code is printed on standard ** output. */ int main(int argc, char **argv){ int i, j, k, h; int bestSize, bestCount; int count; int nChar; int totalLen = 0; int aHash[1000]; /* 1000 is much bigger than nKeyword */ char zText[2000]; /* Remove entries from the list of keywords that have mask==0 */ for(i=j=0; i<nKeyword; i++){ if( aKeywordTable[i].mask==0 ) continue; if( j<i ){ aKeywordTable[j] = aKeywordTable[i]; } j++; } nKeyword = j; /* Fill in the lengths of strings and hashes for all entries. */ for(i=0; i<nKeyword; i++){ Keyword *p = &aKeywordTable[i]; p->len = (int)strlen(p->zName); assert( p->len<sizeof(p->zOrigName) ); memcpy(p->zOrigName, p->zName, p->len+1); totalLen += p->len; p->hash = (charMap(p->zName[0])*4) ^ (charMap(p->zName[p->len-1])*3) ^ (p->len*1); p->id = i+1; } /* Sort the table from shortest to longest keyword */ qsort(aKeywordTable, nKeyword, sizeof(aKeywordTable[0]), keywordCompare1); /* Look for short keywords embedded in longer keywords */ for(i=nKeyword-2; i>=0; i--){ Keyword *p = &aKeywordTable[i]; for(j=nKeyword-1; j>i && p->substrId==0; j--){ Keyword *pOther = &aKeywordTable[j]; if( pOther->substrId ) continue; if( pOther->len<=p->len ) continue; for(k=0; k<=pOther->len-p->len; k++){ if( memcmp(p->zName, &pOther->zName[k], p->len)==0 ){ p->substrId = pOther->id; p->substrOffset = k; break; } } } } /* Compute the longestSuffix value for every word */ for(i=0; i<nKeyword; i++){ Keyword *p = &aKeywordTable[i]; if( p->substrId ) continue; for(j=0; j<nKeyword; j++){ Keyword *pOther; if( j==i ) continue; pOther = &aKeywordTable[j]; if( pOther->substrId ) continue; for(k=p->longestSuffix+1; k<p->len && k<pOther->len; k++){ if( memcmp(&p->zName[p->len-k], pOther->zName, k)==0 ){ p->longestSuffix = k; } } } } /* Sort the table into reverse order by length */ qsort(aKeywordTable, nKeyword, sizeof(aKeywordTable[0]), keywordCompare2); /* Fill in the offset for all entries */ nChar = 0; for(i=0; i<nKeyword; i++){ Keyword *p = &aKeywordTable[i]; if( p->offset>0 || p->substrId ) continue; p->offset = nChar; nChar += p->len; for(k=p->len-1; k>=1; k--){ for(j=i+1; j<nKeyword; j++){ Keyword *pOther = &aKeywordTable[j]; if( pOther->offset>0 || pOther->substrId ) continue; if( pOther->len<=k ) continue; if( memcmp(&p->zName[p->len-k], pOther->zName, k)==0 ){ p = pOther; p->offset = nChar - k; nChar = p->offset + p->len; p->zName += k; p->len -= k; p->prefix = k; j = i; k = p->len; } } } } for(i=0; i<nKeyword; i++){ Keyword *p = &aKeywordTable[i]; if( p->substrId ){ p->offset = findById(p->substrId)->offset + p->substrOffset; } } /* Sort the table by offset */ qsort(aKeywordTable, nKeyword, sizeof(aKeywordTable[0]), keywordCompare3); /* Figure out how big to make the hash table in order to minimize the ** number of collisions */ bestSize = nKeyword; bestCount = nKeyword*nKeyword; for(i=nKeyword/2; i<=2*nKeyword; i++){ for(j=0; j<i; j++) aHash[j] = 0; for(j=0; j<nKeyword; j++){ h = aKeywordTable[j].hash % i; aHash[h] *= 2; aHash[h]++; } for(j=count=0; j<i; j++) count += aHash[j]; if( count<bestCount ){ bestCount = count; bestSize = i; } } /* Compute the hash */ for(i=0; i<bestSize; i++) aHash[i] = 0; for(i=0; i<nKeyword; i++){ h = aKeywordTable[i].hash % bestSize; aKeywordTable[i].iNext = aHash[h]; aHash[h] = i+1; } /* Begin generating code */ printf("%s", zHdr); printf("/* Hash score: %d */\n", bestCount); printf("static int keywordCode(const char *z, int n, int *pType, " "bool *pFlag){\n"); printf(" /* zText[] encodes %d bytes of keywords in %d bytes */\n", totalLen + nKeyword, nChar+1 ); for(i=j=k=0; i<nKeyword; i++){ Keyword *p = &aKeywordTable[i]; if( p->substrId ) continue; memcpy(&zText[k], p->zName, p->len); k += p->len; if( j+p->len>70 ){ printf("%*s */\n", 74-j, ""); j = 0; } if( j==0 ){ printf(" /* "); j = 8; } printf("%s", p->zName); j += p->len; } if( j>0 ){ printf("%*s */\n", 74-j, ""); } printf(" static const char zText[%d] = {\n", nChar); zText[nChar] = 0; for(i=j=0; i<k; i++){ if( j==0 ){ printf(" "); } if( zText[i]==0 ){ printf("0"); }else{ printf("'%c',", zText[i]); } j += 4; if( j>68 ){ printf("\n"); j = 0; } } if( j>0 ) printf("\n"); printf(" };\n"); printf(" static const unsigned short aHash[%d] = {\n", bestSize); for(i=j=0; i<bestSize; i++){ if( j==0 ) printf(" "); printf(" %3d,", aHash[i]); j++; if( j>12 ){ printf("\n"); j = 0; } } printf("%s };\n", j==0 ? "" : "\n"); printf(" static const unsigned short aNext[%d] = {\n", nKeyword); for(i=j=0; i<nKeyword; i++){ if( j==0 ) printf(" "); printf(" %3d,", aKeywordTable[i].iNext); j++; if( j>12 ){ printf("\n"); j = 0; } } printf("%s };\n", j==0 ? "" : "\n"); printf(" static const unsigned char aLen[%d] = {\n", nKeyword); for(i=j=0; i<nKeyword; i++){ if( j==0 ) printf(" "); printf(" %3d,", aKeywordTable[i].len+aKeywordTable[i].prefix); j++; if( j>12 ){ printf("\n"); j = 0; } } printf("%s };\n", j==0 ? "" : "\n"); printf(" static const unsigned short int aOffset[%d] = {\n", nKeyword); for(i=j=0; i<nKeyword; i++){ if( j==0 ) printf(" "); printf(" %3d,", aKeywordTable[i].offset); j++; if( j>12 ){ printf("\n"); j = 0; } } printf("%s };\n", j==0 ? "" : "\n"); printf(" static const unsigned char aCode[%d] = {\n", nKeyword); for(i=j=0; i<nKeyword; i++){ char *zToken = aKeywordTable[i].zTokenType; if( j==0 ) printf(" "); printf("%s,%*s", zToken, (int)(14-strlen(zToken)), ""); j++; if( j>=5 ){ printf("\n"); j = 0; } } printf("%s };\n", j==0 ? "" : "\n"); printf(" static const bool aFlag[%d] = {\n", nKeyword); for(i=j=0; i<nKeyword; i++){ bool isReserved = aKeywordTable[i].isReserved; const char *flag = (isReserved ? "true" : "false"); if( j==0 ) printf(" "); printf("%s,%*s", flag, (int)(14-strlen(flag)), ""); j++; if( j>=5 ){ printf("\n"); j = 0; } } printf("%s };\n", j==0 ? "" : "\n"); printf(" int i, j;\n"); printf(" const char *zKW;\n"); printf(" if( n>=2 ){\n"); printf(" i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) %% %d;\n", bestSize); printf(" for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){\n"); printf(" if( aLen[i]!=n ) continue;\n"); printf(" j = 0;\n"); printf(" zKW = &zText[aOffset[i]];\n"); printf(" while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }\n"); printf(" if( j<n ) continue;\n"); for(i=0; i<nKeyword; i++){ printf(" testcase( i==%d ); /* %s */\n", i, aKeywordTable[i].zOrigName); } printf(" *pType = aCode[i];\n"); printf(" if (pFlag) {\n"); printf(" *pFlag = aFlag[i];\n"); printf(" }\n"); printf(" break;\n"); printf(" }\n"); printf(" }\n"); printf(" return n;\n"); printf("}\n"); printf("int sqlite3KeywordCode(const unsigned char *z, int n){\n"); printf(" int id = TK_ID;\n"); printf(" keywordCode((char*)z, n, &id, NULL);\n"); printf(" return id;\n"); printf("}\n"); printf("#define SQLITE_N_KEYWORD %d\n", nKeyword); return 0; }
the_stack_data/87639085.c
#include<stdio.h> #include<stdlib.h> #include<limits.h> int swap(int *a, int *b){ int temp; temp=*a; *a=*b; *b=temp; } int bub_sort(int p[], int bt[], int at[], int n) { int i,j; for(i=0;i<n;i++) { for(j=0;j<n-1-i;j++) { if(p[j] > p[j+1]) { swap(&p[j],&p[j+1]); swap(&bt[j],&bt[j+1]); swap(&at[j],&at[j+1]); } else if(p[j]==p[j+1]) { if(at[j] > at[j+1]) { swap(&p[j],&p[j+1]); swap(&bt[j],&bt[j+1]); swap(&at[j],&at[j+1]); } } } } } int main() { int n,i,j,f=0; printf("Enter the no of process\n"); scanf("%d",&n); int at[n],p[n],bt[n],bt1[n],ct[n],wt[n],tat[n]; printf("enter the arrival time\n"); for(i=0;i<n;i++) scanf("%d",&at[i]); printf("enter the priority\n"); for(i=0;i<n;i++) scanf("%d",&p[i]); printf("enter the burst time\n"); for(i=0;i<n;i++) scanf("%d",&bt[i]); bub_sort(p,bt,at,n); for(i=0;i<n;i++) bt1[i]=bt[i]; //ct int pno=0; for(i=0;i<n;i++) ct[i]=0; int counter=0; while(1) { for(i=0;i<n;i++) { if(counter>=at[i] && bt[i]!=0) { counter++; bt[i]--; f=1; if(bt[i]==0 && ct[i]==0) { ct[i]=counter; printf("%d\n",ct[i]); pno++; } break; } printf("counter=%d\ti=%d\t bt[i]=%d\n",counter,i,bt[i]); } if(f==0) counter++; if(pno==n) break; } //tat and wt for(i=0;i<n;i++) { tat[i]=ct[i]-at[i]; wt[i]=tat[i]-bt1[i]; } printf("Process\tAt\tBt\tPrio\tCt\tTat\tWt\n"); for(i=0;i<n;i++) printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\n",i+1,at[i],bt1[i],p[i],ct[i],tat[i],wt[i]); return 0; }
the_stack_data/62638702.c
/* { dg-do compile } */ /* { dg-options "-Os -fno-ident" } */ /* { dg-final { scan-assembler-not "test" } } */ int fct1 (void); int fct2 (void); int fct (unsigned nb) { if ((nb >> 5) != 0) return fct1 (); else return fct2 (); }
the_stack_data/154828463.c
/* Copyright 2004, 2005 PathScale, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. */ #ifdef KEY /* Bug 3018 */ #include "pathf90_libU_intrin.h" /* Provide this for backward compatibility, and in case somebody declares it * "external" in Fortran but expects to get it from the library instead of * defining it themselves */ int time_() { return pathf90_time4(); } #endif /* KEY Bug 3018 */
the_stack_data/98279.c
#include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <unistd.h> #include <sys/time.h> #include <time.h> #include <linux/rtc.h> int main(int argc, char **argv) { int fd; int ret; struct rtc_time rtc_tm; fd = open("/dev/rtc0", O_RDWR); if(fd < 0){ perror("open error: "); return fd; } while(1){ ret = ioctl(fd, RTC_RD_TIME, &rtc_tm); printf("%d-%d-%d %d-%d-%d\n", rtc_tm.tm_year+1900, rtc_tm.tm_mon+1, rtc_tm.tm_mday, rtc_tm.tm_hour, rtc_tm.tm_min, rtc_tm.tm_sec); sleep(1); } close(fd); return 0; }
the_stack_data/97012976.c
#include <stdio.h> #include <string.h> #include <ctype.h> #define MAX 80 int convert_to_line(); // Converts single characters to lines // int ignore_tags(); // int check_tag(); int print(); // Prints the line w/o the tags int spacesToUnderscore(); char linea[MAX]; int main() { extern char linea[]; int ignore = 1; int p, strong, h1, h2, h3, h4, h5, h6; p = strong = h1 = 0; // Initialization while (convert_to_line() == 0) { // I should use switch case strstr(linea, "<p>") != NULL ? p++ : 0; strstr(linea, "<h1>") != NULL ? h1++ : 0; strstr(linea, "<h2>") != NULL ? h2++ : 0; strstr(linea, "<h3>") != NULL ? h3++ : 0; strstr(linea, "<h4>") != NULL ? h4++ : 0; strstr(linea, "<h5>") != NULL ? h5++ : 0; strstr(linea, "<h6>") != NULL ? h6++ : 0; h1 > 0 || h2 > 0 || h3 > 0 || h4 > 0 || h5 > 0 || h6 > 0 ? spacesToUnderscore() : 0 ; strstr(linea, "</h1>") != NULL ? h1-- : 0; strstr(linea, "</h2>") != NULL ? h2-- : 0; strstr(linea, "</h3>") != NULL ? h3-- : 0; strstr(linea, "</h4>") != NULL ? h4-- : 0; strstr(linea, "</h5>") != NULL ? h5-- : 0; strstr(linea, "</h6>") != NULL ? h6-- : 0; if (p > 0) { if (strstr(linea, "<strong>") != NULL) { strong++; spacesToUnderscore(); } else { print(); } } if (strstr(linea, "</p>") != NULL) { p--; } if (strstr(linea, "</strong>") != NULL) { strong--; } } return 0; } int print() { extern char linea[]; int ignore = 0; int i; int num_max = strlen(linea); for (i = 0; i < num_max; i++) { if (linea[i] == '<') { ignore = 1; } if (!ignore) { printf("%c", linea[i]); } if (linea[i] == '>') { printf("\n"); // New line for all ignore = 0; } } } int spacesToUnderscore() { extern char linea[]; int space; int i; int ignore = 1; int num_max = strlen(linea); // This functions counts the length for (i = 0; i < num_max; i++) { if (linea[i] == '<') { // Here, we evaluate the char ignore = 1; } if (!ignore) { if (isspace(linea[i])) { space = 1; } else { if (space) { printf("_"); // Replace the space space = 0; // Reestablecer counter } printf("%c", linea[i]); } } if (linea[i] == '>') { ignore = 0; } } return 0; } int convert_to_line() { extern char linea[]; int c, i = 0; for (i = 0; i < MAX && (c = getchar()) != EOF && c != '\n';) { linea[i++] = c; } linea[i] = '\0'; return c == EOF; } // These functions were the experiments /* int check_tag() { extern char linea[]; if (strstr(linea, "<p>") != NULL) { return 1; } if (strstr(linea, "</p>") != NULL) { return 0; } return 0; } */ /* int ignore_tags() { extern char linea[]; int ignore = 0; int i; int num_max = strlen(linea); for (i = 0; i < num_max; i++) { if (linea[i] == '<') { ignore = 1; } if (!ignore) { printf("%c", linea[i]); } if (linea[i] == '>') { ignore = 0; } } } */
the_stack_data/140764839.c
#define offsetof_p_pid (unsigned)(0x10) // proc_t::p_pid #define offsetof_task (unsigned)(0x18) // proc_t::task #define offsetof_p_uid (unsigned)(0x30) // proc_t::p_uid #define offsetof_p_gid (unsigned)(0x34) // proc_t::p_uid #define offsetof_p_ruid (unsigned)(0x38) // proc_t::p_uid #define offsetof_p_rgid (unsigned)(0x3c) // proc_t::p_uid #define offsetof_p_ucred (unsigned)(0x100) // proc_t::p_ucred #define offsetof_p_csflags (unsigned)(0x2a8) // proc_t::p_csflags #define offsetof_itk_self (unsigned)(0xD8) // task_t::itk_self (convert_task_to_port) #define offsetof_itk_sself (unsigned)(0xE8) // task_t::itk_sself (task_get_special_port) #define offsetof_itk_bootstrap (unsigned)0x2b8 // task_t::itk_bootstrap (task_get_special_port) #define offsetof_itk_space (unsigned)((kCFCoreFoundationVersionNumber >= 1443.00) ? (0x308) : (0x300)) // task_t::itk_space #define offsetof_bsd_info (unsigned)((kCFCoreFoundationVersionNumber >= 1443.00) ? (0x368) : (0x360)) // task_t::bsd_info #define offsetof_ip_mscount (unsigned)(0x9C) // ipc_port_t::ip_mscount (ipc_port_make_send) #define offsetof_ip_srights (unsigned)(0xA0) // ipc_port_t::ip_srights (ipc_port_make_send) #define offsetof_ip_kobject (unsigned)(0x68) // ipc_port_t::ip_kobject #define offsetof_p_textvp (unsigned)(0x248) // proc_t::p_textvp #define offsetof_p_textoff (unsigned)(0x250) // proc_t::p_textoff #define offsetof_p_cputype (unsigned)(0x2c0) // proc_t::p_cputype #define offsetof_p_cpu_subtype (unsigned)(0x2c4) // proc_t::p_cpu_subtype #define offsetof_special (unsigned)(2 * sizeof(long)) // host::special #define offsetof_ipc_space_is_table (unsigned)(0x20) // ipc_space::is_table?.. #define offsetof_ucred_cr_uid (unsigned)(0x18) // ucred::cr_uid #define offsetof_ucred_cr_ruid (unsigned)(0x1c) // ucred::cr_ruid #define offsetof_ucred_cr_svuid (unsigned)(0x20) // ucred::cr_svuid #define offsetof_ucred_cr_ngroups (unsigned)(0x24) // ucred::cr_ngroups #define offsetof_ucred_cr_groups (unsigned)(0x28) // ucred::cr_groups #define offsetof_ucred_cr_rgid (unsigned)(0x68) // ucred::cr_rgid #define offsetof_ucred_cr_svgid (unsigned)(0x6c) // ucred::cr_svgid #define offsetof_v_type (unsigned)(0x70) // vnode::v_type #define offsetof_v_id (unsigned)(0x74) // vnode::v_id #define offsetof_v_ubcinfo (unsigned)(0x78) // vnode::v_ubcinfo #define offsetof_ubcinfo_csblobs (unsigned)(0x50) // ubc_info::csblobs #define offsetof_csb_cputype (unsigned)(0x8) // cs_blob::csb_cputype #define offsetof_csb_flags (unsigned)((kCFCoreFoundationVersionNumber >= 1450.14) ? (0xc) : (0x12)) // cs_blob::csb_flags #define offsetof_csb_base_offset (unsigned)((kCFCoreFoundationVersionNumber >= 1450.14) ? (0x10) : (0x16)) // cs_blob::csb_base_offset #define offsetof_csb_entitlements_offset (unsigned)(0x98) // cs_blob::csb_entitlements #define offsetof_csb_signer_type (unsigned)(0xA0) // cs_blob::csb_signer_type #define offsetof_csb_platform_binary (unsigned)(0xA4) // cs_blob::csb_platform_binary #define offsetof_csb_platform_path (unsigned)(0xA8) // cs_blob::csb_platform_path #define offsetof_t_flags (unsigned)(0x3a0) // task::t_flags
the_stack_data/238321.c
// Exercise: Monitoria2 // Author: Kevn Carvalho de Jesus #include <stdio.h> #include <stdlib.h> int calculateDigitOne(int c1, int c2, int c3, int c4, int c5, int c6, int c7, int c8, int c9); int calculateDigitTwo(int c1, int c2, int c3, int c4, int c5, int c6, int c7, int c8, int c9, int c10); int isEqualDigitsCpf(int c1, int c2, int c3, int c4, int c5, int c6, int c7, int c8, int c9, int v1, int v2); void displayCpfValidity(int c1, int c2, int c3, int c4, int c5, int c6, int c7, int c8, int c9, int v1, int v2); int main(void) { int c1, c2, c3, c4, c5, c6, c7, c8, c9, v1, v2; int num1, num2, num3, verif; scanf("%d.%d.%d-%d", &num1, &num2, &num3, &verif); //cuting CPF into your digits c1 = num1 / 100; c3 = num1 % 10; c2 = (num1 % 100 - c3) / 10; c4 = num2 / 100; c6 = num2 % 10; c5 = (num2 % 100 - c6) / 10; c7 = num3 / 100; c9 = num3 % 10; c8 = (num3 % 100 - c9) / 10; v1 = verif / 10; v2 = verif % 10; displayCpfValidity(c1, c2, c3, c4, c5, c6, c7, c8, c9, v1, v2); return 0; } int calculateDigitOne(int c1, int c2, int c3, int c4, int c5, int c6, int c7, int c8, int c9) { int sum = c1*10 + c2*9 + c3*8 + c4*7 + c5*6 + c6*5 + c7*4 + c8*3 + c9*2; int rest = sum % 11; if (rest < 2) return 0; else return (11 - rest); } int calculateDigitTwo(int c1, int c2, int c3, int c4, int c5, int c6, int c7, int c8, int c9, int c10) { int sum = c1*11 + c2*10 + c3*9 + c4*8 + c5*7 + c6*6 + c7*5 + c8*4 + c9*3 + c10*2; int rest = sum % 11; if (rest < 2) return 0; else { if(sum == 202) return 5; return (11 - rest); } } int isEqualDigitsCpf(int c1, int c2, int c3, int c4, int c5, int c6, int c7, int c8, int c9, int v1, int v2) { return ((c1 == c2) && (c1 == c3) && (c1 == c4) && (c1 == c5) && (c1 == c6) && (c1 == c7) && (c1 == c8) && (c1 == c9) && (c1 == v1) && (c1 == v2)) ? 1 : 0; } void displayCpfValidity(int c1, int c2, int c3, int c4, int c5, int c6, int c7, int c8, int c9, int v1, int v2) { if (isEqualDigitsCpf(c1, c2, c3, c4, c5, c6, c7, c8, c9, v1, v2)) printf("CPF invalido: digitos iguais!"); else if (calculateDigitOne(c1, c2, c3, c4, c5, c6, c7, c8, c9) != v1 && calculateDigitTwo(c1, c2, c3, c4, c5, c6, c7, c8, c9, v1) != v2) printf("CPF invalido: dois digitos!"); else if (calculateDigitOne(c1, c2, c3, c4, c5, c6, c7, c8, c9) != v1) printf("CPF invalido: primeiro digito!"); else if (calculateDigitTwo(c1, c2, c3, c4, c5, c6, c7, c8, c9, v1) != v2) printf("CPF invalido: segundo digito!"); else printf("CPF valido!"); }
the_stack_data/67673.c
// RUN: %clang_analyze_cc1 -triple x86_64-unknown-unknown -analyzer-checker=alpha.security.MallocOverflow,unix -verify %s typedef __typeof__(sizeof(int)) size_t; extern void *malloc(size_t); extern void free(void *ptr); void *malloc(unsigned long s); struct table { int nentry; unsigned *table; unsigned offset_max; }; static int table_build(struct table *t) { t->nentry = ((t->offset_max >> 2) + 31) / 32; t->table = (unsigned *)malloc(sizeof(unsigned) * t->nentry); // expected-warning {{the computation of the size of the memory allocation may overflow}} int n; n = 10000; int *p = malloc(sizeof(int) * n); // no-warning free(p); return t->nentry; } static int table_build_1(struct table *t) { t->nentry = (sizeof(struct table) * 2 + 31) / 32; t->table = (unsigned *)malloc(sizeof(unsigned) * t->nentry); // no-warning return t->nentry; } void *f(int n) { return malloc(n * 0 * sizeof(int)); // expected-warning {{Call to 'malloc' has an allocation size of 0 bytes}} }
the_stack_data/148484.c
/* * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") * Copyright (c) 1999 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* Import. */ #include <arpa/nameser.h> #include <ctype.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <time.h> #define SPRINTF(x) ((size_t)sprintf x) /* Forward. */ static int datepart(const char *, int, int, int, int *); /* Public. */ /*% * Convert a date in ASCII into the number of seconds since * 1 January 1970 (GMT assumed). Format is yyyymmddhhmmss, all * digits required, no spaces allowed. */ uint32_t ns_datetosecs(const char *cp, int *errp) { struct tm time; uint32_t result; int mdays, i; static const int days_per_month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (strlen(cp) != 14U) { *errp = 1; return (0); } *errp = 0; memset(&time, 0, sizeof time); time.tm_year = datepart(cp + 0, 4, 1990, 9999, errp) - 1900; time.tm_mon = datepart(cp + 4, 2, 01, 12, errp) - 1; time.tm_mday = datepart(cp + 6, 2, 01, 31, errp); time.tm_hour = datepart(cp + 8, 2, 00, 23, errp); time.tm_min = datepart(cp + 10, 2, 00, 59, errp); time.tm_sec = datepart(cp + 12, 2, 00, 59, errp); if (*errp) /*%< Any parse errors? */ return (0); /* * OK, now because timegm() is not available in all environments, * we will do it by hand. Roll up sleeves, curse the gods, begin! */ #define SECS_PER_DAY ((uint32_t)24*60*60) #define isleap(y) ((((y) % 4) == 0 && ((y) % 100) != 0) || ((y) % 400) == 0) result = time.tm_sec; /*%< Seconds */ result += time.tm_min * 60; /*%< Minutes */ result += time.tm_hour * (60*60); /*%< Hours */ result += (time.tm_mday - 1) * SECS_PER_DAY; /*%< Days */ /* Months are trickier. Look without leaping, then leap */ mdays = 0; for (i = 0; i < time.tm_mon; i++) mdays += days_per_month[i]; result += mdays * SECS_PER_DAY; /*%< Months */ if (time.tm_mon > 1 && isleap(1900+time.tm_year)) result += SECS_PER_DAY; /*%< Add leapday for this year */ /* First figure years without leapdays, then add them in. */ /* The loop is slow, FIXME, but simple and accurate. */ result += (time.tm_year - 70) * (SECS_PER_DAY*365); /*%< Years */ for (i = 70; i < time.tm_year; i++) if (isleap(1900+i)) result += SECS_PER_DAY; /*%< Add leapday for prev year */ return (result); } /* Private. */ /*% * Parse part of a date. Set error flag if any error. * Don't reset the flag if there is no error. */ static int datepart(const char *buf, int size, int min, int max, int *errp) { int result = 0; int i; for (i = 0; i < size; i++) { if (!isdigit((unsigned char)(buf[i]))) *errp = 1; result = (result * 10) + buf[i] - '0'; } if (result < min) *errp = 1; if (result > max) *errp = 1; return (result); } /*! \file */
the_stack_data/40135.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); extern int __VERIFIER_nondet_int(void); /* Generated by CIL v. 1.3.7 */ /* print_CIL_Input is true */ struct JoinPoint { void **(*fp)(struct JoinPoint * ) ; void **args ; int argsCount ; char const **argsType ; void *(*arg)(int , struct JoinPoint * ) ; char const *(*argType)(int , struct JoinPoint * ) ; void **retValue ; char const *retType ; char const *funcName ; char const *targetName ; char const *fileName ; char const *kind ; void *excep_return ; }; struct __UTAC__CFLOW_FUNC { int (*func)(int , int ) ; int val ; struct __UTAC__CFLOW_FUNC *next ; }; struct __UTAC__EXCEPTION { void *jumpbuf ; unsigned long long prtValue ; int pops ; struct __UTAC__CFLOW_FUNC *cflowfuncs ; }; typedef unsigned int size_t; struct __ACC__ERR { void *v ; struct __ACC__ERR *next ; }; #pragma merger(0,"Test.i","") extern int printf(char const * __restrict __format , ...) ; extern int puts(char const *__s ) ; void setClientAddressBookSize(int handle , int value ) ; void setClientAddressBookAlias(int handle , int index , int value ) ; void setClientAddressBookAddress(int handle , int index , int value ) ; void setClientPrivateKey(int handle , int value ) ; int createClientKeyringEntry(int handle ) ; int getClientKeyringUser(int handle , int index ) ; void setClientKeyringUser(int handle , int index , int value ) ; int getClientKeyringPublicKey(int handle , int index ) ; void setClientKeyringPublicKey(int handle , int index , int value ) ; void setClientForwardReceiver(int handle , int value ) ; void setClientId(int handle , int value ) ; int __SELECTED_FEATURE_Base ; int __SELECTED_FEATURE_Keys ; int __SELECTED_FEATURE_Encrypt ; int __SELECTED_FEATURE_AutoResponder ; int __SELECTED_FEATURE_AddressBook ; int __SELECTED_FEATURE_Sign ; int __SELECTED_FEATURE_Forward ; int __SELECTED_FEATURE_Verify ; int __SELECTED_FEATURE_Decrypt ; int __GUIDSL_ROOT_PRODUCTION ; int __GUIDSL_NON_TERMINAL_main ; void select_features(void) ; void select_helpers(void) ; int valid_product(void) ; int is_queue_empty(void) ; int get_queued_client(void) ; int get_queued_email(void) ; void outgoing(int client , int msg ) ; void sendEmail(int sender , int receiver ) ; void generateKeyPair(int client , int seed ) ; int bob ; int rjh ; int chuck ; void setup_bob(int bob___0 ) ; void setup_rjh(int rjh___0 ) ; void setup_chuck(int chuck___0 ) ; void bobToRjh(void) ; void rjhToBob(void) ; void test(void) ; void setup(void) ; int main(void) ; void bobKeyAdd(void) ; void bobKeyAddChuck(void) ; void rjhKeyAdd(void) ; void rjhKeyAddChuck(void) ; void chuckKeyAdd(void) ; void bobKeyChange(void) ; void rjhKeyChange(void) ; void rjhDeletePrivateKey(void) ; void chuckKeyAddRjh(void) ; void bobSetAddressBook(void) ; void rjhEnableForwarding(void) ; void setup_bob__wrappee__Base(int bob___0 ) { { { setClientId(bob___0, bob___0); } return; } } void setup_bob(int bob___0 ) { { { setup_bob__wrappee__Base(bob___0); setClientPrivateKey(bob___0, 123); } return; } } void setup_rjh__wrappee__Base(int rjh___0 ) { { { setClientId(rjh___0, rjh___0); } return; } } void setup_rjh(int rjh___0 ) { { { setup_rjh__wrappee__Base(rjh___0); setClientPrivateKey(rjh___0, 456); } return; } } void setup_chuck__wrappee__Base(int chuck___0 ) { { { setClientId(chuck___0, chuck___0); } return; } } void setup_chuck(int chuck___0 ) { { { setup_chuck__wrappee__Base(chuck___0); setClientPrivateKey(chuck___0, 789); } return; } } void bobToRjh(void) { int tmp ; int tmp___0 ; int tmp___1 ; { { puts("Please enter a subject and a message body.\n"); sendEmail(bob, rjh); tmp___1 = is_queue_empty(); } if (tmp___1) { } else { { tmp = get_queued_email(); tmp___0 = get_queued_client(); outgoing(tmp___0, tmp); } } return; } } void rjhToBob(void) { { { puts("Please enter a subject and a message body.\n"); sendEmail(rjh, bob); } return; } } void setup(void) { char const * __restrict __cil_tmp1 ; char const * __restrict __cil_tmp2 ; char const * __restrict __cil_tmp3 ; { { bob = 1; setup_bob(bob); __cil_tmp1 = (char const * __restrict )"bob: %d\n"; printf(__cil_tmp1, bob); rjh = 2; setup_rjh(rjh); __cil_tmp2 = (char const * __restrict )"rjh: %d\n"; printf(__cil_tmp2, rjh); chuck = 3; setup_chuck(chuck); __cil_tmp3 = (char const * __restrict )"chuck: %d\n"; printf(__cil_tmp3, chuck); } return; } } int main(void) { int retValue_acc ; int tmp ; { { select_helpers(); select_features(); tmp = valid_product(); } if (tmp) { { setup(); test(); } } else { } return (retValue_acc); } } void bobKeyAdd(void) { int tmp ; int tmp___0 ; char const * __restrict __cil_tmp3 ; char const * __restrict __cil_tmp4 ; { { createClientKeyringEntry(bob); setClientKeyringUser(bob, 0, 2); setClientKeyringPublicKey(bob, 0, 456); puts("bob added rjhs key"); tmp = getClientKeyringUser(bob, 0); __cil_tmp3 = (char const * __restrict )"%d\n"; printf(__cil_tmp3, tmp); tmp___0 = getClientKeyringPublicKey(bob, 0); __cil_tmp4 = (char const * __restrict )"%d\n"; printf(__cil_tmp4, tmp___0); } return; } } void rjhKeyAdd(void) { { { createClientKeyringEntry(rjh); setClientKeyringUser(rjh, 0, 1); setClientKeyringPublicKey(rjh, 0, 123); } return; } } void rjhKeyAddChuck(void) { { { createClientKeyringEntry(rjh); setClientKeyringUser(rjh, 0, 3); setClientKeyringPublicKey(rjh, 0, 789); } return; } } void bobKeyAddChuck(void) { { { createClientKeyringEntry(bob); setClientKeyringUser(bob, 1, 3); setClientKeyringPublicKey(bob, 1, 789); } return; } } void chuckKeyAdd(void) { { { createClientKeyringEntry(chuck); setClientKeyringUser(chuck, 0, 1); setClientKeyringPublicKey(chuck, 0, 123); } return; } } void chuckKeyAddRjh(void) { { { createClientKeyringEntry(chuck); setClientKeyringUser(chuck, 0, 2); setClientKeyringPublicKey(chuck, 0, 456); } return; } } void rjhDeletePrivateKey(void) { { { setClientPrivateKey(rjh, 0); } return; } } void bobKeyChange(void) { { { generateKeyPair(bob, 777); } return; } } void rjhKeyChange(void) { { { generateKeyPair(rjh, 666); } return; } } void bobSetAddressBook(void) { { { setClientAddressBookSize(bob, 1); setClientAddressBookAlias(bob, 0, rjh); setClientAddressBookAddress(bob, 0, rjh); setClientAddressBookAddress(bob, 1, chuck); } return; } } void rjhEnableForwarding(void) { { { setClientForwardReceiver(rjh, chuck); } return; } } #pragma merger(0,"Email.i","") int getEmailId(int handle ) ; int getEmailFrom(int handle ) ; void setEmailFrom(int handle , int value ) ; int getEmailTo(int handle ) ; void setEmailTo(int handle , int value ) ; int isEncrypted(int handle ) ; int getEmailEncryptionKey(int handle ) ; int isSigned(int handle ) ; int getEmailSignKey(int handle ) ; int isVerified(int handle ) ; void printMail(int msg ) ; int isReadable(int msg ) ; int createEmail(int from , int to ) ; int cloneEmail(int msg ) ; void printMail__wrappee__Keys(int msg ) { int tmp ; int tmp___0 ; int tmp___1 ; int tmp___2 ; char const * __restrict __cil_tmp6 ; char const * __restrict __cil_tmp7 ; char const * __restrict __cil_tmp8 ; char const * __restrict __cil_tmp9 ; { { tmp = getEmailId(msg); __cil_tmp6 = (char const * __restrict )"ID:\n %i\n"; printf(__cil_tmp6, tmp); tmp___0 = getEmailFrom(msg); __cil_tmp7 = (char const * __restrict )"FROM:\n %i\n"; printf(__cil_tmp7, tmp___0); tmp___1 = getEmailTo(msg); __cil_tmp8 = (char const * __restrict )"TO:\n %i\n"; printf(__cil_tmp8, tmp___1); tmp___2 = isReadable(msg); __cil_tmp9 = (char const * __restrict )"IS_READABLE\n %i\n"; printf(__cil_tmp9, tmp___2); } return; } } void printMail__wrappee__AddressBook(int msg ) { int tmp ; int tmp___0 ; char const * __restrict __cil_tmp4 ; char const * __restrict __cil_tmp5 ; { { printMail__wrappee__Keys(msg); tmp = isEncrypted(msg); __cil_tmp4 = (char const * __restrict )"ENCRYPTED\n %d\n"; printf(__cil_tmp4, tmp); tmp___0 = getEmailEncryptionKey(msg); __cil_tmp5 = (char const * __restrict )"ENCRYPTION KEY\n %d\n"; printf(__cil_tmp5, tmp___0); } return; } } void printMail__wrappee__Forward(int msg ) { int tmp ; int tmp___0 ; char const * __restrict __cil_tmp4 ; char const * __restrict __cil_tmp5 ; { { printMail__wrappee__AddressBook(msg); tmp = isSigned(msg); __cil_tmp4 = (char const * __restrict )"SIGNED\n %i\n"; printf(__cil_tmp4, tmp); tmp___0 = getEmailSignKey(msg); __cil_tmp5 = (char const * __restrict )"SIGNATURE\n %i\n"; printf(__cil_tmp5, tmp___0); } return; } } void printMail(int msg ) { int tmp ; char const * __restrict __cil_tmp3 ; { { printMail__wrappee__Forward(msg); tmp = isVerified(msg); __cil_tmp3 = (char const * __restrict )"SIGNATURE VERIFIED\n %d\n"; printf(__cil_tmp3, tmp); } return; } } int isReadable__wrappee__Keys(int msg ) { int retValue_acc ; { retValue_acc = 1; return (retValue_acc); return (retValue_acc); } } int isReadable(int msg ) { int retValue_acc ; int tmp ; { { tmp = isEncrypted(msg); } if (tmp) { retValue_acc = 0; return (retValue_acc); } else { { retValue_acc = isReadable__wrappee__Keys(msg); } return (retValue_acc); } return (retValue_acc); } } int cloneEmail(int msg ) { int retValue_acc ; { retValue_acc = msg; return (retValue_acc); return (retValue_acc); } } int createEmail(int from , int to ) { int retValue_acc ; int msg ; { { msg = 1; setEmailFrom(msg, from); setEmailTo(msg, to); retValue_acc = msg; } return (retValue_acc); return (retValue_acc); } } #pragma merger(0,"EncryptVerify_spec.i","") void __automaton_fail(void) ; __inline void __utac_acc__EncryptVerify_spec__1(int msg ) { int tmp ; { { tmp = isReadable(msg); } if (tmp) { } else { { __automaton_fail(); } } return; } } #pragma merger(0,"wsllib_check.i","") void __automaton_fail(void) { { ERROR: __VERIFIER_error(); return; } } #pragma merger(0,"libacc.i","") extern __attribute__((__nothrow__, __noreturn__)) void __assert_fail(char const *__assertion , char const *__file , unsigned int __line , char const *__function ) ; extern __attribute__((__nothrow__)) void *malloc(size_t __size ) __attribute__((__malloc__)) ; extern __attribute__((__nothrow__)) void free(void *__ptr ) ; void __utac__exception__cf_handler_set(void *exception , int (*cflow_func)(int , int ) , int val ) { struct __UTAC__EXCEPTION *excep ; struct __UTAC__CFLOW_FUNC *cf ; void *tmp ; unsigned long __cil_tmp7 ; unsigned long __cil_tmp8 ; unsigned long __cil_tmp9 ; unsigned long __cil_tmp10 ; unsigned long __cil_tmp11 ; unsigned long __cil_tmp12 ; unsigned long __cil_tmp13 ; unsigned long __cil_tmp14 ; int (**mem_15)(int , int ) ; int *mem_16 ; struct __UTAC__CFLOW_FUNC **mem_17 ; struct __UTAC__CFLOW_FUNC **mem_18 ; struct __UTAC__CFLOW_FUNC **mem_19 ; { { excep = (struct __UTAC__EXCEPTION *)exception; tmp = malloc(24UL); cf = (struct __UTAC__CFLOW_FUNC *)tmp; mem_15 = (int (**)(int , int ))cf; *mem_15 = cflow_func; __cil_tmp7 = (unsigned long )cf; __cil_tmp8 = __cil_tmp7 + 8; mem_16 = (int *)__cil_tmp8; *mem_16 = val; __cil_tmp9 = (unsigned long )cf; __cil_tmp10 = __cil_tmp9 + 16; __cil_tmp11 = (unsigned long )excep; __cil_tmp12 = __cil_tmp11 + 24; mem_17 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp10; mem_18 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp12; *mem_17 = *mem_18; __cil_tmp13 = (unsigned long )excep; __cil_tmp14 = __cil_tmp13 + 24; mem_19 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp14; *mem_19 = cf; } return; } } void __utac__exception__cf_handler_free(void *exception ) { struct __UTAC__EXCEPTION *excep ; struct __UTAC__CFLOW_FUNC *cf ; struct __UTAC__CFLOW_FUNC *tmp ; unsigned long __cil_tmp5 ; unsigned long __cil_tmp6 ; struct __UTAC__CFLOW_FUNC *__cil_tmp7 ; unsigned long __cil_tmp8 ; unsigned long __cil_tmp9 ; unsigned long __cil_tmp10 ; unsigned long __cil_tmp11 ; void *__cil_tmp12 ; unsigned long __cil_tmp13 ; unsigned long __cil_tmp14 ; struct __UTAC__CFLOW_FUNC **mem_15 ; struct __UTAC__CFLOW_FUNC **mem_16 ; struct __UTAC__CFLOW_FUNC **mem_17 ; { excep = (struct __UTAC__EXCEPTION *)exception; __cil_tmp5 = (unsigned long )excep; __cil_tmp6 = __cil_tmp5 + 24; mem_15 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp6; cf = *mem_15; { while (1) { while_0_continue: /* CIL Label */ ; { __cil_tmp7 = (struct __UTAC__CFLOW_FUNC *)0; __cil_tmp8 = (unsigned long )__cil_tmp7; __cil_tmp9 = (unsigned long )cf; if (__cil_tmp9 != __cil_tmp8) { } else { goto while_0_break; } } { tmp = cf; __cil_tmp10 = (unsigned long )cf; __cil_tmp11 = __cil_tmp10 + 16; mem_16 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp11; cf = *mem_16; __cil_tmp12 = (void *)tmp; free(__cil_tmp12); } } while_0_break: /* CIL Label */ ; } __cil_tmp13 = (unsigned long )excep; __cil_tmp14 = __cil_tmp13 + 24; mem_17 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp14; *mem_17 = (struct __UTAC__CFLOW_FUNC *)0; return; } } void __utac__exception__cf_handler_reset(void *exception ) { struct __UTAC__EXCEPTION *excep ; struct __UTAC__CFLOW_FUNC *cf ; unsigned long __cil_tmp5 ; unsigned long __cil_tmp6 ; struct __UTAC__CFLOW_FUNC *__cil_tmp7 ; unsigned long __cil_tmp8 ; unsigned long __cil_tmp9 ; int (*__cil_tmp10)(int , int ) ; unsigned long __cil_tmp11 ; unsigned long __cil_tmp12 ; int __cil_tmp13 ; unsigned long __cil_tmp14 ; unsigned long __cil_tmp15 ; struct __UTAC__CFLOW_FUNC **mem_16 ; int (**mem_17)(int , int ) ; int *mem_18 ; struct __UTAC__CFLOW_FUNC **mem_19 ; { excep = (struct __UTAC__EXCEPTION *)exception; __cil_tmp5 = (unsigned long )excep; __cil_tmp6 = __cil_tmp5 + 24; mem_16 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp6; cf = *mem_16; { while (1) { while_1_continue: /* CIL Label */ ; { __cil_tmp7 = (struct __UTAC__CFLOW_FUNC *)0; __cil_tmp8 = (unsigned long )__cil_tmp7; __cil_tmp9 = (unsigned long )cf; if (__cil_tmp9 != __cil_tmp8) { } else { goto while_1_break; } } { mem_17 = (int (**)(int , int ))cf; __cil_tmp10 = *mem_17; __cil_tmp11 = (unsigned long )cf; __cil_tmp12 = __cil_tmp11 + 8; mem_18 = (int *)__cil_tmp12; __cil_tmp13 = *mem_18; (*__cil_tmp10)(4, __cil_tmp13); __cil_tmp14 = (unsigned long )cf; __cil_tmp15 = __cil_tmp14 + 16; mem_19 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp15; cf = *mem_19; } } while_1_break: /* CIL Label */ ; } { __utac__exception__cf_handler_free(exception); } return; } } void *__utac__error_stack_mgt(void *env , int mode , int count ) ; static struct __ACC__ERR *head = (struct __ACC__ERR *)0; void *__utac__error_stack_mgt(void *env , int mode , int count ) { void *retValue_acc ; struct __ACC__ERR *new ; void *tmp ; struct __ACC__ERR *temp ; struct __ACC__ERR *next ; void *excep ; unsigned long __cil_tmp10 ; unsigned long __cil_tmp11 ; unsigned long __cil_tmp12 ; unsigned long __cil_tmp13 ; void *__cil_tmp14 ; unsigned long __cil_tmp15 ; unsigned long __cil_tmp16 ; void *__cil_tmp17 ; void **mem_18 ; struct __ACC__ERR **mem_19 ; struct __ACC__ERR **mem_20 ; void **mem_21 ; struct __ACC__ERR **mem_22 ; void **mem_23 ; void **mem_24 ; { if (count == 0) { return (retValue_acc); } else { } if (mode == 0) { { tmp = malloc(16UL); new = (struct __ACC__ERR *)tmp; mem_18 = (void **)new; *mem_18 = env; __cil_tmp10 = (unsigned long )new; __cil_tmp11 = __cil_tmp10 + 8; mem_19 = (struct __ACC__ERR **)__cil_tmp11; *mem_19 = head; head = new; retValue_acc = (void *)new; } return (retValue_acc); } else { } if (mode == 1) { temp = head; { while (1) { while_2_continue: /* CIL Label */ ; if (count > 1) { } else { goto while_2_break; } { __cil_tmp12 = (unsigned long )temp; __cil_tmp13 = __cil_tmp12 + 8; mem_20 = (struct __ACC__ERR **)__cil_tmp13; next = *mem_20; mem_21 = (void **)temp; excep = *mem_21; __cil_tmp14 = (void *)temp; free(__cil_tmp14); __utac__exception__cf_handler_reset(excep); temp = next; count = count - 1; } } while_2_break: /* CIL Label */ ; } { __cil_tmp15 = (unsigned long )temp; __cil_tmp16 = __cil_tmp15 + 8; mem_22 = (struct __ACC__ERR **)__cil_tmp16; head = *mem_22; mem_23 = (void **)temp; excep = *mem_23; __cil_tmp17 = (void *)temp; free(__cil_tmp17); __utac__exception__cf_handler_reset(excep); retValue_acc = excep; } return (retValue_acc); } else { } if (mode == 2) { if (head) { mem_24 = (void **)head; retValue_acc = *mem_24; return (retValue_acc); } else { retValue_acc = (void *)0; return (retValue_acc); } } else { } return (retValue_acc); } } void *__utac__get_this_arg(int i , struct JoinPoint *this ) { void *retValue_acc ; unsigned long __cil_tmp4 ; unsigned long __cil_tmp5 ; int __cil_tmp6 ; int __cil_tmp7 ; unsigned long __cil_tmp8 ; unsigned long __cil_tmp9 ; void **__cil_tmp10 ; void **__cil_tmp11 ; int *mem_12 ; void ***mem_13 ; { if (i > 0) { { __cil_tmp4 = (unsigned long )this; __cil_tmp5 = __cil_tmp4 + 16; mem_12 = (int *)__cil_tmp5; __cil_tmp6 = *mem_12; if (i <= __cil_tmp6) { } else { { __assert_fail("i > 0 && i <= this->argsCount", "libacc.c", 123U, "__utac__get_this_arg"); } } } } else { { __assert_fail("i > 0 && i <= this->argsCount", "libacc.c", 123U, "__utac__get_this_arg"); } } __cil_tmp7 = i - 1; __cil_tmp8 = (unsigned long )this; __cil_tmp9 = __cil_tmp8 + 8; mem_13 = (void ***)__cil_tmp9; __cil_tmp10 = *mem_13; __cil_tmp11 = __cil_tmp10 + __cil_tmp7; retValue_acc = *__cil_tmp11; return (retValue_acc); return (retValue_acc); } } char const *__utac__get_this_argtype(int i , struct JoinPoint *this ) { char const *retValue_acc ; unsigned long __cil_tmp4 ; unsigned long __cil_tmp5 ; int __cil_tmp6 ; int __cil_tmp7 ; unsigned long __cil_tmp8 ; unsigned long __cil_tmp9 ; char const **__cil_tmp10 ; char const **__cil_tmp11 ; int *mem_12 ; char const ***mem_13 ; { if (i > 0) { { __cil_tmp4 = (unsigned long )this; __cil_tmp5 = __cil_tmp4 + 16; mem_12 = (int *)__cil_tmp5; __cil_tmp6 = *mem_12; if (i <= __cil_tmp6) { } else { { __assert_fail("i > 0 && i <= this->argsCount", "libacc.c", 131U, "__utac__get_this_argtype"); } } } } else { { __assert_fail("i > 0 && i <= this->argsCount", "libacc.c", 131U, "__utac__get_this_argtype"); } } __cil_tmp7 = i - 1; __cil_tmp8 = (unsigned long )this; __cil_tmp9 = __cil_tmp8 + 24; mem_13 = (char const ***)__cil_tmp9; __cil_tmp10 = *mem_13; __cil_tmp11 = __cil_tmp10 + __cil_tmp7; retValue_acc = *__cil_tmp11; return (retValue_acc); return (retValue_acc); } } #pragma merger(0,"EmailLib.i","") int initEmail(void) ; void setEmailId(int handle , int value ) ; char *getEmailSubject(int handle ) ; void setEmailSubject(int handle , char *value ) ; char *getEmailBody(int handle ) ; void setEmailBody(int handle , char *value ) ; void setEmailIsEncrypted(int handle , int value ) ; void setEmailEncryptionKey(int handle , int value ) ; void setEmailIsSigned(int handle , int value ) ; void setEmailSignKey(int handle , int value ) ; void setEmailIsSignatureVerified(int handle , int value ) ; int __ste_Email_counter = 0; int initEmail(void) { int retValue_acc ; { if (__ste_Email_counter < 2) { __ste_Email_counter = __ste_Email_counter + 1; retValue_acc = __ste_Email_counter; return (retValue_acc); } else { retValue_acc = -1; return (retValue_acc); } return (retValue_acc); } } int __ste_email_id0 = 0; int __ste_email_id1 = 0; int getEmailId(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_email_id0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_email_id1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } return (retValue_acc); } } void setEmailId(int handle , int value ) { { if (handle == 1) { __ste_email_id0 = value; } else { if (handle == 2) { __ste_email_id1 = value; } else { } } return; } } int __ste_email_from0 = 0; int __ste_email_from1 = 0; int getEmailFrom(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_email_from0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_email_from1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } return (retValue_acc); } } void setEmailFrom(int handle , int value ) { { if (handle == 1) { __ste_email_from0 = value; } else { if (handle == 2) { __ste_email_from1 = value; } else { } } return; } } int __ste_email_to0 = 0; int __ste_email_to1 = 0; int getEmailTo(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_email_to0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_email_to1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } return (retValue_acc); } } void setEmailTo(int handle , int value ) { { if (handle == 1) { __ste_email_to0 = value; } else { if (handle == 2) { __ste_email_to1 = value; } else { } } return; } } char *__ste_email_subject0 ; char *__ste_email_subject1 ; char *getEmailSubject(int handle ) { char *retValue_acc ; void *__cil_tmp3 ; { if (handle == 1) { retValue_acc = __ste_email_subject0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_email_subject1; return (retValue_acc); } else { __cil_tmp3 = (void *)0; retValue_acc = (char *)__cil_tmp3; return (retValue_acc); } } return (retValue_acc); } } void setEmailSubject(int handle , char *value ) { { if (handle == 1) { __ste_email_subject0 = value; } else { if (handle == 2) { __ste_email_subject1 = value; } else { } } return; } } char *__ste_email_body0 = (char *)0; char *__ste_email_body1 = (char *)0; char *getEmailBody(int handle ) { char *retValue_acc ; void *__cil_tmp3 ; { if (handle == 1) { retValue_acc = __ste_email_body0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_email_body1; return (retValue_acc); } else { __cil_tmp3 = (void *)0; retValue_acc = (char *)__cil_tmp3; return (retValue_acc); } } return (retValue_acc); } } void setEmailBody(int handle , char *value ) { { if (handle == 1) { __ste_email_body0 = value; } else { if (handle == 2) { __ste_email_body1 = value; } else { } } return; } } int __ste_email_isEncrypted0 = 0; int __ste_email_isEncrypted1 = 0; int isEncrypted(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_email_isEncrypted0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_email_isEncrypted1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } return (retValue_acc); } } void setEmailIsEncrypted(int handle , int value ) { { if (handle == 1) { __ste_email_isEncrypted0 = value; } else { if (handle == 2) { __ste_email_isEncrypted1 = value; } else { } } return; } } int __ste_email_encryptionKey0 = 0; int __ste_email_encryptionKey1 = 0; int getEmailEncryptionKey(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_email_encryptionKey0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_email_encryptionKey1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } return (retValue_acc); } } void setEmailEncryptionKey(int handle , int value ) { { if (handle == 1) { __ste_email_encryptionKey0 = value; } else { if (handle == 2) { __ste_email_encryptionKey1 = value; } else { } } return; } } int __ste_email_isSigned0 = 0; int __ste_email_isSigned1 = 0; int isSigned(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_email_isSigned0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_email_isSigned1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } return (retValue_acc); } } void setEmailIsSigned(int handle , int value ) { { if (handle == 1) { __ste_email_isSigned0 = value; } else { if (handle == 2) { __ste_email_isSigned1 = value; } else { } } return; } } int __ste_email_signKey0 = 0; int __ste_email_signKey1 = 0; int getEmailSignKey(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_email_signKey0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_email_signKey1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } return (retValue_acc); } } void setEmailSignKey(int handle , int value ) { { if (handle == 1) { __ste_email_signKey0 = value; } else { if (handle == 2) { __ste_email_signKey1 = value; } else { } } return; } } int __ste_email_isSignatureVerified0 ; int __ste_email_isSignatureVerified1 ; int isVerified(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_email_isSignatureVerified0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_email_isSignatureVerified1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } return (retValue_acc); } } void setEmailIsSignatureVerified(int handle , int value ) { { if (handle == 1) { __ste_email_isSignatureVerified0 = value; } else { if (handle == 2) { __ste_email_isSignatureVerified1 = value; } else { } } return; } } #pragma merger(0,"featureselect.i","") int select_one(void) ; int select_one(void) { int retValue_acc ; int choice = __VERIFIER_nondet_int(); { retValue_acc = choice; return (retValue_acc); return (retValue_acc); } } void select_features(void) { { return; } } void select_helpers(void) { { return; } } int valid_product(void) { int retValue_acc ; { retValue_acc = 1; return (retValue_acc); return (retValue_acc); } } #pragma merger(0,"ClientLib.i","") int initClient(void) ; char *getClientName(int handle ) ; void setClientName(int handle , char *value ) ; int getClientOutbuffer(int handle ) ; void setClientOutbuffer(int handle , int value ) ; int getClientAddressBookSize(int handle ) ; int createClientAddressBookEntry(int handle ) ; int getClientAddressBookAlias(int handle , int index ) ; int getClientAddressBookAddress(int handle , int index ) ; int getClientAutoResponse(int handle ) ; void setClientAutoResponse(int handle , int value ) ; int getClientPrivateKey(int handle ) ; int getClientKeyringSize(int handle ) ; int getClientForwardReceiver(int handle ) ; int getClientId(int handle ) ; int findPublicKey(int handle , int userid ) ; int findClientAddressBookAlias(int handle , int userid ) ; int __ste_Client_counter = 0; int initClient(void) { int retValue_acc ; { if (__ste_Client_counter < 3) { __ste_Client_counter = __ste_Client_counter + 1; retValue_acc = __ste_Client_counter; return (retValue_acc); } else { retValue_acc = -1; return (retValue_acc); } return (retValue_acc); } } char *__ste_client_name0 = (char *)0; char *__ste_client_name1 = (char *)0; char *__ste_client_name2 = (char *)0; char *getClientName(int handle ) { char *retValue_acc ; void *__cil_tmp3 ; { if (handle == 1) { retValue_acc = __ste_client_name0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_client_name1; return (retValue_acc); } else { if (handle == 3) { retValue_acc = __ste_client_name2; return (retValue_acc); } else { __cil_tmp3 = (void *)0; retValue_acc = (char *)__cil_tmp3; return (retValue_acc); } } } return (retValue_acc); } } void setClientName(int handle , char *value ) { { if (handle == 1) { __ste_client_name0 = value; } else { if (handle == 2) { __ste_client_name1 = value; } else { if (handle == 3) { __ste_client_name2 = value; } else { } } } return; } } int __ste_client_outbuffer0 = 0; int __ste_client_outbuffer1 = 0; int __ste_client_outbuffer2 = 0; int __ste_client_outbuffer3 = 0; int getClientOutbuffer(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_client_outbuffer0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_client_outbuffer1; return (retValue_acc); } else { if (handle == 3) { retValue_acc = __ste_client_outbuffer2; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } return (retValue_acc); } } void setClientOutbuffer(int handle , int value ) { { if (handle == 1) { __ste_client_outbuffer0 = value; } else { if (handle == 2) { __ste_client_outbuffer1 = value; } else { if (handle == 3) { __ste_client_outbuffer2 = value; } else { } } } return; } } int __ste_ClientAddressBook_size0 = 0; int __ste_ClientAddressBook_size1 = 0; int __ste_ClientAddressBook_size2 = 0; int getClientAddressBookSize(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_ClientAddressBook_size0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_ClientAddressBook_size1; return (retValue_acc); } else { if (handle == 3) { retValue_acc = __ste_ClientAddressBook_size2; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } return (retValue_acc); } } void setClientAddressBookSize(int handle , int value ) { { if (handle == 1) { __ste_ClientAddressBook_size0 = value; } else { if (handle == 2) { __ste_ClientAddressBook_size1 = value; } else { if (handle == 3) { __ste_ClientAddressBook_size2 = value; } else { } } } return; } } int createClientAddressBookEntry(int handle ) { int retValue_acc ; int size ; int tmp ; int __cil_tmp5 ; { { tmp = getClientAddressBookSize(handle); size = tmp; } if (size < 3) { { __cil_tmp5 = size + 1; setClientAddressBookSize(handle, __cil_tmp5); retValue_acc = size + 1; } return (retValue_acc); } else { retValue_acc = -1; return (retValue_acc); } return (retValue_acc); } } int __ste_Client_AddressBook0_Alias0 = 0; int __ste_Client_AddressBook0_Alias1 = 0; int __ste_Client_AddressBook0_Alias2 = 0; int __ste_Client_AddressBook1_Alias0 = 0; int __ste_Client_AddressBook1_Alias1 = 0; int __ste_Client_AddressBook1_Alias2 = 0; int __ste_Client_AddressBook2_Alias0 = 0; int __ste_Client_AddressBook2_Alias1 = 0; int __ste_Client_AddressBook2_Alias2 = 0; int getClientAddressBookAlias(int handle , int index ) { int retValue_acc ; { if (handle == 1) { if (index == 0) { retValue_acc = __ste_Client_AddressBook0_Alias0; return (retValue_acc); } else { if (index == 1) { retValue_acc = __ste_Client_AddressBook0_Alias1; return (retValue_acc); } else { if (index == 2) { retValue_acc = __ste_Client_AddressBook0_Alias2; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } } else { if (handle == 2) { if (index == 0) { retValue_acc = __ste_Client_AddressBook1_Alias0; return (retValue_acc); } else { if (index == 1) { retValue_acc = __ste_Client_AddressBook1_Alias1; return (retValue_acc); } else { if (index == 2) { retValue_acc = __ste_Client_AddressBook1_Alias2; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } } else { if (handle == 3) { if (index == 0) { retValue_acc = __ste_Client_AddressBook2_Alias0; return (retValue_acc); } else { if (index == 1) { retValue_acc = __ste_Client_AddressBook2_Alias1; return (retValue_acc); } else { if (index == 2) { retValue_acc = __ste_Client_AddressBook2_Alias2; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } } else { retValue_acc = 0; return (retValue_acc); } } } return (retValue_acc); } } int findClientAddressBookAlias(int handle , int userid ) { int retValue_acc ; { if (handle == 1) { if (userid == __ste_Client_AddressBook0_Alias0) { retValue_acc = 0; return (retValue_acc); } else { if (userid == __ste_Client_AddressBook0_Alias1) { retValue_acc = 1; return (retValue_acc); } else { if (userid == __ste_Client_AddressBook0_Alias2) { retValue_acc = 2; return (retValue_acc); } else { retValue_acc = -1; return (retValue_acc); } } } } else { if (handle == 2) { if (userid == __ste_Client_AddressBook1_Alias0) { retValue_acc = 0; return (retValue_acc); } else { if (userid == __ste_Client_AddressBook1_Alias1) { retValue_acc = 1; return (retValue_acc); } else { if (userid == __ste_Client_AddressBook1_Alias2) { retValue_acc = 2; return (retValue_acc); } else { retValue_acc = -1; return (retValue_acc); } } } } else { if (handle == 3) { if (userid == __ste_Client_AddressBook2_Alias0) { retValue_acc = 0; return (retValue_acc); } else { if (userid == __ste_Client_AddressBook2_Alias1) { retValue_acc = 1; return (retValue_acc); } else { if (userid == __ste_Client_AddressBook2_Alias2) { retValue_acc = 2; return (retValue_acc); } else { retValue_acc = -1; return (retValue_acc); } } } } else { retValue_acc = -1; return (retValue_acc); } } } return (retValue_acc); } } void setClientAddressBookAlias(int handle , int index , int value ) { { if (handle == 1) { if (index == 0) { __ste_Client_AddressBook0_Alias0 = value; } else { if (index == 1) { __ste_Client_AddressBook0_Alias1 = value; } else { if (index == 2) { __ste_Client_AddressBook0_Alias2 = value; } else { } } } } else { if (handle == 2) { if (index == 0) { __ste_Client_AddressBook1_Alias0 = value; } else { if (index == 1) { __ste_Client_AddressBook1_Alias1 = value; } else { if (index == 2) { __ste_Client_AddressBook1_Alias2 = value; } else { } } } } else { if (handle == 3) { if (index == 0) { __ste_Client_AddressBook2_Alias0 = value; } else { if (index == 1) { __ste_Client_AddressBook2_Alias1 = value; } else { if (index == 2) { __ste_Client_AddressBook2_Alias2 = value; } else { } } } } else { } } } return; } } int __ste_Client_AddressBook0_Address0 = 0; int __ste_Client_AddressBook0_Address1 = 0; int __ste_Client_AddressBook0_Address2 = 0; int __ste_Client_AddressBook1_Address0 = 0; int __ste_Client_AddressBook1_Address1 = 0; int __ste_Client_AddressBook1_Address2 = 0; int __ste_Client_AddressBook2_Address0 = 0; int __ste_Client_AddressBook2_Address1 = 0; int __ste_Client_AddressBook2_Address2 = 0; int getClientAddressBookAddress(int handle , int index ) { int retValue_acc ; { if (handle == 1) { if (index == 0) { retValue_acc = __ste_Client_AddressBook0_Address0; return (retValue_acc); } else { if (index == 1) { retValue_acc = __ste_Client_AddressBook0_Address1; return (retValue_acc); } else { if (index == 2) { retValue_acc = __ste_Client_AddressBook0_Address2; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } } else { if (handle == 2) { if (index == 0) { retValue_acc = __ste_Client_AddressBook1_Address0; return (retValue_acc); } else { if (index == 1) { retValue_acc = __ste_Client_AddressBook1_Address1; return (retValue_acc); } else { if (index == 2) { retValue_acc = __ste_Client_AddressBook1_Address2; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } } else { if (handle == 3) { if (index == 0) { retValue_acc = __ste_Client_AddressBook2_Address0; return (retValue_acc); } else { if (index == 1) { retValue_acc = __ste_Client_AddressBook2_Address1; return (retValue_acc); } else { if (index == 2) { retValue_acc = __ste_Client_AddressBook2_Address2; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } } else { retValue_acc = 0; return (retValue_acc); } } } return (retValue_acc); } } void setClientAddressBookAddress(int handle , int index , int value ) { { if (handle == 1) { if (index == 0) { __ste_Client_AddressBook0_Address0 = value; } else { if (index == 1) { __ste_Client_AddressBook0_Address1 = value; } else { if (index == 2) { __ste_Client_AddressBook0_Address2 = value; } else { } } } } else { if (handle == 2) { if (index == 0) { __ste_Client_AddressBook1_Address0 = value; } else { if (index == 1) { __ste_Client_AddressBook1_Address1 = value; } else { if (index == 2) { __ste_Client_AddressBook1_Address2 = value; } else { } } } } else { if (handle == 3) { if (index == 0) { __ste_Client_AddressBook2_Address0 = value; } else { if (index == 1) { __ste_Client_AddressBook2_Address1 = value; } else { if (index == 2) { __ste_Client_AddressBook2_Address2 = value; } else { } } } } else { } } } return; } } int __ste_client_autoResponse0 = 0; int __ste_client_autoResponse1 = 0; int __ste_client_autoResponse2 = 0; int getClientAutoResponse(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_client_autoResponse0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_client_autoResponse1; return (retValue_acc); } else { if (handle == 3) { retValue_acc = __ste_client_autoResponse2; return (retValue_acc); } else { retValue_acc = -1; return (retValue_acc); } } } return (retValue_acc); } } void setClientAutoResponse(int handle , int value ) { { if (handle == 1) { __ste_client_autoResponse0 = value; } else { if (handle == 2) { __ste_client_autoResponse1 = value; } else { if (handle == 3) { __ste_client_autoResponse2 = value; } else { } } } return; } } int __ste_client_privateKey0 = 0; int __ste_client_privateKey1 = 0; int __ste_client_privateKey2 = 0; int getClientPrivateKey(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_client_privateKey0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_client_privateKey1; return (retValue_acc); } else { if (handle == 3) { retValue_acc = __ste_client_privateKey2; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } return (retValue_acc); } } void setClientPrivateKey(int handle , int value ) { { if (handle == 1) { __ste_client_privateKey0 = value; } else { if (handle == 2) { __ste_client_privateKey1 = value; } else { if (handle == 3) { __ste_client_privateKey2 = value; } else { } } } return; } } int __ste_ClientKeyring_size0 = 0; int __ste_ClientKeyring_size1 = 0; int __ste_ClientKeyring_size2 = 0; int getClientKeyringSize(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_ClientKeyring_size0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_ClientKeyring_size1; return (retValue_acc); } else { if (handle == 3) { retValue_acc = __ste_ClientKeyring_size2; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } return (retValue_acc); } } void setClientKeyringSize(int handle , int value ) { { if (handle == 1) { __ste_ClientKeyring_size0 = value; } else { if (handle == 2) { __ste_ClientKeyring_size1 = value; } else { if (handle == 3) { __ste_ClientKeyring_size2 = value; } else { } } } return; } } int createClientKeyringEntry(int handle ) { int retValue_acc ; int size ; int tmp ; int __cil_tmp5 ; { { tmp = getClientKeyringSize(handle); size = tmp; } if (size < 2) { { __cil_tmp5 = size + 1; setClientKeyringSize(handle, __cil_tmp5); retValue_acc = size + 1; } return (retValue_acc); } else { retValue_acc = -1; return (retValue_acc); } return (retValue_acc); } } int __ste_Client_Keyring0_User0 = 0; int __ste_Client_Keyring0_User1 = 0; int __ste_Client_Keyring0_User2 = 0; int __ste_Client_Keyring1_User0 = 0; int __ste_Client_Keyring1_User1 = 0; int __ste_Client_Keyring1_User2 = 0; int __ste_Client_Keyring2_User0 = 0; int __ste_Client_Keyring2_User1 = 0; int __ste_Client_Keyring2_User2 = 0; int getClientKeyringUser(int handle , int index ) { int retValue_acc ; { if (handle == 1) { if (index == 0) { retValue_acc = __ste_Client_Keyring0_User0; return (retValue_acc); } else { if (index == 1) { retValue_acc = __ste_Client_Keyring0_User1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } else { if (handle == 2) { if (index == 0) { retValue_acc = __ste_Client_Keyring1_User0; return (retValue_acc); } else { if (index == 1) { retValue_acc = __ste_Client_Keyring1_User1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } else { if (handle == 3) { if (index == 0) { retValue_acc = __ste_Client_Keyring2_User0; return (retValue_acc); } else { if (index == 1) { retValue_acc = __ste_Client_Keyring2_User1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } else { retValue_acc = 0; return (retValue_acc); } } } return (retValue_acc); } } void setClientKeyringUser(int handle , int index , int value ) { { if (handle == 1) { if (index == 0) { __ste_Client_Keyring0_User0 = value; } else { if (index == 1) { __ste_Client_Keyring0_User1 = value; } else { } } } else { if (handle == 2) { if (index == 0) { __ste_Client_Keyring1_User0 = value; } else { if (index == 1) { __ste_Client_Keyring1_User1 = value; } else { } } } else { if (handle == 3) { if (index == 0) { __ste_Client_Keyring2_User0 = value; } else { if (index == 1) { __ste_Client_Keyring2_User1 = value; } else { } } } else { } } } return; } } int __ste_Client_Keyring0_PublicKey0 = 0; int __ste_Client_Keyring0_PublicKey1 = 0; int __ste_Client_Keyring0_PublicKey2 = 0; int __ste_Client_Keyring1_PublicKey0 = 0; int __ste_Client_Keyring1_PublicKey1 = 0; int __ste_Client_Keyring1_PublicKey2 = 0; int __ste_Client_Keyring2_PublicKey0 = 0; int __ste_Client_Keyring2_PublicKey1 = 0; int __ste_Client_Keyring2_PublicKey2 = 0; int getClientKeyringPublicKey(int handle , int index ) { int retValue_acc ; { if (handle == 1) { if (index == 0) { retValue_acc = __ste_Client_Keyring0_PublicKey0; return (retValue_acc); } else { if (index == 1) { retValue_acc = __ste_Client_Keyring0_PublicKey1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } else { if (handle == 2) { if (index == 0) { retValue_acc = __ste_Client_Keyring1_PublicKey0; return (retValue_acc); } else { if (index == 1) { retValue_acc = __ste_Client_Keyring1_PublicKey1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } else { if (handle == 3) { if (index == 0) { retValue_acc = __ste_Client_Keyring2_PublicKey0; return (retValue_acc); } else { if (index == 1) { retValue_acc = __ste_Client_Keyring2_PublicKey1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } else { retValue_acc = 0; return (retValue_acc); } } } return (retValue_acc); } } int findPublicKey(int handle , int userid ) { int retValue_acc ; { if (handle == 1) { if (userid == __ste_Client_Keyring0_User0) { retValue_acc = __ste_Client_Keyring0_PublicKey0; return (retValue_acc); } else { if (userid == __ste_Client_Keyring0_User1) { retValue_acc = __ste_Client_Keyring0_PublicKey1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } else { if (handle == 2) { if (userid == __ste_Client_Keyring1_User0) { retValue_acc = __ste_Client_Keyring1_PublicKey0; return (retValue_acc); } else { if (userid == __ste_Client_Keyring1_User1) { retValue_acc = __ste_Client_Keyring1_PublicKey1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } else { if (handle == 3) { if (userid == __ste_Client_Keyring2_User0) { retValue_acc = __ste_Client_Keyring2_PublicKey0; return (retValue_acc); } else { if (userid == __ste_Client_Keyring2_User1) { retValue_acc = __ste_Client_Keyring2_PublicKey1; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } else { retValue_acc = 0; return (retValue_acc); } } } return (retValue_acc); } } void setClientKeyringPublicKey(int handle , int index , int value ) { { if (handle == 1) { if (index == 0) { __ste_Client_Keyring0_PublicKey0 = value; } else { if (index == 1) { __ste_Client_Keyring0_PublicKey1 = value; } else { } } } else { if (handle == 2) { if (index == 0) { __ste_Client_Keyring1_PublicKey0 = value; } else { if (index == 1) { __ste_Client_Keyring1_PublicKey1 = value; } else { } } } else { if (handle == 3) { if (index == 0) { __ste_Client_Keyring2_PublicKey0 = value; } else { if (index == 1) { __ste_Client_Keyring2_PublicKey1 = value; } else { } } } else { } } } return; } } int __ste_client_forwardReceiver0 = 0; int __ste_client_forwardReceiver1 = 0; int __ste_client_forwardReceiver2 = 0; int __ste_client_forwardReceiver3 = 0; int getClientForwardReceiver(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_client_forwardReceiver0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_client_forwardReceiver1; return (retValue_acc); } else { if (handle == 3) { retValue_acc = __ste_client_forwardReceiver2; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } return (retValue_acc); } } void setClientForwardReceiver(int handle , int value ) { { if (handle == 1) { __ste_client_forwardReceiver0 = value; } else { if (handle == 2) { __ste_client_forwardReceiver1 = value; } else { if (handle == 3) { __ste_client_forwardReceiver2 = value; } else { } } } return; } } int __ste_client_idCounter0 = 0; int __ste_client_idCounter1 = 0; int __ste_client_idCounter2 = 0; int getClientId(int handle ) { int retValue_acc ; { if (handle == 1) { retValue_acc = __ste_client_idCounter0; return (retValue_acc); } else { if (handle == 2) { retValue_acc = __ste_client_idCounter1; return (retValue_acc); } else { if (handle == 3) { retValue_acc = __ste_client_idCounter2; return (retValue_acc); } else { retValue_acc = 0; return (retValue_acc); } } } return (retValue_acc); } } void setClientId(int handle , int value ) { { if (handle == 1) { __ste_client_idCounter0 = value; } else { if (handle == 2) { __ste_client_idCounter1 = value; } else { if (handle == 3) { __ste_client_idCounter2 = value; } else { } } } return; } } #pragma merger(0,"Util.i","") int prompt(char *msg ) ; int prompt(char *msg ) { int retValue_acc ; int retval ; char const * __restrict __cil_tmp4 ; { { __cil_tmp4 = (char const * __restrict )"%s\n"; printf(__cil_tmp4, msg); retValue_acc = retval; } return (retValue_acc); return (retValue_acc); } } #pragma merger(0,"Client.i","") void queue(int client , int msg ) ; void mail(int client , int msg ) ; void deliver(int client , int msg ) ; void incoming(int client , int msg ) ; int createClient(char *name ) ; int isKeyPairValid(int publicKey , int privateKey ) ; void sendToAddressBook(int client , int msg ) ; void sign(int client , int msg ) ; void forward(int client , int msg ) ; void verify(int client , int msg ) ; int queue_empty = 1; int queued_message ; int queued_client ; void mail(int client , int msg ) { int tmp ; { { puts("mail sent"); tmp = getEmailTo(msg); incoming(tmp, msg); } return; } } void outgoing__wrappee__Keys(int client , int msg ) { int tmp ; { { tmp = getClientId(client); setEmailFrom(msg, tmp); mail(client, msg); } return; } } void outgoing__wrappee__Encrypt(int client , int msg ) { int receiver ; int tmp ; int pubkey ; int tmp___0 ; { { tmp = getEmailTo(msg); receiver = tmp; tmp___0 = findPublicKey(client, receiver); pubkey = tmp___0; } if (pubkey) { { setEmailEncryptionKey(msg, pubkey); setEmailIsEncrypted(msg, 1); } } else { } { outgoing__wrappee__Keys(client, msg); } return; } } void outgoing__wrappee__AddressBook(int client , int msg ) { int size ; int tmp ; int receiver ; int tmp___0 ; int second ; int tmp___1 ; int tmp___2 ; { { tmp = getClientAddressBookSize(client); size = tmp; } if (size) { { sendToAddressBook(client, msg); puts("sending to alias in address book\n"); tmp___0 = getEmailTo(msg); receiver = tmp___0; puts("sending to second receipient\n"); tmp___1 = getClientAddressBookAddress(client, 1); second = tmp___1; setEmailTo(msg, second); outgoing__wrappee__Encrypt(client, msg); tmp___2 = getClientAddressBookAddress(client, 0); setEmailTo(msg, tmp___2); outgoing__wrappee__Encrypt(client, msg); } } else { { outgoing__wrappee__Encrypt(client, msg); } } return; } } void outgoing(int client , int msg ) { { { sign(client, msg); outgoing__wrappee__AddressBook(client, msg); } return; } } void deliver(int client , int msg ) { { { puts("mail delivered\n"); } return; } } void incoming__wrappee__Sign(int client , int msg ) { { { deliver(client, msg); } return; } } void incoming__wrappee__Forward(int client , int msg ) { int fwreceiver ; int tmp ; { { incoming__wrappee__Sign(client, msg); tmp = getClientForwardReceiver(client); fwreceiver = tmp; } if (fwreceiver) { { setEmailTo(msg, fwreceiver); forward(client, msg); } } else { } return; } } void incoming__wrappee__Verify(int client , int msg ) { { { verify(client, msg); incoming__wrappee__Forward(client, msg); } return; } } void incoming(int client , int msg ) { int privkey ; int tmp ; int tmp___0 ; int tmp___1 ; int tmp___2 ; { { tmp = getClientPrivateKey(client); privkey = tmp; } if (privkey) { { tmp___0 = isEncrypted(msg); } if (tmp___0) { { tmp___1 = getEmailEncryptionKey(msg); tmp___2 = isKeyPairValid(tmp___1, privkey); } if (tmp___2) { { setEmailIsEncrypted(msg, 0); setEmailEncryptionKey(msg, 0); } } else { } } else { } } else { } { incoming__wrappee__Verify(client, msg); } return; } } int createClient(char *name ) { int retValue_acc ; int client ; int tmp ; { { tmp = initClient(); client = tmp; retValue_acc = client; } return (retValue_acc); return (retValue_acc); } } void sendEmail(int sender , int receiver ) { int email ; int tmp ; { { tmp = createEmail(0, receiver); email = tmp; outgoing(sender, email); } return; } } void queue(int client , int msg ) { { queue_empty = 0; queued_message = msg; queued_client = client; return; } } int is_queue_empty(void) { int retValue_acc ; { retValue_acc = queue_empty; return (retValue_acc); return (retValue_acc); } } int get_queued_client(void) { int retValue_acc ; { retValue_acc = queued_client; return (retValue_acc); return (retValue_acc); } } int get_queued_email(void) { int retValue_acc ; { retValue_acc = queued_message; return (retValue_acc); return (retValue_acc); } } int isKeyPairValid(int publicKey , int privateKey ) { int retValue_acc ; char const * __restrict __cil_tmp4 ; { { __cil_tmp4 = (char const * __restrict )"keypair valid %d %d"; printf(__cil_tmp4, publicKey, privateKey); } if (! publicKey) { retValue_acc = 0; return (retValue_acc); } else { if (! privateKey) { retValue_acc = 0; return (retValue_acc); } else { } } retValue_acc = privateKey == publicKey; return (retValue_acc); return (retValue_acc); } } void generateKeyPair(int client , int seed ) { { { setClientPrivateKey(client, seed); } return; } } void sendToAddressBook(int client , int msg ) { { return; } } void sign(int client , int msg ) { int privkey ; int tmp ; { { tmp = getClientPrivateKey(client); privkey = tmp; } if (! privkey) { return; } else { } { setEmailIsSigned(msg, 1); setEmailSignKey(msg, privkey); } return; } } void forward(int client , int msg ) { { { puts("Forwarding message.\n"); printMail(msg); queue(client, msg); } return; } } void verify(int client , int msg ) { int __utac__ad__arg1 ; int tmp ; int tmp___0 ; int pubkey ; int tmp___1 ; int tmp___2 ; int tmp___3 ; int tmp___4 ; { { __utac__ad__arg1 = msg; __utac_acc__EncryptVerify_spec__1(__utac__ad__arg1); tmp = isReadable(msg); } if (tmp) { { tmp___0 = isSigned(msg); } if (tmp___0) { } else { return; } } else { return; } { tmp___1 = getEmailFrom(msg); tmp___2 = findPublicKey(client, tmp___1); pubkey = tmp___2; } if (pubkey) { { tmp___3 = getEmailSignKey(msg); tmp___4 = isKeyPairValid(tmp___3, pubkey); } if (tmp___4) { { setEmailIsSignatureVerified(msg, 1); } } else { } } else { } return; } } #pragma merger(0,"scenario.i","") void test(void) { int op1 ; int op2 ; int op3 ; int op4 ; int op5 ; int op6 ; int op7 ; int op8 ; int op9 ; int op10 ; int op11 ; int splverifierCounter ; int tmp ; int tmp___0 ; int tmp___1 ; int tmp___2 ; int tmp___3 ; int tmp___4 ; int tmp___5 ; int tmp___6 ; int tmp___7 ; int tmp___8 ; int tmp___9 ; { op1 = 0; op2 = 0; op3 = 0; op4 = 0; op5 = 0; op6 = 0; op7 = 0; op8 = 0; op9 = 0; op10 = 0; op11 = 0; splverifierCounter = 0; { while (1) { while_3_continue: /* CIL Label */ ; if (splverifierCounter < 4) { } else { goto while_3_break; } splverifierCounter = splverifierCounter + 1; if (! op1) { { tmp___9 = __VERIFIER_nondet_int(); } if (tmp___9) { { bobKeyAdd(); op1 = 1; } } else { goto _L___8; } } else { _L___8: /* CIL Label */ if (! op2) { { tmp___8 = __VERIFIER_nondet_int(); } if (tmp___8) { op2 = 1; } else { goto _L___7; } } else { _L___7: /* CIL Label */ if (! op3) { { tmp___7 = __VERIFIER_nondet_int(); } if (tmp___7) { { rjhDeletePrivateKey(); op3 = 1; } } else { goto _L___6; } } else { _L___6: /* CIL Label */ if (! op4) { { tmp___6 = __VERIFIER_nondet_int(); } if (tmp___6) { { rjhKeyAdd(); op4 = 1; } } else { goto _L___5; } } else { _L___5: /* CIL Label */ if (! op5) { { tmp___5 = __VERIFIER_nondet_int(); } if (tmp___5) { { chuckKeyAddRjh(); op5 = 1; } } else { goto _L___4; } } else { _L___4: /* CIL Label */ if (! op6) { { tmp___4 = __VERIFIER_nondet_int(); } if (tmp___4) { { rjhEnableForwarding(); op6 = 1; } } else { goto _L___3; } } else { _L___3: /* CIL Label */ if (! op7) { { tmp___3 = __VERIFIER_nondet_int(); } if (tmp___3) { { rjhKeyChange(); op7 = 1; } } else { goto _L___2; } } else { _L___2: /* CIL Label */ if (! op8) { { tmp___2 = __VERIFIER_nondet_int(); } if (tmp___2) { { bobSetAddressBook(); op8 = 1; } } else { goto _L___1; } } else { _L___1: /* CIL Label */ if (! op9) { { tmp___1 = __VERIFIER_nondet_int(); } if (tmp___1) { { chuckKeyAdd(); op9 = 1; } } else { goto _L___0; } } else { _L___0: /* CIL Label */ if (! op10) { { tmp___0 = __VERIFIER_nondet_int(); } if (tmp___0) { { bobKeyChange(); op10 = 1; } } else { goto _L; } } else { _L: /* CIL Label */ if (! op11) { { tmp = __VERIFIER_nondet_int(); } if (tmp) { { chuckKeyAdd(); op11 = 1; } } else { goto while_3_break; } } else { goto while_3_break; } } } } } } } } } } } } while_3_break: /* CIL Label */ ; } { bobToRjh(); } return; } }
the_stack_data/9513781.c
#include <string.h> #include <stdio.h> #include <fcntl.h> #include <dirent.h> #include <sys/stat.h> // The location of the proc filesystem. #define PROCDIR "/proc" // The file used to find the name of each process (e.g. /proc/PID/status). #define STATUSFILE "status" /* The character the name starts on in STATUSFILE, as in how many chars out. * On my system the first line in the file is something like: * Name: init * where "init" is the name of the process and there is a tab after the colon, * so the name would start on character 6. */ #define N_START_CHAR 6 /* The file in PROCDIR the command line is stored in. This file should only * have the command line, no leading chars, and all white space converted to * the following WHITESPACE character. */ #define CMDFILE "cmdline" // The character white space is converted to. #define WHITESPACE '\0' /* Takes in a char* pointing to a string contained within the name of * process. That is, in *just* the name, not in the whole command line, * if you want that use isrunningcmdline() for that (and see the wrapper). * For instance, if the command line is: * MyProg arg1 arg2 arg3 * and then isrunning("arg") is called it would return 0, or not * running. Where as isrunning("rog") would return the pid of MyProg. * Returns a negative int for error, 0 for not found and the pid if found. * Requires that PROCDIR exist and is readable. the file looked * for is /PROCDIR/{pid}/STATUSFILE, the first line of witch should contain: * Name: {name-of-program} * * Return values: * num The pid of the found process. * 0 No process containing prog was found. * -2 The call to opendir(PROCDIR) failed (No PROCDIR directory?). * -3 The call to open( PROCDIR / dent->d_name / STATUSFILE ) failed. * -4 The read from STATUSFILE to N_START_CHAR failed. */ int isrunning(char* prog) { DIR * dir; struct dirent * dent; /* The struct dirent has a member called d_type. * This is supposed to be set to the mode of the named entry; *but* this * is not consistent across platforms or version or anything else. * For instance on my system the variable * _DIRENT_HAVE_D_TYPE is defined, but every entry is set to zero, making * the use of it worse than useless. So, we don't use any entry of * dirent other than dirent->d_name. */ int i, fd; struct stat stbuf; /* This version only implements the standard stat function. * Stat64 should not be necessary, as the maximum number of processes is * the maximum value if the int type. It should not however be too hard * change it to use stat64 instead. */ char c; char statusfile[ sizeof(PROCDIR) + sizeof(STATUSFILE) + 10 // 2^32 takes 10 decimal digits. + 3 // 2 for the null and the two slashes. ]; if ((dir = opendir(PROCDIR)) == NULL) { // Try closing it anyway. closedir(dir); return -2; } // if while((dent = readdir(dir)) != NULL) { strcpy(statusfile, PROCDIR); strcat(statusfile, "/"); strcat(statusfile, dent->d_name); // stat stuff if((stat(statusfile, &stbuf) == -1) || ((stbuf.st_mode & S_IFMT) != S_IFDIR)) continue; i = sizeof(PROCDIR); while ((c = statusfile[i++]) != '\0') if(!isdigit(c)) break; if(c != '\0') continue; strcat(statusfile, "/"); strcat(statusfile, STATUSFILE); // Statusfile is now complete. if((fd = open(statusfile,O_RDONLY)) == -1) { // Close dir and file, or try. close(fd); closedir(dir); return -3; } // if for(i=0; i<N_START_CHAR; i++ ) if(read(fd, &c, 1) != 1) { // Close stuff. close(fd); closedir(dir); return -4; } // if i = 0; while(read(fd,&c,1) == 1 && c != '\n' && prog[i] != '\0' && c != EOF) { if(c == prog[i]) i++; else i = 0; } // We need to close this file nomatter what. close(fd); if(prog[i] == '\0') { closedir(dir); return atoi(dent->d_name); } // if } // while close(fd); closedir(dir); // no process found return 0; } // isrunning /* This is the int isrunningcmdline(char*) function. * It parses the /proc/PID/cmdline file, which should only contain the cmdline. * Most(all) Linux distros combine all null space in the command line and * replace it with a white space delimiter. On my system this is the null char. * This is essentially the same as isrunning except it checks the cmdline (which * includes the arguments). For instancne if: * MyProg arg1 arg2 * was running, isrunningcmdline("arg") would return the pid of MyProg, (unless * another process was found first). This is useful if you have many of the same * program running with different arguments and want to find a particular one. * * The conversion algorithm in isrunningcmdline to convert the given char* to * one with only "null" spaces is the int isspace(char) function from ctype.h * * Otherwise this function behaves the same as isrunning() above with the same * return values (except -4). */ int isrunningcmdline(char* cmd) { DIR * dir; struct dirent * dent; // See note in isrunning(). int i, fd; struct stat stbuf; // See note in isrunning(). char c, cmdfile[sizeof(PROCDIR) + sizeof(CMDFILE) + 10 //2^32 takes 10 decimal digits + 3]; //2 for the null and the two slashes if ((dir = opendir(PROCDIR)) == NULL) { // Try closing it anyway. closedir(dir); return -2; } // if while((dent = readdir(dir)) != NULL) { strcpy(cmdfile, PROCDIR); strcat(cmdfile, "/"); strcat(cmdfile, dent->d_name); // stat stuff if((stat(cmdfile, &stbuf) == -1) || ((stbuf.st_mode & S_IFMT) != S_IFDIR)) continue; i = sizeof(PROCDIR); while ((c = cmdfile[i++]) != '\0') if(!isdigit(c)) break; if(c != '\0') continue; strcat(cmdfile, "/"); strcat(cmdfile, CMDFILE); // Cmdfile is now complete. if((fd = open(cmdfile,O_RDONLY)) == -1) { // Close dir and file, or try. close(fd); closedir(dir); return -3; } // if i = 0; while(read(fd,&c,1) == 1 && c != '\n' && cmd[i] != '\0' && c != EOF) { if(c == cmd[i] || (c == WHITESPACE && isspace(cmd[i]))) i++; else i = 0; } // We need to close this file no matter what. close(fd); // Because this is the cmd line we need to check for ourselves. if(cmd[i] == '\0' && atoi(dent->d_name) != getpid()) { closedir(dir); return atoi(dent->d_name); } // if } // while close(fd); closedir(dir); // No process found. return 0; } // isrunningcmdline
the_stack_data/184518972.c
#include <wchar.h> size_t wcsnlen(const wchar_t* s, size_t n) { const wchar_t* z = wmemchr(s, 0, n); if (z) n = z - s; return n; }
the_stack_data/90766850.c
/*Exercise 3 - Repetition Write a C program to calculate the sum of the numbers from 1 to n. Where n is a keyboard input. e.g. n -> 100 sum = 1+2+3+....+ 99+100 = 5050 n -> 1- sum = 1+2+3+...+10 = 55 */ #include <stdio.h> //function main begins program execution int main() { //declaring variables int num , count = 1 , total = 0; //take user inputs printf("Enter a number : "); scanf("%d", &num); while(count <= num) { total += count; count++; } printf("Total is %d\n", total); return 0; }
the_stack_data/168892773.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strncmp.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: psprawka <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/07/04 12:23:28 by psprawka #+# #+# */ /* Updated: 2018/06/17 13:41:27 by psprawka ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdio.h> int ft_strncmp(char *s1, char *s2, unsigned int n) { unsigned int i; i = 0; while ((s1[i] || s2[i]) && (i < n)) { if ((s1[i] < s2[i]) || (s1[i] > s2[i])) return (s1[i] - s2[i]); i++; } return (0); }
the_stack_data/107980.c
/* ** EPITECH PROJECT, 2017 ** CPool_Day06_2017 ** File description: ** task14 */ int my_str_isprintable(char const *str) { int i = 0; if (str[i] == '\0') return (1); while (str[i] != '\0') { if (str[i] >= 32 && str[i] <= 126) i++; else return (0); } return (1); }
the_stack_data/87335.c
#include <stdio.h> #include <stdint.h> #include <stdlib.h> typedef int64_t i64; i64 hdiv(i64 a, i64 b) { return (a+b-1) / b; } int main() { i64 n, nq; scanf("%lu %lu", &n, &nq); i64* A = malloc(sizeof(i64) * (n + n+1)); i64* skip = A + n; for(i64 i = 0; i < n; i++) scanf("%lu", A+i); i64 skipSize = 1; skip[0] = 0; for(int i = 0; i < n; i++) { if(A[i] == 1) skip[skipSize-1]++; else { skip[skipSize] = 1; A[skipSize-1] = A[i]; skipSize++; } } /*printf("A: "); for(i64 i = 0; i < skipSize-1; i++) printf("%ld ", A[i]); printf("\n"); printf("skip: "); for(i64 i = 0; i < skipSize; i++) printf("%ld ", skip[i]); printf("\n");*/ for(i64 iq = 0; iq < nq; iq++) { i64 cc; scanf("%ld", &cc); i64 res = skip[0] * cc; i64 l = skip[0]; for(i64 i = 0; i < skipSize-1; i++) { const i64 d = hdiv(cc, A[i]); //res += d; res += d*skip[i+1]; l += skip[i+1]; cc = d; if(cc == 1) { res += n - l; break; } } printf("%ld\n", res); } }
the_stack_data/9512409.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_n1 = -1; static integer c__0 = 0; static real c_b63 = 0.f; static integer c__1 = 1; static real c_b84 = 1.f; /* > \brief \b SGESDD */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download SGESDD + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/sgesdd. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/sgesdd. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/sgesdd. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE SGESDD( JOBZ, M, N, A, LDA, S, U, LDU, VT, LDVT, */ /* WORK, LWORK, IWORK, INFO ) */ /* CHARACTER JOBZ */ /* INTEGER INFO, LDA, LDU, LDVT, LWORK, M, N */ /* INTEGER IWORK( * ) */ /* REAL A( LDA, * ), S( * ), U( LDU, * ), */ /* $ VT( LDVT, * ), WORK( * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > SGESDD computes the singular value decomposition (SVD) of a real */ /* > M-by-N matrix A, optionally computing the left and right singular */ /* > vectors. If singular vectors are desired, it uses a */ /* > divide-and-conquer algorithm. */ /* > */ /* > The SVD is written */ /* > */ /* > A = U * SIGMA * transpose(V) */ /* > */ /* > where SIGMA is an M-by-N matrix which is zero except for its */ /* > f2cmin(m,n) diagonal elements, U is an M-by-M orthogonal matrix, and */ /* > V is an N-by-N orthogonal matrix. The diagonal elements of SIGMA */ /* > are the singular values of A; they are real and non-negative, and */ /* > are returned in descending order. The first f2cmin(m,n) columns of */ /* > U and V are the left and right singular vectors of A. */ /* > */ /* > Note that the routine returns VT = V**T, not V. */ /* > */ /* > The divide and conquer algorithm makes very mild assumptions about */ /* > floating point arithmetic. It will work on machines with a guard */ /* > digit in add/subtract, or on those binary machines without guard */ /* > digits which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or */ /* > Cray-2. It could conceivably fail on hexadecimal or decimal machines */ /* > without guard digits, but we know of none. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] JOBZ */ /* > \verbatim */ /* > JOBZ is CHARACTER*1 */ /* > Specifies options for computing all or part of the matrix U: */ /* > = 'A': all M columns of U and all N rows of V**T are */ /* > returned in the arrays U and VT; */ /* > = 'S': the first f2cmin(M,N) columns of U and the first */ /* > f2cmin(M,N) rows of V**T are returned in the arrays U */ /* > and VT; */ /* > = 'O': If M >= N, the first N columns of U are overwritten */ /* > on the array A and all rows of V**T are returned in */ /* > the array VT; */ /* > otherwise, all columns of U are returned in the */ /* > array U and the first M rows of V**T are overwritten */ /* > in the array A; */ /* > = 'N': no columns of U or rows of V**T are computed. */ /* > \endverbatim */ /* > */ /* > \param[in] M */ /* > \verbatim */ /* > M is INTEGER */ /* > The number of rows of the input matrix A. M >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The number of columns of the input matrix A. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in,out] A */ /* > \verbatim */ /* > A is REAL array, dimension (LDA,N) */ /* > On entry, the M-by-N matrix A. */ /* > On exit, */ /* > if JOBZ = 'O', A is overwritten with the first N columns */ /* > of U (the left singular vectors, stored */ /* > columnwise) if M >= N; */ /* > A is overwritten with the first M rows */ /* > of V**T (the right singular vectors, stored */ /* > rowwise) otherwise. */ /* > if JOBZ .ne. 'O', the contents of A are destroyed. */ /* > \endverbatim */ /* > */ /* > \param[in] LDA */ /* > \verbatim */ /* > LDA is INTEGER */ /* > The leading dimension of the array A. LDA >= f2cmax(1,M). */ /* > \endverbatim */ /* > */ /* > \param[out] S */ /* > \verbatim */ /* > S is REAL array, dimension (f2cmin(M,N)) */ /* > The singular values of A, sorted so that S(i) >= S(i+1). */ /* > \endverbatim */ /* > */ /* > \param[out] U */ /* > \verbatim */ /* > U is REAL array, dimension (LDU,UCOL) */ /* > UCOL = M if JOBZ = 'A' or JOBZ = 'O' and M < N; */ /* > UCOL = f2cmin(M,N) if JOBZ = 'S'. */ /* > If JOBZ = 'A' or JOBZ = 'O' and M < N, U contains the M-by-M */ /* > orthogonal matrix U; */ /* > if JOBZ = 'S', U contains the first f2cmin(M,N) columns of U */ /* > (the left singular vectors, stored columnwise); */ /* > if JOBZ = 'O' and M >= N, or JOBZ = 'N', U is not referenced. */ /* > \endverbatim */ /* > */ /* > \param[in] LDU */ /* > \verbatim */ /* > LDU is INTEGER */ /* > The leading dimension of the array U. LDU >= 1; if */ /* > JOBZ = 'S' or 'A' or JOBZ = 'O' and M < N, LDU >= M. */ /* > \endverbatim */ /* > */ /* > \param[out] VT */ /* > \verbatim */ /* > VT is REAL array, dimension (LDVT,N) */ /* > If JOBZ = 'A' or JOBZ = 'O' and M >= N, VT contains the */ /* > N-by-N orthogonal matrix V**T; */ /* > if JOBZ = 'S', VT contains the first f2cmin(M,N) rows of */ /* > V**T (the right singular vectors, stored rowwise); */ /* > if JOBZ = 'O' and M < N, or JOBZ = 'N', VT is not referenced. */ /* > \endverbatim */ /* > */ /* > \param[in] LDVT */ /* > \verbatim */ /* > LDVT is INTEGER */ /* > The leading dimension of the array VT. LDVT >= 1; */ /* > if JOBZ = 'A' or JOBZ = 'O' and M >= N, LDVT >= N; */ /* > if JOBZ = 'S', LDVT >= f2cmin(M,N). */ /* > \endverbatim */ /* > */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is REAL 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. LWORK >= 1. */ /* > If LWORK = -1, a workspace query is assumed. The optimal */ /* > size for the WORK array is calculated and stored in WORK(1), */ /* > and no other work except argument checking is performed. */ /* > */ /* > Let mx = f2cmax(M,N) and mn = f2cmin(M,N). */ /* > If JOBZ = 'N', LWORK >= 3*mn + f2cmax( mx, 7*mn ). */ /* > If JOBZ = 'O', LWORK >= 3*mn + f2cmax( mx, 5*mn*mn + 4*mn ). */ /* > If JOBZ = 'S', LWORK >= 4*mn*mn + 7*mn. */ /* > If JOBZ = 'A', LWORK >= 4*mn*mn + 6*mn + mx. */ /* > These are not tight minimums in all cases; see comments inside code. */ /* > For good performance, LWORK should generally be larger; */ /* > a query is recommended. */ /* > \endverbatim */ /* > */ /* > \param[out] IWORK */ /* > \verbatim */ /* > IWORK is INTEGER array, dimension (8*f2cmin(M,N)) */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit. */ /* > < 0: if INFO = -i, the i-th argument had an illegal value. */ /* > > 0: SBDSDC did not converge, updating process failed. */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date June 2016 */ /* > \ingroup realGEsing */ /* > \par Contributors: */ /* ================== */ /* > */ /* > Ming Gu and Huan Ren, Computer Science Division, University of */ /* > California at Berkeley, USA */ /* > */ /* ===================================================================== */ /* Subroutine */ int sgesdd_(char *jobz, integer *m, integer *n, real *a, integer *lda, real *s, real *u, integer *ldu, real *vt, integer *ldvt, real *work, integer *lwork, integer *iwork, integer *info) { /* System generated locals */ integer a_dim1, a_offset, u_dim1, u_offset, vt_dim1, vt_offset, i__1, i__2, i__3; /* Local variables */ integer lwork_sgelqf_mn__, lwork_sgeqrf_mn__, iscl, lwork_sorglq_mn__, lwork_sorglq_nn__; real anrm; integer idum[1], ierr, itau, lwork_sorgqr_mm__, lwork_sorgqr_mn__, lwork_sormbr_qln_mm__, lwork_sormbr_qln_mn__, lwork_sormbr_qln_nn__, lwork_sormbr_prt_mm__, lwork_sormbr_prt_mn__, lwork_sormbr_prt_nn__, i__; extern logical lsame_(char *, char *); integer chunk; extern /* Subroutine */ int sgemm_(char *, char *, integer *, integer *, integer *, real *, real *, integer *, real *, integer *, real *, real *, integer *); integer minmn, wrkbl, itaup, itauq, mnthr; logical wntqa; integer nwork; logical wntqn, wntqo, wntqs; integer ie, il, ir, bdspac, iu, lwork_sorgbr_p_mm__; extern /* Subroutine */ int sbdsdc_(char *, char *, integer *, real *, real *, real *, integer *, real *, integer *, real *, integer *, real *, integer *, integer *); integer lwork_sorgbr_q_nn__; extern /* Subroutine */ int sgebrd_(integer *, integer *, real *, integer *, real *, real *, real *, real *, real *, integer *, integer *); extern real slamch_(char *), slange_(char *, integer *, integer *, real *, integer *, real *); extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen); real bignum; extern /* Subroutine */ int sgelqf_(integer *, integer *, real *, integer *, real *, real *, integer *, integer *), slascl_(char *, integer *, integer *, real *, real *, integer *, integer *, real *, integer *, integer *), sgeqrf_(integer *, integer *, real *, integer *, real *, real *, integer *, integer *), slacpy_(char *, integer *, integer *, real *, integer *, real *, integer *), slaset_(char *, integer *, integer *, real *, real *, real *, integer *); extern logical sisnan_(real *); extern /* Subroutine */ int sorgbr_(char *, integer *, integer *, integer *, real *, integer *, real *, real *, integer *, integer *); integer ldwrkl; extern /* Subroutine */ int sormbr_(char *, char *, char *, integer *, integer *, integer *, real *, integer *, real *, real *, integer * , real *, integer *, integer *); integer ldwrkr, minwrk, ldwrku, maxwrk; extern /* Subroutine */ int sorglq_(integer *, integer *, integer *, real *, integer *, real *, real *, integer *, integer *); integer ldwkvt; real smlnum; logical wntqas; extern /* Subroutine */ int sorgqr_(integer *, integer *, integer *, real *, integer *, real *, real *, integer *, integer *); logical lquery; integer blk; real dum[1], eps; integer ivt, lwork_sgebrd_mm__, lwork_sgebrd_mn__, lwork_sgebrd_nn__; /* -- LAPACK driver 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..-- */ /* June 2016 */ /* ===================================================================== */ /* Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1 * 1; a -= a_offset; --s; u_dim1 = *ldu; u_offset = 1 + u_dim1 * 1; u -= u_offset; vt_dim1 = *ldvt; vt_offset = 1 + vt_dim1 * 1; vt -= vt_offset; --work; --iwork; /* Function Body */ *info = 0; minmn = f2cmin(*m,*n); wntqa = lsame_(jobz, "A"); wntqs = lsame_(jobz, "S"); wntqas = wntqa || wntqs; wntqo = lsame_(jobz, "O"); wntqn = lsame_(jobz, "N"); lquery = *lwork == -1; if (! (wntqa || wntqs || wntqo || wntqn)) { *info = -1; } else if (*m < 0) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < f2cmax(1,*m)) { *info = -5; } else if (*ldu < 1 || wntqas && *ldu < *m || wntqo && *m < *n && *ldu < * m) { *info = -8; } else if (*ldvt < 1 || wntqa && *ldvt < *n || wntqs && *ldvt < minmn || wntqo && *m >= *n && *ldvt < *n) { *info = -10; } /* Compute workspace */ /* Note: Comments in the code beginning "Workspace:" describe the */ /* minimal amount of workspace allocated at that point in the code, */ /* as well as the preferred amount for good performance. */ /* NB refers to the optimal block size for the immediately */ /* following subroutine, as returned by ILAENV. */ if (*info == 0) { minwrk = 1; maxwrk = 1; bdspac = 0; mnthr = (integer) (minmn * 11.f / 6.f); if (*m >= *n && minmn > 0) { /* Compute space needed for SBDSDC */ if (wntqn) { /* sbdsdc needs only 4*N (or 6*N for uplo=L for LAPACK <= 3.6) */ /* keep 7*N for backwards compatibility. */ bdspac = *n * 7; } else { bdspac = *n * 3 * *n + (*n << 2); } /* Compute space preferred for each routine */ sgebrd_(m, n, dum, m, dum, dum, dum, dum, dum, &c_n1, &ierr); lwork_sgebrd_mn__ = (integer) dum[0]; sgebrd_(n, n, dum, n, dum, dum, dum, dum, dum, &c_n1, &ierr); lwork_sgebrd_nn__ = (integer) dum[0]; sgeqrf_(m, n, dum, m, dum, dum, &c_n1, &ierr); lwork_sgeqrf_mn__ = (integer) dum[0]; sorgbr_("Q", n, n, n, dum, n, dum, dum, &c_n1, &ierr); lwork_sorgbr_q_nn__ = (integer) dum[0]; sorgqr_(m, m, n, dum, m, dum, dum, &c_n1, &ierr); lwork_sorgqr_mm__ = (integer) dum[0]; sorgqr_(m, n, n, dum, m, dum, dum, &c_n1, &ierr); lwork_sorgqr_mn__ = (integer) dum[0]; sormbr_("P", "R", "T", n, n, n, dum, n, dum, dum, n, dum, &c_n1, & ierr); lwork_sormbr_prt_nn__ = (integer) dum[0]; sormbr_("Q", "L", "N", n, n, n, dum, n, dum, dum, n, dum, &c_n1, & ierr); lwork_sormbr_qln_nn__ = (integer) dum[0]; sormbr_("Q", "L", "N", m, n, n, dum, m, dum, dum, m, dum, &c_n1, & ierr); lwork_sormbr_qln_mn__ = (integer) dum[0]; sormbr_("Q", "L", "N", m, m, n, dum, m, dum, dum, m, dum, &c_n1, & ierr); lwork_sormbr_qln_mm__ = (integer) dum[0]; if (*m >= mnthr) { if (wntqn) { /* Path 1 (M >> N, JOBZ='N') */ wrkbl = *n + lwork_sgeqrf_mn__; /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sgebrd_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *n; maxwrk = f2cmax(i__1,i__2); minwrk = bdspac + *n; } else if (wntqo) { /* Path 2 (M >> N, JOBZ='O') */ wrkbl = *n + lwork_sgeqrf_mn__; /* Computing MAX */ i__1 = wrkbl, i__2 = *n + lwork_sorgqr_mn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sgebrd_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sormbr_qln_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sormbr_prt_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + bdspac; wrkbl = f2cmax(i__1,i__2); maxwrk = wrkbl + (*n << 1) * *n; minwrk = bdspac + (*n << 1) * *n + *n * 3; } else if (wntqs) { /* Path 3 (M >> N, JOBZ='S') */ wrkbl = *n + lwork_sgeqrf_mn__; /* Computing MAX */ i__1 = wrkbl, i__2 = *n + lwork_sorgqr_mn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sgebrd_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sormbr_qln_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sormbr_prt_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + bdspac; wrkbl = f2cmax(i__1,i__2); maxwrk = wrkbl + *n * *n; minwrk = bdspac + *n * *n + *n * 3; } else if (wntqa) { /* Path 4 (M >> N, JOBZ='A') */ wrkbl = *n + lwork_sgeqrf_mn__; /* Computing MAX */ i__1 = wrkbl, i__2 = *n + lwork_sorgqr_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sgebrd_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sormbr_qln_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sormbr_prt_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + bdspac; wrkbl = f2cmax(i__1,i__2); maxwrk = wrkbl + *n * *n; /* Computing MAX */ i__1 = *n * 3 + bdspac, i__2 = *n + *m; minwrk = *n * *n + f2cmax(i__1,i__2); } } else { /* Path 5 (M >= N, but not much larger) */ wrkbl = *n * 3 + lwork_sgebrd_mn__; if (wntqn) { /* Path 5n (M >= N, jobz='N') */ /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + bdspac; maxwrk = f2cmax(i__1,i__2); minwrk = *n * 3 + f2cmax(*m,bdspac); } else if (wntqo) { /* Path 5o (M >= N, jobz='O') */ /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sormbr_prt_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sormbr_qln_mn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + bdspac; wrkbl = f2cmax(i__1,i__2); maxwrk = wrkbl + *m * *n; /* Computing MAX */ i__1 = *m, i__2 = *n * *n + bdspac; minwrk = *n * 3 + f2cmax(i__1,i__2); } else if (wntqs) { /* Path 5s (M >= N, jobz='S') */ /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sormbr_qln_mn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sormbr_prt_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + bdspac; maxwrk = f2cmax(i__1,i__2); minwrk = *n * 3 + f2cmax(*m,bdspac); } else if (wntqa) { /* Path 5a (M >= N, jobz='A') */ /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sormbr_qln_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + lwork_sormbr_prt_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *n * 3 + bdspac; maxwrk = f2cmax(i__1,i__2); minwrk = *n * 3 + f2cmax(*m,bdspac); } } } else if (minmn > 0) { /* Compute space needed for SBDSDC */ if (wntqn) { /* sbdsdc needs only 4*N (or 6*N for uplo=L for LAPACK <= 3.6) */ /* keep 7*N for backwards compatibility. */ bdspac = *m * 7; } else { bdspac = *m * 3 * *m + (*m << 2); } /* Compute space preferred for each routine */ sgebrd_(m, n, dum, m, dum, dum, dum, dum, dum, &c_n1, &ierr); lwork_sgebrd_mn__ = (integer) dum[0]; sgebrd_(m, m, &a[a_offset], m, &s[1], dum, dum, dum, dum, &c_n1, & ierr); lwork_sgebrd_mm__ = (integer) dum[0]; sgelqf_(m, n, &a[a_offset], m, dum, dum, &c_n1, &ierr); lwork_sgelqf_mn__ = (integer) dum[0]; sorglq_(n, n, m, dum, n, dum, dum, &c_n1, &ierr); lwork_sorglq_nn__ = (integer) dum[0]; sorglq_(m, n, m, &a[a_offset], m, dum, dum, &c_n1, &ierr); lwork_sorglq_mn__ = (integer) dum[0]; sorgbr_("P", m, m, m, &a[a_offset], n, dum, dum, &c_n1, &ierr); lwork_sorgbr_p_mm__ = (integer) dum[0]; sormbr_("P", "R", "T", m, m, m, dum, m, dum, dum, m, dum, &c_n1, & ierr); lwork_sormbr_prt_mm__ = (integer) dum[0]; sormbr_("P", "R", "T", m, n, m, dum, m, dum, dum, m, dum, &c_n1, & ierr); lwork_sormbr_prt_mn__ = (integer) dum[0]; sormbr_("P", "R", "T", n, n, m, dum, n, dum, dum, n, dum, &c_n1, & ierr); lwork_sormbr_prt_nn__ = (integer) dum[0]; sormbr_("Q", "L", "N", m, m, m, dum, m, dum, dum, m, dum, &c_n1, & ierr); lwork_sormbr_qln_mm__ = (integer) dum[0]; if (*n >= mnthr) { if (wntqn) { /* Path 1t (N >> M, JOBZ='N') */ wrkbl = *m + lwork_sgelqf_mn__; /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sgebrd_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = bdspac + *m; maxwrk = f2cmax(i__1,i__2); minwrk = bdspac + *m; } else if (wntqo) { /* Path 2t (N >> M, JOBZ='O') */ wrkbl = *m + lwork_sgelqf_mn__; /* Computing MAX */ i__1 = wrkbl, i__2 = *m + lwork_sorglq_mn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sgebrd_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sormbr_qln_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sormbr_prt_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + bdspac; wrkbl = f2cmax(i__1,i__2); maxwrk = wrkbl + (*m << 1) * *m; minwrk = bdspac + (*m << 1) * *m + *m * 3; } else if (wntqs) { /* Path 3t (N >> M, JOBZ='S') */ wrkbl = *m + lwork_sgelqf_mn__; /* Computing MAX */ i__1 = wrkbl, i__2 = *m + lwork_sorglq_mn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sgebrd_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sormbr_qln_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sormbr_prt_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + bdspac; wrkbl = f2cmax(i__1,i__2); maxwrk = wrkbl + *m * *m; minwrk = bdspac + *m * *m + *m * 3; } else if (wntqa) { /* Path 4t (N >> M, JOBZ='A') */ wrkbl = *m + lwork_sgelqf_mn__; /* Computing MAX */ i__1 = wrkbl, i__2 = *m + lwork_sorglq_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sgebrd_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sormbr_qln_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sormbr_prt_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + bdspac; wrkbl = f2cmax(i__1,i__2); maxwrk = wrkbl + *m * *m; /* Computing MAX */ i__1 = *m * 3 + bdspac, i__2 = *m + *n; minwrk = *m * *m + f2cmax(i__1,i__2); } } else { /* Path 5t (N > M, but not much larger) */ wrkbl = *m * 3 + lwork_sgebrd_mn__; if (wntqn) { /* Path 5tn (N > M, jobz='N') */ /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + bdspac; maxwrk = f2cmax(i__1,i__2); minwrk = *m * 3 + f2cmax(*n,bdspac); } else if (wntqo) { /* Path 5to (N > M, jobz='O') */ /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sormbr_qln_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sormbr_prt_mn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + bdspac; wrkbl = f2cmax(i__1,i__2); maxwrk = wrkbl + *m * *n; /* Computing MAX */ i__1 = *n, i__2 = *m * *m + bdspac; minwrk = *m * 3 + f2cmax(i__1,i__2); } else if (wntqs) { /* Path 5ts (N > M, jobz='S') */ /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sormbr_qln_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sormbr_prt_mn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + bdspac; maxwrk = f2cmax(i__1,i__2); minwrk = *m * 3 + f2cmax(*n,bdspac); } else if (wntqa) { /* Path 5ta (N > M, jobz='A') */ /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sormbr_qln_mm__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + lwork_sormbr_prt_nn__; wrkbl = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = wrkbl, i__2 = *m * 3 + bdspac; maxwrk = f2cmax(i__1,i__2); minwrk = *m * 3 + f2cmax(*n,bdspac); } } } maxwrk = f2cmax(maxwrk,minwrk); work[1] = (real) maxwrk; if (*lwork < minwrk && ! lquery) { *info = -12; } } if (*info != 0) { i__1 = -(*info); xerbla_("SGESDD", &i__1, (ftnlen)6); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ if (*m == 0 || *n == 0) { return 0; } /* Get machine constants */ eps = slamch_("P"); smlnum = sqrt(slamch_("S")) / eps; bignum = 1.f / smlnum; /* Scale A if f2cmax element outside range [SMLNUM,BIGNUM] */ anrm = slange_("M", m, n, &a[a_offset], lda, dum); if (sisnan_(&anrm)) { *info = -4; return 0; } iscl = 0; if (anrm > 0.f && anrm < smlnum) { iscl = 1; slascl_("G", &c__0, &c__0, &anrm, &smlnum, m, n, &a[a_offset], lda, & ierr); } else if (anrm > bignum) { iscl = 1; slascl_("G", &c__0, &c__0, &anrm, &bignum, m, n, &a[a_offset], lda, & ierr); } if (*m >= *n) { /* A has at least as many rows as columns. If A has sufficiently */ /* more rows than columns, first reduce using the QR */ /* decomposition (if sufficient workspace available) */ if (*m >= mnthr) { if (wntqn) { /* Path 1 (M >> N, JOBZ='N') */ /* No singular vectors to be computed */ itau = 1; nwork = itau + *n; /* Compute A=Q*R */ /* Workspace: need N [tau] + N [work] */ /* Workspace: prefer N [tau] + N*NB [work] */ i__1 = *lwork - nwork + 1; sgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Zero out below R */ i__1 = *n - 1; i__2 = *n - 1; slaset_("L", &i__1, &i__2, &c_b63, &c_b63, &a[a_dim1 + 2], lda); ie = 1; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in A */ /* Workspace: need 3*N [e, tauq, taup] + N [work] */ /* Workspace: prefer 3*N [e, tauq, taup] + 2*N*NB [work] */ i__1 = *lwork - nwork + 1; sgebrd_(n, n, &a[a_offset], lda, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); nwork = ie + *n; /* Perform bidiagonal SVD, computing singular values only */ /* Workspace: need N [e] + BDSPAC */ sbdsdc_("U", "N", n, &s[1], &work[ie], dum, &c__1, dum, &c__1, dum, idum, &work[nwork], &iwork[1], info); } else if (wntqo) { /* Path 2 (M >> N, JOBZ = 'O') */ /* N left singular vectors to be overwritten on A and */ /* N right singular vectors to be computed in VT */ ir = 1; /* WORK(IR) is LDWRKR by N */ if (*lwork >= *lda * *n + *n * *n + *n * 3 + bdspac) { ldwrkr = *lda; } else { ldwrkr = (*lwork - *n * *n - *n * 3 - bdspac) / *n; } itau = ir + ldwrkr * *n; nwork = itau + *n; /* Compute A=Q*R */ /* Workspace: need N*N [R] + N [tau] + N [work] */ /* Workspace: prefer N*N [R] + N [tau] + N*NB [work] */ i__1 = *lwork - nwork + 1; sgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Copy R to WORK(IR), zeroing out below it */ slacpy_("U", n, n, &a[a_offset], lda, &work[ir], &ldwrkr); i__1 = *n - 1; i__2 = *n - 1; slaset_("L", &i__1, &i__2, &c_b63, &c_b63, &work[ir + 1], & ldwrkr); /* Generate Q in A */ /* Workspace: need N*N [R] + N [tau] + N [work] */ /* Workspace: prefer N*N [R] + N [tau] + N*NB [work] */ i__1 = *lwork - nwork + 1; sorgqr_(m, n, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, &ierr); ie = itau; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in WORK(IR) */ /* Workspace: need N*N [R] + 3*N [e, tauq, taup] + N [work] */ /* Workspace: prefer N*N [R] + 3*N [e, tauq, taup] + 2*N*NB [work] */ i__1 = *lwork - nwork + 1; sgebrd_(n, n, &work[ir], &ldwrkr, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); /* WORK(IU) is N by N */ iu = nwork; nwork = iu + *n * *n; /* Perform bidiagonal SVD, computing left singular vectors */ /* of bidiagonal matrix in WORK(IU) and computing right */ /* singular vectors of bidiagonal matrix in VT */ /* Workspace: need N*N [R] + 3*N [e, tauq, taup] + N*N [U] + BDSPAC */ sbdsdc_("U", "I", n, &s[1], &work[ie], &work[iu], n, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite WORK(IU) by left singular vectors of R */ /* and VT by right singular vectors of R */ /* Workspace: need N*N [R] + 3*N [e, tauq, taup] + N*N [U] + N [work] */ /* Workspace: prefer N*N [R] + 3*N [e, tauq, taup] + N*N [U] + N*NB [work] */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "N", n, n, n, &work[ir], &ldwrkr, &work[ itauq], &work[iu], n, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; sormbr_("P", "R", "T", n, n, n, &work[ir], &ldwrkr, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); /* Multiply Q in A by left singular vectors of R in */ /* WORK(IU), storing result in WORK(IR) and copying to A */ /* Workspace: need N*N [R] + 3*N [e, tauq, taup] + N*N [U] */ /* Workspace: prefer M*N [R] + 3*N [e, tauq, taup] + N*N [U] */ i__1 = *m; i__2 = ldwrkr; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = *m - i__ + 1; chunk = f2cmin(i__3,ldwrkr); sgemm_("N", "N", &chunk, n, n, &c_b84, &a[i__ + a_dim1], lda, &work[iu], n, &c_b63, &work[ir], &ldwrkr); slacpy_("F", &chunk, n, &work[ir], &ldwrkr, &a[i__ + a_dim1], lda); /* L10: */ } } else if (wntqs) { /* Path 3 (M >> N, JOBZ='S') */ /* N left singular vectors to be computed in U and */ /* N right singular vectors to be computed in VT */ ir = 1; /* WORK(IR) is N by N */ ldwrkr = *n; itau = ir + ldwrkr * *n; nwork = itau + *n; /* Compute A=Q*R */ /* Workspace: need N*N [R] + N [tau] + N [work] */ /* Workspace: prefer N*N [R] + N [tau] + N*NB [work] */ i__2 = *lwork - nwork + 1; sgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); /* Copy R to WORK(IR), zeroing out below it */ slacpy_("U", n, n, &a[a_offset], lda, &work[ir], &ldwrkr); i__2 = *n - 1; i__1 = *n - 1; slaset_("L", &i__2, &i__1, &c_b63, &c_b63, &work[ir + 1], & ldwrkr); /* Generate Q in A */ /* Workspace: need N*N [R] + N [tau] + N [work] */ /* Workspace: prefer N*N [R] + N [tau] + N*NB [work] */ i__2 = *lwork - nwork + 1; sorgqr_(m, n, n, &a[a_offset], lda, &work[itau], &work[nwork], &i__2, &ierr); ie = itau; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in WORK(IR) */ /* Workspace: need N*N [R] + 3*N [e, tauq, taup] + N [work] */ /* Workspace: prefer N*N [R] + 3*N [e, tauq, taup] + 2*N*NB [work] */ i__2 = *lwork - nwork + 1; sgebrd_(n, n, &work[ir], &ldwrkr, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors */ /* of bidiagoal matrix in U and computing right singular */ /* vectors of bidiagonal matrix in VT */ /* Workspace: need N*N [R] + 3*N [e, tauq, taup] + BDSPAC */ sbdsdc_("U", "I", n, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of R and VT */ /* by right singular vectors of R */ /* Workspace: need N*N [R] + 3*N [e, tauq, taup] + N [work] */ /* Workspace: prefer N*N [R] + 3*N [e, tauq, taup] + N*NB [work] */ i__2 = *lwork - nwork + 1; sormbr_("Q", "L", "N", n, n, n, &work[ir], &ldwrkr, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); i__2 = *lwork - nwork + 1; sormbr_("P", "R", "T", n, n, n, &work[ir], &ldwrkr, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); /* Multiply Q in A by left singular vectors of R in */ /* WORK(IR), storing result in U */ /* Workspace: need N*N [R] */ slacpy_("F", n, n, &u[u_offset], ldu, &work[ir], &ldwrkr); sgemm_("N", "N", m, n, n, &c_b84, &a[a_offset], lda, &work[ir] , &ldwrkr, &c_b63, &u[u_offset], ldu); } else if (wntqa) { /* Path 4 (M >> N, JOBZ='A') */ /* M left singular vectors to be computed in U and */ /* N right singular vectors to be computed in VT */ iu = 1; /* WORK(IU) is N by N */ ldwrku = *n; itau = iu + ldwrku * *n; nwork = itau + *n; /* Compute A=Q*R, copying result to U */ /* Workspace: need N*N [U] + N [tau] + N [work] */ /* Workspace: prefer N*N [U] + N [tau] + N*NB [work] */ i__2 = *lwork - nwork + 1; sgeqrf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); slacpy_("L", m, n, &a[a_offset], lda, &u[u_offset], ldu); /* Generate Q in U */ /* Workspace: need N*N [U] + N [tau] + M [work] */ /* Workspace: prefer N*N [U] + N [tau] + M*NB [work] */ i__2 = *lwork - nwork + 1; sorgqr_(m, m, n, &u[u_offset], ldu, &work[itau], &work[nwork], &i__2, &ierr); /* Produce R in A, zeroing out other entries */ i__2 = *n - 1; i__1 = *n - 1; slaset_("L", &i__2, &i__1, &c_b63, &c_b63, &a[a_dim1 + 2], lda); ie = itau; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize R in A */ /* Workspace: need N*N [U] + 3*N [e, tauq, taup] + N [work] */ /* Workspace: prefer N*N [U] + 3*N [e, tauq, taup] + 2*N*NB [work] */ i__2 = *lwork - nwork + 1; sgebrd_(n, n, &a[a_offset], lda, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors */ /* of bidiagonal matrix in WORK(IU) and computing right */ /* singular vectors of bidiagonal matrix in VT */ /* Workspace: need N*N [U] + 3*N [e, tauq, taup] + BDSPAC */ sbdsdc_("U", "I", n, &s[1], &work[ie], &work[iu], n, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite WORK(IU) by left singular vectors of R and VT */ /* by right singular vectors of R */ /* Workspace: need N*N [U] + 3*N [e, tauq, taup] + N [work] */ /* Workspace: prefer N*N [U] + 3*N [e, tauq, taup] + N*NB [work] */ i__2 = *lwork - nwork + 1; sormbr_("Q", "L", "N", n, n, n, &a[a_offset], lda, &work[ itauq], &work[iu], &ldwrku, &work[nwork], &i__2, & ierr); i__2 = *lwork - nwork + 1; sormbr_("P", "R", "T", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); /* Multiply Q in U by left singular vectors of R in */ /* WORK(IU), storing result in A */ /* Workspace: need N*N [U] */ sgemm_("N", "N", m, n, n, &c_b84, &u[u_offset], ldu, &work[iu] , &ldwrku, &c_b63, &a[a_offset], lda); /* Copy left singular vectors of A from A to U */ slacpy_("F", m, n, &a[a_offset], lda, &u[u_offset], ldu); } } else { /* M .LT. MNTHR */ /* Path 5 (M >= N, but not much larger) */ /* Reduce to bidiagonal form without QR decomposition */ ie = 1; itauq = ie + *n; itaup = itauq + *n; nwork = itaup + *n; /* Bidiagonalize A */ /* Workspace: need 3*N [e, tauq, taup] + M [work] */ /* Workspace: prefer 3*N [e, tauq, taup] + (M+N)*NB [work] */ i__2 = *lwork - nwork + 1; sgebrd_(m, n, &a[a_offset], lda, &s[1], &work[ie], &work[itauq], & work[itaup], &work[nwork], &i__2, &ierr); if (wntqn) { /* Path 5n (M >= N, JOBZ='N') */ /* Perform bidiagonal SVD, only computing singular values */ /* Workspace: need 3*N [e, tauq, taup] + BDSPAC */ sbdsdc_("U", "N", n, &s[1], &work[ie], dum, &c__1, dum, &c__1, dum, idum, &work[nwork], &iwork[1], info); } else if (wntqo) { /* Path 5o (M >= N, JOBZ='O') */ iu = nwork; if (*lwork >= *m * *n + *n * 3 + bdspac) { /* WORK( IU ) is M by N */ ldwrku = *m; nwork = iu + ldwrku * *n; slaset_("F", m, n, &c_b63, &c_b63, &work[iu], &ldwrku); /* IR is unused; silence compile warnings */ ir = -1; } else { /* WORK( IU ) is N by N */ ldwrku = *n; nwork = iu + ldwrku * *n; /* WORK(IR) is LDWRKR by N */ ir = nwork; ldwrkr = (*lwork - *n * *n - *n * 3) / *n; } nwork = iu + ldwrku * *n; /* Perform bidiagonal SVD, computing left singular vectors */ /* of bidiagonal matrix in WORK(IU) and computing right */ /* singular vectors of bidiagonal matrix in VT */ /* Workspace: need 3*N [e, tauq, taup] + N*N [U] + BDSPAC */ sbdsdc_("U", "I", n, &s[1], &work[ie], &work[iu], &ldwrku, & vt[vt_offset], ldvt, dum, idum, &work[nwork], &iwork[ 1], info); /* Overwrite VT by right singular vectors of A */ /* Workspace: need 3*N [e, tauq, taup] + N*N [U] + N [work] */ /* Workspace: prefer 3*N [e, tauq, taup] + N*N [U] + N*NB [work] */ i__2 = *lwork - nwork + 1; sormbr_("P", "R", "T", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); if (*lwork >= *m * *n + *n * 3 + bdspac) { /* Path 5o-fast */ /* Overwrite WORK(IU) by left singular vectors of A */ /* Workspace: need 3*N [e, tauq, taup] + M*N [U] + N [work] */ /* Workspace: prefer 3*N [e, tauq, taup] + M*N [U] + N*NB [work] */ i__2 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, n, n, &a[a_offset], lda, &work[ itauq], &work[iu], &ldwrku, &work[nwork], &i__2, & ierr); /* Copy left singular vectors of A from WORK(IU) to A */ slacpy_("F", m, n, &work[iu], &ldwrku, &a[a_offset], lda); } else { /* Path 5o-slow */ /* Generate Q in A */ /* Workspace: need 3*N [e, tauq, taup] + N*N [U] + N [work] */ /* Workspace: prefer 3*N [e, tauq, taup] + N*N [U] + N*NB [work] */ i__2 = *lwork - nwork + 1; sorgbr_("Q", m, n, n, &a[a_offset], lda, &work[itauq], & work[nwork], &i__2, &ierr); /* Multiply Q in A by left singular vectors of */ /* bidiagonal matrix in WORK(IU), storing result in */ /* WORK(IR) and copying to A */ /* Workspace: need 3*N [e, tauq, taup] + N*N [U] + NB*N [R] */ /* Workspace: prefer 3*N [e, tauq, taup] + N*N [U] + M*N [R] */ i__2 = *m; i__1 = ldwrkr; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = *m - i__ + 1; chunk = f2cmin(i__3,ldwrkr); sgemm_("N", "N", &chunk, n, n, &c_b84, &a[i__ + a_dim1], lda, &work[iu], &ldwrku, &c_b63, & work[ir], &ldwrkr); slacpy_("F", &chunk, n, &work[ir], &ldwrkr, &a[i__ + a_dim1], lda); /* L20: */ } } } else if (wntqs) { /* Path 5s (M >= N, JOBZ='S') */ /* Perform bidiagonal SVD, computing left singular vectors */ /* of bidiagonal matrix in U and computing right singular */ /* vectors of bidiagonal matrix in VT */ /* Workspace: need 3*N [e, tauq, taup] + BDSPAC */ slaset_("F", m, n, &c_b63, &c_b63, &u[u_offset], ldu); sbdsdc_("U", "I", n, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of A and VT */ /* by right singular vectors of A */ /* Workspace: need 3*N [e, tauq, taup] + N [work] */ /* Workspace: prefer 3*N [e, tauq, taup] + N*NB [work] */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, n, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; sormbr_("P", "R", "T", n, n, n, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } else if (wntqa) { /* Path 5a (M >= N, JOBZ='A') */ /* Perform bidiagonal SVD, computing left singular vectors */ /* of bidiagonal matrix in U and computing right singular */ /* vectors of bidiagonal matrix in VT */ /* Workspace: need 3*N [e, tauq, taup] + BDSPAC */ slaset_("F", m, m, &c_b63, &c_b63, &u[u_offset], ldu); sbdsdc_("U", "I", n, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Set the right corner of U to identity matrix */ if (*m > *n) { i__1 = *m - *n; i__2 = *m - *n; slaset_("F", &i__1, &i__2, &c_b63, &c_b84, &u[*n + 1 + (* n + 1) * u_dim1], ldu); } /* Overwrite U by left singular vectors of A and VT */ /* by right singular vectors of A */ /* Workspace: need 3*N [e, tauq, taup] + M [work] */ /* Workspace: prefer 3*N [e, tauq, taup] + M*NB [work] */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; sormbr_("P", "R", "T", n, n, m, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } } } else { /* A has more columns than rows. If A has sufficiently more */ /* columns than rows, first reduce using the LQ decomposition (if */ /* sufficient workspace available) */ if (*n >= mnthr) { if (wntqn) { /* Path 1t (N >> M, JOBZ='N') */ /* No singular vectors to be computed */ itau = 1; nwork = itau + *m; /* Compute A=L*Q */ /* Workspace: need M [tau] + M [work] */ /* Workspace: prefer M [tau] + M*NB [work] */ i__1 = *lwork - nwork + 1; sgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Zero out above L */ i__1 = *m - 1; i__2 = *m - 1; slaset_("U", &i__1, &i__2, &c_b63, &c_b63, &a[(a_dim1 << 1) + 1], lda); ie = 1; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in A */ /* Workspace: need 3*M [e, tauq, taup] + M [work] */ /* Workspace: prefer 3*M [e, tauq, taup] + 2*M*NB [work] */ i__1 = *lwork - nwork + 1; sgebrd_(m, m, &a[a_offset], lda, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); nwork = ie + *m; /* Perform bidiagonal SVD, computing singular values only */ /* Workspace: need M [e] + BDSPAC */ sbdsdc_("U", "N", m, &s[1], &work[ie], dum, &c__1, dum, &c__1, dum, idum, &work[nwork], &iwork[1], info); } else if (wntqo) { /* Path 2t (N >> M, JOBZ='O') */ /* M right singular vectors to be overwritten on A and */ /* M left singular vectors to be computed in U */ ivt = 1; /* WORK(IVT) is M by M */ /* WORK(IL) is M by M; it is later resized to M by chunk for gemm */ il = ivt + *m * *m; if (*lwork >= *m * *n + *m * *m + *m * 3 + bdspac) { ldwrkl = *m; chunk = *n; } else { ldwrkl = *m; chunk = (*lwork - *m * *m) / *m; } itau = il + ldwrkl * *m; nwork = itau + *m; /* Compute A=L*Q */ /* Workspace: need M*M [VT] + M*M [L] + M [tau] + M [work] */ /* Workspace: prefer M*M [VT] + M*M [L] + M [tau] + M*NB [work] */ i__1 = *lwork - nwork + 1; sgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__1, &ierr); /* Copy L to WORK(IL), zeroing about above it */ slacpy_("L", m, m, &a[a_offset], lda, &work[il], &ldwrkl); i__1 = *m - 1; i__2 = *m - 1; slaset_("U", &i__1, &i__2, &c_b63, &c_b63, &work[il + ldwrkl], &ldwrkl); /* Generate Q in A */ /* Workspace: need M*M [VT] + M*M [L] + M [tau] + M [work] */ /* Workspace: prefer M*M [VT] + M*M [L] + M [tau] + M*NB [work] */ i__1 = *lwork - nwork + 1; sorglq_(m, n, m, &a[a_offset], lda, &work[itau], &work[nwork], &i__1, &ierr); ie = itau; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in WORK(IL) */ /* Workspace: need M*M [VT] + M*M [L] + 3*M [e, tauq, taup] + M [work] */ /* Workspace: prefer M*M [VT] + M*M [L] + 3*M [e, tauq, taup] + 2*M*NB [work] */ i__1 = *lwork - nwork + 1; sgebrd_(m, m, &work[il], &ldwrkl, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__1, &ierr); /* Perform bidiagonal SVD, computing left singular vectors */ /* of bidiagonal matrix in U, and computing right singular */ /* vectors of bidiagonal matrix in WORK(IVT) */ /* Workspace: need M*M [VT] + M*M [L] + 3*M [e, tauq, taup] + BDSPAC */ sbdsdc_("U", "I", m, &s[1], &work[ie], &u[u_offset], ldu, & work[ivt], m, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of L and WORK(IVT) */ /* by right singular vectors of L */ /* Workspace: need M*M [VT] + M*M [L] + 3*M [e, tauq, taup] + M [work] */ /* Workspace: prefer M*M [VT] + M*M [L] + 3*M [e, tauq, taup] + M*NB [work] */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, m, m, &work[il], &ldwrkl, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; sormbr_("P", "R", "T", m, m, m, &work[il], &ldwrkl, &work[ itaup], &work[ivt], m, &work[nwork], &i__1, &ierr); /* Multiply right singular vectors of L in WORK(IVT) by Q */ /* in A, storing result in WORK(IL) and copying to A */ /* Workspace: need M*M [VT] + M*M [L] */ /* Workspace: prefer M*M [VT] + M*N [L] */ /* At this point, L is resized as M by chunk. */ i__1 = *n; i__2 = chunk; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MIN */ i__3 = *n - i__ + 1; blk = f2cmin(i__3,chunk); sgemm_("N", "N", m, &blk, m, &c_b84, &work[ivt], m, &a[ i__ * a_dim1 + 1], lda, &c_b63, &work[il], & ldwrkl); slacpy_("F", m, &blk, &work[il], &ldwrkl, &a[i__ * a_dim1 + 1], lda); /* L30: */ } } else if (wntqs) { /* Path 3t (N >> M, JOBZ='S') */ /* M right singular vectors to be computed in VT and */ /* M left singular vectors to be computed in U */ il = 1; /* WORK(IL) is M by M */ ldwrkl = *m; itau = il + ldwrkl * *m; nwork = itau + *m; /* Compute A=L*Q */ /* Workspace: need M*M [L] + M [tau] + M [work] */ /* Workspace: prefer M*M [L] + M [tau] + M*NB [work] */ i__2 = *lwork - nwork + 1; sgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); /* Copy L to WORK(IL), zeroing out above it */ slacpy_("L", m, m, &a[a_offset], lda, &work[il], &ldwrkl); i__2 = *m - 1; i__1 = *m - 1; slaset_("U", &i__2, &i__1, &c_b63, &c_b63, &work[il + ldwrkl], &ldwrkl); /* Generate Q in A */ /* Workspace: need M*M [L] + M [tau] + M [work] */ /* Workspace: prefer M*M [L] + M [tau] + M*NB [work] */ i__2 = *lwork - nwork + 1; sorglq_(m, n, m, &a[a_offset], lda, &work[itau], &work[nwork], &i__2, &ierr); ie = itau; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in WORK(IU). */ /* Workspace: need M*M [L] + 3*M [e, tauq, taup] + M [work] */ /* Workspace: prefer M*M [L] + 3*M [e, tauq, taup] + 2*M*NB [work] */ i__2 = *lwork - nwork + 1; sgebrd_(m, m, &work[il], &ldwrkl, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors */ /* of bidiagonal matrix in U and computing right singular */ /* vectors of bidiagonal matrix in VT */ /* Workspace: need M*M [L] + 3*M [e, tauq, taup] + BDSPAC */ sbdsdc_("U", "I", m, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of L and VT */ /* by right singular vectors of L */ /* Workspace: need M*M [L] + 3*M [e, tauq, taup] + M [work] */ /* Workspace: prefer M*M [L] + 3*M [e, tauq, taup] + M*NB [work] */ i__2 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, m, m, &work[il], &ldwrkl, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); i__2 = *lwork - nwork + 1; sormbr_("P", "R", "T", m, m, m, &work[il], &ldwrkl, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__2, & ierr); /* Multiply right singular vectors of L in WORK(IL) by */ /* Q in A, storing result in VT */ /* Workspace: need M*M [L] */ slacpy_("F", m, m, &vt[vt_offset], ldvt, &work[il], &ldwrkl); sgemm_("N", "N", m, n, m, &c_b84, &work[il], &ldwrkl, &a[ a_offset], lda, &c_b63, &vt[vt_offset], ldvt); } else if (wntqa) { /* Path 4t (N >> M, JOBZ='A') */ /* N right singular vectors to be computed in VT and */ /* M left singular vectors to be computed in U */ ivt = 1; /* WORK(IVT) is M by M */ ldwkvt = *m; itau = ivt + ldwkvt * *m; nwork = itau + *m; /* Compute A=L*Q, copying result to VT */ /* Workspace: need M*M [VT] + M [tau] + M [work] */ /* Workspace: prefer M*M [VT] + M [tau] + M*NB [work] */ i__2 = *lwork - nwork + 1; sgelqf_(m, n, &a[a_offset], lda, &work[itau], &work[nwork], & i__2, &ierr); slacpy_("U", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); /* Generate Q in VT */ /* Workspace: need M*M [VT] + M [tau] + N [work] */ /* Workspace: prefer M*M [VT] + M [tau] + N*NB [work] */ i__2 = *lwork - nwork + 1; sorglq_(n, n, m, &vt[vt_offset], ldvt, &work[itau], &work[ nwork], &i__2, &ierr); /* Produce L in A, zeroing out other entries */ i__2 = *m - 1; i__1 = *m - 1; slaset_("U", &i__2, &i__1, &c_b63, &c_b63, &a[(a_dim1 << 1) + 1], lda); ie = itau; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize L in A */ /* Workspace: need M*M [VT] + 3*M [e, tauq, taup] + M [work] */ /* Workspace: prefer M*M [VT] + 3*M [e, tauq, taup] + 2*M*NB [work] */ i__2 = *lwork - nwork + 1; sgebrd_(m, m, &a[a_offset], lda, &s[1], &work[ie], &work[ itauq], &work[itaup], &work[nwork], &i__2, &ierr); /* Perform bidiagonal SVD, computing left singular vectors */ /* of bidiagonal matrix in U and computing right singular */ /* vectors of bidiagonal matrix in WORK(IVT) */ /* Workspace: need M*M [VT] + 3*M [e, tauq, taup] + BDSPAC */ sbdsdc_("U", "I", m, &s[1], &work[ie], &u[u_offset], ldu, & work[ivt], &ldwkvt, dum, idum, &work[nwork], &iwork[1] , info); /* Overwrite U by left singular vectors of L and WORK(IVT) */ /* by right singular vectors of L */ /* Workspace: need M*M [VT] + 3*M [e, tauq, taup]+ M [work] */ /* Workspace: prefer M*M [VT] + 3*M [e, tauq, taup]+ M*NB [work] */ i__2 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, m, m, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); i__2 = *lwork - nwork + 1; sormbr_("P", "R", "T", m, m, m, &a[a_offset], lda, &work[ itaup], &work[ivt], &ldwkvt, &work[nwork], &i__2, & ierr); /* Multiply right singular vectors of L in WORK(IVT) by */ /* Q in VT, storing result in A */ /* Workspace: need M*M [VT] */ sgemm_("N", "N", m, n, m, &c_b84, &work[ivt], &ldwkvt, &vt[ vt_offset], ldvt, &c_b63, &a[a_offset], lda); /* Copy right singular vectors of A from A to VT */ slacpy_("F", m, n, &a[a_offset], lda, &vt[vt_offset], ldvt); } } else { /* N .LT. MNTHR */ /* Path 5t (N > M, but not much larger) */ /* Reduce to bidiagonal form without LQ decomposition */ ie = 1; itauq = ie + *m; itaup = itauq + *m; nwork = itaup + *m; /* Bidiagonalize A */ /* Workspace: need 3*M [e, tauq, taup] + N [work] */ /* Workspace: prefer 3*M [e, tauq, taup] + (M+N)*NB [work] */ i__2 = *lwork - nwork + 1; sgebrd_(m, n, &a[a_offset], lda, &s[1], &work[ie], &work[itauq], & work[itaup], &work[nwork], &i__2, &ierr); if (wntqn) { /* Path 5tn (N > M, JOBZ='N') */ /* Perform bidiagonal SVD, only computing singular values */ /* Workspace: need 3*M [e, tauq, taup] + BDSPAC */ sbdsdc_("L", "N", m, &s[1], &work[ie], dum, &c__1, dum, &c__1, dum, idum, &work[nwork], &iwork[1], info); } else if (wntqo) { /* Path 5to (N > M, JOBZ='O') */ ldwkvt = *m; ivt = nwork; if (*lwork >= *m * *n + *m * 3 + bdspac) { /* WORK( IVT ) is M by N */ slaset_("F", m, n, &c_b63, &c_b63, &work[ivt], &ldwkvt); nwork = ivt + ldwkvt * *n; /* IL is unused; silence compile warnings */ il = -1; } else { /* WORK( IVT ) is M by M */ nwork = ivt + ldwkvt * *m; il = nwork; /* WORK(IL) is M by CHUNK */ chunk = (*lwork - *m * *m - *m * 3) / *m; } /* Perform bidiagonal SVD, computing left singular vectors */ /* of bidiagonal matrix in U and computing right singular */ /* vectors of bidiagonal matrix in WORK(IVT) */ /* Workspace: need 3*M [e, tauq, taup] + M*M [VT] + BDSPAC */ sbdsdc_("L", "I", m, &s[1], &work[ie], &u[u_offset], ldu, & work[ivt], &ldwkvt, dum, idum, &work[nwork], &iwork[1] , info); /* Overwrite U by left singular vectors of A */ /* Workspace: need 3*M [e, tauq, taup] + M*M [VT] + M [work] */ /* Workspace: prefer 3*M [e, tauq, taup] + M*M [VT] + M*NB [work] */ i__2 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__2, &ierr); if (*lwork >= *m * *n + *m * 3 + bdspac) { /* Path 5to-fast */ /* Overwrite WORK(IVT) by left singular vectors of A */ /* Workspace: need 3*M [e, tauq, taup] + M*N [VT] + M [work] */ /* Workspace: prefer 3*M [e, tauq, taup] + M*N [VT] + M*NB [work] */ i__2 = *lwork - nwork + 1; sormbr_("P", "R", "T", m, n, m, &a[a_offset], lda, &work[ itaup], &work[ivt], &ldwkvt, &work[nwork], &i__2, &ierr); /* Copy right singular vectors of A from WORK(IVT) to A */ slacpy_("F", m, n, &work[ivt], &ldwkvt, &a[a_offset], lda); } else { /* Path 5to-slow */ /* Generate P**T in A */ /* Workspace: need 3*M [e, tauq, taup] + M*M [VT] + M [work] */ /* Workspace: prefer 3*M [e, tauq, taup] + M*M [VT] + M*NB [work] */ i__2 = *lwork - nwork + 1; sorgbr_("P", m, n, m, &a[a_offset], lda, &work[itaup], & work[nwork], &i__2, &ierr); /* Multiply Q in A by right singular vectors of */ /* bidiagonal matrix in WORK(IVT), storing result in */ /* WORK(IL) and copying to A */ /* Workspace: need 3*M [e, tauq, taup] + M*M [VT] + M*NB [L] */ /* Workspace: prefer 3*M [e, tauq, taup] + M*M [VT] + M*N [L] */ i__2 = *n; i__1 = chunk; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing MIN */ i__3 = *n - i__ + 1; blk = f2cmin(i__3,chunk); sgemm_("N", "N", m, &blk, m, &c_b84, &work[ivt], & ldwkvt, &a[i__ * a_dim1 + 1], lda, &c_b63, & work[il], m); slacpy_("F", m, &blk, &work[il], m, &a[i__ * a_dim1 + 1], lda); /* L40: */ } } } else if (wntqs) { /* Path 5ts (N > M, JOBZ='S') */ /* Perform bidiagonal SVD, computing left singular vectors */ /* of bidiagonal matrix in U and computing right singular */ /* vectors of bidiagonal matrix in VT */ /* Workspace: need 3*M [e, tauq, taup] + BDSPAC */ slaset_("F", m, n, &c_b63, &c_b63, &vt[vt_offset], ldvt); sbdsdc_("L", "I", m, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Overwrite U by left singular vectors of A and VT */ /* by right singular vectors of A */ /* Workspace: need 3*M [e, tauq, taup] + M [work] */ /* Workspace: prefer 3*M [e, tauq, taup] + M*NB [work] */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; sormbr_("P", "R", "T", m, n, m, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } else if (wntqa) { /* Path 5ta (N > M, JOBZ='A') */ /* Perform bidiagonal SVD, computing left singular vectors */ /* of bidiagonal matrix in U and computing right singular */ /* vectors of bidiagonal matrix in VT */ /* Workspace: need 3*M [e, tauq, taup] + BDSPAC */ slaset_("F", n, n, &c_b63, &c_b63, &vt[vt_offset], ldvt); sbdsdc_("L", "I", m, &s[1], &work[ie], &u[u_offset], ldu, &vt[ vt_offset], ldvt, dum, idum, &work[nwork], &iwork[1], info); /* Set the right corner of VT to identity matrix */ if (*n > *m) { i__1 = *n - *m; i__2 = *n - *m; slaset_("F", &i__1, &i__2, &c_b63, &c_b84, &vt[*m + 1 + (* m + 1) * vt_dim1], ldvt); } /* Overwrite U by left singular vectors of A and VT */ /* by right singular vectors of A */ /* Workspace: need 3*M [e, tauq, taup] + N [work] */ /* Workspace: prefer 3*M [e, tauq, taup] + N*NB [work] */ i__1 = *lwork - nwork + 1; sormbr_("Q", "L", "N", m, m, n, &a[a_offset], lda, &work[ itauq], &u[u_offset], ldu, &work[nwork], &i__1, &ierr); i__1 = *lwork - nwork + 1; sormbr_("P", "R", "T", n, n, m, &a[a_offset], lda, &work[ itaup], &vt[vt_offset], ldvt, &work[nwork], &i__1, & ierr); } } } /* Undo scaling if necessary */ if (iscl == 1) { if (anrm > bignum) { slascl_("G", &c__0, &c__0, &bignum, &anrm, &minmn, &c__1, &s[1], & minmn, &ierr); } if (anrm < smlnum) { slascl_("G", &c__0, &c__0, &smlnum, &anrm, &minmn, &c__1, &s[1], & minmn, &ierr); } } /* Return optimal workspace in WORK(1) */ work[1] = (real) maxwrk; return 0; /* End of SGESDD */ } /* sgesdd_ */
the_stack_data/1099772.c
#include<stdio.h> int main() { int i,n=8,temp; int a[8]={1,9,2,4,6,1,6,8}; temp=a[n-1]; for(i=n-1;i>=0;i--) { a[i]=a[i-1]; } for(i=0;i<n;i++) printf("%d ",a[i]); }
the_stack_data/872886.c
#include <stdlib.h> #include <stdio.h> int main() { printf("%d\n", (int) sizeof("abcd")); printf("%d\n", (int) (sizeof(L"abcd") / sizeof(wchar_t))); return 0; }
the_stack_data/234519501.c
main () { typedef short int xtype; xtype i; xtype ii; for (i = 0; i < 100; i++) for (ii = 65535; --ii;) ; }
the_stack_data/21367.c
main() { int i,j,k=2; i=0; j=i; i=k+3; i=j; }
the_stack_data/148577201.c
/* * ecorpus_tokens.c: Original work Copyright (C) 2020 by Doug Blewett MIT License 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. * generate corpus stream for encryption */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <ctype.h> #include <limits.h> #include <stdbool.h> #include <math.h> static long int prandom(void) { #ifdef __STRICT_ANSI__ return rand(); #else return random(); #endif } static void psrandom(unsigned int key) { #ifdef __STRICT_ANSI__ srand(key) #else srandom(key); #endif } static void sub_fail(char *argv0) { fprintf(stderr, "%s: corpus options are as follows:\n\n", argv0); fprintf(stderr, " -uniform sets byte values per block to be uniform and random\n"); fprintf(stderr, " -key sets the randomizing seed: -key number\n"); fprintf(stderr, " -byte_list file containing byte values for the corpus: -byte_list file\n"); fprintf(stderr, " -start_skip skip the first N random numbers: -start_skip number\n"); fprintf(stderr, " -skip skip N numbers on each call to random: -skip number\n"); fprintf(stderr, " -skip_random skip randomly at each call to random()\n"); fprintf(stderr, " -skip_random_mask mask for -skip_random: -skip_random_mask number\n"); fprintf(stderr, " -filter_file file of skip N numbers: -filter_file filename\n"); fprintf(stderr, " -filter_skip bytes to skip in the filter file: -filter_skip number\n"); fprintf(stderr, " -filter_mask mask to be used for skip numbers: -filter_mask number\n"); fprintf(stderr, "\n"); exit(1); } static int bytes[256]; static int bytes_count; static int uniform_byte_counts[256]; static int uniform_byte_count; // options static bool uniform = false; static time_t key = 0; static unsigned long start_skip = 0; static FILE *fp_byte_list = NULL; static unsigned long skip = 0; static bool skip_random = false; static unsigned char skip_random_mask = 0377; static FILE *fp_filter = NULL; static unsigned char filter_mask = 0377; static unsigned long filter_skip = 0; void ecorpus_tokens_init(char *argv0, char *stream_file) { FILE *fp_stream = NULL; char buf[1024]; unsigned int rvalue; unsigned long scan_token; unsigned char c; char *ptr = strchr(stream_file, ':'); if (ptr == NULL) { fprintf(stderr, "%s: badly formed stream file: %s\n", argv0, stream_file); sub_fail(argv0); } ptr++; fp_stream = fopen(ptr, "r"); if (fp_stream == NULL) { fprintf(stderr, "%s: cannot open the stream file: %s\n", argv0, ptr); sub_fail(argv0); } while (fgets(buf, 1024, fp_stream) != NULL) { char *argv1 = buf; char *argv2 = ""; char *nptr; int len = strlen(buf); // ignore comments if (*buf == '#') continue; // find and trim the options and arguments - one per line : -skip 23 while (isspace(buf[len - 1])) { len--; buf[len] = '\0'; } // trim leading spaces while (isspace(*argv1)) argv1++; if (argv1 - buf >= len) continue; // find the end of the option token nptr = argv1 + 1; while (!isspace(*nptr)) { if (nptr - buf >= len) break; nptr++; } if (isspace(*nptr)) { *nptr = '\0'; nptr++; } // argument trim leading spaces argv2 = nptr; if (argv2 - buf < len) { while (isspace(*argv2)) { argv2++; if (argv2 - buf >= len) break; } } /* * parse the options to the program */ if (strcmp(argv1, "-uniform") == 0) { uniform = true; continue; } if (strcmp(argv1, "-key") == 0) { if (*argv2 == '\0') { fprintf(stderr, "%s: no -key value given\n", argv0); sub_fail(argv0); } rvalue = sscanf(argv2, "%lu", &scan_token); if (rvalue == 0 || rvalue == EOF || scan_token > UINT_MAX) { fprintf(stderr, "%s: -key value (%s) is not an integer in the range of 0 to %u\n", argv0, argv2, UINT_MAX); sub_fail(argv0); } key = scan_token; continue; } if (strcmp(argv1, "-start_skip") == 0) { if (*argv2 == '\0') { fprintf(stderr, "%s: no -start_skip value given\n", argv0); sub_fail(argv0); } rvalue = sscanf(argv2, "%lu", &scan_token); if (rvalue == 0 || rvalue == EOF || scan_token > UINT_MAX) { fprintf(stderr, "%s: -start_skip value (%s) is not an integer in the range of 0 to %u\n", argv0, argv2, UINT_MAX); sub_fail(argv0); } start_skip = scan_token; continue; } if (strcmp(argv1, "-byte_list") == 0) { if (*argv2 == '\0') { fprintf(stderr, "%s: no -byte_liste filename given\n", argv0); sub_fail(argv0); } fp_byte_list = fopen(argv2, "r"); if (fp_byte_list == NULL) { fprintf(stderr, "%s: cannot open the byte_list: %s\n", argv0, argv2); sub_fail(argv0); } continue; } if (strcmp(argv1, "-skip") == 0) { if (*argv2 == '\0') { fprintf(stderr, "%s: no -skip value given\n", argv0); sub_fail(argv0); } rvalue = sscanf(argv2, "%lu", &scan_token); if (rvalue == 0 || rvalue == EOF || scan_token > UINT_MAX) { fprintf(stderr, "%s: -skip value (%s) is not an integer in the range of 0 to %u\n", argv0, argv2, UINT_MAX); sub_fail(argv0); } skip = scan_token; continue; } if (strcmp(argv1, "-skip_random") == 0) { skip_random = true; continue; } if (strcmp(argv1, "-skip_random_mask") == 0) { int octal_int = 0; if (*argv2 == '\0') { fprintf(stderr, "%s: no -skip_random_mask value given\n", argv0); sub_fail(argv0); } if (*argv2 == '0' || *argv2 == 'o') { if (*argv2 == 'o') ++argv2; rvalue = sscanf(argv2, "%o", &octal_int); } else rvalue = sscanf(argv2, "%i", &octal_int); if (rvalue == 0 || rvalue == EOF || scan_token > UINT_MAX || octal_int < 0 || octal_int > 255) { fprintf(stderr, "%s: -skip_random_mask value (%s) is not an integer in the range of 0 to 255 (0377)\n", argv0, argv2); sub_fail(argv0); } skip_random_mask = octal_int; continue; } if (strcmp(argv1, "-filter_file") == 0) { if (*argv2 == '\0') { fprintf(stderr, "%s: no -filter_file filename given\n", argv0); sub_fail(argv0); } fp_filter = fopen(argv2, "r"); if (fp_filter == NULL) { fprintf(stderr, "%s: cannot open the filter file: %s\n", argv0, argv2); sub_fail(argv0); } continue; } if (strcmp(argv1, "-filter_skip") == 0) { if (*argv2 == '\0') { fprintf(stderr, "%s: no -filter_skip value given\n", argv0); sub_fail(argv0); } rvalue = sscanf(argv2, "%lu", &scan_token); if (rvalue == 0 || rvalue == EOF || scan_token > UINT_MAX) { fprintf(stderr, "%s: -filter_skip value (%s) is not an integer in the range of 0 to %u\n", argv0, argv2, UINT_MAX); sub_fail(argv0); } filter_skip = scan_token; continue; } if (strcmp(argv1, "-filter_mask") == 0) { int octal_int = 0; if (*argv2 == '\0') { fprintf(stderr, "%s: no -filter_mask value given\n", argv0); sub_fail(argv0); } if (*argv2 == '0' || *argv2 == 'o') { if (*argv2 == 'o') ++argv2; rvalue = sscanf(argv2, "%o", &octal_int); } else rvalue = sscanf(argv2, "%i", &octal_int); if (rvalue == 0 || rvalue == EOF || scan_token > UINT_MAX || octal_int < 0 || octal_int > 255) { fprintf(stderr, "%s: -filter_mask value (%s) is not an integer in the range of 0 to 255 (0377)\n", argv0, argv2); sub_fail(argv0); } filter_mask = octal_int; continue; } } if (uniform == true) fprintf(stdout, "uniform blocks enabled\n"); if (key != 0) fprintf(stdout, "key provided\n"); if (fp_byte_list != NULL) fprintf(stdout, "byte_list provided\n"); if (start_skip != 0) fprintf(stdout, "start_skip provided\n"); if (skip != 0) fprintf(stdout, "skip provided\n"); if (skip_random == true) fprintf(stdout, "skip_random enabled\n"); if(fp_filter != NULL) fprintf(stdout, "filter_file provided\n"); /* * open the byte_list file - create the corpus file with specific bytes. * this makes the encrypted files smaller */ if (fp_byte_list != NULL) { bytes_count = 0; for (int i = 0; i < 256; i++) bytes[i] = 0; while (true) { c = fgetc(fp_byte_list) & 0377; if (feof(fp_byte_list)) break; bytes[c]++; /* * optional speed up - remove if balancing byte proportions */ if(bytes[c] == 1) bytes_count++; if (bytes_count == 256) break; } fclose(fp_byte_list); fprintf(stdout, "unique bytes count = %d\n", bytes_count); } else { for (int i = 0; i < 256; i++) bytes[i] = 1; bytes_count = 256; } /* * advance the filter_file the filter_skip byte count */ if (fp_filter != NULL && filter_skip > 0) { for (unsigned int i = filter_skip; i > 0; i--) { c = fgetc(fp_filter); if (feof(fp_filter)) { fclose(fp_filter); fp_filter = NULL; fprintf(stderr, "%s: The filter_file is smaller than the filter_skip count\n", argv0); sub_fail(argv0); break; } } } /* * seed the random number generator */ if (key == 0) { sleep(1); // make back to back corpuses differ key = time(NULL); } psrandom((unsigned int) key); /* * clear the tabulation arrays */ for (int i = 0; i < 256; i++) uniform_byte_counts[i] = 0; uniform_byte_count = 0; /* * generate - all of the stuff above is fluff */ if (skip_random) start_skip += prandom() & skip_random_mask; for (unsigned int j = 0; j < start_skip; j++) prandom(); fclose(fp_stream); } unsigned char ecorpus_next_token () { unsigned char token; while (true) { unsigned long skipr = 0; unsigned long skipf = 0; if (fp_filter != NULL) { fgetc(fp_filter); if (feof(fp_filter)) // loop back around { rewind(fp_filter); for (unsigned int j = filter_skip; j > 0; j--) fgetc(fp_filter); } skipf = fgetc(fp_filter) & filter_mask; } if (skip_random) skipr = prandom() & skip_random_mask; skipr = skipr + skipf + skip; for (unsigned int j = 0; j < skipr; j++) token = prandom(); token = prandom() & 0377; if (bytes[token] == 0) continue; if(uniform && uniform_byte_counts[token] != 0) continue; if(uniform) { uniform_byte_counts[token] = 1; uniform_byte_count++; if (uniform_byte_count == bytes_count) { uniform_byte_count = 0; for (int j = 0; j < 256; j++) uniform_byte_counts[j] = 0; } } return token; } // never here return token; }
the_stack_data/190767102.c
ClearTheScreen(); DrawTheScene(); CompleteDrawing(); SwapBuffers();
the_stack_data/234518689.c
#include <stdio.h> #include <stdlib.h> #define N 32 #define REAL float #define OFFSET1D(x) (x) #define OFFSET3D(x, y, z) ((x) + (y) * N + (z) * N * N) void kernel(float *g1, float *g2, float *i, float *j, float *k) { int x, y, z; for (z = 1; z < N-1; ++z) { for (y = 1; y < N-1; ++y) { for (x = 1; x < N-1; ++x) { float v = g1[OFFSET3D(x, y, z)] + g1[OFFSET3D(x-1, y, z)] * i[OFFSET1D(x-1)] + g1[OFFSET3D(x+1, y, z)] * i[OFFSET1D(x+1)] + g1[OFFSET3D(x, y-1, z)] * j[OFFSET1D(y-1)] + g1[OFFSET3D(x, y+1, z)] * j[OFFSET1D(y+1)] + g1[OFFSET3D(x, y, z-1)] * k[OFFSET1D(z-1)] + g1[OFFSET3D(x, y, z+1)] * k[OFFSET1D(z+1)]; g2[OFFSET3D(x, y, z)] = v; } } } return; } void dump(float *input) { int i; for (i = 0; i < N*N*N; ++i) { printf("%f\n", input[i]); } } int main(int argc, char *argv[]) { REAL *g1, *g2, *k; size_t nelms = N*N*N; g1 = (REAL *)malloc(sizeof(REAL) * nelms); g2 = (REAL *)malloc(sizeof(REAL) * nelms); k = (REAL *)malloc(sizeof(REAL) * N); int i; for (i = 0; i < (int)nelms; i++) { g1[i] = i; g2[i] = i; } for (i = 0; i < N; ++i) { k[i] = 1 + (i%2); // 1 or 2 } kernel(g1, g2, k, k, k); dump(g2); free(g1); free(g2); free(k); return 0; }
the_stack_data/1079234.c
// general protection fault in __free_pages // https://syzkaller.appspot.com/bug?id=3c1f47967b7cbd399d3ba3e65f297a29aa1c5f92 // status:open // autogenerated by syzkaller (http://github.com/google/syzkaller) #define _GNU_SOURCE #include <endian.h> #include <fcntl.h> #include <linux/futex.h> #include <pthread.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string.h> #include <sys/stat.h> #include <sys/syscall.h> #include <unistd.h> static uintptr_t syz_open_dev(uintptr_t a0, uintptr_t a1, uintptr_t a2) { if (a0 == 0xc || a0 == 0xb) { char buf[128]; sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block", (uint8_t)a1, (uint8_t)a2); return open(buf, O_RDWR, 0); } else { char buf[1024]; char* hash; strncpy(buf, (char*)a0, sizeof(buf)); buf[sizeof(buf) - 1] = 0; while ((hash = strchr(buf, '#'))) { *hash = '0' + (char)(a1 % 10); a1 /= 10; } return open(buf, a2, 0); } } static void execute_one(); extern unsigned long long procid; void loop() { while (1) { execute_one(); } } struct thread_t { int created, running, call; pthread_t th; }; static struct thread_t threads[16]; static void execute_call(int call); static int running; static void* thr(void* arg) { struct thread_t* th = (struct thread_t*)arg; for (;;) { while (!__atomic_load_n(&th->running, __ATOMIC_ACQUIRE)) syscall(SYS_futex, &th->running, FUTEX_WAIT, 0, 0); execute_call(th->call); __atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED); __atomic_store_n(&th->running, 0, __ATOMIC_RELEASE); syscall(SYS_futex, &th->running, FUTEX_WAKE); } return 0; } static void execute(int num_calls) { int call, thread; running = 0; for (call = 0; call < num_calls; call++) { for (thread = 0; thread < sizeof(threads) / sizeof(threads[0]); thread++) { struct thread_t* th = &threads[thread]; if (!th->created) { th->created = 1; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 128 << 10); pthread_create(&th->th, &attr, thr, th); } if (!__atomic_load_n(&th->running, __ATOMIC_ACQUIRE)) { th->call = call; __atomic_fetch_add(&running, 1, __ATOMIC_RELAXED); __atomic_store_n(&th->running, 1, __ATOMIC_RELEASE); syscall(SYS_futex, &th->running, FUTEX_WAKE); struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 20 * 1000 * 1000; syscall(SYS_futex, &th->running, FUTEX_WAIT, 1, &ts); if (running) usleep((call == num_calls - 1) ? 10000 : 1000); break; } } } } uint64_t r[1] = {0xffffffffffffffff}; void execute_call(int call) { long res; switch (call) { case 0: memcpy((void*)0x200000c0, "/dev/sg#", 9); res = syz_open_dev(0x200000c0, 0, 2); if (res != -1) r[0] = res; break; case 1: memcpy((void*)0x20000000, "\xb6\x3d\xb8\x5e\x1e\x8d\x02\x00\x00\x00\x00\x00" "\x3e\xf0\x01\x1d\xcc\x60\x6a\xed\x69\xd2\xbc\x70" "\x37\xce\xbc\x9b\xc2\xfe\xff\xff\xff\xff\xff\xff" "\xff\xe2\x2c\x9b\x16\x00\x96\xaa\x1f\xae", 46); syscall(__NR_write, r[0], 0x20000000, 0x2e); break; case 2: *(uint64_t*)0x2085dff0 = 0x20e94000; *(uint64_t*)0x2085dff8 = 0x10024; syscall(__NR_readv, r[0], 0x2085dff0, 0x146); break; } } void execute_one() { execute(3); } int main() { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); for (;;) { loop(); } }
the_stack_data/7951412.c
#include<stdio.h> #include<string.h> void split(char*,char*); int main(){ char path[100]="/bin/:sbin/:/usr/include/"; split(path,":"); return 0; } void split(char *str,char *e){ int len =strlen(str); int i=0,p=0,q=0; for(q=0;q<=len;q++){ if(str[q]==':' || str[q]=='\0'){ while(p<q){ printf("%c",str[p]); p++; } p=q+1; printf("\n"); } } }
the_stack_data/49925.c
#include <stdio.h> #include <stdint.h> static uint8_t bitrev7(uint8_t a) { uint8_t t; t = (a & 1) << 6; t |= (a & 2) << 4; t |= (a & 4) << 2; t |= (a & 8) << 0; t |= (a & 16) >> 2; t |= (a & 32) >> 4; t |= (a & 64) >> 6; return t; } int main(void) { unsigned int i, j, k; uint8_t t; printf("%hu, ", bitrev7(1)); printf("%hu, ", bitrev7(2)); printf("%hu, ", bitrev7(3)); for(i = 0; i < 4; ++i) { for(j = 4; j <= 32; j <<= 1) for(k = 0; k < j/4; ++k) printf("%hu, ", bitrev7(j + (j/4)*i + k)); for(k = 0; k < 8; ++k) printf("%hu, ", bitrev7(64 + 16*i + 2*k)); for(k = 0; k < 8; ++k) printf("%hu, ", bitrev7(64 + 16*i + 2*k+1)); } printf("\n"); }
the_stack_data/36075797.c
/* * info_types.c * * @author: phdenzel */ #include <stdio.h> #include <math.h> void explainTypes() { // types int integerType; short shortType; long longType; long long longlongType; float floatType; double doubleType; long double longdoubleType; char charType; // type sizes int i, s, l, ll, f, d, ld, c; i = sizeof(integerType); s = sizeof(shortType); l = sizeof(longType); ll= sizeof(longlongType); f = sizeof(floatType); d = sizeof(doubleType); ld= sizeof(longdoubleType); c = sizeof(charType); // number ranges long long imax, smax, cmax; imax = pow(2, 8*i-1)-1; smax = pow(2, 8*s-1)-1; cmax = pow(2, 8*c-1)-1; printf("char:\t\thas a size of %2d bytes, i.e. from -%10lld to %10lld\n", c, cmax+1, cmax); printf("short:\t\thas a size of %2d bytes, i.e. from -%10lld to %10lld\n", s, smax+1, smax); printf("int:\t\thas a size of %2d bytes, i.e. from -%10lld to %10lld\n", i, imax+1, imax); printf("long:\t\thas a size of %2d bytes, i.e. %3d bits\n", l, 8*l); printf("long long:\thas a size of %2d bytes, i.e. %3d bits\n", ll, 8*ll); printf("float:\t\thas a size of %2d bytes, i.e. %3d bits\n", f, 8*f); printf("double:\t\thas a size of %2d bytes, i.e. %3d bits\n", d, 8*d); printf("long double:\thas a size of %2d bytes, i.e. %3d bits\n", ld, 8*ld); } int main(int argc, char **argv) { printf("C-TYPES\n"); explainTypes(); printf("The values of numbers are evenly divided around 0.\n"); printf("To double the range of positive numbers for a type, use 'unsigned <type>'.\n"); return 0; }
the_stack_data/823746.c
#include <stdio.h> int test() { #if defined(__LLP64__) if (sizeof(short) == 2 && sizeof(int) == 4 && sizeof(long int) == 4 && sizeof(long long int) == 8 && sizeof(void*) == 8) { (void)printf("Ok\n"); } else { (void)printf("KO __LLP64__\n"); } #elif defined(__LP64__) if (sizeof(short) == 2 && sizeof(int) == 4 && sizeof(long int) == 8 && sizeof(long long int) == 8 && sizeof(void*) == 8) { (void)printf("Ok\n"); } else { (void)printf("KO __LP64__\n"); } #elif defined(__ILP32__) if (sizeof(short) == 2 && sizeof(int) == 4 && sizeof(long int) == 4 && sizeof(void*) == 4) { (void)printf("Ok\n"); } else { (void)printf("KO __ILP32__\n"); } #else (void)printf("KO no __*LP*__ defined.\n"); #endif } int main () { int x; x = test(); printf("%d\n", x); return 0; }
the_stack_data/150144489.c
/* * C Implementation of Kuhn's Hungarian Method * Copyright (C) 2003 Brian Gerkey <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <time.h> /* On WIN32, when NDEBUG is defined (i.e. when building Release), * assert defines to (void)(0) and all of the memory allocation * here fails. By undefining NDEBUG, we get assert back. * (DTS 10/20/10) */ #ifdef _WIN32 #undef NDEBUG #endif #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef _WIN32 /* mmap and unistd.h not available on win32 (DTS 1/19/10) */ #include <sys/mman.h> // for mmap #include <unistd.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> /* * routines to make assignment problems, e.g., randomly or from stored data */ #define MAXUTIL 1000 /* * makes and returns a pointer to an mXn rating matrix with values uniformly * distributed between 1 and MAXUTIL * * allocates storage, which the caller should free(). */ int* make_random_r(size_t m, size_t n) { int i,j; int* r; time_t curr; assert(r = malloc(sizeof(int)*m*n)); curr = time(NULL); srand(curr); for(i=0;i<m;i++) { for(j=0;j<n;j++) { r[i*n+j] = 1+(rand() % MAXUTIL); } } return(r); } #ifndef _WIN32 /* mmap not available on win32 (DTS 1/19/10) */ int* make_r_from_ORlib(char* fname, int* m, int* n) { int fd; int size; char* filebuf; int fileidx,tmpfileidx; int* r; int filesize; int i; if((fd = open(fname,O_RDONLY)) < 0) { perror("open()"); return(NULL); } // find out how big the file is - we need to mmap that many bytes filesize = lseek(fd, 0, SEEK_END); // map the input file into memory, so we can read it if((filebuf = (char*)mmap(0, filesize, PROT_READ, MAP_PRIVATE, fd, (off_t)0)) == MAP_FAILED) { perror("mmap()"); return(NULL); } close(fd); // can close fd once mapped // get the size of the problem if(sscanf(filebuf,"%d%n",&size,&fileidx) != 1) { puts("failed to get problem size from file"); return(NULL); } *m = *n = size; assert(r = malloc(sizeof(int)*size*size)); i=0; while(fileidx < filesize) { // read the next value, grabbing another line if necessary if(sscanf(filebuf+fileidx,"%d%n", r+i, &tmpfileidx) != 1) break; fileidx += tmpfileidx; i++; } return(r); } #endif
the_stack_data/591478.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define TSIZE 45 /** * 存储电影信息的结构体 */ struct film { char title[TSIZE]; int rating; struct film * next; }; char s_gets(char * st, int n); /** * 电影信息 */ int main(void) { // 指向电信信息的头指针 struct film * head = NULL; // 保存当前电影信息和上一条电影信息 struct film * prev, * current; // 临时字符数组保存电影标题 char input[TSIZE]; puts("Enter first movie title:"); while (s_gets(input, TSIZE) && input[0] != '\0') { // 为每一个电影信息分配内存 current = (struct film *) malloc(sizeof(struct film)); // 指定头指针 if (head == NULL) { head = current; } else { prev->next = current; } // 将当前电影信息指向下一部电影的指针设置为NULL current->next = NULL; // 存储电影名称 strcpy(current->title, input); puts("Enter you rating <0-10>:"); scanf("%d", &current->rating); // 过滤多余字符 while (getchar() != '\n') { continue; } puts("Enter next movie title (empty line to stop):"); // 将当前电影存储为上一部电影 prev = current; } if (head == NULL) { puts("No data entered."); } else { puts("Here is the movies list:"); // 打印电影信息,不能直接使用头指针,避免链表头指针被破坏 current = head; while (current != NULL) { printf("Movie: %s, Rating %d;\n", current->title, current->rating); current = current->next; } // 释放内存 // 在许多环境中,程序结束都会自动释放malloc()分配的内存。但是,最好还是成对调用malloc()和free() // 因此,程序在清理内存时为每个已分配的结构都调用free()函数 current = head; while (current != NULL) { current = head; head = current->next; free(current); } } puts("Bye!"); return 0; }
the_stack_data/14201203.c
#include <stdio.h> #include <stdbool.h> // 自己写一个偷懒版的 isBadVersion() bool isBadVersion(int version) { // [1, 2, 3, 4, 5, ..., 100000000, ...] // [G, G, G, G, G, ..., B, B, B, ...] return version >= 100000000; } // [first, last) unsigned int binarySearch(unsigned int first, unsigned int last) { unsigned int mid = first + (last - first) / 2; if (isBadVersion(mid) && !isBadVersion(mid - 1)) return mid; if (!isBadVersion(mid)) return binarySearch(mid + 1, last); return binarySearch(first, mid); } int firstBadVersion(int n) { // signed integer overflow: 2147483647 + 1 cannot be represented in type 'int' return binarySearch(1, (unsigned int)n + 1); } int main() { int ans = firstBadVersion(2147483647); printf("first bad version: %d\n", ans); return 0; }
the_stack_data/259173.c
#include<stdio.h> int main() { int a,b,c; int cnt=0; for(a=1; a<=4; a++){ for(b=1; b<=4; b++){ if(a==b)continue; for(c=1; c<=4; c++) { if(c==b||c==a)continue; printf("%d ",a*100+b*10+c); ++cnt; } } } printf("\n%d\n",cnt); }
the_stack_data/98575268.c
int ft_strlen(char *str) { int length; length = 0; while (str[length]) { length++; } return (length); }
the_stack_data/137412.c
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main (int argc, char **argv) { int aflag = 0; int bflag = 0; char *cvalue = NULL; int index; int c; opterr = 0; while ((c = getopt (argc, argv, "abc:")) != -1) switch (c) { case 'a': aflag = 1; break; case 'b': bflag = 1; break; case 'c': cvalue = optarg; break; case '?': if (optopt == 'c') fprintf (stderr, "Option -%c requires an argument.\n", optopt); else if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: abort (); } printf ("aflag = %d, bflag = %d, cvalue = %s\n", aflag, bflag, cvalue); for (index = optind; index < argc; index++) printf ("Non-option argument %s\n", argv[index]); return 0; }
the_stack_data/110354.c
/* gcc -std=c17 -lc -lm -pthread -o ../_build/c/string_wide_wcscpy.exe ./c/string_wide_wcscpy.c && (cd ../_build/c/;./string_wide_wcscpy.exe) https://en.cppreference.com/w/c/string/wide/wcscpy */ #include <wchar.h> #include <stdio.h> #include <locale.h> int main(void) { wchar_t *src = L"犬 means dog"; // src[0] = L'狗' ; // this would be undefined behavior wchar_t dst[wcslen(src) + 1]; // +1 to accommodate for the null terminator wcscpy(dst, src); dst[0] = L'狗'; // OK setlocale(LC_ALL, "en_US.utf8"); printf("src = %ls\ndst = %ls\n", src, dst); }
the_stack_data/103264330.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdint.h> #include <string.h> #include <errno.h> #include <time.h> #include <stdarg.h> #include <syslog.h> #define LOG_MESSAGE_SIZE 256 static int _syslog = 0; static char *levels[] = { "EMERG", "ALERT", "CRIT", "ERR", "WARNING", "NOTICE", "INFO", "DEBUG" }; static char *colors[] = { "\e[01;31m", "\e[01;31m", "\e[01;31m", "\e[01;31m", "\e[01;33m", "\e[01;33m", "\e[01;32m", "\e[01;36m" }; void logger_log(uint32_t level, const char *msg, ...) { char timestr[20]; time_t curtime = time(NULL); struct tm *loctime = localtime(&curtime); char tmp[LOG_MESSAGE_SIZE]; va_list ap; va_start(ap, msg); vsnprintf(tmp, LOG_MESSAGE_SIZE, msg, ap); va_end(ap); if (_syslog) { syslog(level, "[%s] %s", levels[level], tmp); } else { strftime(timestr, 20, "%Y/%m/%d %H:%M:%S", loctime); fprintf(stderr, "%s%s [%s]\e[0m: %s\n", colors[level], timestr, levels[level], tmp); } } void logger_stderr(const char *msg, ...) { char timestr[20]; time_t curtime = time(NULL); struct tm *loctime = localtime(&curtime); char tmp[LOG_MESSAGE_SIZE]; va_list ap; va_start(ap, msg); vsnprintf(tmp, LOG_MESSAGE_SIZE, msg, ap); va_end(ap); strftime(timestr, 20, "%Y/%m/%d %H:%M:%S", loctime); fprintf(stderr, "\e[01;31m%s [%s]\e[0m: %s\n", timestr, levels[LOG_ERR], tmp); } int logger_init(int syslog) { _syslog = syslog; return 0; }
the_stack_data/56869.c
//***************************************************************************** // // startup_gcc.c - Startup code for use with GNU tools. // // Copyright (c) 2009-2012 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 9107 of the DK-LM3S9B96 Firmware Package. // //***************************************************************************** //***************************************************************************** // // Forward declaration of the default fault handlers. // //***************************************************************************** void ResetISR(void); static void NmiSR(void); static void FaultISR(void); static void IntDefaultHandler(void); //***************************************************************************** // // External declarations for the interrupt handlers used by the application. // //***************************************************************************** extern void TouchScreenIntHandler(void); extern void SysTickHandler(void); //***************************************************************************** // // The entry point for the application. // //***************************************************************************** extern int main(void); //***************************************************************************** // // Reserve space for the system stack. // //***************************************************************************** static unsigned long pulStack[768]; //***************************************************************************** // // The vector table. Note that the proper constructs must be placed on this to // ensure that it ends up at physical address 0x0000.0000. // //***************************************************************************** __attribute__ ((section(".isr_vector"))) void (* const g_pfnVectors[])(void) = { (void (*)(void))((unsigned long)pulStack + sizeof(pulStack)), // The initial stack pointer ResetISR, // The reset handler NmiSR, // The NMI handler FaultISR, // The hard fault handler IntDefaultHandler, // The MPU fault handler IntDefaultHandler, // The bus fault handler IntDefaultHandler, // The usage fault handler 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved IntDefaultHandler, // SVCall handler IntDefaultHandler, // Debug monitor handler 0, // Reserved IntDefaultHandler, // The PendSV handler SysTickHandler, // The SysTick handler IntDefaultHandler, // GPIO Port A IntDefaultHandler, // GPIO Port B IntDefaultHandler, // GPIO Port C IntDefaultHandler, // GPIO Port D IntDefaultHandler, // GPIO Port E IntDefaultHandler, // UART0 Rx and Tx IntDefaultHandler, // UART1 Rx and Tx IntDefaultHandler, // SSI0 Rx and Tx IntDefaultHandler, // I2C0 Master and Slave IntDefaultHandler, // PWM Fault IntDefaultHandler, // PWM Generator 0 IntDefaultHandler, // PWM Generator 1 IntDefaultHandler, // PWM Generator 2 IntDefaultHandler, // Quadrature Encoder 0 IntDefaultHandler, // ADC Sequence 0 IntDefaultHandler, // ADC Sequence 1 IntDefaultHandler, // ADC Sequence 2 TouchScreenIntHandler, // ADC Sequence 3 IntDefaultHandler, // Watchdog timer IntDefaultHandler, // Timer 0 subtimer A IntDefaultHandler, // Timer 0 subtimer B IntDefaultHandler, // Timer 1 subtimer A IntDefaultHandler, // Timer 1 subtimer B IntDefaultHandler, // Timer 2 subtimer A IntDefaultHandler, // Timer 2 subtimer B IntDefaultHandler, // Analog Comparator 0 IntDefaultHandler, // Analog Comparator 1 IntDefaultHandler, // Analog Comparator 2 IntDefaultHandler, // System Control (PLL, OSC, BO) IntDefaultHandler, // FLASH Control IntDefaultHandler, // GPIO Port F IntDefaultHandler, // GPIO Port G IntDefaultHandler, // GPIO Port H IntDefaultHandler, // UART2 Rx and Tx IntDefaultHandler, // SSI1 Rx and Tx IntDefaultHandler, // Timer 3 subtimer A IntDefaultHandler, // Timer 3 subtimer B IntDefaultHandler, // I2C1 Master and Slave IntDefaultHandler, // Quadrature Encoder 1 IntDefaultHandler, // CAN0 IntDefaultHandler, // CAN1 IntDefaultHandler, // CAN2 IntDefaultHandler, // Ethernet IntDefaultHandler, // Hibernate IntDefaultHandler, // USB0 IntDefaultHandler, // PWM Generator 3 IntDefaultHandler, // uDMA Software Transfer IntDefaultHandler, // uDMA Error IntDefaultHandler, // ADC1 Sequence 0 IntDefaultHandler, // ADC1 Sequence 1 IntDefaultHandler, // ADC1 Sequence 2 IntDefaultHandler, // ADC1 Sequence 3 IntDefaultHandler, // I2S0 IntDefaultHandler, // External Bus Interface 0 IntDefaultHandler // GPIO Port J }; //***************************************************************************** // // The following are constructs created by the linker, indicating where the // the "data" and "bss" segments reside in memory. The initializers for the // for the "data" segment resides immediately following the "text" segment. // //***************************************************************************** extern unsigned long _etext; extern unsigned long _data; extern unsigned long _edata; extern unsigned long _bss; extern unsigned long _ebss; //***************************************************************************** // // This is the code that gets called when the processor first starts execution // following a reset event. Only the absolutely necessary set is performed, // after which the application supplied entry() routine is called. Any fancy // actions (such as making decisions based on the reset cause register, and // resetting the bits in that register) are left solely in the hands of the // application. // //***************************************************************************** void ResetISR(void) { unsigned long *pulSrc, *pulDest; // // Copy the data segment initializers from flash to SRAM. // pulSrc = &_etext; for(pulDest = &_data; pulDest < &_edata; ) { *pulDest++ = *pulSrc++; } // // Zero fill the bss segment. // __asm(" ldr r0, =_bss\n" " ldr r1, =_ebss\n" " mov r2, #0\n" " .thumb_func\n" "zero_loop:\n" " cmp r0, r1\n" " it lt\n" " strlt r2, [r0], #4\n" " blt zero_loop"); // // Call the application's entry point. // main(); } //***************************************************************************** // // This is the code that gets called when the processor receives a NMI. This // simply enters an infinite loop, preserving the system state for examination // by a debugger. // //***************************************************************************** static void NmiSR(void) { // // Enter an infinite loop. // while(1) { } } //***************************************************************************** // // This is the code that gets called when the processor receives a fault // interrupt. This simply enters an infinite loop, preserving the system state // for examination by a debugger. // //***************************************************************************** static void FaultISR(void) { // // Enter an infinite loop. // while(1) { } } //***************************************************************************** // // This is the code that gets called when the processor receives an unexpected // interrupt. This simply enters an infinite loop, preserving the system state // for examination by a debugger. // //***************************************************************************** static void IntDefaultHandler(void) { // // Go into an infinite loop. // while(1) { } }
the_stack_data/987222.c
/* Copyright (C) 1992-2020 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <https://www.gnu.org/licenses/>. */ #include <dirent.h> #if !_DIRENT_MATCHES_DIRENT64 # include <string.h> int versionsort (const struct dirent **a, const struct dirent **b) { return __strverscmp ((*a)->d_name, (*b)->d_name); } #endif
the_stack_data/156394530.c
/* $Log: tcas.c,v $ * Revision 10/2020 elbaum -- fault version -- _fl1.c * */ #include <stdio.h> #include <stdlib.h> #define OLEV 600 /* in feets/minute */ #define MAXALTDIFF 600 /* max altitude difference in feet */ #define MINSEP 300 /* min separation in feet */ #define NOZCROSS 100 /* in feet */ /* variables */ typedef int bool; int Cur_Vertical_Sep; bool High_Confidence; bool Two_of_Three_Reports_Valid; int Own_Tracked_Alt; int Own_Tracked_Alt_Rate; int Other_Tracked_Alt; int Alt_Layer_Value; /* 0, 1, 2, 3 */ int Positive_RA_Alt_Thresh[4]; int Up_Separation; int Down_Separation; /* state variables */ int Other_RAC; /* NO_INTENT, DO_NOT_CLIMB, DO_NOT_DESCEND */ #define NO_INTENT 0 #define DO_NOT_CLIMB 1 #define DO_NOT_DESCEND 2 int Other_Capability; /* TCAS_TA, OTHER */ #define TCAS_TA 1 #define OTHER 2 int Climb_Inhibit; /* true/false */ #define UNRESOLVED 0 #define UPWARD_RA 1 #define DOWNWARD_RA 2 void initialize() { Positive_RA_Alt_Thresh[0] = 400; Positive_RA_Alt_Thresh[1] = 500; Positive_RA_Alt_Thresh[2] = 640; Positive_RA_Alt_Thresh[3] = 740; } int ALIM () { return Positive_RA_Alt_Thresh[Alt_Layer_Value]; } int Inhibit_Biased_Climb () { //Mutant: [change '+' into '-'] return (Climb_Inhibit ? Up_Separation - NOZCROSS : Up_Separation); } bool Own_Below_Threat() { return (Own_Tracked_Alt < Other_Tracked_Alt); } bool Own_Above_Threat() { return (Other_Tracked_Alt < Own_Tracked_Alt); } bool Non_Crossing_Biased_Climb() { int upward_preferred; bool result; upward_preferred = Inhibit_Biased_Climb() > Down_Separation; if (upward_preferred) { result = !(Own_Below_Threat()) || ((Own_Below_Threat()) && (!(Down_Separation >= ALIM()))); } else { result = Own_Above_Threat() && (Cur_Vertical_Sep >= MINSEP) && (Up_Separation >= ALIM()); } return result; } bool Non_Crossing_Biased_Descend() { int upward_preferred; bool result; upward_preferred = Inhibit_Biased_Climb() > Down_Separation; if (upward_preferred) { result = Own_Below_Threat() && (Cur_Vertical_Sep >= MINSEP) && (Down_Separation >= ALIM()); } else { result = Own_Above_Threat() && (Up_Separation >= ALIM()); } return result; } int alt_sep_test() { bool enabled, tcas_equipped, intent_not_known; bool need_upward_RA, need_downward_RA; int alt_sep; enabled = High_Confidence && (Own_Tracked_Alt_Rate <= OLEV); tcas_equipped = Other_Capability == TCAS_TA; intent_not_known = Two_of_Three_Reports_Valid && Other_RAC == NO_INTENT; alt_sep = UNRESOLVED; if (enabled && ((tcas_equipped && intent_not_known) || !tcas_equipped)) { need_upward_RA = Non_Crossing_Biased_Climb() && Own_Below_Threat(); need_downward_RA = Non_Crossing_Biased_Descend() && Own_Above_Threat(); if (need_upward_RA && need_downward_RA) /* intentionally unreachable: requires Own_Below_Threat and Own_Above_Threat to both be true - that requires Own_Tracked_Alt < Other_Tracked_Alt and Other_Tracked_Alt < Own_Tracked_Alt, which isn't possible */ alt_sep = UNRESOLVED; else if (need_upward_RA) alt_sep = UPWARD_RA; else if (need_downward_RA) alt_sep = DOWNWARD_RA; else alt_sep = UNRESOLVED; } return alt_sep; } int main(argc, argv) int argc; char *argv[]; { if(argc < 13) { fprintf(stdout, "Error: Command line arguments"); exit(1); } initialize(); Cur_Vertical_Sep = atoi(argv[1]); High_Confidence = atoi(argv[2]); Two_of_Three_Reports_Valid = atoi(argv[3]); Own_Tracked_Alt = atoi(argv[4]); Own_Tracked_Alt_Rate = atoi(argv[5]); Other_Tracked_Alt = atoi(argv[6]); Alt_Layer_Value = atoi(argv[7]); Up_Separation = atoi(argv[8]); Down_Separation = atoi(argv[9]); Other_RAC = atoi(argv[10]); Other_Capability = atoi(argv[11]); Climb_Inhibit = atoi(argv[12]); fprintf(stdout, "%d\n", alt_sep_test()); exit(0); }
the_stack_data/200143996.c
/* Copyright (c) Microsoft Corporation. Licensed under the MIT License. */ #include <errno.h> #include <stdint.h> #include <stdio.h> #include <sys/stat.h> extern int errno; extern int _end; void* _sbrk(int incr) { static unsigned char* heap = NULL; unsigned char* prev_heap; if (heap == NULL) { heap = (unsigned char*)&_end; } prev_heap = heap; heap += incr; return prev_heap; } int _close(int file) { return -1; } int _fstat(int file, struct stat* st) { st->st_mode = S_IFCHR; return 0; } int _isatty(int file) { return 1; } int _lseek(int file, int ptr, int dir) { return 0; } void _exit(int status) { printf("Exiting with status %d.\n", status); while (1) ; } void _kill(int pid, int sig) { return; } int _getpid(void) { return -1; }
the_stack_data/218892068.c
/* * COMPILE LINE (icc): -Ofast -fno-alias -xCORE-AVX2 -xHost -fma -use-intel-optimized-headers -falign-loops -qopenmp -parallel -pthread -ipo -vec */ #define _XOPEN_SOURCE 700 #define _GNU_SOURCE #define N_default 1000 #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char** argv) { unsigned long int N = N_default; unsigned long int nthreads = 1; double S = 0; if (argc > 1) N = atoi(*(argv + 1)); N++; #pragma omp parallel default(none) shared(N, nthreads, S) { #pragma omp master { nthreads = omp_get_num_threads(); } unsigned long int me = omp_get_thread_num(); // No need to do this inside a `single` subregion or outside the `parallel` region. // Computational overhead due to duplication if minimal for realistic nthreads and // in this way there is no need to put `barrier`s. unsigned long int partlen_base = (unsigned long int)(N / nthreads); unsigned long int remaind = N - partlen_base * nthreads; unsigned long int true_partlen = partlen_base + (unsigned long int)(me < remaind); unsigned long int mystart = me * true_partlen + remaind * (unsigned long int)(me >= remaind); unsigned long int mystop = mystart + true_partlen; double* array; // MEMORY ALLOCATION array = (double*)malloc(true_partlen * sizeof(double)); // MEMORY INITIALIZATION #pragma parallel for (unsigned long int ii = mystart; ii < mystop; ii++) { array[ii - mystart] = (double)ii; } double Slocal = 0; // this will store the summation #pragma parallel for (unsigned long int jj = 0; jj < true_partlen; jj++) { Slocal += array[jj]; } free(array); #pragma omp critical S += Slocal; } printf("%g SUM\n\n\n", S); return 0; }
the_stack_data/12637182.c
/* mask pixel x color --> dst */ #ifdef BUILD_MMX static void init_mask_pixel_color_span_funcs_mmx(void) { } #endif #ifdef BUILD_MMX static void init_mask_pixel_color_pt_funcs_mmx(void) { } #endif
the_stack_data/135941.c
#include <stdio.h> int main(){ int num1, num2, num3, sum, diff, mul; printf("Enter 3 Integers to Add Multiply or division :\n"); scanf("%d %d %d", &num1, &num2, &num3); sum = num1 + num2 + num3; diff = num1 - num2 - num3; mul = num1 * num2 * num3; printf("\n*** Results ***\nAddition : %d\nDiffrence : %d\nMultiplication : %d", sum, diff, mul); return 0; }
the_stack_data/181392938.c
#include <stdio.h> #include <stdlib.h> #include <string.h> void *aligned_alloc( size_t alignment, size_t size ); #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) int main(void) { size_t align = 128; size_t bytes = 100*align; char * buffer = aligned_alloc(align,bytes); printf("buffer = %p\n",buffer); memset(buffer,255,bytes); free(buffer); return 0; } #else #error You need C11 compiler. #endif
the_stack_data/225143579.c
#include<stdio.h> #include<sys/socket.h> #include <netinet/in.h> #include<arpa/inet.h> int main(int argc, char **argv){ // TCP 目标地址(数据结构) struct sockaddr_in addr; bzero(&addr, sizeof(addr)); addr.sin_family = AF_INET; // str->int->特殊十六进制数 addr.sin_port = htons(atoi("8888")); // 0.0.0.0:8888 addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 创建套接字描述符 int sock = socket(AF_INET, SOCK_STREAM, 0); // 修改套接字 connect(sock, (struct sockaddr*)&addr, sizeof(addr)); // 读取数据或发送数据 char buffer[] = "Hello"; write(sock, buffer, sizeof(buffer) - 1 ); close(sock); return 0; } // gcc -pthread -o tcp-client tcp-client.c && ./tcp-client
the_stack_data/504763.c
/* * Align function declarations. */ struct buffer *f1(void); void f2(void);
the_stack_data/978628.c
#include <stdlib.h> #include <stdio.h> #include <assert.h> #include <time.h> //count_by_1.c int main(int argc, char** argv) { int i = 0; int while_counter_1 = 0; while (while_counter_1 < 50) { printf("%d , %d , %d , %d \n", 1, while_counter_1++, 1, i); if (!(i < 1000000)) break; i = i + 1; } assert(i == 1000000); return 0; }
the_stack_data/161079772.c
/* * Created by Meissa project team in 2020 */ #include <sys/types.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> int main() { setsockopt(0, IPPROTO_IPV6, IPV6_RECVPKTINFO, NULL, 0); return 0; }
the_stack_data/783731.c
/** * Author: dhayalaarthi.com * Email: [email protected] **/ #include <stdio.h> int main() { char s[100]; scanf("%[^\n]%", &s); printf("Hello, World!\n%s", s); return 0; }
the_stack_data/15763314.c
#ifdef WINDOWS #include <windows.h> #include <time.h> void win_usleep(__int64 usec) { HANDLE timer; LARGE_INTEGER ft; ft.QuadPart = -(10*usec); // Convert to 100 nanosecond interval, negative value indicates relative time timer = CreateWaitableTimer(NULL, TRUE, NULL); SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0); WaitForSingleObject(timer, INFINITE); CloseHandle(timer); } double win_tock(void) { LARGE_INTEGER xfrequency; LARGE_INTEGER xtime; if ((QueryPerformanceFrequency(&xfrequency) != FALSE) && (QueryPerformanceCounter(&xtime) != FALSE)) return (double) (xtime.QuadPart)/xfrequency.QuadPart; else return (double)(clock()) / CLOCKS_PER_SEC; } #ifdef __llvm__ bool #else BOOL #endif win_is_dir(char* str) { DWORD dwAttrib = GetFileAttributes(str); return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); } #endif
the_stack_data/182953808.c
#include <stdio.h> #include <unistd.h> #include <sys/wait.h> int procuraRow(int v,int col,int l[col]) { int i,result=0; for (i = 0;!result && i < col;i++) { if (l[i] == v) result = 1; } return result; } int procura(int v,int row,int col,int m[row][col]) { int i,result = 0; for (i = 0; !result && i < row; i++) { if (!fork()) _exit(procuraRow(v,col,m[i])); } for (i = 0; !result && i < row; i++) { int status; wait(&status); /*if (!WIFEXITED(status)) result = -1; assert(WIFEXITED(status))*/ if (WEXITSTATUS(status)) result = 1; } return result; } int main(int argc,char* argv[]) { int m[2][2] = {{1,2},{10,3}}; if (!procura(1,2,2,m)) printf("0\n"); else printf("1\n"); return 0; }
the_stack_data/107952619.c
#include <stdio.h> //#include <cs50.h> void print_space(int n); void print_hash(int n); int main() { int height, row, space, hash; do { printf ("Height: "); scanf("%10d", &height); // height = get_int(); } while (height > 23 || height < 0); //filters user inputs; get_int rejects numbers less than zero int real_height = height + 1; for (row = 1; row < real_height; row++) { print_space(real_height - row); print_hash(row); printf(" "); print_hash(row); print_space(real_height - row); printf("\n"); } } void print_space(int n) { for (int space = 0; space < n; space++) { printf(" "); } } void print_hash(int n) { for (int hash = 0; hash < n; hash++) { printf ("#"); } }
the_stack_data/44460.c
/* * Copyright (C) 1988 Research Institute for Advanced Computer Science. * All rights reserved. The RIACS Software Policy contains specific * terms and conditions on the use of this software, and must be * distributed with any copies. This file may be redistributed. This * copyright and notice must be preserved in all copies made of this file. */ /* * rletoabA62 * ---------- * * This program converts Utah Raster Toolkit files into the dump format of the * Abekas A62 video storage disk. * * Options: * -N ... do no digital filtering. * -n N ... N specifies the number for frames to write * -f N ... N specifies the first frame number (1-4) to write. * -b R G B ... clear background to this color * * Author/Status: * Bob Brown [email protected] * First write: 29 Jan 1988 * * The interface to the particular raster format used is mostly separated from * the logic of the conversion code. Two routines define the interface: * * rasterInit(fd, width, height) * * This specifies the integer file descriptor for the input file, * the width and the height of the image. It is called exactly once. * * rasterGetRow(red, green, blue) * * This is called to return the next row of the raster. The parameters * point to arrays of unsigned char to hold the RGB values. */ static char rcsid[] = "$Header$"; /* rletoabA62() Tag the file. */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif typedef char bool; /* * Dimensions of the raster image within the A62 */ #define WIDTH 768 #define HEIGHT 512 /* * Global variables are always capitalized. * * These are globals set by program arguments. The static initializations are * the default values. */ int Width = WIDTH; /* Width of the output image */ int Height = HEIGHT; /* Height of the output image */ int Debug = 0; bool NoFilter = FALSE; int Frame = 1; int NumFrames = 2; int BkgRed = 0; int BkgBlue = 0; int BkgGreen= 0; extern char *optarg; /* interface to getopt() */ extern int optind; /* interface to getopt() */ typedef struct { char y, i, q; } yiq_t; #ifdef USE_PROTOTYPES extern void rasterInit(int fd, int width, int height); extern void rasterRowGet(unsigned char *red, unsigned char *green, unsigned char *blue); extern void rasterDone(void); extern void filterY(float *yVal, float c0, float c1, float c2); extern void filterIQ(float *iqVal, float c0, float c1, float c2, int start, int stride); extern void dump1(register yiq_t **raster, int start); extern void dump2(register yiq_t **raster, int start); #else extern void rasterInit(); extern void rasterRowGet(), rasterDone(); extern void filterY(); extern void filterIQ(); extern void dump1(); extern void dump2(); #endif /* * Main entry... */ int main(int argc,char *argv[]) { register int i, j; int errors, c, file; float rTOy[256], gTOy[256], bTOy[256]; float rTOi[256], gTOi[256], bTOi[256]; float rTOq[256], gTOq[256], bTOq[256]; float *iVal, *yVal, *qVal, *tmpVal; unsigned char *red, *green, *blue; int r, g, b; yiq_t **raster; /* * Parse program arguments... * * The -w and -h args should actually not be used. */ errors = 0; while ((c = getopt(argc, argv, "Nn:f:w:h:d:D:b")) != EOF) { switch (c) { case 'b': BkgRed = atoi(argv[optind++]); BkgGreen = atoi(argv[optind++]); BkgBlue = atoi(argv[optind++]); break; case 'N': NoFilter = TRUE; break; case 'w': Width = atoi(optarg); break; case 'f': Frame = atoi(optarg); break; case 'n': NumFrames = atoi(optarg); break; case 'h': Height = atoi(optarg); break; case 'D': Debug = atoi(optarg); break; case '?': errors++; } } if (errors > 0) { fprintf(stderr, "Usage: %s [-n] [-D debug-level] [file]\n", argv[0]); exit(1); } if (optind < argc) { if ((file = open(argv[optind], 0)) < 0) { perror(argv[optind]); exit(1); } } else { file = 0; } /* * Initialize the type manager for Utah RLE files */ rasterInit(file, Width, Height, BkgRed, BkgGreen, BkgBlue); /* * Allocate storage for the RGB inputs, the computed YIQ, and the * results. This is all dynamically allocated because the dimensions of * the framestore are only decided at run time. * * The YIQ arrays are extended two entries at either end to simplify the * filtering code. The effect is that the iVal and qVal arrays can be * indexed [-2 .. Width+2] and yVal [-4 .. Width+4] (the stuff at the * end of the yVal array isn't used). */ red = (unsigned char *) calloc(Width, sizeof *red); green = (unsigned char *) calloc(Width, sizeof *green); blue = (unsigned char *) calloc(Width, sizeof *blue); tmpVal = (float *) calloc(Width + 8, sizeof *yVal); yVal = tmpVal + 4; tmpVal = (float *) calloc(Width + 4, sizeof *iVal); iVal = tmpVal + 2; tmpVal = (float *) calloc(Width + 4, sizeof *qVal); qVal = tmpVal + 2; /* * Allocate storage to hold the 8-bit YIQ values for the entire * picture. */ raster = (yiq_t **) calloc(Height, sizeof *raster); for (i = 0; i < Height; i++) { raster[i] = (yiq_t *) calloc(Width, sizeof **raster); } /* * Build the mappings from R,G,B to Y,I,Q. The pedastal is factored * into this mapping. */ for (i = 0; i < 256; i++) { rTOy[i] = ((float) i / 255.0 * 0.925 + 0.075) * 0.299; gTOy[i] = ((float) i / 255.0 * 0.925 + 0.075) * 0.587; bTOy[i] = ((float) i / 255.0 * 0.925 + 0.075) * 0.114; rTOi[i] = ((float) i / 255.0 * 0.925 + 0.075) * 0.596; gTOi[i] = ((float) i / 255.0 * 0.925 + 0.075) * -0.274; bTOi[i] = ((float) i / 255.0 * 0.925 + 0.075) * -0.322; rTOq[i] = ((float) i / 255.0 * 0.925 + 0.075) * 0.211; gTOq[i] = ((float) i / 255.0 * 0.925 + 0.075) * -0.523; bTOq[i] = ((float) i / 255.0 * 0.925 + 0.075) * 0.312; } /* * process the input raster line by raster line */ for (i = 0; i < Height; i++) { rasterRowGet(red, green, blue); yVal[-4] = yVal[-3] = yVal[-2] = yVal[-1] = 0; iVal[-2] = iVal[-1] = 0; qVal[-2] = qVal[-1] = 0; yVal[Width + 3] = yVal[Width + 2] = yVal[Width + 1] = yVal[Width + 0] = 0; iVal[Width + 0] = iVal[Width + 1] = 0; qVal[Width + 0] = qVal[Width + 1] = 0; /* * Convert RGB to YIQ. The multiplication is done by table lookup * into the [rgb]TO[yiq] arrays. */ for (j = 0; j < Width; j++) { r = red[j]; g = green[j]; b = blue[j]; yVal[j] = rTOy[r] + gTOy[g] + bTOy[b]; iVal[j] = rTOi[r] + gTOi[g] + bTOi[b]; qVal[j] = rTOq[r] + gTOq[g] + bTOq[b]; } if (!NoFilter) { filterY(yVal, 0.62232, 0.21732, -0.02848); filterIQ(iVal, 0.42354, 0.25308, 0.03515, 0, 2); filterIQ(qVal, 0.34594, 0.25122, 0.07581, 1, 2); } /* * Build the YIQ raster */ for (j = 0; j < Width; j++) { raster[Height - i - 1][j].y = yVal[j] * 140.0; raster[Height - i - 1][j].i = iVal[j] * 140.0; raster[Height - i - 1][j].q = qVal[j] * 140.0; } } /* * Dump the raster as four color fields. * * Assert that Width%4 ==0 and Height%4 == 0 * * Despite what the A62 SCSI manual says, for frames I and IV, the even * numbered lines (starting with line 0) begin Y-I and the others begin * Y+I. */ for (i = 0; i < NumFrames; i++) { switch ((i + Frame - 1) % 4 + 1) { case 1: dump2(raster, 0); /* even lines, starts Y-I */ break; case 2: dump1(raster, 1); /* odd lines, starts Y+I */ break; case 3: dump1(raster, 0); /* even lines, starts Y+I */ break; case 4: dump2(raster, 1); /* odd lines, starts Y-I */ break; } } return 0; } /* * filterY * ------- * * Apply and RIF filter to the luminance data. The signal is shifted two pixels * to the right in the process. * * The multiplier arrays m0, m1, and m2 exist to reduce the number of floating * point multiplications and to allow the filtering to occur in place. */ void filterY(yVal, c0, c1, c2) float *yVal, c0, c1, c2; { static float *m0 = NULL; static float *m1 = NULL; static float *m2 = NULL; register int i; if (m1 == NULL) { m0 = (float *) calloc(Width + 8, sizeof(float)); m1 = (float *) calloc(Width + 8, sizeof(float)); m2 = (float *) calloc(Width + 8, sizeof(float)); } for (i = -4; i < Width + 4; i++) { m0[i] = c0 * yVal[i]; m1[i] = c1 * yVal[i]; m2[i] = c2 * yVal[i]; } for (i = 0; i < Width; i++) { yVal[i] = m2[i - 4] + m1[i - 3] + m0[i - 2] + m1[i - 1] + m2[i]; } } /* * filterIQ * -------- * * Apply and RIF filter to the color difference data. * * The multiplier arrays m0, m1, and m2 exist to reduce the number of floating * point multiplications and to allow the filtering to occur in place. * * The "start" and "stride" parameters are used to reduce the number of * computations because I and Q are only used every other pixel. * * This is different from the manual in than the filtering is done on adjacent * pixels, rather than every other pixel. This may be a problem... */ void filterIQ(iqVal, c0, c1, c2, start, stride) float *iqVal, c0, c1, c2; int start, stride; { static float *m0 = NULL; static float *m1 = NULL; static float *m2 = NULL; register int i; if (m1 == NULL) { m0 = (float *) calloc(Width + 4, sizeof(float)); m1 = (float *) calloc(Width + 4, sizeof(float)); m2 = (float *) calloc(Width + 4, sizeof(float)); } for (i = -2; i < Width + 2; i++) { m0[i] = c0 * iqVal[i]; m1[i] = c1 * iqVal[i]; m2[i] = c2 * iqVal[i]; } for (i = start; i < Width; i += stride) { iqVal[i] = m2[i - 2] + m1[i - 1] + m0[i] + m1[i + 1] + m2[i + 2]; } } /* * dump1 * ----- * * Dumps the raster starting with the sequence Y+I Y+Q Y-I Y-Q * * This routine also adds 60 to put the data in the 60 .. 200 range. */ #define OUT(y, OP, iq) putc((char) (raster[i][j + 0].y OP raster[i][j + 0].iq + 60), stdout); void dump1(raster, start) register yiq_t **raster; int start; { register int i, j; for (i = start; i < Height; i += 4) { /* field I */ for (j = 0; j < Width; j += 4) { putc((char) (raster[i][j + 0].y + raster[i][j + 0].i + 60), stdout); putc((char) (raster[i][j + 1].y + raster[i][j + 1].q + 60), stdout); putc((char) (raster[i][j + 2].y - raster[i][j + 2].i + 60), stdout); putc((char) (raster[i][j + 3].y - raster[i][j + 3].q + 60), stdout); } for (j = 0; j < Width; j += 4) { putc((char) (raster[i + 2][j + 0].y - raster[i + 2][j + 0].i + 60), stdout); putc((char) (raster[i + 2][j + 1].y - raster[i + 2][j + 1].q + 60), stdout); putc((char) (raster[i + 2][j + 2].y + raster[i + 2][j + 2].i + 60), stdout); putc((char) (raster[i + 2][j + 3].y + raster[i + 2][j + 3].q + 60), stdout); } } } /* * dump2 * ----- * * Dumps the raster starting with the sequence Y-I Y-Q Y+I Y+Q * * This routine also adds 60 to put the data in the 60 .. 200 range. */ void dump2(raster, start) register yiq_t **raster; int start; { register int i, j; for (i = start; i < Height; i += 4) { /* field I */ for (j = 0; j < Width; j += 4) { putc((char) (raster[i][j + 0].y - raster[i][j + 0].i + 60), stdout); putc((char) (raster[i][j + 1].y - raster[i][j + 1].q + 60), stdout); putc((char) (raster[i][j + 2].y + raster[i][j + 2].i + 60), stdout); putc((char) (raster[i][j + 3].y + raster[i][j + 3].q + 60), stdout); } for (j = 0; j < Width; j += 4) { putc((char) (raster[i + 2][j + 0].y + raster[i + 2][j + 0].i + 60), stdout); putc((char) (raster[i + 2][j + 1].y + raster[i + 2][j + 1].q + 60), stdout); putc((char) (raster[i + 2][j + 2].y - raster[i + 2][j + 2].i + 60), stdout); putc((char) (raster[i + 2][j + 3].y - raster[i + 2][j + 3].q + 60), stdout); } } }
the_stack_data/63326.c
#include<stdio.h> #include<unistd.h> int main(void){ char buf[BUFSIZ]; int bufsize; getcwd(buf,BUFSIZ); printf("%s\n",buf); return 0; }
the_stack_data/50137008.c
/* Test for warnings for overriding designated initializers: -Woverride-init. Bug 24010. */ /* Origin: Joseph Myers <[email protected]> */ /* { dg-do compile } */ /* { dg-options "-Woverride-init" } */ struct s { int a; int b; int c; }; union u { char a; long long b; }; struct s s0 = { .a = 1, .b = 2, .a = 3, /* { dg-warning "initialized field overwritten|near init" } */ 4, /* { dg-warning "initialized field overwritten|near init" } */ 5 }; union u u0 = { .a = 1, .b = 2, /* { dg-warning "initialized field overwritten|near init" } */ .a = 3 }; /* { dg-warning "initialized field overwritten|near init" } */ int a[5] = { [0] = 1, [1] = 2, [0] = 3, /* { dg-warning "initialized field overwritten|near init" } */ [2] = 4 };
the_stack_data/642552.c
/*Exercicios de Revisaso: Noçoes basicas de C. 01/09/2021 - Mariane Bedia de Andrade*/ #include <stdio.h> //Inclui biblioteca de entrada e saida #include <stdlib.h> //standard library - Ela possui funçoes envolvendo alocaçao de memoria, controle de processos, conversoes e outras. int main() { int val1, val2, val3;// definiçao de variaveis printf("-------------------------------------\n"); printf("\t NUMEROS CRESCENTES \n"); printf("-------------------------------------\n"); printf("\n DIGITE O 1o VALOR:"); scanf ("%d", &val1); printf("*O valor digitado foi: %d \n",val1); printf("\n DIGITE O 2o VALOR:"); scanf ("%d", &val2); printf("*O valor digitado foi: %d \n",val2); printf("\n DIGITE O 3o VALOR:"); scanf ("%d", &val3); printf("*O valor digitado foi: %d \n",val3); printf("-------------------------------------\n"); printf("\t NUMEROS CRESCENTES \n"); printf("-------------------------------------\n"); if (val1<=val2 && val1<=val3) { printf("%d",val1); if (val2<=val3) { printf("\n %d",val2); printf("\n %d",val3); } else { printf("\n %d", val3); printf("\n, %d",val2); } } if (val2<=val1 && val2<=val3) { printf("\n %d", val2); if (val3<=val1) { printf("\n %d",val3); printf("\n %d",val1); } else { printf("\n %d",val1); printf("\n %d",val3); } } if(val3<=val1 && val3<=val2) { printf("\n %d",val3); if(val1<=val2) { printf("\n %d",val1); printf("\n %d",val2); } else { printf("\n d%",val2); printf("\n d%",val1); } } return 0; }
the_stack_data/104827369.c
#include <stdio.h> void scilab_rt_hist3d_d2d0d0_(int in00, int in01, double matrixin0[in00][in01], double scalarin0, double scalarin1) { int i; int j; double val0 = 0; for (i = 0; i < in00; ++i) { for (j = 0; j < in01; ++j) { val0 += matrixin0[i][j]; } } printf("%f", val0); printf("%f", scalarin0); printf("%f", scalarin1); }
the_stack_data/92327879.c
//AtCoder Beginner 17 A #include <stdio.h> int main( void ){ double first[2]; double second[2]; double third[2]; int score; scanf( "%lf %lf" , &first[0] , &first[1] ); scanf( "%lf %lf" , &second[0] , &second[1] ); scanf( "%lf %lf" , &third[0] , &third[1] ); score = ( first[0] * (first[1]/10) ) + ( second[0] * (second[1]/10) ) + ( third[0] * (third[1]/10) ); printf( "%d\n" , score ); return 0; }
the_stack_data/107953591.c
/* str_swa.c */ #include <stdio.h> void str_swap(char *dst, char *src); int main() { char str1[80], str2[80]; printf("Input a string1: "); scanf("%s", str1); printf("Input a string2: "); scanf("%s", str2); str_swap(str1, str2); printf("string1: %s\n", str1); printf("string2: %s\n", str2); return 0; } void str_swap(char *dst, char *src) { char swap[80]; int i; for (i = 0; *(dst + i) != '\0'; i++){ swap[i] = *(dst + i); } swap[i] = '\0'; for (i = 0; *(src + i) != '\0'; i++){ *(dst + i) = *(src + i); } *(dst + i) = '\0'; for (i = 0; swap[i] != '\0'; i++){ *(src + i) = swap[i]; } *(src + i)= '\0'; }
the_stack_data/83660.c
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <locale.h> #include <ctype.h> #include <math.h> ///Decima quarta parte const int TAM = 100; void WriteTexto(char *nomeArq); void readTexto (char *nomeArq, int *vet); void WriteBinario (char *nomeArq); /* struct test{ int a; char b; char c; char f; int d; }ttt;*/ int main() { //printf("%d",sizeof(ttt)); setlocale(LC_CTYPE,"portuguese"); char nomeArq[20]; printf("\nDigite o nome do arquivo:\t"); fflush(stdin); gets(nomeArq); strcat(nomeArq,".txt"); WriteTexto(nomeArq); return 0; } void WriteTexto(char *nomeArq){ FILE *fp; int n; fp = fopen(nomeArq,"w"); if (fp==NULL){ printf("Erro ao fechar o arquivo\n"); exit(1); } for(n=0;n<TAM;n++) fprintf(fp, "%d",n); fclose(fp); } void readTexto (char *nomeArq, int *vet){ }
the_stack_data/145451936.c
#include <stdio.h> int main(){ int l,c,i,j,col1,col2,k,tot; printf("Inf QT de Linhas: "); scanf("%d",&l); printf("Inf QT de Colunas: "); scanf("%d",&c); tot=l+c; int vPar[tot],m[l][c]; // Coloco os valores na matriz for(i=0;i<l;i++){ for(j=0;j<c;j++){ printf("Inf Valor P/ L:%d C:%d : ",i,j); scanf("%d",&m[i][j]); } } // Printa a Matriz printf("\nMatriz\n"); for(i=0;i<l;i++){ printf("|"); for(j=0;j<c;j++){ printf("%d|",m[i][j]); } printf("\n"); } printf("Informe o Val de Duas Col: "); scanf("%d%d",&col1,&col2); k=0; vPar[k]; for(i=0;i<l;i++){ if((m[i][col1]%2)==0){ vPar[k]= m[i][col1]; k++; } if((m[i][col2]%2)==0){ vPar[k]=m[i][col2]; k++; } } printf("\nVetor Resultante\n|"); for(i=0;i<k;i++){ printf("%d|",vPar[i]); } printf("\n"); return 0; }
the_stack_data/115764240.c
# include <stdio.h> # include <math.h> #define it 1000 int actual_number = 0; int sequence[it]; int valueinarray(int val, int seq[]) { int i; for(i = 0; i < it; i++) { if(seq[i] == val){ return 1; } } return 0; } int recaman(int seq[] ,int c, int n){ int subs = n-c; if(valueinarray(subs,seq)==1 || subs<=0){ return n+c; } return subs; } void generar() { int i; for(i=0;i<it-1;i++) { sequence[i+1]=recaman(sequence,i+1,sequence[i]); } } int imprimirArreglo(char archivo[]) { int i; FILE *doc =fopen(archivo,"w+"); for(i = 0;i<it;i++){ fprintf(doc,"%d\n",sequence[i]); } return 0; } int main() { sequence[0] = 0; printf("%s%d%s\n","Generating the first ",it," recaman sequence numbers..."); generar(); int aa =imprimirArreglo("recaman.txt"); printf("%s","Done.\n"); return 0; }
the_stack_data/192330877.c
#include <stdio.h> int A[100][100], m, n, counter=0; int insert_matrix() { printf("Enter dimensions of matrix: "); scanf("%d %d", &m, &n); printf("\nEnter elements:\n"); for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { scanf("%d",&A[i][j]); } } } int is_sparse() { for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { if(A[i][j]==0) counter++; } } if(counter>(m*n/2)) printf("\nMatrix is sparse\n"); else printf("\nMatrix is not sparse\n"); } int tuple_matrix() { int element = m*n-counter; printf("\nRows\tColumn\tValue\n"); printf("%d\t%d\t%d\t\n", m, n, element); for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { if(A[i][j]!=0) printf("%d\t%d\t%d\t\n", i+1, j+1, A[i][j]); } } } int transpose_matrix() { for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { A[i][j] = A[j][i]; } } } int main() { insert_matrix(); is_sparse(); tuple_matrix(); return 0; }
the_stack_data/70451003.c
#include <stdio.h> void compare(char *str1, char *str2, int l1, int l2) { int same=0; if(l1 == l2) { int i=0; while(i<l1) { if(*(str1+i) != *(str2+i)) { same = 1; break; } i++; } if(same==0) { printf("Strings are Equal\n"); } else { if(*(str1+i) > *(str2+i)) { printf("1st String is greater than 2nd String\n"); } else { printf("2nd String is greater than 1st String\n"); } } } else { printf("Strings are Not Equal\n"); } } void findLength(char *str1, char *str2) { int i=0,l1=0,l2=0; while(*(str1+i) != '\0') { l1 = l1 + 1; i++; } i=0; while(*(str2+i) != '\0') { l2 = l2 + 1; i++; } compare(str1,str2,l1,l2); } int main() { printf("Comparing Two String\n"); printf("********************\n\n"); char str1[100], str2[100]; printf("Enter 1st String : "); scanf("%[^\n]%*c",str1); printf("Enter 2nd String : "); scanf("%[^\n]%*c",str2); printf("\n"); findLength(str1,str2); return 0; }
the_stack_data/12638194.c
/* Copyright (c) 1991 Sun Wu and Udi Manber. All Rights Reserved. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <ctype.h> #define MAXSYM 256 #define MAXMEMBER 8192 #define CHARTYPE unsigned char #define MaxError 20 #define MAXPATT 256 #define MAXLINE 1024 #define MaxCan 2048 #define BLOCKSIZE 8192 #define MAX_SHIFT_2 4096 #define ON 1 #define LOG_ASCII 8 #define LOG_DNA 3 #define MAXMEMBER_1 65536 #define LONG_EXAC 20 #define LONG_APPX 24 #define W_DELIM 128 extern COUNT, FNAME, SILENT, FILENAMEONLY, num_of_matched; extern DNA ; /* DNA flag is set in checksg when pattern is DNA pattern and p_size > 16 */ extern WORDBOUND, WHOLELINE, NOUPPER; extern unsigned char CurrentFileName[], Progname[]; extern unsigned Mask[]; extern unsigned endposition; unsigned char BSize; /* log_c m */ unsigned char char_map[MAXSYM]; /* data area */ int shift_1; CHARTYPE SHIFT[MAXSYM]; CHARTYPE MEMBER[MAXMEMBER]; CHARTYPE pat[MAXPATT]; unsigned Hashmask; char MEMBER_1[MAXMEMBER_1]; CHARTYPE TR[MAXSYM]; void char_tr(unsigned char *pat, int *m) { int i; unsigned char temp[MAXPATT]; for(i=0; i<MAXSYM; i++) TR[i] = i; if(NOUPPER) { for(i='A'; i<= 'Z'; i++) TR[i] = i + 'a' - 'A'; } if(WORDBOUND) { /* SUN: To be added to be more complete */ for(i=0; i<128; i++) { if(!isalnum(i)) TR[i] = W_DELIM; } } if(WHOLELINE) { memcpy(temp, pat, *m); pat[0] = '\n'; memcpy(pat+1, temp, *m); pat[*m+1] = '\n'; pat[*m+2] = 0; *m = *m + 2; } } void s_output (CHARTYPE *text, int *i) { int bp; if(SILENT) return; if(COUNT) { while(text[*i] != '\n') *i = *i + 1; return; } if(FNAME == ON) printf("%s: ", CurrentFileName); bp = *i; while(text[--bp] != '\n'); while(text[++bp] != '\n') putchar(text[bp]); putchar('\n'); *i = bp; } int verify(register int m, register int n, register int D, CHARTYPE *pat, CHARTYPE *text) { int A[MAXPATT], B[MAXPATT]; register int last = D; register int cost = 0; register int k, i, c; register int m1 = m+1; CHARTYPE *textend = text+n; CHARTYPE *textbegin = text; for (i = 0; i <= m1; i++) A[i] = B[i] = i; while (text < textend) { for (k = 1; k <= last; k++) { cost = B[k-1]+1; if (pat[k-1] != *text) { if (B[k]+1 < cost) cost = B[k]+1; if (A[k-1]+1 < cost) cost = A[k-1]+1; } else cost = cost -1; A[k] = cost; } if(pat[last] == *text++) { A[last+1] = B[last]; last++; } if(A[last] < D) A[last+1] = A[last++]+1; while (A[last] > D) last = last - 1; if(last >= m) return(text - textbegin - 1); if(*text == '\n') { last = D; for(c = 0; c<=m1; c++) A[c] = B[c] = c; } for (k = 1; k <= last; k++) { cost = A[k-1]+1; if (pat[k-1] != *text) { if (A[k]+1 < cost) cost = A[k]+1; if (B[k-1]+1 < cost) cost = B[k-1]+1; } else cost = cost -1; B[k] = cost; } if(pat[last] == *text++) { B[last+1] = A[last]; last++; } if(B[last] < D) B[last+1] = B[last++]+1; while (B[last] > D) last = last -1; if(last >= m) return(text - textbegin - 1); if(*text == '\n') { last = D; for(c = 0; c<=m1; c++) A[c] = B[c] = c; } } return(0); } /* SUN: bm assumes that the content of text[n]...text[n+m-1] is pat[m-1] such that the skip loop is guaranteed to terminated */ void bm(CHARTYPE *pat, int m, CHARTYPE *text, CHARTYPE *textend) { register int shift; register int m1, j, d1; /* printf("%d\t", textend - text); printf("%c, %c", *text, *textend); */ d1 = shift_1; /* at least 1 */ m1 = m - 1; shift = 0; while (text <= textend) { shift = SHIFT[*(text += shift)]; while(shift) { shift = SHIFT[*(text += shift)]; shift = SHIFT[*(text += shift)]; shift = SHIFT[*(text += shift)]; } j = 0; while(TR[pat[m1 - j]] == TR[*(text - j)]) { if(++j == m) break; /* if statement can be saved, but for safty ... */ } if (j == m ) { if(text > textend) return; if(WORDBOUND) { if(TR[*(text+1)] != W_DELIM) goto CONT; if(TR[*(text-m)] != W_DELIM) goto CONT; } num_of_matched++; if(FILENAMEONLY) return; if(!(COUNT)) { if(FNAME) printf("%s: ", CurrentFileName); while(*(--text) != '\n'); while(*(++text) != '\n') putchar(*(text)); putchar(*text); } else { while(*text != '\n') text++; } CONT: shift = 1; } else shift = d1; } return; } /* initmask() initializes the mask table for the pattern */ /* endposition is a mask for the endposition of the pattern */ /* endposition will contain k mask bits if the pattern contains k fragments */ void initmask(CHARTYPE *pattern, unsigned *Mask, register int m, register int D, unsigned *endposition) { register unsigned Bit1, c; register int i, j, frag_num; Bit1 = 1 << 31; /* the first bit of Bit1 is 1, others 0. */ frag_num = D+1; *endposition = 0; for (i = 0; i < frag_num; i++) *endposition = *endposition | (Bit1 >> i); *endposition = *endposition >> (m - frag_num); for(i = 0; i < m; i++) if (pattern[i] == '^' || pattern[i] == '$') { pattern[i] = '\n'; } for(i = 0; i < MAXSYM; i++) Mask[i] = ~0; for(i = 0; i < m; i++) /* initialize the mask table */ { c = pattern[i]; for ( j = 0; j < m; j++) if( c == pattern[j] ) Mask[c] = Mask[c] & ~( Bit1 >> j ) ; } } void prep(CHARTYPE *Pattern, register int M, register int D) /* preprocessing for partitioning_bm */ { register int i, j, k, p, shift; register unsigned m; unsigned hash, b_size = 3; m = M/(D+1); p = M - m*(D+1); for (i = 0; i < MAXSYM; i++) SHIFT[i] = m; for (i = M-1; i>=p ; i--) { shift = (M-1-i)%m; hash = Pattern[i]; if(SHIFT[hash] > shift) SHIFT[hash] = shift; } #ifdef DEBUG for(i=0; i<M; i++) printf(" %d,", SHIFT[Pattern[i]]); printf("\n"); #endif shift_1 = m; for(i=0; i<D+1; i++) { j = M-1 - m*i; for(k=1; k<m; k++) { for(p=0; p<D+1; p++) if(Pattern[j-k] == Pattern[M-1-m*p]) if(k < shift_1) shift_1 = k; } } #ifdef DEBUG printf("\nshift_1 = %d", shift_1); #endif if(shift_1 == 0) shift_1 = 1; for(i=0; i<MAXMEMBER; i++) MEMBER[i] = 0; if (m < 3) b_size = m; for(i=0; i<D+1; i++) { j = M-1 - m*i; hash = 0; for(k=0; k<b_size; k++) { hash = (hash << 2) + Pattern[j-k]; } #ifdef DEBUG printf(" hash = %d,", hash); #endif MEMBER[hash] = 1; } } void agrep( register CHARTYPE *pat, int M, register CHARTYPE *text, register CHARTYPE *textend, int D ) { register int i; register int m = M/(D+1); register CHARTYPE *textstart; register int shift, HASH; int j=0, k, d1; int n, cdx; int Candidate[MaxCan][2], round, lastend=0; unsigned R1[MaxError+1], R2[MaxError+1]; register unsigned int r1, endpos, c; unsigned currentpos; unsigned Bit1; unsigned r_newline; Candidate[0][0] = Candidate[0][1] = 0; d1 = shift_1; cdx = 0; if(m < 3) r1 = m; else r1 = 3; textstart = text; shift = m-1; while (text < textend) { shift = SHIFT[*(text += shift)]; if (text >= textend) break; while(shift) { shift = SHIFT[*(text += shift)]; if (text >= textend) break; shift = SHIFT[*(text += shift)]; if (text >= textend) break; } if (text >= textend) break; j = 1; HASH = *text; while(j < r1) { HASH = (HASH << 2) + *(text-j); j++; } if (MEMBER[HASH]) { i = text - textstart; if((i - M - D - 10) > Candidate[cdx][1]) { Candidate[++cdx][0] = i-M-D-2; Candidate[cdx][1] = i+M+D; } else Candidate[cdx][1] = i+M+D; shift = d1; } else shift = d1; } text = textstart; n = textend - textstart; r_newline = '\n'; /* for those candidate areas, find the D-error matches */ if(Candidate[1][0] < 0) Candidate[1][0] = 0; endpos = endposition; /* the mask table and the endposition */ Bit1 = (1 << 31); for(round = 0; round <= cdx; round++) { i = Candidate[round][0] ; if(Candidate[round][1] > n) Candidate[round][1] = n; if(i < 0) i = 0; #ifdef DEBUG printf("round: %d, start=%d, end=%d, ", round, i, Candidate[round][1]); #endif R1[0] = R2[0] = ~0; R1[1] = R2[1] = ~Bit1; for(k = 1; k <= D; k++) R1[k] = R2[k] = (R1[k-1] >> 1) & R1[k-1]; while (i < Candidate[round][1]) { c = text[i++]; if(c == r_newline) { for(k = 0 ; k <= D; k++) R1[k] = R2[k] = (~0 ); } r1 = Mask[c]; R1[0] = (R2[0] >> 1) | r1; for(k=1; k<=D; k++) R1[k] = ((R2[k] >> 1) | r1) & R2[k-1] & ((R1[k-1] & R2[k-1]) >> 1); if((R1[D] & endpos) == 0) { num_of_matched++; if(FILENAMEONLY) { return; } currentpos = i; if(i <= lastend) i = lastend; else { s_output(text, &currentpos); i = currentpos; } lastend = i; for(k=0; k<=D; k++) R1[k] = R2[k] = ~0; } c = text[i++]; if(c == r_newline) { for(k = 0 ; k <= D; k++) R1[k] = R2[k] = (~0 ); } r1 = Mask[c]; R2[0] = (R1[0] >> 1) | r1; for(k = 1; k <= D; k++) R2[k] = ((R1[k] >> 1) | r1) & R1[k-1] & ((R1[k-1] & R2[k-1]) >> 1); if((R2[D] & endpos) == 0) { currentpos = i; num_of_matched++; if(FILENAMEONLY) { return; } if(i <= lastend) i = lastend; else { s_output(text, &currentpos); i = currentpos; } lastend = i; for(k=0; k<=D; k++) R1[k] = R2[k] = ~0; } } } return; } void prep_bm(unsigned char *Pattern, register m) { int i; unsigned hash; unsigned char lastc; for (i = 0; i < MAXSYM; i++) SHIFT[i] = m; for (i = m-1; i>=0; i--) { hash = TR[Pattern[i]]; if(SHIFT[hash] >= m - 1) SHIFT[hash] = m-1-i; } shift_1 = m-1; lastc = TR[Pattern[m-1]]; for (i= m-2; i>=0; i--) { if(TR[Pattern[i]] == lastc ) { shift_1 = m-1 - i; i = -1; } } if(shift_1 == 0) shift_1 = 1; if(NOUPPER) for(i='A'; i<='Z'; i++) SHIFT[i] = SHIFT[i + 'a' - 'A']; #ifdef DEBUG for(i='a'; i<='z'; i++) printf("%c: %d", i, SHIFT[i]); printf("\n"); for(i='A'; i<='Z'; i++) printf("%c: %d", i, SHIFT[i]); printf("\n"); #endif } /* a_monkey() the approximate monkey move */ void a_monkey( register CHARTYPE *pat, register int m, register CHARTYPE *text, register CHARTYPE *textend, register int D ) { register CHARTYPE *oldtext; register unsigned hash, hashmask, suffix_error; register int m1 = m-1-D, pos; hashmask = Hashmask; oldtext = text; while (text < textend) { text = text+m1; suffix_error = 0; while(suffix_error <= D) { hash = *text--; while(MEMBER_1[hash]) { hash = ((hash << LOG_ASCII) + *(text--)) & hashmask; } suffix_error++; } if(text <= oldtext) { if((pos = verify(m, 2*m+D, D, pat, oldtext)) > 0) { text = oldtext+pos; if(text > textend) return; num_of_matched++; if(FILENAMEONLY) return; if(!(COUNT)) { if(FNAME) printf("%s: ", CurrentFileName); while(*(--text) != '\n'); while(*(++text) != '\n') putchar(*text); printf("\n"); } else { while(*text != '\n') text++; } } else { text = oldtext + m; } } oldtext = text; } } /* monkey uses two characters for delta_1 shifting */ CHARTYPE SHIFT_2[MAX_SHIFT_2]; void monkey( register CHARTYPE *pat, register int m, register CHARTYPE *text, register CHARTYPE *textend ) { register unsigned hash; register CHARTYPE shift; register int m1, j; register unsigned r_newline; r_newline = '\n'; m1 = m - 1; text = text+m1; while (text < textend) { hash = *text; hash = (hash << 3) + *(text-1); shift = SHIFT_2[hash]; while(shift) { text = text + shift; hash = (*text << 3) + *(text-1); shift = SHIFT_2[hash]; } j = 0; while(TR[pat[m1 - j]] == TR[*(text - j)]) { if(++j == m) break; } if (j == m ) { if(text >= textend) return; num_of_matched++; if(FILENAMEONLY) return; if(COUNT) { while (*text != r_newline) text++; text--; } else { if(FNAME) printf("%s: ", CurrentFileName); while(*(--text) != r_newline); while(*(++text) != r_newline) putchar(*text); printf("\n"); text--; } } text++; } } void am_preprocess(CHARTYPE *Pattern) { int i, m; m = strlen(Pattern); for (i = 1, Hashmask = 1 ; i<16 ; i++) Hashmask = (Hashmask << 1) + 1 ; for (i = 0; i < MAXMEMBER_1; i++) MEMBER_1[i] = 0; for (i = m-1; i>=0; i--) { MEMBER_1[Pattern[i]] = 1; } for (i = m-1; i > 0; i--) { MEMBER_1[(Pattern[i] << LOG_ASCII) + Pattern[i-1]] = 1; } } /* preprocessing for monkey() */ void m_preprocess(CHARTYPE *Pattern) { int i, j, m; unsigned hash; m = strlen(Pattern); for (i = 0; i < MAX_SHIFT_2; i++) SHIFT_2[i] = m; for (i = m-1; i>=1; i--) { hash = Pattern[i]; hash = hash << 3; for (j = 0; j< MAXSYM; j++) { if(SHIFT_2[hash+j] == m) SHIFT_2[hash+j] = m-1; } hash = hash + Pattern[i-1]; if(SHIFT_2[hash] >= m - 1) SHIFT_2[hash] = m-1-i; } shift_1 = m-1; for (i= m-2; i>=0; i--) { if(Pattern[i] == Pattern[m-1] ) { shift_1 = m-1 - i; i = -1; } } if(shift_1 == 0) shift_1 = 1; SHIFT_2[0] = 0; } /* monkey4() the approximate monkey move */ char *MEMBER_D; void monkey4( register unsigned char *pat, register int m, register unsigned char *text, register unsigned char *textend, register int D ) { register unsigned char *oldtext; register unsigned hash, hashmask, suffix_error; register int m1=m-1-D, pos; hashmask = Hashmask; oldtext = text ; while (text < textend) { text = text + m1; suffix_error = 0; while(suffix_error <= D) { hash = char_map[*text--]; hash = ((hash << LOG_DNA) + char_map[*(text--)]) & hashmask; while(MEMBER_D[hash]) { hash = ((hash << LOG_DNA) + char_map[*(text--)]) & hashmask; } suffix_error++; } if(text <= oldtext) { if((pos = verify(m, 2*m+D, D, pat, oldtext)) > 0) { text = oldtext+pos; if(text > textend) return; num_of_matched++; if(FILENAMEONLY) return; if(!(COUNT)) { if(FNAME) printf("%s:", CurrentFileName); while(*(--text) != '\n'); while(*(++text) != '\n') putchar(*text); printf("\n"); text++; } else { while(*text != '\n') text++; text++; } } else text = oldtext + m; } oldtext = text; } } int blog(int base, int m ) { int i, exp; exp = base; m = m + m/2; for (i = 1; exp < m; i++) exp = exp * base; return(i); } void prep4(char *Pattern, int m) { int i, j, k; unsigned hash; for(i=0; i< MAXSYM; i++) char_map[i] = 0; char_map['a'] = char_map['A'] = 4; char_map['g'] = char_map['g'] = 1; char_map['t'] = char_map['t'] = 2; char_map['c'] = char_map['c'] = 3; char_map['n'] = char_map['n'] = 5; BSize = blog(4, m); for (i = 1, Hashmask = 1 ; i<BSize*LOG_DNA; i++) Hashmask = (Hashmask << 1) + 1 ; MEMBER_D = (char *) malloc((Hashmask+1) * sizeof(char)); #ifdef DEBUG printf("BSize = %d", BSize); #endif for (i=0; i <= Hashmask; i++) MEMBER_D[i] = 0; for (j=0; j < BSize; j++) { for(i=m-1; i >= j; i--) { hash = 0; for(k=0; k <= j; k++) hash = (hash << LOG_DNA) +char_map[Pattern[i-k]]; #ifdef DEBUG printf("< %d >, ", hash); #endif MEMBER_D[hash] = 1; } } } void sgrep(CHARTYPE *pat, int m, int fd, int D) { CHARTYPE text[BLOCKSIZE+2*MAXLINE+MAXPATT]; /* input text stream */ int offset = 2*MAXLINE; int buf_end, num_read, i, start, end, residue = 0; if(pat[0] == '^' || pat[0] == '$') pat[0] = '\n'; if(pat[m-1] == '^' || pat[m-1] == '$') pat[m-1] = '\n'; char_tr(pat, &m); /* will change pat, and m if WHOLELINE is ON */ text[offset-1] = '\n'; /* initial case */ for(i=0; i < MAXLINE; i++) text[i] = 0; /* security zone */ start = offset; if(WHOLELINE) start--; if(m >= MAXPATT) { fprintf(stderr, "%s: pattern too long\n", Progname); exit(2); } if(D == 0) { if(m > LONG_EXAC) m_preprocess(pat); else prep_bm(pat, m); } else if (DNA) prep4(pat, m); else if(m >= LONG_APPX) am_preprocess(pat); else { prep(pat, m, D); initmask(pat, Mask, m, 0, &endposition); } for(i=1; i<=m; i++) text[BLOCKSIZE+offset+i] = pat[m-1]; /* to make sure the skip loop in bm() won't go out of bound */ while( (num_read = read(fd, text+offset, BLOCKSIZE)) > 0) { buf_end = end = offset + num_read -1 ; while(text[end] != '\n' && end > offset) end--; residue = buf_end - end + 1 ; text[start-1] = '\n'; if(D==0) { if(m > LONG_EXAC) monkey(pat, m, text+start, text+end); else bm(pat, m, text+start, text+end); } else { if(DNA) monkey4( pat, m, text+start, text+end, D ); else { if(m >= LONG_APPX) a_monkey(pat, m, text+start, text+end, D); else agrep(pat, m, text+start, text+end, D); } } if(FILENAMEONLY && num_of_matched) { printf("%s\n", CurrentFileName); return; } start = offset - residue ; if(start < MAXLINE) { start = MAXLINE; } strncpy(text+start, text+end, residue); start++; } /* end of while(num_read = ... */ return; } /* end sgrep */
the_stack_data/57951504.c
#include <math.h> #define TRUE 1 #define FALSE 0 typedef struct { double x; double y; double z; } Vector; /* * Procedural fBm evaluated at "point"; returns value stored in "value". * * Copyright 1994 F. Kenton Musgrave * * Parameters: * ``H'' is the fractal increment parameter * ``lacunarity'' is the gap between successive frequencies * ``octaves'' is the number of frequencies in the fBm */ double fBm( Vector point, double H, double lacunarity, double octaves ) { double value, frequency, remainder, Noise3(); int i; static int first = TRUE; static double *exponent_array; /* precompute and store spectral weights */ if ( first ) { /* seize required memory for exponent_array */ exponent_array = (double *)malloc( (octaves+1) * sizeof(double) ); frequency = 1.0; for (i=0; i<=octaves; i++) { /* compute weight for each frequency */ exponent_array[i] = pow( frequency, -H ); frequency *= lacunarity; } first = FALSE; } value = 0.0; /* initialize vars to proper values */ frequency = 1.0; /* inner loop of spectral construction */ for (i=0; i<octaves; i++) { value += Noise3( point ) * exponent_array[i]; point.x *= lacunarity; point.y *= lacunarity; point.z *= lacunarity; } /* for */ remainder = octaves - (int)octaves; if ( remainder ) /* add in ``octaves'' remainder */ /* ``i'' and spatial freq. are preset in loop above */ value += remainder * Noise3( point ) * exponent_array[i]; return( value ); } /* fBm() */ /* * Procedural multifractal evaluated at "point"; * returns value stored in "value". * * Copyright 1994 F. Kenton Musgrave * * Parameters: * ``H'' determines the highest fractal dimension * ``lacunarity'' is gap between successive frequencies * ``octaves'' is the number of frequencies in the fBm * ``offset'' is the zero offset, which determines multifractality */ double multifractal( Vector point, double H, double lacunarity, double octaves, double offset ) { double value, frequency, remainder, Noise3(); int i; static int first = TRUE; static double *exponent_array; /* precompute and store spectral weights */ if ( first ) { /* seize required memory for exponent_array */ exponent_array = (double *)malloc( (octaves+1) * sizeof(double) ); frequency = 1.0; for (i=0; i<=octaves; i++) { /* compute weight for each frequency */ exponent_array[i] = pow( frequency, -H ); frequency *= lacunarity; } first = FALSE; } value = 1.0; /* initialize vars to proper values */ frequency = 1.0; /* inner loop of multifractal construction */ for (i=0; i<octaves; i++) { value *= offset * frequency * Noise3( point ); point.x *= lacunarity; point.y *= lacunarity; point.z *= lacunarity; } /* for */ remainder = octaves - (int)octaves; if ( remainder ) /* add in ``octaves'' remainder */ /* ``i'' and spatial freq. are preset in loop above */ value += remainder * Noise3( point ) * exponent_array[i]; return value; } /* multifractal() */ /* "Variable Lacunarity Noise" -or- VLNoise3() * A distorted variety of Perlin noise. * * Copyright 1994 F. Kenton Musgrave */ double VLNoise3( Vector point, double distortion ) { Vector offset, VecNoise3(), AddVectors(); double Noise3(); offset.x = point.x +0.5; /* misregister domain */ offset.y = point.y +0.5; offset.z = point.z +0.5; offset = VecNoise3( offset ); /* get a random vector */ offset.x *= distortion; /* scale the randomization */ offset.y *= distortion; offset.z *= distortion; /* ``point'' is the domain; distort domain by adding ``offset'' */ point = AddVectors( point, offset ); return Noise3( point ); /* distorted-domain noise */ } /* VLNoise3() */ /* * Heterogeneous procedural terrain function: stats by altitude method. * Evaluated at "point"; returns value stored in "value". * * Copyright 1994 F. Kenton Musgrave * * Parameters: * ``H'' determines the fractal dimension of the roughest areas * ``lacunarity'' is the gap between successive frequencies * ``octaves'' is the number of frequencies in the fBm * ``offset'' raises the terrain from `sea level' */ double Hetero_Terrain( Vector point, double H, double lacunarity, double octaves, double offset ) { double value, increment, frequency, remainder, Noise3(); int i; static int first = TRUE; static double *exponent_array; /* precompute and store spectral weights, for efficiency */ if ( first ) { /* seize required memory for exponent_array */ exponent_array = (double *)malloc( (octaves+1) * sizeof(double) ); frequency = 1.0; for (i=0; i<=octaves; i++) { /* compute weight for each frequency */ exponent_array[i] = pow( frequency, -H ); frequency *= lacunarity; } first = FALSE; } /* first unscaled octave of function; later octaves are scaled */ value = offset + Noise3( point ); point.x *= lacunarity; point.y *= lacunarity; point.z *= lacunarity; /* spectral construction inner loop, where the fractal is built */ for (i=1; i<octaves; i++) { /* obtain displaced noise value */ increment = Noise3( point ) + offset; /* scale amplitude appropriately for this frequency */ increment *= exponent_array[i]; /* scale increment by current `altitude' of function */ increment *= value; /* add increment to ``value'' */ value += increment; /* raise spatial frequency */ point.x *= lacunarity; point.y *= lacunarity; point.z *= lacunarity; } /* for */ /* take care of remainder in ``octaves'' */ remainder = octaves - (int)octaves; if ( remainder ) { /* ``i'' and spatial freq. are preset in loop above */ /* note that the main loop code is made shorter here */ /* you may want to that loop more like this */ increment = (Noise3( point ) + offset) * exponent_array[i]; value += remainder * increment * value; } return( value ); } /* Hetero_Terrain() */ /* Hybrid additive/multiplicative multifractal terrain model. * * Copyright 1994 F. Kenton Musgrave * * Some good parameter values to start with: * * H: 0.25 * offset: 0.7 */ double HybridMultifractal( Vector point, double H, double lacunarity, double octaves, double offset ) { double frequency, result, signal, weight, remainder; double Noise3(); int i; static int first = TRUE; static double *exponent_array; /* precompute and store spectral weights */ if ( first ) { /* seize required memory for exponent_array */ exponent_array = (double *)malloc( (octaves+1) * sizeof(double) ); frequency = 1.0; for (i=0; i<=octaves; i++) { /* compute weight for each frequency */ exponent_array[i] = pow( frequency, -H); frequency *= lacunarity; } first = FALSE; } /* get first octave of function */ result = ( Noise3( point ) + offset ) * exponent_array[0]; weight = result; /* increase frequency */ point.x *= lacunarity; point.y *= lacunarity; point.z *= lacunarity; /* spectral construction inner loop, where the fractal is built */ for (i=1; i<octaves; i++) { /* prevent divergence */ if ( weight > 1.0 ) weight = 1.0; /* get next higher frequency */ signal = ( Noise3( point ) + offset ) * exponent_array[i]; /* add it in, weighted by previous freq's local value */ result += weight * signal; /* update the (monotonically decreasing) weighting value */ /* (this is why H must specify a high fractal dimension) */ weight *= signal; /* increase frequency */ point.x *= lacunarity; point.y *= lacunarity; point.z *= lacunarity; } /* for */ /* take care of remainder in ``octaves'' */ remainder = octaves - (int)octaves; if ( remainder ) /* ``i'' and spatial freq. are preset in loop above */ result += remainder * Noise3( point ) * exponent_array[i]; return( result ); } /* HybridMultifractal() */ /* Ridged multifractal terrain model. * * Copyright 1994 F. Kenton Musgrave * * Some good parameter values to start with: * * H: 1.0 * offset: 1.0 * gain: 2.0 */ double RidgedMultifractal( Vector point, double H, double lacunarity, double octaves, double offset, double gain ) { double result, frequency, signal, weight, Noise3(); int i; static int first = TRUE; static double *exponent_array; /* precompute and store spectral weights */ if ( first ) { /* seize required memory for exponent_array */ exponent_array = (double *)malloc( (octaves+1) * sizeof(double) ); frequency = 1.0; for (i=0; i<=octaves; i++) { /* compute weight for each frequency */ exponent_array[i] = pow( frequency, -H ); frequency *= lacunarity; } first = FALSE; } /* get first octave */ signal = Noise3( point ); /* get absolute value of signal (this creates the ridges) */ if ( signal < 0.0 ) signal = -signal; /* invert and translate (note that "offset" should be ~= 1.0) */ signal = offset - signal; /* square the signal, to increase "sharpness" of ridges */ signal *= signal; /* assign initial values */ result = signal; weight = 1.0; for( i=1; i<octaves; i++ ) { /* increase the frequency */ point.x *= lacunarity; point.y *= lacunarity; point.z *= lacunarity; /* weight successive contributions by previous signal */ weight = signal * gain; if ( weight > 1.0 ) weight = 1.0; if ( weight < 0.0 ) weight = 0.0; signal = Noise3( point ); if ( signal < 0.0 ) signal = -signal; signal = offset - signal; signal *= signal; /* weight the contribution */ signal *= weight; result += signal * exponent_array[i]; } return( result ); } /* RidgedMultifractal() */