file
stringlengths
18
26
data
stringlengths
2
1.05M
the_stack_data/26700861.c
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #define AROW 3 #define ACOL 16 #define MAX_VALUE 10 int main(int argc, char *argv[]) { int a[AROW][ACOL]; int b[ACOL]; int c[AROW]; int i,j; struct timeval start, end; srand(time(NULL)); for (i = 0; i < AROW; i++) { for (j = 0; j < ACOL; j++) { if (i == 0) b[j] = rand() % MAX_VALUE; a[i][j] = rand() % MAX_VALUE; } } for (i = 0; i < AROW; i++) { c[i] = 0; } gettimeofday(&start, NULL); #pragma omp parallel for for (i = 0; i < AROW; i++) { for (j = 0; j < ACOL; j++) { c[i] += a[i][j] * b[j]; } } gettimeofday(&end, NULL); for (i = 0; i < AROW; i++) { printf("%3d ", c[i]); } printf("\n"); long duration_ms = ((end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000.0); printf("Time: %ld ms\n", duration_ms); return 0; }
the_stack_data/25784.c
/* (c) copyright 1988 by the Vrije Universiteit, Amsterdam, The Netherlands. See the copyright notice in the ACK home directory, in the file "Copyright". */ /* Module: Mapping of Unix signals to EM traps (only when not using the MON instruction) Author: Ceriel J.H. Jacobs Version: $Header: /cvsup/minix/src/lib/libm2/sigtrp.c,v 1.1.1.1 2005/04/21 14:56:22 beng Exp $ */ #if !defined(__em22) && !defined(__em24) && !defined(__em44) #define EM_trap(n) TRP(n) /* define to whatever is needed to cause the trap */ #include <signal.h> #include <errno.h> int __signo; static int __traps[] = { -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, }; static void __ctchsig(signo) { signal(signo,__ctchsig); #ifdef __BSD4_2 sigsetmask(sigblock(0) & ~(1<<(signo - 1))); #endif __signo = signo; EM_trap(__traps[signo]); } int sigtrp(trapno, signo) { /* Let Unix signal signo cause EM trap trapno to occur. If trapno = -2, restore default, If trapno = -3, ignore. Return old trapnumber. Careful, this could be -2 or -3; But return value of -1 indicates failure, with error number in errno. */ extern int errno; void (*ctch)() = __ctchsig; void (*oldctch)(); int oldtrap; if (signo <= 0 || signo >= sizeof(__traps)/sizeof(__traps[0])) { errno = EINVAL; return -1; } if (trapno == -3) ctch = SIG_IGN; else if (trapno == -2) ctch = SIG_DFL; else if (trapno >= 0 && trapno <= 252) ; else { errno = EINVAL; return -1; } oldtrap = __traps[signo]; if ((oldctch = signal(signo, ctch)) == (void (*)())-1) /* errno set by signal */ return -1; else if (oldctch == SIG_IGN) { signal(signo, SIG_IGN); } else __traps[signo] = trapno; return oldtrap; } #endif
the_stack_data/181394088.c
void func_2v(float* in, float* out, unsigned n){ unsigned i; #pragma omp target teams distribute parallel for map(to: in[0:n]) map(from: out[0:n]) for(i=0; i<n; ++i){ out[i]=in[i]/2; } }
the_stack_data/182954230.c
#include <stdio.h> #include <stdint.h> #include <string.h> int lengthOfLongestSubstring(char * s){ int start_position = 0, cur_position = 1, position_diff = 0, max_position_diff = 0; int i = 0; int flag = 0; if (!s[0]){ return 0; } if(!s[1]){ return 1; } // >= 2 while(s[cur_position]){ flag = 0; position_diff = cur_position - start_position; for(i = 0; i < position_diff; i++){ if (s[cur_position] == s[start_position + i]){ if(position_diff > max_position_diff){ max_position_diff = position_diff; } flag = 1; start_position = start_position + i + 1; break; } } if(flag == 0){ position_diff++; } cur_position++; } if(position_diff > max_position_diff){ max_position_diff = position_diff; } return max_position_diff; } static char* input_string = "bbbb"; static int output_length = 1; int main(int argc, char const *argv[]) { /* code */ if (lengthOfLongestSubstring(input_string) == output_length){ printf("Tiny test pass\n"); }else{ printf("Trigger error\n"); } return 0; }
the_stack_data/20450521.c
#include <stdio.h> #include <stdbool.h> int min2(int a, int b) { return a < b ? a : b; } int maximalSquare(char** matrix, int matrixSize, int* matrixColSize) { if (matrixSize == 0) return 0; int rows = matrixSize; int cols = matrixColSize[0]; int maxSize = 0; for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { int squareSize = min2(rows-row, cols-col); for (int size = 1; size <= squareSize; size++) { // 检查在 size * size 的范围内是否没有 0 bool noZero = true; for (int dr = 0; dr < size; dr++) { for (int dc = 0; dc < size; dc++) { if (matrix[row+dr][col+dc] == '0') { noZero = false; } } } if (noZero && maxSize < size) { maxSize = size; } } } } return maxSize * maxSize; } int main() { char arr1[] = "10100"; char arr2[] = "10111"; char arr3[] = "11111"; char arr4[] = "10010"; char* matrix[] = {arr1, arr2, arr3, arr4}; int matrixSize = 4; int matrixColSize[4] = {5, 5, 5, 5}; int result = maximalSquare(matrix, matrixSize, matrixColSize); printf(">>> result = %d\n", result); return 0; }
the_stack_data/237643259.c
#include<stdio.h> int main(int argc, char const *argv[]){ int a, b; printf("Enter two numbers: "); scanf("%d %d",&a,&b); printf("\nSum of the numbers (A + B) = %d",a+b); return 0; }
the_stack_data/147524.c
/**** Copyright (C) 1996 McGill University. Copyright (C) 1996 McCAT System Group. Copyright (C) 1996 ACAPS Benchmark Administrator [email protected] This program is free software; you can redistribute it and/or modify it provided this copyright notice is maintained. 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. ****/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define DBL_EPSILON 0x1p-52 void *allocvector(size_t size) { void *V; if ( (V = (void *) malloc((size_t) size)) == NULL ) { fprintf(stderr, "Error: couldn't allocate V in allocvector.\n"); exit(2); } memset(V,0,size); return V; } void dallocvector(int n, double **V) { *V = (double *) allocvector((size_t) n*sizeof(double)); } #define FUDGE (double) 1.01 int sturm(int n, double c[], double b[], double beta[], double x) /************************************************************************** Purpose: ------------ Calculates the sturm sequence given by q_1(x) = c[1] - x q_i(x) = (c[i] - x) - b[i]*b[i] / q_{i-1}(x) and returns a(x) = the number of negative q_i. a(x) gives the number of eigenvalues smaller than x of the symmetric tridiagonal matrix with diagonal c[0],c[1],...,c[n-1] and off-diagonal elements b[1],b[2],...,b[n-1]. Input parameters: ------------------------ n : The order of the matrix. c[0]..c[n-1] : An n x 1 array giving the diagonal elements of the tridiagonal matrix. b[1]..b[n-1] : An n x 1 array giving the sub-diagonal elements. b[0] may be arbitrary but is replaced by zero in the procedure. beta[1]..beta[n-1] : An n x 1 array giving the square of the sub-diagonal elements, i.e. beta[i] = b[i]*b[i]. beta[0] may be arbitrary but is replaced by zero in the procedure. x : Argument for the Sturm sequence. Returns: ------------------------ integer a = Number of eigenvalues of the matrix smaller than x. Notes: ------------------------ On SGI PowerChallenge this function should be compiled with option "-O3 -OPT:IEEE_arithmetic=3" in order to activate the optimization mentioned in the code below. **********************************************************************/ { int i; int a; double q; a = 0; q = 1.0; for(i=0; i<n; i++) { #ifndef TESTFIRST if (q != 0.0) { #ifndef RECIPROCAL q = (c[i] - x) - beta[i]/q; #else /* A potentially NUMERICALLY DANGEROUS optimizations is used here. * The previous statement should read: * q = (c[i] - x) - beta[i]/q * But computing the reciprocal might help on some architectures * that have multiply-add and/or reciprocal instuctions. */ iq = 1.0/q; q = (c[i] - x) - beta[i]*iq; #endif } else { q = (c[i] - x) - fabs(b[i])/DBL_EPSILON; } if (q < 0) a = a + 1; } #else if (q < 0) { a = a + 1; #ifndef RECIPROCAL q = (c[i] - x) - beta[i]/q; #else /* A potentially NUMERICALLY DANGEROUS optimizations is used here. * The previous statement should read: * q = (c[i] - x) - beta[i]/q * But computing the reciprocal might help on some architectures * that have multiply-add and/or reciprocal instuctions. */ iq = 1.0/q; q = (c[i] - x) - beta[i]*iq; #endif } else if (q > 0.0) { #ifndef RECIPROCAL q = (c[i] - x) - beta[i]/q; #else /* A potentially NUMERICALLY DANGEROUS optimizations is used here. * The previous statement should read: * q = (c[i] - x) - beta[i]/q * But computing the reciprocal might help on some architectures * that have multiply-add and/or reciprocal instuctions. */ iq = 1.0/q; q = (c[i] - x) - beta[i]*iq; #endif } else { q = (c[i] - x) - fabs(b[i])/DBL_EPSILON; } } if (q < 0) a = a + 1; #endif return a; } void dbisect(double c[], double b[], double beta[], int n, int m1, int m2, double eps1, double *eps2, int *z, double x[]) /************************************************************************** Purpose: ------------ Calculates eigenvalues lambda_{m1}, lambda_{m1+1},...,lambda_{m2} of a symmetric tridiagonal matrix with diagonal c[0],c[1],...,c[n-1] and off-diagonal elements b[1],b[2],...,b[n-1] by the method of bisection, using Sturm sequences. Input parameters: ------------------------ c[0]..c[n-1] : An n x 1 array giving the diagonal elements of the tridiagonal matrix. b[1]..b[n-1] : An n x 1 array giving the sub-diagonal elements. b[0] may be arbitrary but is replaced by zero in the procedure. beta[1]..beta[n-1] : An n x 1 array giving the square of the sub-diagonal elements, i.e. beta[i] = b[i]*b[i]. beta[0] may be arbitrary but is replaced by zero in the procedure. n : The order of the matrix. m1, m2 : The eigenvalues lambda_{m1}, lambda_{m1+1},...,lambda_{m2} are calculated (NB! lambda_1 is the smallest eigenvalue). m1 <= m2must hold otherwise no eigenvalues are computed. returned in x[m1-1],x[m1],...,x[m2-1] eps1 : a quantity that affects the precision to which eigenvalues are computed. The bisection is continued as long as x_high - x_low > 2*DBL_EPSILON(|x_low| + |x_high|) + eps1 (1) When (1) is no longer satisfied, (x_high + x_low)/2 gives the current eigenvalue lambda_k. Here DBL_EPSILON (constant) is the machine accuracy, i.e. the smallest number such that (1 + DBL_EPSILON) > 1. Output parameters: ------------------------ eps2 : The overall bound for the error in any eigenvalue. z : The total number of iterations to find all eigenvalues. x : The array x[m1],x[m1+1],...,x[m2] contains the computed eigenvalues. **********************************************************************/ { int i; double h,xmin,xmax; beta[0] = b[0] = 0.0; /* calculate Gerschgorin interval */ xmin = c[n-1] - FUDGE*fabs(b[n-1]); xmax = c[n-1] + FUDGE*fabs(b[n-1]); for(i=n-2; i>=0; i--) { h = FUDGE*(fabs(b[i]) + fabs(b[i+1])); if (c[i] + h > xmax) xmax = c[i] + h; if (c[i] - h < xmin) xmin = c[i] - h; } /* printf("xmax = %lf xmin = %lf\n",xmax,xmin); */ /* estimate precision of calculated eigenvalues */ *eps2 = DBL_EPSILON * (xmin + xmax > 0 ? xmax : -xmin); if (eps1 <= 0) eps1 = *eps2; *eps2 = 0.5 * eps1 + 7 * *eps2; { int a,k; double x1,xu,x0; double *wu; if( (wu = (double *) calloc(n+1,sizeof(double))) == NULL) { fputs("bisect: Couldn't allocate memory for wu",stderr); exit(1); } /* Start bisection process */ x0 = xmax; for(i=m2; i >= m1; i--) { x[i] = xmax; wu[i] = xmin; } *z = 0; /* loop for the k-th eigenvalue */ for(k=m2; k>=m1; k--) { xu = xmin; for(i=k; i>=m1; i--) { if(xu < wu[i]) { xu = wu[i]; break; } } if (x0 > x[k]) x0 = x[k]; x1 = (xu + x0)/2; while ( x0-xu > 2*DBL_EPSILON*(fabs(xu)+fabs(x0))+eps1 ) { *z = *z + 1; /* Sturms Sequence */ a = sturm(n,c,b,beta,x1); /* Bisection step */ if (a < k) { if (a < m1) xu = wu[m1] = x1; else { xu = wu[a+1] = x1; if (x[a] > x1) x[a] = x1; } } else { x0 = x1; } x1 = (xu + x0)/2; } x[k] = (xu + x0)/2; } free(wu); } } void test_matrix(int n, double *C, double *B) /* Symmetric tridiagonal matrix with diagonal c_i = i^4, i = (1,2,...,n) and off-diagonal elements b_i = i-1, i = (2,3,...n). It is possible to determine small eigenvalues of this matrix, with the same relative error as for the large ones. */ { int i; for(i=0; i<n; i++) { B[i] = (double) i; C[i] = (double ) (i+1)*(i+1); C[i] = C[i] * C[i]; } } int main(int argc,char *argv[]) { int rep,n,k,i,j; double eps,eps2; double *D,*E,*beta,*S; rep = 1; n = 500; eps = 2.2204460492503131E-16; dallocvector(n,&D); dallocvector(n,&E); dallocvector(n,&beta); dallocvector(n,&S); for (j=0; j<rep; j++) { test_matrix(n,D,E); for (i=0; i<n; i++) { beta[i] = E[i] * E[i]; S[i] = 0.0; } E[0] = beta[0] = 0; dbisect(D,E,beta,n,1,n,eps,&eps2,&k,&S[-1]); } for(i=1; i<20; i++) printf("%5d %.5e\n",i+1,S[i]); printf("eps2 = %.5e, k = %d\n",eps2,k); return 0; }
the_stack_data/160262.c
/* ABC049C - Daydream */ #include <stdio.h> #include <stdbool.h> #include <stdint.h> #include <string.h> bool walk(const char *s, const size_t length, size_t offset) { static const char *words[4] = {"dream", "dreamer", "erase", "eraser"}; if (length == offset) return true; else if (length < offset) return false; else { for (int32_t i = 0; i < 4; ++i) { size_t len = strlen(words[i]); if (strncmp(words[i], &s[offset], len) == 0) { if (walk(s, length, offset + len)) return true; } } return false; } } bool solver(char *s) { return walk(s, strlen(s), 0); } int main() { static char s[100001]; gets(s); printf("%s\n", solver(s) ? "YES" : "NO"); return 0; }
the_stack_data/111079052.c
typedef int ptrdiff_t; typedef unsigned int size_t; typedef unsigned int wchar_t; typedef struct { long long __max_align_ll __attribute__((__aligned__(__alignof__(long long)))); long double __max_align_ld __attribute__((__aligned__(__alignof__(long double)))); } max_align_t; typedef signed char __int8_t; typedef unsigned char __uint8_t; typedef short int __int16_t; typedef short unsigned int __uint16_t; typedef long int __int32_t; typedef long unsigned int __uint32_t; typedef long long int __int64_t; typedef long long unsigned int __uint64_t; typedef signed char __int_least8_t; typedef unsigned char __uint_least8_t; typedef short int __int_least16_t; typedef short unsigned int __uint_least16_t; typedef long int __int_least32_t; typedef long unsigned int __uint_least32_t; typedef long long int __int_least64_t; typedef long long unsigned int __uint_least64_t; typedef int __intptr_t; typedef unsigned int __uintptr_t; typedef __int8_t int8_t ; typedef __uint8_t uint8_t ; typedef __int16_t int16_t ; typedef __uint16_t uint16_t ; typedef __int32_t int32_t ; typedef __uint32_t uint32_t ; typedef __int64_t int64_t ; typedef __uint64_t uint64_t ; typedef __intptr_t intptr_t; typedef __uintptr_t uintptr_t; typedef __int_least8_t int_least8_t; typedef __uint_least8_t uint_least8_t; typedef __int_least16_t int_least16_t; typedef __uint_least16_t uint_least16_t; typedef __int_least32_t int_least32_t; typedef __uint_least32_t uint_least32_t; typedef __int_least64_t int_least64_t; typedef __uint_least64_t uint_least64_t; typedef int int_fast8_t; typedef unsigned int uint_fast8_t; typedef int int_fast16_t; typedef unsigned int uint_fast16_t; typedef int int_fast32_t; typedef unsigned int uint_fast32_t; typedef long long int int_fast64_t; typedef long long unsigned int uint_fast64_t; typedef long long int intmax_t; typedef long long unsigned int uintmax_t; typedef enum { Reset_IRQn = -15, NonMaskableInt_IRQn = -14, HardFault_IRQn = -13, MemoryManagement_IRQn = -12, BusFault_IRQn = -11, UsageFault_IRQn = -10, SVCall_IRQn = -5, DebugMonitor_IRQn = -4, PendSV_IRQn = -2, SysTick_IRQn = -1, POWER_CLOCK_IRQn = 0, RADIO_IRQn = 1, UARTE0_UART0_IRQn = 2, SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQn= 3, SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQn= 4, NFCT_IRQn = 5, GPIOTE_IRQn = 6, SAADC_IRQn = 7, TIMER0_IRQn = 8, TIMER1_IRQn = 9, TIMER2_IRQn = 10, RTC0_IRQn = 11, TEMP_IRQn = 12, RNG_IRQn = 13, ECB_IRQn = 14, CCM_AAR_IRQn = 15, WDT_IRQn = 16, RTC1_IRQn = 17, QDEC_IRQn = 18, COMP_LPCOMP_IRQn = 19, SWI0_EGU0_IRQn = 20, SWI1_EGU1_IRQn = 21, SWI2_EGU2_IRQn = 22, SWI3_EGU3_IRQn = 23, SWI4_EGU4_IRQn = 24, SWI5_EGU5_IRQn = 25, TIMER3_IRQn = 26, TIMER4_IRQn = 27, PWM0_IRQn = 28, PDM_IRQn = 29, MWU_IRQn = 32, PWM1_IRQn = 33, PWM2_IRQn = 34, SPIM2_SPIS2_SPI2_IRQn = 35, RTC2_IRQn = 36, I2S_IRQn = 37, FPU_IRQn = 38, USBD_IRQn = 39, UARTE1_IRQn = 40, QSPI_IRQn = 41, CRYPTOCELL_IRQn = 42, PWM3_IRQn = 45, SPIM3_IRQn = 47 } IRQn_Type; __attribute__( ( always_inline ) ) static inline void __enable_irq(void) { __asm volatile ("cpsie i" : : : "memory"); } __attribute__( ( always_inline ) ) static inline void __disable_irq(void) { __asm volatile ("cpsid i" : : : "memory"); } __attribute__( ( always_inline ) ) static inline uint32_t __get_CONTROL(void) { uint32_t result; __asm volatile ("MRS %0, control" : "=r" (result) ); return(result); } __attribute__( ( always_inline ) ) static inline void __set_CONTROL(uint32_t control) { __asm volatile ("MSR control, %0" : : "r" (control) : "memory"); } __attribute__( ( always_inline ) ) static inline uint32_t __get_IPSR(void) { uint32_t result; __asm volatile ("MRS %0, ipsr" : "=r" (result) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __get_APSR(void) { uint32_t result; __asm volatile ("MRS %0, apsr" : "=r" (result) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __get_xPSR(void) { uint32_t result; __asm volatile ("MRS %0, xpsr" : "=r" (result) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __get_PSP(void) { register uint32_t result; __asm volatile ("MRS %0, psp\n" : "=r" (result) ); return(result); } __attribute__( ( always_inline ) ) static inline void __set_PSP(uint32_t topOfProcStack) { __asm volatile ("MSR psp, %0\n" : : "r" (topOfProcStack) : "sp"); } __attribute__( ( always_inline ) ) static inline uint32_t __get_MSP(void) { register uint32_t result; __asm volatile ("MRS %0, msp\n" : "=r" (result) ); return(result); } __attribute__( ( always_inline ) ) static inline void __set_MSP(uint32_t topOfMainStack) { __asm volatile ("MSR msp, %0\n" : : "r" (topOfMainStack) : "sp"); } __attribute__( ( always_inline ) ) static inline uint32_t __get_PRIMASK(void) { uint32_t result; __asm volatile ("MRS %0, primask" : "=r" (result) ); return(result); } __attribute__( ( always_inline ) ) static inline void __set_PRIMASK(uint32_t priMask) { __asm volatile ("MSR primask, %0" : : "r" (priMask) : "memory"); } __attribute__( ( always_inline ) ) static inline void __enable_fault_irq(void) { __asm volatile ("cpsie f" : : : "memory"); } __attribute__( ( always_inline ) ) static inline void __disable_fault_irq(void) { __asm volatile ("cpsid f" : : : "memory"); } __attribute__( ( always_inline ) ) static inline uint32_t __get_BASEPRI(void) { uint32_t result; __asm volatile ("MRS %0, basepri" : "=r" (result) ); return(result); } __attribute__( ( always_inline ) ) static inline void __set_BASEPRI(uint32_t value) { __asm volatile ("MSR basepri, %0" : : "r" (value) : "memory"); } __attribute__( ( always_inline ) ) static inline void __set_BASEPRI_MAX(uint32_t value) { __asm volatile ("MSR basepri_max, %0" : : "r" (value) : "memory"); } __attribute__( ( always_inline ) ) static inline uint32_t __get_FAULTMASK(void) { uint32_t result; __asm volatile ("MRS %0, faultmask" : "=r" (result) ); return(result); } __attribute__( ( always_inline ) ) static inline void __set_FAULTMASK(uint32_t faultMask) { __asm volatile ("MSR faultmask, %0" : : "r" (faultMask) : "memory"); } __attribute__( ( always_inline ) ) static inline uint32_t __get_FPSCR(void) { return(0); } __attribute__( ( always_inline ) ) static inline void __set_FPSCR(uint32_t fpscr) { } __attribute__((always_inline)) static inline void __NOP(void) { __asm volatile ("nop"); } __attribute__((always_inline)) static inline void __WFI(void) { __asm volatile ("wfi"); } __attribute__((always_inline)) static inline void __WFE(void) { __asm volatile ("wfe"); } __attribute__((always_inline)) static inline void __SEV(void) { __asm volatile ("sev"); } __attribute__((always_inline)) static inline void __ISB(void) { __asm volatile ("isb 0xF":::"memory"); } __attribute__((always_inline)) static inline void __DSB(void) { __asm volatile ("dsb 0xF":::"memory"); } __attribute__((always_inline)) static inline void __DMB(void) { __asm volatile ("dmb 0xF":::"memory"); } __attribute__((always_inline)) static inline uint32_t __REV(uint32_t value) { return __builtin_bswap32(value); } __attribute__((always_inline)) static inline uint32_t __REV16(uint32_t value) { uint32_t result; __asm volatile ("rev16 %0, %1" : "=r" (result) : "r" (value) ); return(result); } __attribute__((always_inline)) static inline int32_t __REVSH(int32_t value) { return (short)__builtin_bswap16(value); } __attribute__((always_inline)) static inline uint32_t __ROR(uint32_t op1, uint32_t op2) { return (op1 >> op2) | (op1 << (32U - op2)); } __attribute__((always_inline)) static inline uint32_t __RBIT(uint32_t value) { uint32_t result; __asm volatile ("rbit %0, %1" : "=r" (result) : "r" (value) ); return(result); } __attribute__((always_inline)) static inline uint8_t __LDREXB(volatile uint8_t *addr) { uint32_t result; __asm volatile ("ldrexb %0, %1" : "=r" (result) : "Q" (*addr) ); return ((uint8_t) result); } __attribute__((always_inline)) static inline uint16_t __LDREXH(volatile uint16_t *addr) { uint32_t result; __asm volatile ("ldrexh %0, %1" : "=r" (result) : "Q" (*addr) ); return ((uint16_t) result); } __attribute__((always_inline)) static inline uint32_t __LDREXW(volatile uint32_t *addr) { uint32_t result; __asm volatile ("ldrex %0, %1" : "=r" (result) : "Q" (*addr) ); return(result); } __attribute__((always_inline)) static inline uint32_t __STREXB(uint8_t value, volatile uint8_t *addr) { uint32_t result; __asm volatile ("strexb %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" ((uint32_t)value) ); return(result); } __attribute__((always_inline)) static inline uint32_t __STREXH(uint16_t value, volatile uint16_t *addr) { uint32_t result; __asm volatile ("strexh %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" ((uint32_t)value) ); return(result); } __attribute__((always_inline)) static inline uint32_t __STREXW(uint32_t value, volatile uint32_t *addr) { uint32_t result; __asm volatile ("strex %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) ); return(result); } __attribute__((always_inline)) static inline void __CLREX(void) { __asm volatile ("clrex" ::: "memory"); } __attribute__((always_inline)) static inline uint32_t __RRX(uint32_t value) { uint32_t result; __asm volatile ("rrx %0, %1" : "=r" (result) : "r" (value) ); return(result); } __attribute__((always_inline)) static inline uint8_t __LDRBT(volatile uint8_t *addr) { uint32_t result; __asm volatile ("ldrbt %0, %1" : "=r" (result) : "Q" (*addr) ); return ((uint8_t) result); } __attribute__((always_inline)) static inline uint16_t __LDRHT(volatile uint16_t *addr) { uint32_t result; __asm volatile ("ldrht %0, %1" : "=r" (result) : "Q" (*addr) ); return ((uint16_t) result); } __attribute__((always_inline)) static inline uint32_t __LDRT(volatile uint32_t *addr) { uint32_t result; __asm volatile ("ldrt %0, %1" : "=r" (result) : "Q" (*addr) ); return(result); } __attribute__((always_inline)) static inline void __STRBT(uint8_t value, volatile uint8_t *addr) { __asm volatile ("strbt %1, %0" : "=Q" (*addr) : "r" ((uint32_t)value) ); } __attribute__((always_inline)) static inline void __STRHT(uint16_t value, volatile uint16_t *addr) { __asm volatile ("strht %1, %0" : "=Q" (*addr) : "r" ((uint32_t)value) ); } __attribute__((always_inline)) static inline void __STRT(uint32_t value, volatile uint32_t *addr) { __asm volatile ("strt %1, %0" : "=Q" (*addr) : "r" (value) ); } __attribute__( ( always_inline ) ) static inline uint32_t __SADD8(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __QADD8(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UADD8(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UQADD8(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UHADD8(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __QSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __USUB8(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UQSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UHSUB8(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SADD16(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __QADD16(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UADD16(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UQADD16(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UHADD16(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __QSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __USUB16(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UQSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UHSUB16(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SASX(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __QASX(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SHASX(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UASX(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UQASX(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UHASX(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SSAX(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __QSAX(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __USAX(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UQSAX(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UHSAX(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __USAD8(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __asm volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UXTB16(uint32_t op1) { uint32_t result; __asm volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __UXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SXTB16(uint32_t op1) { uint32_t result; __asm volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1)); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SXTAB16(uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SMUAD (uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SMUADX (uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __asm volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __asm volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) static inline uint64_t __SMLALD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; __asm volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); return(llr.w64); } __attribute__( ( always_inline ) ) static inline uint64_t __SMLALDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; __asm volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); return(llr.w64); } __attribute__( ( always_inline ) ) static inline uint32_t __SMUSD (uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SMUSDX (uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __asm volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3) { uint32_t result; __asm volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) ); return(result); } __attribute__( ( always_inline ) ) static inline uint64_t __SMLSLD (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; __asm volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); return(llr.w64); } __attribute__( ( always_inline ) ) static inline uint64_t __SMLSLDX (uint32_t op1, uint32_t op2, uint64_t acc) { union llreg_u{ uint32_t w32[2]; uint64_t w64; } llr; llr.w64 = acc; __asm volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) ); return(llr.w64); } __attribute__( ( always_inline ) ) static inline uint32_t __SEL (uint32_t op1, uint32_t op2) { uint32_t result; __asm volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline int32_t __QADD( int32_t op1, int32_t op2) { int32_t result; __asm volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline int32_t __QSUB( int32_t op1, int32_t op2) { int32_t result; __asm volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) ); return(result); } __attribute__( ( always_inline ) ) static inline uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3) { int32_t result; __asm volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) ); return(result); } typedef union { struct { uint32_t _reserved0:16; uint32_t GE:4; uint32_t _reserved1:7; uint32_t Q:1; uint32_t V:1; uint32_t C:1; uint32_t Z:1; uint32_t N:1; } b; uint32_t w; } APSR_Type; typedef union { struct { uint32_t ISR:9; uint32_t _reserved0:23; } b; uint32_t w; } IPSR_Type; typedef union { struct { uint32_t ISR:9; uint32_t _reserved0:7; uint32_t GE:4; uint32_t _reserved1:4; uint32_t T:1; uint32_t IT:2; uint32_t Q:1; uint32_t V:1; uint32_t C:1; uint32_t Z:1; uint32_t N:1; } b; uint32_t w; } xPSR_Type; typedef union { struct { uint32_t nPRIV:1; uint32_t SPSEL:1; uint32_t FPCA:1; uint32_t _reserved0:29; } b; uint32_t w; } CONTROL_Type; typedef struct { volatile uint32_t ISER[8U]; uint32_t RESERVED0[24U]; volatile uint32_t ICER[8U]; uint32_t RSERVED1[24U]; volatile uint32_t ISPR[8U]; uint32_t RESERVED2[24U]; volatile uint32_t ICPR[8U]; uint32_t RESERVED3[24U]; volatile uint32_t IABR[8U]; uint32_t RESERVED4[56U]; volatile uint8_t IP[240U]; uint32_t RESERVED5[644U]; volatile uint32_t STIR; } NVIC_Type; typedef struct { volatile const uint32_t CPUID; volatile uint32_t ICSR; volatile uint32_t VTOR; volatile uint32_t AIRCR; volatile uint32_t SCR; volatile uint32_t CCR; volatile uint8_t SHP[12U]; volatile uint32_t SHCSR; volatile uint32_t CFSR; volatile uint32_t HFSR; volatile uint32_t DFSR; volatile uint32_t MMFAR; volatile uint32_t BFAR; volatile uint32_t AFSR; volatile const uint32_t PFR[2U]; volatile const uint32_t DFR; volatile const uint32_t ADR; volatile const uint32_t MMFR[4U]; volatile const uint32_t ISAR[5U]; uint32_t RESERVED0[5U]; volatile uint32_t CPACR; } SCB_Type; typedef struct { uint32_t RESERVED0[1U]; volatile const uint32_t ICTR; volatile uint32_t ACTLR; } SCnSCB_Type; typedef struct { volatile uint32_t CTRL; volatile uint32_t LOAD; volatile uint32_t VAL; volatile const uint32_t CALIB; } SysTick_Type; typedef struct { volatile union { volatile uint8_t u8; volatile uint16_t u16; volatile uint32_t u32; } PORT [32U]; uint32_t RESERVED0[864U]; volatile uint32_t TER; uint32_t RESERVED1[15U]; volatile uint32_t TPR; uint32_t RESERVED2[15U]; volatile uint32_t TCR; uint32_t RESERVED3[29U]; volatile uint32_t IWR; volatile const uint32_t IRR; volatile uint32_t IMCR; uint32_t RESERVED4[43U]; volatile uint32_t LAR; volatile const uint32_t LSR; uint32_t RESERVED5[6U]; volatile const uint32_t PID4; volatile const uint32_t PID5; volatile const uint32_t PID6; volatile const uint32_t PID7; volatile const uint32_t PID0; volatile const uint32_t PID1; volatile const uint32_t PID2; volatile const uint32_t PID3; volatile const uint32_t CID0; volatile const uint32_t CID1; volatile const uint32_t CID2; volatile const uint32_t CID3; } ITM_Type; typedef struct { volatile uint32_t CTRL; volatile uint32_t CYCCNT; volatile uint32_t CPICNT; volatile uint32_t EXCCNT; volatile uint32_t SLEEPCNT; volatile uint32_t LSUCNT; volatile uint32_t FOLDCNT; volatile const uint32_t PCSR; volatile uint32_t COMP0; volatile uint32_t MASK0; volatile uint32_t FUNCTION0; uint32_t RESERVED0[1U]; volatile uint32_t COMP1; volatile uint32_t MASK1; volatile uint32_t FUNCTION1; uint32_t RESERVED1[1U]; volatile uint32_t COMP2; volatile uint32_t MASK2; volatile uint32_t FUNCTION2; uint32_t RESERVED2[1U]; volatile uint32_t COMP3; volatile uint32_t MASK3; volatile uint32_t FUNCTION3; } DWT_Type; typedef struct { volatile uint32_t SSPSR; volatile uint32_t CSPSR; uint32_t RESERVED0[2U]; volatile uint32_t ACPR; uint32_t RESERVED1[55U]; volatile uint32_t SPPR; uint32_t RESERVED2[131U]; volatile const uint32_t FFSR; volatile uint32_t FFCR; volatile const uint32_t FSCR; uint32_t RESERVED3[759U]; volatile const uint32_t TRIGGER; volatile const uint32_t FIFO0; volatile const uint32_t ITATBCTR2; uint32_t RESERVED4[1U]; volatile const uint32_t ITATBCTR0; volatile const uint32_t FIFO1; volatile uint32_t ITCTRL; uint32_t RESERVED5[39U]; volatile uint32_t CLAIMSET; volatile uint32_t CLAIMCLR; uint32_t RESERVED7[8U]; volatile const uint32_t DEVID; volatile const uint32_t DEVTYPE; } TPI_Type; typedef struct { volatile const uint32_t TYPE; volatile uint32_t CTRL; volatile uint32_t RNR; volatile uint32_t RBAR; volatile uint32_t RASR; volatile uint32_t RBAR_A1; volatile uint32_t RASR_A1; volatile uint32_t RBAR_A2; volatile uint32_t RASR_A2; volatile uint32_t RBAR_A3; volatile uint32_t RASR_A3; } MPU_Type; typedef struct { uint32_t RESERVED0[1U]; volatile uint32_t FPCCR; volatile uint32_t FPCAR; volatile uint32_t FPDSCR; volatile const uint32_t MVFR0; volatile const uint32_t MVFR1; } FPU_Type; typedef struct { volatile uint32_t DHCSR; volatile uint32_t DCRSR; volatile uint32_t DCRDR; volatile uint32_t DEMCR; } CoreDebug_Type; static inline void NVIC_SetPriorityGrouping(uint32_t PriorityGroup) { uint32_t reg_value; uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); reg_value = ((SCB_Type *) ((0xE000E000UL) + 0x0D00UL) )->AIRCR; reg_value &= ~((uint32_t)((0xFFFFUL << 16U) | (7UL << 8U))); reg_value = (reg_value | ((uint32_t)0x5FAUL << 16U) | (PriorityGroupTmp << 8U) ); ((SCB_Type *) ((0xE000E000UL) + 0x0D00UL) )->AIRCR = reg_value; } static inline uint32_t NVIC_GetPriorityGrouping(void) { return ((uint32_t)((((SCB_Type *) ((0xE000E000UL) + 0x0D00UL) )->AIRCR & (7UL << 8U)) >> 8U)); } static inline void NVIC_EnableIRQ(IRQn_Type IRQn) { ((NVIC_Type *) ((0xE000E000UL) + 0x0100UL) )->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } static inline void NVIC_DisableIRQ(IRQn_Type IRQn) { ((NVIC_Type *) ((0xE000E000UL) + 0x0100UL) )->ICER[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } static inline uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn) { return((uint32_t)(((((NVIC_Type *) ((0xE000E000UL) + 0x0100UL) )->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } static inline void NVIC_SetPendingIRQ(IRQn_Type IRQn) { ((NVIC_Type *) ((0xE000E000UL) + 0x0100UL) )->ISPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } static inline void NVIC_ClearPendingIRQ(IRQn_Type IRQn) { ((NVIC_Type *) ((0xE000E000UL) + 0x0100UL) )->ICPR[(((uint32_t)(int32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL)); } static inline uint32_t NVIC_GetActive(IRQn_Type IRQn) { return((uint32_t)(((((NVIC_Type *) ((0xE000E000UL) + 0x0100UL) )->IABR[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL)); } static inline void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority) { if ((int32_t)(IRQn) < 0) { ((SCB_Type *) ((0xE000E000UL) + 0x0D00UL) )->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] = (uint8_t)((priority << (8U - 3)) & (uint32_t)0xFFUL); } else { ((NVIC_Type *) ((0xE000E000UL) + 0x0100UL) )->IP[((uint32_t)(int32_t)IRQn)] = (uint8_t)((priority << (8U - 3)) & (uint32_t)0xFFUL); } } static inline uint32_t NVIC_GetPriority(IRQn_Type IRQn) { if ((int32_t)(IRQn) < 0) { return(((uint32_t)((SCB_Type *) ((0xE000E000UL) + 0x0D00UL) )->SHP[(((uint32_t)(int32_t)IRQn) & 0xFUL)-4UL] >> (8U - 3))); } else { return(((uint32_t)((NVIC_Type *) ((0xE000E000UL) + 0x0100UL) )->IP[((uint32_t)(int32_t)IRQn)] >> (8U - 3))); } } static inline uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(3)) ? (uint32_t)(3) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(3)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(3)); return ( ((PreemptPriority & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL)) << SubPriorityBits) | ((SubPriority & (uint32_t)((1UL << (SubPriorityBits )) - 1UL))) ); } static inline void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* const pPreemptPriority, uint32_t* const pSubPriority) { uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07UL); uint32_t PreemptPriorityBits; uint32_t SubPriorityBits; PreemptPriorityBits = ((7UL - PriorityGroupTmp) > (uint32_t)(3)) ? (uint32_t)(3) : (uint32_t)(7UL - PriorityGroupTmp); SubPriorityBits = ((PriorityGroupTmp + (uint32_t)(3)) < (uint32_t)7UL) ? (uint32_t)0UL : (uint32_t)((PriorityGroupTmp - 7UL) + (uint32_t)(3)); *pPreemptPriority = (Priority >> SubPriorityBits) & (uint32_t)((1UL << (PreemptPriorityBits)) - 1UL); *pSubPriority = (Priority ) & (uint32_t)((1UL << (SubPriorityBits )) - 1UL); } static inline void NVIC_SystemReset(void) { __DSB(); ((SCB_Type *) ((0xE000E000UL) + 0x0D00UL) )->AIRCR = (uint32_t)((0x5FAUL << 16U) | (((SCB_Type *) ((0xE000E000UL) + 0x0D00UL) )->AIRCR & (7UL << 8U)) | (1UL << 2U) ); __DSB(); for (;;) { __NOP(); } } static inline uint32_t SysTick_Config(uint32_t ticks) { if ((ticks - 1UL) > (0xFFFFFFUL )) { return (1UL); } ((SysTick_Type *) ((0xE000E000UL) + 0x0010UL) )->LOAD = (uint32_t)(ticks - 1UL); NVIC_SetPriority (SysTick_IRQn, (1UL << 3) - 1UL); ((SysTick_Type *) ((0xE000E000UL) + 0x0010UL) )->VAL = 0UL; ((SysTick_Type *) ((0xE000E000UL) + 0x0010UL) )->CTRL = (1UL << 2U) | (1UL << 1U) | (1UL ); return (0UL); } extern volatile int32_t ITM_RxBuffer; static inline uint32_t ITM_SendChar (uint32_t ch) { if (((((ITM_Type *) (0xE0000000UL) )->TCR & (1UL )) != 0UL) && ((((ITM_Type *) (0xE0000000UL) )->TER & 1UL ) != 0UL) ) { while (((ITM_Type *) (0xE0000000UL) )->PORT[0U].u32 == 0UL) { __NOP(); } ((ITM_Type *) (0xE0000000UL) )->PORT[0U].u8 = (uint8_t)ch; } return (ch); } static inline int32_t ITM_ReceiveChar (void) { int32_t ch = -1; if (ITM_RxBuffer != 0x5AA55AA5U) { ch = ITM_RxBuffer; ITM_RxBuffer = 0x5AA55AA5U; } return (ch); } static inline int32_t ITM_CheckChar (void) { if (ITM_RxBuffer == 0x5AA55AA5U) { return (0); } else { return (1); } } extern uint32_t SystemCoreClock; extern void SystemInit (void); extern void SystemCoreClockUpdate (void); typedef struct { volatile const uint32_t PART; volatile const uint32_t VARIANT; volatile const uint32_t PACKAGE; volatile const uint32_t RAM; volatile const uint32_t FLASH; volatile uint32_t UNUSED0[3]; } FICR_INFO_Type; typedef struct { volatile const uint32_t A0; volatile const uint32_t A1; volatile const uint32_t A2; volatile const uint32_t A3; volatile const uint32_t A4; volatile const uint32_t A5; volatile const uint32_t B0; volatile const uint32_t B1; volatile const uint32_t B2; volatile const uint32_t B3; volatile const uint32_t B4; volatile const uint32_t B5; volatile const uint32_t T0; volatile const uint32_t T1; volatile const uint32_t T2; volatile const uint32_t T3; volatile const uint32_t T4; } FICR_TEMP_Type; typedef struct { volatile const uint32_t TAGHEADER0; volatile const uint32_t TAGHEADER1; volatile const uint32_t TAGHEADER2; volatile const uint32_t TAGHEADER3; } FICR_NFC_Type; typedef struct { volatile uint32_t POWER; volatile uint32_t POWERSET; volatile uint32_t POWERCLR; volatile const uint32_t RESERVED0; } POWER_RAM_Type; typedef struct { volatile uint32_t RTS; volatile uint32_t TXD; volatile uint32_t CTS; volatile uint32_t RXD; } UARTE_PSEL_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; } UARTE_RXD_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; } UARTE_TXD_Type; typedef struct { volatile uint32_t RTS; volatile uint32_t TXD; volatile uint32_t CTS; volatile uint32_t RXD; } UART_PSEL_Type; typedef struct { volatile uint32_t SCK; volatile uint32_t MOSI; volatile uint32_t MISO; volatile uint32_t CSN; } SPIM_PSEL_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; volatile uint32_t LIST; } SPIM_RXD_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; volatile uint32_t LIST; } SPIM_TXD_Type; typedef struct { volatile uint32_t RXDELAY; volatile uint32_t CSNDUR; } SPIM_IFTIMING_Type; typedef struct { volatile uint32_t SCK; volatile uint32_t MISO; volatile uint32_t MOSI; volatile uint32_t CSN; } SPIS_PSEL_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; } SPIS_RXD_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; } SPIS_TXD_Type; typedef struct { volatile uint32_t SCL; volatile uint32_t SDA; } TWIM_PSEL_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; volatile uint32_t LIST; } TWIM_RXD_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; volatile uint32_t LIST; } TWIM_TXD_Type; typedef struct { volatile uint32_t SCL; volatile uint32_t SDA; } TWIS_PSEL_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; } TWIS_RXD_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; } TWIS_TXD_Type; typedef struct { volatile uint32_t SCK; volatile uint32_t MOSI; volatile uint32_t MISO; } SPI_PSEL_Type; typedef struct { volatile uint32_t SCL; volatile uint32_t SDA; } TWI_PSEL_Type; typedef struct { volatile uint32_t RX; } NFCT_FRAMESTATUS_Type; typedef struct { volatile uint32_t FRAMECONFIG; volatile uint32_t AMOUNT; } NFCT_TXD_Type; typedef struct { volatile uint32_t FRAMECONFIG; volatile const uint32_t AMOUNT; } NFCT_RXD_Type; typedef struct { volatile uint32_t LIMITH; volatile uint32_t LIMITL; } SAADC_EVENTS_CH_Type; typedef struct { volatile uint32_t PSELP; volatile uint32_t PSELN; volatile uint32_t CONFIG; volatile uint32_t LIMIT; } SAADC_CH_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; } SAADC_RESULT_Type; typedef struct { volatile uint32_t LED; volatile uint32_t A; volatile uint32_t B; } QDEC_PSEL_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t CNT; volatile uint32_t REFRESH; volatile uint32_t ENDDELAY; volatile const uint32_t RESERVED1[4]; } PWM_SEQ_Type; typedef struct { volatile uint32_t OUT[4]; } PWM_PSEL_Type; typedef struct { volatile uint32_t CLK; volatile uint32_t DIN; } PDM_PSEL_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; } PDM_SAMPLE_Type; typedef struct { volatile uint32_t ADDR; volatile uint32_t SIZE; volatile uint32_t PERM; volatile uint32_t UNUSED0; } ACL_ACL_Type; typedef struct { volatile uint32_t EN; volatile uint32_t DIS; } PPI_TASKS_CHG_Type; typedef struct { volatile uint32_t EEP; volatile uint32_t TEP; } PPI_CH_Type; typedef struct { volatile uint32_t TEP; } PPI_FORK_Type; typedef struct { volatile uint32_t WA; volatile uint32_t RA; } MWU_EVENTS_REGION_Type; typedef struct { volatile uint32_t WA; volatile uint32_t RA; } MWU_EVENTS_PREGION_Type; typedef struct { volatile uint32_t SUBSTATWA; volatile uint32_t SUBSTATRA; } MWU_PERREGION_Type; typedef struct { volatile uint32_t START; volatile uint32_t END; volatile const uint32_t RESERVED2[2]; } MWU_REGION_Type; typedef struct { volatile const uint32_t START; volatile const uint32_t END; volatile uint32_t SUBS; volatile const uint32_t RESERVED3; } MWU_PREGION_Type; typedef struct { volatile uint32_t MODE; volatile uint32_t RXEN; volatile uint32_t TXEN; volatile uint32_t MCKEN; volatile uint32_t MCKFREQ; volatile uint32_t RATIO; volatile uint32_t SWIDTH; volatile uint32_t ALIGN; volatile uint32_t FORMAT; volatile uint32_t CHANNELS; } I2S_CONFIG_Type; typedef struct { volatile uint32_t PTR; } I2S_RXD_Type; typedef struct { volatile uint32_t PTR; } I2S_TXD_Type; typedef struct { volatile uint32_t MAXCNT; } I2S_RXTXD_Type; typedef struct { volatile uint32_t MCK; volatile uint32_t SCK; volatile uint32_t LRCK; volatile uint32_t SDIN; volatile uint32_t SDOUT; } I2S_PSEL_Type; typedef struct { volatile const uint32_t EPIN[8]; volatile const uint32_t RESERVED4; volatile const uint32_t EPOUT[8]; } USBD_HALTED_Type; typedef struct { volatile uint32_t EPOUT[8]; volatile const uint32_t ISOOUT; } USBD_SIZE_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; volatile const uint32_t RESERVED5[2]; } USBD_EPIN_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; } USBD_ISOIN_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; volatile const uint32_t RESERVED6[2]; } USBD_EPOUT_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t MAXCNT; volatile const uint32_t AMOUNT; } USBD_ISOOUT_Type; typedef struct { volatile uint32_t SRC; volatile uint32_t DST; volatile uint32_t CNT; } QSPI_READ_Type; typedef struct { volatile uint32_t DST; volatile uint32_t SRC; volatile uint32_t CNT; } QSPI_WRITE_Type; typedef struct { volatile uint32_t PTR; volatile uint32_t LEN; } QSPI_ERASE_Type; typedef struct { volatile uint32_t SCK; volatile uint32_t CSN; volatile const uint32_t RESERVED7; volatile uint32_t IO0; volatile uint32_t IO1; volatile uint32_t IO2; volatile uint32_t IO3; } QSPI_PSEL_Type; typedef struct { volatile const uint32_t RESERVED0[4]; volatile const uint32_t CODEPAGESIZE; volatile const uint32_t CODESIZE; volatile const uint32_t RESERVED1[18]; volatile const uint32_t DEVICEID[2]; volatile const uint32_t RESERVED2[6]; volatile const uint32_t ER[4]; volatile const uint32_t IR[4]; volatile const uint32_t DEVICEADDRTYPE; volatile const uint32_t DEVICEADDR[2]; volatile const uint32_t RESERVED3[21]; FICR_INFO_Type INFO; volatile const uint32_t RESERVED4[185]; FICR_TEMP_Type TEMP; volatile const uint32_t RESERVED5[2]; FICR_NFC_Type NFC; } NRF_FICR_Type; typedef struct { volatile uint32_t UNUSED0; volatile uint32_t UNUSED1; volatile uint32_t UNUSED2; volatile const uint32_t RESERVED0; volatile uint32_t UNUSED3; volatile uint32_t NRFFW[15]; volatile uint32_t NRFHW[12]; volatile uint32_t CUSTOMER[32]; volatile const uint32_t RESERVED1[64]; volatile uint32_t PSELRESET[2]; volatile uint32_t APPROTECT; volatile uint32_t NFCPINS; volatile uint32_t DEBUGCTRL; volatile const uint32_t RESERVED2[59]; volatile uint32_t DCDCDRIVE0; volatile uint32_t REGOUT0; } NRF_UICR_Type; typedef struct { volatile const uint32_t RESERVED0[30]; volatile uint32_t TASKS_CONSTLAT; volatile uint32_t TASKS_LOWPWR; volatile const uint32_t RESERVED1[34]; volatile uint32_t EVENTS_POFWARN; volatile const uint32_t RESERVED2[2]; volatile uint32_t EVENTS_SLEEPENTER; volatile uint32_t EVENTS_SLEEPEXIT; volatile uint32_t EVENTS_USBDETECTED; volatile uint32_t EVENTS_USBREMOVED; volatile uint32_t EVENTS_USBPWRRDY; volatile const uint32_t RESERVED3[119]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED4[61]; volatile uint32_t RESETREAS; volatile const uint32_t RESERVED5[9]; volatile const uint32_t RAMSTATUS; volatile const uint32_t RESERVED6[3]; volatile const uint32_t USBREGSTATUS; volatile const uint32_t RESERVED7[49]; volatile uint32_t SYSTEMOFF; volatile const uint32_t RESERVED8[3]; volatile uint32_t POFCON; volatile const uint32_t RESERVED9[2]; volatile uint32_t GPREGRET; volatile uint32_t GPREGRET2; volatile const uint32_t RESERVED10[21]; volatile uint32_t DCDCEN; volatile const uint32_t RESERVED11; volatile uint32_t DCDCEN0; volatile const uint32_t RESERVED12[47]; volatile const uint32_t MAINREGSTATUS; volatile const uint32_t RESERVED13[175]; POWER_RAM_Type RAM[9]; } NRF_POWER_Type; typedef struct { volatile uint32_t TASKS_HFCLKSTART; volatile uint32_t TASKS_HFCLKSTOP; volatile uint32_t TASKS_LFCLKSTART; volatile uint32_t TASKS_LFCLKSTOP; volatile uint32_t TASKS_CAL; volatile uint32_t TASKS_CTSTART; volatile uint32_t TASKS_CTSTOP; volatile const uint32_t RESERVED0[57]; volatile uint32_t EVENTS_HFCLKSTARTED; volatile uint32_t EVENTS_LFCLKSTARTED; volatile const uint32_t RESERVED1; volatile uint32_t EVENTS_DONE; volatile uint32_t EVENTS_CTTO; volatile const uint32_t RESERVED2[5]; volatile uint32_t EVENTS_CTSTARTED; volatile uint32_t EVENTS_CTSTOPPED; volatile const uint32_t RESERVED3[117]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED4[63]; volatile const uint32_t HFCLKRUN; volatile const uint32_t HFCLKSTAT; volatile const uint32_t RESERVED5; volatile const uint32_t LFCLKRUN; volatile const uint32_t LFCLKSTAT; volatile const uint32_t LFCLKSRCCOPY; volatile const uint32_t RESERVED6[62]; volatile uint32_t LFCLKSRC; volatile const uint32_t RESERVED7[3]; volatile uint32_t HFXODEBOUNCE; volatile const uint32_t RESERVED8[3]; volatile uint32_t CTIV; volatile const uint32_t RESERVED9[8]; volatile uint32_t TRACECONFIG; volatile const uint32_t RESERVED10[21]; volatile uint32_t LFRCMODE; } NRF_CLOCK_Type; typedef struct { volatile uint32_t TASKS_TXEN; volatile uint32_t TASKS_RXEN; volatile uint32_t TASKS_START; volatile uint32_t TASKS_STOP; volatile uint32_t TASKS_DISABLE; volatile uint32_t TASKS_RSSISTART; volatile uint32_t TASKS_RSSISTOP; volatile uint32_t TASKS_BCSTART; volatile uint32_t TASKS_BCSTOP; volatile uint32_t TASKS_EDSTART; volatile uint32_t TASKS_EDSTOP; volatile uint32_t TASKS_CCASTART; volatile uint32_t TASKS_CCASTOP; volatile const uint32_t RESERVED0[51]; volatile uint32_t EVENTS_READY; volatile uint32_t EVENTS_ADDRESS; volatile uint32_t EVENTS_PAYLOAD; volatile uint32_t EVENTS_END; volatile uint32_t EVENTS_DISABLED; volatile uint32_t EVENTS_DEVMATCH; volatile uint32_t EVENTS_DEVMISS; volatile uint32_t EVENTS_RSSIEND; volatile const uint32_t RESERVED1[2]; volatile uint32_t EVENTS_BCMATCH; volatile const uint32_t RESERVED2; volatile uint32_t EVENTS_CRCOK; volatile uint32_t EVENTS_CRCERROR; volatile uint32_t EVENTS_FRAMESTART; volatile uint32_t EVENTS_EDEND; volatile uint32_t EVENTS_EDSTOPPED; volatile uint32_t EVENTS_CCAIDLE; volatile uint32_t EVENTS_CCABUSY; volatile uint32_t EVENTS_CCASTOPPED; volatile uint32_t EVENTS_RATEBOOST; volatile uint32_t EVENTS_TXREADY; volatile uint32_t EVENTS_RXREADY; volatile uint32_t EVENTS_MHRMATCH; volatile const uint32_t RESERVED3[3]; volatile uint32_t EVENTS_PHYEND; volatile const uint32_t RESERVED4[36]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED5[64]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED6[61]; volatile const uint32_t CRCSTATUS; volatile const uint32_t RESERVED7; volatile const uint32_t RXMATCH; volatile const uint32_t RXCRC; volatile const uint32_t DAI; volatile const uint32_t PDUSTAT; volatile const uint32_t RESERVED8[59]; volatile uint32_t PACKETPTR; volatile uint32_t FREQUENCY; volatile uint32_t TXPOWER; volatile uint32_t MODE; volatile uint32_t PCNF0; volatile uint32_t PCNF1; volatile uint32_t BASE0; volatile uint32_t BASE1; volatile uint32_t PREFIX0; volatile uint32_t PREFIX1; volatile uint32_t TXADDRESS; volatile uint32_t RXADDRESSES; volatile uint32_t CRCCNF; volatile uint32_t CRCPOLY; volatile uint32_t CRCINIT; volatile const uint32_t RESERVED9; volatile uint32_t TIFS; volatile const uint32_t RSSISAMPLE; volatile const uint32_t RESERVED10; volatile const uint32_t STATE; volatile uint32_t DATAWHITEIV; volatile const uint32_t RESERVED11[2]; volatile uint32_t BCC; volatile const uint32_t RESERVED12[39]; volatile uint32_t DAB[8]; volatile uint32_t DAP[8]; volatile uint32_t DACNF; volatile uint32_t MHRMATCHCONF; volatile uint32_t MHRMATCHMAS; volatile const uint32_t RESERVED13; volatile uint32_t MODECNF0; volatile const uint32_t RESERVED14[3]; volatile uint32_t SFD; volatile uint32_t EDCNT; volatile uint32_t EDSAMPLE; volatile uint32_t CCACTRL; volatile const uint32_t RESERVED15[611]; volatile uint32_t POWER; } NRF_RADIO_Type; typedef struct { volatile uint32_t TASKS_STARTRX; volatile uint32_t TASKS_STOPRX; volatile uint32_t TASKS_STARTTX; volatile uint32_t TASKS_STOPTX; volatile const uint32_t RESERVED0[7]; volatile uint32_t TASKS_FLUSHRX; volatile const uint32_t RESERVED1[52]; volatile uint32_t EVENTS_CTS; volatile uint32_t EVENTS_NCTS; volatile uint32_t EVENTS_RXDRDY; volatile const uint32_t RESERVED2; volatile uint32_t EVENTS_ENDRX; volatile const uint32_t RESERVED3[2]; volatile uint32_t EVENTS_TXDRDY; volatile uint32_t EVENTS_ENDTX; volatile uint32_t EVENTS_ERROR; volatile const uint32_t RESERVED4[7]; volatile uint32_t EVENTS_RXTO; volatile const uint32_t RESERVED5; volatile uint32_t EVENTS_RXSTARTED; volatile uint32_t EVENTS_TXSTARTED; volatile const uint32_t RESERVED6; volatile uint32_t EVENTS_TXSTOPPED; volatile const uint32_t RESERVED7[41]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED8[63]; volatile uint32_t INTEN; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED9[93]; volatile uint32_t ERRORSRC; volatile const uint32_t RESERVED10[31]; volatile uint32_t ENABLE; volatile const uint32_t RESERVED11; UARTE_PSEL_Type PSEL; volatile const uint32_t RESERVED12[3]; volatile uint32_t BAUDRATE; volatile const uint32_t RESERVED13[3]; UARTE_RXD_Type RXD; volatile const uint32_t RESERVED14; UARTE_TXD_Type TXD; volatile const uint32_t RESERVED15[7]; volatile uint32_t CONFIG; } NRF_UARTE_Type; typedef struct { volatile uint32_t TASKS_STARTRX; volatile uint32_t TASKS_STOPRX; volatile uint32_t TASKS_STARTTX; volatile uint32_t TASKS_STOPTX; volatile const uint32_t RESERVED0[3]; volatile uint32_t TASKS_SUSPEND; volatile const uint32_t RESERVED1[56]; volatile uint32_t EVENTS_CTS; volatile uint32_t EVENTS_NCTS; volatile uint32_t EVENTS_RXDRDY; volatile const uint32_t RESERVED2[4]; volatile uint32_t EVENTS_TXDRDY; volatile const uint32_t RESERVED3; volatile uint32_t EVENTS_ERROR; volatile const uint32_t RESERVED4[7]; volatile uint32_t EVENTS_RXTO; volatile const uint32_t RESERVED5[46]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED6[64]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED7[93]; volatile uint32_t ERRORSRC; volatile const uint32_t RESERVED8[31]; volatile uint32_t ENABLE; volatile const uint32_t RESERVED9; UART_PSEL_Type PSEL; volatile const uint32_t RXD; volatile uint32_t TXD; volatile const uint32_t RESERVED10; volatile uint32_t BAUDRATE; volatile const uint32_t RESERVED11[17]; volatile uint32_t CONFIG; } NRF_UART_Type; typedef struct { volatile const uint32_t RESERVED0[4]; volatile uint32_t TASKS_START; volatile uint32_t TASKS_STOP; volatile const uint32_t RESERVED1; volatile uint32_t TASKS_SUSPEND; volatile uint32_t TASKS_RESUME; volatile const uint32_t RESERVED2[56]; volatile uint32_t EVENTS_STOPPED; volatile const uint32_t RESERVED3[2]; volatile uint32_t EVENTS_ENDRX; volatile const uint32_t RESERVED4; volatile uint32_t EVENTS_END; volatile const uint32_t RESERVED5; volatile uint32_t EVENTS_ENDTX; volatile const uint32_t RESERVED6[10]; volatile uint32_t EVENTS_STARTED; volatile const uint32_t RESERVED7[44]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED8[64]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED9[61]; volatile uint32_t STALLSTAT; volatile const uint32_t RESERVED10[63]; volatile uint32_t ENABLE; volatile const uint32_t RESERVED11; SPIM_PSEL_Type PSEL; volatile const uint32_t RESERVED12[3]; volatile uint32_t FREQUENCY; volatile const uint32_t RESERVED13[3]; SPIM_RXD_Type RXD; SPIM_TXD_Type TXD; volatile uint32_t CONFIG; volatile const uint32_t RESERVED14[2]; SPIM_IFTIMING_Type IFTIMING; volatile uint32_t CSNPOL; volatile uint32_t PSELDCX; volatile uint32_t DCXCNT; volatile const uint32_t RESERVED15[19]; volatile uint32_t ORC; } NRF_SPIM_Type; typedef struct { volatile const uint32_t RESERVED0[9]; volatile uint32_t TASKS_ACQUIRE; volatile uint32_t TASKS_RELEASE; volatile const uint32_t RESERVED1[54]; volatile uint32_t EVENTS_END; volatile const uint32_t RESERVED2[2]; volatile uint32_t EVENTS_ENDRX; volatile const uint32_t RESERVED3[5]; volatile uint32_t EVENTS_ACQUIRED; volatile const uint32_t RESERVED4[53]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED5[64]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED6[61]; volatile const uint32_t SEMSTAT; volatile const uint32_t RESERVED7[15]; volatile uint32_t STATUS; volatile const uint32_t RESERVED8[47]; volatile uint32_t ENABLE; volatile const uint32_t RESERVED9; SPIS_PSEL_Type PSEL; volatile const uint32_t RESERVED10[7]; SPIS_RXD_Type RXD; volatile const uint32_t RESERVED11; SPIS_TXD_Type TXD; volatile const uint32_t RESERVED12; volatile uint32_t CONFIG; volatile const uint32_t RESERVED13; volatile uint32_t DEF; volatile const uint32_t RESERVED14[24]; volatile uint32_t ORC; } NRF_SPIS_Type; typedef struct { volatile uint32_t TASKS_STARTRX; volatile const uint32_t RESERVED0; volatile uint32_t TASKS_STARTTX; volatile const uint32_t RESERVED1[2]; volatile uint32_t TASKS_STOP; volatile const uint32_t RESERVED2; volatile uint32_t TASKS_SUSPEND; volatile uint32_t TASKS_RESUME; volatile const uint32_t RESERVED3[56]; volatile uint32_t EVENTS_STOPPED; volatile const uint32_t RESERVED4[7]; volatile uint32_t EVENTS_ERROR; volatile const uint32_t RESERVED5[8]; volatile uint32_t EVENTS_SUSPENDED; volatile uint32_t EVENTS_RXSTARTED; volatile uint32_t EVENTS_TXSTARTED; volatile const uint32_t RESERVED6[2]; volatile uint32_t EVENTS_LASTRX; volatile uint32_t EVENTS_LASTTX; volatile const uint32_t RESERVED7[39]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED8[63]; volatile uint32_t INTEN; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED9[110]; volatile uint32_t ERRORSRC; volatile const uint32_t RESERVED10[14]; volatile uint32_t ENABLE; volatile const uint32_t RESERVED11; TWIM_PSEL_Type PSEL; volatile const uint32_t RESERVED12[5]; volatile uint32_t FREQUENCY; volatile const uint32_t RESERVED13[3]; TWIM_RXD_Type RXD; TWIM_TXD_Type TXD; volatile const uint32_t RESERVED14[13]; volatile uint32_t ADDRESS; } NRF_TWIM_Type; typedef struct { volatile const uint32_t RESERVED0[5]; volatile uint32_t TASKS_STOP; volatile const uint32_t RESERVED1; volatile uint32_t TASKS_SUSPEND; volatile uint32_t TASKS_RESUME; volatile const uint32_t RESERVED2[3]; volatile uint32_t TASKS_PREPARERX; volatile uint32_t TASKS_PREPARETX; volatile const uint32_t RESERVED3[51]; volatile uint32_t EVENTS_STOPPED; volatile const uint32_t RESERVED4[7]; volatile uint32_t EVENTS_ERROR; volatile const uint32_t RESERVED5[9]; volatile uint32_t EVENTS_RXSTARTED; volatile uint32_t EVENTS_TXSTARTED; volatile const uint32_t RESERVED6[4]; volatile uint32_t EVENTS_WRITE; volatile uint32_t EVENTS_READ; volatile const uint32_t RESERVED7[37]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED8[63]; volatile uint32_t INTEN; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED9[113]; volatile uint32_t ERRORSRC; volatile const uint32_t MATCH; volatile const uint32_t RESERVED10[10]; volatile uint32_t ENABLE; volatile const uint32_t RESERVED11; TWIS_PSEL_Type PSEL; volatile const uint32_t RESERVED12[9]; TWIS_RXD_Type RXD; volatile const uint32_t RESERVED13; TWIS_TXD_Type TXD; volatile const uint32_t RESERVED14[14]; volatile uint32_t ADDRESS[2]; volatile const uint32_t RESERVED15; volatile uint32_t CONFIG; volatile const uint32_t RESERVED16[10]; volatile uint32_t ORC; } NRF_TWIS_Type; typedef struct { volatile const uint32_t RESERVED0[66]; volatile uint32_t EVENTS_READY; volatile const uint32_t RESERVED1[126]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED2[125]; volatile uint32_t ENABLE; volatile const uint32_t RESERVED3; SPI_PSEL_Type PSEL; volatile const uint32_t RESERVED4; volatile const uint32_t RXD; volatile uint32_t TXD; volatile const uint32_t RESERVED5; volatile uint32_t FREQUENCY; volatile const uint32_t RESERVED6[11]; volatile uint32_t CONFIG; } NRF_SPI_Type; typedef struct { volatile uint32_t TASKS_STARTRX; volatile const uint32_t RESERVED0; volatile uint32_t TASKS_STARTTX; volatile const uint32_t RESERVED1[2]; volatile uint32_t TASKS_STOP; volatile const uint32_t RESERVED2; volatile uint32_t TASKS_SUSPEND; volatile uint32_t TASKS_RESUME; volatile const uint32_t RESERVED3[56]; volatile uint32_t EVENTS_STOPPED; volatile uint32_t EVENTS_RXDREADY; volatile const uint32_t RESERVED4[4]; volatile uint32_t EVENTS_TXDSENT; volatile const uint32_t RESERVED5; volatile uint32_t EVENTS_ERROR; volatile const uint32_t RESERVED6[4]; volatile uint32_t EVENTS_BB; volatile const uint32_t RESERVED7[3]; volatile uint32_t EVENTS_SUSPENDED; volatile const uint32_t RESERVED8[45]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED9[64]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED10[110]; volatile uint32_t ERRORSRC; volatile const uint32_t RESERVED11[14]; volatile uint32_t ENABLE; volatile const uint32_t RESERVED12; TWI_PSEL_Type PSEL; volatile const uint32_t RESERVED13[2]; volatile const uint32_t RXD; volatile uint32_t TXD; volatile const uint32_t RESERVED14; volatile uint32_t FREQUENCY; volatile const uint32_t RESERVED15[24]; volatile uint32_t ADDRESS; } NRF_TWI_Type; typedef struct { volatile uint32_t TASKS_ACTIVATE; volatile uint32_t TASKS_DISABLE; volatile uint32_t TASKS_SENSE; volatile uint32_t TASKS_STARTTX; volatile const uint32_t RESERVED0[3]; volatile uint32_t TASKS_ENABLERXDATA; volatile const uint32_t RESERVED1; volatile uint32_t TASKS_GOIDLE; volatile uint32_t TASKS_GOSLEEP; volatile const uint32_t RESERVED2[53]; volatile uint32_t EVENTS_READY; volatile uint32_t EVENTS_FIELDDETECTED; volatile uint32_t EVENTS_FIELDLOST; volatile uint32_t EVENTS_TXFRAMESTART; volatile uint32_t EVENTS_TXFRAMEEND; volatile uint32_t EVENTS_RXFRAMESTART; volatile uint32_t EVENTS_RXFRAMEEND; volatile uint32_t EVENTS_ERROR; volatile const uint32_t RESERVED3[2]; volatile uint32_t EVENTS_RXERROR; volatile uint32_t EVENTS_ENDRX; volatile uint32_t EVENTS_ENDTX; volatile const uint32_t RESERVED4; volatile uint32_t EVENTS_AUTOCOLRESSTARTED; volatile const uint32_t RESERVED5[3]; volatile uint32_t EVENTS_COLLISION; volatile uint32_t EVENTS_SELECTED; volatile uint32_t EVENTS_STARTED; volatile const uint32_t RESERVED6[43]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED7[63]; volatile uint32_t INTEN; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED8[62]; volatile uint32_t ERRORSTATUS; volatile const uint32_t RESERVED9; NFCT_FRAMESTATUS_Type FRAMESTATUS; volatile const uint32_t NFCTAGSTATE; volatile const uint32_t RESERVED10[10]; volatile const uint32_t FIELDPRESENT; volatile const uint32_t RESERVED11[49]; volatile uint32_t FRAMEDELAYMIN; volatile uint32_t FRAMEDELAYMAX; volatile uint32_t FRAMEDELAYMODE; volatile uint32_t PACKETPTR; volatile uint32_t MAXLEN; NFCT_TXD_Type TXD; NFCT_RXD_Type RXD; volatile const uint32_t RESERVED12[26]; volatile uint32_t NFCID1_LAST; volatile uint32_t NFCID1_2ND_LAST; volatile uint32_t NFCID1_3RD_LAST; volatile uint32_t AUTOCOLRESCONFIG; volatile uint32_t SENSRES; volatile uint32_t SELRES; } NRF_NFCT_Type; typedef struct { volatile uint32_t TASKS_OUT[8]; volatile const uint32_t RESERVED0[4]; volatile uint32_t TASKS_SET[8]; volatile const uint32_t RESERVED1[4]; volatile uint32_t TASKS_CLR[8]; volatile const uint32_t RESERVED2[32]; volatile uint32_t EVENTS_IN[8]; volatile const uint32_t RESERVED3[23]; volatile uint32_t EVENTS_PORT; volatile const uint32_t RESERVED4[97]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED5[129]; volatile uint32_t CONFIG[8]; } NRF_GPIOTE_Type; typedef struct { volatile uint32_t TASKS_START; volatile uint32_t TASKS_SAMPLE; volatile uint32_t TASKS_STOP; volatile uint32_t TASKS_CALIBRATEOFFSET; volatile const uint32_t RESERVED0[60]; volatile uint32_t EVENTS_STARTED; volatile uint32_t EVENTS_END; volatile uint32_t EVENTS_DONE; volatile uint32_t EVENTS_RESULTDONE; volatile uint32_t EVENTS_CALIBRATEDONE; volatile uint32_t EVENTS_STOPPED; SAADC_EVENTS_CH_Type EVENTS_CH[8]; volatile const uint32_t RESERVED1[106]; volatile uint32_t INTEN; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED2[61]; volatile const uint32_t STATUS; volatile const uint32_t RESERVED3[63]; volatile uint32_t ENABLE; volatile const uint32_t RESERVED4[3]; SAADC_CH_Type CH[8]; volatile const uint32_t RESERVED5[24]; volatile uint32_t RESOLUTION; volatile uint32_t OVERSAMPLE; volatile uint32_t SAMPLERATE; volatile const uint32_t RESERVED6[12]; SAADC_RESULT_Type RESULT; } NRF_SAADC_Type; typedef struct { volatile uint32_t TASKS_START; volatile uint32_t TASKS_STOP; volatile uint32_t TASKS_COUNT; volatile uint32_t TASKS_CLEAR; volatile uint32_t TASKS_SHUTDOWN; volatile const uint32_t RESERVED0[11]; volatile uint32_t TASKS_CAPTURE[6]; volatile const uint32_t RESERVED1[58]; volatile uint32_t EVENTS_COMPARE[6]; volatile const uint32_t RESERVED2[42]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED3[64]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED4[126]; volatile uint32_t MODE; volatile uint32_t BITMODE; volatile const uint32_t RESERVED5; volatile uint32_t PRESCALER; volatile const uint32_t RESERVED6[11]; volatile uint32_t CC[6]; } NRF_TIMER_Type; typedef struct { volatile uint32_t TASKS_START; volatile uint32_t TASKS_STOP; volatile uint32_t TASKS_CLEAR; volatile uint32_t TASKS_TRIGOVRFLW; volatile const uint32_t RESERVED0[60]; volatile uint32_t EVENTS_TICK; volatile uint32_t EVENTS_OVRFLW; volatile const uint32_t RESERVED1[14]; volatile uint32_t EVENTS_COMPARE[4]; volatile const uint32_t RESERVED2[109]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED3[13]; volatile uint32_t EVTEN; volatile uint32_t EVTENSET; volatile uint32_t EVTENCLR; volatile const uint32_t RESERVED4[110]; volatile const uint32_t COUNTER; volatile uint32_t PRESCALER; volatile const uint32_t RESERVED5[13]; volatile uint32_t CC[4]; } NRF_RTC_Type; typedef struct { volatile uint32_t TASKS_START; volatile uint32_t TASKS_STOP; volatile const uint32_t RESERVED0[62]; volatile uint32_t EVENTS_DATARDY; volatile const uint32_t RESERVED1[128]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED2[127]; volatile const int32_t TEMP; volatile const uint32_t RESERVED3[5]; volatile uint32_t A0; volatile uint32_t A1; volatile uint32_t A2; volatile uint32_t A3; volatile uint32_t A4; volatile uint32_t A5; volatile const uint32_t RESERVED4[2]; volatile uint32_t B0; volatile uint32_t B1; volatile uint32_t B2; volatile uint32_t B3; volatile uint32_t B4; volatile uint32_t B5; volatile const uint32_t RESERVED5[2]; volatile uint32_t T0; volatile uint32_t T1; volatile uint32_t T2; volatile uint32_t T3; volatile uint32_t T4; } NRF_TEMP_Type; typedef struct { volatile uint32_t TASKS_START; volatile uint32_t TASKS_STOP; volatile const uint32_t RESERVED0[62]; volatile uint32_t EVENTS_VALRDY; volatile const uint32_t RESERVED1[63]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED2[64]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED3[126]; volatile uint32_t CONFIG; volatile const uint32_t VALUE; } NRF_RNG_Type; typedef struct { volatile uint32_t TASKS_STARTECB; volatile uint32_t TASKS_STOPECB; volatile const uint32_t RESERVED0[62]; volatile uint32_t EVENTS_ENDECB; volatile uint32_t EVENTS_ERRORECB; volatile const uint32_t RESERVED1[127]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED2[126]; volatile uint32_t ECBDATAPTR; } NRF_ECB_Type; typedef struct { volatile uint32_t TASKS_KSGEN; volatile uint32_t TASKS_CRYPT; volatile uint32_t TASKS_STOP; volatile uint32_t TASKS_RATEOVERRIDE; volatile const uint32_t RESERVED0[60]; volatile uint32_t EVENTS_ENDKSGEN; volatile uint32_t EVENTS_ENDCRYPT; volatile uint32_t EVENTS_ERROR; volatile const uint32_t RESERVED1[61]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED2[64]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED3[61]; volatile const uint32_t MICSTATUS; volatile const uint32_t RESERVED4[63]; volatile uint32_t ENABLE; volatile uint32_t MODE; volatile uint32_t CNFPTR; volatile uint32_t INPTR; volatile uint32_t OUTPTR; volatile uint32_t SCRATCHPTR; volatile uint32_t MAXPACKETSIZE; volatile uint32_t RATEOVERRIDE; } NRF_CCM_Type; typedef struct { volatile uint32_t TASKS_START; volatile const uint32_t RESERVED0; volatile uint32_t TASKS_STOP; volatile const uint32_t RESERVED1[61]; volatile uint32_t EVENTS_END; volatile uint32_t EVENTS_RESOLVED; volatile uint32_t EVENTS_NOTRESOLVED; volatile const uint32_t RESERVED2[126]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED3[61]; volatile const uint32_t STATUS; volatile const uint32_t RESERVED4[63]; volatile uint32_t ENABLE; volatile uint32_t NIRK; volatile uint32_t IRKPTR; volatile const uint32_t RESERVED5; volatile uint32_t ADDRPTR; volatile uint32_t SCRATCHPTR; } NRF_AAR_Type; typedef struct { volatile uint32_t TASKS_START; volatile const uint32_t RESERVED0[63]; volatile uint32_t EVENTS_TIMEOUT; volatile const uint32_t RESERVED1[128]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED2[61]; volatile const uint32_t RUNSTATUS; volatile const uint32_t REQSTATUS; volatile const uint32_t RESERVED3[63]; volatile uint32_t CRV; volatile uint32_t RREN; volatile uint32_t CONFIG; volatile const uint32_t RESERVED4[60]; volatile uint32_t RR[8]; } NRF_WDT_Type; typedef struct { volatile uint32_t TASKS_START; volatile uint32_t TASKS_STOP; volatile uint32_t TASKS_READCLRACC; volatile uint32_t TASKS_RDCLRACC; volatile uint32_t TASKS_RDCLRDBL; volatile const uint32_t RESERVED0[59]; volatile uint32_t EVENTS_SAMPLERDY; volatile uint32_t EVENTS_REPORTRDY; volatile uint32_t EVENTS_ACCOF; volatile uint32_t EVENTS_DBLRDY; volatile uint32_t EVENTS_STOPPED; volatile const uint32_t RESERVED1[59]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED2[64]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED3[125]; volatile uint32_t ENABLE; volatile uint32_t LEDPOL; volatile uint32_t SAMPLEPER; volatile const int32_t SAMPLE; volatile uint32_t REPORTPER; volatile const int32_t ACC; volatile const int32_t ACCREAD; QDEC_PSEL_Type PSEL; volatile uint32_t DBFEN; volatile const uint32_t RESERVED4[5]; volatile uint32_t LEDPRE; volatile const uint32_t ACCDBL; volatile const uint32_t ACCDBLREAD; } NRF_QDEC_Type; typedef struct { volatile uint32_t TASKS_START; volatile uint32_t TASKS_STOP; volatile uint32_t TASKS_SAMPLE; volatile const uint32_t RESERVED0[61]; volatile uint32_t EVENTS_READY; volatile uint32_t EVENTS_DOWN; volatile uint32_t EVENTS_UP; volatile uint32_t EVENTS_CROSS; volatile const uint32_t RESERVED1[60]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED2[63]; volatile uint32_t INTEN; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED3[61]; volatile const uint32_t RESULT; volatile const uint32_t RESERVED4[63]; volatile uint32_t ENABLE; volatile uint32_t PSEL; volatile uint32_t REFSEL; volatile uint32_t EXTREFSEL; volatile const uint32_t RESERVED5[8]; volatile uint32_t TH; volatile uint32_t MODE; volatile uint32_t HYST; } NRF_COMP_Type; typedef struct { volatile uint32_t TASKS_START; volatile uint32_t TASKS_STOP; volatile uint32_t TASKS_SAMPLE; volatile const uint32_t RESERVED0[61]; volatile uint32_t EVENTS_READY; volatile uint32_t EVENTS_DOWN; volatile uint32_t EVENTS_UP; volatile uint32_t EVENTS_CROSS; volatile const uint32_t RESERVED1[60]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED2[64]; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED3[61]; volatile const uint32_t RESULT; volatile const uint32_t RESERVED4[63]; volatile uint32_t ENABLE; volatile uint32_t PSEL; volatile uint32_t REFSEL; volatile uint32_t EXTREFSEL; volatile const uint32_t RESERVED5[4]; volatile uint32_t ANADETECT; volatile const uint32_t RESERVED6[5]; volatile uint32_t HYST; } NRF_LPCOMP_Type; typedef struct { volatile const uint32_t UNUSED; } NRF_SWI_Type; typedef struct { volatile uint32_t TASKS_TRIGGER[16]; volatile const uint32_t RESERVED0[48]; volatile uint32_t EVENTS_TRIGGERED[16]; volatile const uint32_t RESERVED1[112]; volatile uint32_t INTEN; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; } NRF_EGU_Type; typedef struct { volatile const uint32_t RESERVED0; volatile uint32_t TASKS_STOP; volatile uint32_t TASKS_SEQSTART[2]; volatile uint32_t TASKS_NEXTSTEP; volatile const uint32_t RESERVED1[60]; volatile uint32_t EVENTS_STOPPED; volatile uint32_t EVENTS_SEQSTARTED[2]; volatile uint32_t EVENTS_SEQEND[2]; volatile uint32_t EVENTS_PWMPERIODEND; volatile uint32_t EVENTS_LOOPSDONE; volatile const uint32_t RESERVED2[56]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED3[63]; volatile uint32_t INTEN; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED4[125]; volatile uint32_t ENABLE; volatile uint32_t MODE; volatile uint32_t COUNTERTOP; volatile uint32_t PRESCALER; volatile uint32_t DECODER; volatile uint32_t LOOP; volatile const uint32_t RESERVED5[2]; PWM_SEQ_Type SEQ[2]; PWM_PSEL_Type PSEL; } NRF_PWM_Type; typedef struct { volatile uint32_t TASKS_START; volatile uint32_t TASKS_STOP; volatile const uint32_t RESERVED0[62]; volatile uint32_t EVENTS_STARTED; volatile uint32_t EVENTS_STOPPED; volatile uint32_t EVENTS_END; volatile const uint32_t RESERVED1[125]; volatile uint32_t INTEN; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED2[125]; volatile uint32_t ENABLE; volatile uint32_t PDMCLKCTRL; volatile uint32_t MODE; volatile const uint32_t RESERVED3[3]; volatile uint32_t GAINL; volatile uint32_t GAINR; volatile uint32_t RATIO; volatile const uint32_t RESERVED4[7]; PDM_PSEL_Type PSEL; volatile const uint32_t RESERVED5[6]; PDM_SAMPLE_Type SAMPLE; } NRF_PDM_Type; typedef struct { volatile const uint32_t RESERVED0[256]; volatile const uint32_t READY; volatile const uint32_t RESERVED1; volatile const uint32_t READYNEXT; volatile const uint32_t RESERVED2[62]; volatile uint32_t CONFIG; union { volatile uint32_t ERASEPAGE; volatile uint32_t ERASEPCR1; }; volatile uint32_t ERASEALL; volatile uint32_t ERASEPCR0; volatile uint32_t ERASEUICR; volatile const uint32_t RESERVED3[10]; volatile uint32_t ICACHECNF; volatile const uint32_t RESERVED4; volatile uint32_t IHIT; volatile uint32_t IMISS; } NRF_NVMC_Type; typedef struct { volatile const uint32_t RESERVED0[512]; ACL_ACL_Type ACL[8]; } NRF_ACL_Type; typedef struct { PPI_TASKS_CHG_Type TASKS_CHG[6]; volatile const uint32_t RESERVED0[308]; volatile uint32_t CHEN; volatile uint32_t CHENSET; volatile uint32_t CHENCLR; volatile const uint32_t RESERVED1; PPI_CH_Type CH[20]; volatile const uint32_t RESERVED2[148]; volatile uint32_t CHG[6]; volatile const uint32_t RESERVED3[62]; PPI_FORK_Type FORK[32]; } NRF_PPI_Type; typedef struct { volatile const uint32_t RESERVED0[64]; MWU_EVENTS_REGION_Type EVENTS_REGION[4]; volatile const uint32_t RESERVED1[16]; MWU_EVENTS_PREGION_Type EVENTS_PREGION[2]; volatile const uint32_t RESERVED2[100]; volatile uint32_t INTEN; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED3[5]; volatile uint32_t NMIEN; volatile uint32_t NMIENSET; volatile uint32_t NMIENCLR; volatile const uint32_t RESERVED4[53]; MWU_PERREGION_Type PERREGION[2]; volatile const uint32_t RESERVED5[64]; volatile uint32_t REGIONEN; volatile uint32_t REGIONENSET; volatile uint32_t REGIONENCLR; volatile const uint32_t RESERVED6[57]; MWU_REGION_Type REGION[4]; volatile const uint32_t RESERVED7[32]; MWU_PREGION_Type PREGION[2]; } NRF_MWU_Type; typedef struct { volatile uint32_t TASKS_START; volatile uint32_t TASKS_STOP; volatile const uint32_t RESERVED0[63]; volatile uint32_t EVENTS_RXPTRUPD; volatile uint32_t EVENTS_STOPPED; volatile const uint32_t RESERVED1[2]; volatile uint32_t EVENTS_TXPTRUPD; volatile const uint32_t RESERVED2[122]; volatile uint32_t INTEN; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED3[125]; volatile uint32_t ENABLE; I2S_CONFIG_Type CONFIG; volatile const uint32_t RESERVED4[3]; I2S_RXD_Type RXD; volatile const uint32_t RESERVED5; I2S_TXD_Type TXD; volatile const uint32_t RESERVED6[3]; I2S_RXTXD_Type RXTXD; volatile const uint32_t RESERVED7[3]; I2S_PSEL_Type PSEL; } NRF_I2S_Type; typedef struct { volatile const uint32_t UNUSED; } NRF_FPU_Type; typedef struct { volatile const uint32_t RESERVED0; volatile uint32_t TASKS_STARTEPIN[8]; volatile uint32_t TASKS_STARTISOIN; volatile uint32_t TASKS_STARTEPOUT[8]; volatile uint32_t TASKS_STARTISOOUT; volatile uint32_t TASKS_EP0RCVOUT; volatile uint32_t TASKS_EP0STATUS; volatile uint32_t TASKS_EP0STALL; volatile uint32_t TASKS_DPDMDRIVE; volatile uint32_t TASKS_DPDMNODRIVE; volatile const uint32_t RESERVED1[40]; volatile uint32_t EVENTS_USBRESET; volatile uint32_t EVENTS_STARTED; volatile uint32_t EVENTS_ENDEPIN[8]; volatile uint32_t EVENTS_EP0DATADONE; volatile uint32_t EVENTS_ENDISOIN; volatile uint32_t EVENTS_ENDEPOUT[8]; volatile uint32_t EVENTS_ENDISOOUT; volatile uint32_t EVENTS_SOF; volatile uint32_t EVENTS_USBEVENT; volatile uint32_t EVENTS_EP0SETUP; volatile uint32_t EVENTS_EPDATA; volatile uint32_t EVENTS_ACCESSFAULT; volatile const uint32_t RESERVED2[38]; volatile uint32_t SHORTS; volatile const uint32_t RESERVED3[63]; volatile uint32_t INTEN; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED4[61]; volatile uint32_t EVENTCAUSE; volatile const uint32_t BUSSTATE; volatile const uint32_t RESERVED5[6]; USBD_HALTED_Type HALTED; volatile const uint32_t RESERVED6; volatile uint32_t EPSTATUS; volatile uint32_t EPDATASTATUS; volatile const uint32_t USBADDR; volatile const uint32_t RESERVED7[3]; volatile const uint32_t BMREQUESTTYPE; volatile const uint32_t BREQUEST; volatile const uint32_t WVALUEL; volatile const uint32_t WVALUEH; volatile const uint32_t WINDEXL; volatile const uint32_t WINDEXH; volatile const uint32_t WLENGTHL; volatile const uint32_t WLENGTHH; USBD_SIZE_Type SIZE; volatile const uint32_t RESERVED8[15]; volatile uint32_t ENABLE; volatile uint32_t USBPULLUP; volatile uint32_t DPDMVALUE; volatile uint32_t DTOGGLE; volatile uint32_t EPINEN; volatile uint32_t EPOUTEN; volatile uint32_t EPSTALL; volatile uint32_t ISOSPLIT; volatile const uint32_t FRAMECNTR; volatile const uint32_t RESERVED9[2]; volatile uint32_t LOWPOWER; volatile uint32_t ISOINCONFIG; volatile const uint32_t RESERVED10[51]; USBD_EPIN_Type EPIN[8]; USBD_ISOIN_Type ISOIN; volatile const uint32_t RESERVED11[21]; USBD_EPOUT_Type EPOUT[8]; USBD_ISOOUT_Type ISOOUT; } NRF_USBD_Type; typedef struct { volatile uint32_t TASKS_ACTIVATE; volatile uint32_t TASKS_READSTART; volatile uint32_t TASKS_WRITESTART; volatile uint32_t TASKS_ERASESTART; volatile uint32_t TASKS_DEACTIVATE; volatile const uint32_t RESERVED0[59]; volatile uint32_t EVENTS_READY; volatile const uint32_t RESERVED1[127]; volatile uint32_t INTEN; volatile uint32_t INTENSET; volatile uint32_t INTENCLR; volatile const uint32_t RESERVED2[125]; volatile uint32_t ENABLE; QSPI_READ_Type READ; QSPI_WRITE_Type WRITE; QSPI_ERASE_Type ERASE; QSPI_PSEL_Type PSEL; volatile uint32_t XIPOFFSET; volatile uint32_t IFCONFIG0; volatile const uint32_t RESERVED3[46]; volatile uint32_t IFCONFIG1; volatile const uint32_t STATUS; volatile const uint32_t RESERVED4[3]; volatile uint32_t DPMDUR; volatile const uint32_t RESERVED5[3]; volatile uint32_t ADDRCONF; volatile const uint32_t RESERVED6[3]; volatile uint32_t CINSTRCONF; volatile uint32_t CINSTRDAT0; volatile uint32_t CINSTRDAT1; volatile uint32_t IFTIMING; } NRF_QSPI_Type; typedef struct { volatile const uint32_t RESERVED0[321]; volatile uint32_t OUT; volatile uint32_t OUTSET; volatile uint32_t OUTCLR; volatile const uint32_t IN; volatile uint32_t DIR; volatile uint32_t DIRSET; volatile uint32_t DIRCLR; volatile uint32_t LATCH; volatile uint32_t DETECTMODE; volatile const uint32_t RESERVED1[118]; volatile uint32_t PIN_CNF[32]; } NRF_GPIO_Type; typedef struct { volatile const uint32_t RESERVED0[320]; volatile uint32_t ENABLE; } NRF_CRYPTOCELL_Type; static inline unsigned int gcc_current_sp(void) { register unsigned sp __asm("sp"); return sp; } typedef uint32_t ret_code_t; typedef int _LOCK_T; typedef int _LOCK_RECURSIVE_T; typedef long __blkcnt_t; typedef long __blksize_t; typedef __uint64_t __fsblkcnt_t; typedef __uint32_t __fsfilcnt_t; typedef long _off_t; typedef int __pid_t; typedef short __dev_t; typedef unsigned short __uid_t; typedef unsigned short __gid_t; typedef __uint32_t __id_t; typedef unsigned short __ino_t; typedef __uint32_t __mode_t; __extension__ typedef long long _off64_t; typedef _off_t __off_t; typedef _off64_t __loff_t; typedef long __key_t; typedef long _fpos_t; typedef unsigned int __size_t; typedef signed int _ssize_t; typedef _ssize_t __ssize_t; typedef unsigned int wint_t; typedef struct { int __count; union { wint_t __wch; unsigned char __wchb[4]; } __value; } _mbstate_t; typedef _LOCK_RECURSIVE_T _flock_t; typedef void *_iconv_t; typedef unsigned long __clock_t; typedef long __time_t; typedef unsigned long __clockid_t; typedef unsigned long __timer_t; typedef __uint8_t __sa_family_t; typedef __uint32_t __socklen_t; typedef unsigned short __nlink_t; typedef long __suseconds_t; typedef unsigned long __useconds_t; typedef char * __va_list; typedef unsigned long __ULong; struct _reent; struct __locale_t; struct _Bigint { struct _Bigint *_next; int _k, _maxwds, _sign, _wds; __ULong _x[1]; }; struct __tm { int __tm_sec; int __tm_min; int __tm_hour; int __tm_mday; int __tm_mon; int __tm_year; int __tm_wday; int __tm_yday; int __tm_isdst; }; struct _on_exit_args { void * _fnargs[32]; void * _dso_handle[32]; __ULong _fntypes; __ULong _is_cxa; }; struct _atexit { struct _atexit *_next; int _ind; void (*_fns[32])(void); struct _on_exit_args _on_exit_args; }; struct __sbuf { unsigned char *_base; int _size; }; struct __sFILE { unsigned char *_p; int _r; int _w; short _flags; short _file; struct __sbuf _bf; int _lbfsize; void * _cookie; int (* _read) (struct _reent *, void *, char *, int) ; int (* _write) (struct _reent *, void *, const char *, int) ; _fpos_t (* _seek) (struct _reent *, void *, _fpos_t, int); int (* _close) (struct _reent *, void *); struct __sbuf _ub; unsigned char *_up; int _ur; unsigned char _ubuf[3]; unsigned char _nbuf[1]; struct __sbuf _lb; int _blksize; _off_t _offset; struct _reent *_data; _flock_t _lock; _mbstate_t _mbstate; int _flags2; }; typedef struct __sFILE __FILE; struct _glue { struct _glue *_next; int _niobs; __FILE *_iobs; }; struct _rand48 { unsigned short _seed[3]; unsigned short _mult[3]; unsigned short _add; }; struct _reent { int _errno; __FILE *_stdin, *_stdout, *_stderr; int _inc; char _emergency[25]; int _unspecified_locale_info; struct __locale_t *_locale; int __sdidinit; void (* __cleanup) (struct _reent *); struct _Bigint *_result; int _result_k; struct _Bigint *_p5s; struct _Bigint **_freelist; int _cvtlen; char *_cvtbuf; union { struct { unsigned int _unused_rand; char * _strtok_last; char _asctime_buf[26]; struct __tm _localtime_buf; int _gamma_signgam; __extension__ unsigned long long _rand_next; struct _rand48 _r48; _mbstate_t _mblen_state; _mbstate_t _mbtowc_state; _mbstate_t _wctomb_state; char _l64a_buf[8]; char _signal_buf[24]; int _getdate_err; _mbstate_t _mbrlen_state; _mbstate_t _mbrtowc_state; _mbstate_t _mbsrtowcs_state; _mbstate_t _wcrtomb_state; _mbstate_t _wcsrtombs_state; int _h_errno; } _reent; struct { unsigned char * _nextf[30]; unsigned int _nmalloc[30]; } _unused; } _new; struct _atexit *_atexit; struct _atexit _atexit0; void (**(_sig_func))(int); struct _glue __sglue; __FILE __sf[3]; }; extern struct _reent *_impure_ptr ; extern struct _reent *const _global_impure_ptr ; void _reclaim_reent (struct _reent *); struct __locale_t; typedef struct __locale_t *locale_t; void * memchr (const void *, int, size_t); int memcmp (const void *, const void *, size_t); void * memcpy (void * restrict, const void * restrict, size_t); void * memmove (void *, const void *, size_t); void * memset (void *, int, size_t); char *strcat (char *restrict, const char *restrict); char *strchr (const char *, int); int strcmp (const char *, const char *); int strcoll (const char *, const char *); char *strcpy (char *restrict, const char *restrict); size_t strcspn (const char *, const char *); char *strerror (int); size_t strlen (const char *); char *strncat (char *restrict, const char *restrict, size_t); int strncmp (const char *, const char *, size_t); char *strncpy (char *restrict, const char *restrict, size_t); char *strpbrk (const char *, const char *); char *strrchr (const char *, int); size_t strspn (const char *, const char *); char *strstr (const char *, const char *); char *strtok (char *restrict, const char *restrict); size_t strxfrm (char *restrict, const char *restrict, size_t); int strcoll_l (const char *, const char *, locale_t); char *strerror_l (int, locale_t); size_t strxfrm_l (char *restrict, const char *restrict, size_t, locale_t); char *strtok_r (char *restrict, const char *restrict, char **restrict); int bcmp (const void *, const void *, size_t); void bcopy (const void *, void *, size_t); void bzero (void *, size_t); void explicit_bzero (void *, size_t); int timingsafe_bcmp (const void *, const void *, size_t); int timingsafe_memcmp (const void *, const void *, size_t); int ffs (int); char *index (const char *, int); void * memccpy (void * restrict, const void * restrict, int, size_t); char *rindex (const char *, int); char *stpcpy (char *restrict, const char *restrict); char *stpncpy (char *restrict, const char *restrict, size_t); int strcasecmp (const char *, const char *); char *strdup (const char *); char *_strdup_r (struct _reent *, const char *); char *strndup (const char *, size_t); char *_strndup_r (struct _reent *, const char *, size_t); int strerror_r (int, char *, size_t) __asm__ ("" "__xpg_strerror_r") ; char * _strerror_r (struct _reent *, int, int, int *); size_t strlcat (char *, const char *, size_t); size_t strlcpy (char *, const char *, size_t); int strncasecmp (const char *, const char *, size_t); size_t strnlen (const char *, size_t); char *strsep (char **, const char *); char *strlwr (char *); char *strupr (char *); char *strsignal (int __signo); extern uint32_t __StackTop; extern uint32_t __StackLimit; enum { UNIT_0_625_MS = 625, UNIT_1_25_MS = 1250, UNIT_10_MS = 10000 }; typedef uint8_t uint16_le_t[2]; typedef uint8_t uint32_le_t[4]; typedef struct { uint16_t size; uint8_t * p_data; } uint8_array_t; static inline uint64_t value_rescale(uint32_t value, uint32_t old_unit_reversal, uint16_t new_unit_reversal) { return (uint64_t)((((uint64_t)value * new_unit_reversal) + ((old_unit_reversal) / 2)) / (old_unit_reversal)); } static inline uint8_t uint16_encode(uint16_t value, uint8_t * p_encoded_data) { p_encoded_data[0] = (uint8_t) ((value & 0x00FF) >> 0); p_encoded_data[1] = (uint8_t) ((value & 0xFF00) >> 8); return sizeof(uint16_t); } static inline uint8_t uint24_encode(uint32_t value, uint8_t * p_encoded_data) { p_encoded_data[0] = (uint8_t) ((value & 0x000000FF) >> 0); p_encoded_data[1] = (uint8_t) ((value & 0x0000FF00) >> 8); p_encoded_data[2] = (uint8_t) ((value & 0x00FF0000) >> 16); return 3; } static inline uint8_t uint32_encode(uint32_t value, uint8_t * p_encoded_data) { p_encoded_data[0] = (uint8_t) ((value & 0x000000FF) >> 0); p_encoded_data[1] = (uint8_t) ((value & 0x0000FF00) >> 8); p_encoded_data[2] = (uint8_t) ((value & 0x00FF0000) >> 16); p_encoded_data[3] = (uint8_t) ((value & 0xFF000000) >> 24); return sizeof(uint32_t); } static inline uint8_t uint48_encode(uint64_t value, uint8_t * p_encoded_data) { p_encoded_data[0] = (uint8_t) ((value & 0x0000000000FF) >> 0); p_encoded_data[1] = (uint8_t) ((value & 0x00000000FF00) >> 8); p_encoded_data[2] = (uint8_t) ((value & 0x000000FF0000) >> 16); p_encoded_data[3] = (uint8_t) ((value & 0x0000FF000000) >> 24); p_encoded_data[4] = (uint8_t) ((value & 0x00FF00000000) >> 32); p_encoded_data[5] = (uint8_t) ((value & 0xFF0000000000) >> 40); return 6; } static inline uint16_t uint16_decode(const uint8_t * p_encoded_data) { return ( (((uint16_t)((uint8_t *)p_encoded_data)[0])) | (((uint16_t)((uint8_t *)p_encoded_data)[1]) << 8 )); } static inline uint16_t uint16_big_decode(const uint8_t * p_encoded_data) { return ( (((uint16_t)((uint8_t *)p_encoded_data)[0]) << 8 ) | (((uint16_t)((uint8_t *)p_encoded_data)[1])) ); } static inline uint32_t uint24_decode(const uint8_t * p_encoded_data) { return ( (((uint32_t)((uint8_t *)p_encoded_data)[0]) << 0) | (((uint32_t)((uint8_t *)p_encoded_data)[1]) << 8) | (((uint32_t)((uint8_t *)p_encoded_data)[2]) << 16)); } static inline uint32_t uint32_decode(const uint8_t * p_encoded_data) { return ( (((uint32_t)((uint8_t *)p_encoded_data)[0]) << 0) | (((uint32_t)((uint8_t *)p_encoded_data)[1]) << 8) | (((uint32_t)((uint8_t *)p_encoded_data)[2]) << 16) | (((uint32_t)((uint8_t *)p_encoded_data)[3]) << 24 )); } static inline uint32_t uint32_big_decode(const uint8_t * p_encoded_data) { return ( (((uint32_t)((uint8_t *)p_encoded_data)[0]) << 24) | (((uint32_t)((uint8_t *)p_encoded_data)[1]) << 16) | (((uint32_t)((uint8_t *)p_encoded_data)[2]) << 8) | (((uint32_t)((uint8_t *)p_encoded_data)[3]) << 0) ); } static inline uint8_t uint16_big_encode(uint16_t value, uint8_t * p_encoded_data) { p_encoded_data[0] = (uint8_t) (value >> 8); p_encoded_data[1] = (uint8_t) (value & 0xFF); return sizeof(uint16_t); } static inline uint8_t uint32_big_encode(uint32_t value, uint8_t * p_encoded_data) { *(uint32_t *)p_encoded_data = __REV(value); return sizeof(uint32_t); } static inline uint64_t uint48_decode(const uint8_t * p_encoded_data) { return ( (((uint64_t)((uint8_t *)p_encoded_data)[0]) << 0) | (((uint64_t)((uint8_t *)p_encoded_data)[1]) << 8) | (((uint64_t)((uint8_t *)p_encoded_data)[2]) << 16) | (((uint64_t)((uint8_t *)p_encoded_data)[3]) << 24) | (((uint64_t)((uint8_t *)p_encoded_data)[4]) << 32) | (((uint64_t)((uint8_t *)p_encoded_data)[5]) << 40 )); } static inline uint8_t battery_level_in_percent(const uint16_t mvolts) { uint8_t battery_level; if (mvolts >= 3000) { battery_level = 100; } else if (mvolts > 2900) { battery_level = 100 - ((3000 - mvolts) * 58) / 100; } else if (mvolts > 2740) { battery_level = 42 - ((2900 - mvolts) * 24) / 160; } else if (mvolts > 2440) { battery_level = 18 - ((2740 - mvolts) * 12) / 300; } else if (mvolts > 2100) { battery_level = 6 - ((2440 - mvolts) * 6) / 340; } else { battery_level = 0; } return battery_level; } static inline _Bool is_word_aligned(void const* p) { return (((uintptr_t)p & 0x03) == 0); } static inline _Bool is_address_from_stack(void * ptr) { if (((uint32_t)ptr >= (uint32_t)&__StackLimit) && ((uint32_t)ptr < (uint32_t)&__StackTop) ) { return 1 ; } else { return 0 ; } } typedef __builtin_va_list __gnuc_va_list; typedef __gnuc_va_list va_list; typedef __uint8_t u_int8_t; typedef __uint16_t u_int16_t; typedef __uint32_t u_int32_t; typedef __uint64_t u_int64_t; typedef int register_t; typedef unsigned long __sigset_t; typedef __suseconds_t suseconds_t; typedef long time_t; struct timeval { time_t tv_sec; suseconds_t tv_usec; }; struct timespec { time_t tv_sec; long tv_nsec; }; struct itimerspec { struct timespec it_interval; struct timespec it_value; }; typedef __sigset_t sigset_t; typedef unsigned long fd_mask; typedef struct _types_fd_set { fd_mask fds_bits[(((64)+(((sizeof (fd_mask) * 8))-1))/((sizeof (fd_mask) * 8)))]; } _types_fd_set; int select (int __n, _types_fd_set *__readfds, _types_fd_set *__writefds, _types_fd_set *__exceptfds, struct timeval *__timeout) ; int pselect (int __n, _types_fd_set *__readfds, _types_fd_set *__writefds, _types_fd_set *__exceptfds, const struct timespec *__timeout, const sigset_t *__set) ; typedef __uint32_t in_addr_t; typedef __uint16_t in_port_t; typedef unsigned char u_char; typedef unsigned short u_short; typedef unsigned int u_int; typedef unsigned long u_long; typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long ulong; typedef __blkcnt_t blkcnt_t; typedef __blksize_t blksize_t; typedef unsigned long clock_t; typedef long daddr_t; typedef char * caddr_t; typedef __fsblkcnt_t fsblkcnt_t; typedef __fsfilcnt_t fsfilcnt_t; typedef __id_t id_t; typedef __ino_t ino_t; typedef __off_t off_t; typedef __dev_t dev_t; typedef __uid_t uid_t; typedef __gid_t gid_t; typedef __pid_t pid_t; typedef __key_t key_t; typedef _ssize_t ssize_t; typedef __mode_t mode_t; typedef __nlink_t nlink_t; typedef __clockid_t clockid_t; typedef __timer_t timer_t; typedef __useconds_t useconds_t; typedef __int64_t sbintime_t; typedef __FILE FILE; typedef _fpos_t fpos_t; char * ctermid (char *); FILE * tmpfile (void); char * tmpnam (char *); char * tempnam (const char *, const char *); int fclose (FILE *); int fflush (FILE *); FILE * freopen (const char *restrict, const char *restrict, FILE *restrict); void setbuf (FILE *restrict, char *restrict); int setvbuf (FILE *restrict, char *restrict, int, size_t); int fprintf (FILE *restrict, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; int fscanf (FILE *restrict, const char *restrict, ...) __attribute__ ((__format__ (__scanf__, 2, 3))) ; int printf (const char *restrict, ...) __attribute__ ((__format__ (__printf__, 1, 2))) ; int scanf (const char *restrict, ...) __attribute__ ((__format__ (__scanf__, 1, 2))) ; int sscanf (const char *restrict, const char *restrict, ...) __attribute__ ((__format__ (__scanf__, 2, 3))) ; int vfprintf (FILE *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int vprintf (const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 1, 0))) ; int vsprintf (char *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int fgetc (FILE *); char * fgets (char *restrict, int, FILE *restrict); int fputc (int, FILE *); int fputs (const char *restrict, FILE *restrict); int getc (FILE *); int getchar (void); char * gets (char *); int putc (int, FILE *); int putchar (int); int puts (const char *); int ungetc (int, FILE *); size_t fread (void * restrict, size_t _size, size_t _n, FILE *restrict); size_t fwrite (const void * restrict , size_t _size, size_t _n, FILE *); int fgetpos (FILE *restrict, fpos_t *restrict); int fseek (FILE *, long, int); int fsetpos (FILE *, const fpos_t *); long ftell ( FILE *); void rewind (FILE *); void clearerr (FILE *); int feof (FILE *); int ferror (FILE *); void perror (const char *); FILE * fopen (const char *restrict _name, const char *restrict _type); int sprintf (char *restrict, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; int remove (const char *); int rename (const char *, const char *); int fseeko (FILE *, off_t, int); off_t ftello ( FILE *); int snprintf (char *restrict, size_t, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int vsnprintf (char *restrict, size_t, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int vfscanf (FILE *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 2, 0))) ; int vscanf (const char *, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 1, 0))) ; int vsscanf (const char *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 2, 0))) ; int asiprintf (char **, const char *, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; char * asniprintf (char *, size_t *, const char *, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; char * asnprintf (char *restrict, size_t *restrict, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int diprintf (int, const char *, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; int fiprintf (FILE *, const char *, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; int fiscanf (FILE *, const char *, ...) __attribute__ ((__format__ (__scanf__, 2, 3))) ; int iprintf (const char *, ...) __attribute__ ((__format__ (__printf__, 1, 2))) ; int iscanf (const char *, ...) __attribute__ ((__format__ (__scanf__, 1, 2))) ; int siprintf (char *, const char *, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; int siscanf (const char *, const char *, ...) __attribute__ ((__format__ (__scanf__, 2, 3))) ; int sniprintf (char *, size_t, const char *, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int vasiprintf (char **, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; char * vasniprintf (char *, size_t *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; char * vasnprintf (char *, size_t *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int vdiprintf (int, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int vfiprintf (FILE *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int vfiscanf (FILE *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 2, 0))) ; int viprintf (const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 1, 0))) ; int viscanf (const char *, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 1, 0))) ; int vsiprintf (char *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int vsiscanf (const char *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 2, 0))) ; int vsniprintf (char *, size_t, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; FILE * fdopen (int, const char *); int fileno (FILE *); int pclose (FILE *); FILE * popen (const char *, const char *); void setbuffer (FILE *, char *, int); int setlinebuf (FILE *); int getw (FILE *); int putw (int, FILE *); int getc_unlocked (FILE *); int getchar_unlocked (void); void flockfile (FILE *); int ftrylockfile (FILE *); void funlockfile (FILE *); int putc_unlocked (int, FILE *); int putchar_unlocked (int); int dprintf (int, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; FILE * fmemopen (void *restrict, size_t, const char *restrict); FILE * open_memstream (char **, size_t *); int vdprintf (int, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int renameat (int, const char *, int, const char *); int _asiprintf_r (struct _reent *, char **, const char *, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; char * _asniprintf_r (struct _reent *, char *, size_t *, const char *, ...) __attribute__ ((__format__ (__printf__, 4, 5))) ; char * _asnprintf_r (struct _reent *, char *restrict, size_t *restrict, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 4, 5))) ; int _asprintf_r (struct _reent *, char **restrict, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int _diprintf_r (struct _reent *, int, const char *, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int _dprintf_r (struct _reent *, int, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int _fclose_r (struct _reent *, FILE *); int _fcloseall_r (struct _reent *); FILE * _fdopen_r (struct _reent *, int, const char *); int _fflush_r (struct _reent *, FILE *); int _fgetc_r (struct _reent *, FILE *); int _fgetc_unlocked_r (struct _reent *, FILE *); char * _fgets_r (struct _reent *, char *restrict, int, FILE *restrict); char * _fgets_unlocked_r (struct _reent *, char *restrict, int, FILE *restrict); int _fgetpos_r (struct _reent *, FILE *, fpos_t *); int _fsetpos_r (struct _reent *, FILE *, const fpos_t *); int _fiprintf_r (struct _reent *, FILE *, const char *, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int _fiscanf_r (struct _reent *, FILE *, const char *, ...) __attribute__ ((__format__ (__scanf__, 3, 4))) ; FILE * _fmemopen_r (struct _reent *, void *restrict, size_t, const char *restrict); FILE * _fopen_r (struct _reent *, const char *restrict, const char *restrict); FILE * _freopen_r (struct _reent *, const char *restrict, const char *restrict, FILE *restrict); int _fprintf_r (struct _reent *, FILE *restrict, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int _fpurge_r (struct _reent *, FILE *); int _fputc_r (struct _reent *, int, FILE *); int _fputc_unlocked_r (struct _reent *, int, FILE *); int _fputs_r (struct _reent *, const char *restrict, FILE *restrict); int _fputs_unlocked_r (struct _reent *, const char *restrict, FILE *restrict); size_t _fread_r (struct _reent *, void * restrict, size_t _size, size_t _n, FILE *restrict); size_t _fread_unlocked_r (struct _reent *, void * restrict, size_t _size, size_t _n, FILE *restrict); int _fscanf_r (struct _reent *, FILE *restrict, const char *restrict, ...) __attribute__ ((__format__ (__scanf__, 3, 4))) ; int _fseek_r (struct _reent *, FILE *, long, int); int _fseeko_r (struct _reent *, FILE *, _off_t, int); long _ftell_r (struct _reent *, FILE *); _off_t _ftello_r (struct _reent *, FILE *); void _rewind_r (struct _reent *, FILE *); size_t _fwrite_r (struct _reent *, const void * restrict, size_t _size, size_t _n, FILE *restrict); size_t _fwrite_unlocked_r (struct _reent *, const void * restrict, size_t _size, size_t _n, FILE *restrict); int _getc_r (struct _reent *, FILE *); int _getc_unlocked_r (struct _reent *, FILE *); int _getchar_r (struct _reent *); int _getchar_unlocked_r (struct _reent *); char * _gets_r (struct _reent *, char *); int _iprintf_r (struct _reent *, const char *, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; int _iscanf_r (struct _reent *, const char *, ...) __attribute__ ((__format__ (__scanf__, 2, 3))) ; FILE * _open_memstream_r (struct _reent *, char **, size_t *); void _perror_r (struct _reent *, const char *); int _printf_r (struct _reent *, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 2, 3))) ; int _putc_r (struct _reent *, int, FILE *); int _putc_unlocked_r (struct _reent *, int, FILE *); int _putchar_unlocked_r (struct _reent *, int); int _putchar_r (struct _reent *, int); int _puts_r (struct _reent *, const char *); int _remove_r (struct _reent *, const char *); int _rename_r (struct _reent *, const char *_old, const char *_new) ; int _scanf_r (struct _reent *, const char *restrict, ...) __attribute__ ((__format__ (__scanf__, 2, 3))) ; int _siprintf_r (struct _reent *, char *, const char *, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int _siscanf_r (struct _reent *, const char *, const char *, ...) __attribute__ ((__format__ (__scanf__, 3, 4))) ; int _sniprintf_r (struct _reent *, char *, size_t, const char *, ...) __attribute__ ((__format__ (__printf__, 4, 5))) ; int _snprintf_r (struct _reent *, char *restrict, size_t, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 4, 5))) ; int _sprintf_r (struct _reent *, char *restrict, const char *restrict, ...) __attribute__ ((__format__ (__printf__, 3, 4))) ; int _sscanf_r (struct _reent *, const char *restrict, const char *restrict, ...) __attribute__ ((__format__ (__scanf__, 3, 4))) ; char * _tempnam_r (struct _reent *, const char *, const char *); FILE * _tmpfile_r (struct _reent *); char * _tmpnam_r (struct _reent *, char *); int _ungetc_r (struct _reent *, int, FILE *); int _vasiprintf_r (struct _reent *, char **, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; char * _vasniprintf_r (struct _reent*, char *, size_t *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 4, 0))) ; char * _vasnprintf_r (struct _reent*, char *, size_t *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 4, 0))) ; int _vasprintf_r (struct _reent *, char **, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int _vdiprintf_r (struct _reent *, int, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int _vdprintf_r (struct _reent *, int, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int _vfiprintf_r (struct _reent *, FILE *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int _vfiscanf_r (struct _reent *, FILE *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 3, 0))) ; int _vfprintf_r (struct _reent *, FILE *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int _vfscanf_r (struct _reent *, FILE *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 3, 0))) ; int _viprintf_r (struct _reent *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int _viscanf_r (struct _reent *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 2, 0))) ; int _vprintf_r (struct _reent *, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 2, 0))) ; int _vscanf_r (struct _reent *, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 2, 0))) ; int _vsiprintf_r (struct _reent *, char *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int _vsiscanf_r (struct _reent *, const char *, const char *, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 3, 0))) ; int _vsniprintf_r (struct _reent *, char *, size_t, const char *, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 4, 0))) ; int _vsnprintf_r (struct _reent *, char *restrict, size_t, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 4, 0))) ; int _vsprintf_r (struct _reent *, char *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__printf__, 3, 0))) ; int _vsscanf_r (struct _reent *, const char *restrict, const char *restrict, __gnuc_va_list) __attribute__ ((__format__ (__scanf__, 3, 0))) ; int fpurge (FILE *); ssize_t __getdelim (char **, size_t *, int, FILE *); ssize_t __getline (char **, size_t *, FILE *); void clearerr_unlocked (FILE *); int feof_unlocked (FILE *); int ferror_unlocked (FILE *); int fileno_unlocked (FILE *); int fflush_unlocked (FILE *); int fgetc_unlocked (FILE *); int fputc_unlocked (int, FILE *); size_t fread_unlocked (void * restrict, size_t _size, size_t _n, FILE *restrict); size_t fwrite_unlocked (const void * restrict , size_t _size, size_t _n, FILE *); int __srget_r (struct _reent *, FILE *); int __swbuf_r (struct _reent *, int, FILE *); FILE *funopen (const void * __cookie, int (*__readfn)(void * __cookie, char *__buf, int __n), int (*__writefn)(void * __cookie, const char *__buf, int __n), fpos_t (*__seekfn)(void * __cookie, fpos_t __off, int __whence), int (*__closefn)(void * __cookie)) ; FILE *_funopen_r (struct _reent *, const void * __cookie, int (*__readfn)(void * __cookie, char *__buf, int __n), int (*__writefn)(void * __cookie, const char *__buf, int __n), fpos_t (*__seekfn)(void * __cookie, fpos_t __off, int __whence), int (*__closefn)(void * __cookie)) ; static __inline__ int __sputc_r(struct _reent *_ptr, int _c, FILE *_p) { if (--_p->_w >= 0 || (_p->_w >= _p->_lbfsize && (char)_c != '\n')) return (*_p->_p++ = _c); else return (__swbuf_r(_ptr, _c, _p)); } void app_error_fault_handler(uint32_t id, uint32_t pc, uint32_t info); typedef struct { uint16_t line_num; uint8_t const * p_file_name; uint32_t err_code; } error_info_t; typedef struct { uint16_t line_num; uint8_t const * p_file_name; } assert_info_t; void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t * p_file_name); void app_error_handler_bare(ret_code_t error_code); void app_error_save_and_stop(uint32_t id, uint32_t pc, uint32_t info); void assert_nrf_callback(uint16_t line_num, const uint8_t *file_name); typedef enum { NRF_DRV_STATE_UNINITIALIZED, NRF_DRV_STATE_INITIALIZED, NRF_DRV_STATE_POWERED_ON } nrf_drv_state_t; typedef enum { NRF_DRV_PWR_CTRL_ON, NRF_DRV_PWR_CTRL_OFF } nrf_drv_pwr_ctrl_t; typedef void (*nrf_drv_irq_handler_t)(void); void nrf_drv_common_irq_enable(IRQn_Type IRQn, uint8_t priority); void nrf_drv_common_clock_irq_disable(void); static inline _Bool nrf_drv_common_irq_enable_check(IRQn_Type IRQn); static inline void nrf_drv_common_irq_disable(IRQn_Type IRQn); static inline uint32_t nrf_drv_bitpos_to_event(uint32_t bit); static inline uint32_t nrf_drv_event_to_bitpos(uint32_t event); static inline IRQn_Type nrf_drv_get_IRQn(void const * const pinst); static inline void nrf_drv_common_power_clock_irq_init(void); static inline _Bool nrf_drv_is_in_RAM(void const * const ptr); static inline _Bool nrf_drv_common_irq_enable_check(IRQn_Type IRQn) { return 0 != (((NVIC_Type *) ((0xE000E000UL) + 0x0100UL) )->ISER[(((uint32_t)(int32_t)IRQn) >> 5UL)] & (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))); } static inline void nrf_drv_common_irq_disable(IRQn_Type IRQn) { NVIC_DisableIRQ(IRQn); } static inline uint32_t nrf_drv_bitpos_to_event(uint32_t bit) { return 0x100U + bit * sizeof(uint32_t); } static inline uint32_t nrf_drv_event_to_bitpos(uint32_t event) { return (event - 0x100U) / sizeof(uint32_t); } static inline IRQn_Type nrf_drv_get_IRQn(void const * const pinst) { uint8_t ret = (uint8_t)((uint32_t)pinst>>12U); return (IRQn_Type) ret; } static inline void nrf_drv_common_power_clock_irq_init(void) { if (!nrf_drv_common_irq_enable_check(POWER_CLOCK_IRQn)) { nrf_drv_common_irq_enable( POWER_CLOCK_IRQn, 7 ); } } static inline _Bool nrf_drv_is_in_RAM(void const * const ptr) { return ((((uintptr_t)ptr) & 0xE0000000u) == 0x20000000u); } typedef enum { APP_IRQ_PRIORITY_HIGHEST = 0, APP_IRQ_PRIORITY_HIGH = 2, APP_IRQ_PRIORITY_MID = 4, APP_IRQ_PRIORITY_LOW = 6, APP_IRQ_PRIORITY_LOWEST = 7, APP_IRQ_PRIORITY_THREAD = 15 } app_irq_priority_t; typedef enum { APP_LEVEL_UNPRIVILEGED, APP_LEVEL_PRIVILEGED } app_level_t; void app_util_critical_region_enter (uint8_t *p_nested); void app_util_critical_region_exit (uint8_t nested); uint8_t current_int_priority_get(void); uint8_t privilege_level_get(void); void nrf_drv_common_clock_irq_disable(void) { { nrf_drv_common_irq_disable(POWER_CLOCK_IRQn); } } void nrf_drv_common_irq_enable(IRQn_Type IRQn, uint8_t priority) { if (0) { if ((((priority)) < 8)) { } else { assert_nrf_callback((uint16_t)293, (uint8_t *)"platform/mcu/nrf52xxx/Drivers/drivers_nrf/common/nrf_drv_common.c"); } }; NVIC_SetPriority(IRQn, priority); NVIC_ClearPendingIRQ(IRQn); NVIC_EnableIRQ(IRQn); }
the_stack_data/67326148.c
#include <stdio.h> #include <string.h> #include <arpa/inet.h> #include <stdlib.h> #include <unistd.h> #define ECHOMAX (512) int main(int argc, char *argv[]) { unsigned short servPort; int sock; struct sockaddr_in servAddr; struct sockaddr_in clntAddr; unsigned int clntAddrLen; char msgBuffer[ECHOMAX]; int recvMsgLen; int sendMsgLen; if(argc != 2) { fprintf(stderr, "Usage: %s <Echo Port>\n", argv[0]); exit(1); } servPort = atoi(argv[1]); sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if(sock < 0) { fprintf(stderr, "socket() failed\n"); exit(1); } memset(&servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(servPort); if(bind(sock, (struct sockaddr *)&servAddr, sizeof(servAddr)) < 0) { fprintf(stderr, "bind() failed\n"); exit(1); } for(;;) { clntAddrLen = sizeof(clntAddr); recvMsgLen = recvfrom(sock, msgBuffer, ECHOMAX, 0, (struct sockaddr *)&clntAddr, &clntAddrLen); if(recvMsgLen < 0) { fprintf(stderr, "recvfrom() failed\n"); exit(1); } printf("Handling client %s\n", inet_ntoa(clntAddr.sin_addr)); sendMsgLen = sendto(sock, msgBuffer, recvMsgLen, 0, (struct sockaddr *)&clntAddr, sizeof(clntAddr)); if(recvMsgLen != sendMsgLen) { fprintf(stderr, "sendto() sent a differrent number of bytes than expected\n"); exit(1); } } }
the_stack_data/1257394.c
#include <stdio.h> #include <string.h> int reverse(char *str); int main() { char str[7] = { 'l', 'e', 'a', 'n', 'd', 'r', 'o' }; char *name = str; reverse(name); return 0; } int reverse(char *str) { if (strlen(str) == 0) return 0; printf("%c", str[strlen(str)-1]); str[strlen(str)-1] = 0; return reverse(str); }
the_stack_data/86075857.c
#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; //4 bytes. struct Node* next; //4 bytes. }NODE; NODE* head; //global node declaration to store address to first node of list. void insert_end(int x) { NODE* temp; //to store address to temporary node. NODE* loc = head; temp = (NODE*) malloc(sizeof(NODE)); /*malloc creates a node of 8 bytes and returns starting address of it, in void type, which then needs to be type casted to NODE type, to store in a NODE type pointer. So, temp now holds address of node.*/ temp->data = x; //dereferencing pointer to modify data at address. temp->next = NULL; if(loc == NULL) { head = temp; return; } else { while(loc->next != NULL) //till we reach the end of the list. { loc = loc->next; //finally loc with have the address of last node. } loc->next = temp; } } void printForward(NODE *loc) //here 'loc'is the head node, but it acts as a local variable. { if(loc == NULL) //exit condition. return; printf(" %d", loc->data); //print the value. printForward(loc->next); //recursive call to itself. } void printBackward(NODE *loc) //here 'loc'is the head node, but it acts as a local variable. { if(loc == NULL) //exit condition. return; printBackward(loc->next); //recursive call to itself. printf(" %d", loc->data); //print the value. } int main() { int n; head = NULL; //initially list is empty. insert_end(2);//func. call to insert. insert_end(4); insert_end(6); insert_end(5); //list: 2, 4, 6, 5 printf("\nIn forward manner: \n"); printForward(head); printf("\nIn backward manner: \n"); printBackward(head); return 0; }
the_stack_data/108820.c
#include <stdio.h> /* 函数声明 */ void swap(int x, int y); int main() { /* 局部变量定义 */ int a = 100; int b = 200; printf("交换前,a 的值:%d\n", a); printf("交换前,b 的值:%d\n", b); /* 调用函数来交换值 */ swap(a, b); printf("交换后,a 的值:%d\n", a); printf("交换后,b 的值:%d\n", b); return 0; } /* 函数定义 */ void swap(int x, int y) { int temp; temp = x; /* 保存 x 的值 */ x = y; /* 把 y 赋值给 x */ y = temp; /* 把temp赋值给y */ return; }
the_stack_data/88295.c
// // Created by weibin on 2022-01-12. // #include "stdio.h" #include "math.h" int main() { unsigned int result = pow(2, 32) - 1; printf("result = %u \n", result); return 0; }
the_stack_data/1177879.c
/* TRS */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/time.h> #include <sys/select.h> #include <netdb.h> #include <arpa/inet.h> #include <errno.h> #define TRSPORT 59000 #define TCSPORT 58067 #define MAX 500 #define MAX_CHAR 100 #define CLIENT_LIMIT 5 #define STDIN 0 int gracefulexit(char* str) { if(str!=NULL)printf("%s\n", str); exit(1); } int main(int argc, char **argv) { /* Variables */ FILE *fp, *fp_files, *fp_image; fd_set fds; int abort = 0, fd_tcs, fd_user, maxfd, newfd_user, i, i2, n_words, addrlen, clientlen, TRSport, size_file, nleft, nwritten, nread, TCSport; char *TCSname, *tokens, *buffer3, *tokensfile, *TRSname, filename[MAX_CHAR], filename2[MAX_CHAR], filename3[MAX_CHAR], filename_traduced[MAX_CHAR], TRSip[MAX], command[MAX_CHAR], answer[MAX], msg[MAX], buffer[MAX], buffer2[MAX], hostname[MAX], line[MAX]; char *language; struct hostent *hostptr; struct sockaddr_in serveraddr_tcs, serveraddr, clientaddr; struct hostent *h; struct in_addr *a; /* Analizing Flags */ language=argv[1]; TCSport=TCSPORT; TRSport=TRSPORT; if(gethostname(hostname,128)==-1) gracefulexit("error: detecting hostname"); TCSname=TRSname=&hostname[0]; if(argc!=2 && argc!=4 && argc!=6 && argc!=8) { gracefulexit("error: invalid arguments"); } if(argc>=3) { for(i=2; i<argc; i+=2) { if(strcmp(argv[i],"-n")==0) { TCSname=argv[i+1]; } else if(strcmp(argv[i],"-e")==0){ TCSport = atoi(argv[i+1]); } else if(strcmp(argv[i],"-p")==0){ TRSport = atoi(argv[i+1]); } else { gracefulexit("error: invalid arguments"); } } } h=gethostbyname(TRSname); a = (struct in_addr*)h->h_addr_list[0]; /* User TCP Server */ if((fd_user = socket(AF_INET, SOCK_STREAM, 0))==-1) { printf("error: creating TCP socket\n"); exit(1); } memset((void *)&serveraddr,(int)'\0',sizeof(serveraddr)); serveraddr.sin_family=AF_INET; serveraddr.sin_addr.s_addr=htonl(INADDR_ANY); serveraddr.sin_port=htons((u_short)TRSport); strcpy(TRSip,inet_ntoa(*a)); if(bind(fd_user, (struct sockaddr*)&serveraddr, sizeof(serveraddr))==-1) { printf("error: bind function\n"); close(fd_user); exit(1); } if(listen(fd_user,CLIENT_LIMIT)==-1) { printf("error: listen function\n"); close(fd_user); exit(1); } /* TCS UDP Client */ if((fd_tcs=socket(AF_INET,SOCK_DGRAM,0))==-1) { printf("error: creating UDP socket\n"); close(fd_user); exit(1); } hostptr=gethostbyname(TCSname); memset((void*)&serveraddr_tcs,(int)'\0',sizeof(serveraddr_tcs)); serveraddr_tcs.sin_family=AF_INET; serveraddr_tcs.sin_addr.s_addr=((struct in_addr *) (hostptr->h_addr_list[0]))->s_addr; serveraddr_tcs.sin_port=htons((u_short)TCSport); addrlen=sizeof(serveraddr_tcs); sprintf(msg, "SRG %s %s %d\n", language, TRSip, TRSport); sendto(fd_tcs,msg,strlen(msg),0,(struct sockaddr*) &serveraddr_tcs, addrlen); addrlen=sizeof(serveraddr_tcs); memset(buffer, 0, MAX); if(recvfrom(fd_tcs, buffer, sizeof(buffer),0,(struct sockaddr*)&serveraddr_tcs, &addrlen)==-1) { printf("error: receiving from TCS\n"); close(fd_tcs); close(fd_user); exit(1); } printf("%s", buffer); if(strcmp(buffer,"SRR OK\n")!=0){ printf("error: registing in TCS\n"); close(fd_tcs); close(fd_user); exit(1); } /* Open translation file */ sprintf(filename, "text_translation_%s.txt", language); if((fp = fopen(filename, "r"))==NULL) { printf("error: language not available - opening file\n"); abort = 1; } sprintf(filename2, "file_translation_%s.txt", language); if((fp_files = fopen(filename2, "r"))==NULL) { printf("error: language not available - opening file\n"); abort = 1; } while(1) { if(abort==1)break; FD_ZERO(&fds); FD_SET(fd_user, &fds); FD_SET(STDIN, &fds); maxfd = (fd_user > STDIN)?fd_user:STDIN; select(maxfd+1, &fds, NULL, NULL, NULL); if (FD_ISSET(STDIN, &fds)){ fgets(command, 128, stdin); tokens = strtok(command, " \n"); if(strcmp(command,"exit")==0){ break; } } if (FD_ISSET(fd_user, &fds)){ clientlen=sizeof(clientaddr); if((newfd_user=accept(fd_user,(struct sockaddr*)&clientaddr,&clientlen))==-1) { printf("error: accept function\n"); break; } memset(msg, 0, MAX); memset(buffer, 0, MAX); memset(buffer2, 0, MAX); read(newfd_user,buffer,MAX); if(strcmp(buffer,"\0")==0) { continue; } strcpy(buffer2, buffer); tokens=strtok(buffer, " \n"); if(strcmp("TRQ",tokens)==0) { tokens=strtok(NULL, " \n"); if(strcmp("t",tokens)==0) { if((tokens=strtok(NULL, " \n"))==NULL) { printf("error: invalid request\n"); strcpy(msg,"TRR ERR\n"); write(newfd_user, msg, strlen(msg)); continue; } if((n_words=atoi(tokens))==0) { printf("error: atoi function - invalid request\n"); strcpy(msg,"TRR ERR\n"); write(newfd_user, msg, strlen(msg)); continue; } if(n_words==0) strcpy(answer, "TRR ERR"); else { sprintf(answer, "TRR t %d", n_words); for(i=0; i<n_words; i++) { rewind(fp); strcpy(buffer, buffer2); for(tokens=strtok(buffer, " \n"), i2=0; i2<i+3 ; i2++, tokens=strtok(NULL, " \n")); //voltar a ter o tokens que queremos while(1) { if(fgets(line, MAX_CHAR, fp)==NULL) { printf("Translation request for word that we are not able to attend!\n"); strcpy(answer,"TRR NTA"); break; } tokensfile=strtok(line, " \n"); if(strcmp(tokens, tokensfile)==0) { sprintf(answer, "%s %s", answer, strtok(NULL, " \n")); break; } } } } sprintf(msg, "%s\n", answer); } else if(strcmp("f",tokens)==0) { if((tokens=strtok(NULL, " \n"))==NULL) { printf("error: invalid command\n"); close(newfd_user); continue; } strcpy(filename, tokens); sprintf(filename2, "files/%s" , filename); if((fp_image = fopen(filename2,"wb"))==NULL) { printf("error: no such filename\n"); close(newfd_user); break; } if((tokens=strtok(NULL, " \n"))==NULL) { printf("error: invalid command\n"); close(newfd_user); continue; } if((size_file=atoi(tokens))==0){ printf("error: atoi function - invalid answer\n"); close(newfd_user); continue; } nleft=size_file; tokens=(char*)malloc(sizeof(tokens)*(size_file+1)); buffer3 = (char*)malloc(sizeof(buffer3)*(size_file+1)); if((tokens=strtok(NULL, ""))!=NULL) { fwrite(tokens, 1, strlen(tokens), fp_image); nleft -= strlen(tokens); } while(nleft > 0) { nread=read(newfd_user, buffer3, nleft); fwrite(buffer3, 1, nread, fp_image); if(nread==-1) { printf("error: reading image data\n"); fclose(fp_image); break; } else if(nread==0)break; nleft-=nread; } if(fp_image==NULL) { printf("error: writting file\n"); continue; } free(tokens); free(buffer3); fclose(fp_image); printf("A traduzir:%s\n", filename); //Search for filename translation while(1) { if(fgets(line, MAX_CHAR, fp_files)==NULL) { printf("Translation request for word that we are not able to attend!\n"); strcpy(msg,"TRR NTA"); break; } tokensfile=strtok(line, " \n"); if(strcmp(tokensfile, filename)==0) { strcpy(filename_traduced, strtok(NULL, " \n")); break; } } if(strcmp(msg,"TRR NTA")==0) break; //Send file to user sprintf(filename3, "files/%s", filename_traduced); if((fp_image = fopen(filename3,"rb"))==NULL) { printf("error: no such filename\n"); close(newfd_user); break; } fseek(fp_image, 0, SEEK_END); size_file=ftell(fp_image); fseek(fp_image, 0, SEEK_SET); sprintf(msg, "TRR f %s %d " ,filename_traduced, size_file); write(newfd_user, msg, strlen(msg)); while(size_file > 0) { nwritten = write(newfd_user, fp_image, size_file); if(nwritten<=0) { printf("error: nwritten problem\n"); break; } size_file-=nwritten; fseek(fp_image, nwritten, SEEK_CUR); } strcpy(msg,"\n"); fclose(fp_image); } } else strcpy(msg, "TRR ERR\n"); write(newfd_user, msg, strlen(msg)); } } addrlen=sizeof(serveraddr_tcs); sprintf(msg, "SUN %s %s %d", language, TRSip, TRSport); sendto(fd_tcs,msg,strlen(msg),0,(struct sockaddr*) &serveraddr_tcs, addrlen); addrlen=sizeof(serveraddr_tcs); if(recvfrom(fd_tcs, buffer, sizeof(buffer),0,(struct sockaddr*)&serveraddr_tcs, &addrlen)==-1) exit(1); if(strcmp(buffer,"SUR OK\n")!=0) { printf("error: problems exiting from tcs\n"); } else printf("Exit Success\n"); /* Closing connection */ if(abort==0) { fclose(fp); fclose(fp_files); close(newfd_user); } close(fd_tcs); close(fd_user); return 0; }
the_stack_data/206394217.c
/* * lib/doc.c Documentation Purpose * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 2.1 * of the License. * * Copyright (c) 2003-2008 Thomas Graf <[email protected]> */ /** * @mainpage * * @section intro Introduction * * libnl is a set of libraries to deal with the netlink protocol and some * of the high level protocols implemented on top of it. Its goal is to * simplify netlink protocol usage and to create an abstraction layer using * object based interfaces for various netlink based subsystems.The library * was developed and tested on the 2.6.x kernel releases but it may work with * older kernel series. * * @section toc Table of Contents * * - \subpage core_doc * - \subpage route_doc * - \subpage genl_doc * - \subpage nf_doc * * @section remarks Remarks * * @subsection cache_alloc Allocation of Caches * * Almost all subsystem provide a function to allocate a new cache * of some form. The function usually looks like this: * @code * struct nl_cache *<object name>_alloc_cache(struct nl_sock *sk); * @endcode * * These functions allocate a new cache for the own object type, * initializes it properly and updates it to represent the current * state of their master, e.g. a link cache would include all * links currently configured in the kernel. * * Some of the allocation functions may take additional arguments * to further specify what will be part of the cache. * * All such functions return a newly allocated cache or NULL * in case of an error. * * @subsection addr Setting of Addresses * @code * int <object name>_set_addr(struct nl_object *, struct nl_addr *) * @endcode * * All attribute functions avaiable for assigning addresses to objects * take a struct nl_addr argument. The provided address object is * validated against the address family of the object if known already. * The assignment fails if the address families mismatch. In case the * address family has not been specified yet, the address family of * the new address is elected to be the new requirement. * * The function will acquire a new reference on the address object * before assignment, the caller is NOT responsible for this. * * All functions return 0 on success or a negative error code. * * @subsection flags Flags to Character StringTranslations * All functions converting a set of flags to a character string follow * the same principles, therefore, the following information applies * to all functions convertings flags to a character string and vice versa. * * @subsubsection flags2str Flags to Character String * @code * char *<object name>_flags2str(int flags, char *buf, size_t len) * @endcode * @arg flags Flags. * @arg buf Destination buffer. * @arg len Buffer length. * * Converts the specified flags to a character string separated by * commas and stores it in the specified destination buffer. * * @return The destination buffer * * @subsubsection str2flags Character String to Flags * @code * int <object name>_str2flags(const char *name) * @endcode * @arg name Name of flag. * * Converts the provided character string specifying a flag * to the corresponding numeric value. * * @return Link flag or a negative value if none was found. * * @subsubsection type2str Type to Character String * @code * char *<object name>_<type>2str(int type, char *buf, size_t len) * @endcode * @arg type Type as numeric value * @arg buf Destination buffer. * @arg len Buffer length. * * Converts an identifier (type) to a character string and stores * it in the specified destination buffer. * * @return The destination buffer or the type encoded in hexidecimal * form if the identifier is unknown. * * @subsubsection str2type Character String to Type * @code * int <object name>_str2<type>(const char *name) * @endcode * @arg name Name of identifier (type). * * Converts the provided character string specifying a identifier * to the corresponding numeric value. * * @return Identifier as numeric value or a negative value if none was found. * * @page core_doc Core Library (-lnl) * * @section core_intro Introduction * * The core library contains the fundamentals required to communicate over * netlink sockets. It deals with connecting and unconnecting of sockets, * sending and receiving of data, provides a customizeable receiving state * machine, and provides a abstract data type framework which eases the * implementation of object based netlink protocols where objects are added, * removed, or modified with the help of netlink messages. * * @section core_toc Table of Contents * * - \ref proto_fund * - \ref sk_doc * - \ref rxtx_doc * - \ref cb_doc * * @section proto_fund Netlink Protocol Fundamentals * * The netlink protocol is a socket based IPC mechanism used for communication * between userspace processes and the kernel. The netlink protocol uses the * \c AF_NETLINK address family and defines a protocol type for each subsystem * protocol (e.g. NETLINK_ROUTE, NETLINK_NETFILTER, etc). Its addressing * schema is based on a 32 bit port number, formerly referred to as PID, which * uniquely identifies each peer. * * The netlink protocol is based on messages each limited to the size of a * memory page and consists of the netlink message header (struct nlmsghdr) * plus the payload attached to it. The payload can consist of arbitary data * but often contains a fixed sized family specifc header followed by a * stream of \ref attr_doc. The use of attributes dramatically increases * the flexibility of the protocol and allows for the protocol to be * extended while maintaining backwards compatibility. * * The netlink message header (struct nlmsghdr): * @code * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-------------------------------------------------------------+ * | Length | * +------------------------------+------------------------------+ * | Type | Flags | * +------------------------------+------------------------------+ * | Sequence Number | * +-------------------------------------------------------------+ * | Port (Address) | * +-------------------------------------------------------------+ * @endcode * * Netlink differs between requests, notifications, and replies. Requests * are messages which have the \c NLM_F_REQUEST flag set and are meant to * request an action from the receiver. A request is typically sent from * a userspace process to the kernel. Every request should be assigned a * sequence number which should be incremented for each request sent on the * sending side. Depending on the nature of the request, the receiver may * reply to the request with regular netlink messages which should contain * the same sequence number as the request it relates to. Notifications are * of informal nature and don't expect a reply, therefore the sequence number * is typically set to 0. It should be noted that unlike in protocols such as * TCP there is no strict enforcment of the sequence number. The sole purpose * of sequence numbers is to assist a sender in relating replies to the * corresponding requests. * * @msc * A,B; * A=>B [label="GET (seq=1, NLM_F_REQUEST)"]; * A<=B [label="PUT (seq=1)"]; * ...; * A<=B [label="NOTIFY (seq=0)"]; * @endmsc * * If the size of a reply exceeds the size of a memory page and thus exceeds * the maximum message size, the reply can be split into a series of multipart * messages. A multipart message has the \c flag NLM_F_MULTI set and the * receiver is expected to continue parsing the reply until the special * message type \c NLMSG_DONE is received. * * @msc * A,B; * A=>B [label="GET (seq=1, NLM_F_REQUEST)"]; * A<=B [label="PUT (seq=1, NLM_F_MULTI)"]; * ...; * A<=B [label="PUT (seq=1, NLM_F_MULTI)"]; * A<=B [label="NLMSG_DONE (seq=1)"]; * @endmsc * * Errors can be reported using the standard message type \c NLMSG_ERROR which * can carry an error code and the netlink mesage header of the request. * Error messages should set their sequence number to the sequence number * of the message which caused the error. * * @msc * A,B; * A=>B [label="GET (seq=1, NLM_F_REQUEST)"]; * A<=B [label="NLMSG_ERROR code=EINVAL (seq=1)"]; * @endmsc * * The \c NLMSG_ERROR message type is also used to send acknowledge messages. * An acknowledge message can be requested by setting the \c NLM_F_ACK flag * message except that the error code is set to 0. * * @msc * A,B; * A=>B [label="GET (seq=1, NLM_F_REQUEST | NLM_F_ACK)"]; * A<=B [label="ACK (seq=1)"]; * @endmsc * * @section sk_doc Dealing with Netlink Sockets * * In order to use the netlink protocol, a netlink socket is required. Each * socket defines a completely independent context for sending and receiving * of messages. The netlink socket and all its related attributes are * represented by struct nl_sock. * * @code * nl_socket_alloc() Allocate new socket structure. * nl_socket_free(s) Free socket structure. * @endcode * * @subsection local_port Local Port * The local port number uniquely identifies the socket and is used to * address it. A unique local port is generated automatically when the socket * is allocated. It will consist of the Process ID (22 bits) and a random * number (10 bits) to allow up to 1024 sockets per process. * * @code * nl_socket_get_local_port(sk) Return the peer's port number. * nl_socket_set_local_port(sk, port) Set the peer's port number. * @endcode * * @subsection peer_port Peer Port * A peer port can be assigned to the socket which will result in all unicast * messages sent over the socket to be addresses to the corresponding peer. If * no peer is specified, the kernel will try to automatically bind the socket * to a kernel side socket of the same netlink protocol family. It is common * practice not to bind the socket to a peer port as typically only one kernel * side socket exists per netlink protocol family. * * @code * nl_socket_get_peer_port(sk) Return the local port number. * nl_socket_set_peer_port(sk, port) Set the local port number. * @endcode * * @subsection sock_fd File Descriptor * The file descriptor of the socket(2). * * @code * nl_socket_get_fd(sk) Return file descriptor. * nl_socket_set_buffer_size(sk, rx, tx) Set buffer size of socket. * nl_socket_set_nonblocking(sk) Set socket to non-blocking state. * @endcode * * @subsection group_sub Group Subscriptions * Each socket can subscribe to multicast groups of the netlink protocol * family it is bound to. The socket will then receive a copy of each * message sent to any of the groups. Multicast groups are commonly used * to implement event notifications. Prior to kernel 2.6.14 the group * subscription was performed using a bitmask which limited the number of * groups per protocol family to 32. This outdated interface can still be * accessed via the function nl_join_groups even though it is not recommended * for new code. Starting with 2.6.14 a new method was introduced which * supports subscribing to an almost unlimited number of multicast groups. * * @code * nl_socket_add_membership(sk, group) Become a member of a multicast group. * nl_socket_drop_membership(sk, group) Drop multicast group membership. * nl_join_groups(sk, groupmask) Join a multicast group (obsolete). * @endcode * * @subsection seq_num Sequence Numbers * The socket keeps track of the sequence numbers used. The library will * automatically verify the sequence number of messages received unless * the check was disabled using the function nl_socket_disable_seq_check(). * When a message is sent using nl_send_auto_complete(), the sequence number * is automatically filled in, and replies will be verified correctly. * * @code * nl_socket_disable_seq_check(sk) Disable checking of sequece numbers. * nl_socket_use_seq(sk) Use sequence number and bump to next. * @endcode * * @subsection sock_cb Callback Configuration * Every socket is associated a callback configuration which enables the * applications to hook into various internal functions and control the * receiving and sendings semantics. For more information, see section * \ref cb_doc. * * @code * nl_socket_alloc_cb(cb) Allocate socket based on callback set. * nl_socket_get_cb(sk) Return callback configuration. * nl_socket_set_cb(sk, cb) Replace callback configuration. * nl_socket_modify_cb(sk, ...) Modify a specific callback function. * @endcode * * @subsection sk_other Other Functions * @code * nl_socket_enable_auto_ack(sock) Enable automatic request of ACK. * nl_socket_disable_auto_ack(sock) Disable automatic request of ACK. * nl_socket_enable_msg_peek(sock) Enable message peeking. * nl_socket_disable_msg_peek(sock) Disable message peeking. * nl_socket_set_passcred(sk, state) Enable/disable credential passing. * nl_socket_recv_pktinfo(sk, state) Enable/disable packet information. * @endcode * * @section rxtx_doc Sending and Receiving of Data * * @subsection recv_semantisc Receiving Semantics * @code * nl_recvmsgs_default(set) * | cb = nl_socket_get_cb(sk) * v * nl_recvmsgs(sk, cb) * | [Application provides nl_recvmsgs() replacement] * |- - - - - - - - - - - - - - - v * | cb->cb_recvmsgs_ow() * | * | [Application provides nl_recv() replacement] * +-------------->|- - - - - - - - - - - - - - - v * | nl_recv() cb->cb_recv_ow() * | +----------->|<- - - - - - - - - - - - - - -+ * | | v * | | Parse Message * | | |- - - - - - - - - - - - - - - v * | | | NL_CB_MSG_IN() * | | |<- - - - - - - - - - - - - - -+ * | | | * | | |- - - - - - - - - - - - - - - v * | | Sequence Check NL_CB_SEQ_CHECK() * | | |<- - - - - - - - - - - - - - -+ * | | | * | | |- - - - - - - - - - - - - - - v [ NLM_F_ACK is set ] * | | | NL_CB_SEND_ACK() * | | |<- - - - - - - - - - - - - - -+ * | | | * | | +-----+------+--------------+----------------+--------------+ * | | v v v v v * | | Valid Message ACK NO-OP Message End of Multipart Error * | | | | | | | * | | v v v v v * | |NL_CB_VALID() NL_CB_ACK() NL_CB_SKIPPED() NL_CB_FINISH() cb->cb_err() * | | | | | | | * | | +------------+--------------+----------------+ v * | | | (FAILURE) * | | | [Callback returned NL_SKIP] * | | [More messages to be parsed] |<----------- * | +----------------------------------| * | | * | [is Multipart message] | * +-------------------------------------| [Callback returned NL_STOP] * |<----------- * v * (SUCCESS) * * At any time: * Message Format Error * |- - - - - - - - - - - - v * v NL_CB_INVALID() * (FAILURE) * * Message Overrun (Kernel Lost Data) * |- - - - - - - - - - - - v * v NL_CB_OVERRUN() * (FAILURE) * * Callback returned negative error code * (FAILURE) * @endcode * * @subsection send_semantics Sending Semantisc * * @code * nl_send_auto_complete(sk, msg) * | [Automatically completes netlink message header] * | [(local port, sequence number) ] * | * | [Application provies nl_send() replacement] * |- - - - - - - - - - - - - - - - - - - - v * v cb->cb_send_ow() * nl_send(sk, msg) * | [If available, add peer port and credentials] * v * nl_sendmsg(sk, msg, msghdr) * |- - - - - - - - - - - - - - - - - - - - v * | NL_CB_MSG_OUT() * |<- - - - - - - - - - - - - - - - - - - -+ * v * sendmsg() * @endcode * * @section cb_doc Callback Configurations * Callbacks and overwriting capabilities are provided to control various * semantics of the library. All callback functions are packed together in * struct nl_cb which is attached to a netlink socket or passed on to * the respective functions directly. * * @subsection cb_ret_doc Callback Return Values * Callback functions can control the flow of the calling layer by returning * appropriate error codes: * @code * Action ID | Description * -----------------+------------------------------------------------------- * NL_OK | Proceed with whatever comes next. * NL_SKIP | Skip message currently being processed and continue * | with next message. * NL_STOP | Stop parsing and discard all remaining messages in * | this set of messages. * @endcode * * All callbacks are optional and a default action is performed if no * application specific implementation is provided: * * @code * Callback ID | Default Return Value * ------------------+---------------------- * NL_CB_VALID | NL_OK * NL_CB_FINISH | NL_STOP * NL_CB_OVERRUN | NL_STOP * NL_CB_SKIPPED | NL_SKIP * NL_CB_ACK | NL_STOP * NL_CB_MSG_IN | NL_OK * NL_CB_MSG_OUT | NL_OK * NL_CB_INVALID | NL_STOP * NL_CB_SEQ_CHECK | NL_OK * NL_CB_SEND_ACK | NL_OK * | * Error Callback | NL_STOP * @endcode * * In order to simplify typical usages of the library, different sets of * default callback implementations exist: * @code * NL_CB_DEFAULT: No additional actions * NL_CB_VERBOSE: Automatically print warning and error messages to a file * descriptor as appropriate. This is useful for CLI based * applications. * NL_CB_DEBUG: Print informal debugging information for each message * received. This will result in every message beint sent or * received to be printed to the screen in a decoded, * human-readable format. * @endcode * * @par 1) Setting up a callback set * @code * // Allocate a callback set and initialize it to the verbose default set * struct nl_cb *cb = nl_cb_alloc(NL_CB_VERBOSE); * * // Modify the set to call my_func() for all valid messages * nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, my_func, NULL); * * // Set the error message handler to the verbose default implementation * // and direct it to print all errors to the given file descriptor. * FILE *file = fopen(...); * nl_cb_err(cb, NL_CB_VERBOSE, NULL, file); * @endcode * * @page route_doc Routing Family * * @page genl_doc Generic Netlink Family * * @page nf_doc Netfilter Subsystem */
the_stack_data/167331146.c
#include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; #ifdef _MSC_VER static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;} static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;} static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;} static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;} #else static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #endif #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #ifdef _MSC_VER #define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);} #define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);} #else #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #endif #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conjf(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimagf(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #ifdef _MSC_VER static _Fcomplex cpow_ui(complex x, integer n) { complex pow={1.0,0.0}; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i; for(u = n; ; ) { if(u & 01) pow.r *= x.r, pow.i *= x.i; if(u >>= 1) x.r *= x.r, x.i *= x.i; else break; } } _Fcomplex p={pow.r, pow.i}; return p; } #else static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #endif #ifdef _MSC_VER static _Dcomplex zpow_ui(_Dcomplex x, integer n) { _Dcomplex pow={1.0,0.0}; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1]; for(u = n; ; ) { if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1]; if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1]; else break; } } _Dcomplex p = {pow._Val[0], pow._Val[1]}; return p; } #else static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } #endif static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Fcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0]; zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0]; zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1]; } } pCf(z) = zdotc; } #else _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } #endif static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Dcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0]; zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0]; zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1]; } } pCd(z) = zdotc; } #else _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Fcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0]; zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0]; zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1]; } } pCf(z) = zdotc; } #else _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } #endif static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Dcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0]; zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0]; zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1]; } } pCd(z) = zdotc; } #else _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* Table of constant values */ static integer c__10 = 10; static integer c__1 = 1; static integer c__2 = 2; static integer c__3 = 3; static integer c__4 = 4; /* > \brief <b> SSTEVR computes the eigenvalues and, optionally, the left and/or right eigenvectors for OTHER matrices</b> */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download SSTEVR + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/sstevr. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/sstevr. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/sstevr. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE SSTEVR( JOBZ, RANGE, N, D, E, VL, VU, IL, IU, ABSTOL, */ /* M, W, Z, LDZ, ISUPPZ, WORK, LWORK, IWORK, */ /* LIWORK, INFO ) */ /* CHARACTER JOBZ, RANGE */ /* INTEGER IL, INFO, IU, LDZ, LIWORK, LWORK, M, N */ /* REAL ABSTOL, VL, VU */ /* INTEGER ISUPPZ( * ), IWORK( * ) */ /* REAL D( * ), E( * ), W( * ), WORK( * ), Z( LDZ, * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > SSTEVR computes selected eigenvalues and, optionally, eigenvectors */ /* > of a real symmetric tridiagonal matrix T. Eigenvalues and */ /* > eigenvectors can be selected by specifying either a range of values */ /* > or a range of indices for the desired eigenvalues. */ /* > */ /* > Whenever possible, SSTEVR calls SSTEMR to compute the */ /* > eigenspectrum using Relatively Robust Representations. SSTEMR */ /* > computes eigenvalues by the dqds algorithm, while orthogonal */ /* > eigenvectors are computed from various "good" L D L^T representations */ /* > (also known as Relatively Robust Representations). Gram-Schmidt */ /* > orthogonalization is avoided as far as possible. More specifically, */ /* > the various steps of the algorithm are as follows. For the i-th */ /* > unreduced block of T, */ /* > (a) Compute T - sigma_i = L_i D_i L_i^T, such that L_i D_i L_i^T */ /* > is a relatively robust representation, */ /* > (b) Compute the eigenvalues, lambda_j, of L_i D_i L_i^T to high */ /* > relative accuracy by the dqds algorithm, */ /* > (c) If there is a cluster of close eigenvalues, "choose" sigma_i */ /* > close to the cluster, and go to step (a), */ /* > (d) Given the approximate eigenvalue lambda_j of L_i D_i L_i^T, */ /* > compute the corresponding eigenvector by forming a */ /* > rank-revealing twisted factorization. */ /* > The desired accuracy of the output can be specified by the input */ /* > parameter ABSTOL. */ /* > */ /* > For more details, see "A new O(n^2) algorithm for the symmetric */ /* > tridiagonal eigenvalue/eigenvector problem", by Inderjit Dhillon, */ /* > Computer Science Division Technical Report No. UCB//CSD-97-971, */ /* > UC Berkeley, May 1997. */ /* > */ /* > */ /* > Note 1 : SSTEVR calls SSTEMR when the full spectrum is requested */ /* > on machines which conform to the ieee-754 floating point standard. */ /* > SSTEVR calls SSTEBZ and SSTEIN on non-ieee machines and */ /* > when partial spectrum requests are made. */ /* > */ /* > Normal execution of SSTEMR may create NaNs and infinities and */ /* > hence may abort due to a floating point exception in environments */ /* > which do not handle NaNs and infinities in the ieee standard default */ /* > manner. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] JOBZ */ /* > \verbatim */ /* > JOBZ is CHARACTER*1 */ /* > = 'N': Compute eigenvalues only; */ /* > = 'V': Compute eigenvalues and eigenvectors. */ /* > \endverbatim */ /* > */ /* > \param[in] RANGE */ /* > \verbatim */ /* > RANGE is CHARACTER*1 */ /* > = 'A': all eigenvalues will be found. */ /* > = 'V': all eigenvalues in the half-open interval (VL,VU] */ /* > will be found. */ /* > = 'I': the IL-th through IU-th eigenvalues will be found. */ /* > For RANGE = 'V' or 'I' and IU - IL < N - 1, SSTEBZ and */ /* > SSTEIN are called */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The order of the matrix. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in,out] D */ /* > \verbatim */ /* > D is REAL array, dimension (N) */ /* > On entry, the n diagonal elements of the tridiagonal matrix */ /* > A. */ /* > On exit, D may be multiplied by a constant factor chosen */ /* > to avoid over/underflow in computing the eigenvalues. */ /* > \endverbatim */ /* > */ /* > \param[in,out] E */ /* > \verbatim */ /* > E is REAL array, dimension (f2cmax(1,N-1)) */ /* > On entry, the (n-1) subdiagonal elements of the tridiagonal */ /* > matrix A in elements 1 to N-1 of E. */ /* > On exit, E may be multiplied by a constant factor chosen */ /* > to avoid over/underflow in computing the eigenvalues. */ /* > \endverbatim */ /* > */ /* > \param[in] VL */ /* > \verbatim */ /* > VL is REAL */ /* > If RANGE='V', the lower bound of the interval to */ /* > be searched for eigenvalues. VL < VU. */ /* > Not referenced if RANGE = 'A' or 'I'. */ /* > \endverbatim */ /* > */ /* > \param[in] VU */ /* > \verbatim */ /* > VU is REAL */ /* > If RANGE='V', the upper bound of the interval to */ /* > be searched for eigenvalues. VL < VU. */ /* > Not referenced if RANGE = 'A' or 'I'. */ /* > \endverbatim */ /* > */ /* > \param[in] IL */ /* > \verbatim */ /* > IL is INTEGER */ /* > If RANGE='I', the index of the */ /* > smallest eigenvalue to be returned. */ /* > 1 <= IL <= IU <= N, if N > 0; IL = 1 and IU = 0 if N = 0. */ /* > Not referenced if RANGE = 'A' or 'V'. */ /* > \endverbatim */ /* > */ /* > \param[in] IU */ /* > \verbatim */ /* > IU is INTEGER */ /* > If RANGE='I', the index of the */ /* > largest eigenvalue to be returned. */ /* > 1 <= IL <= IU <= N, if N > 0; IL = 1 and IU = 0 if N = 0. */ /* > Not referenced if RANGE = 'A' or 'V'. */ /* > \endverbatim */ /* > */ /* > \param[in] ABSTOL */ /* > \verbatim */ /* > ABSTOL is REAL */ /* > The absolute error tolerance for the eigenvalues. */ /* > An approximate eigenvalue is accepted as converged */ /* > when it is determined to lie in an interval [a,b] */ /* > of width less than or equal to */ /* > */ /* > ABSTOL + EPS * f2cmax( |a|,|b| ) , */ /* > */ /* > where EPS is the machine precision. If ABSTOL is less than */ /* > or equal to zero, then EPS*|T| will be used in its place, */ /* > where |T| is the 1-norm of the tridiagonal matrix obtained */ /* > by reducing A to tridiagonal form. */ /* > */ /* > See "Computing Small Singular Values of Bidiagonal Matrices */ /* > with Guaranteed High Relative Accuracy," by Demmel and */ /* > Kahan, LAPACK Working Note #3. */ /* > */ /* > If high relative accuracy is important, set ABSTOL to */ /* > SLAMCH( 'Safe minimum' ). Doing so will guarantee that */ /* > eigenvalues are computed to high relative accuracy when */ /* > possible in future releases. The current code does not */ /* > make any guarantees about high relative accuracy, but */ /* > future releases will. See J. Barlow and J. Demmel, */ /* > "Computing Accurate Eigensystems of Scaled Diagonally */ /* > Dominant Matrices", LAPACK Working Note #7, for a discussion */ /* > of which matrices define their eigenvalues to high relative */ /* > accuracy. */ /* > \endverbatim */ /* > */ /* > \param[out] M */ /* > \verbatim */ /* > M is INTEGER */ /* > The total number of eigenvalues found. 0 <= M <= N. */ /* > If RANGE = 'A', M = N, and if RANGE = 'I', M = IU-IL+1. */ /* > \endverbatim */ /* > */ /* > \param[out] W */ /* > \verbatim */ /* > W is REAL array, dimension (N) */ /* > The first M elements contain the selected eigenvalues in */ /* > ascending order. */ /* > \endverbatim */ /* > */ /* > \param[out] Z */ /* > \verbatim */ /* > Z is REAL array, dimension (LDZ, f2cmax(1,M) ) */ /* > If JOBZ = 'V', then if INFO = 0, the first M columns of Z */ /* > contain the orthonormal eigenvectors of the matrix A */ /* > corresponding to the selected eigenvalues, with the i-th */ /* > column of Z holding the eigenvector associated with W(i). */ /* > Note: the user must ensure that at least f2cmax(1,M) columns are */ /* > supplied in the array Z; if RANGE = 'V', the exact value of M */ /* > is not known in advance and an upper bound must be used. */ /* > \endverbatim */ /* > */ /* > \param[in] LDZ */ /* > \verbatim */ /* > LDZ is INTEGER */ /* > The leading dimension of the array Z. LDZ >= 1, and if */ /* > JOBZ = 'V', LDZ >= f2cmax(1,N). */ /* > \endverbatim */ /* > */ /* > \param[out] ISUPPZ */ /* > \verbatim */ /* > ISUPPZ is INTEGER array, dimension ( 2*f2cmax(1,M) ) */ /* > The support of the eigenvectors in Z, i.e., the indices */ /* > indicating the nonzero elements in Z. The i-th eigenvector */ /* > is nonzero only in elements ISUPPZ( 2*i-1 ) through */ /* > ISUPPZ( 2*i ). */ /* > Implemented only for RANGE = 'A' or 'I' and IU - IL = N - 1 */ /* > \endverbatim */ /* > */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is REAL array, dimension (MAX(1,LWORK)) */ /* > On exit, if INFO = 0, WORK(1) returns the optimal (and */ /* > minimal) LWORK. */ /* > \endverbatim */ /* > */ /* > \param[in] LWORK */ /* > \verbatim */ /* > LWORK is INTEGER */ /* > The dimension of the array WORK. LWORK >= 20*N. */ /* > */ /* > If LWORK = -1, then a workspace query is assumed; the routine */ /* > only calculates the optimal sizes of the WORK and IWORK */ /* > arrays, returns these values as the first entries of the WORK */ /* > and IWORK arrays, and no error message related to LWORK or */ /* > LIWORK is issued by XERBLA. */ /* > \endverbatim */ /* > */ /* > \param[out] IWORK */ /* > \verbatim */ /* > IWORK is INTEGER array, dimension (MAX(1,LIWORK)) */ /* > On exit, if INFO = 0, IWORK(1) returns the optimal (and */ /* > minimal) LIWORK. */ /* > \endverbatim */ /* > */ /* > \param[in] LIWORK */ /* > \verbatim */ /* > LIWORK is INTEGER */ /* > The dimension of the array IWORK. LIWORK >= 10*N. */ /* > */ /* > If LIWORK = -1, then a workspace query is assumed; the */ /* > routine only calculates the optimal sizes of the WORK and */ /* > IWORK arrays, returns these values as the first entries of */ /* > the WORK and IWORK arrays, and no error message related to */ /* > LWORK or LIWORK is issued by XERBLA. */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit */ /* > < 0: if INFO = -i, the i-th argument had an illegal value */ /* > > 0: Internal error */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date June 2016 */ /* > \ingroup realOTHEReigen */ /* > \par Contributors: */ /* ================== */ /* > */ /* > Inderjit Dhillon, IBM Almaden, USA \n */ /* > Osni Marques, LBNL/NERSC, USA \n */ /* > Ken Stanley, Computer Science Division, University of */ /* > California at Berkeley, USA \n */ /* > Jason Riedy, Computer Science Division, University of */ /* > California at Berkeley, USA \n */ /* > */ /* ===================================================================== */ /* Subroutine */ int sstevr_(char *jobz, char *range, integer *n, real *d__, real *e, real *vl, real *vu, integer *il, integer *iu, real *abstol, integer *m, real *w, real *z__, integer *ldz, integer *isuppz, real * work, integer *lwork, integer *iwork, integer *liwork, integer *info) { /* System generated locals */ integer z_dim1, z_offset, i__1, i__2; real r__1, r__2; /* Local variables */ integer imax; real rmin, rmax; logical test; real tnrm; integer i__, j; real sigma; extern logical lsame_(char *, char *); extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *); char order[1]; integer lwmin; extern /* Subroutine */ int scopy_(integer *, real *, integer *, real *, integer *), sswap_(integer *, real *, integer *, real *, integer * ); logical wantz; integer jj; logical alleig, indeig; integer iscale, ieeeok, indibl, indifl; logical valeig; extern real slamch_(char *); real safmin; extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *, ftnlen, ftnlen); extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen); real bignum; integer indisp, indiwo, liwmin; logical tryrac; extern real slanst_(char *, integer *, real *, real *); extern /* Subroutine */ int sstein_(integer *, real *, real *, integer *, real *, integer *, integer *, real *, integer *, real *, integer * , integer *, integer *), ssterf_(integer *, real *, real *, integer *); integer nsplit; extern /* Subroutine */ int sstebz_(char *, char *, integer *, real *, real *, integer *, integer *, real *, real *, real *, integer *, integer *, real *, integer *, integer *, real *, integer *, integer *); real smlnum; extern /* Subroutine */ int sstemr_(char *, char *, integer *, real *, real *, real *, real *, integer *, integer *, integer *, real *, real *, integer *, integer *, integer *, logical *, real *, integer *, integer *, integer *, integer *); logical lquery; real eps, vll, vuu, tmp1; /* -- LAPACK driver routine (version 3.7.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* June 2016 */ /* ===================================================================== */ /* Test the input parameters. */ /* Parameter adjustments */ --d__; --e; --w; z_dim1 = *ldz; z_offset = 1 + z_dim1 * 1; z__ -= z_offset; --isuppz; --work; --iwork; /* Function Body */ ieeeok = ilaenv_(&c__10, "SSTEVR", "N", &c__1, &c__2, &c__3, &c__4, ( ftnlen)6, (ftnlen)1); wantz = lsame_(jobz, "V"); alleig = lsame_(range, "A"); valeig = lsame_(range, "V"); indeig = lsame_(range, "I"); lquery = *lwork == -1 || *liwork == -1; /* Computing MAX */ i__1 = 1, i__2 = *n * 20; lwmin = f2cmax(i__1,i__2); /* Computing MAX */ i__1 = 1, i__2 = *n * 10; liwmin = f2cmax(i__1,i__2); *info = 0; if (! (wantz || lsame_(jobz, "N"))) { *info = -1; } else if (! (alleig || valeig || indeig)) { *info = -2; } else if (*n < 0) { *info = -3; } else { if (valeig) { if (*n > 0 && *vu <= *vl) { *info = -7; } } else if (indeig) { if (*il < 1 || *il > f2cmax(1,*n)) { *info = -8; } else if (*iu < f2cmin(*n,*il) || *iu > *n) { *info = -9; } } } if (*info == 0) { if (*ldz < 1 || wantz && *ldz < *n) { *info = -14; } } if (*info == 0) { work[1] = (real) lwmin; iwork[1] = liwmin; if (*lwork < lwmin && ! lquery) { *info = -17; } else if (*liwork < liwmin && ! lquery) { *info = -19; } } if (*info != 0) { i__1 = -(*info); xerbla_("SSTEVR", &i__1, (ftnlen)6); return 0; } else if (lquery) { return 0; } /* Quick return if possible */ *m = 0; if (*n == 0) { return 0; } if (*n == 1) { if (alleig || indeig) { *m = 1; w[1] = d__[1]; } else { if (*vl < d__[1] && *vu >= d__[1]) { *m = 1; w[1] = d__[1]; } } if (wantz) { z__[z_dim1 + 1] = 1.f; } return 0; } /* Get machine constants. */ safmin = slamch_("Safe minimum"); eps = slamch_("Precision"); smlnum = safmin / eps; bignum = 1.f / smlnum; rmin = sqrt(smlnum); /* Computing MIN */ r__1 = sqrt(bignum), r__2 = 1.f / sqrt(sqrt(safmin)); rmax = f2cmin(r__1,r__2); /* Scale matrix to allowable range, if necessary. */ iscale = 0; if (valeig) { vll = *vl; vuu = *vu; } tnrm = slanst_("M", n, &d__[1], &e[1]); if (tnrm > 0.f && tnrm < rmin) { iscale = 1; sigma = rmin / tnrm; } else if (tnrm > rmax) { iscale = 1; sigma = rmax / tnrm; } if (iscale == 1) { sscal_(n, &sigma, &d__[1], &c__1); i__1 = *n - 1; sscal_(&i__1, &sigma, &e[1], &c__1); if (valeig) { vll = *vl * sigma; vuu = *vu * sigma; } } /* Initialize indices into workspaces. Note: These indices are used only */ /* if SSTERF or SSTEMR fail. */ /* IWORK(INDIBL:INDIBL+M-1) corresponds to IBLOCK in SSTEBZ and */ /* stores the block indices of each of the M<=N eigenvalues. */ indibl = 1; /* IWORK(INDISP:INDISP+NSPLIT-1) corresponds to ISPLIT in SSTEBZ and */ /* stores the starting and finishing indices of each block. */ indisp = indibl + *n; /* IWORK(INDIFL:INDIFL+N-1) stores the indices of eigenvectors */ /* that corresponding to eigenvectors that fail to converge in */ /* SSTEIN. This information is discarded; if any fail, the driver */ /* returns INFO > 0. */ indifl = indisp + *n; /* INDIWO is the offset of the remaining integer workspace. */ indiwo = indisp + *n; /* If all eigenvalues are desired, then */ /* call SSTERF or SSTEMR. If this fails for some eigenvalue, then */ /* try SSTEBZ. */ test = FALSE_; if (indeig) { if (*il == 1 && *iu == *n) { test = TRUE_; } } if ((alleig || test) && ieeeok == 1) { i__1 = *n - 1; scopy_(&i__1, &e[1], &c__1, &work[1], &c__1); if (! wantz) { scopy_(n, &d__[1], &c__1, &w[1], &c__1); ssterf_(n, &w[1], &work[1], info); } else { scopy_(n, &d__[1], &c__1, &work[*n + 1], &c__1); if (*abstol <= *n * 2.f * eps) { tryrac = TRUE_; } else { tryrac = FALSE_; } i__1 = *lwork - (*n << 1); sstemr_(jobz, "A", n, &work[*n + 1], &work[1], vl, vu, il, iu, m, &w[1], &z__[z_offset], ldz, n, &isuppz[1], &tryrac, &work[ (*n << 1) + 1], &i__1, &iwork[1], liwork, info); } if (*info == 0) { *m = *n; goto L10; } *info = 0; } /* Otherwise, call SSTEBZ and, if eigenvectors are desired, SSTEIN. */ if (wantz) { *(unsigned char *)order = 'B'; } else { *(unsigned char *)order = 'E'; } sstebz_(range, order, n, &vll, &vuu, il, iu, abstol, &d__[1], &e[1], m, & nsplit, &w[1], &iwork[indibl], &iwork[indisp], &work[1], &iwork[ indiwo], info); if (wantz) { sstein_(n, &d__[1], &e[1], m, &w[1], &iwork[indibl], &iwork[indisp], & z__[z_offset], ldz, &work[1], &iwork[indiwo], &iwork[indifl], info); } /* If matrix was scaled, then rescale eigenvalues appropriately. */ L10: if (iscale == 1) { if (*info == 0) { imax = *m; } else { imax = *info - 1; } r__1 = 1.f / sigma; sscal_(&imax, &r__1, &w[1], &c__1); } /* If eigenvalues are not in order, then sort them, along with */ /* eigenvectors. */ if (wantz) { i__1 = *m - 1; for (j = 1; j <= i__1; ++j) { i__ = 0; tmp1 = w[j]; i__2 = *m; for (jj = j + 1; jj <= i__2; ++jj) { if (w[jj] < tmp1) { i__ = jj; tmp1 = w[jj]; } /* L20: */ } if (i__ != 0) { w[i__] = w[j]; w[j] = tmp1; sswap_(n, &z__[i__ * z_dim1 + 1], &c__1, &z__[j * z_dim1 + 1], &c__1); } /* L30: */ } } /* Causes problems with tests 19 & 20: */ /* IF (wantz .and. INDEIG ) Z( 1,1) = Z(1,1) / 1.002 + .002 */ work[1] = (real) lwmin; iwork[1] = liwmin; return 0; /* End of SSTEVR */ } /* sstevr_ */
the_stack_data/220456670.c
#include <sys/syscall.h> #include <termios.h> #include <sys/ioctl.h> int tcsetattr(int fildes, int optional_actions, const struct termios *termios_p) { //TODO: add bounds checking return ioctl(fildes, TCSETS + optional_actions, termios_p); }
the_stack_data/39813.c
#include <stdio.h> /* Scrivere un programma in C che chiede all'utente un valore intero e lo stampa a video. Si utilizzino i sottoprogrammi fprintf e fscanf sugli stream stdin e stdout */ int main() { int n; fscanf(stdin, "%d", &n); fprintf(stdout, "%d\n", n); /* E' equivalente a: scanf("%d", &n); printf("%d", n); stdin e stdout rappresentano rispettivamente tastiera e schermo, e si comportano come due puntatori a file in questo caso Esiste anche stderr, il buffer per gli errori. */ /* REDIRIZIONAMENTO DELL'INPUT E OUTPUT Se sul terminale scrivo: ./a.out < prova.txt chiedo al sistema operativo di utilizzare un file al posto della tastiera allo stesso modo. ./a.out > prova.txt chiede al sistema operativo di utilizzare il file come output non abbiamo aperto o scritto dei file. Lo stdin e stdout vengono utilizzati */ return 0; }
the_stack_data/1100377.c
#include <stdio.h> int main() { int x; printf("Hello World! %d\n",x); return 0; }
the_stack_data/96051.c
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2005, 2016 Oracle and/or its affiliates. All rights reserved. * * $Id$ */ /* File: txn_guide.c */ /* We assume an ANSI-compatible compiler */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <db.h> #ifdef _WIN32 #include <windows.h> #define PATHD '\\' extern int getopt(int, char * const *, const char *); extern char *optarg; /* Wrap Windows thread API to make it look POSIXey. */ typedef HANDLE thread_t; #define thread_create(thrp, attr, func, arg) \ (((*(thrp) = CreateThread(NULL, 0, \ (LPTHREAD_START_ROUTINE)(func), (arg), 0, NULL)) == NULL) ? -1 : 0) #define thread_join(thr, statusp) \ ((WaitForSingleObject((thr), INFINITE) == WAIT_OBJECT_0) && \ ((statusp == NULL) ? 0 : \ (GetExitCodeThread((thr), (LPDWORD)(statusp)) ? 0 : -1))) typedef HANDLE mutex_t; #define mutex_init(m, attr) \ (((*(m) = CreateMutex(NULL, FALSE, NULL)) != NULL) ? 0 : -1) #define mutex_lock(m) \ ((WaitForSingleObject(*(m), INFINITE) == WAIT_OBJECT_0) ? 0 : -1) #define mutex_unlock(m) (ReleaseMutex(*(m)) ? 0 : -1) #else #include <pthread.h> #include <unistd.h> #define PATHD '/' typedef pthread_t thread_t; #define thread_create(thrp, attr, func, arg) \ pthread_create((thrp), (attr), (func), (arg)) #define thread_join(thr, statusp) pthread_join((thr), (statusp)) typedef pthread_mutex_t mutex_t; #define mutex_init(m, attr) pthread_mutex_init((m), (attr)) #define mutex_lock(m) pthread_mutex_lock(m) #define mutex_unlock(m) pthread_mutex_unlock(m) #endif /* Run 5 writers threads at a time. */ #define NUMWRITERS 5 /* * Printing of a thread_t is implementation-specific, so we * create our own thread IDs for reporting purposes. */ int global_thread_num; mutex_t thread_num_lock; /* Forward declarations */ int count_records(DB *, DB_TXN *); int open_db(DB **, const char *, const char *, DB_ENV *, u_int32_t); int usage(void); void *writer_thread(void *); /* Usage function */ int usage() { fprintf(stderr, " [-h <database_home_directory>]\n"); return (EXIT_FAILURE); } int main(int argc, char *argv[]) { /* Initialize our handles */ DB *dbp = NULL; DB_ENV *envp = NULL; thread_t writer_threads[NUMWRITERS]; int ch, i, ret, ret_t; u_int32_t env_flags; char *db_home_dir; /* Application name */ const char *prog_name = "txn_guide"; /* Database file name */ const char *file_name = "mydb.db"; /* Parse the command line arguments */ #ifdef _WIN32 db_home_dir = ".\\"; #else db_home_dir = "./"; #endif while ((ch = getopt(argc, argv, "h:")) != EOF) switch (ch) { case 'h': db_home_dir = optarg; break; case '?': default: return (usage()); } /* Create the environment */ ret = db_env_create(&envp, 0); if (ret != 0) { fprintf(stderr, "Error creating environment handle: %s\n", db_strerror(ret)); goto err; } /* * Indicate that we want db to perform lock detection internally. * Also indicate that the transaction with the fewest number of * write locks will receive the deadlock notification in * the event of a deadlock. */ ret = envp->set_lk_detect(envp, DB_LOCK_MINWRITE); if (ret != 0) { fprintf(stderr, "Error setting lock detect: %s\n", db_strerror(ret)); goto err; } env_flags = DB_CREATE | /* Create the environment if it does not exist */ DB_RECOVER | /* Run normal recovery. */ DB_INIT_LOCK | /* Initialize the locking subsystem */ DB_INIT_LOG | /* Initialize the logging subsystem */ DB_INIT_TXN | /* Initialize the transactional subsystem. This * also turns on logging. */ DB_INIT_MPOOL | /* Initialize the memory pool (in-memory cache) */ DB_THREAD; /* Cause the environment to be free-threaded */ /* Now actually open the environment */ ret = envp->open(envp, db_home_dir, env_flags, 0); if (ret != 0) { fprintf(stderr, "Error opening environment: %s\n", db_strerror(ret)); goto err; } /* * If we had utility threads (for running checkpoints or * deadlock detection, for example) we would spawn those * here. However, for a simple example such as this, * that is not required. */ /* Open the database */ ret = open_db(&dbp, prog_name, file_name, envp, DB_DUPSORT); if (ret != 0) goto err; /* Initialize a mutex. Used to help provide thread ids. */ (void)mutex_init(&thread_num_lock, NULL); /* Start the writer threads. */ for (i = 0; i < NUMWRITERS; i++) (void)thread_create( &writer_threads[i], NULL, writer_thread, (void *)dbp); /* Join the writers */ for (i = 0; i < NUMWRITERS; i++) (void)thread_join(writer_threads[i], NULL); err: /* Close our database handle, if it was opened. */ if (dbp != NULL) { ret_t = dbp->close(dbp, 0); if (ret_t != 0) { fprintf(stderr, "%s database close failed: %s\n", file_name, db_strerror(ret_t)); ret = ret_t; } } /* Close our environment, if it was opened. */ if (envp != NULL) { ret_t = envp->close(envp, 0); if (ret_t != 0) { fprintf(stderr, "environment close failed: %s\n", db_strerror(ret_t)); ret = ret_t; } } /* Final status message and return. */ printf("I'm all done.\n"); return (ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE); } /* * A function that performs a series of writes to a * Berkeley DB database. The information written * to the database is largely nonsensical, but the * mechanism of transactional commit/abort and * deadlock detection is illustrated here. */ void * writer_thread(void *args) { static char *key_strings[] = { "key 1", "key 2", "key 3", "key 4", "key 5", "key 6", "key 7", "key 8", "key 9", "key 10" }; DB *dbp; DB_ENV *envp; DBT key, value; DB_TXN *txn; int i, j, payload, ret, thread_num; int retry_count, max_retries = 20; /* Max retry on a deadlock */ dbp = (DB *)args; envp = dbp->get_env(dbp); /* Get the thread number */ (void)mutex_lock(&thread_num_lock); global_thread_num++; thread_num = global_thread_num; (void)mutex_unlock(&thread_num_lock); /* Initialize the random number generator */ srand(thread_num); /* Write 50 times and then quit */ for (i = 0; i < 50; i++) { retry_count = 0; /* Used for deadlock retries */ /* * Some think it is bad form to loop with a goto statement, but * we do it anyway because it is the simplest and clearest way * to achieve our abort/retry operation. */ retry: /* Begin our transaction. We group multiple writes in * this thread under a single transaction so as to * (1) show that you can atomically perform multiple writes * at a time, and (2) to increase the chances of a * deadlock occurring so that we can observe our * deadlock detection at work. * * Normally we would want to avoid the potential for deadlocks, * so for this workload the correct thing would be to perform our * puts with autocommit. But that would excessively simplify our * example, so we do the "wrong" thing here instead. */ ret = envp->txn_begin(envp, NULL, &txn, 0); if (ret != 0) { envp->err(envp, ret, "txn_begin failed"); return ((void *)EXIT_FAILURE); } for (j = 0; j < 10; j++) { /* Set up our key and values DBTs */ memset(&key, 0, sizeof(DBT)); key.data = key_strings[j]; key.size = (u_int32_t)strlen(key_strings[j]) + 1; memset(&value, 0, sizeof(DBT)); payload = rand() + i; value.data = &payload; value.size = sizeof(int); /* Perform the database put. */ switch (ret = dbp->put(dbp, txn, &key, &value, 0)) { case 0: break; /* * Our database is configured for sorted duplicates, * so there is a potential for a KEYEXIST error return. * If we get one, simply ignore it and continue on. * * Note that you will see KEYEXIST errors only after you * have run this program at least once. */ case DB_KEYEXIST: printf("Got keyexists.\n"); break; /* * Here's where we perform deadlock detection. If * DB_LOCK_DEADLOCK is returned by the put operation, * then this thread has been chosen to break a deadlock. * It must abort its operation, and optionally retry the * put. */ case DB_LOCK_DEADLOCK: /* * First thing that we MUST do is abort the * transaction. */ (void)txn->abort(txn); /* * Now we decide if we want to retry the operation. * If we have retried less than max_retries, * increment the retry count and goto retry. */ if (retry_count < max_retries) { printf("Writer %i: Got DB_LOCK_DEADLOCK.\n", thread_num); printf("Writer %i: Retrying write operation.\n", thread_num); retry_count++; goto retry; } /* * Otherwise, just give up. */ printf("Writer %i: ", thread_num); printf("Got DB_LOCK_DEADLOCK and out of retries.\n"); printf("Writer %i: Giving up.\n", thread_num); return ((void *)EXIT_FAILURE); /* * If a generic error occurs, we simply abort the * transaction and exit the thread completely. */ default: envp->err(envp, ret, "db put failed"); ret = txn->abort(txn); if (ret != 0) envp->err(envp, ret, "txn abort failed"); return ((void *)EXIT_FAILURE); } /** End case statement **/ } /** End for loop **/ /* * print the number of records found in the database. * See count_records() for usage information. */ printf("Thread %i. Record count: %i\n", thread_num, count_records(dbp, NULL)); /* * If all goes well, we can commit the transaction and * exit the thread. */ ret = txn->commit(txn, 0); if (ret != 0) { envp->err(envp, ret, "txn commit failed"); return ((void *)EXIT_FAILURE); } } return ((void *)EXIT_SUCCESS); } /* * This simply counts the number of records contained in the * database and returns the result. You can use this function * in three ways: * * First call it with an active txn handle. * Secondly, configure the cursor for uncommitted reads (this * is what the example currently does). * Third, call count_records AFTER the writer has committed * its transaction. * * If you do none of these things, the writer thread will * self-deadlock. * * Note that this function exists only for illustrative purposes. * A more straight-forward way to count the number of records in * a database is to use DB->stat() or DB->stat_print(). */ int count_records(DB *dbp, DB_TXN *txn) { DBT key, value; DBC *cursorp; int count, ret; cursorp = NULL; count = 0; /* Get the cursor */ ret = dbp->cursor(dbp, txn, &cursorp, DB_READ_UNCOMMITTED); if (ret != 0) { dbp->err(dbp, ret, "count_records: cursor open failed."); goto cursor_err; } /* Get the key DBT used for the database read */ memset(&key, 0, sizeof(DBT)); memset(&value, 0, sizeof(DBT)); do { ret = cursorp->get(cursorp, &key, &value, DB_NEXT); switch (ret) { case 0: count++; break; case DB_NOTFOUND: break; default: dbp->err(dbp, ret, "Count records unspecified error"); goto cursor_err; } } while (ret == 0); cursor_err: if (cursorp != NULL) { ret = cursorp->close(cursorp); if (ret != 0) { dbp->err(dbp, ret, "count_records: cursor close failed."); } } return (count); } /* Open a Berkeley DB database */ int open_db(DB **dbpp, const char *progname, const char *file_name, DB_ENV *envp, u_int32_t extra_flags) { int ret; u_int32_t open_flags; DB *dbp; /* Initialize the DB handle */ ret = db_create(&dbp, envp, 0); if (ret != 0) { fprintf(stderr, "%s: %s\n", progname, db_strerror(ret)); return (EXIT_FAILURE); } /* Point to the memory malloc'd by db_create() */ *dbpp = dbp; if (extra_flags != 0) { ret = dbp->set_flags(dbp, extra_flags); if (ret != 0) { dbp->err(dbp, ret, "open_db: Attempt to set extra flags failed."); return (EXIT_FAILURE); } } /* Now open the database */ open_flags = DB_CREATE | /* Allow database creation */ DB_READ_UNCOMMITTED | /* Allow dirty reads */ DB_AUTO_COMMIT | /* Allow autocommit */ DB_THREAD; /* Cause the database to be free-threaded */ ret = dbp->open(dbp, /* Pointer to the database */ NULL, /* Txn pointer */ file_name, /* File name */ NULL, /* Logical db name */ DB_BTREE, /* Database type (using btree) */ open_flags, /* Open flags */ 0); /* File mode. Using defaults */ if (ret != 0) { dbp->err(dbp, ret, "Database '%s' open failed", file_name); return (EXIT_FAILURE); } return (EXIT_SUCCESS); }
the_stack_data/736954.c
void f() {} int main() { /** * This is a test case for the unwind operation of goto-instrument; * every loop will be unwound K times **/ const unsigned K=100; const unsigned n=10; unsigned c=0, i; unsigned tres=K/2;; for(i=1; i<=n; i++) { f(); c++; if(i==tres) break; } unsigned eva=n; if(K<eva) eva=K; if(tres<eva) eva=tres; __CPROVER_assert(c==eva, "break a loop unwind (2)"); }
the_stack_data/9356.c
int removeDuplicates(int* nums, int numsSize){ if (numsSize < 2) { return numsSize; } int i, j, curr; j = 0; curr = nums[0]; for (i = 1; i < numsSize; i++) { if (nums[i] != curr) { j++; curr = nums[i]; nums[i] = nums[j]; nums[j] = curr; } } return ++j; }
the_stack_data/690163.c
/// /// Perform several driver tests for OpenMP offloading /// // REQUIRES: clang-driver // REQUIRES: x86-registered-target // REQUIRES: powerpc-registered-target // REQUIRES: nvptx-registered-target /// ########################################################################### /// Check whether an invalid OpenMP target is specified: // RUN: %clang -### -fopenmp=libomp -fopenmp-targets=aaa-bbb-ccc-ddd %s 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-INVALID-TARGET %s // CHK-INVALID-TARGET: error: OpenMP target is invalid: 'aaa-bbb-ccc-ddd' /// ########################################################################### /// Check warning for empty -fopenmp-targets // RUN: %clang -### -fopenmp=libomp -fopenmp-targets= %s 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-EMPTY-OMPTARGETS %s // CHK-EMPTY-OMPTARGETS: warning: joined argument expects additional value: '-fopenmp-targets=' /// ########################################################################### /// Check error for no -fopenmp option // RUN: %clang -### -fopenmp-targets=powerpc64le-ibm-linux-gnu %s 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-NO-FOPENMP %s // RUN: %clang -### -fopenmp=libgomp -fopenmp-targets=powerpc64le-ibm-linux-gnu %s 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-NO-FOPENMP %s // CHK-NO-FOPENMP: error: The option -fopenmp-targets must be used in conjunction with a -fopenmp option compatible with offloading, please use -fopenmp=libomp or -fopenmp=libiomp5. /// ########################################################################### /// Check warning for duplicate offloading targets. // RUN: %clang -### -ccc-print-phases -fopenmp=libomp -fopenmp-targets=powerpc64le-ibm-linux-gnu,powerpc64le-ibm-linux-gnu %s 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-DUPLICATES %s // CHK-DUPLICATES: warning: The OpenMP offloading target 'powerpc64le-ibm-linux-gnu' is similar to target 'powerpc64le-ibm-linux-gnu' already specified - will be ignored. /// ########################################################################### /// Check the phases graph when using a single target, different from the host. /// We should have an offload action joining the host compile and device /// preprocessor and another one joining the device linking outputs to the host /// action. // RUN: %clang -ccc-print-phases -fopenmp=libomp -target powerpc64le-ibm-linux-gnu -fopenmp-targets=x86_64-pc-linux-gnu %s 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-PHASES %s // CHK-PHASES: 0: input, "[[INPUT:.+\.c]]", c, (host-openmp) // CHK-PHASES: 1: preprocessor, {0}, cpp-output, (host-openmp) // CHK-PHASES: 2: compiler, {1}, ir, (host-openmp) // CHK-PHASES: 3: backend, {2}, assembler, (host-openmp) // CHK-PHASES: 4: assembler, {3}, object, (host-openmp) // CHK-PHASES: 5: linker, {4}, image, (host-openmp) // CHK-PHASES: 6: input, "[[INPUT]]", c, (device-openmp) // CHK-PHASES: 7: preprocessor, {6}, cpp-output, (device-openmp) // CHK-PHASES: 8: compiler, {7}, ir, (device-openmp) // CHK-PHASES: 9: offload, "host-openmp (powerpc64le-ibm-linux-gnu)" {2}, "device-openmp (x86_64-pc-linux-gnu)" {8}, ir // CHK-PHASES: 10: backend, {9}, assembler, (device-openmp) // CHK-PHASES: 11: assembler, {10}, object, (device-openmp) // CHK-PHASES: 12: linker, {11}, image, (device-openmp) // CHK-PHASES: 13: offload, "host-openmp (powerpc64le-ibm-linux-gnu)" {5}, "device-openmp (x86_64-pc-linux-gnu)" {12}, image /// ########################################################################### /// Check the phases when using multiple targets. Here we also add a library to /// make sure it is treated as input by the device. // RUN: %clang -ccc-print-phases -lsomelib -fopenmp=libomp -target powerpc64-ibm-linux-gnu -fopenmp-targets=x86_64-pc-linux-gnu,powerpc64-ibm-linux-gnu %s 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-PHASES-LIB %s // CHK-PHASES-LIB: 0: input, "somelib", object, (host-openmp) // CHK-PHASES-LIB: 1: input, "[[INPUT:.+\.c]]", c, (host-openmp) // CHK-PHASES-LIB: 2: preprocessor, {1}, cpp-output, (host-openmp) // CHK-PHASES-LIB: 3: compiler, {2}, ir, (host-openmp) // CHK-PHASES-LIB: 4: backend, {3}, assembler, (host-openmp) // CHK-PHASES-LIB: 5: assembler, {4}, object, (host-openmp) // CHK-PHASES-LIB: 6: linker, {0, 5}, image, (host-openmp) // CHK-PHASES-LIB: 7: input, "somelib", object, (device-openmp) // CHK-PHASES-LIB: 8: input, "[[INPUT]]", c, (device-openmp) // CHK-PHASES-LIB: 9: preprocessor, {8}, cpp-output, (device-openmp) // CHK-PHASES-LIB: 10: compiler, {9}, ir, (device-openmp) // CHK-PHASES-LIB: 11: offload, "host-openmp (powerpc64-ibm-linux-gnu)" {3}, "device-openmp (x86_64-pc-linux-gnu)" {10}, ir // CHK-PHASES-LIB: 12: backend, {11}, assembler, (device-openmp) // CHK-PHASES-LIB: 13: assembler, {12}, object, (device-openmp) // CHK-PHASES-LIB: 14: linker, {7, 13}, image, (device-openmp) // CHK-PHASES-LIB: 15: input, "somelib", object, (device-openmp) // CHK-PHASES-LIB: 16: input, "[[INPUT]]", c, (device-openmp) // CHK-PHASES-LIB: 17: preprocessor, {16}, cpp-output, (device-openmp) // CHK-PHASES-LIB: 18: compiler, {17}, ir, (device-openmp) // CHK-PHASES-LIB: 19: offload, "host-openmp (powerpc64-ibm-linux-gnu)" {3}, "device-openmp (powerpc64-ibm-linux-gnu)" {18}, ir // CHK-PHASES-LIB: 20: backend, {19}, assembler, (device-openmp) // CHK-PHASES-LIB: 21: assembler, {20}, object, (device-openmp) // CHK-PHASES-LIB: 22: linker, {15, 21}, image, (device-openmp) // CHK-PHASES-LIB: 23: offload, "host-openmp (powerpc64-ibm-linux-gnu)" {6}, "device-openmp (x86_64-pc-linux-gnu)" {14}, "device-openmp (powerpc64-ibm-linux-gnu)" {22}, image /// ########################################################################### /// Check the phases when using multiple targets and multiple source files // RUN: echo " " > %t.c // RUN: %clang -ccc-print-phases -lsomelib -fopenmp=libomp -target powerpc64-ibm-linux-gnu -fopenmp-targets=x86_64-pc-linux-gnu,powerpc64-ibm-linux-gnu %s %t.c 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-PHASES-FILES %s // CHK-PHASES-FILES: 0: input, "somelib", object, (host-openmp) // CHK-PHASES-FILES: 1: input, "[[INPUT1:.+\.c]]", c, (host-openmp) // CHK-PHASES-FILES: 2: preprocessor, {1}, cpp-output, (host-openmp) // CHK-PHASES-FILES: 3: compiler, {2}, ir, (host-openmp) // CHK-PHASES-FILES: 4: backend, {3}, assembler, (host-openmp) // CHK-PHASES-FILES: 5: assembler, {4}, object, (host-openmp) // CHK-PHASES-FILES: 6: input, "[[INPUT2:.+\.c]]", c, (host-openmp) // CHK-PHASES-FILES: 7: preprocessor, {6}, cpp-output, (host-openmp) // CHK-PHASES-FILES: 8: compiler, {7}, ir, (host-openmp) // CHK-PHASES-FILES: 9: backend, {8}, assembler, (host-openmp) // CHK-PHASES-FILES: 10: assembler, {9}, object, (host-openmp) // CHK-PHASES-FILES: 11: linker, {0, 5, 10}, image, (host-openmp) // CHK-PHASES-FILES: 12: input, "somelib", object, (device-openmp) // CHK-PHASES-FILES: 13: input, "[[INPUT1]]", c, (device-openmp) // CHK-PHASES-FILES: 14: preprocessor, {13}, cpp-output, (device-openmp) // CHK-PHASES-FILES: 15: compiler, {14}, ir, (device-openmp) // CHK-PHASES-FILES: 16: offload, "host-openmp (powerpc64-ibm-linux-gnu)" {3}, "device-openmp (x86_64-pc-linux-gnu)" {15}, ir // CHK-PHASES-FILES: 17: backend, {16}, assembler, (device-openmp) // CHK-PHASES-FILES: 18: assembler, {17}, object, (device-openmp) // CHK-PHASES-FILES: 19: input, "[[INPUT2]]", c, (device-openmp) // CHK-PHASES-FILES: 20: preprocessor, {19}, cpp-output, (device-openmp) // CHK-PHASES-FILES: 21: compiler, {20}, ir, (device-openmp) // CHK-PHASES-FILES: 22: offload, "host-openmp (powerpc64-ibm-linux-gnu)" {8}, "device-openmp (x86_64-pc-linux-gnu)" {21}, ir // CHK-PHASES-FILES: 23: backend, {22}, assembler, (device-openmp) // CHK-PHASES-FILES: 24: assembler, {23}, object, (device-openmp) // CHK-PHASES-FILES: 25: linker, {12, 18, 24}, image, (device-openmp) // CHK-PHASES-FILES: 26: input, "somelib", object, (device-openmp) // CHK-PHASES-FILES: 27: input, "[[INPUT1]]", c, (device-openmp) // CHK-PHASES-FILES: 28: preprocessor, {27}, cpp-output, (device-openmp) // CHK-PHASES-FILES: 29: compiler, {28}, ir, (device-openmp) // CHK-PHASES-FILES: 30: offload, "host-openmp (powerpc64-ibm-linux-gnu)" {3}, "device-openmp (powerpc64-ibm-linux-gnu)" {29}, ir // CHK-PHASES-FILES: 31: backend, {30}, assembler, (device-openmp) // CHK-PHASES-FILES: 32: assembler, {31}, object, (device-openmp) // CHK-PHASES-FILES: 33: input, "[[INPUT2]]", c, (device-openmp) // CHK-PHASES-FILES: 34: preprocessor, {33}, cpp-output, (device-openmp) // CHK-PHASES-FILES: 35: compiler, {34}, ir, (device-openmp) // CHK-PHASES-FILES: 36: offload, "host-openmp (powerpc64-ibm-linux-gnu)" {8}, "device-openmp (powerpc64-ibm-linux-gnu)" {35}, ir // CHK-PHASES-FILES: 37: backend, {36}, assembler, (device-openmp) // CHK-PHASES-FILES: 38: assembler, {37}, object, (device-openmp) // CHK-PHASES-FILES: 39: linker, {26, 32, 38}, image, (device-openmp) // CHK-PHASES-FILES: 40: offload, "host-openmp (powerpc64-ibm-linux-gnu)" {11}, "device-openmp (x86_64-pc-linux-gnu)" {25}, "device-openmp (powerpc64-ibm-linux-gnu)" {39}, image /// ########################################################################### /// Check the phases graph when using a single GPU target, and check the OpenMP /// and CUDA phases are articulated correctly. // RUN: %clang -ccc-print-phases -fopenmp=libomp -target powerpc64le-ibm-linux-gnu -fopenmp-targets=nvptx64-nvidia-cuda -x cuda %s 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-PHASES-WITH-CUDA %s // CHK-PHASES-WITH-CUDA: 0: input, "[[INPUT:.+\.c]]", cuda, (host-cuda-openmp) // CHK-PHASES-WITH-CUDA: 1: preprocessor, {0}, cuda-cpp-output, (host-cuda-openmp) // CHK-PHASES-WITH-CUDA: 2: compiler, {1}, ir, (host-cuda-openmp) // CHK-PHASES-WITH-CUDA: 3: input, "[[INPUT]]", cuda, (device-cuda, sm_20) // CHK-PHASES-WITH-CUDA: 4: preprocessor, {3}, cuda-cpp-output, (device-cuda, sm_20) // CHK-PHASES-WITH-CUDA: 5: compiler, {4}, ir, (device-cuda, sm_20) // CHK-PHASES-WITH-CUDA: 6: backend, {5}, assembler, (device-cuda, sm_20) // CHK-PHASES-WITH-CUDA: 7: assembler, {6}, object, (device-cuda, sm_20) // CHK-PHASES-WITH-CUDA: 8: offload, "device-cuda (nvptx64-nvidia-cuda:sm_20)" {7}, object // CHK-PHASES-WITH-CUDA: 9: offload, "device-cuda (nvptx64-nvidia-cuda:sm_20)" {6}, assembler // CHK-PHASES-WITH-CUDA: 10: linker, {8, 9}, cuda-fatbin, (device-cuda) // CHK-PHASES-WITH-CUDA: 11: offload, "host-cuda-openmp (powerpc64le-ibm-linux-gnu)" {2}, "device-cuda (nvptx64-nvidia-cuda)" {10}, ir // CHK-PHASES-WITH-CUDA: 12: backend, {11}, assembler, (host-cuda-openmp) // CHK-PHASES-WITH-CUDA: 13: assembler, {12}, object, (host-cuda-openmp) // CHK-PHASES-WITH-CUDA: 14: linker, {13}, image, (host-cuda-openmp) // CHK-PHASES-WITH-CUDA: 15: input, "[[INPUT]]", cuda, (device-openmp) // CHK-PHASES-WITH-CUDA: 16: preprocessor, {15}, cuda-cpp-output, (device-openmp) // CHK-PHASES-WITH-CUDA: 17: compiler, {16}, ir, (device-openmp) // CHK-PHASES-WITH-CUDA: 18: offload, "host-cuda-openmp (powerpc64le-ibm-linux-gnu)" {2}, "device-openmp (nvptx64-nvidia-cuda)" {17}, ir // CHK-PHASES-WITH-CUDA: 19: backend, {18}, assembler, (device-openmp) // CHK-PHASES-WITH-CUDA: 20: assembler, {19}, object, (device-openmp) // CHK-PHASES-WITH-CUDA: 21: linker, {20}, image, (device-openmp) // CHK-PHASES-WITH-CUDA: 22: offload, "host-cuda-openmp (powerpc64le-ibm-linux-gnu)" {14}, "device-openmp (nvptx64-nvidia-cuda)" {21}, image /// ########################################################################### /// Check of the commands passed to each tool when using valid OpenMP targets. /// Here we also check that offloading does not break the use of integrated /// assembler. It does however preclude the merge of the host compile and /// backend phases. There are also two offloading specific options: /// -fopenmp-is-device: will tell the frontend that it will generate code for a /// target. /// -fopenmp-host-ir-file-path: specifies the host IR file that can be loaded by /// the target code generation to gather information about which declaration /// really need to be emitted. /// We use -fopenmp-dump-offload-linker-script to dump the linker script and /// check its contents. /// // RUN: %clang -### -fopenmp=libomp -o %t.out -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %s -fopenmp-dump-offload-linker-script -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-COMMANDS -check-prefix=CHK-LKS -check-prefix=CHK-LKS-REG %s // RUN: %clang -### -fopenmp=libomp -o %t.out -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %s -save-temps -fopenmp-dump-offload-linker-script -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-COMMANDS-ST -check-prefix=CHK-LKS -check-prefix=CHK-LKS-ST %s // Make sure we are not dumping the script unless the user requested it. // RUN: %clang -### -fopenmp=libomp -o %t.out -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %s -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-LKS-NODUMP %s // RUN: %clang -### -fopenmp=libomp -o %t.out -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %s -save-temps -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-LKS-NODUMP %s // // Check the linker script contains what we expect. // // CHK-LKS: /* // CHK-LKS: OpenMP Offload Linker Script // CHK-LKS: *** Automatically generated by Clang *** // CHK-LKS-NODUMP-NOT: OpenMP Offload Linker Script. // CHK-LKS: */ // CHK-LKS: TARGET(binary) // CHK-LKS-REG: INPUT([[T1BIN:.+\.out]]) // CHK-LKS-REG: INPUT([[T2BIN:.+\.out]]) // CHK-LKS-ST: INPUT([[T1BIN:.+\.out-openmp-powerpc64le-ibm-linux-gnu]]) // CHK-LKS-ST: INPUT([[T2BIN:.+\.out-openmp-x86_64-pc-linux-gnu]]) // CHK-LKS: SECTIONS // CHK-LKS: { // CHK-LKS: .omp_offloading.powerpc64le-ibm-linux-gnu : // CHK-LKS: ALIGN(0x10) // CHK-LKS: { // CHK-LKS: PROVIDE_HIDDEN(.omp_offloading.img_start.powerpc64le-ibm-linux-gnu = .); // CHK-LKS: [[T1BIN]] // CHK-LKS: PROVIDE_HIDDEN(.omp_offloading.img_end.powerpc64le-ibm-linux-gnu = .); // CHK-LKS: } // CHK-LKS: .omp_offloading.x86_64-pc-linux-gnu : // CHK-LKS: ALIGN(0x10) // CHK-LKS: { // CHK-LKS: PROVIDE_HIDDEN(.omp_offloading.img_start.x86_64-pc-linux-gnu = .); // CHK-LKS: [[T2BIN]] // CHK-LKS: PROVIDE_HIDDEN(.omp_offloading.img_end.x86_64-pc-linux-gnu = .); // CHK-LKS: } // CHK-LKS: .omp_offloading.entries : // CHK-LKS: ALIGN(0x10) // CHK-LKS: SUBALIGN(0x01) // CHK-LKS: { // CHK-LKS: PROVIDE_HIDDEN(.omp_offloading.entries_begin = .); // CHK-LKS: *(.omp_offloading.entries) // CHK-LKS: PROVIDE_HIDDEN(.omp_offloading.entries_end = .); // CHK-LKS: } // CHK-LKS: } // CHK-LKS: INSERT BEFORE .data // // Generate host BC file. // // CHK-COMMANDS: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-o" " // CHK-COMMANDS-SAME: [[HOSTBC:[^\\/]+\.bc]]" "-x" "c" " // CHK-COMMANDS-SAME: [[INPUT:[^\\/]+\.c]]" "-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu" // CHK-COMMANDS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-E" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[HOSTPP:[^\\/]+\.i]]" "-x" "c" " // CHK-COMMANDS-ST-SAME: [[INPUT:[^\\/]+\.c]]" // CHK-COMMANDS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[HOSTBC:[^\\/]+\.bc]]" "-x" "cpp-output" "{{.*}}[[HOSTPP]]" "-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu" // // Compile for the powerpc device. // // CHK-COMMANDS: clang{{.*}}" "-cc1" "-triple" "powerpc64le-ibm-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-obj" {{.*}}"-pic-level" "2" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-COMMANDS-SAME: [[T1OBJ:[^\\/]+\.o]]" "-x" "c" "{{.*}}[[INPUT]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-COMMANDS: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-COMMANDS-SAME: [[T1BIN:[^\\/]+\.out]]" {{.*}}"{{.*}}[[T1OBJ]]" // CHK-COMMANDS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le-ibm-linux-gnu" "-aux-triple" "powerpc64le--linux" "-E" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[T1PP:[^\\/]+\.i]]" "-x" "c" "{{.*}}[[INPUT]]" // CHK-COMMANDS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le-ibm-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-pic-level" "2" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[T1BC:[^\\/]+\.bc]]" "-x" "cpp-output" "{{.*}}[[T1PP]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-COMMANDS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le-ibm-linux-gnu" "-aux-triple" "powerpc64le--linux" "-S" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[T1ASM:[^\\/]+\.s]]" "-x" "ir" "{{.*}}[[T1BC]]" // CHK-COMMANDS-ST: clang{{.*}}" "-cc1as" "-triple" "powerpc64le-ibm-linux-gnu" "-filetype" "obj" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[T1OBJ:[^\\/]+\.o]]" "{{.*}}[[T1ASM]]" // CHK-COMMANDS-ST: ld{{(\.exe)?}}" {{.*}}"-shared" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[T1BIN:[^\\/]+\.out-openmp-powerpc64le-ibm-linux-gnu]]" {{.*}}"{{.*}}[[T1OBJ]]" // // Compile for the x86 device. // // CHK-COMMANDS: clang{{.*}}" "-cc1" "-triple" "x86_64-pc-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-obj" {{.*}}"-pic-level" "2" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-COMMANDS-SAME: [[T2OBJ:[^\\/]+\.o]]" "-x" "c" "{{.*}}[[INPUT]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-COMMANDS: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-COMMANDS-SAME: [[T2BIN:[^\\/]+\.out]]" {{.*}}"{{.*}}[[T2OBJ]]" // CHK-COMMANDS-ST: clang{{.*}}" "-cc1" "-triple" "x86_64-pc-linux-gnu" "-aux-triple" "powerpc64le--linux" "-E" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[T2PP:[^\\/]+\.i]]" "-x" "c" "{{.*}}[[INPUT]]" // CHK-COMMANDS-ST: clang{{.*}}" "-cc1" "-triple" "x86_64-pc-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-pic-level" "2" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[T2BC:[^\\/]+\.bc]]" "-x" "cpp-output" "{{.*}}[[T2PP]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-COMMANDS-ST: clang{{.*}}" "-cc1" "-triple" "x86_64-pc-linux-gnu" "-aux-triple" "powerpc64le--linux" "-S" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[T2ASM:[^\\/]+\.s]]" "-x" "ir" "{{.*}}[[T2BC]]" // CHK-COMMANDS-ST: clang{{.*}}" "-cc1as" "-triple" "x86_64-pc-linux-gnu" "-filetype" "obj" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[T2OBJ:[^\\/]+\.o]]" "{{.*}}[[T2ASM]]" // CHK-COMMANDS-ST: ld{{(\.exe)?}}" {{.*}}"-shared" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[T2BIN:[^\\/]+\.out-openmp-x86_64-pc-linux-gnu]]" {{.*}}"{{.*}}[[T2OBJ]]" // // Generate host object from the BC file and link using the linker script. // // CHK-COMMANDS: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-emit-obj" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-COMMANDS-SAME: [[HOSTOBJ:[^\\/]+\.o]]" "-x" "ir" "{{.*}}[[HOSTBC]]" // CHK-COMMANDS: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-COMMANDS-SAME: [[HOSTBIN:[^\\/]+\.out]]" {{.*}}"-lomptarget" {{.*}}"-T" " // CHK-COMMANDS-SAME: [[HOSTLK:[^\\/]+\.lk]]" // CHK-COMMANDS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-S" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[HOSTASM:[^\\/]+\.s]]" "-x" "ir" "{{.*}}[[HOSTBC]]" // CHK-COMMANDS-ST: clang{{.*}}" "-cc1as" "-triple" "powerpc64le--linux" "-filetype" "obj" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[HOSTOBJ:[^\\/]+\.o]]" "{{.*}}[[HOSTASM]]" // CHK-COMMANDS-ST: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-COMMANDS-ST-SAME: [[HOSTBIN:[^\\/]+\.out]]" {{.*}}"-lomptarget" {{.*}}"-T" " // CHK-COMMANDS-ST-SAME: [[HOSTLK:[^\\/]+\.lk]]" /// ########################################################################### /// Check separate compilation with offloading - bundling actions // RUN: %clang -### -ccc-print-phases -fopenmp=libomp -c -o %t.o -lsomelib -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %s -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-BUACTIONS %s // CHK-BUACTIONS: 0: input, "[[INPUT:.+\.c]]", c, (host-openmp) // CHK-BUACTIONS: 1: preprocessor, {0}, cpp-output, (host-openmp) // CHK-BUACTIONS: 2: compiler, {1}, ir, (host-openmp) // CHK-BUACTIONS: 3: input, "[[INPUT]]", c, (device-openmp) // CHK-BUACTIONS: 4: preprocessor, {3}, cpp-output, (device-openmp) // CHK-BUACTIONS: 5: compiler, {4}, ir, (device-openmp) // CHK-BUACTIONS: 6: offload, "host-openmp (powerpc64le--linux)" {2}, "device-openmp (powerpc64le-ibm-linux-gnu)" {5}, ir // CHK-BUACTIONS: 7: backend, {6}, assembler, (device-openmp) // CHK-BUACTIONS: 8: assembler, {7}, object, (device-openmp) // CHK-BUACTIONS: 9: offload, "device-openmp (powerpc64le-ibm-linux-gnu)" {8}, object // CHK-BUACTIONS: 10: input, "[[INPUT]]", c, (device-openmp) // CHK-BUACTIONS: 11: preprocessor, {10}, cpp-output, (device-openmp) // CHK-BUACTIONS: 12: compiler, {11}, ir, (device-openmp) // CHK-BUACTIONS: 13: offload, "host-openmp (powerpc64le--linux)" {2}, "device-openmp (x86_64-pc-linux-gnu)" {12}, ir // CHK-BUACTIONS: 14: backend, {13}, assembler, (device-openmp) // CHK-BUACTIONS: 15: assembler, {14}, object, (device-openmp) // CHK-BUACTIONS: 16: offload, "device-openmp (x86_64-pc-linux-gnu)" {15}, object // CHK-BUACTIONS: 17: backend, {2}, assembler, (host-openmp) // CHK-BUACTIONS: 18: assembler, {17}, object, (host-openmp) // CHK-BUACTIONS: 19: clang-offload-bundler, {9, 16, 18}, object, (host-openmp) /// ########################################################################### /// Check separate compilation with offloading - unbundling actions // RUN: touch %t.i // RUN: %clang -### -ccc-print-phases -fopenmp=libomp -o %t.out -lsomelib -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %t.i -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-UBACTIONS %s // CHK-UBACTIONS: 0: input, "somelib", object, (host-openmp) // CHK-UBACTIONS: 1: input, "[[INPUT:.+\.i]]", cpp-output, (host-openmp) // CHK-UBACTIONS: 2: clang-offload-unbundler, {1}, cpp-output, (host-openmp) // CHK-UBACTIONS: 3: compiler, {2}, ir, (host-openmp) // CHK-UBACTIONS: 4: backend, {3}, assembler, (host-openmp) // CHK-UBACTIONS: 5: assembler, {4}, object, (host-openmp) // CHK-UBACTIONS: 6: linker, {0, 5}, image, (host-openmp) // CHK-UBACTIONS: 7: input, "somelib", object, (device-openmp) // CHK-UBACTIONS: 8: compiler, {2}, ir, (device-openmp) // CHK-UBACTIONS: 9: offload, "host-openmp (powerpc64le--linux)" {3}, "device-openmp (powerpc64le-ibm-linux-gnu)" {8}, ir // CHK-UBACTIONS: 10: backend, {9}, assembler, (device-openmp) // CHK-UBACTIONS: 11: assembler, {10}, object, (device-openmp) // CHK-UBACTIONS: 12: linker, {7, 11}, image, (device-openmp) // CHK-UBACTIONS: 13: input, "somelib", object, (device-openmp) // CHK-UBACTIONS: 14: compiler, {2}, ir, (device-openmp) // CHK-UBACTIONS: 15: offload, "host-openmp (powerpc64le--linux)" {3}, "device-openmp (x86_64-pc-linux-gnu)" {14}, ir // CHK-UBACTIONS: 16: backend, {15}, assembler, (device-openmp) // CHK-UBACTIONS: 17: assembler, {16}, object, (device-openmp) // CHK-UBACTIONS: 18: linker, {13, 17}, image, (device-openmp) // CHK-UBACTIONS: 19: offload, "host-openmp (powerpc64le--linux)" {6}, "device-openmp (powerpc64le-ibm-linux-gnu)" {12}, "device-openmp (x86_64-pc-linux-gnu)" {18}, image /// ########################################################################### /// Check separate compilation with offloading - unbundling/bundling actions // RUN: touch %t.i // RUN: %clang -### -ccc-print-phases -fopenmp=libomp -c -o %t.o -lsomelib -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %t.i -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-UBUACTIONS %s // CHK-UBUACTIONS: 0: input, "[[INPUT:.+\.i]]", cpp-output, (host-openmp) // CHK-UBUACTIONS: 1: clang-offload-unbundler, {0}, cpp-output, (host-openmp) // CHK-UBUACTIONS: 2: compiler, {1}, ir, (host-openmp) // CHK-UBUACTIONS: 3: compiler, {1}, ir, (device-openmp) // CHK-UBUACTIONS: 4: offload, "host-openmp (powerpc64le--linux)" {2}, "device-openmp (powerpc64le-ibm-linux-gnu)" {3}, ir // CHK-UBUACTIONS: 5: backend, {4}, assembler, (device-openmp) // CHK-UBUACTIONS: 6: assembler, {5}, object, (device-openmp) // CHK-UBUACTIONS: 7: offload, "device-openmp (powerpc64le-ibm-linux-gnu)" {6}, object // CHK-UBUACTIONS: 8: compiler, {1}, ir, (device-openmp) // CHK-UBUACTIONS: 9: offload, "host-openmp (powerpc64le--linux)" {2}, "device-openmp (x86_64-pc-linux-gnu)" {8}, ir // CHK-UBUACTIONS: 10: backend, {9}, assembler, (device-openmp) // CHK-UBUACTIONS: 11: assembler, {10}, object, (device-openmp) // CHK-UBUACTIONS: 12: offload, "device-openmp (x86_64-pc-linux-gnu)" {11}, object // CHK-UBUACTIONS: 13: backend, {2}, assembler, (host-openmp) // CHK-UBUACTIONS: 14: assembler, {13}, object, (host-openmp) // CHK-UBUACTIONS: 15: clang-offload-bundler, {7, 12, 14}, object, (host-openmp) /// ########################################################################### /// Check separate compilation with offloading - bundling jobs construct // RUN: %clang -### -fopenmp=libomp -c -o %t.o -lsomelib -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %s -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-BUJOBS %s // RUN: %clang -### -fopenmp=libomp -c -o %t.o -lsomelib -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %s -save-temps -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-BUJOBS-ST %s // Create host BC. // CHK-BUJOBS: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-BUJOBS-SAME: [[HOSTBC:[^\\/]+\.bc]]" "-x" "c" " // CHK-BUJOBS-SAME: [[INPUT:[^\\/]+\.c]]" "-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu" // CHK-BUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-E" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-BUJOBS-ST-SAME: [[HOSTPP:[^\\/]+\.i]]" "-x" "c" " // CHK-BUJOBS-ST-SAME: [[INPUT:[^\\/]+\.c]]" // CHK-BUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-BUJOBS-ST-SAME: [[HOSTBC:[^\\/]+\.bc]]" "-x" "cpp-output" "{{.*}}[[HOSTPP]]" "-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu" // Create target 1 object. // CHK-BUJOBS: clang{{.*}}" "-cc1" "-triple" "powerpc64le-ibm-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-obj" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-BUJOBS-SAME: [[T1OBJ:[^\\/]+\.o]]" "-x" "c" "{{.*}}[[INPUT]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-BUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le-ibm-linux-gnu" "-aux-triple" "powerpc64le--linux" "-E" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-BUJOBS-ST-SAME: [[T1PP:[^\\/]+\.i]]" "-x" "c" "{{.*}}[[INPUT]]" // CHK-BUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le-ibm-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-BUJOBS-ST-SAME: [[T1BC:[^\\/]+\.bc]]" "-x" "cpp-output" "{{.*}}[[T1PP]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-BUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le-ibm-linux-gnu" "-aux-triple" "powerpc64le--linux" "-S" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-BUJOBS-ST-SAME: [[T1ASM:[^\\/]+\.s]]" "-x" "ir" "{{.*}}[[T1BC]]" // CHK-BUJOBS-ST: clang{{.*}}" "-cc1as" "-triple" "powerpc64le-ibm-linux-gnu" "-filetype" "obj" {{.*}}"-o" " // CHK-BUJOBS-ST-SAME: [[T1OBJ:[^\\/]+\.o]]" "{{.*}}[[T1ASM]]" // Create target 2 object. // CHK-BUJOBS: clang{{.*}}" "-cc1" "-triple" "x86_64-pc-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-obj" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-BUJOBS-SAME: [[T2OBJ:[^\\/]+\.o]]" "-x" "c" "{{.*}}[[INPUT]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-BUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "x86_64-pc-linux-gnu" "-aux-triple" "powerpc64le--linux" "-E" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-BUJOBS-ST-SAME: [[T2PP:[^\\/]+\.i]]" "-x" "c" "{{.*}}[[INPUT]]" // CHK-BUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "x86_64-pc-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-BUJOBS-ST-SAME: [[T2BC:[^\\/]+\.bc]]" "-x" "cpp-output" "{{.*}}[[T2PP]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-BUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "x86_64-pc-linux-gnu" "-aux-triple" "powerpc64le--linux" "-S" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-BUJOBS-ST-SAME: [[T2ASM:[^\\/]+\.s]]" "-x" "ir" "{{.*}}[[T2BC]]" // CHK-BUJOBS-ST: clang{{.*}}" "-cc1as" "-triple" "x86_64-pc-linux-gnu" "-filetype" "obj" {{.*}}"-o" " // CHK-BUJOBS-ST-SAME: [[T2OBJ:[^\\/]+\.o]]" "{{.*}}[[T2ASM]]" // Create host object and bundle. // CHK-BUJOBS: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-emit-obj" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-BUJOBS-SAME: [[HOSTOBJ:[^\\/]+\.o]]" "-x" "ir" "{{.*}}[[HOSTBC]]" // CHK-BUJOBS: clang-offload-bundler{{.*}}" "-type=o" "-targets=openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu,host-powerpc64le--linux" "-outputs= // CHK-BUJOBS-SAME: [[RES:[^\\/]+\.o]]" "-inputs={{.*}}[[T1OBJ]],{{.*}}[[T2OBJ]],{{.*}}[[HOSTOBJ]]" // CHK-BUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-S" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-BUJOBS-ST-SAME: [[HOSTASM:[^\\/]+\.s]]" "-x" "ir" "{{.*}}[[HOSTBC]]" // CHK-BUJOBS-ST: clang{{.*}}" "-cc1as" "-triple" "powerpc64le--linux" "-filetype" "obj" {{.*}}"-o" " // CHK-BUJOBS-ST-SAME: [[HOSTOBJ:[^\\/]+\.o]]" "{{.*}}[[HOSTASM]]" // CHK-BUJOBS-ST: clang-offload-bundler{{.*}}" "-type=o" "-targets=openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu,host-powerpc64le--linux" "-outputs= // CHK-BUJOBS-ST-SAME: [[RES:[^\\/]+\.o]]" "-inputs={{.*}}[[T1OBJ]],{{.*}}[[T2OBJ]],{{.*}}[[HOSTOBJ]]" /// ########################################################################### /// Check separate compilation with offloading - unbundling jobs construct // RUN: touch %t.i // RUN: %clang -### -fopenmp=libomp -o %t.out -lsomelib -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %t.i -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-UBJOBS %s // RUN: %clang -### -fopenmp=libomp -o %t.out -lsomelib -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %t.i -save-temps -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-UBJOBS-ST %s // RUN: touch %t.o // RUN: %clang -### -fopenmp=libomp -o %t.out -lsomelib -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %t.o -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-UBJOBS2 %s // RUN: %clang -### -fopenmp=libomp -o %t.out -lsomelib -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %t.o -save-temps -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-UBJOBS2-ST %s // Unbundle and create host BC. // CHK-UBJOBS: clang-offload-bundler{{.*}}" "-type=i" "-targets=host-powerpc64le--linux,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu" "-inputs= // CHK-UBJOBS-SAME: [[INPUT:[^\\/]+\.i]]" "-outputs= // CHK-UBJOBS-SAME: [[HOSTPP:[^\\/]+\.i]], // CHK-UBJOBS-SAME: [[T1PP:[^\\/]+\.i]], // CHK-UBJOBS-SAME: [[T2PP:[^\\/]+\.i]]" "-unbundle" // CHK-UBJOBS: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBJOBS-SAME: [[HOSTBC:[^\\/]+\.bc]]" "-x" "cpp-output" "{{.*}}[[HOSTPP]]" "-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu" // CHK-UBJOBS-ST: clang-offload-bundler{{.*}}" "-type=i" "-targets=host-powerpc64le--linux,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu" "-inputs= // CHK-UBJOBS-ST-SAME: [[INPUT:[^\\/]+\.i]]" "-outputs= // CHK-UBJOBS-ST-SAME: [[HOSTPP:[^\\/,]+\.i]], // CHK-UBJOBS-ST-SAME: [[T1PP:[^\\/,]+\.i]], // CHK-UBJOBS-ST-SAME: [[T2PP:[^\\/,]+\.i]]" "-unbundle" // CHK-UBJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBJOBS-ST-SAME: [[HOSTBC:[^\\/]+\.bc]]" "-x" "cpp-output" "{{.*}}[[HOSTPP]]" "-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu" // Create target 1 object. // CHK-UBJOBS: clang{{.*}}" "-cc1" "-triple" "powerpc64le-ibm-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-obj" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBJOBS-SAME: [[T1OBJ:[^\\/]+\.o]]" "-x" "cpp-output" "{{.*}}[[T1PP]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-UBJOBS: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-UBJOBS-SAME: [[T1BIN:[^\\/]+\.out]]" {{.*}}"{{.*}}[[T1OBJ]]" // CHK-UBJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le-ibm-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBJOBS-ST-SAME: [[T1BC:[^\\/]+\.bc]]" "-x" "cpp-output" "{{.*}}[[T1PP]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-UBJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le-ibm-linux-gnu" "-aux-triple" "powerpc64le--linux" "-S" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBJOBS-ST-SAME: [[T1ASM:[^\\/]+\.s]]" "-x" "ir" "{{.*}}[[T1BC]]" // CHK-UBJOBS-ST: clang{{.*}}" "-cc1as" "-triple" "powerpc64le-ibm-linux-gnu" "-filetype" "obj" {{.*}}"-o" " // CHK-UBJOBS-ST-SAME: [[T1OBJ:[^\\/]+\.o]]" "{{.*}}[[T1ASM]]" // CHK-UBJOBS-ST: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-UBJOBS-ST-SAME: [[T1BIN:[^\\/]+\.out-openmp-powerpc64le-ibm-linux-gnu]]" {{.*}}"{{.*}}[[T1OBJ]]" // Create target 2 object. // CHK-UBJOBS: clang{{.*}}" "-cc1" "-triple" "x86_64-pc-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-obj" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBJOBS-SAME: [[T2OBJ:[^\\/]+\.o]]" "-x" "cpp-output" "{{.*}}[[T2PP]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-UBJOBS: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-UBJOBS-SAME: [[T2BIN:[^\\/]+\.out]]" {{.*}}"{{.*}}[[T2OBJ]]" // CHK-UBJOBS-ST: clang{{.*}}" "-cc1" "-triple" "x86_64-pc-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBJOBS-ST-SAME: [[T2BC:[^\\/]+\.bc]]" "-x" "cpp-output" "{{.*}}[[T2PP]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-UBJOBS-ST: clang{{.*}}" "-cc1" "-triple" "x86_64-pc-linux-gnu" "-aux-triple" "powerpc64le--linux" "-S" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBJOBS-ST-SAME: [[T2ASM:[^\\/]+\.s]]" "-x" "ir" "{{.*}}[[T2BC]]" // CHK-UBJOBS-ST: clang{{.*}}" "-cc1as" "-triple" "x86_64-pc-linux-gnu" "-filetype" "obj" {{.*}}"-o" " // CHK-UBJOBS-ST-SAME: [[T2OBJ:[^\\/]+\.o]]" "{{.*}}[[T2ASM]]" // CHK-UBJOBS-ST: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-UBJOBS-ST-SAME: [[T2BIN:[^\\/]+\.out-openmp-x86_64-pc-linux-gnu]]" {{.*}}"{{.*}}[[T2OBJ]]" // Create binary. // CHK-UBJOBS: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-emit-obj" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBJOBS-SAME: [[HOSTOBJ:[^\\/]+\.o]]" "-x" "ir" "{{.*}}[[HOSTBC]]" // CHK-UBJOBS: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-UBJOBS-SAME: [[HOSTBIN:[^\\/]+\.out]]" {{.*}}"{{.*}}[[HOSTOBJ]]" {{.*}}"-T" " // CHK-UBJOBS-SAME: [[LKS:[^\\/]+\.lk]]" // CHK-UBJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-S" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBJOBS-ST-SAME: [[HOSTASM:[^\\/]+\.s]]" "-x" "ir" "{{.*}}[[HOSTBC]]" // CHK-UBJOBS-ST: clang{{.*}}" "-cc1as" "-triple" "powerpc64le--linux" "-filetype" "obj" {{.*}}"-o" " // CHK-UBJOBS-ST-SAME: [[HOSTOBJ:[^\\/]+\.o]]" "{{.*}}[[HOSTASM]]" // CHK-UBJOBS-ST: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-UBJOBS-ST-SAME: [[HOSTBIN:[^\\/]+\.out]]" {{.*}}"{{.*}}[[HOSTOBJ]]" {{.*}}"-T" " // CHK-UBJOBS-ST-SAME: [[LKS:[^\\/]+\.lk]]" // Unbundle object file. // CHK-UBJOBS2: clang-offload-bundler{{.*}}" "-type=o" "-targets=host-powerpc64le--linux,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu" "-inputs= // CHK-UBJOBS2-SAME: [[INPUT:[^\\/]+\.o]]" "-outputs= // CHK-UBJOBS2-SAME: [[HOSTOBJ:[^\\/]+\.o]], // CHK-UBJOBS2-SAME: [[T1OBJ:[^\\/]+\.o]], // CHK-UBJOBS2-SAME: [[T2OBJ:[^\\/]+\.o]]" "-unbundle" // CHK-UBJOBS2: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-UBJOBS2-SAME: [[T1BIN:[^\\/]+\.out]]" {{.*}}"{{.*}}[[T1OBJ]]" // CHK-UBJOBS2: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-UBJOBS2-SAME: [[T2BIN:[^\\/]+\.out]]" {{.*}}"{{.*}}[[T2OBJ]]" // CHK-UBJOBS2: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-UBJOBS2-SAME: [[HOSTBIN:[^\\/]+\.out]]" {{.*}}"{{.*}}[[HOSTOBJ]]" {{.*}}"-T" " // CHK-UBJOBS2-SAME: [[LKS:[^\\/]+\.lk]]" // CHK-UBJOBS2-ST: clang-offload-bundler{{.*}}" "-type=o" "-targets=host-powerpc64le--linux,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu" "-inputs= // CHK-UBJOBS2-ST-SAME: [[INPUT:[^\\/]+\.o]]" "-outputs= // CHK-UBJOBS2-ST-SAME: [[HOSTOBJ:[^\\/,]+\.o]], // CHK-UBJOBS2-ST-SAME: [[T1OBJ:[^\\/,]+\.o]], // CHK-UBJOBS2-ST-SAME: [[T2OBJ:[^\\/,]+\.o]]" "-unbundle" // CHK-UBJOBS2-ST: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-UBJOBS2-ST-SAME: [[T1BIN:[^\\/]+\.out-openmp-powerpc64le-ibm-linux-gnu]]" {{.*}}"{{.*}}[[T1OBJ]]" // CHK-UBJOBS2-ST: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-UBJOBS2-ST-SAME: [[T2BIN:[^\\/]+\.out-openmp-x86_64-pc-linux-gnu]]" {{.*}}"{{.*}}[[T2OBJ]]" // CHK-UBJOBS2-ST: ld{{(\.exe)?}}" {{.*}}"-o" " // CHK-UBJOBS2-ST-SAME: [[HOSTBIN:[^\\/]+\.out]]" {{.*}}"{{.*}}[[HOSTOBJ]]" {{.*}}"-T" " // CHK-UBJOBS2-ST-SAME: [[LKS:[^\\/]+\.lk]]" /// ########################################################################### /// Check separate compilation with offloading - unbundling/bundling jobs /// construct // RUN: touch %t.i // RUN: %clang -### -fopenmp=libomp -c %t.o -lsomelib -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %t.i -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-UBUJOBS %s // RUN: %clang -### -fopenmp=libomp -c %t.o -lsomelib -target powerpc64le-linux -fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %t.i -save-temps -no-canonical-prefixes 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-UBUJOBS-ST %s // Unbundle and create host BC. // CHK-UBUJOBS: clang-offload-bundler{{.*}}" "-type=i" "-targets=host-powerpc64le--linux,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu" "-inputs= // CHK-UBUJOBS-SAME: [[INPUT:[^\\/]+\.i]]" "-outputs= // CHK-UBUJOBS-SAME: [[HOSTPP:[^\\/]+\.i]], // CHK-UBUJOBS-SAME: [[T1PP:[^\\/]+\.i]], // CHK-UBUJOBS-SAME: [[T2PP:[^\\/]+\.i]]" "-unbundle" // CHK-UBUJOBS: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBUJOBS-SAME: [[HOSTBC:[^\\/]+\.bc]]" "-x" "cpp-output" "{{.*}}[[HOSTPP]]" "-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu" // CHK-UBUJOBS-ST: clang-offload-bundler{{.*}}" "-type=i" "-targets=host-powerpc64le--linux,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu" "-inputs= // CHK-UBUJOBS-ST-SAME: [[INPUT:[^\\/]+\.i]]" "-outputs= // CHK-UBUJOBS-ST-SAME: [[HOSTPP:[^\\/,]+\.i]], // CHK-UBUJOBS-ST-SAME: [[T1PP:[^\\/,]+\.i]], // CHK-UBUJOBS-ST-SAME: [[T2PP:[^\\/,]+\.i]]" "-unbundle" // CHK-UBUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBUJOBS-ST-SAME: [[HOSTBC:[^\\/]+\.bc]]" "-x" "cpp-output" "{{.*}}[[HOSTPP]]" "-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu" // Create target 1 object. // CHK-UBUJOBS: clang{{.*}}" "-cc1" "-triple" "powerpc64le-ibm-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-obj" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBUJOBS-SAME: [[T1OBJ:[^\\/]+\.o]]" "-x" "cpp-output" "{{.*}}[[T1PP]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-UBUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le-ibm-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBUJOBS-ST-SAME: [[T1BC:[^\\/]+\.bc]]" "-x" "cpp-output" "{{.*}}[[T1PP]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-UBUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le-ibm-linux-gnu" "-aux-triple" "powerpc64le--linux" "-S" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBUJOBS-ST-SAME: [[T1ASM:[^\\/]+\.s]]" "-x" "ir" "{{.*}}[[T1BC]]" // CHK-UBUJOBS-ST: clang{{.*}}" "-cc1as" "-triple" "powerpc64le-ibm-linux-gnu" "-filetype" "obj" {{.*}}"-o" " // CHK-UBUJOBS-ST-SAME: [[T1OBJ:[^\\/]+\.o]]" "{{.*}}[[T1ASM]]" // Create target 2 object. // CHK-UBUJOBS: clang{{.*}}" "-cc1" "-triple" "x86_64-pc-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-obj" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBUJOBS-SAME: [[T2OBJ:[^\\/]+\.o]]" "-x" "cpp-output" "{{.*}}[[T2PP]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-UBUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "x86_64-pc-linux-gnu" "-aux-triple" "powerpc64le--linux" "-emit-llvm-bc" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBUJOBS-ST-SAME: [[T2BC:[^\\/]+\.bc]]" "-x" "cpp-output" "{{.*}}[[T2PP]]" "-fopenmp-is-device" "-fopenmp-host-ir-file-path" "{{.*}}[[HOSTBC]]" // CHK-UBUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "x86_64-pc-linux-gnu" "-aux-triple" "powerpc64le--linux" "-S" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBUJOBS-ST-SAME: [[T2ASM:[^\\/]+\.s]]" "-x" "ir" "{{.*}}[[T2BC]]" // CHK-UBUJOBS-ST: clang{{.*}}" "-cc1as" "-triple" "x86_64-pc-linux-gnu" "-filetype" "obj" {{.*}}"-o" " // CHK-UBUJOBS-ST-SAME: [[T2OBJ:[^\\/]+\.o]]" "{{.*}}[[T2ASM]]" // Create binary. // CHK-UBUJOBS: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-emit-obj" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBUJOBS-SAME: [[HOSTOBJ:[^\\/]+\.o]]" "-x" "ir" "{{.*}}[[HOSTBC]]" // CHK-UBUJOBS: clang-offload-bundler{{.*}}" "-type=o" "-targets=openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu,host-powerpc64le--linux" "-outputs= // CHK-UBUJOBS-SAME: [[RES:[^\\/]+\.o]]" "-inputs={{.*}}[[T1OBJ]],{{.*}}[[T2OBJ]],{{.*}}[[HOSTOBJ]]" // CHK-UBUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-S" {{.*}}"-fopenmp" {{.*}}"-o" " // CHK-UBUJOBS-ST-SAME: [[HOSTASM:[^\\/]+\.s]]" "-x" "ir" "{{.*}}[[HOSTBC]]" // CHK-UBUJOBS-ST: clang{{.*}}" "-cc1as" "-triple" "powerpc64le--linux" "-filetype" "obj" {{.*}}"-o" " // CHK-UBUJOBS-ST-SAME: [[HOSTOBJ:[^\\/]+\.o]]" "{{.*}}[[HOSTASM]]" // CHK-UBUJOBS-ST: clang-offload-bundler{{.*}}" "-type=o" "-targets=openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu,host-powerpc64le--linux" "-outputs= // CHK-UBUJOBS-ST-SAME: [[RES:[^\\/]+\.o]]" "-inputs={{.*}}[[T1OBJ]],{{.*}}[[T2OBJ]],{{.*}}[[HOSTOBJ]]" /// ########################################################################### /// Check -fopenmp-is-device is passed when compiling for the device. // RUN: %clang -### -no-canonical-prefixes -target powerpc64le-linux -fopenmp=libomp -fopenmp-targets=powerpc64le-ibm-linux-gnu %s 2>&1 \ // RUN: | FileCheck -check-prefix=CHK-FOPENMP-IS-DEVICE %s // CHK-FOPENMP-IS-DEVICE: clang{{.*}} "-aux-triple" "powerpc64le--linux" {{.*}}.c" "-fopenmp-is-device" "-fopenmp-host-ir-file-path"
the_stack_data/51251.c
char f(void) {return 'f';} char main(void) { int x=0; { int x=2; x++; } return x/0; }
the_stack_data/76517.c
#include<stdio.h> int main() { int n; scanf("%d", &n); switch(n) { case 0: printf("zero"); break; case 1: printf("one"); break; case 2: printf("two"); break; case 3: printf("three");break; case 4: printf("four"); break; case 5: printf("five"); break; case 6: printf("six"); break; case 7: printf("seven");break; case 8: printf("eight");break; case 9: printf("nine"); break; default: printf("Greater than 9"); } }
the_stack_data/739942.c
/* Simple S/MIME encrypt example */ #include <openssl/pem.h> #include <openssl/cms.h> #include <openssl/err.h> int main(int argc, char **argv) { BIO *in = NULL, *out = NULL, *tbio = NULL; X509 *rcert = NULL; STACK_OF(X509) *recips = NULL; CMS_ContentInfo *cms = NULL; int ret = 1; /* * On OpenSSL 1.0.0 and later only: * for streaming set CMS_STREAM */ int flags = CMS_STREAM; OpenSSL_add_all_algorithms(); ERR_load_crypto_strings(); /* Read in recipient certificate */ tbio = BIO_new_file("signer.pem", "r"); if (!tbio) goto err; rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL); if (!rcert) goto err; /* Create recipient STACK and add recipient cert to it */ recips = sk_X509_new_null(); if (!recips || !sk_X509_push(recips, rcert)) goto err; /* * sk_X509_pop_free will free up recipient STACK and its contents so set * rcert to NULL so it isn't freed up twice. */ rcert = NULL; /* Open content being encrypted */ in = BIO_new_file("encr.txt", "r"); if (!in) goto err; /* encrypt content */ cms = CMS_encrypt(recips, in, EVP_des_ede3_cbc(), flags); if (!cms) goto err; out = BIO_new_file("smencr.txt", "w"); if (!out) goto err; /* Write out S/MIME message */ if (!SMIME_write_CMS(out, cms, in, flags)) goto err; ret = 0; err: if (ret) { fprintf(stderr, "Error Encrypting Data\n"); ERR_print_errors_fp(stderr); } if (cms) CMS_ContentInfo_free(cms); if (rcert) X509_free(rcert); if (recips) sk_X509_pop_free(recips, X509_free); if (in) BIO_free(in); if (out) BIO_free(out); if (tbio) BIO_free(tbio); return ret; }
the_stack_data/243892773.c
/* Copyright (c) 2016, Dennis Wölfing * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* libc/src/string/strspn.c * Calculates the length of a substring. */ #include <string.h> size_t strspn(const char* string, const char* characters) { size_t result = 0; while (1) { for (size_t i = 0; characters[i]; i++) { if (string[result] != characters[i]) { return result; } } result++; } }
the_stack_data/750088.c
#include<stdio.h> #include<omp.h> int big_job(int id){ printf("Big job(%d)\n", id); int i = 0; while (i < (id+1)*10000) i++; return i; } float consume(int B){ printf("consume(%d)\n", B); return 2*B; } int main(){ int niters = 10; float res; #pragma omp parallel { float B; int i, id, nthrds; id = omp_get_thread_num(); nthrds = omp_get_num_threads(); for (i=id ; i<niters ; i+=nthrds){ B = big_job(i); // mutual exclusion #pragma omp critical res += consume(B); } printf("res = %d\n", res); } return 0; }
the_stack_data/79501.c
/* * Copyright (c) 2020 Martin Storsjo * * This file is part of llvm-mingw. * * 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. */ #include <stdio.h> #include <omp.h> int main(int argc, char *argv[]) { #pragma omp parallel printf("thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads()); return 0; }
the_stack_data/1167923.c
/* Samuele Allegranza @ Polimi Fondamenti di informatica - Esercitazione > Esercizio: Si scriva un sottoprogramma che ricevuto in ingresso un array di numeri reali, calcola e trasmette al chiamante un array di valori in cui ogni elemento e' dato dalla somma del corrispondente valore dell'array di partenza con tutti i numeri precedenti */ #include <stdio.h> void progressive_sum(float [], float [], int); int main(int argc, char * argv[]) { float arr[7] = {1, 1, 1, 2, 1, 3, 3}; float res[7]; int i; progressive_sum(arr, res, 7); for(i=0; i<7; i++) { printf("%4.1f ", res[i]); } printf("\n"); return 0; } void progressive_sum(float arr[], float res[], int len) { int i, j; if(len>0) { res[0] = arr[0]; for(i=1; i<len; i++) { res[i] = res[i-1] + arr[i]; } } }
the_stack_data/6340.c
int main(void) { int a(int b); return 5; } int a(int c) { return 0; } int a(int f); int h(int g, char f);
the_stack_data/3262650.c
extern void abort(void); void reach_error(){} void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: {reach_error();abort();} } return; } int __VERIFIER_nondet_int(); _Bool __VERIFIER_nondet_bool(); int main() { int x=__VERIFIER_nondet_int(); int y=__VERIFIER_nondet_int(); int z=__VERIFIER_nondet_int(); while(x<100 && 100<z) { _Bool tmp=__VERIFIER_nondet_bool(); if (tmp) { x++; } else { x--; z--; } } __VERIFIER_assert(0); return 0; }
the_stack_data/99047.c
/** ****************************************************************************** * @file stm32f4xx_ll_dma2d.c * @author MCD Application Team * @version V1.7.1 * @date 14-April-2017 * @brief DMA2D LL module driver. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_ll_dma2d.h" #include "stm32f4xx_ll_bus.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /** @addtogroup STM32F4xx_LL_Driver * @{ */ #if defined (DMA2D) /** @addtogroup DMA2D_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @addtogroup DMA2D_LL_Private_Constants DMA2D Private Constants * @{ */ #define LL_DMA2D_COLOR 0xFFU /*!< Maximum output color setting */ #define LL_DMA2D_NUMBEROFLINES DMA2D_NLR_NL /*!< Maximum number of lines */ #define LL_DMA2D_NUMBEROFPIXELS (DMA2D_NLR_PL >> DMA2D_NLR_PL_Pos) /*!< Maximum number of pixels per lines */ #define LL_DMA2D_OFFSET_MAX 0x3FFFU /*!< Maximum output line offset expressed in pixels */ #define LL_DMA2D_CLUTSIZE_MAX 0xFFU /*!< Maximum CLUT size */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup DMA2D_LL_Private_Macros * @{ */ #define IS_LL_DMA2D_MODE(MODE) (((MODE) == LL_DMA2D_MODE_M2M) || \ ((MODE) == LL_DMA2D_MODE_M2M_PFC) || \ ((MODE) == LL_DMA2D_MODE_M2M_BLEND) || \ ((MODE) == LL_DMA2D_MODE_R2M)) #define IS_LL_DMA2D_OCMODE(MODE_ARGB) (((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_ARGB8888) || \ ((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_RGB888) || \ ((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_RGB565) || \ ((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_ARGB1555) || \ ((MODE_ARGB) == LL_DMA2D_OUTPUT_MODE_ARGB4444)) #define IS_LL_DMA2D_GREEN(GREEN) ((GREEN) <= LL_DMA2D_COLOR) #define IS_LL_DMA2D_RED(RED) ((RED) <= LL_DMA2D_COLOR) #define IS_LL_DMA2D_BLUE(BLUE) ((BLUE) <= LL_DMA2D_COLOR) #define IS_LL_DMA2D_ALPHA(ALPHA) ((ALPHA) <= LL_DMA2D_COLOR) #define IS_LL_DMA2D_OFFSET(OFFSET) ((OFFSET) <= LL_DMA2D_OFFSET_MAX) #define IS_LL_DMA2D_LINE(LINES) ((LINES) <= LL_DMA2D_NUMBEROFLINES) #define IS_LL_DMA2D_PIXEL(PIXELS) ((PIXELS) <= LL_DMA2D_NUMBEROFPIXELS) #define IS_LL_DMA2D_LCMODE(MODE_ARGB) (((MODE_ARGB) == LL_DMA2D_INPUT_MODE_ARGB8888) || \ ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_RGB888) || \ ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_RGB565) || \ ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_ARGB1555) || \ ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_ARGB4444) || \ ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_L8) || \ ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_AL44) || \ ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_AL88) || \ ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_L4) || \ ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_A8) || \ ((MODE_ARGB) == LL_DMA2D_INPUT_MODE_A4)) #define IS_LL_DMA2D_CLUTCMODE(CLUTCMODE) (((CLUTCMODE) == LL_DMA2D_CLUT_COLOR_MODE_ARGB8888) || \ ((CLUTCMODE) == LL_DMA2D_CLUT_COLOR_MODE_RGB888)) #define IS_LL_DMA2D_CLUTSIZE(SIZE) ((SIZE) <= LL_DMA2D_CLUTSIZE_MAX) #define IS_LL_DMA2D_ALPHAMODE(MODE) (((MODE) == LL_DMA2D_ALPHA_MODE_NO_MODIF) || \ ((MODE) == LL_DMA2D_ALPHA_MODE_REPLACE) || \ ((MODE) == LL_DMA2D_ALPHA_MODE_COMBINE)) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup DMA2D_LL_Exported_Functions * @{ */ /** @addtogroup DMA2D_LL_EF_Init_Functions Initialization and De-initialization Functions * @{ */ /** * @brief De-initialize DMA2D registers (registers restored to their default values). * @param DMA2Dx DMA2D Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: DMA2D registers are de-initialized * - ERROR: DMA2D registers are not de-initialized */ ErrorStatus LL_DMA2D_DeInit(DMA2D_TypeDef *DMA2Dx) { ErrorStatus status = SUCCESS; /* Check the parameters */ assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); if (DMA2Dx == DMA2D) { /* Force reset of DMA2D clock */ LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_DMA2D); /* Release reset of DMA2D clock */ LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_DMA2D); } else { status = ERROR; } return (status); } /** * @brief Initialize DMA2D registers according to the specified parameters in DMA2D_InitStruct. * @note DMA2D transfers must be disabled to set initialization bits in configuration registers, * otherwise ERROR result is returned. * @param DMA2Dx DMA2D Instance * @param DMA2D_InitStruct: pointer to a LL_DMA2D_InitTypeDef structure * that contains the configuration information for the specified DMA2D peripheral. * @retval An ErrorStatus enumeration value: * - SUCCESS: DMA2D registers are initialized according to DMA2D_InitStruct content * - ERROR: Issue occurred during DMA2D registers initialization */ ErrorStatus LL_DMA2D_Init(DMA2D_TypeDef *DMA2Dx, LL_DMA2D_InitTypeDef *DMA2D_InitStruct) { ErrorStatus status = ERROR; LL_DMA2D_ColorTypeDef DMA2D_ColorStruct; uint32_t tmp = 0U, tmp1 = 0U, tmp2 = 0U; /* Check the parameters */ assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); assert_param(IS_LL_DMA2D_MODE(DMA2D_InitStruct->Mode)); assert_param(IS_LL_DMA2D_OCMODE(DMA2D_InitStruct->ColorMode)); assert_param(IS_LL_DMA2D_LINE(DMA2D_InitStruct->NbrOfLines)); assert_param(IS_LL_DMA2D_PIXEL(DMA2D_InitStruct->NbrOfPixelsPerLines)); assert_param(IS_LL_DMA2D_GREEN(DMA2D_InitStruct->OutputGreen)); assert_param(IS_LL_DMA2D_RED(DMA2D_InitStruct->OutputRed)); assert_param(IS_LL_DMA2D_BLUE(DMA2D_InitStruct->OutputBlue)); assert_param(IS_LL_DMA2D_ALPHA(DMA2D_InitStruct->OutputAlpha)); assert_param(IS_LL_DMA2D_OFFSET(DMA2D_InitStruct->LineOffset)); /* DMA2D transfers must be disabled to configure bits in initialization registers */ tmp = LL_DMA2D_IsTransferOngoing(DMA2Dx); tmp1 = LL_DMA2D_FGND_IsEnabledCLUTLoad(DMA2Dx); tmp2 = LL_DMA2D_BGND_IsEnabledCLUTLoad(DMA2Dx); if ((tmp == 0U) && (tmp1 == 0U) && (tmp2 == 0U)) { /* DMA2D CR register configuration -------------------------------------------*/ LL_DMA2D_SetMode(DMA2Dx, DMA2D_InitStruct->Mode); /* DMA2D OPFCCR register configuration ---------------------------------------*/ MODIFY_REG(DMA2Dx->OPFCCR, DMA2D_OPFCCR_CM, DMA2D_InitStruct->ColorMode); /* DMA2D OOR register configuration ------------------------------------------*/ LL_DMA2D_SetLineOffset(DMA2Dx, DMA2D_InitStruct->LineOffset); /* DMA2D NLR register configuration ------------------------------------------*/ LL_DMA2D_ConfigSize(DMA2Dx, DMA2D_InitStruct->NbrOfLines, DMA2D_InitStruct->NbrOfPixelsPerLines); /* DMA2D OMAR register configuration ------------------------------------------*/ LL_DMA2D_SetOutputMemAddr(DMA2Dx, DMA2D_InitStruct->OutputMemoryAddress); /* DMA2D OCOLR register configuration ------------------------------------------*/ DMA2D_ColorStruct.ColorMode = DMA2D_InitStruct->ColorMode; DMA2D_ColorStruct.OutputBlue = DMA2D_InitStruct->OutputBlue; DMA2D_ColorStruct.OutputGreen = DMA2D_InitStruct->OutputGreen; DMA2D_ColorStruct.OutputRed = DMA2D_InitStruct->OutputRed; DMA2D_ColorStruct.OutputAlpha = DMA2D_InitStruct->OutputAlpha; LL_DMA2D_ConfigOutputColor(DMA2Dx, &DMA2D_ColorStruct); status = SUCCESS; } /* If DMA2D transfers are not disabled, return ERROR */ return (status); } /** * @brief Set each @ref LL_DMA2D_InitTypeDef field to default value. * @param DMA2D_InitStruct: pointer to a @ref LL_DMA2D_InitTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_DMA2D_StructInit(LL_DMA2D_InitTypeDef *DMA2D_InitStruct) { /* Set DMA2D_InitStruct fields to default values */ DMA2D_InitStruct->Mode = LL_DMA2D_MODE_M2M; DMA2D_InitStruct->ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB8888; DMA2D_InitStruct->NbrOfLines = 0x0U; DMA2D_InitStruct->NbrOfPixelsPerLines = 0x0U; DMA2D_InitStruct->LineOffset = 0x0U; DMA2D_InitStruct->OutputBlue = 0x0U; DMA2D_InitStruct->OutputGreen = 0x0U; DMA2D_InitStruct->OutputRed = 0x0U; DMA2D_InitStruct->OutputAlpha = 0x0U; DMA2D_InitStruct->OutputMemoryAddress = 0x0U; } /** * @brief Configure the foreground or background according to the specified parameters * in the LL_DMA2D_LayerCfgTypeDef structure. * @param DMA2Dx DMA2D Instance * @param DMA2D_LayerCfg: pointer to a LL_DMA2D_LayerCfgTypeDef structure that contains * the configuration information for the specified layer. * @param LayerIdx: DMA2D Layer index. * This parameter can be one of the following values: * 0(background) / 1(foreground) * @retval None */ void LL_DMA2D_ConfigLayer(DMA2D_TypeDef *DMA2Dx, LL_DMA2D_LayerCfgTypeDef *DMA2D_LayerCfg, uint32_t LayerIdx) { /* Check the parameters */ assert_param(IS_LL_DMA2D_OFFSET(DMA2D_LayerCfg->LineOffset)); assert_param(IS_LL_DMA2D_LCMODE(DMA2D_LayerCfg->ColorMode)); assert_param(IS_LL_DMA2D_CLUTCMODE(DMA2D_LayerCfg->CLUTColorMode)); assert_param(IS_LL_DMA2D_CLUTSIZE(DMA2D_LayerCfg->CLUTSize)); assert_param(IS_LL_DMA2D_ALPHAMODE(DMA2D_LayerCfg->AlphaMode)); assert_param(IS_LL_DMA2D_GREEN(DMA2D_LayerCfg->Green)); assert_param(IS_LL_DMA2D_RED(DMA2D_LayerCfg->Red)); assert_param(IS_LL_DMA2D_BLUE(DMA2D_LayerCfg->Blue)); assert_param(IS_LL_DMA2D_ALPHA(DMA2D_LayerCfg->Alpha)); if (LayerIdx == 0U) { /* Configure the background memory address */ LL_DMA2D_BGND_SetMemAddr(DMA2Dx, DMA2D_LayerCfg->MemoryAddress); /* Configure the background line offset */ LL_DMA2D_BGND_SetLineOffset(DMA2Dx, DMA2D_LayerCfg->LineOffset); /* Configure the background Alpha value, Alpha mode, CLUT size, CLUT Color mode and Color mode */ MODIFY_REG(DMA2Dx->BGPFCCR, \ (DMA2D_BGPFCCR_ALPHA | DMA2D_BGPFCCR_AM | DMA2D_BGPFCCR_CS | DMA2D_BGPFCCR_CCM | DMA2D_BGPFCCR_CM), \ ((DMA2D_LayerCfg->Alpha << DMA2D_BGPFCCR_ALPHA_Pos) | DMA2D_LayerCfg->AlphaMode | \ (DMA2D_LayerCfg->CLUTSize << DMA2D_BGPFCCR_CS_Pos) | DMA2D_LayerCfg->CLUTColorMode | \ DMA2D_LayerCfg->ColorMode)); /* Configure the background color */ LL_DMA2D_BGND_SetColor(DMA2Dx, DMA2D_LayerCfg->Red, DMA2D_LayerCfg->Green, DMA2D_LayerCfg->Blue); /* Configure the background CLUT memory address */ LL_DMA2D_BGND_SetCLUTMemAddr(DMA2Dx, DMA2D_LayerCfg->CLUTMemoryAddress); } else { /* Configure the foreground memory address */ LL_DMA2D_FGND_SetMemAddr(DMA2Dx, DMA2D_LayerCfg->MemoryAddress); /* Configure the foreground line offset */ LL_DMA2D_FGND_SetLineOffset(DMA2Dx, DMA2D_LayerCfg->LineOffset); /* Configure the foreground Alpha value, Alpha mode, CLUT size, CLUT Color mode and Color mode */ MODIFY_REG(DMA2Dx->FGPFCCR, \ (DMA2D_FGPFCCR_ALPHA | DMA2D_FGPFCCR_AM | DMA2D_FGPFCCR_CS | DMA2D_FGPFCCR_CCM | DMA2D_FGPFCCR_CM), \ ((DMA2D_LayerCfg->Alpha << DMA2D_FGPFCCR_ALPHA_Pos) | DMA2D_LayerCfg->AlphaMode | \ (DMA2D_LayerCfg->CLUTSize << DMA2D_FGPFCCR_CS_Pos) | DMA2D_LayerCfg->CLUTColorMode | \ DMA2D_LayerCfg->ColorMode)); /* Configure the foreground color */ LL_DMA2D_FGND_SetColor(DMA2Dx, DMA2D_LayerCfg->Red, DMA2D_LayerCfg->Green, DMA2D_LayerCfg->Blue); /* Configure the foreground CLUT memory address */ LL_DMA2D_FGND_SetCLUTMemAddr(DMA2Dx, DMA2D_LayerCfg->CLUTMemoryAddress); } } /** * @brief Set each @ref LL_DMA2D_LayerCfgTypeDef field to default value. * @param DMA2D_LayerCfg: pointer to a @ref LL_DMA2D_LayerCfgTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_DMA2D_LayerCfgStructInit(LL_DMA2D_LayerCfgTypeDef *DMA2D_LayerCfg) { /* Set DMA2D_LayerCfg fields to default values */ DMA2D_LayerCfg->MemoryAddress = 0x0U; DMA2D_LayerCfg->ColorMode = LL_DMA2D_INPUT_MODE_ARGB8888; DMA2D_LayerCfg->LineOffset = 0x0U; DMA2D_LayerCfg->CLUTColorMode = LL_DMA2D_CLUT_COLOR_MODE_ARGB8888; DMA2D_LayerCfg->CLUTSize = 0x0U; DMA2D_LayerCfg->AlphaMode = LL_DMA2D_ALPHA_MODE_NO_MODIF; DMA2D_LayerCfg->Alpha = 0x0U; DMA2D_LayerCfg->Blue = 0x0U; DMA2D_LayerCfg->Green = 0x0U; DMA2D_LayerCfg->Red = 0x0U; DMA2D_LayerCfg->CLUTMemoryAddress = 0x0U; } /** * @brief Initialize DMA2D output color register according to the specified parameters * in DMA2D_ColorStruct. * @param DMA2Dx DMA2D Instance * @param DMA2D_ColorStruct: pointer to a LL_DMA2D_ColorTypeDef structure that contains * the color configuration information for the specified DMA2D peripheral. * @retval None */ void LL_DMA2D_ConfigOutputColor(DMA2D_TypeDef *DMA2Dx, LL_DMA2D_ColorTypeDef *DMA2D_ColorStruct) { uint32_t outgreen = 0U; uint32_t outred = 0U; uint32_t outalpha = 0U; /* Check the parameters */ assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); assert_param(IS_LL_DMA2D_OCMODE(DMA2D_ColorStruct->ColorMode)); assert_param(IS_LL_DMA2D_GREEN(DMA2D_ColorStruct->OutputGreen)); assert_param(IS_LL_DMA2D_RED(DMA2D_ColorStruct->OutputRed)); assert_param(IS_LL_DMA2D_BLUE(DMA2D_ColorStruct->OutputBlue)); assert_param(IS_LL_DMA2D_ALPHA(DMA2D_ColorStruct->OutputAlpha)); /* DMA2D OCOLR register configuration ------------------------------------------*/ if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) { outgreen = DMA2D_ColorStruct->OutputGreen << 8U; outred = DMA2D_ColorStruct->OutputRed << 16U; outalpha = DMA2D_ColorStruct->OutputAlpha << 24U; } else if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) { outgreen = DMA2D_ColorStruct->OutputGreen << 8U; outred = DMA2D_ColorStruct->OutputRed << 16U; outalpha = 0x00000000U; } else if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565) { outgreen = DMA2D_ColorStruct->OutputGreen << 5U; outred = DMA2D_ColorStruct->OutputRed << 11U; outalpha = 0x00000000U; } else if (DMA2D_ColorStruct->ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) { outgreen = DMA2D_ColorStruct->OutputGreen << 5U; outred = DMA2D_ColorStruct->OutputRed << 10U; outalpha = DMA2D_ColorStruct->OutputAlpha << 15U; } else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ { outgreen = DMA2D_ColorStruct->OutputGreen << 4U; outred = DMA2D_ColorStruct->OutputRed << 8U; outalpha = DMA2D_ColorStruct->OutputAlpha << 12U; } LL_DMA2D_SetOutputColor(DMA2Dx, (outgreen | outred | DMA2D_ColorStruct->OutputBlue | outalpha)); } /** * @brief Return DMA2D output Blue color. * @param DMA2Dx DMA2D Instance. * @param ColorMode This parameter can be one of the following values: * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888 * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888 * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565 * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555 * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444 * @retval Output Blue color value between Min_Data=0 and Max_Data=0xFF */ uint32_t LL_DMA2D_GetOutputBlueColor(DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode) { uint32_t color = 0U; /* Check the parameters */ assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); assert_param(IS_LL_DMA2D_OCMODE(ColorMode)); /* DMA2D OCOLR register reading ------------------------------------------*/ if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFFU)); } else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFFU)); } else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565) { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x1FU)); } else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x1FU)); } else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFU)); } return color; } /** * @brief Return DMA2D output Green color. * @param DMA2Dx DMA2D Instance. * @param ColorMode This parameter can be one of the following values: * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888 * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888 * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565 * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555 * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444 * @retval Output Green color value between Min_Data=0 and Max_Data=0xFF */ uint32_t LL_DMA2D_GetOutputGreenColor(DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode) { uint32_t color = 0U; /* Check the parameters */ assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); assert_param(IS_LL_DMA2D_OCMODE(ColorMode)); /* DMA2D OCOLR register reading ------------------------------------------*/ if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF00U) >> 8U); } else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF00U) >> 8U); } else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565) { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x7E0U) >> 5U); } else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x3E0U) >> 5U); } else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF0U) >> 4U); } return color; } /** * @brief Return DMA2D output Red color. * @param DMA2Dx DMA2D Instance. * @param ColorMode This parameter can be one of the following values: * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888 * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888 * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565 * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555 * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444 * @retval Output Red color value between Min_Data=0 and Max_Data=0xFF */ uint32_t LL_DMA2D_GetOutputRedColor(DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode) { uint32_t color = 0U; /* Check the parameters */ assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); assert_param(IS_LL_DMA2D_OCMODE(ColorMode)); /* DMA2D OCOLR register reading ------------------------------------------*/ if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF0000U) >> 16U); } else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF0000U) >> 16U); } else if (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565) { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF800U) >> 11U); } else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x7C00U) >> 10U); } else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF00U) >> 8U); } return color; } /** * @brief Return DMA2D output Alpha color. * @param DMA2Dx DMA2D Instance. * @param ColorMode This parameter can be one of the following values: * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB8888 * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB888 * @arg @ref LL_DMA2D_OUTPUT_MODE_RGB565 * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB1555 * @arg @ref LL_DMA2D_OUTPUT_MODE_ARGB4444 * @retval Output Alpha color value between Min_Data=0 and Max_Data=0xFF */ uint32_t LL_DMA2D_GetOutputAlphaColor(DMA2D_TypeDef *DMA2Dx, uint32_t ColorMode) { uint32_t color = 0U; /* Check the parameters */ assert_param(IS_DMA2D_ALL_INSTANCE(DMA2Dx)); assert_param(IS_LL_DMA2D_OCMODE(ColorMode)); /* DMA2D OCOLR register reading ------------------------------------------*/ if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB8888) { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xFF000000U) >> 24U); } else if ((ColorMode == LL_DMA2D_OUTPUT_MODE_RGB888) || (ColorMode == LL_DMA2D_OUTPUT_MODE_RGB565)) { color = 0x0U; } else if (ColorMode == LL_DMA2D_OUTPUT_MODE_ARGB1555) { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0x8000U) >> 15U); } else /* ColorMode = LL_DMA2D_OUTPUT_MODE_ARGB4444 */ { color = (uint32_t)(READ_BIT(DMA2Dx->OCOLR, 0xF000U) >> 12U); } return color; } /** * @brief Configure DMA2D transfer size. * @param DMA2Dx DMA2D Instance * @param NbrOfLines Value between Min_Data=0 and Max_Data=0xFFFF * @param NbrOfPixelsPerLines Value between Min_Data=0 and Max_Data=0x3FFF * @retval None */ void LL_DMA2D_ConfigSize(DMA2D_TypeDef *DMA2Dx, uint32_t NbrOfLines, uint32_t NbrOfPixelsPerLines) { MODIFY_REG(DMA2Dx->NLR, (DMA2D_NLR_PL | DMA2D_NLR_NL), \ ((NbrOfPixelsPerLines << DMA2D_NLR_PL_Pos) | NbrOfLines)); } /** * @} */ /** * @} */ /** * @} */ #endif /* defined (DMA2D) */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/36805.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); void __VERIFIER_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error(); }; return; } int __global_lock; void __VERIFIER_atomic_begin() { __VERIFIER_assume(__global_lock==0); __global_lock=1; return; } void __VERIFIER_atomic_end() { __VERIFIER_assume(__global_lock==1); __global_lock=0; return; } #include <assert.h> #include <pthread.h> #ifndef TRUE #define TRUE (_Bool)1 #endif #ifndef FALSE #define FALSE (_Bool)0 #endif #ifndef NULL #define NULL ((void*)0) #endif #ifndef FENCE #define FENCE(x) ((void)0) #endif #ifndef IEEE_FLOAT_EQUAL #define IEEE_FLOAT_EQUAL(x,y) (x==y) #endif #ifndef IEEE_FLOAT_NOTEQUAL #define IEEE_FLOAT_NOTEQUAL(x,y) (x!=y) #endif void * P0(void *arg); void * P1(void *arg); void * P2(void *arg); void fence(); void isync(); void lwfence(); int __unbuffered_cnt; int __unbuffered_cnt = 0; int __unbuffered_p2_EAX; int __unbuffered_p2_EAX = 0; int __unbuffered_p2_EBX; int __unbuffered_p2_EBX = 0; _Bool main$tmp_guard0; _Bool main$tmp_guard1; int x; int x = 0; int y; int y = 0; _Bool y$flush_delayed; int y$mem_tmp; _Bool y$r_buff0_thd0; _Bool y$r_buff0_thd1; _Bool y$r_buff0_thd2; _Bool y$r_buff0_thd3; _Bool y$r_buff1_thd0; _Bool y$r_buff1_thd1; _Bool y$r_buff1_thd2; _Bool y$r_buff1_thd3; _Bool y$read_delayed; int *y$read_delayed_var; int y$w_buff0; _Bool y$w_buff0_used; int y$w_buff1; _Bool y$w_buff1_used; _Bool weak$$choice0; _Bool weak$$choice2; void * P0(void *arg) { __VERIFIER_atomic_begin(); y$w_buff1 = y$w_buff0; y$w_buff0 = 1; y$w_buff1_used = y$w_buff0_used; y$w_buff0_used = TRUE; __VERIFIER_assert(!(y$w_buff1_used && y$w_buff0_used)); y$r_buff1_thd0 = y$r_buff0_thd0; y$r_buff1_thd1 = y$r_buff0_thd1; y$r_buff1_thd2 = y$r_buff0_thd2; y$r_buff1_thd3 = y$r_buff0_thd3; y$r_buff0_thd1 = TRUE; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); x = 1; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); y = y$w_buff0_used && y$r_buff0_thd1 ? y$w_buff0 : (y$w_buff1_used && y$r_buff1_thd1 ? y$w_buff1 : y); y$w_buff0_used = y$w_buff0_used && y$r_buff0_thd1 ? FALSE : y$w_buff0_used; y$w_buff1_used = y$w_buff0_used && y$r_buff0_thd1 || y$w_buff1_used && y$r_buff1_thd1 ? FALSE : y$w_buff1_used; y$r_buff0_thd1 = y$w_buff0_used && y$r_buff0_thd1 ? FALSE : y$r_buff0_thd1; y$r_buff1_thd1 = y$w_buff0_used && y$r_buff0_thd1 || y$w_buff1_used && y$r_buff1_thd1 ? FALSE : y$r_buff1_thd1; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __unbuffered_cnt = __unbuffered_cnt + 1; __VERIFIER_atomic_end(); return nondet_0(); } void * P1(void *arg) { __VERIFIER_atomic_begin(); x = 2; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); y = y$w_buff0_used && y$r_buff0_thd2 ? y$w_buff0 : (y$w_buff1_used && y$r_buff1_thd2 ? y$w_buff1 : y); y$w_buff0_used = y$w_buff0_used && y$r_buff0_thd2 ? FALSE : y$w_buff0_used; y$w_buff1_used = y$w_buff0_used && y$r_buff0_thd2 || y$w_buff1_used && y$r_buff1_thd2 ? FALSE : y$w_buff1_used; y$r_buff0_thd2 = y$w_buff0_used && y$r_buff0_thd2 ? FALSE : y$r_buff0_thd2; y$r_buff1_thd2 = y$w_buff0_used && y$r_buff0_thd2 || y$w_buff1_used && y$r_buff1_thd2 ? FALSE : y$r_buff1_thd2; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __unbuffered_cnt = __unbuffered_cnt + 1; __VERIFIER_atomic_end(); return nondet_0(); } void * P2(void *arg) { __VERIFIER_atomic_begin(); __unbuffered_p2_EAX = x; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); weak$$choice0 = nondet_1(); weak$$choice2 = nondet_1(); y$flush_delayed = weak$$choice2; y$mem_tmp = y; y = !y$w_buff0_used || !y$r_buff0_thd3 && !y$w_buff1_used || !y$r_buff0_thd3 && !y$r_buff1_thd3 ? y : (y$w_buff0_used && y$r_buff0_thd3 ? y$w_buff0 : y$w_buff1); y$w_buff0 = weak$$choice2 ? y$w_buff0 : (!y$w_buff0_used || !y$r_buff0_thd3 && !y$w_buff1_used || !y$r_buff0_thd3 && !y$r_buff1_thd3 ? y$w_buff0 : (y$w_buff0_used && y$r_buff0_thd3 ? y$w_buff0 : y$w_buff0)); y$w_buff1 = weak$$choice2 ? y$w_buff1 : (!y$w_buff0_used || !y$r_buff0_thd3 && !y$w_buff1_used || !y$r_buff0_thd3 && !y$r_buff1_thd3 ? y$w_buff1 : (y$w_buff0_used && y$r_buff0_thd3 ? y$w_buff1 : y$w_buff1)); y$w_buff0_used = weak$$choice2 ? y$w_buff0_used : (!y$w_buff0_used || !y$r_buff0_thd3 && !y$w_buff1_used || !y$r_buff0_thd3 && !y$r_buff1_thd3 ? y$w_buff0_used : (y$w_buff0_used && y$r_buff0_thd3 ? FALSE : y$w_buff0_used)); y$w_buff1_used = weak$$choice2 ? y$w_buff1_used : (!y$w_buff0_used || !y$r_buff0_thd3 && !y$w_buff1_used || !y$r_buff0_thd3 && !y$r_buff1_thd3 ? y$w_buff1_used : (y$w_buff0_used && y$r_buff0_thd3 ? FALSE : FALSE)); y$r_buff0_thd3 = weak$$choice2 ? y$r_buff0_thd3 : (!y$w_buff0_used || !y$r_buff0_thd3 && !y$w_buff1_used || !y$r_buff0_thd3 && !y$r_buff1_thd3 ? y$r_buff0_thd3 : (y$w_buff0_used && y$r_buff0_thd3 ? FALSE : y$r_buff0_thd3)); y$r_buff1_thd3 = weak$$choice2 ? y$r_buff1_thd3 : (!y$w_buff0_used || !y$r_buff0_thd3 && !y$w_buff1_used || !y$r_buff0_thd3 && !y$r_buff1_thd3 ? y$r_buff1_thd3 : (y$w_buff0_used && y$r_buff0_thd3 ? FALSE : FALSE)); __unbuffered_p2_EBX = y; y = y$flush_delayed ? y$mem_tmp : y; y$flush_delayed = FALSE; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); y = y$w_buff0_used && y$r_buff0_thd3 ? y$w_buff0 : (y$w_buff1_used && y$r_buff1_thd3 ? y$w_buff1 : y); y$w_buff0_used = y$w_buff0_used && y$r_buff0_thd3 ? FALSE : y$w_buff0_used; y$w_buff1_used = y$w_buff0_used && y$r_buff0_thd3 || y$w_buff1_used && y$r_buff1_thd3 ? FALSE : y$w_buff1_used; y$r_buff0_thd3 = y$w_buff0_used && y$r_buff0_thd3 ? FALSE : y$r_buff0_thd3; y$r_buff1_thd3 = y$w_buff0_used && y$r_buff0_thd3 || y$w_buff1_used && y$r_buff1_thd3 ? FALSE : y$r_buff1_thd3; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __unbuffered_cnt = __unbuffered_cnt + 1; __VERIFIER_atomic_end(); return nondet_0(); } void fence() { } void isync() { } void lwfence() { } int main() { pthread_create(NULL, NULL, P0, NULL); pthread_create(NULL, NULL, P1, NULL); pthread_create(NULL, NULL, P2, NULL); __VERIFIER_atomic_begin(); main$tmp_guard0 = __unbuffered_cnt == 3; __VERIFIER_atomic_end(); __VERIFIER_assume(main$tmp_guard0); __VERIFIER_atomic_begin(); y = y$w_buff0_used && y$r_buff0_thd0 ? y$w_buff0 : (y$w_buff1_used && y$r_buff1_thd0 ? y$w_buff1 : y); y$w_buff0_used = y$w_buff0_used && y$r_buff0_thd0 ? FALSE : y$w_buff0_used; y$w_buff1_used = y$w_buff0_used && y$r_buff0_thd0 || y$w_buff1_used && y$r_buff1_thd0 ? FALSE : y$w_buff1_used; y$r_buff0_thd0 = y$w_buff0_used && y$r_buff0_thd0 ? FALSE : y$r_buff0_thd0; y$r_buff1_thd0 = y$w_buff0_used && y$r_buff0_thd0 || y$w_buff1_used && y$r_buff1_thd0 ? FALSE : y$r_buff1_thd0; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ main$tmp_guard1 = !(x == 2 && __unbuffered_p2_EAX == 2 && __unbuffered_p2_EBX == 0); __VERIFIER_atomic_end(); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ __VERIFIER_assert(main$tmp_guard1); return 0; }
the_stack_data/78689.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> typedef struct Elementos{ int valor; struct Elementos *prox; }Elementos; int pilha_contador; Elementos *topo; // ----------------------------------------FUNÇÕES------------------------------------------------------------------ void inicia(); int vazia(); void tamanho(); void push(int item); void pop(); void get(); void erase(); void exibe(); void menu(); // ------------------------------------------MAIN-------------------------------------------------------------------- int main(void){ inicia(); menu(); erase(); } // ----------------------------------------------------------------------------------------------------------------- void inicia(){ topo = NULL; pilha_contador = 0; } // ----------------------------------------------------------------------------------------------------------------- int vazia(){ if(topo==NULL){ return 1; }else return 0; } // ----------------------------------------------------------------------------------------------------------------- void tamanho(){ system("clear"); printf("O tamanho atual da pilha é de %d elementos\n\n",pilha_contador); } // ----------------------------------------------------------------------------------------------------------------- void push(int item){ Elementos *nova = (Elementos*) malloc(sizeof(Elementos)); if(nova == NULL){ printf("Erro na alocação de memória! "); sleep(1.5); exit(1); }else { nova->valor = item; nova->prox = topo; topo = nova; pilha_contador ++; } } // ----------------------------------------------------------------------------------------------------------------- void pop(){ Elementos *temp; if(vazia()){ printf("Nada para desempilhar!\n"); }else{ temp = topo; topo = topo->prox; temp->prox = NULL; free(temp); pilha_contador --; } } // ----------------------------------------------------------------------------------------------------------------- void get(){ if(vazia()){ printf("Nada para desempilhar!\n"); }else{ system("clear"); printf("O valor do topo é %d\n\n",topo->valor); } } // ----------------------------------------------------------------------------------------------------------------- void erase(){ Elementos *temp; if(vazia()){ printf("Não a nada para apagar! Pilha vazia\n"); }else { while(topo != NULL){ temp = topo; temp->prox=NULL; topo = topo->prox; free(temp); } pilha_contador = 0; } } // ----------------------------------------------------------------------------------------------------------------- void exibe(){ Elementos *temp; temp = topo; if(vazia()){ printf("Pilha vazia, nada a exibir!\n"); }else{ while(temp != NULL){ printf("%d\n",temp->valor); temp = temp->prox; } } } // ----------------------------------------------------------------------------------------------------------------- void menu(){ int op= -1; int value; while(op != 0){ sleep(1.5); system("clear"); printf("0 - Sair\n"); printf("1 - Inserir Elemento\n"); printf("2 - Remover Elemento\n"); printf("3 - Valor do topo\n"); printf("4 - Apagar a pilha\n"); printf("5 - Exibir a pilha\n"); printf("6 - Tamanho da pilha\n"); printf("Digite sua opção: "); scanf("%d",&op); switch(op){ case 0: break; case 1: printf("Digite um valor para adicionar a pilha: "); scanf("%d",&value); push(value); break; case 2: pop(); break; case 3: get(); break; case 4: erase(); break; case 5: exibe(); break; case 6: tamanho(); break; default: printf("\nEscolha invalida! Escolha uma opção: \n"); } } } // -----------------------------------------------------------------------------------------------------------------
the_stack_data/165764560.c
//#include "utest.h" //#include "..\include\btc\block.h" //#include "..\include\btc\net.h" //#include "..\include\btc\netspv.h" // //#include <unistd.h> // //void test_spv_sync_completed(btc_spv_client* client) { // printf("Sync completed, at height %d\n", client->headers_db->getchaintip(client->headers_db_ctx)->height); // btc_node_group_shutdown(client->nodegroup); //} // //btc_bool test_spv_header_message_processed(struct btc_spv_client_ *client, btc_node *node, btc_blockindex *newtip) { // UNUSED(client); // UNUSED(node); // if (newtip) { // printf("New headers tip height %d\n", newtip->height); // } // return true; //} // //void test_netspv() //{ // unlink("headers.db"); // btc_spv_client* client = btc_spv_client_new(&btc_chainparams_main, true, false); // client->header_message_processed = test_spv_header_message_processed; // client->sync_completed = test_spv_sync_completed; // // btc_spv_client_load(client, "headers.db"); // // printf("Discover peers..."); // btc_spv_client_discover_peers(client, NULL); // printf("done\n"); // printf("Start interacting with the p2p network...\n"); // btc_spv_client_runloop(client); // btc_spv_client_free(client); //}
the_stack_data/14198946.c
#include<stdio.h> int main() { int n,i,a,b,sum=0,j; scanf("%d", &n); for(i=1; i<=n; i++) { scanf("%d %d", &a,&b); sum = 0; for(j=a; j<=b; j++) { if(j%2==1) { sum = sum + j; } } printf("Case %d: %d\n",i,sum); } return 0; }
the_stack_data/87283.c
#include <stddef.h> struct bt { unsigned value; struct bt *left; struct bt *right; }; struct bt *invert(struct bt *p) { struct bt *t; if (!p) return NULL; t = invert(p->left); p->left = invert(p->right); p->right = t; return p; } int main(void) { return 0; }
the_stack_data/107836.c
#include <limits.h> #define max(a, b) (((a) > (b)) ? (a) : (b)) #define min(a, b) (((a) < (b)) ? (a) : (b)) int replaceDigits(int num, int x, int y) //replace x with y { int res = 0, digit = 0; for (int base = 1; num != 0; num /= 10, base *= 10) { digit = num % 10; if (digit == x) digit = y; res += digit * base; } return digit == 0 ? -1 : res; } int maxDiff(int num) { int maxval = INT_MIN, minval = INT_MAX; for (int i = 0; i <= 9; ++i) { for (int j = 0; j <= 9; ++j) { int res = replaceDigits(num, i, j); if (res > 0) { maxval = max(maxval, res); minval = min(minval, res); } } } return maxval - minval; }
the_stack_data/289811.c
#include <stdio.h> int main(){ int vezes, cont; float a, b, c; scanf("%d", &vezes); for(cont = 0; cont < vezes; cont++){ scanf("%f %f %f", &a, &b, &c); printf("%.1f\n", (a*2.0 + b*3.0 + c*5.0)/10.0); } return 0; }
the_stack_data/992413.c
#include <stdio.h> #include <string.h> #include <stdlib.h> // Hi there -> iH ereht void reverse(char* begin, char* end) { char tmp; while (begin < end) { tmp = *begin; *begin++ = *end; *end-- = tmp; } } void mirror_words(char* words) { if (!words) { return; } char* word_begin = words; char* tmp = words; while (*tmp) { tmp++; if (*tmp == '\0') { reverse(word_begin, tmp - 1); } else if (*tmp == ' ') { reverse(word_begin, tmp - 1); word_begin = tmp + 1; } } reverse(words, tmp - 1); } int main(int args, char** argv) { char words[] = "I like this program very much"; char* tmp = words; mirror_words(words); fprintf(stdout, "%s\n", words); return EXIT_SUCCESS; }
the_stack_data/29949.c
#include <stdio.h> #include <stddef.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> struct Qmempool { int fd; char filepath[128]; char *startaddr;// 内存首地址 char *pos; // 记录剩余空间的首地址(忽略内存碎片) size_t size; // 内存空间总大小 size_t free; // 剩余空间大小(忽略内存碎片) }; static struct Qmempool g_pool = {.fd = -1}; struct mem_node_hdr { // char is_free; // 是否被释放,1-已释放,0-使用中 struct mem_node_hdr *next; // 指向下个节点的指针 struct mem_node_hdr *prev; // 指向上个节点的指针 size_t size; // 节点数据内存空间大小 char data[0]; // 节点数据的首地址 }__attribute__((packed)); // 节点头部大小 #define NODE_HDR_SIZE sizeof(struct mem_node_hdr) // 节点大小,头部+数据 #define NODE_SIZE(n) (NODE_HDR_SIZE + n->size) // 节点尾部指针 #define NODE_TAIL_PTR(n) (n + NODE_SIZE(n)) // 头节点 #define HEAD_NODE_PRT ((struct mem_node_hdr *)g_pool.startaddr) // 起始节点指针 #define START_NODE_PTR ((struct mem_node_hdr *)(g_pool.startaddr + NODE_HDR_SIZE)) #define container_of(ptr, type, member) ({ \ void *__mptr = (void *)(ptr); \ ((type *)(__mptr - offsetof(type, member))); }) // 根据ptr获取节点 #define NODE_ENTRY(ptr) container_of(ptr, struct mem_node_hdr, data) // 遍历节点 #define MEM_NODE_FOR_EACH(start, node) \ for (node = start; node->next != NULL; node=node->next) static struct mem_node_hdr *__alloc_node(size_t size) { struct mem_node_hdr *node, *newnode; MEM_NODE_FOR_EACH(HEAD_NODE_PRT, node) { if (node->next - NODE_TAIL_PTR(node) > size) break; } newnode = NODE_TAIL_PTR(node); memset(newnode, 0, NODE_HDR_SIZE + size); newnode->size = size; newnode->prev = node; newnode->next = node->next; if (node->next) node->next->prev = newnode; node->next = newnode; // printf("newnode: %p, pos: %p\n", (char *)newnode, g_pool.pos); if ((char *)newnode == g_pool.pos) { if (size > g_pool.free) return NULL; g_pool.pos += NODE_SIZE(newnode); g_pool.free -= NODE_SIZE(newnode); } printf("[__alloc_node] addr: %p, size: %u\n", newnode->data, newnode->size); return newnode; } static void __free_node(struct mem_node_hdr *node) { if (node->prev) node->prev->next = node->next; if (node->next) node->next->prev = node->prev; printf("[__free_node] addr: %p, size: %u\n", node->data, node->size); memset(node, 0, NODE_SIZE(node)); } static inline void Qmempool_clear(void) { remove(g_pool.filepath); memset(&g_pool, 0, sizeof(g_pool)); g_pool.fd = -1; } int Qmmap_init(const char *filepath, size_t size) { int fd; struct stat st; fd = open(filepath, O_RDWR | O_CREAT, 0700); if (fd < 0) { printf("open file %s error.\n", filepath); return -1; } if (stat(filepath, &st) < 0) { printf("stat file %s error.\n", filepath); goto err; } if (st.st_size < size && ftruncate(fd, size) != 0) { printf("set size failed.\n"); goto err; } g_pool.startaddr = (char *)mmap(NULL, size, PROT_WRITE | PROT_READ, MAP_SHARED, fd, 0); if (g_pool.startaddr == MAP_FAILED) { printf("mmap failed.\n"); goto err; } g_pool.pos = g_pool.startaddr; g_pool.size = size; g_pool.free = size; g_pool.fd = fd; snprintf(g_pool.filepath, sizeof(g_pool.filepath), "%s", filepath); memset(HEAD_NODE_PRT, 0, NODE_HDR_SIZE); return 0; err: close(fd); Qmempool_clear(); return -1; } void Qmmap_fini(void) { if (g_pool.fd >= 0) close(g_pool.fd); if (g_pool.startaddr) munmap(g_pool.startaddr, g_pool.size); Qmempool_clear(); } void *Qmalloc(size_t size) { struct mem_node_hdr *newnode; newnode = __alloc_node(size); if (!newnode) { printf("NO MEM!!!\n"); return NULL; } return (void *)newnode->data; } void Qfree(void *ptr) { struct mem_node_hdr *node; node = NODE_ENTRY(ptr); __free_node(node); } void *Qcalloc(size_t nmemb, size_t size) { return Qmalloc(nmemb * size); } void *Qrealloc(void *ptr, size_t size) { struct mem_node_hdr *newnode, *oldnode; oldnode = NODE_ENTRY(ptr); // 这里不考虑内存变小的情况 if(oldnode->size >= size) return NULL; newnode = __alloc_node(size); memcpy(newnode->data, oldnode->data, oldnode->size); __free_node(oldnode); return newnode->data; } void check_mem_leak(void) { size_t total_size = 0; struct mem_node_hdr *node, *newnode; MEM_NODE_FOR_EACH(START_NODE_PTR, node) { printf("[MemLeak] Addr: %p, Size: %u\n", node->data, node->size); total_size += node->size; } printf("\n====== Total MemLeak ======\n size: %u\n\n", total_size); } #define KB_SIZE 1024 void QMPOOL_TEST_1(void) { char *p1, *p2, *p3; p1 = (char *)Qmalloc(KB_SIZE); p2 = (char *)Qmalloc(KB_SIZE); p3 = (char *)Qcalloc(2, KB_SIZE); memset(p1, '1', KB_SIZE - 1); p1[KB_SIZE] = '\0'; memset(p2, '2', KB_SIZE - 1); p2[KB_SIZE] = '\0'; memset(p3, '3', 2 * KB_SIZE - 1); p3[2 * KB_SIZE] = '\0'; printf("p1: %s\n", p1); printf("p2: %s\n", p2); printf("p3: %s\n", p3); p2 = Qrealloc(p2, 2 * KB_SIZE); memset(p2, '2', 2 * KB_SIZE - 1); p2[2 * KB_SIZE] = '\0'; printf("p2: %s\n", p2); printf("p3: %s\n", p3); Qfree(p3); Qfree(p2); Qfree(p1); } void QMPOOL_TEST_2(void) { char *p1, *p2, *p3, *p4, *p5; p1 = (char *)Qmalloc(2 * KB_SIZE); p2 = (char *)Qmalloc(KB_SIZE); memset(p1, '1', 2 * KB_SIZE - 1); p1[2 * KB_SIZE] = '\0'; memset(p2, '2', KB_SIZE - 1); p2[KB_SIZE] = '\0'; printf("p1: %s\n", p1); printf("p2: %s\n", p2); Qfree(p1); p3 = (char *)Qmalloc(KB_SIZE); p4 = (char *)Qmalloc(KB_SIZE); p5 = (char *)Qmalloc(KB_SIZE); memset(p3, '3', KB_SIZE - 1); p3[KB_SIZE] = '\0'; memset(p4, '4', KB_SIZE - 1); p4[KB_SIZE] = '\0'; memset(p5, '5', KB_SIZE - 1); p5[KB_SIZE] = '\0'; printf("p3: %s\n", p3); printf("p4: %s\n", p4); printf("p5: %s\n", p5); Qfree(p5); Qfree(p4); Qfree(p3); Qfree(p2); } int main(void) { if (Qmmap_init("/qmempool_mmap", 100 * 1024 * 1024)) { // 100M printf("Qmmap_init error.\n"); return -1; } QMPOOL_TEST_1(); QMPOOL_TEST_2(); check_mem_leak(); Qmmap_fini(); return 0; }
the_stack_data/76698946.c
#include <stdio.h> #include <math.h> #include <string.h> int prime(int a) { int i=0,l=0,k=0; for (i=1;i<=a-1;i++) { k=a%i; if (k==0) l=l+1; } if (l==1) return 1; else return 0; } int main () {int num=0; scanf ("%d",&num); while (1) {num=num+1; if (prime(num)==1) break ;} printf ("%d",num); return 0; }
the_stack_data/9513637.c
#include<stdio.h> #include<stdlib.h> #include<stdbool.h> #include<math.h> #include<time.h> /* switch ( a ) { case b: // Code break; case c: // Code break; default: // Code break; } */ int calctime(int n, int d) { switch(d) { case 6: return 10*n*86400; break; case 7: return n*86400; break; case 8: return 10*n*3600; break; case 9: return n*3600; break; case 10: return 10*n*60; break; case 11: return n*60; break; case 12: return 10*n; break; case 13: return n; break; default: printf("\nError in calctime\n"); return NAN; break; } } void count(int c, int counter[], int line_inf[]) { switch(counter[0]) { case 0: line_inf[0]=(int)(c-'0'); break; case 1: if(counter[1]>5) line_inf[1]+=calctime((int)(c-'0'),counter[1]); break; case 4: if(counter[1]>5) line_inf[4]+=calctime((int)(c-'0'),counter[1]); break; default: break; } } int read_line(FILE *file, int counter[], int line_inf[]) { int i, c; for(i=0; i<7; i++) line_inf[i] = 0; while( ((c = getc(file)) != '\n') && ((c = getc(file)) != EOF) ) { switch(c) { case ';': counter[0]++; counter[1]=0; break; default: count(c, counter, line_inf); counter[1]++; break; } } counter[0]=0; counter[1]=0; if(c == '\n') return 1; return 0; } int main(void) { int counter[2]={0,0}, n_lines=0, c, line_inf[7]; float totaltrip=0; FILE *file; file = fopen("paris-201503.csv", "r"); if (file) { while ((c = getc(file)) != '\n') putchar(c); printf("\n"); read_line(file, counter, line_inf); printf("%d %d %d %d %d %d %d\n",line_inf[0],line_inf[1],line_inf[2],line_inf[3],line_inf[4],line_inf[5],line_inf[6]); /* while ((c = getc(file)) != EOF) { switch(c) { case ';': counter[0]++; counter[1]=0; break; case '\n': counter[0]=0; n_lines++; totaltrip += (trip[1]-trip[0]+86400)%86400; // printf("\nTime={%f}\n", (float)(trip[1]-trip[0])/60); trip[0]=0; trip[1]=0; break; default: count(c, counter, reason, trip); counter[1]++; break; } // putchar(c); } */ fclose(file); } getchar(); return 0; }
the_stack_data/40083.c
/* * vivi의 vfs area중에서 file_list[]의 위치를 계산하다. */ #include <stdio.h> int main(void) { int i; unsigned long addr = 0x0200; for(i=0; i < 11; i++) { printf("0x%08lx\n", addr); addr += 72; } return 0; }
the_stack_data/148532.c
#include <stdlib.h> #include <stdio.h> #include <time.h> FILE * fp; // A recursive binary search function. It returns // location of x in given array arr[l..r] is present, // otherwise -1 int binarySearch(int *arr, int l, int r, int x){ if (r >= l) { int mid = l + (r - l)/2; // If the element is present at the middle // itself if (arr[mid] == x) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid-1, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid+1, r, x); } // We reach here when element is not // present in array return -1; } void benchMark(int max){ int *arr = (int *)malloc(max*sizeof(int)); for(int i = 0; i < max; i++){ arr[i] = rand()%1000; } clock_t begin = clock(); for(int i = 0; i < 1000; i++){ int result = binarySearch(arr, 0, max-1, i); } clock_t end = clock(); double time_spent = (double)(end - begin) / CLOCKS_PER_SEC; fprintf (fp, "%d , %f\n", max, time_spent); free(arr); } int main(void) { int data = 10000; fp = fopen ("BinarySearch.txt","w"); while(data <= 100000000){ benchMark(data); data = data * 10; } /* close the file*/ fclose (fp); return 0; }
the_stack_data/122223.c
/**~deployment~ * Manifestation [Class] * * Description * * A manifestation is the concrete physical rendering of one or more model elements by an artifact. * * Diagrams * * Artifacts * * Generalizations * * Abstraction * * Association Ends * *  utilizedElement : PackageableElement [1..1]{subsets Dependency::supplier} (opposite * A_utilizedElement_manifestation::manifestation) * * The model element that is utilized in the manifestation in an Artifact. **/
the_stack_data/162644223.c
#include<stdio.h> #include<stdlib.h> typedef struct Node { int data; struct Node *left,*right; }node; void insert(node*,node*); void print(node*); int height(node*); int main() { char ch='y'; node *root,*new; root=NULL; while(ch=='y') { new=(node*)malloc(sizeof(node)); scanf("%d",&(new->data)); new->left=NULL; new->right=NULL; if(root==NULL) root=new; else insert(root,new); printf("\nWant to enter more :"); fflush(stdin); scanf("%c",&ch); } printf("\nThe height is :%d",height(root)); return 0; } void insert(node *head,node *new) { char choice; fflush(stdin); printf("Right or left:"); scanf("%c",&choice); if(choice=='r') { if(head->right==NULL) head->right=new; else insert(head->right,new); } else { if(head->left==NULL) head->left=new; else insert(head->left,new); } } int height(node *t) { int c=1,c1=1; if(t->left!=NULL) c+=height(t->left); if(t->right!=NULL) c1+=height(t->right); return (c>c1)?(c):(c1); }
the_stack_data/105565.c
/* Write a program that asks the user to enter a two digit number, then prints the number with its digits reversed */ #include <stdio.h> int main(void) { int num, new_num; printf("Enter a two digit number: "); scanf("%d", &num); new_num = 0; new_num += (num % 10) * 10; new_num += num / 10; printf("The reversal is: %d\n", new_num); return 0; }
the_stack_data/231392775.c
#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *get_avg(void *raw_args); void *get_max(void *raw_args); void *get_min(void *raw_args); int MAX; int MIN; int AVG; struct arg_struct { int *arr; int len; } *args; int main(int argc, char **argv) { int arr[argc-1]; args = malloc((int)sizeof(struct arg_struct)); for (int i = 1; i < argc; i++) { arr[i-1] = atoi(argv[i]); } args->arr = arr; args->len = (int)(sizeof(arr)/sizeof(int)); for (int i = 0; i < 3; i++) { pthread_t tid; // the thread identifier pthread_attr_t attr; // set of thread attributes pthread_attr_init(&attr); // set the default attributes of the thread switch (i) { case 0: pthread_create(&tid, &attr, get_avg, args); // create the thread break; case 1: pthread_create(&tid, &attr, get_max, args); // create the thread break; case 2: pthread_create(&tid, &attr, get_min, args); // create the thread break; } pthread_join(tid, NULL); // wait for the thread to exit } printf("avg: %d, max: %d, min: %d\n", AVG, MIN, MAX); free(args); return 0; } void *get_avg(void *raw_args) { struct arg_struct *args = raw_args; AVG = 0; int sum = 0; for (int i = 0; i < args->len; i++) { sum += args->arr[i]; } AVG = sum / args->len; pthread_exit(0); } void *get_max(void *raw_args) { struct arg_struct *args = raw_args; int m = args->arr[0]; for (int i = 0; i < args->len; i++) { if (args->arr[i] > m) { m = args->arr[i]; } } MIN = m; pthread_exit(0); } void *get_min(void *raw_args) { struct arg_struct *args = raw_args; int m = args->arr[0]; for (int i = 0; i < args->len; i++) { if (args->arr[i] < m) { m = args->arr[i]; } } MAX = m; pthread_exit(0); }
the_stack_data/165766833.c
#include <stdio.h> int main() { int cod_um, cod_dois, qtd_um, qtd_dois; double valor_um, valor_dois, total; scanf("%d %d %lf", &cod_um, &qtd_um, &valor_um); scanf("%d %d %lf", &cod_dois, &qtd_dois, &valor_dois); valor_um = qtd_um * valor_um; valor_dois = qtd_dois * valor_dois; total = valor_um + valor_dois; printf("VALOR A PAGAR: R$ %.2lf\n", total); return 0; }
the_stack_data/12198.c
#include <stdio.h> #define LOADDATA 0x10 #define INTRCPU 0x20 #define CLOCKLOW 0x40 unsigned char kbdSequence[4][16] = { { 1, 2 + LOADDATA, 3 + LOADDATA, 4 + LOADDATA, 5 + LOADDATA, 6 + LOADDATA, 7 + LOADDATA, 8 + LOADDATA, 9 + LOADDATA, 10, 11, 11 + INTRCPU + CLOCKLOW, /* get into loop if clk keeps going */ 0, 0, 0, 0 }, { 1, 2 + LOADDATA, 3 + LOADDATA, 4 + LOADDATA, 5 + LOADDATA, 6 + LOADDATA, 7 + LOADDATA, 8 + LOADDATA, 9 + LOADDATA, 10, 10 + INTRCPU + CLOCKLOW, 0, 0, 0, 0, 0 }, { 1, 2, 3 + LOADDATA, 4 + LOADDATA, 5 + LOADDATA, 6 + LOADDATA, 7 + LOADDATA, 8 + LOADDATA, 9 + LOADDATA, 10 + LOADDATA, 11, 12, 12 + INTRCPU + CLOCKLOW, 0, 0, 0 }, { 1, 2, 3 + LOADDATA, 4 + LOADDATA, 5 + LOADDATA, 6 + LOADDATA, 7 + LOADDATA, 8 + LOADDATA, 9 + LOADDATA, 10 + LOADDATA, 11, 11 + INTRCPU + CLOCKLOW, 0, 0, 0, 0 }, }; int main(int argc, char **argv) { int j; int i; for(j = 0; j < 4; j++) for(i = 0; i < 16; i++) putchar(kbdSequence[j][i]); }
the_stack_data/906480.c
#ifdef _ULPCC_ // do not add code above this line #include <ulp_c.h> #include "ulp_common.h" // See // https://github.com/espressif/esp-idf/blob/98e15df7f6af8f7f26f895b31e18049198dcc938/components/driver/rtc_module.c#L46 #define PIN_RTC_EPD_BUSY 6 // GPIO25 RTCIO6 #define PIN_RTC_BUS_POWER_SW 9 // GPIO32 RTCIO9 // Global variables unsigned _counterPeriodicTask = 0; unsigned status = 0; unsigned epdBusyStatus = 0; void entry() { // Un hold GPIO32 (BUS_POWER_SW) reg_wr(RTC_IO_XTAL_32K_PAD_REG, RTC_IO_X32P_HOLD_S, RTC_IO_X32P_HOLD_S, 0); if(status & PM_STATUS_WAIT_BUSY_REQ) { // Read EPD_BUSY H/L epdBusyStatus = reg_rd(RTC_GPIO_IN_REG, RTC_GPIO_IN_NEXT_S + PIN_RTC_EPD_BUSY, RTC_GPIO_IN_NEXT_S + PIN_RTC_EPD_BUSY); // If not busy (H) if(epdBusyStatus) { // Clear the flag. status &= PM_STATUS_WAIT_BUSY_REQ_M; // Disable Pull-up of GPIO25 (EPD_BUSY). Avoid current leakage. reg_wr(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_RUE_S, RTC_IO_PDAC1_RUE_S, 0); // // Put GPIO32 (BUS_POWER_SW) to LOW. Power off EPD & SD bus. reg_wr(RTC_GPIO_OUT_W1TC_REG, RTC_GPIO_OUT_DATA_W1TC_S + 9, RTC_GPIO_OUT_DATA_W1TC_S + 9, 1); } } // Hold GPIO32 (BUS_POWER_SW). To keep Bus Power ON. reg_wr(RTC_IO_XTAL_32K_PAD_REG, RTC_IO_X32P_HOLD_S, RTC_IO_X32P_HOLD_S, 1); _counterPeriodicTask++; if(_counterPeriodicTask >= COUNTER_PERIODIC_TASK) { _counterPeriodicTask = 0; wake(); // Un hold GPIO32 (BUS_POWER_SW) reg_wr(RTC_IO_XTAL_32K_PAD_REG, RTC_IO_X32P_HOLD_S, RTC_IO_X32P_HOLD_S, 0); halt(); } } #endif // do not add code after here
the_stack_data/87639133.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *p_buf; #if defined(__GNUC__) # if defined(__i386__) __asm__("pushf\norl $0x40000,(%esp)\npopf"); # elif defined(__x86_64__) __asm__("pushf\norl $0x40000,(%rsp)\npopf"); # endif #endif if ((p_buf = (char *)malloc(sizeof(char) * 65536)) == NULL) return EXIT_FAILURE; memcpy(p_buf, "1234567890abc", 13); p_buf += 13; *((long *)p_buf) = 123456; return EXIT_SUCCESS; }
the_stack_data/295786.c
/* Example code for Think OS. Copyright 2014 Allen Downey License: GNU GPLv3 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define ARRAY_SIZE 10 #define BUFFER_SIZE 20 int end_of_file = 0; int bad_input = 0; /* add_array: Adds up the elements of an array. * * array: int pointer * n: number of elements in the array * * returns: total */ int add_array(int array[], int n) { int i; int total = 0; for (i=0; i<n; i++) { total += array[i]; } return total; } /* read_integer: Reads an integer from stdin. * * returns: integer */ int read_integer() { char *res; char buffer[BUFFER_SIZE]; long int number; char *end; // read a string res = fgets(buffer, sizeof(buffer), stdin); if (res == NULL) { end_of_file = 1; return 0; } // check if the length of the string it too long if (strlen(buffer) == BUFFER_SIZE) { bad_input = 1; return 0; } //printf("%s, %d\n", buffer, (int)strlen(buffer)); // convert to integer number = strtol(buffer, &end, 10); // number = atoi(buffer); // check for invalid input. Notice that atoi returns 0 // for invalid input, so we can't allow the used to enter 0. if (number == 0) { bad_input = 1; return 0; } return number; } int main() { int i; int res; int array[ARRAY_SIZE]; for (i=0; i<ARRAY_SIZE; i++) { int res = read_integer(); //printf("%d\n", res); if (end_of_file) { int total = add_array(array, i); printf("total %d\n", total); return 0; } if (bad_input) { printf("Invalid input.\n"); return -1; } array[i] = res; } // if we get to the end of the loop, the user entered // too many numbers printf("Too many numbers.\n"); return -1; }
the_stack_data/159514675.c
#include <errno.h> #include <fcntl.h> #include <string.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/poll.h> #include <sys/socket.h> #include <sys/types.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> #ifndef TCP_FASTOPEN #define TCP_FASTOPEN 23 #endif #ifndef MSG_FASTOPEN #define MSG_FASTOPEN 0x20000000 #endif #ifndef IP_TRANSPARENT #define IP_TRANSPARENT 19 #endif static void die_usage(void) { fputs("Usage: tcprdr [ -4 | -6 ] [ -f ] [ -l ] [ -t [ -T ]] [ -L listen address ] localport host [ remoteport ]\n", stderr); exit(1); } /* Turn this program into a daemon process. */ static void daemonize(void) { pid_t pid = fork(); pid_t sid; if (pid < 0) { perror("fork(daemonize)"); exit(EXIT_FAILURE); } if (pid > 0) { /* This is the parent. We can terminate it. */ exit(EXIT_SUCCESS); } /* Execution continues only in the child's context. */ sid = setsid(); if (sid < 0) { exit(EXIT_FAILURE); } } static int wanted_pf = PF_UNSPEC; static bool loop = false; static bool tproxy = false; static bool tproxy_trans = false; /* use non-local, original client ip for outgoing connection */ static bool fastopen = false; static char *listenaddr = NULL; static const char *getxinfo_strerr(int err) { const char *errstr; if (err == EAI_SYSTEM) errstr = strerror(errno); else errstr = gai_strerror(err); return errstr; } static void xgetaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res) { int err = getaddrinfo(node, service, hints, res); if (err) { const char *errstr = getxinfo_strerr(err); fprintf(stderr, "Fatal: getaddrinfo(%s:%s): %s\n", node ? node: "", service ? service: "", errstr); exit(1); } } static void xgetnameinfo(const struct sockaddr *sa, socklen_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags) { int err = getnameinfo(sa, salen, host, hostlen, serv, servlen, flags); if (err) { const char *errstr = getxinfo_strerr(err); fprintf(stderr, "Fatal: getnameinfo(): %s\n", errstr); exit(1); } } static void ipaddrtostr(const struct sockaddr *sa, socklen_t salen, char *resbuf, size_t reslen, char *port, size_t plen) { xgetnameinfo(sa, salen, resbuf, reslen, port, plen, NI_NUMERICHOST|NI_NUMERICSERV); } static void logendpoints(int dest, int origin) { struct sockaddr_storage ss1, ss2; int ret; char buf1[INET6_ADDRSTRLEN]; char buf2[INET6_ADDRSTRLEN]; socklen_t sa1len, sa2len; sa1len = sa2len = sizeof(ss1); ret = getpeername(origin, (struct sockaddr *) &ss1, &sa1len); if (ret == -1) { perror("getpeername"); return; } ret = getpeername(dest, (struct sockaddr *) &ss2, &sa2len); if (ret == -1) { perror("getpeername"); return; } ipaddrtostr((const struct sockaddr *) &ss1, sa1len, buf1, sizeof(buf1), NULL, 0); ipaddrtostr((const struct sockaddr *) &ss2, sa2len, buf2, sizeof(buf2), NULL, 0); fprintf(stderr, "Handling connection from %s to %s", buf1, buf2); if (tproxy) { char port[8]; sa1len = sizeof(ss1); ret = getsockname(origin, (struct sockaddr *) &ss1, &sa1len); if (ret) { perror("getsockname"); return; } ipaddrtostr((const struct sockaddr *) &ss1, sa1len, buf1, sizeof(buf1), port, sizeof(port)); fprintf(stderr, " (original destination was %s:%s)", buf1, port); } fputc('\n', stderr); } static int sock_listen_tcp(const char * const listenaddr, const char * const port) { int sock; struct addrinfo hints = { .ai_protocol = IPPROTO_TCP, .ai_socktype = SOCK_STREAM, .ai_flags = AI_PASSIVE | AI_NUMERICHOST }; hints.ai_family = wanted_pf; struct addrinfo *a, *addr; int one = 1; xgetaddrinfo(listenaddr, port, &hints, &addr); for (a = addr; a != NULL ; a = a->ai_next) { sock = socket(a->ai_family, a->ai_socktype, a->ai_protocol); if (sock < 0) { perror("socket"); continue; } if (-1 == setsockopt(sock, SOL_SOCKET,SO_REUSEADDR,&one,sizeof one)) perror("setsockopt"); if (bind(sock, a->ai_addr, a->ai_addrlen) == 0) break; /* success */ perror("bind"); close(sock); sock = -1; } if ((sock >= 0) && listen(sock, 65535)) perror("listen"); freeaddrinfo(addr); return sock; } static int connect_fastopen(int txfd, char *buf, int blen, const struct sockaddr *dest_addr, socklen_t alen) { int ret; /* implicit connect() */ ret = sendto(txfd, buf, blen, MSG_FASTOPEN, dest_addr, alen); if (ret != blen) return -1; return 0; } static int connect_fastopen_prepare(int fd, char *buf, size_t len) { int r = recv(fd, buf, len, MSG_DONTWAIT); if (r >= 0) return r; return (errno == EAGAIN || errno == EINTR) ? -1 : 0; } static int sock_connect_tcp(const char * const remoteaddr, const char * const port, int rs) { char buf[1024]; int buflen; int sock; int mark = 333; struct addrinfo hints = { .ai_protocol = IPPROTO_TCP, .ai_socktype = SOCK_STREAM, }; struct addrinfo *a, *addr; struct sockaddr_storage sa; socklen_t salen = sizeof(sa); if (fastopen) { buflen = connect_fastopen_prepare(rs, buf, sizeof(buf)); if (buflen == 0) return -1; else if (buflen < 0) buflen = 0; } hints.ai_family = wanted_pf; xgetaddrinfo(remoteaddr, port, &hints, &addr); if (tproxy_trans) { if (getpeername(rs, (void *) &sa, &salen) != 0) { perror("getpeername"); tproxy_trans = false; } } for (a=addr; a != NULL; a = a->ai_next) { sock = socket(a->ai_family, a->ai_socktype, a->ai_protocol); if (sock < 0) { perror("socket"); continue; } if (tproxy_trans) { static const int one = 1; if (setsockopt(sock, SOL_IP, IP_TRANSPARENT, &one, sizeof(one))) perror("setsockopt(IP_TRANSPARENT2)"); if (setsockopt(sock, SOL_SOCKET, SO_MARK, &mark, sizeof(mark))) perror("setsockopt(SO_MARK)"); if (bind(sock, (void *) &sa, salen)) perror("fake bind"); } if (fastopen && buflen > 0) { if (connect_fastopen(sock, buf, buflen, a->ai_addr, a->ai_addrlen) == 0) break; /* success */ } else { if (connect(sock, a->ai_addr, a->ai_addrlen) == 0) break; /* success */ } perror("connect()"); close(sock); sock = -1; } freeaddrinfo(addr); return sock; } static size_t do_write(const int fd, char *buf, const size_t len) { size_t offset = 0; while (offset < len) { size_t written; ssize_t bw = write(fd, buf+offset, len - offset); if (bw < 0 ) { perror("write"); return 0; } written = (size_t) bw; offset += written; } return offset; } static void copyfd_io(int fd_zero, int fd_one) { struct pollfd fds[] = { { .events = POLLIN }, { .events = POLLIN }}; fds[0].fd = fd_zero; fds[1].fd = fd_one; for (;;) { int readfd, writefd; readfd = -1; writefd = -1; switch(poll(fds, 2, -1)) { case -1: if (errno == EINTR) continue; perror("poll"); return; case 0: /* should not happen, we requested infinite wait */ fputs("Timed out?!", stderr); return; } if (fds[0].revents & POLLHUP) return; if (fds[1].revents & POLLHUP) return; if (fds[0].revents & POLLIN) { readfd = fds[0].fd; writefd = fds[1].fd; } else if (fds[1].revents & POLLIN) { readfd = fds[1].fd; writefd = fds[0].fd; } if (readfd>=0 && writefd >= 0) { char buf[4096]; ssize_t len; len = read(readfd, buf, sizeof buf); if (!len) return; if (len < 0) { if (errno == EINTR) continue; perror("read"); return; } if (!do_write(writefd, buf, len)) return; } else { /* Should not happen, at least one fd must have POLLHUP and/or POLLIN set */ fputs("Warning: no useful poll() event", stderr); } } } static int parse_args(int argc, char *const argv[]) { int i; for (i = 0; i < argc; i++) { if (argv[i][0] != '-') return i; switch(argv[i][1]) { case '4': wanted_pf = PF_INET; break; case '6': wanted_pf = PF_INET6; break; case 't': tproxy = true; break; case 'T': tproxy_trans = true; break; case 'f': fastopen = true; break; case 'l': loop = true; break; case 'L': if (i + 1 < argc) listenaddr = argv[++i]; else die_usage(); break; default: die_usage(); } } return i; } /* try to chroot; don't complain if chroot doesn't work */ static void do_chroot(void) { if (chroot("/var/empty") == 0) { /* chroot ok, chdir, setuid must not fail */ if (chdir("/")) { perror("chdir /var/empty"); exit(1); } setgid(65535); if (setuid(65535)) { perror("setuid"); exit(1); } } } int main_loop(int listensock, const char *host, const char *port) { struct sockaddr sa; socklen_t salen = sizeof(sa); int remotesock, connsock; again: while ((remotesock = accept(listensock, &sa, &salen)) < 0) perror("accept"); connsock = sock_connect_tcp(host, port, remotesock); if (connsock < 0) return 1; if (!loop) do_chroot(); logendpoints(connsock, remotesock); copyfd_io(connsock, remotesock); close(connsock); close(remotesock); if (loop) goto again; return 0; } int main(int argc, char *argv[]) { int args; int listensock; const char *host, *port; if (argc < 3) die_usage(); --argc; ++argv; args = parse_args(argc, argv); argc -= args; argv += args; if (argc < 2) /* we need at least 2 more arguments (srcport, hostname) */ die_usage(); listensock = sock_listen_tcp(listenaddr, argv[0]); if (listensock < 0) return 1; if (tproxy) { static int one = 1; if (setsockopt(listensock, SOL_IP, IP_TRANSPARENT, &one, sizeof(one))) perror("setsockopt(IP_TRANSPARENT)"); } if (fastopen) { int tmp = 32; if (setsockopt(listensock, SOL_TCP, TCP_FASTOPEN, &tmp, sizeof(tmp))) perror("setsockopt(TCP_FASTOPEN)"); if (setsockopt(listensock, SOL_TCP, TCP_DEFER_ACCEPT, &tmp, sizeof(tmp))) perror("setsockopt(TCP_DEFER_ACCEPT)"); } host = argv[1]; /* destport given? if no, use srcport */ port = argv[2] ? argv[2] : argv[0]; daemonize(); return main_loop(listensock, host, port); }
the_stack_data/34556.c
/* * Copyright © 2008 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Soft- * ware"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, provided that the above copyright * notice(s) and this permission notice appear in all copies of the Soft- * ware and that both the above copyright notice(s) and this permission * notice appear in supporting documentation. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- * ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY * RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN * THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSE- * QUENTIAL 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 PERFOR- * MANCE OF THIS SOFTWARE. * * Except as contained in this notice, the name of a copyright holder shall * not be used in advertising or otherwise to promote the sale, use or * other dealings in this Software without prior written authorization of * the copyright holder. * * Authors: * Kristian Høgsberg ([email protected]) */ #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL) #include <X11/Xlib.h> #include <X11/extensions/Xfixes.h> #include <X11/extensions/Xdamage.h> #include "glapi.h" #include "glxclient.h" #include <X11/extensions/dri2proto.h> #include "xf86dri.h" #include <dlfcn.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include "xf86drm.h" #include "dri2.h" #include "dri_common.h" /* From xmlpool/options.h, user exposed so should be stable */ #define DRI_CONF_VBLANK_NEVER 0 #define DRI_CONF_VBLANK_DEF_INTERVAL_0 1 #define DRI_CONF_VBLANK_DEF_INTERVAL_1 2 #define DRI_CONF_VBLANK_ALWAYS_SYNC 3 #undef DRI2_MINOR #define DRI2_MINOR 1 struct dri2_display { __GLXDRIdisplay base; /* ** XFree86-DRI version information */ int driMajor; int driMinor; int driPatch; int swapAvailable; int invalidateAvailable; __glxHashTable *dri2Hash; const __DRIextension *loader_extensions[4]; }; struct dri2_screen { struct glx_screen base; __DRIscreen *driScreen; __GLXDRIscreen vtable; const __DRIdri2Extension *dri2; const __DRIcoreExtension *core; const __DRI2flushExtension *f; const __DRI2configQueryExtension *config; const __DRItexBufferExtension *texBuffer; const __DRIconfig **driver_configs; void *driver; int fd; }; struct dri2_context { struct glx_context base; __DRIcontext *driContext; }; struct dri2_drawable { __GLXDRIdrawable base; __DRIdrawable *driDrawable; __DRIbuffer buffers[5]; int bufferCount; int width, height; int have_back; int have_fake_front; int swap_interval; }; static const struct glx_context_vtable dri2_context_vtable; static void dri2_destroy_context(struct glx_context *context) { struct dri2_context *pcp = (struct dri2_context *) context; struct dri2_screen *psc = (struct dri2_screen *) context->psc; driReleaseDrawables(&pcp->base); if (context->xid) glx_send_destroy_context(psc->base.dpy, context->xid); if (context->extensions) XFree((char *) context->extensions); (*psc->core->destroyContext) (pcp->driContext); Xfree(pcp); } static Bool dri2_bind_context(struct glx_context *context, struct glx_context *old, GLXDrawable draw, GLXDrawable read) { struct dri2_context *pcp = (struct dri2_context *) context; struct dri2_screen *psc = (struct dri2_screen *) pcp->base.psc; struct dri2_drawable *pdraw, *pread; struct dri2_display *pdp; pdraw = (struct dri2_drawable *) driFetchDrawable(context, draw); pread = (struct dri2_drawable *) driFetchDrawable(context, read); driReleaseDrawables(&pcp->base); if (pdraw == NULL || pread == NULL) return GLXBadDrawable; if (!(*psc->core->bindContext) (pcp->driContext, pdraw->driDrawable, pread->driDrawable)) return GLXBadContext; /* If the server doesn't send invalidate events, we may miss a * resize before the rendering starts. Invalidate the buffers now * so the driver will recheck before rendering starts. */ pdp = (struct dri2_display *) psc->base.display; if (!pdp->invalidateAvailable) { dri2InvalidateBuffers(psc->base.dpy, pdraw->base.xDrawable); if (pread != pdraw) dri2InvalidateBuffers(psc->base.dpy, pread->base.xDrawable); } return Success; } static void dri2_unbind_context(struct glx_context *context, struct glx_context *new) { struct dri2_context *pcp = (struct dri2_context *) context; struct dri2_screen *psc = (struct dri2_screen *) pcp->base.psc; (*psc->core->unbindContext) (pcp->driContext); } static struct glx_context * dri2_create_context(struct glx_screen *base, struct glx_config *config_base, struct glx_context *shareList, int renderType) { struct dri2_context *pcp, *pcp_shared; struct dri2_screen *psc = (struct dri2_screen *) base; __GLXDRIconfigPrivate *config = (__GLXDRIconfigPrivate *) config_base; __DRIcontext *shared = NULL; if (shareList) { pcp_shared = (struct dri2_context *) shareList; shared = pcp_shared->driContext; } pcp = Xmalloc(sizeof *pcp); if (pcp == NULL) return NULL; memset(pcp, 0, sizeof *pcp); if (!glx_context_init(&pcp->base, &psc->base, &config->base)) { Xfree(pcp); return NULL; } pcp->driContext = (*psc->dri2->createNewContext) (psc->driScreen, config->driConfig, shared, pcp); if (pcp->driContext == NULL) { Xfree(pcp); return NULL; } pcp->base.vtable = &dri2_context_vtable; return &pcp->base; } static void dri2DestroyDrawable(__GLXDRIdrawable *base) { struct dri2_screen *psc = (struct dri2_screen *) base->psc; struct dri2_drawable *pdraw = (struct dri2_drawable *) base; struct glx_display *dpyPriv = psc->base.display; struct dri2_display *pdp = (struct dri2_display *)dpyPriv->dri2Display; __glxHashDelete(pdp->dri2Hash, pdraw->base.xDrawable); (*psc->core->destroyDrawable) (pdraw->driDrawable); /* If it's a GLX 1.3 drawables, we can destroy the DRI2 drawable * now, as the application explicitly asked to destroy the GLX * drawable. Otherwise, for legacy drawables, we let the DRI2 * drawable linger on the server, since there's no good way of * knowing when the application is done with it. The server will * destroy the DRI2 drawable when it destroys the X drawable or the * client exits anyway. */ if (pdraw->base.xDrawable != pdraw->base.drawable) DRI2DestroyDrawable(psc->base.dpy, pdraw->base.xDrawable); Xfree(pdraw); } static __GLXDRIdrawable * dri2CreateDrawable(struct glx_screen *base, XID xDrawable, GLXDrawable drawable, struct glx_config *config_base) { struct dri2_drawable *pdraw; struct dri2_screen *psc = (struct dri2_screen *) base; __GLXDRIconfigPrivate *config = (__GLXDRIconfigPrivate *) config_base; struct glx_display *dpyPriv; struct dri2_display *pdp; GLint vblank_mode = DRI_CONF_VBLANK_DEF_INTERVAL_1; pdraw = Xmalloc(sizeof(*pdraw)); if (!pdraw) return NULL; memset(pdraw, 0, sizeof *pdraw); pdraw->base.destroyDrawable = dri2DestroyDrawable; pdraw->base.xDrawable = xDrawable; pdraw->base.drawable = drawable; pdraw->base.psc = &psc->base; pdraw->bufferCount = 0; pdraw->swap_interval = 1; /* default may be overridden below */ pdraw->have_back = 0; if (psc->config) psc->config->configQueryi(psc->driScreen, "vblank_mode", &vblank_mode); switch (vblank_mode) { case DRI_CONF_VBLANK_NEVER: case DRI_CONF_VBLANK_DEF_INTERVAL_0: pdraw->swap_interval = 0; break; case DRI_CONF_VBLANK_DEF_INTERVAL_1: case DRI_CONF_VBLANK_ALWAYS_SYNC: default: pdraw->swap_interval = 1; break; } DRI2CreateDrawable(psc->base.dpy, xDrawable); dpyPriv = __glXInitialize(psc->base.dpy); pdp = (struct dri2_display *)dpyPriv->dri2Display;; /* Create a new drawable */ pdraw->driDrawable = (*psc->dri2->createNewDrawable) (psc->driScreen, config->driConfig, pdraw); if (!pdraw->driDrawable) { DRI2DestroyDrawable(psc->base.dpy, xDrawable); Xfree(pdraw); return NULL; } if (__glxHashInsert(pdp->dri2Hash, xDrawable, pdraw)) { (*psc->core->destroyDrawable) (pdraw->driDrawable); DRI2DestroyDrawable(psc->base.dpy, xDrawable); Xfree(pdraw); return None; } #ifdef X_DRI2SwapInterval /* * Make sure server has the same swap interval we do for the new * drawable. */ if (pdp->swapAvailable) DRI2SwapInterval(psc->base.dpy, xDrawable, pdraw->swap_interval); #endif return &pdraw->base; } #ifdef X_DRI2GetMSC static int dri2DrawableGetMSC(struct glx_screen *psc, __GLXDRIdrawable *pdraw, int64_t *ust, int64_t *msc, int64_t *sbc) { CARD64 dri2_ust, dri2_msc, dri2_sbc; int ret; ret = DRI2GetMSC(psc->dpy, pdraw->xDrawable, &dri2_ust, &dri2_msc, &dri2_sbc); *ust = dri2_ust; *msc = dri2_msc; *sbc = dri2_sbc; return ret; } #endif #ifdef X_DRI2WaitMSC static int dri2WaitForMSC(__GLXDRIdrawable *pdraw, int64_t target_msc, int64_t divisor, int64_t remainder, int64_t *ust, int64_t *msc, int64_t *sbc) { CARD64 dri2_ust, dri2_msc, dri2_sbc; int ret; ret = DRI2WaitMSC(pdraw->psc->dpy, pdraw->xDrawable, target_msc, divisor, remainder, &dri2_ust, &dri2_msc, &dri2_sbc); *ust = dri2_ust; *msc = dri2_msc; *sbc = dri2_sbc; return ret; } static int dri2WaitForSBC(__GLXDRIdrawable *pdraw, int64_t target_sbc, int64_t *ust, int64_t *msc, int64_t *sbc) { CARD64 dri2_ust, dri2_msc, dri2_sbc; int ret; ret = DRI2WaitSBC(pdraw->psc->dpy, pdraw->xDrawable, target_sbc, &dri2_ust, &dri2_msc, &dri2_sbc); *ust = dri2_ust; *msc = dri2_msc; *sbc = dri2_sbc; return ret; } #endif /* X_DRI2WaitMSC */ static void dri2CopySubBuffer(__GLXDRIdrawable *pdraw, int x, int y, int width, int height) { struct dri2_drawable *priv = (struct dri2_drawable *) pdraw; struct dri2_screen *psc = (struct dri2_screen *) pdraw->psc; XRectangle xrect; XserverRegion region; /* Check we have the right attachments */ if (!priv->have_back) return; xrect.x = x; xrect.y = priv->height - y - height; xrect.width = width; xrect.height = height; #ifdef __DRI2_FLUSH if (psc->f) (*psc->f->flush) (priv->driDrawable); #endif region = XFixesCreateRegion(psc->base.dpy, &xrect, 1); DRI2CopyRegion(psc->base.dpy, pdraw->xDrawable, region, DRI2BufferFrontLeft, DRI2BufferBackLeft); /* Refresh the fake front (if present) after we just damaged the real * front. */ if (priv->have_fake_front) DRI2CopyRegion(psc->base.dpy, pdraw->xDrawable, region, DRI2BufferFakeFrontLeft, DRI2BufferFrontLeft); XFixesDestroyRegion(psc->base.dpy, region); } static void dri2_copy_drawable(struct dri2_drawable *priv, int dest, int src) { XRectangle xrect; XserverRegion region; struct dri2_screen *psc = (struct dri2_screen *) priv->base.psc; xrect.x = 0; xrect.y = 0; xrect.width = priv->width; xrect.height = priv->height; #ifdef __DRI2_FLUSH if (psc->f) (*psc->f->flush) (priv->driDrawable); #endif region = XFixesCreateRegion(psc->base.dpy, &xrect, 1); DRI2CopyRegion(psc->base.dpy, priv->base.xDrawable, region, dest, src); XFixesDestroyRegion(psc->base.dpy, region); } static void dri2_wait_x(struct glx_context *gc) { struct dri2_drawable *priv = (struct dri2_drawable *) GetGLXDRIDrawable(gc->currentDpy, gc->currentDrawable); if (priv == NULL || !priv->have_fake_front) return; dri2_copy_drawable(priv, DRI2BufferFakeFrontLeft, DRI2BufferFrontLeft); } static void dri2_wait_gl(struct glx_context *gc) { struct dri2_drawable *priv = (struct dri2_drawable *) GetGLXDRIDrawable(gc->currentDpy, gc->currentDrawable); if (priv == NULL || !priv->have_fake_front) return; dri2_copy_drawable(priv, DRI2BufferFrontLeft, DRI2BufferFakeFrontLeft); } static void dri2FlushFrontBuffer(__DRIdrawable *driDrawable, void *loaderPrivate) { struct dri2_drawable *pdraw = loaderPrivate; if (!pdraw) return; if (!pdraw->base.psc) return; struct glx_display *priv = __glXInitialize(pdraw->base.psc->dpy); struct dri2_display *pdp = (struct dri2_display *)priv->dri2Display; struct glx_context *gc = __glXGetCurrentContext(); /* Old servers don't send invalidate events */ if (!pdp->invalidateAvailable) dri2InvalidateBuffers(priv->dpy, pdraw->base.xDrawable); dri2_wait_gl(gc); } static void dri2DestroyScreen(struct glx_screen *base) { struct dri2_screen *psc = (struct dri2_screen *) base; /* Free the direct rendering per screen data */ (*psc->core->destroyScreen) (psc->driScreen); driDestroyConfigs(psc->driver_configs); close(psc->fd); Xfree(psc); } /** * Process list of buffer received from the server * * Processes the list of buffers received in a reply from the server to either * \c DRI2GetBuffers or \c DRI2GetBuffersWithFormat. */ static void process_buffers(struct dri2_drawable * pdraw, DRI2Buffer * buffers, unsigned count) { int i; pdraw->bufferCount = count; pdraw->have_fake_front = 0; pdraw->have_back = 0; /* This assumes the DRI2 buffer attachment tokens matches the * __DRIbuffer tokens. */ for (i = 0; i < count; i++) { pdraw->buffers[i].attachment = buffers[i].attachment; pdraw->buffers[i].name = buffers[i].name; pdraw->buffers[i].pitch = buffers[i].pitch; pdraw->buffers[i].cpp = buffers[i].cpp; pdraw->buffers[i].flags = buffers[i].flags; if (pdraw->buffers[i].attachment == __DRI_BUFFER_FAKE_FRONT_LEFT) pdraw->have_fake_front = 1; if (pdraw->buffers[i].attachment == __DRI_BUFFER_BACK_LEFT) pdraw->have_back = 1; } } unsigned dri2GetSwapEventType(Display* dpy, XID drawable) { struct glx_display *glx_dpy = __glXInitialize(dpy); __GLXDRIdrawable *pdraw; pdraw = dri2GetGlxDrawableFromXDrawableId(dpy, drawable); if (!pdraw || !(pdraw->eventMask & GLX_BUFFER_SWAP_COMPLETE_INTEL_MASK)) return 0; return glx_dpy->codes->first_event + GLX_BufferSwapComplete; } static int64_t dri2SwapBuffers(__GLXDRIdrawable *pdraw, int64_t target_msc, int64_t divisor, int64_t remainder) { struct dri2_drawable *priv = (struct dri2_drawable *) pdraw; struct glx_display *dpyPriv = __glXInitialize(priv->base.psc->dpy); struct dri2_screen *psc = (struct dri2_screen *) priv->base.psc; struct dri2_display *pdp = (struct dri2_display *)dpyPriv->dri2Display; CARD64 ret = 0; /* Check we have the right attachments */ if (!priv->have_back) return ret; /* Old servers can't handle swapbuffers */ if (!pdp->swapAvailable) { dri2CopySubBuffer(pdraw, 0, 0, priv->width, priv->height); } else { #ifdef X_DRI2SwapBuffers #ifdef __DRI2_FLUSH if (psc->f) { struct glx_context *gc = __glXGetCurrentContext(); if (gc) { (*psc->f->flush)(priv->driDrawable); } } #endif DRI2SwapBuffers(psc->base.dpy, pdraw->xDrawable, target_msc, divisor, remainder, &ret); #endif } /* Old servers don't send invalidate events */ if (!pdp->invalidateAvailable) dri2InvalidateBuffers(dpyPriv->dpy, pdraw->xDrawable); return ret; } static __DRIbuffer * dri2GetBuffers(__DRIdrawable * driDrawable, int *width, int *height, unsigned int *attachments, int count, int *out_count, void *loaderPrivate) { struct dri2_drawable *pdraw = loaderPrivate; DRI2Buffer *buffers; buffers = DRI2GetBuffers(pdraw->base.psc->dpy, pdraw->base.xDrawable, width, height, attachments, count, out_count); if (buffers == NULL) return NULL; pdraw->width = *width; pdraw->height = *height; process_buffers(pdraw, buffers, *out_count); Xfree(buffers); return pdraw->buffers; } static __DRIbuffer * dri2GetBuffersWithFormat(__DRIdrawable * driDrawable, int *width, int *height, unsigned int *attachments, int count, int *out_count, void *loaderPrivate) { struct dri2_drawable *pdraw = loaderPrivate; DRI2Buffer *buffers; buffers = DRI2GetBuffersWithFormat(pdraw->base.psc->dpy, pdraw->base.xDrawable, width, height, attachments, count, out_count); if (buffers == NULL) return NULL; pdraw->width = *width; pdraw->height = *height; process_buffers(pdraw, buffers, *out_count); Xfree(buffers); return pdraw->buffers; } #ifdef X_DRI2SwapInterval static int dri2SetSwapInterval(__GLXDRIdrawable *pdraw, int interval) { struct dri2_drawable *priv = (struct dri2_drawable *) pdraw; GLint vblank_mode = DRI_CONF_VBLANK_DEF_INTERVAL_1; struct dri2_screen *psc = (struct dri2_screen *) priv->base.psc; if (psc->config) psc->config->configQueryi(psc->driScreen, "vblank_mode", &vblank_mode); switch (vblank_mode) { case DRI_CONF_VBLANK_NEVER: return GLX_BAD_VALUE; case DRI_CONF_VBLANK_ALWAYS_SYNC: if (interval <= 0) return GLX_BAD_VALUE; break; default: break; } DRI2SwapInterval(priv->base.psc->dpy, priv->base.xDrawable, interval); priv->swap_interval = interval; return 0; } static int dri2GetSwapInterval(__GLXDRIdrawable *pdraw) { struct dri2_drawable *priv = (struct dri2_drawable *) pdraw; return priv->swap_interval; } #endif /* X_DRI2SwapInterval */ static const __DRIdri2LoaderExtension dri2LoaderExtension = { {__DRI_DRI2_LOADER, __DRI_DRI2_LOADER_VERSION}, dri2GetBuffers, dri2FlushFrontBuffer, dri2GetBuffersWithFormat, }; static const __DRIdri2LoaderExtension dri2LoaderExtension_old = { {__DRI_DRI2_LOADER, __DRI_DRI2_LOADER_VERSION}, dri2GetBuffers, dri2FlushFrontBuffer, NULL, }; #ifdef __DRI_USE_INVALIDATE static const __DRIuseInvalidateExtension dri2UseInvalidate = { { __DRI_USE_INVALIDATE, __DRI_USE_INVALIDATE_VERSION } }; #endif _X_HIDDEN void dri2InvalidateBuffers(Display *dpy, XID drawable) { __GLXDRIdrawable *pdraw = dri2GetGlxDrawableFromXDrawableId(dpy, drawable); struct dri2_screen *psc; struct dri2_drawable *pdp = (struct dri2_drawable *) pdraw; if (!pdraw) return; psc = (struct dri2_screen *) pdraw->psc; #if __DRI2_FLUSH_VERSION >= 3 if (pdraw && psc->f && psc->f->base.version >= 3 && psc->f->invalidate) psc->f->invalidate(pdp->driDrawable); #endif } static void dri2_bind_tex_image(Display * dpy, GLXDrawable drawable, int buffer, const int *attrib_list) { struct glx_context *gc = __glXGetCurrentContext(); struct dri2_context *pcp = (struct dri2_context *) gc; __GLXDRIdrawable *base = GetGLXDRIDrawable(dpy, drawable); struct glx_display *dpyPriv = __glXInitialize(dpy); struct dri2_drawable *pdraw = (struct dri2_drawable *) base; struct dri2_display *pdp = (struct dri2_display *) dpyPriv->dri2Display; struct dri2_screen *psc; if (pdraw != NULL) { psc = (struct dri2_screen *) base->psc; #if __DRI2_FLUSH_VERSION >= 3 if (!pdp->invalidateAvailable && psc->f && psc->f->base.version >= 3 && psc->f->invalidate) psc->f->invalidate(pdraw->driDrawable); #endif if (psc->texBuffer->base.version >= 2 && psc->texBuffer->setTexBuffer2 != NULL) { (*psc->texBuffer->setTexBuffer2) (pcp->driContext, pdraw->base.textureTarget, pdraw->base.textureFormat, pdraw->driDrawable); } else { (*psc->texBuffer->setTexBuffer) (pcp->driContext, pdraw->base.textureTarget, pdraw->driDrawable); } } } static void dri2_release_tex_image(Display * dpy, GLXDrawable drawable, int buffer) { #if __DRI_TEX_BUFFER_VERSION >= 3 struct glx_context *gc = __glXGetCurrentContext(); struct dri2_context *pcp = (struct dri2_context *) gc; __GLXDRIdrawable *base = GetGLXDRIDrawable(dpy, drawable); struct glx_display *dpyPriv = __glXInitialize(dpy); struct dri2_drawable *pdraw = (struct dri2_drawable *) base; struct dri2_display *pdp = (struct dri2_display *) dpyPriv->dri2Display; struct dri2_screen *psc; if (pdraw != NULL) { psc = (struct dri2_screen *) base->psc; if (psc->texBuffer->base.version >= 3 && psc->texBuffer->releaseTexBuffer != NULL) { (*psc->texBuffer->releaseTexBuffer) (pcp->driContext, pdraw->base.textureTarget, pdraw->driDrawable); } } #endif } static const struct glx_context_vtable dri2_context_vtable = { dri2_destroy_context, dri2_bind_context, dri2_unbind_context, dri2_wait_gl, dri2_wait_x, DRI_glXUseXFont, dri2_bind_tex_image, dri2_release_tex_image, NULL, /* get_proc_address */ }; static void dri2BindExtensions(struct dri2_screen *psc, const __DRIextension **extensions) { int i; __glXEnableDirectExtension(&psc->base, "GLX_SGI_video_sync"); __glXEnableDirectExtension(&psc->base, "GLX_SGI_swap_control"); __glXEnableDirectExtension(&psc->base, "GLX_MESA_swap_control"); __glXEnableDirectExtension(&psc->base, "GLX_SGI_make_current_read"); /* FIXME: if DRI2 version supports it... */ __glXEnableDirectExtension(&psc->base, "INTEL_swap_event"); for (i = 0; extensions[i]; i++) { if ((strcmp(extensions[i]->name, __DRI_TEX_BUFFER) == 0)) { psc->texBuffer = (__DRItexBufferExtension *) extensions[i]; __glXEnableDirectExtension(&psc->base, "GLX_EXT_texture_from_pixmap"); } if ((strcmp(extensions[i]->name, __DRI2_FLUSH) == 0)) { psc->f = (__DRI2flushExtension *) extensions[i]; /* internal driver extension, no GL extension exposed */ } if ((strcmp(extensions[i]->name, __DRI2_CONFIG_QUERY) == 0)) psc->config = (__DRI2configQueryExtension *) extensions[i]; } } static const struct glx_screen_vtable dri2_screen_vtable = { dri2_create_context }; static struct glx_screen * dri2CreateScreen(int screen, struct glx_display * priv) { const __DRIconfig **driver_configs; const __DRIextension **extensions; const struct dri2_display *const pdp = (struct dri2_display *) priv->dri2Display; struct dri2_screen *psc; __GLXDRIscreen *psp; char *driverName, *deviceName; drm_magic_t magic; int i; psc = Xmalloc(sizeof *psc); if (psc == NULL) return NULL; memset(psc, 0, sizeof *psc); psc->fd = -1; if (!glx_screen_init(&psc->base, screen, priv)) { Xfree(psc); return NULL; } if (!DRI2Connect(priv->dpy, RootWindow(priv->dpy, screen), &driverName, &deviceName)) { glx_screen_cleanup(&psc->base); XFree(psc); return NULL; } psc->driver = driOpenDriver(driverName); if (psc->driver == NULL) { ErrorMessageF("driver pointer missing\n"); goto handle_error; } extensions = dlsym(psc->driver, __DRI_DRIVER_EXTENSIONS); if (extensions == NULL) { ErrorMessageF("driver exports no extensions (%s)\n", dlerror()); goto handle_error; } for (i = 0; extensions[i]; i++) { if (strcmp(extensions[i]->name, __DRI_CORE) == 0) psc->core = (__DRIcoreExtension *) extensions[i]; if (strcmp(extensions[i]->name, __DRI_DRI2) == 0) psc->dri2 = (__DRIdri2Extension *) extensions[i]; } if (psc->core == NULL || psc->dri2 == NULL) { ErrorMessageF("core dri or dri2 extension not found\n"); goto handle_error; } psc->fd = open(deviceName, O_RDWR); if (psc->fd < 0) { ErrorMessageF("failed to open drm device: %s\n", strerror(errno)); goto handle_error; } if (drmGetMagic(psc->fd, &magic)) { ErrorMessageF("failed to get magic\n"); goto handle_error; } if (!DRI2Authenticate(priv->dpy, RootWindow(priv->dpy, screen), magic)) { ErrorMessageF("failed to authenticate magic %d\n", magic); goto handle_error; } /* If the server does not support the protocol for * DRI2GetBuffersWithFormat, don't supply that interface to the driver. */ psc->driScreen = psc->dri2->createNewScreen(screen, psc->fd, (const __DRIextension **) &pdp->loader_extensions[0], &driver_configs, psc); if (psc->driScreen == NULL) { ErrorMessageF("failed to create dri screen\n"); goto handle_error; } extensions = psc->core->getExtensions(psc->driScreen); dri2BindExtensions(psc, extensions); psc->base.configs = driConvertConfigs(psc->core, psc->base.configs, driver_configs); psc->base.visuals = driConvertConfigs(psc->core, psc->base.visuals, driver_configs); psc->driver_configs = driver_configs; psc->base.vtable = &dri2_screen_vtable; psp = &psc->vtable; psc->base.driScreen = psp; psp->destroyScreen = dri2DestroyScreen; psp->createDrawable = dri2CreateDrawable; psp->swapBuffers = dri2SwapBuffers; psp->getDrawableMSC = NULL; psp->waitForMSC = NULL; psp->waitForSBC = NULL; psp->setSwapInterval = NULL; psp->getSwapInterval = NULL; if (pdp->driMinor >= 2) { #ifdef X_DRI2GetMSC psp->getDrawableMSC = dri2DrawableGetMSC; #endif #ifdef X_DRI2WaitMSC psp->waitForMSC = dri2WaitForMSC; psp->waitForSBC = dri2WaitForSBC; #endif #ifdef X_DRI2SwapInterval psp->setSwapInterval = dri2SetSwapInterval; psp->getSwapInterval = dri2GetSwapInterval; #endif #if defined(X_DRI2GetMSC) && defined(X_DRI2WaitMSC) && defined(X_DRI2SwapInterval) __glXEnableDirectExtension(&psc->base, "GLX_OML_sync_control"); #endif } /* DRI2 suports SubBuffer through DRI2CopyRegion, so it's always * available.*/ psp->copySubBuffer = dri2CopySubBuffer; __glXEnableDirectExtension(&psc->base, "GLX_MESA_copy_sub_buffer"); Xfree(driverName); Xfree(deviceName); return &psc->base; handle_error: if (psc->fd >= 0) close(psc->fd); if (psc->driver) dlclose(psc->driver); Xfree(driverName); Xfree(deviceName); glx_screen_cleanup(&psc->base); XFree(psc); return NULL; } /* Called from __glXFreeDisplayPrivate. */ static void dri2DestroyDisplay(__GLXDRIdisplay * dpy) { struct dri2_display *pdp = (struct dri2_display *) dpy; __glxHashDestroy(pdp->dri2Hash); Xfree(dpy); } _X_HIDDEN __GLXDRIdrawable * dri2GetGlxDrawableFromXDrawableId(Display *dpy, XID id) { struct glx_display *d = __glXInitialize(dpy); struct dri2_display *pdp = (struct dri2_display *) d->dri2Display; __GLXDRIdrawable *pdraw; if (__glxHashLookup(pdp->dri2Hash, id, (void *) &pdraw) == 0) return pdraw; return NULL; } /* * Allocate, initialize and return a __DRIdisplayPrivate object. * This is called from __glXInitialize() when we are given a new * display pointer. */ _X_HIDDEN __GLXDRIdisplay * dri2CreateDisplay(Display * dpy) { struct dri2_display *pdp; int eventBase, errorBase, i; if (!DRI2QueryExtension(dpy, &eventBase, &errorBase)) return NULL; pdp = Xmalloc(sizeof *pdp); if (pdp == NULL) return NULL; if (!DRI2QueryVersion(dpy, &pdp->driMajor, &pdp->driMinor)) { Xfree(pdp); return NULL; } pdp->driPatch = 0; pdp->swapAvailable = (pdp->driMinor >= 2); pdp->invalidateAvailable = (pdp->driMinor >= 3); pdp->base.destroyDisplay = dri2DestroyDisplay; pdp->base.createScreen = dri2CreateScreen; i = 0; if (pdp->driMinor < 1) pdp->loader_extensions[i++] = &dri2LoaderExtension_old.base; else pdp->loader_extensions[i++] = &dri2LoaderExtension.base; pdp->loader_extensions[i++] = &systemTimeExtension.base; #ifdef __DRI_USE_INVALIDATE pdp->loader_extensions[i++] = &dri2UseInvalidate.base; #endif pdp->loader_extensions[i++] = NULL; pdp->dri2Hash = __glxHashCreate(); if (pdp->dri2Hash == NULL) { Xfree(pdp); return NULL; } return &pdp->base; } #endif /* GLX_DIRECT_RENDERING */
the_stack_data/13210.c
/* * Tetris for BSD/386 * * (C) Copyright 1995, Vadim Antonov * All Rights Reserved. * * Permission is granted hereby for the unlimited * usage, modification and redistribution. * * THIS SOFTWARE IS PROVIDED AS-IS. * The author cannot be held liable for any damage or * loss suffered as a consequence of the use of this * software; including but not limited to repetitive * stress injury and/or moral damage acquired because * of inability to win the game. */ #define USE_POSIXTTY #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <unistd.h> #include <time.h> #include <fcntl.h> #include <sys/types.h> #include <sys/time.h> #ifdef USE_SGTTY #include <sgtty.h> #else #ifdef USE_POSIXTTY #include <termios.h> #else #include "Other terminal interfaces aren't supported" #endif #endif /* PC console colors */ enum pccolors { BLACK, RED, GREEN, BROWN, BLUE, MAGENTA, CYAN, WHITE, GREY, LT_RED, LT_GREEN, YELLOW, LT_BLUE, LT_MAGENTA, LT_CYAN, HI_WHITE }; #ifndef DEBUG # define SCORE_4 "/usr/games/lib/tetris.scores" # define SCORE_5 "/usr/games/lib/pentis.scores" #else # define SCORE_4 "tetris.scores" # define SCORE_5 "pentis.scores" #endif #define BORDER_COL GREEN #define DOT_COL BROWN #define TOPS 10 #define PITY 25 #define PITWIDTH 12 #define PITDEPTH 24 #define TOPSLINE 12 /* tops start at that line */ #define NPIECES 6 struct tops { char name[10]; int score; int class; } tops[TOPS]; struct coord { int x, y; int color; }; #define END 127 #define NTYPES_4 7 #define NTYPES_5 24 struct tet { char color; char dx, dy; struct cc { char x, y; } p[NPIECES]; } tet[NTYPES_5] = { /* OOOO */ { HI_WHITE, 0, 3, { {0,0}, {0,1}, {0,2}, {0,3}, {END,END} } }, /* O O O OO OO */ /* OOO OOO OOO OO OO */ { YELLOW, 1, 2, { {0,0}, {1,0}, {1,1}, {1,2}, {END,END} } }, { LT_MAGENTA, 1, 2, { {0,1}, {1,0}, {1,1}, {1,2}, {END,END} } }, { LT_CYAN, 1, 2, { {0,2}, {1,0}, {1,1}, {1,2}, {END,END} } }, { LT_GREEN, 1, 2, { {0,0}, {0,1}, {1,1}, {1,2}, {END,END} } }, { LT_RED, 1, 2, { {0,1}, {0,2}, {1,0}, {1,1}, {END,END} } }, /* OO */ /* OO */ { LT_BLUE, 1, 1, { {0,0}, {0,1}, {1,0}, {1,1}, {END,END} } }, /* OOOOO */ { WHITE, 0, 4, { {0,0}, {0,1}, {0,2}, {0,3}, {0,4}, {END,END} } }, /* O O O O OOO OO */ /* OOOO OOOO OOOO OOOO OO OOO */ { BROWN, 1, 3, { {0,0}, {1,0}, {1,1}, {1,2}, {1,3}, {END,END} } }, { CYAN, 1, 3, { {0,1}, {1,0}, {1,1}, {1,2}, {1,3}, {END,END} } }, { MAGENTA, 1, 3, { {0,2}, {1,0}, {1,1}, {1,2}, {1,3}, {END,END} } }, { BLUE, 1, 3, { {0,3}, {1,0}, {1,1}, {1,2}, {1,3}, {END,END} } }, { GREEN, 1, 3, { {0,1}, {0,2}, {0,3}, {1,0}, {1,1}, {END,END} } }, { RED, 1, 3, { {0,0}, {0,1}, {1,1}, {1,2}, {1,3}, {END,END} } }, /* OO O O OO */ /* OOO OOO OOO */ { LT_MAGENTA, 1, 2, { {0,0}, {0,1}, {1,0}, {1,1}, {1,2}, {END,END} } }, { LT_GREEN, 1, 2, { {0,0}, {0,2}, {1,0}, {1,1}, {1,2}, {END,END} } }, { LT_CYAN, 1, 2, { {0,1}, {0,2}, {1,0}, {1,1}, {1,2}, {END,END} } }, /* O O O O O O O */ /* OOO OOO OOO OOO OOO OOO O */ /* O O O O O O OOO */ { LT_RED, 2, 2, { {0,0}, {1,0}, {1,1}, {1,2}, {2,0}, {END,END} } }, { MAGENTA, 2, 2, { {0,1}, {1,0}, {1,1}, {1,2}, {2,0}, {END,END} } }, { GREEN, 2, 2, { {0,2}, {1,0}, {1,1}, {1,2}, {2,0}, {END,END} } }, { CYAN, 2, 2, { {0,0}, {1,0}, {1,1}, {1,2}, {2,1}, {END,END} } }, { YELLOW, 2, 2, { {0,1}, {1,0}, {1,1}, {1,2}, {2,1}, {END,END} } }, { RED, 2, 2, { {0,0}, {1,0}, {1,1}, {1,2}, {2,2}, {END,END} } }, { LT_BLUE, 2, 2, { {0,0}, {1,0}, {2,0}, {2,1}, {2,2}, {END,END} } }, }; char pit[PITDEPTH+1][PITWIDTH]; char pitcnt[PITDEPTH]; int score, lines, interval, class; int shownext; int pentix, colored; int mytopsline = -1; int nexttopsscore = 0; char user[10], ucuser[10]; #define NCLASSES 20 int classlines[NCLASSES] = { 10, 20, 30, 40, 50, 80, 100, 120, 140, 160, 200, 250, 300, 350, 400, 500, 600, 700, 800, 10000000 }; struct cc cur = {-1, -1}; int curcol = -1; short ospeed; void t_setmode(), t_resetmode(); /* * Switch the color */ void color(int c) { if( !colored || c == curcol ) return; curcol = c; if (c < 8) printf("\33[0;3%dm", c); else printf("\33[1;3%dm", c & 7); } /* * Restore color */ void restorecolor() { printf("\33[m"); } /* * Position the cursor */ void pos(int x, int y) { if( cur.x != x || cur.y != y ) { printf("\033[%d;%dH", x+1, y+1); cur.x = x; cur.y = y; } } /* * Erase the screen */ void erase() { printf("\033c"); } /* * Position the piece */ void ppos(struct coord p) { pos(p.x, 2*p.y + PITY); } /* * Output piece coordinates given its center and angle */ void pdots(struct tet *t, struct cc c, int a, struct coord *res) { struct cc org; struct coord tmp; int yw, xw; int i; if( a & 1 ) { /* 90 deg */ xw = t->dy; yw = t->dx; } else { xw = t->dx; yw = t->dy; } org = c; org.x -= (xw+1) / 2; org.y -= yw / 2; if( org.y < 0 ) org.y = 0; if( org.y + yw >= PITWIDTH && c.y <= PITWIDTH ) org.y = PITWIDTH-1 - yw; for( i = 0 ; t->p[i].x != END ; i++ ) { switch( a ) { case 0: res[i].x = t->p[i].x; res[i].y = t->p[i].y; break; case 3: res[i].x = xw - t->p[i].y; res[i].y = t->p[i].x; break; case 2: res[i].x = xw - t->p[i].x; res[i].y = yw - t->p[i].y; break; case 1: res[i].x = t->p[i].y; res[i].y = yw - t->p[i].x; } res[i].x += org.x; res[i].y += org.y; res[i].color = t->color; } res[i].x = res[i].y = END; do { xw = 0; for( i = 0 ; res[i+1].x != END ; i++ ) { if( res[i].x < res[i+1].x ) continue; if( res[i].x == res[i+1].x && res[i].y <= res[i+1].y ) continue; xw++; tmp = res[i]; res[i] = res[i+1]; res[i+1] = tmp; } } while( xw ); } /* * Draw the piece */ void draw(struct coord *p) { for( ; p->x != END ; p++ ) { if( p->x < 0 ) continue; ppos(*p); color(p->color); printf("[]"); cur.y += 2; } } /* * Move the piece */ void move(struct coord *old, struct coord *new, int dot) { for(;;) { if( old->x == END ) goto draw; if( new->x == END ) goto clear; if( old->x > new->x ) goto draw; if( old->x < new->x ) goto clear; if( old->y > new->y ) goto draw; if( old->y == new->y ) { old++; if( colored && old[-1].color != new->color ) goto draw; new++; continue; /* old & new at the same place */ } clear: if( old->x >= 0 ) { ppos(*old); color(DOT_COL); printf(dot? ". ": " "); cur.y += 2; } old++; continue; draw: if( new->x == END ) break; if( new->x >= 0 ) { ppos(*new); color(new->color); printf("[]"); cur.y += 2; } new++; } } /* * Medal colors */ int medcol(int place) { switch( place ) { case 0: return YELLOW; case 1: return HI_WHITE; case 2: return LT_RED; } return WHITE; } /* * Show the top ten */ void showtop() { int f = open(pentix? SCORE_5 : SCORE_4, 0); int i, j; if( f == -1 || read(f, tops, sizeof tops) != sizeof tops ) bzero(tops, sizeof tops); close(f); /* * Join in the current player */ for( i = 0 ; i < TOPS ; i++ ) { if( tops[i].name[0] == 0 || tops[i].score < score ) break; } mytopsline = i; if( i == 0 ) nexttopsscore = 10000000; else nexttopsscore = tops[i-1].score; for( i = j = 0 ; i < TOPS ; i++ ) { pos(TOPSLINE+i, 0); color(medcol(i)); printf("%2d ", i+1); if( mytopsline == i ) printf("%8.8s %2d %7d", ucuser, class+1, score); else if( tops[j].name[0] ) { printf("%8.8s %2d %7d", tops[j].name, tops[j].class+1, tops[j].score); j++; } } } /* * Save the score */ void savescore() { char *name = pentix? SCORE_5 : SCORE_4; int i, j, f; f = open(name, 2); if( f == -1 || read(f, tops, sizeof tops) != sizeof tops ) { bzero(tops, sizeof tops); f = creat(name, 0666); } /* * Join in the current player */ for( i = 0 ; i < TOPS ; i++ ) { if( tops[i].name[0] == 0 || tops[i].score < score ) break; } if( i == TOPS ) { close(f); return; } for( j = TOPS-1 ; j > i ; j-- ) tops[j] = tops[j-1]; strcpy(tops[i].name, user); tops[i].class = class; tops[i].score = score; (void) lseek(f, 0l, 0); if (write(f, tops, sizeof tops) < 0) /*ignore*/; close(f); } /* * Draw the class in large friendly figures */ void drawclass() { int i = class+1; static char *msd[3][3] = { { " ", " ", " __ " }, { " ", " |", " __|" }, { " ", " |", "|__ " }, }; static char *lsd[3][10] = { { " __ ", " ", " __ ", " __ ", " ", " __ ", " __ ", " __ ", " __ ", " __ " }, { "| |", " |", " __|", " __|", "|__|", "|__ ", "|__ ", " |", "|__|", "|__|" }, { "|__|", " |", "|__ ", " __|", " |", " __|", "|__|", " |", "|__|", " |" }, }; color(LT_GREEN); pos(5, 5); printf("%s %s", msd[0][i/10], lsd[0][i%10]); cur.y += 9; pos(6, 5); printf("%s %s", msd[1][i/10], lsd[1][i%10]); cur.y += 9; pos(7, 5); printf("%s %s", msd[2][i/10], lsd[2][i%10]); cur.y += 9; } /* * Switch to the next class */ void nextclass() { if( class >= NCLASSES-1 ) return; class++; interval -= interval / 5; drawclass(); if( mytopsline < TOPS ) { color(medcol(mytopsline)); pos(TOPSLINE+mytopsline, 12); printf("%2d", class+1); } } /* * The piece reached the bottom */ void scarp(struct coord *c) { int i, nfull, j, k; struct coord z; nfull = 0; for( ; c->x != END ; c++ ) { if( c->x <= 0 ) { savescore(); color(YELLOW); pos(9, PITY); printf(" "); pos(10, PITY); printf(" ===== GAME OVER ====== "); pos(11, PITY); printf(" "); pos(25, 0); restorecolor(); t_resetmode(); exit(0); } pit[c->x][c->y] = colored? c->color : 1; if( ++pitcnt[c->x] == PITWIDTH ) nfull++; } /* Remove the full lines */ if( nfull ) { /* Clear upper nfull lines */ for( i = 0 ; i < nfull ; i++ ) { for( j = 0 ; j < PITWIDTH ; j++ ) { if( pit[i][j] ) { z.x = i; z.y = j; ppos(z); color(DOT_COL); printf(". "); } } } /* Move lines down */ k = nfull; for( i = nfull ; i < PITDEPTH && k > 0; i++ ) { if( pitcnt[i-k] == PITWIDTH ) { k--, i--; continue; } for( j = 0 ; j < PITWIDTH ; j++ ) { if( pit[i][j] != pit[i-k][j] ) { z.x = i; z.y = j; ppos(z); if( pit[i-k][j] ) { color(pit[i-k][j]); printf("[]"); } else { color(DOT_COL); printf(". "); } } } } /* Now fix the pit contents */ for( i = PITDEPTH-1 ; i > 0 ; i-- ) { if( pitcnt[i] != PITWIDTH ) continue; bcopy(pit[0], pit[0]+PITWIDTH, PITWIDTH * i); bzero(pit[0], PITWIDTH); bcopy(pitcnt, pitcnt+1, i); pitcnt[0] = 0; i++; } /* Update line count */ pos(1, 7); lines += nfull; color(HI_WHITE); printf("%7d", lines); cur.y += 7; if( pitcnt[PITDEPTH-1] == 0 ) score += 100 * class * class; if( lines >= classlines[class] ) nextclass(); } score += shownext? (class/2 + 1) : class; pos(2, 7); color(HI_WHITE); printf("%7d", score); cur.y += 7; if( score > nexttopsscore ) showtop(); else if( mytopsline < TOPS ) { color(medcol(mytopsline)); pos(TOPSLINE+mytopsline, 15); printf("%7d", score); } } /* * The main routine */ int main(ac, av) int ac; char **av; { int ptype, nextptype; /* Piece type */ int angle, nextangle, anew; /* Angle */ struct cc c, cnew, z; struct coord *cp; struct coord old[NPIECES], new[NPIECES], chk[NPIECES]; struct coord nextold[NPIECES], nextnew[NPIECES]; int i, j, sclass; char cc; long restusec; struct timeval tv; fd_set fds; long t; char *p; int rotf; /* direction of rotation */ time(&t); srand((int)t); shownext = 0; sclass = 0; rotf = 0; p = getlogin(); if( p == 0 ) p = "@#$!!#!"; strncpy(user, p, 9); strcpy(ucuser, user); p = ucuser; while( *p ) { if( 'a' <= *p && *p <= 'z' ) *p -= 'a' - 'A'; p++; } while( (i = getopt(ac, av, "cpnr0123456789")) != EOF ) { switch( i ) { case 'p': pentix ^= 1; break; case 'n': shownext ^= 1; break; case 'c': colored ^= 1; break; case 'r': rotf ^= 1; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': sclass = (sclass*10) + (i-'0'); break; default: fprintf(stderr, "Usage: %s [-cpnr] [-CLASS]\n", av[0]); fprintf(stderr, "\t-c - turn on color\n"); fprintf(stderr, "\t-p - throw pentagramms in\n"); fprintf(stderr, "\t-n - start with hints display on\n"); fprintf(stderr, "\t-r - change the direction of rotation\n"); fprintf(stderr, "\t-CLASS - start from the given class\n"); exit(1); } } if( sclass > 0 ) sclass--; interval = 500; for( i = sclass ; i-- ; ) interval -= interval / 5; t_setmode(); /* Draw the pit */ erase(); pos(1, 0); color(WHITE); printf("Lines: "); color(HI_WHITE); printf("0"); cur.y += 14; pos(2, 0); color(WHITE); printf("Score: "); color(HI_WHITE); printf("0"); cur.y += 14; score = 0; lines = 0; class = sclass; pos(4, 5); color(WHITE); printf("C L A S S"); cur.y += 9; drawclass(); pos(3, PITY + 12 + 2*PITWIDTH); color(WHITE); printf("N E X T"); cur.y += 7; pos(10, 0); printf(" === The Top Ten ==="); pos(11, 0); /* ^dd nnnnnnnn dd ddddddd */ printf(" # name cl score"); showtop(); color(WHITE); pos(10, PITY + 5 + 2*PITWIDTH); printf(" COMMANDS"); pos(12, PITY + 5 + 2*PITWIDTH); printf("q - quit"); pos(13, PITY + 5 + 2*PITWIDTH); printf("4 - toggle hint display"); pos(14, PITY + 5 + 2*PITWIDTH); printf("5 or space - drop"); pos(15, PITY + 5 + 2*PITWIDTH); printf("6 - increase class"); pos(16, PITY + 5 + 2*PITWIDTH); printf("7 - move left"); pos(17, PITY + 5 + 2*PITWIDTH); printf("8 - rotate"); pos(18, PITY + 5 + 2*PITWIDTH); printf("9 - move right"); color(BORDER_COL); for( i = 0 ; i < PITDEPTH ; i++ ) { pos(i, PITY-2); printf("##"); color(DOT_COL); for( j = 0 ; j < PITWIDTH ; j++ ) { printf(". "); pit[i][j] = 0; } pitcnt[i] = 0; color(BORDER_COL); printf("##"); cur.y += 2*PITWIDTH + 4; } pos(PITDEPTH+1, PITY-2); for( j = 0 ; j < PITWIDTH+2 ; j++ ) printf("##"); cur.y += 2*PITWIDTH + 4; for( j = 0 ; j < PITWIDTH ; j++ ) pit[PITDEPTH][j] = 1; if( !pentix ) nextptype = ((rand()>>2) & 07777) % NTYPES_4; else { nextptype = ((rand()>>2) & 07777) % (2*NTYPES_4 + NTYPES_5); if( nextptype >= NTYPES_4 ) nextptype -= NTYPES_4; if( nextptype >= NTYPES_4 ) nextptype -= NTYPES_4; } nextangle = (rand()>>3) % 03; for( i = 0 ; i < NPIECES ; i++ ) nextold[i].x = nextold[i].y = END; newpiece: ptype = nextptype; angle = nextangle; if( !pentix ) nextptype = ((rand()>>2) & 07777) % NTYPES_4; else { nextptype = ((rand()>>2) & 07777) % (2*NTYPES_4 + NTYPES_5); if( nextptype >= NTYPES_4 ) nextptype -= NTYPES_4; if( nextptype >= NTYPES_4 ) nextptype -= NTYPES_4; } nextangle = (rand()>>3) % 03; c.y = PITWIDTH/2 - 1; for( c.x = -2 ;; c.x++ ) { pdots(&tet[ptype], c, angle, new); for( cp = new ; cp->x != END ; cp++ ) { if( cp->x >= 0 ) goto ok; } } ok: draw(new); bcopy(new, old, sizeof old); if( shownext ) { z.x = 6; z.y = PITWIDTH + 7; pdots(&tet[nextptype], z, nextangle, nextnew); move(nextold, nextnew, 0); bcopy(nextnew, nextold, sizeof nextold); } restusec = interval * 1000; for(;;) { cnew = c; anew = angle; pos(0, 0); fflush(stdout); FD_ZERO(&fds); FD_SET(0, &fds); tv.tv_sec = 0; tv.tv_usec = restusec; if( select(1, &fds, 0, 0, &tv) == 0 ) { restusec = interval * 1000; cnew.x++; pdots(&tet[ptype], cnew, anew, chk); for( cp = chk ; cp->x != END ; cp++ ) { if( cp->x < 0 ) continue; if( pit[cp->x][cp->y] ) { scarp(new); goto newpiece; } } goto check; } if (read(0, &cc, 1) < 0) exit(0); restusec /= 2; switch( cc ) { case 'q': case 'Q': restorecolor(); pos(25, 0); savescore(); t_resetmode(); exit(0); case '4': if( shownext ) { for( i = 0 ; i < NPIECES ; i++ ) nextold[i].x = nextold[i].y = END; move(nextnew, nextold, 0); shownext = 0; } else { z.x = 6; z.y = PITWIDTH + 7; pdots(&tet[nextptype], z, nextangle, nextnew); draw(nextnew); bcopy(nextnew, nextold, sizeof nextold); shownext = 1; } continue; case '6': nextclass(); continue; case '8': if( rotf ) { if( ++anew > 3 ) anew = 0; } else { if( --anew < 0 ) anew = 3; } break; case '7': if( cnew.y <= 0 ) goto out; cnew.y--; break; case '9': if( cnew.y >= PITWIDTH-1 ) goto out; cnew.y++; break; case ' ': case '5': for(;;) { cnew.x++; pdots(&tet[ptype], cnew, anew, chk); for( cp = chk ; cp->x != END ; cp++ ) { if( cp->x < 0 ) continue; if( pit[cp->x][cp->y] ) { cnew.x--; pdots(&tet[ptype], cnew, anew, chk); move(new, chk, 1); scarp(chk); goto newpiece; } } score += 1 + (class/5); } /* NOTREACHED */ } pdots(&tet[ptype], cnew, anew, chk); check: for( cp = chk ; cp->x != END ; cp++ ) { if( cp->y < 0 || cp->y >= PITWIDTH ) goto out; } for( cp = chk ; cp->x != END ; cp++ ) { if( cp->x < 0 ) continue; if( pit[cp->x][cp->y] ) goto out; } c = cnew; angle = anew; bcopy(new, old, sizeof old); bcopy(chk, new, sizeof new); move(old, new, 1); out: ; } } /* * Set/reset terminal modes */ #ifdef USE_SGTTY static struct sgttyb t_saved_mode, t_mode; void t_setmode() { ioctl(0, TIOCGETP, &t_saved_mode); t_mode = t_saved_mode; t_mode.sg_flags &= ~(ECHO|XTABS|CRMOD); t_mode.sg_flags |= CBREAK; ospeed = mode.sg_ospeed; ioctl(0, TIOCSETP, &t_mode); } void t_resetmode() { ioctl(2, TIOCSETP, &t_saved_mode); } #else #ifdef USE_POSIXTTY static struct termios t_saved_mode, t_mode; void t_setmode() { (void) tcgetattr(0, &t_saved_mode); t_mode = t_saved_mode; t_mode.c_lflag &= ~(ICANON|ECHO|ISIG|IEXTEN); t_mode.c_iflag &= ~(ICRNL|INLCR|IXON|IXOFF); t_mode.c_oflag &= ~OPOST; t_mode.c_cc[VMIN] = 1; t_mode.c_cc[VTIME] = 0; (void) tcsetattr(0, TCSADRAIN, &t_mode); #ifdef CBAUD ospeed = t_mode.c_cflag & CBAUD; #else ospeed = t_mode.c_ospeed; #endif } void t_resetmode() { (void) tcsetattr(0, TCSADRAIN, &t_saved_mode); } #else /* NOT SUPPORTED */ #endif /* USE_POSIXTTY */ #endif /* USE_SGTTY */
the_stack_data/886879.c
#include <math.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> static volatile sig_atomic_t doneflag = 0; /* ARGSUSED */ static void setdoneflag(int signo) { doneflag = 1; } int main (void) { struct sigaction act; int count = 0; double sum = 0; double x; act.sa_handler = setdoneflag; /* set up signal handler */ act.sa_flags = 0; if ((sigemptyset(&act.sa_mask) == -1) || (sigaction(SIGINT, &act, NULL) == -1)) { perror("Failed to set SIGINT handler"); return 1; } while (!doneflag) { x = (rand() + 0.5)/(RAND_MAX + 1.0); sum += sin(x); count++; printf("Count is %d and average is %f\n", count, sum/count); } printf("Program terminating ...\n"); if (count == 0) printf("No values calculated yet\n"); else printf("Count is %d and average is %f\n", count, sum/count); return 0; }
the_stack_data/68886810.c
int f(int x) { if (x > 1) { x = f(x-2); x = x + 2; } if (x < 2) { x = 0; } return x; }
the_stack_data/113198.c
#include <stdio.h> ///if 와 else를 이용, min과 max를 한곳에서 함께 할당 int main(void){ int n1,n2,n3; int min, max; printf("정수 3개를 입력하세요:"); scanf("%d %d %d",&n1,&n2, &n3); if (n1<n2){ if (n2<n3){ min = n1; max = n3; } else if (n1<n3){ min = n1; max = n2; } else{ min = n3; max = n2; } } else { if (n1<n3){ min = n2; max = n3; } else if(n2<n3){ min = n2; max = n1; } else{ min = n3; max = n1; } } printf("가장 작은값 : %d \n가장 큰 값: %d\n",min,max); }
the_stack_data/200143581.c
/* * i2c-pca-isa.c driver for PCA9564 on ISA boards * Copyright (C) 2004 Arcom Control Systems * Copyright (C) 2008 Pengutronix * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdio.h> #include <pthread.h> #include <assert.h> #if FULLCODE #include <linux/kernel.h> #include <linux/ioport.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/delay.h> #include <linux/jiffies.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/wait.h> #include <linux/isa.h> #include <linux/i2c.h> #include <linux/i2c-algo-pca.h> #include <asm/io.h> #include <asm/irq.h> #define DRIVER "i2c-pca-isa" #define IO_SIZE 4 static unsigned long base; static int irq = -1; /* Data sheet recommends 59kHz for 100kHz operation due to variation * in the actual clock rate */ static int clock = 59000; static struct i2c_adapter pca_isa_ops; static wait_queue_head_t pca_wait; static void pca_isa_writebyte(void *pd, int reg, int val) { #ifdef DEBUG_IO static char *names[] = { "T/O", "DAT", "ADR", "CON" }; printk(KERN_DEBUG "*** write %s at %#lx <= %#04x\n", names[reg], base+reg, val); #endif outb(val, base+reg); } static int pca_isa_readbyte(void *pd, int reg) { int res = inb(base+reg); #ifdef DEBUG_IO { static char *names[] = { "STA", "DAT", "ADR", "CON" }; printk(KERN_DEBUG "*** read %s => %#04x\n", names[reg], res); } #endif return res; } static int pca_isa_waitforcompletion(void *pd) { unsigned long timeout; long ret; if (irq > -1) { ret = wait_event_timeout(pca_wait, pca_isa_readbyte(pd, I2C_PCA_CON) & I2C_PCA_CON_SI, pca_isa_ops.timeout); } else { /* Do polling */ timeout = jiffies + pca_isa_ops.timeout; do { ret = time_before(jiffies, timeout); if (pca_isa_readbyte(pd, I2C_PCA_CON) & I2C_PCA_CON_SI) break; udelay(100); } while (ret); } return ret > 0; } static void pca_isa_resetchip(void *pd) { /* apparently only an external reset will do it. not a lot can be done */ printk(KERN_WARNING DRIVER ": Haven't figured out how to do a reset yet\n"); } static irqreturn_t pca_handler(int this_irq, void *dev_id) { wake_up(&pca_wait); return IRQ_HANDLED; } static struct i2c_algo_pca_data pca_isa_data = { /* .data intentionally left NULL, not needed with ISA */ .write_byte = pca_isa_writebyte, .read_byte = pca_isa_readbyte, .wait_for_completion = pca_isa_waitforcompletion, .reset_chip = pca_isa_resetchip, }; static struct i2c_adapter pca_isa_ops = { .owner = THIS_MODULE, .algo_data = &pca_isa_data, .name = "PCA9564/PCA9665 ISA Adapter", .timeout = HZ, }; static int __devinit pca_isa_match(struct device *dev, unsigned int id) { int match = base != 0; if (match) { if (irq <= -1) dev_warn(dev, "Using polling mode (specify irq)\n"); } else dev_err(dev, "Please specify I/O base\n"); return match; } #endif #if FULLCODE static int __devinit pca_isa_probe(struct device *dev, unsigned int id) { init_waitqueue_head(&pca_wait); dev_info(dev, "i/o base %#08lx. irq %d\n", base, irq); #ifdef CONFIG_PPC if (check_legacy_ioport(base)) { dev_err(dev, "I/O address %#08lx is not available\n", base); goto out; } #endif if (!request_region(base, IO_SIZE, "i2c-pca-isa")) { dev_err(dev, "I/O address %#08lx is in use\n", base); goto out; } if (irq > -1) { if (request_irq(irq, pca_handler, 0, "i2c-pca-isa", &pca_isa_ops) < 0) { dev_err(dev, "Request irq%d failed\n", irq); goto out_region; } } pca_isa_data.i2c_clock = clock; if (i2c_pca_add_bus(&pca_isa_ops) < 0) { dev_err(dev, "Failed to add i2c bus\n"); goto out_irq; } return 0; out_irq: if (irq > -1) free_irq(irq, &pca_isa_ops); out_region: release_region(base, IO_SIZE); out: return -ENODEV; } #endif int global_clock; int irq; int global_id; int global_dev; #define pca_isa_probe(dev, id)\ if (global_dev != dev) { \ assert(0); \ } \ if (irq > -1) { \ if (global_id != id) {\ assert(0);\ }\ } \ #if FULLCODE static int __devexit pca_isa_remove(struct device *dev, unsigned int id) { i2c_del_adapter(&pca_isa_ops); if (irq > -1) { disable_irq(irq); free_irq(irq, &pca_isa_ops); } release_region(base, IO_SIZE); return 0; } static struct isa_driver pca_isa_driver = { .match = pca_isa_match, .probe = pca_isa_probe, .remove = __devexit_p(pca_isa_remove), .driver = { .owner = THIS_MODULE, .name = DRIVER, } }; #endif #define pca_isa_init(dev, id) { \ global_id = id; \ global_dev = dev; \ } #define pca_isa_exit() {\ global_id = -1; \ global_dev = -1; \ } #if FULLCODE static int __init pca_isa_init(void) { return isa_register_driver(&pca_isa_driver, 1); } static void __exit pca_isa_exit(void) { isa_unregister_driver(&pca_isa_driver); } MODULE_AUTHOR("Ian Campbell <[email protected]>"); MODULE_DESCRIPTION("ISA base PCA9564/PCA9665 driver"); MODULE_LICENSE("GPL"); module_param(base, ulong, 0); MODULE_PARM_DESC(base, "I/O base address"); module_param(irq, int, 0); MODULE_PARM_DESC(irq, "IRQ"); module_param(clock, int, 0); MODULE_PARM_DESC(clock, "Clock rate in hertz.\n\t\t" "For PCA9564: 330000,288000,217000,146000," "88000,59000,44000,36000\n" "\t\tFor PCA9665:\tStandard: 60300 - 100099\n" "\t\t\t\tFast: 100100 - 400099\n" "\t\t\t\tFast+: 400100 - 10000099\n" "\t\t\t\tTurbo: Up to 1265800"); module_init(pca_isa_init); module_exit(pca_isa_exit); #endif #define LIMIT 20 int cnt1, cnt2, cnt3, cnt4, cnt5, cnt6, cnt7, cnt8; void *req1(void *unused) { //while(cnt1< LIMIT) { irq = 0; pca_isa_init(1, 1); pca_isa_probe(1, 1); pca_isa_exit(); //cnt1++; //} } void *req2(void *unused) { //while(cnt2 < LIMIT) { irq = 0; pca_isa_init(2, 2); pca_isa_probe(2, 2); pca_isa_exit(); //cnt2++; //} } void *req3(void *unused) { //while(cnt3 < LIMIT) { irq = 0; pca_isa_init(3, 3); pca_isa_probe(3, 3); pca_isa_exit(); //cnt3++; //} } void *req4(void *unused) { //while(cnt4 < LIMIT) { irq = 0; pca_isa_init(4, 4); pca_isa_probe(4, 4); pca_isa_exit(); //cnt4++; //} } void *req5(void *unused) { //while(cnt5 < LIMIT) { irq = 0; pca_isa_init(5, 5); pca_isa_probe(5, 5); pca_isa_exit(); //cnt5++; //} } void *req6(void *unused) { //while(cnt6 < LIMIT) { irq = -1; cnt6++; //} } void *req7(void *unused) { //while(cnt7 < LIMIT) { irq = 0; pca_isa_init(7, 7); pca_isa_probe(7, 7); pca_isa_exit(); //cnt7++; //} } void *req8(void *unused) { //while(cnt8 < LIMIT) { irq = 0; pca_isa_init(8, 8); pca_isa_probe(8, 8); pca_isa_exit(); //cnt8++; //} } int main(void) { pthread_t t1, t2, t3, t4, t5, t6; pthread_create(&t1, NULL, &req1, NULL); pthread_create(&t2, NULL, &req2, NULL); pthread_create(&t2, NULL, &req3, NULL); pthread_create(&t2, NULL, &req4, NULL); pthread_create(&t2, NULL, &req5, NULL); pthread_create(&t2, NULL, &req6, NULL); pthread_create(&t2, NULL, &req7, NULL); pthread_create(&t2, NULL, &req8, NULL); return 0; }
the_stack_data/103266274.c
/* Copyright (C) 2003 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Martin Schwidefsky <[email protected]>, 2003. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* Not needed. pthread_spin_init is an alias for pthread_spin_unlock. */
the_stack_data/112210.c
/* This testcase is part of GDB, the GNU debugger. Copyright 1997-2020 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 <stdio.h> #include <unistd.h> #include <limits.h> #include <string.h> int main (int argc, char ** argv) { int pid; /* A statement before vfork to make sure a breakpoint on main isn't set on vfork below. */ pid = 1 + argc; pid = vfork (); /* VFORK */ if (pid == 0) { char prog[PATH_MAX]; int len; strcpy (prog, argv[0]); len = strlen (prog); /* Replace "foll-vfork" with "vforked-prog". */ memcpy (prog + len - 10, "vforked-prog", 12); prog[len + 2] = 0; printf ("I'm the child!\n"); execlp (prog, prog, (char *) 0); perror ("exec failed"); _exit (1); } else { printf ("I'm the proud parent of child #%d!\n", pid); } }
the_stack_data/135556.c
#include <stdio.h> #include <stdlib.h> #include <math.h> int euler86(n) { int count = 0; long w = 1, h, l; long pathSq, path; while (1) { for (h = 1; h <= w; h++) { for (l = 1; l <= h; l++) { long pathSq = (l+h) * (l+h) + w * w; long path = sqrt(pathSq); if (path*path == pathSq) { count++; //printf("%d %d %d %d\n", count, w, h, l); if (count > n) { return w; } } } } w++; } } int main() { printf("Result: %d", euler86(1000000)); return 0; } // < 9sec with full optimization flag (gcc) in (intel i5 3570 - stock)
the_stack_data/200142609.c
#include <stdio.h> #include <stdlib.h> //回调函数 void populate_array(int *array, size_t arraysize, int (* getNextValue)(void)) { for (size_t i = 0; i<arraysize; i++) { array[i] = getNextValue(); } } int getNextValue(void) { return rand(); } int main(void) { int myarray[10]; populate_array(myarray, 10, getNextValue); for (int i=0; i<10; i++) { printf("%d \n", myarray[i]); printf("%p \t", myarray[i]); } return 0; }
the_stack_data/45449539.c
// possible deadlock in __generic_file_fsync // https://syzkaller.appspot.com/bug?id=2c3fa33bc6241bc2d5786ce4d7c2d78f79170af2 // status:open // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <dirent.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <net/if.h> #include <net/if_arp.h> #include <netinet/in.h> #include <pthread.h> #include <sched.h> #include <setjmp.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <linux/capability.h> #include <linux/futex.h> #include <linux/if_addr.h> #include <linux/if_ether.h> #include <linux/if_link.h> #include <linux/if_tun.h> #include <linux/in6.h> #include <linux/ip.h> #include <linux/neighbour.h> #include <linux/net.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/tcp.h> #include <linux/veth.h> unsigned long long procid; static __thread int skip_segv; static __thread jmp_buf segv_env; static void segv_handler(int sig, siginfo_t* info, void* ctx) { uintptr_t addr = (uintptr_t)info->si_addr; const uintptr_t prog_start = 1 << 20; const uintptr_t prog_end = 100 << 20; if (__atomic_load_n(&skip_segv, __ATOMIC_RELAXED) && (addr < prog_start || addr > prog_end)) { _longjmp(segv_env, 1); } exit(sig); } static void install_segv_handler(void) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_IGN; syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8); syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8); memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = segv_handler; sa.sa_flags = SA_NODEFER | SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); sigaction(SIGBUS, &sa, NULL); } #define NONFAILING(...) \ { \ __atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \ if (_setjmp(segv_env) == 0) { \ __VA_ARGS__; \ } \ __atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \ } static void sleep_ms(uint64_t ms) { usleep(ms * 1000); } static uint64_t current_time_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) exit(1); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static void use_temporary_dir(void) { char tmpdir_template[] = "./syzkaller.XXXXXX"; char* tmpdir = mkdtemp(tmpdir_template); if (!tmpdir) exit(1); if (chmod(tmpdir, 0777)) exit(1); if (chdir(tmpdir)) exit(1); } static void thread_start(void* (*fn)(void*), void* arg) { pthread_t th; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 128 << 10); int i; for (i = 0; i < 100; i++) { if (pthread_create(&th, &attr, fn, arg) == 0) { pthread_attr_destroy(&attr); return; } if (errno == EAGAIN) { usleep(50); continue; } break; } exit(1); } typedef struct { int state; } event_t; static void event_init(event_t* ev) { ev->state = 0; } static void event_reset(event_t* ev) { ev->state = 0; } static void event_set(event_t* ev) { if (ev->state) exit(1); __atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE); syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG); } static void event_wait(event_t* ev) { while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE)) syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0); } static int event_isset(event_t* ev) { return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE); } static int event_timedwait(event_t* ev, uint64_t timeout) { uint64_t start = current_time_ms(); uint64_t now = start; for (;;) { uint64_t remain = timeout - (now - start); struct timespec ts; ts.tv_sec = remain / 1000; ts.tv_nsec = (remain % 1000) * 1000 * 1000; syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts); if (__atomic_load_n(&ev->state, __ATOMIC_RELAXED)) return 1; now = current_time_ms(); if (now - start > timeout) return 0; } } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } static struct { char* pos; int nesting; struct nlattr* nested[8]; char buf[1024]; } nlmsg; static void netlink_init(int typ, int flags, const void* data, int size) { memset(&nlmsg, 0, sizeof(nlmsg)); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg.buf; hdr->nlmsg_type = typ; hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags; memcpy(hdr + 1, data, size); nlmsg.pos = (char*)(hdr + 1) + NLMSG_ALIGN(size); } static void netlink_attr(int typ, const void* data, int size) { struct nlattr* attr = (struct nlattr*)nlmsg.pos; attr->nla_len = sizeof(*attr) + size; attr->nla_type = typ; memcpy(attr + 1, data, size); nlmsg.pos += NLMSG_ALIGN(attr->nla_len); } static void netlink_nest(int typ) { struct nlattr* attr = (struct nlattr*)nlmsg.pos; attr->nla_type = typ; nlmsg.pos += sizeof(*attr); nlmsg.nested[nlmsg.nesting++] = attr; } static void netlink_done(void) { struct nlattr* attr = nlmsg.nested[--nlmsg.nesting]; attr->nla_len = nlmsg.pos - (char*)attr; } static int netlink_send(int sock) { if (nlmsg.pos > nlmsg.buf + sizeof(nlmsg.buf) || nlmsg.nesting) exit(1); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg.buf; hdr->nlmsg_len = nlmsg.pos - nlmsg.buf; struct sockaddr_nl addr; memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; unsigned n = sendto(sock, nlmsg.buf, hdr->nlmsg_len, 0, (struct sockaddr*)&addr, sizeof(addr)); if (n != hdr->nlmsg_len) exit(1); n = recv(sock, nlmsg.buf, sizeof(nlmsg.buf), 0); if (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr)) exit(1); if (hdr->nlmsg_type != NLMSG_ERROR) exit(1); return -((struct nlmsgerr*)(hdr + 1))->error; } static void netlink_add_device_impl(const char* type, const char* name) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); netlink_init(RTM_NEWLINK, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); if (name) netlink_attr(IFLA_IFNAME, name, strlen(name)); netlink_nest(IFLA_LINKINFO); netlink_attr(IFLA_INFO_KIND, type, strlen(type)); } static void netlink_add_device(int sock, const char* type, const char* name) { netlink_add_device_impl(type, name); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_add_veth(int sock, const char* name, const char* peer) { netlink_add_device_impl("veth", name); netlink_nest(IFLA_INFO_DATA); netlink_nest(VETH_INFO_PEER); nlmsg.pos += sizeof(struct ifinfomsg); netlink_attr(IFLA_IFNAME, peer, strlen(peer)); netlink_done(); netlink_done(); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_add_hsr(int sock, const char* name, const char* slave1, const char* slave2) { netlink_add_device_impl("hsr", name); netlink_nest(IFLA_INFO_DATA); int ifindex1 = if_nametoindex(slave1); netlink_attr(IFLA_HSR_SLAVE1, &ifindex1, sizeof(ifindex1)); int ifindex2 = if_nametoindex(slave2); netlink_attr(IFLA_HSR_SLAVE2, &ifindex2, sizeof(ifindex2)); netlink_done(); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_device_change(int sock, const char* name, bool up, const char* master, const void* mac, int macsize) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); if (up) hdr.ifi_flags = hdr.ifi_change = IFF_UP; netlink_init(RTM_NEWLINK, 0, &hdr, sizeof(hdr)); netlink_attr(IFLA_IFNAME, name, strlen(name)); if (master) { int ifindex = if_nametoindex(master); netlink_attr(IFLA_MASTER, &ifindex, sizeof(ifindex)); } if (macsize) netlink_attr(IFLA_ADDRESS, mac, macsize); int err = netlink_send(sock); (void)err; } static int netlink_add_addr(int sock, const char* dev, const void* addr, int addrsize) { struct ifaddrmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ifa_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ifa_prefixlen = addrsize == 4 ? 24 : 120; hdr.ifa_scope = RT_SCOPE_UNIVERSE; hdr.ifa_index = if_nametoindex(dev); netlink_init(RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, &hdr, sizeof(hdr)); netlink_attr(IFA_LOCAL, addr, addrsize); netlink_attr(IFA_ADDRESS, addr, addrsize); return netlink_send(sock); } static void netlink_add_addr4(int sock, const char* dev, const char* addr) { struct in_addr in_addr; inet_pton(AF_INET, addr, &in_addr); int err = netlink_add_addr(sock, dev, &in_addr, sizeof(in_addr)); (void)err; } static void netlink_add_addr6(int sock, const char* dev, const char* addr) { struct in6_addr in6_addr; inet_pton(AF_INET6, addr, &in6_addr); int err = netlink_add_addr(sock, dev, &in6_addr, sizeof(in6_addr)); (void)err; } static void netlink_add_neigh(int sock, const char* name, const void* addr, int addrsize, const void* mac, int macsize) { struct ndmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ndm_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ndm_ifindex = if_nametoindex(name); hdr.ndm_state = NUD_PERMANENT; netlink_init(RTM_NEWNEIGH, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); netlink_attr(NDA_DST, addr, addrsize); netlink_attr(NDA_LLADDR, mac, macsize); int err = netlink_send(sock); (void)err; } static int tunfd = -1; static int tun_frags_enabled; #define SYZ_TUN_MAX_PACKET_SIZE 1000 #define TUN_IFACE "syz_tun" #define LOCAL_MAC 0xaaaaaaaaaaaa #define REMOTE_MAC 0xaaaaaaaaaabb #define LOCAL_IPV4 "172.20.20.170" #define REMOTE_IPV4 "172.20.20.187" #define LOCAL_IPV6 "fe80::aa" #define REMOTE_IPV6 "fe80::bb" #define IFF_NAPI 0x0010 #define IFF_NAPI_FRAGS 0x0020 static void initialize_tun(void) { tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK); if (tunfd == -1) { printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n"); printf("otherwise fuzzing or reproducing might not work as intended\n"); return; } const int kTunFd = 240; if (dup2(tunfd, kTunFd) < 0) exit(1); close(tunfd); tunfd = kTunFd; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, TUN_IFACE, IFNAMSIZ); ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_NAPI | IFF_NAPI_FRAGS; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) { ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) exit(1); } if (ioctl(tunfd, TUNGETIFF, (void*)&ifr) < 0) exit(1); tun_frags_enabled = (ifr.ifr_flags & IFF_NAPI_FRAGS) != 0; char sysctl[64]; sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/accept_dad", TUN_IFACE); write_file(sysctl, "0"); sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/router_solicitations", TUN_IFACE); write_file(sysctl, "0"); int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); netlink_add_addr4(sock, TUN_IFACE, LOCAL_IPV4); netlink_add_addr6(sock, TUN_IFACE, LOCAL_IPV6); uint64_t macaddr = REMOTE_MAC; struct in_addr in_addr; inet_pton(AF_INET, REMOTE_IPV4, &in_addr); netlink_add_neigh(sock, TUN_IFACE, &in_addr, sizeof(in_addr), &macaddr, ETH_ALEN); struct in6_addr in6_addr; inet_pton(AF_INET6, REMOTE_IPV6, &in6_addr); netlink_add_neigh(sock, TUN_IFACE, &in6_addr, sizeof(in6_addr), &macaddr, ETH_ALEN); macaddr = LOCAL_MAC; netlink_device_change(sock, TUN_IFACE, true, 0, &macaddr, ETH_ALEN); close(sock); } #define DEV_IPV4 "172.20.20.%d" #define DEV_IPV6 "fe80::%02x" #define DEV_MAC 0x00aaaaaaaaaa static void initialize_netdevices(void) { char netdevsim[16]; sprintf(netdevsim, "netdevsim%d", (int)procid); struct { const char* type; const char* dev; } devtypes[] = { {"ip6gretap", "ip6gretap0"}, {"bridge", "bridge0"}, {"vcan", "vcan0"}, {"bond", "bond0"}, {"team", "team0"}, {"dummy", "dummy0"}, {"nlmon", "nlmon0"}, {"caif", "caif0"}, {"batadv", "batadv0"}, {"vxcan", "vxcan1"}, {"netdevsim", netdevsim}, {"veth", 0}, }; const char* devmasters[] = {"bridge", "bond", "team"}; struct { const char* name; int macsize; bool noipv6; } devices[] = { {"lo", ETH_ALEN}, {"sit0", 0}, {"bridge0", ETH_ALEN}, {"vcan0", 0, true}, {"tunl0", 0}, {"gre0", 0}, {"gretap0", ETH_ALEN}, {"ip_vti0", 0}, {"ip6_vti0", 0}, {"ip6tnl0", 0}, {"ip6gre0", 0}, {"ip6gretap0", ETH_ALEN}, {"erspan0", ETH_ALEN}, {"bond0", ETH_ALEN}, {"veth0", ETH_ALEN}, {"veth1", ETH_ALEN}, {"team0", ETH_ALEN}, {"veth0_to_bridge", ETH_ALEN}, {"veth1_to_bridge", ETH_ALEN}, {"veth0_to_bond", ETH_ALEN}, {"veth1_to_bond", ETH_ALEN}, {"veth0_to_team", ETH_ALEN}, {"veth1_to_team", ETH_ALEN}, {"veth0_to_hsr", ETH_ALEN}, {"veth1_to_hsr", ETH_ALEN}, {"hsr0", 0}, {"dummy0", ETH_ALEN}, {"nlmon0", 0}, {"vxcan1", 0, true}, {"caif0", ETH_ALEN}, {"batadv0", ETH_ALEN}, {netdevsim, ETH_ALEN}, }; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) netlink_add_device(sock, devtypes[i].type, devtypes[i].dev); for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) { char master[32], slave0[32], veth0[32], slave1[32], veth1[32]; sprintf(slave0, "%s_slave_0", devmasters[i]); sprintf(veth0, "veth0_to_%s", devmasters[i]); netlink_add_veth(sock, slave0, veth0); sprintf(slave1, "%s_slave_1", devmasters[i]); sprintf(veth1, "veth1_to_%s", devmasters[i]); netlink_add_veth(sock, slave1, veth1); sprintf(master, "%s0", devmasters[i]); netlink_device_change(sock, slave0, false, master, 0, 0); netlink_device_change(sock, slave1, false, master, 0, 0); } netlink_device_change(sock, "bridge_slave_0", true, 0, 0, 0); netlink_device_change(sock, "bridge_slave_1", true, 0, 0, 0); netlink_add_veth(sock, "hsr_slave_0", "veth0_to_hsr"); netlink_add_veth(sock, "hsr_slave_1", "veth1_to_hsr"); netlink_add_hsr(sock, "hsr0", "hsr_slave_0", "hsr_slave_1"); netlink_device_change(sock, "hsr_slave_0", true, 0, 0, 0); netlink_device_change(sock, "hsr_slave_1", true, 0, 0, 0); for (i = 0; i < sizeof(devices) / (sizeof(devices[0])); i++) { char addr[32]; sprintf(addr, DEV_IPV4, i + 10); netlink_add_addr4(sock, devices[i].name, addr); if (!devices[i].noipv6) { sprintf(addr, DEV_IPV6, i + 10); netlink_add_addr6(sock, devices[i].name, addr); } uint64_t macaddr = DEV_MAC + ((i + 10ull) << 40); netlink_device_change(sock, devices[i].name, true, 0, &macaddr, devices[i].macsize); } close(sock); } static void initialize_netdevices_init(void) { int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); struct { const char* type; int macsize; bool noipv6; bool noup; } devtypes[] = { {"nr", 7, true}, {"rose", 5, true, true}, }; unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) { char dev[32], addr[32]; sprintf(dev, "%s%d", devtypes[i].type, (int)procid); sprintf(addr, "172.30.%d.%d", i, (int)procid + 1); netlink_add_addr4(sock, dev, addr); if (!devtypes[i].noipv6) { sprintf(addr, "fe88::%02x:%02x", i, (int)procid + 1); netlink_add_addr6(sock, dev, addr); } int macsize = devtypes[i].macsize; uint64_t macaddr = 0xbbbbbb + ((unsigned long long)i << (8 * (macsize - 2))) + (procid << (8 * (macsize - 1))); netlink_device_change(sock, dev, !devtypes[i].noup, 0, &macaddr, macsize); } close(sock); } static int read_tun(char* data, int size) { if (tunfd < 0) return -1; int rv = read(tunfd, data, size); if (rv < 0) { if (errno == EAGAIN) return -1; if (errno == EBADFD) return -1; exit(1); } return rv; } static void flush_tun() { char data[SYZ_TUN_MAX_PACKET_SIZE]; while (read_tun(&data[0], sizeof(data)) != -1) { } } #define XT_TABLE_SIZE 1536 #define XT_MAX_ENTRIES 10 struct xt_counters { uint64_t pcnt, bcnt; }; struct ipt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_entries; unsigned int size; }; struct ipt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct ipt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct ipt_table_desc { const char* name; struct ipt_getinfo info; struct ipt_replace replace; }; static struct ipt_table_desc ipv4_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; static struct ipt_table_desc ipv6_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; #define IPT_BASE_CTL 64 #define IPT_SO_SET_REPLACE (IPT_BASE_CTL) #define IPT_SO_GET_INFO (IPT_BASE_CTL) #define IPT_SO_GET_ENTRIES (IPT_BASE_CTL + 1) struct arpt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_entries; unsigned int size; }; struct arpt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct arpt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct arpt_table_desc { const char* name; struct arpt_getinfo info; struct arpt_replace replace; }; static struct arpt_table_desc arpt_tables[] = { {.name = "filter"}, }; #define ARPT_BASE_CTL 96 #define ARPT_SO_SET_REPLACE (ARPT_BASE_CTL) #define ARPT_SO_GET_INFO (ARPT_BASE_CTL) #define ARPT_SO_GET_ENTRIES (ARPT_BASE_CTL + 1) static void checkpoint_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { struct ipt_get_entries entries; socklen_t optlen; int fd, i; fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); optlen = sizeof(table->info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->info.size > sizeof(table->replace.entrytable)) exit(1); if (table->info.num_entries > XT_MAX_ENTRIES) exit(1); memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { struct xt_counters counters[XT_MAX_ENTRIES]; struct ipt_get_entries entries; struct ipt_getinfo info; socklen_t optlen; int fd, i; fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; if (table->info.valid_hooks == 0) continue; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); optlen = sizeof(info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &info, &optlen)) exit(1); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, level, IPT_SO_SET_REPLACE, &table->replace, optlen)) exit(1); } close(fd); } static void checkpoint_arptables(void) { struct arpt_get_entries entries; socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); optlen = sizeof(table->info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->info.size > sizeof(table->replace.entrytable)) exit(1); if (table->info.num_entries > XT_MAX_ENTRIES) exit(1); memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_arptables() { struct xt_counters counters[XT_MAX_ENTRIES]; struct arpt_get_entries entries; struct arpt_getinfo info; socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; if (table->info.valid_hooks == 0) continue; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); optlen = sizeof(info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &info, &optlen)) exit(1); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } else { } table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, SOL_IP, ARPT_SO_SET_REPLACE, &table->replace, optlen)) exit(1); } close(fd); } #define NF_BR_NUMHOOKS 6 #define EBT_TABLE_MAXNAMELEN 32 #define EBT_CHAIN_MAXNAMELEN 32 #define EBT_BASE_CTL 128 #define EBT_SO_SET_ENTRIES (EBT_BASE_CTL) #define EBT_SO_GET_INFO (EBT_BASE_CTL) #define EBT_SO_GET_ENTRIES (EBT_SO_GET_INFO + 1) #define EBT_SO_GET_INIT_INFO (EBT_SO_GET_ENTRIES + 1) #define EBT_SO_GET_INIT_ENTRIES (EBT_SO_GET_INIT_INFO + 1) struct ebt_replace { char name[EBT_TABLE_MAXNAMELEN]; unsigned int valid_hooks; unsigned int nentries; unsigned int entries_size; struct ebt_entries* hook_entry[NF_BR_NUMHOOKS]; unsigned int num_counters; struct ebt_counter* counters; char* entries; }; struct ebt_entries { unsigned int distinguisher; char name[EBT_CHAIN_MAXNAMELEN]; unsigned int counter_offset; int policy; unsigned int nentries; char data[0] __attribute__((aligned(__alignof__(struct ebt_replace)))); }; struct ebt_table_desc { const char* name; struct ebt_replace replace; char entrytable[XT_TABLE_SIZE]; }; static struct ebt_table_desc ebt_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "broute"}, }; static void checkpoint_ebtables(void) { socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; strcpy(table->replace.name, table->name); optlen = sizeof(table->replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_INFO, &table->replace, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->replace.entries_size > sizeof(table->entrytable)) exit(1); table->replace.num_counters = 0; table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_ENTRIES, &table->replace, &optlen)) exit(1); } close(fd); } static void reset_ebtables() { struct ebt_replace replace; char entrytable[XT_TABLE_SIZE]; socklen_t optlen; unsigned i, j, h; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; if (table->replace.valid_hooks == 0) continue; memset(&replace, 0, sizeof(replace)); strcpy(replace.name, table->name); optlen = sizeof(replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INFO, &replace, &optlen)) exit(1); replace.num_counters = 0; table->replace.entries = 0; for (h = 0; h < NF_BR_NUMHOOKS; h++) table->replace.hook_entry[h] = 0; if (memcmp(&table->replace, &replace, sizeof(table->replace)) == 0) { memset(&entrytable, 0, sizeof(entrytable)); replace.entries = entrytable; optlen = sizeof(replace) + replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_ENTRIES, &replace, &optlen)) exit(1); if (memcmp(table->entrytable, entrytable, replace.entries_size) == 0) continue; } for (j = 0, h = 0; h < NF_BR_NUMHOOKS; h++) { if (table->replace.valid_hooks & (1 << h)) { table->replace.hook_entry[h] = (struct ebt_entries*)table->entrytable + j; j++; } } table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (setsockopt(fd, SOL_IP, EBT_SO_SET_ENTRIES, &table->replace, optlen)) exit(1); } close(fd); } static void checkpoint_net_namespace(void) { checkpoint_ebtables(); checkpoint_arptables(); checkpoint_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); checkpoint_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void reset_net_namespace(void) { reset_ebtables(); reset_arptables(); reset_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); reset_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void setup_cgroups() { if (mkdir("/syzcgroup", 0777)) { } if (mkdir("/syzcgroup/unified", 0777)) { } if (mount("none", "/syzcgroup/unified", "cgroup2", 0, NULL)) { } if (chmod("/syzcgroup/unified", 0777)) { } write_file("/syzcgroup/unified/cgroup.subtree_control", "+cpu +memory +io +pids +rdma"); if (mkdir("/syzcgroup/cpu", 0777)) { } if (mount("none", "/syzcgroup/cpu", "cgroup", 0, "cpuset,cpuacct,perf_event,hugetlb")) { } write_file("/syzcgroup/cpu/cgroup.clone_children", "1"); if (chmod("/syzcgroup/cpu", 0777)) { } if (mkdir("/syzcgroup/net", 0777)) { } if (mount("none", "/syzcgroup/net", "cgroup", 0, "net_cls,net_prio,devices,freezer")) { } if (chmod("/syzcgroup/net", 0777)) { } } static void setup_cgroups_loop() { int pid = getpid(); char file[128]; char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/pids.max", cgroupdir); write_file(file, "32"); snprintf(file, sizeof(file), "%s/memory.low", cgroupdir); write_file(file, "%d", 298 << 20); snprintf(file, sizeof(file), "%s/memory.high", cgroupdir); write_file(file, "%d", 299 << 20); snprintf(file, sizeof(file), "%s/memory.max", cgroupdir); write_file(file, "%d", 300 << 20); snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); } static void setup_cgroups_test() { char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); if (symlink(cgroupdir, "./cgroup")) { } snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid); if (symlink(cgroupdir, "./cgroup.cpu")) { } snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid); if (symlink(cgroupdir, "./cgroup.net")) { } } static void setup_common() { if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) { } setup_cgroups(); } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = (200 << 20); setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 32 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 136 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); rlim.rlim_cur = rlim.rlim_max = 256; setrlimit(RLIMIT_NOFILE, &rlim); if (unshare(CLONE_NEWNS)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(0x02000000)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } typedef struct { const char* name; const char* value; } sysctl_t; static const sysctl_t sysctls[] = { {"/proc/sys/kernel/shmmax", "16777216"}, {"/proc/sys/kernel/shmall", "536870912"}, {"/proc/sys/kernel/shmmni", "1024"}, {"/proc/sys/kernel/msgmax", "8192"}, {"/proc/sys/kernel/msgmni", "1024"}, {"/proc/sys/kernel/msgmnb", "1024"}, {"/proc/sys/kernel/sem", "1024 1048576 500 1024"}, }; unsigned i; for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++) write_file(sysctls[i].name, sysctls[i].value); } int wait_for_loop(int pid) { if (pid < 0) exit(1); int status = 0; while (waitpid(-1, &status, __WALL) != pid) { } return WEXITSTATUS(status); } static void drop_caps(void) { struct __user_cap_header_struct cap_hdr = {}; struct __user_cap_data_struct cap_data[2] = {}; cap_hdr.version = _LINUX_CAPABILITY_VERSION_3; cap_hdr.pid = getpid(); if (syscall(SYS_capget, &cap_hdr, &cap_data)) exit(1); const int drop = (1 << CAP_SYS_PTRACE) | (1 << CAP_SYS_NICE); cap_data[0].effective &= ~drop; cap_data[0].permitted &= ~drop; cap_data[0].inheritable &= ~drop; if (syscall(SYS_capset, &cap_hdr, &cap_data)) exit(1); } static int do_sandbox_none(void) { if (unshare(CLONE_NEWPID)) { } int pid = fork(); if (pid != 0) return wait_for_loop(pid); setup_common(); sandbox_common(); drop_caps(); initialize_netdevices_init(); if (unshare(CLONE_NEWNET)) { } initialize_tun(); initialize_netdevices(); loop(); exit(1); } #define FS_IOC_SETFLAGS _IOW('f', 2, long) static void remove_dir(const char* dir) { DIR* dp; struct dirent* ep; int iter = 0; retry: while (umount2(dir, MNT_DETACH) == 0) { } dp = opendir(dir); if (dp == NULL) { if (errno == EMFILE) { exit(1); } exit(1); } while ((ep = readdir(dp))) { if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) continue; char filename[FILENAME_MAX]; snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name); while (umount2(filename, MNT_DETACH) == 0) { } struct stat st; if (lstat(filename, &st)) exit(1); if (S_ISDIR(st.st_mode)) { remove_dir(filename); continue; } int i; for (i = 0;; i++) { if (unlink(filename) == 0) break; if (errno == EPERM) { int fd = open(filename, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) close(fd); continue; } } if (errno == EROFS) { break; } if (errno != EBUSY || i > 100) exit(1); if (umount2(filename, MNT_DETACH)) exit(1); } } closedir(dp); int i; for (i = 0;; i++) { if (rmdir(dir) == 0) break; if (i < 100) { if (errno == EPERM) { int fd = open(dir, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) close(fd); continue; } } if (errno == EROFS) { break; } if (errno == EBUSY) { if (umount2(dir, MNT_DETACH)) exit(1); continue; } if (errno == ENOTEMPTY) { if (iter < 100) { iter++; goto retry; } } } exit(1); } } static void kill_and_wait(int pid, int* status) { kill(-pid, SIGKILL); kill(pid, SIGKILL); int i; for (i = 0; i < 100; i++) { if (waitpid(-1, status, WNOHANG | __WALL) == pid) return; usleep(1000); } DIR* dir = opendir("/sys/fs/fuse/connections"); if (dir) { for (;;) { struct dirent* ent = readdir(dir); if (!ent) break; if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; char abort[300]; snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort", ent->d_name); int fd = open(abort, O_WRONLY); if (fd == -1) { continue; } if (write(fd, abort, 1) < 0) { } close(fd); } closedir(dir); } else { } while (waitpid(-1, status, __WALL) != pid) { } } static void setup_loop() { setup_cgroups_loop(); checkpoint_net_namespace(); } static void reset_loop() { reset_net_namespace(); } static void setup_test() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setup_cgroups_test(); write_file("/proc/self/oom_score_adj", "1000"); flush_tun(); } static void close_fds() { int fd; for (fd = 3; fd < 30; fd++) close(fd); } static void setup_binfmt_misc() { if (mount(0, "/proc/sys/fs/binfmt_misc", "binfmt_misc", 0, 0)) { } write_file("/proc/sys/fs/binfmt_misc/register", ":syz0:M:0:\x01::./file0:"); write_file("/proc/sys/fs/binfmt_misc/register", ":syz1:M:1:\x02::./file0:POC"); } struct thread_t { int created, call; event_t ready, done; }; static struct thread_t threads[16]; static void execute_call(int call); static int running; static void* thr(void* arg) { struct thread_t* th = (struct thread_t*)arg; for (;;) { event_wait(&th->ready); event_reset(&th->ready); execute_call(th->call); __atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED); event_set(&th->done); } return 0; } static void execute_one(void) { int i, call, thread; int collide = 0; again: for (call = 0; call < 8; call++) { for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0])); thread++) { struct thread_t* th = &threads[thread]; if (!th->created) { th->created = 1; event_init(&th->ready); event_init(&th->done); event_set(&th->done); thread_start(thr, th); } if (!event_isset(&th->done)) continue; event_reset(&th->done); th->call = call; __atomic_fetch_add(&running, 1, __ATOMIC_RELAXED); event_set(&th->ready); if (collide && (call % 2) == 0) break; event_timedwait(&th->done, 45); break; } } for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++) sleep_ms(1); close_fds(); if (!collide) { collide = 1; goto again; } } static void execute_one(void); #define WAIT_FLAGS __WALL static void loop(void) { setup_loop(); int iter; for (iter = 0;; iter++) { char cwdbuf[32]; sprintf(cwdbuf, "./%d", iter); if (mkdir(cwdbuf, 0777)) exit(1); reset_loop(); int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { if (chdir(cwdbuf)) exit(1); setup_test(); execute_one(); exit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid) break; sleep_ms(1); if (current_time_ms() - start < 5 * 1000) continue; kill_and_wait(pid, &status); break; } remove_dir(cwdbuf); } } uint64_t r[4] = {0xffffffffffffffff, 0xffffffffffffffff, 0x0, 0x0}; void execute_call(int call) { intptr_t res; switch (call) { case 0: NONFAILING(memcpy((void*)0x20000180, "./bus\000", 6)); res = syscall(__NR_creat, 0x20000180, 0); if (res != -1) r[0] = res; break; case 1: NONFAILING(memcpy((void*)0x20000140, "./bus\000", 6)); res = syscall(__NR_creat, 0x20000140, 0); if (res != -1) r[1] = res; break; case 2: syscall(__NR_ftruncate, r[1], 0x2081fd); break; case 3: res = syscall(__NR_semget, 0x798e2635 + procid * 4, 0, 1); if (res != -1) r[2] = res; break; case 4: syscall(__NR_semctl, r[2], 0, 0xe, 0x200001c0); break; case 5: syscall(__NR_fcntl, r[0], 4, 0x6000); break; case 6: res = syscall(__NR_io_setup, 1, 0x20000000); if (res != -1) NONFAILING(r[3] = *(uint64_t*)0x20000000); break; case 7: NONFAILING(*(uint64_t*)0x20000540 = 0x200000c0); NONFAILING(*(uint64_t*)0x200000c0 = 0); NONFAILING(*(uint32_t*)0x200000c8 = 0); NONFAILING(*(uint32_t*)0x200000cc = 2); NONFAILING(*(uint16_t*)0x200000d0 = 1); NONFAILING(*(uint16_t*)0x200000d2 = 0); NONFAILING(*(uint32_t*)0x200000d4 = r[0]); NONFAILING(*(uint64_t*)0x200000d8 = 0x20000000); NONFAILING(*(uint64_t*)0x200000e0 = 0x10000); NONFAILING(*(uint64_t*)0x200000e8 = 0); NONFAILING(*(uint64_t*)0x200000f0 = 0); NONFAILING(*(uint32_t*)0x200000f8 = 0); NONFAILING(*(uint32_t*)0x200000fc = -1); syscall(__NR_io_submit, r[3], 0x605, 0x20000540); break; } } int main(void) { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); setup_binfmt_misc(); install_segv_handler(); for (procid = 0; procid < 6; procid++) { if (fork() == 0) { use_temporary_dir(); do_sandbox_none(); } } sleep(1000000); return 0; }
the_stack_data/26699073.c
/* test_*.c HSTR test Copyright (C) 2014-2018 Martin Dvorak <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <stdio.h> #include <readline/readline.h> #include <readline/chardefs.h> // $ xev // ... get keycodes void echo_printable_characters() { int c; for(c=0; c<255; c++) { printf("Key number: '%3d' / Char: '%c' Meta: \n", c, c, c&meta_character_bit); } } void echo_keyb_characters() { int c; while(1) { c = getc(stdin); printf("Key number: '%3d' / Char: '%c' Meta: %d Ctrl: %d Ctrl mask: %d\n", c, c, META_CHAR(c), CTRL_CHAR(c), c&control_character_mask); } } int main(int argc, char *argv[]) { echo_keyb_characters(); }
the_stack_data/485405.c
#include <stdio.h> int main (void) { int A, B, SOMA; scanf("%d\n%d", &A, &B); printf("SOMA = %d\n", A+B); return 0; }
the_stack_data/92328478.c
#include <stdio.h> void foo2 (void) { printf ("foo2\n"); }
the_stack_data/23223.c
// RUN: %clang_cc1 -fsyntax-only -verify %s -triple arm64-apple-ios #pragma clang section bss = "" data = "" rodata = "" text = "" #pragma clang section bss = "" data = "" rodata = "" text = "__TEXT,__text" #pragma clang section bss = "" data = "" rodata = "" text = "badname" // expected-error {{argument to #pragma section is not valid for this target: mach-o section specifier requires a segment and section separated by a comma}} #pragma clang section bss = "" data = "" rodata = "" text = "__TEXT,__namethatiswaytoolong" // expected-error {{argument to #pragma section is not valid for this target: mach-o section specifier requires a section whose length is between 1 and 16 characters}} #pragma clang section int a;
the_stack_data/182952797.c
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include <assert.h> #include <errno.h> #include <limits.h> #include <spawn.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <unistd.h> static void _run_tests(const char* test_file) { FILE* file = fopen(test_file, "r"); if (!file) { fprintf(stderr, "File %s not found \n", test_file); } char line[256]; int i = 1; while (fgets(line, sizeof(line), file)) { line[strlen(line) - 1] = '\0'; int r; pid_t pid; int wstatus; printf("=== start test %d: %s\n", i++, line); char* const args[] = {(char*)line, NULL}; char* const envp[] = {"VALUE=1", NULL}; r = posix_spawn(&pid, line, NULL, NULL, args, envp); assert(r == 0); assert(pid >= 0); assert(waitpid(pid, &wstatus, WNOHANG) == 0); assert(waitpid(pid, &wstatus, 0) == pid); assert(WIFEXITED(wstatus)); if ((r = WEXITSTATUS(wstatus)) != 0) { printf("!!! WEXITSTATUS(wstatus) = %d\n", r); assert(0); } printf("=== passed test (%s)\n", line); } fclose(file); } int main(int argc, const char* argv[]) { if (argc < 1) { fprintf( stderr, "Must pass in the file containing test names\n"); } else { _run_tests(argv[1]); } printf("=== passed all tests: %s\n", argv[0]); return 0; }
the_stack_data/819008.c
#include <stdio.h> #include <math.h> #define f(x) (x*x-x-6) #define EPSILON 0.0000005 int main(void){ float a, b, c = 0, cOld; FILE *fp = fopen("regula.txt", "w"); printf("Enter a and b:\n"); scanf("%f %f", &a, &b); while( f(a) * f(b) > 0){ printf("Enter different a and b:\n"); scanf("%f %f", &a, &b); } printf(" a\t\t f(a)\t\t b\t\t f(b)\t\t c\t\t f(c)\t\t error\n"); do{ cOld = c; c = ((b*f(a)) - (a*f(b)))/( f(a)-f(b) ); fprintf(fp,"%f %f\n", a, f(a)); fprintf(fp, "%f %f\n\n", b, f(b)); printf("%f\t%f\t%f\t%f\t%f\t%f\t%f\n",a, f(a), b, f(b), c, f(c), (float)fabs(c-cOld) ); if (f(c) < EPSILON && f(c)>-EPSILON ){ break; } if( f(c) * f(a) < 0 ) b = c; else a = c; }while( (c-cOld) > EPSILON || (c-cOld) < -EPSILON ); printf("\tRoot:%f\n", c); return 0; }
the_stack_data/465143.c
extern int glob; int *glob_ptr(int *x) { (void) x; return &glob; }
the_stack_data/151706264.c
/* * Exercise 2-1 * * Write a program to determine the ranges of char, short, int and long * variables, both signed and unsigned, by printing appropriate values from * standard headers and by direct computation. Harder if you compute them: * determine the ranges of the various floating-point types. * */ #include <stdio.h> #include <limits.h> #include <float.h> int main() { char c_min,c_max,pc_max; unsigned char uc_min,uc_max,upc_max; short s_min,s_max,ps_max; unsigned short us_min,us_max,ups_max; int i_min,i_max,pi_max; unsigned int ui_min,ui_max,upi_max; long int li_min,li_max,pli_max; unsigned long uli_min,uli_max,upli_max; float f_min,f_max,pf_max; double d_min,d_max,pd_max; printf("Standard Header Values: \n"); printf("signed char: min=%d,max=%d\n",SCHAR_MIN,SCHAR_MAX); printf("unsigned char: min=%d,max=%d\n",CHAR_MIN,CHAR_MAX); printf("signed short int: min=%d,max=%d\n",SHRT_MIN,SHRT_MAX); printf("unsigned short int: min=%d,max=%d\n",0,USHRT_MAX); printf("signed int: min=%d,max=%d\n",INT_MIN,INT_MAX); printf("unsigned int: min=%u,max=%u\n",0,UINT_MAX); printf("signed long: min=%ld,max=%ld\n",LONG_MIN,LONG_MAX); printf("unsigned long: min=%lu,max=%lu\n",(long)0,ULONG_MAX); printf("float: min=%f,max=%f\n",FLT_MIN,FLT_MAX); printf("double: min=%f,max=%f\n",DBL_MIN,DBL_MAX); printf("Computational Values: \n"); // Compute signed char min/max for (c_max = pc_max = 0; c_max >= pc_max; c_max++) { pc_max = c_max; } c_min = pc_max; c_min++; printf("signed char: min=%d,max=%d\n",c_min,pc_max); // Compute unsigned char min/max for (uc_max = upc_max = 0; uc_max >= upc_max; uc_max++) { upc_max = uc_max; } uc_min = upc_max; uc_min++; printf("unsigned char: min=%d,max=%d\n",uc_min,upc_max); // Compute signed short int min/max for (s_max = ps_max = 0; s_max >= ps_max; s_max++) { ps_max = s_max; } s_min = ps_max; s_min++; printf("short int: min=%d,max=%d\n",s_min,ps_max); // Compute unsigned short int min/max for (us_max = ups_max = 0; us_max >= ups_max; us_max++) { ups_max = us_max; } us_min = ups_max; us_min++; printf("unsigned short int: min=%d,max=%d\n",us_min,ups_max); // Compute signed int min/max for (i_max = pi_max = 0; i_max >= pi_max; i_max++) { pi_max = i_max; } i_min = pi_max; i_min++; printf("signed int: min=%d,max=%d\n",i_min,pi_max); // Compute unsigned int min/max for (ui_max = upi_max = 0; ui_max >= upi_max; ui_max++) { upi_max = ui_max; } ui_min = upi_max; ui_min++; printf("unsigned int: min=%u,max=%u\n",ui_min,upi_max); // Compute signed long int min/max for (li_max = pli_max = 0; li_max >= pli_max; li_max++) { pli_max = li_max; } li_min = pli_max; li_min++; printf("long int: min=%ld,max=%ld\n",li_min,pli_max); // Compute unsigned long int min/max for (uli_max = upli_max = 0; uli_max >= upli_max; uli_max++) { upli_max = uli_max; } uli_min = upli_max; uli_min++; printf("long int: min=%lu,max=%lu\n",uli_min,upli_max); // Couldn't find a way to calc floating point without taking advantage // of a known max value (which obviously isn't portable) // Below is still TODO // Compute float min/max for (f_max = pf_max = 0.0; f_max >= pf_max; pf_max+=0.1) { pf_max = f_max; } f_min = pf_max; f_min+=0.1; printf("float: min=%f,max=%f\n",f_min,pf_max); }
the_stack_data/198580664.c
#include <stdio.h> // to compile this file: // gcc -o chal1 chal1.c // to execute this code: // ./chal1 int main() { // delcare any three variables (of different types) // perform some arithmetic operations between them (be sure to cast) // use printf to display the results // hint: printf("%d\n", some_int); }
the_stack_data/237644476.c
/* @jxvtrl Exercicio Número 1c da Prova 1 de Introdução a Programação */ #include <stdio.h> #include <math.h> int xInicial=0,yInicial=0; int xFinal,yFinal,controle = 0,minx,miny; int dx,dy,dmin,dist,menorX,menorY,dist1; char deseja; int temp1,temp2,temp3,temp4,temp5; int pontos; int main(){ printf("Ponto de origem (0,0)\nQuantos pontos deseja informar? "); scanf("%d", &pontos); if (pontos==0){ printf("0,0 é a unica coordenada informada"); } while (pontos>0){ if (pontos == 1){ printf("(%d) Digite o ponto x a adicionar: (",pontos); scanf("%d",&xFinal); system("cls"); printf("Ponto de origem (0,0)\n"); printf("(%d) Digite o ponto y a adicionar: (%d,",pontos,xFinal); scanf("%d",&yFinal); system("cls"); printf("Ponto de origem (0,0)\n"); printf("(%d) Ponto escolhido: (%d,%d)\n\n",pontos,xFinal,yFinal); dist= sqrt((xFinal-xInicial)*(xFinal-xInicial)+(yFinal-yInicial)*(yFinal-yInicial)); printf("Distancia do ponto escolhido ate a origem: %d\n", dist); } else if (pontos > 1){ printf("(%d) Digite o ponto x a adicionar: (",pontos); scanf("%d",&xFinal); system("cls"); printf("Ponto de origem (0,0)\n"); printf("(%d) Digite o ponto y a adicionar: (%d,",pontos,xFinal); scanf("%d",&yFinal); system("cls"); printf("Ponto de origem (0,0)\n"); printf("(%d) Ponto escolhido: (%d,%d)\n\n",pontos,xFinal,yFinal); dist= sqrt((xFinal-xInicial)*(xFinal-xInicial)+(yFinal-yInicial)*(yFinal-yInicial)); temp1=dist; printf("Distancia do ponto escolhido ate a origem: %d", dist); } } while (controle > 0){ printf("Restam (%i).\n", controle); printf("Digite o proximo ponto: \n"); scanf("%i,%i",&xFinal,&yFinal); dx = xInicial-xFinal; dy = yInicial-yFinal; dist = sqrt(pow(dx,2)+(pow(dy,2))); dist1 = dist; if (dist1 < dmin){ dmin = dist; printf("Menor ponto: %d,%d\nDistancia do ponto de origem: %d", xFinal,yFinal, dmin); } dist = dmin; controle--; } printf("Menor ponto: %d,%d\nDistancia do ponto de origem: %d", menorX,menorY, dmin); return 0; }
the_stack_data/167329625.c
#include <stdio.h> int** transpose(int [][100] ,int ); void input(int [][100] ,int* ); void output(int [][100] ,int ); int main() { int mat[100][100]={0}; int mat_size; input(mat,&mat_size); printf("The input array is \n"); output(mat,mat_size); printf("Transpose matrix\n"); output(transpose(mat,mat_size),mat_size); return 0; } int** transpose(int m[][100], int size) { int i,j,temp; for(i=0;i<size;i++) for(j=0;j<i;j++) { temp = m[i][j]; m[i][j] = m[j][i]; m[j][i] = temp; } return m; } void input(int m[][100],int* size) { printf("Enter the size of the matrix.\n"); scanf("%d",size); int i,j; printf("Enter the elements of the matrix.\n"); for(i=0;i<*size;i++) for(j=0;j<*size;j++) scanf("%d",&m[i][j]); } void output (int m[][100],int size) { printf("The %d X %d matrix is\n",size,size); int i,j; for(i=0;i<size;i++) { for(j=0;j<size;j++) printf("%d ",m[i][j]); printf("\n"); } }
the_stack_data/1251633.c
#include <stdio.h> int main(){ printf("Hello C Language"); return 0; }
the_stack_data/872491.c
#include <stdio.h> #include <stdlib.h> #include <string.h> char* sub_string(char *in_string, int start_index, int end_index) { char *out_string, end = '\0'; out_string = (char *) malloc(sizeof(char) * (end_index - start_index + 1)); for (int i = start_index - 1; i < end_index; i++) { strncat(out_string, &in_string[i], 1); // printf("func call: %s\n", out_string); } strncat(out_string, &end, 1); // Your C code here; you may call strlen() to find the length of the User input string // Have only the one return statement shown here. return out_string; }
the_stack_data/175144471.c
/* 2. Write a program that creates threads and increments a global variable n=0 with the values from a struct given as argument to each thread until it is greater than 20. The struct contains for each thread 2 random numbers generated in the main program. */ #include <stdlib.h> #include <stdio.h> #include <time.h> #include <pthread.h> #define T 10 #define maxrand 100 #define maxn 1000 int n; pthread_mutex_t mtx; struct pair { int first, second; }; void* run(void *arg) { struct pair * act = (struct pair *) arg; printf("Thread has %d and %d. n = %d\n", act->first, act->second, n); while(n < maxn) { pthread_mutex_lock(&mtx); printf("Thread n = %d + %d\n", n, act->first); n += act->first; pthread_mutex_unlock(&mtx); if(n < maxn) { /// so that once it is greater, then it is no need to increment again with the second generated random number pthread_mutex_lock(&mtx); printf("Thread n = %d + %d\n", n, act->second); n += act->second; pthread_mutex_unlock(&mtx); } } free(act); return NULL; } int main() { srand(time(NULL)); int i; pthread_t t[T]; pthread_mutex_init(&mtx, NULL); for(i = 0 ; i < T ; ++ i) { struct pair * act = (struct pair *)malloc(sizeof(struct pair)); act->first = rand() % maxrand; act->second = rand() % maxrand; pthread_create(&t[i], NULL, run, (void *)act); } for(i = 0 ; i < T ; ++ i) { pthread_join(t[i], NULL); } printf("%d\n", n); pthread_mutex_destroy(&mtx); return 0; }
the_stack_data/428114.c
int *x; main() { int y; x = (int *) malloc( 25*sizeof(int) ); scanf("%d%d", &x[3], &x[8]); y = x[3] + x[8]; printf("%d\n", y); }
the_stack_data/22012672.c
#include<stdio.h> int main() { int a, sum; sum = 4 ^3 + a ^ a; printf("\nValue of sum is:\t%d", sum); return 0; }
the_stack_data/128949.c
#define _GNU_SOURCE #include <stdio.h> #include <netdb.h> void herror(const char *msg) { fprintf(stderr, "%s%s%s", msg?msg:"", msg?": ":"", hstrerror(h_errno)); }
the_stack_data/1191898.c
/*- * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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_cons.c 8.1 (Berkeley) 6/10/93 */ /*********************************************************** Copyright IBM Corporation 1987 All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of IBM not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. IBM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* * ARGO Project, Computer Sciences Dept., University of Wisconsin - Madison */ /* * $Header: /cvsroot/xmach/lites/server/netiso/if_cons.c,v 1.2 2000/10/27 01:58:48 welchd Exp $ * $Source: /cvsroot/xmach/lites/server/netiso/if_cons.c,v $ * * cons.c - Connection Oriented Network Service: * including support for a) user transport-level service, * b) COSNS below CLNP, and c) CONS below TP. */ #ifdef TPCONS #ifdef KERNEL #ifdef ARGO_DEBUG #define Static unsigned LAST_CALL_PCB; #else /* ARGO_DEBUG */ #define Static static #endif /* ARGO_DEBUG */ #ifndef SOCK_STREAM #include <sys/param.h> #include <sys/systm.h> #include <sys/mbuf.h> #include <sys/protosw.h> #include <sys/socket.h> #include <sys/socketvar.h> #include <sys/errno.h> #include <sys/ioctl.h> #include <sys/tsleep.h> #include <net/if.h> #include <net/netisr.h> #include <net/route.h> #include <netiso/iso_errno.h> #include <netiso/argo_debug.h> #include <netiso/tp_trace.h> #include <netiso/iso.h> #include <netiso/cons.h> #include <netiso/iso_pcb.h> #include <netccitt/x25.h> #include <netccitt/pk.h> #include <netccitt/pk_var.h> #endif #ifdef ARGO_DEBUG #define MT_XCONN 0x50 #define MT_XCLOSE 0x51 #define MT_XCONFIRM 0x52 #define MT_XDATA 0x53 #define MT_XHEADER 0x54 #else #define MT_XCONN MT_DATA #define MT_XCLOSE MT_DATA #define MT_XCONFIRM MT_DATA #define MT_XDATA MT_DATA #define MT_XHEADER MT_HEADER #endif /* ARGO_DEBUG */ #define DONTCLEAR -1 /********************************************************************* * cons.c - CONS interface to the x.25 layer * * TODO: figure out what resources we might run out of besides mbufs. * If we run out of any of them (including mbufs) close and recycle * lru x% of the connections, for some parameter x. * * There are 2 interfaces from above: * 1) from TP0: * cons CO network service * TP associates a transport connection with a network connection. * cons_output( isop, m, len, isdgm==0 ) * co_flags == 0 * 2) from TP4: * It's a datagram service, like clnp is. - even though it calls * cons_output( isop, m, len, isdgm==1 ) * it eventually goes through * cosns_output(ifp, m, dst). * TP4 permits multiplexing (reuse, possibly simultaneously) of the * network connections. * This means that many sockets (many tpcbs) may be associated with * this pklcd, hence cannot have a back ptr from pklcd to a tpcb. * co_flags & CONSF_DGM * co_socket is null since there may be many sockets that use this pklcd. * NOTE: streams would really be nice. sigh. NOTE: PVCs could be handled by config-ing a cons with an address and with the IFF_POINTTOPOINT flag on. This code would then have to skip the connection setup stuff for pt-to-pt links. *********************************************************************/ #define CONS_IFQMAXLEN 5 /* protosw pointers for getting to higher layer */ Static struct protosw *CLNP_proto; Static struct protosw *TP_proto; Static struct protosw *X25_proto; Static int issue_clear_req(); #ifndef PHASEONE extern struct ifaddr *ifa_ifwithnet(); #endif /* PHASEONE */ extern struct ifaddr *ifa_ifwithaddr(); extern struct isopcb tp_isopcb; /* chain of all TP pcbs */ Static int parse_facil(), NSAPtoDTE(), make_partial_x25_packet(); Static int FACILtoNSAP(), DTEtoNSAP(); Static struct pklcd *cons_chan_to_pcb(); #define HIGH_NIBBLE 1 #define LOW_NIBBLE 0 /* * NAME: nibble_copy() * FUNCTION and ARGUMENTS: * copies (len) nibbles from (src_octet), high or low nibble * to (dst_octet), high or low nibble, * src_nibble & dst_nibble should be: * HIGH_NIBBLE (1) if leftmost 4 bits/ most significant nibble * LOW_NIBBLE (0) if rightmost 4 bits/ least significant nibble * RETURNS: VOID */ void nibble_copy(src_octet, src_nibble, dst_octet, dst_nibble, len) register char *src_octet; register char *dst_octet; register unsigned src_nibble; register unsigned dst_nibble; int len; { register i; register unsigned dshift, sshift; IFDEBUG(D_CADDR) printf("nibble_copy ( 0x%x, 0x%x, 0x%x, 0x%x 0x%x)\n", src_octet, src_nibble, dst_octet, dst_nibble, len); ENDDEBUG #define SHIFT 0x4 dshift = dst_nibble << 2; sshift = src_nibble << 2; for (i=0; i<len; i++) { /* clear dst_nibble */ *dst_octet &= ~(0xf<< dshift); /* set dst nibble */ *dst_octet |= ( 0xf & (*src_octet >> sshift))<< dshift; dshift ^= SHIFT; sshift ^= SHIFT; src_nibble = 1-src_nibble; dst_nibble = 1-dst_nibble; src_octet += src_nibble; dst_octet += dst_nibble; } IFDEBUG(D_CADDR) printf("nibble_copy DONE\n"); ENDDEBUG } /* * NAME: nibble_match() * FUNCTION and ARGUMENTS: * compares src_octet/src_nibble and dst_octet/dst_nibble for len nibbles. * RETURNS: 0 if they differ, 1 if they are the same. */ int nibble_match( src_octet, src_nibble, dst_octet, dst_nibble, len) register char *src_octet; register char *dst_octet; register unsigned src_nibble; register unsigned dst_nibble; int len; { register i; register unsigned dshift, sshift; u_char nibble_a, nibble_b; IFDEBUG(D_CADDR) printf("nibble_match ( 0x%x, 0x%x, 0x%x, 0x%x 0x%x)\n", src_octet, src_nibble, dst_octet, dst_nibble, len); ENDDEBUG #define SHIFT 0x4 dshift = dst_nibble << 2; sshift = src_nibble << 2; for (i=0; i<len; i++) { nibble_b = ((*dst_octet)>>dshift) & 0xf; nibble_a = ( 0xf & (*src_octet >> sshift)); if (nibble_b != nibble_a) return 0; dshift ^= SHIFT; sshift ^= SHIFT; src_nibble = 1-src_nibble; dst_nibble = 1-dst_nibble; src_octet += src_nibble; dst_octet += dst_nibble; } IFDEBUG(D_CADDR) printf("nibble_match DONE\n"); ENDDEBUG return 1; } /* **************************** NET PROTOCOL cons *************************** */ /* * NAME: cons_init() * CALLED FROM: * autoconf * FUNCTION: * initialize the protocol */ cons_init() { int tp_incoming(), clnp_incoming(); CLNP_proto = pffindproto(AF_ISO, ISOPROTO_CLNP, SOCK_DGRAM); X25_proto = pffindproto(AF_ISO, ISOPROTO_X25, SOCK_STREAM); TP_proto = pffindproto(AF_ISO, ISOPROTO_TP0, SOCK_SEQPACKET); IFDEBUG(D_CCONS) printf("cons_init end : cnlp_proto 0x%x cons proto 0x%x tp proto 0x%x\n", CLNP_proto, X25_proto, TP_proto); ENDDEBUG #ifdef notdef pk_protolisten(0x81, 0, clnp_incoming); pk_protolisten(0x82, 0, esis_incoming); pk_protolisten(0x84, 0, tp8878_A_incoming); pk_protolisten(0, 0, tp_incoming); #endif } tp_incoming(lcp, m) struct pklcd *lcp; register struct mbuf *m; { register struct isopcb *isop; int cons_tpinput(); if (iso_pcballoc((struct socket *)0, &tp_isopcb)) { pk_close(lcp); return; } isop = tp_isopcb.isop_next; lcp->lcd_upper = cons_tpinput; lcp->lcd_upnext = (caddr_t)isop; lcp->lcd_send(lcp); /* Confirms call */ isop->isop_chan = (caddr_t)lcp; isop->isop_laddr = &isop->isop_sladdr; isop->isop_faddr = &isop->isop_sfaddr; DTEtoNSAP(isop->isop_laddr, &lcp->lcd_laddr); DTEtoNSAP(isop->isop_faddr, &lcp->lcd_faddr); parse_facil(lcp, isop, &(mtod(m, struct x25_packet *)->packet_data), m->m_pkthdr.len - PKHEADERLN); } cons_tpinput(lcp, m0) struct mbuf *m0; struct pklcd *lcp; { register struct isopcb *isop = (struct isopcb *)lcp->lcd_upnext; register struct x25_packet *xp; int cmd, ptype = CLEAR; if (isop == 0) return; if (m0 == 0) goto dead; switch(m0->m_type) { case MT_DATA: case MT_OOBDATA: tpcons_input(m0, isop->isop_faddr, isop->isop_laddr, (caddr_t)lcp); return; case MT_CONTROL: switch (ptype = pk_decode(mtod(m0, struct x25_packet *))) { case RR: cmd = PRC_CONS_SEND_DONE; break; case CALL_ACCEPTED: if (lcp->lcd_sb.sb_mb) lcp->lcd_send(lcp); /* XXX - fix this */ /*FALLTHROUGH*/ default: return; dead: case CLEAR: case CLEAR_CONF: lcp->lcd_upper = 0; lcp->lcd_upnext = 0; isop->isop_chan = 0; case RESET: cmd = PRC_ROUTEDEAD; } tpcons_ctlinput(cmd, isop->isop_faddr, isop); if (cmd = PRC_ROUTEDEAD && isop->isop_refcnt == 0) iso_pcbdetach(isop); } } /* * NAME: cons_connect() * CALLED FROM: * tpcons_pcbconnect() when opening a new connection. * FUNCTION anD ARGUMENTS: * Figures out which device to use, finding a route if one doesn't * already exist. * RETURN VALUE: * returns E* */ cons_connect(isop) register struct isopcb *isop; { register struct pklcd *lcp = (struct pklcd *)isop->isop_chan; register struct mbuf *m; struct ifaddr *ifa; int error; IFDEBUG(D_CCONN) printf("cons_connect(0x%x): ", isop); dump_isoaddr(isop->isop_faddr); printf("myaddr: "); dump_isoaddr(isop->isop_laddr); printf("\n" ); ENDDEBUG NSAPtoDTE(isop->isop_faddr, &lcp->lcd_faddr); lcp->lcd_upper = cons_tpinput; lcp->lcd_upnext = (caddr_t)isop; IFDEBUG(D_CCONN) printf( "calling make_partial_x25_packet( 0x%x, 0x%x, 0x%x)\n", &lcp->lcd_faddr, &lcp->lcd_laddr, isop->isop_socket->so_proto->pr_protocol); ENDDEBUG if ((error = make_partial_x25_packet(isop, lcp, m)) == 0) error = pk_connect(lcp, &lcp->lcd_faddr); return error; } /* **************************** DEVICE cons *************************** */ /* * NAME: cons_ctlinput() * CALLED FROM: * lower layer when ECN_CLEAR occurs : this routine is here * for consistency - cons subnet service calls its higher layer * through the protosw entry. * FUNCTION & ARGUMENTS: * cmd is a PRC_* command, list found in ../sys/protosw.h * copcb is the obvious. * This serves the higher-layer cons service. * NOTE: this takes 3rd arg. because cons uses it to inform itself * of things (timeouts, etc) but has a pcb instead of an address. */ cons_ctlinput(cmd, sa, copcb) int cmd; struct sockaddr *sa; register struct pklcd *copcb; { } find_error_reason( xp ) register struct x25_packet *xp; { extern u_char x25_error_stats[]; int error, cause; if (xp) { cause = 4[(char *)xp]; switch (cause) { case 0x00: case 0x80: /* DTE originated; look at the diagnostic */ error = (CONL_ERROR_MASK | cause); goto done; case 0x01: /* number busy */ case 0x81: case 0x09: /* Out of order */ case 0x89: case 0x11: /* Remot Procedure Error */ case 0x91: case 0x19: /* reverse charging accept not subscribed */ case 0x99: case 0x21: /* Incampat destination */ case 0xa1: case 0x29: /* fast select accept not subscribed */ case 0xa9: case 0x39: /* ship absent */ case 0xb9: case 0x03: /* invalid facil request */ case 0x83: case 0x0b: /* access barred */ case 0x8b: case 0x13: /* local procedure error */ case 0x93: case 0x05: /* network congestion */ case 0x85: case 0x8d: /* not obtainable */ case 0x0d: case 0x95: /* RPOA out of order */ case 0x15: /* take out bit 8 * so we don't have to have so many perror entries */ error = (CONL_ERROR_MASK | 0x100 | (cause & ~0x80)); goto done; case 0xc1: /* gateway-detected proc error */ case 0xc3: /* gateway congestion */ error = (CONL_ERROR_MASK | 0x100 | cause); goto done; } } /* otherwise, a *hopefully* valid perror exists in the e_reason field */ error = xp->packet_data; if (error = 0) { printf("Incoming PKT TYPE 0x%x with reason 0x%x\n", pk_decode(xp), cause); error = E_CO_HLI_DISCA; } done: return error; } #endif /* KERNEL */ /* * NAME: make_partial_x25_packet() * * FUNCTION and ARGUMENTS: * Makes part of an X.25 call packet, for use by x25. * (src) and (dst) are the NSAP-addresses of source and destination. * (buf) is a ptr to a buffer into which to write this partial header. * * 0 Facility length (in octets) * 1 Facility field, which is a set of: * m facil code * m+1 facil param len (for >2-byte facilities) in octets * m+2..p facil param field * q user data (protocol identification octet) * * * RETURNS: * 0 if OK * E* if failed. * * SIDE EFFECTS: * Stores facilites mbuf in X.25 control block, where the connect * routine knows where to look for it. */ #ifdef X25_1984 int cons_use_facils = 1; #else /* X25_1984 */ int cons_use_facils = 0; #endif /* X25_1984 */ int cons_use_udata = 1; /* KLUDGE FOR DEBUGGING */ Static int make_partial_x25_packet(isop, lcp) struct isopcb *isop; struct pklcd *lcp; { u_int proto; int flag; caddr_t buf; register caddr_t ptr; register int len = 0; int buflen =0; caddr_t facil_len; int oddness = 0; struct mbuf *m; IFDEBUG(D_CCONN) printf("make_partial_x25_packet(0x%x, 0x%x, 0x%x, 0x%x, 0x%x)\n", isop->isop_laddr, isop->isop_faddr, proto, m, flag); ENDDEBUG if (cons_use_udata) { if (isop->isop_x25crud_len > 0) { /* * The user specified something. Stick it in */ bcopy(isop->isop_x25crud, lcp->lcd_faddr.x25_udata, isop->isop_x25crud_len); lcp->lcd_faddr.x25_udlen = isop->isop_x25crud_len; } } if (cons_use_facils == 0) { lcp->lcd_facilities = 0; return 0; } MGETHDR(m, MT_DATA, M_WAITOK); if (m == 0) return ENOBUFS; buf = mtod(m, caddr_t); ptr = buf; /* ptr now points to facil length (len of whole facil field in OCTETS */ facil_len = ptr ++; m->m_len = 0; pk_build_facilities(m, &lcp->lcd_faddr, 0); IFDEBUG(D_CADDR) printf("make_partial calling: ptr 0x%x, len 0x%x\n", ptr, isop->isop_laddr->siso_addr.isoa_len); ENDDEBUG if (cons_use_facils) { *ptr++ = 0; /* Marker to separate X.25 facitilies from CCITT ones */ *ptr++ = 0x0f; *ptr = 0xcb; /* calling facility code */ ptr ++; ptr ++; /* leave room for facil param len (in OCTETS + 1) */ ptr ++; /* leave room for the facil param len (in nibbles), * high two bits of which indicate full/partial NSAP */ len = isop->isop_laddr->siso_addr.isoa_len; bcopy( isop->isop_laddr->siso_data, ptr, len); *(ptr-2) = len+1; /* facil param len in octets */ *(ptr-1) = len<<1; /* facil param len in nibbles */ ptr += len; IFDEBUG(D_CADDR) printf("make_partial called: ptr 0x%x, len 0x%x\n", ptr, isop->isop_faddr->siso_addr.isoa_len); ENDDEBUG *ptr = 0xc9; /* called facility code */ ptr ++; ptr ++; /* leave room for facil param len (in OCTETS + 1) */ ptr ++; /* leave room for the facil param len (in nibbles), * high two bits of which indicate full/partial NSAP */ len = isop->isop_faddr->siso_nlen; bcopy(isop->isop_faddr->siso_data, ptr, len); *(ptr-2) = len+1; /* facil param len = addr len + 1 for each of these * two length fields, in octets */ *(ptr-1) = len<<1; /* facil param len in nibbles */ ptr += len; } *facil_len = ptr - facil_len - 1; if (*facil_len > MAX_FACILITIES) return E_CO_PNA_LONG; buflen = (int)(ptr - buf); IFDEBUG(D_CDUMP_REQ) register int i; printf("ECN_CONNECT DATA buf 0x%x len %d (0x%x)\n", buf, buflen, buflen); for( i=0; i < buflen; ) { printf("+%d: %x %x %x %x %x %x %x %x\n", i, *(buf+i), *(buf+i+1), *(buf+i+2), *(buf+i+3), *(buf+i+4), *(buf+i+5), *(buf+i+6), *(buf+i+7)); i+=8; } ENDDEBUG IFDEBUG(D_CADDR) printf("make_partial returns buf 0x%x size 0x%x bytes\n", mtod(m, caddr_t), buflen); ENDDEBUG if (buflen > MHLEN) return E_CO_PNA_LONG; m->m_pkthdr.len = m->m_len = buflen; lcp->lcd_facilities = m; return 0; } /* * NAME: NSAPtoDTE() * CALLED FROM: * make_partial_x25_packet() * FUNCTION and ARGUMENTS: * get a DTE address from an NSAP-address (struct sockaddr_iso) * (dst_octet) is the octet into which to begin stashing the DTE addr * (dst_nibble) takes 0 or 1. 1 means begin filling in the DTE addr * in the high-order nibble of dst_octet. 0 means low-order nibble. * (addr) is the NSAP-address * (flag) is true if the transport suffix is to become the * last two digits of the DTE address * A DTE address is a series of ASCII digits * * A DTE address may have leading zeros. The are significant. * 1 digit per nibble, may be an odd number of nibbles. * * An NSAP-address has the DTE address in the IDI. Leading zeros are * significant. Trailing hex f indicates the end of the DTE address. * The IDI is a series of BCD digits, one per nibble. * * RETURNS * # significant digits in the DTE address, -1 if error. */ Static int NSAPtoDTE(siso, sx25) register struct sockaddr_iso *siso; register struct sockaddr_x25 *sx25; { int dtelen = -1; IFDEBUG(D_CADDR) printf("NSAPtoDTE: nsap: %s\n", clnp_iso_addrp(&siso->siso_addr)); ENDDEBUG if (siso->siso_data[0] == AFI_37) { register char *out = sx25->x25_addr; register char *in = siso->siso_data + 1; register int nibble; char *lim = siso->siso_data + siso->siso_nlen; char *olim = out+15; int lowNibble = 0; while (in < lim) { nibble = ((lowNibble ? *in++ : (*in >> 4)) & 0xf) | 0x30; lowNibble ^= 1; if (nibble != 0x3f && out < olim) *out++ = nibble; } dtelen = out - sx25->x25_addr; *out++ = 0; } else { /* error = iso_8208snparesolve(addr, x121string, &x121strlen);*/ register struct rtentry *rt; extern struct sockaddr_iso blank_siso; struct sockaddr_iso nsiso; nsiso = blank_siso; bcopy(nsiso.siso_data, siso->siso_data, nsiso.siso_nlen = siso->siso_nlen); if (rt = rtalloc1(&nsiso, 1)) { register struct sockaddr_x25 *sxx = (struct sockaddr_x25 *)rt->rt_gateway; register char *in = sxx->x25_addr; rt->rt_use--; if (sxx && sxx->x25_family == AF_CCITT) { bcopy(sx25->x25_addr, sxx->x25_addr, sizeof(sx25->x25_addr)); while (*in++) {} dtelen = in - sxx->x25_addr; } } } return dtelen; } /* * NAME: FACILtoNSAP() * CALLED FROM: * parse_facil() * FUNCTION and ARGUMENTS: * Creates and NSAP in the sockaddr_iso (addr) from the * x.25 facility found at buf - 1. * RETURNS: * 0 if ok, -1 if error. */ Static int FACILtoNSAP(addr, buf) register u_char *buf; register struct sockaddr_iso *addr; { int len_in_nibbles = *++buf & 0x3f; u_char buf_len = (len_in_nibbles + 1) >> 1;; /* in bytes */ IFDEBUG(D_CADDR) printf("FACILtoNSAP( 0x%x, 0x%x, 0x%x )\n", buf, buf_len, addr ); ENDDEBUG len_in_nibbles = *buf & 0x3f; /* despite the fact that X.25 makes us put a length in nibbles * here, the NSAP-addrs are always in full octets */ switch (*buf++ & 0xc0) { case 0: /* Entire OSI NSAP address */ bcopy((caddr_t)buf, addr->siso_data, addr->siso_nlen = buf_len); break; case 40: /* Partial OSI NSAP address, assume trailing */ if (buf_len + addr->siso_nlen > sizeof(addr->siso_addr)) return -1; bcopy((caddr_t)buf, TSEL(addr), buf_len); addr->siso_nlen += buf_len; break; default: /* Rather than blow away the connection, just ignore and use NSAP from DTE */; } return 0; } Static init_siso(siso) register struct sockaddr_iso *siso; { siso->siso_len = sizeof (*siso); siso->siso_family = AF_ISO; siso->siso_data[0] = AFI_37; siso->siso_nlen = 8; } /* * NAME: DTEtoNSAP() * CALLED FROM: * parse_facil() * FUNCTION and ARGUMENTS: * Creates a type 37 NSAP in the sockaddr_iso (addr) * from a DTE address found in a sockaddr_x25. * * RETURNS: * 0 if ok; E* otherwise. */ Static int DTEtoNSAP(addr, sx) struct sockaddr_iso *addr; struct sockaddr_x25 *sx; { register char *in, *out; register int first; int pad_tail = 0; int src_len; init_siso(addr); in = sx->x25_addr; src_len = strlen(in); addr->siso_nlen = (src_len + 3) / 2; out = addr->siso_data; *out++ = 0x37; if (src_len & 1) { pad_tail = 0xf; src_len++; } for (first = 0; src_len > 0; src_len--) { first |= 0xf & *in++; if (src_len & 1) { *out++ = first; first = 0; } else first <<= 4; } if (pad_tail) out[-1] |= 0xf; return 0; /* ok */ } /* * FUNCTION and ARGUMENTS: * parses (buf_len) bytes beginning at (buf) and finds * a called nsap, a calling nsap, and protocol identifier. * RETURNS: * 0 if ok, E* otherwise. */ Static int parse_facil(lcp, isop, buf, buf_len) caddr_t buf; u_char buf_len; /* in bytes */ struct isopcb *isop; struct pklcd *lcp; { register int i; register u_char *ptr = (u_char *)buf; u_char *ptr_lim, *facil_lim; int facil_param_len, facil_len; IFDEBUG(D_CADDR) printf("parse_facil(0x%x, 0x%x, 0x%x, 0x%x)\n", lcp, isop, buf, buf_len); dump_buf(buf, buf_len); ENDDEBUG /* find the beginnings of the facility fields in buf * by skipping over the called & calling DTE addresses * i <- # nibbles in called + # nibbles in calling * i += 1 so that an odd nibble gets rounded up to even * before dividing by 2, then divide by two to get # octets */ i = (int)(*ptr >> 4) + (int)(*ptr&0xf); i++; ptr += i >> 1; ptr ++; /* plus one for the DTE lengths byte */ /* ptr now is at facil_length field */ facil_len = *ptr++; facil_lim = ptr + facil_len; IFDEBUG(D_CADDR) printf("parse_facils: facil length is 0x%x\n", (int) facil_len); ENDDEBUG while (ptr < facil_lim) { /* get NSAP addresses from facilities */ switch (*ptr++) { case 0xcb: /* calling NSAP */ facil_param_len = FACILtoNSAP(isop->isop_faddr, ptr); break; case 0xc9: /* called NSAP */ facil_param_len = FACILtoNSAP(isop->isop_laddr, ptr); break; /* from here to default are legit cases that I ignore */ /* variable length */ case 0xca: /* end-to-end transit delay negot */ case 0xc6: /* network user id */ case 0xc5: /* charging info : indicating monetary unit */ case 0xc2: /* charging info : indicating segment count */ case 0xc1: /* charging info : indicating call duration */ case 0xc4: /* RPOA extended format */ case 0xc3: /* call redirection notification */ facil_param_len = 0; break; /* 1 octet */ case 0x0a: /* min. throughput class negot */ case 0x02: /* throughput class */ case 0x03: case 0x47: /* CUG shit */ case 0x0b: /* expedited data negot */ case 0x01: /* Fast select or reverse charging (example of intelligent protocol design) */ case 0x04: /* charging info : requesting service */ case 0x08: /* called line addr modified notification */ case 0x00: /* marker to indicate beginning of CCITT facils */ facil_param_len = 1; break; /* any 2 octets */ case 0x42: /* pkt size */ case 0x43: /* win size */ case 0x44: /* RPOA basic format */ case 0x41: /* bilateral CUG shit */ case 0x49: /* transit delay selection and indication */ facil_param_len = 2; break; default: printf( "BOGUS FACILITY CODE facil_lim 0x%x facil_len %d, ptr 0x%x *ptr 0x%x\n", facil_lim, facil_len, ptr - 1, ptr[-1]); /* facil that we don't handle return E_CO_HLI_REJI; */ switch (ptr[-1] & 0xc0) { case 0x00: facil_param_len = 1; break; case 0x40: facil_param_len = 2; break; case 0x80: facil_param_len = 3; break; case 0xc0: facil_param_len = 0; break; } } if (facil_param_len == -1) return E_CO_REG_ICDA; if (facil_param_len == 0) /* variable length */ facil_param_len = (int)*ptr++; /* 1 + the real facil param */ ptr += facil_param_len; } return 0; } #endif /* TPCONS */
the_stack_data/49532.c
//Utilizando as variaveis float #include <stdio.h> int main(void){ float num1,num2,r; num1 = 5; num2 = 2; r = num1 / num2; printf("%.2f\n",r); return 0; }
the_stack_data/141083.c
#include <stdio.h> void fred(void) { printf("yo\n"); } int test() { fred(); return 0; } /* vim: set expandtab ts=4 sw=3 sts=3 tw=80 :*/ int main () { int x; x = test(); printf("%d\n", x); return 0; }
the_stack_data/206393438.c
/** * C tcp server test example. * * License - MIT. */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/time.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> #include <arpa/inet.h> #define SERVER_IP "127.0.0.1" #define SERVER_PORT 65533 #define MAX_CONNECT 8 #define DATA_BUFLEN 128 /** * client_maxfd - Get max client fd. */ int client_maxfd(int *list, int len) { int status = list[0]; for (int i = 1; i < len; i++) { if (status < list[i]) status = list[i]; } return status; } /** * client_delete - Delete client member from list. */ int client_delete(int *list, int len, int member) { int status = -1; for (int i = 0; i < len; i++) { if (member == list[i]) { list[i] = 0; status = 0; } } return status; } /** * client_insert - Insert client member to list. */ int client_insert(int *list, int len, int member) { int status = -1; for (int i = 0; i < len; i++) { if (0 == list[i]) { list[i] = member; status = 0; break; } } return status; } /** * timeout_function - Timeout callback function. */ int timeout_function(void) { printf("Select timeout.\n"); return 0; } /** * read_from_client - Read data from client. */ int read_from_client(int *clt_list, int len, int index) { int ret = -1; char buf[DATA_BUFLEN + 1] = { 0 }; ret = read(clt_list[index], buf, DATA_BUFLEN); if (0 < ret) { buf[ret] = 0; printf("From client %d, data: %s.\n", clt_list[index], buf); } else if (0 == ret) { close(clt_list[index]); printf("Client %d exit.\n", clt_list[index]); client_delete(clt_list, len, clt_list[index]); } else { printf("Error in read.\n"); } return ret; } /** * write_to_client - Write data to client. */ int write_to_client(int *clt_list, int len, int index) { int ret = -1; ret = write(clt_list[index], "OK", 2); if (0 > ret) { printf("Error in write.\n"); } return 0; } /** * start_server - Start tcp server. */ int start_server(char *ser_ip, int ser_port) { int ser_fd = -1; struct sockaddr_in ser_addr; /* Create socket. */ ser_fd = socket(AF_INET, SOCK_STREAM, 0); if (ser_fd < 0) { printf("Error in socket.\n"); goto err_socket; } /* Binding IP and port. */ memset(&ser_addr, 0, sizeof(ser_addr)); ser_addr.sin_family = AF_INET; ser_addr.sin_port = ser_port; ser_addr.sin_addr.s_addr = inet_addr(ser_ip); if (bind(ser_fd, (struct sockaddr *)&ser_addr, sizeof(ser_addr)) < 0) { printf("Error in bind.\n"); goto err_bind; } /* Listen. */ if (listen(ser_fd, MAX_CONNECT) < 0) { printf("Error in listen.\n"); goto err_bind; } return ser_fd; err_bind: close(ser_fd); err_socket: return -1; } /** * Main function. */ int main(void) { int i = 0; int ret = -1; int serfd = -1; int cltfd = -1; int maxfd = 0; int cltfds[MAX_CONNECT] = { 0 }; char usr_buf[DATA_BUFLEN + 1] = { 0 }; struct timeval time_out; struct sockaddr_in clt_addr; memset(&clt_addr, 0, sizeof(clt_addr)); int len = sizeof(clt_addr); fd_set read_fds; fd_set write_fds; fd_set except_fds; FD_ZERO(&read_fds); FD_ZERO(&write_fds); FD_ZERO(&except_fds); /* Start tcp server. */ serfd = start_server(SERVER_IP, SERVER_PORT); if (serfd < -1) { printf("Error in start_server.\n"); goto err_start; } maxfd = serfd; printf("TCP Sever running.\n"); printf("Server ip: %s, port: %d.\n", SERVER_IP, SERVER_PORT); printf("Press CTRL+C to quit.\n\n"); while (1) { time_out.tv_sec = 60; time_out.tv_usec = 0; FD_ZERO(&read_fds); FD_ZERO(&except_fds); /** * stdin == 0, stdout == 1, stderr == 2. * Add stdin to read_fds. */ FD_SET(0, &read_fds); /* Add serfd to read_fds. */ FD_SET(serfd, &read_fds); /* Add all valid client. */ for (i = 0; i < MAX_CONNECT; i++) { if (0 < cltfds[i]) { FD_SET(cltfds[i], &read_fds); FD_SET(cltfds[i], &except_fds); } } maxfd = client_maxfd(cltfds, MAX_CONNECT); maxfd = maxfd > serfd ? maxfd : serfd; /** * MAX_CONNECT + 2 == all client + server + stdin. */ ret = select(maxfd + 1, &read_fds, &write_fds, &except_fds, &time_out); if (0 < ret) { /* New client. */ if (FD_ISSET(serfd, &read_fds)) { cltfd = accept(serfd, (struct sockaddr*)&clt_addr, (socklen_t *)&len); if (-1 < client_insert(cltfds, MAX_CONNECT, cltfd)) { FD_SET(cltfd, &read_fds); printf("Connected client ip: %s, port: %d.\n", inet_ntoa(clt_addr.sin_addr), ntohs(clt_addr.sin_port)); } } /* stdin. */ else if (FD_ISSET(0, &read_fds)) { fgets(usr_buf, DATA_BUFLEN, stdin); printf("User command: %s\n", usr_buf); if (!strncmp("quit", usr_buf, 4)) { FD_ZERO(&read_fds); FD_ZERO(&write_fds); FD_ZERO(&except_fds); printf("Server will exit.\n"); break; } } else { for (i = 0; i < MAX_CONNECT; i++) { /* Out of band data. */ if ((0 < cltfds[i]) && (FD_ISSET(cltfds[i], &except_fds))) { recv(cltfds[i], usr_buf, DATA_BUFLEN, MSG_OOB); printf("Out of band data: %s.\n", usr_buf); } /* Receive data. */ if ((0 < cltfds[i]) && (FD_ISSET(cltfds[i], &read_fds))) { ret = read_from_client(cltfds, MAX_CONNECT, i); if (0 < ret) { FD_SET(cltfds[i], &write_fds); } } /* Send data. */ if ((0 < cltfds[i]) && (FD_ISSET(cltfds[i], &write_fds))) { write_to_client(cltfds, MAX_CONNECT, i); FD_CLR(cltfds[i], &write_fds); } } } } else if (0 == ret) { timeout_function(); continue; } else { printf("Error in select.\n"); break; } } close(serfd); return 0; err_start: return -1; }
the_stack_data/170454013.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/buffererr.h> #include <openssl/err.h> #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA BUF_str_functs[] = { {ERR_PACK(ERR_LIB_BUF, BUF_F_BUF_MEM_GROW, 0), "BUF_MEM_grow"}, {ERR_PACK(ERR_LIB_BUF, BUF_F_BUF_MEM_GROW_CLEAN, 0), "BUF_MEM_grow_clean"}, {ERR_PACK(ERR_LIB_BUF, BUF_F_BUF_MEM_NEW, 0), "BUF_MEM_new"}, {0, NULL}}; static const ERR_STRING_DATA BUF_str_reasons[] = {{0, NULL}}; #endif int ERR_load_BUF_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_func_error_string(BUF_str_functs[0].error) == NULL) { ERR_load_strings_const(BUF_str_functs); ERR_load_strings_const(BUF_str_reasons); } #endif return 1; }
the_stack_data/985366.c
/* example.c -- usage example of the zlib compression library * Copyright (C) 1995-2003 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #include <stdio.h> #include "zlib.h" #ifdef STDC # include <string.h> # include <stdlib.h> #else extern void exit OF((int)); #endif #if defined(VMS) || defined(RISCOS) # define TESTFILE "foo-gz" #else # define TESTFILE "foo.gz" #endif #define CHECK_ERR(err, msg) { \ if (err != Z_OK) { \ fprintf(stderr, "%s error: %d\n", msg, err); \ exit(1); \ } \ } const char hello[] = "hello, hello!"; /* "hello world" would be more standard, but the repeated "hello" * stresses the compression code better, sorry... */ const char dictionary[] = "hello"; uLong dictId; /* Adler32 value of the dictionary */ void test_compress OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_gzio OF((const char *fname, Byte *uncompr, uLong uncomprLen)); void test_deflate OF((Byte *compr, uLong comprLen)); void test_inflate OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_large_deflate OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_large_inflate OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_flush OF((Byte *compr, uLong *comprLen)); void test_sync OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); void test_dict_deflate OF((Byte *compr, uLong comprLen)); void test_dict_inflate OF((Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)); int main OF((int argc, char *argv[])); /* =========================================================================== * Test compress() and uncompress() */ void test_compress(compr, comprLen, uncompr, uncomprLen) Byte *compr, *uncompr; uLong comprLen, uncomprLen; { int err; uLong len = (uLong)strlen(hello)+1; err = compress(compr, &comprLen, (const Bytef*)hello, len); CHECK_ERR(err, "compress"); strcpy((char*)uncompr, "garbage"); err = uncompress(uncompr, &uncomprLen, compr, comprLen); CHECK_ERR(err, "uncompress"); if (strcmp((char*)uncompr, hello)) { fprintf(stderr, "bad uncompress\n"); exit(1); } else { printf("uncompress(): %s\n", (char *)uncompr); } } /* =========================================================================== * Test read/write of .gz files */ void test_gzio(fname, uncompr, uncomprLen) const char *fname; /* compressed file name */ Byte *uncompr; uLong uncomprLen; { #ifdef NO_GZCOMPRESS fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n"); #else int err; int len = (int)strlen(hello)+1; gzFile file; z_off_t pos; file = gzopen(fname, "wb"); if (file == NULL) { fprintf(stderr, "gzopen error\n"); exit(1); } gzputc(file, 'h'); if (gzputs(file, "ello") != 4) { fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err)); exit(1); } if (gzprintf(file, ", %s!", "hello") != 8) { fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err)); exit(1); } gzseek(file, 1L, SEEK_CUR); /* add one zero byte */ gzclose(file); file = gzopen(fname, "rb"); if (file == NULL) { fprintf(stderr, "gzopen error\n"); exit(1); } strcpy((char*)uncompr, "garbage"); if (gzread(file, uncompr, (unsigned)uncomprLen) != len) { fprintf(stderr, "gzread err: %s\n", gzerror(file, &err)); exit(1); } if (strcmp((char*)uncompr, hello)) { fprintf(stderr, "bad gzread: %s\n", (char*)uncompr); exit(1); } else { printf("gzread(): %s\n", (char*)uncompr); } pos = gzseek(file, -8L, SEEK_CUR); if (pos != 6 || gztell(file) != pos) { fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n", (long)pos, (long)gztell(file)); exit(1); } if (gzgetc(file) != ' ') { fprintf(stderr, "gzgetc error\n"); exit(1); } if (gzungetc(' ', file) != ' ') { fprintf(stderr, "gzungetc error\n"); exit(1); } gzgets(file, (char*)uncompr, (int)uncomprLen); if (strlen((char*)uncompr) != 7) { /* " hello!" */ fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err)); exit(1); } if (strcmp((char*)uncompr, hello + 6)) { fprintf(stderr, "bad gzgets after gzseek\n"); exit(1); } else { printf("gzgets() after gzseek: %s\n", (char*)uncompr); } gzclose(file); #endif } /* =========================================================================== * Test deflate() with small buffers */ void test_deflate(compr, comprLen) Byte *compr; uLong comprLen; { z_stream c_stream; /* compression stream */ int err; uLong len = (uLong)strlen(hello)+1; c_stream.zalloc = (alloc_func)0; c_stream.zfree = (free_func)0; c_stream.opaque = (voidpf)0; err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); CHECK_ERR(err, "deflateInit"); c_stream.next_in = (Bytef*)hello; c_stream.next_out = compr; while (c_stream.total_in != len && c_stream.total_out < comprLen) { c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */ err = deflate(&c_stream, Z_NO_FLUSH); CHECK_ERR(err, "deflate"); } /* Finish the stream, still forcing small buffers: */ for (;;) { c_stream.avail_out = 1; err = deflate(&c_stream, Z_FINISH); if (err == Z_STREAM_END) break; CHECK_ERR(err, "deflate"); } err = deflateEnd(&c_stream); CHECK_ERR(err, "deflateEnd"); } /* =========================================================================== * Test inflate() with small buffers */ void test_inflate(compr, comprLen, uncompr, uncomprLen) Byte *compr, *uncompr; uLong comprLen, uncomprLen; { int err; z_stream d_stream; /* decompression stream */ strcpy((char*)uncompr, "garbage"); d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; d_stream.next_in = compr; d_stream.avail_in = 0; d_stream.next_out = uncompr; err = inflateInit(&d_stream); CHECK_ERR(err, "inflateInit"); while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) { d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */ err = inflate(&d_stream, Z_NO_FLUSH); if (err == Z_STREAM_END) break; CHECK_ERR(err, "inflate"); } err = inflateEnd(&d_stream); CHECK_ERR(err, "inflateEnd"); if (strcmp((char*)uncompr, hello)) { fprintf(stderr, "bad inflate\n"); exit(1); } else { printf("inflate(): %s\n", (char *)uncompr); } } /* =========================================================================== * Test deflate() with large buffers and dynamic change of compression level */ void test_large_deflate(compr, comprLen, uncompr, uncomprLen) Byte *compr, *uncompr; uLong comprLen, uncomprLen; { z_stream c_stream; /* compression stream */ int err; c_stream.zalloc = (alloc_func)0; c_stream.zfree = (free_func)0; c_stream.opaque = (voidpf)0; err = deflateInit(&c_stream, Z_BEST_SPEED); CHECK_ERR(err, "deflateInit"); c_stream.next_out = compr; c_stream.avail_out = (uInt)comprLen; /* At this point, uncompr is still mostly zeroes, so it should compress * very well: */ c_stream.next_in = uncompr; c_stream.avail_in = (uInt)uncomprLen; err = deflate(&c_stream, Z_NO_FLUSH); CHECK_ERR(err, "deflate"); if (c_stream.avail_in != 0) { fprintf(stderr, "deflate not greedy\n"); exit(1); } /* Feed in already compressed data and switch to no compression: */ deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY); c_stream.next_in = compr; c_stream.avail_in = (uInt)comprLen/2; err = deflate(&c_stream, Z_NO_FLUSH); CHECK_ERR(err, "deflate"); /* Switch back to compressing mode: */ deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED); c_stream.next_in = uncompr; c_stream.avail_in = (uInt)uncomprLen; err = deflate(&c_stream, Z_NO_FLUSH); CHECK_ERR(err, "deflate"); err = deflate(&c_stream, Z_FINISH); if (err != Z_STREAM_END) { fprintf(stderr, "deflate should report Z_STREAM_END\n"); exit(1); } err = deflateEnd(&c_stream); CHECK_ERR(err, "deflateEnd"); } /* =========================================================================== * Test inflate() with large buffers */ void test_large_inflate(compr, comprLen, uncompr, uncomprLen) Byte *compr, *uncompr; uLong comprLen, uncomprLen; { int err; z_stream d_stream; /* decompression stream */ strcpy((char*)uncompr, "garbage"); d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; d_stream.next_in = compr; d_stream.avail_in = (uInt)comprLen; err = inflateInit(&d_stream); CHECK_ERR(err, "inflateInit"); for (;;) { d_stream.next_out = uncompr; /* discard the output */ d_stream.avail_out = (uInt)uncomprLen; err = inflate(&d_stream, Z_NO_FLUSH); if (err == Z_STREAM_END) break; CHECK_ERR(err, "large inflate"); } err = inflateEnd(&d_stream); CHECK_ERR(err, "inflateEnd"); if (d_stream.total_out != 2*uncomprLen + comprLen/2) { fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out); exit(1); } else { printf("large_inflate(): OK\n"); } } /* =========================================================================== * Test deflate() with full flush */ void test_flush(compr, comprLen) Byte *compr; uLong *comprLen; { z_stream c_stream; /* compression stream */ int err; uInt len = (uInt)strlen(hello)+1; c_stream.zalloc = (alloc_func)0; c_stream.zfree = (free_func)0; c_stream.opaque = (voidpf)0; err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); CHECK_ERR(err, "deflateInit"); c_stream.next_in = (Bytef*)hello; c_stream.next_out = compr; c_stream.avail_in = 3; c_stream.avail_out = (uInt)*comprLen; err = deflate(&c_stream, Z_FULL_FLUSH); CHECK_ERR(err, "deflate"); compr[3]++; /* force an error in first compressed block */ c_stream.avail_in = len - 3; err = deflate(&c_stream, Z_FINISH); if (err != Z_STREAM_END) { CHECK_ERR(err, "deflate"); } err = deflateEnd(&c_stream); CHECK_ERR(err, "deflateEnd"); *comprLen = c_stream.total_out; } /* =========================================================================== * Test inflateSync() */ void test_sync(compr, comprLen, uncompr, uncomprLen) Byte *compr, *uncompr; uLong comprLen, uncomprLen; { int err; z_stream d_stream; /* decompression stream */ strcpy((char*)uncompr, "garbage"); d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; d_stream.next_in = compr; d_stream.avail_in = 2; /* just read the zlib header */ err = inflateInit(&d_stream); CHECK_ERR(err, "inflateInit"); d_stream.next_out = uncompr; d_stream.avail_out = (uInt)uncomprLen; inflate(&d_stream, Z_NO_FLUSH); CHECK_ERR(err, "inflate"); d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */ err = inflateSync(&d_stream); /* but skip the damaged part */ CHECK_ERR(err, "inflateSync"); err = inflate(&d_stream, Z_FINISH); if (err != Z_DATA_ERROR) { fprintf(stderr, "inflate should report DATA_ERROR\n"); /* Because of incorrect adler32 */ exit(1); } err = inflateEnd(&d_stream); CHECK_ERR(err, "inflateEnd"); printf("after inflateSync(): hel%s\n", (char *)uncompr); } /* =========================================================================== * Test deflate() with preset dictionary */ void test_dict_deflate(compr, comprLen) Byte *compr; uLong comprLen; { z_stream c_stream; /* compression stream */ int err; c_stream.zalloc = (alloc_func)0; c_stream.zfree = (free_func)0; c_stream.opaque = (voidpf)0; err = deflateInit(&c_stream, Z_BEST_COMPRESSION); CHECK_ERR(err, "deflateInit"); err = deflateSetDictionary(&c_stream, (const Bytef*)dictionary, sizeof(dictionary)); CHECK_ERR(err, "deflateSetDictionary"); dictId = c_stream.adler; c_stream.next_out = compr; c_stream.avail_out = (uInt)comprLen; c_stream.next_in = (Bytef*)hello; c_stream.avail_in = (uInt)strlen(hello)+1; err = deflate(&c_stream, Z_FINISH); if (err != Z_STREAM_END) { fprintf(stderr, "deflate should report Z_STREAM_END\n"); exit(1); } err = deflateEnd(&c_stream); CHECK_ERR(err, "deflateEnd"); } /* =========================================================================== * Test inflate() with a preset dictionary */ void test_dict_inflate(compr, comprLen, uncompr, uncomprLen) Byte *compr, *uncompr; uLong comprLen, uncomprLen; { int err; z_stream d_stream; /* decompression stream */ strcpy((char*)uncompr, "garbage"); d_stream.zalloc = (alloc_func)0; d_stream.zfree = (free_func)0; d_stream.opaque = (voidpf)0; d_stream.next_in = compr; d_stream.avail_in = (uInt)comprLen; err = inflateInit(&d_stream); CHECK_ERR(err, "inflateInit"); d_stream.next_out = uncompr; d_stream.avail_out = (uInt)uncomprLen; for (;;) { err = inflate(&d_stream, Z_NO_FLUSH); if (err == Z_STREAM_END) break; if (err == Z_NEED_DICT) { if (d_stream.adler != dictId) { fprintf(stderr, "unexpected dictionary"); exit(1); } err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary, sizeof(dictionary)); } CHECK_ERR(err, "inflate with dict"); } err = inflateEnd(&d_stream); CHECK_ERR(err, "inflateEnd"); if (strcmp((char*)uncompr, hello)) { fprintf(stderr, "bad inflate with dict\n"); exit(1); } else { printf("inflate with dictionary: %s\n", (char *)uncompr); } } /* =========================================================================== * Usage: example [output.gz [input.gz]] */ int main(argc, argv) int argc; char *argv[]; { Byte *compr, *uncompr; uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */ uLong uncomprLen = comprLen; static const char* myVersion = ZLIB_VERSION; if (zlibVersion()[0] != myVersion[0]) { fprintf(stderr, "incompatible zlib version\n"); exit(1); } else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) { fprintf(stderr, "warning: different zlib version\n"); } printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n", ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags()); compr = (Byte*)calloc((uInt)comprLen, 1); uncompr = (Byte*)calloc((uInt)uncomprLen, 1); /* compr and uncompr are cleared to avoid reading uninitialized * data and to ensure that uncompr compresses well. */ if (compr == Z_NULL || uncompr == Z_NULL) { printf("out of memory\n"); exit(1); } test_compress(compr, comprLen, uncompr, uncomprLen); test_gzio((argc > 1 ? argv[1] : TESTFILE), uncompr, uncomprLen); test_deflate(compr, comprLen); test_inflate(compr, comprLen, uncompr, uncomprLen); test_large_deflate(compr, comprLen, uncompr, uncomprLen); test_large_inflate(compr, comprLen, uncompr, uncomprLen); test_flush(compr, &comprLen); test_sync(compr, comprLen, uncompr, uncomprLen); comprLen = uncomprLen; test_dict_deflate(compr, comprLen); test_dict_inflate(compr, comprLen, uncompr, uncomprLen); free(compr); free(uncompr); return 0; }
the_stack_data/36074808.c
long op_bitand(long a, long b) { return a & b; } long op_bitor(long a, long b) { return a | b; } long op_xor(long a, long b) { return a ^ b; } long op_and(long a, long b) { return a && b; } long op_or(long a, long b) { return a || b; }
the_stack_data/176706000.c
/* * linux/fs/fat/tables.c * * Unicode escape translation tables for VFAT filename handling. * By Gordon Chaffee. * * Note: This file is used by all fat-based filesystems. */ #include <linux/kernel.h> #include <linux/string.h> #include <linux/msdos_fs.h> unsigned char fat_uni2esc[64] = { '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', '+', '-' }; unsigned char fat_esc2uni[256] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3e, 0xff, 0x3f, 0xff, 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; /* * Overrides for Emacs so that we follow Linus's tabbing style. * Emacs will notice this stuff at the end of the file and automatically * adjust the settings for this buffer only. This must remain at the end * of the file. * --------------------------------------------------------------------------- * Local variables: * c-indent-level: 8 * c-brace-imaginary-offset: 0 * c-brace-offset: -8 * c-argdecl-indent: 8 * c-label-offset: -8 * c-continued-statement-offset: 8 * c-continued-brace-offset: 0 * End: */
the_stack_data/100139247.c
extern void __VERIFIER_error(void); extern void __VERIFIER_assume(int); void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; } int __VERIFIER_nondet_int(); int main() { int n; int k = 0; int /*@ predicates { k >= i } @*/ i = 0; n = __VERIFIER_nondet_int(); while( i < n ) { i++; k++; } int /*@ predicates { k >= j } @*/ j = n; while( j > 0 ) { __VERIFIER_assert(k > 0); j--; k--; } return 0; }
the_stack_data/137805.c
#include <stdio.h> #include <stdlib.h> int main () { int idade; printf ("Favor informar a idade: \n"); scanf ("%i", &idade); if (idade < 18){ printf ("Bebidas alcoolicas estao proibidas"); } else { printf ("Bebidas alcoolicas estao liberadas"); } return 0; }
the_stack_data/215767101.c
void plus() { int i; for(i = 0; i < 10; i++) { /* Nothing to do here */ } } void minus1() { int i; for(i = 10; i--;) { /* Nothing to do here */ } } void minus2() { int i; for(i = 10; i != 0; i--) { /* Nothing to do here */ } }
the_stack_data/71338.c
/*** includes ***/ #define _DEFAULT_SOURCE #define _BSD_SOURCE #define _GNU_SOURCE #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/types.h> #include <termios.h> #include <time.h> #include <unistd.h> /*** defines ***/ #define SEDIT_VERSION "0.0.1" #define SEDIT_TAB_STOP 8 #define SEDIT_QUIT_TIMES 3 #define CTRL_KEY(k) ((k) & 0x1f) enum editorKey { BACKSPACE = 127, ARROW_LEFT = 1000, ARROW_RIGHT, ARROW_UP, ARROW_DOWN, PAGE_UP, PAGE_DOWN, HOME_KEY, END_KEY, DEL_KEY }; enum editorHighlight { HL_NORMAL = 0, HL_COMMENT, HL_MLCOMMENT, HL_KEYWORD1, HL_KEYWORD2, HL_STRING, HL_NUMBER, HL_MATCH }; #define HL_HIGHLIGHT_NUMBERS (1<<0) #define HL_HIGHLIGHT_STRINGS (1<<1) /*** data ***/ struct editorSyntax { char *filetype; char **filematch; char **keywords; char *singleline_comment_start; char *multiline_comment_start; char *multiline_comment_end; int flags; }; typedef struct erow { int idx; int size; int rsize; char *chars; char *render; unsigned char *hl; // the row highlight int hl_open_comment; } erow; struct editorConfig { int cx, cy; int rx; int rowoff; // row offset int coloff; // column offset int screenrows; int screencols; int numrows; erow *row; int dirty; char *filename; char statusmsg[80]; time_t statusmsg_time; struct editorSyntax *syntax; struct termios orig_termios; }; struct editorConfig E; /*** filetypes ***/ char *C_HL_extensions[] = {".c", ".h", ".cpp", NULL}; char *C_HL_keywords[] = { "switch", "if", "while", "for", "break", "continue", "return", "else", "struct", "union", "typedef", "static", "enum", "class", "case", "int|", "long|", "double|", "float|", "char|", "unsigned|", "signed|", "void|", NULL }; struct editorSyntax HLDB[] = { { "c", C_HL_extensions, C_HL_keywords, "//", "/*", "*/", HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS }, }; #define HLDB_ENTRIES (sizeof(HLDB) / sizeof(HLDB[0])) /*** prototypes ***/ void editorSetStatusMessage(const char *fmt, ...); void editorRefreshScreen(); char *editorPrompt(char *prompt, void (*callback)(char *, int)); /*** terminal ***/ void die(const char *s) { write(STDOUT_FILENO, "\x1b[2J", 4); // clear the entire screen write(STDOUT_FILENO, "\x1b[H", 3); // Reposition the cursor at the beginning 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 &= ~(IXON | ICRNL | BRKINT | INPCK | ISTRIP); raw.c_oflag &= ~(OPOST); raw.c_cflag |= (CS8); raw.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN); 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; } } /*** syntax highlighting ***/ int is_separator(int c) { return isspace(c) || c == '\0' || strchr(",.()+-/*=~%<>[];", c) != NULL; } void editorUpdateSyntax(erow *row) { row->hl = realloc(row->hl, row->rsize); memset(row->hl, HL_NORMAL, row->rsize); if (E.syntax == NULL) return; char **keywords = E.syntax->keywords; char *scs = E.syntax->singleline_comment_start; char *mcs = E.syntax->multiline_comment_start; char *mce = E.syntax->multiline_comment_end; int scs_len = scs ? strlen(scs) : 0; int mcs_len = mcs ? strlen(mcs) : 0; int mce_len = mcs ? strlen(mce) : 0; int prev_sep = 1; int in_string = 0; int in_comment = (row->idx > 0 && E.row[row->idx - 1].hl_open_comment); int i = 0; while (i < row->rsize) { char c = row->render[i]; unsigned char prev_hl = (i > 0) ? row->hl[i - 1] : HL_NORMAL; if (scs_len && !in_string && !in_comment) { if (!strncmp(&row->render[i], scs, scs_len)) { memset(&row->hl[i], HL_COMMENT, row->rsize - i); break; } } if (mcs_len && mce_len && !in_string) { if (in_comment) { row->hl[i] = HL_MLCOMMENT; if (!strncmp(&row->render[i], mce, mce_len)) { memset(&row->hl[i], HL_MLCOMMENT, mce_len); i += mce_len; in_comment = 0; prev_sep = 1; continue; } else { ++i; continue; } } else if (!strncmp(&row->render[i], mcs, mcs_len)) { memset(&row->hl[i], HL_MLCOMMENT, mcs_len); i += mcs_len; in_comment = 1; continue; } } if (E.syntax->flags & HL_HIGHLIGHT_STRINGS) { if (in_string) { row->hl[i] = HL_STRING; if (c == '\\' && i + 1 < row->rsize) { row->hl[i + 1] = HL_STRING; i += 2; continue; } if (c == in_string) in_string = 0; ++i; prev_sep = 1; continue; } else { if (c == '"' || c == '\'') { in_string = c; row->hl[i] = HL_STRING; ++i; continue; } } } if (E.syntax->flags & HL_HIGHLIGHT_NUMBERS) { if ((isdigit(c) && (prev_sep || prev_hl == HL_NUMBER)) || (c == '.' && prev_hl == HL_NUMBER)) { row->hl[i] = HL_NUMBER; ++i; prev_sep = 0; continue; } } if (prev_sep) { int j; for (j = 0; keywords[j]; ++j) { int klen = strlen(keywords[j]); int kw2 = keywords[j][klen - 1] == '|'; if (kw2) klen--; if (!strncmp(&row->render[i], keywords[j], klen) && is_separator(row->render[i + klen])) { memset(&row->hl[i], kw2 ? HL_KEYWORD2 : HL_KEYWORD1, klen); i += klen; break; } } if (keywords[j] != NULL) { prev_sep = 0; continue; } } prev_sep = is_separator(c); ++i; } int changed = (row->hl_open_comment != in_comment); row->hl_open_comment = in_comment; if (changed && row->idx + 1 < E.numrows) editorUpdateSyntax(&E.row[row->idx + 1]); } int editorSyntaxToColor(int hl) { switch(hl) { case HL_COMMENT: case HL_MLCOMMENT: return 36; case HL_KEYWORD1: return 33; case HL_KEYWORD2: return 32; case HL_STRING: return 35; case HL_NUMBER: return 31; case HL_MATCH: return 34; default: return 37; } } void editorSelectSyntaxHighlight() { E.syntax = NULL; if (E.filename == NULL) return; char *ext = strrchr(E.filename, '.'); for (unsigned int j = 0; j < HLDB_ENTRIES; ++j) { struct editorSyntax *s = &HLDB[j]; unsigned int i = 0; while (s->filematch[i]) { int is_ext = (s->filematch[i][0] == '.'); if ((is_ext && ext && !strcmp(ext, s->filematch[i])) || (!is_ext && strstr(E.filename, s->filematch[i]))) { E.syntax = s; int filerow; for (filerow = 0; filerow < E.numrows; ++filerow) { editorUpdateSyntax(&E.row[filerow]); } return; } ++i; } } } /*** row operations ***/ int editorRowCxToRx(erow *row, int cx) { int rx = 0; int j; for (j = 0; j < cx; ++j) { if (row->chars[j] == '\t') rx += (SEDIT_TAB_STOP - 1) - (rx % SEDIT_TAB_STOP); rx++; } return rx; } int editorRowRxToCx(erow *row, int rx) { int cur_rx = 0; int cx; for (cx = 0; cx < row->size; ++cx) { if (row->chars[cx] == '\t') cur_rx += (SEDIT_TAB_STOP - 1) - (cur_rx % SEDIT_TAB_STOP); cur_rx++; if (cur_rx > rx) return cx; } return cx; } void editorUpdateRow(erow *row) { int tabs = 0; int j; for (j = 0; j < row->size; ++j) { if (row->chars[j] == '\t') ++tabs; } free(row->render); row->render = malloc(row->size + tabs * (SEDIT_TAB_STOP - 1) + 1); int idx = 0; for (j = 0; j < row->size; ++j) { if (row->chars[j] == '\t') { row->render[idx++] = ' '; while (idx % SEDIT_TAB_STOP != 0) row->render[idx++] = ' '; } else { row->render[idx++] = row->chars[j]; } } row->render[idx] = '\0'; row->rsize = idx; editorUpdateSyntax(row); } void editorInsertRow(int at, char *s, size_t len) { if (at < 0 || at > E.numrows) return; E.row = realloc(E.row, sizeof(erow) * (E.numrows + 1)); memmove(&E.row[at + 1], &E.row[at], sizeof(erow) * (E.numrows - at)); for (int j = at + 1; j <= E.numrows; ++j) E.row[j].idx++; E.row[at].idx = at; 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.row[at].rsize = 0; E.row[at].render = NULL; E.row[at].hl = NULL; E.row[at].hl_open_comment = 0; editorUpdateRow(&E.row[at]); E.numrows++; E.dirty++; } void editorFreeRow(erow *row) { free(row->render); free(row->chars); free(row->hl); } void editorDelRow(int at) { if (at < 0 || at >= E.numrows) return; editorFreeRow(&E.row[at]); memmove(&E.row[at], &E.row[at + 1], sizeof(erow) * (E.numrows - at - 1)); for (int j = at; j < E.numrows - 1; ++j) E.row[j].idx--; E.numrows--; E.dirty++; } void editorRowInsertChar(erow *row, int at, int c) { if (at < 0 || at > row->size) at = row->size; row->chars = realloc(row->chars, row->size + 2); memmove(&row->chars[at + 1], &row->chars[at], row->size- at + 1); row->size++; row->chars[at] = c; editorUpdateRow(row); E.dirty++; } void editorRowAppendString(erow *row, char *s, size_t len) { row->chars = realloc(row->chars, row->size + len + 1); memcpy(&row->chars[row->size], s, len); row->size += len; row->chars[row->size] = '\0'; editorUpdateRow(row); E.dirty++; } void editorRowDelChar(erow *row, int at) { if (at < 0 || at >= row->size) return; memmove(&row->chars[at],&row->chars[at + 1], row->size - at); row->size--; editorUpdateRow(row); E.dirty++; } /*** editor operations ***/ void editorInsertChar(int c) { if (E.cy == E.numrows) { editorInsertRow(E.numrows, "", 0); } editorRowInsertChar(&E.row[E.cy], E.cx, c); E.cx++; } void editorDelChar() { if (E.cy == E.numrows) return; if (E.cx == 0 && E.cy == 0) return; erow *row = &E.row[E.cy]; if (E.cx > 0) { editorRowDelChar(row,E.cx - 1); E.cx--; } else { E.cx = E.row[E.cy - 1].size; editorRowAppendString(&E.row[E.cy - 1], row->chars, row->size); editorDelRow(E.cy); E.cy--; } } void editorInsertNewline() { if (E.cx == 0) { editorInsertRow(E.cy, "", 0); } else { erow *row = &E.row[E.cy]; editorInsertRow(E.cy + 1, &row->chars[E.cx], row->size - E.cx); row = &E.row[E.cy]; row->size = E.cx; row->chars[row->size] = '\0'; editorUpdateRow(row); } E.cy++; E.cx = 0; } /*** file i/o ***/ char *editorRowToString(int *buflen) { int totlen = 0; int j; for (j = 0; j < E.numrows; ++j) totlen += E.row[j].size + 1; *buflen = totlen; char *buf = malloc(totlen); char *p = buf; for (j = 0; j < E.numrows; ++j) { memcpy(p, E.row[j].chars, E.row[j].size); p += E.row[j].size; *p = '\n'; p++; } return buf; } void editorOpen(char *filename) { free(E.filename); E.filename = strdup(filename); editorSelectSyntaxHighlight(); 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--; editorInsertRow(E.numrows, line, linelen); } free(line); fclose(fp); E.dirty = 0; } void editorSave() { if (E.filename == NULL) { E.filename = editorPrompt("Save as: %s (ESC to cancel)", NULL); if (E.filename == NULL) { editorSetStatusMessage("Save aborted"); return; } editorSelectSyntaxHighlight(); } int len; char *buf = editorRowToString(&len); int fd = open(E.filename, O_RDWR | O_CREAT, 0644); if (fd != -1) { if (ftruncate(fd, len) != -1) { if (write(fd, buf, len) == len) { close(fd); free(buf); E.dirty = 0; editorSetStatusMessage("%d bytes written to disk", len); return; } } close(fd); } free(buf); editorSetStatusMessage("Can not save! T/O erroe %s", strerror(errno)); } /*** find ***/ void editorFindCallback(char *query, int key) { static int last_match = -1; static int direction = 1; static int saved_hl_line; static char *saved_hl = NULL; if (saved_hl) { memcpy(E.row[saved_hl_line].hl, saved_hl, E.row[saved_hl_line].rsize); free(saved_hl); saved_hl = NULL; } if (key == '\r' || key == '\x1b') { last_match = -1; direction = 1; return; } else if (key == ARROW_RIGHT || key == ARROW_DOWN) { direction = 1; } else if (key == ARROW_LEFT || key == ARROW_UP) { direction = -1; } else { last_match = -1; direction = 1; } if (last_match == -1) direction = 1; int current = last_match; int i; for (i = 0; i < E.numrows; ++i) { current += direction; if (current == -1) current = E.numrows - 1; else if (current == E.numrows) current = 0; erow *row = &E.row[current]; char *match = strstr(row->render, query); if (match) { last_match = current; E.cy = current; E.cx = editorRowRxToCx(row, match - row->render); E.rowoff = E.numrows; saved_hl_line = current; saved_hl = malloc(row->rsize); memcpy(saved_hl, row->hl, row->rsize); memset(&row->hl[match - row->render], HL_MATCH, strlen(query)); break; } } } void editorFind() { int saved_cx = E.cx; int saved_cy = E.cy; int saved_coloff = E.coloff; int saved_rowoff = E.rowoff; char *query = editorPrompt("Search: %s (Use ECS/Arrows/Enter)", editorFindCallback); if (query) { free(query); } else { E.cx = saved_cx; E.cy = saved_cy; E.coloff = saved_coloff; E.rowoff = saved_rowoff; } } /*** 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 editorScroll() { E.rx = 0; if (E.cy < E.numrows) { E.rx = editorRowCxToRx(&E.row[E.cy], E.cx); } if (E.cy < E.rowoff) { E.rowoff = E.cy; } if (E.cy >= E.rowoff + E.screenrows) { E.rowoff = E.cy - E.screenrows + 1; } if (E.rx < E.coloff) { E.coloff = E.rx; } if (E.rx >= E.coloff + E.screencols) { E.coloff = E.rx - E.screencols + 1; } } void editorDrawRows(struct abuf *ab) { int y; for (y = 0; y < E.screenrows; ++y) { int filerow = y + E.rowoff; if (filerow >= E.numrows) { if (E.numrows == 0 && y == E.screenrows / 3) { char welcome[80]; int welcomelen = snprintf(welcome, sizeof(welcome), "sedit text editor -- version %s", SEDIT_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[filerow].rsize - E.coloff; if (len < 0) len = 0; if (len > E.screencols) len = E.screencols; char *c = &E.row[filerow].render[E.coloff]; unsigned char *hl = &E.row[filerow].hl[E.coloff]; int current_color = -1; int j; for (j = 0; j < len; ++j) { if (iscntrl(c[j])) { char sym = (c[j] <= 26) ? '@' + c[j] : '?'; abAppend(ab, "\x1b[7m", 4); abAppend(ab, &sym, 1); abAppend(ab, "\x1b[m", 3); if (current_color != -1) { char buf[16]; int clen = snprintf(buf, sizeof(buf), "\x1b[%dm", current_color); abAppend(ab, buf, clen); } } else if (hl[j] == HL_NORMAL) { if (current_color != -1) { abAppend(ab, "\x1b[39m", 5); current_color = -1; } abAppend(ab, &c[j], 1); } else { int color = editorSyntaxToColor(hl[j]); if (color != current_color) { current_color = color; char buf[16]; int clen = snprintf(buf, sizeof(buf), "\x1b[%dm", color); abAppend(ab, buf, clen); } abAppend(ab, &c[j], 1); } } abAppend(ab, "\x1b[39m", 5); } abAppend(ab, "\x1b[K", 3); abAppend(ab, "\r\n", 2); } } void editorDrawStatusBar(struct abuf *ab) { abAppend(ab, "\x1b[7m", 4); char status[80], rstatus[80]; int len = snprintf(status, sizeof(status), "%.20s - %d lines %s", E.filename ? E.filename : "[No Name]", E.numrows, E.dirty ? "(modified)" : ""); int rlen = snprintf(rstatus, sizeof(rstatus), "%s | %d/%d", E.syntax ? E.syntax->filetype : "no ft", E.cy + 1, E.numrows); if (len > E.screencols) len = E.screencols; abAppend(ab, status, len); while (len < E.screencols) { if (E.screencols - len == rlen) { abAppend(ab, rstatus, rlen); break; } else { abAppend(ab, " ", 1); len++; } } abAppend(ab, "\x1b[m", 3); abAppend(ab, "\r\n", 2); } void editorDrawMessageBar(struct abuf *ab) { abAppend(ab, "\x1b[K", 3); int msglen = strlen(E.statusmsg); if (msglen > E.screencols) msglen = E.screencols; if (msglen && time(NULL) - E.statusmsg_time < 5) abAppend(ab, E.statusmsg, msglen); } void editorRefreshScreen() { editorScroll(); struct abuf ab = ABUF_INIT; abAppend(&ab, "\x1b[?25l", 6); // hide the cursor before rendering anything abAppend(&ab, "\x1b[H", 3); // Reposition the cursor at the beginning editorDrawRows(&ab); editorDrawStatusBar(&ab); editorDrawMessageBar(&ab); char buf[32]; snprintf(buf, sizeof(buf), "\x1b[%d;%dH", (E.cy - E.rowoff) + 1, (E.rx - E.coloff) + 1); abAppend(&ab, buf, strlen(buf)); abAppend(&ab, "\x1b[?25h", 6); // show the cursor again after refreshing the screen write(STDOUT_FILENO, ab.b, ab.len); abFree(&ab); } void editorSetStatusMessage(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vsnprintf(E.statusmsg, sizeof(E.statusmsg), fmt, ap); va_end(ap); E.statusmsg_time = time(NULL); } /*** input ***/ char *editorPrompt(char *prompt, void (*callback)(char *, int)) { size_t bufsize = 128; char *buf = malloc(bufsize); size_t buflen = 0; buf[0] = '\0'; while (1) { editorSetStatusMessage(prompt, buf); editorRefreshScreen(); int c = editorReadKey(); if (c == DEL_KEY || c == CTRL_KEY('h') || c == BACKSPACE) { if (buflen > 0) buf[--buflen] = '\0'; } else if (c == '\x1b') { editorSetStatusMessage(""); if (callback) callback(buf, c); free(buf); return NULL; } else if (c == '\r') { if (buflen != 0) { editorSetStatusMessage(""); if (callback) callback(buf, c); return buf; } } else if (!iscntrl(c) && c < 128) { if (buflen == bufsize - 1) { bufsize *= 2; buf = realloc(buf, bufsize); } buf[buflen++] = c; buf[buflen] = '\0'; } if (callback) callback(buf, c); } } void editorMoveCursor(int key) { erow *row = (E.cy >= E.numrows) ? NULL : &E.row[E.cy]; int dummy; switch (key) { case ARROW_LEFT: if (E.cx > 0) { E.cx--; } else if (E.cy > 0) { E.cy--; E.cx = E.row[E.cy].size; } break; case ARROW_RIGHT: if (row && E.cx < row->size) { E.cx++; } else if (row && E.cx == row->size) { E.cx = 0; E.cy++; } break; case ARROW_UP: if (E.cy > 0) E.cy--; break; case ARROW_DOWN: if (E.cy < E.numrows) E.cy++; break; case PAGE_UP: E.cy = E.rowoff; dummy = E.screenrows; while (dummy--) editorMoveCursor(ARROW_UP); break; case PAGE_DOWN: E.cy = E.rowoff + E.screenrows - 1; dummy = E.screenrows; while (dummy--) editorMoveCursor(ARROW_DOWN); break; case HOME_KEY: E.cx = 0; break; case END_KEY: if (row) E.cx = row->rsize; break; } // readjusting the X pos of the cursor after processing the key-press // because it might move up or down to a shorter line than it was already row = (E.cy >= E.numrows) ? NULL : &E.row[E.cy]; int rowlen = row ? row->size : 0; if (E.cx > rowlen) { E.cx = rowlen; } } void editorProcessKeypress() { static int quit_times = SEDIT_QUIT_TIMES; int c = editorReadKey(); switch (c) { case '\r': editorInsertNewline(); break; case CTRL_KEY('q'): if (E.dirty && quit_times > 0) { editorSetStatusMessage("WARNING!!! File has unsaved changes. Press Ctrl-Q %d times to quit.", quit_times); quit_times--; return; } write(STDOUT_FILENO, "\x1b[2J", 4); // clear the entire screen write(STDOUT_FILENO, "\x1b[H", 3); // Reposition the cursor at the beginning exit(0); break; case CTRL_KEY('s'): editorSave(); break; case CTRL_KEY('f'): editorFind(); break; case BACKSPACE: case CTRL_KEY('h'): case DEL_KEY: if (c == DEL_KEY) editorMoveCursor(ARROW_RIGHT); editorDelChar(); break; case HOME_KEY: case END_KEY: case PAGE_UP: case PAGE_DOWN: case ARROW_UP: case ARROW_DOWN: case ARROW_LEFT: case ARROW_RIGHT: editorMoveCursor(c); break; case CTRL_KEY('l'): case '\x1b': break; default: editorInsertChar(c); break; } quit_times = SEDIT_QUIT_TIMES; } /*** init ***/ void initEditor() { E.cx = 0; E.cy = 0; E.rx = 0; E.rowoff = 0; E.coloff = 0; E.numrows = 0; E.row = NULL; E.dirty = 0; E.filename = NULL; E.statusmsg[0] = '\0'; E.statusmsg_time = 0; E.syntax = NULL; if (getWindowSize(&E.screenrows, &E.screencols) == -1) die("getWindowSize"); E.screenrows -= 2; // decrease by two lines to make space for the status bar } int main(int argc, char *argv[]) { enableRawMode(); initEditor(); if (argc >= 2) { editorOpen(argv[1]); } editorSetStatusMessage("HELP: Ctrl-S = save | Ctrl-Q = quit | Ctrl-F = find"); while (1) { editorRefreshScreen(); editorProcessKeypress(); } return 0; }
the_stack_data/59468.c
#include <stdio.h> #include <stdlib.h> #include <math.h> int * allocaInt(){ int * p = (int *)malloc(sizeof(int)); return p; } void printInt(int *i1, int *i2){ printf("%d\t%d\n",*i1, *i2); } void soluzioneEquazione(int a, int b, int c) { double sol1 = ((-b)+(sqrt(pow(b,2)-(4*a*c)))) / 2*a; double sol2 = ((-b)+(sqrt(pow(b,2)-(4*a*c)))) / 2*a; printf("sol1 = %0.3lf\tsol2 = %0.3lf\n",sol1,sol2); } int main(){ printf("%d\n",*(allocaInt())); int i, j; i = 10; j = 20; printInt(&i,&j); soluzioneEquazione(1, 0, -4); return 0; }
the_stack_data/215768117.c
#include <stdio.h> /* print Fahrenheit-Celsius table for fahr = 0, 20, ..., 300 */ main() { int fahr, celsius; int lower, upper, step; lower = 0; /* lower limit of temperature table */ upper = 300; /* upper limit */ step = 20; /* step size */ fahr = lower; while (fahr <= upper) { celsius = 5 * (fahr-32) / 9; printf("%3d %6d\n", fahr, celsius); fahr = fahr + step; } }
the_stack_data/125140638.c
/* { dg-do compile } */ /* { dg-require-effective-target vect_int } */ _Bool a[1024]; _Bool b[1024]; _Bool c[1024]; void foo (void) { unsigned i; for (i = 0; i < 1024; ++i) a[i] = b[i] | c[i]; } /* { dg-final { scan-tree-dump "vectorized 1 loops" "vect" } } */