file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/117329339.c
//***************************************************************************** // // startup_gcc.c - Startup code for use with GNU tools. // // Copyright (c) 2008-2013 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 10636 of the EK-LM3S3748 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 SysTickHandler(void); extern void UART1IntHandler(void); extern void uDMAIntHandler(void); extern void uDMAErrorHandler(void); //***************************************************************************** // // The entry point for the application. // //***************************************************************************** extern int main(void); //***************************************************************************** // // Reserve space for the system stack. // //***************************************************************************** static unsigned long pulStack[256]; //***************************************************************************** // // 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 UART1IntHandler, // UART1 Rx and Tx IntDefaultHandler, // SSI0 Rx and Tx IntDefaultHandler, // I2C0 Master and Slave IntDefaultHandler, // PWM Fault IntDefaultHandler, // PWM Generator 0 IntDefaultHandler, // PWM Generator 1 IntDefaultHandler, // PWM Generator 2 IntDefaultHandler, // Quadrature Encoder 0 IntDefaultHandler, // ADC Sequence 0 IntDefaultHandler, // ADC Sequence 1 IntDefaultHandler, // ADC Sequence 2 IntDefaultHandler, // ADC Sequence 3 IntDefaultHandler, // Watchdog timer IntDefaultHandler, // Timer 0 subtimer A IntDefaultHandler, // Timer 0 subtimer B IntDefaultHandler, // Timer 1 subtimer A IntDefaultHandler, // Timer 1 subtimer B IntDefaultHandler, // Timer 2 subtimer A IntDefaultHandler, // Timer 2 subtimer B IntDefaultHandler, // Analog Comparator 0 IntDefaultHandler, // Analog Comparator 1 IntDefaultHandler, // Analog Comparator 2 IntDefaultHandler, // System Control (PLL, OSC, BO) IntDefaultHandler, // FLASH Control IntDefaultHandler, // GPIO Port F IntDefaultHandler, // GPIO Port G IntDefaultHandler, // GPIO Port H IntDefaultHandler, // UART2 Rx and Tx IntDefaultHandler, // SSI1 Rx and Tx IntDefaultHandler, // Timer 3 subtimer A IntDefaultHandler, // Timer 3 subtimer B IntDefaultHandler, // I2C1 Master and Slave IntDefaultHandler, // Quadrature Encoder 1 IntDefaultHandler, // CAN0 IntDefaultHandler, // CAN1 IntDefaultHandler, // CAN2 IntDefaultHandler, // Ethernet IntDefaultHandler, // Hibernate IntDefaultHandler, // USB0 IntDefaultHandler, // PWM Generator 3 uDMAIntHandler, // uDMA Software Transfer uDMAErrorHandler // uDMA Error }; //***************************************************************************** // // 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/67324230.c
#include <stdio.h> void scilab_rt_bar_d2i0_(int in00, int in01, double matrixin0[in00][in01], int scalarin0) { 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("%d", scalarin0); }
the_stack_data/163292.c
#include <stdio.h> #include <string.h> #include <stdbool.h> #define clr(ar) memset(ar, 0, sizeof(ar)) #define read() freopen("lol.txt", "r", stdin) int popcount(int x){ int counter = 0; __asm__ volatile("POPCNT %1, %0;" :"=r"(counter) :"r"(x) : ); return counter; } int lzcount(int x){ int counter = 0; __asm__ volatile("LZCNT %1, %0;" :"=r"(counter) :"r"(x) : ); return counter; } /// Returns i if x = 2^i and 0 otherwise int bitscan(unsigned int x){ __asm__ volatile("bsf %0, %0" : "=r" (x) : "0" (x)); return x; } double fsqrt(double x){ /// Also works for long double __asm__ volatile("fsqrt" : "+t" (x)); return x; } int gcd(int a, int b){ int res; __asm__ volatile( "movl %1, %%eax;" "movl %2, %%ebx;" "repeat_%=:\n" "cmpl $0, %%ebx;" "je terminate_%=\n;" "xorl %%edx, %%edx;" "idivl %%ebx;" "movl %%ebx, %%eax;" "movl %%edx, %%ebx;" "jmp repeat_%=\n;" "terminate_%=:\n" "movl %%eax, %0;" : "=g"(res) : "g"(a), "g"(b) : "eax", "ebx", "edx" ); return res; } int main(){ printf("%d\n", lzcount(13)); return 0; }
the_stack_data/178265802.c
#include <stdlib.h> #include <stdint.h> /* Test if an array contains 0 recursively */ int64_t contains0_rec (int64_t *arr, int64_t len, int64_t i) { if (i >= len) { return 0; } else if (arr[i] == 0) { return 1; } else { return contains0_rec (arr, len, i+1); } } /* Like contains0_rec but with len first */ int64_t contains0_rec_ (uint64_t len, int64_t *arr, uint64_t i) { if (i >= len) { return 0; } else if (arr[i] == 0) { return 1; } else { return contains0_rec_ (len, arr, i+1); } } /* Test if an array contains 0 */ int64_t contains0 (int64_t *arr, uint64_t len) { for (uint64_t i = 0; i < len; ++i) { if (arr[i] == 0) { return 1; } } return 0; } /* Test if an array contains 0 */ int64_t contains0_after (int64_t *arr, uint64_t len, uint64_t i) { for (; i < len; ++i) { if (arr[i] == 0) { return 1; } } return 0; } /* Test if a sorted array contains 0 by divide-and-conquer */ int64_t contains0_sorted_rec (int64_t *arr, uint64_t len) { if (len == 0) { return 0; } else if (len == 1) { return arr[0] == 0 ? 1 : 0; } else { uint64_t halfway = len / 2; if (arr[halfway] > 0) { return contains0_sorted_rec (arr, halfway); } else { return contains0_sorted_rec (arr+halfway, len - halfway); } } } /* Zero out an array */ void zero_array (int64_t *arr, uint64_t len) { for (uint64_t i = 0; i < len; ++i) { arr[i] = 0; } } /* Zero out an array starting at a given offset */ void zero_array_from (int64_t *arr, uint64_t len, uint64_t off) { for (; off < len; ++off) { arr[off] = 0; } } /* Zeroes every negative element of an array and returns the sum of the results */ uint64_t filter_and_sum_pos (int64_t * arr, uint64_t len) { uint64_t sum = 0; for (uint64_t i = 0; i < len; ++i) { if (arr[i] < 0) { arr[i] = 0; } sum += arr[i]; } return sum; } uint64_t sum_2d (int64_t **arr, uint64_t l1, uint64_t l2) { uint64_t sum = 0; for (uint64_t i = 0; i < l1; ++i) { for (uint64_t j = 0; j < l2; ++j) { sum += arr[i][j]; } } return sum; } /* Finds the sum of the elements of an array by incrementing the given pointer instead of using a for loop over an index */ uint64_t sum_inc_ptr(const uint8_t *arr, size_t len) { uint64_t sum = 0; while (len--) { sum += arr[0]; arr += 1; } return sum; } /* Like the above, but uses an array of int64_t */ uint64_t sum_inc_ptr_64(const uint64_t *arr, size_t len) { uint64_t sum = 0; while (len--) { sum += arr[0]; arr += 8; } return sum; } /* For an array of even length, returns the sum of the even components of the array minus the sum of the odd components of an array */ uint64_t even_odd_sums_diff(const uint64_t *arr, size_t len) { uint64_t sum = 0; for (uint64_t i = 1; i < len; i += 2) { sum += arr[i-1] - arr[i]; } return sum; }
the_stack_data/64200880.c
#include <stdio.h> int main() { int n,m,p,c; scanf("%d%d%d%d",&n,&m,&p,&c); while (n!=0 || m!=0 || p!=0 || c!=0) { printf("%d\n",p+n-m); scanf("%d%d%d%d",&n,&m,&p,&c); } return 0; }
the_stack_data/156393123.c
#include <stdio.h> #include <stdbool.h> void main(void){ int a[2]; a[0] = 2017; a[1] = 2018; printf("a[0] = %d\na[1] = %d\n", *a, a[1]); }
the_stack_data/889644.c
/* * This program generates first 'n' rows of Pascals's Triangle. */ #include<stdio.h> #include<stdlib.h> #include<assert.h> #include<string.h> #include<stdbool.h> /* * This function returns the 'num' rows of a Pascal's Triangle. If 'num' * less than or equal to zero, then this function returns NULL. The time * complexity of this function is O(n^2), where 'n' is the number of rows * in the Pascal's Triangle. The space complexity of this function is * O(n^2), where 'n' is the number of rows in the Pascal's Triangle. */ int** get_pascals_triangle (int num) { int index, inner_index; int** pascals_triangle; /* * If 'num' is less than or equal to zero, then return NULL */ if (num <= 0) { return(NULL); } /* * Allocate 'num' rows for Pascal's Triangle */ pascals_triangle = (int**)malloc(sizeof(int*) * num); /* * If memory allocation fails, then return NULL */ if (!pascals_triangle) { return(NULL); } /* * Allocate memory for each of the rows for the Pascal's Triangle */ for (index = 0; index < num; ++index) { /* * Allocate memory according to the number of entries in a row * in the triangle */ pascals_triangle[index] = (int*)malloc(sizeof(int) * (index + 1)); /* * If the memory allocation fails, then free all the previously * allocated memory and return NULL */ if (!pascals_triangle[index]) { /* * Free the previously allocated rows */ for (inner_index = 0; inner_index < index; ++inner_index) { free(pascals_triangle[inner_index]); } /* * Free the allocated row pointers */ free(pascals_triangle); return(NULL); } } /* * Set the only element of the first row to one */ pascals_triangle[0][0] = 1; /* * Iterate through the rest of the rows and populate * the Pascal's Triangle */ for (index = 1; index < num; ++index) { /* * Populate a given row of the triangle */ for (inner_index = 0; inner_index < (index + 1); ++inner_index) { if (inner_index == 0) { /* * Copy the first element of the previous row in the * zeroth element of the current row */ pascals_triangle[index][0] = pascals_triangle[index - 1][0]; } else if (inner_index == index) { /* * Copy the last element of the previous row in the * last element of the current row */ pascals_triangle[index][inner_index] = pascals_triangle[index - 1][inner_index - 1]; } else { /* * For the rest of the elements, sum the adjacent numbers * in the previous row */ pascals_triangle[index][inner_index] = pascals_triangle[index - 1][inner_index - 1] + pascals_triangle[index - 1][inner_index] ; } } } /* * Return the Pascal's Triangle */ return(pascals_triangle); } /* * This function checks if the two Pascal's Triangles of 'num' rows are * same or not. If the two Pascal's Triangle are same, then this function * returns 'true' otherwise this function returns 'false'. The time * complexity of this function is O(n^2), where 'n' is the number of rows * in the Pascal's Triangle. The space complexity of this function is * O(n^2), where 'n' is the number of rows in the Pascal's Triangle. */ bool check_if_equal_pascals_triangles (int num, int exp[][num], int** act) { int index; /* * If either of the Pascal's Triangle are invalid or the * number of rows in the Pascal's Triangles is invalid, then * return 'false' */ if (!exp || !act || (num <= 0)) { return(false); } /* * Compare each of the rows in the two Pascal's Triangles */ for (index = 0; index < num; ++index) { /* * If either of the rows are NULL, then return 'false' */ if (!exp[index] || !act[index]) { return(false); } /* * If the entries in the two array rows are not same, then * return 'false' */ if (memcmp(exp[index], act[index], sizeof(int) * (index + 1))) { return(false); } } /* * Since the two Pascal's Triangles are same, so return * 'true' */ return(true); } int main () { /* * Test 0: If the number of rows is not valid, then the Pascal's * Triangle should be NULL. */ int** act_pt0 = get_pascals_triangle(0); int** exp_pt0 = NULL; assert(act_pt0 == exp_pt0); /* * Test 1: Test a Pascal's Triangle having one row. */ int** act_pt1 = get_pascals_triangle(1); int exp_pt1[][1] = { {1} }; assert(check_if_equal_pascals_triangles(1, exp_pt1, act_pt1)); /* * Test 2: Test a Pascal's Triangle having two rows. */ int** act_pt2 = get_pascals_triangle(2); int exp_pt2[][2] = { {1}, {1, 1} }; assert(check_if_equal_pascals_triangles(2, exp_pt2, act_pt2)); /* * Test 3: Test a Pascal's Triangle having three rows. */ int** act_pt3 = get_pascals_triangle(3); int exp_pt3[][3] = { {1}, {1, 1}, {1, 2, 1} }; assert(check_if_equal_pascals_triangles(3, exp_pt3, act_pt3)); /* * Test 4: Test a Pascal's Triangle having four rows. */ int** act_pt4 = get_pascals_triangle(4); int exp_pt4[][4] = { {1}, {1, 1}, {1, 2, 1}, {1, 3, 3, 1} }; assert(check_if_equal_pascals_triangles(4, exp_pt4, act_pt4)); /* * Test 5: Test a Pascal's Triangle having ten rows. */ int** act_pt5 = get_pascals_triangle(10); int exp_pt5[][10] = { {1}, {1, 1}, {1, 2, 1}, {1, 3, 3, 1}, {1, 4 ,6, 4, 1}, {1, 5, 10, 10, 5, 1}, {1, 6, 15, 20, 15, 6, 1}, {1, 7, 21, 35, 35, 21, 7, 1}, {1, 8, 28, 56, 70, 56, 28, 8, 1}, {1, 9, 36, 84, 126, 126, 84, 36, 9, 1} }; assert(check_if_equal_pascals_triangles(10, exp_pt5, act_pt5)); return(0); }
the_stack_data/1125749.c
#include<stdio.h> int main(){ printf("1 2 3 4\n"); printf("%d %d %d %d\n", 1, 2, 3, 4); printf("1 "); printf("2 "); printf("3 "); printf("4\n"); return 0; }
the_stack_data/94329.c
void foo() { static int wxyz = 42; } void main() { foo(); static int wxyz = 12345; if (1) { static int wxyz = 54321; printf("%d\n", wxyz); } }
the_stack_data/43887588.c
#include <stdio.h> #include <stdlib.h> #include <locale.h> #include <string.h> int main(void) { setlocale(LC_ALL, "Portuguese"); char cont; int x, escolha; float valor, celciu, fahrenheit, reais, dolares; do { printf("Qual converção você quer usar agora?\nDigite '1' se for de Celsius para Fahrenheit ou '2' se for de Real para Dólar:\n"); scanf("%d", &escolha); if (escolha == 1) { printf("Digite o valor em Celcius que irá ser convertido:\n"); scanf("%f", &celciu); fahrenheit = celciu*1.8 + 32; printf("O valor de %.1f Ceucius em Fahrenheit é de %.1f", celciu, fahrenheit); } else if (escolha == 2) { printf("Digite o valor em Reais que irá ser convertido:\n"); scanf("%f", &reais); printf("Digite o valor do Dolar que vale um Real:\n"); scanf("%f", &dolares); valor= reais/dolares; printf("O valor de %.2f reais em Dolares é de %.2f", reais, valor); } else if (escolha != 1 && escolha != 2) { continue; } printf("\nQuer fazer outra converção?(s/n)\n"); scanf("%s", &cont); system("pause"); system("cls"); } while (cont == 's'); return 0; }
the_stack_data/220454508.c
#include <stdio.h> // Typecasting syntax // (type) value; int main() { int a = 3; float b = 54; printf("The value of a is %d\n", (int) b); return 0; }
the_stack_data/220455680.c
/* * Exercise 5-10 */ #include <stdio.h> #include <math.h> #include <stdlib.h> #define MAXOPS 100 #define OPERATOR 1 double buffer[MAXOPS]; int bufp = 0; // index of buffer; always points to next empty spot. double pop(void); void push(double); int main(int argc, char *argv[]) { double op1, op2; char c; char arg; while (argc-- > 1) { // process the next arg *argv++; if (isdigit(c = **argv)) { push(atof(*argv)); } else { printf("%c\n", c); switch (c) { case '+': push(pop() + pop()); break; case '*': push(pop() * pop()); break; case '/': op2 = pop(); push(pop() / op2); break; case '-': op2 = pop(); push(pop() - op2); break; default: printf("op not recognized\n"); break; } } } printf("%.8g\n", pop()); } double pop(void) { if (bufp == 0) { printf("Buffer empty\n"); return -1; } else return buffer[--bufp]; } void push(double n) { if (bufp == MAXOPS) printf("Buffer full\n"); else buffer[bufp++] = n; }
the_stack_data/53129.c
#include<stdio.h> #include<stdlib.h> int main(void) { int hour; printf("Please input the 24-hour system => "); scanf("%d",&hour); hour = (hour>=12)?hour-12:hour; printf("Present time: %d\n",hour); system("pause"); return 0; }
the_stack_data/43886600.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_toupper.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mdulcie <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/10/29 23:03:39 by mdulcie #+# #+# */ /* Updated: 2020/11/08 19:46:12 by mdulcie ### ########.fr */ /* */ /* ************************************************************************** */ int ft_toupper(int c) { if (c >= 'a' && c <= 'z') c += 'A' - 'a'; return (c); }
the_stack_data/253825.c
/* TAGS: min c */ /* LIFT_OPTS: explicit +--explicit_args +--explicit_args_count 8 */ /* LIFT_OPTS: default */ /* LD_OPTS: -lm */ /* * Copyright (c) 2018 Trail of Bits, Inc. * * 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 <complex.h> #include <stdio.h> #include <math.h> #include <float.h> int main(void) { long double complex z = 1.25 + 2.54*I; long double complex res = cexpl( z ); long double img = cimagl(res); long double real = creall(res); if ( real + 2.877 < 0 && real + 2.8776 > 0 && img - 1.975 > 0 && img - 1.976 < 0 ) printf( "OK\n" ); else printf( "NOK\n" ); printf("%i\n\t%i + %i\n", 42, (int)real, (int)img); }
the_stack_data/841452.c
/* { dg-do run } */ #include <omp.h> #include <stdlib.h> void do_by_16 (float *x, int iam, int ipoints) { } void a36 (float *x, int npoints) { int iam, ipoints; omp_set_dynamic (0); omp_set_num_threads (16); #pragma omp parallel shared(x, npoints) private(iam, ipoints) { if (omp_get_num_threads () != 16) abort (); iam = omp_get_thread_num (); ipoints = npoints / 16; do_by_16 (x, iam, ipoints); } } int main() { float a[10]; a36 (a, 10); return 0; }
the_stack_data/51699681.c
#include <inttypes.h> // GDB JIT interface stub struct { uint32_t version; uint32_t action_flag; void* relevant_entry; void* first_entry; } __jit_debug_descriptor = { 1, 0, 0, 0 }; void __jit_debug_register_code() { } // end GDB JIT interface stub int main() { return 0; }
the_stack_data/192506.c
// RUN: %clang_cc1 -disable-noundef-analysis -triple s390x-linux-gnu \ // RUN: -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,HARD-FLOAT // RUN: %clang_cc1 -disable-noundef-analysis -triple s390x-linux-gnu -target-feature +vector \ // RUN: -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,HARD-FLOAT // RUN: %clang_cc1 -disable-noundef-analysis -triple s390x-linux-gnu -target-cpu z13 \ // RUN: -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,HARD-FLOAT // RUN: %clang_cc1 -disable-noundef-analysis -triple s390x-linux-gnu -target-cpu arch11 \ // RUN: -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,HARD-FLOAT // RUN: %clang_cc1 -disable-noundef-analysis -triple s390x-linux-gnu -target-cpu z14 \ // RUN: -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,HARD-FLOAT // RUN: %clang_cc1 -disable-noundef-analysis -triple s390x-linux-gnu -target-cpu arch12 \ // RUN: -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,HARD-FLOAT // RUN: %clang_cc1 -disable-noundef-analysis -triple s390x-linux-gnu -target-cpu z15 \ // RUN: -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,HARD-FLOAT // RUN: %clang_cc1 -disable-noundef-analysis -triple s390x-linux-gnu -target-cpu arch13 \ // RUN: -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,HARD-FLOAT // RUN: %clang_cc1 -disable-noundef-analysis -triple s390x-linux-gnu -target-cpu arch13 \ // RUN: -emit-llvm -o - %s -mfloat-abi soft | FileCheck %s \ // RUN: --check-prefixes=CHECK,SOFT-FLOAT // RUN: %clang_cc1 -disable-noundef-analysis -triple s390x-linux-gnu -target-cpu arch14 \ // RUN: -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,HARD-FLOAT // RUN: %clang_cc1 -disable-noundef-analysis -triple s390x-linux-gnu -target-cpu arch14 \ // RUN: -emit-llvm -o - %s -mfloat-abi soft | FileCheck %s \ // RUN: --check-prefixes=CHECK,SOFT-FLOAT // Scalar types char pass_char(char arg) { return arg; } // CHECK-LABEL: define{{.*}} signext i8 @pass_char(i8 signext %{{.*}}) short pass_short(short arg) { return arg; } // CHECK-LABEL: define{{.*}} signext i16 @pass_short(i16 signext %{{.*}}) int pass_int(int arg) { return arg; } // CHECK-LABEL: define{{.*}} signext i32 @pass_int(i32 signext %{{.*}}) long pass_long(long arg) { return arg; } // CHECK-LABEL: define{{.*}} i64 @pass_long(i64 %{{.*}}) long long pass_longlong(long long arg) { return arg; } // CHECK-LABEL: define{{.*}} i64 @pass_longlong(i64 %{{.*}}) __int128 pass_int128(__int128 arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_int128(i128* noalias sret(i128) align 16 %{{.*}}, i128* %0) float pass_float(float arg) { return arg; } // CHECK-LABEL: define{{.*}} float @pass_float(float %{{.*}}) double pass_double(double arg) { return arg; } // CHECK-LABEL: define{{.*}} double @pass_double(double %{{.*}}) long double pass_longdouble(long double arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_longdouble(fp128* noalias sret(fp128) align 8 %{{.*}}, fp128* %0) // Complex types _Complex char pass_complex_char(_Complex char arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_complex_char({ i8, i8 }* noalias sret({ i8, i8 }) align 1 %{{.*}}, { i8, i8 }* %{{.*}}arg) _Complex short pass_complex_short(_Complex short arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_complex_short({ i16, i16 }* noalias sret({ i16, i16 }) align 2 %{{.*}}, { i16, i16 }* %{{.*}}arg) _Complex int pass_complex_int(_Complex int arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_complex_int({ i32, i32 }* noalias sret({ i32, i32 }) align 4 %{{.*}}, { i32, i32 }* %{{.*}}arg) _Complex long pass_complex_long(_Complex long arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_complex_long({ i64, i64 }* noalias sret({ i64, i64 }) align 8 %{{.*}}, { i64, i64 }* %{{.*}}arg) _Complex long long pass_complex_longlong(_Complex long long arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_complex_longlong({ i64, i64 }* noalias sret({ i64, i64 }) align 8 %{{.*}}, { i64, i64 }* %{{.*}}arg) _Complex float pass_complex_float(_Complex float arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_complex_float({ float, float }* noalias sret({ float, float }) align 4 %{{.*}}, { float, float }* %{{.*}}arg) _Complex double pass_complex_double(_Complex double arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_complex_double({ double, double }* noalias sret({ double, double }) align 8 %{{.*}}, { double, double }* %{{.*}}arg) _Complex long double pass_complex_longdouble(_Complex long double arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_complex_longdouble({ fp128, fp128 }* noalias sret({ fp128, fp128 }) align 8 %{{.*}}, { fp128, fp128 }* %{{.*}}arg) // Aggregate types struct agg_1byte { char a[1]; }; struct agg_1byte pass_agg_1byte(struct agg_1byte arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_agg_1byte(%struct.agg_1byte* noalias sret(%struct.agg_1byte) align 1 %{{.*}}, i8 %{{.*}}) struct agg_2byte { char a[2]; }; struct agg_2byte pass_agg_2byte(struct agg_2byte arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_agg_2byte(%struct.agg_2byte* noalias sret(%struct.agg_2byte) align 1 %{{.*}}, i16 %{{.*}}) struct agg_3byte { char a[3]; }; struct agg_3byte pass_agg_3byte(struct agg_3byte arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_agg_3byte(%struct.agg_3byte* noalias sret(%struct.agg_3byte) align 1 %{{.*}}, %struct.agg_3byte* %{{.*}}) struct agg_4byte { char a[4]; }; struct agg_4byte pass_agg_4byte(struct agg_4byte arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_agg_4byte(%struct.agg_4byte* noalias sret(%struct.agg_4byte) align 1 %{{.*}}, i32 %{{.*}}) struct agg_5byte { char a[5]; }; struct agg_5byte pass_agg_5byte(struct agg_5byte arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_agg_5byte(%struct.agg_5byte* noalias sret(%struct.agg_5byte) align 1 %{{.*}}, %struct.agg_5byte* %{{.*}}) struct agg_6byte { char a[6]; }; struct agg_6byte pass_agg_6byte(struct agg_6byte arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_agg_6byte(%struct.agg_6byte* noalias sret(%struct.agg_6byte) align 1 %{{.*}}, %struct.agg_6byte* %{{.*}}) struct agg_7byte { char a[7]; }; struct agg_7byte pass_agg_7byte(struct agg_7byte arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_agg_7byte(%struct.agg_7byte* noalias sret(%struct.agg_7byte) align 1 %{{.*}}, %struct.agg_7byte* %{{.*}}) struct agg_8byte { char a[8]; }; struct agg_8byte pass_agg_8byte(struct agg_8byte arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_agg_8byte(%struct.agg_8byte* noalias sret(%struct.agg_8byte) align 1 %{{.*}}, i64 %{{.*}}) struct agg_16byte { char a[16]; }; struct agg_16byte pass_agg_16byte(struct agg_16byte arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_agg_16byte(%struct.agg_16byte* noalias sret(%struct.agg_16byte) align 1 %{{.*}}, %struct.agg_16byte* %{{.*}}) // Float-like aggregate types struct agg_float { float a; }; struct agg_float pass_agg_float(struct agg_float arg) { return arg; } // HARD-FLOAT-LABEL: define{{.*}} void @pass_agg_float(%struct.agg_float* noalias sret(%struct.agg_float) align 4 %{{.*}}, float %{{.*}}) // SOFT-FLOAT-LABEL: define{{.*}} void @pass_agg_float(%struct.agg_float* noalias sret(%struct.agg_float) align 4 %{{.*}}, i32 %{{.*}}) struct agg_double { double a; }; struct agg_double pass_agg_double(struct agg_double arg) { return arg; } // HARD-FLOAT-LABEL: define{{.*}} void @pass_agg_double(%struct.agg_double* noalias sret(%struct.agg_double) align 8 %{{.*}}, double %{{.*}}) // SOFT-FLOAT-LABEL: define{{.*}} void @pass_agg_double(%struct.agg_double* noalias sret(%struct.agg_double) align 8 %{{.*}}, i64 %{{.*}}) struct agg_longdouble { long double a; }; struct agg_longdouble pass_agg_longdouble(struct agg_longdouble arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_agg_longdouble(%struct.agg_longdouble* noalias sret(%struct.agg_longdouble) align 8 %{{.*}}, %struct.agg_longdouble* %{{.*}}) struct agg_float_a8 { float a __attribute__((aligned (8))); }; struct agg_float_a8 pass_agg_float_a8(struct agg_float_a8 arg) { return arg; } // HARD-FLOAT-LABEL: define{{.*}} void @pass_agg_float_a8(%struct.agg_float_a8* noalias sret(%struct.agg_float_a8) align 8 %{{.*}}, double %{{.*}}) // SOFT-FLOAT-LABEL: define{{.*}} void @pass_agg_float_a8(%struct.agg_float_a8* noalias sret(%struct.agg_float_a8) align 8 %{{.*}}, i64 %{{.*}}) struct agg_float_a16 { float a __attribute__((aligned (16))); }; struct agg_float_a16 pass_agg_float_a16(struct agg_float_a16 arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_agg_float_a16(%struct.agg_float_a16* noalias sret(%struct.agg_float_a16) align 16 %{{.*}}, %struct.agg_float_a16* %{{.*}}) // Verify that the following are *not* float-like aggregate types struct agg_nofloat1 { float a; float b; }; struct agg_nofloat1 pass_agg_nofloat1(struct agg_nofloat1 arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_agg_nofloat1(%struct.agg_nofloat1* noalias sret(%struct.agg_nofloat1) align 4 %{{.*}}, i64 %{{.*}}) struct agg_nofloat2 { float a; int b; }; struct agg_nofloat2 pass_agg_nofloat2(struct agg_nofloat2 arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_agg_nofloat2(%struct.agg_nofloat2* noalias sret(%struct.agg_nofloat2) align 4 %{{.*}}, i64 %{{.*}}) struct agg_nofloat3 { float a; int : 0; }; struct agg_nofloat3 pass_agg_nofloat3(struct agg_nofloat3 arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_agg_nofloat3(%struct.agg_nofloat3* noalias sret(%struct.agg_nofloat3) align 4 %{{.*}}, i32 %{{.*}}) // Union types likewise are *not* float-like aggregate types union union_float { float a; }; union union_float pass_union_float(union union_float arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_union_float(%union.union_float* noalias sret(%union.union_float) align 4 %{{.*}}, i32 %{{.*}}) union union_double { double a; }; union union_double pass_union_double(union union_double arg) { return arg; } // CHECK-LABEL: define{{.*}} void @pass_union_double(%union.union_double* noalias sret(%union.union_double) align 8 %{{.*}}, i64 %{{.*}}) // Accessing variable argument lists int va_int(__builtin_va_list l) { return __builtin_va_arg(l, int); } // CHECK-LABEL: define{{.*}} signext i32 @va_int(%struct.__va_list_tag* %{{.*}}) // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 20 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to i32* // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 4 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to i32* // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi i32* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: [[RET:%[^ ]+]] = load i32, i32* [[VA_ARG_ADDR]] // CHECK: ret i32 [[RET]] long va_long(__builtin_va_list l) { return __builtin_va_arg(l, long); } // CHECK-LABEL: define{{.*}} i64 @va_long(%struct.__va_list_tag* %{{.*}}) // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to i64* // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to i64* // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi i64* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: [[RET:%[^ ]+]] = load i64, i64* [[VA_ARG_ADDR]] // CHECK: ret i64 [[RET]] long long va_longlong(__builtin_va_list l) { return __builtin_va_arg(l, long long); } // CHECK-LABEL: define{{.*}} i64 @va_longlong(%struct.__va_list_tag* %{{.*}}) // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to i64* // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to i64* // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi i64* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: [[RET:%[^ ]+]] = load i64, i64* [[VA_ARG_ADDR]] // CHECK: ret i64 [[RET]] double va_double(__builtin_va_list l) { return __builtin_va_arg(l, double); } // CHECK-LABEL: define{{.*}} double @va_double(%struct.__va_list_tag* %{{.*}}) // HARD-FLOAT: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 1 // SOFT-FLOAT: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // HARD-FLOAT: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 4 // SOFT-FLOAT: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // HARD-FLOAT: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 128 // SOFT-FLOAT: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to double* // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to double* // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi double* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: [[RET:%[^ ]+]] = load double, double* [[VA_ARG_ADDR]] // CHECK: ret double [[RET]] long double va_longdouble(__builtin_va_list l) { return __builtin_va_arg(l, long double); } // CHECK-LABEL: define{{.*}} void @va_longdouble(fp128* noalias sret(fp128) align 8 %{{.*}}, %struct.__va_list_tag* %{{.*}}) // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to fp128** // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to fp128** // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi fp128** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: [[INDIRECT_ARG:%[^ ]+]] = load fp128*, fp128** [[VA_ARG_ADDR]] // CHECK: [[RET:%[^ ]+]] = load fp128, fp128* [[INDIRECT_ARG]] // CHECK: store fp128 [[RET]], fp128* %{{.*}} // CHECK: ret void _Complex char va_complex_char(__builtin_va_list l) { return __builtin_va_arg(l, _Complex char); } // CHECK-LABEL: define{{.*}} void @va_complex_char({ i8, i8 }* noalias sret({ i8, i8 }) align 1 %{{.*}}, %struct.__va_list_tag* %{{.*}} // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to { i8, i8 }** // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to { i8, i8 }** // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi { i8, i8 }** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: [[INDIRECT_ARG:%[^ ]+]] = load { i8, i8 }*, { i8, i8 }** [[VA_ARG_ADDR]] // CHECK: ret void struct agg_1byte va_agg_1byte(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_1byte); } // CHECK-LABEL: define{{.*}} void @va_agg_1byte(%struct.agg_1byte* noalias sret(%struct.agg_1byte) align 1 %{{.*}}, %struct.__va_list_tag* %{{.*}} // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 23 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_1byte* // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 7 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_1byte* // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_1byte* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: ret void struct agg_2byte va_agg_2byte(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_2byte); } // CHECK-LABEL: define{{.*}} void @va_agg_2byte(%struct.agg_2byte* noalias sret(%struct.agg_2byte) align 1 %{{.*}}, %struct.__va_list_tag* %{{.*}} // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 22 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_2byte* // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 6 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_2byte* // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_2byte* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: ret void struct agg_3byte va_agg_3byte(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_3byte); } // CHECK-LABEL: define{{.*}} void @va_agg_3byte(%struct.agg_3byte* noalias sret(%struct.agg_3byte) align 1 %{{.*}}, %struct.__va_list_tag* %{{.*}} // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_3byte** // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_3byte** // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_3byte** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: [[INDIRECT_ARG:%[^ ]+]] = load %struct.agg_3byte*, %struct.agg_3byte** [[VA_ARG_ADDR]] // CHECK: ret void struct agg_4byte va_agg_4byte(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_4byte); } // CHECK-LABEL: define{{.*}} void @va_agg_4byte(%struct.agg_4byte* noalias sret(%struct.agg_4byte) align 1 %{{.*}}, %struct.__va_list_tag* %{{.*}} // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 20 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_4byte* // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 4 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_4byte* // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_4byte* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: ret void struct agg_8byte va_agg_8byte(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_8byte); } // CHECK-LABEL: define{{.*}} void @va_agg_8byte(%struct.agg_8byte* noalias sret(%struct.agg_8byte) align 1 %{{.*}}, %struct.__va_list_tag* %{{.*}} // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_8byte* // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_8byte* // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_8byte* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: ret void struct agg_float va_agg_float(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_float); } // CHECK-LABEL: define{{.*}} void @va_agg_float(%struct.agg_float* noalias sret(%struct.agg_float) align 4 %{{.*}}, %struct.__va_list_tag* %{{.*}} // HARD-FLOAT: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 1 // SOFT-FLOAT: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // HARD-FLOAT: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 4 // SOFT-FLOAT: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // HARD-FLOAT: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 128 // SOFT-FLOAT: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 20 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_float* // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 4 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_float* // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_float* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: ret void struct agg_double va_agg_double(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_double); } // CHECK-LABEL: define{{.*}} void @va_agg_double(%struct.agg_double* noalias sret(%struct.agg_double) align 8 %{{.*}}, %struct.__va_list_tag* %{{.*}} // HARD-FLOAT: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 1 // SOFT-FLOAT: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // HARD-FLOAT: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 4 // SOFT-FLOAT: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // HARD-FLOAT: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 128 // SOFT-FLOAT: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_double* // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_double* // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_double* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: ret void struct agg_longdouble va_agg_longdouble(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_longdouble); } // CHECK-LABEL: define{{.*}} void @va_agg_longdouble(%struct.agg_longdouble* noalias sret(%struct.agg_longdouble) align 8 %{{.*}}, %struct.__va_list_tag* %{{.*}} // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_longdouble** // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_longdouble** // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_longdouble** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: [[INDIRECT_ARG:%[^ ]+]] = load %struct.agg_longdouble*, %struct.agg_longdouble** [[VA_ARG_ADDR]] // CHECK: ret void struct agg_float_a8 va_agg_float_a8(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_float_a8); } // CHECK-LABEL: define{{.*}} void @va_agg_float_a8(%struct.agg_float_a8* noalias sret(%struct.agg_float_a8) align 8 %{{.*}}, %struct.__va_list_tag* %{{.*}} // HARD-FLOAT: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 1 // SOFT-FLOAT: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // HARD-FLOAT: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 4 // SOFT-FLOAT: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // HARD-FLOAT: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 128 // SOFT-FLOAT: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_float_a8* // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_float_a8* // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_float_a8* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: ret void struct agg_float_a16 va_agg_float_a16(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_float_a16); } // CHECK-LABEL: define{{.*}} void @va_agg_float_a16(%struct.agg_float_a16* noalias sret(%struct.agg_float_a16) align 16 %{{.*}}, %struct.__va_list_tag* %{{.*}} // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_float_a16** // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_float_a16** // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_float_a16** [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: [[INDIRECT_ARG:%[^ ]+]] = load %struct.agg_float_a16*, %struct.agg_float_a16** [[VA_ARG_ADDR]] // CHECK: ret void struct agg_nofloat1 va_agg_nofloat1(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_nofloat1); } // CHECK-LABEL: define{{.*}} void @va_agg_nofloat1(%struct.agg_nofloat1* noalias sret(%struct.agg_nofloat1) align 4 %{{.*}}, %struct.__va_list_tag* %{{.*}} // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_nofloat1* // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_nofloat1* // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_nofloat1* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: ret void struct agg_nofloat2 va_agg_nofloat2(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_nofloat2); } // CHECK-LABEL: define{{.*}} void @va_agg_nofloat2(%struct.agg_nofloat2* noalias sret(%struct.agg_nofloat2) align 4 %{{.*}}, %struct.__va_list_tag* %{{.*}} // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 16 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_nofloat2* // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 0 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_nofloat2* // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_nofloat2* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: ret void struct agg_nofloat3 va_agg_nofloat3(__builtin_va_list l) { return __builtin_va_arg(l, struct agg_nofloat3); } // CHECK-LABEL: define{{.*}} void @va_agg_nofloat3(%struct.agg_nofloat3* noalias sret(%struct.agg_nofloat3) align 4 %{{.*}}, %struct.__va_list_tag* %{{.*}} // CHECK: [[REG_COUNT_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 0 // CHECK: [[REG_COUNT:%[^ ]+]] = load i64, i64* [[REG_COUNT_PTR]] // CHECK: [[FITS_IN_REGS:%[^ ]+]] = icmp ult i64 [[REG_COUNT]], 5 // CHECK: br i1 [[FITS_IN_REGS]], // CHECK: [[SCALED_REG_COUNT:%[^ ]+]] = mul i64 [[REG_COUNT]], 8 // CHECK: [[REG_OFFSET:%[^ ]+]] = add i64 [[SCALED_REG_COUNT]], 20 // CHECK: [[REG_SAVE_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 3 // CHECK: [[REG_SAVE_AREA:%[^ ]+]] = load i8*, i8** [[REG_SAVE_AREA_PTR:[^ ]+]] // CHECK: [[RAW_REG_ADDR:%[^ ]+]] = getelementptr i8, i8* [[REG_SAVE_AREA]], i64 [[REG_OFFSET]] // CHECK: [[REG_ADDR:%[^ ]+]] = bitcast i8* [[RAW_REG_ADDR]] to %struct.agg_nofloat3* // CHECK: [[REG_COUNT1:%[^ ]+]] = add i64 [[REG_COUNT]], 1 // CHECK: store i64 [[REG_COUNT1]], i64* [[REG_COUNT_PTR]] // CHECK: [[OVERFLOW_ARG_AREA_PTR:%[^ ]+]] = getelementptr inbounds %struct.__va_list_tag, %struct.__va_list_tag* %{{.*}}, i32 0, i32 2 // CHECK: [[OVERFLOW_ARG_AREA:%[^ ]+]] = load i8*, i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[RAW_MEM_ADDR:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 4 // CHECK: [[MEM_ADDR:%[^ ]+]] = bitcast i8* [[RAW_MEM_ADDR]] to %struct.agg_nofloat3* // CHECK: [[OVERFLOW_ARG_AREA2:%[^ ]+]] = getelementptr i8, i8* [[OVERFLOW_ARG_AREA]], i64 8 // CHECK: store i8* [[OVERFLOW_ARG_AREA2]], i8** [[OVERFLOW_ARG_AREA_PTR]] // CHECK: [[VA_ARG_ADDR:%[^ ]+]] = phi %struct.agg_nofloat3* [ [[REG_ADDR]], %{{.*}} ], [ [[MEM_ADDR]], %{{.*}} ] // CHECK: ret void
the_stack_data/4038.c
//#include<cs50.h> //Importing cs50 library #include<string.h> //for getting string library for strlen #include<ctype.h> //for getting islower isupper fuctions #include<stdio.h> int main(void) { //This searches for each element & gives result with position no. when its found int a[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; printf("~ ~ ~ Welcome ~ ~ ~!\nWe have a collectin of Prime numbers from 1 to 30\n"); printf("Enter a prime Number in range to search > "); int find; scanf("%d", &find); int po = -1; //Records position for (int i = 0; i < 10 ; i++) //Loop for evaluation for entire array a[] { if (find == a[i]) { po = i + 1; } } if (po < 0) { printf("\n\nFailure ! Result not found. Enter a Prime number (1-30) next time\n\nAborting...\n"); } else { printf("\n\nSuccess !\nResult found at position no. %d\n\n", po); } }
the_stack_data/97011830.c
/** * \file appl_sample_example_10.c * * Source File for Generic OnOff Server as LPN Standalone application without CLI or * menu based console input interface. */ /* * Copyright (C) 2018. Mindtree Ltd. * All rights reserved. */ #if (MESH_STANDALONE == 10) /* ----------------------------------------- Header File Inclusion */ #include "MS_common.h" #include "MS_access_api.h" #include "MS_config_api.h" #include "MS_health_server_api.h" #include "MS_generic_onoff_api.h" #include "blebrr.h" #include "nvsto.h" #include "model_state_handler_pl.h" /* Console Input/Output */ #define CONSOLE_OUT(...) printf(__VA_ARGS__) #define CONSOLE_IN(...) scanf(__VA_ARGS__) void appl_dump_bytes(UCHAR *buffer, UINT16 length); void appl_mesh_sample (void); #define UI_FRND_CRITERIA 0x4B #define UI_FRND_RECEIVE_DELAY_MS 100 #define UI_FRND_POLLTIMEOUT_100MS 100 #define UI_FRND_SETUPTIMEOUT 10000 /* ----------------------------------------- External Global Variables */ /* ----------------------------------------- Exported Global Variables */ /* ----------------------------------------- Static Global Variables */ /* ----------------------------------------- Functions */ /* Model Server - Foundation Models */ /* Health Server - Test Routines */ static void UI_health_self_test_00(UINT8 test_id, UINT16 company_id) { } static void UI_health_self_test_01(UINT8 test_id, UINT16 company_id) { } static void UI_health_self_test_FF(UINT8 test_id, UINT16 company_id) { } /* List of Self Tests */ static MS_HEALTH_SERVER_SELF_TEST UI_health_server_self_tests[] = { { 0x00, /* Test ID: 0x00 */ UI_health_self_test_00 }, { 0x01, /* Test ID: 0x01 */ UI_health_self_test_01 }, { 0xFF, /* Test ID: 0xFF */ UI_health_self_test_FF } }; /** * \brief Health Server application Asynchronous Notification Callback. * * \par Description * Health Server calls the registered callback to indicate events occurred to the * application. * * \param handle Model Handle. * \param event_type Health Server Event type. * \param event_param Parameter associated with the event if any or NULL. * \param param_len Size of the event parameter data. 0 if event param is NULL. */ static API_RESULT UI_health_server_cb ( MS_ACCESS_MODEL_HANDLE * handle, UINT8 event_type, UINT8 * event_param, UINT16 param_len ) { CONSOLE_OUT( "Health Server Callback. Not handled. Returning\n"); return API_SUCCESS; } API_RESULT UI_register_foundation_model_servers ( MS_ACCESS_ELEMENT_HANDLE element_handle ) { /* Configuration Server */ MS_ACCESS_MODEL_HANDLE UI_config_server_model_handle; MS_ACCESS_MODEL_HANDLE UI_health_server_model_handle; API_RESULT retval; /* Health Server */ UINT16 company_id; MS_HEALTH_SERVER_SELF_TEST * self_tests; UINT32 num_self_tests; CONSOLE_OUT("In Model Server - Foundation Models\n"); retval = MS_config_server_init(element_handle, &UI_config_server_model_handle); CONSOLE_OUT("Config Model Server Registration Status: 0x%04X\n", retval); /* Health Server */ company_id = 0x0000; self_tests = &UI_health_server_self_tests[0]; num_self_tests = sizeof(UI_health_server_self_tests)/sizeof(MS_HEALTH_SERVER_SELF_TEST); retval = MS_health_server_init ( element_handle, &UI_health_server_model_handle, company_id, self_tests, num_self_tests, UI_health_server_cb ); if (API_SUCCESS == retval) { CONSOLE_OUT( "Health Server Initialized. Model Handle: 0x%04X\n", UI_health_server_model_handle); } else { CONSOLE_OUT( "[ERR] Sensor Server Initialization Failed. Result: 0x%04X\n", retval); } return retval; } /* ---- Generic OnOff States and Get/Set Handlers */ static MS_STATE_GENERIC_ONOFF_STRUCT UI_generic_onoff; /* Generic OnOff Model state Initialization */ void UI_generic_onoff_model_states_initialization(void) { EM_mem_set(&UI_generic_onoff, 0, sizeof(UI_generic_onoff)); } /* Generic OnOff Model Get Handler */ API_RESULT UI_generic_onoff_model_state_get(UINT16 state_t, UINT16 state_inst, void * param, UINT8 direction) { API_RESULT retval; retval = API_SUCCESS; switch(state_t) { case MS_STATE_GENERIC_ONOFF_T: { MS_STATE_GENERIC_ONOFF_STRUCT * param_p; param_p = (MS_STATE_GENERIC_ONOFF_STRUCT *)param; /* Ignoring Instance and direction right now */ *param_p = UI_generic_onoff; } break; default: break; } return retval; } /* Generic OnOff Model Set Handler */ API_RESULT UI_generic_onoff_model_state_set(UINT16 state_t, UINT16 state_inst, void * param, UINT8 direction) { API_RESULT retval; retval = API_SUCCESS; switch (state_t) { case MS_STATE_GENERIC_ONOFF_T: { MS_STATE_GENERIC_ONOFF_STRUCT * param_p; param_p = (MS_STATE_GENERIC_ONOFF_STRUCT *)param; /* Instantaneous Change */ UI_generic_onoff.onoff = param_p->onoff; *param_p = UI_generic_onoff; CONSOLE_OUT("[state] current: 0x%02X\n", UI_generic_onoff.onoff); CONSOLE_OUT("[state] target: 0x%02X\n", UI_generic_onoff.target_onoff); CONSOLE_OUT("[state] remaining_time: 0x%02X\n", UI_generic_onoff.transition_time); generic_onoff_set_pl(param_p->onoff); /* Ignoring Instance and direction right now */ } break; default: break; } return retval; } /* Model state Initialization */ void UI_model_states_initialization(void) { /* Generic OnOff States */ UI_generic_onoff_model_states_initialization(); } /* Generic OnOff Model Server */ /** * \brief Server Application Asynchronous Notification Callback. * * \par Description * Generic_Onoff server calls the registered callback to indicate events occurred to the application. * * \param [in] ctx Context of message received for a specific model instance. * \param [in] msg_raw Uninterpreted/raw received message. * \param [in] req_type Requested message type. * \param [in] state_params Model specific state parameters. * \param [in] ext_params Additional parameters. */ API_RESULT UI_generic_onoff_server_cb ( /* IN */ MS_ACCESS_MODEL_REQ_MSG_CONTEXT * ctx, /* IN */ MS_ACCESS_MODEL_REQ_MSG_RAW * msg_raw, /* IN */ MS_ACCESS_MODEL_REQ_MSG_T * req_type, /* IN */ MS_ACCESS_MODEL_STATE_PARAMS * state_params, /* IN */ MS_ACCESS_MODEL_EXT_PARAMS * ext_params ) { MS_STATE_GENERIC_ONOFF_STRUCT param; MS_ACCESS_MODEL_STATE_PARAMS current_state_params; API_RESULT retval; retval = API_SUCCESS; /* Check message type */ if (MS_ACCESS_MODEL_REQ_MSG_T_GET == req_type->type) { CONSOLE_OUT("[GENERIC_ONOFF] GET Request.\n"); UI_generic_onoff_model_state_get(state_params->state_type, 0, &param, 0); current_state_params.state_type = state_params->state_type; current_state_params.state = &param; /* Using same as target state and remaining time as 0 */ } else if (MS_ACCESS_MODEL_REQ_MSG_T_SET == req_type->type) { CONSOLE_OUT("[GENERIC_ONOFF] SET Request.\n"); retval = UI_generic_onoff_model_state_set(state_params->state_type, 0, (MS_STATE_GENERIC_ONOFF_STRUCT *)state_params->state, 0); current_state_params.state_type = state_params->state_type; current_state_params.state = (MS_STATE_GENERIC_ONOFF_STRUCT *)state_params->state; } /* See if to be acknowledged */ if (0x01 == req_type->to_be_acked) { CONSOLE_OUT("[GENERIC_ONOFF] Sending Response.\n"); /* Parameters: Request Context, Current State, Target State (NULL: to be ignored), Remaining Time (0: to be ignored), Additional Parameters (NULL: to be ignored) */ retval = MS_generic_onoff_server_state_update(ctx, &current_state_params, NULL, 0, NULL); } return retval; } API_RESULT UI_register_generic_onoff_model_server ( MS_ACCESS_ELEMENT_HANDLE element_handle ) { /* Generic OnOff Server */ MS_ACCESS_MODEL_HANDLE UI_generic_onoff_server_model_handle; API_RESULT retval; CONSOLE_OUT("In Generic OnOff Model Server\n"); retval = MS_generic_onoff_server_init ( element_handle, &UI_generic_onoff_server_model_handle, UI_generic_onoff_server_cb ); if (API_SUCCESS == retval) { CONSOLE_OUT( "Generic Onoff Server Initialized. Model Handle: 0x%04X\n", UI_generic_onoff_server_model_handle); } else { CONSOLE_OUT( "[ERR] Generic Onoff Server Initialization Failed. Result: 0x%04X\n", retval); } return retval; } void UI_lpn_seek_friend(void); void UI_frndsetup_cb(MS_SUBNET_HANDLE subnet, UCHAR event_type, UINT16 status) { API_RESULT retval; UINT16 num_subaddr; UINT16 subaddr[5]; CONSOLE_OUT("\nFriendship Event 0x%02X on Subnet 0x%04X - 0x%04X\n", event_type, subnet, status); switch (event_type) { case MS_TRN_FRIEND_SETUP_CNF: CONSOLE_OUT("Recvd MS_TRN_FRIEND_SETUP_CNF - 0x%04X\n", status); if (API_SUCCESS == status) { /* Get the subscription list */ num_subaddr = sizeof(subaddr) / sizeof(UINT16); MS_access_cm_get_all_model_subscription_list(&num_subaddr, subaddr); if (0 < num_subaddr) { CONSOLE_OUT("Initiating FriendSubscriptionListAdd - %d addr\n", num_subaddr); retval = MS_trn_lpn_subscrn_list_add(subaddr, num_subaddr); CONSOLE_OUT("Retval - 0x%04X\n", retval); } } else { CONSOLE_OUT("Friendship Setup Failure%04X\n", status); UI_lpn_seek_friend(); } break; case MS_TRN_FRIEND_SUBSCRNLIST_CNF: CONSOLE_OUT("Recvd MS_TRN_FRIEND_SUBSCRNLIST_CNF - 0x%04X\n", status); break; case MS_TRN_FRIEND_CLEAR_CNF: CONSOLE_OUT("Recvd MS_TRN_FRIEND_CLEAR_CNF - 0x%04X\n", status); break; case MS_TRN_FRIEND_TERMINATE_IND: CONSOLE_OUT("Recvd MS_TRN_FRIEND_TERMINATE_IND - 0x%04X\n", status); /* Enable Friend feature */ MS_ENABLE_FRIEND_FEATURE(); break; default: break; } } void UI_lpn_seek_friend (void) { API_RESULT retval; /* Disable Friend feature */ MS_DISABLE_FRIEND_FEATURE(); /* Enable LPN feature */ MS_ENABLE_LPN_FEATURE(); CONSOLE_OUT ("Requesting for friendship...\n"); retval = MS_trn_lpn_setup_friendship ( 0x00, UI_FRND_CRITERIA, UI_FRND_RECEIVE_DELAY_MS, UI_FRND_POLLTIMEOUT_100MS, UI_FRND_SETUPTIMEOUT, UI_frndsetup_cb ); CONSOLE_OUT ("Retval - 0x%04X\n", retval); return; } /* Provisionee */ #define UI_PROV_OUTPUT_OOB_ACTIONS \ (PROV_MASK_OOOB_ACTION_BLINK | PROV_MASK_OOOB_ACTION_BEEP | \ PROV_MASK_OOOB_ACTION_VIBRATE | PROV_MASK_OOOB_ACTION_NUMERIC | \ PROV_MASK_OOOB_ACTION_ALPHANUMERIC) /** Output OOB Maximum size supported */ #define UI_PROV_OUTPUT_OOB_SIZE 0x08 /** Input OOB Actions supported */ #define UI_PROV_INPUT_OOB_ACTIONS \ (PROV_MASK_IOOB_ACTION_PUSH | PROV_MASK_IOOB_ACTION_TWIST | \ PROV_MASK_IOOB_ACTION_NUMERIC | PROV_MASK_IOOB_ACTION_ALPHANUMERIC) /** Input OOB Maximum size supported */ #define UI_PROV_INPUT_OOB_SIZE 0x08 /** Beacon setup timeout in seconds */ #define UI_PROV_SETUP_TIMEOUT_SECS 30 /** Attention timeout for device in seconds */ #define UI_PROV_DEVICE_ATTENTION_TIMEOUT 30 #define PROV_AUTHVAL_SIZE_PL 16 /** Authentication values for OOB Display - To be made random */ #define UI_DISPLAY_AUTH_DIGIT 3 #define UI_DISPLAY_AUTH_NUMERIC 35007 #define UI_DISPLAY_AUTH_STRING "f00l" /** Provisioning capabilities of local device */ DECL_STATIC PROV_CAPABILITIES_S UI_prov_capab = { /** Number of Elements */ 0x01, /** Supported algorithms */ PROV_MASK_ALGO_EC_FIPS_P256, /** Public key type */ PROV_MASK_PUBKEY_OOBINFO, /** Static OOB type */ PROV_MASK_STATIC_OOBINFO, /** Output OOB information */ { UI_PROV_OUTPUT_OOB_ACTIONS, UI_PROV_OUTPUT_OOB_SIZE }, /** Input OOB information */ { UI_PROV_INPUT_OOB_ACTIONS, UI_PROV_INPUT_OOB_SIZE }, }; /** Unprovisioned device identifier */ PROV_DEVICE_S UI_lprov_device = { /** UUID */ {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}, /** OOB Flag */ 0x00, /** * Encoded URI Information * For example, to give a web address, "https://www.abc.com" * the URI encoded data would be - * 0x17 0x2F 0x2F 0x77 0x77 0x77 0x2E 0x61 0x62 0x63 0x2E 0x63 0x6F 0x6D * where 0x17 is the URI encoding for https: */ NULL }; /** Data exchanged during Provisiong procedure */ DECL_STATIC PROV_DATA_S UI_prov_data = { /** NetKey */ { 0x45, 0x74, 0x68, 0x65, 0x72, 0x4d, 0x69, 0x6e, 0x64, 0x4e, 0x65, 0x74, 0x4b, 0x65, 0x79, 0x00 }, /** Index of the NetKey */ 0x0000, /** Flags bitmask */ 0x00, /** Current value of the IV index */ 0x00000001, /** Unicast address of the primary element */ 0x0002 }; /** Current role of application - Provisioner/Device */ DECL_STATIC UCHAR UI_prov_role; /** Provisioning Handle */ DECL_STATIC PROV_HANDLE UI_prov_handle; API_RESULT UI_prov_callback ( PROV_HANDLE * phandle, UCHAR event_type, API_RESULT event_result, void * event_data, UINT16 event_datalen ) { PROV_DEVICE_S * rdev; PROV_CAPABILITIES_S * rcap; PROV_DATA_S * rdata; PROV_OOB_TYPE_S * oob_info; API_RESULT retval; UCHAR i; UCHAR authstr[PROV_AUTHVAL_SIZE_PL << 1]; UINT32 authnum; UCHAR authtype; UCHAR * pauth; UINT16 authsize; UCHAR pdata[(MS_DEVICE_UUID_SIZE * 2) + 1]; UCHAR * t_data; switch (event_type) { case PROV_EVT_PROVISIONING_SETUP: CONSOLE_OUT("Recvd PROV_EVT_PROVISIONING_SETUP\n"); CONSOLE_OUT("Status - 0x%04X\n", event_result); /* Display the attention timeout */ CONSOLE_OUT("Attention TImeout - %d\n", *((UCHAR *)event_data)); break; case PROV_EVT_OOB_DISPLAY: CONSOLE_OUT("Recvd PROV_EVT_OOB_DISPLAY\n"); CONSOLE_OUT("Status - 0x%04X\n", event_result); /* Reference the Authenticatio Type information */ oob_info = (PROV_OOB_TYPE_S *)event_data; CONSOLE_OUT("Authenticaion Action - 0x%02X\n", oob_info->action); CONSOLE_OUT("Authenticaion Size - 0x%02X\n", oob_info->size); /* If role is Device, the action is of Output OOB, else Input OOB */ if (PROV_ROLE_DEVICE == UI_prov_role) { if (PROV_OOOB_ACTION_ALPHANUMERIC == oob_info->action) { authtype = 1; } else if (PROV_OOOB_ACTION_NUMERIC == oob_info->action) { authtype = 2; } else { authtype = 0; } } else { if (PROV_IOOB_ACTION_ALPHANUMERIC == oob_info->action) { authtype = 1; } else if (PROV_IOOB_ACTION_NUMERIC == oob_info->action) { authtype = 2; } else { authtype = 0; } } if (1 == authtype) { EM_str_copy (authstr, UI_DISPLAY_AUTH_STRING); CONSOLE_OUT("\n\n>>> AuthVal - %s <<<\n\n", authstr); pauth = authstr; authsize = EM_str_len(authstr); } else if (2 == authtype) { authnum = (UINT32)UI_DISPLAY_AUTH_NUMERIC; CONSOLE_OUT("\n\n>>> AuthVal - %d <<<\n\n", authnum); pauth = (UCHAR *)&authnum; authsize = sizeof(UINT32); } else { authnum = (UINT32)UI_DISPLAY_AUTH_DIGIT; CONSOLE_OUT("\n\n>>> AuthVal - %d <<<\n\n", authnum); pauth = (UCHAR *)&authnum; authsize = sizeof(UINT32); } /* Call to input the oob */ CONSOLE_OUT("Setting the Authval...\n"); retval = MS_prov_set_authval(&UI_prov_handle, pauth, authsize); CONSOLE_OUT("Retval - 0x%04X\n", retval); break; case PROV_EVT_OOB_ENTRY: CONSOLE_OUT("Recvd PROV_EVT_OOB_ENTRY\n"); CONSOLE_OUT("Status - 0x%04X\n", event_result); /* Reference the Authenticatio Type information */ oob_info = (PROV_OOB_TYPE_S *)event_data; CONSOLE_OUT("Authenticaion Action - 0x%02X\n", oob_info->action); CONSOLE_OUT("Authenticaion Size - 0x%02X\n", oob_info->size); break; case PROV_EVT_DEVINPUT_COMPLETE: CONSOLE_OUT("Recvd PROV_EVT_DEVINPUT_COMPLETE\n"); CONSOLE_OUT("Status - 0x%04X\n", event_result); break; case PROV_EVT_PROVDATA_INFO: CONSOLE_OUT("Recvd PROV_EVT_PROVDATA_INFO\n"); CONSOLE_OUT("Status - 0x%04X\n", event_result); /* Reference the Provisioning Data */ rdata = (PROV_DATA_S *)event_data; CONSOLE_OUT("NetKey : "); appl_dump_bytes(rdata->netkey, PROV_KEY_NETKEY_SIZE); CONSOLE_OUT("Key ID : 0x%04X\n", rdata->keyid); CONSOLE_OUT("Flags : 0x%02X\n", rdata->flags); CONSOLE_OUT("IVIndex : 0x%08X\n", rdata->ivindex); CONSOLE_OUT("UAddr : 0x%04X\n", rdata->uaddr); /* Provide Provisioning Data to Access Layer */ MS_access_cm_set_prov_data ( rdata ); break; case PROV_EVT_PROVISIONING_COMPLETE: CONSOLE_OUT("Recvd PROV_EVT_PROVISIONING_COMPLETE\n"); CONSOLE_OUT("Status - 0x%04X\n", event_result); if (API_SUCCESS == event_result) { /* Already Set while handling PROV_EVT_PROVDATA_INFO */ } break; default: CONSOLE_OUT("Unknown Event - 0x%02X\n", event_type); } return API_SUCCESS; } void UI_register_prov(void) { API_RESULT retval; CONSOLE_OUT("Registering with Provisioning layer...\n"); retval = MS_prov_register(&UI_prov_capab, UI_prov_callback); CONSOLE_OUT("Retval - 0x%04X\n", retval); } void UI_setup_prov(UCHAR role, UCHAR brr) { API_RESULT retval; if (PROV_ROLE_PROVISIONER != role) { CONSOLE_OUT("Setting up Device for Provisioning ...\n"); retval = MS_prov_setup ( brr, role, &UI_lprov_device, UI_PROV_SETUP_TIMEOUT_SECS ); UI_prov_role = PROV_ROLE_DEVICE; } else { CONSOLE_OUT("Setting up Provisioner for Provisioning ...\n"); retval = MS_prov_setup ( brr, role, NULL, UI_PROV_SETUP_TIMEOUT_SECS ); UI_prov_role = PROV_ROLE_PROVISIONER; } CONSOLE_OUT("Retval - 0x%04X\n", retval); } void UI_prov_bind(UCHAR brr, UCHAR index) { API_RESULT retval; /* Call to bind with the selected device */ CONSOLE_OUT("Binding with the selected device...\n"); retval = MS_prov_bind(brr, &UI_lprov_device, UI_PROV_DEVICE_ATTENTION_TIMEOUT, &UI_prov_handle); CONSOLE_OUT("Retval - 0x%04X\n", retval); } void appl_mesh_sample (void) { MS_ACCESS_NODE_ID node_id; MS_ACCESS_ELEMENT_DESC element; MS_ACCESS_ELEMENT_HANDLE element_handle; API_RESULT retval; UCHAR role, brr; MS_CONFIG * config_ptr; #ifdef MS_HAVE_DYNAMIC_CONFIG MS_CONFIG config; /* Initialize dynamic configuration */ MS_INIT_CONFIG(config); config_ptr = &config; #else config_ptr = NULL; #endif /* MS_HAVE_DYNAMIC_CONFIG */ /* Initialize OSAL */ EM_os_init(); /* Initialize Debug Module */ EM_debug_init(); /* Initialize Timer Module */ EM_timer_init(); timer_em_init(); /* Initialize utilities */ nvsto_init(); /* Initialize Mesh Stack */ MS_init(config_ptr); /* Register with underlying BLE stack */ blebrr_register(); /* Create Node */ retval = MS_access_create_node(&node_id); /* Register Element */ /** * TBD: Define GATT Namespace Descriptions from * https://www.bluetooth.com/specifications/assigned-numbers/gatt-namespace-descriptors * * Using 'main' (0x0106) as Location temporarily. */ element.loc = 0x0106; retval = MS_access_register_element ( node_id, &element, &element_handle ); if (API_SUCCESS == retval) { /* Register foundation model servers */ retval = UI_register_foundation_model_servers(element_handle); } if (API_SUCCESS == retval) { /* Register Generic OnOff model server */ retval = UI_register_generic_onoff_model_server(element_handle); } if (API_SUCCESS == retval) { /* Initialize model states */ UI_model_states_initialization(); } /* Configure as provisionee/device */ UI_register_prov(); /** * setup <role:[1 - Device, 2 - Provisioner]> <bearer:[1 - Adv, 2 - GATT] */ role = PROV_ROLE_DEVICE; brr = PROV_BRR_ADV; UI_setup_prov(role, brr); UI_prov_bind(brr, 0x00); /* Enable Friend feature */ MS_ENABLE_FRIEND_FEATURE(); return; } #endif /* (MESH_STANDALONE == 10) */
the_stack_data/165766618.c
#include <stdio.h> int main(){ int a = 50; int b = 2; int Addition = a + b; int Subtraction = a - b; int Multiplication = a * b; int Division = a / b; int Modulus = a % b; int Increment = ++a; int Decrement = --b; printf("%i\n", Addition); printf("%i\n", Subtraction); printf("%i\n", Multiplication); printf("%i\n", Division); printf("%i\n", Modulus); printf("%i\n", Increment); printf("%i", Decrement); return 0; }
the_stack_data/90765916.c
#include <stdio.h> #include <stdlib.h> #include <time.h> /* * * Majority Number n/3 + 1 * * Is there better algorithm than O(nlg(n)) ? * Is O(n) practical? * Useful links : * * 1. http://stackoverflow.com/questions/4325200/find-the-majority-element-in-array * 2. http://www.geeksforgeeks.org/majority-element/ * 3. https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm * */ /* Using findRank Algorithms Find the elements at ranks n/3 and 2n/3 then It is trivial that the majoirty element is one among them. Find that by using a loop of O(n) Yo Yo */ void swap(int *a,int *b){ int temp; temp = *a; *a = *b; *b = temp; } int pivot(int a[], int i, int j){ int pivot = i + rand() % (j - i +1); return pivot; } int partition(int A[], int f, int l, int pivot){ int i,j; i = f; swap(&A[pivot],&A[l]); j = l - 1; while( i < j) { while(A[i] <= A[pivot]) i++; while(A[j] > A[pivot]) j--; if(i <= j){ swap(&A[i],&A[j]); i++; } } j++; swap(&A[j],&A[l]); return j; } // int partition(int A[], int f, int l, int pivot){ // int i,j; // i = f; // j = l; // swap(&A[pivot],&A[j]); // while( i < j) // { // while(A[i] <= A[pivot]) i++; // while(A[j] > A[pivot]) j--; // if(i <= j) // swap(&A[i],&A[j]); // i++; // j--; // } // swap(&A[j],&A[l]); // return j; // } // int partition(int arr[], int start, int end, int pos) // { // if (start == end) // return start; // int i, j; // i = start - 1; // j = start; // //pos = pivot(arr, start, end); // swap(&arr[pos], &arr[end]); // while (j < end) // { // if (arr[j] <= arr[end]) // { // i = i + 1; // swap(&arr[i], &arr[j]); // } // j++; // } // i = i + 1; // swap(&arr[i], &arr[end]); // return i; // } int findRank(int a[], int i, int j, int r){ int p = pivot(a,i,j); // modify it with goodPivot to get O(n) algorithm TODO int k = partition(a,i,j,p); if(r == j-k+1) return k; // returns the index of the pivot else if( r < j-k+1) return findRank(a,k+1,j,r); else return findRank(a,i,k - 1,r-j+k-1); } int main(int argc, char const *argv[]) { int a[] = {3, 3, 4, 2, 4, 4, 2, 4, 4}; int size = sizeof(a) / sizeof(a[0]); int oneThird = size/3, twoThrid = (2*size)/3; int chanceOne, chanceTwo; chanceOne = findRank(a, 0, size -1, oneThird); chanceTwo = findRank(a, 0, size -1, twoThrid); printf("Possibilities for Majority element are : %d %d\n", a[(size - 1) - chanceOne + 1], a[(size - 1) - chanceTwo + 1] ); int ele1 = a[(size - 1) - chanceOne + 1]; int ele2 = a[(size - 1) - chanceTwo + 1]; int count1 = 0, count2 = 0; for(int i = 1; i < size ; i++){ if(a[i] == ele1){ count1++; } } if(count1 >= ((size/3) + 1)) printf("Majority element can be %d\n", ele1); for(int i = 1; i < size ; i++){ if(a[i] == ele2){ count2++; } } if(count2 >= ((size/3) + 1)) printf("Majority element can be %d\n", ele2); return 0; }
the_stack_data/64735.c
/* Check that non-freeable locations are not freed. */ #include <malloc.h> int main() { int *p = (int *) malloc(10*sizeof(int)); p++; free(p); return 0; }
the_stack_data/43073.c
#include "libgen.h" #include "string.h" char* basename(char* path) { if (!path) return "."; size_t len = strlen(path); if (len == 0) return "."; while (len > 1 && path[len - 1] == '/') path[--len] = 0; char* last_slash = strrchr(path, '/'); if (!last_slash) return path; if (len == 1) return "/"; return last_slash + 1; }
the_stack_data/165767590.c
// RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp -fopenmp -fno-openmp-extensions -ferror-limit 100 -o - %s -Wuninitialized // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp -fopenmp -fno-openmp-extensions -ferror-limit 100 -o - -x c++ %s -Wuninitialized // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp -fopenmp-simd -fno-openmp-extensions -ferror-limit 100 -o - %s -Wuninitialized // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp -fopenmp-simd -fno-openmp-extensions -ferror-limit 100 -o - -x c++ %s -Wuninitialized // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,ompx -fopenmp -fopenmp-extensions -ferror-limit 100 -o - %s -Wuninitialized // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,ompx -fopenmp -fopenmp-extensions -ferror-limit 100 -o - -x c++ %s -Wuninitialized // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,ompx -fopenmp-simd -fopenmp-extensions -ferror-limit 100 -o - %s -Wuninitialized // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,ompx -fopenmp-simd -fopenmp-extensions -ferror-limit 100 -o - -x c++ %s -Wuninitialized int main(int argc, char **argv) { int r; #pragma omp target exit data // expected-error {{expected at least one 'map' clause for '#pragma omp target exit data'}} #pragma omp target exit data map(r) // expected-error {{map type must be specified for '#pragma omp target exit data'}} #pragma omp target exit data map(tofrom: r) // expected-error {{map type 'tofrom' is not allowed for '#pragma omp target exit data'}} #pragma omp target exit data map(always, from: r) allocate(r) // expected-error {{unexpected OpenMP clause 'allocate' in directive '#pragma omp target exit data'}} #pragma omp target exit data map(delete: r) #pragma omp target exit data map(release: r) #pragma omp target exit data map(always, alloc: r) // expected-error {{map type 'alloc' is not allowed for '#pragma omp target exit data'}} #pragma omp target exit data map(to: r) // expected-error {{map type 'to' is not allowed for '#pragma omp target exit data'}} // omp-error@+2 {{incorrect map type modifier, expected one of: 'always', 'close', 'mapper'}} // ompx-error@+1 {{map type modifier 'ompx_hold' is not allowed for '#pragma omp target exit data'}} #pragma omp target exit data map(ompx_hold, from: r) // omp-error@+2 {{incorrect map type modifier, expected one of: 'always', 'close', 'mapper'}} // ompx-error@+1 {{map type modifier 'ompx_hold' is not allowed for '#pragma omp target exit data'}} #pragma omp target exit data map(ompx_hold, release: r) // omp-error@+2 {{incorrect map type modifier, expected one of: 'always', 'close', 'mapper'}} // ompx-error@+1 {{map type modifier 'ompx_hold' is not allowed for '#pragma omp target exit data'}} #pragma omp target exit data map(ompx_hold, delete: r) return 0; }
the_stack_data/662607.c
#include <stdio.h> #include <stdlib.h> int main() { while (1) { printf("##################\n"); printf("# #\n"); printf("# SEJA BEM VINDO #\n"); printf("# #\n"); printf("##################\n"); break; } return 0; }
the_stack_data/84273.c
/* Copyright (c) 2002-2005 Vladislav Goncharov. * * Redistribution and use in source forms, with and without modification, * are permitted provided that this entire comment appears intact. * * Redistribution in binary form may occur without any restrictions. * * This software is provided ``AS IS'' without any warranties of any kind. */ // -*- mode: C++; tab-width: 4; indent-tabs-mode: nil -*- (for GNU Emacs) // // $Id: memtrack.c,v 1.2 2002/12/03 12:14:27 dev Exp $ #if DBG /* * Debug NonPaged pool routines (helpers to find memory leaks and pool corruption) */ #include <ntddk.h> #include "memtrack.h" #pragma warning(disable:4996) #define MAGIC 'TMEM' #define INT_3 __asm int 3 struct prefix { ULONG magic; struct prefix *next; struct prefix *prev; ULONG size; const char *file; ULONG line; char data[]; }; struct postfix { ULONG size; ULONG magic; }; static KSPIN_LOCK guard; static struct prefix *first, *last; static ULONG count; static struct postfix *check(struct prefix *p); void memtrack_init() { KeInitializeSpinLock(&guard); } void memtrack_free() { KIRQL irql; ULONG total = 0; KeAcquireSpinLock(&guard, &irql); if (first != NULL) { struct prefix *p; for (p = first; p; p = p->next) { check(p); KdPrint(("memtrack: memory leak detected! %s:%u (%u bytes)\n", p->file, p->line, p->size)); total += p->size; } } KeReleaseSpinLock(&guard, irql); KdPrint(("memtrack: Total memory leakage: %u bytes (%u blocks)\n", total, count)); if (total) INT_3; } void * mt_malloc(ULONG size, const char *file, ULONG line) { KIRQL irql; struct prefix *data; struct postfix *pd; #if 1 // check pool integrity KeAcquireSpinLock(&guard, &irql); for (data = first; data; data = data->next) check(data); for (data = last; data; data = data->prev) check(data); KeReleaseSpinLock(&guard, irql); #endif if (size == 0) { KdPrint(("memtrack: mt_malloc: size == 0!\n")); INT_3; return NULL; } data = (struct prefix *)ExAllocatePool(NonPagedPool, sizeof(struct prefix) + size + sizeof(struct postfix)); if (data == NULL) return NULL; data->magic = MAGIC; data->next = NULL; data->prev = NULL; data->size = size; data->file = file; data->line = line; memset(data->data, 0xcc, size); // fill by 0xcc: new pd = (struct postfix *)(data->data + data->size); pd->size = size; pd->magic = MAGIC; KeAcquireSpinLock(&guard, &irql); if (last) { last->next = data; data->prev = last; last = data; } else { data->prev = NULL; first = last = data; } count++; KeReleaseSpinLock(&guard, irql); return data->data; } void free(void *ptr) { KIRQL irql; struct prefix *data = (struct prefix *)((char *)ptr - sizeof(struct prefix)); struct postfix *pd = check(data); if (pd == NULL) return; KeAcquireSpinLock(&guard, &irql); if (data->next != NULL) data->next->prev = data->prev; else last = data->prev; if (data->prev != NULL) data->prev->next = data->next; else first = data->next; memset(data->data, 0xc9, data->size); // fill by 0xc9: free data->size = (ULONG)-1; pd->size = (ULONG)-1; count--; KeReleaseSpinLock(&guard, irql); ExFreePool(data); } struct postfix * check(struct prefix *p) { struct postfix *pd; if (p->magic != MAGIC) { KdPrint(("memtrack: check: invalid pre-magic! 0x%x\n", p)); INT_3; return NULL; } pd = (struct postfix *)(p->data + p->size); if (pd->magic != MAGIC) { KdPrint(("memtrack: memtrack_free: invalid post-magic! 0x%x\n", pd)); INT_3; return NULL; } if (p->size != pd->size) { KdPrint(("memtrack: memtracl_free: invalid post-size! 0x%x 0x%x\n", p, pd)); INT_3; return NULL; } return pd; } #endif /* DBG */
the_stack_data/107954182.c
#include <stdio.h> int main() { char c; printf("Enter a character: "); scanf("%c", &c); // %d displays the integer value of a character // %c displays the actual character printf("ASCII value of %c = %d", c, c); return 0; }
the_stack_data/1135613.c
#include <stdlib.h> #include <stdio.h> #include <time.h> #define PASSWORD_MIN_LEN 1 #define PASSWORD_MAX_LEN 32 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x))) static const char valid_characters[] = { ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~' }; int main(int argc, const char** argv) { char password[PASSWORD_MAX_LEN + 1]; size_t minlen, maxlen, len; size_t i; int n; /* Set seed. */ srandom(time(NULL)); /* Check arguments. */ if (argc == 2) { if (((n = atoi(argv[1])) < PASSWORD_MIN_LEN) || (n > PASSWORD_MAX_LEN)) { fprintf(stderr, "Invalid length '%s' (valid range: %u .. %u).\n", argv[1], PASSWORD_MIN_LEN, PASSWORD_MAX_LEN); return -1; } len = n; } else if (argc == 3) { if (((n = atoi(argv[1])) < PASSWORD_MIN_LEN) || (n > PASSWORD_MAX_LEN)) { fprintf(stderr, "Invalid length '%s' (valid range: %u .. %u).\n", argv[1], PASSWORD_MIN_LEN, PASSWORD_MAX_LEN); return -1; } minlen = n; if (((n = atoi(argv[2])) < PASSWORD_MIN_LEN) || (n > PASSWORD_MAX_LEN)) { fprintf(stderr, "Invalid length '%s' (valid range: %u .. %u).\n", argv[2], PASSWORD_MIN_LEN, PASSWORD_MAX_LEN); return -1; } maxlen = n; if (minlen > maxlen) { fprintf(stderr, "The minimum length (%s) is greater than " "the maximum length (%s).\n", argv[1], argv[2]); return -1; } /* Generate random length between minlen and maxlen. */ len = (random() % (maxlen - minlen + 1)) + minlen; } else { fprintf(stderr, "Usage: %s <length> [<maximum-length>]\n", argv[0]); fprintf(stderr, "\t<length> ::= %u .. %u\n", PASSWORD_MIN_LEN, PASSWORD_MAX_LEN); return -1; } /* Generate random password of length 'len'. */ for (i = 0; i < len; i++) { password[i] = valid_characters[random() % ARRAY_SIZE(valid_characters)]; } password[i] = 0; printf("Password length: %lu, password: '%s'.\n", len, password); return 0; }
the_stack_data/149891.c
#include <stdlib.h> // Converts an ASCII character to an integer int atoi(const char* str) { int32_t value = 0; // Walk the string... for (size_t i = 0; str[i] != '\0'; i++) { // Only convert sane input if (str[i] >= '0' && str[i] <= '9') { // 0 as a string character is numerically 48 dec // So, to go from the ASCII character to decimal, subtract 48 // The multiply by 10 effectively shifts the existing number over // Since value is initially 0, the multiplication does nothing on the first round value = (value * 10) + (str[i] - '0'); } else break; } // Finally, negate if needed... if (str[0] == '-') { value = -value; } return value; } // Skips sanity and negative checks, use only if you can guarantee the input meets these requirements! int atoi_fast(const char* str) { int32_t value = 0; for (size_t i = 0; str[i] != '\0'; i++) { value = (value * 10) + (str[i] - '0'); } return value; }
the_stack_data/25138470.c
#include <stdio.h> #define xchg(x,y)\ __asm__("xchg %1, %0":"+m"(x),"+r"(y)) //The XCHG (exchange data) instruction exchanges the contents of two operands. int main (){ int x=23; int y = 24; xchg(x,y); printf("x = %d \n",x); printf("y = %d \n",y); return 0; }
the_stack_data/360309.c
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define MAXELEMS 10000000 // nr. max de posicoes #define MAXTHREADS 100 // nr. max de threads #define min(a, b) (a) < (b) ? (a) : (b) int npos; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; // mutex p/a sec.critica int buf[MAXELEMS], pos = 0, val = 0; // variaveis partilhadas void *fill(void *nr) { while (1) { pthread_mutex_lock(&mut); if (pos >= npos) { pthread_mutex_unlock(&mut); return NULL; } buf[pos] = val; pos++; val++; pthread_mutex_unlock(&mut); *(int *)nr += 1; } } void *verify(void *arg) { int k; for (k = 0; k < npos; k++) { pthread_mutex_lock(&mut); if (buf[k] != k && k <= pos) // detecta valores errados printf("ERROR: buf[%d] = %d\n", k, buf[k]); pthread_mutex_unlock(&mut); } return NULL; } int main(int argc, char *argv[]) { int k, nthr, count[MAXTHREADS]; // array para contagens pthread_t tidf[MAXTHREADS], tidv; // tids dos threads int total; if (argc != 3) { printf("Usage: %s <nr_pos> <nr_thrs>\n", argv[0]); return 1; } npos = min(atoi(argv[1]), MAXELEMS); //no. efectivo de posicoes nthr = min(atoi(argv[2]), MAXTHREADS); //no. efectivo de threads pthread_create(&tidv, NULL, verify, NULL); for (k = 0; k < nthr; k++) { // criacao das threads 'fill' count[k] = 0; pthread_create(&tidf[k], NULL, fill, &count[k]); } total = 0; for (k = 0; k < nthr; k++) { //espera threads 'fill' pthread_join(tidf[k], NULL); printf("count[%d] = %d\n", k, count[k]); total += count[k]; } pthread_join(tidv, NULL); // espera thread 'verify' printf("total count = %d\n", total); // mostra total return 0; }
the_stack_data/95449153.c
#ifdef STM32F2xx #include "stm32f2xx_hal_dma_ex.c" #endif #ifdef STM32F4xx #include "stm32f4xx_hal_dma_ex.c" #endif #ifdef STM32F7xx #include "stm32f7xx_hal_dma_ex.c" #endif #ifdef STM32G0xx #include "stm32g0xx_hal_dma_ex.c" #endif #ifdef STM32G4xx #include "stm32g4xx_hal_dma_ex.c" #endif #ifdef STM32H7xx #include "stm32h7xx_hal_dma_ex.c" #endif #ifdef STM32L4xx #include "stm32l4xx_hal_dma_ex.c" #endif #ifdef STM32MP1xx #include "stm32mp1xx_hal_dma_ex.c" #endif #ifdef STM32WBxx #include "stm32wbxx_hal_dma_ex.c" #endif
the_stack_data/608116.c
/* * unfs3 Windows compatibility layer * Copyright 2006 Peter Åstrand <[email protected]> for Cendio AB * see file LICENSE for license details */ #ifdef WIN32 #define _WIN32_WINDOWS 0x0410 /* We require Windows 98 or later For GetLongPathName */ #include "config.h" #include <errno.h> #include <stdio.h> #include "winsupport.h" #include "Config/exports.h" #include "daemon.h" #include <assert.h> #include <windows.h> #include <wincrypt.h> #include <ctype.h> #include <fcntl.h> #include <limits.h> #include <direct.h> #include <dirent.h> #include <locale.h> #define MAX_NUM_DRIVES 26 #define FT70SEC 11644473600LL /* seconds between 1601-01-01 and 1970-01-01 */ #define wsizeof(x) (sizeof(x)/sizeof(wchar_t)) typedef struct _fdname { int fd; char *name; struct _fdname *next; } fdname; static fdname *fdnames = NULL; static char *get_fdname(int fd) { fdname *fn; for (fn = fdnames; fn; fn = fn->next) { if (fn->fd == fd) { return fn->name; break; } } assert(0); return NULL; } static int add_fdname(int fd, const char *name) { fdname *fn; fn = malloc(sizeof(fdname)); if (!fn) { logmsg(LOG_CRIT, "add_mount: Unable to allocate memory"); return -1; } fn->fd = fd; fn->name = strdup(name); fn->next = fdnames; fdnames = fn; return fd; } static void remove_fdname(int fd) { fdname *fn, **prevnext = &fdnames; for (fn = fdnames; fn; fn = fn->next) { if (fn->fd == fd) { *prevnext = fn->next; free(fn->name); free(fn); break; } prevnext = &fn->next; } } /* * The following UTF-8 validation is borrowed from * ftp://ftp.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c. */ /* * Copyright 2001-2004 Unicode, Inc. * * Disclaimer * * This source code is provided as is by Unicode, Inc. No claims are * made as to fitness for any particular purpose. No warranties of any * kind are expressed or implied. The recipient agrees to determine * applicability of information provided. If this file has been * purchased on magnetic or optical media from Unicode, Inc., the * sole remedy for any claim will be exchange of defective media * within 90 days of receipt. * * Limitations on Rights to Redistribute This Code * * Unicode, Inc. hereby grants the right to freely use the information * supplied in this file in the creation of products supporting the * Unicode Standard, and to make copies of this file in any form * for internal or external distribution as long as this notice * remains attached. */ /* * Index into the table below with the first byte of a UTF-8 sequence to * get the number of trailing bytes that are supposed to follow it. * Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is * left as-is for anyone who may want to do such conversion, which was * allowed in earlier algorithms. */ static const char trailingBytesForUTF8[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 }; /* * Utility routine to tell whether a sequence of bytes is legal UTF-8. * This must be called with the length pre-determined by the first byte. * If not calling this from ConvertUTF8to*, then the length can be set by: * length = trailingBytesForUTF8[*source]+1; * and the sequence is illegal right away if there aren't that many bytes * available. * If presented with a length > 4, this returns 0. The Unicode * definition of UTF-8 goes up to 4-byte sequences. */ static int isLegalUTF8(const unsigned char *source, int length) { unsigned char a; const unsigned char *srcptr = source + length; switch (length) { default: return 0; /* Everything else falls through when "1"... */ case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; case 2: if ((a = (*--srcptr)) > 0xBF) return 0; switch (*source) { /* no fall-through in this inner switch */ case 0xE0: if (a < 0xA0) return 0; break; case 0xED: if (a > 0x9F) return 0; break; case 0xF0: if (a < 0x90) return 0; break; case 0xF4: if (a > 0x8F) return 0; break; default: if (a < 0x80) return 0; } case 1: if (*source >= 0x80 && *source < 0xC2) return 0; } if (*source > 0xF4) return 0; return 1; } /* End of code borrowed from ConvertUTF.c */ int isLegalUTF8String(const unsigned char *source) { const unsigned char *seq, *sourceend; int seqlen; sourceend = source + strlen(source); seq = source; while (seq < sourceend) { seqlen = trailingBytesForUTF8[*seq] + 1; if (!isLegalUTF8(seq, seqlen)) return 0; seq += seqlen; } return 1; } /* Translate an internal representation of a path (like /c/home) to a Windows path (like c:\home) */ static wchar_t *intpath2winpath(const char *intpath) { wchar_t *winpath; int winpath_len; wchar_t *slash; const char *lastrootslash; wchar_t *lastslash; size_t intlen; /* Verify that input is valid UTF-8. We cannot use MB_ERR_INVALID_CHARS to MultiByteToWideChar, since it's only available in late versions of Windows. */ if (!isLegalUTF8String(intpath)) { logmsg(LOG_CRIT, "intpath2winpath: Illegal UTF-8 string:%s", intpath); return NULL; } /* Skip over multiple root slashes for paths like ///home/john */ lastrootslash = intpath; while (*lastrootslash == '/') lastrootslash++; if (lastrootslash != intpath) lastrootslash--; intlen = strlen(lastrootslash); /* One extra for /c -> c:\ */ winpath_len = sizeof(wchar_t) * (intlen + 2); winpath = malloc(winpath_len); if (!winpath) { logmsg(LOG_CRIT, "intpath2winpath: Unable to allocate memory"); return NULL; } if (!MultiByteToWideChar (CP_UTF8, 0, lastrootslash, -1, winpath, winpath_len)) { logmsg(LOG_CRIT, "intpath2winpath: MultiByteToWideChar failed"); return NULL; } /* If path ends with /.., chop of the last component. Eventually, we might want to eliminate all occurances of .. */ lastslash = wcsrchr(winpath, '/'); if (!wcscmp(lastslash, L"/..")) { *lastslash = '\0'; lastslash = wcsrchr(winpath, '/'); *lastslash = '\0'; } /* Translate /x -> x:/ and /x/something -> x:/something */ if ((winpath[0] == '/') && winpath[1]) { switch (winpath[2]) { case '\0': winpath[2] = '/'; winpath[3] = '\0'; /* fall through */ case '/': winpath[0] = winpath[1]; winpath[1] = ':'; break; default: break; } } while ((slash = wcschr(winpath, '/')) != NULL) { *slash = '\\'; } return winpath; } int win_seteuid(U(uid_t euid)) { return 0; } int win_setegid(U(gid_t egid)) { return 0; } int win_truncate(const char *path, off_t length) { int fd, ret, saved_errno; fd = win_open(path, O_WRONLY); if (fd < 0) return -1; ret = chsize(fd, length); saved_errno = errno; win_close(fd); errno = saved_errno; return ret; } int win_chown(U(const char *path), U(uid_t owner), U(gid_t group)) { errno = EINVAL; return -1; } int win_fchown(U(int fd), U(uid_t owner), U(gid_t group)) { errno = EINVAL; return -1; } int win_fchmod(int fildes, mode_t mode) { wchar_t *winpath; int ret; winpath = intpath2winpath(get_fdname(fildes)); if (!winpath) { errno = EINVAL; return -1; } ret = _wchmod(winpath, mode); free(winpath); return ret; } int inet_aton(const char *cp, struct in_addr *addr) { addr->s_addr = inet_addr(cp); return (addr->s_addr == INADDR_NONE) ? 0 : 1; } /* If you need a good laugh, take a look at the "Suggested Interix replacement" at: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnucmg/html/UCMGch10.asp */ ssize_t pread(int fd, void *buf, size_t count, off64_t offset) { ssize_t size; __int64 ret; if ((ret = _lseeki64(fd, (__int64)offset, SEEK_SET)) < 0) { fprintf(stderr, "Seeking for offset %I64d failed when reading.\n", offset); return -1; } size = read(fd, buf, count); return size; } ssize_t pwrite(int fd, const void *buf, size_t count, off64_t offset) { ssize_t size; __int64 ret; if ((ret = _lseeki64(fd, (__int64)offset, SEEK_SET)) < 0) { fprintf(stderr, "Seeking for offset %I64d failed when writing.\n", offset); return -1; } size = write(fd, buf, count); return size; } void syslog(U(int priority), U(const char *format), ...) { assert(0); } int win_init() { WORD winsock_ver; WSADATA wsadata; /* Set up locale, so that string compares works correctly */ setlocale(LC_ALL, ""); /* Verify that -s is used */ if (!opt_singleuser) { fprintf(stderr, "Single-user mode is required on this platform.\n"); exit(1); } /* Verify that -d is used */ if (opt_detach) { fprintf(stderr, "Foreground (debug) mode is required on this platform.\n"); exit(1); } /* init winsock */ winsock_ver = MAKEWORD(1, 1); if (WSAStartup(winsock_ver, &wsadata)) { fprintf(stderr, "Unable to initialise WinSock\n"); exit(1); } if (LOBYTE(wsadata.wVersion) != 1 || HIBYTE(wsadata.wVersion) != 1) { fprintf(stderr, "WinSock version is incompatible with 1.1\n"); WSACleanup(); exit(1); } /* disable error popups, for example from drives not ready */ SetErrorMode(SEM_FAILCRITICALERRORS); return 0; } void win_shutdown() { WSACleanup(); } /* Wrapper for Windows stat function, which provides st_dev and st_ino. These are calculated as follows: st_dev is set to the drive number (0=A 1=B ...). Our virtual root "/" gets a st_dev of 0xff. st_ino is hashed from the full file path. Each half produces a 32 bit hash. These are concatenated to a 64 bit value. The risk that st_ino is the same for two files on the system is, if I'm not mistaken, b=pigeon(2**32, f)**2. For f=1000, b=1e-08. By using a 64 bit hash function this risk can be lowered. Possible future enhancement. pigeon() can be calculated in Python with: def pigeon(m, n): res = 1.0 for i in range(m - n + 1, m): res = res * i / m return 1 - res */ int win_stat(const char *file_name, backend_statstruct * buf) { wchar_t *winpath; int ret; wchar_t pathbuf[4096]; int retval; size_t namelen; wchar_t *splitpoint; char savedchar; struct _stati64 win_statbuf; unsigned long long fti; /* Special case: Our top-level virtual root, containing each drive represented as a directory. Compare with "My Computer" etc. This virtual root has a hardcoded hash value of 1, to simplify debugging etc. */ if (!strcmp(file_name, "/")) { buf->st_mode = S_IFDIR | S_IRUSR | S_IWUSR; buf->st_nlink = MAX_NUM_DRIVES + 3; /* 3 extra for: . .. / */ buf->st_uid = 1; buf->st_gid = 1; buf->st_rdev = 0; buf->st_size = 4096; buf->st_atime = 0; buf->st_mtime = 0; buf->st_ctime = 0; buf->st_dev = 0xff; buf->st_ino = 1; return 0; } /* Since we're using FindFile() we have to make sure no one is trying to sneak in wildcard characters */ if (strcspn(file_name, "*?<>\"") != strlen(file_name)) { errno = EINVAL; return -1; } winpath = intpath2winpath(file_name); if (!winpath) { errno = EINVAL; return -1; } ret = _wstati64(winpath, &win_statbuf); if (ret < 0) { free(winpath); return ret; } /* Copy values to our struct */ buf->st_mode = win_statbuf.st_mode; buf->st_nlink = win_statbuf.st_nlink; buf->st_uid = win_statbuf.st_uid; buf->st_gid = win_statbuf.st_gid; buf->st_rdev = win_statbuf.st_rdev; buf->st_size = win_statbuf.st_size; buf->st_blocks = win_statbuf.st_size / 512; /* Windows miscalculates DST sometimes in stat() calls, so we need to use more standard Windows APIs. However CreateFile() cannot open files we don't have access to (excluding GetFileTime()) and GetFileAttributesEx() doesn't work on locked files. So that leaves FindFile() which seems to work everywhere. We just need to avoid wildcards (checked above). */ if (wcslen(winpath) == 3) { WIN32_FILE_ATTRIBUTE_DATA fileinfo; /* But just to make things interesting FindFile() doesn't work on root directories, so we have to use GetFileAttributesEx() here and pray there are no locking issues... */ retval = GetFileAttributesExW(winpath, GetFileExInfoStandard, &fileinfo); if (!retval) { free(winpath); errno = EACCES; return -1; } fti = (unsigned long long)fileinfo.ftLastAccessTime.dwHighDateTime << 32 | fileinfo.ftLastAccessTime.dwLowDateTime; buf->st_atime = fti / 10000000 - FT70SEC; fti = (unsigned long long)fileinfo.ftLastWriteTime.dwHighDateTime << 32 | fileinfo.ftLastWriteTime.dwLowDateTime; buf->st_mtime = fti / 10000000 - FT70SEC; /* Windows doesn't have "change time", so use modification time */ buf->st_ctime = buf->st_mtime; } else { HANDLE h; WIN32_FIND_DATAW finddata; h = FindFirstFileW(winpath, &finddata); if (h == INVALID_HANDLE_VALUE) { free(winpath); errno = EACCES; return -1; } FindClose(h); fti = (unsigned long long)finddata.ftLastAccessTime.dwHighDateTime << 32 | finddata.ftLastAccessTime.dwLowDateTime; buf->st_atime = fti / 10000000 - FT70SEC; fti = (unsigned long long)finddata.ftLastWriteTime.dwHighDateTime << 32 | finddata.ftLastWriteTime.dwLowDateTime; buf->st_mtime = fti / 10000000 - FT70SEC; /* Windows doesn't have "change time", so use modification time */ buf->st_ctime = buf->st_mtime; } /* * Windows doesn't update the modification time for directories * on FAT, so mark it as invalid (0) and let upper layers deal * with this by looking at the contents */ if (S_ISDIR(buf->st_mode)) { wchar_t rootpath[4]; wchar_t fsname[MAX_PATH+1]; wcsncpy(rootpath, winpath, 3); rootpath[3] = L'\0'; retval = GetVolumeInformationW(rootpath, NULL, 0, NULL, NULL, NULL, fsname, sizeof(fsname)); if (retval && (wcsstr(fsname, L"FAT") != NULL)) { buf->st_mtime = 0; buf->st_ctime = 0; } } retval = GetFullPathNameW(winpath, wsizeof(pathbuf), pathbuf, NULL); if (!retval) { errno = ENOENT; return -1; } /* Set st_dev to the drive number */ buf->st_dev = tolower(pathbuf[0]) - 'a'; /* GetLongPathName fails if called with only x:\, and drive x is not ready. So, only call it for other paths. */ if (pathbuf[0] && wcscmp(pathbuf + 1, L":\\")) { retval = GetLongPathNameW(pathbuf, pathbuf, wsizeof(pathbuf)); if (!retval || (unsigned) retval > wsizeof(pathbuf)) { /* Strangely enough, GetLongPathName returns ERROR_SHARING_VIOLATION for locked files, such as hiberfil.sys */ if (GetLastError() != ERROR_SHARING_VIOLATION) { errno = ENAMETOOLONG; return -1; } } } /* Hash st_ino, by splitting in two halves */ namelen = wcslen(pathbuf); splitpoint = &pathbuf[namelen / 2]; savedchar = *splitpoint; *splitpoint = '\0'; buf->st_ino = wfnv1a_32(pathbuf); assert(sizeof(buf->st_ino) == 8); buf->st_ino = buf->st_ino << 32; *splitpoint = savedchar; buf->st_ino |= wfnv1a_32(splitpoint); #if 0 fprintf(stderr, "win_stat: file=%s, ret=%d, st_dev=0x%x, st_ino=0x%I64x\n", file_name, ret, buf->st_dev, buf->st_ino); #endif free(winpath); return ret; } int win_open(const char *pathname, int flags, ...) { va_list args; mode_t mode; int fd; wchar_t *winpath; va_start(args, flags); mode = va_arg(args, int); va_end(args); winpath = intpath2winpath(pathname); if (!winpath) { errno = EINVAL; return -1; } fd = _wopen(winpath, flags | O_BINARY, mode); free(winpath); if (fd < 0) { return fd; } return add_fdname(fd, pathname); } int win_close(int fd) { remove_fdname(fd); return close(fd); } int win_fstat(int fd, backend_statstruct * buf) { return win_stat(get_fdname(fd), buf); } /* opendir implementation which emulates a virtual root with the drive letters presented as directories. */ UNFS3_WIN_DIR *win_opendir(const char *name) { wchar_t *winpath; UNFS3_WIN_DIR *ret; ret = malloc(sizeof(UNFS3_WIN_DIR)); if (!ret) { logmsg(LOG_CRIT, "win_opendir: Unable to allocate memory"); return NULL; } if (!strcmp("/", name)) { /* Emulate root */ ret->stream = NULL; ret->currentdrive = 0; ret->logdrives = GetLogicalDrives(); } else { winpath = intpath2winpath(name); if (!winpath) { free(ret); errno = EINVAL; return NULL; } ret->stream = _wopendir(winpath); free(winpath); if (ret->stream == NULL) { free(ret); ret = NULL; } } return ret; } struct dirent *win_readdir(UNFS3_WIN_DIR * dir) { if (dir->stream == NULL) { /* Emulate root */ for (; dir->currentdrive < MAX_NUM_DRIVES; dir->currentdrive++) { if (dir->logdrives & 1 << dir->currentdrive) break; } if (dir->currentdrive < MAX_NUM_DRIVES) { dir->de.d_name[0] = 'a' + dir->currentdrive; dir->de.d_name[1] = '\0'; dir->currentdrive++; return &dir->de; } else { return NULL; } } else { struct _wdirent *de; de = _wreaddir(dir->stream); if (!de) { return NULL; } if (!WideCharToMultiByte (CP_UTF8, 0, de->d_name, -1, dir->de.d_name, sizeof(dir->de.d_name), NULL, NULL)) { logmsg(LOG_CRIT, "win_readdir: WideCharToMultiByte failed"); return NULL; } return &dir->de; } } int win_closedir(UNFS3_WIN_DIR * dir) { if (dir->stream == NULL) { free(dir); return 0; } else { return _wclosedir(dir->stream); } } void openlog(U(const char *ident), U(int option), U(int facility)) { } char *win_realpath(const char *path, char *resolved_path) { return normpath(path, resolved_path); } int win_readlink(U(const char *path), U(char *buf), U(size_t bufsiz)) { errno = ENOSYS; return -1; } int win_mkdir(const char *pathname, U(mode_t mode)) { wchar_t *winpath; int ret; if (!strcmp("/", pathname)) { /* Emulate root */ errno = EROFS; return -1; } winpath = intpath2winpath(pathname); if (!winpath) { errno = EINVAL; return -1; } /* FIXME: Use mode */ ret = _wmkdir(winpath); free(winpath); return ret; } int win_symlink(U(const char *oldpath), U(const char *newpath)) { errno = ENOSYS; return -1; } int win_mknod(U(const char *pathname), U(mode_t mode), U(dev_t dev)) { errno = ENOSYS; return -1; } int win_mkfifo(U(const char *pathname), U(mode_t mode)) { errno = ENOSYS; return -1; } int win_link(U(const char *oldpath), U(const char *newpath)) { errno = ENOSYS; return -1; } int win_statvfs(const char *path, backend_statvfsstruct * buf) { wchar_t *winpath; DWORD SectorsPerCluster; DWORD BytesPerSector; DWORD NumberOfFreeClusters; DWORD TotalNumberOfClusters; ULARGE_INTEGER FreeBytesAvailable; ULARGE_INTEGER TotalNumberOfBytes; ULARGE_INTEGER TotalNumberOfFreeBytes; if (!strcmp("/", path)) { /* Emulate root */ buf->f_frsize = 1024; buf->f_blocks = 1024; buf->f_bfree = 0; buf->f_bavail = 0; buf->f_files = 1024; buf->f_ffree = 0; return 0; } winpath = intpath2winpath(path); if (!winpath) { errno = EINVAL; return -1; } winpath[3] = '\0'; /* Cut off after x:\ */ if (!GetDiskFreeSpaceW (winpath, &SectorsPerCluster, &BytesPerSector, &NumberOfFreeClusters, &TotalNumberOfClusters)) { errno = EIO; return -1; } if (!GetDiskFreeSpaceExW (winpath, &FreeBytesAvailable, &TotalNumberOfBytes, &TotalNumberOfFreeBytes)) { errno = EIO; return -1; } buf->f_frsize = BytesPerSector; buf->f_blocks = TotalNumberOfBytes.QuadPart / BytesPerSector; buf->f_bfree = TotalNumberOfFreeBytes.QuadPart / BytesPerSector; buf->f_bavail = FreeBytesAvailable.QuadPart / BytesPerSector; buf->f_files = buf->f_blocks / SectorsPerCluster; buf->f_ffree = buf->f_bfree / SectorsPerCluster; free(winpath); return 0; } int win_remove(const char *pathname) { wchar_t *winpath; int ret; if (!strcmp("/", pathname)) { /* Emulate root */ errno = EROFS; return -1; } winpath = intpath2winpath(pathname); if (!winpath) { errno = EINVAL; return -1; } ret = _wremove(winpath); free(winpath); return ret; } int win_chmod(const char *path, mode_t mode) { wchar_t *winpath; int ret; if (!strcmp("/", path)) { /* Emulate root */ errno = EROFS; return -1; } winpath = intpath2winpath(path); if (!winpath) { errno = EINVAL; return -1; } ret = _wchmod(winpath, mode); free(winpath); return ret; } int win_utime(const char *path, const struct utimbuf *times) { wchar_t *winpath; int ret = 0; HANDLE h; unsigned long long fti; FILETIME atime, mtime; if (!strcmp("/", path)) { /* Emulate root */ errno = EROFS; return -1; } winpath = intpath2winpath(path); if (!winpath) { errno = EINVAL; return -1; } /* Unfortunately, we cannot use utime(), since it doesn't support directories. */ fti = ((unsigned long long)times->actime + FT70SEC) * 10000000; atime.dwHighDateTime = (fti >> 32) & 0xffffffff; atime.dwLowDateTime = fti & 0xffffffff; fti = ((unsigned long long)times->modtime + FT70SEC) * 10000000; mtime.dwHighDateTime = (fti >> 32) & 0xffffffff; mtime.dwLowDateTime = fti & 0xffffffff; h = CreateFileW(winpath, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL); if (!SetFileTime(h, NULL, &atime, &mtime)) { errno = EACCES; ret = -1; } CloseHandle(h); free(winpath); return ret; } int win_rmdir(const char *path) { wchar_t *winpath; int ret; if (!strcmp("/", path)) { /* Emulate root */ errno = EROFS; return -1; } winpath = intpath2winpath(path); if (!winpath) { errno = EINVAL; return -1; } ret = _wrmdir(winpath); free(winpath); return ret; } int win_rename(const char *oldpath, const char *newpath) { wchar_t *oldwinpath, *newwinpath; int ret; if (!strcmp("/", oldpath) && !strcmp("/", newpath)) { /* Emulate root */ errno = EROFS; return -1; } oldwinpath = intpath2winpath(oldpath); if (!oldwinpath) { errno = EINVAL; return -1; } newwinpath = intpath2winpath(newpath); if (!newwinpath) { free(oldwinpath); errno = EINVAL; return -1; } ret = _wrename(oldwinpath, newwinpath); free(oldwinpath); free(newwinpath); return ret; } int win_gen_nonce(char *nonce) { HCRYPTPROV hCryptProv; if (!CryptAcquireContext (&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { logmsg(LOG_ERR, "CryptAcquireContext failed with error 0x%lx", GetLastError()); return -1; } if (!CryptGenRandom(hCryptProv, 32, nonce)) { logmsg(LOG_ERR, "CryptGenRandom failed with error 0x%lx", GetLastError()); return -1; } if (!CryptReleaseContext(hCryptProv, 0)) { logmsg(LOG_ERR, "CryptReleaseContext failed with error 0x%lx", GetLastError()); return -1; } return 0; } /* Just like strncasecmp, but compare two UTF8 strings. Limited to 4096 chars. */ int win_utf8ncasecmp(const char *s1, const char *s2, size_t n) { wchar_t ws1[4096], ws2[4096]; int converted; /* Make sure input is valid UTF-8 */ if (!isLegalUTF8String(s1)) { logmsg(LOG_CRIT, "win_utf8ncasecmp: Illegal UTF-8 string:%s", s1); return -1; } if (!isLegalUTF8String(s2)) { logmsg(LOG_CRIT, "win_utf8ncasecmp: Illegal UTF-8 string:%s", s2); return -1; } /* Convert both strings to wide chars */ converted = MultiByteToWideChar(CP_UTF8, 0, s1, n, ws1, wsizeof(ws1)); if (!converted) { logmsg(LOG_CRIT, "win_utf8ncasecmp: MultiByteToWideChar failed"); return -1; } ws1[converted] = '\0'; converted = MultiByteToWideChar(CP_UTF8, 0, s2, n, ws2, wsizeof(ws2)); if (!converted) { logmsg(LOG_CRIT, "win_utf8ncasecmp: MultiByteToWideChar failed"); return 1; } ws2[converted] = '\0'; /* compare */ return _wcsicmp(ws1, ws2); } #endif /* WIN32 */ /* ISO C forbids an empty source file */ typedef short pier;
the_stack_data/82950394.c
/*** includes ***/ #define _DEFAULT_SOURCE #define _BSD_SOURCE #define _GNU_SOURCE #include <ctype.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/types.h> #include <termios.h> #include <unistd.h> /*** defines ***/ #define KILO_VERSION "0.0.1" #define CTRL_KEY(k) ((k) & 0x1f) enum editorKey { ARROW_LEFT = 1000, ARROW_RIGHT, ARROW_UP, ARROW_DOWN, DEL_KEY, HOME_KEY, END_KEY, PAGE_UP, PAGE_DOWN }; /*** data ***/ typedef struct erow { int size; char *chars; } erow; struct editorConfig { int cx, cy; int screenrows; int screencols; int numrows; erow *row; struct termios orig_termios; }; struct editorConfig E; /*** terminal ***/ void die(const char *s) { write(STDOUT_FILENO, "\x1b[2J", 4); write(STDOUT_FILENO, "\x1b[H", 3); perror(s); exit(1); } void disableRawMode() { if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &E.orig_termios) == -1) die("tcsetattr"); } void enableRawMode() { if (tcgetattr(STDIN_FILENO, &E.orig_termios) == -1) die("tcgetattr"); atexit(disableRawMode); struct termios raw = E.orig_termios; raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); raw.c_oflag &= ~(OPOST); raw.c_cflag |= (CS8); raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); raw.c_cc[VMIN] = 0; raw.c_cc[VTIME] = 1; if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) die("tcsetattr"); } int editorReadKey() { int nread; char c; while ((nread = read(STDIN_FILENO, &c, 1)) != 1) { if (nread == -1 && errno != EAGAIN) die("read"); } if (c == '\x1b') { char seq[3]; if (read(STDIN_FILENO, &seq[0], 1) != 1) return '\x1b'; if (read(STDIN_FILENO, &seq[1], 1) != 1) return '\x1b'; if (seq[0] == '[') { if (seq[1] >= '0' && seq[1] <= '9') { if (read(STDIN_FILENO, &seq[2], 1) != 1) return '\x1b'; if (seq[2] == '~') { switch (seq[1]) { case '1': return HOME_KEY; case '3': return DEL_KEY; case '4': return END_KEY; case '5': return PAGE_UP; case '6': return PAGE_DOWN; case '7': return HOME_KEY; case '8': return END_KEY; } } } else { switch (seq[1]) { case 'A': return ARROW_UP; case 'B': return ARROW_DOWN; case 'C': return ARROW_RIGHT; case 'D': return ARROW_LEFT; case 'H': return HOME_KEY; case 'F': return END_KEY; } } } else if (seq[0] == 'O') { switch (seq[1]) { case 'H': return HOME_KEY; case 'F': return END_KEY; } } return '\x1b'; } else { return c; } } int getCursorPosition(int *rows, int *cols) { char buf[32]; unsigned int i = 0; if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) return -1; while (i < sizeof(buf) - 1) { if (read(STDIN_FILENO, &buf[i], 1) != 1) break; if (buf[i] == 'R') break; i++; } buf[i] = '\0'; if (buf[0] != '\x1b' || buf[1] != '[') return -1; if (sscanf(&buf[2], "%d;%d", rows, cols) != 2) return -1; return 0; } int getWindowSize(int *rows, int *cols) { struct winsize ws; if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) { if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12) return -1; return getCursorPosition(rows, cols); } else { *cols = ws.ws_col; *rows = ws.ws_row; return 0; } } /*** row operations ***/ void editorAppendRow(char *s, size_t len) { E.row = realloc(E.row, sizeof(erow) * (E.numrows + 1)); int at = E.numrows; E.row[at].size = len; E.row[at].chars = malloc(len + 1); memcpy(E.row[at].chars, s, len); E.row[at].chars[len] = '\0'; E.numrows++; } /*** file i/o ***/ void editorOpen(char *filename) { FILE *fp = fopen(filename, "r"); if (!fp) die("fopen"); char *line = NULL; size_t linecap = 0; ssize_t linelen; while ((linelen = getline(&line, &linecap, fp)) != -1) { while (linelen > 0 && (line[linelen - 1] == '\n' || line[linelen - 1] == '\r')) linelen--; editorAppendRow(line, linelen); } free(line); fclose(fp); } /*** append buffer ***/ struct abuf { char *b; int len; }; #define ABUF_INIT {NULL, 0} void abAppend(struct abuf *ab, const char *s, int len) { char *new = realloc(ab->b, ab->len + len); if (new == NULL) return; memcpy(&new[ab->len], s, len); ab->b = new; ab->len += len; } void abFree(struct abuf *ab) { free(ab->b); } /*** output ***/ void editorDrawRows(struct abuf *ab) { int y; for (y = 0; y < E.screenrows; y++) { if (y >= E.numrows) { if (E.numrows == 0 && y == E.screenrows / 3) { char welcome[80]; int welcomelen = snprintf(welcome, sizeof(welcome), "Kilo editor -- version %s", KILO_VERSION); if (welcomelen > E.screencols) welcomelen = E.screencols; int padding = (E.screencols - welcomelen) / 2; if (padding) { abAppend(ab, "~", 1); padding--; } while (padding--) abAppend(ab, " ", 1); abAppend(ab, welcome, welcomelen); } else { abAppend(ab, "~", 1); } } else { int len = E.row[y].size; if (len > E.screencols) len = E.screencols; abAppend(ab, E.row[y].chars, len); } abAppend(ab, "\x1b[K", 3); if (y < E.screenrows - 1) { abAppend(ab, "\r\n", 2); } } } void editorRefreshScreen() { struct abuf ab = ABUF_INIT; abAppend(&ab, "\x1b[?25l", 6); abAppend(&ab, "\x1b[H", 3); editorDrawRows(&ab); char buf[32]; snprintf(buf, sizeof(buf), "\x1b[%d;%dH", E.cy + 1, E.cx + 1); abAppend(&ab, buf, strlen(buf)); abAppend(&ab, "\x1b[?25h", 6); write(STDOUT_FILENO, ab.b, ab.len); abFree(&ab); } /*** input ***/ void editorMoveCursor(int key) { switch (key) { case ARROW_LEFT: if (E.cx != 0) { E.cx--; } break; case ARROW_RIGHT: if (E.cx != E.screencols - 1) { E.cx++; } break; case ARROW_UP: if (E.cy != 0) { E.cy--; } break; case ARROW_DOWN: if (E.cy != E.screenrows - 1) { E.cy++; } break; } } void editorProcessKeypress() { int c = editorReadKey(); switch (c) { case CTRL_KEY('q'): write(STDOUT_FILENO, "\x1b[2J", 4); write(STDOUT_FILENO, "\x1b[H", 3); exit(0); break; case HOME_KEY: E.cx = 0; break; case END_KEY: E.cx = E.screencols - 1; break; case PAGE_UP: case PAGE_DOWN: { int times = E.screenrows; while (times--) editorMoveCursor(c == PAGE_UP ? ARROW_UP : ARROW_DOWN); } break; case ARROW_UP: case ARROW_DOWN: case ARROW_LEFT: case ARROW_RIGHT: editorMoveCursor(c); break; } } /*** init ***/ void initEditor() { E.cx = 0; E.cy = 0; E.numrows = 0; E.row = NULL; if (getWindowSize(&E.screenrows, &E.screencols) == -1) die("getWindowSize"); } int main(int argc, char *argv[]) { enableRawMode(); initEditor(); if (argc >= 2) { editorOpen(argv[1]); } while (1) { editorRefreshScreen(); editorProcessKeypress(); } return 0; }
the_stack_data/106595.c
#include<stdio.h> #if __EMSCRIPTEN__ #include<emscripten.h> #endif int main(int argc, char **argv) { puts("Super advanced example!"); #if __EMSCRIPTEN__ EM_ASM(alert('Inline JavaScript!');); #endif return 0; }
the_stack_data/29762.c
#include <stdio.h> #include <math.h> int main() { float x0, x1, epsilon, residual; x0 = 0.0; x1 = 0.0; epsilon = 0.000005; residual = 0.0; int k = 0; /* * Newtonverfahren - f(x) = x^2 - 2*x - 0.15 */ printf("k\tX0\tX1\tResiduum\n"); do { x0 = x1; x1 = x0 - (((x0 * x0) - (2 * x0) - 0.15) / ((2 * x0) - 2)); residual = fabs(x0 - x1); k++; printf("%i\t%.5f\t%.5f\t%.5f\n",k,x0,x1,residual); } while (fabs(residual) > epsilon); return 0; }
the_stack_data/31388598.c
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> // 232 greyscale, 16 colour #define MANDEL_COLOR_MIN 16 #define MANDEL_COLOR_MAX 255 #define MANDEL_COLOR_RANGE (MANDEL_COLOR_MAX - MANDEL_COLOR_MIN) void put_colored(int color, char *what) { printf("\033[38;5;%dm%s", color, what); } int main(int argc, char **argv) { if (argc != 3) { fputs("Need 2 args: rows, columns\n", stderr); return 1; } int rows = atoi(argv[1]); int columns = atoi(argv[2]); int centre_x = columns / 2; int centre_y = rows / 2; double scale_x = 2 / (double)columns; double scale_y = 2 / (double)rows; centre_x += .5 / scale_x; int max_iters = 10; int *arr = malloc(rows * columns * sizeof *arr); while (true) { for (int row = 0; row < rows; row++) { for (int col = 0; col < columns; col++) { double mandel_re = (col - centre_x) * scale_x; double mandel_im = (row - centre_y) * scale_y; double orig_re = mandel_re; double orig_im = mandel_im; int iters = 0; if ((mandel_re + 1 / 4.) * (mandel_re + 1 / 4.) + mandel_im * mandel_im < 0.25) { iters = max_iters; } else { while (mandel_re * mandel_re + mandel_im * mandel_im < 4) { double temp_im = mandel_re * mandel_im * 2 + orig_im; mandel_re = mandel_re * mandel_re - mandel_im * mandel_im + orig_re; mandel_im = temp_im; iters++; if (iters == max_iters) break; } } iters = (int) (log(iters) / log(max_iters) * MANDEL_COLOR_RANGE); arr[row * columns + col] = iters + MANDEL_COLOR_MIN; } } // Draw! printf("\033[1;1H"); for (int i = 0; i < rows * columns; i++) put_colored(arr[i], "█"); fflush(stdout); max_iters *= 2; } }
the_stack_data/173579139.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strlcat.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: anicusan <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/07/12 00:24:37 by anicusan #+# #+# */ /* Updated: 2016/07/12 00:24:58 by anicusan ### ########.fr */ /* */ /* ************************************************************************** */ int ft_strlen(const char *str) { unsigned long i; i = 0; if (!str) return (0); while (str[i]) i++; return (i); } unsigned int ft_strlcat(char *dest, char *src, unsigned int size) { char *d; char *s; unsigned int n; unsigned int dlen; d = dest; s = src; n = size; while (*d != '\0' && n-- != 0) d++; dlen = d - dest; n = size - dlen; if (n == 0) return (dlen + ft_strlen(s)); while (*s != '\0') { if (n != 1) { *d++ = *s; n--; } s++; } *d = '\0'; return (dlen + (s - src)); }
the_stack_data/529973.c
//@AUTHOR : Guilherme Cardoso Oliveira <[email protected]> //@lICENSE: MIT //@DATE : 2021-06-29 #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define DATA_STRUCT_NAME "AVL Tree" #define ERR_NO_MEMORY "Not enough memory" //----------------------------------------------------------- //DATA typedef int Data; #define DATA_FORMAT "%d" //----------------------------------------------------------- //NODE typedef struct node { Data data; int height; struct node *left; struct node *right; } * Node; //----------------------------------------------------------- //Binary Tree typedef struct tree { Node root; } * Tree; //----------------------------------------------------------- //UTILITY METHODS void error(char *msg) { printf("\n[ERR] %s", msg); exit(1); } int max(int a, int b) { return (a > b)? a : b; } //----------------------------------------------------------- //NODE METHODS bool empty(Node node) { return node == NULL; } Node new_node(Data data) { Node node = (Node) malloc(sizeof(Node)); if(empty(node)) error(ERR_NO_MEMORY); node->data = data; node->height = 0; //leaf node->left = NULL; node->right = NULL; return node; } int height(Node node) { return (empty(node))? -1 : node->height; } void updateHeight(Node node) { node->height = max(height(node->left), height(node->right))+1; } int balance(Node node) { return (empty(node))? 0 : height(node->right) - height(node->left); } // node = 3 Node rotateToLeft(Node node) { //printf("ROTACAO PRA ESQUERDA\n"); Node right = node->right; //4 node->right = right->left; //x right->left = node; //3 updateHeight(node ); updateHeight(right); return right; } //node = 5 Node rotateToRight(Node node) { //printf("ROTACAO PRA DIREITA\n"); Node left = node->left; //left = 4 node->left = left->right; //x left->right = node; // 5 updateHeight(node ); updateHeight(left); return left; } Node rotateToLeftAndRight(Node node) { //printf("ROTACAO PRA ESQUERDA/DIREITA\n"); node->left = rotateToLeft(node->left); return rotateToRight(node); } Node rotateToRightAndLeft(Node node) { //printf("ROTACAO PRA DIREITA/ESQUERDA\n"); node->right = rotateToRight(node->right); return rotateToLeft(node); } Node applyRotationTable(Node node, Data data) { //printf("Olhando data: %d | B:%d\n", node->data, balance(node)); int balance_factor = balance(node); // left left Case if (balance_factor < -1 && data < node->left->data) return rotateToRight(node); // Right Right Case if (balance_factor > 1 && data > node->right->data) return rotateToLeft(node); // Left Right Case if (balance_factor < -1 && data > node->left->data) return rotateToLeftAndRight(node); // Right Left Case if (balance_factor > 1 && data < node->right->data) return rotateToRightAndLeft(node); return node; } Node insert_node(Node current, Data data) { if(empty(current)) return new_node(data); if(data < current->data) current->left = insert_node(current->left , data); else current->right = insert_node(current->right, data); //update height (recursively) current->height = 1 + max(height(current->left), height(current->right)); //apply rotation(s) return applyRotationTable(current, data); } void print_node(Node current) { if(empty(current)) return; printf(DATA_FORMAT, current->data); printf("("); print_node(current->left); print_node(current->right); printf(") "); } //----------------------------------------------------------- //TREE METHODS bool isEmpty(Tree tree) { return tree == NULL; } Tree new_tree() { Tree tree = (Tree) malloc(sizeof(Tree)); if(isEmpty(tree)) error(ERR_NO_MEMORY); tree->root = NULL; return tree; } void insert(Tree tree, Data data) { tree->root = insert_node(tree->root, data); //printf("---\n"); } void print(Tree tree) { printf("\n"); print_node(tree->root); } //----------------------------------------------------------- //MAIN int main() { Tree tree = new_tree(); insert(tree, 1); insert(tree, 3); insert(tree, 2); print(tree); return 0; }
the_stack_data/145454076.c
// RUN: c-index-test -code-completion-at=%s:6:2 -remap-file="%s;%S/Inputs/remap-complete-to.c" %s | FileCheck %s // CHECK: FunctionDecl:{ResultType int}{TypedText f0}{LeftParen (} void f() { }
the_stack_data/242330187.c
/* * Copyright (C) 2010 Gil Mendes * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /** * @file * @brief Execute shell command function. */ #include <stdlib.h> #include <unistd.h> /** Execute a shell command. * @param command Command line to execute, will be run using 'sh -c <line>'. * @return Exit status of process (in format returned by wait()), * or -1 if unable to fork the process. */ int system(const char *command) { int status; pid_t pid; pid = fork(); if(pid == 0) { execl("/system/bin/sh", "/system/bin/sh", "-c", command, NULL); exit(127); } else if(pid > 0) { pid = waitpid(pid, &status, 0); if(pid < 0) { return -1; } return status; } else { return -1; } }
the_stack_data/118751.c
//Se ingresan cuatro numeros y se saca el promedio. #include <stdio.h> int main(){ int n1,n2,n3,n4; int resultado; printf("Ingrese cuatro numeros para sacar su promedio: "); scanf("%i %i %i %i",&n1,&n2,&n3,&n4); resultado = (n1 + n2 + n3 + n4)/4; printf("El promedio de esos numeros es: %i",resultado); return 0; }
the_stack_data/154829876.c
#include<stdio.h> int main() { printf("\n\n\t\tStudytonight - Best place to learn\n\n\n"); int n, m, c, d, first[10][10], second[10][10], sum[10][10], diff[10][10]; printf("\nEnter the number of rows and columns of the first matrix \n\n"); scanf("%d%d", &m, &n); printf("\nEnter the %d elements of the first matrix \n\n", m*n); for(c = 0; c < m; c++) // to iterate the rows for(d = 0; d < n; d++) // to iterate the columns scanf("%d", &first[c][d]); printf("\nEnter the %d elements of the second matrix \n\n", m*n); for(c = 0; c < m; c++) // to iterate the rows for(d = 0; d < n; d++) // to iterate the columns scanf("%d", &second[c][d]); /* printing the first matrix */ printf("\n\nThe first matrix is: \n\n"); for(c = 0; c < m; c++) // to iterate the rows { for(d = 0; d < n; d++) // to iterate the columns { printf("%d\t", first[c][d]); } printf("\n"); } /* printing the second matrix */ printf("\n\nThe second matrix is: \n\n"); for(c = 0; c < m; c++) // to iterate the rows { for(d = 0; d < n; d++) // to iterate the columns { printf("%d\t", second[c][d]); } printf("\n"); } /* finding the SUM of the two matrices and storing in another matrix sum of the same size */ for(c = 0; c < m; c++) for(d = 0; d < n; d++) sum[c][d] = first[c][d] + second[c][d]; // printing the elements of the sum matrix printf("\n\nThe sum of the two entered matrices is: \n\n"); for(c = 0; c < m; c++) { for(d = 0; d < n; d++) { printf("%d\t", sum[c][d]); } printf("\n"); } /* finding the DIFFERENCE of the two matrices and storing in another matrix difference of the same size */ for(c = 0; c < m; c++) for(d = 0; d < n; d++) diff[c][d] = first[c][d] - second[c][d]; // printing the elements of the diff matrix printf("\n\nThe difference(subtraction) of the two entered matrices is: \n\n"); for(c = 0; c < m; c++) { for(d = 0; d < n; d++) { printf("%d\t", diff[c][d]); } printf("\n"); } printf("\n\n\t\t\tCoding is Fun !\n\n\n"); return 0; }
the_stack_data/243892958.c
int main() { int a = 68; int b =5 ; a = a << a << b; return a; }
the_stack_data/1209269.c
#include<stdio.h> #include<assert.h> int main() { int rs, rt, ach, acl; int result, resulth, resultl; rs = 0x00FFBBAA; rt = 0x4B231000; resulth = 0x4b0f01; resultl = 0x71f8a000; __asm ("mult $ac1, %2, %3\n\t" "mfhi %0, $ac1\n\t" "mflo %1, $ac1\n\t" : "=r"(ach), "=r"(acl) : "r"(rs), "r"(rt) ); assert(ach == resulth); assert(acl == resultl); return 0; }
the_stack_data/11168.c
int foo(int a, int b) { #define A0(a, b) ((a)+(b)) #define A1(a, b) ((a)>(b))?A0((a)-(b), (b)):A0((b)-(a), (a)) #define A2(a, b) ((a)>(b))?A1((a)-(b), (b)):A1((b)-(a), (a)) #define A3(a, b) ((a)>(b))?A2((a)-(b), (b)):A2((b)-(a), (a)) #define A4(a, b) ((a)>(b))?A3((a)-(b), (b)):A3((b)-(a), (a)) #define A5(a, b) ((a)>(b))?A4((a)-(b), (b)):A4((b)-(a), (a)) #define A6(a, b) ((a)>(b))?A5((a)-(b), (b)):A5((b)-(a), (a)) #define A7(a, b) ((a)>(b))?A6((a)-(b), (b)):A6((b)-(a), (a)) #define A8(a, b) ((a)>(b))?A7((a)-(b), (b)):A7((b)-(a), (a)) #define A9(a, b) ((a)>(b))?A8((a)-(b), (b)):A8((b)-(a), (a)) #define A10(a, b) ((a)>(b))?A9((a)-(b), (b)):A9((b)-(a), (a)) #define A11(a, b) ((a)>(b))?A10((a)-(b), (b)):A10((b)-(a), (a)) return A10(a, b); }
the_stack_data/97013563.c
#include <stdio.h> #include <stdlib.h> #include <pthread.h> int foo; void *thread_body() { foo += 1; } int main(int argc, char **argv) { int result = 0; int number = 0; pthread_t thread; foo = 0; if (2 > argc) { printf("usage: %s <number>\n", argv[0]); return result; } number = atoi(argv[1]); pthread_create(&thread, NULL, thread_body, NULL); foo += number; pthread_join(thread, NULL); return result; }
the_stack_data/23015.c
int main() { int *x[5][5]; int i1=2; int i2=1; int y; x[i1][i2] = &y; return(0); }
the_stack_data/181392719.c
#include <stdio.h> int main(){ int qt,i,qfil,j,idade,sex=0,flagid=2,contIdade18=0, contid=0,contM18=0, idM=0,sexom; //cSf=0,cSm=0, float result; scanf("%d",&qt); for(i=0;i<qt;i++){ scanf("%d",&qfil); for(j=1;j<=qfil;j++){ scanf("%d %d",&idade,&sex); // Sexo do Filho Mais Velho if(idade>idM){ idM=idade; sexom=sex; } /*if(sex==2){ cSf++; } else if (sex==2){ cSm++; }*/ if(idade>=18){ flagid=1; } if(idade>=18 && sex==1){ contid++; contM18=contM18+idade; } } // Fim do For mais Interno if(sexom==1){ printf("Masculino\n"); } if(sexom==2){ printf("Feminino\n"); } sexom=0; if(flagid==1){ contIdade18++; } flagid=0; } result=(float)contM18/contid; printf("%d (qde. de famílias com filhos maiores de idade)\n",contIdade18); printf("%.2f (média de idade dos homens m. de idade)\n",result); return 0; }
the_stack_data/161079953.c
// RUN: %clang_cc1 -E %s 2>&1 | FileCheck %s -strict-whitespace // PR6101 int a; // CHECK: # 1 "{{.*}}line-directive-output.c" // Check that we do not emit an enter marker for the main file. // CHECK-NOT: # 1 "{{.*}}line-directive-output.c" 1 // CHECK: int a; // CHECK-NEXT: # 50 "{{.*}}line-directive-output.c" // CHECK-NEXT: int b; #line 50 int b; // CHECK: # 13 "{{.*}}line-directive-output.c" // CHECK-NEXT: int c; # 13 int c; // CHECK-NEXT: # 1 "A.c" #line 1 "A.c" // CHECK-NEXT: # 2 "A.c" #line 2 // CHECK-NEXT: # 1 "B.c" #line 1 "B.c" // CHECK-NEXT: # 1000 "A.c" #line 1000 "A.c" int y; // CHECK: # 1010 "A.c" int z; extern int x; # 3 "temp2.h" 1 extern int y; # 7 "A.c" 2 extern int z; // CHECK: # 25 "A.c" // CHECK: # 50 "C.c" 1 # 50 "C.c" 1 // CHECK-NEXT: # 2000 "A.c" 2 # 2000 "A.c" 2 # 42 "A.c" # 44 "A.c" # 49 "A.c"
the_stack_data/181393491.c
#include <stdlib.h> void main () { int x, y, z; int *p, *q, *r; int **a, **b, **c; int *m; a = &p; b = &q; p = &x; q = &y; *a = &z; *b = *a; r = *a; c = &q; c = &r; m = malloc(sizeof(int*)); *c = m; switch(rand()) { case 0: assert(p != &x); // fail case 1: assert(p != &z); // fail case 2: assert(q != m); // fail case 3: assert(q != &x); // fail case 4: assert(q != &y); // fail case 5: assert(q != &z); // fail case 6: assert(r != m); // fail case 7: assert(r != &x); // fail case 8: assert(r != &z); // fail case 9: assert(a != &p); // fail case 10: assert(b != &q); // fail case 11: assert(c != &q); // fail default: assert(c != &r); // fail } } /* p -> {&x, &z} q -> {alloc#14, &x, &y, &z} r -> {alloc#14, &x, &z} a -> {&p} b -> {&q} c -> {&q, &r} */
the_stack_data/151706052.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern void signal(int sig , void *func ) ; extern float strtof(char const *str , char const *endptr ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned char input[1] , unsigned char output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; void megaInit(void) { { } } void RandomFunc(unsigned char input[1] , unsigned char output[1] ) { unsigned char state[1] ; { state[0UL] = (input[0UL] | 51238316UL) >> (unsigned char)3; if ((state[0UL] >> (unsigned char)3) & (unsigned char)1) { if ((state[0UL] >> (unsigned char)4) & (unsigned char)1) { state[0UL] >>= ((state[0UL] >> (unsigned char)3) & (unsigned char)7) | 1UL; state[0UL] >>= ((state[0UL] >> (unsigned char)1) & (unsigned char)7) | 1UL; } else { state[0UL] <<= ((state[0UL] >> (unsigned char)3) & (unsigned char)7) | 1UL; state[0UL] <<= ((state[0UL] >> (unsigned char)3) & (unsigned char)7) | 1UL; } } else { state[0UL] >>= ((state[0UL] >> (unsigned char)1) & (unsigned char)7) | 1UL; state[0UL] >>= ((state[0UL] >> (unsigned char)4) & (unsigned char)7) | 1UL; } output[0UL] = (state[0UL] ^ 246575798UL) << (unsigned char)7; } } int main(int argc , char *argv[] ) { unsigned char input[1] ; unsigned char output[1] ; int randomFuns_i5 ; unsigned char randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = (unsigned char )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 128) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } }
the_stack_data/198580452.c
/* Copyright 1991 Digital Equipment Corporation. ** All Rights Reserved. ** Last modified on Thu Feb 17 16:32:31 MET 1994 by rmeyer *****************************************************************/ /* $Id: xdisplaylist.c,v 1.2 1994/12/08 23:37:00 duchier Exp $ */ #ifndef lint static char vcid[] = "$Id: xdisplaylist.c,v 1.2 1994/12/08 23:37:00 duchier Exp $"; #endif /* lint */ #ifdef X11 #ifdef REV401PLUS #include "defs.h" #endif #ifdef REV102 #include <stdio.h> /* #include <malloc.h> 11.9 */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <limits.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include "extern.h" #include "xdisplaylist.h" /*****************************************/ #endif typedef struct wl_Line { Action action; ListLinks links; int x0, y0, x1, y1; long function; long color; long linewidth; } Line; typedef struct wl_Rectangle { Action action; ListLinks links; int x, y, width, height; long function; long color; long linewidth; } Rectangle; typedef struct wl_Arc { Action action; ListLinks links; int x, y, width, height, startangle, arcangle; long function; long color; long linewidth; } Arc; typedef struct wl_String { Action action; ListLinks links; int x, y; char *str; long function; long color; long font; } String; typedef struct wl_GraphicClosure { Display *display; Drawable drawable; GC gc; } GraphicClosure; typedef struct wl_PostScriptClosure { long display; Drawable window; long f; long height; } PostScriptClosure; typedef struct wl_Polygon { Action action; ListLinks links; XPoint *points; long npoints; long function; long color; long linewidth; } Polygon; typedef union wl_DisplayElt { Action action; Line line; Rectangle rectangle; Arc arc; String str; Polygon polygon; } DisplayElt; typedef DisplayElt *RefDisplayElt; /*****************************************/ static ListLinks *x_get_links_of_display_list (elt) DisplayElt *elt; { return &((Line *) elt)->links; } ListHeader * x_display_list () { ListHeader *display_list; display_list = (ListHeader *) malloc (sizeof (ListHeader)); List_SetLinkProc (display_list, x_get_links_of_display_list); return display_list; } /*****************************************/ void x_set_gc (display, gc, function, color, linewidth, font) Display *display; GC gc; long function; unsigned long color; long linewidth; Font font; { XGCValues gcvalues; unsigned long valuemask; gcvalues.function = function; gcvalues.foreground = color; valuemask = GCFunction | GCForeground; if (linewidth != xDefaultLineWidth) { gcvalues.line_width = linewidth; valuemask |= GCLineWidth; } if (font != xDefaultFont) { gcvalues.font = font; valuemask |= GCFont; } XChangeGC (display, gc, valuemask, &gcvalues); } /*****************************************/ #define AllocDisplayElt() malloc (sizeof (DisplayElt)) #define FreeDisplayElt(E) free (E) void x_record_line (displaylist, action, x0, y0, x1, y1, function, color, linewidth) ListHeader *displaylist; Action action; long x0, y0, x1, y1; unsigned long function, color, linewidth; { Line * elt; elt = (Line *) AllocDisplayElt (); elt->action = action; elt->x0 = x0; elt->y0 = y0; elt->x1 = x1; elt->y1 = y1; elt->function = function; elt->color = color; elt->linewidth = linewidth; List_Append (displaylist, (Ref) elt); } /*****************************************/ void x_record_arc (displaylist, action, x, y, width, height, startangle, arcangle, function, color, linewidth) ListHeader *displaylist; Action action; long x, y, width, height, startangle, arcangle; unsigned long function, color, linewidth; { Arc * elt; elt = (Arc *) AllocDisplayElt (); elt->action = action; elt->x = x; elt->y = y; elt->width = width; elt->height = height; elt->startangle = startangle; elt->arcangle = arcangle; elt->function = function; elt->color = color; elt->linewidth = linewidth; List_Append (displaylist, (Ref) elt); } /*****************************************/ void x_record_rectangle (displaylist, action, x, y, width, height, function, color, linewidth) ListHeader *displaylist; Action action; long x, y, width, height; unsigned long function, color, linewidth; { Rectangle * elt; elt = (Rectangle *) AllocDisplayElt (); elt->action = action; elt->x = x; elt->y = y; elt->width = width; elt->height = height; elt->function = function; elt->color = color; elt->linewidth = linewidth; List_Append (displaylist, (Ref) elt); } /*****************************************/ void x_record_polygon (displaylist, action, points, npoints, function, color, linewidth) ListHeader *displaylist; Action action; XPoint *points; long npoints; unsigned long function, color, linewidth; { Polygon * elt; XPoint *p; elt = (Polygon *) AllocDisplayElt (); elt->action = action; elt->npoints = npoints; elt->points = p = (XPoint *) malloc (npoints*2*sizeof(short)); for (; npoints > 0; npoints--, p++, points++) *p = *points; elt->function = function; elt->color = color; elt->linewidth = linewidth; List_Append (displaylist, (Ref) elt); } /*****************************************/ void x_record_string (displaylist, action, x, y, str, font, function, color) ListHeader *displaylist; Action action; long x, y; Font font; // REV401PLUS changed from long char *str; unsigned long function, color; { String * elt; elt = (String *) AllocDisplayElt (); elt->action = action; elt->x = x; elt->y = y; elt->str = (char *) malloc (strlen (str)+1); /* 11.9 */ strcpy (elt->str, str); *(elt->str+strlen(str)) = '\0'; elt->function = function; elt->color = color; elt->font = font; List_Append (displaylist, (Ref) elt); } /*****************************************/ static long x_draw_elt (elt, g) DisplayElt *elt; GraphicClosure *g; { Line *line; Arc *arc; Rectangle *rectangle; String *s; Polygon *polygon; switch (elt->action) { case DRAW_LINE: line = (Line *) elt; x_set_gc (g->display, g->gc, line->function, line->color, line->linewidth, xDefaultFont); XDrawLine (g->display, g->drawable, g->gc, line->x0, line->y0, line->x1, line->y1); break; case DRAW_ARC: case FILL_ARC: arc = (Arc *) elt; x_set_gc (g->display, g->gc, arc->function, arc->color, arc->linewidth, xDefaultFont); if (arc->action == DRAW_ARC) XDrawArc (g->display, g->drawable, g->gc, arc->x, arc->y, arc->width, arc->height, arc->startangle, arc->arcangle); else XFillArc (g->display, g->drawable, g->gc, arc->x, arc->y, arc->width, arc->height, arc->startangle, arc->arcangle); break; case DRAW_RECTANGLE: case FILL_RECTANGLE: rectangle = (Rectangle *) elt; x_set_gc (g->display, g->gc, rectangle->function, rectangle->color, rectangle->linewidth, xDefaultFont); if (rectangle->action == DRAW_RECTANGLE) XDrawRectangle (g->display, g->drawable, g->gc, rectangle->x, rectangle->y, rectangle->width, rectangle->height); else XFillRectangle (g->display, g->drawable, g->gc, rectangle->x, rectangle->y, rectangle->width, rectangle->height); break; case DRAW_STRING: case DRAW_IMAGE_STRING: s = (String *) elt; x_set_gc (g->display, g->gc, s->function, s->color, xDefaultLineWidth, s->font); if (s->action == DRAW_STRING) XDrawString (g->display, g->drawable, g->gc, s->x, s->y, s->str, strlen (s->str)); else XDrawImageString (g->display, g->drawable, g->gc, s->x, s->y, s->str, strlen (s->str)); break; case DRAW_POLYGON: case FILL_POLYGON: polygon = (Polygon *) elt; x_set_gc (g->display, g->gc, polygon->function, polygon->color, polygon->linewidth, xDefaultFont); if (polygon->action == FILL_POLYGON) XFillPolygon (g->display, g->drawable, g->gc, polygon->points, polygon->npoints, Complex, CoordModeOrigin); else XDrawLines (g->display, g->drawable, g->gc, polygon->points, polygon->npoints, CoordModeOrigin); break; } return TRUE; } /*****************************************/ /* note if we have not been able to create a pixmap for the window, then the pixmap is the window itself, and the pixmapgc is the gc of the window. - jch - Thu Aug 6 16:58:22 MET DST 1992 */ void x_refresh_window (display, window, pixmap, pixmapgc, displaylist) Display *display; Window window; Pixmap pixmap; GC pixmapgc; ListHeader *displaylist; { XWindowAttributes attr; GraphicClosure g; /* disable the GraphicsExpose emitted by XCopyArea */ XSetGraphicsExposures (display, pixmapgc, False); /* get the geometry of the window */ XGetWindowAttributes (display, window, &attr); #if 0 /* does not work with a pixmap, only with windows !! @#@^&%#(*&! - jch */ XClearArea (display, pixmap, 0, 0, attr.width, attr.height, False); #endif x_set_gc (display, pixmapgc, GXcopy, attr.backing_pixel, xDefaultLineWidth, xDefaultFont); XFillRectangle (display, pixmap, pixmapgc, 0, 0, attr.width, attr.height); g.display = display; g.drawable = pixmap; g.gc = pixmapgc; List_Enum (displaylist, x_draw_elt, &g); if (window != pixmap) XCopyArea (display, pixmap, window, pixmapgc, 0, 0, attr.width, attr.height, 0, 0); XSync (display, 0); } /*****************************************/ static long x_free_elt (elt, closure) DisplayElt *elt; long *closure; { Line *line; Arc *arc; Rectangle *rectangle; String *s; Polygon *polygon; /* free the attributes of the element */ switch (elt->action) { case DRAW_LINE: /* no attribute to free ? */ break; case DRAW_ARC: case FILL_ARC: /* no attribute to free ? */ break; case DRAW_RECTANGLE: case FILL_RECTANGLE: /* no attribute to free ? */ break; case DRAW_STRING: case DRAW_IMAGE_STRING: s = (String *) elt; free (s->str); break; case DRAW_POLYGON: case FILL_POLYGON: polygon = (Polygon *) elt; free (polygon->points); break; } /* finaly, free the element itself */ FreeDisplayElt (elt); return TRUE; } /*****************************************/ void x_free_display_list (displaylist) ListHeader *displaylist; { List_Enum (displaylist, x_free_elt, NULL); } /*****************************************/ static char *prolog[] = { "%!PS-Adobe-2.0\n", "/mt {moveto} def /lt {lineto} def /slw {setlinewidth} def\n", "/np {newpath} def /st {stroke} def /fi {fill} def /cp {closepath} def\n", "1 setlinecap 1 setlinejoin\n", "/line {/lw exch def /b exch def /g exch def /r exch def\n", " /y1 exch def /x1 exch def \n", " /y0 exch def /x0 exch def\n", " r 65535 div g 65535 div b 65535 div setrgbcolor\n", " np lw slw x0 y0 mt x1 y1 lt st} def\n", "/rect {/sf exch def /lw exch def\n", " /b exch def /g exch def /r exch def\n", " /h exch def /w exch def \n", " /y exch def /x exch def\n", " r 65535 div g 65535 div b 65535 div setrgbcolor\n", " np lw slw x y mt x w add y lt x w add y h sub lt\n", " x y h sub lt cp sf {st} {fi} ifelse} def\n", "/earcdict 100 dict def\n", /* see cookbook ex #3 */ "earcdict /mtrx matrix put\n", "/earc {earcdict begin\n", " /sf exch def /lw exch def\n", " /b exch def /g exch def /r exch def\n", " r 65535 div g 65535 div b 65535 div setrgbcolor\n", " /ea exch def /sa exch def\n", " /yr exch def /xr exch def /y exch def /x exch def\n", " /savematrix mtrx currentmatrix def\n", " np x y translate xr yr scale 0 0 1 sa ea arc\n", " savematrix setmatrix lw slw sf {st} {fi} ifelse\n", " end} def\n", "/Helvetica findfont 18 scalefont setfont\n", "/dstr {/sf exch def\n", " /b exch def /g exch def /r exch def\n", " /str exch def /y exch def /x exch def\n", " r 65535 div g 65535 div b 65535 div setrgbcolor\n", " x y mt str show} def\n", 0 }; static void x_postscript_prolog (f) long f; { long i; for (i = 0; prolog[i] != 0; i++) write (f, prolog[i], strlen (prolog[i])); } /*****************************************/ #define BUF_SIZE 512 static char nstr[BUF_SIZE]; static char *add_number (buf, n) char *buf; long n; { long m, i; char *s; for (m=n, i=1; m>=10; i++) m /= 10; if (i < BUF_SIZE && strlen (buf) + i < BUF_SIZE) { sprintf (nstr, "%ld ", n); strcat (buf, nstr); } return buf; } static char *add_string (buf, s) char *buf, *s; { if (strlen (buf) + strlen(s) < BUF_SIZE) strcat (buf, s); return buf; } static void x_get_rgb_values (display, window, color, rgb) Display *display; Window window; unsigned long color; XColor *rgb; { XWindowAttributes windowAttributes; XGetWindowAttributes (display, window, &windowAttributes); rgb->pixel = color; XQueryColor (display, windowAttributes.colormap, rgb); } static long x_postscript_elt (elt, psc) DisplayElt *elt; PostScriptClosure *psc; { Line *line; Arc *arc; Rectangle *rectangle; String *s; Polygon *polygon; char buf[BUF_SIZE]; char *pbuf; XPoint *p; XColor color; long i; buf[0] = 0; pbuf = buf; switch (elt->action) { case DRAW_LINE: line = (Line *) elt; pbuf = add_number (pbuf, line->x0); pbuf = add_number (pbuf, psc->height - line->y0); pbuf = add_number (pbuf, line->x1); pbuf = add_number (pbuf, psc->height - line->y1); x_get_rgb_values (psc->display, psc->window, line->color, &color); pbuf = add_number (pbuf, color.red); pbuf = add_number (pbuf, color.green); pbuf = add_number (pbuf, color.blue); pbuf = add_number (pbuf, line->linewidth); pbuf = add_string (pbuf, "line\n"); write (psc->f, pbuf, strlen (pbuf)); break; case DRAW_RECTANGLE: case FILL_RECTANGLE: rectangle = (Rectangle *) elt; pbuf = add_number (pbuf, rectangle->x); pbuf = add_number (pbuf, psc->height - rectangle->y); pbuf = add_number (pbuf, rectangle->width); pbuf = add_number (pbuf, rectangle->height); x_get_rgb_values (psc->display, psc->window, rectangle->color, &color); pbuf = add_number (pbuf, color.red); pbuf = add_number (pbuf, color.green); pbuf = add_number (pbuf, color.blue); if (rectangle->action == DRAW_RECTANGLE) { pbuf = add_number (pbuf, rectangle->linewidth); pbuf = add_string (pbuf, "true "); } else { pbuf = add_number (pbuf, 1); pbuf = add_string (pbuf, "false "); } pbuf = add_string (pbuf, "rect\n"); write (psc->f, pbuf, strlen (pbuf)); break; case DRAW_ARC: case FILL_ARC: arc = (Arc *) elt; pbuf = add_number (pbuf, arc->x+arc->width/2); pbuf = add_number (pbuf, psc->height - (arc->y+arc->height/2)); pbuf = add_number (pbuf, arc->width/2); pbuf = add_number (pbuf, arc->height/2); pbuf = add_number (pbuf, arc->startangle); pbuf = add_number (pbuf, (arc->startangle+arc->arcangle)/64); x_get_rgb_values (psc->display, psc->window, arc->color, &color); pbuf = add_number (pbuf, color.red); pbuf = add_number (pbuf, color.green); pbuf = add_number (pbuf, color.blue); if (arc->action == DRAW_ARC) { pbuf = add_number (pbuf, arc->linewidth); pbuf = add_string (pbuf, "true "); } else { pbuf = add_number (pbuf, 1); pbuf = add_string (pbuf, "false "); } pbuf = add_string (pbuf, "earc\n"); write (psc->f, pbuf, strlen (pbuf)); break; case DRAW_STRING: case DRAW_IMAGE_STRING: s = (String *) elt; pbuf = add_number (pbuf, s->x); pbuf = add_number (pbuf, psc->height - s->y); pbuf = add_string (pbuf, "("); pbuf = add_string (pbuf, s->str); pbuf = add_string (pbuf, ") "); x_get_rgb_values (psc->display, psc->window, s->color, &color); pbuf = add_number (pbuf, color.red); pbuf = add_number (pbuf, color.green); pbuf = add_number (pbuf, color.blue); if (s->action == DRAW_STRING) pbuf = add_string (pbuf, "true "); else pbuf = add_string (pbuf, "false "); pbuf = add_string (pbuf, "dstr\n"); write (psc->f, pbuf, strlen (pbuf)); break; case FILL_POLYGON: polygon = (Polygon *) elt; x_get_rgb_values (psc->display, psc->window, polygon->color, &color); pbuf = add_number (pbuf, color.red); pbuf = add_string (pbuf, "65535 div "); pbuf = add_number (pbuf, color.green); pbuf = add_string (pbuf, "65535 div "); pbuf = add_number (pbuf, color.blue); pbuf = add_string (pbuf, "65535 div "); pbuf = add_string (pbuf, "setrgbcolor "); p = polygon->points; pbuf = add_string (pbuf, "np "); pbuf = add_number (pbuf, p->x); pbuf = add_number (pbuf, psc->height - p->y); pbuf = add_string (pbuf, "mt\n"); ++p; for (i=1; i<polygon->npoints; i++, p++) { pbuf = add_number (pbuf, p->x); pbuf = add_number (pbuf, psc->height - p->y); pbuf = add_string (pbuf, "lt "); if (i%4==0) pbuf = add_string (pbuf, "\n"); } pbuf = add_string (pbuf, "cp fi\n"); write (psc->f, pbuf, strlen (pbuf)); break; } return TRUE; } /*****************************************/ long x_postscript_window (display, window, displaylist, filename) Display *display; Window window; ListHeader *displaylist; char *filename; { XWindowAttributes windowAttributes; PostScriptClosure psc; psc.display =(long)display; psc.window = window; if ((psc.f = open (filename, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR|S_IRWXG)) == -1) { Errorline ("\n*** Error: cannot open file %s.\n", filename); return FALSE; } XGetWindowAttributes (display, window, &windowAttributes); psc.height = windowAttributes.height; x_postscript_prolog (psc.f); List_Enum (displaylist, x_postscript_elt, &psc); write (psc.f, "showpage\n", strlen ("showpage\n")); close (psc.f); return TRUE; } /*****************************************/ #endif
the_stack_data/182953629.c
#include <stdio.h> int main(void){ float rate = 0, price = 0, cost = 0, commission = 0; printf("\nEnter The Rate: "); scanf("%f", &rate); printf("\n Enter the Cost: "); scanf("%f", &cost); printf("\n Enter the Price "); scanf("%f", &price); commission = rate * (price - cost); printf("\nCommission is = %.6f", commission); return 0; }
the_stack_data/783910.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <semaphore.h> #include <fcntl.h> #include <sys/mman.h> #define N 10 int * countdown; int * process_counter; int * shutdown; //mutex per regolare accesso concorrente alle variabili sem_t * count_mutex; void child_process(); int main() { int res; countdown = mmap(NULL, sizeof(int)*(N+2) + sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); if (countdown == MAP_FAILED) { perror("mmap()"); exit(EXIT_FAILURE); } process_counter = &countdown[1]; shutdown = &process_counter[N]; count_mutex = (sem_t *)(&shutdown[1]); *countdown = 0; *shutdown = 0; res = sem_init(count_mutex, 1, // 1 => il semaforo è condiviso tra processi, // 0 => il semaforo è condiviso tra threads del processo 1 // valore iniziale del semaforo (se mettiamo 0 che succede?) ); if(res==-1){ perror("sem_init"); exit(EXIT_FAILURE); } for(int i =0; i<N; i++){ switch(fork()){ case 0: child_process(i); break; case -1: perror("fork"); exit(EXIT_FAILURE); break; default: ; } } printf("ora dormo 1 sec\n"); //dopo avere avviato i processi figli, il processo padre dorme 1 secondo //e poi imposta il valore di countdown al valore 100000. sleep(1); printf("setto countdown\n"); if (sem_wait(count_mutex) == -1) { perror("sem_wait"); exit(EXIT_FAILURE); } *countdown = 100000; if (sem_post(count_mutex) == -1) { perror("sem_post"); exit(EXIT_FAILURE); } int countdown_copy=-1; while(countdown_copy != 0){ if (sem_wait(count_mutex) == -1) { perror("sem_wait"); exit(EXIT_FAILURE); } countdown_copy = *countdown; if(countdown_copy == 0){ *shutdown=1; } if (sem_post(count_mutex) == -1) { perror("sem_post"); exit(EXIT_FAILURE); } } for(int j=0; j<N; j++){ if(wait(NULL) == -1){ perror("wait()"); exit(EXIT_FAILURE); } } for(int k=0; k<N; k++){ printf("process_counter[%d] = %d\n", k, process_counter[k]); } return 0; } void child_process(int i){ int shut_copy=0; while(shut_copy == 0){ if (sem_wait(count_mutex) == -1) { perror("sem_wait"); exit(EXIT_FAILURE); } if(*countdown > 0){ (*countdown)--; //printf("countdown : %d\n", *countdown); process_counter[i]++; } shut_copy = *shutdown; if (sem_post(count_mutex) == -1) { perror("sem_post"); exit(EXIT_FAILURE); } } exit(EXIT_SUCCESS); }
the_stack_data/55893.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) */ /* > \brief <b> SPPSV computes the solution to system of linear equations A * X = B for OTHER matrices</b> */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download SPPSV + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/sppsv.f "> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/sppsv.f "> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/sppsv.f "> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE SPPSV( UPLO, N, NRHS, AP, B, LDB, INFO ) */ /* CHARACTER UPLO */ /* INTEGER INFO, LDB, N, NRHS */ /* REAL AP( * ), B( LDB, * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > SPPSV computes the solution to a real system of linear equations */ /* > A * X = B, */ /* > where A is an N-by-N symmetric positive definite matrix stored in */ /* > packed format and X and B are N-by-NRHS matrices. */ /* > */ /* > The Cholesky decomposition is used to factor A as */ /* > A = U**T* U, if UPLO = 'U', or */ /* > A = L * L**T, if UPLO = 'L', */ /* > where U is an upper triangular matrix and L is a lower triangular */ /* > matrix. The factored form of A is then used to solve the system of */ /* > equations A * X = B. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] UPLO */ /* > \verbatim */ /* > UPLO is CHARACTER*1 */ /* > = 'U': Upper triangle of A is stored; */ /* > = 'L': Lower triangle of A is stored. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The number of linear equations, i.e., the order of the */ /* > matrix A. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] NRHS */ /* > \verbatim */ /* > NRHS is INTEGER */ /* > The number of right hand sides, i.e., the number of columns */ /* > of the matrix B. NRHS >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in,out] AP */ /* > \verbatim */ /* > AP is REAL array, dimension (N*(N+1)/2) */ /* > On entry, the upper or lower triangle of the symmetric matrix */ /* > A, packed columnwise in a linear array. The j-th column of A */ /* > is stored in the array AP as follows: */ /* > if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j; */ /* > if UPLO = 'L', AP(i + (j-1)*(2n-j)/2) = A(i,j) for j<=i<=n. */ /* > See below for further details. */ /* > */ /* > On exit, if INFO = 0, the factor U or L from the Cholesky */ /* > factorization A = U**T*U or A = L*L**T, in the same storage */ /* > format as A. */ /* > \endverbatim */ /* > */ /* > \param[in,out] B */ /* > \verbatim */ /* > B is REAL array, dimension (LDB,NRHS) */ /* > On entry, the N-by-NRHS right hand side matrix B. */ /* > On exit, if INFO = 0, the N-by-NRHS solution matrix X. */ /* > \endverbatim */ /* > */ /* > \param[in] LDB */ /* > \verbatim */ /* > LDB is INTEGER */ /* > The leading dimension of the array B. LDB >= f2cmax(1,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: if INFO = i, the leading minor of order i of A is not */ /* > positive definite, so the factorization could not be */ /* > completed, and the solution has not been computed. */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date December 2016 */ /* > \ingroup realOTHERsolve */ /* > \par Further Details: */ /* ===================== */ /* > */ /* > \verbatim */ /* > */ /* > The packed storage scheme is illustrated by the following example */ /* > when N = 4, UPLO = 'U': */ /* > */ /* > Two-dimensional storage of the symmetric matrix A: */ /* > */ /* > a11 a12 a13 a14 */ /* > a22 a23 a24 */ /* > a33 a34 (aij = conjg(aji)) */ /* > a44 */ /* > */ /* > Packed storage of the upper triangle of A: */ /* > */ /* > AP = [ a11, a12, a22, a13, a23, a33, a14, a24, a34, a44 ] */ /* > \endverbatim */ /* > */ /* ===================================================================== */ /* Subroutine */ int sppsv_(char *uplo, integer *n, integer *nrhs, real *ap, real *b, integer *ldb, integer *info) { /* System generated locals */ integer b_dim1, b_offset, i__1; /* Local variables */ extern logical lsame_(char *, char *); extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen), spptrf_( char *, integer *, real *, integer *), spptrs_(char *, integer *, integer *, real *, real *, integer *, integer *); /* -- 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..-- */ /* December 2016 */ /* ===================================================================== */ /* Test the input parameters. */ /* Parameter adjustments */ --ap; b_dim1 = *ldb; b_offset = 1 + b_dim1 * 1; b -= b_offset; /* Function Body */ *info = 0; if (! lsame_(uplo, "U") && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*nrhs < 0) { *info = -3; } else if (*ldb < f2cmax(1,*n)) { *info = -6; } if (*info != 0) { i__1 = -(*info); xerbla_("SPPSV ", &i__1, (ftnlen)6); return 0; } /* Compute the Cholesky factorization A = U**T*U or A = L*L**T. */ spptrf_(uplo, n, &ap[1], info); if (*info == 0) { /* Solve the system A*X = B, overwriting B with X. */ spptrs_(uplo, n, nrhs, &ap[1], &b[b_offset], ldb, info); } return 0; /* End of SPPSV */ } /* sppsv_ */
the_stack_data/98576292.c
/* $Id: db_elf.c,v 1.4 1998/10/09 23:32:03 peter Exp $ */ /* $NetBSD: db_elf.c,v 1.4 1998/05/03 18:49:54 thorpej Exp $ */ /*- * Copyright (c) 1997 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility, * NASA Ames Research Center. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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. */ #if defined(__ELF__) && defined(__alpha__) #include "opt_ddb.h" #include <sys/types.h> #include <sys/param.h> #include <sys/systm.h> #include <sys/proc.h> #include <machine/db_machdep.h> #include <ddb/db_sym.h> #include <ddb/db_output.h> #include <machine/elf.h> static char *db_elf_find_strtab __P((db_symtab_t *)); #define STAB_TO_SYMSTART(stab) ((Elf_Sym *)((stab)->start)) #define STAB_TO_SYMEND(stab) ((Elf_Sym *)((stab)->end)) #define STAB_TO_EHDR(stab) ((Elf_Ehdr *)((stab)->private)) #define STAB_TO_SHDR(stab, e) ((Elf_Shdr *)((stab)->private + (e)->e_shoff)) void X_db_sym_init(void *symtab, void *esymtab, char *name); /* * Find the symbol table and strings; tell ddb about them. */ void X_db_sym_init(symtab, esymtab, name) void *symtab; /* pointer to start of symbol table */ void *esymtab; /* pointer to end of string table, for checking - rounded up to integer boundary */ char *name; { Elf_Ehdr *elf; Elf_Shdr *shp; Elf_Sym *symp, *symtab_start, *symtab_end; char *strtab_start, *strtab_end; int i; if (ALIGNED_POINTER(symtab, long) == 0) { printf("DDB: bad symbol table start address %p\n", symtab); return; } symtab_start = symtab_end = NULL; strtab_start = strtab_end = NULL; /* * The format of the symbols loaded by the boot program is: * * Elf exec header * first section header * . . . * . . . * last section header * first symbol or string table section * . . . * . . . * last symbol or string table section */ /* * Validate the Elf header. */ elf = (Elf_Ehdr *)symtab; if (elf->e_ident[EI_MAG0] != ELFMAG0 || elf->e_ident[EI_MAG1] != ELFMAG1 || elf->e_ident[EI_MAG2] != ELFMAG2 || elf->e_ident[EI_MAG3] != ELFMAG3) goto badheader; if (!ELF_MACHINE_OK(elf->e_machine)) goto badheader; /* * We need to avoid the section header string table (small string * table which names the sections). We do this by assuming that * the following two conditions will be true: * * (1) .shstrtab will be smaller than one page. * (2) .strtab will be larger than one page. * * When we encounter what we think is the .shstrtab, we change * its section type Elf_sht_null so that it will be ignored * later. */ shp = (Elf_Shdr *)((char*)symtab + elf->e_shoff); for (i = 0; i < elf->e_shnum; i++) { if (shp[i].sh_addr || i == elf->e_shstrndx) continue; switch (shp[i].sh_type) { case SHT_STRTAB: if (shp[i].sh_size < PAGE_SIZE) { shp[i].sh_type = SHT_NULL; continue; } if (strtab_start != NULL) goto multiple_strtab; strtab_start = (char *)symtab + shp[i].sh_offset; strtab_end = (char *)symtab + shp[i].sh_offset + shp[i].sh_size; break; case SHT_SYMTAB: if (symtab_start != NULL) goto multiple_symtab; symtab_start = (Elf_Sym *)((char*)symtab + shp[i].sh_offset); symtab_end = (Elf_Sym *)((char*)symtab + shp[i].sh_offset + shp[i].sh_size); break; default: /* Ignore all other sections. */ break; } } /* * Now, sanity check the symbols against the string table. */ if (symtab_start == NULL || strtab_start == NULL || ALIGNED_POINTER(symtab_start, long) == 0 || ALIGNED_POINTER(strtab_start, long) == 0) goto badheader; for (symp = symtab_start; symp < symtab_end; symp++) if (symp->st_name + strtab_start > strtab_end) goto badheader; /* * Link the symbol table into the debugger. */ db_add_symbol_table((char *)symtab_start, (char *)symtab_end, name, (char *)symtab); printf("[ preserving %lu bytes of %s symbol table ]\n", (u_long)roundup(((char*)esymtab - (char*)symtab), sizeof(u_long)), name); return; badheader: printf("[ %s symbol table not valid ]\n", name); return; multiple_strtab: printf("[ %s has multiple string tables ]\n", name); return; multiple_symtab: printf("[ %s has multiple symbol tables ]\n", name); return; } /* * Internal helper function - return a pointer to the string table * for the current symbol table. */ static char * db_elf_find_strtab(stab) db_symtab_t *stab; { Elf_Ehdr *elf = STAB_TO_EHDR(stab); Elf_Shdr *shp = STAB_TO_SHDR(stab, elf); int i; for (i = 0; i < elf->e_shnum; i++) { if (shp[i].sh_type == SHT_STRTAB && !shp[i].sh_addr && i != elf->e_shstrndx) return (stab->private + shp[i].sh_offset); } return (NULL); } /* * Lookup the symbol with the given name. */ db_sym_t X_db_lookup(stab, symstr) db_symtab_t *stab; char *symstr; { Elf_Sym *symp, *symtab_start, *symtab_end; char *strtab; symtab_start = STAB_TO_SYMSTART(stab); symtab_end = STAB_TO_SYMEND(stab); strtab = db_elf_find_strtab(stab); if (strtab == NULL) return ((db_sym_t)0); for (symp = symtab_start; symp < symtab_end; symp++) { if (symp->st_name != 0 && db_eqname(strtab + symp->st_name, symstr, 0)) return ((db_sym_t)symp); } return ((db_sym_t)0); } /* * Search for the symbol with the given address (matching within the * provided threshold). */ db_sym_t X_db_search_symbol(symtab, off, strategy, diffp) db_symtab_t *symtab; db_addr_t off; db_strategy_t strategy; db_expr_t *diffp; /* in/out */ { Elf_Sym *rsymp, *symp, *symtab_start, *symtab_end; db_expr_t diff = *diffp; symtab_start = STAB_TO_SYMSTART(symtab); symtab_end = STAB_TO_SYMEND(symtab); rsymp = NULL; for (symp = symtab_start; symp < symtab_end; symp++) { if (symp->st_name == 0) continue; if (ELF_ST_TYPE(symp->st_info) != STT_OBJECT && ELF_ST_TYPE(symp->st_info) != STT_FUNC) continue; if (off >= symp->st_value) { if ((off - symp->st_value) < diff) { diff = off - symp->st_value; rsymp = symp; if (diff == 0) { if (strategy == DB_STGY_PROC && ELF_ST_TYPE(symp->st_info) == STT_FUNC && ELF_ST_BIND(symp->st_info) != STB_LOCAL) break; if (strategy == DB_STGY_ANY && ELF_ST_BIND(symp->st_info) != STB_LOCAL) break; } } else if ((off - symp->st_value) == diff) { if (rsymp == NULL) rsymp = symp; else if (ELF_ST_BIND(rsymp->st_info) == STB_LOCAL && ELF_ST_BIND(symp->st_info) != STB_LOCAL) { /* pick the external symbol */ rsymp = symp; } } } } if (rsymp == NULL) *diffp = off; else *diffp = diff; return ((db_sym_t)rsymp); } /* * Return the name and value for a symbol. */ void X_db_symbol_values(symtab, sym, namep, valuep) db_symtab_t *symtab; db_sym_t sym; char **namep; db_expr_t *valuep; { Elf_Sym *symp = (Elf_Sym *)sym; char *strtab; if (namep) { strtab = db_elf_find_strtab(symtab); if (strtab == NULL) *namep = NULL; else *namep = strtab + symp->st_name; } if (valuep) *valuep = symp->st_value; } /* * Return the file and line number of the current program counter * if we can find the appropriate debugging symbol. */ boolean_t X_db_line_at_pc(symtab, cursym, filename, linenum, off) db_symtab_t *symtab; db_sym_t cursym; char **filename; int *linenum; db_expr_t off; { /* * XXX We don't support this (yet). */ return (FALSE); } /* * Returns the number of arguments to a function and their * names if we can find the appropriate debugging symbol. */ boolean_t X_db_sym_numargs(symtab, cursym, nargp, argnamep) db_symtab_t *symtab; db_sym_t cursym; int *nargp; char **argnamep; { /* * XXX We don't support this (yet). */ return (FALSE); } /* * Initialization routine for Elf files. */ extern void *ksym_start, *ksym_end; void kdb_init(void) { if (ksym_end > ksym_start) X_db_sym_init(ksym_start, ksym_end, "kernel"); } #endif
the_stack_data/75139158.c
#include <stdio.h> #include <stdlib.h> int main() { int a[99][99], b[99][99], c[99][99], i, j, m, n; printf("Enter size for rows and columns\n"); scanf("%d %d", &m, &n); printf("Enter Matrix 1 Elements of %d x %d\n", m, n); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { scanf("%d", &a[i][j]); } } printf("Enter Matrix 2 Elements of %d x %d\n", m, n); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { scanf("%d", &b[i][j]); } } printf("Elements of Matrix 1\n"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { printf("%d\t", a[i][j]); } printf("\n"); } printf("Elements of Matrix 2\n"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { printf("%d\t", b[i][j]); } printf("\n"); } for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { c[i][j] = a[i][j] + b[i][j]; } } printf("Sum of Matrix 1 and Matrix 2\n"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { printf("%d\t", c[i][j]); } printf("\n"); } return 0; }
the_stack_data/135760.c
#if defined(BUILD_UMM_MALLOC_C) #ifdef UMM_INFO #include <stdint.h> #include <stddef.h> #include <stdbool.h> #include <math.h> /* ---------------------------------------------------------------------------- * One of the coolest things about this little library is that it's VERY * easy to get debug information about the memory heap by simply iterating * through all of the memory blocks. * * As you go through all the blocks, you can check to see if it's a free * block by looking at the high order bit of the next block index. You can * also see how big the block is by subtracting the next block index from * the current block number. * * The umm_info function does all of that and makes the results available * in the ummHeapInfo structure. * ---------------------------------------------------------------------------- */ // UMM_HEAP_INFO ummHeapInfo; void *umm_info( void *ptr, bool force ) { UMM_CRITICAL_DECL(id_info); UMM_INIT_HEAP; uint16_t blockNo = 0; /* Protect the critical section... */ UMM_CRITICAL_ENTRY(id_info); umm_heap_context_t *_context = umm_get_current_heap(); /* * Clear out all of the entries in the ummHeapInfo structure before doing * any calculations.. */ memset( &_context->info, 0, sizeof( _context->info ) ); DBGLOG_FORCE( force, "\n" ); DBGLOG_FORCE( force, "+----------+-------+--------+--------+-------+--------+--------+\n" ); DBGLOG_FORCE( force, "|0x%08lx|B %5d|NB %5d|PB %5d|Z %5d|NF %5d|PF %5d|\n", DBGLOG_32_BIT_PTR(&UMM_BLOCK(blockNo)), blockNo, UMM_NBLOCK(blockNo) & UMM_BLOCKNO_MASK, UMM_PBLOCK(blockNo), (UMM_NBLOCK(blockNo) & UMM_BLOCKNO_MASK )-blockNo, UMM_NFREE(blockNo), UMM_PFREE(blockNo) ); /* * Now loop through the block lists, and keep track of the number and size * of used and free blocks. The terminating condition is an nb pointer with * a value of zero... */ blockNo = UMM_NBLOCK(blockNo) & UMM_BLOCKNO_MASK; while( UMM_NBLOCK(blockNo) & UMM_BLOCKNO_MASK ) { size_t curBlocks = (UMM_NBLOCK(blockNo) & UMM_BLOCKNO_MASK )-blockNo; ++_context->info.totalEntries; _context->info.totalBlocks += curBlocks; /* Is this a free block? */ if( UMM_NBLOCK(blockNo) & UMM_FREELIST_MASK ) { ++_context->info.freeEntries; _context->info.freeBlocks += curBlocks; _context->info.freeBlocksSquared += (curBlocks * curBlocks); if (_context->info.maxFreeContiguousBlocks < curBlocks) { _context->info.maxFreeContiguousBlocks = curBlocks; } DBGLOG_FORCE( force, "|0x%08lx|B %5d|NB %5d|PB %5d|Z %5u|NF %5d|PF %5d|\n", DBGLOG_32_BIT_PTR(&UMM_BLOCK(blockNo)), blockNo, UMM_NBLOCK(blockNo) & UMM_BLOCKNO_MASK, UMM_PBLOCK(blockNo), (uint16_t)curBlocks, UMM_NFREE(blockNo), UMM_PFREE(blockNo) ); /* Does this block address match the ptr we may be trying to free? */ if( ptr == &UMM_BLOCK(blockNo) ) { /* Release the critical section... */ UMM_CRITICAL_EXIT(id_info); return( ptr ); } } else { ++_context->info.usedEntries; _context->info.usedBlocks += curBlocks; DBGLOG_FORCE( force, "|0x%08lx|B %5d|NB %5d|PB %5d|Z %5u|\n", DBGLOG_32_BIT_PTR(&UMM_BLOCK(blockNo)), blockNo, UMM_NBLOCK(blockNo) & UMM_BLOCKNO_MASK, UMM_PBLOCK(blockNo), (uint16_t)curBlocks ); } blockNo = UMM_NBLOCK(blockNo) & UMM_BLOCKNO_MASK; } /* * The very last block is used as a placeholder to indicate that * there are no more blocks in the heap, so it cannot be used * for anything - at the same time, the size of this block must * ALWAYS be exactly 1 ! */ DBGLOG_FORCE( force, "|0x%08lx|B %5d|NB %5d|PB %5d|Z %5d|NF %5d|PF %5d|\n", DBGLOG_32_BIT_PTR(&UMM_BLOCK(blockNo)), blockNo, UMM_NBLOCK(blockNo) & UMM_BLOCKNO_MASK, UMM_PBLOCK(blockNo), UMM_NUMBLOCKS-blockNo, UMM_NFREE(blockNo), UMM_PFREE(blockNo) ); DBGLOG_FORCE( force, "+----------+-------+--------+--------+-------+--------+--------+\n" ); DBGLOG_FORCE( force, "Total Entries %5d Used Entries %5d Free Entries %5d\n", _context->info.totalEntries, _context->info.usedEntries, _context->info.freeEntries ); DBGLOG_FORCE( force, "Total Blocks %5d Used Blocks %5d Free Blocks %5d\n", _context->info.totalBlocks, _context->info.usedBlocks, _context->info.freeBlocks ); DBGLOG_FORCE( force, "+--------------------------------------------------------------+\n" ); DBGLOG_FORCE( force, "Usage Metric: %5d\n", umm_usage_metric_core(_context)); DBGLOG_FORCE( force, "Fragmentation Metric: %5d\n", umm_fragmentation_metric_core(_context)); DBGLOG_FORCE( force, "+--------------------------------------------------------------+\n" ); #if defined(UMM_STATS) || defined(UMM_STATS_FULL) #if !defined(UMM_INLINE_METRICS) if (_context->info.freeBlocks == _context->stats.free_blocks) { DBGLOG_FORCE( force, "heap info Free blocks and heap statistics Free blocks match.\n"); } else { DBGLOG_FORCE( force, "\nheap info Free blocks %5d != heap statistics Free Blocks %5d\n\n", _context->info.freeBlocks, _context->stats.free_blocks ); } DBGLOG_FORCE( force, "+--------------------------------------------------------------+\n" ); #endif umm_print_stats(force); #endif /* Release the critical section... */ UMM_CRITICAL_EXIT(id_info); return( NULL ); } /* ------------------------------------------------------------------------ */ size_t umm_free_heap_size_core( umm_heap_context_t *_context ) { return (size_t)_context->info.freeBlocks * sizeof(umm_block); } size_t umm_free_heap_size( void ) { #ifndef UMM_INLINE_METRICS umm_info(NULL, false); #endif return umm_free_heap_size_core(umm_get_current_heap()); } //C Breaking change in upstream umm_max_block_size() was changed to //C umm_max_free_block_size() keeping old function name for (dot) releases. //C TODO: update at next major release. //C size_t umm_max_free_block_size( void ) { size_t umm_max_block_size_core( umm_heap_context_t *_context ) { return _context->info.maxFreeContiguousBlocks * sizeof(umm_block); } size_t umm_max_block_size( void ) { umm_info(NULL, false); return umm_max_block_size_core(umm_get_current_heap()); } /* Without build option UMM_INLINE_METRICS, calls to umm_usage_metric() or umm_fragmentation_metric() must to be preceeded by a call to umm_info(NULL, false) for updated results. */ int umm_usage_metric_core( umm_heap_context_t *_context ) { //C Note, umm_metrics also appears in the upstrean w/o definition. I suspect it is suppose to be ummHeapInfo. // DBGLOG_DEBUG( "usedBlocks %d totalBlocks %d\n", umm_metrics.usedBlocks, ummHeapInfo.totalBlocks); DBGLOG_DEBUG( "usedBlocks %d totalBlocks %d\n", _context->info.usedBlocks, _context->info.totalBlocks); if (_context->info.freeBlocks) return (int)((_context->info.usedBlocks * 100)/(_context->info.freeBlocks)); return -1; // no freeBlocks } int umm_usage_metric( void ) { #ifndef UMM_INLINE_METRICS umm_info(NULL, false); #endif return umm_usage_metric_core(umm_get_current_heap()); } uint32_t sqrt32 (uint32_t n); int umm_fragmentation_metric_core( umm_heap_context_t *_context ) { // DBGLOG_DEBUG( "freeBlocks %d freeBlocksSquared %d\n", umm_metrics.freeBlocks, ummHeapInfo.freeBlocksSquared); DBGLOG_DEBUG( "freeBlocks %d freeBlocksSquared %d\n", _context->info.freeBlocks, _context->info.freeBlocksSquared); if (0 == _context->info.freeBlocks) { return 0; } else { //upstream version: return (100 - (((uint32_t)(sqrtf(ummHeapInfo.freeBlocksSquared)) * 100)/(ummHeapInfo.freeBlocks))); return (100 - (((uint32_t)(sqrt32(_context->info.freeBlocksSquared)) * 100)/(_context->info.freeBlocks))); } } int umm_fragmentation_metric( void ) { #ifndef UMM_INLINE_METRICS umm_info(NULL, false); #endif return umm_fragmentation_metric_core(umm_get_current_heap()); } #ifdef UMM_INLINE_METRICS static void umm_fragmentation_metric_init( umm_heap_context_t *_context ) { _context->info.freeBlocks = UMM_NUMBLOCKS - 2; _context->info.freeBlocksSquared = _context->info.freeBlocks * _context->info.freeBlocks; } static void umm_fragmentation_metric_add( umm_heap_context_t *_context, uint16_t c ) { uint16_t blocks = (UMM_NBLOCK(c) & UMM_BLOCKNO_MASK) - c; DBGLOG_DEBUG( "Add block %d size %d to free metric\n", c, blocks); _context->info.freeBlocks += blocks; _context->info.freeBlocksSquared += (blocks * blocks); } static void umm_fragmentation_metric_remove( umm_heap_context_t *_context, uint16_t c ) { uint16_t blocks = (UMM_NBLOCK(c) & UMM_BLOCKNO_MASK) - c; DBGLOG_DEBUG( "Remove block %d size %d from free metric\n", c, blocks); _context->info.freeBlocks -= blocks; _context->info.freeBlocksSquared -= (blocks * blocks); } #endif // UMM_INLINE_METRICS /* ------------------------------------------------------------------------ */ #endif #endif // defined(BUILD_UMM_MALLOC_C)
the_stack_data/112026.c
#include "stdio.h" int main() { int n,s,q,i; float m; q=0; m=0; scanf("%d",&n); for(i= 0;i<n;++i) { scanf("%d",&s); q=q+s; m=(float)q/(i+1); } printf("Sum: %d\nAvg: %.2f",q,m); return 0; }
the_stack_data/967945.c
// ***************************************************************************************** // // File description: // // Author: Joao Costa // Purpose: Proc module using a Linux implementation // // ***************************************************************************************** // Only relevant is OS is Linux #ifdef OS_LINUX // ***************************************************************************************** // // Section: Import headers // // ***************************************************************************************** // Force baseline before system headers #include "general/general_baseline.h" // System includes <here> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <limits.h> // Generic OSAPI includes #include "general/general.h" #include "common/common.h" // Include own headers #include "error/modules/error_proc.h" #include "proc/linux/proc_linux_priv.h" // ***************************************************************************************** // // Section: Macros/Constant definitions // // ***************************************************************************************** extern const char * OSAPI_FS_PROC_NAME; const char * OSAPI_FS_PROC_STAT_FILENAME = "stat"; static const t_size OSAPI_FS_PROC_SIZE = 100; static const t_size OSAPI_FS_PROC_STAT_ENTRY_SIZE = PATH_MAX + 1000; // ***************************************************************************************** // // Section: Function definition // // ***************************************************************************************** t_status parse_linux_proc_stat_line( char * line, t_proc_info * p_proc_info ) { t_status st; char * token, * rest; status_reset( & st ); // Process line // 1. The process ID token = strtok_r( line, OSAPI_SPACE_STRING, &rest ); p_proc_info->id.pid = (t_pid) atoi( token ); // 2. The filename of the executable, in parentheses (if it contains spaces it prevents the usage of fscanf token = strtok_r( NULL, ")", &rest ); strncpy( p_proc_info->id.name, &token[1], 16 ); // Remove space in between ) and the next argument token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); // 3. Process state: RSDZTW if( token[0] != 'R' && token[0] != 'S' && token[0] != 'T' && token[0] != 'Z' && token[0] != 'D' && token[0] != 'W' && token[0] != 'I' && token[0] != 't' && token[0] != 'X' ) token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); p_proc_info->state = token[0]; // 4. The PID of the parent token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); p_proc_info->id.ppid = (t_pid) atoi( token ); // 5. The process group ID of the process token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); p_proc_info->id.pgrp = (t_pid) atoi( token ); // 6. The session ID of the process token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); p_proc_info->id.session = (t_pid) atoi( token ); // 7. The controlling terminal of the process token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); //p_proc_info->tty_nr = atoi( token ); // 8. The ID of the foreground process group of the controlling terminal of the process token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); p_proc_info->id.tpgid = atoi( token ); // 9. The kernel flags word of the process token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); // 10. The number of minor faults the process has made which have not required loading a memory page from disk token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); // 11. The number of minor faults that the process's waited-for children have made token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); // 12. The number of major faults the process has made which have required loading a memory page from disk token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); // 13. The number of major faults that the process's waited-for children have made token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); // 14. Amount of time that this process has been scheduled in user mode, measured in clock ticks token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); p_proc_info->resources.utime = (t_size) atol( token ); // 15. Amount of time that this process has been scheduled in kernel mode, measured in clock ticks token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); p_proc_info->resources.stime = (t_size) atol( token ); // 16. Amount of time that this process's waited-for children have been scheduled in user mode, measured in clock ticks token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); // 17. Amount of time that this process's waited-for children have been scheduled in kernel mode, measured in clock ticks token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); // 18. Scheduling priority or raw nice value token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); // 19. The nice value token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); // 20. Number of threads in this process token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); p_proc_info->resources.num_threads = (t_size) atol( token ); // 21. The time in jiffies before the next SIGALRM is sent to the process due to an interval timer token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); // 22. The time the process started after system boot. token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); p_proc_info->starttime = (uint64_t) atol( token ); // 23. Virtual memory size in bytes token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); p_proc_info->resources.vsize = (t_size) atol( token ); // 24. Resident Set Size: number of pages the process has in real memory token = strtok_r( NULL, OSAPI_SPACE_STRING, &rest ); p_proc_info->resources.ram = (t_size) atoi( token ); // 25. Current soft limit in bytes on the rss of the process // 26. The address above which program text can run // 27. The address below which program text can run // 28. The address of the start (i.e., bottom) of the stack // 29. The current value of ESP (stack pointer), as found in the kernel stack page for the process // 30. The current EIP (instruction pointer) // 31. The bitmap of pending signals, displayed as a decimal number. // 32. The bitmap of blocked signals, displayed as a decimal number. // 33. The bitmap of ignored signals, displayed as a decimal number. // 34. The bitmap of caught signals, displayed as a decimal number // 35. This is the "channel" in which the process is waiting // 36. Number of pages swapped (not maintained) // 37. Cumulative nswap for child processes (not maintained) or exit signal number (since Linux 2.1.22) // 38. Signal to be sent to parent when we die // 39. CPU number last executed on // 40. Real-time scheduling priority // 41. Scheduling policy // 42. Aggregated block I/O delays, measured in clock ticks // 43. Guest time of the process measured in clock ticks // 44. Guest time of the process's children, measured in clock ticks return st; } // Verify if there are empty spaces in the process name that prevents usage of fscanf bool has_linux_proc_stat_file_spaces( char * line ) { bool ret = false; char * begin, * end; char process_name [ NAME_MAX + 1 ]; begin = strstr( line, "(" ); if( begin != NULL ) { end = strstr( begin + 1, ") " ); if( end != NULL ) { // Make sure that size doesn't exceed the allocated buffer t_size sz = end - begin > NAME_MAX ? (t_size) NAME_MAX : (t_size) (end - begin -1); memset( process_name, '\0', sizeof( process_name ) ); strncpy( process_name, begin + 1, sz ); if( strstr( process_name, " " ) != NULL ) ret = true; } } return ret; } t_status proc_info_last_processing( t_proc_info * p_pinfo ) { t_status st; long sz; status_reset( & st ); sz = sysconf(_SC_PAGESIZE); // Size of memory pages in Linux if( sz > 0 ) p_pinfo->resources.ram = p_pinfo->resources.ram * (t_size) sz; sz = sysconf(_SC_CLK_TCK); // Number of clock ticks per second if( sz > 0 ) { p_pinfo->resources.utime = p_pinfo->resources.utime / (t_size) sz; p_pinfo->resources.stime = p_pinfo->resources.stime / (t_size) sz; p_pinfo->starttime = (uint64_t) ( p_pinfo->starttime / ((uint64_t) sz) ); } return st; } t_status choose_linux_proc_stat_decoder( FILE * fp, t_proc_info * p_pinfo ) { t_status st; char line [ OSAPI_FS_PROC_STAT_ENTRY_SIZE ]; /* int tty, flags; int cnswap, exit_signal, processor; int rt_priority, policy; long minflt, cminflt, majflt, cmajflt, cutime, cstime, priority, nice; unsigned long long itrealvalue, delayacct_blkio_ticks; unsigned long rsslim, startcode, endcode, startstack, kstkesp, kstkeip; unsigned long signal, blocked, sigignore, sigcatch, wchan, nswap, guest_time, cguest_time; */ status_reset( & st ); if( fp == (FILE *) 0 || p_pinfo == (t_proc_info *) 0 ) status_iset( OSAPI_MODULE_PROC, __func__, osapi_proc_error_params, &st ); else { if( fgets( line, (int) OSAPI_FS_PROC_STAT_ENTRY_SIZE, fp ) == NULL ) status_eset( OSAPI_MODULE_PROC, __func__, errno, &st ); else { // Does the process name contain spaces? if( has_linux_proc_stat_file_spaces( line ) ) st = parse_linux_proc_stat_line( line, p_pinfo ); else { rewind( fp ); // There are 44 arguments to be read from the file /* if( fscanf( fp, "%d %s %c %d %d %d %d %d %u %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %llu %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %d %d %d %u %u %llu %lu %ld", &(p_pinfo->id.pid), p_pinfo->id.name, &(p_pinfo->state), &(p_pinfo->id.ppid), &(p_pinfo->id.pgrp), &(p_pinfo->id.session), &tty, &(p_pinfo->id.tpgid), &flags, &minflt , &cminflt , &majflt, &cmajflt, &(p_pinfo->resources.utime), &(p_pinfo->resources.stime), &cutime, &cstime, &priority, &nice, &(p_pinfo->resources.num_threads), &itrealvalue, &(p_pinfo->starttime), &(p_pinfo->resources.vsize), &(p_pinfo->resources.ram), &rsslim, &startcode, &endcode, &startstack, &kstkesp, &kstkeip, &signal, &blocked, &sigignore, &sigcatch, &wchan, &nswap, &cnswap, &exit_signal, &processor, &rt_priority, &policy, &delayacct_blkio_ticks, &guest_time, &cguest_time ) != 44 ) */ // Arguments that are currently needed if( fscanf( fp, "%d %s %c %d %d %d %*d %d %*u %*u %*u %*u %*u %lu %lu %*d %*d %*d %*d %ld %lu %*u %ld %lu", &(p_pinfo->id.pid), p_pinfo->id.name, &(p_pinfo->state), &(p_pinfo->id.ppid), &(p_pinfo->id.pgrp), &(p_pinfo->id.session), &(p_pinfo->id.tpgid), &(p_pinfo->resources.utime), &(p_pinfo->resources.stime), &(p_pinfo->resources.num_threads), &(p_pinfo->starttime), &(p_pinfo->resources.vsize), &(p_pinfo->resources.ram) ) != 24 ) status_eset( OSAPI_MODULE_PROC, __func__, errno, &st ); } // Post-processing st = proc_info_last_processing( p_pinfo ); } } return st; } t_status parse_linux_proc_stat_file( t_pid pid, t_proc_info * p_proc_info ) { t_status st; FILE * p_status_file = NULL; char filename [ OSAPI_FS_PROC_SIZE + 1 ]; status_reset( & st ); snprintf( filename, OSAPI_FS_PROC_SIZE, "%s/%d/%s", OSAPI_FS_PROC_NAME, pid, OSAPI_FS_PROC_STAT_FILENAME ); filename[ OSAPI_FS_PROC_SIZE ] = '\0'; // Ensure that it's null terminated p_status_file = fopen( filename, "r" ); if( p_status_file == NULL ) status_eset( OSAPI_MODULE_PROC, __func__, errno, &st ); else st = choose_linux_proc_stat_decoder( p_status_file, p_proc_info ); return st; } #endif // End of OS Linux
the_stack_data/103266042.c
static int eqeq(int a, int b) { return (a == b) == (b == a); } static int nene(int a, int b) { return (a != b) == (b != a); } static int ltgt(int a, int b) { return (a < b) == (b > a); } static int lege(int a, int b) { return (a <= b) == (b >= a); } static int gele(int a, int b) { return (a >= b) == (b <= a); } static int gtlt(int a, int b) { return (a > b) == (b < a); } static int eneqne(int a, int b) { return (a == b) == !(b != a); } static int enneeq(int a, int b) { return (a != b) == !(b == a); } static int enltle(int a, int b) { return (a < b) == !(b <= a); } static int enlelt(int a, int b) { return (a <= b) == !(b < a); } static int engegt(int a, int b) { return (a >= b) == !(b > a); } static int engtge(int a, int b) { return (a > b) == !(b >= a); } static int neeqne(int a, int b) { return (a == b) != (b != a); } static int neneeq(int a, int b) { return (a != b) != (b == a); } static int neltle(int a, int b) { return (a < b) != (b <= a); } static int nelelt(int a, int b) { return (a <= b) != (b < a); } static int negegt(int a, int b) { return (a >= b) != (b > a); } static int negtge(int a, int b) { return (a > b) != (b >= a); } /* * check-name: cse-dual-compare * check-command: test-linearize $file * check-output-ignore * check-known-to-fail * * check-output-excludes: set[gl][et]\\. * check-output-excludes: seteq\\. * check-output-excludes: setne\\. */
the_stack_data/26699245.c
/* Copyright (c) 2009-2018 ARM Limited. All rights reserved. SPDX-License-Identifier: Apache-2.0 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 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. NOTICE: This file has been modified by Nordic Semiconductor ASA. */ /* NOTE: Template files (including this one) are application specific and therefore expected to be copied into the application project folder prior to its use! */ #ifdef NRF52840_XXAA #include <stdint.h> #include <stdbool.h> #include "nrf.h" #include "system_nrf52840.h" /*lint ++flb "Enter library region" */ #define __SYSTEM_CLOCK_64M (64000000UL) static bool errata_36(void); static bool errata_66(void); static bool errata_98(void); static bool errata_103(void); static bool errata_115(void); static bool errata_120(void); static bool errata_136(void); #if defined ( __CC_ARM ) uint32_t SystemCoreClock __attribute__((used)) = __SYSTEM_CLOCK_64M; #elif defined ( __ICCARM__ ) __root uint32_t SystemCoreClock = __SYSTEM_CLOCK_64M; #elif defined ( __GNUC__ ) uint32_t SystemCoreClock __attribute__((used)) = __SYSTEM_CLOCK_64M; #endif void SystemCoreClockUpdate(void) { SystemCoreClock = __SYSTEM_CLOCK_64M; } void SystemInit(void) { /* Enable SWO trace functionality. If ENABLE_SWO is not defined, SWO pin will be used as GPIO (see Product Specification to see which one). */ #if defined (ENABLE_SWO) CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; NRF_CLOCK->TRACECONFIG |= CLOCK_TRACECONFIG_TRACEMUX_Serial << CLOCK_TRACECONFIG_TRACEMUX_Pos; NRF_P1->PIN_CNF[0] = (GPIO_PIN_CNF_DRIVE_H0H1 << GPIO_PIN_CNF_DRIVE_Pos) | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos); #endif /* Enable Trace functionality. If ENABLE_TRACE is not defined, TRACE pins will be used as GPIOs (see Product Specification to see which ones). */ #if defined (ENABLE_TRACE) CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; NRF_CLOCK->TRACECONFIG |= CLOCK_TRACECONFIG_TRACEMUX_Parallel << CLOCK_TRACECONFIG_TRACEMUX_Pos; NRF_P0->PIN_CNF[7] = (GPIO_PIN_CNF_DRIVE_H0H1 << GPIO_PIN_CNF_DRIVE_Pos) | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos); NRF_P1->PIN_CNF[0] = (GPIO_PIN_CNF_DRIVE_H0H1 << GPIO_PIN_CNF_DRIVE_Pos) | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos); NRF_P0->PIN_CNF[12] = (GPIO_PIN_CNF_DRIVE_H0H1 << GPIO_PIN_CNF_DRIVE_Pos) | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos); NRF_P0->PIN_CNF[11] = (GPIO_PIN_CNF_DRIVE_H0H1 << GPIO_PIN_CNF_DRIVE_Pos) | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos); NRF_P1->PIN_CNF[9] = (GPIO_PIN_CNF_DRIVE_H0H1 << GPIO_PIN_CNF_DRIVE_Pos) | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos); #endif /* Workaround for Errata 36 "CLOCK: Some registers are not reset when expected" found at the Errata document for your device located at https://www.nordicsemi.com/DocLib */ if (errata_36()){ NRF_CLOCK->EVENTS_DONE = 0; NRF_CLOCK->EVENTS_CTTO = 0; NRF_CLOCK->CTIV = 0; } /* Workaround for Errata 66 "TEMP: Linearity specification not met with default settings" found at the Errata document for your device located at https://www.nordicsemi.com/DocLib */ if (errata_66()){ NRF_TEMP->A0 = NRF_FICR->TEMP.A0; NRF_TEMP->A1 = NRF_FICR->TEMP.A1; NRF_TEMP->A2 = NRF_FICR->TEMP.A2; NRF_TEMP->A3 = NRF_FICR->TEMP.A3; NRF_TEMP->A4 = NRF_FICR->TEMP.A4; NRF_TEMP->A5 = NRF_FICR->TEMP.A5; NRF_TEMP->B0 = NRF_FICR->TEMP.B0; NRF_TEMP->B1 = NRF_FICR->TEMP.B1; NRF_TEMP->B2 = NRF_FICR->TEMP.B2; NRF_TEMP->B3 = NRF_FICR->TEMP.B3; NRF_TEMP->B4 = NRF_FICR->TEMP.B4; NRF_TEMP->B5 = NRF_FICR->TEMP.B5; NRF_TEMP->T0 = NRF_FICR->TEMP.T0; NRF_TEMP->T1 = NRF_FICR->TEMP.T1; NRF_TEMP->T2 = NRF_FICR->TEMP.T2; NRF_TEMP->T3 = NRF_FICR->TEMP.T3; NRF_TEMP->T4 = NRF_FICR->TEMP.T4; } /* Workaround for Errata 98 "NFCT: Not able to communicate with the peer" found at the Errata document for your device located at https://www.nordicsemi.com/DocLib */ if (errata_98()){ *(volatile uint32_t *)0x4000568Cul = 0x00038148ul; } /* Workaround for Errata 103 "CCM: Wrong reset value of CCM MAXPACKETSIZE" found at the Errata document for your device located at https://www.nordicsemi.com/DocLib */ if (errata_103()){ NRF_CCM->MAXPACKETSIZE = 0xFBul; } /* Workaround for Errata 115 "RAM: RAM content cannot be trusted upon waking up from System ON Idle or System OFF mode" found at the Errata document for your device located at https://www.nordicsemi.com/DocLib */ if (errata_115()){ *(volatile uint32_t *)0x40000EE4 = (*(volatile uint32_t *)0x40000EE4 & 0xFFFFFFF0) | (*(uint32_t *)0x10000258 & 0x0000000F); } /* Workaround for Errata 120 "QSPI: Data read or written is corrupted" found at the Errata document for your device located at https://www.nordicsemi.com/DocLib */ if (errata_120()){ *(volatile uint32_t *)0x40029640ul = 0x200ul; } /* Workaround for Errata 136 "System: Bits in RESETREAS are set when they should not be" found at the Errata document for your device located at https://www.nordicsemi.com/DocLib */ if (errata_136()){ if (NRF_POWER->RESETREAS & POWER_RESETREAS_RESETPIN_Msk){ NRF_POWER->RESETREAS = ~POWER_RESETREAS_RESETPIN_Msk; } } /* Enable the FPU if the compiler used floating point unit instructions. __FPU_USED is a MACRO defined by the * compiler. Since the FPU consumes energy, remember to disable FPU use in the compiler if floating point unit * operations are not used in your code. */ #if (__FPU_USED == 1) SCB->CPACR |= (3UL << 20) | (3UL << 22); __DSB(); __ISB(); #endif /* Configure NFCT pins as GPIOs if NFCT is not to be used in your code. If CONFIG_NFCT_PINS_AS_GPIOS is not defined, two GPIOs (see Product Specification to see which ones) will be reserved for NFC and will not be available as normal GPIOs. */ #if defined (CONFIG_NFCT_PINS_AS_GPIOS) if ((NRF_UICR->NFCPINS & UICR_NFCPINS_PROTECT_Msk) == (UICR_NFCPINS_PROTECT_NFC << UICR_NFCPINS_PROTECT_Pos)){ NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen << NVMC_CONFIG_WEN_Pos; while (NRF_NVMC->READY == NVMC_READY_READY_Busy){} NRF_UICR->NFCPINS &= ~UICR_NFCPINS_PROTECT_Msk; while (NRF_NVMC->READY == NVMC_READY_READY_Busy){} NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos; while (NRF_NVMC->READY == NVMC_READY_READY_Busy){} NVIC_SystemReset(); } #endif /* Configure GPIO pads as pPin Reset pin if Pin Reset capabilities desired. If CONFIG_GPIO_AS_PINRESET is not defined, pin reset will not be available. One GPIO (see Product Specification to see which one) will then be reserved for PinReset and not available as normal GPIO. */ #if defined (CONFIG_GPIO_AS_PINRESET) if (((NRF_UICR->PSELRESET[0] & UICR_PSELRESET_CONNECT_Msk) != (UICR_PSELRESET_CONNECT_Connected << UICR_PSELRESET_CONNECT_Pos)) || ((NRF_UICR->PSELRESET[1] & UICR_PSELRESET_CONNECT_Msk) != (UICR_PSELRESET_CONNECT_Connected << UICR_PSELRESET_CONNECT_Pos))){ NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen << NVMC_CONFIG_WEN_Pos; while (NRF_NVMC->READY == NVMC_READY_READY_Busy){} NRF_UICR->PSELRESET[0] = 18; while (NRF_NVMC->READY == NVMC_READY_READY_Busy){} NRF_UICR->PSELRESET[1] = 18; while (NRF_NVMC->READY == NVMC_READY_READY_Busy){} NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren << NVMC_CONFIG_WEN_Pos; while (NRF_NVMC->READY == NVMC_READY_READY_Busy){} NVIC_SystemReset(); } #endif SystemCoreClockUpdate(); } static bool errata_36(void) { if (*(uint32_t *)0x10000130ul == 0x8ul){ if (*(uint32_t *)0x10000134ul == 0x0ul){ return true; } if (*(uint32_t *)0x10000134ul == 0x1ul){ return true; } if (*(uint32_t *)0x10000134ul == 0x2ul){ return true; } if (*(uint32_t *)0x10000134ul == 0x3ul){ return true; } } /* Apply by default for unknown devices until errata is confirmed fixed. */ return true; } static bool errata_66(void) { if (*(uint32_t *)0x10000130ul == 0x8ul){ if (*(uint32_t *)0x10000134ul == 0x0ul){ return true; } if (*(uint32_t *)0x10000134ul == 0x1ul){ return true; } if (*(uint32_t *)0x10000134ul == 0x2ul){ return true; } if (*(uint32_t *)0x10000134ul == 0x3ul){ return true; } } /* Apply by default for unknown devices until errata is confirmed fixed. */ return true; } static bool errata_98(void) { if (*(uint32_t *)0x10000130ul == 0x8ul){ if (*(uint32_t *)0x10000134ul == 0x0ul){ return true; } } return false; } static bool errata_103(void) { if (*(uint32_t *)0x10000130ul == 0x8ul){ if (*(uint32_t *)0x10000134ul == 0x0ul){ return true; } } return false; } static bool errata_115(void) { if (*(uint32_t *)0x10000130ul == 0x8ul){ if (*(uint32_t *)0x10000134ul == 0x0ul){ return true; } } return false; } static bool errata_120(void) { if (*(uint32_t *)0x10000130ul == 0x8ul){ if (*(uint32_t *)0x10000134ul == 0x0ul){ return true; } } return false; } static bool errata_136(void) { if (*(uint32_t *)0x10000130ul == 0x8ul){ if (*(uint32_t *)0x10000134ul == 0x0ul){ return true; } if (*(uint32_t *)0x10000134ul == 0x1ul){ return true; } if (*(uint32_t *)0x10000134ul == 0x2ul){ return true; } if (*(uint32_t *)0x10000134ul == 0x3ul){ return true; } } /* Apply by default for unknown devices until errata is confirmed fixed. */ return true; } /*lint --flb "Leave library region" */ #endif
the_stack_data/823967.c
#include <stdio.h> #include <stdlib.h> struct RandomListNode { int label; struct RandomListNode *next; struct RandomListNode *random; }; static struct RandomListNode *copyRandomList(struct RandomListNode *head) { if (head == NULL) { return NULL; } struct RandomListNode *p, *new; for (p = head; p != NULL; p = p->next->next) { new = malloc(sizeof(*new)); new->label = p->label; new->next = p->next; p->next = new; } for (p = head; p != NULL; p = p->next->next) { new = p->next; new->random = p->random != NULL ? p->random->next : NULL; } struct RandomListNode dummy; struct RandomListNode *prev = &dummy; for (p = head; p != NULL; p = p->next) { new = p->next; p->next = new->next; prev->next = new; prev = new; new->next = NULL; } return dummy.next; } int main(int argc, char **argv) { int i, count = argc - 1; struct RandomListNode *head = NULL, *p, *prev; for (i = 0; i < count; i++) { p = malloc(sizeof(*p)); p->label = atoi(argv[i + 1]); p->next = NULL; p->random = NULL; if (head == NULL) { head = p; } else { prev->next = p; prev->random = p; } prev = p; } struct RandomListNode *r = head; struct RandomListNode *q = p = copyRandomList(head); for (r = head; r != NULL; r = r->next) { printf("%d ", r->label); } printf("\n"); for (r = head; r != NULL; r = r->random) { printf("%d ", r->label); } printf("\n"); for (; p != NULL; p = p->next) { printf("%d ", p->label); } printf("\n"); for (; q != NULL; q = q->random) { printf("%d ", q->label); } printf("\n"); return 0; }
the_stack_data/91448.c
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { char name[50]; int count; } List; void printList(List *list, int y) { for( int i = 0; i < y; i++) { printf("Palavra: %s, vezes: %d \n", list[i].name, list[i].count); } } int genererate(char phrase[10][50], int y) { y += 1; List list[y]; for ( int i = 0; i < y; i++ ) { list[i].count = 1; for ( int j = 0; j < y; j++ ) { if ( strcmp(phrase[i], phrase[j]) == 0 && i != j) { strcpy(list[i].name, phrase[i]); list[i].count += 1; } } } printList(list,y); return 0; } void printBV(char phrase[10][50], int y) { for (int i = 0; i <= y; i++) { printf("%s\n", phrase[i]); } } void toLowerCase(char *phrase) { for (int i = 0; i < strlen(phrase); i++) { phrase[i] = tolower(phrase[i]); } } char *mostRepetitiveWorld(char *phrase) { int words = 0; char vector[10][50]; for (int i = 0; i < strlen(phrase); i++) { if (phrase[i] == ' ') { words++; } } int i = 0; int j = 0; int k = 0; while (j <= words) { while (phrase[i] != ' ' && phrase[i] != '\0') { vector[j][i - k] = phrase[i]; i++; } vector[j][i - k] = '\0'; i++; j++; k = i; } /* printBV(vector, words); */ genererate(vector, words); return phrase; } int main(void) { char string[] = "Bom dia como vai você bom dia como"; toLowerCase(string); /* printf("%s\n", string); */ mostRepetitiveWorld(string); return 0; }
the_stack_data/70286.c
#include<stdio.h> #include<stdlib.h> typedef struct Node { int data; struct Node *next; }node; node *front=NULL; node *rear=NULL; void enQueue(int x) { node *n1; n1=(node*)malloc(sizeof(node)); n1->data=x; if(rear==NULL) { front=rear=n1; return; } rear->next=n1; n1->next=front; rear=rear->next; } int deQueue() { int x; node *temp; if(front==NULL) { printf("\nQueue is empty"); return(0); } temp=front; front=front->next; rear->next=front; x=temp->data; temp->next=NULL; free(temp); return(x); } void display(node *l) { int ch; printf("\nPress 1 to traverse, 2 to exit"); while(1) { printf(" %d ",l->data); scanf("%d",&ch); if(ch==1) l=l->next; else break; } } int main() { int x,i,del,t; printf("\n***** Circular Queue *****\n"); printf("\n1. Enter the element ."); printf("\n2. Delete the element."); printf("\n3. Display the Queue."); printf("\n4. Exit."); while(1){ printf("\n Enter choice :"); scanf("%d",&x); switch(x){ case 1 : printf("\nEnter the element :"); scanf("%d",&t); enQueue(t); break; case 2 : del=deQueue(); printf("\nDeleted Element :%d",del); break; case 3 : display(front); break; case 4 : exit(0); default : printf("\n Wrong Input . Try Again."); break; } } }
the_stack_data/170454225.c
int main(){80-0 <= 20*2;}
the_stack_data/176706236.c
// // Created by wifi on 19-2-26. // #include <stdio.h> int main(){ while(1) printf("s"); }
the_stack_data/18889107.c
/*author @bbarton 1/28/22 Gives a list of snacks, which you are free to purchase. */ #include <stdio.h> #include <string.h> #include <stdlib.h> struct snack { char name[15]; float cost; int quantity; }; void cashRegister(float money, struct snack choice){ float change; change = money - choice.cost; if (choice.quantity == 0){ printf("Sorry, we are out of %s!\n", choice.name); } else if (change < 0){ printf("You don't have enough money, sorry. \n"); } else { printf("You bought %s", choice.name); printf("\nYou have $%0.2f left\n", change); } } int main() { float money; int choice; struct snack *snackbar = malloc(sizeof(struct snack)*3); if (snackbar == NULL){ printf("ERROR: malloc failed!"); exit(1); } strcpy(snackbar[0].name, "Tostitos"); snackbar[0].cost = 3.49; snackbar[0].quantity = 4; strcpy(snackbar[1].name, "Persimmons"); snackbar[1].cost = 1.00; snackbar[1].quantity = 6; strcpy(snackbar[2].name, "Gummy Sharks"); snackbar[2].cost = 2.75; snackbar[2].quantity = 0; printf("Welcome to the Crust Bucket! \n"); //the name is gross, sorry printf("How much money do you have? "); scanf("%f", &money); printf("0) Tostitos cost: $3.49 quantity: 4 \n"); printf("1) Persimmons cost: $1.00 quantity: 6 \n"); printf("2) Gummy Sharks cost: $2.75 quantity: 0 \n"); printf("What snack would you like to buy? [0,1,2] "); scanf("%d", &choice); if (choice == 0){ cashRegister(money, snackbar[0]); } else if (choice == 1){ cashRegister(money, snackbar[1]); } else if (choice == 2){ cashRegister(money, snackbar[2]); } else { printf("That item is not sold here, sorry.\n"); } free(snackbar); snackbar = NULL; return 0; }
the_stack_data/206392586.c
/* -*- mode: c; c-basic-offset: 8; -*- * vim: noexpandtab sw=8 ts=8 sts=0: * * netdebug.c * * debug functionality for o2net * * Copyright (C) 2005, 2008 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License 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 021110-1307, USA. * */ #ifdef CONFIG_DEBUG_FS #include <linux/module.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/idr.h> #include <linux/kref.h> #include <linux/seq_file.h> #include <linux/debugfs.h> #include <linux/uaccess.h> #include "tcp.h" #include "nodemanager.h" #define MLOG_MASK_PREFIX ML_TCP #include "masklog.h" #include "tcp_internal.h" #define O2NET_DEBUG_DIR "o2net" #define SC_DEBUG_NAME "sock_containers" #define NST_DEBUG_NAME "send_tracking" #define STATS_DEBUG_NAME "stats" #define NODES_DEBUG_NAME "connected_nodes" #define SHOW_SOCK_CONTAINERS 0 #define SHOW_SOCK_STATS 1 static struct dentry *o2net_dentry; static struct dentry *sc_dentry; static struct dentry *nst_dentry; static struct dentry *stats_dentry; static struct dentry *nodes_dentry; static DEFINE_SPINLOCK(o2net_debug_lock); static LIST_HEAD(sock_containers); static LIST_HEAD(send_tracking); void o2net_debug_add_nst(struct o2net_send_tracking *nst) { spin_lock(&o2net_debug_lock); list_add(&nst->st_net_debug_item, &send_tracking); spin_unlock(&o2net_debug_lock); } void o2net_debug_del_nst(struct o2net_send_tracking *nst) { spin_lock(&o2net_debug_lock); if (!list_empty(&nst->st_net_debug_item)) list_del_init(&nst->st_net_debug_item); spin_unlock(&o2net_debug_lock); } static struct o2net_send_tracking *next_nst(struct o2net_send_tracking *nst_start) { struct o2net_send_tracking *nst, *ret = NULL; assert_spin_locked(&o2net_debug_lock); list_for_each_entry(nst, &nst_start->st_net_debug_item, st_net_debug_item) { /* discover the head of the list */ if (&nst->st_net_debug_item == &send_tracking) break; /* use st_task to detect real nsts in the list */ if (nst->st_task != NULL) { ret = nst; break; } } return ret; } static void *nst_seq_start(struct seq_file *seq, loff_t *pos) { struct o2net_send_tracking *nst, *dummy_nst = seq->private; spin_lock(&o2net_debug_lock); nst = next_nst(dummy_nst); spin_unlock(&o2net_debug_lock); return nst; } static void *nst_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct o2net_send_tracking *nst, *dummy_nst = seq->private; spin_lock(&o2net_debug_lock); nst = next_nst(dummy_nst); list_del_init(&dummy_nst->st_net_debug_item); if (nst) list_add(&dummy_nst->st_net_debug_item, &nst->st_net_debug_item); spin_unlock(&o2net_debug_lock); return nst; /* unused, just needs to be null when done */ } static int nst_seq_show(struct seq_file *seq, void *v) { struct o2net_send_tracking *nst, *dummy_nst = seq->private; ktime_t now; s64 sock, send, status; spin_lock(&o2net_debug_lock); nst = next_nst(dummy_nst); if (!nst) goto out; now = ktime_get(); sock = ktime_to_us(ktime_sub(now, nst->st_sock_time)); send = ktime_to_us(ktime_sub(now, nst->st_send_time)); status = ktime_to_us(ktime_sub(now, nst->st_status_time)); /* get_task_comm isn't exported. oh well. */ seq_printf(seq, "%p:\n" " pid: %lu\n" " tgid: %lu\n" " process name: %s\n" " node: %u\n" " sc: %p\n" " message id: %d\n" " message type: %u\n" " message key: 0x%08x\n" " sock acquiry: %lld usecs ago\n" " send start: %lld usecs ago\n" " wait start: %lld usecs ago\n", nst, (unsigned long)task_pid_nr(nst->st_task), (unsigned long)nst->st_task->tgid, nst->st_task->comm, nst->st_node, nst->st_sc, nst->st_id, nst->st_msg_type, nst->st_msg_key, (long long)sock, (long long)send, (long long)status); out: spin_unlock(&o2net_debug_lock); return 0; } static void nst_seq_stop(struct seq_file *seq, void *v) { } static const struct seq_operations nst_seq_ops = { .start = nst_seq_start, .next = nst_seq_next, .stop = nst_seq_stop, .show = nst_seq_show, }; static int nst_fop_open(struct inode *inode, struct file *file) { struct o2net_send_tracking *dummy_nst; dummy_nst = __seq_open_private(file, &nst_seq_ops, sizeof(*dummy_nst)); if (!dummy_nst) return -ENOMEM; o2net_debug_add_nst(dummy_nst); return 0; } static int nst_fop_release(struct inode *inode, struct file *file) { struct seq_file *seq = file->private_data; struct o2net_send_tracking *dummy_nst = seq->private; o2net_debug_del_nst(dummy_nst); return seq_release_private(inode, file); } static const struct file_operations nst_seq_fops = { .open = nst_fop_open, .read = seq_read, .llseek = seq_lseek, .release = nst_fop_release, }; void o2net_debug_add_sc(struct o2net_sock_container *sc) { spin_lock(&o2net_debug_lock); list_add(&sc->sc_net_debug_item, &sock_containers); spin_unlock(&o2net_debug_lock); } void o2net_debug_del_sc(struct o2net_sock_container *sc) { spin_lock(&o2net_debug_lock); list_del_init(&sc->sc_net_debug_item); spin_unlock(&o2net_debug_lock); } struct o2net_sock_debug { int dbg_ctxt; struct o2net_sock_container *dbg_sock; }; static struct o2net_sock_container *next_sc(struct o2net_sock_container *sc_start) { struct o2net_sock_container *sc, *ret = NULL; assert_spin_locked(&o2net_debug_lock); list_for_each_entry(sc, &sc_start->sc_net_debug_item, sc_net_debug_item) { /* discover the head of the list miscast as a sc */ if (&sc->sc_net_debug_item == &sock_containers) break; /* use sc_page to detect real scs in the list */ if (sc->sc_page != NULL) { ret = sc; break; } } return ret; } static void *sc_seq_start(struct seq_file *seq, loff_t *pos) { struct o2net_sock_debug *sd = seq->private; struct o2net_sock_container *sc, *dummy_sc = sd->dbg_sock; spin_lock(&o2net_debug_lock); sc = next_sc(dummy_sc); spin_unlock(&o2net_debug_lock); return sc; } static void *sc_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct o2net_sock_debug *sd = seq->private; struct o2net_sock_container *sc, *dummy_sc = sd->dbg_sock; spin_lock(&o2net_debug_lock); sc = next_sc(dummy_sc); list_del_init(&dummy_sc->sc_net_debug_item); if (sc) list_add(&dummy_sc->sc_net_debug_item, &sc->sc_net_debug_item); spin_unlock(&o2net_debug_lock); return sc; /* unused, just needs to be null when done */ } #ifdef CONFIG_OCFS2_FS_STATS # define sc_send_count(_s) ((_s)->sc_send_count) # define sc_recv_count(_s) ((_s)->sc_recv_count) # define sc_tv_acquiry_total_ns(_s) (ktime_to_ns((_s)->sc_tv_acquiry_total)) # define sc_tv_send_total_ns(_s) (ktime_to_ns((_s)->sc_tv_send_total)) # define sc_tv_status_total_ns(_s) (ktime_to_ns((_s)->sc_tv_status_total)) # define sc_tv_process_total_ns(_s) (ktime_to_ns((_s)->sc_tv_process_total)) #else # define sc_send_count(_s) (0U) # define sc_recv_count(_s) (0U) # define sc_tv_acquiry_total_ns(_s) (0LL) # define sc_tv_send_total_ns(_s) (0LL) # define sc_tv_status_total_ns(_s) (0LL) # define sc_tv_process_total_ns(_s) (0LL) #endif /* So that debugfs.ocfs2 can determine which format is being used */ #define O2NET_STATS_STR_VERSION 1 static void sc_show_sock_stats(struct seq_file *seq, struct o2net_sock_container *sc) { if (!sc) return; seq_printf(seq, "%d,%u,%lu,%lld,%lld,%lld,%lu,%lld\n", O2NET_STATS_STR_VERSION, sc->sc_node->nd_num, (unsigned long)sc_send_count(sc), (long long)sc_tv_acquiry_total_ns(sc), (long long)sc_tv_send_total_ns(sc), (long long)sc_tv_status_total_ns(sc), (unsigned long)sc_recv_count(sc), (long long)sc_tv_process_total_ns(sc)); } static void sc_show_sock_container(struct seq_file *seq, struct o2net_sock_container *sc) { struct inet_sock *inet = NULL; __be32 saddr = 0, daddr = 0; __be16 sport = 0, dport = 0; if (!sc) return; if (sc->sc_sock) { inet = inet_sk(sc->sc_sock->sk); /* the stack's structs aren't sparse endian clean */ saddr = (__force __be32)inet->inet_saddr; daddr = (__force __be32)inet->inet_daddr; sport = (__force __be16)inet->inet_sport; dport = (__force __be16)inet->inet_dport; } /* XXX sigh, inet-> doesn't have sparse annotation so any * use of it here generates a warning with -Wbitwise */ seq_printf(seq, "%p:\n" " krefs: %d\n" " sock: %pI4:%u -> " "%pI4:%u\n" " remote node: %s\n" " page off: %zu\n" " handshake ok: %u\n" " timer: %lld usecs\n" " data ready: %lld usecs\n" " advance start: %lld usecs\n" " advance stop: %lld usecs\n" " func start: %lld usecs\n" " func stop: %lld usecs\n" " func key: 0x%08x\n" " func type: %u\n", sc, atomic_read(&sc->sc_kref.refcount), &saddr, inet ? ntohs(sport) : 0, &daddr, inet ? ntohs(dport) : 0, sc->sc_node->nd_name, sc->sc_page_off, sc->sc_handshake_ok, (long long)ktime_to_us(sc->sc_tv_timer), (long long)ktime_to_us(sc->sc_tv_data_ready), (long long)ktime_to_us(sc->sc_tv_advance_start), (long long)ktime_to_us(sc->sc_tv_advance_stop), (long long)ktime_to_us(sc->sc_tv_func_start), (long long)ktime_to_us(sc->sc_tv_func_stop), sc->sc_msg_key, sc->sc_msg_type); } static int sc_seq_show(struct seq_file *seq, void *v) { struct o2net_sock_debug *sd = seq->private; struct o2net_sock_container *sc, *dummy_sc = sd->dbg_sock; spin_lock(&o2net_debug_lock); sc = next_sc(dummy_sc); if (sc) { if (sd->dbg_ctxt == SHOW_SOCK_CONTAINERS) sc_show_sock_container(seq, sc); else sc_show_sock_stats(seq, sc); } spin_unlock(&o2net_debug_lock); return 0; } static void sc_seq_stop(struct seq_file *seq, void *v) { } static const struct seq_operations sc_seq_ops = { .start = sc_seq_start, .next = sc_seq_next, .stop = sc_seq_stop, .show = sc_seq_show, }; static int sc_common_open(struct file *file, int ctxt) { struct o2net_sock_debug *sd; struct o2net_sock_container *dummy_sc; dummy_sc = kzalloc(sizeof(*dummy_sc), GFP_KERNEL); if (!dummy_sc) return -ENOMEM; sd = __seq_open_private(file, &sc_seq_ops, sizeof(*sd)); if (!sd) { kfree(dummy_sc); return -ENOMEM; } sd->dbg_ctxt = ctxt; sd->dbg_sock = dummy_sc; o2net_debug_add_sc(dummy_sc); return 0; } static int sc_fop_release(struct inode *inode, struct file *file) { struct seq_file *seq = file->private_data; struct o2net_sock_debug *sd = seq->private; struct o2net_sock_container *dummy_sc = sd->dbg_sock; o2net_debug_del_sc(dummy_sc); return seq_release_private(inode, file); } static int stats_fop_open(struct inode *inode, struct file *file) { return sc_common_open(file, SHOW_SOCK_STATS); } static const struct file_operations stats_seq_fops = { .open = stats_fop_open, .read = seq_read, .llseek = seq_lseek, .release = sc_fop_release, }; static int sc_fop_open(struct inode *inode, struct file *file) { return sc_common_open(file, SHOW_SOCK_CONTAINERS); } static const struct file_operations sc_seq_fops = { .open = sc_fop_open, .read = seq_read, .llseek = seq_lseek, .release = sc_fop_release, }; static int o2net_fill_bitmap(char *buf, int len) { unsigned long map[BITS_TO_LONGS(O2NM_MAX_NODES)]; int i = -1, out = 0; o2net_fill_node_map(map, sizeof(map)); while ((i = find_next_bit(map, O2NM_MAX_NODES, i + 1)) < O2NM_MAX_NODES) out += snprintf(buf + out, PAGE_SIZE - out, "%d ", i); out += snprintf(buf + out, PAGE_SIZE - out, "\n"); return out; } static int nodes_fop_open(struct inode *inode, struct file *file) { char *buf; buf = kmalloc(PAGE_SIZE, GFP_KERNEL); if (!buf) return -ENOMEM; i_size_write(inode, o2net_fill_bitmap(buf, PAGE_SIZE)); file->private_data = buf; return 0; } static int o2net_debug_release(struct inode *inode, struct file *file) { kfree(file->private_data); return 0; } static ssize_t o2net_debug_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) { return simple_read_from_buffer(buf, nbytes, ppos, file->private_data, i_size_read(file->f_mapping->host)); } static const struct file_operations nodes_fops = { .open = nodes_fop_open, .release = o2net_debug_release, .read = o2net_debug_read, .llseek = generic_file_llseek, }; void o2net_debugfs_exit(void) { debugfs_remove(nodes_dentry); debugfs_remove(stats_dentry); debugfs_remove(sc_dentry); debugfs_remove(nst_dentry); debugfs_remove(o2net_dentry); } int o2net_debugfs_init(void) { umode_t mode = S_IFREG|S_IRUSR; o2net_dentry = debugfs_create_dir(O2NET_DEBUG_DIR, NULL); if (o2net_dentry) nst_dentry = debugfs_create_file(NST_DEBUG_NAME, mode, o2net_dentry, NULL, &nst_seq_fops); if (nst_dentry) sc_dentry = debugfs_create_file(SC_DEBUG_NAME, mode, o2net_dentry, NULL, &sc_seq_fops); if (sc_dentry) stats_dentry = debugfs_create_file(STATS_DEBUG_NAME, mode, o2net_dentry, NULL, &stats_seq_fops); if (stats_dentry) nodes_dentry = debugfs_create_file(NODES_DEBUG_NAME, mode, o2net_dentry, NULL, &nodes_fops); if (nodes_dentry) return 0; o2net_debugfs_exit(); mlog_errno(-ENOMEM); return -ENOMEM; } #endif /* CONFIG_DEBUG_FS */
the_stack_data/56648.c
int main() { int a = 5; int b = 2; int c = a + b; for (int i = b; i < 20; i++) { b = i; c = i % a; } return c; } // 5: {a}
the_stack_data/215767337.c
//1234 a #include <stdio.h> int main() { FILE *f = fopen("stdio/fscanf_offby1.c", "r"); int x; fscanf(f, "//%d", &x); printf("%d, %ld, %d\n", x, ftell(f), fgetc(f)); }
the_stack_data/761105.c
// NB: This code will never be run, but we do need a realistic-looking // executable for the tests. int main() {}
the_stack_data/167329413.c
#include <stdio.h> #include <sys/stat.h> #include <stdbool.h> #include <stdlib.h> #include <dirent.h> #include <unistd.h> #include <string.h> #include <ftw.h> static int num_dirs, num_regular; static int callback(const char *fpath, const struct stat *sb, int typeflag) { // Define stuff here if(typeflag == FTW_F){ num_regular++; } if(typeflag == FTW_D){ num_dirs++; } return 0; } #define MAX_FTW_DEPTH 16 int main(int argc, char** argv) { if (argc != 2) { printf ("Usage: %s <path>\n", argv[0]); printf (" where <path> is the file or root of the tree you want to summarize.\n"); return 1; } num_dirs = 0; num_regular = 0; ftw(argv[1], callback, MAX_FTW_DEPTH); printf("There were %d directories.\n", num_dirs); printf("There were %d regular files.\n", num_regular); }
the_stack_data/1037299.c
#include <stdlib.h> #define SP #define ROLL /* Translated to C by Bonnie Toy 5/88 (modified on 2/25/94 to fix a problem with daxpy for unequal increments or equal increments not equal to 1. Jack Dongarra) To compile single precision version for Sun-4: cc -DSP -O4 -fsingle -fsingle2 clinpack.c -lm To compile double precision version for Sun-4: cc -DDP -O4 clinpack.c -lm To obtain rolled source BLAS, add -DROLL to the command lines. To obtain unrolled source BLAS, add -DUNROLL to the command lines. You must specify one of -DSP or -DDP to compile correctly. You must specify one of -DROLL or -DUNROLL to compile correctly. */ #define DEBUG 0 #ifdef SP #define REAL float #define ZERO 0.0 #define ONE 1.0 #define PREC "Single " #endif #ifdef DP #define REAL double #define ZERO 0.0e0 #define ONE 1.0e0 #define PREC "Double " #endif #define NTIMES 10 #ifdef ROLL #define ROLLING "Rolled " #endif #ifdef UNROLL #define ROLLING "Unrolled " #endif #include <stdio.h> #include <math.h> static REAL time[9][9]; /*----------------------*/ void print_time (row) int row; { /* fprintf(stderr,"%11.2f%11.2f%11.2f%11.0f%11.2f%11.2f\n", (double)time[0][row], (double)time[1][row], (double)time[2][row], (double)time[3][row], (double)time[4][row], (double)time[5][row]); */ } /*----------------------*/ void matgen(a,lda,n,b,norma) REAL a[],b[],*norma; int lda, n; /* We would like to declare a[][lda], but c does not allow it. In this function, references to a[i][j] are written a[lda*i+j]. */ { int init, i, j; #if(DEBUG) printf("->matgen\n"); #endif init = 1325; *norma = 0.0; for (j = 0; j < n; j++) { for (i = 0; i < n; i++) { init = 3125*init % 65536; a[lda*j+i] = (init - 32768.0)/16384.0; *norma = (a[lda*j+i] > *norma) ? a[lda*j+i] : *norma; } } for (i = 0; i < n; i++) { b[i] = 0.0; } for (j = 0; j < n; j++) { for (i = 0; i < n; i++) { b[i] = b[i] + a[lda*j+i]; } } } /*----------------------*/ void daxpy(n,da,dx,incx,dy,incy) /* constant times a vector plus a vector. jack dongarra, linpack, 3/11/78. */ REAL dx[],dy[],da; int incx,incy,n; { int i,ix,iy; //daxpy(n-(k+1),t,&a[lda*k+k+1],1,&b[k+1],1); //printf("2.1.2: a[%d]=%e b[%d]=%e\n", lda*k+k+1, a[lda*k+k+1], k+1, b[k+1]); #if(DEBUG) printf("->daxpy\n"); #endif if(n <= 0) return; if (da == ZERO) return; if(incx != 1 || incy != 1) { /* code for unequal increments or equal increments not equal to 1 */ ix = 0; iy = 0; if(incx < 0) ix = (-n+1)*incx; if(incy < 0)iy = (-n+1)*incy; for (i = 0;i < n; i++) { dy[iy] = dy[iy] + da*dx[ix]; //printf("2.1.1.1: dy[%d]=%f\n", iy, dy[iy]); ix = ix + incx; iy = iy + incy; } return; } /* code for both increments equal to 1 */ #ifdef ROLL for (i = 0;i < n; i++) { //printf("2.1.1.2.1: dy[%d]=%f\n", i, dy[i]); dy[i] = dy[i] + da*dx[i]; //printf("2.1.1.2.2: dy[%d]=%f\n", i, dy[i]); } #endif #ifdef UNROLL m = n % 4; if ( m != 0) { for (i = 0; i < m; i++) { dy[i] = dy[i] + da*dx[i]; //printf("2.1.1.3: dy[%d]=%f\n", i, dy[i]); } if (n < 4) return; } for (i = m; i < n; i = i + 4) { dy[i] = dy[i] + da*dx[i]; //printf("2.1.1.4: dy[%d]=%f\n", i, dy[i]); dy[i+1] = dy[i+1] + da*dx[i+1]; //printf("2.1.1.4: dy[%d]=%f\n", i+1, dy[i+1]); dy[i+2] = dy[i+2] + da*dx[i+2]; //printf("2.1.1.4: dy[%d]=%f\n", i+2, dy[i+2]); dy[i+3] = dy[i+3] + da*dx[i+3]; //printf("2.1.1.4: dy[%d]=%f\n", i+3, dy[i+3]); } #endif } /*----------------------*/ void dgesl(a,lda,n,ipvt,b,job) int lda,n,ipvt[],job; REAL a[],b[]; /* We would like to declare a[][lda], but c does not allow it. In this function, references to a[i][j] are written a[lda*i+j]. */ /* dgesl solves the double precision system a * x = b or trans(a) * x = b using the factors computed by dgeco or dgefa. on entry a double precision[n][lda] the output from dgeco or dgefa. lda integer the leading dimension of the array a . n integer the order of the matrix a . ipvt integer[n] the pivot vector from dgeco or dgefa. b double precision[n] the right hand side vector. job integer = 0 to solve a*x = b , = nonzero to solve trans(a)*x = b where trans(a) is the transpose. on return b the solution vector x . error condition a division by zero will occur if the input factor contains a zero on the diagonal. technically this indicates singularity but it is often caused by improper arguments or improper setting of lda . it will not occur if the subroutines are called correctly and if dgeco has set rcond .gt. 0.0 or dgefa has set info .eq. 0 . to compute inverse(a) * c where c is a matrix with p columns dgeco(a,lda,n,ipvt,rcond,z) if (!rcond is too small){ for (j=0,j<p,j++) dgesl(a,lda,n,ipvt,c[j][0],0); } linpack. this version dated 08/14/78 . cleve moler, university of new mexico, argonne national lab. functions blas daxpy,ddot */ { /* internal variables */ REAL ddot(),t; int k,kb,l,nm1; #if(DEBUG) printf("->dgesl\n"); #endif nm1 = n - 1; if (job == 0) { /* job = 0 , solve a * x = b first solve l*y = b */ if (nm1 >= 1) { for (k = 0; k < nm1; k++) { l = ipvt[k]; t = b[l]; if (l != k){ b[l] = b[k]; b[k] = t; } //printf("2.1.1: a[%d]=%f b[%d]=%f\n", lda*k+k+1, a[lda*k+k+1], k+1, b[k+1]); daxpy(n-(k+1),t,&a[lda*k+k+1],1,&b[k+1],1); //printf("2.1.2: a[%d]=%f b[%d]=%f\n", lda*k+k+1, a[lda*k+k+1], k+1, b[k+1]); } } /* now solve u*x = y */ for (kb = 0; kb < n; kb++) { k = n - (kb + 1); b[k] = b[k]/a[lda*k+k]; t = -b[k]; daxpy(k,t,&a[lda*k+0],1,&b[0],1); //printf("2.2: a[%d]=%f b[%d]=%f\n", lda*k+0, a[lda*k+0], 0, b[0]); } } else { /* job = nonzero, solve trans(a) * x = b first solve trans(u)*y = b */ for (k = 0; k < n; k++) { t = ddot(k,&a[lda*k+0],1,&b[0],1); //printf("2.3: a[%d]=%f b[%d]=%f\n", lda*k+0, a[lda*k+0], 0, b[0]); b[k] = (b[k] - t)/a[lda*k+k]; //printf("2.4: b[%d]=%f\n", k, b[k]); } /* now solve trans(l)*x = y */ if (nm1 >= 1) { for (kb = 1; kb < nm1; kb++) { k = n - (kb+1); b[k] = b[k] + ddot(n-(k+1),&a[lda*k+k+1],1,&b[k+1],1); //printf("2.5: a[%d]=%f b[%d]=%f\n", lda*k+k+1, a[lda*k+k+1], k , b[k]); l = ipvt[k]; if (l != k) { t = b[l]; b[l] = b[k]; b[k] = t; //printf("2.6: b[%d]=%f\n", k, b[k]); } } } } } /*----------------------*/ REAL ddot(n,dx,incx,dy,incy) /* forms the dot product of two vectors. jack dongarra, linpack, 3/11/78. */ REAL dx[],dy[]; int incx,incy,n; { REAL dtemp; int i,ix,iy; #if(DEBUG) printf("->ddot\n"); #endif dtemp = ZERO; if(n <= 0) return(ZERO); if(incx != 1 || incy != 1) { /* code for unequal increments or equal increments not equal to 1 */ ix = 0; iy = 0; if (incx < 0) ix = (-n+1)*incx; if (incy < 0) iy = (-n+1)*incy; for (i = 0;i < n; i++) { dtemp = dtemp + dx[ix]*dy[iy]; ix = ix + incx; iy = iy + incy; } return(dtemp); } /* code for both increments equal to 1 */ #ifdef ROLL for (i=0;i < n; i++) dtemp = dtemp + dx[i]*dy[i]; return(dtemp); #endif #ifdef UNROLL m = n % 5; if (m != 0) { for (i = 0; i < m; i++) dtemp = dtemp + dx[i]*dy[i]; if (n < 5) return(dtemp); } for (i = m; i < n; i = i + 5) { dtemp = dtemp + dx[i]*dy[i] + dx[i+1]*dy[i+1] + dx[i+2]*dy[i+2] + dx[i+3]*dy[i+3] + dx[i+4]*dy[i+4]; } return(dtemp); #endif } /*----------------------*/ void dscal(n,da,dx,incx) /* scales a vector by a constant. jack dongarra, linpack, 3/11/78. */ REAL da,dx[]; int n, incx; { int i,nincx; #if(DEBUG) printf("->dscal\n"); #endif if(n <= 0)return; if(incx != 1) { /* code for increment not equal to 1 */ nincx = n*incx; for (i = 0; i < nincx; i = i + incx) dx[i] = da*dx[i]; return; } /* code for increment equal to 1 */ #ifdef ROLL for (i = 0; i < n; i++) dx[i] = da*dx[i]; #endif #ifdef UNROLL m = n % 5; if (m != 0) { for (i = 0; i < m; i++) dx[i] = da*dx[i]; if (n < 5) return; } for (i = m; i < n; i = i + 5){ dx[i] = da*dx[i]; dx[i+1] = da*dx[i+1]; dx[i+2] = da*dx[i+2]; dx[i+3] = da*dx[i+3]; dx[i+4] = da*dx[i+4]; } #endif } /*----------------------*/ int idamax(n,dx,incx) /* finds the index of element having max. absolute value. jack dongarra, linpack, 3/11/78. */ REAL dx[]; int incx,n; { REAL dmax; int i, ix, itemp=0; #if(DEBUG) printf("->idamax\n"); #endif if( n < 1 ) return(-1); if(n ==1 ) return(0); if(incx != 1) { /* code for increment not equal to 1 */ ix = 1; dmax = fabs((double)dx[0]); ix = ix + incx; for (i = 1; i < n; i++) { if(fabs((double)dx[ix]) > dmax) { itemp = i; dmax = fabs((double)dx[ix]); } ix = ix + incx; } } else { /* code for increment equal to 1 */ itemp = 0; dmax = fabs((double)dx[0]); for (i = 1; i < n; i++) { if(fabs((double)dx[i]) > dmax) { itemp = i; dmax = fabs((double)dx[i]); } } } return (itemp); } /*----------------------*/ REAL epslon (x) REAL x; /* estimate unit roundoff in quantities of size x. */ { REAL a,b,c,eps; /* this program should function properly on all systems satisfying the following two assumptions, 1. the base used in representing dfloating point numbers is not a power of three. 2. the quantity a in statement 10 is represented to the accuracy used in dfloating point variables that are stored in memory. the statement number 10 and the go to 10 are intended to force optimizing compilers to generate code satisfying assumption 2. under these assumptions, it should be true that, a is not exactly equal to four-thirds, b has a zero for its last bit or digit, c is not exactly equal to one, eps measures the separation of 1.0 from the next larger dfloating point number. the developers of eispack would appreciate being informed about any systems where these assumptions do not hold. ***************************************************************** this routine is one of the auxiliary routines used by eispack iii to avoid machine dependencies. ***************************************************************** this version dated 4/6/83. */ #if(DEBUG) printf("->epslon\n"); #endif a = 4.0e0/3.0e0; eps = ZERO; while (eps == ZERO) { b = a - ONE; c = b + b + b; eps = fabs((double)(c-ONE)); } return(eps*fabs((double)x)); } /*----------------------*/ void dmxpy (n1, y, n2, ldm, x, m) REAL y[], x[], m[]; int n1, n2, ldm; /* We would like to declare m[][ldm], but c does not allow it. In this function, references to m[i][j] are written m[ldm*i+j]. */ /* purpose: multiply matrix m times vector x and add the result to vector y. parameters: n1 integer, number of elements in vector y, and number of rows in matrix m y double [n1], vector of length n1 to which is added the product m*x n2 integer, number of elements in vector x, and number of columns in matrix m ldm integer, leading dimension of array m x double [n2], vector of length n2 m double [ldm][n2], matrix of n1 rows and n2 columns ---------------------------------------------------------------------- */ { int j,i,jmin; /* cleanup odd vector */ #if(DEBUG) printf("->dmxpy\n"); #endif j = n2 % 2; if (j >= 1) { j = j - 1; for (i = 0; i < n1; i++) y[i] = (y[i]) + x[j]*m[ldm*j+i]; } /* cleanup odd group of two vectors */ j = n2 % 4; if (j >= 2) { j = j - 1; for (i = 0; i < n1; i++) y[i] = ( (y[i]) + x[j-1]*m[ldm*(j-1)+i]) + x[j]*m[ldm*j+i]; } /* cleanup odd group of four vectors */ j = n2 % 8; if (j >= 4) { j = j - 1; for (i = 0; i < n1; i++) y[i] = ((( (y[i]) + x[j-3]*m[ldm*(j-3)+i]) + x[j-2]*m[ldm*(j-2)+i]) + x[j-1]*m[ldm*(j-1)+i]) + x[j]*m[ldm*j+i]; } /* cleanup odd group of eight vectors */ j = n2 % 16; if (j >= 8) { j = j - 1; for (i = 0; i < n1; i++) y[i] = ((((((( (y[i]) + x[j-7]*m[ldm*(j-7)+i]) + x[j-6]*m[ldm*(j-6)+i]) + x[j-5]*m[ldm*(j-5)+i]) + x[j-4]*m[ldm*(j-4)+i]) + x[j-3]*m[ldm*(j-3)+i]) + x[j-2]*m[ldm*(j-2)+i]) + x[j-1]*m[ldm*(j-1)+i]) + x[j] *m[ldm*j+i]; } /* main loop - groups of sixteen vectors */ jmin = (n2%16)+16; for (j = jmin-1; j < n2; j = j + 16) { for (i = 0; i < n1; i++) y[i] = ((((((((((((((( (y[i]) + x[j-15]*m[ldm*(j-15)+i]) + x[j-14]*m[ldm*(j-14)+i]) + x[j-13]*m[ldm*(j-13)+i]) + x[j-12]*m[ldm*(j-12)+i]) + x[j-11]*m[ldm*(j-11)+i]) + x[j-10]*m[ldm*(j-10)+i]) + x[j- 9]*m[ldm*(j- 9)+i]) + x[j- 8]*m[ldm*(j- 8)+i]) + x[j- 7]*m[ldm*(j- 7)+i]) + x[j- 6]*m[ldm*(j- 6)+i]) + x[j- 5]*m[ldm*(j- 5)+i]) + x[j- 4]*m[ldm*(j- 4)+i]) + x[j- 3]*m[ldm*(j- 3)+i]) + x[j- 2]*m[ldm*(j- 2)+i]) + x[j- 1]*m[ldm*(j- 1)+i]) + x[j] *m[ldm*j+i]; } } /*----------------------*/ void dgefa(a,lda,n,ipvt,info) REAL a[]; int lda,n,ipvt[],*info; /* We would like to declare a[][lda], but c does not allow it. In this function, references to a[i][j] are written a[lda*i+j]. */ /* dgefa factors a double precision matrix by gaussian elimination. dgefa is usually called by dgeco, but it can be called directly with a saving in time if rcond is not needed. (time for dgeco) = (1 + 9/n)*(time for dgefa) . on entry a REAL precision[n][lda] the matrix to be factored. lda integer the leading dimension of the array a . n integer the order of the matrix a . on return a an upper triangular matrix and the multipliers which were used to obtain it. the factorization can be written a = l*u where l is a product of permutation and unit lower triangular matrices and u is upper triangular. ipvt integer[n] an integer vector of pivot indices. info integer = 0 normal value. = k if u[k][k] .eq. 0.0 . this is not an error condition for this subroutine, but it does indicate that dgesl or dgedi will divide by zero if called. use rcond in dgeco for a reliable indication of singularity. linpack. this version dated 08/14/78 . cleve moler, university of new mexico, argonne national lab. functions blas daxpy,dscal,idamax */ { /* internal variables */ REAL t; int idamax(),j,k,kp1,l,nm1; /* gaussian elimination with partial pivoting */ #if(DEBUG) printf("->dgefa\n"); #endif *info = 0; nm1 = n - 1; if (nm1 >= 0) { for (k = 0; k < nm1; k++) { kp1 = k + 1; /* find l = pivot index */ l = idamax(n-k,&a[lda*k+k],1) + k; ipvt[k] = l; /* zero pivot implies this column already triangularized */ if (a[lda*k+l] != ZERO) { /* interchange if necessary */ if (l != k) { t = a[lda*k+l]; a[lda*k+l] = a[lda*k+k]; a[lda*k+k] = t; } /* compute multipliers */ t = -ONE/a[lda*k+k]; dscal(n-(k+1),t,&a[lda*k+k+1],1); /* row elimination with column indexing */ for (j = kp1; j < n; j++) { t = a[lda*j+l]; if (l != k) { a[lda*j+l] = a[lda*j+k]; a[lda*j+k] = t; } daxpy(n-(k+1),t,&a[lda*k+k+1],1, &a[lda*j+k+1],1); } } else { *info = k; } } } ipvt[n-1] = n-1; if (a[lda*(n-1)+(n-1)] == ZERO) *info = n-1; } int main (int argc, const char *argv[]) { static REAL aa[200][200],a[200][201],b[200],x[200]; REAL cray,ops,total=0.0,norma,normx; REAL resid=0.0,residn=0.0,eps=0.0; REAL epslon(),kf; static int ipvt[200],n,i,ntimes,info,lda,ldaa,kflops; ntimes = argc >= 2 ? atoi(argv[1]) : NTIMES; lda = 201; ldaa = 200; cray = .056; n = 100; printf("Begin %d\n", n); //fprintf(stdout,ROLLING);fprintf(stdout,PREC);fprintf(stdout,"Precision Linpack\n\n"); //fprintf(stderr,ROLLING);fprintf(stderr,PREC);fprintf(stderr,"Precision Linpack\n\n"); ops = (2.0e0*(n*n*n))/3.0 + 2.0*(n*n); for (i = 0; i < n; i++) { printf("1: b[%d]=%f\n", i, (double)b[i] ); } matgen(a,lda,n,b,&norma); for (i = 0; i < n; i++) { printf("2: b[%d]=%f\n", i, (double)b[i] ); } dgefa(a,lda,n,ipvt,&info); dgesl(a,lda,n,ipvt,b,0); for (i = 0; i < n; i++) { printf("3: b[%d]=%f\n", i, (double)b[i] ); } /* compute a residual to verify results. */ for (i = 0; i < n; i++) { printf("x[%d]=%f b[%d]=%f\n", i, (double)x[i], i, (double)b[i] ); x[i] = b[i]; } printf(" %f %f %f %f %f\n", (double)residn, (double)resid, (double)eps, (double)x[0]-1, (double)x[n-1]-1); matgen(a,lda,n,b,&norma); printf(" %f %f %f %f %f\n", (double)residn, (double)resid, (double)eps, (double)x[0]-1, (double)x[n-1]-1); for (i = 0; i < n; i++) { b[i] = -b[i]; } printf(" %f %f %f %f %f\n", (double)residn, (double)resid, (double)eps, (double)x[0]-1, (double)x[n-1]-1); dmxpy(n,b,n,lda,x,a); printf(" %f %f %f %f %f\n", (double)residn, (double)resid, (double)eps, (double)x[0]-1, (double)x[n-1]-1); resid = 0.0; normx = 0.0; for (i = 0; i < n; i++) { resid = (resid > fabs((double)b[i])) ? resid : fabs((double)b[i]); normx = (normx > fabs((double)x[i])) ? normx : fabs((double)x[i]); printf(" %f %f %f %f %f\n", (double)residn, (double)resid, (double)eps, (double)x[0]-1, (double)x[n-1]-1); } eps = epslon((REAL)ONE); printf(" %f %f %f %f %f\n", (double)residn, (double)resid, (double)eps, (double)x[0]-1, (double)x[n-1]-1); residn = resid/( n*norma*normx*eps ); //printf(" norm. resid resid machep"); //printf(" x[0]-1 x[n-1]-1\n"); printf(" %f %f %f %f %f\n", (double)residn, (double)resid, (double)eps, (double)x[0]-1, (double)x[n-1]-1); // fprintf(stderr," times are reported for matrices of order %5d\n",n); // fprintf(stderr," dgefa dgesl total kflops unit"); // fprintf(stderr," ratio\n"); time[2][0] = total; time[3][0] = ops/(1.0e3*total); time[4][0] = 2.0e3/time[3][0]; time[5][0] = total/cray; // fprintf(stderr," times for array with leading dimension of%5d\n",lda); print_time(0); matgen(a,lda,n,b,&norma); dgefa(a,lda,n,ipvt,&info); dgesl(a,lda,n,ipvt,b,0); matgen(a,lda,n,b,&norma); dgefa(a,lda,n,ipvt,&info); dgesl(a,lda,n,ipvt,b,0); for (i = 0; i < ntimes; i++) { matgen(a,lda,n,b,&norma); dgefa(a,lda,n,ipvt,&info); } for (i = 0; i < ntimes; i++) { dgesl(a,lda,n,ipvt,b,0); } print_time(1); print_time(2); print_time(3); matgen(aa,ldaa,n,b,&norma); dgefa(aa,ldaa,n,ipvt,&info); dgesl(aa,ldaa,n,ipvt,b,0); matgen(aa,ldaa,n,b,&norma); dgefa(aa,ldaa,n,ipvt,&info); dgesl(aa,ldaa,n,ipvt,b,0); matgen(aa,ldaa,n,b,&norma); dgefa(aa,ldaa,n,ipvt,&info); dgesl(aa,ldaa,n,ipvt,b,0); for (i = 0; i < ntimes; i++) { matgen(aa,ldaa,n,b,&norma); dgefa(aa,ldaa,n,ipvt,&info); } for (i = 0; i < ntimes; i++) { dgesl(aa,ldaa,n,ipvt,b,0); } /* the following code sequence implements the semantics of the Fortran intrinsics "nint(min(time[3][3],time[3][7]))" */ kf = (time[3][3] < time[3][7]) ? time[3][3] : time[3][7]; kf = (kf > ZERO) ? (kf + .5) : (kf - .5); if (fabs((double)kf) < ONE) kflops = 0; else { kflops = floor(fabs((double)kf)); if (kf < ZERO) kflops = -kflops; } // fprintf(stderr," times for array with leading dimension of%4d\n",ldaa); print_time(4); print_time(5); print_time(6); print_time(7); // fprintf(stderr,ROLLING);fprintf(stderr,PREC); // fprintf(stderr," Precision %5d Kflops ; %d Reps \n",kflops,ntimes); printf("End (ntimes=%d) %d\n", ntimes, n); #ifdef MICROBLAZE void exit(int); exit(0); #endif return(0); }
the_stack_data/22012444.c
/* adler32.c -- compute the Adler-32 checksum of a data stream * Copyright (C) 1995-1996 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* $Id: adler32.c,v 1.1.1.1 2000/11/06 19:54:01 mguthaus Exp $ */ #include "zlib.h" #define BASE 65521L /* largest prime smaller than 65536 */ #define NMAX 5552 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ #define DO1(buf,i) {s1 += buf[i]; s2 += s1;} #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); /* ========================================================================= */ uLong adler32(adler, buf, len) uLong adler; const Bytef *buf; uInt len; { unsigned long s1 = adler & 0xffff; unsigned long s2 = (adler >> 16) & 0xffff; int k; if (buf == Z_NULL) return 1L; while (len > 0) { k = len < NMAX ? len : NMAX; len -= k; while (k >= 16) { DO16(buf); buf += 16; k -= 16; } if (k != 0) do { s1 += *buf++; s2 += s1; } while (--k); s1 %= BASE; s2 %= BASE; } return (s2 << 16) | s1; }
the_stack_data/49704.c
#include <stdio.h> static struct sss{ long f; struct {char m;} snd; } sss; #define _offsetof(st,f) ((char *)&((st *) 16)->f - (char *) 16) int main (void) { printf ("+++Struct char inside struct starting with long:\n"); printf ("size=%d,align=%d\n", sizeof (sss), __alignof__ (sss)); printf ("offset-long=%d,offset-sss-char=%d,\nalign-long=%d,align-sss-char=%d\n", _offsetof (struct sss, f), _offsetof (struct sss, snd), __alignof__ (sss.f), __alignof__ (sss.snd)); return 0; }
the_stack_data/11076509.c
#include<stdio.h> void bub_sort(int a[],int n) { int i,j,temp; for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } } int main() { int n,i; printf("Enter number of elements to be inserted into the array : "); scanf("%d",&n); int a[n]; printf("\n Enter the elements : "); for(i=0;i<n;i++) { scanf("%d",&a[i]); } bub_sort(a,n); printf("\nArray elelments after sorting : "); for(i=0;i<n;i++) { printf("%d ",a[i]); } return 0; }
the_stack_data/168894154.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2008-2015 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <string.h> struct s { int a; int *b; }; struct ss { struct s a; struct s b; }; struct arraystruct { int y; struct s x[2]; }; struct ns { const char *null_str; int length; }; struct lazystring { const char *lazy_str; }; struct hint_error { int x; }; struct children_as_list { int x; }; #ifdef __cplusplus struct S : public s { int zs; }; struct SS { int zss; S s; }; struct SSS { SSS (int x, const S& r); int a; const S &b; }; SSS::SSS (int x, const S& r) : a(x), b(r) { } class VirtualTest { private: int value; public: VirtualTest () { value = 1; } }; class Vbase1 : public virtual VirtualTest { }; class Vbase2 : public virtual VirtualTest { }; class Vbase3 : public virtual VirtualTest { }; class Derived : public Vbase1, public Vbase2, public Vbase3 { private: int value; public: Derived () { value = 2; } }; class Fake { int sname; public: Fake (const int name = 0): sname (name) { } }; #endif struct substruct { int a; int b; }; struct outerstruct { struct substruct s; int x; }; struct outerstruct substruct_test (void) { struct outerstruct outer; outer.s.a = 0; outer.s.b = 0; outer.x = 0; outer.s.a = 3; /* MI outer breakpoint here */ return outer; } typedef struct string_repr { struct whybother { const char *contents; } whybother; } string; /* This lets us avoid malloc. */ int array[100]; int narray[10]; struct justchildren { int len; int *elements; }; typedef struct justchildren nostring_type; struct memory_error { const char *s; }; struct container { string name; int len; int *elements; }; typedef struct container zzz_type; string make_string (const char *s) { string result; result.whybother.contents = s; return result; } zzz_type make_container (const char *s) { zzz_type result; result.name = make_string (s); result.len = 0; result.elements = 0; return result; } void add_item (zzz_type *c, int val) { if (c->len == 0) c->elements = array; c->elements[c->len] = val; ++c->len; } void set_item(zzz_type *c, int i, int val) { if (i < c->len) c->elements[i] = val; } void init_s(struct s *s, int a) { s->a = a; s->b = &s->a; } void init_ss(struct ss *s, int a, int b) { init_s(&s->a, a); init_s(&s->b, b); } void do_nothing(void) { int c; c = 23; /* Another MI breakpoint */ } struct nullstr { char *s; }; struct string_repr string_1 = { { "one" } }; struct string_repr string_2 = { { "two" } }; static int eval_func (int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8) { return p1; } static void eval_sub (void) { struct eval_type_s { int x; } eval1 = { 1 }, eval2 = { 2 }, eval3 = { 3 }, eval4 = { 4 }, eval5 = { 5 }, eval6 = { 6 }, eval7 = { 7 }, eval8 = { 8 }, eval9 = { 9 }; eval1.x++; /* eval-break */ } static void bug_14741() { zzz_type c = make_container ("bug_14741"); add_item (&c, 71); set_item(&c, 0, 42); /* breakpoint bug 14741 */ set_item(&c, 0, 5); } int main () { struct ss ss; struct ss ssa[2]; struct arraystruct arraystruct; string x = make_string ("this is x"); zzz_type c = make_container ("container"); zzz_type c2 = make_container ("container2"); const struct string_repr cstring = { { "const string" } }; /* Clearing by being `static' could invoke an other GDB C++ bug. */ struct nullstr nullstr; nostring_type nstype, nstype2; struct memory_error me; struct ns ns, ns2; struct lazystring estring, estring2; struct hint_error hint_error; struct children_as_list children_as_list; nstype.elements = narray; nstype.len = 0; me.s = "blah"; init_ss(&ss, 1, 2); init_ss(ssa+0, 3, 4); init_ss(ssa+1, 5, 6); memset (&nullstr, 0, sizeof nullstr); arraystruct.y = 7; init_s (&arraystruct.x[0], 23); init_s (&arraystruct.x[1], 24); ns.null_str = "embedded\0null\0string"; ns.length = 20; /* Make a "corrupted" string. */ ns2.null_str = NULL; ns2.length = 20; estring.lazy_str = "embedded x\201\202\203\204" ; /* Incomplete UTF-8, but ok Latin-1. */ estring2.lazy_str = "embedded x\302"; #ifdef __cplusplus S cps; cps.zs = 7; init_s(&cps, 8); SS cpss; cpss.zss = 9; init_s(&cpss.s, 10); SS cpssa[2]; cpssa[0].zss = 11; init_s(&cpssa[0].s, 12); cpssa[1].zss = 13; init_s(&cpssa[1].s, 14); SSS sss(15, cps); SSS& ref (sss); Derived derived; Fake fake (42); #endif add_item (&c, 23); /* MI breakpoint here */ add_item (&c, 72); #ifdef MI add_item (&c, 1011); c.elements[0] = 1023; c.elements[0] = 2323; add_item (&c2, 2222); add_item (&c2, 3333); substruct_test (); do_nothing (); #endif nstype.elements[0] = 7; nstype.elements[1] = 42; nstype.len = 2; nstype2 = nstype; eval_sub (); bug_14741(); /* break to inspect struct and union */ return 0; }
the_stack_data/122014698.c
#include <stdio.h> #include <string.h> #define TAM 100 int main() { char string_primeiro[TAM + 1]; char string_segundo [TAM + 1]; printf ("Forneca um texto: "); fgets (string_primeiro, TAM, stdin); printf ("Forneca um texto: "); fgets (string_segundo, TAM, stdin); printf ("Resultado da comparacao: \n%s%s= %d", string_primeiro, string_segundo, strncmp(string_primeiro, string_segundo, TAM)); return 0; }
the_stack_data/154831308.c
/*** * This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License. * When used, please cite the following article(s): V. Mrazek, L. Sekanina, Z. Vasicek "Libraries of Approximate Circuits: Automated Design and Application in CNN Accelerators" IEEE Journal on Emerging and Selected Topics in Circuits and Systems, Vol 10, No 4, 2020 * This file contains a circuit from a sub-set of pareto optimal circuits with respect to the pwr and wce parameters ***/ // MAE% = 0.07 % // MAE = 1.4 // WCE% = 0.20 % // WCE = 4.0 // WCRE% = 100.00 % // EP% = 62.50 % // MRE% = 1.57 % // MSE = 4.0 // PDK45_PWR = 0.068 mW // PDK45_AREA = 187.3 um2 // PDK45_DELAY = 0.80 ns #include <stdint.h> #include <stdlib.h> uint64_t mul8x3u_0UB(const uint64_t A,const uint64_t B) { uint64_t dout_11, dout_14, dout_15, dout_16, dout_17, dout_18, dout_20, dout_21, dout_22, dout_23, dout_24, dout_25, dout_26, dout_34, dout_35, dout_36, dout_37, dout_38, dout_39, dout_40, dout_41, dout_42, dout_43, dout_44, dout_45, dout_46, dout_47, dout_48, dout_49, dout_50, dout_51, dout_52, dout_53, dout_54, dout_55, dout_56, dout_57, dout_58, dout_59, dout_60, dout_61, dout_62, dout_63, dout_64, dout_65, dout_66, dout_67, dout_68, dout_71, dout_72, dout_76, dout_77, dout_78, dout_79, dout_80, dout_81, dout_82, dout_83, dout_84, dout_85, dout_86, dout_87, dout_88, dout_89, dout_90, dout_91, dout_92, dout_93, dout_94, dout_95, dout_96, dout_97, dout_98, dout_99, dout_100, dout_101, dout_102, dout_103, dout_104, dout_105; uint64_t O; dout_11=((A >> 2)&1)&((B >> 0)&1); dout_14=((A >> 3)&1)&((B >> 0)&1); dout_15=((A >> 4)&1)&((B >> 0)&1); dout_16=((A >> 5)&1)&((B >> 0)&1); dout_17=((A >> 6)&1)&((B >> 0)&1); dout_18=((A >> 7)&1)&((B >> 0)&1); dout_20=((A >> 1)&1)&((B >> 1)&1); dout_21=((A >> 2)&1)&((B >> 1)&1); dout_22=((A >> 3)&1)&((B >> 1)&1); dout_23=((A >> 4)&1)&((B >> 1)&1); dout_24=((A >> 5)&1)&((B >> 1)&1); dout_25=((A >> 6)&1)&((B >> 1)&1); dout_26=((A >> 7)&1)&((B >> 1)&1); dout_34=dout_14^dout_21; dout_35=dout_14&dout_21; dout_36=dout_34&dout_20; dout_37=dout_34^dout_20; dout_38=dout_35|dout_36; dout_39=dout_15^dout_22; dout_40=dout_15&dout_22; dout_41=dout_39&dout_38; dout_42=dout_39^dout_38; dout_43=dout_40|dout_41; dout_44=dout_16^dout_23; dout_45=dout_16&dout_23; dout_46=dout_44&dout_43; dout_47=dout_44^dout_43; dout_48=dout_45|dout_46; dout_49=dout_17^dout_24; dout_50=dout_17&dout_24; dout_51=dout_49&dout_48; dout_52=dout_49^dout_48; dout_53=dout_50|dout_51; dout_54=dout_18^dout_25; dout_55=dout_18&dout_25; dout_56=dout_54&dout_53; dout_57=dout_54^dout_53; dout_58=dout_55|dout_56; dout_59=dout_58&((A >> 7)&1); dout_60=dout_58^dout_26; dout_61=((A >> 0)&1)&((B >> 2)&1); dout_62=((A >> 1)&1)&((B >> 2)&1); dout_63=((A >> 2)&1)&((B >> 2)&1); dout_64=((A >> 3)&1)&((B >> 2)&1); dout_65=((A >> 4)&1)&((B >> 2)&1); dout_66=((A >> 5)&1)&((B >> 2)&1); dout_67=((A >> 6)&1)&((B >> 2)&1); dout_68=((A >> 7)&1)&((B >> 2)&1); dout_71=dout_37^dout_62; dout_72=dout_37&dout_62; dout_76=dout_42^dout_63; dout_77=dout_42&dout_63; dout_78=dout_76&dout_72; dout_79=dout_76^dout_72; dout_80=dout_77|dout_78; dout_81=dout_47^dout_64; dout_82=dout_47&dout_64; dout_83=dout_81&dout_80; dout_84=dout_81^dout_80; dout_85=dout_82|dout_83; dout_86=dout_52^dout_65; dout_87=dout_52&dout_65; dout_88=dout_86&dout_85; dout_89=dout_86^dout_85; dout_90=dout_87|dout_88; dout_91=dout_57^dout_66; dout_92=dout_57&dout_66; dout_93=dout_91&dout_90; dout_94=dout_91^dout_90; dout_95=dout_92|dout_93; dout_96=dout_60^dout_67; dout_97=dout_60&dout_67; dout_98=dout_96&dout_95; dout_99=dout_96^dout_95; dout_100=dout_97|dout_98; dout_101=dout_59^dout_68; dout_102=dout_59&((B >> 2)&1); dout_103=((A >> 7)&1)&dout_100; dout_104=dout_101^dout_100; dout_105=dout_102|dout_103; O = 0; O |= (dout_11&1) << 0; O |= (dout_11&1) << 1; O |= (dout_61&1) << 2; O |= (dout_71&1) << 3; O |= (dout_79&1) << 4; O |= (dout_84&1) << 5; O |= (dout_89&1) << 6; O |= (dout_94&1) << 7; O |= (dout_99&1) << 8; O |= (dout_104&1) << 9; O |= (dout_105&1) << 10; return O; }
the_stack_data/92324883.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> //fumction declaration int minimum(int no1, int no2); int maximum(int no1, int no2); int multiply(int no1, int no2); int main() { int no1, no2; printf("Enter a value for no 1 : "); scanf("%d", &no1); printf("Enter a value for no 2 : "); scanf("%d", &no2); printf("%d ", minimum(no1, no2)); printf("%d ", maximum(no1, no2)); printf("%d ", multiply(no1, no2)); return 0; } int minimum(int no1, int no2) { return (no1 < no2) ? no1:no2; } int maximum(int no1, int no2) { return (no1 > no2) ? no1:no2; } int multiply(int no1, int no2) { return no1*no2; }
the_stack_data/46712.c
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef int vektor[10]; /* struct { char name[21]; int age; } student1, student2; */ typedef struct { char name[21]; int age; } STUDENT; float average_age(STUDENT s1, STUDENT s2){ float average; average = (s1.age + s2.age) / 2.; return average; } STUDENT older(STUDENT s1, STUDENT s2){ if (s1.age > s2.age) return s1; else return s2; } typedef struct{ char type[21]; int branches; int age; float height; } TTree; int branches_amount(TTree s1, TTree s2) { int amount_of_branches = s1.branches + s2.branches; return amount_of_branches; } int main() { vektor u,v; STUDENT s1, s2; // dotted notation s1.age = 16; strcpy(s1.name,"Karel"); scanf("%20s", &s2.name); s2.age = s1.age + 1; STUDENT s3 = s1; // it is possible to work with the whole notation // calling function printf("Average age of student is %f\n", average_age(s1, s2)); // calling function s3 = older(s1, s2); printf("Older student is %s\n", s3.name); TTree se1={"dub", 150, 5, 3.7}; TTree se2; printf("Enter type of tree: "); scanf("%20s", &se2.type); printf("Enter amount of branches: "); scanf("%d", &se2.branches); printf("Enter age of tree: "); scanf("%d", &se2.age); printf("Enter height of tree: "); scanf("%f", &se2.height); // calling function printf("The amount of branches is %d\n", branches_amount(se1, se2)); return 0; }
the_stack_data/187643235.c
/* Generated by re2c */ #line 1 "simple.re" #define NULL ((char*) 0) char *scan(char *p){ char *q; #define YYCTYPE char #define YYCURSOR p #define YYLIMIT p #define YYMARKER q #define YYFILL(n) #line 13 "<stdout>" { YYCTYPE yych; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy2; default: goto yy4; } yy2: ++YYCURSOR; yych = *YYCURSOR; goto yy7; yy3: #line 10 "simple.re" {return YYCURSOR;} #line 39 "<stdout>" yy4: ++YYCURSOR; #line 11 "simple.re" {return NULL;} #line 44 "<stdout>" yy6: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; yy7: switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy6; default: goto yy3; } } #line 12 "simple.re" }
the_stack_data/61054.c
// Example for testing part of CS333 P2. // This is by NO MEANS a complete test. #ifdef CS333_P2 #include "types.h" #include "user.h" static void uidTest(uint nval) { uint uid = getuid(); printf(1, "Current UID is: %d\n", uid); printf(1, "Setting UID to %d\n", nval); if (setuid(nval) < 0) printf(2, "Error. Invalid UID: %d\n", nval); uid = getuid(); printf(1, "Current UID is: %d\n", uid); sleep(5 * TPS); // now type control-p } static void gidTest(uint nval) { uint gid = getgid(); printf(1, "Current GID is: %d\n", gid); printf(1, "Setting GID to %d\n", nval); if (setgid(nval) < 0) printf(2, "Error. Invalid GID: %d\n", nval); setgid(nval); gid = getgid(); printf(1, "Current GID is: %d\n", gid); sleep(5 * TPS); // now type control-p } static void forkTest(uint nval) { uint uid, gid; int pid; printf(1, "Setting UID to %d and GID to %d before fork(). Value" " should be inherited\n", nval, nval); if (setuid(nval) < 0) printf(2, "Error. Invalid UID: %d\n", nval); if (setgid(nval) < 0) printf(2, "Error. Invalid UID: %d\n", nval); printf(1, "Before fork(), UID = %d, GID = %d\n", getuid(), getgid()); pid = fork(); if (pid == 0) { // child uid = getuid(); gid = getgid(); printf(1, "Child: UID is: %d, GID is: %d\n", uid, gid); sleep(5 * TPS); // now type control-p exit(); } else //sleep(10 * TPS); // wait for child to exit before proceeding wait(); } static void invalidTest(uint nval) { printf(1, "Setting UID to %d. This test should FAIL\n", nval); if (setuid(nval) < 0) printf(1, "SUCCESS! The setuid sytem call indicated failure\n"); else printf(2, "FAILURE! The setuid system call indicates success\n"); printf(1, "Setting GID to %d. This test should FAIL\n", nval); if (setgid(nval) < 0) printf(1, "SUCCESS! The setgid sytem call indicated failure\n"); else printf(2, "FAILURE! The setgid system call indicates success\n"); printf(1, "Setting UID to %d. This test should FAIL\n", -1); if (setuid(-1) < 0) printf(1, "SUCCESS! The setuid sytem call indicated failure\n"); else printf(2, "FAILURE! The setuid system call indicates success\n"); printf(1, "Setting GID to %d. This test should FAIL\n", -1); if (setgid(-1) < 0) printf(1, "SUCCESS! The setgid sytem call indicated failure\n"); else printf(2, "FAILURE! The setgid system call indicates success\n"); } static int testuidgid(void) { uint nval, ppid; // get/set uid test nval = 100; uidTest(nval); // get/set gid test nval = 200; gidTest(nval); // getppid test ppid = getppid(); printf(1, "My parent process is: %d\n", ppid); // fork tests to demonstrate UID/GID inheritance nval = 111; forkTest(nval); // tests for invalid values for uid and gid nval = 32800; // 32767 is max value invalidTest(nval); printf(1, "Done!\n"); return 0; } int main() { testuidgid(); exit(); } #endif
the_stack_data/211080244.c
// general protection fault in cbs_destroy // https://syzkaller.appspot.com/bug?id=8fdd21f601550b6e5e43dec7d4a96955879a5aac // status:open // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <endian.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> uint64_t r[2] = {0xffffffffffffffff, 0xffffffffffffffff}; int main(void) { syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 3ul, 0x32ul, -1, 0); intptr_t res = 0; res = syscall(__NR_socket, 0x10ul, 3ul, 0ul); if (res != -1) r[0] = res; res = syscall(__NR_socket, 2ul, 2ul, 0x88ul); if (res != -1) r[1] = res; *(uint64_t*)0x20000240 = 0; *(uint32_t*)0x20000248 = 0x1c6; *(uint64_t*)0x20000250 = 0x20000080; *(uint64_t*)0x20000080 = 0x20000880; memcpy((void*)0x20000880, "\x48\x00\x00\x00\x24\x00\x07\x05\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00", 20); *(uint32_t*)0x20000894 = r[1]; memcpy((void*)0x20000898, "\x00\x00\x00\x11\xff\xff\xff\xff\x00\x00\x00\x00\x08\x00\x01\x00\x63" "\x62\x73\x00\x1c\x00\x02\x00\x19\x00\x01\x00\x00\x00\x00\x00\x07\x00" "\x00\x00\x05\x00\x00\x00\x00\xfe\xff\x00\x00\x00\x00\x00\x00\x00\x00" "\xa2\xe3\x87\xd6\x3e\x72\x17\x59\x05\x78\x00\x3f\x91\x16\x0e\x12\xe5" "\xca\xb3\x8e\xa6\xd1\x4b\x05\xd0\xdf\x91\x5a\x3f\x95\x8c\x8b\x0b\x00" "\x00\x30", 87); *(uint64_t*)0x20000088 = 0x48; *(uint64_t*)0x20000258 = 1; *(uint64_t*)0x20000260 = 0; *(uint64_t*)0x20000268 = 0; *(uint32_t*)0x20000270 = 0x65580000; syscall(__NR_sendmsg, r[0], 0x20000240ul, 0ul); return 0; }
the_stack_data/154830080.c
#include <stdio.h> #include <ctype.h> #include <stdbool.h> #define STOP '|' int main(void) { char c; char prev; long n_chars = 0L; int n_lines = 0; int n_words = 0; int p_lines = 0; bool inword = false; printf("Enter text to be analyzed (| to terminate): \n"); prev = '\n'; while((c = getchar()) != STOP) { n_chars++; if(c == '\n') n_lines++; if(!isspace(c) && !inword) { inword = true; n_words++; } if(isspace(c) && inword) inword = false; prev = c; } if(prev != '\n') p_lines = 1; printf("characters = %ld, words = %d, lines = %d, \n",n_chars, n_words, n_lines); printf("partial lines = %d\n", p_lines); return 0; }
the_stack_data/122015510.c
void foo(int x) { int arr[x]; }
the_stack_data/115766132.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 num1, int num2) { if (num1 > num2) { return num2; } else { return num1; } } int maximum(int num1, int num2) { if (num1 > num2) { return num1; } else { return num2; } } int multiply(int num1, int num2) { return num1 * num2; }
the_stack_data/242329971.c
#include "math.h" double cos(double n) { return 0.0; }
the_stack_data/667166.c
#include <unistd.h> #include <fcntl.h> #include <stdio.h> int main (int argc, char** argv) { int fd = open(".", 0, 0); int status; status = fsync(fd); printf("fsync exited with status code %d\n", status); close(fd); return 0; }
the_stack_data/81512.c
// TODO: test properly #include <stdint.h> uintptr_t __StackPoint = 0; //void create_StackPoint(){}
the_stack_data/1759.c
/* * @lc app=leetcode id=5 lang=c * * [5] Longest Palindromic Substring * * https://leetcode.com/problems/longest-palindromic-substring/description/ * * algorithms * Medium (27.31%) * Likes: 3747 * Dislikes: 356 * Total Accepted: 577.7K * Total Submissions: 2.1M * Testcase Example: '"babad"' * * Given a string s, find the longest palindromic substring in s. You may * assume that the maximum length of s is 1000. * * Example 1: * * * Input: "babad" * Output: "bab" * Note: "aba" is also a valid answer. * * * Example 2: * * * Input: "cbbd" * Output: "bb" * * */ #include <stdbool.h> #include <string.h> #include <stdlib.h> #include <stdio.h> char *longestPalindrome(char *s) { int len = strlen(s); if(len == 0) { return ""; } if(len == 1) { return s; } bool(*isPalindrome)[len] = (bool(*)[len])malloc(len * len * sizeof(bool)); // 从 i 到 j 是回文 memset(isPalindrome, false, len * len * sizeof(bool)); int left = 0; int right = 0; int maxLen = 1; for (int j = 0; j < len; j++) { isPalindrome[j][j] = 1; for (int i = 0; i < j; i++) { if (j == i + 1 && s[i] == s[j]) { isPalindrome[i][j] = true; if (j - i + 1 > maxLen) { left = i; right = j; maxLen = j - i + 1; } } else if (j > i + 1 && s[i] == s[j] && isPalindrome[i + 1][j - 1]) { isPalindrome[i][j] = true; if (j - i + 1 > maxLen) { left = i; right = j; maxLen = j - i + 1; } } } } char *ret = malloc((maxLen + 1) * sizeof(char)); memcpy(ret, s + left, maxLen * sizeof(char)); ret[maxLen] = '\0'; return ret; }
the_stack_data/215768321.c
/* Author : Arnob Mahmud mail : [email protected] */ #include <stdio.h> int main(int argc, char const *argv[]) { int m, x, bnm; printf(" mx "); for (int i = 0; i <= 10; i++) { printf(" %4d ", i); } printf("\n----------------------------------------------------------------------\n"); for (int m = 0; m <= 10; m++) { printf("%4d", m); for (int x = 0; x <= m; x++) { if (x == 0) { bnm = 1; } else { bnm = bnm * (m - x + 1) / x; } printf(" %4d ", bnm); } printf("\n"); } printf("----------------------------------------------------------------------\n"); return 0; }
the_stack_data/76701362.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern float strtof(char const *str , char const *endptr ) ; extern void signal(int sig , void *func ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned char input[1] , unsigned char output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; void megaInit(void) { { } } void RandomFunc(unsigned char input[1] , unsigned char output[1] ) { unsigned char state[1] ; unsigned char local1 ; { state[0UL] = (input[0UL] + 51238316UL) + (unsigned char)234; local1 = 0UL; while (local1 < (unsigned char)0) { if (state[0UL] < local1) { state[local1] = state[0UL] + state[0UL]; } else { state[0UL] += state[0UL]; } if (state[0UL] != local1) { state[0UL] += state[local1]; } else { state[local1] += state[local1]; } local1 += 2UL; } output[0UL] = (state[0UL] + 119333056UL) * (unsigned char)203; } } int main(int argc , char *argv[] ) { unsigned char input[1] ; unsigned char output[1] ; int randomFuns_i5 ; unsigned char randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = (unsigned char )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 101) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } }
the_stack_data/18887299.c
/* --------------------------- */ // Laurens van der Sluis // 1703647 // Huib Aldewereld // Week 1 opdracht 3 /* --------------------------- */ #include <stdio.h> int main(){ int n; printf("Voer een getal in tussen 1 en 80: "); while(!scanf("%d", &n) || !(0<n && n<81)){ printf("Ongeldige invoer\n"); while(getchar() != '\n'); printf("Voer een getal in.\n"); } for (int i=0; i<n; i++){ for (int a=0; a<=i; a++){ printf("*"); } printf("\n"); } int i = n-1; while (i!=0) { int a = i; while (a!=0) { printf("*"); a--; } printf("\n"); i--; } return 0; }
the_stack_data/54826306.c
// %brief% C language template in non-OS. #include <stdio.h> void main() { }
the_stack_data/150067.c
#include "stdio.h" int one_appear_count_by_binary(int num){ int count = 0; while(num !=0 ){ num &= num-1; count++; } return count; } int main(int argc, char const *argv[]) { int test = 10; printf("%d\n", one_appear_count_by_binary(test)); printf("%d\n", one_appear_count_by_binary(32+1)); return 0; }
the_stack_data/125141786.c
#include <stdio.h> #include <string.h> int fac(int n) { int i, sum=1; for (i=2; i<=n; i++) sum=sum*i; return sum; } void put(char str[11][20], char s[11][20]) { int i, j; for (i=0; i<11; i++) { for (j=0; j<20; j++) s[i][j]=str[i][j]; } return; } void cut(int n, char s[11][20]) { int i, j, step, maxstep=0, k, flag=0, len; char tmp[11][20]; put(s, tmp); for (i=0; i<n; i++) if (strlen(s[i])>maxstep) maxstep=strlen(s[i]); for (step=maxstep-1; step>0; step--) { for (k=0; k<n; k++) { len=strlen(tmp[k]); for (i=0; i<step; i++) { if (step<len && tmp[k][len-step+i]==tmp[k+1][i]) flag=1; else { flag=0; break; } } if (flag==1) { for (j=0; j<step; j++) s[k][len-step+j]=0; flag=0; } } } return; } void unite(char *sup, int n, char s[][20]) { int i, k, j; for (i=0, k=0, j=0; i<201 && k<n; i++, j++) { if (j>=strlen(s[k])) { j=0; k++; } sup[i] = s[k][j]; } return; } void swap(char *a, char *b) { char temp[20], i; for (i=0; i<20; i++) { temp[i]=a[i]; a[i]=b[i]; b[i]=temp[i]; } return; } int main() { int n, i, j, min=0, len; char str[11][20]={{0}}, sup[201]={0}, s[11][20]={{0}}; scanf("%d\n",&n); for (i=0; i<n; i++) gets(str[i]); put(str, s); cut(n, s); unite(sup, n, s); min=strlen(sup); memset(sup, 0, 201); put(str, s); if (n>=10) n=n-2; /* Иначе алгоритм при n=10 работает больше 2 секунд, т.к. работает за n! (у меня при n=9 работает за 1,4 секунды, на сервере в 2 секунды не укладывается) */ for (j=1, i=0; j<fac(n); j++, i++) { if (i>=n) i=0; if (i==n-1) swap(str[i], str[0]); else swap(str[i], str[i+1]); put(str, s); cut(n, s); unite(sup, n, s); len=strlen(sup); if (len<min) min=len; memset(sup, 0, 201); } printf("%d\n", min); return 0; }