file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/65573.c
int main() { return sizeof(struct { int a; char b; }); }
the_stack_data/117327169.c
#include<stdio.h> #include<string.h> int main() { int i,j,n; char str[100][100],s[100]; printf("Enter number of names : "); scanf("%d",&n); printf("Enter names in any order:\n"); for(i=0;i<n;i++) {scanf("%s",str[i]);} for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(strcmp(str[i],str[j])>0) { strcpy(s,str[i]); strcpy(str[i],str[j]); strcpy(str[j],s); } } } printf("The sorted order of names are:\n"); for(i=0;i<n;i++) {printf("%s\n",str[i]);} return 0; }
the_stack_data/725930.c
/** Lab work week 4 Programming Question 4, program written in C language that Make a copy of Q2 above but this time, use your function to change the contents of the array, i.e. multiply each number in the array by 2. When your function has finished and your program continues in your main(), print the contents of your array in your main() In the main function ask user to enter 5 numbers and store numbers into the array Pass the array to the function and multiply each element in the array by 2 Created by Iosif Dobos, C16735789 @copyright all rights are reserved Date: 14.02.2017 */ #include <stdio.h> #include <stdlib.h> #define SIZE 5 //function prototype void my_arr(int []); int main() { int my_array[SIZE]; int i; //asking user to fill data into the array printf("Please enter data into the array: \n"); for(i=0; i<SIZE; i++) { scanf("%d", &my_array[i]); } //call function my_array and try to access the content of the array //and change the value my_arr( my_array); //display the new array value for (i=0; i<SIZE; i++) { printf("%d\t", my_array[i]); } return 0; } //implement function my_arr() void my_arr(int array[SIZE]) { int i; for (i=0; i<SIZE; i++) { array[i]= array[i]*2; } }
the_stack_data/70449492.c
void mx_printchar(char c); void mx_printint(int n); void mx_printint(int n){ if(n < 0){ mx_printchar('-'); n *= -1; } if(n < 10) mx_printchar('0' + n); else{ int l = 0; int t = n; for(;t;t/=10) l++; int d = 1; for(int i = 1; i < l; i++) d *= 10; mx_printchar('0' + (( n- n % d) / d)); mx_printint(n % d); } } void mx_printchar(char c){ write(1, &c, 1); }
the_stack_data/85035.c
#include <sys/types.h> #include <stddef.h> #undef KEY #if defined(__i386) # define KEY '_','_','i','3','8','6' #elif defined(__x86_64) # define KEY '_','_','x','8','6','_','6','4' #elif defined(__ppc__) # define KEY '_','_','p','p','c','_','_' #elif defined(__ppc64__) # define KEY '_','_','p','p','c','6','4','_','_' #elif defined(__aarch64__) # define KEY '_','_','a','a','r','c','h','6','4','_','_' #elif defined(__ARM_ARCH_7A__) # define KEY '_','_','A','R','M','_','A','R','C','H','_','7','A','_','_' #elif defined(__ARM_ARCH_7S__) # define KEY '_','_','A','R','M','_','A','R','C','H','_','7','S','_','_' #endif #define SIZE (sizeof(size_t)) char info_size[] = {'I', 'N', 'F', 'O', ':', 's','i','z','e','[', ('0' + ((SIZE / 10000)%10)), ('0' + ((SIZE / 1000)%10)), ('0' + ((SIZE / 100)%10)), ('0' + ((SIZE / 10)%10)), ('0' + (SIZE % 10)), ']', #ifdef KEY ' ','k','e','y','[', KEY, ']', #endif '\0'}; #ifdef __CLASSIC_C__ int main(argc, argv) int argc; char *argv[]; #else int main(int argc, char *argv[]) #endif { int require = 0; require += info_size[argc]; (void)argv; return require; }
the_stack_data/231392890.c
/* Copyright (c) 2017-2020, Michael Santos <[email protected]> * * 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. */ #ifdef RESTRICT_PROCESS_seccomp #include <errno.h> #include <linux/audit.h> #include <linux/filter.h> #include <linux/seccomp.h> #include <stddef.h> #include <sys/prctl.h> #include <sys/syscall.h> #include "xmppipe.h" /* macros from openssh-7.2/restrict_process-seccomp-filter.c */ /* Linux seccomp_filter restrict_process */ #define SECCOMP_FILTER_FAIL SECCOMP_RET_KILL /* Use a signal handler to emit violations when debugging */ #ifdef RESTRICT_PROCESS_SECCOMP_FILTER_DEBUG #undef SECCOMP_FILTER_FAIL #define SECCOMP_FILTER_FAIL SECCOMP_RET_TRAP #endif /* RESTRICT_PROCESS_SECCOMP_FILTER_DEBUG */ /* Simple helpers to avoid manual errors (but larger BPF programs). */ #define SC_DENY(_nr, _errno) \ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, __NR_##_nr, 0, 1) \ , BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ERRNO | (_errno)) #define SC_ALLOW(_nr) \ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, __NR_##_nr, 0, 1) \ , BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ALLOW) #define SC_ALLOW_ARG(_nr, _arg_nr, _arg_val) \ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, __NR_##_nr, 0, 4) \ , /* load first syscall argument */ \ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, \ offsetof(struct seccomp_data, args[(_arg_nr)])), \ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, (_arg_val), 0, 1), \ BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ALLOW), /* reload syscall number; \ all rules expect it in \ accumulator */ \ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, offsetof(struct seccomp_data, nr)) /* * http://outflux.net/teach-seccomp/ * https://github.com/gebi/teach-seccomp * */ #define syscall_nr (offsetof(struct seccomp_data, nr)) #define arch_nr (offsetof(struct seccomp_data, arch)) #if defined(__i386__) #define SECCOMP_AUDIT_ARCH AUDIT_ARCH_I386 #elif defined(__x86_64__) #define SECCOMP_AUDIT_ARCH AUDIT_ARCH_X86_64 #elif defined(__arm__) #define SECCOMP_AUDIT_ARCH AUDIT_ARCH_ARM #elif defined(__aarch64__) #define SECCOMP_AUDIT_ARCH AUDIT_ARCH_AARCH64 #else #warning "seccomp: unsupported platform" #define SECCOMP_AUDIT_ARCH 0 #endif int restrict_process_init(xmppipe_state_t *state) { struct sock_filter filter[] = { /* Ensure the syscall arch convention is as expected. */ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, offsetof(struct seccomp_data, arch)), BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, SECCOMP_AUDIT_ARCH, 1, 0), BPF_STMT(BPF_RET + BPF_K, SECCOMP_FILTER_FAIL), /* Load the syscall number for checking. */ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, offsetof(struct seccomp_data, nr)), /* Syscalls to allow */ /* dns */ #ifdef __NR_madvise SC_ALLOW(madvise), #endif #ifdef __NR_socket SC_ALLOW(socket), #endif #ifdef __NR_recvfrom SC_ALLOW(recvfrom), #endif #ifdef __NR_recv SC_ALLOW(recv), #endif #ifdef __NR_recvmsg SC_ALLOW(recvmsg), #endif #ifdef __NR_sendto SC_ALLOW(sendto), #endif #ifdef __NR_send SC_ALLOW(send), #endif #ifdef __NR_sendmsg SC_ALLOW(sendmsg), #endif #ifdef __NR_sendmmsg SC_ALLOW(sendmmsg), #endif #ifdef __NR_connect SC_ALLOW(connect), #endif #ifdef __NR_bind SC_ALLOW(bind), #endif #ifdef __NR_stat SC_ALLOW(stat), #endif #ifdef __NR_stat64 SC_ALLOW(stat64), #endif #ifdef __NR_uname SC_ALLOW(uname), #endif /* /etc/resolv.conf */ #ifdef __NR_open SC_ALLOW(open), #endif #ifdef __NR_openat SC_ALLOW(openat), #endif #ifdef __NR_close SC_ALLOW(close), #endif /* inet */ #ifdef __NR_getpeername SC_ALLOW(getpeername), #endif #ifdef __NR_getsockname SC_ALLOW(getsockname), #endif #ifdef __NR_setsockopt SC_ALLOW(setsockopt), #endif #ifdef __NR_getsockopt SC_ALLOW(getsockopt), #endif #ifdef __NR_lseek SC_ALLOW(lseek), #endif #ifdef __NR__llseek SC_ALLOW(_llseek), #endif #ifdef __NR_newfstatat SC_ALLOW(newfstatat), #endif /* uuid */ #ifdef __NR_gettimeofday SC_ALLOW(gettimeofday), #endif #ifdef __NR_getpid SC_ALLOW(getpid), #endif #ifdef __NR_brk SC_ALLOW(brk), #endif #ifdef __NR_clock_gettime SC_ALLOW(clock_gettime), #endif #ifdef __NR_exit_group SC_ALLOW(exit_group), #endif #ifdef __NR_fcntl SC_ALLOW(fcntl), #endif #ifdef __NR_fcntl64 SC_ALLOW(fcntl64), #endif #ifdef __NR_fstat SC_ALLOW(fstat), #endif #ifdef __NR_fstat64 SC_ALLOW(fstat64), #endif #ifdef __NR_getrandom SC_ALLOW(getrandom), #endif #ifdef __NR_getppid SC_ALLOW(getppid), #endif #ifdef __NR_gettid SC_ALLOW(gettid), #endif #ifdef __NR_gettimeofday SC_ALLOW(gettimeofday), #endif #ifdef __NR_getuid SC_ALLOW(getuid), #endif #ifdef __NR_getuid32 SC_ALLOW(getuid32), #endif #ifdef __NR_geteuid SC_ALLOW(geteuid), #endif #ifdef __NR_getgid SC_ALLOW(getgid), #endif #ifdef __NR_getegid SC_ALLOW(getegid), #endif #ifdef __NR_ioctl SC_ALLOW(ioctl), #endif #ifdef __NR_mmap SC_ALLOW(mmap), #endif #ifdef __NR_munmap SC_ALLOW(munmap), #endif #ifdef __NR_mprotect SC_ALLOW(mprotect), #endif #ifdef __NR_poll SC_ALLOW(poll), #endif #ifdef __NR_ppoll SC_ALLOW(ppoll), #endif #ifdef __NR_read SC_ALLOW(read), #endif #ifdef __NR__newselect SC_ALLOW(_newselect), #endif #ifdef __NR_select SC_ALLOW(select), #endif #ifdef __NR_pselect6 SC_ALLOW(pselect6), #endif #ifdef __NR_stat SC_ALLOW(stat), #endif #ifdef __NR_stat64 SC_ALLOW(stat64), #endif #ifdef __NR_write SC_ALLOW(write), #endif #ifdef __NR_writev SC_ALLOW(writev), #endif #ifdef __NR_mmap SC_ALLOW(mmap), #endif #ifdef __NR_mmap2 SC_ALLOW(mmap2), #endif #ifdef __NR_access SC_ALLOW(access), #endif #ifdef __NR_faccessat SC_ALLOW(faccessat), #endif #ifdef __NR_lseek SC_ALLOW(lseek), #endif #ifdef __NR_prctl SC_ALLOW(prctl), #endif #ifdef __NR_futex SC_ALLOW(futex), #endif #ifdef __NR_sysinfo SC_ALLOW(sysinfo), #endif #ifdef __NR_restart_syscall SC_ALLOW(restart_syscall), #endif /* Default deny */ BPF_STMT(BPF_RET + BPF_K, SECCOMP_FILTER_FAIL)}; struct sock_fprog prog = { .len = (unsigned short)(sizeof(filter) / sizeof(filter[0])), .filter = filter, }; if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) return -1; return prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog); } int restrict_process_stdin(xmppipe_state_t *state) { struct sock_filter filter[] = { /* Ensure the syscall arch convention is as expected. */ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, offsetof(struct seccomp_data, arch)), BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, SECCOMP_AUDIT_ARCH, 1, 0), BPF_STMT(BPF_RET + BPF_K, SECCOMP_FILTER_FAIL), /* Load the syscall number for checking. */ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, offsetof(struct seccomp_data, nr)), /* Syscalls to non-fatally deny */ #ifdef __NR_open SC_DENY(open, EACCES), #endif #ifdef __NR_close SC_DENY(close, EBADF), #endif /* Syscalls to allow */ #ifdef __NR_madvise SC_ALLOW(madvise), #endif #ifdef __NR_pselect6 SC_ALLOW(pselect6), #endif #ifdef __NR_brk SC_ALLOW(brk), #endif #ifdef __NR_clock_gettime SC_ALLOW(clock_gettime), #endif #ifdef __NR_exit_group SC_ALLOW(exit_group), #endif #ifdef __NR_fcntl SC_ALLOW(fcntl), #endif #ifdef __NR_fcntl64 SC_ALLOW(fcntl64), #endif #ifdef __NR_fstat SC_ALLOW(fstat), #endif #ifdef __NR_fstat64 SC_ALLOW(fstat64), #endif #ifdef __NR_getppid SC_ALLOW(getppid), #endif #ifdef __NR_gettid SC_ALLOW(gettid), #endif #ifdef __NR_gettimeofday SC_ALLOW(gettimeofday), #endif #ifdef __NR_getuid SC_ALLOW(getuid), #endif #ifdef __NR_getuid32 SC_ALLOW(getuid32), #endif #ifdef __NR_ioctl SC_ALLOW(ioctl), #endif #ifdef __NR_mmap SC_ALLOW(mmap), #endif #ifdef __NR_munmap SC_ALLOW(munmap), #endif #ifdef __NR_mprotect SC_ALLOW(mprotect), #endif #ifdef __NR_poll SC_ALLOW(poll), #endif #ifdef __NR_ppoll SC_ALLOW(ppoll), #endif #ifdef __NR_read SC_ALLOW(read), #endif #ifdef __NR__newselect SC_ALLOW(_newselect), #endif #ifdef __NR_select SC_ALLOW(select), #endif #ifdef __NR_stat SC_ALLOW(stat), #endif #ifdef __NR_stat64 SC_ALLOW(stat64), #endif #ifdef __NR_write SC_ALLOW(write), #endif #ifdef __NR_writev SC_ALLOW(writev), #endif #ifdef __NR_restart_syscall SC_ALLOW(restart_syscall), #endif /* Default deny */ BPF_STMT(BPF_RET + BPF_K, SECCOMP_FILTER_FAIL)}; struct sock_fprog prog = { .len = (unsigned short)(sizeof(filter) / sizeof(filter[0])), .filter = filter, }; return prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog); } #endif
the_stack_data/57949195.c
/* minimal_gpio.c 2019-07-03 Public Domain Original Site: http://abyz.me.uk/rpi/pigpio/examples.html */ #include <stdio.h> #include <unistd.h> #include <stdint.h> #include <string.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> static volatile uint32_t piPeriphBase = 0x20000000; static volatile int pi_is_2711 = 0; #define SYST_BASE (piPeriphBase + 0x003000) #define DMA_BASE (piPeriphBase + 0x007000) #define CLK_BASE (piPeriphBase + 0x101000) #define GPIO_BASE (piPeriphBase + 0x200000) #define UART0_BASE (piPeriphBase + 0x201000) #define PCM_BASE (piPeriphBase + 0x203000) #define SPI0_BASE (piPeriphBase + 0x204000) #define I2C0_BASE (piPeriphBase + 0x205000) #define PWM_BASE (piPeriphBase + 0x20C000) #define BSCS_BASE (piPeriphBase + 0x214000) #define UART1_BASE (piPeriphBase + 0x215000) #define I2C1_BASE (piPeriphBase + 0x804000) #define I2C2_BASE (piPeriphBase + 0x805000) #define DMA15_BASE (piPeriphBase + 0xE05000) #define DMA_LEN 0x1000 /* allow access to all channels */ #define CLK_LEN 0xA8 #define GPIO_LEN 0xF4 #define SYST_LEN 0x1C #define PCM_LEN 0x24 #define PWM_LEN 0x28 #define I2C_LEN 0x1C #define BSCS_LEN 0x40 #define GPSET0 7 #define GPSET1 8 #define GPCLR0 10 #define GPCLR1 11 #define GPLEV0 13 #define GPLEV1 14 #define GPPUD 37 #define GPPUDCLK0 38 #define GPPUDCLK1 39 /* BCM2711 has different pulls */ #define GPPUPPDN0 57 #define GPPUPPDN1 58 #define GPPUPPDN2 59 #define GPPUPPDN3 60 #define SYST_CS 0 #define SYST_CLO 1 #define SYST_CHI 2 static volatile uint32_t *gpioReg = MAP_FAILED; static volatile uint32_t *systReg = MAP_FAILED; static volatile uint32_t *bscsReg = MAP_FAILED; #define PI_BANK (gpio>>5) #define PI_BIT (1<<(gpio&0x1F)) /* gpio modes. */ #define PI_INPUT 0 #define PI_OUTPUT 1 #define PI_ALT0 4 #define PI_ALT1 5 #define PI_ALT2 6 #define PI_ALT3 7 #define PI_ALT4 3 #define PI_ALT5 2 void gpioSetMode(unsigned gpio, unsigned mode) { int reg, shift; reg = gpio/10; shift = (gpio%10) * 3; gpioReg[reg] = (gpioReg[reg] & ~(7<<shift)) | (mode<<shift); } int gpioGetMode(unsigned gpio) { int reg, shift; reg = gpio/10; shift = (gpio%10) * 3; return (*(gpioReg + reg) >> shift) & 7; } /* Values for pull-ups/downs off, pull-down and pull-up. */ #define PI_PUD_OFF 0 #define PI_PUD_DOWN 1 #define PI_PUD_UP 2 void gpioSetPullUpDown(unsigned gpio, unsigned pud) { int shift = (gpio & 0xf) << 1; uint32_t bits; uint32_t pull = 0; if (pi_is_2711) { switch (pud) { case PI_PUD_OFF: pull = 0; break; case PI_PUD_UP: pull = 1; break; case PI_PUD_DOWN: pull = 2; break; } bits = *(gpioReg + GPPUPPDN0 + (gpio>>4)); bits &= ~(3 << shift); bits |= (pull << shift); *(gpioReg + GPPUPPDN0 + (gpio>>4)) = bits; } else { *(gpioReg + GPPUD) = pud; usleep(20); *(gpioReg + GPPUDCLK0 + PI_BANK) = PI_BIT; usleep(20); *(gpioReg + GPPUD) = 0; *(gpioReg + GPPUDCLK0 + PI_BANK) = 0; } } int gpioRead(unsigned gpio) { if ((*(gpioReg + GPLEV0 + PI_BANK) & PI_BIT) != 0) return 1; else return 0; } void gpioWrite(unsigned gpio, unsigned level) { if (level == 0) *(gpioReg + GPCLR0 + PI_BANK) = PI_BIT; else *(gpioReg + GPSET0 + PI_BANK) = PI_BIT; } void gpioTrigger(unsigned gpio, unsigned pulseLen, unsigned level) { if (level == 0) *(gpioReg + GPCLR0 + PI_BANK) = PI_BIT; else *(gpioReg + GPSET0 + PI_BANK) = PI_BIT; usleep(pulseLen); if (level != 0) *(gpioReg + GPCLR0 + PI_BANK) = PI_BIT; else *(gpioReg + GPSET0 + PI_BANK) = PI_BIT; } /* Bit (1<<x) will be set if gpio x is high. */ uint32_t gpioReadBank1(void) { return (*(gpioReg + GPLEV0)); } uint32_t gpioReadBank2(void) { return (*(gpioReg + GPLEV1)); } /* To clear gpio x bit or in (1<<x). */ void gpioClearBank1(uint32_t bits) { *(gpioReg + GPCLR0) = bits; } void gpioClearBank2(uint32_t bits) { *(gpioReg + GPCLR1) = bits; } /* To set gpio x bit or in (1<<x). */ void gpioSetBank1(uint32_t bits) { *(gpioReg + GPSET0) = bits; } void gpioSetBank2(uint32_t bits) { *(gpioReg + GPSET1) = bits; } unsigned gpioHardwareRevision(void) { static unsigned rev = 0; FILE *filp; char buf[512]; char term; int chars=4; /* number of chars in revision string */ filp = fopen ("/proc/cpuinfo", "r"); if (filp != NULL) { while (fgets(buf, sizeof(buf), filp) != NULL) { if (!strncasecmp("revision", buf, 8)) { if (sscanf(buf+strlen(buf)-(chars+1), "%x%c", &rev, &term) == 2) { if (term != '\n') rev = 0; else rev &= 0xFFFFFF; /* mask out warranty bit */ } } } fclose(filp); } filp = fopen("/proc/device-tree/soc/ranges" , "rb"); if (filp != NULL) { if (fread(buf, 1, sizeof(buf), filp) >= 8) { piPeriphBase = buf[4]<<24 | buf[5]<<16 | buf[6]<<8 | buf[7]; if (!piPeriphBase) piPeriphBase = buf[8]<<24 | buf[9]<<16 | buf[10]<<8 | buf[11]; if (piPeriphBase == 0xFE000000) pi_is_2711 = 1; } fclose(filp); } return rev; } /* Returns the number of microseconds after system boot. Wraps around after 1 hour 11 minutes 35 seconds. */ uint32_t gpioTick(void) { return systReg[SYST_CLO]; } /* Map in registers. */ static uint32_t * initMapMem(int fd, uint32_t addr, uint32_t len) { return (uint32_t *) mmap(0, len, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED|MAP_LOCKED, fd, addr); } int gpioInitialise(void) { int fd; gpioHardwareRevision(); /* sets rev and peripherals base address */ fd = open("/dev/mem", O_RDWR | O_SYNC) ; if (fd < 0) { fprintf(stderr, "This program needs root privileges. Try using sudo\n"); return -1; } gpioReg = initMapMem(fd, GPIO_BASE, GPIO_LEN); systReg = initMapMem(fd, SYST_BASE, SYST_LEN); bscsReg = initMapMem(fd, BSCS_BASE, BSCS_LEN); close(fd); if ((gpioReg == MAP_FAILED) || (systReg == MAP_FAILED) || (bscsReg == MAP_FAILED)) { fprintf(stderr, "Bad, mmap failed\n"); return -1; } return 0; }
the_stack_data/168892920.c
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2016 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. END_LEGAL */ /* * This test prints the application's blocked signal mask at various points. * By comparing a native run with a run under Pin, we can verify that Pin emulates * the signal mask correctly. */ #include <stdio.h> #include <stdlib.h> #include <signal.h> #ifdef TARGET_ANDROID #include "android_ucontext.h" #else #include <sys/ucontext.h> #endif #if defined(TARGET_MAC) || (TARGET_ANDROID) #define MAXMASK 32 #else #define MAXMASK 64 #endif static void Handle(int); static void PrintCurrentMask(const char *); static void PrintMask(const char *, sigset_t *); int main() { struct sigaction act; sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGSTOP); sigaddset(&mask, SIGFPE); if (sigprocmask(SIG_SETMASK, &mask, 0) != 0) { fprintf(stderr, "unable to set blocked signal mask\n"); return 1; } PrintCurrentMask("Initial: "); act.sa_handler = Handle; act.sa_flags = SA_NODEFER; sigemptyset(&act.sa_mask); sigaddset(&act.sa_mask, SIGSEGV); sigaddset(&act.sa_mask, SIGHUP); sigaddset(&act.sa_mask, SIGKILL); if (sigaction(SIGUSR1, &act, 0) != 0) { fprintf(stderr, "Unable to set USR1 handler\n"); return 1; } act.sa_flags = 0; if (sigaction(SIGUSR2, &act, 0) != 0) { fprintf(stderr, "Unable to set USR2 handler\n"); return 1; } raise(SIGUSR1); PrintCurrentMask("After USR1: "); raise(SIGUSR2); PrintCurrentMask("After USR2: "); sigemptyset(&act.sa_mask); if (sigaction(SIGUSR1, 0, &act) != 0) { fprintf(stderr, "Unable to get USR1 hander\n"); return 1; } PrintMask("USR1 Blocks: ", &act.sa_mask); sigemptyset(&act.sa_mask); if (sigaction(SIGUSR2, 0, &act) != 0) { fprintf(stderr, "Unable to get USR2 hander\n"); return 1; } PrintMask("USR2 Blocks: ", &act.sa_mask); return 0; } static void Handle(int sig) { if (sig == SIGUSR1) PrintCurrentMask("USR1 handler: "); else if (sig == SIGUSR2) PrintCurrentMask("USR2 handler: "); else { fprintf(stderr, "Unexpected signal %d\n", sig); exit(1); } } static void PrintCurrentMask(const char *prefix) { sigset_t mask; if (sigprocmask(SIG_SETMASK, 0, &mask) == 0) PrintMask(prefix, &mask); else printf("%s[ERROR]\n", prefix); } static void PrintMask(const char *prefix, sigset_t *mask) { int sig; int first; first = 1; printf("%s[", prefix); for (sig = 1; sig < MAXMASK; sig++) { if (sigismember(mask, sig)) { if (!first) printf(" "); first = 0; printf("%d", sig); } } printf("]\n"); }
the_stack_data/67820.c
/*- * Copyright (c) 1986, 1988, 1991, 1993 * The Regents of the University of California. All rights reserved. * (c) UNIX System Laboratories, Inc. * All or some portions of this file are derived from material licensed * to the University of California by American Telephone and Telegraph * Co. or Unix System Laboratories, Inc. and are reproduced herein with * the permission of UNIX System Laboratories, Inc. * * 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. * 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. * * @(#)subr_prf.c 8.3 (Berkeley) 1/21/94 */ /* * Portions copyright (c) 2009-2018, ARM Limited and Contributors. * All rights reserved. */ #include <stdio.h> #include <stdint.h> #include <stdarg.h> #include <stddef.h> #include <string.h> #include <ctype.h> typedef unsigned char u_char; typedef unsigned int u_int; typedef int64_t quad_t; typedef uint64_t u_quad_t; typedef unsigned long u_long; typedef unsigned short u_short; static inline int imax(int a, int b) { return (a > b ? a : b); } /* * Note that stdarg.h and the ANSI style va_start macro is used for both * ANSI and traditional C compilers. */ #define TOCONS 0x01 #define TOTTY 0x02 #define TOLOG 0x04 /* Max number conversion buffer length: a u_quad_t in base 2, plus NUL byte. */ #define MAXNBUF (sizeof(intmax_t) * 8 + 1) struct putchar_arg { int flags; int pri; struct tty *tty; char *p_bufr; size_t n_bufr; char *p_next; size_t remain; }; struct snprintf_arg { char *str; size_t remain; }; extern int log_open; static char *ksprintn(char *nbuf, uintmax_t num, int base, int *len, int upper); static void snprintf_func(int ch, void *arg); static int kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap); int vsnprintf(char *str, size_t size, const char *format, va_list ap); static char const hex2ascii_data[] = "0123456789abcdefghijklmnopqrstuvwxyz"; #define hex2ascii(hex) (hex2ascii_data[hex]) /* * Scaled down version of sprintf(3). */ int sprintf(char *buf, const char *cfmt, ...) { int retval; va_list ap; va_start(ap, cfmt); retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap); buf[retval] = '\0'; va_end(ap); return (retval); } /* * Scaled down version of vsprintf(3). */ int vsprintf(char *buf, const char *cfmt, va_list ap) { int retval; retval = kvprintf(cfmt, NULL, (void *)buf, 10, ap); buf[retval] = '\0'; return (retval); } /* * Scaled down version of snprintf(3). */ int snprintf(char *str, size_t size, const char *format, ...) { int retval; va_list ap; va_start(ap, format); retval = vsnprintf(str, size, format, ap); va_end(ap); return(retval); } /* * Scaled down version of vsnprintf(3). */ int vsnprintf(char *str, size_t size, const char *format, va_list ap) { struct snprintf_arg info; int retval; info.str = str; info.remain = size; retval = kvprintf(format, snprintf_func, &info, 10, ap); if (info.remain >= 1) *info.str++ = '\0'; return (retval); } static void snprintf_func(int ch, void *arg) { struct snprintf_arg *const info = arg; if (info->remain >= 2) { *info->str++ = ch; info->remain--; } } /* * Kernel version which takes radix argument vsnprintf(3). */ int vsnrprintf(char *str, size_t size, int radix, const char *format, va_list ap) { struct snprintf_arg info; int retval; info.str = str; info.remain = size; retval = kvprintf(format, snprintf_func, &info, radix, ap); if (info.remain >= 1) *info.str++ = '\0'; return (retval); } /* * Put a NUL-terminated ASCII number (base <= 36) in a buffer in reverse * order; return an optional length and a pointer to the last character * written in the buffer (i.e., the first character of the string). * The buffer pointed to by `nbuf' must have length >= MAXNBUF. */ static char * ksprintn(char *nbuf, uintmax_t num, int base, int *lenp, int upper) { char *p, c; p = nbuf; *p = '\0'; do { c = hex2ascii(num % base); *++p = upper ? toupper(c) : c; } while (num /= base); if (lenp) *lenp = p - nbuf; return (p); } /* * Scaled down version of printf(3). * * Two additional formats: * * The format %b is supported to decode error registers. * Its usage is: * * printf("reg=%b\n", regval, "<base><arg>*"); * * where <base> is the output base expressed as a control character, e.g. * \10 gives octal; \20 gives hex. Each arg is a sequence of characters, * the first of which gives the bit number to be inspected (origin 1), and * the next characters (up to a control character, i.e. a character <= 32), * give the name of the register. Thus: * * kvprintf("reg=%b\n", 3, "\10\2BITTWO\1BITONE\n"); * * would produce output: * * reg=3<BITTWO,BITONE> * * XXX: %D -- Hexdump, takes pointer and separator string: * ("%6D", ptr, ":") -> XX:XX:XX:XX:XX:XX * ("%*D", len, ptr, " " -> XX XX XX XX ... */ int kvprintf(char const *fmt, void (*func)(int, void*), void *arg, int radix, va_list ap) { #define PCHAR(c) {int cc=(c); if (func) (*func)(cc,arg); else *d++ = cc; retval++; } char nbuf[MAXNBUF]; char *d; const char *p, *percent, *q; u_char *up; int ch, n; uintmax_t num; int base, lflag, qflag, tmp, width, ladjust, sharpflag, neg, sign, dot; int cflag, hflag, jflag, tflag, zflag; int dwidth, upper; char padc; int stop = 0, retval = 0; num = 0; if (!func) d = (char *) arg; else d = NULL; if (fmt == NULL) fmt = "(fmt null)\n"; if (radix < 2 || radix > 36) radix = 10; for (;;) { padc = ' '; width = 0; while ((ch = (u_char)*fmt++) != '%' || stop) { if (ch == '\0') return (retval); PCHAR(ch); } percent = fmt - 1; qflag = 0; lflag = 0; ladjust = 0; sharpflag = 0; neg = 0; sign = 0; dot = 0; dwidth = 0; upper = 0; cflag = 0; hflag = 0; jflag = 0; tflag = 0; zflag = 0; reswitch: switch (ch = (u_char)*fmt++) { case '.': dot = 1; goto reswitch; case '#': sharpflag = 1; goto reswitch; case '+': sign = 1; goto reswitch; case '-': ladjust = 1; goto reswitch; case '%': PCHAR(ch); break; case '*': if (!dot) { width = va_arg(ap, int); if (width < 0) { ladjust = !ladjust; width = -width; } } else { dwidth = va_arg(ap, int); } goto reswitch; case '0': if (!dot) { padc = '0'; goto reswitch; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': for (n = 0;; ++fmt) { n = n * 10 + ch - '0'; ch = *fmt; if (ch < '0' || ch > '9') break; } if (dot) dwidth = n; else width = n; goto reswitch; case 'b': num = (u_int)va_arg(ap, int); p = va_arg(ap, char *); for (q = ksprintn(nbuf, num, *p++, NULL, 0); *q;) PCHAR(*q--); if (num == 0) break; for (tmp = 0; *p;) { n = *p++; if (num & (1 << (n - 1))) { PCHAR(tmp ? ',' : '<'); for (; (n = *p) > ' '; ++p) PCHAR(n); tmp = 1; } else for (; *p > ' '; ++p) continue; } if (tmp) PCHAR('>'); break; case 'c': PCHAR(va_arg(ap, int)); break; case 'D': up = va_arg(ap, u_char *); p = va_arg(ap, char *); if (!width) width = 16; while(width--) { PCHAR(hex2ascii(*up >> 4)); PCHAR(hex2ascii(*up & 0x0f)); up++; if (width) for (q=p;*q;q++) PCHAR(*q); } break; case 'd': case 'i': base = 10; sign = 1; goto handle_sign; case 'h': if (hflag) { hflag = 0; cflag = 1; } else hflag = 1; goto reswitch; case 'j': jflag = 1; goto reswitch; case 'l': if (lflag) { lflag = 0; qflag = 1; } else lflag = 1; goto reswitch; case 'n': if (jflag) *(va_arg(ap, intmax_t *)) = retval; else if (qflag) *(va_arg(ap, quad_t *)) = retval; else if (lflag) *(va_arg(ap, long *)) = retval; else if (zflag) *(va_arg(ap, size_t *)) = retval; else if (hflag) *(va_arg(ap, short *)) = retval; else if (cflag) *(va_arg(ap, char *)) = retval; else *(va_arg(ap, int *)) = retval; break; case 'o': base = 8; goto handle_nosign; case 'p': base = 16; sharpflag = (width == 0); sign = 0; num = (uintptr_t)va_arg(ap, void *); goto number; case 'q': qflag = 1; goto reswitch; case 'r': base = radix; if (sign) goto handle_sign; goto handle_nosign; case 's': p = va_arg(ap, char *); if (p == NULL) p = "(null)"; if (!dot) n = strlen (p); else for (n = 0; n < dwidth && p[n]; n++) continue; width -= n; if (!ladjust && width > 0) while (width--) PCHAR(padc); while (n--) PCHAR(*p++); if (ladjust && width > 0) while (width--) PCHAR(padc); break; case 't': tflag = 1; goto reswitch; case 'u': base = 10; goto handle_nosign; case 'X': upper = 1; case 'x': base = 16; goto handle_nosign; case 'y': base = 16; sign = 1; goto handle_sign; case 'z': zflag = 1; goto reswitch; handle_nosign: sign = 0; if (jflag) num = va_arg(ap, uintmax_t); else if (qflag) num = va_arg(ap, u_quad_t); else if (tflag) num = va_arg(ap, ptrdiff_t); else if (lflag) num = va_arg(ap, u_long); else if (zflag) num = va_arg(ap, size_t); else if (hflag) num = (u_short)va_arg(ap, int); else if (cflag) num = (u_char)va_arg(ap, int); else num = va_arg(ap, u_int); goto number; handle_sign: if (jflag) num = va_arg(ap, intmax_t); else if (qflag) num = va_arg(ap, quad_t); else if (tflag) num = va_arg(ap, ptrdiff_t); else if (lflag) num = va_arg(ap, long); else if (zflag) num = va_arg(ap, ssize_t); else if (hflag) num = (short)va_arg(ap, int); else if (cflag) num = (char)va_arg(ap, int); else num = va_arg(ap, int); number: if (sign && (intmax_t)num < 0) { neg = 1; num = -(intmax_t)num; } p = ksprintn(nbuf, num, base, &n, upper); tmp = 0; if (sharpflag && num != 0) { if (base == 8) tmp++; else if (base == 16) tmp += 2; } if (neg) tmp++; if (!ladjust && padc == '0') dwidth = width - tmp; width -= tmp + imax(dwidth, n); dwidth -= n; if (!ladjust) while (width-- > 0) PCHAR(' '); if (neg) PCHAR('-'); if (sharpflag && num != 0) { if (base == 8) { PCHAR('0'); } else if (base == 16) { PCHAR('0'); PCHAR('x'); } } while (dwidth-- > 0) PCHAR('0'); while (*p) PCHAR(*p--); if (ladjust) while (width-- > 0) PCHAR(' '); break; default: while (percent < fmt) PCHAR(*percent++); /* * Since we ignore an formatting argument it is no * longer safe to obey the remaining formatting * arguments as the arguments will no longer match * the format specs. */ stop = 1; break; } } #undef PCHAR }
the_stack_data/90766603.c
/* PR c/68412 */ /* { dg-do compile } */ /* { dg-options "-Wall -Wextra" } */ #define M (sizeof (int) * __CHAR_BIT__) int fn1 (int i) { return i == (-1 << 8); /* { dg-warning "left shift of negative value" } */ } int fn2 (int i) { return i == (1 << M); /* { dg-warning "left shift count" } */ } int fn3 (int i) { return i == 10 << (M - 1); /* { dg-warning "requires" } */ } int fn4 (int i) { return i == 1 << -1; /* { dg-warning "left shift count" } */ } int fn5 (int i) { return i == 1 >> M; /* { dg-warning "right shift count" } */ } int fn6 (int i) { return i == 1 >> -1; /* { dg-warning "right shift count" } */ }
the_stack_data/31388456.c
/* K.N.King "C Programming. A Modern Approach." Programming project 10 p.157 Write a program that counts the number of vowels (a, e, i, o, and u) in a sentence: "Enter a sentence: And that's the way it is. Your sentence contains 6 vowels. " */ #include <stdlib.h> #include <ctype.h> #include <stdio.h> int IsVowel(char c); int main(void) { char c = '\0'; int count = 0; printf("Enter a sentence: "); while ( (c = getchar()) != '\n' && c != EOF) { if (IsVowel(c)) { ++count; } } printf("Your sentence contains %d vowels.\n", count); getchar(); return EXIT_SUCCESS; } int IsVowel(char c) { c = tolower(c); return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; }
the_stack_data/48576500.c
bar (foo, a) int (**foo) (); { (foo)[1] = bar; foo[a] (1); }
the_stack_data/184518721.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "THNN/generic/SpatialAdaptiveMaxPooling.c" #else #define START_IND(a,b,c) (int)floor((float)(a * c) / b) #define END_IND(a,b,c) (int)ceil((float)((a + 1) * c) / b) // #define START_IND(a,b,c) a * c / b // #define END_IND(a,b,c) (a + 1) * c / b + ((a + 1) * c % b > 0)?1:0 // 4d tensor B x D x H x W static void THNN_(SpatialAdaptiveMaxPooling_updateOutput_frame)( scalar_t *input_p, scalar_t *output_p, THIndex_t *ind_p, int64_t sizeD, int64_t isizeH, int64_t isizeW, int64_t osizeH, int64_t osizeW, int64_t istrideD, int64_t istrideH, int64_t istrideW) { int64_t d; #pragma omp parallel for private(d) for (d = 0; d < sizeD; d++) { /* loop over output */ int64_t oh, ow; for(oh = 0; oh < osizeH; oh++) { int istartH = START_IND(oh, osizeH, isizeH); int iendH = END_IND(oh, osizeH, isizeH); int kH = iendH - istartH; for(ow = 0; ow < osizeW; ow++) { int istartW = START_IND(ow, osizeW, isizeW); int iendW = END_IND(ow, osizeW, isizeW); int kW = iendW - istartW; /* local pointers */ scalar_t *ip = input_p + d*istrideD + istartH*istrideH + istartW*istrideW; scalar_t *op = output_p + d*osizeH*osizeW + oh*osizeW + ow; THIndex_t *indp = ind_p + d*osizeH*osizeW + oh*osizeW + ow; /* compute local max: */ int64_t maxindex = -1; scalar_t maxval = -FLT_MAX; int ih, iw; for(ih = 0; ih < kH; ih++) { for(iw = 0; iw < kW; iw++) { scalar_t val = *(ip + ih*istrideH + iw*istrideW); if ((val > maxval) || std::isnan(val)) { maxval = val; maxindex = (ih+istartH)*isizeW + (iw+istartW); } } } /* set output to local max */ *op = maxval; /* store location of max */ *indp = maxindex + TH_INDEX_BASE; } } } } void THNN_(SpatialAdaptiveMaxPooling_updateOutput)( THNNState *state, THTensor *input, THTensor *output, THIndexTensor *indices, int osizeW, int osizeH) { int dimW = 2; int dimH = 1; int64_t sizeB = 1; int64_t sizeD = 0; int64_t isizeH = 0; int64_t isizeW = 0; int64_t istrideD = 0; int64_t istrideH = 0; int64_t istrideW = 0; int64_t istrideB = 0; scalar_t *input_data = nullptr; scalar_t *output_data = nullptr; THIndex_t *indices_data = nullptr; THNN_ARGCHECK(!input->is_empty() && (input->dim() == 3 || input->dim() == 4), 2, input, "non-empty 3D or 4D (batch mode) tensor expected for input, but got: %s"); if (input->dim() == 4) { istrideB = input->stride(0); sizeB = input->size(0); dimW++; dimH++; } /* sizes */ sizeD = input->size(dimH-1); isizeH = input->size(dimH); isizeW = input->size(dimW); /* strides */ istrideD = input->stride(dimH-1); istrideH = input->stride(dimH); istrideW = input->stride(dimW); /* resize output */ if (input->dim() == 3) { THTensor_(resize3d)(output, sizeD, osizeH, osizeW); /* indices will contain i,j locations for each output point */ THIndexTensor_(resize3d)(indices, sizeD, osizeH, osizeW); input_data = input->data<scalar_t>(); output_data = output->data<scalar_t>(); indices_data = THIndexTensor_(data)(indices); THNN_(SpatialAdaptiveMaxPooling_updateOutput_frame)(input_data, output_data, indices_data, sizeD, isizeH, isizeW, osizeH, osizeW, istrideD, istrideH, istrideW); } else { int64_t b; THTensor_(resize4d)(output, sizeB, sizeD, osizeH, osizeW); /* indices will contain i,j locations for each output point */ THIndexTensor_(resize4d)(indices, sizeB, sizeD, osizeH, osizeW); input_data = input->data<scalar_t>(); output_data = output->data<scalar_t>(); indices_data = THIndexTensor_(data)(indices); #pragma omp parallel for private(b) for (b = 0; b < sizeB; b++) { THNN_(SpatialAdaptiveMaxPooling_updateOutput_frame)(input_data+b*istrideB, output_data+b*sizeD*osizeH*osizeW, indices_data+b*sizeD*osizeH*osizeW, sizeD, isizeH, isizeW, osizeH, osizeW, istrideD, istrideH, istrideW); } } } static void THNN_(SpatialAdaptiveMaxPooling_updateGradInput_frame)( scalar_t *gradInput_p, scalar_t *gradOutput_p, THIndex_t *ind_p, int64_t sizeD, int64_t isizeH, int64_t isizeW, int64_t osizeH, int64_t osizeW) { int64_t d; #pragma omp parallel for private(d) for (d = 0; d < sizeD; d++) { scalar_t *gradInput_p_d = gradInput_p + d*isizeH*isizeW; scalar_t *gradOutput_p_d = gradOutput_p + d*osizeH*osizeW; THIndex_t *ind_p_d = ind_p + d*osizeH*osizeW; /* calculate max points */ int64_t oh, ow; for(oh = 0; oh < osizeH; oh++) { for(ow = 0; ow < osizeW; ow++) { /* retrieve position of max */ int64_t maxp = ind_p_d[oh*osizeW + ow] - TH_INDEX_BASE; /* update gradient */ gradInput_p_d[maxp] += gradOutput_p_d[oh*osizeW + ow]; } } } } void THNN_(SpatialAdaptiveMaxPooling_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THIndexTensor *indices) { int dimW = 2; int dimH = 1; int64_t sizeB = 1; int sizeD; int isizeH; int isizeW; int osizeH; int osizeW; scalar_t *gradInput_data; scalar_t *gradOutput_data; THIndex_t *indices_data; /* get contiguous gradOutput */ gradOutput = THTensor_(newContiguous)(gradOutput); /* resize */ THTensor_(resizeAs)(gradInput, input); THTensor_(zero)(gradInput); if (input->dim() == 4) { sizeB = input->size(0); dimW++; dimH++; } /* sizes */ sizeD = input->size(dimH-1); isizeH = input->size(dimH); isizeW = input->size(dimW); osizeH = gradOutput->size(dimH); osizeW = gradOutput->size(dimW); /* get raw pointers */ gradInput_data = gradInput->data<scalar_t>(); gradOutput_data = gradOutput->data<scalar_t>(); indices_data = THIndexTensor_(data)(indices); /* backprop */ if (input->dim() == 3) { THNN_(SpatialAdaptiveMaxPooling_updateGradInput_frame)(gradInput_data, gradOutput_data, indices_data, sizeD, isizeH, isizeW, osizeH, osizeW); } else { int64_t b; #pragma omp parallel for private(b) for (b = 0; b < sizeB; b++) { THNN_(SpatialAdaptiveMaxPooling_updateGradInput_frame)(gradInput_data+b*sizeD*isizeH*isizeW, gradOutput_data+b*sizeD*osizeH*osizeW, indices_data+b*sizeD*osizeH*osizeW, sizeD, isizeH, isizeW, osizeH, osizeW); } } /* cleanup */ c10::raw::intrusive_ptr::decref(gradOutput); } #endif
the_stack_data/32949566.c
/* $Id$ */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <assert.h> #include <string.h> #if __cplusplus extern "C" { #endif void UtimeOpsC__Set_second (struct tm *t, int second ) { t->tm_sec = second ; } void UtimeOpsC__Set_minute (struct tm *t, int minute ) { t->tm_min = minute ; } void UtimeOpsC__Set_hour (struct tm *t, int hour ) { t->tm_hour = hour ; } void UtimeOpsC__Set_day (struct tm *t, int day ) { t->tm_mday = day ; } void UtimeOpsC__Set_month (struct tm *t, int month ) { t->tm_mon = month ; } void UtimeOpsC__Set_year (struct tm *t, int year ) { t->tm_year = year - 1900 ; } void UtimeOpsC__Set_wday (struct tm *t, int wday ) { t->tm_wday = wday ; } /***********************************************************************/ int UtimeOpsC__Get_second (const struct tm *t) { return t->tm_sec ; } int UtimeOpsC__Get_gmtoff (const struct tm *t) { #if _WIN32 return 0; #else return t->tm_gmtoff ; #endif } int UtimeOpsC__Get_minute (const struct tm *t) { return t->tm_min ; } const char * UtimeOpsC__Get_zone (const struct tm *t) { #if _WIN32 assert (0); return 0 ; #else return t->tm_zone ; #endif } int UtimeOpsC__Get_hour (const struct tm *t) { return t->tm_hour ; } int UtimeOpsC__Get_day (const struct tm *t) { return t->tm_mday ; } int UtimeOpsC__Get_month (const struct tm *t) { return t->tm_mon ; } int UtimeOpsC__Get_year (const struct tm *t) { return t->tm_year + 1900 ; } int UtimeOpsC__Get_wday (const struct tm *t) { return t->tm_wday ; } double UtimeOpsC__mktime(struct tm *t) { t->tm_isdst = -1; #if !_WIN32 t->tm_gmtoff = 0; #endif t->tm_wday = 0; t->tm_yday = 0; return mktime(t); } struct tm * UtimeOpsC__localtime_r(double clock, struct tm *result) { time_t clocki=clock; #if _WIN32 struct tm *res = localtime(&clocki); if (!res) return res; *result = *res; res = result; #else struct tm *res= localtime_r(&clocki, result); #endif #if 0 printf("clock: %f\n", clock); printf("tm: %d %d %d\n", res->tm_hour, res->tm_min, res->tm_sec); printf("tm: %s\n", res->tm_zone); #endif return res; } struct tm * UtimeOpsC__make_T() { return (struct tm*)calloc(sizeof(struct tm), 1); } void UtimeOpsC__delete_T(struct tm *t) { free(t); } char * UtimeOpsC__ctime_r(time_t *clock, char *buf) { #if _WIN32 strcpy(buf, ctime(clock)); return buf; #else return ctime_r(clock, buf); #endif } void UtimeOpsC__check_types(void) { /* This is incorrect on many systems. */ /* we really should assert that a Modula-3 INTEGER is equally sized to C's time_t */ assert(sizeof(time_t) == sizeof(long)); } void UtimeOpsC__write_double_clock(double time, time_t *buf) { *buf = time; } #if __cplusplus } /* extern "C" */ #endif
the_stack_data/835049.c
/* Bug: z does not seem to have a pointer type. */ p3(x, z) double x, *z; { *z = x/2; }
the_stack_data/120095.c
/*- * Copyright (c) 1980 The Regents of the University of California. * All rights reserved. * * %sccs.include.proprietary.c% */ #ifndef lint static char sccsid[] = "@(#)r_asin.c 5.3 (Berkeley) 04/12/91"; #endif /* not lint */ float r_asin(x) float *x; { double asin(); return( asin(*x) ); }
the_stack_data/28524.c
/* * Copyright (c) 2013 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* * This file defines a set of function for performing atomic accesses on * memory locations according to the GCCMM library interface, providing * library support for the C11/C++11 atomics. * * See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary * * Clang often emits atomic instructions instead of library calls when * user code does atomics (e.g. by using the ``__sync_*`` * primitives). Nonetheless library calls to the functions implemented * in this file are emitted by Clang in certain circumstances, and * user/library code sometimes calls these functions directly. This file * is linked into user code before the PNaCl toolchain creates a * portable executable, and implements GCCMM's functions as calls to * PNaCl's atomic intrinsics. Failing to link with this file would lead * to undefined reference errors at link time. * * This file doesn't assume that the underlying NaCl atomic intrinsics * are/aren't lock-free: it merely punts to the translator which may * implement some of the supported sizes as lock-free. * * Note that similar functions may be implemented by backends which * don't support some lockless atomic accesses, e.g. MIPS for 64-bit * atomics. These are entirely separate from this file and should not be * confused. * * TODO(jfb) We currently don't handle 16-bit atomics or wider at all in * the PNaCl ABI. Implementing these here requires care * because C11/C++11 atomics that are implemented with a lock * all need to go through the same lock (or locks, if * sharded), and this requires a contract with Clang's code * generation if we are to implement these in the current * file. Implementing them here is also not forward-looking * because hardware may support lock-free accesses for these * sizes. */ #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include <unistd.h> /* Clang complains if we redefine builtins directly. */ #pragma redefine_extname __pnacl_atomic_load __atomic_load #pragma redefine_extname __pnacl_atomic_store __atomic_store #pragma redefine_extname __pnacl_atomic_exchange __atomic_exchange #pragma redefine_extname __pnacl_atomic_compare_exchange \ __atomic_compare_exchange /* * Memory order from GCCMM. */ enum AtomicOrderingKind { AO_ABI_memory_order_relaxed = 0, AO_ABI_memory_order_consume = 1, AO_ABI_memory_order_acquire = 2, AO_ABI_memory_order_release = 3, AO_ABI_memory_order_acq_rel = 4, AO_ABI_memory_order_seq_cst = 5 }; /* * Part of the stable ABI from llvm/IR/NaClAtomicIntrinsics.h. */ enum AtomicRMWOperation { AtomicInvalid = 0, /* Invalid, keep first. */ AtomicAdd, AtomicSub, AtomicOr, AtomicAnd, AtomicXor, AtomicExchange, AtomicNum /* Invalid, keep last. */ }; enum MemoryOrder { MemoryOrderInvalid = 0, /* Invalid, keep first. */ MemoryOrderRelaxed, MemoryOrderConsume, MemoryOrderAcquire, MemoryOrderRelease, MemoryOrderAcquireRelease, MemoryOrderSequentiallyConsistent, MemoryOrderNum /* Invalid, keep last. */ }; /* * Map GCCMM's memory order (also used by LLVM) to NaCl's stable ABI * equivalent. */ static enum MemoryOrder map_mem(enum AtomicOrderingKind order) { /* * TODO(jfb) For now PNaCl only supports sequentially-consistent. * When this changes we should map AO_ABI_(.*) to MemoryOrder\1. */ (void) order; return MemoryOrderSequentiallyConsistent; } /* * All the atomic sizes currently handled by PNaCl. * Invokes DO_ATOMIC(BITS, BYTES). */ #define DO_FOR_ALL_ATOMIC_SIZES() \ DO_ATOMIC(8, 1) \ DO_ATOMIC(16, 2) \ DO_ATOMIC(32, 4) \ DO_ATOMIC(64, 8) /* Convenience type definitions. */ #define DO_ATOMIC(BITS, BYTES) \ typedef uint##BITS##_t I##BYTES; DO_FOR_ALL_ATOMIC_SIZES() #undef DO_ATOMIC /* * NaCl atomic intrinsics ABI from llvm/IR/Intrinsics.td: * __llvm_nacl_atomic_{load,store,rmw,cmpxchg}_{1,2,4,8} * Used by the below optimized sized functions. * Note: these expect a memory order from the stable ABI. */ #define DO_ATOMIC(BITS, BYTES) \ I##BYTES \ __llvm_nacl_atomic_load_##BYTES( \ I##BYTES *mem, int model) \ asm("llvm.nacl.atomic.load.i" #BITS); \ void \ __llvm_nacl_atomic_store_##BYTES( \ I##BYTES val, I##BYTES *mem, int model) \ asm("llvm.nacl.atomic.store.i" #BITS); \ I##BYTES \ __llvm_nacl_atomic_rmw_##BYTES( \ int op, I##BYTES *mem, I##BYTES val, int model) \ asm("llvm.nacl.atomic.rmw.i" #BITS); \ I##BYTES \ __llvm_nacl_atomic_cmpxchg_##BYTES( \ I##BYTES *mem, I##BYTES expected, I##BYTES desired, \ int success, int failure) \ asm("llvm.nacl.atomic.cmpxchg.i" #BITS); DO_FOR_ALL_ATOMIC_SIZES() #undef DO_ATOMIC /* * GCCMM optimized sized functions: * - __atomic_fetch_{add,sub,or,and,xor}_{1,2,4,8}. * - __atomic_{load,store,exchange,compare_exchange}_{1,2,4,8}. * User/library accessible, and used by some of the generic function below. */ #define DO_ATOMIC_RMW(BITS, BYTES, OP, OPCASE) \ I##BYTES \ __atomic_fetch_##OP##_##BYTES( \ I##BYTES *mem, I##BYTES val, int model) { \ return __llvm_nacl_atomic_rmw_##BYTES( \ Atomic##OPCASE, mem, val, map_mem(model)); \ } #define DO_ATOMIC(BITS, BYTES) \ I##BYTES \ __atomic_load_##BYTES( \ I##BYTES *mem, int model) { \ return __llvm_nacl_atomic_load_##BYTES(mem, map_mem(model)); \ } \ void \ __atomic_store_##BYTES( \ I##BYTES *mem, I##BYTES val, int model) { \ __llvm_nacl_atomic_store_##BYTES(val, mem, map_mem(model)); \ } \ I##BYTES \ __atomic_exchange_##BYTES( \ I##BYTES *mem, I##BYTES val, int model) { \ return __llvm_nacl_atomic_rmw_##BYTES( \ AtomicExchange, mem, val, map_mem(model)); \ } \ bool \ __atomic_compare_exchange_##BYTES( \ I##BYTES *mem, I##BYTES *expected, I##BYTES desired, \ int success, int failure) { \ I##BYTES e = *expected; \ I##BYTES old = __llvm_nacl_atomic_cmpxchg_##BYTES( \ mem, e, desired, map_mem(success), map_mem(failure)); \ bool succeeded = old == e; \ *expected = old; \ return succeeded; \ } \ DO_ATOMIC_RMW(BITS, BYTES, add, Add) \ DO_ATOMIC_RMW(BITS, BYTES, sub, Sub) \ DO_ATOMIC_RMW(BITS, BYTES, or, Or) \ DO_ATOMIC_RMW(BITS, BYTES, and, And) \ DO_ATOMIC_RMW(BITS, BYTES, xor, Xor) DO_FOR_ALL_ATOMIC_SIZES() #undef DO_ATOMIC #undef DO_ATOMIC_RMW __attribute__((noinline, noreturn)) static void unhandled_size(const char *error_string, size_t size) { write(2, error_string, size); abort(); } #define UNHANDLED_SIZE(WHAT) do { \ static const char msg[] = "Aborting: __atomic_" #WHAT \ " called with size greater than 8 bytes\n"; \ unhandled_size(msg, sizeof(msg) - 1); \ } while (0) /* * Generic GCCMM functions which handle objects of arbitrary size. * Calls the optimized sized functions above. */ void __pnacl_atomic_load(size_t size, void *mem, void *ret, int model) { #define DO_ATOMIC(BITS, BYTES) \ case BYTES: { \ I##BYTES res = __atomic_load_##BYTES( \ (I##BYTES*)(mem), model); \ *(I##BYTES*)(ret) = res; \ } break; switch(size) { DO_FOR_ALL_ATOMIC_SIZES(); default: UNHANDLED_SIZE(load); } #undef DO_ATOMIC } void __pnacl_atomic_store(size_t size, void *mem, void *val, int model) { #define DO_ATOMIC(BITS, BYTES) \ case BYTES: { \ I##BYTES v = *(I##BYTES*)(val); \ __atomic_store_##BYTES( \ (I##BYTES*)(mem), v, model); \ } break; switch(size) { DO_FOR_ALL_ATOMIC_SIZES(); default: UNHANDLED_SIZE(store); } #undef DO_ATOMIC } void __pnacl_atomic_exchange(size_t size, void *mem, void *val, void *ret, int model) { #define DO_ATOMIC(BITS, BYTES) \ case BYTES: { \ I##BYTES v = *(I##BYTES*)(val); \ I##BYTES res = __atomic_exchange_##BYTES( \ (I##BYTES*)(mem), v, model); \ *(I##BYTES*)(ret) = res; \ } break; switch(size) { DO_FOR_ALL_ATOMIC_SIZES(); default: UNHANDLED_SIZE(exchange); } #undef DO_ATOMIC } bool __pnacl_atomic_compare_exchange(size_t size, void *mem, void *expected, void *desired, int success, int failure) { #define DO_ATOMIC(BITS, BYTES) \ case BYTES: { \ I##BYTES d = *(I##BYTES*)(desired); \ return __atomic_compare_exchange_##BYTES( \ (I##BYTES*)(mem), (I##BYTES*)(expected), d, \ success, failure); \ } switch(size) { DO_FOR_ALL_ATOMIC_SIZES(); default: UNHANDLED_SIZE(compare_exchange); } #undef DO_ATOMIC }
the_stack_data/62638951.c
#include <stdio.h> int main(void) { int line, i, j, k, r[5]; char nya[100]; scanf("%d", &line); getchar(); for (i = 0; i < line; i++) { for (k = 0; k < 5; k++) { r[k] = 0; } gets(nya); for (j = 0; nya[j] != '\0'; j++) { if (nya[j] == 'a') { r[0]++; } if (nya[j] == 'e') { r[1]++; } if (nya[j] == 'i') { r[2]++; } if (nya[j] == 'o') { r[3]++; } if (nya[j] == 'u') { r[4]++; } } printf("a:%d\n", r[0] ); printf("e:%d\n", r[1] ); printf("i:%d\n", r[2] ); printf("o:%d\n", r[3] ); printf("u:%d\n", r[4] ); if (i != line - 1) { printf("\n"); } } return 0; }
the_stack_data/119517.c
#include <stdio.h> int main() { int nbe=0; int x=0; int i=0; printf("combien de nombres voulez vous entrer?\n"); scanf("%d",&nbe); int tab[nbe]; for (i=0; i<nbe; i++) { printf("donnez un nombre\n"); scanf("%d",&x); tab[i]=x; } i=0; while (tab[i]>=0 && tab[i]<=20 && i<nbe) { i++; } if (i==nbe) { printf("vos nombres sont bien compris entre 0 et 20, barvo!!!!!\n"); } else { printf("arretes de faire de la merde, tes nombres ne sont pas entre 0 et 20\n"); } return 0; }
the_stack_data/243892896.c
/* mbed Microcontroller Library * Copyright (c) 2018 GigaDevice Semiconductor Inc. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ #if DEVICE_SLEEP #include "sleep_api.h" #include "us_ticker_api.h" #include "mbed_critical.h" #include "mbed_error.h" extern void ticker_timer_data_save(void); extern void ticker_timer_data_restore(void); extern int serial_busy_state_check(void); /*! \brief configure the system clock to 120M by PLL which selects HXTAL(25M) as its clock source \param[in] none \param[out] none \retval none */ static void system_clock_120m_hxtal(void) { uint32_t timeout = 0U; uint32_t stab_flag = 0U; /* enable HXTAL */ RCU_CTL |= RCU_CTL_HXTALEN; /* wait until HXTAL is stable or the startup time is longer than HXTAL_STARTUP_TIMEOUT */ do { timeout++; stab_flag = (RCU_CTL & RCU_CTL_HXTALSTB); } while ((0U == stab_flag) && (HXTAL_STARTUP_TIMEOUT != timeout)); /* if fail */ if (0U == (RCU_CTL & RCU_CTL_HXTALSTB)) { while (1) { } } RCU_APB1EN |= RCU_APB1EN_PMUEN; PMU_CTL |= PMU_CTL_LDOVS; /* HXTAL is stable */ /* AHB = SYSCLK */ RCU_CFG0 |= RCU_AHB_CKSYS_DIV1; /* APB2 = AHB/1 */ RCU_CFG0 |= RCU_APB2_CKAHB_DIV1; /* APB1 = AHB/2 */ RCU_CFG0 |= RCU_APB1_CKAHB_DIV2; #if (defined(GD32F30X_HD) || defined(GD32F30X_XD)) /* select HXTAL/2 as clock source */ RCU_CFG0 &= ~(RCU_CFG0_PLLSEL | RCU_CFG0_PREDV0); RCU_CFG0 |= (RCU_PLLSRC_HXTAL_IRC48M | RCU_CFG0_PREDV0); /* CK_PLL = (CK_HXTAL/2) * 30 = 120 MHz */ RCU_CFG0 &= ~(RCU_CFG0_PLLMF | RCU_CFG0_PLLMF_4 | RCU_CFG0_PLLMF_5); RCU_CFG0 |= RCU_PLL_MUL30; #elif defined(GD32F30X_CL) /* CK_PLL = (CK_PREDIV0) * 30 = 120 MHz */ RCU_CFG0 &= ~(RCU_CFG0_PLLMF | RCU_CFG0_PLLMF_4 | RCU_CFG0_PLLMF_5); RCU_CFG0 |= (RCU_PLLSRC_HXTAL_IRC48M | RCU_PLL_MUL30); /* CK_PREDIV0 = (CK_HXTAL)/5 *8 /10 = 4 MHz */ RCU_CFG1 &= ~(RCU_CFG1_PLLPRESEL | RCU_CFG1_PREDV0SEL | RCU_CFG1_PLL1MF | RCU_CFG1_PREDV1 | RCU_CFG1_PREDV0); RCU_CFG1 |= (RCU_PLLPRESRC_HXTAL | RCU_PREDV0SRC_CKPLL1 | RCU_PLL1_MUL8 | RCU_PREDV1_DIV5 | RCU_PREDV0_DIV10); /* enable PLL1 */ RCU_CTL |= RCU_CTL_PLL1EN; /* wait till PLL1 is ready */ while ((RCU_CTL & RCU_CTL_PLL1STB) == 0U) { } #endif /* GD32F30X_HD and GD32F30X_XD */ /* enable PLL */ RCU_CTL |= RCU_CTL_PLLEN; /* wait until PLL is stable */ while (0U == (RCU_CTL & RCU_CTL_PLLSTB)) { } /* enable the high-drive to extend the clock frequency to 120 MHz */ PMU_CTL |= PMU_CTL_HDEN; while (0U == (PMU_CS & PMU_CS_HDRF)) { } /* select the high-drive mode */ PMU_CTL |= PMU_CTL_HDS; while (0U == (PMU_CS & PMU_CS_HDSRF)) { } /* select PLL as system clock */ RCU_CFG0 &= ~RCU_CFG0_SCS; RCU_CFG0 |= RCU_CKSYSSRC_PLL; /* wait until PLL is selected as system clock */ while (0U == (RCU_CFG0 & RCU_SCSS_PLL)) { } } /** Send the microcontroller to sleep * * The processor is setup ready for sleep, and sent to sleep. In this mode, the * system clock to the core is stopped until a reset or an interrupt occurs. This eliminates * dynamic power used by the processor, memory systems and buses. The processor, peripheral and * memory state are maintained, and the peripherals continue to work and can generate interrupts. * * The processor can be woken up by any internal peripheral interrupt or external pin interrupt. * * The wake-up time shall be less than 10 us. * */ void hal_sleep(void) { /* Disable Interrupts */ core_util_critical_section_enter(); /* Enter SLEEP mode */ pmu_to_sleepmode(WFI_CMD); /* Enable Interrupts */ core_util_critical_section_exit(); } /** Send the microcontroller to deep sleep * * This processor is setup ready for deep sleep, and sent to sleep using __WFI(). This mode * has the same sleep features as sleep plus it powers down peripherals and high frequency clocks. * All state is still maintained. * * The processor can only be woken up by low power ticker, RTC, an external interrupt on a pin or a watchdog timer. * * The wake-up time shall be less than 10 ms. */ void hal_deepsleep(void) { if (0 != serial_busy_state_check()) { return; } /* Disable Interrupts */ core_util_critical_section_enter(); ticker_timer_data_save(); /* Enter DEEP SLEEP mode */ rcu_periph_clock_enable(RCU_PMU); pmu_to_deepsleepmode(PMU_LDO_NORMAL, WFI_CMD); /* Reconfigure the PLL after weak up */ system_clock_120m_hxtal(); ticker_timer_data_restore(); /* Enable Interrupts */ core_util_critical_section_exit(); } #endif /* DEVICE_SLEEP */
the_stack_data/885947.c
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <limits.h> #define SUBCHUNK1SIZE (16) #define AUDIO_FORMAT (1) /*For PCM*/ #define NUM_CHANNELS (2) #define SAMPLE_RATE (44100) #define BITS_PER_SAMPLE (16) #define BYTE_RATE (SAMPLE_RATE * NUM_CHANNELS * BITS_PER_SAMPLE/8) #define BLOCK_ALIGN (NUM_CHANNELS * BITS_PER_SAMPLE/8) typedef struct wavfileHeader { char ChunkID[4]; /* 4 */ int32_t ChunkSize; /* 4 */ char Format[4]; /* 4 */ char Subchunk1ID[4]; /* 4 */ int32_t Subchunk1Size; /* 4 */ int16_t AudioFormat; /* 2 */ int16_t NumChannels; /* 2 */ int32_t SampleRate; /* 4 */ int32_t ByteRate; /* 4 */ int16_t BlockAlign; /* 2 */ int16_t BitsPerSample; /* 2 */ char Subchunk2ID[4]; int32_t Subchunk2Size; } s_wavfileHeader; /*Data structure to hold a single frame with two channels*/ typedef struct stereo16PCM { int16_t left; int16_t right; } s_stereo16PCM; typedef s_wavfileHeader* s_Header; int Create16stereo(FILE* file_p,int32_t SampleRate,int32_t FrameCount) { int ret; s_wavfileHeader wavHeader; int32_t subchunk2_size; int32_t chunk_size; size_t write_count; subchunk2_size = FrameCount * NUM_CHANNELS * BITS_PER_SAMPLE/8; chunk_size = 4 + (8 + SUBCHUNK1SIZE) + (8 + subchunk2_size); wavHeader.ChunkID[0] = 'R'; wavHeader.ChunkID[1] = 'I'; wavHeader.ChunkID[2] = 'F'; wavHeader.ChunkID[3] = 'F'; wavHeader.ChunkSize = chunk_size; wavHeader.Format[0] = 'W'; wavHeader.Format[1] = 'A'; wavHeader.Format[2] = 'V'; wavHeader.Format[3] = 'E'; wavHeader.Subchunk1ID[0] = 'f'; wavHeader.Subchunk1ID[1] = 'm'; wavHeader.Subchunk1ID[2] = 't'; wavHeader.Subchunk1ID[3] = ' '; wavHeader.Subchunk1Size = SUBCHUNK1SIZE; wavHeader.AudioFormat = AUDIO_FORMAT; wavHeader.NumChannels = NUM_CHANNELS; wavHeader.SampleRate = SampleRate; wavHeader.ByteRate = BYTE_RATE; wavHeader.BlockAlign = BLOCK_ALIGN; wavHeader.BitsPerSample = BITS_PER_SAMPLE; wavHeader.Subchunk2ID[0] = 'd'; wavHeader.Subchunk2ID[1] = 'a'; wavHeader.Subchunk2ID[2] = 't'; wavHeader.Subchunk2ID[3] = 'a'; wavHeader.Subchunk2Size = subchunk2_size; write_count = fwrite(&wavHeader,sizeof(s_wavfileHeader), 1,file_p); ret = (1 != write_count)? -1 : 0; return ret; } s_stereo16PCM *stereoBufferallocate(int32_t FrameCount) { return (s_stereo16PCM *)malloc(sizeof(s_stereo16PCM) * FrameCount); } size_t write_PCM16wav_data(FILE* file_p,int32_t FrameCount,s_stereo16PCM *buffer_p) { size_t ret; ret = fwrite(buffer_p,sizeof(s_stereo16PCM), FrameCount,file_p); return ret; } int wavTypeConvert(char *path) { int ret; FILE* file_p; int count=0; size_t written; s_stereo16PCM *buffer_p = NULL; double duration,sample_count; FILE * infile = fopen(path,"rb"); if(NULL == infile) { perror("fopen fail in infile"); ret = -1; } s_Header meta = (s_Header)malloc(sizeof(s_wavfileHeader)); fread(meta, 1, sizeof(s_wavfileHeader), infile); short int *dataP = malloc(meta->Subchunk2Size); while(fread(dataP,1,meta->Subchunk2Size,infile) > 0) sample_count = (meta->Subchunk2Size)/2; duration = sample_count/SAMPLE_RATE; int32_t FrameCount = duration * SAMPLE_RATE; /*Open the wav file*/ file_p = fopen(path, "w"); if(NULL == file_p) { perror("fopen failed in main"); ret = -1; } /*Allocate the data buffer*/ buffer_p = stereoBufferallocate(FrameCount); if(NULL == buffer_p) { perror("fopen failed in main"); ret = -1; } /*Write the wav file header*/ ret = Create16stereo(file_p,SAMPLE_RATE,FrameCount); if(ret < 0) { perror("write_PCM16_stereo_header failed in main"); ret = -1; } for(count=0;count <= FrameCount;count++) { buffer_p[count].left = dataP[count]; buffer_p[count].right = dataP[count]; } /*Write the data out to file*/ written = write_PCM16wav_data( file_p, FrameCount, buffer_p); if(written < FrameCount) { perror("write_PCM16wav_data failed in main"); ret = -1; } /*Free and close everything*/ free(buffer_p); free(meta); fclose(file_p); fclose(infile); return ret; }
the_stack_data/97012725.c
#include <stdio.h> int main() { char s[12]; int EGN[12]; int sum=0,i; int teglo[9]={2,4,8,5,10,9,7,3,6}; int dati[12]={31,28,31,30,31,30,31,31,30,31,30,31}; scanf("%s",s); //---------proverka za simvoli -------- for(i=0;i<10;i++) { if(s[i]<'0' || s[i]>'9') { printf("\n0"); //printf("\n proverka na simvoli"); return 0; } } for(i=0;i<10;i++) { EGN[i]=s[i]-'0'; } //---------- proverka na kontrolno chislo for(i=0;i<9;i++) { sum=sum+teglo[i]*EGN[i]; } sum=sum % 11; if(sum<10) { if(EGN[9] != sum) { printf("\n0"); return 0; } }else{ if(EGN[9] != '0') { printf("\n0"); return 0; } } //---------proverka za dati int mes,den,god; god=EGN[0]*10+EGN[1]; den=EGN[4]*10+EGN[5]; mes=EGN[2]*10+EGN[3]; if(god % 4 == 0){dati[1]=29;} if(mes>20 && mes<33){mes=mes-20;} if(mes>40 && mes<53){mes=mes-40;} if(den>dati[mes-1] || den<1) { printf("\n0"); return 0; } if(mes<1 || mes>12) { printf("\n0"); return 0; } printf("\n1"); return 0; }
the_stack_data/37468.c
#include <stdio.h> #define tmax 50 int pile[tmax]; int sommet; void initpile(void){ sommet = -1; } void empiler(int x){ if(sommet < tmax-1){ sommet++; pile[sommet] = x; } } void depiler(int *x){ if(sommet > -1){ *x = pile[sommet]; sommet--; } } int pilevide(){ return (sommet == -1); } int fibo(int n){ int resultat = 0; int temp; initpile(); empiler(n); while(! pilevide()){ depiler(&temp); if(temp == 0 || temp == 1) resultat += temp; else{ empiler(temp - 1); empiler(temp - 2); } } return resultat; } int main(void){ printf("%i\n", fibo(13)); return 0; }
the_stack_data/242330049.c
/* * nq CMD... - run CMD... in background and in order, saving output * -w ... wait for all jobs/listed jobs queued so far to finish * -t ... exit 0 if no (listed) job needs waiting * -q quiet, do not output job id * -c clean, don't keep output if job exited with status 0 * * - requires POSIX.1-2008 and having flock(2) * - enforcing order works like this: * - every job has a flock(2)ed output file ala ",TIMESTAMP.PID" * - every job starts only after all earlier flock(2)ed files finished * - the lock is released when job terminates * - no sub-second file system time stamps are required, jobs are started * with millisecond precision * - we try hard to make the currently running ,* file have +x bit * - you can re-queue jobs using "sh ,jobid" * * To the extent possible under law, Leah Neukirchen <[email protected]> * has waived all copyright and related or neighboring rights to this work. * http://creativecommons.org/publicdomain/zero/1.0/ */ /* for FreeBSD. */ #define _WITH_DPRINTF #if defined(__sun) && defined(__SVR4) && !defined(HAVE_DPRINTF) #define NEED_DPRINTF #endif #include <sys/file.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #define FILENAME_BUFFERSIZE 64 #ifdef NEED_DPRINTF #include <stdarg.h> static int dprintf(int fd, const char *fmt, ...) { char buf[128]; // good enough for usage in nq va_list ap; int r; va_start(ap, fmt); r = vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); if (r >= 0 && r < sizeof buf) return write(fd, buf, r); return -1; } #endif static void swrite(int fd, char *str) { size_t l = strlen(str); if (write(fd, str, l) != l) { perror("write"); exit(222); } } static void write_execline(int fd, int argc, char *argv[]) { int i; char *s; swrite(fd, "exec"); for (i = 0; i < argc; i++) { if (!strpbrk(argv[i], "\001\002\003\004\005\006\007\010" "\011\012\013\014\015\016\017\020" "\021\022\023\024\025\026\027\030" "\031\032\033\034\035\036\037\040" "`^#*[]=|\\?${}()'\"<>&;\177")) { swrite(fd, " "); swrite(fd, argv[i]); } else { swrite(fd, " '"); for (s = argv[i]; *s; s++) { if (*s == '\'') swrite(fd, "'\\''"); else write(fd, s, 1); } swrite(fd, "'"); } } } int main(int argc, char *argv[]) { int64_t ms; int dirfd = 0, lockfd = 0; int opt = 0, cflag = 0, qflag = 0, tflag = 0, wflag = 0; int pipefd[2]; char lockfile[FILENAME_BUFFERSIZE]; pid_t child; struct timeval started; struct dirent *ent; DIR *dir; /* timestamp is milliseconds since epoch. */ gettimeofday(&started, NULL); ms = (int64_t)started.tv_sec*1000 + started.tv_usec/1000; while ((opt = getopt(argc, argv, "+chqtw")) != -1) { switch (opt) { case 'c': cflag = 1; break; case 'w': wflag = 1; break; case 't': tflag = 1; break; case 'q': qflag = 1; break; case 'h': default: goto usage; } } if (!tflag && !wflag && argc <= optind) { usage: swrite(2, "usage: nq [-c] [-q] [-w ... | -t ... | CMD...]\n"); exit(1); } char *path = getenv("NQDIR"); if (!path) path = "."; if (mkdir(path, 0777) < 0) { if (errno != EEXIST) { perror("mkdir"); exit(111); } } #ifdef O_DIRECTORY dirfd = open(path, O_RDONLY | O_DIRECTORY); #else dirfd = open(path, O_RDONLY); #endif if (dirfd < 0) { perror("dir open"); exit(111); } if (tflag || wflag) { snprintf(lockfile, sizeof lockfile, ".,%011" PRIx64 ".%d", ms, getpid()); goto wait; } if (pipe(pipefd) < 0) { perror("pipe"); exit(111); }; /* first fork, parent exits to run in background. */ child = fork(); if (child == -1) { perror("fork"); exit(111); } else if (child > 0) { char c; /* wait until child has backgrounded. */ close(pipefd[1]); read(pipefd[0], &c, 1); exit(0); } close(pipefd[0]); /* second fork, child later execs the job, parent collects status. */ child = fork(); if (child == -1) { perror("fork"); exit(111); } else if (child > 0) { int status; /* output expected lockfile name. */ snprintf(lockfile, sizeof lockfile, ",%011" PRIx64 ".%d", ms, child); if (!qflag) dprintf(1, "%s\n", lockfile); close(0); close(1); close(2); /* signal parent to exit. */ close(pipefd[1]); wait(&status); lockfd = openat(dirfd, lockfile, O_RDWR | O_APPEND); if (lockfd < 0) { perror("open"); exit(222); } fchmod(lockfd, 0600); if (WIFEXITED(status)) { dprintf(lockfd, "\n[exited with status %d.]\n", WEXITSTATUS(status)); if (cflag && WEXITSTATUS(status) == 0) unlinkat(dirfd, lockfile, 0); } else { dprintf(lockfd, "\n[killed by signal %d.]\n", WTERMSIG(status)); } exit(0); } close(pipefd[1]); /* create and lock lockfile. since this cannot be done in one step, use a different filename first. */ snprintf(lockfile, sizeof lockfile, ".,%011" PRIx64 ".%d", ms, getpid()); lockfd = openat(dirfd, lockfile, O_CREAT | O_EXCL | O_RDWR | O_APPEND, 0600); if (lockfd < 0) { perror("open"); exit(222); } if (flock(lockfd, LOCK_EX) < 0) { perror("flock"); exit(222); } /* drop leading '.' */ renameat(dirfd, lockfile, dirfd, lockfile+1); /* block until rename is committed */ fsync(dirfd); write_execline(lockfd, argc, argv); if (dup2(lockfd, 2) < 0 || dup2(lockfd, 1) < 0) { perror("dup2"); exit(222); } wait: if ((tflag || wflag) && argc - optind > 0) { /* wait for files passed as command line arguments. */ int i; for (i = optind; i < argc; i++) { int fd; if (strchr(argv[i], '/')) fd = open(argv[i], O_RDWR); else fd = openat(dirfd, argv[i], O_RDWR); if (fd < 0) continue; if (flock(fd, LOCK_EX | LOCK_NB) == -1 && errno == EWOULDBLOCK) { if (tflag) exit(1); flock(fd, LOCK_EX); /* sit it out. */ } fchmod(fd, 0600); close(fd); } } else { dir = fdopendir(dirfd); if (!dir) { perror("fdopendir"); exit(111); } again: while ((ent = readdir(dir))) { /* wait for all ,* files. */ if (ent->d_name[0] == ',' && strcmp(ent->d_name, lockfile+1) < 0) { int fd; fd = openat(dirfd, ent->d_name, O_RDWR); if (fd < 0) continue; if (flock(fd, LOCK_EX | LOCK_NB) == -1 && errno == EWOULDBLOCK) { if (tflag) exit(1); flock(fd, LOCK_EX); /* sit it out. */ close(fd); rewinddir(dir); goto again; } fchmod(fd, 0600); close(fd); } } closedir(dir); /* closes dirfd too. */ } if (tflag || wflag) exit(0); /* ready to run. */ swrite(lockfd, "\n\n"); fchmod(lockfd, 0700); close(lockfd); setenv("NQJOBID", lockfile+1, 1); setsid(); execvp(argv[optind], argv+optind); perror("execvp"); return 222; }
the_stack_data/23574074.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { float temp; float *p2; temp = 26.5; p2 = &temp; *p2 = 29.0; printf("(b) %.1f \n", temp); return 0; }
the_stack_data/671848.c
/** * ppjC je programski jezik podskup jezika C definiran u dokumentu * https://github.com/fer-ppj/ppj-labosi/raw/master/upute/ppj-labos-upute.pdf * * ova skripta poziva ppjC kompajler (za sada samo analizator) pritiskom * na tipku [Ctrl+S], [Shift+Enter] ili [Alt+3] i prikazuje rezultat analize. * * ne garantiram tocnost leksera, sintaksnog niti semantickog analizatora koji * se ovdje pokrece. * * URL skripte prati verzije izvornog programa, tako da je moguca razmjena * izvornih programa u timu putem URL-ova. */ int printf(const char format[]) { /* i wish i could printf */ return 0; } int main(void) { int asd = 123; return printf("hello world!\n"); }
the_stack_data/7949083.c
#include<stdio.h> #include<stdlib.h> struct bst { struct bst *lc,*rc; int data; }; struct bst *root=NULL; struct bst* getnode(int k) { struct bst *temp=(struct bst*)malloc(sizeof(struct bst)); temp->data=k; temp->lc=temp->rc=NULL; return temp; } struct bst* minval(struct bst *node) { while(node->lc!=NULL) node=node->lc; return node; } struct bst* insert(struct bst *root,int data) { if (root==NULL) return getnode(data); else if(data < root->data) root->lc=insert(root->lc,data); else root->rc=insert(root->rc,data); return root; } int search(struct bst *temp,int key) { if(temp==NULL) return 0; if(temp->data==key) return 1; else if(temp->data < key) search(temp->rc,key); else search(temp->lc,key); } void inorder(struct bst *root) { if(root==NULL) return; else { inorder(root->lc); printf("%d ",root->data); inorder(root->rc); } } void preorder(struct bst *root) { if(root==NULL) return; else { printf("%d ",root->data); preorder(root->lc); preorder(root->rc); } } void postorder(struct bst *root) { if(root==NULL) return; else { postorder(root->lc); postorder(root->rc); printf("%d ",root->data); } } struct bst* del(struct bst *root,int key) { if(root==NULL) return root; if(key > root->data) root->rc=del(root->rc,key); else if(key < root->data) root->lc=del(root->lc,key); else { if(root->lc==NULL) { struct bst *temp=root->rc; free(root); return temp; } else if(root->rc==NULL) { struct bst *temp=root->lc; free(root); return temp; } else { struct bst *temp=minval(root->rc); root->data=temp->data; root->rc=del(root->rc,temp->data); } } return root; } void main() { while(1){ int op; printf("1.INSERT\n2.DELETE\n3.TRAVERSE\n4.SEARCH\n5.EXIT\n"); printf("SELECT AN OPERATION:"); scanf("%d",&op); switch(op) { case 1: printf("Enter Data:"); int data; scanf("%d",&data); root=insert(root,data); break; case 2: printf("Enter key:"); int dl; scanf("%d",&dl); root=del(root,dl); break; case 3: printf("1.PREORDER\n2.INORDER\n3.POSTORDER\n"); int opt; printf("Select an Option:"); scanf("%d",&opt); if(opt==1) { printf("PREORDER:"); preorder(root); } else if(opt==2) { printf("INORDER:"); inorder(root); } else if(opt==3) { printf("POSTORDER:"); postorder(root); } printf("\n"); break; case 4: printf("Enter key"); int key,result; scanf("%d",&key); result=search(root,key); if(result==0) printf("No "); printf("Key Found\n"); break; case 5: exit(0); break; default:printf("INVALID INPUT\n"); } } }
the_stack_data/117689.c
#include <stdbool.h> #include <stdio.h> int main(void) { bool digit_seen[10][2] = {{false}}; int digit; long n; printf("Enter a number: "); scanf("%ld", &n); printf("Repeated digits: "); while (n > 0) { digit = n % 10; n /= 10; if (digit_seen[digit][0]) digit_seen[digit][1] = true; digit_seen[digit][0] = true; } for (int i = 0; i < 10; i++) { if (digit_seen[i][1]) printf("%d", i); } printf("\n"); return 0; }
the_stack_data/212643153.c
#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <unistd.h> #define PAGE_NUM 1024 void main(int argc, char **argv){ int fd, i; unsigned int *addr; unsigned int offset, count; long page_size, map_size; if(argc < 2){ printf("Usage: %s ADDRESS(hex) NUM(dec)\n", argv[0]); return; } fd = open( "/dev/mem", O_RDWR | O_SYNC ); if( fd == -1 ){ printf( "Can't open /dev/mem.\n" ); return; } offset = strtoul( argv[1], NULL, 16 ); count = strtoul( argv[2], NULL, 10 ); page_size = getpagesize(); map_size = page_size * PAGE_NUM; // Assign memory map addr = mmap( NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset & 0xFFFF0000); if( addr == MAP_FAILED ){ printf( "Error: mmap()\n" ); return; } // Read for( i = 0; i < count; i++ ){ printf( "%08X: %08X\n", ( (offset & 0xFFFFFFFC) + (i * 4) ), ( addr[((offset & 0x0000FFFC) /4 ) + i] ) ); } // Free munmap(addr, map_size); close(fd); return; }
the_stack_data/278060.c
#include <stdio.h> int main () { printf("Guten Morgen\n"); return 0; }
the_stack_data/150143154.c
#include <stdio.h> int main() { int c; while ((c=getchar())!=EOF) { if (c==' ') putchar('\n'); else putchar(c); } return 0; }
the_stack_data/59511597.c
#include<stdio.h> #include<stdlib.h> #include<signal.h> #include<unistd.h> #include<sys/wait.h> #include<string.h> int pid1,pid2; int pipe_fd[2]; void my_func(int sig_no) { if(sig_no == SIGINT){ printf("Receive SIGINT.\n"); kill(pid1,SIGUSR1); kill(pid2,SIGUSR1); } } void fun1(int sig_no) { if(sig_no == SIGUSR1){ printf("Child Process l is Killed by Parent!\n"); exit(0); } } void fun2(int sig_no) { if(sig_no == SIGUSR1){ printf("Child Process 2 is Killed by Parent!\n"); exit(0); } } int main(){ if(pipe(pipe_fd)<0){ printf("pipe create error "); return -1; } if(signal(SIGINT, my_func) == SIG_ERR) printf("can't catch SIGINT.\n'"); pid1=fork(); if(pid1==0){ signal(SIGINT,SIG_IGN); printf("process1 pid:%d\n",getpid()); if(signal(SIGUSR1,fun1) ==SIG_ERR) printf("can't catch SIGUER1\n"); int x=1; char w_buf[]={'I',' ','s','e','n','d',' ','y','o','u',' ','x',' ','t','i','m','e','s','.','\n','\0'}; while(1){ w_buf[11]=x-0+'0'; if(write(pipe_fd[1],w_buf,strlen(w_buf))==-1) printf("pipe write error\n"); x++; sleep(1); } } else{ pid2=fork(); if(pid2==0){ signal(SIGINT,SIG_IGN); printf("process2 pid:%d\n",getpid()); if(signal(SIGUSR1,fun2) ==SIG_ERR) printf("can't catch SIGUER1\n"); char r_buf[50]; while(1){ read(pipe_fd[0],r_buf,50); printf("%s",r_buf); } } } int p1state,p2state; waitpid(pid1,&p1state,0); waitpid(pid2,&p2state,0); close(pipe_fd[0]); close(pipe_fd[1]); printf("Parent Process is Killed!\n"); return 0; }
the_stack_data/131247.c
/* * -- SuperLU routine (version 2.0) -- * Univ. of California Berkeley, Xerox Palo Alto Research Center, * and Lawrence Berkeley National Lab. * November 15, 1997 * */ /* * File name: smyblas2.c * Purpose: * Level 2 BLAS operations: solves and matvec, written in C. * Note: * This is only used when the system lacks an efficient BLAS library. */ /* * Solves a dense UNIT lower triangular system. The unit lower * triangular matrix is stored in a 2D array M(1:nrow,1:ncol). * The solution will be returned in the rhs vector. */ /* local prototypes*/ void slsolve ( int, int, float *, float *); void susolve ( int, int, float *, float *); void smatvec ( int, int, int, float *, float *, float *); void slsolve ( int ldm, int ncol, float *M, float *rhs ) { int k; float x0, x1, x2, x3, x4, x5, x6, x7; float *M0; register float *Mki0, *Mki1, *Mki2, *Mki3, *Mki4, *Mki5, *Mki6, *Mki7; register int firstcol = 0; M0 = &M[0]; while ( firstcol < ncol - 7 ) { /* Do 8 columns */ Mki0 = M0 + 1; Mki1 = Mki0 + ldm + 1; Mki2 = Mki1 + ldm + 1; Mki3 = Mki2 + ldm + 1; Mki4 = Mki3 + ldm + 1; Mki5 = Mki4 + ldm + 1; Mki6 = Mki5 + ldm + 1; Mki7 = Mki6 + ldm + 1; x0 = rhs[firstcol]; x1 = rhs[firstcol+1] - x0 * *Mki0++; x2 = rhs[firstcol+2] - x0 * *Mki0++ - x1 * *Mki1++; x3 = rhs[firstcol+3] - x0 * *Mki0++ - x1 * *Mki1++ - x2 * *Mki2++; x4 = rhs[firstcol+4] - x0 * *Mki0++ - x1 * *Mki1++ - x2 * *Mki2++ - x3 * *Mki3++; x5 = rhs[firstcol+5] - x0 * *Mki0++ - x1 * *Mki1++ - x2 * *Mki2++ - x3 * *Mki3++ - x4 * *Mki4++; x6 = rhs[firstcol+6] - x0 * *Mki0++ - x1 * *Mki1++ - x2 * *Mki2++ - x3 * *Mki3++ - x4 * *Mki4++ - x5 * *Mki5++; x7 = rhs[firstcol+7] - x0 * *Mki0++ - x1 * *Mki1++ - x2 * *Mki2++ - x3 * *Mki3++ - x4 * *Mki4++ - x5 * *Mki5++ - x6 * *Mki6++; rhs[++firstcol] = x1; rhs[++firstcol] = x2; rhs[++firstcol] = x3; rhs[++firstcol] = x4; rhs[++firstcol] = x5; rhs[++firstcol] = x6; rhs[++firstcol] = x7; ++firstcol; for (k = firstcol; k < ncol; k++) rhs[k] = rhs[k] - x0 * *Mki0++ - x1 * *Mki1++ - x2 * *Mki2++ - x3 * *Mki3++ - x4 * *Mki4++ - x5 * *Mki5++ - x6 * *Mki6++ - x7 * *Mki7++; M0 += 8 * ldm + 8; } while ( firstcol < ncol - 3 ) { /* Do 4 columns */ Mki0 = M0 + 1; Mki1 = Mki0 + ldm + 1; Mki2 = Mki1 + ldm + 1; Mki3 = Mki2 + ldm + 1; x0 = rhs[firstcol]; x1 = rhs[firstcol+1] - x0 * *Mki0++; x2 = rhs[firstcol+2] - x0 * *Mki0++ - x1 * *Mki1++; x3 = rhs[firstcol+3] - x0 * *Mki0++ - x1 * *Mki1++ - x2 * *Mki2++; rhs[++firstcol] = x1; rhs[++firstcol] = x2; rhs[++firstcol] = x3; ++firstcol; for (k = firstcol; k < ncol; k++) rhs[k] = rhs[k] - x0 * *Mki0++ - x1 * *Mki1++ - x2 * *Mki2++ - x3 * *Mki3++; M0 += 4 * ldm + 4; } if ( firstcol < ncol - 1 ) { /* Do 2 columns */ Mki0 = M0 + 1; Mki1 = Mki0 + ldm + 1; x0 = rhs[firstcol]; x1 = rhs[firstcol+1] - x0 * *Mki0++; rhs[++firstcol] = x1; ++firstcol; for (k = firstcol; k < ncol; k++) rhs[k] = rhs[k] - x0 * *Mki0++ - x1 * *Mki1++; } } /* * Solves a dense upper triangular system. The upper triangular matrix is * stored in a 2-dim array M(1:ldm,1:ncol). The solution will be returned * in the rhs vector. */ void susolve ( ldm, ncol, M, rhs ) int ldm; /* in */ int ncol; /* in */ float *M; /* in */ float *rhs; /* modified */ { float xj; int jcol, j, irow; jcol = ncol - 1; for (j = 0; j < ncol; j++) { xj = rhs[jcol] / M[jcol + jcol*ldm]; /* M(jcol, jcol) */ rhs[jcol] = xj; for (irow = 0; irow < jcol; irow++) rhs[irow] -= xj * M[irow + jcol*ldm]; /* M(irow, jcol) */ jcol--; } } /* * Performs a dense matrix-vector multiply: Mxvec = Mxvec + M * vec. * The input matrix is M(1:nrow,1:ncol); The product is returned in Mxvec[]. */ void smatvec ( ldm, nrow, ncol, M, vec, Mxvec ) int ldm; /* in -- leading dimension of M */ int nrow; /* in */ int ncol; /* in */ float *M; /* in */ float *vec; /* in */ float *Mxvec; /* in/out */ { float vi0, vi1, vi2, vi3, vi4, vi5, vi6, vi7; float *M0; register float *Mki0, *Mki1, *Mki2, *Mki3, *Mki4, *Mki5, *Mki6, *Mki7; register int firstcol = 0; int k; M0 = &M[0]; while ( firstcol < ncol - 7 ) { /* Do 8 columns */ Mki0 = M0; Mki1 = Mki0 + ldm; Mki2 = Mki1 + ldm; Mki3 = Mki2 + ldm; Mki4 = Mki3 + ldm; Mki5 = Mki4 + ldm; Mki6 = Mki5 + ldm; Mki7 = Mki6 + ldm; vi0 = vec[firstcol++]; vi1 = vec[firstcol++]; vi2 = vec[firstcol++]; vi3 = vec[firstcol++]; vi4 = vec[firstcol++]; vi5 = vec[firstcol++]; vi6 = vec[firstcol++]; vi7 = vec[firstcol++]; for (k = 0; k < nrow; k++) Mxvec[k] += vi0 * *Mki0++ + vi1 * *Mki1++ + vi2 * *Mki2++ + vi3 * *Mki3++ + vi4 * *Mki4++ + vi5 * *Mki5++ + vi6 * *Mki6++ + vi7 * *Mki7++; M0 += 8 * ldm; } while ( firstcol < ncol - 3 ) { /* Do 4 columns */ Mki0 = M0; Mki1 = Mki0 + ldm; Mki2 = Mki1 + ldm; Mki3 = Mki2 + ldm; vi0 = vec[firstcol++]; vi1 = vec[firstcol++]; vi2 = vec[firstcol++]; vi3 = vec[firstcol++]; for (k = 0; k < nrow; k++) Mxvec[k] += vi0 * *Mki0++ + vi1 * *Mki1++ + vi2 * *Mki2++ + vi3 * *Mki3++ ; M0 += 4 * ldm; } while ( firstcol < ncol ) { /* Do 1 column */ Mki0 = M0; vi0 = vec[firstcol++]; for (k = 0; k < nrow; k++) Mxvec[k] += vi0 * *Mki0++; M0 += ldm; } }
the_stack_data/116501.c
#include <stdio.h> #define MAX 100 int main() { int i, n, a[MAX], count_even = 0, count_odd = 0, sum_even = 0, sum_odd = 0; scanf("%d", &n); for (i = 0; i < n; ++i) scanf("%d", &a[i]); for (i = 0; i < n; ++i) { if (a[i] % 2) { count_odd++; sum_odd += a[i]; } else { count_even++; sum_even += a[i]; } } printf("Sum even: %d\nSum odd: %d\n", sum_even, sum_odd); printf("Ratio: %.2f\n", (float)count_even / count_odd); return 0; }
the_stack_data/62637947.c
#include "syscall.h" #if HAVE_LINUX_AIO_ABI_H || HAVE_LINUX_IO_URING_H #include <sys/syscall.h> #include <unistd.h> #endif #if HAVE_LINUX_AIO_ABI_H int io_setup(unsigned nr_events, aio_context_t *ctx_idp) { return (int)syscall(__NR_io_setup, nr_events, ctx_idp); } int io_destroy(aio_context_t ctx_id) { return (int)syscall(__NR_io_destroy, ctx_id); } int io_submit(aio_context_t ctx_id, long nr, struct iocb **iocbpp) { return (int)syscall(__NR_io_submit, ctx_id, nr, iocbpp); } int io_getevents(aio_context_t ctx_id, long min_nr, long nr, struct io_event *events, struct timespec *timeout) { return (int)syscall(__NR_io_getevents, ctx_id, min_nr, nr, events, timeout); } #endif #if HAVE_LINUX_IO_URING_H int io_uring_register(int fd, unsigned int opcode, const void *arg, unsigned int nr_args) { return (int)syscall(__NR_io_uring_register, fd, opcode, arg, nr_args); } int io_uring_setup(unsigned int entries, struct io_uring_params *p) { return (int)syscall(__NR_io_uring_setup, entries, p); } int io_uring_enter(int fd, unsigned int to_submit, unsigned int min_complete, unsigned int flags, sigset_t *sig) { return (int)syscall(__NR_io_uring_enter, fd, to_submit, min_complete, flags, sig, _NSIG / 8); } #endif
the_stack_data/220456995.c
// RUN: %clam --inline --lower-select --lower-unsigned-icmp --crab-print-invariants=false --crab-dom=boxes --crab-check=assert %opts --crab-sanity-checks "%s" 2>&1 | OutputCheck -l debug %s // CHECK: ^0 Number of total safe checks$ // CHECK: ^0 Number of total error checks$ // CHECK: ^1 Number of total warning checks$ extern void __VERIFIER_error() __attribute__ ((__noreturn__)); extern char __VERIFIER_nondet_char(void); extern int __VERIFIER_nondet_int(void); extern long __VERIFIER_nondet_long(void); extern void *__VERIFIER_nondet_pointer(void); extern int __VERIFIER_nondet_int(); /* Generated by CIL v. 1.3.6 */ /* print_CIL_Input is true */ int ssl3_connect(int initial_state ) { int s__info_callback = __VERIFIER_nondet_int() ; int s__in_handshake = __VERIFIER_nondet_int() ; int s__state ; int s__new_session ; int s__server ; int s__version = __VERIFIER_nondet_int() ; int s__type ; int s__init_num ; int s__bbio = __VERIFIER_nondet_int() ; int s__wbio = __VERIFIER_nondet_int() ; int s__hit = __VERIFIER_nondet_int() ; int s__rwstate ; int s__init_buf___0 = __VERIFIER_nondet_int() ; int s__debug = __VERIFIER_nondet_int() ; int s__shutdown ; int s__ctx__info_callback = __VERIFIER_nondet_int() ; int s__ctx__stats__sess_connect_renegotiate = __VERIFIER_nondet_int() ; int s__ctx__stats__sess_connect = __VERIFIER_nondet_int() ; int s__ctx__stats__sess_hit = __VERIFIER_nondet_int() ; int s__ctx__stats__sess_connect_good = __VERIFIER_nondet_int() ; int s__s3__change_cipher_spec ; int s__s3__flags = __VERIFIER_nondet_int() ; int s__s3__delay_buf_pop_ret ; int s__s3__tmp__cert_req = __VERIFIER_nondet_int() ; int s__s3__tmp__new_compression = __VERIFIER_nondet_int() ; int s__s3__tmp__reuse_message = __VERIFIER_nondet_int() ; int s__s3__tmp__new_cipher = __VERIFIER_nondet_int() ; int s__s3__tmp__new_cipher__algorithms = __VERIFIER_nondet_int() ; int s__s3__tmp__next_state___0 ; int s__s3__tmp__new_compression__id = __VERIFIER_nondet_int() ; int s__session__cipher ; int s__session__compress_meth ; int buf ; unsigned long tmp ; unsigned long l ; int num1 = __VERIFIER_nondet_int() ; int cb ; int ret ; int new_state ; int state ; int skip ; int tmp___0 ; int tmp___1 = __VERIFIER_nondet_int() ; int tmp___2 = __VERIFIER_nondet_int() ; int tmp___3 = __VERIFIER_nondet_int() ; int tmp___4 = __VERIFIER_nondet_int() ; int tmp___5 = __VERIFIER_nondet_int() ; int tmp___6 = __VERIFIER_nondet_int() ; int tmp___7 = __VERIFIER_nondet_int() ; int tmp___8 = __VERIFIER_nondet_int() ; int tmp___9 = __VERIFIER_nondet_int() ; int blastFlag ; int __cil_tmp55 ; unsigned long __cil_tmp56 ; long __cil_tmp57 ; long __cil_tmp58 ; long __cil_tmp59 ; long __cil_tmp60 ; long __cil_tmp61 ; long __cil_tmp62 ; long __cil_tmp63 ; long __cil_tmp64 ; long __cil_tmp65 ; { ; s__state = initial_state; blastFlag = 0; tmp = __VERIFIER_nondet_int(); cb = 0; ret = -1; skip = 0; tmp___0 = 0; if (s__info_callback != 0) { cb = s__info_callback; } else { if (s__ctx__info_callback != 0) { cb = s__ctx__info_callback; } } s__in_handshake ++; if (tmp___1 + 12288) { if (tmp___2 + 16384) { } } { while (1) { while_0_continue: /* CIL Label */ ; state = s__state; if (s__state == 12292) { goto switch_1_12292; } else { if (s__state == 16384) { goto switch_1_16384; } else { if (s__state == 4096) { goto switch_1_4096; } else { if (s__state == 20480) { goto switch_1_20480; } else { if (s__state == 4099) { goto switch_1_4099; } else { if (s__state == 4368) { goto switch_1_4368; } else { if (s__state == 4369) { goto switch_1_4369; } else { if (s__state == 4384) { goto switch_1_4384; } else { if (s__state == 4385) { goto switch_1_4385; } else { if (s__state == 4400) { goto switch_1_4400; } else { if (s__state == 4401) { goto switch_1_4401; } else { if (s__state == 4416) { goto switch_1_4416; } else { if (s__state == 4417) { goto switch_1_4417; } else { if (s__state == 4432) { goto switch_1_4432; } else { if (s__state == 4433) { goto switch_1_4433; } else { if (s__state == 4448) { goto switch_1_4448; } else { if (s__state == 4449) { goto switch_1_4449; } else { if (s__state == 4464) { goto switch_1_4464; } else { if (s__state == 4465) { goto switch_1_4465; } else { if (s__state == 4466) { goto switch_1_4466; } else { if (s__state == 4467) { goto switch_1_4467; } else { if (s__state == 4480) { goto switch_1_4480; } else { if (s__state == 4481) { goto switch_1_4481; } else { if (s__state == 4496) { goto switch_1_4496; } else { if (s__state == 4497) { goto switch_1_4497; } else { if (s__state == 4512) { goto switch_1_4512; } else { if (s__state == 4513) { goto switch_1_4513; } else { if (s__state == 4528) { goto switch_1_4528; } else { if (s__state == 4529) { goto switch_1_4529; } else { if (s__state == 4560) { goto switch_1_4560; } else { if (s__state == 4561) { goto switch_1_4561; } else { if (s__state == 4352) { goto switch_1_4352; } else { if (s__state == 3) { goto switch_1_3; } else { goto switch_1_default; if (0) { switch_1_12292: s__new_session = 1; s__state = 4096; s__ctx__stats__sess_connect_renegotiate ++; switch_1_16384: ; switch_1_4096: ; switch_1_20480: ; switch_1_4099: s__server = 0; if (cb != 0) { } { __cil_tmp55 = s__version + 65280; if (__cil_tmp55 != 768) { ret = -1; goto end; } } s__type = 4096; if (s__init_buf___0 == 0) { buf = __VERIFIER_nondet_int(); if (buf == 0) { ret = -1; goto end; } if (! tmp___3) { ret = -1; goto end; } s__init_buf___0 = buf; } if (! tmp___4) { ret = -1; goto end; } if (! tmp___5) { ret = -1; goto end; } s__state = 4368; s__ctx__stats__sess_connect ++; s__init_num = 0; goto switch_1_break; switch_1_4368: ; switch_1_4369: s__shutdown = 0; ret = __VERIFIER_nondet_int(); if (blastFlag == 0) { blastFlag = 1; } if (ret <= 0) { goto end; } s__state = 4384; s__init_num = 0; if (s__bbio != s__wbio) { } goto switch_1_break; switch_1_4384: ; switch_1_4385: ret = __VERIFIER_nondet_int(); if (blastFlag == 1) { blastFlag = 2; } if (ret <= 0) { goto end; } if (s__hit) { s__state = 4560; } else { s__state = 4400; } s__init_num = 0; goto switch_1_break; switch_1_4400: ; switch_1_4401: ; { __cil_tmp56 = (unsigned long )s__s3__tmp__new_cipher__algorithms; if (__cil_tmp56 + 256UL) { skip = 1; } else { ret = __VERIFIER_nondet_int(); if (blastFlag == 2) { blastFlag = 3; } else { if (blastFlag == 4) { blastFlag = 5; } } if (ret <= 0) { goto end; } } } s__state = 4416; s__init_num = 0; goto switch_1_break; switch_1_4416: ; switch_1_4417: ret = __VERIFIER_nondet_int(); if (blastFlag == 3) { blastFlag = 4; } if (ret <= 0) { goto end; } s__state = 4432; s__init_num = 0; if (! tmp___6) { ret = -1; goto end; } goto switch_1_break; switch_1_4432: ; switch_1_4433: ret = __VERIFIER_nondet_int(); if (blastFlag == 4) { goto ERROR; } if (ret <= 0) { goto end; } s__state = 4448; s__init_num = 0; goto switch_1_break; switch_1_4448: ; switch_1_4449: ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } if (s__s3__tmp__cert_req) { s__state = 4464; } else { s__state = 4480; } s__init_num = 0; goto switch_1_break; switch_1_4464: ; switch_1_4465: ; switch_1_4466: ; switch_1_4467: ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } s__state = 4480; s__init_num = 0; goto switch_1_break; switch_1_4480: ; switch_1_4481: ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } l = (unsigned long )s__s3__tmp__new_cipher__algorithms; if (s__s3__tmp__cert_req == 1) { s__state = 4496; } else { s__state = 4512; s__s3__change_cipher_spec = 0; } s__init_num = 0; goto switch_1_break; switch_1_4496: ; switch_1_4497: ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } s__state = 4512; s__init_num = 0; s__s3__change_cipher_spec = 0; goto switch_1_break; switch_1_4512: ; switch_1_4513: ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } s__state = 4528; s__init_num = 0; s__session__cipher = s__s3__tmp__new_cipher; if (s__s3__tmp__new_compression == 0) { s__session__compress_meth = 0; } else { s__session__compress_meth = s__s3__tmp__new_compression__id; } if (! tmp___7) { ret = -1; goto end; } if (! tmp___8) { ret = -1; goto end; } goto switch_1_break; switch_1_4528: ; switch_1_4529: ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } s__state = 4352; __cil_tmp57 = (long )s__s3__flags; __cil_tmp58 = __cil_tmp57 - 5; s__s3__flags = (int )__cil_tmp58; if (s__hit) { s__s3__tmp__next_state___0 = 3; { __cil_tmp59 = (long )s__s3__flags; if (__cil_tmp59 + 2L) { s__state = 3; __cil_tmp60 = (long )s__s3__flags; __cil_tmp61 = __cil_tmp60 * 4L; s__s3__flags = (int )__cil_tmp61; s__s3__delay_buf_pop_ret = 0; } } } else { s__s3__tmp__next_state___0 = 4560; } s__init_num = 0; goto switch_1_break; switch_1_4560: ; switch_1_4561: ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } if (s__hit) { s__state = 4512; } else { s__state = 3; } s__init_num = 0; goto switch_1_break; switch_1_4352: { __cil_tmp62 = (long )num1; if (__cil_tmp62 > 0L) { s__rwstate = 2; num1 = tmp___9; { __cil_tmp63 = (long )num1; if (__cil_tmp63 <= 0L) { ret = -1; goto end; } } s__rwstate = 1; } } s__state = s__s3__tmp__next_state___0; goto switch_1_break; switch_1_3: if (s__init_buf___0 != 0) { s__init_buf___0 = 0; } { __cil_tmp64 = (long )s__s3__flags; __cil_tmp65 = __cil_tmp64 + 4L; if (! __cil_tmp65) { } } s__init_num = 0; s__new_session = 0; if (s__hit) { s__ctx__stats__sess_hit ++; } ret = 1; s__ctx__stats__sess_connect_good ++; if (cb != 0) { } goto end; switch_1_default: ret = -1; goto end; } else { switch_1_break: ; } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } if (! s__s3__tmp__reuse_message) { if (! skip) { if (s__debug) { ret = __VERIFIER_nondet_int(); if (ret <= 0) { goto end; } } if (cb != 0) { if (s__state != state) { new_state = s__state; s__state = state; s__state = new_state; } } } } skip = 0; } while_0_break: /* CIL Label */ ; } end: s__in_handshake --; if (cb != 0) { } return (ret); ERROR: __VERIFIER_error(); return (-1); } } int main(void) { int s ; { { s = 12292; ssl3_connect(s); } return (0); } }
the_stack_data/173577369.c
/* Author @nimishbongale Version 1.0.4 Date 26/09/2018 A program which performs binary search */ #include <stdio.h> int m; void binsearch(int a[],int l,int u,int ele)//recursive function to perform binary search { m=(l+u)/2; if(a[m]==ele) { printf("Element found at pos %d!",(m+1)); return; } else if(u==(l+1)) { printf("Element not found!"); return; } else if(ele>a[m]) binsearch(a,m,u,ele); else binsearch(a,l,m,ele); } int main()//driver function { int n,num,i; printf("Enter the no. of elements: "); scanf("%d",&num); int b[num]; printf("Enter the sorted array\n");//accepting input for(i=0;i<num;i++) scanf("%d",&b[i]); printf("Enter the element to be searched for: "); scanf("%d",&n); binsearch(b,0,num,n); return 0; }
the_stack_data/146949.c
#include <stdio.h> #include <math.h> #define N 21 #define font 178 void fill_ring(int coor[N][N], int r1, int r2) { int i, j; for(j = 0; j <= N-1; j++) { for(i = 0; i <= N-1; i++) { if(pow(i-((N-1)/2), 2) + pow(j-((N-1)/2), 2) < pow(r1, 2) && !(pow(i-((N-1)/2), 2) + pow(j-((N-1)/2), 2) < pow(r2, 2))) { coor[j][i] = 1; } } } } void draw_ring(int coor[N][N]) { int i, j; for(j = 0; j <= N-1; j++) { for(i = 0; i <= N-1; i++) { if(coor[j][i] == 1) { printf("%c", font); } else { printf(" "); } } printf("\n"); } } int main(void) { int coordinate[N][N] = {0}; int r1, r2; printf("Please enter radius of big circle: "); scanf("%i", &r1); printf("Please enter radius of small circle: "); scanf("%i", &r2); fill_ring(coordinate, r1, r2); draw_ring(coordinate); return 0; }
the_stack_data/27532.c
#include <stdlib.h> #include <stdio.h> #include "omp.h" int main() { #pragma omp parallel { int ID = omp_get_thread_num(); printf("Hello the current thread id is (%d)\n", ID); } }
the_stack_data/1058327.c
// example to test uninterpreted function #include <stdint.h> uint32_t BlackBox(uint32_t a) { return a; } uint32_t Reference(uint32_t a, uint32_t b) { uint32_t c = 2 * a; uint32_t d = 2 * b; uint32_t e = c + d; uint32_t res = BlackBox(e); return res; } uint32_t Target(uint32_t a, uint32_t b) { uint32_t c = a + b; uint32_t d = 2 * c; uint32_t res = BlackBox(d); return res; }
the_stack_data/184517737.c
#include <stdio.h> int main(void) { int age, x = 0, sum = 0; float avg; while(1) { scanf("%d", &age); if (age > 0) { sum += age; x++; } if (age < 0) break; } avg = (float) sum / x; printf("%.2f\n", avg); return 0; }
the_stack_data/31387440.c
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <pthread.h> #define MAX_STRING 180 const int vocab_hash_size = 500000000; // Maximum 500M entries in the vocabulary typedef float real; // Precision of float numbers struct vocab_word { long long cn; char *word; }; char train_file[MAX_STRING], output_file[MAX_STRING]; struct vocab_word *vocab; int debug_mode = 2, min_count = 5, *vocab_hash, min_reduce = 1; long long vocab_max_size = 10000, vocab_size = 0; long long train_words = 0; real threshold = 100; unsigned long long next_random = 1; // Reads a single word from a file, assuming space + tab + EOL to be word boundaries void ReadWord(char *word, FILE *fin) { int a = 0, ch; while (!feof(fin)) { ch = fgetc(fin); if (ch == 13) continue; if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { if (a > 0) { if (ch == '\n') ungetc(ch, fin); break; } if (ch == '\n') { strcpy(word, (char *)"</s>"); return; } else continue; } word[a] = ch; a++; if (a >= MAX_STRING - 1) a--; // Truncate too long words } word[a] = 0; } // Returns hash value of a word int GetWordHash(char *word) { unsigned long long a, hash = 1; for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a]; hash = hash % vocab_hash_size; return hash; } // Returns position of a word in the vocabulary; if the word is not found, returns -1 int SearchVocab(char *word) { unsigned int hash = GetWordHash(word); while (1) { if (vocab_hash[hash] == -1) return -1; if (!strcmp(word, vocab[vocab_hash[hash]].word)) return vocab_hash[hash]; hash = (hash + 1) % vocab_hash_size; } return -1; } // Reads a word and returns its index in the vocabulary int ReadWordIndex(FILE *fin) { char word[MAX_STRING]; ReadWord(word, fin); if (feof(fin)) return -1; return SearchVocab(word); } // Adds a word to the vocabulary int AddWordToVocab(char *word) { unsigned int hash, length = strlen(word) + 1; if (length > MAX_STRING) length = MAX_STRING; vocab[vocab_size].word = (char *)calloc(length, sizeof(char)); strcpy(vocab[vocab_size].word, word); vocab[vocab_size].cn = 0; vocab_size++; // Reallocate memory if needed if (vocab_size + 2 >= vocab_max_size) { vocab_max_size += 10000; vocab=(struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word)); } hash = GetWordHash(word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash]=vocab_size - 1; return vocab_size - 1; } // Used later for sorting by word counts int VocabCompare(const void *a, const void *b) { return ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn; } // Sorts the vocabulary by frequency using word counts void SortVocab() { int a; unsigned int hash; // Sort the vocabulary and keep </s> at the first position qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare); for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; for (a = 0; a < vocab_size; a++) { // Words occuring less than min_count times will be discarded from the vocab if (vocab[a].cn < min_count) { vocab_size--; free(vocab[vocab_size].word); } else { // Hash will be re-computed, as after the sorting it is not actual hash = GetWordHash(vocab[a].word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash] = a; } } vocab = (struct vocab_word *)realloc(vocab, vocab_size * sizeof(struct vocab_word)); } // Reduces the vocabulary by removing infrequent tokens void ReduceVocab() { int a, b = 0; unsigned int hash; for (a = 0; a < vocab_size; a++) if (vocab[a].cn > min_reduce) { vocab[b].cn = vocab[a].cn; vocab[b].word = vocab[a].word; b++; } else free(vocab[a].word); vocab_size = b; for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; for (a = 0; a < vocab_size; a++) { // Hash will be re-computed, as it is not actual hash = GetWordHash(vocab[a].word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash] = a; } fflush(stdout); min_reduce++; } void LearnVocabFromTrainFile() { char word[MAX_STRING], last_word[MAX_STRING], bigram_word[MAX_STRING * 2]; FILE *fin; long long a, i, start = 1; for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; fin = fopen(train_file, "rb"); if (fin == NULL) { printf("ERROR: training data file not found!\n"); exit(1); } vocab_size = 0; AddWordToVocab((char *)"</s>"); while (1) { ReadWord(word, fin); if (feof(fin)) break; if (!strcmp(word, "</s>")) { start = 1; continue; } else start = 0; train_words++; if ((debug_mode > 1) && (train_words % 100000 == 0)) { printf("Words processed: %lldK Vocab size: %lldK %c", train_words / 1000, vocab_size / 1000, 13); fflush(stdout); } i = SearchVocab(word); if (i == -1) { a = AddWordToVocab(word); vocab[a].cn = 1; } else vocab[i].cn++; if (start) continue; sprintf(bigram_word, "%s_%s", last_word, word); bigram_word[MAX_STRING - 1] = 0; strcpy(last_word, word); i = SearchVocab(bigram_word); if (i == -1) { a = AddWordToVocab(bigram_word); vocab[a].cn = 1; } else vocab[i].cn++; if (vocab_size > vocab_hash_size * 0.7) ReduceVocab(); } SortVocab(); if (debug_mode > 0) { printf("\nVocab size (unigrams + bigrams): %lld\n", vocab_size); printf("Words in train file: %lld\n", train_words); } fclose(fin); } void TrainModel() { long long pa = 0, pb = 0, pab = 0, oov, i, li = -1, cn = 0; char word[MAX_STRING], last_word[MAX_STRING], bigram_word[MAX_STRING * 2]; real score; FILE *fo, *fin; printf("Starting training using file %s\n", train_file); LearnVocabFromTrainFile(); fin = fopen(train_file, "rb"); fo = fopen(output_file, "wb"); word[0] = 0; while (1) { strcpy(last_word, word); ReadWord(word, fin); if (feof(fin)) break; if (!strcmp(word, "</s>")) { fprintf(fo, "\n"); continue; } cn++; if ((debug_mode > 1) && (cn % 100000 == 0)) { printf("Words written: %lldK%c", cn / 1000, 13); fflush(stdout); } oov = 0; i = SearchVocab(word); if (i == -1) oov = 1; else pb = vocab[i].cn; if (li == -1) oov = 1; li = i; sprintf(bigram_word, "%s_%s", last_word, word); bigram_word[MAX_STRING - 1] = 0; i = SearchVocab(bigram_word); if (i == -1) oov = 1; else pab = vocab[i].cn; if (pa < min_count) oov = 1; if (pb < min_count) oov = 1; if (oov) score = 0; else score = (pab - min_count) / (real)pa / (real)pb * (real)train_words; if (score > threshold) { fprintf(fo, "_%s", word); pb = 0; } else fprintf(fo, " %s", word); pa = pb; } fclose(fo); fclose(fin); } int ArgPos(char *str, int argc, char **argv) { int a; for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) { if (a == argc - 1) { printf("Argument missing for %s\n", str); exit(1); } return a; } return -1; } int main(int argc, char **argv) { int i; if (argc == 1) { printf("WORD2PHRASE tool v0.1a\n\n"); printf("Options:\n"); printf("Parameters for training:\n"); printf("\t-train <file>\n"); printf("\t\tUse text data from <file> to train the model\n"); printf("\t-output <file>\n"); printf("\t\tUse <file> to save the resulting word vectors / word clusters / phrases\n"); printf("\t-min-count <int>\n"); printf("\t\tThis will discard words that appear less than <int> times; default is 5\n"); printf("\t-threshold <float>\n"); printf("\t\t The <float> value represents threshold for forming the phrases (higher means less phrases); default 100\n"); printf("\t-debug <int>\n"); printf("\t\tSet the debug mode (default = 2 = more info during training)\n"); printf("\nExamples:\n"); printf("./word2phrase -train text.txt -output phrases.txt -threshold 100 -debug 2\n\n"); return 0; } if ((i = ArgPos((char *)"-train", argc, argv)) > 0) strcpy(train_file, argv[i + 1]); if ((i = ArgPos((char *)"-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-output", argc, argv)) > 0) strcpy(output_file, argv[i + 1]); if ((i = ArgPos((char *)"-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-threshold", argc, argv)) > 0) threshold = atof(argv[i + 1]); vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word)); vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int)); TrainModel(); return 0; }
the_stack_data/178266717.c
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers // Copyright (c) 2014-2018, The Monero Project // Copyright (c) 2014-2018, The Aeon Project // Copyright (c) 2018-2019, The TurtleCoin Developers // // Please see the included LICENSE file for more information. /* This file contains the portable version of the slow-hash routines for the CryptoNight hashing algorithm */ #if !(!defined NO_AES && (defined(__arm__) || defined(__aarch64__))) \ && !(!defined NO_AES && (defined(__x86_64__) || (defined(_MSC_VER) && defined(_WIN64)))) #pragma message("info: Using slow-hash-portable.c") #include "slow-hash-common.h" void slow_hash_allocate_state(void) { // Do nothing, this is just to maintain compatibility with the upgraded slow-hash.c return; } void slow_hash_free_state(void) { // As above return; } #if defined(__GNUC__) #define RDATA_ALIGN16 __attribute__((aligned(16))) #define STATIC static #define INLINE inline #else /* defined(__GNUC__) */ #define RDATA_ALIGN16 #define STATIC static #define INLINE #endif /* defined(__GNUC__) */ #define U64(x) ((uint64_t *)(x)) static void (*const extra_hashes[4])(const void *, size_t, char *) = {hash_extra_blake, hash_extra_groestl, hash_extra_jh, hash_extra_skein}; extern void aesb_single_round(const uint8_t *in, uint8_t *out, const uint8_t *expandedKey); extern void aesb_pseudo_round(const uint8_t *in, uint8_t *out, const uint8_t *expandedKey); static void mul(const uint8_t *a, const uint8_t *b, uint8_t *res) { uint64_t a0, b0; uint64_t hi, lo; a0 = SWAP64LE(((uint64_t *)a)[0]); b0 = SWAP64LE(((uint64_t *)b)[0]); lo = mul128(a0, b0, &hi); ((uint64_t *)res)[0] = SWAP64LE(hi); ((uint64_t *)res)[1] = SWAP64LE(lo); } static void sum_half_blocks(uint8_t *a, const uint8_t *b) { uint64_t a0, a1, b0, b1; a0 = SWAP64LE(((uint64_t *)a)[0]); a1 = SWAP64LE(((uint64_t *)a)[1]); b0 = SWAP64LE(((uint64_t *)b)[0]); b1 = SWAP64LE(((uint64_t *)b)[1]); a0 += b0; a1 += b1; ((uint64_t *)a)[0] = SWAP64LE(a0); ((uint64_t *)a)[1] = SWAP64LE(a1); } static void copy_block(uint8_t *dst, const uint8_t *src) { memcpy(dst, src, AES_BLOCK_SIZE); } static void swap_blocks(uint8_t *a, uint8_t *b) { uint64_t t[2]; U64(t)[0] = U64(a)[0]; U64(t)[1] = U64(a)[1]; U64(a)[0] = U64(b)[0]; U64(a)[1] = U64(b)[1]; U64(b)[0] = U64(t)[0]; U64(b)[1] = U64(t)[1]; } static void xor_blocks(uint8_t *a, const uint8_t *b) { size_t i; for (i = 0; i < AES_BLOCK_SIZE; i++) { a[i] ^= b[i]; } } static void xor64(uint8_t *left, const uint8_t *right) { size_t i; for (i = 0; i < 8; ++i) { left[i] ^= right[i]; } } void cn_slow_hash( const void *data, size_t length, char *hash, int light, int variant, int prehashed, uint32_t page_size, uint32_t scratchpad, uint32_t iterations) { uint32_t init_rounds = (scratchpad / INIT_SIZE_BYTE); uint32_t aes_rounds = (iterations / 2); size_t lightFlag = (light ? 2 : 1); uint8_t text[INIT_SIZE_BYTE]; uint8_t a[AES_BLOCK_SIZE]; uint8_t b[AES_BLOCK_SIZE * 2]; uint8_t c[AES_BLOCK_SIZE]; uint8_t c1[AES_BLOCK_SIZE]; uint8_t d[AES_BLOCK_SIZE]; RDATA_ALIGN16 uint8_t expandedKey[256]; union cn_slow_hash_state state; size_t i, j; uint8_t *p = NULL; oaes_ctx *aes_ctx; static void (*const extra_hashes[4])(const void *, size_t, char *) = { hash_extra_blake, hash_extra_groestl, hash_extra_jh, hash_extra_skein}; #ifndef FORCE_USE_HEAP uint8_t long_state[page_size]; #else /* FORCE_USE_HEAP */ #pragma message("warning: ACTIVATING FORCE_USE_HEAP IN slow-hash-portable.c") uint8_t *long_state = (uint8_t *)malloc(page_size); #endif /* FORCE_USE_HEAP */ if (prehashed) { memcpy(&state.hs, data, length); } else { hash_process(&state.hs, data, length); } memcpy(text, state.init, INIT_SIZE_BYTE); aes_ctx = (oaes_ctx *)oaes_alloc(); oaes_key_import_data(aes_ctx, state.hs.b, AES_KEY_SIZE); VARIANT1_PORTABLE_INIT(); VARIANT2_PORTABLE_INIT(); // use aligned data memcpy(expandedKey, aes_ctx->key->exp_data, aes_ctx->key->exp_data_len); for (i = 0; i < init_rounds; i++) { for (j = 0; j < INIT_SIZE_BLK; j++) aesb_pseudo_round(&text[AES_BLOCK_SIZE * j], &text[AES_BLOCK_SIZE * j], expandedKey); memcpy(&long_state[i * INIT_SIZE_BYTE], text, INIT_SIZE_BYTE); } U64(a)[0] = U64(&state.k[0])[0] ^ U64(&state.k[32])[0]; U64(a)[1] = U64(&state.k[0])[1] ^ U64(&state.k[32])[1]; U64(b)[0] = U64(&state.k[16])[0] ^ U64(&state.k[48])[0]; U64(b)[1] = U64(&state.k[16])[1] ^ U64(&state.k[48])[1]; for (i = 0; i < aes_rounds; i++) { #define MASK(div) ((uint32_t)(((page_size / AES_BLOCK_SIZE) / (div)-1) << 4)) #define state_index(x, div) ((*(uint32_t *)x) & MASK(div)) // Iteration 1 j = state_index(a, lightFlag); p = &long_state[j]; aesb_single_round(p, p, a); copy_block(c1, p); VARIANT2_PORTABLE_SHUFFLE_ADD(long_state, j); xor_blocks(p, b); VARIANT1_1(p); // Iteration 2 j = state_index(c1, lightFlag); p = &long_state[j]; copy_block(c, p); VARIANT2_PORTABLE_INTEGER_MATH(c, c1); mul(c1, c, d); VARIANT2_2_PORTABLE(); VARIANT2_PORTABLE_SHUFFLE_ADD(long_state, j); sum_half_blocks(a, d); swap_blocks(a, c); xor_blocks(a, c); VARIANT1_2(c + 8); copy_block(p, c); if (variant >= 2) { copy_block(b + AES_BLOCK_SIZE, b); } copy_block(b, c1); } memcpy(text, state.init, INIT_SIZE_BYTE); oaes_key_import_data(aes_ctx, &state.hs.b[32], AES_KEY_SIZE); memcpy(expandedKey, aes_ctx->key->exp_data, aes_ctx->key->exp_data_len); for (i = 0; i < init_rounds; i++) { for (j = 0; j < INIT_SIZE_BLK; j++) { xor_blocks(&text[j * AES_BLOCK_SIZE], &long_state[i * INIT_SIZE_BYTE + j * AES_BLOCK_SIZE]); aesb_pseudo_round(&text[AES_BLOCK_SIZE * j], &text[AES_BLOCK_SIZE * j], expandedKey); } } oaes_free((OAES_CTX **)&aes_ctx); memcpy(state.init, text, INIT_SIZE_BYTE); hash_permutation(&state.hs); extra_hashes[state.hs.b[0] & 3](&state, 200, hash); oaes_free((OAES_CTX **)&aes_ctx); #ifdef FORCE_USE_HEAP free(long_state); #endif /* FORCE_USE_HEAP */ } #endif
the_stack_data/68836.c
/* * Copyright (C) 2009-2013, Lorenzo Pallara [email protected] * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/types.h> #include <sys/time.h> #include <arpa/inet.h> #include <unistd.h> #include <time.h> #ifdef __APPLE__ #include <errno.h> // #define CLOCK_REALTIME 0x2d4e1588 // #define CLOCK_MONOTONIC 0x0 /* * Bellow we provide an alternative for clock_gettime, * which is not implemented in Mac OS X. */ // static inline int clock_gettime(int clock_id, struct timespec *ts) // { // struct timeval tv; // if (clock_id != CLOCK_REALTIME) // { // errno = EINVAL; // return -1; // } // if (gettimeofday(&tv, NULL) < 0) // { // return -1; // } // ts->tv_sec = tv.tv_sec; // ts->tv_nsec = tv.tv_usec * 1000; // return 0; // } #endif #define TS_PACKET_SIZE 188 long long int usecDiff(struct timespec* time_stop, struct timespec* time_start) { long long int temp = 0; long long int utemp = 0; if (time_stop && time_start) { if (time_stop->tv_nsec >= time_start->tv_nsec) { utemp = time_stop->tv_nsec - time_start->tv_nsec; temp = time_stop->tv_sec - time_start->tv_sec; } else { utemp = time_stop->tv_nsec + 1000000000 - time_start->tv_nsec; temp = time_stop->tv_sec - 1 - time_start->tv_sec; } if (temp >= 0 && utemp >= 0) { temp = (temp * 1000000000) + utemp; } else { fprintf(stderr, "start time %ld.%ld is after stop time %ld.%ld\n", time_start->tv_sec, time_start->tv_nsec, time_stop->tv_sec, time_stop->tv_nsec); temp = -1; } } else { fprintf(stderr, "memory is garbaged?\n"); temp = -1; } return temp / 1000; } int main (int argc, char *argv[]) { int sockfd; int len; int rc; int sent; int transport_fd; struct sockaddr_in addr; unsigned long int packet_size; char* tsfile; unsigned char* send_buf; unsigned int bitrate; unsigned long long int packet_time; unsigned long long int real_time; struct timespec time_start; struct timespec time_stop; struct timespec nano_sleep_packet; memset(&addr, 0, sizeof(addr)); memset(&time_start, 0, sizeof(time_start)); memset(&time_stop, 0, sizeof(time_stop)); memset(&nano_sleep_packet, 0, sizeof(nano_sleep_packet)); if(argc < 5 ) { fprintf(stderr, "Usage: %s file.ts ipaddr port bitrate [ts_packet_per_ip_packet]\n", argv[0]); fprintf(stderr, "ts_packet_per_ip_packet default is 7\n"); fprintf(stderr, "bit rate refers to transport stream bit rate\n"); fprintf(stderr, "zero bitrate is 100.000.000 bps\n"); return 0; } else { tsfile = argv[1]; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(argv[2]); addr.sin_port = htons(atoi(argv[3])); bitrate = atoi(argv[4]); if (bitrate <= 0) { bitrate = 100000000; } if (argc >= 6) { packet_size = strtoul(argv[5], 0, 0) * TS_PACKET_SIZE; } else { packet_size = 7 * TS_PACKET_SIZE; } } sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd < 0) { fprintf(stderr, "socket(): error "); return 0; } transport_fd = open(tsfile, O_RDONLY); if(transport_fd < 0) { fprintf(stderr, "can't open file %s\n", tsfile); close(sockfd); return 0; } rc = connect(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)); if(rc < 0) { fprintf(stderr, "connect() error\n"); close(transport_fd); close(sockfd); return 0; } else { fprintf(stderr, "connect successful\n"); } int completed = 0; send_buf = malloc(packet_size); packet_time = 0; real_time = 0; nano_sleep_packet.tv_nsec = 665778; /* 1 packet at 100mbps*/ clock_gettime(CLOCK_MONOTONIC, &time_start); while (!completed) { clock_gettime(CLOCK_MONOTONIC, &time_stop); real_time = usecDiff(&time_stop, &time_start); if (real_time * bitrate > packet_time * 1000000) { /* theorical bits against sent bits */ len = read(transport_fd, send_buf, packet_size); if(len < 0) { fprintf(stderr, "ts file read error \n"); completed = 1; } else if (len == 0) { fprintf(stderr, "ts sent done\n"); completed = 1; } else { sent = send(sockfd, send_buf, len, 0); /* write(STDOUT_FILENO, send_buf, len); */ if(sent <= 0) { fprintf(stderr, "send(): error "); completed = 1; } else { /* if (sent != len) { fprintf(stderr, "sent failed to send the whole packet, sent %d bytes\n", sent); } */ packet_time += packet_size * 8; } } } else { nanosleep(&nano_sleep_packet, 0); } } close(transport_fd); close(sockfd); free(send_buf); return 0; }
the_stack_data/25136620.c
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #define BUFSIZE 512 #define FLAGS_RESTRICTED 0x001 #define FLAGS_EXCEEDLIMIT 0x002 #define FLAGS_KLINEEXEMPT 0x004 #define FLAGS_NEEDIDENT 0x010 #define FLAGS_NOTILDE 0x020 struct flag_table_struct { const char *name; int flag; }; static struct flag_table_struct flag_table[] = { { "restricted", FLAGS_RESTRICTED }, { "exceed_limit", FLAGS_EXCEEDLIMIT }, { "kline_exempt", FLAGS_KLINEEXEMPT }, { "need_ident", FLAGS_NEEDIDENT }, { "no_tilde", FLAGS_NOTILDE }, { NULL, 0 } }; struct AuthBlock { struct AuthBlock *next; char **hostname; int hostnum; char *spoof; char *passwd; int class; int flags; /* indicates one of above */ int special; int specialk; }; static struct AuthBlock *auth_spoof = NULL; static struct AuthBlock *auth_special = NULL; static struct AuthBlock *auth_passwd = NULL; static struct AuthBlock *auth_general = NULL; static struct AuthBlock *auth_restricted = NULL; static void ConvertConf(FILE* file,FILE *out); static void set_flags(struct AuthBlock *, const char *, const char *); static void usage(void); static char *getfield(char *); static struct AuthBlock *find_matching_conf(struct AuthBlock *); static void ReplaceQuotes(char *out, char *in); static void oldParseOneLine(FILE *out, char *in); static void write_auth_entries(FILE *out); static void write_specific(FILE *out, struct AuthBlock *); static int match(struct AuthBlock *, struct AuthBlock *); int main(int argc,char *argv[]) { FILE *in; FILE *out; if(argc < 3) usage(); if((in = fopen(argv[1],"r")) == NULL) { fprintf(stderr, "Can't open %s for reading\n", argv[1]); usage(); } if((out = fopen(argv[2],"w")) == NULL) { fprintf(stderr, "Can't open %s for writing\n", argv[2]); usage(); } ConvertConf(in, out); return 0; } void usage() { fprintf(stderr, "convertilines conf.old conf.new\n"); exit(-1); } /* * ConvertConf() * Read configuration file. * * * Inputs - FILE* to config file to convert * - FILE* to output for new style conf * */ #define MAXCONFLINKS 150 static void ConvertConf(FILE* file, FILE *out) { char line[BUFSIZE]; char quotedLine[BUFSIZE]; char* p; while (fgets(line, sizeof(line), file)) { if ((p = strchr(line, '\n'))) *p = '\0'; ReplaceQuotes(quotedLine,line); if(!*quotedLine || quotedLine[0] == '#' || quotedLine[0] == '\n' || quotedLine[0] == ' ' || quotedLine[0] == '\t') continue; if(quotedLine[0] == '.') { char *filename; char *back; if(!strncmp(quotedLine+1,"include ",8)) { if( (filename = strchr(quotedLine+8,'"')) ) filename++; else { fprintf(stderr, "Bad config line: %s", quotedLine); continue; } if((back = strchr(filename,'"'))) *back = '\0'; else { fprintf(stderr, "Bad config line: %s", quotedLine); continue; } } } /* Could we test if it's conf line at all? -Vesa */ if (quotedLine[1] == ':') oldParseOneLine(out,quotedLine); } fclose(file); write_auth_entries(out); fclose(out); } /* * ReplaceQuotes * Inputs - input line to quote * Output - quoted line * Side Effects - All quoted chars in input are replaced * with quoted values in output, # chars replaced with '\0' * otherwise input is copied to output. */ static void ReplaceQuotes(char* quotedLine,char *inputLine) { char *in; char *out; static char quotes[] = { 0, /* */ 0, /* a */ '\b', /* b */ 0, /* c */ 0, /* d */ 0, /* e */ '\f', /* f */ 0, /* g */ 0, /* h */ 0, /* i */ 0, /* j */ 0, /* k */ 0, /* l */ 0, /* m */ '\n', /* n */ 0, /* o */ 0, /* p */ 0, /* q */ '\r', /* r */ 0, /* s */ '\t', /* t */ 0, /* u */ '\v', /* v */ 0, /* w */ 0, /* x */ 0, /* y */ 0, /* z */ 0,0,0,0,0,0 }; /* * Do quoting of characters and # detection. */ for (out = quotedLine,in = inputLine; *in; out++, in++) { if (*in == '\\') { in++; if(*in == '\\') *out = '\\'; else if(*in == '#') *out = '#'; else *out = quotes[ (unsigned int) (*in & 0x1F) ]; } else if (*in == '#') { *out = '\0'; return; } else *out = *in; } *out = '\0'; } /* * oldParseOneLine * Inputs - pointer to line to parse * - pointer to output to write * Output - * Side Effects - Parse one old style conf line. */ static void oldParseOneLine(FILE *out,char* line) { char conf_letter; char* tmp; const char* host_field=NULL; const char* passwd_field=NULL; const char* user_field=NULL; const char* port_field = NULL; const char* classconf_field = NULL; int class_field = 0; tmp = getfield(line); conf_letter = *tmp; for (;;) /* Fake loop, that I can use break here --msa */ { /* host field */ if ((host_field = getfield(NULL)) == NULL) return; /* pass field */ if ((passwd_field = getfield(NULL)) == NULL) break; /* user field */ if ((user_field = getfield(NULL)) == NULL) break; /* port field */ if ((port_field = getfield(NULL)) == NULL) break; /* class field */ if ((classconf_field = getfield(NULL)) == NULL) break; break; } if (!passwd_field) passwd_field = ""; if (!user_field) user_field = ""; if (!port_field) port_field = ""; if (classconf_field) class_field = atoi(classconf_field); switch( conf_letter ) { case 'i': case 'I': { struct AuthBlock *ptr; struct AuthBlock *tempptr; tempptr = malloc(sizeof(struct AuthBlock)); memset(tempptr, 0, sizeof(*tempptr)); if(conf_letter == 'i') { tempptr->flags |= FLAGS_RESTRICTED; tempptr->specialk = 1; } if(passwd_field && *passwd_field) tempptr->passwd = strdup(passwd_field); tempptr->class = class_field; set_flags(tempptr, user_field, host_field); /* dont add specials/passworded ones to existing auth blocks */ if((ptr = find_matching_conf(tempptr))) { int authindex; authindex = ptr->hostnum; ptr->hostnum++; ptr->hostname = realloc((void *)ptr->hostname, ptr->hostnum * sizeof(void *)); ptr->hostname[authindex] = strdup(tempptr->hostname[0]); free(tempptr->hostname[0]); free(tempptr->hostname); free(tempptr); } else { ptr = tempptr; if(ptr->spoof) { ptr->next = auth_spoof; auth_spoof = ptr; } else if(ptr->special) { ptr->next = auth_special; auth_special = ptr; } else if(ptr->passwd) { ptr->next = auth_passwd; auth_passwd = ptr; } else if(ptr->specialk) { ptr->next = auth_restricted; auth_restricted = ptr; } else { ptr->next = auth_general; auth_general = ptr; } } } break; default: break; } } static void write_auth_entries(FILE *out) { struct AuthBlock *ptr; for(ptr = auth_spoof; ptr; ptr = ptr->next) write_specific(out, ptr); for(ptr = auth_special; ptr; ptr = ptr->next) write_specific(out, ptr); for(ptr = auth_passwd; ptr; ptr = ptr->next) write_specific(out, ptr); for(ptr = auth_general; ptr; ptr = ptr->next) write_specific(out, ptr); for(ptr = auth_restricted; ptr; ptr = ptr->next) write_specific(out, ptr); } static void write_specific(FILE *out, struct AuthBlock *ptr) { int i; int prev = 0; fprintf(out, "auth {\n"); for(i = 0; i < ptr->hostnum; i++) fprintf(out, "\tuser = \"%s\";\n", ptr->hostname[i]); if(ptr->spoof) fprintf(out, "\tspoof = \"%s\";\n", ptr->spoof); if(ptr->passwd) fprintf(out, "\tpassword = \"%s\";\n", ptr->passwd); if(ptr->flags) { fprintf(out, "\tflags = "); for(i = 0; flag_table[i].flag; i++) { if(ptr->flags & flag_table[i].flag) { fprintf(out, "%s%s", prev ? ", " : "", flag_table[i].name); prev = 1; } } fprintf(out, ";\n"); } fprintf(out, "\tclass = \"%d\";\n", ptr->class); fprintf(out, "};\n"); } /* * field breakup for ircd.conf file. */ static char *getfield(char *newline) { static char *line = NULL; char *end, *field; if (newline) line = newline; if (line == NULL) return(NULL); field = line; if ((end = strchr(line,':')) == NULL) { line = NULL; if ((end = strchr(field,'\n')) == NULL) end = field + strlen(field); } else line = end + 1; *end = '\0'; return(field); } struct AuthBlock *find_matching_conf(struct AuthBlock *acptr) { struct AuthBlock *ptr; for(ptr = auth_spoof; ptr; ptr = ptr->next) { if(match(ptr, acptr)) return ptr; } for(ptr = auth_special; ptr; ptr = ptr->next) { if(match(ptr, acptr)) return ptr; } for(ptr = auth_passwd; ptr; ptr = ptr->next) { if(match(ptr, acptr)) return ptr; } for(ptr = auth_restricted; ptr; ptr = ptr->next) { if(match(ptr, acptr)) return ptr; } for(ptr = auth_general; ptr; ptr = ptr->next) { if(match(ptr, acptr)) return ptr; } return NULL; } static int match(struct AuthBlock *ptr, struct AuthBlock *acptr) { if((ptr->class == acptr->class) && (ptr->flags == acptr->flags)) { const char *p1, *p2; /* check the spoofs match.. */ if(ptr->spoof) p1 = ptr->spoof; else p1 = ""; if(acptr->spoof) p2 = acptr->spoof; else p2 = ""; if(strcmp(p1, p2)) return 0; /* now check the passwords match.. */ if(ptr->passwd) p1 = ptr->passwd; else p1 = ""; if(acptr->passwd) p2 = acptr->passwd; else p2 = ""; if(strcmp(p1, p2)) return 0; return 1; } return 0; } void set_flags(struct AuthBlock *ptr, const char *user_field, const char *host_field) { for(; *user_field; user_field++) { switch(*user_field) { case '=': if(host_field) ptr->spoof = strdup(host_field); ptr->special = 1; break; case '-': ptr->flags |= FLAGS_NOTILDE; ptr->special = 1; break; case '+': ptr->flags |= FLAGS_NEEDIDENT; ptr->specialk = 1; break; case '^': /* is exempt from k/g lines */ ptr->flags |= FLAGS_KLINEEXEMPT; ptr->special = 1; break; case '>': ptr->flags |= FLAGS_EXCEEDLIMIT; ptr->special = 1; break; case '!': case '$': case '%': case '&': case '<': break; default: { int authindex; authindex = ptr->hostnum; ptr->hostnum++; ptr->hostname = realloc((void *)ptr->hostname, ptr->hostnum * sizeof(void *)); /* if the IP field contains something useful, use that */ if(strcmp(host_field, "NOMATCH") && (*host_field != 'x') && strcmp(host_field, "*") && !ptr->spoof) ptr->hostname[authindex] = strdup(host_field); else ptr->hostname[authindex] = strdup(user_field); return; } } } }
the_stack_data/1176414.c
#include <stdio.h> void main() { int a[10][10], m, n; printf("Enter Rows and Columns::"); scanf("%d%d", &m, &n); printf("Enter Elements::\n"); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { scanf("%d", &a[i][j]); } } printf("\nLower Triangle:\n"); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i >= j) printf("%d\t", a[i][j]); else printf(" \t"); } printf("\n"); } printf("\n\t\t\t\t\tANKIT(D-6)\n"); }
the_stack_data/25861.c
#include <stdio.h> #include <string.h> #include <stdlib.h> unsigned pow2(unsigned exponent) { int i, r = 1; for (i = 0 ; i < exponent; i++) { r = r * 2; } return r; } unsigned setBits(unsigned x, int p, int n, unsigned y) { int i, j; char ok = 0; unsigned OrNumber; unsigned AndNumber; OrNumber = (y & ~(~0 << n)) << (p + 1 - n) ; AndNumber = (~0 << (p + 1)) | (pow2(p + 2 - n) -1); return (x & AndNumber) | OrNumber; } int main(){ char s1[100]; int c, i = 0; int p, n; unsigned x, y; printf("\nEnter The x:\n"); while ((c = getchar()) != EOF) { if (c == '\n') break; s1[i] = c; i += 1; } s1[i] = '\0'; x = atoi(s1); memset(s1, 0, sizeof(s1)); i = 0; printf("\nEnter The y:\n"); while ((c = getchar()) != EOF) { if (c == '\n') break; s1[i] = c; i += 1; } s1[i] = '\0'; y = atoi(s1); memset(s1, 0, sizeof(s1)); i = 0; printf("\nEnter The p:\n"); while ((c = getchar()) != EOF) { if (c == '\n') break; s1[i] = c; i += 1; } s1[i] = '\0'; p = atoi(s1); memset(s1, 0, sizeof(s1)); i = 0; printf("\nEnter The n:\n"); while ((c = getchar()) != EOF) { if (c == '\n') break; s1[i] = c; i += 1; } s1[i] = '\0'; n = atoi(s1); memset(s1, 0, sizeof(s1)); i = 0; printf("\nThe result is:%d\n", setBits(x, p, n, y)); }
the_stack_data/26700784.c
#include <stdio.h> #define MAXLINE 1000 int getln(char line[], int maxline); void copy(char to[], char from[]); int main() { int len; char line[MAXLINE]; while ((len = getln(line, MAXLINE)) > 0) { if(len > 80) printf("%s", line); } return 0; } int getln(char line[], int maxline) { int i, j, c; j = 0; for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i) { if (i < maxline - 2) { line[j] = c; ++j; } } if (c == '\n') { line[j] = c; ++j; ++i; } line[j] = '\0'; return i; }
the_stack_data/742364.c
#include <stdio.h> int main(int argc, char **argv) { FILE *fp; FILE *ofp; if (argc == 1) { fp = stdin; ofp = stdout; } else if (argc == 2) { fp = fopen(argv[1], "r"); ofp = stdout; } else { fp = fopen(argv[1], "r"); ofp = fopen(argv[2], "w"); } unsigned int ch; int n = 0; while (n++ < 1500) { ch = getc(fp); switch (ch) { case 0x95: ch = ' '; break; case 0xD4: ch = 'a'; break; case 0xD7: ch = 'b'; break; case 0xD6: ch = 'c'; break; case 0xD1: ch = 'd'; break; case 0xD0: ch = 'e'; break; case 0xD3: ch = 'f'; break; case 0xD2: ch = 'g'; break; case 0xDD: ch = 'h'; break; case 0xDC: ch = 'i'; break; case 0xDF: ch = 'j'; break; case 0xDE: ch = 'k'; break; case 0xD9: ch = 'l'; break; case 0xD8: ch = 'm'; break; case 0xDB: ch = 'n'; break; case 0xDA: ch = 'o'; break; case 0xC5: ch = 'p'; break; case 0xC4: ch = 'q'; break; case 0xC7: ch = 'r'; break; case 0xC6: ch = 's'; break; case 0xC1: ch = 't'; break; case 0xC0: ch = 'u'; break; case 0xC3: ch = 'v'; break; case 0xC2: ch = 'w'; break; //case 0x: ch = 'x'; break; case 0xCC: ch = 'y'; break; //case 0x: ch = 'z'; break; case 0xF4: ch = 'A'; break; //case 0xF3: ch = 'B'; break; //case 0x: ch = 'C'; break; case 0xF1: ch = 'D'; break; case 0xF0: ch = 'E'; break; case 0xF3: ch = 'F'; break; case 0xF2: ch = 'G'; break; //case 0x: ch = 'H'; break; case 0xFC: ch = 'I'; break; case 0xFF: ch = 'J'; break; //case 0x: ch = 'K'; break; case 0xF9: ch = 'L'; break; case 0xF8: ch = 'M'; break; case 0xFB: ch = 'N'; break; case 0xFA: ch = 'O'; break; case 0xE5: ch = 'P'; break; case 0xE4: ch = 'Q'; break; case 0xE7: ch = 'R'; break; case 0xE6: ch = 'S'; break; case 0xE1: ch = 'T'; break; /* case 0xch = 'U'; break; case 0xch = 'V'; break; case 0xch = 'W'; break; case 0xch = 'X'; break; case 0xch = 'Y'; break; case 0xch = 'Z'; break; case 0x: ch = ':'; break; */ // case 0xch = '\''; break; default: ch = '.'; break; } putc(ch, ofp); } fclose(ofp); exit(0); }
the_stack_data/145792.c
#include <stdio.h> int main(){ int n,x,y,z,r; scanf("%i %i %i %i",&n,&x,&y,&z); if(n>=0 && n<=1000 && x>=1 && x<=1000 && y>=1 && y<=1000 && z>=1 && z<=1000){ if(n>=(x+y+z)){ r=3; }else if(n>=(x+y) || n>=(x+z) || n>(y+z)){ r=2; }else if(n>=x || n>=y || n>=z){ r=1; }else{ r=0; } } printf("%i",r); return 0; }
the_stack_data/623953.c
/************************************************************************************************** * * * This file is part of BLASFEO. * * * * BLASFEO -- BLAS For Embedded Optimization. * * Copyright (C) 2019 by Gianluca Frison. * * Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * * All rights reserved. * * * * The 2-Clause BSD License * * * * 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. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * * Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * * * **************************************************************************************************/ #if defined(LA_EXTERNAL_BLAS_WRAPPER) | defined(LA_REFERENCE) | defined(TESTING_MODE) // create a matrix structure for a matrix of size m*n void ALLOCATE_STRMAT(int m, int n, struct STRMAT *sA) { sA->m = m; sA->n = n; int tmp = m<n ? m : n; // al(min(m,n)) // XXX max ??? #if defined(LA_EXTERNAL_BLAS_WRAPPER) ZEROS_ALIGN(&(sA->pA), sA->m, sA->n); ZEROS_ALIGN(&(sA->dA), tmp, 1); #else ZEROS(&(sA->pA), sA->m, sA->n); ZEROS(&(sA->dA), tmp, 1); #endif sA->memsize = (m*n+tmp)*sizeof(REAL); sA->use_dA = 0; return; } // free memory of a matrix structure void FREE_STRMAT(struct STRMAT *sA) { #if defined(LA_EXTERNAL_BLAS_WRAPPER) FREE_ALIGN(sA->pA); FREE_ALIGN(sA->dA); #else FREE(sA->pA); FREE(sA->dA); #endif return; } // create a vector structure for a vector of size m void ALLOCATE_STRVEC(int m, struct STRVEC *sa) { sa->m = m; #if defined(LA_EXTERNAL_BLAS_WRAPPER) ZEROS_ALIGN(&(sa->pa), sa->m, 1); #else ZEROS(&(sa->pa), sa->m, 1); #endif sa->memsize = m*sizeof(REAL); return; } // free memory of a vector structure void FREE_STRVEC(struct STRVEC *sa) { #if defined(LA_EXTERNAL_BLAS_WRAPPER) FREE_ALIGN(sa->pa); #else FREE(sa->pa); #endif return; } // print a matrix structure void PRINT_STRMAT(int m, int n, struct STRMAT *sA, int ai, int aj) { int lda = sA->m; REAL *pA = sA->pA + ai + aj*lda; PRINT_MAT(m, n, pA, lda); return; } // print a vector structure void PRINT_STRVEC(int m, struct STRVEC *sa, int ai) { REAL *pa = sa->pa + ai; PRINT_MAT(m, 1, pa, m); return; } // print and transpose a vector structure void PRINT_TRAN_STRVEC(int m, struct STRVEC *sa, int ai) { REAL *pa = sa->pa + ai; PRINT_MAT(1, m, pa, 1); return; } // print a matrix structure void PRINT_TO_FILE_STRMAT(FILE *file, int m, int n, struct STRMAT *sA, int ai, int aj) { int lda = sA->m; REAL *pA = sA->pA + ai + aj*lda; PRINT_TO_FILE_MAT(file, m, n, pA, lda); return; } // print a matrix structure void PRINT_TO_FILE_EXP_STRMAT(FILE *file, int m, int n, struct STRMAT *sA, int ai, int aj) { int lda = sA->m; REAL *pA = sA->pA + ai + aj*lda; PRINT_TO_FILE_EXP_MAT(file, m, n, pA, lda); return; } // print a matrix structure void PRINT_TO_STRING_STRMAT(char **out_buf, int m, int n, struct STRMAT *sA, int ai, int aj) { int lda = sA->m; REAL *pA = sA->pA + ai + aj*lda; PRINT_TO_STRING_MAT(out_buf, m, n, pA, lda); return; } // print a vector structure void PRINT_TO_FILE_STRVEC(FILE *file, int m, struct STRVEC *sa, int ai) { REAL *pa = sa->pa + ai; PRINT_TO_FILE_MAT(file, m, 1, pa, m); return; } // print a vector structure void PRINT_TO_STRING_STRVEC(char **out_buf, int m, struct STRVEC *sa, int ai) { REAL *pa = sa->pa + ai; PRINT_TO_STRING_MAT(out_buf, m, 1, pa, m); return; } // print and transpose a vector structure void PRINT_TO_FILE_TRAN_STRVEC(FILE *file, int m, struct STRVEC *sa, int ai) { REAL *pa = sa->pa + ai; PRINT_TO_FILE_MAT(file, 1, m, pa, 1); return; } // print and transpose a vector structure void PRINT_TO_STRING_TRAN_STRVEC(char **buf_out, int m, struct STRVEC *sa, int ai) { REAL *pa = sa->pa + ai; PRINT_TO_STRING_MAT(buf_out, 1, m, pa, 1); return; } // print a matrix structure void PRINT_EXP_STRMAT(int m, int n, struct STRMAT *sA, int ai, int aj) { int lda = sA->m; REAL *pA = sA->pA + ai + aj*lda; PRINT_EXP_MAT(m, n, pA, lda); return; } // print a vector structure void PRINT_EXP_STRVEC(int m, struct STRVEC *sa, int ai) { REAL *pa = sa->pa + ai; PRINT_EXP_MAT(m, 1, pa, m); return; } // print and transpose a vector structure void PRINT_EXP_TRAN_STRVEC(int m, struct STRVEC *sa, int ai) { REAL *pa = sa->pa + ai; PRINT_EXP_MAT(1, m, pa, 1); return; } #endif
the_stack_data/165768448.c
#include <stdio.h> void main() { int m, n; for (m = 5; m < 7; m++) { for (n = 0; n < 3; n++) { if (m == 5 && n == 1) break; printf("m(%d) - n(%d)\n", m, n); } } }
the_stack_data/67325076.c
#include <term.h> #define no_pad_char tigetflag("npc") /** pad character doesn't exist **/ /* TERMINFO_NAME(npc) TERMCAP_NAME(NP) XOPEN(400) */
the_stack_data/393800.c
/** ****************************************************************************** * @file main.c * @author Auto-generated by STM32CubeIDE * @version V1.0 * @brief Default main function. ****************************************************************************** */ #if !defined(__SOFT_FP__) && defined(__ARM_FP) #warning "FPU is not initialized, but the project is compiling for an FPU. Please initialize the FPU before use." #endif int main(void) { for(;;); }
the_stack_data/355988.c
/* !C*********************************************************************** !DESCRIPTION: This program reads MODIS BRDF/albedo parameters saved in binary files, computes the black and white sky albedos (with Wolfgang's simple polynomial equation) and then assuming optical depth is an input, computes the actual albedo (linear combination of white and black-sky albedo) and saves in binary format. !INPUTS: semiempirical BRDF parameters in binary (use MRT to convert data from HDF file to binary file) Optical depth Solar zenith angle !OUTPUTS: Actual albedo !DEVELOPERS: Feng Gao, Crystal Schaaf (Boston University) [email protected], [email protected] !REVISIONS: 1/2000, 5/2000, 1/2002 !END ******************************************************************* */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #define SUCCESS 0 #define FAILURE -1 #define Max_Str_Len 100 #ifndef PI #define PI 3.1415926535 #endif #define D2R PI/180.0 #define NROWS 1200 #define NCOLS 1200 #define FILLV 32767 #define SCALE_FACTOR 0.001 typedef struct { float iso; float vol; float geo; } PARAMETERS; typedef struct { int aerosol_type; int bandno; float solar_zenith; float optical_depth; float skyl; } SKYL; void usage(void); void read_skyl_table (float skyl_lut[2][10][90][50]); float get_skyl (SKYL s,float skyl_lut[2][10][90][50]); float cal_bsa(PARAMETERS p, SKYL s); float cal_wsa(PARAMETERS p); float cal_actual_albedo(PARAMETERS p, SKYL s); void main(int argc, char **argv) { char outname[Max_Str_Len]; char iso_name[Max_Str_Len]; char vol_name[Max_Str_Len]; char geo_name[Max_Str_Len]; int i,j; short int par_data[3]; float albedo; float skyl_lut[2][10][90][50]; PARAMETERS p; SKYL s; FILE *iso, *vol, *geo, *out; /* see if commmand line are correct or not */ if(argc!=15) { usage(); exit(1); } /* parse command line */ for(i=1;i<argc;i++){ if(strcmp(argv[i],"-iso")==0) strcpy(iso_name,argv[++i]); else if(strcmp(argv[i],"-vol")==0) strcpy(vol_name,argv[++i]); else if(strcmp(argv[i],"-geo")==0) strcpy(geo_name,argv[++i]); else if(strcmp(argv[i],"-band")==0) /* use 0-based index */ s.bandno = atoi(argv[++i])-1; else if(strcmp(argv[i],"-out")==0) strcpy(outname,argv[++i]); else if(strcmp(argv[i],"-od")==0) s.optical_depth=atof(argv[++i]); else if(strcmp(argv[i],"-szn")==0) s.solar_zenith=atof(argv[++i]); else{ printf("\nWrong option:%s\n",argv[i]); usage(); exit(1); } } printf("\nRead SKYL table \n"); read_skyl_table(skyl_lut); /* open BRDF parameters binary files */ if((iso=fopen(iso_name,"rb"))==NULL){ printf("Parameter %s open file error!\n",iso_name); exit(1); } /* open BRDF parameters binary files */ if((vol=fopen(vol_name,"rb"))==NULL){ printf("Parameter %s open file error!\n",vol_name); exit(1); } /* open BRDF parameters binary files */ if((geo=fopen(geo_name,"rb"))==NULL){ printf("Parameter %s open file error!\n",geo_name); exit(1); } /* open output file for write */ if((out=fopen(outname,"wb"))==NULL){ printf("Output %s openfile error!\n",outname); exit(1); } printf("Computing actual albedo\n"); /* to process each line */ for(i=0; i<NROWS; i++){ /* process each pixel */ for(j=0; j<NCOLS; j++){ /* read BRDF parameters */ fread(&par_data[0],1,2,iso); fread(&par_data[1],1,2,vol); fread(&par_data[2],1,2,geo); /* for Linux system, you need to comment out the following lines - from Stephen M. Margle on May 3, 2004 */ //par_data[0]= ((par_data[0]>> 8) | (par_data[0]<< 8)); //par_data[1]= ((par_data[1]>> 8) | (par_data[1]<< 8)); //par_data[2]= ((par_data[2]>> 8) | (par_data[2]<< 8)); /* check parameters and see if they are valid values */ if(par_data[0]!=FILLV ) { /* calculate real parameter values */ p.iso=par_data[0]*SCALE_FACTOR; p.vol=par_data[1]*SCALE_FACTOR; p.geo=par_data[2]*SCALE_FACTOR; /* NOTE: need to make sure you get the right LUT band order: # bandwidth: 0: 0.620-0.670 (red) # 1: 0.841-0.876 (nir) # 2: 0.459-0.479 # 3: 0.545-0.565 # 4: 1.230-1.250 # 5: 1.628-1.652 # 6: 2.105-2.155 # BB 7: 0.400-0.700 (vis) # BB 8: 0.700-4.000 (nir) # BB 9: 0.250-4.000 (sw) you may need index your band order to LUT band order, such as: s.bandno=index[band]; */ /* assume continental type, but finally need to get it from BRDF_type 0: continental 1: maritime */ s.aerosol_type=0; /* get SKYL from SKYL lookup table (it depends on optical depth, solar zenith angle, aerosol type, and bands) */ s.skyl=get_skyl(s,skyl_lut); albedo=cal_actual_albedo(p,s); } else albedo=FILLV; fwrite(&albedo,1,sizeof(float),out); } } printf("Finished\n\n"); } void usage(void) { printf("\nUsage: actual_albedo_bin.exe [-iso][-vol][-geo][-band][-od][-szn][-out] \n\n"); printf(" -iso <f_iso_file> input isotropic binary file\n"); printf(" -vol <f_vol_file> input volumetric binary file\n"); printf(" -geo <f_geo_file> input geometric binary file\n"); printf(" -band <band_no> input band no (int, 1-10)\n"); printf(" -od <optical_depth> input optical depth (float, range: 0.0-1.0)\n"); printf(" -szn <solar_zenith> input solar zenith angle you want to compute\n"); printf(" (float, range: 0.0-89.0 degrees)\n"); printf(" -out <albedo_file> output file to save actual albedo in binary\n\n"); } /******************************************************* read SKYL LUT from pre-generated LUT file (skyl_lut.dat) 2 aerosol types 10 bands (7 MODIS bands + 3 broad bands (VIS, NIR, SW) 90 degrees (0-89 degrees with 1 degree step 50 optical depth ( 0-1 with 0.02 step) ********************************************************/ void read_skyl_table (float skyl_lut[2][10][90][50]) { char str[Max_Str_Len]; FILE *in; int aerosol,band,szn,od,NBANDS; NBANDS=10; /* MODIS defaults */ if((in=fopen("skyl_lut.dat","r"))==NULL) { printf("Can't open SKYL LUT file (skyl_lut.dat) \n"); exit(1); } for(aerosol=0;aerosol<2;aerosol++) { fscanf(in,"%s %s\n",str,str); for(band=0;band<NBANDS;band++) { fscanf(in,"%s %s\n",str,str); for(od=0;od<51;od++) fscanf(in,"%s ",str); for(szn=0;szn<90;szn++){ fscanf(in,"%s ",str); for(od=0;od<50;od++) { fscanf(in,"%f ",&(skyl_lut[aerosol][band][szn][od])); /*printf("%5.3f ",(skyl_lut[aerosol][band][szn][od]));*/ } } /*printf("\n"); getchar();*/ } } fclose(in); } /* get SKYL value from LUT */ float get_skyl (SKYL s,float skyl_lut[2][10][90][50]) { int szn,od; szn=(int)(s.solar_zenith+0.5); /*get solar zenith index */ if(szn==90) szn=89; od=(int)(s.optical_depth/0.02+0.5); /*get optical depth index */ if(od>=50) od=49; return skyl_lut[s.aerosol_type][s.bandno][szn][od]; } /******************************************** calculate actual albedo with the linear combination of white-sky and black-sky albedo **********************************************/ float cal_actual_albedo(PARAMETERS p, SKYL s) { float actual_albedo; float bsa,wsa; bsa=cal_bsa(p,s); wsa=cal_wsa(p); actual_albedo=wsa*s.skyl + bsa*(1.0-s.skyl); if(actual_albedo<0) actual_albedo=0; if(actual_albedo>1) actual_albedo=1; return actual_albedo; } /******************************************* calculate black-sky albedo according to Wolfgang's polynomial albedo representation ********************************************/ float cal_bsa(PARAMETERS p, SKYL s) { int i; float bsa,bsa_weight[3],szn,sq_szn,cub_szn; float poly_coef[3][3]={1.0,-0.007574,-1.284909, 0.0,-0.070987,-0.166314, 0.0, 0.307588, 0.041840}; szn=s.solar_zenith*D2R; sq_szn=szn*szn; cub_szn=sq_szn*szn; for(i=0;i<3;i++) bsa_weight[i]=poly_coef[0][i]+poly_coef[1][i]*sq_szn+poly_coef[2][i]*cub_szn; bsa=bsa_weight[0]*p.iso+bsa_weight[1]*p.vol+bsa_weight[2]*p.geo; return bsa; } /* calculate white-sky albedo with fixed weight */ float cal_wsa(PARAMETERS p) { float wsa,wsa_weight[3]={1.0,0.189184,-1.377622}; wsa=wsa_weight[0]*p.iso+wsa_weight[1]*p.vol+wsa_weight[2]*p.geo; return wsa; }
the_stack_data/156392365.c
/* * ctime.c * Original Author: G. Haley */ /* FUNCTION <<ctime>>---convert time to local and format as string INDEX ctime INDEX ctime_r SYNOPSIS #include <time.h> char *ctime(const time_t *<[clock]>); char *ctime_r(const time_t *<[clock]>, char *<[buf]>); DESCRIPTION Convert the time value at <[clock]> to local time (like <<localtime>>) and format it into a string of the form . Wed Jun 15 11:38:07 1988\n\0 (like <<asctime>>). RETURNS A pointer to the string containing a formatted timestamp. PORTABILITY ANSI C requires <<ctime>>. <<ctime>> requires no supporting OS subroutines. */ #include <time.h> #ifndef _REENT_ONLY char * ctime (const time_t * tim_p) { return asctime (localtime (tim_p)); } #endif
the_stack_data/75429.c
#include <stdio.h> #include <math.h> int jePopolno (int a) { int s = 0; for (int i = 2; i < sqrt(a); ++i) { if (a % i == 0) { s += i; s += a / i; } } return (s + 1) == a; // ker smo enko spustili } int main () { int n; scanf("%d", &n); for (int i = 2; i <= n; ++i) { if (jePopolno(i)) { printf("%d ", i); } } printf("\n"); return 0; }
the_stack_data/43887446.c
#include<stdio.h> #include<limits.h> /* Our structure */ struct rec { int x,y,z; }; int main(int argc,char* argv[]) { /* This is a mock binary that simulates a binary that processes jpg files. In particular it processes files that have the four magic bytes 0xFF0xD80xFF0xE0. */ if(argc<=1){ printf("Usage: %s jpg_file\n",argv[0]); } unsigned char ch; unsigned char magic_bytes[4]; int counter; FILE *ptr_myfile; struct rec my_record; ptr_myfile=fopen(argv[1],"rb"); if (!ptr_myfile) { printf("Unable to open file!"); return 1; } for(int i=0;i<123089;++i){ //for(int j=0;j<INT_MAX;++j){ printf("%d\n",i); //} } int i =0; // obtain file size: fseek (ptr_myfile , 0 , SEEK_END); int lSize = ftell (ptr_myfile); rewind (ptr_myfile); fread(magic_bytes,1,4,ptr_myfile); if(!(magic_bytes[0]==0xFF&&magic_bytes[1]==0xD8&&magic_bytes[2]==0xFF&&magic_bytes[3]==0xE0)){ printf("No JPG file"); return 0; } for(int i=0;i<123089;++i){ //for(int j=0;j<INT_MAX;++j){ printf("%d\n",i); //} } printf("Magic Bytes\n"); for(i=0;i<4;++i){ printf("%02X ",magic_bytes[i]); } printf("\n$$$\n"); i=0; rewind(ptr_myfile); for(int i=0;i<lSize;++i) { ch = fgetc(ptr_myfile); printf("%02X ",ch); if( !(i % 16) ){ putc('\n', stdout); } } printf("\n"); fclose(ptr_myfile); return 0; }
the_stack_data/114852.c
#include<stdio.h> main() { printf("linux programming\n"); }
the_stack_data/318894.c
/* $XConsortium: dlsym.c,v 1.1 93/12/06 16:24:15 kaleb Exp $ */ /* * Stub interface to dynamic linker routines * that SunOS uses but didn't ship with 4.1. * * The C library routine wcstombs in SunOS 4.1 tries to dynamically * load some routines using the dlsym interface, described in dlsym(3x). * Unfortunately SunOS 4.1 does not include the necessary library, libdl. * * The R5 Xlib uses wcstombs. If you link dynamcally, your program can * run even with the unresolved reference to dlsym. However, if you * link statically, you will encounter this bug. One workaround * is to include these stub routines when you link. */ void *dlopen() { return 0; } void *dlsym() { return 0; } int dlclose() { return -1; }
the_stack_data/170453892.c
/** ****************************************************************************** * @file stm32l4xx_ll_dac.c * @author MCD Application Team * @version V1.3.0 * @date 29-January-2016 * @brief DAC LL module driver ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 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 "stm32l4xx_ll_dac.h" #include "stm32l4xx_ll_bus.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0) #endif /** @addtogroup STM32L4xx_LL_Driver * @{ */ #if defined (DAC1) /** @addtogroup DAC_LL DAC * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @addtogroup DAC_LL_Private_Macros * @{ */ #define IS_LL_DAC_CHANNEL(__DACX__, __DAC_CHANNEL__) \ ( \ ((__DAC_CHANNEL__) == LL_DAC_CHANNEL_1) \ || ((__DAC_CHANNEL__) == LL_DAC_CHANNEL_2) \ ) #define IS_LL_DAC_TRIGGER_SOURCE(__TRIGGER_SOURCE__) \ ( ((__TRIGGER_SOURCE__) == LL_DAC_TRIGGER_SOFTWARE) \ || ((__TRIGGER_SOURCE__) == LL_DAC_TRIGGER_TIM2_TRGO) \ || ((__TRIGGER_SOURCE__) == LL_DAC_TRIGGER_TIM4_TRGO) \ || ((__TRIGGER_SOURCE__) == LL_DAC_TRIGGER_TIM5_TRGO) \ || ((__TRIGGER_SOURCE__) == LL_DAC_TRIGGER_TIM6_TRGO) \ || ((__TRIGGER_SOURCE__) == LL_DAC_TRIGGER_TIM7_TRGO) \ || ((__TRIGGER_SOURCE__) == LL_DAC_TRIGGER_TIM8_TRGO) \ || ((__TRIGGER_SOURCE__) == LL_DAC_TRIGGER_EXT_IT9) ) #define IS_LL_DAC_WAVE_AUTO_GENER_MODE(__WAVE_AUTO_GENERATION_MODE__) \ ( ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_NONE) \ || ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_NOISE) \ || ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_TRIANGLE)) #define IS_LL_DAC_WAVE_AUTO_GENER_CONFIG(__WAVE_AUTO_GENERATION_CONFIG__) \ ( ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BIT0) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS1_0) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS2_0) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS3_0) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS4_0) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS5_0) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS6_0) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS7_0) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS8_0) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS9_0) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS10_0) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS11_0) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_1) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_3) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_7) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_15) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_31) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_63) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_127) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_255) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_511) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_1023) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_2047) \ || ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_4095)) #define IS_LL_DAC_OUTPUT_BUFFER(__OUTPUT_BUFFER__) \ ( ((__OUTPUT_BUFFER__) == LL_DAC_OUTPUT_BUFFER_ENABLE) \ || ((__OUTPUT_BUFFER__) == LL_DAC_OUTPUT_BUFFER_DISABLE)) #define IS_LL_DAC_OUTPUT_CONNECTION(__OUTPUT_CONNECTION__) \ ( ((__OUTPUT_CONNECTION__) == LL_DAC_OUTPUT_CONNECT_GPIO) \ || ((__OUTPUT_CONNECTION__) == LL_DAC_OUTPUT_CONNECT_INTERNAL)) #define IS_LL_DAC_OUTPUT_MODE(__OUTPUT_MODE__) \ ( ((__OUTPUT_MODE__) == LL_DAC_OUTPUT_MODE_NORMAL) \ || ((__OUTPUT_MODE__) == LL_DAC_OUTPUT_MODE_SAMPLE_AND_HOLD)) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup DAC_LL_Exported_Functions * @{ */ /** @addtogroup DAC_LL_EF_Init * @{ */ /** * @brief De-initialize registers of the selected DAC instance * to their default reset values. * @param DACx DAC instance * @retval An ErrorStatus enumeration value: * - SUCCESS: DAC registers are de-initialized * - ERROR: DAC registers are not de-initialized */ ErrorStatus LL_DAC_DeInit(DAC_TypeDef *DACx) { /* Check the parameters */ assert_param(IS_DAC_ALL_INSTANCE(DACx)); /* Force reset of DAC clock */ LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_DAC1); /* Release reset of DAC clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_DAC1); return SUCCESS; } /** * @brief Initialize some features of DAC instance. * @note The setting of these parameters by function @ref LL_DAC_Init() * is conditioned to DAC state: * DAC instance must be disabled. * @param DACx DAC instance * @param DAC_Channel This parameter can be one of the following values: * @arg @ref LL_DAC_CHANNEL_1 * @arg @ref LL_DAC_CHANNEL_2 * @param DAC_InitStruct Pointer to a @ref LL_DAC_InitTypeDef structure * @retval An ErrorStatus enumeration value: * - SUCCESS: DAC registers are initialized * - ERROR: DAC registers are not initialized */ ErrorStatus LL_DAC_Init(DAC_TypeDef *DACx, uint32_t DAC_Channel, LL_DAC_InitTypeDef *DAC_InitStruct) { ErrorStatus status = SUCCESS; /* Check the parameters */ assert_param(IS_DAC_ALL_INSTANCE(DACx)); assert_param(IS_LL_DAC_CHANNEL(DACx, DAC_Channel)); assert_param(IS_LL_DAC_TRIGGER_SOURCE(DAC_InitStruct->TriggerSource)); assert_param(IS_LL_DAC_OUTPUT_BUFFER(DAC_InitStruct->OutputBuffer)); assert_param(IS_LL_DAC_OUTPUT_CONNECTION(DAC_InitStruct->OutputConnection)); assert_param(IS_LL_DAC_OUTPUT_MODE(DAC_InitStruct->OutputMode)); assert_param(IS_LL_DAC_WAVE_AUTO_GENER_MODE(DAC_InitStruct->WaveAutoGeneration)); if (DAC_InitStruct->WaveAutoGeneration != LL_DAC_WAVE_AUTO_GENERATION_NONE) { assert_param(IS_LL_DAC_WAVE_AUTO_GENER_CONFIG(DAC_InitStruct->WaveAutoGenerationConfig)); } /* Note: Hardware constraint (refer to description of this function) */ /* DAC instance must be disabled. */ if(LL_DAC_IsEnabled(DACx, DAC_Channel) == 0U) { /* Configuration of DAC channel: */ /* - TriggerSource */ /* - WaveAutoGeneration */ /* - OutputBuffer */ /* - OutputConnection */ /* - OutputMode */ if (DAC_InitStruct->WaveAutoGeneration != LL_DAC_WAVE_AUTO_GENERATION_NONE) { MODIFY_REG(DACx->CR, ( DAC_CR_TSEL1 | DAC_CR_WAVE1 | DAC_CR_MAMP1 ) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) , ( DAC_InitStruct->TriggerSource | DAC_InitStruct->WaveAutoGeneration | DAC_InitStruct->WaveAutoGenerationConfig ) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) ); } else { MODIFY_REG(DACx->CR, ( DAC_CR_TSEL1 | DAC_CR_WAVE1 ) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) , ( DAC_InitStruct->TriggerSource | LL_DAC_WAVE_AUTO_GENERATION_NONE ) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) ); } MODIFY_REG(DACx->MCR, ( DAC_MCR_MODE1_1 | DAC_MCR_MODE1_0 | DAC_MCR_MODE1_2 ) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) , ( DAC_InitStruct->OutputBuffer | DAC_InitStruct->OutputConnection | DAC_InitStruct->OutputMode ) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK) ); } else { /* Initialization error: DAC instance is not disabled. */ status = ERROR; } return status; } /** * @brief Set each @ref LL_DAC_InitTypeDef field to default value. * @param DAC_InitStruct pointer to a @ref LL_DAC_InitTypeDef structure * whose fields will be set to default values. * @retval None */ void LL_DAC_StructInit(LL_DAC_InitTypeDef *DAC_InitStruct) { /* Set DAC_InitStruct fields to default values */ DAC_InitStruct->TriggerSource = LL_DAC_TRIGGER_SOFTWARE; DAC_InitStruct->WaveAutoGeneration = LL_DAC_WAVE_AUTO_GENERATION_NONE; /* Note: Parameter discarded if wave auto generation is disabled, */ /* set anyway to its default value. */ DAC_InitStruct->WaveAutoGenerationConfig = LL_DAC_NOISE_LFSR_UNMASK_BIT0; DAC_InitStruct->OutputBuffer = LL_DAC_OUTPUT_BUFFER_ENABLE; DAC_InitStruct->OutputConnection = LL_DAC_OUTPUT_CONNECT_GPIO; DAC_InitStruct->OutputMode = LL_DAC_OUTPUT_MODE_NORMAL; } /** * @} */ /** * @} */ /** * @} */ #endif /* DAC1 */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/77831.c
struct X; struct Y { struct X *a; }; #if 0 /* Not allowed in Microsoft MSVC */ struct X { }; #endif
the_stack_data/212643018.c
#include<stdio.h> #include<stdlib.h> typedef struct link { struct link*prev; int data; struct link*next; }node; //h->prev=next; void createDLL(node *); void displayDLL(node *); node* deleteFront(node *); void deleteEnd(node *); void deletePos(node *); node* findNode(node *,int ); int main() { int x,y; node *h=(node*)malloc(sizeof(node)); //h->prev=next; while(1) { printf("\nPress 1 to create a double Linked List"); printf("\nPress 2 to display the double Linked List"); printf("\nPress 3 to delete the double Linked List"); printf("\nPress 4 to exit : "); scanf("%d",&x); switch(x) { case 1: createDLL(h); break; case 2: displayDLL(h); break; case 3: printf("Press 1 to delete at start.\n"); printf("Press 2 to delete at end.\n"); printf("Press 3 to delete at different position. \n"); printf("Press 4 to go to the previous menu.\n"); scanf("%d",&y); switch(y) { case 1: h=deleteFront(h); break; case 2: deleteEnd(h); break; case 3: deletePos(h); break; case 4: break; } break; case 4: exit(0); } } return 0; } void createDLL(node *l) { int x; while(1) { printf("\nEnter data : "); scanf("%d",&l->data); printf("\nAnother node(0/1)"); scanf("%d",&x); if(x==0) { l->next=NULL; break; } l->next=(node*)malloc(sizeof(node)); l->next->prev=l; l=l->next; } } void displayDLL(node *l) { int x; printf("\nPress 1 ,2,0 for right,transverse & exit"); while(1) { printf(" %d ",l->data); scanf("%d",&x); if(x==1) { if(l->next==NULL) printf("\n last node"); else l=l->next; } else if(x==2) { if(l->prev==NULL) printf("\n first node"); else l=l->prev; } else if(x==0) break; } } node* deleteFront(node* h) { node *temp=h; h=h->next; h->prev=NULL; free(temp); return h; } void deleteEnd(node* h) { while(h->next->next!=NULL) h=h->next; node *temp=h->next; h->next=NULL; free(temp); } void deletePos(node* h) { node *l=h; node *t; int x; printf(" Enter the node to be deleted :"); scanf("%d",&x); while(l->next->data!=x){ l=l->next; } t=l->next; l->next=t->next; l->next->prev=l; t->next=t->prev=NULL; free(t); }
the_stack_data/40763675.c
/* cmpflt.c -- 浮点数比较 */ #include <math.h> #include <stdio.h> int main(int argc, char const *argv[]) { const double ANSWER = 3.14159; double response; printf("what is the value of pi?\n"); scanf("%lf",&response); /* 在用户的答案和正确值的误差小于 0.0001 之前,这个循环反复地请求输入答案 */ while(fabs(response - ANSWER) > 0.0001){ printf("Try again!\n"); scanf("%lf",&response); } printf("Close enought!\n"); return 0; }
the_stack_data/130084.c
#include <stdio.h> main() { int c; while((c = getchar()) != EOF) { putchar(c); c = getchar(); } }
the_stack_data/38535.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <sys/shm.h> #include <sys/sem.h> #include <unistd.h> #include <signal.h> #include <time.h> #include <sys/wait.h> #include <errno.h> int msg_id,shm_id,sem_id; struct poruka { long tip_poruke; char poruka[100]; int tmp; }; int main() { srand(time(NULL)); struct sembuf opr_p, opr_v; struct poruka red_poruka; key_t kljuc; pid_t pid; int flag,pice_id,rbr,gost_id; int *buff; // 0 = br_piva, 1 = br_sokova kljuc = ftok("./organizator.c",'Z'); //printf("kljuc = %d\n", kljuc); msg_id = msgget(kljuc,IPC_CREAT|0666); //printf("msg_id = %d\n", msg_id); pid = getpid(); red_poruka.tip_poruke = 1; red_poruka.tmp = pid; msgsnd(msg_id, &red_poruka, sizeof(red_poruka), 0); printf("Proces %d: Cekam da se pronadje sto\n",pid); msgrcv(msg_id, &red_poruka, sizeof(red_poruka), 2, 0); rbr = red_poruka.tmp; printf("Proces %d: Dobio sam sto sa brojem %d\n",pid,rbr); kljuc = ftok("./gost.c", rbr); shm_id = shmget(kljuc, sizeof(int)*2, 0); //printf("shm_id = %d\n", shm_id); buff = shmat(shm_id, NULL, 0); sem_id = semget(kljuc, 6, 0); //printf("sem_id = %d\n", sem_id); int ind; while(1) { flag = rand()%2; if(flag) pice_id = 0; else pice_id = 3; if(!pice_id) printf("Proces %d: Proveravam da li na stolu ima piva\n",pid); else printf("Proces %d: Proveravam da li na stolu ima sokova\n",pid); opr_p.sem_op = -1; opr_p.sem_flg = 0; opr_v.sem_op = 1; opr_v.sem_flg = 0; opr_p.sem_num = pice_id+2; ind = semop(sem_id, &opr_p, 1); // Da li neko vec pije pivo(sok) if(ind == -1) break; opr_p.sem_num = pice_id; opr_v.sem_num = pice_id+1; ind = semop(sem_id, &opr_p, 1); // Kriticni region if(ind == -1) break; if(pice_id == 0) { printf("Proces %d: Dosao sam na red, uzimam pivo\n",pid); buff[0]++; sleep(3); printf("Proces %d: Do sada je popijeno %d piva\n", pid, buff[0]); printf("Proces %d: Pijem pivo\n", pid); sleep(3); printf("Proces %d: Vratio sam praznu kriglu\n", pid); printf("--------------------------------------\n"); } else { printf("Proces %d: Dosao sam na red, uzimam sok\n",pid); buff[1]++; sleep(3); printf("Proces %d: Do sada je popijeno %d sokova\n", pid, buff[1]); printf("Proces %d: Pijem sok\n", pid); sleep(3); printf("Proces %d: Vratio sam praznu casu od soka\n", pid); printf("--------------------------------------------\n"); } ind = semop(sem_id, &opr_v, 1); // Kriticni region if(ind == -1) break; opr_v.sem_num = pice_id+2; ind = semop(sem_id, &opr_v, 1); // Da li neko vec pije pivo(sok) if(ind == -1) break; } shmdt(buff); return 0; }
the_stack_data/150142397.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #define BUFFER_SIZE (8 * 1024) #define HEADER_SIZE (16) int main (int argc, char *argv[]) { FILE * fp; unsigned char buffer[BUFFER_SIZE]; unsigned char header[HEADER_SIZE]; unsigned int checksum, count; int i, len; if(argc != 2) { printf("Usage: mk4412 <file>\n"); return -1; } fp = fopen(argv[1], "r+b"); if(fp == NULL) { printf("Can not open file '%s'\n", argv[1]); return -1; } fseek(fp, 0L, SEEK_END); len = ftell(fp); count = (len < BUFFER_SIZE) ? len : BUFFER_SIZE; fseek(fp, 0L, SEEK_SET); memset(buffer, 0, sizeof(buffer)); if(fread(buffer, 1, count, fp) != count) { printf("Can't read %s\n", argv[1]); fclose(fp); return -1; } for(i = 16, checksum = 0; i < count; i++) { checksum += buffer[i] & 0xff; } memset(header, 0, sizeof(header)); header[3] = (0x1f >> 24) & 0xff; header[2] = (0x1f >> 16) & 0xff; header[1] = (0x1f >> 8) & 0xff; header[0] = (0x1f >> 0) & 0xff; header[7] = (checksum >> 24) & 0xff; header[6] = (checksum >> 16) & 0xff; header[5] = (checksum >> 8) & 0xff; header[4] = (checksum >> 0) & 0xff; header[0] ^= 0xbc; header[1] ^= 0xca; header[2] ^= 0xba; header[3] ^= 0xcb; header[4] ^= 0xcb; header[5] ^= 0xce; header[6] ^= 0xcd; header[7] ^= 0xdf; header[8] ^= 0xb7; header[9] ^= 0xba; header[10] ^= 0xbe; header[11] ^= 0xbb; header[12] ^= 0xba; header[13] ^= 0xad; header[14] ^= 0xdf; header[15] ^= 0xdf; for (i = 1; i < HEADER_SIZE; i++) { header[i] ^= header[i-1]; } fseek(fp, 0L, SEEK_SET); if(fwrite(header, 1, sizeof(header), fp) != sizeof(header)) { printf("Write header error %s\n", argv[1]); fclose(fp); return -1; } fclose(fp); printf("The checksum is 0x%08x for %ld bytes [0x%08x ~ 0x%08x]\n", checksum, (count - sizeof(header)), sizeof(header), (count - 1)); return 0; }
the_stack_data/212642390.c
extern unsigned int __VERIFIER_nondet_uint(void); extern void __VERIFIER_error(); unsigned int sum(unsigned int n, unsigned int m) { if (n == 0) { return m; } else { return sum(n - 1, m + 1); } } int main(void) { unsigned int a = __VERIFIER_nondet_uint(); unsigned int b = __VERIFIER_nondet_uint(); unsigned int result = sum(a, b); if (result != a + b) { ERROR: __VERIFIER_error(); } }
the_stack_data/109506.c
#include <assert.h> typedef int (*other_function_type)(int n); void foo(other_function_type other_function) { // returning from the function call is unreachable -> the following assertion // should succeed // requesting `pointer-check` will then catch the fact that there is no valid // candidate function to call resulting in an invalid function pointer // failure assert(other_function(4) > 5); }
the_stack_data/86074571.c
/* * BSD-3-Clause * * Copyright (c) 2020 Wonpyo Kim, * Hallym University Software Convergence School, Hongpub. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <unistd.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #define SIZE 4 static int **array_allocation(int value); static void *matmul_thread(void *arg); static void print_arrays(void); struct thread_parameter { int n_threads; int position; int state; // 0: lived, 1: terminated, 2: joined }; static pthread_mutex_t t_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t t_cond = PTHREAD_COND_INITIALIZER; static int **A, **B, **Y; static int processing; void main(int argc, char *argv[]) { int i, j; int n_threads, lived; pthread_t *tid; pthread_attr_t attr; struct thread_parameter *t_param; double sum; n_threads = 4; lived = n_threads; A = array_allocation(1); B = array_allocation(1); Y = array_allocation(0); printf("[Original Arrays]\n"); print_arrays(); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); tid = (pthread_t *)calloc(n_threads, sizeof(pthread_t)); t_param = (struct thread_parameter *)calloc(n_threads, sizeof(struct thread_parameter)); for (i = 0; i < SIZE; i++) { t_param[i].n_threads = n_threads; t_param[i].position = (int)i; t_param[i].state = 0; if (pthread_create(&tid[i], &attr, matmul_thread, (void *)&t_param[i]) != 0) { perror("pthread_create() failed"); exit(1); } } while (lived > 0) { if (pthread_mutex_lock(&t_mutex) != 0) { perror("pthread_mutex_lock() failed"); exit(1); } while (processing == 0) { if (pthread_cond_wait(&t_cond, &t_mutex) != 0) { perror("pthread_cond_wait() failed"); exit(1); } } for (i = 0; i < n_threads; i++) { if (t_param[i].state == 1) { if (pthread_join(tid[i], NULL) != 0) { perror("pthread_join() failed"); exit(1); } t_param[i].state = 2; lived--; processing--; printf("Thread %d ended. (lived: %d\n", i, lived); } } if (pthread_mutex_unlock(&t_mutex) != 0) { perror("pthread_mutex_unlock() failed"); exit(1); } } pthread_attr_destroy(&attr); printf("\n[Result Arrays]\n"); print_arrays(); free(A); free(B); free(Y); free(tid); free(t_param); exit(0); } int ** array_allocation(int value) { int i, j; int **array; array = (int **)calloc(SIZE, sizeof(int **)); for (i = 0; i < SIZE; i++) { array[i] = (int *)calloc(SIZE, sizeof(int)); for (j = 0; j < SIZE; j++) { array[i][j] = value; } } return array; } static void * matmul_thread(void *arg) { int i, j, k; int ret; int start, end; double sum; struct thread_parameter *t_param; sum = 0.0; t_param = (struct thread_parameter *)arg; start = SIZE / t_param->n_threads * t_param->position; end = SIZE / t_param->n_threads * (t_param->position+1); if (pthread_mutex_lock(&t_mutex) != 0) { perror("pthread_mutex_lock() failed"); exit(1); } processing++; for (i = 0; i < SIZE; i++) { for (j = start; j < end; j++) { sum = 0.0; for (k = 0; k < SIZE; k++) { if (t_param->position != 0) { B[k][j] = B[k][j] * (2*t_param->position); } sum += A[i][k] * B[k][j]; } Y[i][j] = (int)sum; } } t_param->state = 1; if (pthread_mutex_unlock(&t_mutex) != 0) { perror("pthread_mutex_unlock() failed"); exit(1); } if (pthread_cond_signal(&t_cond) != 0) { perror("pthread_cond_signal() failed"); exit(1); } pthread_exit(NULL); } void print_arrays(void) { int i, j; for (i = 0; i < SIZE; i++) { for (j = 0; j < SIZE; j++) { printf("%4d ", A[i][j]); } printf(" "); for (j = 0; j < SIZE; j++) { printf("%4d ", B[i][j]); } printf(" "); for (j = 0; j < SIZE; j++) { printf("%4d ", Y[i][j]); } printf("\n"); } printf("\n"); }
the_stack_data/146802.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int distance, index, cost = 0; printf("Enter the distance: "); scanf("%d", &distance); // Conditional statements // Handling edge cases if (distance < 0) { printf("ERROR \n"); exit(1); } if (distance <= 50) { cost = distance * 300; } else if (distance > 50 && distance <= 100) { cost = 50 * 300 + (distance - 50) * 200; } else if (distance > 100) { cost = 50 * 300 + 50 * 200 + (distance - 100) * 150; } // Print the distance printf("Amount spend is: %d \n", cost); return 0; }
the_stack_data/173577222.c
#include <stdio.h> #include <stdlib.h> struct ListNode { int val; struct ListNode *next; }; /* Search specific value insie the list and return index */ int search_val(struct ListNode *obj, int value) { int index = 1; struct ListNode *current = NULL; current = obj; while (current->next != NULL) { if(current->val == value) return index; current = current->next; index++; } return -1; } /* Insert node after node m */ void insert_node(struct ListNode *obj, int m, int value) { struct ListNode *current = NULL; struct ListNode *new_node = malloc(sizeof(new_node)); struct ListNode *tmp = NULL; int index = 1; new_node->val = value; current = obj; while (index < m){ index++; current = current->next; } tmp = current->next; current->next = new_node; new_node->next = tmp; } /* remove m node */ void remove_node(struct ListNode *obj, int m) { struct ListNode *current = NULL; struct ListNode *left_node = NULL; struct ListNode *tmp = NULL; int index = 1; current = obj; while(index < m) { index++; left_node = current; current = current->next; } tmp = current->next; left_node->next = tmp; free(current); } void print_list(struct ListNode *obj) { struct ListNode *current = obj; while(current->next != NULL) { printf("%d ", current->val); current = current->next; } printf("\n"); } int main(int argv, char *argc[]) { struct ListNode *head = malloc(sizeof(head)); struct ListNode *current; int i = 0; int N = strtol(argc[1], NULL, 0); int target = 5; int index = 0; /* initial head node */ head->val = 1; head->next = NULL; /* initial linked list */ current = head; for (i = 2; i <= N; i++) { current->next = malloc(sizeof(current->next)); current = current->next; current->next = NULL; current->val = i; } /* list all val in each node */ print_list(head); index = search_val(head,target); printf("target: %d, index: %d\n", target, index); target = 8; printf("delete node: %d\n", target); remove_node(head, target); print_list(head); target = 10; printf("insert node: %d\n", target); insert_node(head, target, 111); print_list(head); return 0; }
the_stack_data/27479.c
#include <stdio.h> #include <stdlib.h> struct Projetos{ int codigo, ano, status; char titulo[30], chave[40], desc[60], autores[60], inst[30], gerenteN[20], gerenteS[20]; }; void cadastrar(struct Projetos projeto[], size_t len){ int i = 1, j, code, proc; char op = 's'; printf ("\nCadastro de projetos\n"); printf ("\nInforme as seguintes informacoes do projeto: \n"); while (i <= 200 && op == 's') { j = 1; proc = 0; printf("\nCodigo: "); scanf("%d", &code); while (j <= 200 && proc == 0){ if (code == projeto[j].codigo){ proc = 1; } else { j++; } } if (proc == 1){ printf("Codigo ja cadastrado!\n"); }else{ projeto[i].codigo = code; printf("Titulo: "); fgets(projeto[i].titulo, 30, stdin); printf("Palavras-chave(4): "); fgets(projeto[i].chave, 30, stdin); printf("Descricao: "); fgets(projeto[i].desc, 60, stdin); printf("Autores: "); fgets(projeto[i].autores, 60, stdin); printf("Instituicao: "); fgets(projeto[i].inst, 20, stdin); printf("Ano: "); scanf("%d", &projeto[i].ano); printf("Gerente Responsavel: "); scanf("%s%s", projeto[i].gerenteN, projeto[i].gerenteS); printf("Status: (1 - a fazer, 2 - fazendo, 3 - concluido) "); scanf("%d", &projeto[i].status); i++; } printf("Deseja cadastrar mais um projeto? 's'- sim 'n'- nao "); scanf(" %c", &op); } } void pesquisarProjeto(struct Projetos projeto[], size_t len){ int i = 1, j, proc; char code, op = 's'; printf("\nPesquisa por projeto cadastrado\n"); do { j = 1; proc = 0; printf("\nInsira o codigo do projeto: "); scanf("%d", &code); while (j <= 200 && proc == 0){ if (code == projeto[j].codigo){ proc = 1; } else { j++; } } if (proc == 0){ printf("Projeto nao cadastrado!\n"); } else { printf("\nCodigo: %d\n", projeto[i].codigo); printf("Titulo: %s\n", projeto[i].titulo); printf("Palavras-chave: %s\n", projeto[i].chave); printf("Descricao: %s\n", projeto[i].desc); printf("Autores: %s\n", projeto[i].autores); printf("Instituicao: %s\n", projeto[i].inst); printf("Ano: %d\n", &projeto[i].ano); printf("Gerente Responsavel: %s%s\n", projeto[i].gerenteN, projeto[i].gerenteS); switch (projeto[i].status){ case 1 : printf("Status: a fazer\n"); break; case 2 : printf("Status: fazendo\n"); break; case 3: printf("Status: concluido\n"); break; } i++; } printf("\nDeseja pesquisar mais um projeto? 's'- sim 'n'- nao "); scanf(" %c", &op); }while (op == 's' && i <= 200); } void listarTodos(struct Projetos projeto[], size_t len){ int i = 1; printf("\nListagem de Projetos\n"); do { printf("\nCodigo: %d\n", projeto[i].codigo); printf("Titulo: %s\n", projeto[i].titulo); printf("Palavras-chave: %s\n", projeto[i].chave); printf("Descricao: %s\n", projeto[i].desc); printf("Autores: %s\n", projeto[i].autores); printf("Instituicao: %s\n", projeto[i].inst); printf("Ano: %d\n", &projeto[i].ano); printf("Gerente Responsavel: %s%s\n", projeto[i].gerenteN, projeto[i].gerenteS); switch (projeto[i].status){ case 1 : printf("Status: a fazer\n"); break; case 2 : printf("Status: fazendo\n"); break; case 3: printf("Status: concluido\n"); break; } i++; }while (i <= 200); } void listarAfazer(struct Projetos projeto[], size_t len){ int i = 1; printf("\nListagem de Projetos a fazer\n"); do { if (projeto[i].status == 1){ printf("\nCodigo: %d\n", projeto[i].codigo); printf("Titulo: %s\n", projeto[i].titulo); printf("Palavras-chave: %s\n", projeto[i].chave); printf("Descricao: %s\n", projeto[i].desc); printf("Autores: %s\n", projeto[i].autores); printf("Instituicao: %s\n", projeto[i].inst); printf("Ano: %d\n", &projeto[i].ano); printf("Gerente Responsavel: %s%s\n", projeto[i].gerenteN, projeto[i].gerenteS); printf("Status: a fazer\n"); } i++; }while (i <= 200); } void listarEmcurso(struct Projetos projeto[], size_t len){ int i = 1; printf("\nListagem de Projetos em curso\n"); do { if (projeto[i].status == 2){ printf("\nCodigo: %d\n", projeto[i].codigo); printf("Titulo: %s\n", projeto[i].titulo); printf("Palavras-chave: %s\n", projeto[i].chave); printf("Descricao: %s\n", projeto[i].desc); printf("Autores: %s\n", projeto[i].autores); printf("Instituicao: %s\n", projeto[i].inst); printf("Ano: %d\n", &projeto[i].ano); printf("Gerente Responsavel: %s%s\n", projeto[i].gerenteN, projeto[i].gerenteS); printf("Status: em curso\n"); } i++; }while (i <= 200); } void listarFinalizado(struct Projetos projeto[], size_t len){ int i = 1; printf("\nListagem de Projetos finalizados\n"); do { if (projeto[i].status == 3){ printf("\nCodigo: %d\n", projeto[i].codigo); printf("Titulo: %s\n", projeto[i].titulo); printf("Palavras-chave: %s\n", projeto[i].chave); printf("Descricao: %s\n", projeto[i].desc); printf("Autores: %s\n", projeto[i].autores); printf("Instituicao: %s\n", projeto[i].inst); printf("Ano: %d\n", &projeto[i].ano); printf("Gerente Responsavel: %s%s\n", projeto[i].gerenteN, projeto[i].gerenteS); printf("Status: finalizado\n"); } i++; }while (i <= 200); } void main(){ struct Projetos proj[200]; int i, option1 = 0; char option2 = 's'; printf("Projetos\n"); while (option1 != 7 && option2 == 's'){ printf("\nDigite 1 se deseja cadastrar um Projeto\n"); printf("Digite 2 se deseja pesquisar um Projeto via codigo\n"); printf("Se deseja abrir uma listagem de projetos, digite:\n"); printf(" 3 - para todos projetos\n"); printf(" 4 - para projetos a fazer\n"); printf(" 5 - para projetos em curso \n"); printf(" 6 - para projetos finalizados\n"); printf("Digite 7 para sair\n"); scanf("%d", &option1); if (option1 != 7){ switch (option1){ case 1 : cadastrar(proj, sizeof(proj)); break; case 2 : pesquisarProjeto(proj, sizeof(proj)); break; case 3 : listarTodos(proj, sizeof(proj)); break; case 4 : listarAfazer(proj, sizeof(proj)); case 5 : listarEmcurso(proj, sizeof(proj)); break; case 6 : listarFinalizado(proj, sizeof(proj)); break; default : printf("Invalido!"); } } printf("\nDeseja escolher outra opcao? 's'- sim 'n'- nao \n"); scanf(" %c", &option2); } }
the_stack_data/31386683.c
/* $FreeBSD: soc2013/dpl/head/tools/regression/tls/libyy/yy.c 133109 2004-08-03 09:04:01Z dfr $ */ int __thread yy1 = 101;
the_stack_data/248580306.c
/* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_INCLUDE #define F2C_INCLUDE #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimag(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* Table of constant values */ static integer c__1 = 1; /* > \brief \b DORBDB1 */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download DORBDB1 + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dorbdb1 .f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dorbdb1 .f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dorbdb1 .f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE DORBDB1( M, P, Q, X11, LDX11, X21, LDX21, THETA, PHI, */ /* TAUP1, TAUP2, TAUQ1, WORK, LWORK, INFO ) */ /* INTEGER INFO, LWORK, M, P, Q, LDX11, LDX21 */ /* DOUBLE PRECISION PHI(*), THETA(*) */ /* DOUBLE PRECISION TAUP1(*), TAUP2(*), TAUQ1(*), WORK(*), */ /* $ X11(LDX11,*), X21(LDX21,*) */ /* > \par Purpose: */ /* ============= */ /* > */ /* >\verbatim */ /* > */ /* > DORBDB1 simultaneously bidiagonalizes the blocks of a tall and skinny */ /* > matrix X with orthonomal columns: */ /* > */ /* > [ B11 ] */ /* > [ X11 ] [ P1 | ] [ 0 ] */ /* > [-----] = [---------] [-----] Q1**T . */ /* > [ X21 ] [ | P2 ] [ B21 ] */ /* > [ 0 ] */ /* > */ /* > X11 is P-by-Q, and X21 is (M-P)-by-Q. Q must be no larger than P, */ /* > M-P, or M-Q. Routines DORBDB2, DORBDB3, and DORBDB4 handle cases in */ /* > which Q is not the minimum dimension. */ /* > */ /* > The orthogonal matrices P1, P2, and Q1 are P-by-P, (M-P)-by-(M-P), */ /* > and (M-Q)-by-(M-Q), respectively. They are represented implicitly by */ /* > Householder vectors. */ /* > */ /* > B11 and B12 are Q-by-Q bidiagonal matrices represented implicitly by */ /* > angles THETA, PHI. */ /* > */ /* >\endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] M */ /* > \verbatim */ /* > M is INTEGER */ /* > The number of rows X11 plus the number of rows in X21. */ /* > \endverbatim */ /* > */ /* > \param[in] P */ /* > \verbatim */ /* > P is INTEGER */ /* > The number of rows in X11. 0 <= P <= M. */ /* > \endverbatim */ /* > */ /* > \param[in] Q */ /* > \verbatim */ /* > Q is INTEGER */ /* > The number of columns in X11 and X21. 0 <= Q <= */ /* > MIN(P,M-P,M-Q). */ /* > \endverbatim */ /* > */ /* > \param[in,out] X11 */ /* > \verbatim */ /* > X11 is DOUBLE PRECISION array, dimension (LDX11,Q) */ /* > On entry, the top block of the matrix X to be reduced. On */ /* > exit, the columns of tril(X11) specify reflectors for P1 and */ /* > the rows of triu(X11,1) specify reflectors for Q1. */ /* > \endverbatim */ /* > */ /* > \param[in] LDX11 */ /* > \verbatim */ /* > LDX11 is INTEGER */ /* > The leading dimension of X11. LDX11 >= P. */ /* > \endverbatim */ /* > */ /* > \param[in,out] X21 */ /* > \verbatim */ /* > X21 is DOUBLE PRECISION array, dimension (LDX21,Q) */ /* > On entry, the bottom block of the matrix X to be reduced. On */ /* > exit, the columns of tril(X21) specify reflectors for P2. */ /* > \endverbatim */ /* > */ /* > \param[in] LDX21 */ /* > \verbatim */ /* > LDX21 is INTEGER */ /* > The leading dimension of X21. LDX21 >= M-P. */ /* > \endverbatim */ /* > */ /* > \param[out] THETA */ /* > \verbatim */ /* > THETA is DOUBLE PRECISION array, dimension (Q) */ /* > The entries of the bidiagonal blocks B11, B21 are defined by */ /* > THETA and PHI. See Further Details. */ /* > \endverbatim */ /* > */ /* > \param[out] PHI */ /* > \verbatim */ /* > PHI is DOUBLE PRECISION array, dimension (Q-1) */ /* > The entries of the bidiagonal blocks B11, B21 are defined by */ /* > THETA and PHI. See Further Details. */ /* > \endverbatim */ /* > */ /* > \param[out] TAUP1 */ /* > \verbatim */ /* > TAUP1 is DOUBLE PRECISION array, dimension (P) */ /* > The scalar factors of the elementary reflectors that define */ /* > P1. */ /* > \endverbatim */ /* > */ /* > \param[out] TAUP2 */ /* > \verbatim */ /* > TAUP2 is DOUBLE PRECISION array, dimension (M-P) */ /* > The scalar factors of the elementary reflectors that define */ /* > P2. */ /* > \endverbatim */ /* > */ /* > \param[out] TAUQ1 */ /* > \verbatim */ /* > TAUQ1 is DOUBLE PRECISION array, dimension (Q) */ /* > The scalar factors of the elementary reflectors that define */ /* > Q1. */ /* > \endverbatim */ /* > */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is DOUBLE PRECISION array, dimension (LWORK) */ /* > \endverbatim */ /* > */ /* > \param[in] LWORK */ /* > \verbatim */ /* > LWORK is INTEGER */ /* > The dimension of the array WORK. LWORK >= M-Q. */ /* > */ /* > If LWORK = -1, then a workspace query is assumed; the routine */ /* > only calculates the optimal size of the WORK array, returns */ /* > this value as the first entry of the WORK array, and no error */ /* > message related to LWORK is issued by XERBLA. */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit. */ /* > < 0: if INFO = -i, the i-th argument had an illegal value. */ /* > \endverbatim */ /* > */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date July 2012 */ /* > \ingroup doubleOTHERcomputational */ /* > \par Further Details: */ /* ===================== */ /* > */ /* > \verbatim */ /* > */ /* > The upper-bidiagonal blocks B11, B21 are represented implicitly by */ /* > angles THETA(1), ..., THETA(Q) and PHI(1), ..., PHI(Q-1). Every entry */ /* > in each bidiagonal band is a product of a sine or cosine of a THETA */ /* > with a sine or cosine of a PHI. See [1] or DORCSD for details. */ /* > */ /* > P1, P2, and Q1 are represented as products of elementary reflectors. */ /* > See DORCSD2BY1 for details on generating P1, P2, and Q1 using DORGQR */ /* > and DORGLQ. */ /* > \endverbatim */ /* > \par References: */ /* ================ */ /* > */ /* > [1] Brian D. Sutton. Computing the complete CS decomposition. Numer. */ /* > Algorithms, 50(1):33-65, 2009. */ /* > */ /* ===================================================================== */ /* Subroutine */ int dorbdb1_(integer *m, integer *p, integer *q, doublereal * x11, integer *ldx11, doublereal *x21, integer *ldx21, doublereal * theta, doublereal *phi, doublereal *taup1, doublereal *taup2, doublereal *tauq1, doublereal *work, integer *lwork, integer *info) { /* System generated locals */ integer x11_dim1, x11_offset, x21_dim1, x21_offset, i__1, i__2, i__3, i__4; doublereal d__1, d__2; /* Local variables */ extern /* Subroutine */ int drot_(integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *); integer lworkmin; extern doublereal dnrm2_(integer *, doublereal *, integer *); integer lworkopt; doublereal c__; integer i__; doublereal s; extern /* Subroutine */ int dlarf_(char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *); integer ilarf, llarf, childinfo; extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen); logical lquery; extern /* Subroutine */ int dorbdb5_(integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, integer *); integer iorbdb5, lorbdb5; extern /* Subroutine */ int dlarfgp_(integer *, doublereal *, doublereal * , integer *, doublereal *); /* -- LAPACK computational routine (version 3.7.1) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* July 2012 */ /* ==================================================================== */ /* Test input arguments */ /* Parameter adjustments */ x11_dim1 = *ldx11; x11_offset = 1 + x11_dim1 * 1; x11 -= x11_offset; x21_dim1 = *ldx21; x21_offset = 1 + x21_dim1 * 1; x21 -= x21_offset; --theta; --phi; --taup1; --taup2; --tauq1; --work; /* Function Body */ *info = 0; lquery = *lwork == -1; if (*m < 0) { *info = -1; } else if (*p < *q || *m - *p < *q) { *info = -2; } else if (*q < 0 || *m - *q < *q) { *info = -3; } else if (*ldx11 < f2cmax(1,*p)) { *info = -5; } else /* if(complicated condition) */ { /* Computing MAX */ i__1 = 1, i__2 = *m - *p; if (*ldx21 < f2cmax(i__1,i__2)) { *info = -7; } } /* Compute workspace */ if (*info == 0) { ilarf = 2; /* Computing MAX */ i__1 = *p - 1, i__2 = *m - *p - 1, i__1 = f2cmax(i__1,i__2), i__2 = *q - 1; llarf = f2cmax(i__1,i__2); iorbdb5 = 2; lorbdb5 = *q - 2; /* Computing MAX */ i__1 = ilarf + llarf - 1, i__2 = iorbdb5 + lorbdb5 - 1; lworkopt = f2cmax(i__1,i__2); lworkmin = lworkopt; work[1] = (doublereal) lworkopt; if (*lwork < lworkmin && ! lquery) { *info = -14; } } if (*info != 0) { i__1 = -(*info); xerbla_("DORBDB1", &i__1, (ftnlen)7); return 0; } else if (lquery) { return 0; } /* Reduce columns 1, ..., Q of X11 and X21 */ i__1 = *q; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = *p - i__ + 1; dlarfgp_(&i__2, &x11[i__ + i__ * x11_dim1], &x11[i__ + 1 + i__ * x11_dim1], &c__1, &taup1[i__]); i__2 = *m - *p - i__ + 1; dlarfgp_(&i__2, &x21[i__ + i__ * x21_dim1], &x21[i__ + 1 + i__ * x21_dim1], &c__1, &taup2[i__]); theta[i__] = atan2(x21[i__ + i__ * x21_dim1], x11[i__ + i__ * x11_dim1]); c__ = cos(theta[i__]); s = sin(theta[i__]); x11[i__ + i__ * x11_dim1] = 1.; x21[i__ + i__ * x21_dim1] = 1.; i__2 = *p - i__ + 1; i__3 = *q - i__; dlarf_("L", &i__2, &i__3, &x11[i__ + i__ * x11_dim1], &c__1, &taup1[ i__], &x11[i__ + (i__ + 1) * x11_dim1], ldx11, &work[ilarf]); i__2 = *m - *p - i__ + 1; i__3 = *q - i__; dlarf_("L", &i__2, &i__3, &x21[i__ + i__ * x21_dim1], &c__1, &taup2[ i__], &x21[i__ + (i__ + 1) * x21_dim1], ldx21, &work[ilarf]); if (i__ < *q) { i__2 = *q - i__; drot_(&i__2, &x11[i__ + (i__ + 1) * x11_dim1], ldx11, &x21[i__ + ( i__ + 1) * x21_dim1], ldx21, &c__, &s); i__2 = *q - i__; dlarfgp_(&i__2, &x21[i__ + (i__ + 1) * x21_dim1], &x21[i__ + (i__ + 2) * x21_dim1], ldx21, &tauq1[i__]); s = x21[i__ + (i__ + 1) * x21_dim1]; x21[i__ + (i__ + 1) * x21_dim1] = 1.; i__2 = *p - i__; i__3 = *q - i__; dlarf_("R", &i__2, &i__3, &x21[i__ + (i__ + 1) * x21_dim1], ldx21, &tauq1[i__], &x11[i__ + 1 + (i__ + 1) * x11_dim1], ldx11, &work[ilarf]); i__2 = *m - *p - i__; i__3 = *q - i__; dlarf_("R", &i__2, &i__3, &x21[i__ + (i__ + 1) * x21_dim1], ldx21, &tauq1[i__], &x21[i__ + 1 + (i__ + 1) * x21_dim1], ldx21, &work[ilarf]); i__2 = *p - i__; /* Computing 2nd power */ d__1 = dnrm2_(&i__2, &x11[i__ + 1 + (i__ + 1) * x11_dim1], &c__1); i__3 = *m - *p - i__; /* Computing 2nd power */ d__2 = dnrm2_(&i__3, &x21[i__ + 1 + (i__ + 1) * x21_dim1], &c__1); c__ = sqrt(d__1 * d__1 + d__2 * d__2); phi[i__] = atan2(s, c__); i__2 = *p - i__; i__3 = *m - *p - i__; i__4 = *q - i__ - 1; dorbdb5_(&i__2, &i__3, &i__4, &x11[i__ + 1 + (i__ + 1) * x11_dim1] , &c__1, &x21[i__ + 1 + (i__ + 1) * x21_dim1], &c__1, & x11[i__ + 1 + (i__ + 2) * x11_dim1], ldx11, &x21[i__ + 1 + (i__ + 2) * x21_dim1], ldx21, &work[iorbdb5], &lorbdb5, &childinfo); } } return 0; /* End of DORBDB1 */ } /* dorbdb1_ */
the_stack_data/165768503.c
int ft_str_is_numeric(char *str) { int i; i = 0; while (str[i]) { if (str[i] < '0' || str[i] > '9') return (0); i++; } return (1); }
the_stack_data/117328034.c
int main() { signed int i, j; i = j; i++; }
the_stack_data/26701547.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern float strtof(char const *str , char const *endptr ) ; extern void signal(int sig , void *func ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned char input[1] , unsigned char output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; int main(int argc , char *argv[] ) { unsigned char input[1] ; unsigned char output[1] ; int randomFuns_i5 ; unsigned char randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = (unsigned char )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == (unsigned char)42) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } } void RandomFunc(unsigned char input[1] , unsigned char output[1] ) { unsigned char state[1] ; { state[0UL] = input[0UL] + (unsigned char)69; if ((state[0UL] >> (unsigned char)4) & (unsigned char)1) { if ((state[0UL] >> (unsigned char)4) & (unsigned char)1) { if ((state[0UL] >> (unsigned char)2) & (unsigned char)1) { state[0UL] += state[0UL]; state[0UL] += state[0UL]; } else { state[0UL] += state[0UL]; state[0UL] += state[0UL]; } } else if ((state[0UL] >> (unsigned char)2) & (unsigned char)1) { state[0UL] += state[0UL]; state[0UL] += state[0UL]; } else { state[0UL] += state[0UL]; state[0UL] += state[0UL]; } } else { state[0UL] += state[0UL]; state[0UL] += state[0UL]; } output[0UL] = state[0UL] + (unsigned char)180; } } void megaInit(void) { { } }
the_stack_data/144551.c
/*** * This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License. * When used, please cite the following article(s): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993 * This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published. ***/ #include <stdint.h> #include <stdlib.h> /// Approximate function add8_030 /// Library = EvoApprox8b /// Circuit = add8_030 /// Area (180) = 784 /// Delay (180) = 1.250 /// Power (180) = 201.40 /// Area (45) = 59 /// Delay (45) = 0.480 /// Power (45) = 19.24 /// Nodes = 14 /// HD = 172672 /// MAE = 3.46875 /// MSE = 18.50000 /// MRE = 1.86 % /// WCE = 11 /// WCRE = 500 % /// EP = 90.6 % uint16_t add8_030(uint8_t a, uint8_t b) { uint16_t c = 0; uint8_t n4 = (a >> 2) & 0x1; uint8_t n6 = (a >> 3) & 0x1; uint8_t n8 = (a >> 4) & 0x1; uint8_t n10 = (a >> 5) & 0x1; uint8_t n12 = (a >> 6) & 0x1; uint8_t n14 = (a >> 7) & 0x1; uint8_t n18 = (b >> 1) & 0x1; uint8_t n20 = (b >> 2) & 0x1; uint8_t n22 = (b >> 3) & 0x1; uint8_t n24 = (b >> 4) & 0x1; uint8_t n26 = (b >> 5) & 0x1; uint8_t n28 = (b >> 6) & 0x1; uint8_t n30 = (b >> 7) & 0x1; uint8_t n33; uint8_t n38; uint8_t n40; uint8_t n51; uint8_t n52; uint8_t n78; uint8_t n127; uint8_t n132; uint8_t n182; uint8_t n212; uint8_t n232; uint8_t n233; uint8_t n282; uint8_t n283; uint8_t n332; uint8_t n333; uint8_t n382; uint8_t n383; n33 = ~(n22 & n6); n38 = ~n33; n40 = n20 ^ n20; n51 = n4; n52 = n51 & n38; n78 = n52; n127 = ~n40; n132 = n127 | n20; n182 = n6 | n22; n212 = n78; n232 = (n8 ^ n24) ^ n212; n233 = (n8 & n24) | (n24 & n212) | (n8 & n212); n282 = (n10 ^ n26) ^ n233; n283 = (n10 & n26) | (n26 & n233) | (n10 & n233); n332 = (n12 ^ n28) ^ n283; n333 = (n12 & n28) | (n28 & n283) | (n12 & n283); n382 = (n14 ^ n30) ^ n333; n383 = (n14 & n30) | (n30 & n333) | (n14 & n333); c |= (n127 & 0x1) << 0; c |= (n18 & 0x1) << 1; c |= (n132 & 0x1) << 2; c |= (n182 & 0x1) << 3; c |= (n232 & 0x1) << 4; c |= (n282 & 0x1) << 5; c |= (n332 & 0x1) << 6; c |= (n382 & 0x1) << 7; c |= (n383 & 0x1) << 8; return c; }
the_stack_data/178265887.c
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(){ int S[100], T[100]; char checked[100]; int n,q; int i=0; int j; int c=0; char input[400]; char *p; memset(checked,0,sizeof(checked)); scanf("%d\n",&n); gets(input); //split p = strtok(input," "); S[0] = atoi(p); while(p != NULL){ p = strtok(NULL," "); if(p != NULL){ i++; S[i] = atoi(p); } } //end split scanf("%d\n",&q); gets(input); //split i=0; p = strtok(input," "); T[0] = atoi(p); while(p != NULL){ p = strtok(NULL," "); if(p != NULL){ i++; T[i] = atoi(p); } } //end split for(i=0;i<q;i++){ for(j=0;j<n;j++){ if(T[i] == S[j] && checked[i] == 0){ c++; checked[i] = 1; } } } printf("%d\n",c); return 0; }
the_stack_data/132953966.c
#include <stdio.h> int Factorial(const int N); int main() { int N, NF; scanf("%d", &N); NF = Factorial(N); if (NF) printf("%d! = %d\n", N, NF); else printf("Invalid input\n"); return 0; } int Factorial(const int N) { if (N < 0) return 0; int ans = 1, i; for (i = 2; i <= N; i++) ans *= i; return ans; }
the_stack_data/64200805.c
int Fstype(const char *path,char type[]) { *type = 0; return -1; }
the_stack_data/52224.c
/* * FreeRTOS Kernel V10.3.0 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #ifdef RUN_FREERTOS_DEMO /****************************************************************************** * NOTE 1: This project provides two demo applications. A simple blinky * style project, and a more comprehensive test and demo application. The * mainCREATE_SIMPLE_BLINKY_DEMO_ONLY setting in main.c is used to select * between the two. See the notes on using mainCREATE_SIMPLE_BLINKY_DEMO_ONLY * in main.c. This file implements the simply blinky style version. * * NOTE 2: This file only contains the source code that is specific to the * basic demo. Generic functions, such FreeRTOS hook functions, and functions * required to configure the hardware are defined in main.c. ****************************************************************************** * * main_blinky() creates one queue, and two tasks. It then starts the * scheduler. * * The Queue Send Task: * The queue send task is implemented by the prvQueueSendTask() function in * this file. prvQueueSendTask() sits in a loop that causes it to repeatedly * block for 1000 milliseconds, before sending the value 100 to the queue that * was created within main_blinky(). Once the value is sent, the task loops * back around to block for another 1000 milliseconds...and so on. * * The Queue Receive Task: * The queue receive task is implemented by the prvQueueReceiveTask() function * in this file. prvQueueReceiveTask() sits in a loop where it repeatedly * blocks on attempts to read data from the queue that was created within * main_blinky(). When data is received, the task checks the value of the * data, and if the value equals the expected 100, writes 'Blink' to the UART * (the UART is used in place of the LED to allow easy execution in QEMU). The * 'block time' parameter passed to the queue receive function specifies that * the task should be held in the Blocked state indefinitely to wait for data to * be available on the queue. The queue receive task will only leave the * Blocked state when the queue send task writes to the queue. As the queue * send task writes to the queue every 1000 milliseconds, the queue receive * task leaves the Blocked state every 1000 milliseconds, and therefore toggles * the LED every 200 milliseconds. */ /* Standard includes. */ #include <stdio.h> #include <string.h> #include <unistd.h> /* Kernel includes. */ #include "FreeRTOS.h" #include "task.h" #include "queue.h" /* Priorities used by the tasks. */ #define mainQUEUE_RECEIVE_TASK_PRIORITY ( tskIDLE_PRIORITY + 2 ) #define mainQUEUE_SEND_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) /* The rate at which data is sent to the queue. The 200ms value is converted to ticks using the pdMS_TO_TICKS() macro. */ #define mainQUEUE_SEND_FREQUENCY_MS pdMS_TO_TICKS( 1000 ) /* The maximum number items the queue can hold. The priority of the receiving task is above the priority of the sending task, so the receiving task will preempt the sending task and remove the queue items each time the sending task writes to the queue. Therefore the queue will never have more than one item in it at any time, and even with a queue length of 1, the sending task will never find the queue full. */ #define mainQUEUE_LENGTH ( 1 ) /*-----------------------------------------------------------*/ /* * Called by main when mainCREATE_SIMPLE_BLINKY_DEMO_ONLY is set to 1 in * main.c. */ void main_blinky( void ); /* * The tasks as described in the comments at the top of this file. */ static void prvQueueReceiveTask( void *pvParameters ); static void prvQueueSendTask( void *pvParameters ); /*-----------------------------------------------------------*/ /* The queue used by both tasks. */ static QueueHandle_t xQueue = NULL; /*-----------------------------------------------------------*/ void main_blinky( void ) { /* Create the queue. */ xQueue = xQueueCreate( mainQUEUE_LENGTH, sizeof( uint32_t ) ); if( xQueue != NULL ) { /* Start the two tasks as described in the comments at the top of this file. */ xTaskCreate( prvQueueReceiveTask, /* The function that implements the task. */ "Rx", /* The text name assigned to the task - for debug only as it is not used by the kernel. */ configMINIMAL_STACK_SIZE * 2U, /* The size of the stack to allocate to the task. */ NULL, /* The parameter passed to the task - not used in this case. */ mainQUEUE_RECEIVE_TASK_PRIORITY, /* The priority assigned to the task. */ NULL ); /* The task handle is not required, so NULL is passed. */ xTaskCreate( prvQueueSendTask, "TX", configMINIMAL_STACK_SIZE * 2U, NULL, mainQUEUE_SEND_TASK_PRIORITY, NULL ); /* Start the tasks and timer running. */ vTaskStartScheduler(); } /* If all is well, the scheduler will now be running, and the following line will never be reached. If the following line does execute, then there was insufficient FreeRTOS heap memory available for the Idle and/or timer tasks to be created. See the memory management section on the FreeRTOS web site for more details on the FreeRTOS heap http://www.freertos.org/a00111.html. */ for( ;; ); } /*-----------------------------------------------------------*/ static void prvQueueSendTask( void *pvParameters ) { TickType_t xNextWakeTime; const unsigned long ulValueToSend = 100UL; BaseType_t xReturned; /* Remove compiler warning about unused parameter. */ ( void ) pvParameters; /* Initialise xNextWakeTime - this only needs to be done once. */ xNextWakeTime = xTaskGetTickCount(); for( ;; ) { /* Place this task in the blocked state until it is time to run again. */ vTaskDelayUntil( &xNextWakeTime, mainQUEUE_SEND_FREQUENCY_MS ); /* Send to the queue - causing the queue receive task to unblock and toggle the LED. 0 is used as the block time so the sending operation will not block - it shouldn't need to block as the queue should always be empty at this point in the code. */ xReturned = xQueueSend( xQueue, &ulValueToSend, 0U ); configASSERT( xReturned == pdPASS ); } } /*-----------------------------------------------------------*/ static void prvQueueReceiveTask( void *pvParameters ) { unsigned long ulReceivedValue; const unsigned long ulExpectedValue = 100UL; const char * const pcPassMessage = "Blink\r\n"; const char * const pcFailMessage = "Unexpected value received\r\n"; extern void vSendString( const char * const pcString ); extern void vToggleLED( void ); /* Remove compiler warning about unused parameter. */ ( void ) pvParameters; for( ;; ) { /* Wait until something arrives in the queue - this task will block indefinitely provided INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. */ xQueueReceive( xQueue, &ulReceivedValue, portMAX_DELAY ); /* To get here something must have been received from the queue, but is it the expected value? If it is, toggle the LED. */ if( ulReceivedValue == ulExpectedValue ) { vSendString( pcPassMessage ); vToggleLED(); ulReceivedValue = 0U; } else { vSendString( pcFailMessage ); } } } /*-----------------------------------------------------------*/ #endif
the_stack_data/75562.c
// Given code 'struct aa { char s1[4]; char * s2;} a; memcpy(a.s1, ...);', // this test checks that the CStringChecker only invalidates the destination buffer array a.s1 (instead of a.s1 and a.s2). // At the moment the whole of the destination array content is invalidated. // If a.s1 region has a symbolic offset, the whole region of 'a' is invalidated. // Specific triple set to test structures of size 0. // RUN: %clang_analyze_cc1 -triple x86_64-pc-linux-gnu -analyzer-checker=core,unix.Malloc,debug.ExprInspection -analyzer-store=region -verify -analyzer-config eagerly-assume=false %s typedef __typeof(sizeof(int)) size_t; char *strdup(const char *s); void free(void *); void *memcpy(void *dst, const void *src, size_t n); // expected-note{{passing argument to parameter 'dst' here}} void *malloc(size_t n); void clang_analyzer_eval(int); struct aa { char s1[4]; char *s2; }; // Test different types of structure initialisation. int f0() { struct aa a0 = {{1, 2, 3, 4}, 0}; a0.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(a0.s1, input, 4); clang_analyzer_eval(a0.s1[0] == 'a'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a0.s1[1] == 'b'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a0.s1[2] == 'c'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a0.s1[3] == 'd'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a0.s2 == 0); // expected-warning{{UNKNOWN}} free(a0.s2); // no warning return 0; } int f1() { struct aa a1; a1.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(a1.s1, input, 4); clang_analyzer_eval(a1.s1[0] == 'a'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a1.s1[1] == 'b'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a1.s1[2] == 'c'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a1.s1[3] == 'd'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a1.s2 == 0); // expected-warning{{UNKNOWN}} free(a1.s2); // no warning return 0; } int f2() { struct aa a2 = {{1, 2}}; a2.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(a2.s1, input, 4); clang_analyzer_eval(a2.s1[0] == 'a'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a2.s1[1] == 'b'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a2.s1[2] == 'c'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a2.s1[3] == 'd'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a2.s2 == 0); // expected-warning{{UNKNOWN}} free(a2.s2); // no warning return 0; } int f3() { struct aa a3 = {{1, 2, 3, 4}, 0}; a3.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; int * dest = (int*)a3.s1; memcpy(dest, input, 4); clang_analyzer_eval(a3.s1[0] == 'a'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(dest[0] == 'a'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a3.s1[1] == 'b'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(dest[1] == 'b'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a3.s1[2] == 'c'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(dest[2] == 'c'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a3.s1[3] == 'd'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(dest[3] == 'd'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a3.s2 == 0); // expected-warning{{UNKNOWN}} free(a3.s2); // no warning return 0; } struct bb { struct aa a; char * s2; }; int f4() { struct bb b0 = {{1, 2, 3, 4}, 0}; b0.s2 = strdup("hello"); b0.a.s2 = strdup("hola"); char input[] = {'a', 'b', 'c', 'd'}; char * dest = (char*)(b0.a.s1); memcpy(dest, input, 4); clang_analyzer_eval(b0.a.s1[0] == 'a'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(dest[0] == 'a'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(b0.a.s1[1] == 'b'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(dest[1] == 'b'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(b0.a.s1[2] == 'c'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(dest[2] == 'c'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(b0.a.s1[3] == 'd'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(dest[3] == 'd'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(b0.s2 == 0); // expected-warning{{UNKNOWN}} free(b0.a.s2); // no warning free(b0.s2); // no warning return 0; } // Test that memory leaks are caught. int f5() { struct aa a0 = {{1, 2, 3, 4}, 0}; a0.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(a0.s1, input, 4); return 0; // expected-warning{{Potential leak of memory pointed to by 'a0.s2'}} } int f6() { struct aa a1; a1.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(a1.s1, input, 4); return 0; // expected-warning{{Potential leak of memory pointed to by 'a1.s2'}} } int f7() { struct aa a2 = {{1, 2}}; a2.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(a2.s1, input, 4); return 0; // expected-warning{{Potential leak of memory pointed to by 'a2.s2'}} } int f8() { struct aa a3 = {{1, 2, 3, 4}, 0}; a3.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; int * dest = (int*)a3.s1; memcpy(dest, input, 4); return 0; // expected-warning{{Potential leak of memory pointed to by 'a3.s2'}} } int f9() { struct bb b0 = {{1, 2, 3, 4}, 0}; b0.s2 = strdup("hello"); b0.a.s2 = strdup("hola"); char input[] = {'a', 'b', 'c', 'd'}; char * dest = (char*)(b0.a.s1); memcpy(dest, input, 4); free(b0.a.s2); // expected-warning{{Potential leak of memory pointed to by 'b0.s2'}} return 0; } int f10() { struct bb b0 = {{1, 2, 3, 4}, 0}; b0.s2 = strdup("hello"); b0.a.s2 = strdup("hola"); char input[] = {'a', 'b', 'c', 'd'}; char * dest = (char*)(b0.a.s1); memcpy(dest, input, 4); free(b0.s2); // expected-warning{{Potential leak of memory pointed to by 'b0.a.s2'}} return 0; } // Test invalidating fields being addresses of array. struct cc { char * s1; char * s2; }; int f11() { char x[4] = {1, 2}; x[0] = 1; x[1] = 2; struct cc c0; c0.s2 = strdup("hello"); c0.s1 = &x[0]; char input[] = {'a', 'b', 'c', 'd'}; memcpy(c0.s1, input, 4); clang_analyzer_eval(x[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(x[1] == 2); // expected-warning{{UNKNOWN}} clang_analyzer_eval(c0.s1[0] == 'a'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(c0.s1[1] == 'b'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(c0.s1[2] == 'c'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(c0.s1[3] == 'd'); // expected-warning{{UNKNOWN}} free(c0.s2); // no-warning return 0; } // Test inverting field position between s1 and s2. struct dd { char *s2; char s1[4]; }; int f12() { struct dd d0 = {0, {1, 2, 3, 4}}; d0.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(d0.s1, input, 4); clang_analyzer_eval(d0.s1[0] == 'a'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(d0.s1[1] == 'b'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(d0.s1[2] == 'c'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(d0.s1[3] == 'd'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(d0.s2 == 0); // expected-warning{{UNKNOWN}} free(d0.s2); // no warning return 0; } // Test arrays of structs. struct ee { int a; char b; }; struct EE { struct ee s1[2]; char * s2; }; int f13() { struct EE E0 = {{{1, 2}, {3, 4}}, 0}; E0.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(E0.s1, input, 4); clang_analyzer_eval(E0.s1[0].a == 'a'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(E0.s1[0].b == 'b'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(E0.s1[1].a == 'c'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(E0.s1[1].b == 'd'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(E0.s2 == 0); // expected-warning{{UNKNOWN}} free(E0.s2); // no warning return 0; } // Test global parameters. struct aa a15 = {{1, 2, 3, 4}, 0}; int f15() { a15.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(a15.s1, input, 4); clang_analyzer_eval(a15.s1[0] == 'a'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a15.s1[1] == 'b'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a15.s1[2] == 'c'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a15.s1[3] == 'd'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a15.s2 == 0); // expected-warning{{UNKNOWN}} free(a15.s2); // no warning return 0; } // Test array of 0 sized elements. struct empty {}; struct gg { struct empty s1[4]; char * s2; }; int f16() { struct gg g0 = {{}, 0}; g0.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(g0.s1, input, 4); clang_analyzer_eval(*(int*)(&g0.s1[0]) == 'a'); // expected-warning{{UNKNOWN}}\ expected-warning{{Potential leak of memory pointed to by 'g0.s2'}} clang_analyzer_eval(*(int*)(&g0.s1[1]) == 'b'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(*(int*)(&g0.s1[2]) == 'c'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(*(int*)(&g0.s1[3]) == 'd'); // expected-warning{{UNKNOWN}} clang_analyzer_eval(g0.s2 == 0); // expected-warning{{UNKNOWN}} free(g0.s2); // no warning return 0; } // Test array of 0 elements. struct hh { char s1[0]; char * s2; }; int f17() { struct hh h0; h0.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(h0.s1, input, 4); clang_analyzer_eval(h0.s1[0] == 'a'); // expected-warning{{UNKNOWN}}\ expected-warning{{Potential leak of memory pointed to by 'h0.s2'}} clang_analyzer_eval(h0.s2 == 0); // expected-warning{{UNKNOWN}} free(h0.s2); // no warning return 0; } // Test writing past the array. struct ii { char s1[4]; int i; int j; char * s2; }; int f18() { struct ii i18 = {{1, 2, 3, 4}, 5, 6}; i18.i = 10; i18.j = 11; i18.s2 = strdup("hello"); char input[100] = {3}; memcpy(i18.s1, input, 100); // expected-warning {{'memcpy' will always overflow; destination buffer has size 24, but size argument is 100}} clang_analyzer_eval(i18.s1[0] == 1); // expected-warning{{UNKNOWN}}\ expected-warning{{Potential leak of memory pointed to by 'i18.s2'}} clang_analyzer_eval(i18.s1[1] == 2); // expected-warning{{UNKNOWN}} clang_analyzer_eval(i18.s1[2] == 3); // expected-warning{{UNKNOWN}} clang_analyzer_eval(i18.s1[3] == 4); // expected-warning{{UNKNOWN}} clang_analyzer_eval(i18.i == 10); // expected-warning{{UNKNOWN}} clang_analyzer_eval(i18.j == 11); // expected-warning{{UNKNOWN}} return 0; } int f181() { struct ii i181 = {{1, 2, 3, 4}, 5, 6}; i181.i = 10; i181.j = 11; i181.s2 = strdup("hello"); char input[100] = {3}; memcpy(i181.s1, input, 5); // invalidate the whole region of i181 clang_analyzer_eval(i181.s1[0] == 1); // expected-warning{{UNKNOWN}}\ expected-warning{{Potential leak of memory pointed to by 'i181.s2'}} clang_analyzer_eval(i181.s1[1] == 2); // expected-warning{{UNKNOWN}} clang_analyzer_eval(i181.s1[2] == 3); // expected-warning{{UNKNOWN}} clang_analyzer_eval(i181.s1[3] == 4); // expected-warning{{UNKNOWN}} clang_analyzer_eval(i181.i == 10); // expected-warning{{UNKNOWN}} clang_analyzer_eval(i181.j == 11); // expected-warning{{UNKNOWN}} return 0; } // Test array with a symbolic offset. struct jj { char s1[2]; char * s2; }; struct JJ { struct jj s1[3]; char * s2; }; int f19(int i) { struct JJ J0 = {{{1, 2, 0}, {3, 4, 0}, {5, 6, 0}}, 0}; J0.s2 = strdup("hello"); J0.s1[0].s2 = strdup("hello"); J0.s1[1].s2 = strdup("hi"); J0.s1[2].s2 = strdup("world"); char input[2] = {'a', 'b'}; memcpy(J0.s1[i].s1, input, 2); clang_analyzer_eval(J0.s1[0].s1[0] == 1); // expected-warning{{UNKNOWN}}\ expected-warning{{Potential leak of memory pointed to by field 's2'}}\ expected-warning{{Potential leak of memory pointed to by 'J0.s2'}} clang_analyzer_eval(J0.s1[0].s1[1] == 2); // expected-warning{{UNKNOWN}} clang_analyzer_eval(J0.s1[1].s1[0] == 3); // expected-warning{{UNKNOWN}} clang_analyzer_eval(J0.s1[1].s1[1] == 4); // expected-warning{{UNKNOWN}} clang_analyzer_eval(J0.s1[2].s1[0] == 5); // expected-warning{{UNKNOWN}} clang_analyzer_eval(J0.s1[2].s1[1] == 6); // expected-warning{{UNKNOWN}} clang_analyzer_eval(J0.s1[i].s1[0] == 5); // expected-warning{{UNKNOWN}} clang_analyzer_eval(J0.s1[i].s1[1] == 6); // expected-warning{{UNKNOWN}} // FIXME: memory leak warning for J0.s2 should be emitted here instead of after memcpy call. return 0; // no warning } // Test array with its super region having symbolic offseted regions. int f20(int i) { struct aa * a20 = malloc(sizeof(struct aa) * 2); a20[0].s1[0] = 1; a20[0].s1[1] = 2; a20[0].s1[2] = 3; a20[0].s1[3] = 4; a20[0].s2 = strdup("hello"); a20[1].s1[0] = 5; a20[1].s1[1] = 6; a20[1].s1[2] = 7; a20[1].s1[3] = 8; a20[1].s2 = strdup("world"); a20[i].s2 = strdup("hola"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(a20[0].s1, input, 4); clang_analyzer_eval(a20[0].s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a20[0].s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a20[0].s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a20[0].s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a20[0].s2 == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a20[1].s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a20[1].s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a20[1].s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a20[1].s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a20[1].s2 == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a20[i].s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a20[i].s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a20[i].s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a20[i].s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a20[i].s2 == 0); // expected-warning{{UNKNOWN}}\ expected-warning{{Potential leak of memory pointed to by 'a20'}} return 0; } // Test array's region and super region both having symbolic offsets. int f21(int i) { struct aa * a21 = malloc(sizeof(struct aa) * 2); a21[0].s1[0] = 1; a21[0].s1[1] = 2; a21[0].s1[2] = 3; a21[0].s1[3] = 4; a21[0].s2 = 0; a21[1].s1[0] = 5; a21[1].s1[1] = 6; a21[1].s1[2] = 7; a21[1].s1[3] = 8; a21[1].s2 = 0; a21[i].s2 = strdup("hello"); a21[i].s1[0] = 1; a21[i].s1[1] = 2; a21[i].s1[2] = 3; a21[i].s1[3] = 4; char input[] = {'a', 'b', 'c', 'd'}; memcpy(a21[i].s1, input, 4); clang_analyzer_eval(a21[0].s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a21[0].s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a21[0].s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a21[0].s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a21[0].s2 == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a21[1].s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a21[1].s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a21[1].s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a21[1].s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a21[1].s2 == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a21[i].s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a21[i].s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a21[i].s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a21[i].s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a21[i].s2 == 0); // expected-warning{{UNKNOWN}}\ expected-warning{{Potential leak of memory pointed to by 'a21'}} return 0; } // Test regions aliasing other regions. struct ll { char s1[4]; char * s2; }; struct mm { char s3[4]; char * s4; }; int f24() { struct ll l24 = {{1, 2, 3, 4}, 0}; struct mm * m24 = (struct mm *)&l24; m24->s4 = strdup("hello"); char input[] = {1, 2, 3, 4}; memcpy(m24->s3, input, 4); clang_analyzer_eval(m24->s3[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m24->s3[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m24->s3[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m24->s3[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(l24.s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(l24.s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(l24.s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(l24.s1[3] == 1); // expected-warning{{UNKNOWN}}\ expected-warning{{Potential leak of memory pointed to by field 's4'}} return 0; } // Test region with potential aliasing and symbolic offsets. // Store assumes no aliasing. int f25(int i, int j, struct ll * l, struct mm * m) { m->s4 = strdup("hola"); // m->s4 not tracked m->s3[0] = 1; m->s3[1] = 2; m->s3[2] = 3; m->s3[3] = 4; m->s3[j] = 5; // invalidates m->s3 l->s2 = strdup("hello"); // l->s2 not tracked l->s1[0] = 6; l->s1[1] = 7; l->s1[2] = 8; l->s1[3] = 9; l->s1[i] = 10; // invalidates l->s1 char input[] = {1, 2, 3, 4}; memcpy(m->s3, input, 4); // does not invalidate l->s1[i] clang_analyzer_eval(m->s3[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m->s3[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m->s3[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m->s3[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m->s3[i] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m->s3[j] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(l->s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(l->s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(l->s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(l->s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(l->s1[i] == 1); // expected-warning{{FALSE}} clang_analyzer_eval(l->s1[j] == 1); // expected-warning{{UNKNOWN}} return 0; } // Test size with symbolic size argument. int f26(int i) { struct aa a26 = {{1, 2, 3, 4}, 0}; a26.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(a26.s1, input, i); // i assumed in bound clang_analyzer_eval(a26.s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a26.s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a26.s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a26.s1[3] == 1); // expected-warning{{UNKNOWN}}\ expected-warning{{Potential leak of memory pointed to by 'a26.s2'}} return 0; } // Test sizeof as a size argument. int f261() { struct aa a261 = {{1, 2, 3, 4}, 0}; a261.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(a261.s1, input, sizeof(a261.s1)); clang_analyzer_eval(a261.s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a261.s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a261.s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a261.s1[3] == 1); // expected-warning{{UNKNOWN}}\ expected-warning{{Potential leak of memory pointed to by 'a261.s2'}} return 0; } // Test negative size argument. int f262() { struct aa a262 = {{1, 2, 3, 4}, 0}; a262.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(a262.s1, input, -1); // expected-warning{{'memcpy' will always overflow; destination buffer has size 16, but size argument is 18446744073709551615}} clang_analyzer_eval(a262.s1[0] == 1); // expected-warning{{UNKNOWN}}\ expected-warning{{Potential leak of memory pointed to by 'a262.s2'}} clang_analyzer_eval(a262.s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a262.s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a262.s1[3] == 1); // expected-warning{{UNKNOWN}} return 0; } // Test size argument being an unknown value. struct xx { char s1[4]; char * s2; }; int f263(int n, char * len) { struct xx x263 = {0}; x263.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(x263.s1, input, *(len + n)); clang_analyzer_eval(x263.s1[0] == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(x263.s1[1] == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(x263.s1[2] == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(x263.s1[3] == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(x263.s2 == 0); // expected-warning{{UNKNOWN}} return 0; // expected-warning{{Potential leak of memory pointed to by 'x263.s2'}} } // Test casting regions with symbolic offseted sub regions. int f27(int i) { struct mm m27 = {{1, 2, 3, 4}, 0}; m27.s4 = strdup("hello"); m27.s3[i] = 5; char input[] = {'a', 'b', 'c', 'd'}; memcpy(((struct ll*)(&m27))->s1, input, 4); clang_analyzer_eval(m27.s3[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m27.s3[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m27.s3[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m27.s3[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m27.s3[i] == 1); // expected-warning{{UNKNOWN}}\ expected-warning{{Potential leak of memory pointed to by 'm27.s4'}} return 0; } int f28(int i, int j, int k, int l) { struct mm m28[2]; m28[i].s4 = strdup("hello"); m28[j].s3[k] = 1; struct ll * l28 = (struct ll*)(&m28[1]); l28->s1[l] = 2; char input[] = {'a', 'b', 'c', 'd'}; // expected-warning{{Potential leak of memory pointed to by field 's4'}} memcpy(l28->s1, input, 4); clang_analyzer_eval(m28[0].s3[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m28[0].s3[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m28[0].s3[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m28[0].s3[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m28[1].s3[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m28[1].s3[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m28[1].s3[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m28[1].s3[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m28[i].s3[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m28[i].s3[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m28[i].s3[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m28[i].s3[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m28[j].s3[k] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(l28->s1[l] == 2); // expected-warning{{UNKNOWN}} return 0; } int f29(int i, int j, int k, int l, int m) { struct mm m29[2]; m29[i].s4 = strdup("hello"); m29[j].s3[k] = 1; struct ll * l29 = (struct ll*)(&m29[l]); l29->s1[m] = 2; char input[] = {'a', 'b', 'c', 'd'}; memcpy(l29->s1, input, 4); clang_analyzer_eval(m29[0].s3[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m29[0].s3[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m29[0].s3[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m29[0].s3[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m29[1].s3[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m29[1].s3[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m29[1].s3[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m29[1].s3[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m29[i].s3[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m29[i].s3[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m29[i].s3[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m29[i].s3[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(m29[j].s3[k] == 1); // expected-warning{{TRUE}} clang_analyzer_eval(l29->s1[m] == 2); // expected-warning{{UNKNOWN}} // FIXME: Should warn that m29[i].s4 leaks. But not on the previous line, // because l29 and m29 alias. return 0; } // Test unions' fields. union uu { char x; char s1[4]; }; int f30() { union uu u30 = { .s1 = {1, 2, 3, 4}}; char input[] = {1, 2, 3, 4}; memcpy(u30.s1, input, 4); clang_analyzer_eval(u30.s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(u30.s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(u30.s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(u30.s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(u30.x == 1); // expected-warning{{UNKNOWN}} return 0; } struct kk { union uu u; char * s2; }; int f31() { struct kk k31; k31.s2 = strdup("hello"); k31.u.x = 1; char input[] = {'a', 'b', 'c', 'd'}; memcpy(k31.u.s1, input, 4); clang_analyzer_eval(k31.u.s1[0] == 1); // expected-warning{{UNKNOWN}}\ expected-warning{{Potential leak of memory pointed to by 'k31.s2'}} clang_analyzer_eval(k31.u.s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(k31.u.s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(k31.u.s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(k31.u.x == 1); // expected-warning{{UNKNOWN}} // FIXME: memory leak warning for k31.s2 should be emitted here. return 0; } union vv { int x; char * s2; }; int f32() { union vv v32; v32.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(v32.s2, input, 4); clang_analyzer_eval(v32.s2[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(v32.s2[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(v32.s2[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(v32.s2[3] == 1); // expected-warning{{UNKNOWN}}\ expected-warning{{Potential leak of memory pointed to by 'v32.s2'}} return 0; } struct nn { int s1; int i; int j; int k; char * s2; }; // Test bad types to dest buffer. int f33() { struct nn n33 = {1, 2, 3, 4, 0}; n33.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(n33.s1, input, 4); // expected-warning{{incompatible integer to pointer conversion passing 'int' to parameter of type 'void *'}} clang_analyzer_eval(n33.i == 2); // expected-warning{{TRUE}} clang_analyzer_eval(n33.j == 3); // expected-warning{{TRUE}} clang_analyzer_eval(n33.k == 4); // expected-warning{{TRUE}} clang_analyzer_eval(((char*)(n33.s1))[0] == 1); // expected-warning{{UNKNOWN}}\ expected-warning{{cast to 'char *' from smaller integer type 'int'}} clang_analyzer_eval(((char*)(n33.s1))[1] == 1); // expected-warning{{UNKNOWN}}\ expected-warning{{cast to 'char *' from smaller integer type 'int'}} clang_analyzer_eval(((char*)(n33.s1))[2] == 1); // expected-warning{{UNKNOWN}}\ expected-warning{{cast to 'char *' from smaller integer type 'int'}} clang_analyzer_eval(((char*)(n33.s1))[3] == 1); // expected-warning{{UNKNOWN}}\ expected-warning{{cast to 'char *' from smaller integer type 'int'}} clang_analyzer_eval(n33.s2 == 0); //expected-warning{{UNKNOWN}} return 0; // expected-warning{{Potential leak of memory pointed to by 'n33.s2'}} } // Test destination buffer being an unknown value. struct ww { int s1[4]; char s2; }; int f34(struct ww * w34, int n) { w34->s2 = 3; char input[] = {'a', 'b', 'c', 'd'}; memcpy(w34->s1 + n, input , 4); clang_analyzer_eval(w34->s1[0] == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(w34->s1[1] == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(w34->s1[2] == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(w34->s1[3] == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(w34->s1[n] == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(w34->s2 == 3); // expected-warning{{TRUE}} return 0; } // Test dest buffer as an element region with a symbolic index and size parameter as a symbolic value. struct yy { char s1[4]; char * s2; }; int f35(int i, int n) { struct yy y35 = {{1, 2, 3, 4}, 0}; y35.s2 = strdup("hello"); char input[] = {'a', 'b', 'c', 'd'}; memcpy(&(y35.s1[i]), input, n); clang_analyzer_eval(y35.s1[0] == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(y35.s1[1] == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(y35.s1[2] == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(y35.s1[3] == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(y35.s1[i] == 0); // expected-warning{{UNKNOWN}} clang_analyzer_eval(y35.s2 == 0); // expected-warning{{UNKNOWN}} return 0; // expected-warning{{Potential leak of memory pointed to by 'y35.s2'}} } // Test regions with negative offsets. struct zz { char s1[4]; int s2; }; int f36(struct zz * z36) { char input[] = {'a', 'b', 'c', 'd'}; z36->s1[0] = 0; z36->s1[1] = 1; z36->s1[2] = 2; z36->s1[3] = 3; z36->s2 = 10; z36 = z36 - 1; // Decrement by 8 bytes (struct zz is 8 bytes). z36->s1[0] = 4; z36->s1[1] = 5; z36->s1[2] = 6; z36->s1[3] = 7; z36->s2 = 11; memcpy(z36->s1, input, 4); clang_analyzer_eval(z36->s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z36->s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z36->s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z36->s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z36->s2 == 11); // expected-warning{{TRUE}} z36 = z36 + 1; // Increment back. clang_analyzer_eval(z36->s1[0] == 0); // expected-warning{{TRUE}} clang_analyzer_eval(z36->s1[1] == 1); // expected-warning{{TRUE}} clang_analyzer_eval(z36->s1[2] == 2); // expected-warning{{TRUE}} clang_analyzer_eval(z36->s1[3] == 3); // expected-warning{{TRUE}} clang_analyzer_eval(z36->s2 == 10); // expected-warning{{TRUE}} return 0; } int f37(struct zz * z37) { char input[] = {'a', 'b', 'c', 'd'}; z37->s1[0] = 0; z37->s1[1] = 1; z37->s1[2] = 2; z37->s1[3] = 3; z37->s2 = 10; z37 = (struct zz *)((char*)(z37) - 4); // Decrement by 4 bytes (struct zz is 8 bytes). z37->s1[0] = 4; z37->s1[1] = 5; z37->s1[2] = 6; z37->s1[3] = 7; z37->s2 = 11; memcpy(z37->s1, input, 4); clang_analyzer_eval(z37->s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z37->s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z37->s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z37->s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z37->s2 == 11); // expected-warning{{TRUE}} z37 = (struct zz *)((char*)(z37) + 4); // Increment back. clang_analyzer_eval(z37->s1[0] == 11); // expected-warning{{TRUE}} clang_analyzer_eval(z37->s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z37->s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z37->s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z37->s2 == 10); // expected-warning{{TRUE}} return 0; } int f38(struct zz * z38) { char input[] = {'a', 'b', 'c', 'd'}; z38->s1[0] = 0; z38->s1[1] = 1; z38->s1[2] = 2; z38->s1[3] = 3; z38->s2 = 10; z38 = (struct zz *)((char*)(z38) - 2); // Decrement by 2 bytes (struct zz is 8 bytes). z38->s1[0] = 4; z38->s1[1] = 5; z38->s1[2] = 6; z38->s1[3] = 7; z38->s2 = 11; memcpy(z38->s1, input, 4); clang_analyzer_eval(z38->s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z38->s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z38->s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z38->s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z38->s2 == 11); // expected-warning{{TRUE}} z38 = (struct zz *)((char*)(z38) + 2); // Increment back. clang_analyzer_eval(z38->s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z38->s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z38->s1[2] == 11); // expected-warning{{TRUE}} clang_analyzer_eval(z38->s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(z38->s2 == 10); // expected-warning{{UNKNOWN}} return 0; } // Test negative offsets with a different structure layout. struct z0 { int s2; char s1[4]; }; int f39(struct z0 * d39) { char input[] = {'a', 'b', 'c', 'd'}; d39->s1[0] = 0; d39->s1[1] = 1; d39->s1[2] = 2; d39->s1[3] = 3; d39->s2 = 10; d39 = (struct z0 *)((char*)(d39) - 2); // Decrement by 2 bytes (struct z0 is 8 bytes). d39->s1[0] = 4; d39->s1[1] = 5; d39->s1[2] = 6; d39->s1[3] = 7; d39->s2 = 11; memcpy(d39->s1, input, 4); clang_analyzer_eval(d39->s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(d39->s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(d39->s1[2] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(d39->s1[3] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(d39->s2 == 11); // expected-warning{{TRUE}} d39 = (struct z0 *)((char*)(d39) + 2); // Increment back. clang_analyzer_eval(d39->s1[0] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(d39->s1[1] == 1); // expected-warning{{UNKNOWN}} clang_analyzer_eval(d39->s1[2] == 2); // expected-warning{{TRUE}} clang_analyzer_eval(d39->s1[3] == 3); // expected-warning{{TRUE}} // FIXME: d39->s2 should evaluate to at least UNKNOWN or FALSE, // 'collectSubRegionBindings(...)' in RegionStore.cpp will need to // handle a regions' upper boundary overflowing. clang_analyzer_eval(d39->s2 == 10); // expected-warning{{TRUE}} return 0; }
the_stack_data/179831427.c
#include <stdio.h> extern int demo7_entry(char *); int main(int argc, char *argv[]) { int i = demo7_entry("bar"); int k = demo7_entry("foo"); int j = demo7_entry("foobar"); printf("i == %d\nk == %d\nj == %d\n", i, k, j); return 0; }
the_stack_data/114919.c
#include <stdio.h> int main() { printf("This code was in file %s in function %s, at line %d\n",\ __FILE__, __FUNCTION__, __LINE__); return 0; }
the_stack_data/693116.c
#include <stdio.h> #include <time.h> struct { int a; int b; } s[5000]; void Funcion (int *R) { int ii, i, X1, X2; for(ii = 1; ii <= 40000; ii++){ X1 = 0; X2 = 0; for (i = 0; i < 5000; i++) { X1 += 2*s[i].a+ii; X2 += 2*s[i].b-ii; } if (X1<X2) R[ii] = X1; else R[ii] = X2; //R[ii] = (X1 < X2) ? X1 : X2; } } int main() { int R[40000]; struct timespec cgt1,cgt2; double ncgt; clock_gettime(CLOCK_REALTIME,&cgt1); Funcion(R); clock_gettime(CLOCK_REALTIME,&cgt2); ncgt=(double) (cgt2.tv_sec-cgt1.tv_sec)+( double) ((cgt2.tv_nsec-cgt1.tv_nsec)/(1.e+9)); printf("R[0] = %i, R[39999] = %i\n", R[0], R[39999]); printf("\nTiempo (seg.) = %11.9f\n", ncgt); return 0; }
the_stack_data/68888520.c
// Check pointers to functions // FI: this is not supported by PIPS infrastructure void fpointer01(char c, void * _stream, void (* my_fputc)(const char c,void * _stream), int * col, int indent, int * nbout) { if((c == '\n')||(c == '\r')) { /* on change de ligne */ *col = 0; } else { /* indentation ok ? */ while(*col < indent) { my_fputc(' ',_stream); (*nbout)++; (*col)++; } (*col)++; } /* dans tous les cas il faut afficher le caractere passe */ my_fputc(c,_stream); (*nbout)++; }
the_stack_data/198579967.c
/* ** SQLCipher ** crypto_impl.c developed by Stephen Lombardo (Zetetic LLC) ** sjlombardo at zetetic dot net ** http://zetetic.net ** ** Copyright (c) 2011, ZETETIC LLC ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** * Neither the name of the ZETETIC LLC 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 ZETETIC LLC ''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 ZETETIC LLC 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. ** */ /* BEGIN CRYPTO */ #ifdef SQLITE_HAS_CODEC #include <openssl/rand.h> #include <openssl/evp.h> #include <openssl/hmac.h> #include "sqliteInt.h" #include "btreeInt.h" #include "crypto.h" #ifndef OMIT_MEMLOCK #if defined(__unix__) || defined(__APPLE__) #include <sys/mman.h> #elif defined(_WIN32) # include <windows.h> #endif #endif /* the default implementation of SQLCipher uses a cipher_ctx to keep track of read / write state separately. The following struct and associated functions are defined here */ typedef struct { int derive_key; EVP_CIPHER *evp_cipher; EVP_CIPHER_CTX ectx; HMAC_CTX hctx; int kdf_iter; int fast_kdf_iter; int key_sz; int iv_sz; int block_sz; int pass_sz; int reserve_sz; int hmac_sz; int use_hmac; unsigned char *key; unsigned char *hmac_key; char *pass; } cipher_ctx; void sqlcipher_cipher_ctx_free(cipher_ctx **); int sqlcipher_cipher_ctx_cmp(cipher_ctx *, cipher_ctx *); int sqlcipher_cipher_ctx_copy(cipher_ctx *, cipher_ctx *); int sqlcipher_cipher_ctx_init(cipher_ctx **); int sqlcipher_cipher_ctx_set_pass(cipher_ctx *, const void *, int); int sqlcipher_cipher_ctx_key_derive(codec_ctx *, cipher_ctx *); /* prototype for pager HMAC function */ int sqlcipher_page_hmac(cipher_ctx *, Pgno, unsigned char *, int, unsigned char *); static int default_use_hmac = DEFAULT_USE_HMAC; struct codec_ctx { int kdf_salt_sz; int page_sz; unsigned char *kdf_salt; unsigned char *hmac_kdf_salt; unsigned char *buffer; Btree *pBt; cipher_ctx *read_ctx; cipher_ctx *write_ctx; }; void sqlcipher_activate() { sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); if(EVP_get_cipherbyname(CIPHER) == NULL) { OpenSSL_add_all_algorithms(); } sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); } /* fixed time zero memory check tests every position of a memory segement matches a single value (i.e. the memory is all zeros)*/ int sqlcipher_ismemset(const unsigned char *a0, unsigned char value, int len) { int i = 0, noMatch = 0; for(i = 0; i < len; i++) noMatch = (noMatch || (a0[i] != value)); return noMatch; } /* fixed time memory comparison routine */ int sqlcipher_memcmp(const unsigned char *a0, const unsigned char *a1, int len) { int i = 0, noMatch = 0; for(i = 0; i < len; i++) { noMatch = (noMatch || (a0[i] != a1[i])); } return noMatch; } /* generate a defined number of pseudorandom bytes */ int sqlcipher_random (void *buffer, int length) { return RAND_bytes((unsigned char *)buffer, length); } /** * Free and wipe memory. Uses SQLites internal sqlite3_free so that memory * can be countend and memory leak detection works in the tet suite. * If ptr is not null memory will be freed. * If sz is greater than zero, the memory will be overwritten with zero before it is freed * If sz is > 0, and not compiled with OMIT_MEMLOCK, system will attempt to unlock the * memory segment so it can be paged */ void sqlcipher_free(void *ptr, int sz) { if(ptr) { if(sz > 0) { memset(ptr, 0, sz); #ifndef OMIT_MEMLOCK #if defined(__unix__) || defined(__APPLE__) munlock(ptr, sz); #elif defined(_WIN32) VirtualUnlock(ptr, sz); #endif #endif } sqlite3_free(ptr); } } /** * allocate memory. Uses sqlite's internall malloc wrapper so memory can be * reference counted and leak detection works. Unless compiled with OMIT_MEMLOCK * attempts to lock the memory pages so sensitive information won't be swapped */ void* sqlcipher_malloc(int sz) { void *ptr = sqlite3Malloc(sz); #ifndef OMIT_MEMLOCK if(ptr) { #if defined(__unix__) || defined(__APPLE__) mlock(ptr, sz); #elif defined(_WIN32) VirtualLock(ptr, sz); #endif } #endif return ptr; } /** * Initialize a a new cipher_ctx struct. This function will allocate memory * for the cipher context and for the key * * returns SQLITE_OK if initialization was successful * returns SQLITE_NOMEM if an error occured allocating memory */ int sqlcipher_cipher_ctx_init(cipher_ctx **iCtx) { cipher_ctx *ctx; *iCtx = (cipher_ctx *) sqlcipher_malloc(sizeof(cipher_ctx)); ctx = *iCtx; if(ctx == NULL) return SQLITE_NOMEM; memset(ctx, 0, sizeof(cipher_ctx)); ctx->key = (unsigned char *) sqlcipher_malloc(EVP_MAX_KEY_LENGTH); ctx->hmac_key = (unsigned char *) sqlcipher_malloc(EVP_MAX_KEY_LENGTH); if(ctx->key == NULL) return SQLITE_NOMEM; if(ctx->hmac_key == NULL) return SQLITE_NOMEM; return SQLITE_OK; } /** * Free and wipe memory associated with a cipher_ctx */ void sqlcipher_cipher_ctx_free(cipher_ctx **iCtx) { cipher_ctx *ctx = *iCtx; CODEC_TRACE(("cipher_ctx_free: entered iCtx=%p\n", iCtx)); sqlcipher_free(ctx->key, ctx->key_sz); sqlcipher_free(ctx->hmac_key, ctx->key_sz); sqlcipher_free(ctx->pass, ctx->pass_sz); sqlcipher_free(ctx, sizeof(cipher_ctx)); } /** * Compare one cipher_ctx to another. * * returns 0 if all the parameters (except the derived key data) are the same * returns 1 otherwise */ int sqlcipher_cipher_ctx_cmp(cipher_ctx *c1, cipher_ctx *c2) { CODEC_TRACE(("sqlcipher_cipher_ctx_cmp: entered c1=%p c2=%p\n", c1, c2)); if( c1->evp_cipher == c2->evp_cipher && c1->iv_sz == c2->iv_sz && c1->kdf_iter == c2->kdf_iter && c1->fast_kdf_iter == c2->fast_kdf_iter && c1->key_sz == c2->key_sz && c1->pass_sz == c2->pass_sz && c1->use_hmac == c2->use_hmac && c1->hmac_sz == c2->hmac_sz && ( c1->pass == c2->pass || !sqlcipher_memcmp((const unsigned char*)c1->pass, (const unsigned char*)c2->pass, c1->pass_sz) ) ) return 0; return 1; } /** * Copy one cipher_ctx to another. For instance, assuming that read_ctx is a * fully initialized context, you could copy it to write_ctx and all yet data * and pass information across * * returns SQLITE_OK if initialization was successful * returns SQLITE_NOMEM if an error occured allocating memory */ int sqlcipher_cipher_ctx_copy(cipher_ctx *target, cipher_ctx *source) { void *key = target->key; void *hmac_key = target->hmac_key; CODEC_TRACE(("sqlcipher_cipher_ctx_copy: entered target=%p, source=%p\n", target, source)); sqlcipher_free(target->pass, target->pass_sz); memcpy(target, source, sizeof(cipher_ctx)); target->key = key; //restore pointer to previously allocated key data memcpy(target->key, source->key, EVP_MAX_KEY_LENGTH); target->hmac_key = hmac_key; //restore pointer to previously allocated hmac key data memcpy(target->hmac_key, source->hmac_key, EVP_MAX_KEY_LENGTH); target->pass = sqlcipher_malloc(source->pass_sz); if(target->pass == NULL) return SQLITE_NOMEM; memcpy(target->pass, source->pass, source->pass_sz); return SQLITE_OK; } /** * Set the raw password / key data for a cipher context * * returns SQLITE_OK if assignment was successfull * returns SQLITE_NOMEM if an error occured allocating memory * returns SQLITE_ERROR if the key couldn't be set because the pass was null or size was zero */ int sqlcipher_cipher_ctx_set_pass(cipher_ctx *ctx, const void *zKey, int nKey) { sqlcipher_free(ctx->pass, ctx->pass_sz); ctx->pass_sz = nKey; if(zKey && nKey) { ctx->pass = sqlcipher_malloc(nKey); if(ctx->pass == NULL) return SQLITE_NOMEM; memcpy(ctx->pass, zKey, nKey); return SQLITE_OK; } return SQLITE_ERROR; } int sqlcipher_codec_ctx_set_pass(codec_ctx *ctx, const void *zKey, int nKey, int for_ctx) { cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; int rc; if((rc = sqlcipher_cipher_ctx_set_pass(c_ctx, zKey, nKey)) != SQLITE_OK) return rc; c_ctx->derive_key = 1; if(for_ctx == 2) if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK) return rc; return SQLITE_OK; } int sqlcipher_codec_ctx_set_cipher(codec_ctx *ctx, const char *cipher_name, int for_ctx) { cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; int rc; c_ctx->evp_cipher = (EVP_CIPHER *) EVP_get_cipherbyname(cipher_name); c_ctx->key_sz = EVP_CIPHER_key_length(c_ctx->evp_cipher); c_ctx->iv_sz = EVP_CIPHER_iv_length(c_ctx->evp_cipher); c_ctx->block_sz = EVP_CIPHER_block_size(c_ctx->evp_cipher); c_ctx->hmac_sz = EVP_MD_size(EVP_sha1()); c_ctx->derive_key = 1; if(for_ctx == 2) if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK) return rc; return SQLITE_OK; } int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *ctx, int kdf_iter, int for_ctx) { cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; int rc; c_ctx->kdf_iter = kdf_iter; c_ctx->derive_key = 1; if(for_ctx == 2) if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK) return rc; return SQLITE_OK; } int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *ctx, int fast_kdf_iter, int for_ctx) { cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; int rc; c_ctx->fast_kdf_iter = fast_kdf_iter; c_ctx->derive_key = 1; if(for_ctx == 2) if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK) return rc; return SQLITE_OK; } /* set the global default flag for HMAC */ void sqlcipher_set_default_use_hmac(int use) { default_use_hmac = use; } /* set the codec flag for whether this individual database should be using hmac */ int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use) { int reserve = EVP_MAX_IV_LENGTH; /* base reserve size will be IV only */ if(use) reserve += ctx->read_ctx->hmac_sz; /* if reserve will include hmac, update that size */ /* calculate the amount of reserve needed in even increments of the cipher block size */ reserve = ((reserve % ctx->read_ctx->block_sz) == 0) ? reserve : ((reserve / ctx->read_ctx->block_sz) + 1) * ctx->read_ctx->block_sz; CODEC_TRACE(("sqlcipher_codec_ctx_set_use_hmac: use=%d block_sz=%d md_size=%d reserve=%d\n", use, ctx->read_ctx->block_sz, ctx->read_ctx->hmac_sz, reserve)); ctx->write_ctx->use_hmac = ctx->read_ctx->use_hmac = use; ctx->write_ctx->reserve_sz = ctx->read_ctx->reserve_sz = reserve; return SQLITE_OK; } void sqlcipher_codec_ctx_set_error(codec_ctx *ctx, int error) { CODEC_TRACE(("sqlcipher_codec_ctx_set_error: ctx=%p, error=%d\n", ctx, error)); sqlite3pager_sqlite3PagerSetError(ctx->pBt->pBt->pPager, error); ctx->pBt->pBt->db->errCode = error; } int sqlcipher_codec_ctx_get_pagesize(codec_ctx *ctx) { return ctx->page_sz; } int sqlcipher_codec_ctx_get_reservesize(codec_ctx *ctx) { return ctx->read_ctx->reserve_sz; } void* sqlcipher_codec_ctx_get_data(codec_ctx *ctx) { return ctx->buffer; } void* sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx) { return ctx->kdf_salt; } void sqlcipher_codec_get_pass(codec_ctx *ctx, void **zKey, int *nKey) { *zKey = ctx->read_ctx->pass; *nKey = ctx->read_ctx->pass_sz; } int sqlcipher_codec_ctx_set_pagesize(codec_ctx *ctx, int size) { /* attempt to free the existing page buffer */ sqlcipher_free(ctx->buffer,ctx->page_sz); ctx->page_sz = size; /* pre-allocate a page buffer of PageSize bytes. This will be used as a persistent buffer for encryption and decryption operations to avoid overhead of multiple memory allocations*/ ctx->buffer = sqlcipher_malloc(size); if(ctx->buffer == NULL) return SQLITE_NOMEM; return SQLITE_OK; } int sqlcipher_codec_ctx_init(codec_ctx **iCtx, Db *pDb, Pager *pPager, sqlite3_file *fd, const void *zKey, int nKey) { int rc; codec_ctx *ctx; *iCtx = sqlcipher_malloc(sizeof(codec_ctx)); ctx = *iCtx; if(ctx == NULL) return SQLITE_NOMEM; memset(ctx, 0, sizeof(codec_ctx)); /* initialize all pointers and values to 0 */ ctx->pBt = pDb->pBt; /* assign pointer to database btree structure */ /* allocate space for salt data. Then read the first 16 bytes directly off the database file. This is the salt for the key derivation function. If we get a short read allocate a new random salt value */ ctx->kdf_salt_sz = FILE_HEADER_SZ; ctx->kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz); if(ctx->kdf_salt == NULL) return SQLITE_NOMEM; /* allocate space for separate hmac salt data. We want the HMAC derivation salt to be different than the encryption key derivation salt */ ctx->hmac_kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz); if(ctx->hmac_kdf_salt == NULL) return SQLITE_NOMEM; /* Always overwrite page size and set to the default because the first page of the database in encrypted and thus sqlite can't effectively determine the pagesize. this causes an issue in cases where bytes 16 & 17 of the page header are a power of 2 as reported by John Lehman */ if((rc = sqlcipher_codec_ctx_set_pagesize(ctx, SQLITE_DEFAULT_PAGE_SIZE)) != SQLITE_OK) return rc; if((rc = sqlcipher_cipher_ctx_init(&ctx->read_ctx)) != SQLITE_OK) return rc; if((rc = sqlcipher_cipher_ctx_init(&ctx->write_ctx)) != SQLITE_OK) return rc; if(fd == NULL || sqlite3OsRead(fd, ctx->kdf_salt, FILE_HEADER_SZ, 0) != SQLITE_OK) { /* if unable to read the bytes, generate random salt */ if(sqlcipher_random(ctx->kdf_salt, FILE_HEADER_SZ) != 1) return SQLITE_ERROR; } if((rc = sqlcipher_codec_ctx_set_cipher(ctx, CIPHER, 0)) != SQLITE_OK) return rc; if((rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, PBKDF2_ITER, 0)) != SQLITE_OK) return rc; if((rc = sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, FAST_PBKDF2_ITER, 0)) != SQLITE_OK) return rc; if((rc = sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, 0)) != SQLITE_OK) return rc; /* Use HMAC signatures by default. Note that codec_set_use_hmac will implicity call codec_set_page_size to set the default */ if((rc = sqlcipher_codec_ctx_set_use_hmac(ctx, default_use_hmac)) != SQLITE_OK) return rc; if((rc = sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx)) != SQLITE_OK) return rc; return SQLITE_OK; } /** * Free and wipe memory associated with a cipher_ctx, including the allocated * read_ctx and write_ctx. */ void sqlcipher_codec_ctx_free(codec_ctx **iCtx) { codec_ctx *ctx = *iCtx; CODEC_TRACE(("codec_ctx_free: entered iCtx=%p\n", iCtx)); sqlcipher_free(ctx->kdf_salt, ctx->kdf_salt_sz); sqlcipher_free(ctx->hmac_kdf_salt, ctx->kdf_salt_sz); sqlcipher_free(ctx->buffer, 0); sqlcipher_cipher_ctx_free(&ctx->read_ctx); sqlcipher_cipher_ctx_free(&ctx->write_ctx); sqlcipher_free(ctx, sizeof(codec_ctx)); } int sqlcipher_page_hmac(cipher_ctx *ctx, Pgno pgno, unsigned char *in, int in_sz, unsigned char *out) { HMAC_CTX_init(&ctx->hctx); HMAC_Init_ex(&ctx->hctx, ctx->hmac_key, ctx->key_sz, EVP_sha1(), NULL); /* include the encrypted page data, initialization vector, and page number in HMAC. This will prevent both tampering with the ciphertext, manipulation of the IV, or resequencing otherwise valid pages out of order in a database */ HMAC_Update(&ctx->hctx, in, in_sz); HMAC_Update(&ctx->hctx, (const unsigned char*) &pgno, sizeof(Pgno)); HMAC_Final(&ctx->hctx, out, NULL); HMAC_CTX_cleanup(&ctx->hctx); return SQLITE_OK; } /* * ctx - codec context * pgno - page number in database * size - size in bytes of input and output buffers * mode - 1 to encrypt, 0 to decrypt * in - pointer to input bytes * out - pouter to output bytes */ int sqlcipher_page_cipher(codec_ctx *ctx, int for_ctx, Pgno pgno, int mode, int page_sz, unsigned char *in, unsigned char *out) { cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; unsigned char *iv_in, *iv_out, *hmac_in, *hmac_out, *out_start; int tmp_csz, csz, size; /* calculate some required positions into various buffers */ size = page_sz - c_ctx->reserve_sz; /* adjust size to useable size and memset reserve at end of page */ iv_out = out + size; iv_in = in + size; /* hmac will be written immediately after the initialization vector. the remainder of the page reserve will contain random bytes. note, these pointers are only valid when use_hmac is true */ hmac_in = in + size + c_ctx->iv_sz; hmac_out = out + size + c_ctx->iv_sz; out_start = out; /* note the original position of the output buffer pointer, as out will be rewritten during encryption */ CODEC_TRACE(("codec_cipher:entered pgno=%d, mode=%d, size=%d\n", pgno, mode, size)); CODEC_HEXDUMP("codec_cipher: input page data", in, page_sz); /* the key size should never be zero. If it is, error out. */ if(c_ctx->key_sz == 0) { CODEC_TRACE(("codec_cipher: error possible context corruption, key_sz is zero for pgno=%d\n", pgno)); memset(out, 0, page_sz); return SQLITE_ERROR; } if(mode == CIPHER_ENCRYPT) { /* start at front of the reserve block, write random data to the end */ if(sqlcipher_random(iv_out, c_ctx->reserve_sz) != 1) return SQLITE_ERROR; } else { /* CIPHER_DECRYPT */ memcpy(iv_out, iv_in, c_ctx->iv_sz); /* copy the iv from the input to output buffer */ } if(c_ctx->use_hmac && (mode == CIPHER_DECRYPT)) { if(sqlcipher_page_hmac(c_ctx, pgno, in, size + c_ctx->iv_sz, hmac_out) != SQLITE_OK) { memset(out, 0, page_sz); CODEC_TRACE(("codec_cipher: hmac operations failed for pgno=%d\n", pgno)); return SQLITE_ERROR; } CODEC_TRACE(("codec_cipher: comparing hmac on in=%p out=%p hmac_sz=%d\n", hmac_in, hmac_out, c_ctx->hmac_sz)); if(sqlcipher_memcmp(hmac_in, hmac_out, c_ctx->hmac_sz) != 0) { /* the hmac check failed */ if(sqlcipher_ismemset(in, 0, page_sz) == 0) { /* first check if the entire contents of the page is zeros. If so, this page resulted from a short read (i.e. sqlite attempted to pull a page after the end of the file. these short read failures must be ignored for autovaccum mode to work so wipe the output buffer and return SQLITE_OK to skip the decryption step. */ CODEC_TRACE(("codec_cipher: zeroed page (short read) for pgno %d, encryption but returning SQLITE_OK\n", pgno)); memset(out, 0, page_sz); return SQLITE_OK; } else { /* if the page memory is not all zeros, it means the there was data and a hmac on the page. since the check failed, the page was either tampered with or corrupted. wipe the output buffer, and return SQLITE_ERROR to the caller */ CODEC_TRACE(("codec_cipher: hmac check failed for pgno=%d returning SQLITE_ERROR\n", pgno)); memset(out, 0, page_sz); return SQLITE_ERROR; } } } EVP_CipherInit(&c_ctx->ectx, c_ctx->evp_cipher, NULL, NULL, mode); EVP_CIPHER_CTX_set_padding(&c_ctx->ectx, 0); EVP_CipherInit(&c_ctx->ectx, NULL, c_ctx->key, iv_out, mode); EVP_CipherUpdate(&c_ctx->ectx, out, &tmp_csz, in, size); csz = tmp_csz; out += tmp_csz; EVP_CipherFinal(&c_ctx->ectx, out, &tmp_csz); csz += tmp_csz; EVP_CIPHER_CTX_cleanup(&c_ctx->ectx); assert(size == csz); if(c_ctx->use_hmac && (mode == CIPHER_ENCRYPT)) { sqlcipher_page_hmac(c_ctx, pgno, out_start, size + c_ctx->iv_sz, hmac_out); } CODEC_HEXDUMP("codec_cipher: output page data", out_start, page_sz); return SQLITE_OK; } /** * Derive an encryption key for a cipher contex key based on the raw password. * * If the raw key data is formated as x'hex' and there are exactly enough hex chars to fill * the key space (i.e 64 hex chars for a 256 bit key) then the key data will be used directly. * * Otherwise, a key data will be derived using PBKDF2 * * returns SQLITE_OK if initialization was successful * returns SQLITE_ERROR if the key could't be derived (for instance if pass is NULL or pass_sz is 0) */ int sqlcipher_cipher_ctx_key_derive(codec_ctx *ctx, cipher_ctx *c_ctx) { CODEC_TRACE(("codec_key_derive: entered c_ctx->pass=%s, c_ctx->pass_sz=%d \ ctx->kdf_salt=%p ctx->kdf_salt_sz=%d c_ctx->kdf_iter=%d \ ctx->hmac_kdf_salt=%p, c_ctx->fast_kdf_iter=%d c_ctx->key_sz=%d\n", c_ctx->pass, c_ctx->pass_sz, ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->kdf_iter, ctx->hmac_kdf_salt, c_ctx->fast_kdf_iter, c_ctx->key_sz)); if(c_ctx->pass && c_ctx->pass_sz) { // if pass is not null if (c_ctx->pass_sz == ((c_ctx->key_sz*2)+3) && sqlite3StrNICmp(c_ctx->pass ,"x'", 2) == 0) { int n = c_ctx->pass_sz - 3; /* adjust for leading x' and tailing ' */ const char *z = c_ctx->pass + 2; /* adjust lead offset of x' */ CODEC_TRACE(("codec_key_derive: using raw key from hex\n")); cipher_hex2bin(z, n, c_ctx->key); } else { CODEC_TRACE(("codec_key_derive: deriving key using full PBKDF2 with %d iterations\n", c_ctx->kdf_iter)); PKCS5_PBKDF2_HMAC_SHA1( c_ctx->pass, c_ctx->pass_sz, ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->kdf_iter, c_ctx->key_sz, c_ctx->key); } /* if this context is setup to use hmac checks, generate a seperate and different key for HMAC. In this case, we use the output of the previous KDF as the input to this KDF run. This ensures a distinct but predictable HMAC key. */ if(c_ctx->use_hmac) { int i; /* start by copying the kdf key into the hmac salt slot then XOR it with the fixed hmac salt defined at compile time this ensures that the salt passed in to derive the hmac key, while easy to derive and publically known, is not the same as the salt used to generate the encryption key */ memcpy(ctx->hmac_kdf_salt, ctx->kdf_salt, ctx->kdf_salt_sz); for(i = 0; i < ctx->kdf_salt_sz; i++) { ctx->hmac_kdf_salt[i] ^= HMAC_SALT_MASK; } CODEC_TRACE(("codec_key_derive: deriving hmac key from encryption key using PBKDF2 with %d iterations\n", c_ctx->fast_kdf_iter)); PKCS5_PBKDF2_HMAC_SHA1( (const char*)c_ctx->key, c_ctx->key_sz, ctx->hmac_kdf_salt, ctx->kdf_salt_sz, c_ctx->fast_kdf_iter, c_ctx->key_sz, c_ctx->hmac_key); } c_ctx->derive_key = 0; return SQLITE_OK; }; return SQLITE_ERROR; } int sqlcipher_codec_key_derive(codec_ctx *ctx) { /* derive key on first use if necessary */ if(ctx->read_ctx->derive_key) { if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->read_ctx) != SQLITE_OK) return SQLITE_ERROR; } if(ctx->write_ctx->derive_key) { if(sqlcipher_cipher_ctx_cmp(ctx->write_ctx, ctx->read_ctx) == 0) { // the relevant parameters are the same, just copy read key if(sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx) != SQLITE_OK) return SQLITE_ERROR; } else { if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->write_ctx) != SQLITE_OK) return SQLITE_ERROR; } } return SQLITE_OK; } int sqlcipher_codec_key_copy(codec_ctx *ctx, int source) { if(source == CIPHER_READ_CTX) { return sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx); } else { return sqlcipher_cipher_ctx_copy(ctx->read_ctx, ctx->write_ctx); } } #ifndef OMIT_EXPORT /* * Implementation of an "export" function that allows a caller * to duplicate the main database to an attached database. This is intended * as a conveneince for users who need to: * * 1. migrate from an non-encrypted database to an encrypted database * 2. move from an encrypted database to a non-encrypted database * 3. convert beween the various flavors of encrypted databases. * * This implementation is based heavily on the procedure and code used * in vacuum.c, but is exposed as a function that allows export to any * named attached database. */ /* ** Finalize a prepared statement. If there was an error, store the ** text of the error message in *pzErrMsg. Return the result code. ** ** Based on vacuumFinalize from vacuum.c */ static int sqlcipher_finalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){ int rc; rc = sqlite3VdbeFinalize((Vdbe*)pStmt); if( rc ){ sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db)); } return rc; } /* ** Execute zSql on database db. Return an error code. ** ** Based on execSql from vacuum.c */ static int sqlcipher_execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ sqlite3_stmt *pStmt; VVA_ONLY( int rc; ) if( !zSql ){ return SQLITE_NOMEM; } if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){ sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db)); return sqlite3_errcode(db); } VVA_ONLY( rc = ) sqlite3_step(pStmt); assert( rc!=SQLITE_ROW ); return sqlcipher_finalize(db, pStmt, pzErrMsg); } /* ** Execute zSql on database db. The statement returns exactly ** one column. Execute this as SQL on the same database. ** ** Based on execExecSql from vacuum.c */ static int sqlcipher_execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ sqlite3_stmt *pStmt; int rc; rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; while( SQLITE_ROW==sqlite3_step(pStmt) ){ rc = sqlcipher_execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0)); if( rc!=SQLITE_OK ){ sqlcipher_finalize(db, pStmt, pzErrMsg); return rc; } } return sqlcipher_finalize(db, pStmt, pzErrMsg); } /* * copy database and schema from the main database to an attached database * * Based on sqlite3RunVacuum from vacuum.c */ void sqlcipher_exportFunc(sqlite3_context *context, int argc, sqlite3_value **argv) { sqlite3 *db = sqlite3_context_db_handle(context); const char* attachedDb = (const char*) sqlite3_value_text(argv[0]); int saved_flags; /* Saved value of the db->flags */ int saved_nChange; /* Saved value of db->nChange */ int saved_nTotalChange; /* Saved value of db->nTotalChange */ void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */ int rc = SQLITE_OK; /* Return code from service routines */ char *zSql = NULL; /* SQL statements */ char *pzErrMsg = NULL; saved_flags = db->flags; saved_nChange = db->nChange; saved_nTotalChange = db->nTotalChange; saved_xTrace = db->xTrace; db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin; db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder); db->xTrace = 0; /* Query the schema of the main database. Create a mirror schema ** in the temporary database. */ zSql = sqlite3_mprintf( "SELECT 'CREATE TABLE %s.' || substr(sql,14) " " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'" " AND rootpage>0" , attachedDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); zSql = sqlite3_mprintf( "SELECT 'CREATE INDEX %s.' || substr(sql,14)" " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %%' " , attachedDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); zSql = sqlite3_mprintf( "SELECT 'CREATE UNIQUE INDEX %s.' || substr(sql,21) " " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %%'" , attachedDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); /* Loop through the tables in the main database. For each, do ** an "INSERT INTO rekey_db.xxx SELECT * FROM main.xxx;" to copy ** the contents to the temporary database. */ zSql = sqlite3_mprintf( "SELECT 'INSERT INTO %s.' || quote(name) " "|| ' SELECT * FROM main.' || quote(name) || ';'" "FROM main.sqlite_master " "WHERE type = 'table' AND name!='sqlite_sequence' " " AND rootpage>0" , attachedDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); /* Copy over the sequence table */ zSql = sqlite3_mprintf( "SELECT 'DELETE FROM %s.' || quote(name) || ';' " "FROM %s.sqlite_master WHERE name='sqlite_sequence' " , attachedDb, attachedDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); zSql = sqlite3_mprintf( "SELECT 'INSERT INTO %s.' || quote(name) " "|| ' SELECT * FROM main.' || quote(name) || ';' " "FROM %s.sqlite_master WHERE name=='sqlite_sequence';" , attachedDb, attachedDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); /* Copy the triggers, views, and virtual tables from the main database ** over to the temporary database. None of these objects has any ** associated storage, so all we have to do is copy their entries ** from the SQLITE_MASTER table. */ zSql = sqlite3_mprintf( "INSERT INTO %s.sqlite_master " " SELECT type, name, tbl_name, rootpage, sql" " FROM main.sqlite_master" " WHERE type='view' OR type='trigger'" " OR (type='table' AND rootpage=0)" , attachedDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; sqlite3_free(zSql); zSql = NULL; end_of_export: db->flags = saved_flags; db->nChange = saved_nChange; db->nTotalChange = saved_nTotalChange; db->xTrace = saved_xTrace; sqlite3_free(zSql); if(rc) { if(pzErrMsg != NULL) { sqlite3_result_error(context, pzErrMsg, -1); sqlite3DbFree(db, pzErrMsg); } else { sqlite3_result_error(context, sqlite3ErrStr(rc), -1); } } } #endif #endif
the_stack_data/95024.c
#include <stdio.h> int ac(int a) { a++; if (a < 10) { return ac(a); } return a; } int main() { int a = ac(1); printf("%d\n",a); return 0; }
the_stack_data/161080466.c
#include <sys/types.h> #include <fcntl.h> #include <sys/wait.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <time.h> #include <sys/mman.h> #include <assert.h> #include <string.h> #define NCHILD 16 #define PENNY_MSG_SZ 32 #define RAND_SPAN (RAND_MAX/4) struct child_data { int child_off; int pending; /* does the child have pending data? */ int pipe[2]; /* pipe to send the bytecoin return message to parent. [0] is readable, [1] writable */ int nbpipe[2]; /* pipe to send the bytecoin return message to parent with the read-side being non-blocking */ char *shmem; /* shared memory to send the bytecoin return message to parent */ }; struct child_data children[NCHILD]; char *shmem; void create_pipes(struct child_data *d) { /* d->pipe[0] is the "read" end of the pipe, and d->pipe[1] is for "writes" */ if (pipe(d->pipe)) { perror("pipe creation error"); exit(EXIT_FAILURE); } if (pipe(d->nbpipe)) { perror("nbpipe creation error"); exit(EXIT_FAILURE); } if (fcntl(d->nbpipe[0], F_SETFL, O_NONBLOCK)) { perror("nbpipe error setting to non-blocking"); exit(EXIT_FAILURE); } } void create_shmem(struct child_data *d) { assert(shmem != NULL); d->shmem = shmem + (d->child_off * PENNY_MSG_SZ); } void ipc_init(void) { int i; shmem = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); for (i = 0; i < NCHILD; i++) { struct child_data *c = &children[i]; c->child_off = i; c->pending = 1; create_shmem(c); create_pipes(c); } } /* * I hear bitcoin is amazing. But who wouldn't want a pennycoin? Lets * do some pennycoin mining! * * TODO 1: update this to send over the non-blocking channel (the * write is still blocking!!!!). * * TODO 2: send the message back in shared memory instead of over a * pipe! */ void pennycoin_mining(struct child_data *us, char byte) { char return_message[PENNY_MSG_SZ]; unsigned int i; (void)us; /* emulate trying to find a specific byte! */ while (rand() % RAND_SPAN != byte) ; for (i = 0; i < PENNY_MSG_SZ; i++) { return_message[i] = byte; } /* Add code here to send the return message back to the parent! */ write(us->pipe[1], return_message, PENNY_MSG_SZ); return; } int main(int argc, char *argv[]) { int i, msgs_received = 0; time_t t; (void)argc; (void)argv; srand((unsigned int)time(&t)); ipc_init(); for (i = 0; i < NCHILD; i++) { switch (fork()) { case -1: { perror("fork failed"); exit(EXIT_FAILURE); } case 0: { /* child */ pennycoin_mining(&children[i], i+1); exit(EXIT_SUCCESS); }} } /* * Parent logic to understand. Remember your TODOs! * * TODO 1: update this to receive over the non-blocking * channel, the `read` should be non-blocking so that we can * check for the *next* available pennycoin. * * TODO 2: receive the message from a child in shared memory * instead of over a pipe! */ while (msgs_received < NCHILD) { for (i = 0; i < NCHILD; i++) { char msg[PENNY_MSG_SZ]; int ret; /* Skip over the children for which we've already received a message */ if (!children[i].pending) continue; /* read from the child. */ ret = read(children[i].pipe[0], msg, PENNY_MSG_SZ); if (ret < 0) { if (errno == EAGAIN) { /* non-blocking logic here! */ continue; /* Just keep on going through all the children */ } else { perror("Parent reading from child"); exit(EXIT_FAILURE); } } /* We got a message! */ assert(ret == PENNY_MSG_SZ); assert(msg[0] == i+1); children[i].pending = 0; msgs_received++; printf("Mining %d done, cha-ching!\n", i); } } for (i = 0; i < NCHILD; i++) { int status; wait(&status); } munmap(shmem, 4096); return 0; }
the_stack_data/220455605.c
/* file: count_lines.c * description: Counts newline characters in buffer * author: Daniel Garrigan Lummei Analytics LLC * updated: October 2016 * email: [email protected] * copyright: MIT license */ #include <string.h> size_t count_lines(const char *buff) { char *p = NULL; size_t nl = 0; p = strchr(buff, '\n'); while (p) { p = strchr(p+1, '\n'); nl++; } return nl; }
the_stack_data/43886685.c
/* { dg-do compile } */ /* { dg-require-effective-target arm_arch_v8a_ok */ /* { dg-require-effective-target arm_v8_vfp_ok } */ /* { dg-options "-O2 -mcpu=cortex-a57" } */ /* { dg-add-options arm_v8_vfp } */ double foo (double x, double y) { volatile int i = 0; return i == 0 ? x : y; } /* { dg-final { scan-assembler-times "vseleq.f64\td\[0-9\]+" 1 } } */
the_stack_data/673450.c
#include <stdio.h> int main(){ int i; double x[100]; for(i=0;i<100;i++){ scanf("%lf", &x[i]); if(x[i] <= 10.0) printf("A[%d] = %.1lf\n", i, x[i]); } return 0; }
the_stack_data/51699604.c
/* * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. */ /* * Copyright (c) 2018, Joyent, Inc. */ /* * getentropy(3C) is an OpenBSD compatible wrapper around getrandom(2). */ #include <errno.h> #include <sys/random.h> int getentropy(void *buf, size_t buflen) { ssize_t ret; if (buflen > 256) { errno = EIO; return (-1); } ret = getrandom(buf, buflen, 0); if (ret == -1 || ret != buflen) { if (errno != EFAULT) errno = EIO; return (-1); } return (0); }
the_stack_data/295928.c
/* * shmatch.c -- shell interface to posix regular expression matching. */ /* Copyright (C) 2003-2015 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash 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. Bash 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 Bash. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #if defined (HAVE_POSIX_REGEXP) #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #include "bashansi.h" #include <stdio.h> #include <regex.h> #include "shell.h" #include "variables.h" #include "externs.h" extern int glob_ignore_case, match_ignore_case; int sh_regmatch (string, pattern, flags) const char *string; const char *pattern; int flags; { regex_t regex = { 0 }; regmatch_t *matches; int rflags; #if defined (ARRAY_VARS) SHELL_VAR *rematch; ARRAY *amatch; int subexp_ind; char *subexp_str; int subexp_len; #endif int result; #if defined (ARRAY_VARS) rematch = (SHELL_VAR *)NULL; #endif rflags = REG_EXTENDED; if (match_ignore_case) rflags |= REG_ICASE; #if !defined (ARRAY_VARS) rflags |= REG_NOSUB; #endif if (regcomp (&regex, pattern, rflags)) return 2; /* flag for printing a warning here. */ #if defined (ARRAY_VARS) matches = (regmatch_t *)malloc (sizeof (regmatch_t) * (regex.re_nsub + 1)); #else matches = NULL; #endif /* man regexec: NULL PMATCH ignored if NMATCH == 0 */ if (regexec (&regex, string, matches ? regex.re_nsub + 1 : 0, matches, 0)) result = EXECUTION_FAILURE; else result = EXECUTION_SUCCESS; /* match */ #if defined (ARRAY_VARS) subexp_len = strlen (string) + 10; subexp_str = malloc (subexp_len + 1); /* Store the parenthesized subexpressions in the array BASH_REMATCH. Element 0 is the portion that matched the entire regexp. Element 1 is the part that matched the first subexpression, and so on. */ unbind_variable_noref ("BASH_REMATCH"); rematch = make_new_array_variable ("BASH_REMATCH"); amatch = array_cell (rematch); if (matches && (flags & SHMAT_SUBEXP) && result == EXECUTION_SUCCESS && subexp_str) { for (subexp_ind = 0; subexp_ind <= regex.re_nsub; subexp_ind++) { memset (subexp_str, 0, subexp_len); strncpy (subexp_str, string + matches[subexp_ind].rm_so, matches[subexp_ind].rm_eo - matches[subexp_ind].rm_so); array_insert (amatch, subexp_ind, subexp_str); } } #if 0 VSETATTR (rematch, att_readonly); #endif free (subexp_str); free (matches); #endif /* ARRAY_VARS */ regfree (&regex); return result; } #endif /* HAVE_POSIX_REGEXP */
the_stack_data/68887536.c
#define MAX 5 int main(void) { char string_B[MAX]; int nc_B; while(string_B[nc_B]!='\0') nc_B++; }
the_stack_data/72012261.c
/* $Id$ */ #include <pthread.h> #include <stdlib.h> int main(int argc, char *argv[]) { void *p; (void)argc; (void)argv; p = pthread_barrier_init; exit(0); }
the_stack_data/35870.c
/* ** my_strncmp.c for my_strncmp in /home/arbona/CPool/CPool_Day06 ** ** Made by Thomas Arbona ** Login <[email protected]> ** ** Started on Mon Oct 10 10:23:27 2016 Thomas Arbona ** Last update Tue Oct 11 14:39:43 2016 Thomas Arbona */ int my_strlen(char *str); int my_strncmp(char *s1, char *s2, int n) { int iterator; iterator = 0; while ((n < 0 || iterator < n) && s1[iterator] != '\0' && s2[iterator] != '\0') { if (s1[iterator] != s2[iterator]) return (s1[iterator] - s2[iterator]); iterator += 1; } if (iterator != n) return (s1[iterator] - s2[iterator]); return (0); }
the_stack_data/5335.c
/* Spurious uninitialized variable warnings, from gdb */ /* { dg-do compile } */ /* { dg-options "-O2 -Wuninitialized" } */ struct os { struct o *o; }; struct o { struct o *next; struct os *se; }; void f(struct o *o){ struct os *s; if(o) s = o->se; while(o && s == o->se){ s++; // here `o' is non-zero and thus s is initialized s == o->se // `?' is essential, `if' does not trigger the warning ? (o = o->next, o ? s = o->se : 0) : 0; } }