file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/947636.c | extern int __VERIFIER_nondet_int();
extern void __VERIFIER_assume(int);
int nondet_signed_int() {
int r = __VERIFIER_nondet_int();
__VERIFIER_assume ((-0x7fffffff - 1) <= r && r <= 0x7fffffff);
return r;
}
signed int main()
{
signed int K;
signed int x;
K = nondet_signed_int();
x = nondet_signed_int();
while(!(x == K))
if(!(K >= x))
{
while(!(!(x - 1 < (-0x7fffffff - 1) || 0x7fffffff < x - 1)));
x = x - 1;
}
else
{
while(!(!(x + 1 < (-0x7fffffff - 1) || 0x7fffffff < x + 1)));
x = x + 1;
}
return 0;
}
|
the_stack_data/74468.c | #include <math.h>
#include <stdint.h>
double fabs(double x)
{
union {double f; uint64_t i;} u = {x};
u.i &= -1ULL/2;
return u.f;
}
|
the_stack_data/115813.c | #include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
int cstatus, pstatus;
pid_t pid;
for (cstatus = 0; cstatus < 2; ++cstatus) {
switch (pid = fork()) {
case -1:
perror("fork");
return 1;
case 0:
_exit(cstatus);
default:
if (wait(&pstatus) != pid) {
perror("wait");
return 1;
}
printf("#define STATUS%d %d\n", cstatus, pstatus);
}
}
return 0;
}
|
the_stack_data/59512885.c | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
unsigned long parse_int (char *str);
int main (int argc, char *argv[]) {
unsigned long addr, length;
int devmem;
void *mapping;
long page_size;
off_t map_base, extra_bytes;
char *buf;
ssize_t ret;
if (argc != 3) {
fprintf(stderr, "Usage: %s ADDR LENGTH\n", argv[0]);
exit(EXIT_FAILURE);
}
addr = parse_int(argv[1]);
length = parse_int(argv[2]);
devmem = open("/dev/mem", O_RDONLY);
if (devmem == -1) {
perror("Could not open /dev/mem");
goto open_fail;
}
page_size = sysconf(_SC_PAGE_SIZE);
map_base = addr & ~(page_size - 1);
extra_bytes = addr - map_base;
mapping = mmap(NULL, length + extra_bytes, PROT_READ, MAP_SHARED,
devmem, map_base);
if (mapping == MAP_FAILED) {
perror("Could not map memory");
goto map_fail;
}
buf = malloc(length);
if (buf == NULL) {
fprintf(stderr, "Failed to allocate memory\n");
goto alloc_fail;
}
/*
* Using a separate buffer for write stops the kernel from
* complaining quite as much as if we passed the mmap()ed
* buffer directly to write().
*/
memcpy(buf, (char *)mapping + extra_bytes, length);
ret = write(STDOUT_FILENO, buf, length);
if (ret == -1) {
perror("Could not write data");
} else if (ret != (ssize_t)length) {
fprintf(stderr, "Only wrote %ld bytes\n", ret);
}
free(buf);
alloc_fail:
munmap(mapping, length + extra_bytes);
map_fail:
close(devmem);
open_fail:
return EXIT_SUCCESS;
}
unsigned long parse_int (char *str) {
long long result;
char *endptr;
result = strtoll(str, &endptr, 0);
if (str[0] == '\0' || *endptr != '\0') {
fprintf(stderr, "\"%s\" is not a valid number\n", str);
exit(EXIT_FAILURE);
}
return (unsigned long)result;
}
|
the_stack_data/24820.c | # include <stdio.h>
# include <stdlib.h>
struct listaCirc{
int info;
struct listaCirc *prox;
};
typedef struct listaCirc ListaC;
ListaC *inserir(ListaC *l, int n);
main(){
ListaC *l, *p;
l = NULL;
l = inserir(l, 10);
l = inserir(l, 20);
l = inserir(l, 30);
l = inserir(l, 40);
p = l -> prox;
puts("Lista Encadeada Circulasr");
do{
printf("%d \n", p -> info);
p = p -> prox;
}while(p != l -> prox);
system("pause");
}
ListaC *inserir(ListaC *l, int n){
ListaC *novo;
novo = (ListaC *)malloc(sizeof(ListaC));
novo -> info = n;
if(l == NULL){
novo -> prox = novo;
} else {
novo -> prox = l -> prox;
l -> prox = novo;
}
return novo;
}
|
the_stack_data/61076024.c | /*
* MIT License
*
* Copyright (c) 2022 Shunyong Yang ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#define CRC_WITH_TABLE
#define CRC32_TABLE_SIZE (256)
#define REVERSE_POLY(poly_in, poly_out) __asm__("rbit %w[c], %w[v]":[c]"+r"(poly_out):[v]"r"(poly_in))
static uint32_t crc32_table_reverse[CRC32_TABLE_SIZE];
void build_crc32_reverse_table(uint32_t *table, uint32_t poly_reverse)
{
uint32_t i, j;
for (i = 0; i < CRC32_TABLE_SIZE; i++) {
uint32_t data = i;
for (j = 0; j < 8; j++) {
if (data & 0x01)
data = (data >> 1) ^ poly_reverse;
else
data = data >> 1;
}
table[i] = data;
}
}
uint32_t crc32_poly_reverse_without_table(uint8_t *src, uint32_t size, uint32_t poly_reverse)
{
uint32_t crc = 0xFFFFFFFF;
for (int i = 0; i < size; i++) {
crc = crc ^ *src++;
for (int j = 0; j < 8; j++) {
if (crc & 0x01)
crc = (crc >> 1) ^ poly_reverse;
else
crc = crc >> 1;
}
}
return ~crc;
}
uint32_t crc32_poly_reverse_with_table(uint8_t *src, uint32_t size, uint32_t * table)
{
uint32_t crc = 0xFFFFFFFF;
for (int i = 0; i < size; i++) {
crc = crc32_table_reverse[(crc ^ *src++) & 0xff] ^ (crc >> 8);
}
return ~crc;
}
uint32_t crc32_sw(uint8_t *src, uint32_t size, uint32_t polynomial)
{
uint8_t *pdata = (uint8_t *)src;
uint32_t poly_reverse;
REVERSE_POLY(polynomial, poly_reverse);
#ifdef CRC_WITH_TABLE
build_crc32_reverse_table(crc32_table_reverse, poly_reverse);
return crc32_poly_reverse_with_table(src, size, crc32_table_reverse);
#else
return crc32_poly_reverse_without_table(src, size, poly_reverse);
#endif
}
|
the_stack_data/165768781.c | /*
* @Author: JIANG Yilun
* @Date: 2022-03-24 15:32:52
* @LastEditTime: 2022-03-24 15:33:25
* @LastEditors: JIANG Yilun
* @Description:
* @FilePath: /UGA_INF/INF203/Language C/semaine 7/TP7/aff_arg.c
*/
#include<stdio.h>
int main (int argc, char *argv[]) {
int i ;
printf("\nargc : %d\n\n",argc);
for (i=0 ; i<argc ; i++)
printf("l'argument numero %d est %s\n",i, argv[i]) ;
printf("\n");
return 0;
}
|
the_stack_data/165769409.c | // RUN: %clang_cc1 -verify %s
void f();
void f() __asm__("fish");
void g();
void f() {
g();
}
void g() __asm__("gold"); // expected-error{{cannot apply asm label to function after its first use}}
void h() __asm__("hose"); // expected-note{{previous declaration is here}}
void h() __asm__("hair"); // expected-error{{conflicting asm label}}
int x;
int x __asm__("xenon");
int y;
int test() { return y; }
int y __asm__("yacht"); // expected-error{{cannot apply asm label to variable after its first use}}
int z __asm__("zebra"); // expected-note{{previous declaration is here}}
int z __asm__("zooms"); // expected-error{{conflicting asm label}}
// No diagnostics on the following.
void __real_readlink() __asm("readlink");
void readlink() __asm("__protected_readlink");
void readlink() { __real_readlink(); }
|
the_stack_data/67324037.c | int main()
{
int x, y;
float z = x * y + x * (x + y) / (x*y) - (x + y) / x+y - y+x * x+y;
}
|
the_stack_data/48575812.c | #include <stdio.h>
int main(){
printf("Hello World!");
return 0;
} |
the_stack_data/105949.c | #include <unistd.h>
#include "syscall.h"
uid_t geteuid(void)
{
return __syscall(SYS_geteuid);
}
|
the_stack_data/64532.c | # 1 "/afs/ece.cmu.edu/usr/markb1/Documents/fpga_sandbox/RecComp/Lab2/ug871-design-files/Introduction/lab2/fir_test.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/afs/ece.cmu.edu/usr/markb1/Documents/fpga_sandbox/RecComp/Lab2/ug871-design-files/Introduction/lab2/fir_test.c"
# 46 "/afs/ece.cmu.edu/usr/markb1/Documents/fpga_sandbox/RecComp/Lab2/ug871-design-files/Introduction/lab2/fir_test.c"
# 1 "/usr/include/stdio.h" 1 3 4
# 27 "/usr/include/stdio.h" 3 4
# 1 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include-fixed/features.h" 1 3 4
# 339 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include-fixed/features.h" 3 4
# 1 "/usr/include/sys/cdefs.h" 1 3 4
# 392 "/usr/include/sys/cdefs.h" 3 4
# 1 "/usr/include/bits/wordsize.h" 1 3 4
# 393 "/usr/include/sys/cdefs.h" 2 3 4
# 340 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include-fixed/features.h" 2 3 4
# 362 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include-fixed/features.h" 3 4
# 1 "/usr/include/gnu/stubs.h" 1 3 4
# 10 "/usr/include/gnu/stubs.h" 3 4
# 1 "/usr/include/gnu/stubs-64.h" 1 3 4
# 11 "/usr/include/gnu/stubs.h" 2 3 4
# 363 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include-fixed/features.h" 2 3 4
# 28 "/usr/include/stdio.h" 2 3 4
# 1 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include/stddef.h" 1 3 4
# 212 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include/stddef.h" 3 4
typedef long unsigned int size_t;
# 34 "/usr/include/stdio.h" 2 3 4
# 1 "/usr/include/bits/types.h" 1 3 4
# 27 "/usr/include/bits/types.h" 3 4
# 1 "/usr/include/bits/wordsize.h" 1 3 4
# 28 "/usr/include/bits/types.h" 2 3 4
typedef unsigned char __u_char;
typedef unsigned short int __u_short;
typedef unsigned int __u_int;
typedef unsigned long int __u_long;
typedef signed char __int8_t;
typedef unsigned char __uint8_t;
typedef signed short int __int16_t;
typedef unsigned short int __uint16_t;
typedef signed int __int32_t;
typedef unsigned int __uint32_t;
typedef signed long int __int64_t;
typedef unsigned long int __uint64_t;
typedef long int __quad_t;
typedef unsigned long int __u_quad_t;
# 130 "/usr/include/bits/types.h" 3 4
# 1 "/usr/include/bits/typesizes.h" 1 3 4
# 131 "/usr/include/bits/types.h" 2 3 4
typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;
typedef int __pid_t;
typedef struct { int __val[2]; } __fsid_t;
typedef long int __clock_t;
typedef unsigned long int __rlim_t;
typedef unsigned long int __rlim64_t;
typedef unsigned int __id_t;
typedef long int __time_t;
typedef unsigned int __useconds_t;
typedef long int __suseconds_t;
typedef int __daddr_t;
typedef int __key_t;
typedef int __clockid_t;
typedef void * __timer_t;
typedef long int __blksize_t;
typedef long int __blkcnt_t;
typedef long int __blkcnt64_t;
typedef unsigned long int __fsblkcnt_t;
typedef unsigned long int __fsblkcnt64_t;
typedef unsigned long int __fsfilcnt_t;
typedef unsigned long int __fsfilcnt64_t;
typedef long int __fsword_t;
typedef long int __ssize_t;
typedef long int __syscall_slong_t;
typedef unsigned long int __syscall_ulong_t;
typedef __off64_t __loff_t;
typedef __quad_t *__qaddr_t;
typedef char *__caddr_t;
typedef long int __intptr_t;
typedef unsigned int __socklen_t;
# 36 "/usr/include/stdio.h" 2 3 4
# 44 "/usr/include/stdio.h" 3 4
struct _IO_FILE;
typedef struct _IO_FILE FILE;
# 64 "/usr/include/stdio.h" 3 4
typedef struct _IO_FILE __FILE;
# 74 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/libio.h" 1 3 4
# 32 "/usr/include/libio.h" 3 4
# 1 "/usr/include/_G_config.h" 1 3 4
# 15 "/usr/include/_G_config.h" 3 4
# 1 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include/stddef.h" 1 3 4
# 16 "/usr/include/_G_config.h" 2 3 4
# 1 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include-fixed/wchar.h" 1 3 4
# 57 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include-fixed/wchar.h" 3 4
# 1 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include/stddef.h" 1 3 4
# 353 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include/stddef.h" 3 4
typedef unsigned int wint_t;
# 58 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include-fixed/wchar.h" 2 3 4
# 1 "/usr/include/bits/wchar.h" 1 3 4
# 22 "/usr/include/bits/wchar.h" 3 4
# 1 "/usr/include/bits/wordsize.h" 1 3 4
# 23 "/usr/include/bits/wchar.h" 2 3 4
# 60 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include-fixed/wchar.h" 2 3 4
# 85 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include-fixed/wchar.h" 3 4
typedef struct
{
int __count;
union
{
wint_t __wch;
char __wchb[4];
} __value;
} __mbstate_t;
# 21 "/usr/include/_G_config.h" 2 3 4
typedef struct
{
__off_t __pos;
__mbstate_t __state;
} _G_fpos_t;
typedef struct
{
__off64_t __pos;
__mbstate_t __state;
} _G_fpos64_t;
# 33 "/usr/include/libio.h" 2 3 4
# 50 "/usr/include/libio.h" 3 4
# 1 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include/stdarg.h" 1 3 4
# 40 "/afs/ece.cmu.edu/support/xilinx/xilinx.release/Vivado-2017.2/Vivado_HLS/2017.2/lnx64/tools/gcc/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.6.3/include/stdarg.h" 3 4
typedef __builtin_va_list __gnuc_va_list;
# 51 "/usr/include/libio.h" 2 3 4
# 145 "/usr/include/libio.h" 3 4
struct _IO_jump_t; struct _IO_FILE;
# 155 "/usr/include/libio.h" 3 4
typedef void _IO_lock_t;
struct _IO_marker {
struct _IO_marker *_next;
struct _IO_FILE *_sbuf;
int _pos;
# 178 "/usr/include/libio.h" 3 4
};
enum __codecvt_result
{
__codecvt_ok,
__codecvt_partial,
__codecvt_error,
__codecvt_noconv
};
# 246 "/usr/include/libio.h" 3 4
struct _IO_FILE {
int _flags;
char* _IO_read_ptr;
char* _IO_read_end;
char* _IO_read_base;
char* _IO_write_base;
char* _IO_write_ptr;
char* _IO_write_end;
char* _IO_buf_base;
char* _IO_buf_end;
char *_IO_save_base;
char *_IO_backup_base;
char *_IO_save_end;
struct _IO_marker *_markers;
struct _IO_FILE *_chain;
int _fileno;
int _flags2;
__off_t _old_offset;
unsigned short _cur_column;
signed char _vtable_offset;
char _shortbuf[1];
_IO_lock_t *_lock;
# 294 "/usr/include/libio.h" 3 4
__off64_t _offset;
# 303 "/usr/include/libio.h" 3 4
void *__pad1;
void *__pad2;
void *__pad3;
void *__pad4;
size_t __pad5;
int _mode;
char _unused2[15 * sizeof (int) - 4 * sizeof (void *) - sizeof (size_t)];
};
typedef struct _IO_FILE _IO_FILE;
struct _IO_FILE_plus;
extern struct _IO_FILE_plus _IO_2_1_stdin_;
extern struct _IO_FILE_plus _IO_2_1_stdout_;
extern struct _IO_FILE_plus _IO_2_1_stderr_;
# 339 "/usr/include/libio.h" 3 4
typedef __ssize_t __io_read_fn (void *__cookie, char *__buf, size_t __nbytes);
typedef __ssize_t __io_write_fn (void *__cookie, const char *__buf,
size_t __n);
typedef int __io_seek_fn (void *__cookie, __off64_t *__pos, int __w);
typedef int __io_close_fn (void *__cookie);
# 391 "/usr/include/libio.h" 3 4
extern int __underflow (_IO_FILE *);
extern int __uflow (_IO_FILE *);
extern int __overflow (_IO_FILE *, int);
# 435 "/usr/include/libio.h" 3 4
extern int _IO_getc (_IO_FILE *__fp);
extern int _IO_putc (int __c, _IO_FILE *__fp);
extern int _IO_feof (_IO_FILE *__fp) __attribute__ ((__nothrow__ , __leaf__));
extern int _IO_ferror (_IO_FILE *__fp) __attribute__ ((__nothrow__ , __leaf__));
extern int _IO_peekc_locked (_IO_FILE *__fp);
extern void _IO_flockfile (_IO_FILE *) __attribute__ ((__nothrow__ , __leaf__));
extern void _IO_funlockfile (_IO_FILE *) __attribute__ ((__nothrow__ , __leaf__));
extern int _IO_ftrylockfile (_IO_FILE *) __attribute__ ((__nothrow__ , __leaf__));
# 465 "/usr/include/libio.h" 3 4
extern int _IO_vfscanf (_IO_FILE * __restrict, const char * __restrict,
__gnuc_va_list, int *__restrict);
extern int _IO_vfprintf (_IO_FILE *__restrict, const char *__restrict,
__gnuc_va_list);
extern __ssize_t _IO_padn (_IO_FILE *, int, __ssize_t);
extern size_t _IO_sgetn (_IO_FILE *, void *, size_t);
extern __off64_t _IO_seekoff (_IO_FILE *, __off64_t, int, int);
extern __off64_t _IO_seekpos (_IO_FILE *, __off64_t, int);
extern void _IO_free_backup_area (_IO_FILE *) __attribute__ ((__nothrow__ , __leaf__));
# 75 "/usr/include/stdio.h" 2 3 4
typedef __gnuc_va_list va_list;
# 90 "/usr/include/stdio.h" 3 4
typedef __off_t off_t;
# 102 "/usr/include/stdio.h" 3 4
typedef __ssize_t ssize_t;
typedef _G_fpos_t fpos_t;
# 164 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/bits/stdio_lim.h" 1 3 4
# 165 "/usr/include/stdio.h" 2 3 4
extern struct _IO_FILE *stdin;
extern struct _IO_FILE *stdout;
extern struct _IO_FILE *stderr;
extern int remove (const char *__filename) __attribute__ ((__nothrow__ , __leaf__));
extern int rename (const char *__old, const char *__new) __attribute__ ((__nothrow__ , __leaf__));
extern FILE *tmpfile (void) ;
# 209 "/usr/include/stdio.h" 3 4
extern char *tmpnam (char *__s) __attribute__ ((__nothrow__ , __leaf__)) ;
extern char *tmpnam_r (char *__s) __attribute__ ((__nothrow__ , __leaf__)) ;
# 227 "/usr/include/stdio.h" 3 4
extern char *tempnam (const char *__dir, const char *__pfx)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) ;
extern int fclose (FILE *__stream);
extern int fflush (FILE *__stream);
# 252 "/usr/include/stdio.h" 3 4
extern int fflush_unlocked (FILE *__stream);
# 266 "/usr/include/stdio.h" 3 4
extern FILE *fopen (const char *__restrict __filename,
const char *__restrict __modes) ;
extern FILE *freopen (const char *__restrict __filename,
const char *__restrict __modes,
FILE *__restrict __stream) ;
# 295 "/usr/include/stdio.h" 3 4
# 306 "/usr/include/stdio.h" 3 4
extern FILE *fdopen (int __fd, const char *__modes) __attribute__ ((__nothrow__ , __leaf__)) ;
# 319 "/usr/include/stdio.h" 3 4
extern FILE *fmemopen (void *__s, size_t __len, const char *__modes)
__attribute__ ((__nothrow__ , __leaf__)) ;
extern FILE *open_memstream (char **__bufloc, size_t *__sizeloc) __attribute__ ((__nothrow__ , __leaf__)) ;
extern void setbuf (FILE *__restrict __stream, char *__restrict __buf) __attribute__ ((__nothrow__ , __leaf__));
extern int setvbuf (FILE *__restrict __stream, char *__restrict __buf,
int __modes, size_t __n) __attribute__ ((__nothrow__ , __leaf__));
extern void setbuffer (FILE *__restrict __stream, char *__restrict __buf,
size_t __size) __attribute__ ((__nothrow__ , __leaf__));
extern void setlinebuf (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int fprintf (FILE *__restrict __stream,
const char *__restrict __format, ...);
extern int printf (const char *__restrict __format, ...);
extern int sprintf (char *__restrict __s,
const char *__restrict __format, ...) __attribute__ ((__nothrow__));
extern int vfprintf (FILE *__restrict __s, const char *__restrict __format,
__gnuc_va_list __arg);
extern int vprintf (const char *__restrict __format, __gnuc_va_list __arg);
extern int vsprintf (char *__restrict __s, const char *__restrict __format,
__gnuc_va_list __arg) __attribute__ ((__nothrow__));
extern int snprintf (char *__restrict __s, size_t __maxlen,
const char *__restrict __format, ...)
__attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 3, 4)));
extern int vsnprintf (char *__restrict __s, size_t __maxlen,
const char *__restrict __format, __gnuc_va_list __arg)
__attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 3, 0)));
# 412 "/usr/include/stdio.h" 3 4
extern int vdprintf (int __fd, const char *__restrict __fmt,
__gnuc_va_list __arg)
__attribute__ ((__format__ (__printf__, 2, 0)));
extern int dprintf (int __fd, const char *__restrict __fmt, ...)
__attribute__ ((__format__ (__printf__, 2, 3)));
extern int fscanf (FILE *__restrict __stream,
const char *__restrict __format, ...) ;
extern int scanf (const char *__restrict __format, ...) ;
extern int sscanf (const char *__restrict __s,
const char *__restrict __format, ...) __attribute__ ((__nothrow__ , __leaf__));
# 463 "/usr/include/stdio.h" 3 4
# 526 "/usr/include/stdio.h" 3 4
extern int fgetc (FILE *__stream);
extern int getc (FILE *__stream);
extern int getchar (void);
# 550 "/usr/include/stdio.h" 3 4
extern int getc_unlocked (FILE *__stream);
extern int getchar_unlocked (void);
# 561 "/usr/include/stdio.h" 3 4
extern int fgetc_unlocked (FILE *__stream);
extern int fputc (int __c, FILE *__stream);
extern int putc (int __c, FILE *__stream);
extern int putchar (int __c);
# 594 "/usr/include/stdio.h" 3 4
extern int fputc_unlocked (int __c, FILE *__stream);
extern int putc_unlocked (int __c, FILE *__stream);
extern int putchar_unlocked (int __c);
extern int getw (FILE *__stream);
extern int putw (int __w, FILE *__stream);
extern char *fgets (char *__restrict __s, int __n, FILE *__restrict __stream)
;
# 638 "/usr/include/stdio.h" 3 4
extern char *gets (char *__s) __attribute__ ((__deprecated__));
# 665 "/usr/include/stdio.h" 3 4
extern __ssize_t __getdelim (char **__restrict __lineptr,
size_t *__restrict __n, int __delimiter,
FILE *__restrict __stream) ;
extern __ssize_t getdelim (char **__restrict __lineptr,
size_t *__restrict __n, int __delimiter,
FILE *__restrict __stream) ;
extern __ssize_t getline (char **__restrict __lineptr,
size_t *__restrict __n,
FILE *__restrict __stream) ;
extern int fputs (const char *__restrict __s, FILE *__restrict __stream);
extern int puts (const char *__s);
extern int ungetc (int __c, FILE *__stream);
extern size_t fread (void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream) ;
extern size_t fwrite (const void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __s);
# 737 "/usr/include/stdio.h" 3 4
extern size_t fread_unlocked (void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream) ;
extern size_t fwrite_unlocked (const void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream);
extern int fseek (FILE *__stream, long int __off, int __whence);
extern long int ftell (FILE *__stream) ;
extern void rewind (FILE *__stream);
# 773 "/usr/include/stdio.h" 3 4
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;
# 792 "/usr/include/stdio.h" 3 4
extern int fgetpos (FILE *__restrict __stream, fpos_t *__restrict __pos);
extern int fsetpos (FILE *__stream, const fpos_t *__pos);
# 815 "/usr/include/stdio.h" 3 4
# 824 "/usr/include/stdio.h" 3 4
extern void clearerr (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int feof (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int ferror (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern void clearerr_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int feof_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int ferror_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern void perror (const char *__s);
# 1 "/usr/include/bits/sys_errlist.h" 1 3 4
# 26 "/usr/include/bits/sys_errlist.h" 3 4
extern int sys_nerr;
extern const char *const sys_errlist[];
# 854 "/usr/include/stdio.h" 2 3 4
extern int fileno (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int fileno_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
# 873 "/usr/include/stdio.h" 3 4
extern FILE *popen (const char *__command, const char *__modes) ;
extern int pclose (FILE *__stream);
extern char *ctermid (char *__s) __attribute__ ((__nothrow__ , __leaf__));
# 913 "/usr/include/stdio.h" 3 4
extern void flockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int ftrylockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
# 943 "/usr/include/stdio.h" 3 4
# 47 "/afs/ece.cmu.edu/usr/markb1/Documents/fpga_sandbox/RecComp/Lab2/ug871-design-files/Introduction/lab2/fir_test.c" 2
# 1 "/usr/include/math.h" 1 3 4
# 29 "/usr/include/math.h" 3 4
# 1 "/usr/include/bits/huge_val.h" 1 3 4
# 34 "/usr/include/math.h" 2 3 4
# 46 "/usr/include/math.h" 3 4
# 1 "/usr/include/bits/mathdef.h" 1 3 4
# 47 "/usr/include/math.h" 2 3 4
# 70 "/usr/include/math.h" 3 4
# 1 "/usr/include/bits/mathcalls.h" 1 3 4
# 52 "/usr/include/bits/mathcalls.h" 3 4
extern double acos (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __acos (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double asin (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __asin (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double atan (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __atan (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double atan2 (double __y, double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __atan2 (double __y, double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double cos (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __cos (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double sin (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __sin (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double tan (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __tan (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double cosh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __cosh (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double sinh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __sinh (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double tanh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __tanh (double __x) __attribute__ ((__nothrow__ , __leaf__));
# 86 "/usr/include/bits/mathcalls.h" 3 4
extern double acosh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __acosh (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double asinh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __asinh (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double atanh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __atanh (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double exp (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __exp (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double frexp (double __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__)); extern double __frexp (double __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__));
extern double ldexp (double __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__)); extern double __ldexp (double __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__));
extern double log (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __log (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double log10 (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __log10 (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double modf (double __x, double *__iptr) __attribute__ ((__nothrow__ , __leaf__)); extern double __modf (double __x, double *__iptr) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__nonnull__ (2)));
# 127 "/usr/include/bits/mathcalls.h" 3 4
extern double expm1 (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __expm1 (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double log1p (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __log1p (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double logb (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __logb (double __x) __attribute__ ((__nothrow__ , __leaf__));
# 152 "/usr/include/bits/mathcalls.h" 3 4
extern double pow (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __pow (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double sqrt (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __sqrt (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double hypot (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __hypot (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double cbrt (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __cbrt (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double ceil (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __ceil (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double fabs (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __fabs (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double floor (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __floor (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double fmod (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __fmod (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern int __isinf (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __finite (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int isinf (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int finite (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double drem (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __drem (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double significand (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __significand (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double copysign (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __copysign (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
# 231 "/usr/include/bits/mathcalls.h" 3 4
extern int __isnan (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int isnan (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double j0 (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __j0 (double) __attribute__ ((__nothrow__ , __leaf__));
extern double j1 (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __j1 (double) __attribute__ ((__nothrow__ , __leaf__));
extern double jn (int, double) __attribute__ ((__nothrow__ , __leaf__)); extern double __jn (int, double) __attribute__ ((__nothrow__ , __leaf__));
extern double y0 (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __y0 (double) __attribute__ ((__nothrow__ , __leaf__));
extern double y1 (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __y1 (double) __attribute__ ((__nothrow__ , __leaf__));
extern double yn (int, double) __attribute__ ((__nothrow__ , __leaf__)); extern double __yn (int, double) __attribute__ ((__nothrow__ , __leaf__));
extern double erf (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __erf (double) __attribute__ ((__nothrow__ , __leaf__));
extern double erfc (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __erfc (double) __attribute__ ((__nothrow__ , __leaf__));
extern double lgamma (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __lgamma (double) __attribute__ ((__nothrow__ , __leaf__));
# 265 "/usr/include/bits/mathcalls.h" 3 4
extern double gamma (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __gamma (double) __attribute__ ((__nothrow__ , __leaf__));
extern double lgamma_r (double, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__)); extern double __lgamma_r (double, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__));
extern double rint (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __rint (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double nextafter (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __nextafter (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double remainder (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __remainder (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double scalbn (double __x, int __n) __attribute__ ((__nothrow__ , __leaf__)); extern double __scalbn (double __x, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int ilogb (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern int __ilogb (double __x) __attribute__ ((__nothrow__ , __leaf__));
# 359 "/usr/include/bits/mathcalls.h" 3 4
extern double scalb (double __x, double __n) __attribute__ ((__nothrow__ , __leaf__)); extern double __scalb (double __x, double __n) __attribute__ ((__nothrow__ , __leaf__));
# 71 "/usr/include/math.h" 2 3 4
# 89 "/usr/include/math.h" 3 4
# 1 "/usr/include/bits/mathcalls.h" 1 3 4
# 52 "/usr/include/bits/mathcalls.h" 3 4
extern float acosf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __acosf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float asinf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __asinf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float atanf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __atanf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float atan2f (float __y, float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __atan2f (float __y, float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float cosf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __cosf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float sinf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __sinf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float tanf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __tanf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float coshf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __coshf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float sinhf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __sinhf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float tanhf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __tanhf (float __x) __attribute__ ((__nothrow__ , __leaf__));
# 86 "/usr/include/bits/mathcalls.h" 3 4
extern float acoshf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __acoshf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float asinhf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __asinhf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float atanhf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __atanhf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float expf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __expf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float frexpf (float __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__)); extern float __frexpf (float __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__));
extern float ldexpf (float __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__)); extern float __ldexpf (float __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__));
extern float logf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __logf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float log10f (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __log10f (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float modff (float __x, float *__iptr) __attribute__ ((__nothrow__ , __leaf__)); extern float __modff (float __x, float *__iptr) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__nonnull__ (2)));
# 127 "/usr/include/bits/mathcalls.h" 3 4
extern float expm1f (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __expm1f (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float log1pf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __log1pf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float logbf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __logbf (float __x) __attribute__ ((__nothrow__ , __leaf__));
# 152 "/usr/include/bits/mathcalls.h" 3 4
extern float powf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __powf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float sqrtf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __sqrtf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float hypotf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __hypotf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float cbrtf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __cbrtf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float ceilf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __ceilf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float fabsf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __fabsf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float floorf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __floorf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float fmodf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __fmodf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern int __isinff (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __finitef (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int isinff (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int finitef (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float dremf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __dremf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float significandf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __significandf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float copysignf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __copysignf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
# 231 "/usr/include/bits/mathcalls.h" 3 4
extern int __isnanf (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int isnanf (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float j0f (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __j0f (float) __attribute__ ((__nothrow__ , __leaf__));
extern float j1f (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __j1f (float) __attribute__ ((__nothrow__ , __leaf__));
extern float jnf (int, float) __attribute__ ((__nothrow__ , __leaf__)); extern float __jnf (int, float) __attribute__ ((__nothrow__ , __leaf__));
extern float y0f (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __y0f (float) __attribute__ ((__nothrow__ , __leaf__));
extern float y1f (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __y1f (float) __attribute__ ((__nothrow__ , __leaf__));
extern float ynf (int, float) __attribute__ ((__nothrow__ , __leaf__)); extern float __ynf (int, float) __attribute__ ((__nothrow__ , __leaf__));
extern float erff (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __erff (float) __attribute__ ((__nothrow__ , __leaf__));
extern float erfcf (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __erfcf (float) __attribute__ ((__nothrow__ , __leaf__));
extern float lgammaf (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __lgammaf (float) __attribute__ ((__nothrow__ , __leaf__));
# 265 "/usr/include/bits/mathcalls.h" 3 4
extern float gammaf (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __gammaf (float) __attribute__ ((__nothrow__ , __leaf__));
extern float lgammaf_r (float, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__)); extern float __lgammaf_r (float, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__));
extern float rintf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __rintf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float nextafterf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __nextafterf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float remainderf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __remainderf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float scalbnf (float __x, int __n) __attribute__ ((__nothrow__ , __leaf__)); extern float __scalbnf (float __x, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int ilogbf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern int __ilogbf (float __x) __attribute__ ((__nothrow__ , __leaf__));
# 359 "/usr/include/bits/mathcalls.h" 3 4
extern float scalbf (float __x, float __n) __attribute__ ((__nothrow__ , __leaf__)); extern float __scalbf (float __x, float __n) __attribute__ ((__nothrow__ , __leaf__));
# 90 "/usr/include/math.h" 2 3 4
# 133 "/usr/include/math.h" 3 4
# 1 "/usr/include/bits/mathcalls.h" 1 3 4
# 52 "/usr/include/bits/mathcalls.h" 3 4
extern long double acosl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __acosl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double asinl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __asinl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double atanl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __atanl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double atan2l (long double __y, long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __atan2l (long double __y, long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double cosl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __cosl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double sinl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __sinl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double tanl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __tanl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double coshl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __coshl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double sinhl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __sinhl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double tanhl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __tanhl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
# 86 "/usr/include/bits/mathcalls.h" 3 4
extern long double acoshl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __acoshl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double asinhl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __asinhl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double atanhl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __atanhl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double expl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __expl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double frexpl (long double __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__)); extern long double __frexpl (long double __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__));
extern long double ldexpl (long double __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__)); extern long double __ldexpl (long double __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__));
extern long double logl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __logl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double log10l (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __log10l (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double modfl (long double __x, long double *__iptr) __attribute__ ((__nothrow__ , __leaf__)); extern long double __modfl (long double __x, long double *__iptr) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__nonnull__ (2)));
# 127 "/usr/include/bits/mathcalls.h" 3 4
extern long double expm1l (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __expm1l (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double log1pl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __log1pl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double logbl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __logbl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
# 152 "/usr/include/bits/mathcalls.h" 3 4
extern long double powl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __powl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double sqrtl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __sqrtl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double hypotl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __hypotl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double cbrtl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __cbrtl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double ceill (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __ceill (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double fabsl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __fabsl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double floorl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __floorl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double fmodl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __fmodl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern int __isinfl (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __finitel (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int isinfl (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int finitel (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double dreml (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __dreml (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double significandl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __significandl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double copysignl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __copysignl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
# 231 "/usr/include/bits/mathcalls.h" 3 4
extern int __isnanl (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int isnanl (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double j0l (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __j0l (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double j1l (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __j1l (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double jnl (int, long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __jnl (int, long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double y0l (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __y0l (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double y1l (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __y1l (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double ynl (int, long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __ynl (int, long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double erfl (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __erfl (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double erfcl (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __erfcl (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double lgammal (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __lgammal (long double) __attribute__ ((__nothrow__ , __leaf__));
# 265 "/usr/include/bits/mathcalls.h" 3 4
extern long double gammal (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __gammal (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double lgammal_r (long double, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__)); extern long double __lgammal_r (long double, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__));
extern long double rintl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __rintl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double nextafterl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __nextafterl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double remainderl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __remainderl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double scalbnl (long double __x, int __n) __attribute__ ((__nothrow__ , __leaf__)); extern long double __scalbnl (long double __x, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int ilogbl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern int __ilogbl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
# 359 "/usr/include/bits/mathcalls.h" 3 4
extern long double scalbl (long double __x, long double __n) __attribute__ ((__nothrow__ , __leaf__)); extern long double __scalbl (long double __x, long double __n) __attribute__ ((__nothrow__ , __leaf__));
# 134 "/usr/include/math.h" 2 3 4
# 149 "/usr/include/math.h" 3 4
extern int signgam;
# 288 "/usr/include/math.h" 3 4
typedef enum
{
_IEEE_ = -1,
_SVID_,
_XOPEN_,
_POSIX_,
_ISOC_
} _LIB_VERSION_TYPE;
extern _LIB_VERSION_TYPE _LIB_VERSION;
# 313 "/usr/include/math.h" 3 4
struct exception
{
int type;
char *name;
double arg1;
double arg2;
double retval;
};
extern int matherr (struct exception *__exc);
# 475 "/usr/include/math.h" 3 4
# 48 "/afs/ece.cmu.edu/usr/markb1/Documents/fpga_sandbox/RecComp/Lab2/ug871-design-files/Introduction/lab2/fir_test.c" 2
# 1 "/afs/ece.cmu.edu/usr/markb1/Documents/fpga_sandbox/RecComp/Lab2/ug871-design-files/Introduction/lab2/fir.h" 1
# 50 "/afs/ece.cmu.edu/usr/markb1/Documents/fpga_sandbox/RecComp/Lab2/ug871-design-files/Introduction/lab2/fir.h"
typedef int coef_t;
typedef int data_t;
typedef int acc_t;
void fir (
data_t *y,
coef_t c[11 +1],
data_t x
);
# 49 "/afs/ece.cmu.edu/usr/markb1/Documents/fpga_sandbox/RecComp/Lab2/ug871-design-files/Introduction/lab2/fir_test.c" 2
int main () {
const int SAMPLES=600;
FILE *fp;
data_t signal, output;
coef_t taps[11] = {0,-10,-9,23,56,63,56,23,-9,-10,0,};
int i, ramp_up;
signal = 0;
ramp_up = 1;
fp=fopen("out.dat","w");
for (i=0;i<=SAMPLES;i++) {
if (ramp_up == 1)
signal = signal + 1;
else
signal = signal - 1;
fir(&output,taps,signal);
if ((ramp_up == 1) && (signal >= 75))
ramp_up = 0;
else if ((ramp_up == 0) && (signal <= -75))
ramp_up = 1;
fprintf(fp,"%i %d %d\n",i,signal,output);
}
fclose(fp);
printf ("Comparing against output data \n");
if (system("diff -w out.dat out.gold.dat")) {
fprintf(stdout, "*******************************************\n");
fprintf(stdout, "FAIL: Output DOES NOT match the golden output\n");
fprintf(stdout, "*******************************************\n");
return 1;
} else {
fprintf(stdout, "*******************************************\n");
fprintf(stdout, "PASS: The output matches the golden output!\n");
fprintf(stdout, "*******************************************\n");
return 0;
}
}
|
the_stack_data/43274.c | #include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
float uint2float(uint32_t u)
{
int n = 0;
uint32_t s = u & 0x80000000;
u = u & 0x7fffffff; /* 去掉sign位 */
/* 找到1.frac中1的位置 */
for(int i = 0; i < 31; i++)
{
if ((u >> i) == 0x1)
{
n = i;
break;
}
}
printf("n = %d\n", n);
return 0;
}
int main()
{
uint32_t a = 0x08000000;
uint2float(a);
return 0;
}
|
the_stack_data/405114.c | #include<stdio.h>
int main()
{
long n,m,x=1,y=1,i=0,out;
scanf("%ld%ld",&m,&n);
while(i<m-n)
{
x*=m-i;
i++;
}
i=1;
while(i<=m-n)
{
y*=i;
i++;
}
out=x/y;
printf("%ld",out);
return 0;
} |
the_stack_data/90764899.c | int a = 100;
char b = (char) 250;
int main(void) {
return 0;
} |
the_stack_data/84074.c | /*
* Byte-oriented AES-256 implementation.
* All lookup tables replaced with 'on the fly' calculations.
*
* Copyright (c) 2007 Ilya O. Levin, http://www.literatecode.com
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
/* #include "aes256.h" */
#define N_EXEC 10
/* #define CHECK_RES */
#ifndef uint8_t
#define uint8_t unsigned char
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
uint8_t key[32];
uint8_t enckey[32];
uint8_t deckey[32];
} aes256_context;
void aes256_init(aes256_context *, uint8_t * /* key */);
void aes256_done(aes256_context *);
void aes256_encrypt_ecb(aes256_context *, uint8_t * /* plaintext */);
void aes256_decrypt_ecb(aes256_context *, uint8_t * /* cipertext */);
#ifdef __cplusplus
}
#endif
#define FD(x) (((x) >> 1) ^ (((x) & 1) ? 0x8d : 0))
#define BACK_TO_TABLES
static uint8_t rj_xtime(uint8_t);
static void aes_subBytes(uint8_t *);
static void aes_subBytes_inv(uint8_t *);
static void aes_addRoundKey(uint8_t *, uint8_t *);
static void aes_addRoundKey_cpy(uint8_t *, uint8_t *, uint8_t *);
static void aes_shiftRows(uint8_t *);
static void aes_shiftRows_inv(uint8_t *);
static void aes_mixColumns(uint8_t *);
static void aes_mixColumns_inv(uint8_t *);
static void aes_expandEncKey(uint8_t *, uint8_t *);
static void aes_expandDecKey(uint8_t *, uint8_t *);
#ifndef BACK_TO_TABLES
static uint8_t gf_alog(uint8_t);
static uint8_t gf_log(uint8_t);
static uint8_t gf_mulinv(uint8_t);
static uint8_t rj_sbox(uint8_t);
static uint8_t rj_sbox_inv(uint8_t);
#endif
#ifdef BACK_TO_TABLES
static const uint8_t sbox[256] =
{
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,
0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc,
0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a,
0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,
0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17,
0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88,
0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9,
0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6,
0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94,
0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68,
0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
};
static const uint8_t sboxinv[256] =
{
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38,
0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87,
0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d,
0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2,
0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16,
0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a,
0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02,
0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea,
0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85,
0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89,
0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20,
0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31,
0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d,
0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0,
0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26,
0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d
};
#define rj_sbox(x) sbox[(x)]
#define rj_sbox_inv(x) sboxinv[(x)]
#else /* tableless subroutines */
/* -------------------------------------------------------------------------- */
static uint8_t gf_alog(uint8_t x) // calculate anti-logarithm gen 3
{
uint8_t y = 1, i;
for (i = 0; i < x; i++) y ^= rj_xtime(y);
return y;
} /* gf_alog */
/* -------------------------------------------------------------------------- */
static uint8_t gf_log(uint8_t x) // calculate logarithm gen 3
{
uint8_t y, i = 0;
if (x)
for (i = 1, y = 1; i > 0; i++ )
{
y ^= rj_xtime(y);
if (y == x) break;
}
return i;
} /* gf_log */
/* -------------------------------------------------------------------------- */
static uint8_t gf_mulinv(uint8_t x) // calculate multiplicative inverse
{
return (x) ? gf_alog(255 - gf_log(x)) : 0;
} /* gf_mulinv */
/* -------------------------------------------------------------------------- */
static uint8_t rj_sbox(uint8_t x)
{
uint8_t y, sb;
sb = y = gf_mulinv(x);
y = (uint8_t)(y << 1) | (y >> 7), sb ^= y;
y = (uint8_t)(y << 1) | (y >> 7), sb ^= y;
y = (uint8_t)(y << 1) | (y >> 7), sb ^= y;
y = (uint8_t)(y << 1) | (y >> 7), sb ^= y;
return (sb ^ 0x63);
} /* rj_sbox */
/* -------------------------------------------------------------------------- */
static uint8_t rj_sbox_inv(uint8_t x)
{
uint8_t y, sb;
y = x ^ 0x63;
sb = y = (uint8_t)(y << 1) | (y >> 7);
y = (uint8_t)(y << 2) | (y >> 6);
sb ^= y;
y = (uint8_t)(y << 3) | (y >> 5);
sb ^= y;
return gf_mulinv(sb);
} /* rj_sbox_inv */
#endif
/* -------------------------------------------------------------------------- */
static uint8_t rj_xtime(uint8_t x)
{
uint8_t y = (uint8_t)(x << 1);
return (x & 0x80) ? (y ^ 0x1b) : y;
} /* rj_xtime */
/* -------------------------------------------------------------------------- */
static void aes_subBytes(uint8_t *buf)
{
register uint8_t i = 16;
while (i--) buf[i] = rj_sbox(buf[i]);
} /* aes_subBytes */
/* -------------------------------------------------------------------------- */
static void aes_subBytes_inv(uint8_t *buf)
{
register uint8_t i = 16;
while (i--) buf[i] = rj_sbox_inv(buf[i]);
} /* aes_subBytes_inv */
/* -------------------------------------------------------------------------- */
static void aes_addRoundKey(uint8_t *buf, uint8_t *key)
{
register uint8_t i = 16;
while (i--) buf[i] ^= key[i];
} /* aes_addRoundKey */
/* -------------------------------------------------------------------------- */
static void aes_addRoundKey_cpy(uint8_t *buf, uint8_t *key, uint8_t *cpk)
{
register uint8_t i = 16;
while (i--) buf[i] ^= (cpk[i] = key[i]), cpk[16 + i] = key[16 + i];
} /* aes_addRoundKey_cpy */
/* -------------------------------------------------------------------------- */
static void aes_shiftRows(uint8_t *buf)
{
register uint8_t i, j; /* to make it potentially parallelable :) */
i = buf[1], buf[1] = buf[5], buf[5] = buf[9], buf[9] = buf[13], buf[13] = i;
i = buf[10], buf[10] = buf[2], buf[2] = i;
j = buf[3], buf[3] = buf[15], buf[15] = buf[11], buf[11] = buf[7], buf[7] = j;
j = buf[14], buf[14] = buf[6], buf[6] = j;
} /* aes_shiftRows */
/* -------------------------------------------------------------------------- */
static void aes_shiftRows_inv(uint8_t *buf)
{
register uint8_t i, j; /* same as above :) */
i = buf[1], buf[1] = buf[13], buf[13] = buf[9], buf[9] = buf[5], buf[5] = i;
i = buf[2], buf[2] = buf[10], buf[10] = i;
j = buf[3], buf[3] = buf[7], buf[7] = buf[11], buf[11] = buf[15], buf[15] = j;
j = buf[6], buf[6] = buf[14], buf[14] = j;
} /* aes_shiftRows_inv */
/* -------------------------------------------------------------------------- */
static void aes_mixColumns(uint8_t *buf)
{
register uint8_t i, a, b, c, d, e;
for (i = 0; i < 16; i += 4)
{
a = buf[i];
b = buf[i + 1];
c = buf[i + 2];
d = buf[i + 3];
e = a ^ b ^ c ^ d;
buf[i] ^= e ^ rj_xtime(a ^ b);
buf[i + 1] ^= e ^ rj_xtime(b ^ c);
buf[i + 2] ^= e ^ rj_xtime(c ^ d);
buf[i + 3] ^= e ^ rj_xtime(d ^ a);
}
} /* aes_mixColumns */
/* -------------------------------------------------------------------------- */
void aes_mixColumns_inv(uint8_t *buf)
{
register uint8_t i, a, b, c, d, e, x, y, z;
for (i = 0; i < 16; i += 4)
{
a = buf[i];
b = buf[i + 1];
c = buf[i + 2];
d = buf[i + 3];
e = a ^ b ^ c ^ d;
z = rj_xtime(e);
x = e ^ rj_xtime(rj_xtime(z ^ a ^ c));
y = e ^ rj_xtime(rj_xtime(z ^ b ^ d));
buf[i] ^= x ^ rj_xtime(a ^ b);
buf[i + 1] ^= y ^ rj_xtime(b ^ c);
buf[i + 2] ^= x ^ rj_xtime(c ^ d);
buf[i + 3] ^= y ^ rj_xtime(d ^ a);
}
} /* aes_mixColumns_inv */
/* -------------------------------------------------------------------------- */
static void aes_expandEncKey(uint8_t *k, uint8_t *rc)
{
register uint8_t i;
k[0] ^= rj_sbox(k[29]) ^ (*rc);
k[1] ^= rj_sbox(k[30]);
k[2] ^= rj_sbox(k[31]);
k[3] ^= rj_sbox(k[28]);
*rc = rj_xtime( *rc);
for(i = 4; i < 16; i += 4) k[i] ^= k[i - 4], k[i + 1] ^= k[i - 3],
k[i + 2] ^= k[i - 2], k[i + 3] ^= k[i - 1];
k[16] ^= rj_sbox(k[12]);
k[17] ^= rj_sbox(k[13]);
k[18] ^= rj_sbox(k[14]);
k[19] ^= rj_sbox(k[15]);
for(i = 20; i < 32; i += 4) k[i] ^= k[i - 4], k[i + 1] ^= k[i - 3],
k[i + 2] ^= k[i - 2], k[i + 3] ^= k[i - 1];
} /* aes_expandEncKey */
/* -------------------------------------------------------------------------- */
void aes_expandDecKey(uint8_t *k, uint8_t *rc)
{
uint8_t i;
for(i = 28; i > 16; i -= 4) k[i + 0] ^= k[i - 4], k[i + 1] ^= k[i - 3],
k[i + 2] ^= k[i - 2], k[i + 3] ^= k[i - 1];
k[16] ^= rj_sbox(k[12]);
k[17] ^= rj_sbox(k[13]);
k[18] ^= rj_sbox(k[14]);
k[19] ^= rj_sbox(k[15]);
for(i = 12; i > 0; i -= 4) k[i + 0] ^= k[i - 4], k[i + 1] ^= k[i - 3],
k[i + 2] ^= k[i - 2], k[i + 3] ^= k[i - 1];
*rc = FD(*rc);
k[0] ^= rj_sbox(k[29]) ^ (*rc);
k[1] ^= rj_sbox(k[30]);
k[2] ^= rj_sbox(k[31]);
k[3] ^= rj_sbox(k[28]);
} /* aes_expandDecKey */
/* -------------------------------------------------------------------------- */
void aes256_init(aes256_context *ctx, uint8_t *k)
{
uint8_t rcon = 1;
register uint8_t i;
for (i = 0; i < sizeof(ctx->key); i++) ctx->enckey[i] = ctx->deckey[i] = k[i];
for (i = 8; --i;) aes_expandEncKey(ctx->deckey, &rcon);
} /* aes256_init */
/* -------------------------------------------------------------------------- */
void aes256_done(aes256_context *ctx)
{
register uint8_t i;
for (i = 0; i < sizeof(ctx->key); i++)
ctx->key[i] = ctx->enckey[i] = ctx->deckey[i] = 0;
} /* aes256_done */
/* -------------------------------------------------------------------------- */
void aes256_encrypt_ecb(aes256_context *ctx, uint8_t *buf)
{
uint8_t i, rcon;
aes_addRoundKey_cpy(buf, ctx->enckey, ctx->key);
for(i = 1, rcon = 1; i < 14; ++i)
{
aes_subBytes(buf);
aes_shiftRows(buf);
aes_mixColumns(buf);
if( i & 1 ) aes_addRoundKey( buf, &ctx->key[16]);
else aes_expandEncKey(ctx->key, &rcon), aes_addRoundKey(buf, ctx->key);
}
aes_subBytes(buf);
aes_shiftRows(buf);
aes_expandEncKey(ctx->key, &rcon);
aes_addRoundKey(buf, ctx->key);
} /* aes256_encrypt */
/* -------------------------------------------------------------------------- */
void aes256_decrypt_ecb(aes256_context *ctx, uint8_t *buf)
{
uint8_t i, rcon;
aes_addRoundKey_cpy(buf, ctx->deckey, ctx->key);
aes_shiftRows_inv(buf);
aes_subBytes_inv(buf);
for (i = 14, rcon = 0x80; --i;)
{
if( ( i & 1 ) )
{
aes_expandDecKey(ctx->key, &rcon);
aes_addRoundKey(buf, &ctx->key[16]);
}
else aes_addRoundKey(buf, ctx->key);
aes_mixColumns_inv(buf);
aes_shiftRows_inv(buf);
aes_subBytes_inv(buf);
}
aes_addRoundKey( buf, ctx->key);
} /* aes256_decrypt */
#define DUMP(s, i, buf, sz) {printf(s); \
for (i = 0; i < (sz);i++) \
printf("%02x ", buf[i]); \
printf("\n");}
#ifdef CHECK_RES
unsigned int global_check1 = 1;
unsigned int global_check2 = 2;
#endif
uint8_t key[32] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32};
uint8_t buf[16] = {21, 22, 23, 24, 25, 26, 27, 28, 29, 210, 211, 212, 213, 214, 215, 216};
int main (int argc, char *argv[])
{
aes256_context ctx;
uint8_t i;
/* uint8_t buf_before[16]; */
/* int is_error = 0; */
/* uint8_t tst[16] = {0x8e, 0xa2, 0xb7, 0xca, */
/* 0x51, 0x67, 0x45, 0xbf, */
/* 0xea, 0xfc, 0x49, 0x90, */
/* 0x4b, 0x49, 0x60, 0x89}; */
int exec = 0;
while (exec++ < N_EXEC) {
/* #ifdef CHECK_RES */
/* global_check1 = 0x11111111; */
/* global_check2 = 0x22222222; */
/* #endif */
/* #ifdef CHECK_RES */
/* for (i = 0; i < sizeof(buf);i++) buf_before[i] = buf[i]; */
/* /\* DUMP("txt: ", i, buf, sizeof(buf)); *\/ */
/* /\* DUMP("key: ", i, key, sizeof(key)); *\/ */
/* /\* printf("---\n"); *\/ */
/* #endif */
aes256_init(&ctx, key);
aes256_encrypt_ecb(&ctx, buf);
/* #ifdef CHECK_RES */
/* /\* DUMP("enc: ", i, buf, sizeof(buf)); *\/ */
/* /\* printf("tst: 8e a2 b7 ca 51 67 45 bf ea fc 49 90 4b 49 60 89\n"); *\/ */
/* is_error = 0; */
/* for (i = 0; i < sizeof(buf);i++) { */
/* if (buf[i] == tst[i]) */
/* is_error++; */
/* } */
/* if (is_error != sizeof(buf)) */
/* global_check1 = 0x88776655; */
/* else */
/* global_check1 = 0x11223344; */
/* #endif */
aes256_init(&ctx, key);
aes256_decrypt_ecb(&ctx, buf);
/* DUMP("dec: ", i, buf, sizeof(buf)); */
aes256_done(&ctx);
/* #ifdef CHECK_RES */
/* is_error = 0; */
/* for (i = 0; i < sizeof(buf);i++) { */
/* if (buf[i] == buf_before[i]) */
/* is_error++; */
/* } */
/* if (is_error != sizeof(buf)) */
/* global_check2 = 0x87654321; */
/* else */
/* global_check2 = 0x12345678; */
/* #endif */
}
return 0;
} /* main */
|
the_stack_data/107954385.c | #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
/*********************/
/* 3d geometry types */
/*********************/
typedef struct Point3Struct { /* 3d point */
double x, y, z;
} Point3;
typedef Point3 Vector3;
//FIXME
double BilinearInterpolation(double q11, double q12, double q21, double q22, double x1, double x2, double y1, double y2, double x, double y);
/* Function to find the cross over point (the point before
which elements are smaller than or equal to x and after
which greater than x)
http://www.geeksforgeeks.org/find-k-closest-elements-given-value/ */
int
findCrossOver(double arr[], int low, int high, double x)
{
int mid;
// Base cases
if (arr[high] <= x) // x is greater than all
return high;
if (arr[low] > x) // x is smaller than all
return low;
// Find the middle point
mid = (low + high)/2; /* low + (high - low)/2 */
/* If x is same as middle element, then return mid */
if (arr[mid] <= x && arr[mid+1] > x)
return mid;
/* If x is greater than arr[mid], then either arr[mid + 1]
is ceiling of x or ceiling lies in arr[mid+1...high] */
if (arr[mid] < x)
return findCrossOver(arr, mid+1, high, x);
return findCrossOver(arr, low, mid - 1, x);
}
/* https://helloacm.com/cc-function-to-compute-the-bilinear-interpolation/ */
double
BilinearInterpolation(double q11, double q12, double q21, double q22, double x1, double x2, double y1, double y2, double x, double y)
{
double x2x1, y2y1, x2x, y2y, yy1, xx1;
x2x1 = x2 - x1;
y2y1 = y2 - y1;
x2x = x2 - x;
y2y = y2 - y;
yy1 = y - y1;
xx1 = x - x1;
return 1.0 / (x2x1 * y2y1) * (
q11 * x2x * y2y +
q21 * xx1 * y2y +
q12 * x2x * yy1 +
q22 * xx1 * yy1
);
}
/*
* C code from the article
* "Tri-linear Interpolation"
* by Steve Hill, [email protected]
* in "Graphics Gems IV", Academic Press, 1994
*
*/
#if 0
double
trilinear(Point3 *p, double *d, int xsize, int ysize, int zsize, double def)
{
# define DENS(X, Y, Z) d[(X)+xsize*((Y)+ysize*(Z))]
int x0, y0, z0,
x1, y1, z1;
double *dp,
fx, fy, fz,
d000, d001, d010, d011,
d100, d101, d110, d111,
dx00, dx01, dx10, dx11,
dxy0, dxy1, dxyz;
x0 = floor(p->x);
fx = p->x - x0;
y0 = floor(p->y);
fy = p->y - y0;
z0 = floor(p->z);
fz = p->z - z0;
x1 = x0 + 1;
y1 = y0 + 1;
z1 = z0 + 1;
if (x0 >= 0 && x1 < xsize &&
y0 >= 0 && y1 < ysize &&
z0 >= 0 && z1 < zsize) {
dp = &DENS(x0, y0, z0);
d000 = dp[0];
d100 = dp[1];
dp += xsize;
d010 = dp[0];
d110 = dp[1];
dp += xsize*ysize;
d011 = dp[0];
d111 = dp[1];
dp -= xsize;
d001 = dp[0];
d101 = dp[1];
} else {
# define INRANGE(X, Y, Z) \
((X) >= 0 && (X) < xsize && \
(Y) >= 0 && (Y) < ysize && \
(Z) >= 0 && (Z) < zsize)
d000 = INRANGE(x0, y0, z0) ? DENS(x0, y0, z0) : def;
d001 = INRANGE(x0, y0, z1) ? DENS(x0, y0, z1) : def;
d010 = INRANGE(x0, y1, z0) ? DENS(x0, y1, z0) : def;
d011 = INRANGE(x0, y1, z1) ? DENS(x0, y1, z1) : def;
d100 = INRANGE(x1, y0, z0) ? DENS(x1, y0, z0) : def;
d101 = INRANGE(x1, y0, z1) ? DENS(x1, y0, z1) : def;
d110 = INRANGE(x1, y1, z0) ? DENS(x1, y1, z0) : def;
d111 = INRANGE(x1, y1, z1) ? DENS(x1, y1, z1) : def;
}
/* linear interpolation from l (when a=0) to h (when a=1)*/
/* (equal to (a*h)+((1-a)*l) */
#define LERP(a,l,h) ((l)+(((h)-(l))*(a)))
dx00 = LERP(fx, d000, d100);
dx01 = LERP(fx, d001, d101);
dx10 = LERP(fx, d010, d110);
dx11 = LERP(fx, d011, d111);
dxy0 = LERP(fy, dx00, dx10);
dxy1 = LERP(fy, dx01, dx11);
dxyz = LERP(fz, dxy0, dxy1);
return dxyz;
}
#endif
/* trilinear interpolation
Paul Bourke
July 1997
http://paulbourke.net/miscellaneous/interpolation/ */
double
TrilinearInterpolation(double x, double y, double z, int xind, int yind, int zind, double ***td)
{
double V000, V100, V010, V001, V101, V011, V110, V111, Vxyz;
V000 = td[zind][yind][xind];
V100 = td[zind][yind][xind+1];
V010 = td[zind][yind+1][xind];
V001 = td[zind+1][yind][xind];
V101 = td[zind+1][yind][xind+1];
V011 = td[zind+1][yind+1][xind];
V110 = td[zind][yind+1][xind+1];
V111 = td[zind+1][yind+1][xind+1];
Vxyz = V000 * (1 - x) * (1 - y) * (1 - z) +
V100 * x * (1 - y) * (1 - z) +
V010 * (1 - x) * y * (1 - z) +
V001 * (1 - x) * (1 - y) * z +
V101 * x * (1 - y) * z +
V011 * (1 - x) * y * z +
V110 * x * y * (1 - z) +
V111 * x * y * z;
return Vxyz;
}
|
the_stack_data/9511748.c | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern void signal(int sig , void *func ) ;
extern float strtof(char const *str , char const *endptr ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void RandomFunc(unsigned int input[1] , unsigned int output[1] )
{
unsigned int state[1] ;
unsigned int local1 ;
char copy11 ;
char copy12 ;
char copy13 ;
{
state[0UL] = (input[0UL] - 51238316UL) - 339126204U;
local1 = 0UL;
while (local1 < 1UL) {
copy11 = *((char *)(& state[0UL]) + 1);
*((char *)(& state[0UL]) + 1) = *((char *)(& state[0UL]) + 3);
*((char *)(& state[0UL]) + 3) = copy11;
copy12 = *((char *)(& state[0UL]) + 0);
*((char *)(& state[0UL]) + 0) = *((char *)(& state[0UL]) + 3);
*((char *)(& state[0UL]) + 3) = copy12;
local1 ++;
}
local1 = 0UL;
while (local1 < 1UL) {
copy13 = *((char *)(& state[0UL]) + 2);
*((char *)(& state[0UL]) + 2) = *((char *)(& state[0UL]) + 1);
*((char *)(& state[0UL]) + 1) = copy13;
state[local1] |= ((state[0UL] + state[local1]) & 7U) << 2UL;
local1 ++;
}
output[0UL] = (state[0UL] >> 3U) | (state[0UL] << 29U);
}
}
void megaInit(void)
{
{
}
}
int main(int argc , char *argv[] )
{
unsigned int input[1] ;
unsigned int output[1] ;
int randomFuns_i5 ;
unsigned int 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 int )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 1513953142U) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
|
the_stack_data/165767797.c | /* Copyright (C) 1997 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>, 1997.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <errno.h>
#include <unistd.h>
/* This file is used if no system call is available. */
ssize_t
__syscall_pwrite64 (int fd, const char *buf, size_t count,
off_t offset_hi, off_t offset_lo)
{
__set_errno (ENOSYS);
return -1;
}
|
the_stack_data/154689.c | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
/* Maximum number of children */
#define MAX_NO_CLD 10
int main ()
{
int i, ncld, wtime, status;
pid_t cpid, mypid, parpid;
/* Parent process gets its own ID and its parent's ID */
mypid = getpid();
parpid = getppid();
printf("Parent: PID = %u, PPID = %u\n", mypid, parpid);
/* Parent process obtains the number of children from the user */
printf("Parent: Number of children = ");
scanf("%d", &ncld);
if ((ncld < 0) || (ncld > MAX_NO_CLD)) ncld = 5;
printf("\n");
/* Child creation loop */
for (i=0; i<ncld; ++i) {
/* Create the next child */
//printf("Child %d:\n",i);
cpid = fork();
/* The child process executes the following conditional block */
if (cpid == 0) {
/* Child process gets its own ID and its parent's ID */
mypid = getpid();
parpid = getppid();
srand(mypid);
wtime = 1 + rand() % 10;
printf("Child %d: PID = %u, PPID = %u, work time = %d\n",i, mypid, parpid, wtime);
/* Child process does some work (sleeping is a hard work!) */
sleep(wtime);
printf("\nChild %d: Work done...\n", i);
/* Child process exits with status i (the loop variable) */
exit(i);
}
/* The parent continues to the next iteration */
}
/* Parent waits for all the children to terminate */
for (i=0; i<ncld; ++i) {
/* Parent waits for any child to terminate */
/* Use waitpid() if the wait is on a specific child */
wait(&status);
/* Parent uses the exit status to identify the child */
printf("Parent: Child %d terminates...\n", WEXITSTATUS(status));
}
printf("\nParent terminates...\n");
exit(0);
}
|
the_stack_data/51699486.c | /* Fig. 7.10: fig07_10.c
Converting a string to uppercase using a
non-constant pointer to non-constant data */
#include <stdio.h>
#include <ctype.h>
void convertToUppercase( char *sPtr ); /* prototype */
int main( void )
{
char string[] = "characters and $32.98"; /* initialize char array */
printf( "The string before conversion is: %s", string );
convertToUppercase( string );
printf( "\nThe string after conversion is: %s\n", string );
return 0; /* indicates successful termination */
} /* end main */
/* convert string to uppercase letters */
void convertToUppercase( char *sPtr )
{
while ( *sPtr != '\0' ) { /* current character is not '\0' */
if ( islower( *sPtr ) ) { /* if character is lowercase, */
*sPtr = toupper( *sPtr ); /* convert to uppercase */
} /* end if */
++sPtr; /* move sPtr to the next character */
} /* end while */
} /* end function convertToUppercase */
/**************************************************************************
* (C) Copyright 1992-2010 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/
|
the_stack_data/43888799.c | int main() {
int a = 1;
int b = 1;
int c = 1;
if(a == 1) {
if(b < 5) {
c = 2;
}
} else {
if(b < 5) {
c = 3;
}
}
return c;
}
|
the_stack_data/155501.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2013-2017 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
int
main ()
{
return 0;
}
|
the_stack_data/242330380.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 int input[1] , unsigned int output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void RandomFunc(unsigned int input[1] , unsigned int output[1] )
{
unsigned int state[1] ;
{
state[0UL] = (input[0UL] - 51238316UL) - 339126204U;
if ((state[0UL] >> 3U) & 1U) {
if (! (state[0UL] & 1U)) {
state[0UL] |= (state[0UL] & 7U) << 2UL;
}
} else
if ((state[0UL] >> 4U) & 1U) {
state[0UL] += state[0UL];
} else {
state[0UL] *= state[0UL];
}
output[0UL] = ((state[0UL] << 9U) | (state[0UL] >> 23U)) ^ 942792860U;
}
}
void megaInit(void)
{
{
}
}
int main(int argc , char *argv[] )
{
unsigned int input[1] ;
unsigned int output[1] ;
int randomFuns_i5 ;
unsigned int 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 int )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 3606750526U) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
|
the_stack_data/491187.c | // RUN: %clang_cc1 %s -verify
void f1(void) __attribute__((ownership_takes("foo"))); // expected-error {{'ownership_takes' attribute requires parameter 1 to be an identifier}}
void *f2(void) __attribute__((ownership_returns(foo, 1, 2))); // expected-error {{'ownership_returns' attribute takes no more than 1 argument}}
void f3(void) __attribute__((ownership_holds(foo, 1))); // expected-error {{'ownership_holds' attribute parameter 1 is out of bounds}}
void *f4(void) __attribute__((ownership_returns(foo)));
void f5(void) __attribute__((ownership_holds(foo))); // expected-error {{'ownership_holds' attribute takes at least 2 arguments}}
void f6(void) __attribute__((ownership_holds(foo, 1, 2, 3))); // expected-error {{'ownership_holds' attribute parameter 1 is out of bounds}}
void f7(void) __attribute__((ownership_takes(foo))); // expected-error {{'ownership_takes' attribute takes at least 2 arguments}}
void f8(int *i, int *j, int k) __attribute__((ownership_holds(foo, 1, 2, 4))); // expected-error {{'ownership_holds' attribute parameter 3 is out of bounds}}
int f9 __attribute__((ownership_takes(foo, 1))); // expected-warning {{'ownership_takes' attribute only applies to functions}}
void f10(int i) __attribute__((ownership_holds(foo, 1))); // expected-error {{'ownership_holds' attribute only applies to pointer arguments}}
void *f11(float i) __attribute__((ownership_returns(foo, 1))); // expected-error {{'ownership_returns' attribute only applies to integer arguments}}
void *f12(float i, int k, int f, int *j) __attribute__((ownership_returns(foo, 4))); // expected-error {{'ownership_returns' attribute only applies to integer arguments}}
void f13(int *i, int *j) __attribute__((ownership_holds(foo, 1))) __attribute__((ownership_takes(foo, 2)));
void f14(int i, int j, int *k) __attribute__((ownership_holds(foo, 3))) __attribute__((ownership_takes(foo, 3))); // expected-error {{'ownership_holds' and 'ownership_takes' attributes are not compatible}}
|
the_stack_data/118556.c | // printf関数を使うために必要
#include <stdio.h>
// pow関数を使うために必要
#include <math.h>
// exit関数を使うために必要
#include <stdlib.h>
// ラベルを付ける
#define TRUE 1
#define FALSE 0
#define MAX_DIGIT 8
/******************************
2進数関連
******************************/
// Change Integer to Binaryの略。10進数から2進数に変換する。整数部のみ対応
// CIntBinが再帰するたびに*pが後ろに行く(桁あがり)
// 初期状態で*pは配列の一番右のポインタである必要がある。
void CIntBin(int *p, int target) {
if (target == 1) {
*p = TRUE;
} else {
*p = target % 2; /* TRUE or FLASE */
CIntBin(--p, (int)(target/2)); /* 小数部切り捨てで再帰 */
}
}
// Change Float to Binaryの略。10進数から2進数に変換する。小数部のみ対応
// CFloatBinが再帰するたびに*pが前に行く(桁さがり)
// 初期状態で*pは配列の一番左のポインタである必要がある。CIntBinとは逆なので注意。
void CFloatBin(int *p, float target) {
if (target >= 1) {
printf("Error at 'CFloatBin'!! target is %.2f > 1.0\n", target);
exit(1);
}
target *= 2;
if (target == 1) {
*p = 1;
} else if (target > 1) {
*p = 1;
CFloatBin(++p, target - 1); /* 整数部は必ず1 */
} else {
*p = 0;
CFloatBin(++p, target);
}
}
// Change to Decimalの略。2進数から10進数に変換する。少数にも対応している。
// CDecが再帰するたびにmultiが次々2で割られていく。それをindex回続ける。
// multiは初期状態で2^(整数桁-1)である必要がある。
// 最上位桁から最下位桁までその桁の重みを掛けて、加算する。
float CDec(int *target, float multi, int index) {
if (index == 1) {
return *target * multi;
} else {
return (*target * multi) + CDec(++target, multi/2, --index);
}
}
// Reverse Binaryの略。与えられた配列の全ての真偽値を反転する。
// 再帰するたび*pは前に進んでいく。真偽値の否定は!で求めることができる。
void revBin(int *p, int index) {
if (index == 0) {
return;
} else {
*p = !*p;
revBin(++p, --index);
}
}
/******************************
加算器関連 Wikipedia参照
******************************/
// 半加算器。a,bを受け取り、sを返す。繰り上がりはcで出力する。
void harfAdder(int *a, int *b, int *s, int *c){
*c = *a && *b;
*s = (*a || *b) && (!*c);
}
// 全加算器。a,b,cを受け取り、sを返す。繰り上がりは上書きされたcで出力する。
// harfAdderと引数の並びが違うのはWikipedia準拠のため。
void fullAdder(int *a, int *b, int *c, int *s) {
int tmpa;
int tmpb;
tmpa = *a;
tmpb = *b;
harfAdder(a ,b ,&tmpa ,&tmpb);
harfAdder(&tmpa ,c ,s ,c);
*c = tmpb || *c;
}
// 与えられた配列の各桁をそれぞれ全加算器に通していく。
// 向きは最下位から最上位桁。cは次の桁に持ち越す。
// 配列aは上書きされて、加算結果が代入される。もともとの配列aは破壊されるが、配列bは破壊されない。
// 初期状態で*a,*bはそれぞれの配列の一番右のポインタであり、変数cは0である必要がある。
// 最上位桁に行ったにも関わらず、繰り上がりしている場合、オーバーフローしているので異常終了。
void adder(int *a, int *b, int *c, int index) {
if (index == 0) {
if (*c == 1) {
printf("Error at 'adder'!! Overflow!!\n");
exit(1);
}
return;
} else {
fullAdder(a, b, c, a);
adder(--a, --b, c, --index);
}
}
/******************************
配列に対する一般的な関数群
******************************/
// Initial Arrayの略。配列を0で初期化する
void initArray(int *target, int index) {
if (index == 0) {
return;
} else {
*target = 0;
initArray(++target, --index);
}
}
// Display Arrayの略。配列の中身を表示する。最後に改行を出力する。
void dispArray(int *target, int index) {
if (index == 0) {
printf("\n");
return;
} else {
printf("%d", *target);
dispArray(++target, --index);
}
}
int main() {
/******************************
1. 10進数49を2進数で表わせ
******************************/
int target;
int targetBin[MAX_DIGIT];
// targetを49で初期化
target = 49;
// targetBinを0で初期化
initArray(targetBin, MAX_DIGIT);
// targetを2進数に変換する。結果はtargetBinに代入される
CIntBin(&targetBin[MAX_DIGIT - 1], target);
// ラベルとtargetBinの表示
printf("1.) 49 is ");
dispArray(targetBin, MAX_DIGIT);
/******************************
2. 10進数-69を8桁の符号付き2進数(2の補数)で表わせ
******************************/
// int target;
// int targetBin[MAX_DEGIT];
int addBin[MAX_DIGIT];
int c;
// targetを-69で初期化
target = -69;
// 繰り上がり変数の初期化
c = 0;
// 使用する配列を0で初期化
initArray(targetBin, MAX_DIGIT);
initArray(addBin, MAX_DIGIT);
// targetの絶対値を2進数に変換する。結果はtargetBinに代入される
CIntBin(&targetBin[MAX_DIGIT - 1], (-1) * target);
// 1を2進数に変換する。結果はaddBinに代入される
CIntBin(&addBin[MAX_DIGIT - 1], 1);
// targetBinの全ての真偽値を反転する
revBin(targetBin, MAX_DIGIT);
// 加算器にtargetBinとaddBinを放り込む。結果はtargetBinに代入される。
// 変数cは繰り上がり用の変数。
adder(&targetBin[MAX_DIGIT - 1], &addBin[MAX_DIGIT - 1], &c, MAX_DIGIT);
// ラベルとtargetBinの表示
printf("2.) -69 is ");
dispArray(targetBin, MAX_DIGIT);
/******************************
3. 10進数0.8125を2進数で表わせ
******************************/
// int targetBin[MAX_DEGIT];
float targetFlort;
// targetFloatを0.8125で初期化
targetFlort = 0.8125;
// targetBinを0で初期化
initArray(targetBin, MAX_DIGIT);
// targetFloatを2進数に変換する。結果はtargetBinに代入される。
CFloatBin(targetBin, targetFlort);
// ラベルとtargetBinの表示
printf("3.) 0.8125 is 0.");
dispArray(targetBin, MAX_DIGIT);
/******************************
4. 2進数101.1001を10進数で表わせ
******************************/
// tmpBinの初期化
int tmpBin[] = {1,0,1,1,0,0,1};
int intPartDegit;
int allDegit;
// 整数部の桁数
intPartDegit = 3;
// 全体の桁数
allDegit = 7;
// ラベルの出力後、CDec関数でfloat型に変換したものを直接出力する
printf("4.) 101.1001 is %f\n", CDec(tmpBin, pow(2, intPartDegit - 1), allDegit));
/******************************
5. 符号付き2進数 1101001を10進数で表わせ
******************************/
// int c;
// int allDegit;
// addBin[MAX_DEGIT];
// signedBinの初期化
int signedBin[] = {1,1,0,1,0,0,1};
// ラベルの出力
printf("5.) signed 1101001 is ");
if (tmpBin[0] == 0) { // 最上位ビットがFalseの場合
// 全体の桁数(整数部の桁数)
allDegit = 7;
printf("%f\n", CDec(signedBin, pow(2, allDegit - 1), allDegit));
} else { // 最上位ビットがTrueの場合
// 全体の桁数(整数部の桁数)
allDegit = 7;
// 繰り上がり変数の初期化
c = 0;
// addBinの初期化
initArray(addBin, allDegit);
// signedBinの全ての真偽値を反転する。
revBin(signedBin, allDegit);
// 1を2進数に変換する。結果はaddBinに代入される。
CIntBin(&addBin[allDegit - 1], 1);
// 加算器にsignedBinとaddBinを放り込む。結果はsignedBinに代入される。
// 変数cは繰り上がり用の変数
adder(&signedBin[allDegit - 1], &addBin[allDegit - 1], &c, allDegit);
// CDec関数でfloat型に変換したものに-1を乗算して出力する。
printf("%.0f\n", -1 * CDec(signedBin, pow(2, allDegit - 1), allDegit));
}
/******************************
6. 符号なし2進数 1101001を10進数で表わせ
******************************/
// int allDegit;
int unsignedBin[] = {1,1,0,1,0,0,1};
// 全体の桁数(整数部の桁数)
allDegit = 7;
// ラベルの出力後、CDec関数でfloat型に変換したものを出力する。
printf("6.) unsigned 1101001 is %.0f\n", CDec(unsignedBin, pow(2, allDegit - 1), allDegit));
return 0;
}
|
the_stack_data/36429.c | #include <stdio.h>
#define IN 0
#define OUT 1
int main()
{
int c, state;
state = OUT;
while((c = getchar()) != EOF) {
if (c == ' ' || c == '\t' || c == '\n') {
if (state == IN) {
putchar('\n');
}
state = OUT;
}
else {
putchar(c);
state = IN;
}
}
}
|
the_stack_data/97013764.c | /**
* C tcp client test example.
*
* License - MIT.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#define SOCKET_PATH "/tmp/testunix.sock"
/**
* connect_server - Connect server.
*/
int connect_server(void)
{
int clt_fd = -1;
struct sockaddr_un ser_addr;
/* Create socket. */
clt_fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (0 > clt_fd) {
printf("Error in socket.\n");
goto err_socket;
}
/* Connect to server. */
memset(&ser_addr, 0, sizeof(ser_addr));
ser_addr.sun_family = AF_UNIX;
strncpy(ser_addr.sun_path, SOCKET_PATH, strlen(SOCKET_PATH) + 1);
if (0 > connect(clt_fd, (struct sockaddr *)&ser_addr, sizeof(ser_addr))) {
printf("Error in connect.\n");
goto err_connect;
}
return clt_fd;
err_connect:
close(clt_fd);
err_socket:
return -1;
}
/**
* Main function.
*/
int main(void)
{
int i = 0;
int cltfd = -1;
char test_buf[] = "Test for client";
char buf[128] = { 0 };
cltfd = connect_server();
if (cltfd < 0) {
printf("Error in client connect.\n");
goto err_client;
}
for (i = 0; i < 5; i++) {
write(cltfd, test_buf, strlen(test_buf));
read(cltfd, buf, 127);
printf("Client recv: %s.\n", buf);
sleep(1);
}
close(cltfd);
return 0;
err_client:
return -1;
}
|
the_stack_data/242331008.c | /**
* KC705 PCIe Vivado Project General Test DMA
* Project Name:
* Design Name:
* FW Version
* working with kernel 3.10.58
*
* SVN keywords
* $Date: 2015-11-06 16:46:06 +0000 (Fri, 06 Nov 2015) $
* $Revision: 7931 $
* $URL: http://metis.ipfn.ist.utl.pt:8888/svn/cdaq/Users/Bernardo/FPGA/Vivado/KC705/Software/trunk/driver/kc705-pcie-drv.c $
*
* Copyright 2014 - 2015 IPFN-Instituto Superior Tecnico, Portugal
* Creation Date 2014-02-10
*
* Licensed under the EUPL, Version 1.1 or - as soon they
* will be approved by the European Commission - subsequent
* versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
//#include <sys/types.h>
//#include <sys/stat.h>
//#include <sys/ioctl.h>
#include <fcntl.h>
//#include <linux/types.h>
#include <math.h>
//#include <signal.h>
#include <string.h>
#define DMA_ACQ_SIZE 2048
char DEVNAME[] = "/dev/kc705_pcie1";
int main(int argc, char **argv)
{
int i, ii, rc, fd;
char * devn;
int flags = 0;
FILE * fdi;
int32_t * dataBuff; //[DMA_ACQ_SIZE / sizeof(int16_t) ]; // user space buffer for data
unsigned int Npackets=1;
int32_t * pAdcData;
int32_t * pAdcDataWr;
if(argc > 2)
devn = argv[2];
else
devn = DEVNAME;
if(argc > 1){
Npackets = atoi(argv[1]);
}
else{
printf("%s [Npackets dev_name]\n", argv[0]);
return -1;
}
pAdcData = (int32_t *) malloc(DMA_ACQ_SIZE * Npackets);
pAdcDataWr = pAdcData;
flags |= O_RDONLY;
printf("opening device\t");
extern int errno;
fd=open(devn,flags);
if (fd < 0) {
fprintf (stderr,"Error: cannot open device %s \n", devn);
fprintf (stderr," errno = %i\n",errno);
printf ("open error : %s\n", strerror(errno));
exit(1);
}
printf("device opened: \n"); // /Opening the device
dataBuff = (int32_t *) malloc(DMA_ACQ_SIZE);
for (i=0; i < Npackets; i++) {
rc = read(fd, dataBuff, DMA_ACQ_SIZE); // loop read.
memcpy(pAdcDataWr, dataBuff, DMA_ACQ_SIZE);
pAdcDataWr += DMA_ACQ_SIZE/sizeof(int32_t);
/*
for (ii=0; ii < DMA_ACQ_SIZE/sizeof(int32_t); ii++) {
if ((dataBuff[2*ii+1] & 0xFFF) != 0xA59)
printf("NOK %d d:%X, ", ii, dataBuff[2*ii+1]);
}
printf("\n");
*/
for (ii=0; ii < 10; ii++) {
printf("%d d:%X, ", ii, dataBuff[2*ii]);
}
printf("\n");
for (ii=0; ii < 10; ii++) {
printf("0x%08X, ", dataBuff[2*ii+1]);
}
printf(" \n");
}
printf("read OK: %d Npackets %d \n", rc, Npackets);
close(fd);
fdi = fopen("data.bin","wb"); /*Test if can open files to write */
pAdcDataWr = pAdcData;
for (i=0; i < Npackets; i++) {
fwrite(pAdcDataWr, 1, DMA_ACQ_SIZE, fdi);
pAdcDataWr += DMA_ACQ_SIZE/sizeof(int32_t);
}
fclose(fdi);
free(dataBuff);
free(pAdcData);
// printf("Acquired %d packets, %d samples, chanNumb: %d\n", Npackets, SAMP_PER_PACKET * Npackets, chanNumb );
return 0;
}
|
the_stack_data/701364.c | /* ANSI-C code produced by gperf version 3.0.4 */
/* Command-line: gperf -L ANSI-C -N hoedown_find_block_tag -c -C -E -S 1 --ignore-case -m100 mldb/ext/hoedown/html_block_names.gperf */
/* Computed positions: -k'1-2' */
#if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \
&& ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \
&& (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \
&& ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \
&& ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \
&& ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \
&& ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \
&& ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \
&& ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \
&& ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \
&& ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \
&& ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \
&& ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \
&& ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \
&& ('Z' == 90) && ('[' == 91) && ('\\' == 92) && (']' == 93) \
&& ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \
&& ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \
&& ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \
&& ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \
&& ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \
&& ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \
&& ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \
&& ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126))
/* The character set is not based on ISO-646. */
#error "gperf generated tables don't work with this execution character set. Please report a bug to <[email protected]>."
#endif
/* maximum key range = 24, duplicates = 0 */
#ifndef GPERF_DOWNCASE
#define GPERF_DOWNCASE 1
static unsigned char gperf_downcase[256] =
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194,
195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209,
210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224,
225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
255
};
#endif
#ifndef GPERF_CASE_STRNCMP
#define GPERF_CASE_STRNCMP 1
static int
gperf_case_strncmp (register const char *s1, register const char *s2, register unsigned int n)
{
for (; n > 0;)
{
unsigned char c1 = gperf_downcase[(unsigned char)*s1++];
unsigned char c2 = gperf_downcase[(unsigned char)*s2++];
if (c1 != 0 && c1 == c2)
{
n--;
continue;
}
return (int)c1 - (int)c2;
}
return 0;
}
#endif
#ifdef __GNUC__
__inline
#else
#ifdef __cplusplus
inline
#endif
#endif
static unsigned int
hash (register const char *str, register unsigned int len)
{
static const unsigned char asso_values[] =
{
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
22, 21, 19, 18, 16, 0, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 1, 25, 0, 25,
1, 0, 0, 13, 0, 25, 25, 11, 2, 1,
0, 25, 25, 5, 0, 2, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 1, 25,
0, 25, 1, 0, 0, 13, 0, 25, 25, 11,
2, 1, 0, 25, 25, 5, 0, 2, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25
};
register int hval = len;
switch (hval)
{
default:
hval += asso_values[(unsigned char)str[1]+1];
/*FALLTHROUGH*/
case 1:
hval += asso_values[(unsigned char)str[0]];
break;
}
return hval;
}
#ifdef __GNUC__
__inline
#if defined __GNUC_STDC_INLINE__ || defined __GNUC_GNU_INLINE__
__attribute__ ((__gnu_inline__))
#endif
#endif
const char *
hoedown_find_block_tag (register const char *str, register unsigned int len)
{
enum
{
TOTAL_KEYWORDS = 24,
MIN_WORD_LENGTH = 1,
MAX_WORD_LENGTH = 10,
MIN_HASH_VALUE = 1,
MAX_HASH_VALUE = 24
};
if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
{
register int key = hash (str, len);
if (key <= MAX_HASH_VALUE && key >= MIN_HASH_VALUE)
{
register const char *resword;
switch (key - 1)
{
case 0:
resword = "p";
goto compare;
case 1:
resword = "h6";
goto compare;
case 2:
resword = "div";
goto compare;
case 3:
resword = "del";
goto compare;
case 4:
resword = "form";
goto compare;
case 5:
resword = "table";
goto compare;
case 6:
resword = "figure";
goto compare;
case 7:
resword = "pre";
goto compare;
case 8:
resword = "fieldset";
goto compare;
case 9:
resword = "noscript";
goto compare;
case 10:
resword = "script";
goto compare;
case 11:
resword = "style";
goto compare;
case 12:
resword = "dl";
goto compare;
case 13:
resword = "ol";
goto compare;
case 14:
resword = "ul";
goto compare;
case 15:
resword = "math";
goto compare;
case 16:
resword = "ins";
goto compare;
case 17:
resword = "h5";
goto compare;
case 18:
resword = "iframe";
goto compare;
case 19:
resword = "h4";
goto compare;
case 20:
resword = "h3";
goto compare;
case 21:
resword = "blockquote";
goto compare;
case 22:
resword = "h2";
goto compare;
case 23:
resword = "h1";
goto compare;
}
return 0;
compare:
if ((((unsigned char)*str ^ (unsigned char)*resword) & ~32) == 0 && !gperf_case_strncmp (str, resword, len) && resword[len] == '\0')
return resword;
}
}
return 0;
}
|
the_stack_data/168893961.c | #ifdef __cplusplus
# error "A C++ compiler has been selected for C."
#endif
#if defined(__18CXX)
# define ID_VOID_MAIN
#endif
#if defined(__CLASSIC_C__)
/* cv-qualifiers did not exist in K&R C */
# define const
# define volatile
#endif
/* Version number components: V=Version, R=Revision, P=Patch
Version date components: YYYY=Year, MM=Month, DD=Day */
#if defined(__INTEL_COMPILER) || defined(__ICC)
# define COMPILER_ID "Intel"
# if defined(_MSC_VER)
# define SIMULATE_ID "MSVC"
# endif
/* __INTEL_COMPILER = VRP */
# define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER/100)
# define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER/10 % 10)
# if defined(__INTEL_COMPILER_UPDATE)
# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER_UPDATE)
# else
# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER % 10)
# endif
# if defined(__INTEL_COMPILER_BUILD_DATE)
/* __INTEL_COMPILER_BUILD_DATE = YYYYMMDD */
# define COMPILER_VERSION_TWEAK DEC(__INTEL_COMPILER_BUILD_DATE)
# endif
# if defined(_MSC_VER)
/* _MSC_VER = VVRR */
# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
# endif
#elif defined(__PATHCC__)
# define COMPILER_ID "PathScale"
# define COMPILER_VERSION_MAJOR DEC(__PATHCC__)
# define COMPILER_VERSION_MINOR DEC(__PATHCC_MINOR__)
# if defined(__PATHCC_PATCHLEVEL__)
# define COMPILER_VERSION_PATCH DEC(__PATHCC_PATCHLEVEL__)
# endif
#elif defined(__BORLANDC__) && defined(__CODEGEARC_VERSION__)
# define COMPILER_ID "Embarcadero"
# define COMPILER_VERSION_MAJOR HEX(__CODEGEARC_VERSION__>>24 & 0x00FF)
# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF)
# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF)
#elif defined(__BORLANDC__)
# define COMPILER_ID "Borland"
/* __BORLANDC__ = 0xVRR */
# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8)
# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF)
#elif defined(__WATCOMC__) && __WATCOMC__ < 1200
# define COMPILER_ID "Watcom"
/* __WATCOMC__ = VVRR */
# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100)
# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10)
# if (__WATCOMC__ % 10) > 0
# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10)
# endif
#elif defined(__WATCOMC__)
# define COMPILER_ID "OpenWatcom"
/* __WATCOMC__ = VVRP + 1100 */
# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100)
# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10)
# if (__WATCOMC__ % 10) > 0
# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10)
# endif
#elif defined(__SUNPRO_C)
# define COMPILER_ID "SunPro"
# if __SUNPRO_C >= 0x5100
/* __SUNPRO_C = 0xVRRP */
# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>12)
# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xFF)
# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF)
# else
/* __SUNPRO_CC = 0xVRP */
# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>8)
# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xF)
# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF)
# endif
#elif defined(__HP_cc)
# define COMPILER_ID "HP"
/* __HP_cc = VVRRPP */
# define COMPILER_VERSION_MAJOR DEC(__HP_cc/10000)
# define COMPILER_VERSION_MINOR DEC(__HP_cc/100 % 100)
# define COMPILER_VERSION_PATCH DEC(__HP_cc % 100)
#elif defined(__DECC)
# define COMPILER_ID "Compaq"
/* __DECC_VER = VVRRTPPPP */
# define COMPILER_VERSION_MAJOR DEC(__DECC_VER/10000000)
# define COMPILER_VERSION_MINOR DEC(__DECC_VER/100000 % 100)
# define COMPILER_VERSION_PATCH DEC(__DECC_VER % 10000)
#elif defined(__IBMC__) && defined(__COMPILER_VER__)
# define COMPILER_ID "zOS"
/* __IBMC__ = VRP */
# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100)
# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10)
# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10)
#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ >= 800
# define COMPILER_ID "XL"
/* __IBMC__ = VRP */
# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100)
# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10)
# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10)
#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ < 800
# define COMPILER_ID "VisualAge"
/* __IBMC__ = VRP */
# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100)
# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10)
# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10)
#elif defined(__PGI)
# define COMPILER_ID "PGI"
# define COMPILER_VERSION_MAJOR DEC(__PGIC__)
# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__)
# if defined(__PGIC_PATCHLEVEL__)
# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__)
# endif
#elif defined(_CRAYC)
# define COMPILER_ID "Cray"
# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR)
# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR)
#elif defined(__TI_COMPILER_VERSION__)
# define COMPILER_ID "TI"
/* __TI_COMPILER_VERSION__ = VVVRRRPPP */
# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000)
# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000)
# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000)
#elif defined(__FUJITSU) || defined(__FCC_VERSION) || defined(__fcc_version)
# define COMPILER_ID "Fujitsu"
#elif defined(__TINYC__)
# define COMPILER_ID "TinyCC"
#elif defined(__BCC__)
# define COMPILER_ID "Bruce"
#elif defined(__SCO_VERSION__)
# define COMPILER_ID "SCO"
#elif defined(__clang__) && defined(__apple_build_version__)
# define COMPILER_ID "AppleClang"
# if defined(_MSC_VER)
# define SIMULATE_ID "MSVC"
# endif
# define COMPILER_VERSION_MAJOR DEC(__clang_major__)
# define COMPILER_VERSION_MINOR DEC(__clang_minor__)
# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__)
# if defined(_MSC_VER)
/* _MSC_VER = VVRR */
# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
# endif
# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__)
#elif defined(__clang__)
# define COMPILER_ID "Clang"
# if defined(_MSC_VER)
# define SIMULATE_ID "MSVC"
# endif
# define COMPILER_VERSION_MAJOR DEC(__clang_major__)
# define COMPILER_VERSION_MINOR DEC(__clang_minor__)
# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__)
# if defined(_MSC_VER)
/* _MSC_VER = VVRR */
# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
# endif
#elif defined(__GNUC__)
# define COMPILER_ID "GNU"
# define COMPILER_VERSION_MAJOR DEC(__GNUC__)
# if defined(__GNUC_MINOR__)
# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__)
# endif
# if defined(__GNUC_PATCHLEVEL__)
# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__)
# endif
#elif defined(_MSC_VER)
# define COMPILER_ID "MSVC"
/* _MSC_VER = VVRR */
# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100)
# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100)
# if defined(_MSC_FULL_VER)
# if _MSC_VER >= 1400
/* _MSC_FULL_VER = VVRRPPPPP */
# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000)
# else
/* _MSC_FULL_VER = VVRRPPPP */
# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000)
# endif
# endif
# if defined(_MSC_BUILD)
# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD)
# endif
#elif defined(__VISUALDSPVERSION__) || defined(__ADSPBLACKFIN__) || defined(__ADSPTS__) || defined(__ADSP21000__)
# define COMPILER_ID "ADSP"
#if defined(__VISUALDSPVERSION__)
/* __VISUALDSPVERSION__ = 0xVVRRPP00 */
# define COMPILER_VERSION_MAJOR HEX(__VISUALDSPVERSION__>>24)
# define COMPILER_VERSION_MINOR HEX(__VISUALDSPVERSION__>>16 & 0xFF)
# define COMPILER_VERSION_PATCH HEX(__VISUALDSPVERSION__>>8 & 0xFF)
#endif
#elif defined(__IAR_SYSTEMS_ICC__ ) || defined(__IAR_SYSTEMS_ICC)
# define COMPILER_ID "IAR"
#elif defined(__ARMCC_VERSION)
# define COMPILER_ID "ARMCC"
#if __ARMCC_VERSION >= 1000000
/* __ARMCC_VERSION = VRRPPPP */
# define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000)
# define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100)
# define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000)
#else
/* __ARMCC_VERSION = VRPPPP */
# define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000)
# define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10)
# define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000)
#endif
#elif defined(__SDCC_VERSION_MAJOR) || defined(SDCC)
# define COMPILER_ID "SDCC"
# if defined(__SDCC_VERSION_MAJOR)
# define COMPILER_VERSION_MAJOR DEC(__SDCC_VERSION_MAJOR)
# define COMPILER_VERSION_MINOR DEC(__SDCC_VERSION_MINOR)
# define COMPILER_VERSION_PATCH DEC(__SDCC_VERSION_PATCH)
# else
/* SDCC = VRP */
# define COMPILER_VERSION_MAJOR DEC(SDCC/100)
# define COMPILER_VERSION_MINOR DEC(SDCC/10 % 10)
# define COMPILER_VERSION_PATCH DEC(SDCC % 10)
# endif
#elif defined(_SGI_COMPILER_VERSION) || defined(_COMPILER_VERSION)
# define COMPILER_ID "MIPSpro"
# if defined(_SGI_COMPILER_VERSION)
/* _SGI_COMPILER_VERSION = VRP */
# define COMPILER_VERSION_MAJOR DEC(_SGI_COMPILER_VERSION/100)
# define COMPILER_VERSION_MINOR DEC(_SGI_COMPILER_VERSION/10 % 10)
# define COMPILER_VERSION_PATCH DEC(_SGI_COMPILER_VERSION % 10)
# else
/* _COMPILER_VERSION = VRP */
# define COMPILER_VERSION_MAJOR DEC(_COMPILER_VERSION/100)
# define COMPILER_VERSION_MINOR DEC(_COMPILER_VERSION/10 % 10)
# define COMPILER_VERSION_PATCH DEC(_COMPILER_VERSION % 10)
# endif
/* These compilers are either not known or too old to define an
identification macro. Try to identify the platform and guess that
it is the native compiler. */
#elif defined(__sgi)
# define COMPILER_ID "MIPSpro"
#elif defined(__hpux) || defined(__hpua)
# define COMPILER_ID "HP"
#else /* unknown compiler */
# define COMPILER_ID ""
#endif
/* Construct the string literal in pieces to prevent the source from
getting matched. Store it in a pointer rather than an array
because some compilers will just produce instructions to fill the
array rather than assigning a pointer to a static array. */
char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]";
#ifdef SIMULATE_ID
char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]";
#endif
#ifdef __QNXNTO__
char const* qnxnto = "INFO" ":" "qnxnto[]";
#endif
#if defined(__CRAYXE) || defined(__CRAYXC)
char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]";
#endif
#define STRINGIFY_HELPER(X) #X
#define STRINGIFY(X) STRINGIFY_HELPER(X)
/* Identify known platforms by name. */
#if defined(__linux) || defined(__linux__) || defined(linux)
# define PLATFORM_ID "Linux"
#elif defined(__CYGWIN__)
# define PLATFORM_ID "Cygwin"
#elif defined(__MINGW32__)
# define PLATFORM_ID "MinGW"
#elif defined(__APPLE__)
# define PLATFORM_ID "Darwin"
#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
# define PLATFORM_ID "Windows"
#elif defined(__FreeBSD__) || defined(__FreeBSD)
# define PLATFORM_ID "FreeBSD"
#elif defined(__NetBSD__) || defined(__NetBSD)
# define PLATFORM_ID "NetBSD"
#elif defined(__OpenBSD__) || defined(__OPENBSD)
# define PLATFORM_ID "OpenBSD"
#elif defined(__sun) || defined(sun)
# define PLATFORM_ID "SunOS"
#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__)
# define PLATFORM_ID "AIX"
#elif defined(__sgi) || defined(__sgi__) || defined(_SGI)
# define PLATFORM_ID "IRIX"
#elif defined(__hpux) || defined(__hpux__)
# define PLATFORM_ID "HP-UX"
#elif defined(__HAIKU__)
# define PLATFORM_ID "Haiku"
#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS)
# define PLATFORM_ID "BeOS"
#elif defined(__QNX__) || defined(__QNXNTO__)
# define PLATFORM_ID "QNX"
#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__)
# define PLATFORM_ID "Tru64"
#elif defined(__riscos) || defined(__riscos__)
# define PLATFORM_ID "RISCos"
#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__)
# define PLATFORM_ID "SINIX"
#elif defined(__UNIX_SV__)
# define PLATFORM_ID "UNIX_SV"
#elif defined(__bsdos__)
# define PLATFORM_ID "BSDOS"
#elif defined(_MPRAS) || defined(MPRAS)
# define PLATFORM_ID "MP-RAS"
#elif defined(__osf) || defined(__osf__)
# define PLATFORM_ID "OSF1"
#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv)
# define PLATFORM_ID "SCO_SV"
#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX)
# define PLATFORM_ID "ULTRIX"
#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX)
# define PLATFORM_ID "Xenix"
#elif defined(__WATCOMC__)
# if defined(__LINUX__)
# define PLATFORM_ID "Linux"
# elif defined(__DOS__)
# define PLATFORM_ID "DOS"
# elif defined(__OS2__)
# define PLATFORM_ID "OS2"
# elif defined(__WINDOWS__)
# define PLATFORM_ID "Windows3x"
# else /* unknown platform */
# define PLATFORM_ID
# endif
#else /* unknown platform */
# define PLATFORM_ID
#endif
/* For windows compilers MSVC and Intel we can determine
the architecture of the compiler being used. This is because
the compilers do not have flags that can change the architecture,
but rather depend on which compiler is being used
*/
#if defined(_WIN32) && defined(_MSC_VER)
# if defined(_M_IA64)
# define ARCHITECTURE_ID "IA64"
# elif defined(_M_X64) || defined(_M_AMD64)
# define ARCHITECTURE_ID "x64"
# elif defined(_M_IX86)
# define ARCHITECTURE_ID "X86"
# elif defined(_M_ARM)
# if _M_ARM == 4
# define ARCHITECTURE_ID "ARMV4I"
# elif _M_ARM == 5
# define ARCHITECTURE_ID "ARMV5I"
# else
# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM)
# endif
# elif defined(_M_MIPS)
# define ARCHITECTURE_ID "MIPS"
# elif defined(_M_SH)
# define ARCHITECTURE_ID "SHx"
# else /* unknown architecture */
# define ARCHITECTURE_ID ""
# endif
#elif defined(__WATCOMC__)
# if defined(_M_I86)
# define ARCHITECTURE_ID "I86"
# elif defined(_M_IX86)
# define ARCHITECTURE_ID "X86"
# else /* unknown architecture */
# define ARCHITECTURE_ID ""
# endif
#else
# define ARCHITECTURE_ID
#endif
/* Convert integer to decimal digit literals. */
#define DEC(n) \
('0' + (((n) / 10000000)%10)), \
('0' + (((n) / 1000000)%10)), \
('0' + (((n) / 100000)%10)), \
('0' + (((n) / 10000)%10)), \
('0' + (((n) / 1000)%10)), \
('0' + (((n) / 100)%10)), \
('0' + (((n) / 10)%10)), \
('0' + ((n) % 10))
/* Convert integer to hex digit literals. */
#define HEX(n) \
('0' + ((n)>>28 & 0xF)), \
('0' + ((n)>>24 & 0xF)), \
('0' + ((n)>>20 & 0xF)), \
('0' + ((n)>>16 & 0xF)), \
('0' + ((n)>>12 & 0xF)), \
('0' + ((n)>>8 & 0xF)), \
('0' + ((n)>>4 & 0xF)), \
('0' + ((n) & 0xF))
/* Construct a string literal encoding the version number components. */
#ifdef COMPILER_VERSION_MAJOR
char const info_version[] = {
'I', 'N', 'F', 'O', ':',
'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[',
COMPILER_VERSION_MAJOR,
# ifdef COMPILER_VERSION_MINOR
'.', COMPILER_VERSION_MINOR,
# ifdef COMPILER_VERSION_PATCH
'.', COMPILER_VERSION_PATCH,
# ifdef COMPILER_VERSION_TWEAK
'.', COMPILER_VERSION_TWEAK,
# endif
# endif
# endif
']','\0'};
#endif
/* Construct a string literal encoding the version number components. */
#ifdef SIMULATE_VERSION_MAJOR
char const info_simulate_version[] = {
'I', 'N', 'F', 'O', ':',
's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[',
SIMULATE_VERSION_MAJOR,
# ifdef SIMULATE_VERSION_MINOR
'.', SIMULATE_VERSION_MINOR,
# ifdef SIMULATE_VERSION_PATCH
'.', SIMULATE_VERSION_PATCH,
# ifdef SIMULATE_VERSION_TWEAK
'.', SIMULATE_VERSION_TWEAK,
# endif
# endif
# endif
']','\0'};
#endif
/* Construct the string literal in pieces to prevent the source from
getting matched. Store it in a pointer rather than an array
because some compilers will just produce instructions to fill the
array rather than assigning a pointer to a static array. */
char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]";
char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]";
#if !defined(__STDC__)
# if defined(_MSC_VER) && !defined(__clang__)
# define C_DIALECT "90"
# else
# define C_DIALECT
# endif
#elif __STDC_VERSION__ >= 201000L
# define C_DIALECT "11"
#elif __STDC_VERSION__ >= 199901L
# define C_DIALECT "99"
#else
# define C_DIALECT "90"
#endif
const char* info_language_dialect_default =
"INFO" ":" "dialect_default[" C_DIALECT "]";
/*--------------------------------------------------------------------------*/
#ifdef ID_VOID_MAIN
void main() {}
#else
# if defined(__CLASSIC_C__)
int main(argc, argv) int argc; char *argv[];
# else
int main(int argc, char* argv[])
# endif
{
int require = 0;
require += info_compiler[argc];
require += info_platform[argc];
require += info_arch[argc];
#ifdef COMPILER_VERSION_MAJOR
require += info_version[argc];
#endif
#ifdef SIMULATE_ID
require += info_simulate[argc];
#endif
#ifdef SIMULATE_VERSION_MAJOR
require += info_simulate_version[argc];
#endif
#if defined(__CRAYXE) || defined(__CRAYXC)
require += info_cray[argc];
#endif
require += info_language_dialect_default[argc];
(void)argv;
return require;
}
#endif
|
the_stack_data/82950193.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int t;
char in[10], *p;
scanf("%d\n", &t);
while (t--) {
gets(in);
p = strchr(in, '+');
if (p) printf("%d\n", atoi(in) + atoi(p + 1));
else puts("skipped");
}
} |
the_stack_data/1071436.c | // https://github.com/goblint/analyzer/issues/231#issuecomment-868369123
int main(void) {
int x = 0;
while(1) {
while(1) {
x++;
}
x--;
}
x--;
return x;
} |
the_stack_data/448143.c | #include <stdio.h>
#include <ctype.h>
#include <math.h>
double atof(char s[]);
int main(void)
{
char t1[5] = "30"; // -> 30
char t2[5] = "30."; // 30
char t3[5] = "0.30"; // 0.3
char t4[5] = ".30"; // 0.3
char t5[5] = "3e1"; // 30
char t6[6] = "3.0e1"; // 30
char t7[5] = "e1"; // -> 0, perhaps it should give 10 instead?
char t8[5] = "3e-1"; // -> 0.3
char t9[5] = "-3e3"; // -> -3000
printf("1In: %s\tOut:%f\n", t1, atof(t1));
printf("2In: %s\tOut:%f\n", t2, atof(t2));
printf("3In: %s\tOut:%f\n", t3, atof(t3));
printf("4In: %s\tOut:%f\n", t4, atof(t4));
printf("5In: %s\tOut:%f\n", t5, atof(t5));
printf("6In: %s\tOut:%f\n", t6, atof(t6));
printf("7In: %s\tOut:%f\n", t7, atof(t7));
printf("8In: %s\tOut:%f\n", t8, atof(t8));
printf("9In: %s\tOut:%f\n", t9, atof(t9));
}
/* atof: converts a string in the form of ([+-])?([0-9]+)(\.[0-9]*)?([eE][0-9]+)?
to a double in base 10 */
double atof(char s[])
{
double val;
int i, sign, power, exp, expsign;
for (i = 0; isspace(s[i]); i++)
; /* skip whitespace padding on the left */
sign = (s[i] == '-' ? -1 : 1);
if (s[i] == '-' || s[i] == '+')
i++;
for (val = 0.0; isdigit(s[i]); i++)
val = 10 * val + (s[i] - '0');
if (s[i] == '.')
i++;
for (power = 0; isdigit(s[i]); i++) {
val = 10 * val + (s[i] - '0');
power--;
}
if (s[i] == 'e' || s[i] == 'E') /* this would be a great use case for recursion, but I don't yet know how to slice an array */
i++;
expsign = (s[i] == '-' ? -1 : 1);
if (s[i] == '-' || s[i] == '+')
i++;
for (exp = 0; isdigit(s[i]); i++) /* seperate variables are necessary unless we know how many places are in the exponent */
exp = 10 * exp + (s[i] - '0');
exp *= expsign;
exp += power;
val *= sign;
return val * pow(10, exp);
}
|
the_stack_data/66861.c | #include <stdio.h>
int main(void) {
int n = 10;
int iterations = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
iterations++;
}
}
}
printf("Iterations: %d\n", iterations);
}
|
the_stack_data/25138677.c | #include <stdio.h>
#include <stdlib.h>
char *mget(char*);
int mlen(char*);
int permut(char**, int, int, int, int);
char *dop0(char*, char*);
int max = 0;
int ir[10][10];
int main(int argc, char **argv) {
int n = 0, lens = 0, no = 0;
int i, j;
scanf("%d\n", &n);
char *str[n];
char v[n][256];
for(i = 0; i < 10; i++) {
for(j = 0; j < 10; j++) ir[i][j] = 0;
}
for(i = 0; i < n; i++) {
mget(&v[i][0]);
//puts("ok ");
str[i] = &v[i][0];
}
//puts("ok ");
for(i = 0; i < n; i++) lens += mlen(&v[i][0]);
//ret = (char *)malloc(lens * sizeof(char) + 1);
//ret[0] = '\0';
for(i = 0; i < n; i++) { //puts("begin permutation\n");
no = (1 << i);
permut(str, no, n, i, 0);
no = 0; //puts("end permutation\n");
}
//puts("ok\n");
printf("%d\n", lens - max);
return 0;
}
/* Get string of stdin in S */
char *mget(char *s) {
char k = getchar();
int i;
for (i = 0; k != '\0' && k != '\n'; i++) {
s[i] = k;
k = getchar();
}
s[i] = '\0';
return s;
}
/* Return length if the S-string */
int mlen(char *s) {
int i = 0;
while(s[i] != '\0') i++; //printf("%c", s[i]); }
return i;
}
/* This function get all different reselects of N string */
int permut(char **str, int no, int n, int j, int sumpref) {
if (no == ((1 << n) - 1)) {
if ((sumpref - max) > 0) max = sumpref;
//printf("_____end of_____max = %d\n", max);
return 0;
}
int i; //printf("Call function permut, last string is str[%d], no = %d\n", j, no);
for(i = 0; i < n; i++) {
if (no & (1 << i)) { /*puts("contin\n");*/ continue; }
no += (1 << i); //printf("no = %d\n", no);
if (!ir[i][j]) {
char *re = dop0(str[i], str[j]);
ir[i][j] = myprefix(re, mlen(str[i]));
sumpref += ir[i][j];
free(re);
} else {
sumpref += ir[i][j];
}
permut(str, no, n, i, sumpref);
sumpref -= ir[i][j];
no -= (1 << i);
}
return 0;
}
/* my_dop0 for */
char *dop0(char *a, char *b) {
int i = 0, j = 0;
char *temp = (char*)malloc(256 * sizeof(char));
while(a[i] != '\0' && a[i] != '\n') {
temp[i] = a[i];
i++;
}
while(b[j] != '\0') {
temp[i + j] = b[j];
j++;
}
temp[i + j] = '\0';
//puts("dop0\n");
return temp;
}
/* original prefix function */
int fprefix(char *s, int l0) {
int len = mlen(s); //printf("%d", len);
int p[len], i, t;
for(i = 0; i < len; i++) p[i] = 0;
p[0] = t = 0;
for(i = 1; i < len; i++) {
while((t > 0) && s[t] != s[i]) t = p[t -1];
if (s[t] == s[i]) t++;
p[i] = t;
}
//printf("len of prefix string *%s* = %d\n", s, p[i - 1]);
return p[i - 1];
}
int myprefix(char *s, int l0) {
int len = mlen(s);
int i = l0 + 1, cou = 0, j = 0, beg = 0;
while(i < len) {
if ((s[i] != s[j]) && beg) {
cou = j = 0;
beg = 0;
i -= (cou - 1);
continue;
}
if (s[i] != s[j]) {
cou = j = 0;
i++;
continue;
}
if (s[j] == (l0 - 2) && i < (len - 1)) {
cou = j = 0;
continue;
}
if (s[i] == s[j]) {
cou++;
beg = 1;
i++;
j++;
continue;
}
}
return cou;
}
|
the_stack_data/421889.c | /* Simple test mrdisc solicitation agent
*
* Copyright (c) 2017 Joachim Nilsson <[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.
*/
#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netinet/ip.h>
#include <netinet/igmp.h>
#include <netinet/icmp6.h>
#include <sys/socket.h>
#define MC_ALL_ROUTERS "224.0.0.2"
#define MC6_ALL_ROUTERS "ff02::2"
#define IGMP_MRDISC_ANNOUNCE 0x30
#define IGMP_MRDISC_SOLICIT 0x31
#define IGMP_MRDISC_TERM 0x32
#define ICMP6_MRDISC_SOLICIT 152
uint16_t in_cksum(uint16_t *p, size_t len);
void compose_addr6(struct sockaddr_in6 *sin, char *group);
static int open_socket(char *ifname)
{
unsigned char ra[4] = { IPOPT_RA, 0x04, 0x00, 0x00 };
struct ifreq ifr;
char loop;
int val = 1;
int sd, rc;
sd = socket(AF_INET, SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_IGMP);
if (sd < 0)
err(1, "Cannot open socket");
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", ifname);
if (setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) < 0) {
if (ENODEV == errno) {
warnx("Not a valid interface, %s, skipping ...", ifname);
close(sd);
return -1;
}
err(1, "Cannot bind socket to interface %s", ifname);
}
rc = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_TTL, &val, sizeof(val));
if (rc < 0)
err(1, "Cannot set TTL");
rc = setsockopt(sd, IPPROTO_IP, IP_OPTIONS, &ra, sizeof(ra));
if (rc < 0)
err(1, "Cannot set IP OPTIONS");
return sd;
}
static int open_socket6(char *ifname)
{
int loop = 0;
int sd, hops = 1, rc;
struct ifreq ifr;
/**
* hopopt[8]:
* {
* "nexthdr": 0x00 (updated by kernel), "hdrextlen": 0x00,
* "rtalert": {
* "type": 0x05, "length": 0x00, "value": [ 0x00, 0x00 ] },
* }
* "PadN": [ 0x01, 0x00 ]
* }
*/
unsigned char hopopt[8] = { 0x00, 0x00, 0x05, 0x02, 0x00, 0x00, 0x01, 0x00 };
sd = socket(AF_INET6, SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_ICMPV6);
if (sd < 0)
err(1, "Cannot open socket");
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", ifname);
if (setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) < 0) {
if (ENODEV == errno) {
warnx("Not a valid interface, %s, skipping ...", ifname);
close(sd);
return -1;
}
err(1, "Cannot bind socket to interface %s", ifname);
}
rc = setsockopt(sd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &hops, sizeof(hops));
if (rc < 0)
err(1, "Cannot set hop limit");
rc = setsockopt(sd, IPPROTO_IPV6, IPV6_HOPOPTS, &hopopt, sizeof(hopopt));
if (rc < 0)
err(1, "Cannot set IPV6 hop-by-hop option");
return sd;
}
static void compose_addr(struct sockaddr_in *sin, char *group)
{
memset(sin, 0, sizeof(*sin));
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = inet_addr(group);
}
static int send_message(int sd, uint8_t type, uint8_t interval)
{
struct sockaddr dest;
struct igmp igmp;
ssize_t num;
memset(&igmp, 0, sizeof(igmp));
igmp.igmp_type = type;
igmp.igmp_code = interval;
igmp.igmp_cksum = in_cksum((uint16_t *)&igmp, sizeof(igmp) / 2);
compose_addr((struct sockaddr_in *)&dest, MC_ALL_ROUTERS);
num = sendto(sd, &igmp, sizeof(igmp), 0, &dest, sizeof(dest));
if (num < 0)
err(1, "Cannot send IGMP control message");
return 0;
}
static int send_message6(int sd, uint8_t type, uint8_t interval)
{
ssize_t num;
struct icmp6_hdr icmp6;
struct sockaddr_in6 dest;
memset(&icmp6, 0, sizeof(icmp6));
icmp6.icmp6_type = type;
icmp6.icmp6_code = interval;
icmp6.icmp6_cksum = 0; /* updated by kernel */
compose_addr6(&dest, MC6_ALL_ROUTERS);
num = sendto(sd, &icmp6, sizeof(icmp6), 0, (struct sockaddr *)&dest,
sizeof(dest));
if (num < 0)
return 1;
return 0;
}
int main(int argc, char *argv[])
{
int v4 = 1;
int v6 = 1;
char *ifname;
int sd, ret;
if (argc < 2)
errx(1, "Usage: %s [-4|-6] IFNAME", argv[0]);
if (!strncmp(argv[1], "-4", strlen("-4"))) {
v6 = 0;
ifname = argv[2];
} else if (!strncmp(argv[1], "-6", strlen("-6"))) {
v4 = 0;
ifname = argv[2];
} else {
ifname = argv[1];
}
if ((!v4 || !v6) && argc < 3)
errx(1, "Usage: %s [-4|-6] IFNAME", argv[0]);
if (v4) {
sd = open_socket(ifname);
if (sd < 0)
return 1;
ret = send_message(sd, IGMP_MRDISC_SOLICIT, 0);
close(sd);
}
if (v6) {
sd = open_socket6(ifname);
if (sd < 0)
return 1;
ret |= send_message6(sd, ICMP6_MRDISC_SOLICIT, 0);
close(sd);
}
return ret;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
|
the_stack_data/9512993.c | /* dlarrd.f -- translated by f2c (version 20061008) */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <assert.h>
#define imax(a,b) ( (a) > (b) ? (a) : (b) )
#define imin(a,b) ( (a) < (b) ? (a) : (b) )
#define TRUE_ (1)
#define FALSE_ (0)
/* Table of constant values */
static int c__1 = 1;
static int c_n1 = -1;
static int c__3 = 3;
static int c__2 = 2;
static int c__0 = 0;
/* Subroutine */
int xdrrd_(char *range, char *order, int *n, long double *vl,
long double *vu, int *il, int *iu, long double *gers,
long double *reltol, long double *d__, long double *e, long double *e2,
long double *pivmin, int *nsplit, int *isplit, int *m,
long double *w, long double *werr, long double *wl, long double *wu,
int *iblock, int *indexw, long double *work, int *iwork,
int *info)
{
/* System generated locals */
int i__1, i__2, i__3;
long double d__1, d__2;
/* Builtin functions */
// long double log(long double);
/* Local variables */
int i__, j, ib, ie, je, nb;
long double gl;
int im, in;
long double gu;
int iw, jee;
long double eps;
int nwl;
long double wlu, wul;
int nwu;
long double tmp1, tmp2;
int iend, jblk, ioff, iout, itmp1, itmp2, jdisc;
extern int xlsame_(char *, char *);
int iinfo;
long double atoli;
int iwoff, itmax;
long double wkill, rtoli, uflow, tnorm;
// extern long double dlamch_(char *);
int ibegin;
extern /* Subroutine */ int xdebz_(int *, int *, int *,
int *, int *, int *, long double *, long double *,
long double *, long double *, long double *, long double *, int *,
long double *, long double *, int *, int *, long double *,
int *, int *);
int irange, idiscl, idumma[1];
/* extern int ilaenv_(int *, char *, char *, int *, int *, */
/* int *, int *); */
int idiscu;
int ncnvrg, toofew;
/* -- LAPACK auxiliary routine (version 3.2.1) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* -- April 2009 -- */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* XDRRD computes the eigenvalues of a symmetric tridiagonal */
/* matrix T to suitable accuracy. This is an auxiliary code to be */
/* called from DSTEMR. */
/* The user may ask for all eigenvalues, all eigenvalues */
/* in the half-open interval (VL, VU], or the IL-th through IU-th */
/* eigenvalues. */
/* To avoid overflow, the matrix must be scaled so that its */
/* largest element is no greater than overflow**(1/2) * */
/* underflow**(1/4) in absolute value, and for greatest */
/* accuracy, it should not be much smaller than that. */
/* See W. Kahan "Accurate Eigenvalues of a Symmetric Tridiagonal */
/* Matrix", Report CS41, Computer Science Dept., Stanford */
/* University, July 21, 1966. */
/* Arguments */
/* ========= */
/* RANGE (input) CHARACTER */
/* = 'A': ("All") all eigenvalues will be found. */
/* = 'V': ("Value") all eigenvalues in the half-open interval */
/* (VL, VU] will be found. */
/* = 'I': ("Index") the IL-th through IU-th eigenvalues (of the */
/* entire matrix) will be found. */
/* ORDER (input) CHARACTER */
/* = 'B': ("By Block") the eigenvalues will be grouped by */
/* split-off block (see IBLOCK, ISPLIT) and */
/* ordered from smallest to largest within */
/* the block. */
/* = 'E': ("Entire matrix") */
/* the eigenvalues for the entire matrix */
/* will be ordered from smallest to */
/* largest. */
/* N (input) INT */
/* The order of the tridiagonal matrix T. N >= 0. */
/* VL (input) LONG DOUBLE PRECISION */
/* VU (input) LONG DOUBLE PRECISION */
/* If RANGE='V', the lower and upper bounds of the interval to */
/* be searched for eigenvalues. Eigenvalues less than or equal */
/* to VL, or greater than VU, will not be returned. VL < VU. */
/* Not referenced if RANGE = 'A' or 'I'. */
/* IL (input) INT */
/* IU (input) INT */
/* If RANGE='I', the indices (in ascending order) of the */
/* smallest and largest eigenvalues to be returned. */
/* 1 <= IL <= IU <= N, if N > 0; IL = 1 and IU = 0 if N = 0. */
/* Not referenced if RANGE = 'A' or 'V'. */
/* GERS (input) LONG DOUBLE PRECISION array, dimension (2*N) */
/* The N Gerschgorin intervals (the i-th Gerschgorin interval */
/* is (GERS(2*i-1), GERS(2*i)). */
/* RELTOL (input) LONG DOUBLE PRECISION */
/* The minimum relative width of an interval. When an interval */
/* is narrower than RELTOL times the larger (in */
/* magnitude) endpoint, then it is considered to be */
/* sufficiently small, i.e., converged. Note: this should */
/* always be at least radix*machine epsilon. */
/* D (input) LONG DOUBLE PRECISION array, dimension (N) */
/* The n diagonal elements of the tridiagonal matrix T. */
/* E (input) LONG DOUBLE PRECISION array, dimension (N-1) */
/* The (n-1) off-diagonal elements of the tridiagonal matrix T. */
/* E2 (input) LONG DOUBLE PRECISION array, dimension (N-1) */
/* The (n-1) squared off-diagonal elements of the tridiagonal matrix T. */
/* PIVMIN (input) LONG DOUBLE PRECISION */
/* The minimum pivot allowed in the Sturm sequence for T. */
/* NSPLIT (input) INT */
/* The number of diagonal blocks in the matrix T. */
/* 1 <= NSPLIT <= N. */
/* ISPLIT (input) INT array, dimension (N) */
/* The splitting points, at which T breaks up into submatrices. */
/* The first submatrix consists of rows/columns 1 to ISPLIT(1), */
/* the second of rows/columns ISPLIT(1)+1 through ISPLIT(2), */
/* etc., and the NSPLIT-th consists of rows/columns */
/* ISPLIT(NSPLIT-1)+1 through ISPLIT(NSPLIT)=N. */
/* (Only the first NSPLIT elements will actually be used, but */
/* since the user cannot know a priori what value NSPLIT will */
/* have, N words must be reserved for ISPLIT.) */
/* M (output) INT */
/* The actual number of eigenvalues found. 0 <= M <= N. */
/* (See also the description of INFO=2,3.) */
/* W (output) LONG DOUBLE PRECISION array, dimension (N) */
/* On exit, the first M elements of W will contain the */
/* eigenvalue approximations. XDRRD computes an interval */
/* I_j = (a_j, b_j] that includes eigenvalue j. The eigenvalue */
/* approximation is given as the interval midpoint */
/* W(j)= ( a_j + b_j)/2. The corresponding error is bounded by */
/* WERR(j) = abs( a_j - b_j)/2 */
/* WERR (output) LONG DOUBLE PRECISION array, dimension (N) */
/* The error bound on the corresponding eigenvalue approximation */
/* in W. */
/* WL (output) LONG DOUBLE PRECISION */
/* WU (output) LONG DOUBLE PRECISION */
/* The interval (WL, WU] contains all the wanted eigenvalues. */
/* If RANGE='V', then WL=VL and WU=VU. */
/* If RANGE='A', then WL and WU are the global Gerschgorin bounds */
/* on the spectrum. */
/* If RANGE='I', then WL and WU are computed by XDEBZ from the */
/* index range specified. */
/* IBLOCK (output) INT array, dimension (N) */
/* At each row/column j where E(j) is zero or small, the */
/* matrix T is considered to split into a block diagonal */
/* matrix. On exit, if INFO = 0, IBLOCK(i) specifies to which */
/* block (from 1 to the number of blocks) the eigenvalue W(i) */
/* belongs. (XDRRD may use the remaining N-M elements as */
/* workspace.) */
/* INDEXW (output) INT array, dimension (N) */
/* The indices of the eigenvalues within each block (submatrix); */
/* for example, INDEXW(i)= j and IBLOCK(i)=k imply that the */
/* i-th eigenvalue W(i) is the j-th eigenvalue in block k. */
/* WORK (workspace) LONG DOUBLE PRECISION array, dimension (4*N) */
/* IWORK (workspace) INT array, dimension (3*N) */
/* INFO (output) INT */
/* = 0: successful exit */
/* < 0: if INFO = -i, the i-th argument had an illegal value */
/* > 0: some or all of the eigenvalues failed to converge or */
/* were not computed: */
/* =1 or 3: Bisection failed to converge for some */
/* eigenvalues; these eigenvalues are flagged by a */
/* negative block number. The effect is that the */
/* eigenvalues may not be as accurate as the */
/* absolute and relative tolerances. This is */
/* generally caused by unexpectedly inaccurate */
/* arithmetic. */
/* =2 or 3: RANGE='I' only: Not all of the eigenvalues */
/* IL:IU were found. */
/* Effect: M < IU+1-IL */
/* Cause: non-monotonic arithmetic, causing the */
/* Sturm sequence to be non-monotonic. */
/* Cure: recalculate, using RANGE='A', and pick */
/* out eigenvalues IL:IU. In some cases, */
/* increasing the PARAMETER "FUDGE" may */
/* make things work. */
/* = 4: RANGE='I', and the Gershgorin interval */
/* initially used was too small. No eigenvalues */
/* were computed. */
/* Probable cause: your machine has sloppy */
/* floating-point arithmetic. */
/* Cure: Increase the PARAMETER "FUDGE", */
/* recompile, and try again. */
/* Internal Parameters */
/* =================== */
/* FUDGE LONG DOUBLE PRECISION, default = 2 */
/* A "fudge factor" to widen the Gershgorin intervals. Ideally, */
/* a value of 1 should work, but on machines with sloppy */
/* arithmetic, this needs to be larger. The default for */
/* publicly released versions should be large enough to handle */
/* the worst machine around. Note that this has no effect */
/* on accuracy of the solution. */
/* Based on contributions by */
/* W. Kahan, University of California, Berkeley, USA */
/* Beresford Parlett, University of California, Berkeley, USA */
/* Jim Demmel, University of California, Berkeley, USA */
/* Inderjit Dhillon, University of Texas, Austin, USA */
/* Osni Marques, LBNL/NERSC, USA */
/* Christof Voemel, University of California, Berkeley, USA */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. Local Arrays .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Parameter adjustments */
--iwork;
--work;
--indexw;
--iblock;
--werr;
--w;
--isplit;
--e2;
--e;
--d__;
--gers;
/* Function Body */
*info = 0;
/* Decode RANGE */
if (xlsame_(range, "A")) {
irange = 1;
} else if (xlsame_(range, "V")) {
irange = 2;
} else if (xlsame_(range, "I")) {
irange = 3;
} else {
irange = 0;
}
/* Check for Errors */
if (irange <= 0) {
*info = -1;
} else if (! (xlsame_(order, "B") || xlsame_(order,
"E"))) {
*info = -2;
} else if (*n < 0) {
*info = -3;
} else if (irange == 2) {
if (*vl >= *vu) {
*info = -5;
}
} else if (irange == 3 && (*il < 1 || *il > imax(1,*n))) {
*info = -6;
} else if (irange == 3 && (*iu < imin(*n,*il) || *iu > *n)) {
*info = -7;
}
if (*info != 0) {
return 0;
}
/* Initialize error flags */
*info = 0;
ncnvrg = FALSE_;
toofew = FALSE_;
/* Quick return if possible */
*m = 0;
if (*n == 0) {
return 0;
}
/* Simplification: */
if (irange == 3 && *il == 1 && *iu == *n) {
irange = 1;
}
/* Get machine constants */
eps = LDBL_EPSILON; // odmch_("P");
uflow = LDBL_MIN; // odmch_("U");
/* Special Case when N=1 */
/* Treat case of 1x1 matrix for quick return */
if (*n == 1) {
if (irange == 1 || irange == 2 && d__[1] > *vl && d__[1] <= *vu ||
irange == 3 && *il == 1 && *iu == 1) {
*m = 1;
w[1] = d__[1];
/* The computation error of the eigenvalue is zero */
werr[1] = 0.;
iblock[1] = 1;
indexw[1] = 1;
}
return 0;
}
/* NB is the minimum vector length for vector bisection, or 0 */
/* if only scalar is to be done. */
nb = 1; // ilaenv_(&c__1, "DSTEBZ", " ", n, &c_n1, &c_n1, &c_n1);
if (nb <= 1) {
nb = 0;
}
/* Find global spectral radius */
gl = d__[1];
gu = d__[1];
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
/* Computing MIN */
d__1 = gl, d__2 = gers[(i__ << 1) - 1];
gl = fminl(d__1,d__2);
/* Computing MAX */
d__1 = gu, d__2 = gers[i__ * 2];
gu = fmaxl(d__1,d__2);
/* L5: */
}
/* Compute global Gerschgorin bounds and spectral diameter */
/* Computing MAX */
d__1 = fabsl(gl), d__2 = fabsl(gu);
tnorm = fmaxl(d__1,d__2);
gl = gl - tnorm * 2. * eps * *n - *pivmin * 4.;
gu = gu + tnorm * 2. * eps * *n + *pivmin * 4.;
/* [JAN/28/2009] remove the line below since SPDIAM variable not use */
/* SPDIAM = GU - GL */
/* Input arguments for XDEBZ: */
/* The relative tolerance. An interval (a,b] lies within */
/* "relative tolerance" if b-a < RELTOL*max(|a|,|b|), */
rtoli = *reltol;
/* Set the absolute tolerance for interval convergence to zero to force */
/* interval convergence based on relative size of the interval. */
/* This is dangerous because intervals might not converge when RELTOL is */
/* small. But at least a very small number should be selected so that for */
/* strongly graded matrices, the code can get relatively accurate */
/* eigenvalues. */
atoli = uflow * 4. + *pivmin * 4.;
if (irange == 3) {
/* RANGE='I': Compute an interval containing eigenvalues */
/* IL through IU. The initial interval [GL,GU] from the global */
/* Gerschgorin bounds GL and GU is refined by XDEBZ. */
itmax = (int) ((log(tnorm + *pivmin) - log(*pivmin)) / log(2.)) +
2;
work[*n + 1] = gl;
work[*n + 2] = gl;
work[*n + 3] = gu;
work[*n + 4] = gu;
work[*n + 5] = gl;
work[*n + 6] = gu;
iwork[1] = -1;
iwork[2] = -1;
iwork[3] = *n + 1;
iwork[4] = *n + 1;
iwork[5] = *il - 1;
iwork[6] = *iu;
xdebz_(&c__3, &itmax, n, &c__2, &c__2, &nb, &atoli, &rtoli, pivmin, &
d__[1], &e[1], &e2[1], &iwork[5], &work[*n + 1], &work[*n + 5]
, &iout, &iwork[1], &w[1], &iblock[1], &iinfo);
if (iinfo != 0) {
*info = iinfo;
return 0;
}
/* On exit, output intervals may not be ordered by ascending negcount */
if (iwork[6] == *iu) {
*wl = work[*n + 1];
wlu = work[*n + 3];
nwl = iwork[1];
*wu = work[*n + 4];
wul = work[*n + 2];
nwu = iwork[4];
} else {
*wl = work[*n + 2];
wlu = work[*n + 4];
nwl = iwork[2];
*wu = work[*n + 3];
wul = work[*n + 1];
nwu = iwork[3];
}
/* On exit, the interval [WL, WLU] contains a value with negcount NWL, */
/* and [WUL, WU] contains a value with negcount NWU. */
if (nwl < 0 || nwl >= *n || nwu < 1 || nwu > *n) {
*info = 4;
return 0;
}
} else if (irange == 2) {
*wl = *vl;
*wu = *vu;
} else if (irange == 1) {
*wl = gl;
*wu = gu;
}
/* Find Eigenvalues -- Loop Over blocks and recompute NWL and NWU. */
/* NWL accumulates the number of eigenvalues .le. WL, */
/* NWU accumulates the number of eigenvalues .le. WU */
*m = 0;
iend = 0;
*info = 0;
nwl = 0;
nwu = 0;
i__1 = *nsplit;
for (jblk = 1; jblk <= i__1; ++jblk) {
ioff = iend;
ibegin = ioff + 1;
iend = isplit[jblk];
in = iend - ioff;
if (in == 1) {
/* 1x1 block */
if (*wl >= d__[ibegin] - *pivmin) {
++nwl;
}
if (*wu >= d__[ibegin] - *pivmin) {
++nwu;
}
if (irange == 1 || *wl < d__[ibegin] - *pivmin && *wu >= d__[
ibegin] - *pivmin) {
++(*m);
w[*m] = d__[ibegin];
werr[*m] = 0.;
/* The gap for a single block doesn't matter for the later */
/* algorithm and is assigned an arbitrary large value */
iblock[*m] = jblk;
indexw[*m] = 1;
}
/* Disabled 2x2 case because of a failure on the following matrix */
/* RANGE = 'I', IL = IU = 4 */
/* Original Tridiagonal, d = [ */
/* -0.150102010615740E+00 */
/* -0.849897989384260E+00 */
/* -0.128208148052635E-15 */
/* 0.128257718286320E-15 */
/* ]; */
/* e = [ */
/* -0.357171383266986E+00 */
/* -0.180411241501588E-15 */
/* -0.175152352710251E-15 */
/* ]; */
/* ELSE IF( IN.EQ.2 ) THEN */
/* * 2x2 block */
/* DISC = SQRT( (HALF*(D(IBEGIN)-D(IEND)))**2 + E(IBEGIN)**2 ) */
/* TMP1 = HALF*(D(IBEGIN)+D(IEND)) */
/* L1 = TMP1 - DISC */
/* IF( WL.GE. L1-PIVMIN ) */
/* $ NWL = NWL + 1 */
/* IF( WU.GE. L1-PIVMIN ) */
/* $ NWU = NWU + 1 */
/* IF( IRANGE.EQ.ALLRNG .OR. ( WL.LT.L1-PIVMIN .AND. WU.GE. */
/* $ L1-PIVMIN ) ) THEN */
/* M = M + 1 */
/* W( M ) = L1 */
/* * The uncertainty of eigenvalues of a 2x2 matrix is very small */
/* WERR( M ) = EPS * ABS( W( M ) ) * TWO */
/* IBLOCK( M ) = JBLK */
/* INDEXW( M ) = 1 */
/* ENDIF */
/* L2 = TMP1 + DISC */
/* IF( WL.GE. L2-PIVMIN ) */
/* $ NWL = NWL + 1 */
/* IF( WU.GE. L2-PIVMIN ) */
/* $ NWU = NWU + 1 */
/* IF( IRANGE.EQ.ALLRNG .OR. ( WL.LT.L2-PIVMIN .AND. WU.GE. */
/* $ L2-PIVMIN ) ) THEN */
/* M = M + 1 */
/* W( M ) = L2 */
/* * The uncertainty of eigenvalues of a 2x2 matrix is very small */
/* WERR( M ) = EPS * ABS( W( M ) ) * TWO */
/* IBLOCK( M ) = JBLK */
/* INDEXW( M ) = 2 */
/* ENDIF */
} else {
/* General Case - block of size IN >= 2 */
/* Compute local Gerschgorin interval and use it as the initial */
/* interval for XDEBZ */
gu = d__[ibegin];
gl = d__[ibegin];
tmp1 = 0.;
i__2 = iend;
for (j = ibegin; j <= i__2; ++j) {
/* Computing MIN */
d__1 = gl, d__2 = gers[(j << 1) - 1];
gl = fminl(d__1,d__2);
/* Computing MAX */
d__1 = gu, d__2 = gers[j * 2];
gu = fmaxl(d__1,d__2);
/* L40: */
}
/* [JAN/28/2009] */
/* change SPDIAM by TNORM in lines 2 and 3 thereafter */
/* line 1: remove computation of SPDIAM (not useful anymore) */
/* SPDIAM = GU - GL */
/* GL = GL - FUDGE*SPDIAM*EPS*IN - FUDGE*PIVMIN */
/* GU = GU + FUDGE*SPDIAM*EPS*IN + FUDGE*PIVMIN */
gl = gl - tnorm * 2. * eps * in - *pivmin * 2.;
gu = gu + tnorm * 2. * eps * in + *pivmin * 2.;
if (irange > 1) {
if (gu < *wl) {
/* the local block contains none of the wanted eigenvalues */
nwl += in;
nwu += in;
goto L70;
}
/* refine search interval if possible, only range (WL,WU] matters */
gl = fmaxl(gl,*wl);
gu = fminl(gu,*wu);
if (gl >= gu) {
goto L70;
}
}
/* Find negcount of initial interval boundaries GL and GU */
work[*n + 1] = gl;
work[*n + in + 1] = gu;
xdebz_(&c__1, &c__0, &in, &in, &c__1, &nb, &atoli, &rtoli,
pivmin, &d__[ibegin], &e[ibegin], &e2[ibegin], idumma, &
work[*n + 1], &work[*n + (in << 1) + 1], &im, &iwork[1], &
w[*m + 1], &iblock[*m + 1], &iinfo);
if (iinfo != 0) {
*info = iinfo;
return 0;
}
nwl += iwork[1];
nwu += iwork[in + 1];
iwoff = *m - iwork[1];
/* Compute Eigenvalues */
itmax = (int) ((log(gu - gl + *pivmin) - log(*pivmin)) / log(
2.)) + 2;
xdebz_(&c__2, &itmax, &in, &in, &c__1, &nb, &atoli, &rtoli,
pivmin, &d__[ibegin], &e[ibegin], &e2[ibegin], idumma, &
work[*n + 1], &work[*n + (in << 1) + 1], &iout, &iwork[1],
&w[*m + 1], &iblock[*m + 1], &iinfo);
if (iinfo != 0) {
*info = iinfo;
return 0;
}
/* Copy eigenvalues into W and IBLOCK */
/* Use -JBLK for block number for unconverged eigenvalues. */
/* Loop over the number of output intervals from XDEBZ */
i__2 = iout;
for (j = 1; j <= i__2; ++j) {
/* eigenvalue approximation is middle point of interval */
tmp1 = (work[j + *n] + work[j + in + *n]) * .5;
/* semi length of error interval */
tmp2 = (d__1 = work[j + *n] - work[j + in + *n], fabsl(d__1)) *
.5;
if (j > iout - iinfo) {
/* Flag non-convergence. */
ncnvrg = TRUE_;
ib = -jblk;
} else {
ib = jblk;
}
i__3 = iwork[j + in] + iwoff;
for (je = iwork[j] + 1 + iwoff; je <= i__3; ++je) {
w[je] = tmp1;
werr[je] = tmp2;
indexw[je] = je - iwoff;
iblock[je] = ib;
/* L50: */
}
/* L60: */
}
*m += im;
}
L70:
;
}
/* If RANGE='I', then (WL,WU) contains eigenvalues NWL+1,...,NWU */
/* If NWL+1 < IL or NWU > IU, discard extra eigenvalues. */
if (irange == 3) {
idiscl = *il - 1 - nwl;
idiscu = nwu - *iu;
if (idiscl > 0) {
im = 0;
i__1 = *m;
for (je = 1; je <= i__1; ++je) {
/* Remove some of the smallest eigenvalues from the left so that */
/* at the end IDISCL =0. Move all eigenvalues up to the left. */
if (w[je] <= wlu && idiscl > 0) {
--idiscl;
} else {
++im;
w[im] = w[je];
werr[im] = werr[je];
indexw[im] = indexw[je];
iblock[im] = iblock[je];
}
/* L80: */
}
*m = im;
}
if (idiscu > 0) {
/* Remove some of the largest eigenvalues from the right so that */
/* at the end IDISCU =0. Move all eigenvalues up to the left. */
im = *m + 1;
for (je = *m; je >= 1; --je) {
if (w[je] >= wul && idiscu > 0) {
--idiscu;
} else {
--im;
w[im] = w[je];
werr[im] = werr[je];
indexw[im] = indexw[je];
iblock[im] = iblock[je];
}
/* L81: */
}
jee = 0;
i__1 = *m;
for (je = im; je <= i__1; ++je) {
++jee;
w[jee] = w[je];
werr[jee] = werr[je];
indexw[jee] = indexw[je];
iblock[jee] = iblock[je];
/* L82: */
}
*m = *m - im + 1;
}
if (idiscl > 0 || idiscu > 0) {
/* Code to deal with effects of bad arithmetic. (If N(w) is */
/* monotone non-decreasing, this should never happen.) */
/* Some low eigenvalues to be discarded are not in (WL,WLU], */
/* or high eigenvalues to be discarded are not in (WUL,WU] */
/* so just kill off the smallest IDISCL/largest IDISCU */
/* eigenvalues, by marking the corresponding IBLOCK = 0 */
if (idiscl > 0) {
wkill = *wu;
i__1 = idiscl;
for (jdisc = 1; jdisc <= i__1; ++jdisc) {
iw = 0;
i__2 = *m;
for (je = 1; je <= i__2; ++je) {
if (iblock[je] != 0 && (w[je] < wkill || iw == 0)) {
iw = je;
wkill = w[je];
}
/* L90: */
}
iblock[iw] = 0;
/* L100: */
}
}
if (idiscu > 0) {
wkill = *wl;
i__1 = idiscu;
for (jdisc = 1; jdisc <= i__1; ++jdisc) {
iw = 0;
i__2 = *m;
for (je = 1; je <= i__2; ++je) {
if (iblock[je] != 0 && (w[je] >= wkill || iw == 0)) {
iw = je;
wkill = w[je];
}
/* L110: */
}
iblock[iw] = 0;
/* L120: */
}
}
/* Now erase all eigenvalues with IBLOCK set to zero */
im = 0;
i__1 = *m;
for (je = 1; je <= i__1; ++je) {
if (iblock[je] != 0) {
++im;
w[im] = w[je];
werr[im] = werr[je];
indexw[im] = indexw[je];
iblock[im] = iblock[je];
}
/* L130: */
}
*m = im;
}
if (idiscl < 0 || idiscu < 0) {
toofew = TRUE_;
}
}
if (irange == 1 && *m != *n || irange == 3 && *m != *iu - *il + 1) {
toofew = TRUE_;
}
/* If ORDER='B', do nothing the eigenvalues are already sorted by */
/* block. */
/* If ORDER='E', sort the eigenvalues from smallest to largest */
if (xlsame_(order, "E") && *nsplit > 1) {
i__1 = *m - 1;
for (je = 1; je <= i__1; ++je) {
ie = 0;
tmp1 = w[je];
i__2 = *m;
for (j = je + 1; j <= i__2; ++j) {
if (w[j] < tmp1) {
ie = j;
tmp1 = w[j];
}
/* L140: */
}
if (ie != 0) {
tmp2 = werr[ie];
itmp1 = iblock[ie];
itmp2 = indexw[ie];
w[ie] = w[je];
werr[ie] = werr[je];
iblock[ie] = iblock[je];
indexw[ie] = indexw[je];
w[je] = tmp1;
werr[je] = tmp2;
iblock[je] = itmp1;
indexw[je] = itmp2;
}
/* L150: */
}
}
*info = 0;
if (ncnvrg) {
++(*info);
}
if (toofew) {
*info += 2;
}
return 0;
/* End of XDRRD */
} /* xdrrd_ */
|
the_stack_data/95449354.c |
int ft_fibonacci(int index)
{
if (index < 0)
return (-1);
else if (index == 0)
return (0);
else if (index == 1)
return (1);
else
return(ft_fibonacci(index - 1) + ft_fibonacci(index - 2));
} |
the_stack_data/145454271.c | #include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#define ZYNQ_BASE 0x80000000 //base address for 64 sequence of integer
#define START_RUN_OFFSET 0x00000100 //for start signal
#define STATUS_OFFSET 0x00000104 //for status signal
/*===========================================================================*/
int main(int argc, char *argv[])
{
volatile int fd = open( "/dev/mem", O_RDWR);//volatile是一個變數聲明限定詞,可能會在任何時刻被意外的更新
volatile int map_len = 0x400;
volatile unsigned int* io = (volatile unsigned int *)mmap(NULL, map_len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, ZYNQ_BASE);
/*
NULL :指向欲映射的核心起始位址,NULL代表讓系統自動選定位址
map_len :代表映射的大小。將文件的多大長度映射到記憶體
參數prot :映射區域的保護方式。可以為以下幾種方式的組合:
PROT_EXEC 映射區域可被執行
PROT_READ 映射區域可被讀取
PROT_WRITE 映射區域可被寫入
PROT_NONE 映射區域不能存取
參數flags :影響映射區域的各種特性。在調用mmap()時必須要指定MAP_SHARED 或MAP_PRIVATE。
MAP_SHARED 允許其他映射該文件的行程共享,對映射區域的寫入數據會複製回文件。
MAP_PRIVATE 不允許其他映射該文件的行程共享,對映射區域的寫入操作會產生一個映射的複製(copy-on-write),對此區域所做的修改不會寫回原文件。
fd :要映射到核心中的文件
ZYNQ_BASE :從文件映射開始處的偏移量
*/
int i,j;
int m[64];
int outm[64];
// int cnt;
if(io == MAP_FAILED) {
perror("Mapping memory for absolute memory access failed.\n");
exit(1);
}
printf("Zynq_BASE mapping successful :\n0x%x to 0x%x, size = %d\n", ZYNQ_BASE, (int)io, map_len);
/*
for (i=5;i<64;i++){
m[i] = 0 ;
}
*/
m[0] = 0x3f000000;//0.5
m[1] = 0x3e99999a;//0.3
m[2] = 0x3e800000;//0.25
m[3] = 0x3f4ccccd;//0.8
m[4] = 0x3f19999a;//0.6
m[5] = 0x3fc00000;//1.5
m[6] = 0x3fa00000;//1.25
m[7] = 0x3f400000;//0.75
m[8] = 0x40600000;//3.5
m[9] = 0x40900000;//4.5
m[10] = 0x41200000;//10
m[11] = 0x40280000;//2.625
m[12] = 0x3fe00000;//1.75
m[13] = 0x40f80000;//7.75
m[14] = 0x41b20000;//22.25
m[15] = 0x410c0000;//1.75
printf("Original values:\n");
for (i=0;i<16;i++){
printf("Input %2d = %32x \n",i,m[i]);
// if(i%4==3) putchar(10);
}
printf("// -----------------------------Running!-------------------------------------//\n");
for (i=0;i<16;i++)
*(io+i) = m[i];
for (i=0;i<16;i++)
m[i] = *(io+i);
/*
printf("Values before caculation:\n");
for (i=0;i<16;i++){
printf("%32x ",m[i]);
if(i%4==3) putchar(10);
}
*/
printf("start run\n");
// -------------------------------------------------------------------------
// start run
// -------------------------------------------------------------------------
*(io+(START_RUN_OFFSET/4)) = 1;
*(io+(START_RUN_OFFSET/4)) = 0;
printf("polling busy\n");
// -------------------------------------------------------------------------
// polling busy
// -------------------------------------------------------------------------
while ( *(io+(STATUS_OFFSET/4))!=(volatile unsigned int)0){
printf("0x%x\n",*(io+(STATUS_OFFSET/4)));
}
printf("operation finish\n");
for (i=0;i<64;i++)
outm[i] = *(io+i);
printf("// ------------------------------Finish!-------------------------------------//\n");
printf("Values after caculation:\n");
for (i=1;i<17;i++){
printf("answer %2d = %32x \n",i-1,outm[i]);
// if(i%4==3) putchar(10);
}
munmap((void *)io, map_len);//釋放指標io指向的記憶體空間,並設釋放的記憶體大小
close(fd);
return 0;
}
/*===========================================================================*/
|
the_stack_data/29565.c | #include <stdio.h>
#include <stdlib.h>
struct node{
struct node* prev;
int data;
struct node* next;
};
struct node* head = NULL;
void insert(int x){
struct node* temp = (struct node*) malloc(sizeof(struct node));
temp -> prev = NULL;
temp -> data = x;
temp -> next = NULL;
if(head != NULL){
temp -> next = head;
head -> prev = temp;
}
head = temp;
}
void print(int ck){
struct node* temp1 = head;
if(ck){
while(temp1 != NULL){
printf("%d ", temp1 -> data);
temp1 = temp1 -> next;
}
}
else{
while(temp1 -> next != NULL){
temp1 = temp1 -> next;
}
while(temp1 != NULL){
printf("%d ", temp1 -> data);
temp1 = temp1 -> prev;
}
}
printf("\n");
}
int main(){
int x, i;
for(i = 0; i < 5; i++){
scanf("%d", &x);
insert(x);
print(1);
}
return 0;
}
|
the_stack_data/106792.c | // build it doing: gcc test.c -ldl -otest
#include <stdio.h>
#include <dlfcn.h>
int main()
{
dlopen( "./ngx_mod_harbour.so", RTLD_NOW );
printf( "%s\n", dlerror() );
return 0;
}
|
the_stack_data/380448.c | /**
* \file
* \brief arguments test.
*/
/*
* Copyright (c) 2014, HP Labs.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, Universitaetstr. 6, CH-8092 Zurich. Attn: Systems Group.
*/
#include <stdio.h>
int main(int argc, char *argv[])
{
for (int i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}
|
the_stack_data/9511603.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 1993, 1994, 1995, 1998, 1999, 2000, 2001, 2004, 2007, 2008
Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Please email any bugs, comments, and/or additions to this file to:
[email protected] */
/* Support program for testing gdb's ability to call functions
in the inferior, pass appropriate arguments to those functions,
and get the returned result. */
#ifdef NO_PROTOTYPES
#define PARAMS(paramlist) ()
#else
#define PARAMS(paramlist) paramlist
#endif
# include <stdlib.h>
# include <string.h>
char char_val1 = 'a';
char char_val2 = 'b';
short short_val1 = 10;
short short_val2 = -23;
int int_val1 = 87;
int int_val2 = -26;
long long_val1 = 789;
long long_val2 = -321;
float float_val1 = 3.14159;
float float_val2 = -2.3765;
float float_val3 = 0.25;
float float_val4 = 1.25;
float float_val5 = 2.25;
float float_val6 = 3.25;
float float_val7 = 4.25;
float float_val8 = 5.25;
float float_val9 = 6.25;
float float_val10 = 7.25;
float float_val11 = 8.25;
float float_val12 = 9.25;
float float_val13 = 10.25;
float float_val14 = 11.25;
float float_val15 = 12.25;
double double_val1 = 45.654;
double double_val2 = -67.66;
double double_val3 = 0.25;
double double_val4 = 1.25;
double double_val5 = 2.25;
double double_val6 = 3.25;
double double_val7 = 4.25;
double double_val8 = 5.25;
double double_val9 = 6.25;
double double_val10 = 7.25;
double double_val11 = 8.25;
double double_val12 = 9.25;
double double_val13 = 10.25;
double double_val14 = 11.25;
double double_val15 = 12.25;
#define DELTA (0.001)
char *string_val1 = (char *)"string 1";
char *string_val2 = (char *)"string 2";
char char_array_val1[] = "carray 1";
char char_array_val2[] = "carray 2";
struct struct1 {
char c;
short s;
int i;
long l;
float f;
double d;
char a[4];
} struct_val1 = { 'x', 87, 76, 51, 2.1234, 9.876, "foo" };
/* Some functions that can be passed as arguments to other test
functions, or called directly. */
#ifdef PROTOTYPES
int add (int a, int b)
#else
int add (a, b) int a, b;
#endif
{
return (a + b);
}
#ifdef PROTOTYPES
int doubleit (int a)
#else
int doubleit (a) int a;
#endif
{
return (a + a);
}
int (*func_val1) PARAMS((int,int)) = add;
int (*func_val2) PARAMS((int)) = doubleit;
/* An enumeration and functions that test for specific values. */
enum enumtype { enumval1, enumval2, enumval3 };
enum enumtype enum_val1 = enumval1;
enum enumtype enum_val2 = enumval2;
enum enumtype enum_val3 = enumval3;
#ifdef PROTOTYPES
int t_enum_value1 (enum enumtype enum_arg)
#else
int t_enum_value1 (enum_arg) enum enumtype enum_arg;
#endif
{
return (enum_arg == enum_val1);
}
#ifdef PROTOTYPES
int t_enum_value2 (enum enumtype enum_arg)
#else
int t_enum_value2 (enum_arg) enum enumtype enum_arg;
#endif
{
return (enum_arg == enum_val2);
}
#ifdef PROTOTYPES
int t_enum_value3 (enum enumtype enum_arg)
#else
int t_enum_value3 (enum_arg) enum enumtype enum_arg;
#endif
{
return (enum_arg == enum_val3);
}
/* A function that takes a vector of integers (along with an explicit
count) and returns their sum. */
#ifdef PROTOTYPES
int sum_args (int argc, int argv[])
#else
int sum_args (argc, argv) int argc; int argv[];
#endif
{
int sumval = 0;
int idx;
for (idx = 0; idx < argc; idx++)
{
sumval += argv[idx];
}
return (sumval);
}
/* Test that we can call functions that take structs and return
members from that struct */
#ifdef PROTOTYPES
char t_structs_c (struct struct1 tstruct) { return (tstruct.c); }
short t_structs_s (struct struct1 tstruct) { return (tstruct.s); }
int t_structs_i (struct struct1 tstruct) { return (tstruct.i); }
long t_structs_l (struct struct1 tstruct) { return (tstruct.l); }
float t_structs_f (struct struct1 tstruct) { return (tstruct.f); }
double t_structs_d (struct struct1 tstruct) { return (tstruct.d); }
char *t_structs_a (struct struct1 tstruct)
{
static char buf[8];
strcpy (buf, tstruct.a);
return buf;
}
#else
char t_structs_c (tstruct) struct struct1 tstruct; { return (tstruct.c); }
short t_structs_s (tstruct) struct struct1 tstruct; { return (tstruct.s); }
int t_structs_i (tstruct) struct struct1 tstruct; { return (tstruct.i); }
long t_structs_l (tstruct) struct struct1 tstruct; { return (tstruct.l); }
float t_structs_f (tstruct) struct struct1 tstruct; { return (tstruct.f); }
double t_structs_d (tstruct) struct struct1 tstruct; { return (tstruct.d); }
char *t_structs_a (tstruct) struct struct1 tstruct;
{
static char buf[8];
strcpy (buf, tstruct.a);
return buf;
}
#endif
/* Test that calling functions works if there are a lot of arguments. */
#ifdef PROTOTYPES
int
sum10 (int i0, int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8, int i9)
#else
int
sum10 (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9)
int i0, i1, i2, i3, i4, i5, i6, i7, i8, i9;
#endif
{
return i0 + i1 + i2 + i3 + i4 + i5 + i6 + i7 + i8 + i9;
}
/* Test that args are passed in the right order. */
#ifdef PROTOTYPES
int
cmp10 (int i0, int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8, int i9)
#else
int
cmp10 (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9)
int i0, i1, i2, i3, i4, i5, i6, i7, i8, i9;
#endif
{
return
(i0 == 0) && (i1 == 1) && (i2 == 2) && (i3 == 3) && (i4 == 4) &&
(i5 == 5) && (i6 == 6) && (i7 == 7) && (i8 == 8) && (i9 == 9);
}
/* Functions that expect specific values to be passed and return
either 0 or 1, depending upon whether the values were
passed incorrectly or correctly, respectively. */
#ifdef PROTOTYPES
int t_char_values (char char_arg1, char char_arg2)
#else
int t_char_values (char_arg1, char_arg2)
char char_arg1, char_arg2;
#endif
{
return ((char_arg1 == char_val1) && (char_arg2 == char_val2));
}
int
#ifdef PROTOTYPES
t_small_values (char arg1, short arg2, int arg3, char arg4, short arg5,
char arg6, short arg7, int arg8, short arg9, short arg10)
#else
t_small_values (arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10)
char arg1;
short arg2;
int arg3;
char arg4;
short arg5;
char arg6;
short arg7;
int arg8;
short arg9;
short arg10;
#endif
{
return arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10;
}
#ifdef PROTOTYPES
int t_short_values (short short_arg1, short short_arg2)
#else
int t_short_values (short_arg1, short_arg2)
short short_arg1, short_arg2;
#endif
{
return ((short_arg1 == short_val1) && (short_arg2 == short_val2));
}
#ifdef PROTOTYPES
int t_int_values (int int_arg1, int int_arg2)
#else
int t_int_values (int_arg1, int_arg2)
int int_arg1, int_arg2;
#endif
{
return ((int_arg1 == int_val1) && (int_arg2 == int_val2));
}
#ifdef PROTOTYPES
int t_long_values (long long_arg1, long long_arg2)
#else
int t_long_values (long_arg1, long_arg2)
long long_arg1, long_arg2;
#endif
{
return ((long_arg1 == long_val1) && (long_arg2 == long_val2));
}
/* NOTE: THIS FUNCTION MUST NOT BE PROTOTYPED!!!!!
There must be one version of "t_float_values" (this one)
that is not prototyped, and one (if supported) that is (following).
That way GDB can be tested against both cases. */
int t_float_values (float_arg1, float_arg2)
float float_arg1, float_arg2;
{
return ((float_arg1 - float_val1) < DELTA
&& (float_arg1 - float_val1) > -DELTA
&& (float_arg2 - float_val2) < DELTA
&& (float_arg2 - float_val2) > -DELTA);
}
int
#ifdef NO_PROTOTYPES
/* In this case we are just duplicating t_float_values, but that is the
easiest way to deal with either ANSI or non-ANSI. */
t_float_values2 (float_arg1, float_arg2)
float float_arg1, float_arg2;
#else
t_float_values2 (float float_arg1, float float_arg2)
#endif
{
return ((float_arg1 - float_val1) < DELTA
&& (float_arg1 - float_val1) > -DELTA
&& (float_arg2 - float_val2) < DELTA
&& (float_arg2 - float_val2) > -DELTA);
}
/* This function has many arguments to force some of them to be passed via
the stack instead of registers, to test that GDB can construct correctly
the parameter save area. Note that Linux/ppc32 has 8 float registers to use
for float parameter passing and Linux/ppc64 has 13, so the number of
arguments has to be at least 14 to contemplate these platforms. */
float
#ifdef NO_PROTOTYPES
t_float_many_args (f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13,
f14, f15)
float f1, float f2, float f3, float f4, float f5, float f6, float f7,
float f8, float f9, float f10, float f11, float f12, float f13, float f14,
float f15;
#else
t_float_many_args (float f1, float f2, float f3, float f4, float f5, float f6,
float f7, float f8, float f9, float f10, float f11,
float f12, float f13, float f14, float f15)
#endif
{
float sum_args;
float sum_values;
sum_args = f1 + f2 + f3 + f4 + f5 + f6 + f7 + f8 + f9 + f10 + f11 + f12
+ f13 + f14 + f15;
sum_values = float_val1 + float_val2 + float_val3 + float_val4 + float_val5
+ float_val6 + float_val7 + float_val8 + float_val9
+ float_val10 + float_val11 + float_val12 + float_val13
+ float_val14 + float_val15;
return ((sum_args - sum_values) < DELTA
&& (sum_args - sum_values) > -DELTA);
}
#ifdef PROTOTYPES
int t_double_values (double double_arg1, double double_arg2)
#else
int t_double_values (double_arg1, double_arg2)
double double_arg1, double_arg2;
#endif
{
return ((double_arg1 - double_val1) < DELTA
&& (double_arg1 - double_val1) > -DELTA
&& (double_arg2 - double_val2) < DELTA
&& (double_arg2 - double_val2) > -DELTA);
}
/* This function has many arguments to force some of them to be passed via
the stack instead of registers, to test that GDB can construct correctly
the parameter save area. Note that Linux/ppc32 has 8 float registers to use
for float parameter passing and Linux/ppc64 has 13, so the number of
arguments has to be at least 14 to contemplate these platforms. */
double
#ifdef NO_PROTOTYPES
t_double_many_args (f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13,
f14, f15)
double f1, double f2, double f3, double f4, double f5, double f6,
double f7, double f8, double f9, double f10, double f11, double f12,
double f13, double f14, double f15;
#else
t_double_many_args (double f1, double f2, double f3, double f4, double f5,
double f6, double f7, double f8, double f9, double f10,
double f11, double f12, double f13, double f14, double f15)
#endif
{
double sum_args;
double sum_values;
sum_args = f1 + f2 + f3 + f4 + f5 + f6 + f7 + f8 + f9 + f10 + f11 + f12
+ f13 + f14 + f15;
sum_values = double_val1 + double_val2 + double_val3 + double_val4
+ double_val5 + double_val6 + double_val7 + double_val8
+ double_val9 + double_val10 + double_val11 + double_val12
+ double_val13 + double_val14 + double_val15;
return ((sum_args - sum_values) < DELTA
&& (sum_args - sum_values) > -DELTA);
}
#ifdef PROTOTYPES
int t_string_values (char *string_arg1, char *string_arg2)
#else
int t_string_values (string_arg1, string_arg2)
char *string_arg1, *string_arg2;
#endif
{
return (!strcmp (string_arg1, string_val1) &&
!strcmp (string_arg2, string_val2));
}
#ifdef PROTOTYPES
int t_char_array_values (char char_array_arg1[], char char_array_arg2[])
#else
int t_char_array_values (char_array_arg1, char_array_arg2)
char char_array_arg1[], char_array_arg2[];
#endif
{
return (!strcmp (char_array_arg1, char_array_val1) &&
!strcmp (char_array_arg2, char_array_val2));
}
#ifdef PROTOTYPES
int t_double_int (double double_arg1, int int_arg2)
#else
int t_double_int (double_arg1, int_arg2)
double double_arg1;
int int_arg2;
#endif
{
return ((double_arg1 - int_arg2) < DELTA
&& (double_arg1 - int_arg2) > -DELTA);
}
#ifdef PROTOTYPES
int t_int_double (int int_arg1, double double_arg2)
#else
int t_int_double (int_arg1, double_arg2)
int int_arg1;
double double_arg2;
#endif
{
return ((int_arg1 - double_arg2) < DELTA
&& (int_arg1 - double_arg2) > -DELTA);
}
/* This used to simply compare the function pointer arguments with
known values for func_val1 and func_val2. Doing so is valid ANSI
code, but on some machines (RS6000, HPPA, others?) it may fail when
called directly by GDB.
In a nutshell, it's not possible for GDB to determine when the address
of a function or the address of the function's stub/trampoline should
be passed.
So, to avoid GDB lossage in the common case, we perform calls through the
various function pointers and compare the return values. For the HPPA
at least, this allows the common case to work.
If one wants to try something more complicated, pass the address of
a function accepting a "double" as one of its first 4 arguments. Call
that function indirectly through the function pointer. This would fail
on the HPPA. */
#ifdef PROTOTYPES
int t_func_values (int (*func_arg1)(int, int), int (*func_arg2)(int))
#else
int t_func_values (func_arg1, func_arg2)
int (*func_arg1) PARAMS ((int, int));
int (*func_arg2) PARAMS ((int));
#endif
{
return ((*func_arg1) (5,5) == (*func_val1) (5,5)
&& (*func_arg2) (6) == (*func_val2) (6));
}
#ifdef PROTOTYPES
int t_call_add (int (*func_arg1)(int, int), int a, int b)
#else
int t_call_add (func_arg1, a, b)
int (*func_arg1) PARAMS ((int, int));
int a, b;
#endif
{
return ((*func_arg1)(a, b));
}
/* Gotta have a main to be able to generate a linked, runnable
executable, and also provide a useful place to set a breakpoint. */
int main ()
{
#ifdef usestubs
set_debug_traps();
breakpoint();
#endif
malloc(1);
t_double_values(double_val1, double_val2);
t_structs_c(struct_val1);
return 0 ;
}
|
the_stack_data/165766554.c | #include<stdio.h>
main()
{
int arr[100]={0},n,i,binarynum[100]={0};
scanf("%d",&n);
i=0;
while(n>0)
{
arr[i]=n%2;
n=n/2;
i=i+1;
}
int x=0;
for(int j=i-1;j>=0;j--)
arr[j]=binarynum[x];
x=x++;
}
|
the_stack_data/57949317.c |
#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
#include "sqlite3session.h"
#include <assert.h>
#include <string.h>
#ifndef SQLITE_AMALGAMATION
# include "sqliteInt.h"
# include "vdbeInt.h"
#endif
typedef struct SessionTable SessionTable;
typedef struct SessionChange SessionChange;
typedef struct SessionBuffer SessionBuffer;
typedef struct SessionInput SessionInput;
/*
** Minimum chunk size used by streaming versions of functions.
*/
#ifndef SESSIONS_STRM_CHUNK_SIZE
# ifdef SQLITE_TEST
# define SESSIONS_STRM_CHUNK_SIZE 64
# else
# define SESSIONS_STRM_CHUNK_SIZE 1024
# endif
#endif
static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE;
typedef struct SessionHook SessionHook;
struct SessionHook {
void *pCtx;
int (*xOld)(void*,int,sqlite3_value**);
int (*xNew)(void*,int,sqlite3_value**);
int (*xCount)(void*);
int (*xDepth)(void*);
};
/*
** Session handle structure.
*/
struct sqlite3_session {
sqlite3 *db; /* Database handle session is attached to */
char *zDb; /* Name of database session is attached to */
int bEnableSize; /* True if changeset_size() enabled */
int bEnable; /* True if currently recording */
int bIndirect; /* True if all changes are indirect */
int bAutoAttach; /* True to auto-attach tables */
int rc; /* Non-zero if an error has occurred */
void *pFilterCtx; /* First argument to pass to xTableFilter */
int (*xTableFilter)(void *pCtx, const char *zTab);
i64 nMalloc; /* Number of bytes of data allocated */
i64 nMaxChangesetSize;
sqlite3_value *pZeroBlob; /* Value containing X'' */
sqlite3_session *pNext; /* Next session object on same db. */
SessionTable *pTable; /* List of attached tables */
SessionHook hook; /* APIs to grab new and old data with */
};
/*
** Instances of this structure are used to build strings or binary records.
*/
struct SessionBuffer {
u8 *aBuf; /* Pointer to changeset buffer */
int nBuf; /* Size of buffer aBuf */
int nAlloc; /* Size of allocation containing aBuf */
};
/*
** An object of this type is used internally as an abstraction for
** input data. Input data may be supplied either as a single large buffer
** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
** sqlite3changeset_start_strm()).
*/
struct SessionInput {
int bNoDiscard; /* If true, do not discard in InputBuffer() */
int iCurrent; /* Offset in aData[] of current change */
int iNext; /* Offset in aData[] of next change */
u8 *aData; /* Pointer to buffer containing changeset */
int nData; /* Number of bytes in aData */
SessionBuffer buf; /* Current read buffer */
int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
void *pIn; /* First argument to xInput */
int bEof; /* Set to true after xInput finished */
};
/*
** Structure for changeset iterators.
*/
struct sqlite3_changeset_iter {
SessionInput in; /* Input buffer or stream */
SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
int bPatchset; /* True if this is a patchset */
int bInvert; /* True to invert changeset */
int bSkipEmpty; /* Skip noop UPDATE changes */
int rc; /* Iterator error code */
sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
char *zTab; /* Current table */
int nCol; /* Number of columns in zTab */
int op; /* Current operation */
int bIndirect; /* True if current change was indirect */
u8 *abPK; /* Primary key array */
sqlite3_value **apValue; /* old.* and new.* values */
};
/*
** Each session object maintains a set of the following structures, one
** for each table the session object is monitoring. The structures are
** stored in a linked list starting at sqlite3_session.pTable.
**
** The keys of the SessionTable.aChange[] hash table are all rows that have
** been modified in any way since the session object was attached to the
** table.
**
** The data associated with each hash-table entry is a structure containing
** a subset of the initial values that the modified row contained at the
** start of the session. Or no initial values if the row was inserted.
*/
struct SessionTable {
SessionTable *pNext;
char *zName; /* Local name of table */
int nCol; /* Number of columns in table zName */
int bStat1; /* True if this is sqlite_stat1 */
const char **azCol; /* Column names */
u8 *abPK; /* Array of primary key flags */
int nEntry; /* Total number of entries in hash table */
int nChange; /* Size of apChange[] array */
SessionChange **apChange; /* Hash table buckets */
};
/*
** RECORD FORMAT:
**
** The following record format is similar to (but not compatible with) that
** used in SQLite database files. This format is used as part of the
** change-set binary format, and so must be architecture independent.
**
** Unlike the SQLite database record format, each field is self-contained -
** there is no separation of header and data. Each field begins with a
** single byte describing its type, as follows:
**
** 0x00: Undefined value.
** 0x01: Integer value.
** 0x02: Real value.
** 0x03: Text value.
** 0x04: Blob value.
** 0x05: SQL NULL value.
**
** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
** and so on in sqlite3.h. For undefined and NULL values, the field consists
** only of the single type byte. For other types of values, the type byte
** is followed by:
**
** Text values:
** A varint containing the number of bytes in the value (encoded using
** UTF-8). Followed by a buffer containing the UTF-8 representation
** of the text value. There is no nul terminator.
**
** Blob values:
** A varint containing the number of bytes in the value, followed by
** a buffer containing the value itself.
**
** Integer values:
** An 8-byte big-endian integer value.
**
** Real values:
** An 8-byte big-endian IEEE 754-2008 real value.
**
** Varint values are encoded in the same way as varints in the SQLite
** record format.
**
** CHANGESET FORMAT:
**
** A changeset is a collection of DELETE, UPDATE and INSERT operations on
** one or more tables. Operations on a single table are grouped together,
** but may occur in any order (i.e. deletes, updates and inserts are all
** mixed together).
**
** Each group of changes begins with a table header:
**
** 1 byte: Constant 0x54 (capital 'T')
** Varint: Number of columns in the table.
** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
**
** Followed by one or more changes to the table.
**
** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
** 1 byte: The "indirect-change" flag.
** old.* record: (delete and update only)
** new.* record: (insert and update only)
**
** The "old.*" and "new.*" records, if present, are N field records in the
** format described above under "RECORD FORMAT", where N is the number of
** columns in the table. The i'th field of each record is associated with
** the i'th column of the table, counting from left to right in the order
** in which columns were declared in the CREATE TABLE statement.
**
** The new.* record that is part of each INSERT change contains the values
** that make up the new row. Similarly, the old.* record that is part of each
** DELETE change contains the values that made up the row that was deleted
** from the database. In the changeset format, the records that are part
** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
** fields.
**
** Within the old.* record associated with an UPDATE change, all fields
** associated with table columns that are not PRIMARY KEY columns and are
** not modified by the UPDATE change are set to "undefined". Other fields
** are set to the values that made up the row before the UPDATE that the
** change records took place. Within the new.* record, fields associated
** with table columns modified by the UPDATE change contain the new
** values. Fields associated with table columns that are not modified
** are set to "undefined".
**
** PATCHSET FORMAT:
**
** A patchset is also a collection of changes. It is similar to a changeset,
** but leaves undefined those fields that are not useful if no conflict
** resolution is required when applying the changeset.
**
** Each group of changes begins with a table header:
**
** 1 byte: Constant 0x50 (capital 'P')
** Varint: Number of columns in the table.
** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
**
** Followed by one or more changes to the table.
**
** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
** 1 byte: The "indirect-change" flag.
** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
** full record for INSERT).
**
** As in the changeset format, each field of the single record that is part
** of a patchset change is associated with the correspondingly positioned
** table column, counting from left to right within the CREATE TABLE
** statement.
**
** For a DELETE change, all fields within the record except those associated
** with PRIMARY KEY columns are omitted. The PRIMARY KEY fields contain the
** values identifying the row to delete.
**
** For an UPDATE change, all fields except those associated with PRIMARY KEY
** columns and columns that are modified by the UPDATE are set to "undefined".
** PRIMARY KEY fields contain the values identifying the table row to update,
** and fields associated with modified columns contain the new column values.
**
** The records associated with INSERT changes are in the same format as for
** changesets. It is not possible for a record associated with an INSERT
** change to contain a field set to "undefined".
**
** REBASE BLOB FORMAT:
**
** A rebase blob may be output by sqlite3changeset_apply_v2() and its
** streaming equivalent for use with the sqlite3_rebaser APIs to rebase
** existing changesets. A rebase blob contains one entry for each conflict
** resolved using either the OMIT or REPLACE strategies within the apply_v2()
** call.
**
** The format used for a rebase blob is very similar to that used for
** changesets. All entries related to a single table are grouped together.
**
** Each group of entries begins with a table header in changeset format:
**
** 1 byte: Constant 0x54 (capital 'T')
** Varint: Number of columns in the table.
** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
**
** Followed by one or more entries associated with the table.
**
** 1 byte: Either SQLITE_INSERT (0x12), DELETE (0x09).
** 1 byte: Flag. 0x01 for REPLACE, 0x00 for OMIT.
** record: (in the record format defined above).
**
** In a rebase blob, the first field is set to SQLITE_INSERT if the change
** that caused the conflict was an INSERT or UPDATE, or to SQLITE_DELETE if
** it was a DELETE. The second field is set to 0x01 if the conflict
** resolution strategy was REPLACE, or 0x00 if it was OMIT.
**
** If the change that caused the conflict was a DELETE, then the single
** record is a copy of the old.* record from the original changeset. If it
** was an INSERT, then the single record is a copy of the new.* record. If
** the conflicting change was an UPDATE, then the single record is a copy
** of the new.* record with the PK fields filled in based on the original
** old.* record.
*/
/*
** For each row modified during a session, there exists a single instance of
** this structure stored in a SessionTable.aChange[] hash table.
*/
struct SessionChange {
u8 op; /* One of UPDATE, DELETE, INSERT */
u8 bIndirect; /* True if this change is "indirect" */
int nMaxSize; /* Max size of eventual changeset record */
int nRecord; /* Number of bytes in buffer aRecord[] */
u8 *aRecord; /* Buffer containing old.* record */
SessionChange *pNext; /* For hash-table collisions */
};
/*
** Write a varint with value iVal into the buffer at aBuf. Return the
** number of bytes written.
*/
static int sessionVarintPut(u8 *aBuf, int iVal){
return putVarint32(aBuf, iVal);
}
/*
** Return the number of bytes required to store value iVal as a varint.
*/
static int sessionVarintLen(int iVal){
return sqlite3VarintLen(iVal);
}
/*
** Read a varint value from aBuf[] into *piVal. Return the number of
** bytes read.
*/
static int sessionVarintGet(u8 *aBuf, int *piVal){
return getVarint32(aBuf, *piVal);
}
/* Load an unaligned and unsigned 32-bit integer */
#define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
/*
** Read a 64-bit big-endian integer value from buffer aRec[]. Return
** the value read.
*/
static sqlite3_int64 sessionGetI64(u8 *aRec){
u64 x = SESSION_UINT32(aRec);
u32 y = SESSION_UINT32(aRec+4);
x = (x<<32) + y;
return (sqlite3_int64)x;
}
/*
** Write a 64-bit big-endian integer value to the buffer aBuf[].
*/
static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
aBuf[0] = (i>>56) & 0xFF;
aBuf[1] = (i>>48) & 0xFF;
aBuf[2] = (i>>40) & 0xFF;
aBuf[3] = (i>>32) & 0xFF;
aBuf[4] = (i>>24) & 0xFF;
aBuf[5] = (i>>16) & 0xFF;
aBuf[6] = (i>> 8) & 0xFF;
aBuf[7] = (i>> 0) & 0xFF;
}
/*
** This function is used to serialize the contents of value pValue (see
** comment titled "RECORD FORMAT" above).
**
** If it is non-NULL, the serialized form of the value is written to
** buffer aBuf. *pnWrite is set to the number of bytes written before
** returning. Or, if aBuf is NULL, the only thing this function does is
** set *pnWrite.
**
** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
** within a call to sqlite3_value_text() (may fail if the db is utf-16))
** SQLITE_NOMEM is returned.
*/
static int sessionSerializeValue(
u8 *aBuf, /* If non-NULL, write serialized value here */
sqlite3_value *pValue, /* Value to serialize */
sqlite3_int64 *pnWrite /* IN/OUT: Increment by bytes written */
){
int nByte; /* Size of serialized value in bytes */
if( pValue ){
int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
eType = sqlite3_value_type(pValue);
if( aBuf ) aBuf[0] = eType;
switch( eType ){
case SQLITE_NULL:
nByte = 1;
break;
case SQLITE_INTEGER:
case SQLITE_FLOAT:
if( aBuf ){
/* TODO: SQLite does something special to deal with mixed-endian
** floating point values (e.g. ARM7). This code probably should
** too. */
u64 i;
if( eType==SQLITE_INTEGER ){
i = (u64)sqlite3_value_int64(pValue);
}else{
double r;
assert( sizeof(double)==8 && sizeof(u64)==8 );
r = sqlite3_value_double(pValue);
memcpy(&i, &r, 8);
}
sessionPutI64(&aBuf[1], i);
}
nByte = 9;
break;
default: {
u8 *z;
int n;
int nVarint;
assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
if( eType==SQLITE_TEXT ){
z = (u8 *)sqlite3_value_text(pValue);
}else{
z = (u8 *)sqlite3_value_blob(pValue);
}
n = sqlite3_value_bytes(pValue);
if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
nVarint = sessionVarintLen(n);
if( aBuf ){
sessionVarintPut(&aBuf[1], n);
if( n>0 ) memcpy(&aBuf[nVarint + 1], z, n);
}
nByte = 1 + nVarint + n;
break;
}
}
}else{
nByte = 1;
if( aBuf ) aBuf[0] = '\0';
}
if( pnWrite ) *pnWrite += nByte;
return SQLITE_OK;
}
/*
** Allocate and return a pointer to a buffer nByte bytes in size. If
** pSession is not NULL, increase the sqlite3_session.nMalloc variable
** by the number of bytes allocated.
*/
static void *sessionMalloc64(sqlite3_session *pSession, i64 nByte){
void *pRet = sqlite3_malloc64(nByte);
if( pSession ) pSession->nMalloc += sqlite3_msize(pRet);
return pRet;
}
/*
** Free buffer pFree, which must have been allocated by an earlier
** call to sessionMalloc64(). If pSession is not NULL, decrease the
** sqlite3_session.nMalloc counter by the number of bytes freed.
*/
static void sessionFree(sqlite3_session *pSession, void *pFree){
if( pSession ) pSession->nMalloc -= sqlite3_msize(pFree);
sqlite3_free(pFree);
}
/*
** This macro is used to calculate hash key values for data structures. In
** order to use this macro, the entire data structure must be represented
** as a series of unsigned integers. In order to calculate a hash-key value
** for a data structure represented as three such integers, the macro may
** then be used as follows:
**
** int hash_key_value;
** hash_key_value = HASH_APPEND(0, <value 1>);
** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
**
** In practice, the data structures this macro is used for are the primary
** key values of modified rows.
*/
#define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
/*
** Append the hash of the 64-bit integer passed as the second argument to the
** hash-key value passed as the first. Return the new hash-key value.
*/
static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
h = HASH_APPEND(h, i & 0xFFFFFFFF);
return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
}
/*
** Append the hash of the blob passed via the second and third arguments to
** the hash-key value passed as the first. Return the new hash-key value.
*/
static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
int i;
for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
return h;
}
/*
** Append the hash of the data type passed as the second argument to the
** hash-key value passed as the first. Return the new hash-key value.
*/
static unsigned int sessionHashAppendType(unsigned int h, int eType){
return HASH_APPEND(h, eType);
}
/*
** This function may only be called from within a pre-update callback.
** It calculates a hash based on the primary key values of the old.* or
** new.* row currently available and, assuming no error occurs, writes it to
** *piHash before returning. If the primary key contains one or more NULL
** values, *pbNullPK is set to true before returning.
**
** If an error occurs, an SQLite error code is returned and the final values
** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
** and the output variables are set as described above.
*/
static int sessionPreupdateHash(
sqlite3_session *pSession, /* Session object that owns pTab */
SessionTable *pTab, /* Session table handle */
int bNew, /* True to hash the new.* PK */
int *piHash, /* OUT: Hash value */
int *pbNullPK /* OUT: True if there are NULL values in PK */
){
unsigned int h = 0; /* Hash value to return */
int i; /* Used to iterate through columns */
assert( *pbNullPK==0 );
assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
for(i=0; i<pTab->nCol; i++){
if( pTab->abPK[i] ){
int rc;
int eType;
sqlite3_value *pVal;
if( bNew ){
rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
}else{
rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
}
if( rc!=SQLITE_OK ) return rc;
eType = sqlite3_value_type(pVal);
h = sessionHashAppendType(h, eType);
if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
i64 iVal;
if( eType==SQLITE_INTEGER ){
iVal = sqlite3_value_int64(pVal);
}else{
double rVal = sqlite3_value_double(pVal);
assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
memcpy(&iVal, &rVal, 8);
}
h = sessionHashAppendI64(h, iVal);
}else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
const u8 *z;
int n;
if( eType==SQLITE_TEXT ){
z = (const u8 *)sqlite3_value_text(pVal);
}else{
z = (const u8 *)sqlite3_value_blob(pVal);
}
n = sqlite3_value_bytes(pVal);
if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
h = sessionHashAppendBlob(h, n, z);
}else{
assert( eType==SQLITE_NULL );
assert( pTab->bStat1==0 || i!=1 );
*pbNullPK = 1;
}
}
}
*piHash = (h % pTab->nChange);
return SQLITE_OK;
}
/*
** The buffer that the argument points to contains a serialized SQL value.
** Return the number of bytes of space occupied by the value (including
** the type byte).
*/
static int sessionSerialLen(u8 *a){
int e = *a;
int n;
if( e==0 || e==0xFF ) return 1;
if( e==SQLITE_NULL ) return 1;
if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
return sessionVarintGet(&a[1], &n) + 1 + n;
}
/*
** Based on the primary key values stored in change aRecord, calculate a
** hash key. Assume the has table has nBucket buckets. The hash keys
** calculated by this function are compatible with those calculated by
** sessionPreupdateHash().
**
** The bPkOnly argument is non-zero if the record at aRecord[] is from
** a patchset DELETE. In this case the non-PK fields are omitted entirely.
*/
static unsigned int sessionChangeHash(
SessionTable *pTab, /* Table handle */
int bPkOnly, /* Record consists of PK fields only */
u8 *aRecord, /* Change record */
int nBucket /* Assume this many buckets in hash table */
){
unsigned int h = 0; /* Value to return */
int i; /* Used to iterate through columns */
u8 *a = aRecord; /* Used to iterate through change record */
for(i=0; i<pTab->nCol; i++){
int eType = *a;
int isPK = pTab->abPK[i];
if( bPkOnly && isPK==0 ) continue;
/* It is not possible for eType to be SQLITE_NULL here. The session
** module does not record changes for rows with NULL values stored in
** primary key columns. */
assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
|| eType==SQLITE_TEXT || eType==SQLITE_BLOB
|| eType==SQLITE_NULL || eType==0
);
assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
if( isPK ){
a++;
h = sessionHashAppendType(h, eType);
if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
h = sessionHashAppendI64(h, sessionGetI64(a));
a += 8;
}else{
int n;
a += sessionVarintGet(a, &n);
h = sessionHashAppendBlob(h, n, a);
a += n;
}
}else{
a += sessionSerialLen(a);
}
}
return (h % nBucket);
}
/*
** Arguments aLeft and aRight are pointers to change records for table pTab.
** This function returns true if the two records apply to the same row (i.e.
** have the same values stored in the primary key columns), or false
** otherwise.
*/
static int sessionChangeEqual(
SessionTable *pTab, /* Table used for PK definition */
int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
u8 *aLeft, /* Change record */
int bRightPkOnly, /* True if aRight[] contains PK fields only */
u8 *aRight /* Change record */
){
u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
u8 *a2 = aRight; /* Cursor to iterate through aRight */
int iCol; /* Used to iterate through table columns */
for(iCol=0; iCol<pTab->nCol; iCol++){
if( pTab->abPK[iCol] ){
int n1 = sessionSerialLen(a1);
int n2 = sessionSerialLen(a2);
if( n1!=n2 || memcmp(a1, a2, n1) ){
return 0;
}
a1 += n1;
a2 += n2;
}else{
if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
}
}
return 1;
}
/*
** Arguments aLeft and aRight both point to buffers containing change
** records with nCol columns. This function "merges" the two records into
** a single records which is written to the buffer at *paOut. *paOut is
** then set to point to one byte after the last byte written before
** returning.
**
** The merging of records is done as follows: For each column, if the
** aRight record contains a value for the column, copy the value from
** their. Otherwise, if aLeft contains a value, copy it. If neither
** record contains a value for a given column, then neither does the
** output record.
*/
static void sessionMergeRecord(
u8 **paOut,
int nCol,
u8 *aLeft,
u8 *aRight
){
u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
u8 *a2 = aRight; /* Cursor used to iterate through aRight */
u8 *aOut = *paOut; /* Output cursor */
int iCol; /* Used to iterate from 0 to nCol */
for(iCol=0; iCol<nCol; iCol++){
int n1 = sessionSerialLen(a1);
int n2 = sessionSerialLen(a2);
if( *a2 ){
memcpy(aOut, a2, n2);
aOut += n2;
}else{
memcpy(aOut, a1, n1);
aOut += n1;
}
a1 += n1;
a2 += n2;
}
*paOut = aOut;
}
/*
** This is a helper function used by sessionMergeUpdate().
**
** When this function is called, both *paOne and *paTwo point to a value
** within a change record. Before it returns, both have been advanced so
** as to point to the next value in the record.
**
** If, when this function is called, *paTwo points to a valid value (i.e.
** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
** pointer is returned and *pnVal is set to the number of bytes in the
** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
** set to the number of bytes in the value at *paOne. If *paOne points
** to the "no value" placeholder, *pnVal is set to 1. In other words:
**
** if( *paTwo is valid ) return *paTwo;
** return *paOne;
**
*/
static u8 *sessionMergeValue(
u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
int *pnVal /* OUT: Bytes in returned value */
){
u8 *a1 = *paOne;
u8 *a2 = *paTwo;
u8 *pRet = 0;
int n1;
assert( a1 );
if( a2 ){
int n2 = sessionSerialLen(a2);
if( *a2 ){
*pnVal = n2;
pRet = a2;
}
*paTwo = &a2[n2];
}
n1 = sessionSerialLen(a1);
if( pRet==0 ){
*pnVal = n1;
pRet = a1;
}
*paOne = &a1[n1];
return pRet;
}
/*
** This function is used by changeset_concat() to merge two UPDATE changes
** on the same row.
*/
static int sessionMergeUpdate(
u8 **paOut, /* IN/OUT: Pointer to output buffer */
SessionTable *pTab, /* Table change pertains to */
int bPatchset, /* True if records are patchset records */
u8 *aOldRecord1, /* old.* record for first change */
u8 *aOldRecord2, /* old.* record for second change */
u8 *aNewRecord1, /* new.* record for first change */
u8 *aNewRecord2 /* new.* record for second change */
){
u8 *aOld1 = aOldRecord1;
u8 *aOld2 = aOldRecord2;
u8 *aNew1 = aNewRecord1;
u8 *aNew2 = aNewRecord2;
u8 *aOut = *paOut;
int i;
if( bPatchset==0 ){
int bRequired = 0;
assert( aOldRecord1 && aNewRecord1 );
/* Write the old.* vector first. */
for(i=0; i<pTab->nCol; i++){
int nOld;
u8 *aOld;
int nNew;
u8 *aNew;
aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
if( pTab->abPK[i]==0 ) bRequired = 1;
memcpy(aOut, aOld, nOld);
aOut += nOld;
}else{
*(aOut++) = '\0';
}
}
if( !bRequired ) return 0;
}
/* Write the new.* vector */
aOld1 = aOldRecord1;
aOld2 = aOldRecord2;
aNew1 = aNewRecord1;
aNew2 = aNewRecord2;
for(i=0; i<pTab->nCol; i++){
int nOld;
u8 *aOld;
int nNew;
u8 *aNew;
aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
if( bPatchset==0
&& (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
){
*(aOut++) = '\0';
}else{
memcpy(aOut, aNew, nNew);
aOut += nNew;
}
}
*paOut = aOut;
return 1;
}
/*
** This function is only called from within a pre-update-hook callback.
** It determines if the current pre-update-hook change affects the same row
** as the change stored in argument pChange. If so, it returns true. Otherwise
** if the pre-update-hook does not affect the same row as pChange, it returns
** false.
*/
static int sessionPreupdateEqual(
sqlite3_session *pSession, /* Session object that owns SessionTable */
SessionTable *pTab, /* Table associated with change */
SessionChange *pChange, /* Change to compare to */
int op /* Current pre-update operation */
){
int iCol; /* Used to iterate through columns */
u8 *a = pChange->aRecord; /* Cursor used to scan change record */
assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
for(iCol=0; iCol<pTab->nCol; iCol++){
if( !pTab->abPK[iCol] ){
a += sessionSerialLen(a);
}else{
sqlite3_value *pVal; /* Value returned by preupdate_new/old */
int rc; /* Error code from preupdate_new/old */
int eType = *a++; /* Type of value from change record */
/* The following calls to preupdate_new() and preupdate_old() can not
** fail. This is because they cache their return values, and by the
** time control flows to here they have already been called once from
** within sessionPreupdateHash(). The first two asserts below verify
** this (that the method has already been called). */
if( op==SQLITE_INSERT ){
/* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
}else{
/* assert( db->pPreUpdate->pUnpacked ); */
rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
}
assert( rc==SQLITE_OK );
if( sqlite3_value_type(pVal)!=eType ) return 0;
/* A SessionChange object never has a NULL value in a PK column */
assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
|| eType==SQLITE_BLOB || eType==SQLITE_TEXT
);
if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
i64 iVal = sessionGetI64(a);
a += 8;
if( eType==SQLITE_INTEGER ){
if( sqlite3_value_int64(pVal)!=iVal ) return 0;
}else{
double rVal;
assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
memcpy(&rVal, &iVal, 8);
if( sqlite3_value_double(pVal)!=rVal ) return 0;
}
}else{
int n;
const u8 *z;
a += sessionVarintGet(a, &n);
if( sqlite3_value_bytes(pVal)!=n ) return 0;
if( eType==SQLITE_TEXT ){
z = sqlite3_value_text(pVal);
}else{
z = sqlite3_value_blob(pVal);
}
if( n>0 && memcmp(a, z, n) ) return 0;
a += n;
}
}
}
return 1;
}
/*
** If required, grow the hash table used to store changes on table pTab
** (part of the session pSession). If a fatal OOM error occurs, set the
** session object to failed and return SQLITE_ERROR. Otherwise, return
** SQLITE_OK.
**
** It is possible that a non-fatal OOM error occurs in this function. In
** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
** Growing the hash table in this case is a performance optimization only,
** it is not required for correct operation.
*/
static int sessionGrowHash(
sqlite3_session *pSession, /* For memory accounting. May be NULL */
int bPatchset,
SessionTable *pTab
){
if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
int i;
SessionChange **apNew;
sqlite3_int64 nNew = 2*(sqlite3_int64)(pTab->nChange ? pTab->nChange : 128);
apNew = (SessionChange**)sessionMalloc64(
pSession, sizeof(SessionChange*) * nNew
);
if( apNew==0 ){
if( pTab->nChange==0 ){
return SQLITE_ERROR;
}
return SQLITE_OK;
}
memset(apNew, 0, sizeof(SessionChange *) * nNew);
for(i=0; i<pTab->nChange; i++){
SessionChange *p;
SessionChange *pNext;
for(p=pTab->apChange[i]; p; p=pNext){
int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
pNext = p->pNext;
p->pNext = apNew[iHash];
apNew[iHash] = p;
}
}
sessionFree(pSession, pTab->apChange);
pTab->nChange = nNew;
pTab->apChange = apNew;
}
return SQLITE_OK;
}
/*
** This function queries the database for the names of the columns of table
** zThis, in schema zDb.
**
** Otherwise, if they are not NULL, variable *pnCol is set to the number
** of columns in the database table and variable *pzTab is set to point to a
** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
** point to an array of pointers to column names. And *pabPK (again, if not
** NULL) is set to point to an array of booleans - true if the corresponding
** column is part of the primary key.
**
** For example, if the table is declared as:
**
** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
**
** Then the four output variables are populated as follows:
**
** *pnCol = 4
** *pzTab = "tbl1"
** *pazCol = {"w", "x", "y", "z"}
** *pabPK = {1, 0, 0, 1}
**
** All returned buffers are part of the same single allocation, which must
** be freed using sqlite3_free() by the caller
*/
static int sessionTableInfo(
sqlite3_session *pSession, /* For memory accounting. May be NULL */
sqlite3 *db, /* Database connection */
const char *zDb, /* Name of attached database (e.g. "main") */
const char *zThis, /* Table name */
int *pnCol, /* OUT: number of columns */
const char **pzTab, /* OUT: Copy of zThis */
const char ***pazCol, /* OUT: Array of column names for table */
u8 **pabPK /* OUT: Array of booleans - true for PK col */
){
char *zPragma;
sqlite3_stmt *pStmt;
int rc;
sqlite3_int64 nByte;
int nDbCol = 0;
int nThis;
int i;
u8 *pAlloc = 0;
char **azCol = 0;
u8 *abPK = 0;
assert( pazCol && pabPK );
nThis = sqlite3Strlen30(zThis);
if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
if( rc==SQLITE_OK ){
/* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */
zPragma = sqlite3_mprintf(
"SELECT 0, 'tbl', '', 0, '', 1 UNION ALL "
"SELECT 1, 'idx', '', 0, '', 2 UNION ALL "
"SELECT 2, 'stat', '', 0, '', 0"
);
}else if( rc==SQLITE_ERROR ){
zPragma = sqlite3_mprintf("");
}else{
*pazCol = 0;
*pabPK = 0;
*pnCol = 0;
if( pzTab ) *pzTab = 0;
return rc;
}
}else{
zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
}
if( !zPragma ){
*pazCol = 0;
*pabPK = 0;
*pnCol = 0;
if( pzTab ) *pzTab = 0;
return SQLITE_NOMEM;
}
rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
sqlite3_free(zPragma);
if( rc!=SQLITE_OK ){
*pazCol = 0;
*pabPK = 0;
*pnCol = 0;
if( pzTab ) *pzTab = 0;
return rc;
}
nByte = nThis + 1;
while( SQLITE_ROW==sqlite3_step(pStmt) ){
nByte += sqlite3_column_bytes(pStmt, 1);
nDbCol++;
}
rc = sqlite3_reset(pStmt);
if( rc==SQLITE_OK ){
nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
pAlloc = sessionMalloc64(pSession, nByte);
if( pAlloc==0 ){
rc = SQLITE_NOMEM;
}
}
if( rc==SQLITE_OK ){
azCol = (char **)pAlloc;
pAlloc = (u8 *)&azCol[nDbCol];
abPK = (u8 *)pAlloc;
pAlloc = &abPK[nDbCol];
if( pzTab ){
memcpy(pAlloc, zThis, nThis+1);
*pzTab = (char *)pAlloc;
pAlloc += nThis+1;
}
i = 0;
while( SQLITE_ROW==sqlite3_step(pStmt) ){
int nName = sqlite3_column_bytes(pStmt, 1);
const unsigned char *zName = sqlite3_column_text(pStmt, 1);
if( zName==0 ) break;
memcpy(pAlloc, zName, nName+1);
azCol[i] = (char *)pAlloc;
pAlloc += nName+1;
abPK[i] = sqlite3_column_int(pStmt, 5);
i++;
}
rc = sqlite3_reset(pStmt);
}
/* If successful, populate the output variables. Otherwise, zero them and
** free any allocation made. An error code will be returned in this case.
*/
if( rc==SQLITE_OK ){
*pazCol = (const char **)azCol;
*pabPK = abPK;
*pnCol = nDbCol;
}else{
*pazCol = 0;
*pabPK = 0;
*pnCol = 0;
if( pzTab ) *pzTab = 0;
sessionFree(pSession, azCol);
}
sqlite3_finalize(pStmt);
return rc;
}
/*
** This function is only called from within a pre-update handler for a
** write to table pTab, part of session pSession. If this is the first
** write to this table, initalize the SessionTable.nCol, azCol[] and
** abPK[] arrays accordingly.
**
** If an error occurs, an error code is stored in sqlite3_session.rc and
** non-zero returned. Or, if no error occurs but the table has no primary
** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
** indicate that updates on this table should be ignored. SessionTable.abPK
** is set to NULL in this case.
*/
static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
if( pTab->nCol==0 ){
u8 *abPK;
assert( pTab->azCol==0 || pTab->abPK==0 );
pSession->rc = sessionTableInfo(pSession, pSession->db, pSession->zDb,
pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
);
if( pSession->rc==SQLITE_OK ){
int i;
for(i=0; i<pTab->nCol; i++){
if( abPK[i] ){
pTab->abPK = abPK;
break;
}
}
if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){
pTab->bStat1 = 1;
}
if( pSession->bEnableSize ){
pSession->nMaxChangesetSize += (
1 + sessionVarintLen(pTab->nCol) + pTab->nCol + strlen(pTab->zName)+1
);
}
}
}
return (pSession->rc || pTab->abPK==0);
}
/*
** Versions of the four methods in object SessionHook for use with the
** sqlite_stat1 table. The purpose of this is to substitute a zero-length
** blob each time a NULL value is read from the "idx" column of the
** sqlite_stat1 table.
*/
typedef struct SessionStat1Ctx SessionStat1Ctx;
struct SessionStat1Ctx {
SessionHook hook;
sqlite3_session *pSession;
};
static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){
SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
sqlite3_value *pVal = 0;
int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal);
if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
pVal = p->pSession->pZeroBlob;
}
*ppVal = pVal;
return rc;
}
static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){
SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
sqlite3_value *pVal = 0;
int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal);
if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
pVal = p->pSession->pZeroBlob;
}
*ppVal = pVal;
return rc;
}
static int sessionStat1Count(void *pCtx){
SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
return p->hook.xCount(p->hook.pCtx);
}
static int sessionStat1Depth(void *pCtx){
SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
return p->hook.xDepth(p->hook.pCtx);
}
static int sessionUpdateMaxSize(
int op,
sqlite3_session *pSession, /* Session object pTab is attached to */
SessionTable *pTab, /* Table that change applies to */
SessionChange *pC /* Update pC->nMaxSize */
){
i64 nNew = 2;
if( pC->op==SQLITE_INSERT ){
if( op!=SQLITE_DELETE ){
int ii;
for(ii=0; ii<pTab->nCol; ii++){
sqlite3_value *p = 0;
pSession->hook.xNew(pSession->hook.pCtx, ii, &p);
sessionSerializeValue(0, p, &nNew);
}
}
}else if( op==SQLITE_DELETE ){
nNew += pC->nRecord;
if( sqlite3_preupdate_blobwrite(pSession->db)>=0 ){
nNew += pC->nRecord;
}
}else{
int ii;
u8 *pCsr = pC->aRecord;
for(ii=0; ii<pTab->nCol; ii++){
int bChanged = 1;
int nOld = 0;
int eType;
sqlite3_value *p = 0;
pSession->hook.xNew(pSession->hook.pCtx, ii, &p);
if( p==0 ){
return SQLITE_NOMEM;
}
eType = *pCsr++;
switch( eType ){
case SQLITE_NULL:
bChanged = sqlite3_value_type(p)!=SQLITE_NULL;
break;
case SQLITE_FLOAT:
case SQLITE_INTEGER: {
if( eType==sqlite3_value_type(p) ){
sqlite3_int64 iVal = sessionGetI64(pCsr);
if( eType==SQLITE_INTEGER ){
bChanged = (iVal!=sqlite3_value_int64(p));
}else{
double dVal;
memcpy(&dVal, &iVal, 8);
bChanged = (dVal!=sqlite3_value_double(p));
}
}
nOld = 8;
pCsr += 8;
break;
}
default: {
int nByte;
nOld = sessionVarintGet(pCsr, &nByte);
pCsr += nOld;
nOld += nByte;
assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
if( eType==sqlite3_value_type(p)
&& nByte==sqlite3_value_bytes(p)
&& (nByte==0 || 0==memcmp(pCsr, sqlite3_value_blob(p), nByte))
){
bChanged = 0;
}
pCsr += nByte;
break;
}
}
if( bChanged && pTab->abPK[ii] ){
nNew = pC->nRecord + 2;
break;
}
if( bChanged ){
nNew += 1 + nOld;
sessionSerializeValue(0, p, &nNew);
}else if( pTab->abPK[ii] ){
nNew += 2 + nOld;
}else{
nNew += 2;
}
}
}
if( nNew>pC->nMaxSize ){
int nIncr = nNew - pC->nMaxSize;
pC->nMaxSize = nNew;
pSession->nMaxChangesetSize += nIncr;
}
return SQLITE_OK;
}
/*
** This function is only called from with a pre-update-hook reporting a
** change on table pTab (attached to session pSession). The type of change
** (UPDATE, INSERT, DELETE) is specified by the first argument.
**
** Unless one is already present or an error occurs, an entry is added
** to the changed-rows hash table associated with table pTab.
*/
static void sessionPreupdateOneChange(
int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
sqlite3_session *pSession, /* Session object pTab is attached to */
SessionTable *pTab /* Table that change applies to */
){
int iHash;
int bNull = 0;
int rc = SQLITE_OK;
SessionStat1Ctx stat1 = {{0,0,0,0,0},0};
if( pSession->rc ) return;
/* Load table details if required */
if( sessionInitTable(pSession, pTab) ) return;
/* Check the number of columns in this xPreUpdate call matches the
** number of columns in the table. */
if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
pSession->rc = SQLITE_SCHEMA;
return;
}
/* Grow the hash table if required */
if( sessionGrowHash(pSession, 0, pTab) ){
pSession->rc = SQLITE_NOMEM;
return;
}
if( pTab->bStat1 ){
stat1.hook = pSession->hook;
stat1.pSession = pSession;
pSession->hook.pCtx = (void*)&stat1;
pSession->hook.xNew = sessionStat1New;
pSession->hook.xOld = sessionStat1Old;
pSession->hook.xCount = sessionStat1Count;
pSession->hook.xDepth = sessionStat1Depth;
if( pSession->pZeroBlob==0 ){
sqlite3_value *p = sqlite3ValueNew(0);
if( p==0 ){
rc = SQLITE_NOMEM;
goto error_out;
}
sqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC);
pSession->pZeroBlob = p;
}
}
/* Calculate the hash-key for this change. If the primary key of the row
** includes a NULL value, exit early. Such changes are ignored by the
** session module. */
rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
if( rc!=SQLITE_OK ) goto error_out;
if( bNull==0 ){
/* Search the hash table for an existing record for this row. */
SessionChange *pC;
for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
}
if( pC==0 ){
/* Create a new change object containing all the old values (if
** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
** values (if this is an INSERT). */
sqlite3_int64 nByte; /* Number of bytes to allocate */
int i; /* Used to iterate through columns */
assert( rc==SQLITE_OK );
pTab->nEntry++;
/* Figure out how large an allocation is required */
nByte = sizeof(SessionChange);
for(i=0; i<pTab->nCol; i++){
sqlite3_value *p = 0;
if( op!=SQLITE_INSERT ){
TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
assert( trc==SQLITE_OK );
}else if( pTab->abPK[i] ){
TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
assert( trc==SQLITE_OK );
}
/* This may fail if SQLite value p contains a utf-16 string that must
** be converted to utf-8 and an OOM error occurs while doing so. */
rc = sessionSerializeValue(0, p, &nByte);
if( rc!=SQLITE_OK ) goto error_out;
}
/* Allocate the change object */
pC = (SessionChange *)sessionMalloc64(pSession, nByte);
if( !pC ){
rc = SQLITE_NOMEM;
goto error_out;
}else{
memset(pC, 0, sizeof(SessionChange));
pC->aRecord = (u8 *)&pC[1];
}
/* Populate the change object. None of the preupdate_old(),
** preupdate_new() or SerializeValue() calls below may fail as all
** required values and encodings have already been cached in memory.
** It is not possible for an OOM to occur in this block. */
nByte = 0;
for(i=0; i<pTab->nCol; i++){
sqlite3_value *p = 0;
if( op!=SQLITE_INSERT ){
pSession->hook.xOld(pSession->hook.pCtx, i, &p);
}else if( pTab->abPK[i] ){
pSession->hook.xNew(pSession->hook.pCtx, i, &p);
}
sessionSerializeValue(&pC->aRecord[nByte], p, &nByte);
}
/* Add the change to the hash-table */
if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
pC->bIndirect = 1;
}
pC->nRecord = nByte;
pC->op = op;
pC->pNext = pTab->apChange[iHash];
pTab->apChange[iHash] = pC;
}else if( pC->bIndirect ){
/* If the existing change is considered "indirect", but this current
** change is "direct", mark the change object as direct. */
if( pSession->hook.xDepth(pSession->hook.pCtx)==0
&& pSession->bIndirect==0
){
pC->bIndirect = 0;
}
}
assert( rc==SQLITE_OK );
if( pSession->bEnableSize ){
rc = sessionUpdateMaxSize(op, pSession, pTab, pC);
}
}
/* If an error has occurred, mark the session object as failed. */
error_out:
if( pTab->bStat1 ){
pSession->hook = stat1.hook;
}
if( rc!=SQLITE_OK ){
pSession->rc = rc;
}
}
static int sessionFindTable(
sqlite3_session *pSession,
const char *zName,
SessionTable **ppTab
){
int rc = SQLITE_OK;
int nName = sqlite3Strlen30(zName);
SessionTable *pRet;
/* Search for an existing table */
for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
}
if( pRet==0 && pSession->bAutoAttach ){
/* If there is a table-filter configured, invoke it. If it returns 0,
** do not automatically add the new table. */
if( pSession->xTableFilter==0
|| pSession->xTableFilter(pSession->pFilterCtx, zName)
){
rc = sqlite3session_attach(pSession, zName);
if( rc==SQLITE_OK ){
pRet = pSession->pTable;
while( ALWAYS(pRet) && pRet->pNext ){
pRet = pRet->pNext;
}
assert( pRet!=0 );
assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
}
}
}
assert( rc==SQLITE_OK || pRet==0 );
*ppTab = pRet;
return rc;
}
/*
** The 'pre-update' hook registered by this module with SQLite databases.
*/
static void xPreUpdate(
void *pCtx, /* Copy of third arg to preupdate_hook() */
sqlite3 *db, /* Database handle */
int op, /* SQLITE_UPDATE, DELETE or INSERT */
char const *zDb, /* Database name */
char const *zName, /* Table name */
sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
){
sqlite3_session *pSession;
int nDb = sqlite3Strlen30(zDb);
assert( sqlite3_mutex_held(db->mutex) );
for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
SessionTable *pTab;
/* If this session is attached to a different database ("main", "temp"
** etc.), or if it is not currently enabled, there is nothing to do. Skip
** to the next session object attached to this database. */
if( pSession->bEnable==0 ) continue;
if( pSession->rc ) continue;
if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
pSession->rc = sessionFindTable(pSession, zName, &pTab);
if( pTab ){
assert( pSession->rc==SQLITE_OK );
sessionPreupdateOneChange(op, pSession, pTab);
if( op==SQLITE_UPDATE ){
sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
}
}
}
}
/*
** The pre-update hook implementations.
*/
static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
}
static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
}
static int sessionPreupdateCount(void *pCtx){
return sqlite3_preupdate_count((sqlite3*)pCtx);
}
static int sessionPreupdateDepth(void *pCtx){
return sqlite3_preupdate_depth((sqlite3*)pCtx);
}
/*
** Install the pre-update hooks on the session object passed as the only
** argument.
*/
static void sessionPreupdateHooks(
sqlite3_session *pSession
){
pSession->hook.pCtx = (void*)pSession->db;
pSession->hook.xOld = sessionPreupdateOld;
pSession->hook.xNew = sessionPreupdateNew;
pSession->hook.xCount = sessionPreupdateCount;
pSession->hook.xDepth = sessionPreupdateDepth;
}
typedef struct SessionDiffCtx SessionDiffCtx;
struct SessionDiffCtx {
sqlite3_stmt *pStmt;
int nOldOff;
};
/*
** The diff hook implementations.
*/
static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
*ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
return SQLITE_OK;
}
static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
*ppVal = sqlite3_column_value(p->pStmt, iVal);
return SQLITE_OK;
}
static int sessionDiffCount(void *pCtx){
SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
}
static int sessionDiffDepth(void *pCtx){
return 0;
}
/*
** Install the diff hooks on the session object passed as the only
** argument.
*/
static void sessionDiffHooks(
sqlite3_session *pSession,
SessionDiffCtx *pDiffCtx
){
pSession->hook.pCtx = (void*)pDiffCtx;
pSession->hook.xOld = sessionDiffOld;
pSession->hook.xNew = sessionDiffNew;
pSession->hook.xCount = sessionDiffCount;
pSession->hook.xDepth = sessionDiffDepth;
}
static char *sessionExprComparePK(
int nCol,
const char *zDb1, const char *zDb2,
const char *zTab,
const char **azCol, u8 *abPK
){
int i;
const char *zSep = "";
char *zRet = 0;
for(i=0; i<nCol; i++){
if( abPK[i] ){
zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
);
zSep = " AND ";
if( zRet==0 ) break;
}
}
return zRet;
}
static char *sessionExprCompareOther(
int nCol,
const char *zDb1, const char *zDb2,
const char *zTab,
const char **azCol, u8 *abPK
){
int i;
const char *zSep = "";
char *zRet = 0;
int bHave = 0;
for(i=0; i<nCol; i++){
if( abPK[i]==0 ){
bHave = 1;
zRet = sqlite3_mprintf(
"%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
);
zSep = " OR ";
if( zRet==0 ) break;
}
}
if( bHave==0 ){
assert( zRet==0 );
zRet = sqlite3_mprintf("0");
}
return zRet;
}
static char *sessionSelectFindNew(
int nCol,
const char *zDb1, /* Pick rows in this db only */
const char *zDb2, /* But not in this one */
const char *zTbl, /* Table name */
const char *zExpr
){
char *zRet = sqlite3_mprintf(
"SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
" SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
")",
zDb1, zTbl, zDb2, zTbl, zExpr
);
return zRet;
}
static int sessionDiffFindNew(
int op,
sqlite3_session *pSession,
SessionTable *pTab,
const char *zDb1,
const char *zDb2,
char *zExpr
){
int rc = SQLITE_OK;
char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
if( zStmt==0 ){
rc = SQLITE_NOMEM;
}else{
sqlite3_stmt *pStmt;
rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
if( rc==SQLITE_OK ){
SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
pDiffCtx->pStmt = pStmt;
pDiffCtx->nOldOff = 0;
while( SQLITE_ROW==sqlite3_step(pStmt) ){
sessionPreupdateOneChange(op, pSession, pTab);
}
rc = sqlite3_finalize(pStmt);
}
sqlite3_free(zStmt);
}
return rc;
}
static int sessionDiffFindModified(
sqlite3_session *pSession,
SessionTable *pTab,
const char *zFrom,
const char *zExpr
){
int rc = SQLITE_OK;
char *zExpr2 = sessionExprCompareOther(pTab->nCol,
pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
);
if( zExpr2==0 ){
rc = SQLITE_NOMEM;
}else{
char *zStmt = sqlite3_mprintf(
"SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
);
if( zStmt==0 ){
rc = SQLITE_NOMEM;
}else{
sqlite3_stmt *pStmt;
rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
if( rc==SQLITE_OK ){
SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
pDiffCtx->pStmt = pStmt;
pDiffCtx->nOldOff = pTab->nCol;
while( SQLITE_ROW==sqlite3_step(pStmt) ){
sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
}
rc = sqlite3_finalize(pStmt);
}
sqlite3_free(zStmt);
}
}
return rc;
}
int sqlite3session_diff(
sqlite3_session *pSession,
const char *zFrom,
const char *zTbl,
char **pzErrMsg
){
const char *zDb = pSession->zDb;
int rc = pSession->rc;
SessionDiffCtx d;
memset(&d, 0, sizeof(d));
sessionDiffHooks(pSession, &d);
sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
if( pzErrMsg ) *pzErrMsg = 0;
if( rc==SQLITE_OK ){
char *zExpr = 0;
sqlite3 *db = pSession->db;
SessionTable *pTo; /* Table zTbl */
/* Locate and if necessary initialize the target table object */
rc = sessionFindTable(pSession, zTbl, &pTo);
if( pTo==0 ) goto diff_out;
if( sessionInitTable(pSession, pTo) ){
rc = pSession->rc;
goto diff_out;
}
/* Check the table schemas match */
if( rc==SQLITE_OK ){
int bHasPk = 0;
int bMismatch = 0;
int nCol; /* Columns in zFrom.zTbl */
u8 *abPK;
const char **azCol = 0;
rc = sessionTableInfo(0, db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
if( rc==SQLITE_OK ){
if( pTo->nCol!=nCol ){
bMismatch = 1;
}else{
int i;
for(i=0; i<nCol; i++){
if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
if( abPK[i] ) bHasPk = 1;
}
}
}
sqlite3_free((char*)azCol);
if( bMismatch ){
if( pzErrMsg ){
*pzErrMsg = sqlite3_mprintf("table schemas do not match");
}
rc = SQLITE_SCHEMA;
}
if( bHasPk==0 ){
/* Ignore tables with no primary keys */
goto diff_out;
}
}
if( rc==SQLITE_OK ){
zExpr = sessionExprComparePK(pTo->nCol,
zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
);
}
/* Find new rows */
if( rc==SQLITE_OK ){
rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
}
/* Find old rows */
if( rc==SQLITE_OK ){
rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
}
/* Find modified rows */
if( rc==SQLITE_OK ){
rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
}
sqlite3_free(zExpr);
}
diff_out:
sessionPreupdateHooks(pSession);
sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
return rc;
}
/*
** Create a session object. This session object will record changes to
** database zDb attached to connection db.
*/
int sqlite3session_create(
sqlite3 *db, /* Database handle */
const char *zDb, /* Name of db (e.g. "main") */
sqlite3_session **ppSession /* OUT: New session object */
){
sqlite3_session *pNew; /* Newly allocated session object */
sqlite3_session *pOld; /* Session object already attached to db */
int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
/* Zero the output value in case an error occurs. */
*ppSession = 0;
/* Allocate and populate the new session object. */
pNew = (sqlite3_session *)sqlite3_malloc64(sizeof(sqlite3_session) + nDb + 1);
if( !pNew ) return SQLITE_NOMEM;
memset(pNew, 0, sizeof(sqlite3_session));
pNew->db = db;
pNew->zDb = (char *)&pNew[1];
pNew->bEnable = 1;
memcpy(pNew->zDb, zDb, nDb+1);
sessionPreupdateHooks(pNew);
/* Add the new session object to the linked list of session objects
** attached to database handle $db. Do this under the cover of the db
** handle mutex. */
sqlite3_mutex_enter(sqlite3_db_mutex(db));
pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
pNew->pNext = pOld;
sqlite3_mutex_leave(sqlite3_db_mutex(db));
*ppSession = pNew;
return SQLITE_OK;
}
/*
** Free the list of table objects passed as the first argument. The contents
** of the changed-rows hash tables are also deleted.
*/
static void sessionDeleteTable(sqlite3_session *pSession, SessionTable *pList){
SessionTable *pNext;
SessionTable *pTab;
for(pTab=pList; pTab; pTab=pNext){
int i;
pNext = pTab->pNext;
for(i=0; i<pTab->nChange; i++){
SessionChange *p;
SessionChange *pNextChange;
for(p=pTab->apChange[i]; p; p=pNextChange){
pNextChange = p->pNext;
sessionFree(pSession, p);
}
}
sessionFree(pSession, (char*)pTab->azCol); /* cast works around VC++ bug */
sessionFree(pSession, pTab->apChange);
sessionFree(pSession, pTab);
}
}
/*
** Delete a session object previously allocated using sqlite3session_create().
*/
void sqlite3session_delete(sqlite3_session *pSession){
sqlite3 *db = pSession->db;
sqlite3_session *pHead;
sqlite3_session **pp;
/* Unlink the session from the linked list of sessions attached to the
** database handle. Hold the db mutex while doing so. */
sqlite3_mutex_enter(sqlite3_db_mutex(db));
pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
if( (*pp)==pSession ){
*pp = (*pp)->pNext;
if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
break;
}
}
sqlite3_mutex_leave(sqlite3_db_mutex(db));
sqlite3ValueFree(pSession->pZeroBlob);
/* Delete all attached table objects. And the contents of their
** associated hash-tables. */
sessionDeleteTable(pSession, pSession->pTable);
/* Assert that all allocations have been freed and then free the
** session object itself. */
assert( pSession->nMalloc==0 );
sqlite3_free(pSession);
}
/*
** Set a table filter on a Session Object.
*/
void sqlite3session_table_filter(
sqlite3_session *pSession,
int(*xFilter)(void*, const char*),
void *pCtx /* First argument passed to xFilter */
){
pSession->bAutoAttach = 1;
pSession->pFilterCtx = pCtx;
pSession->xTableFilter = xFilter;
}
/*
** Attach a table to a session. All subsequent changes made to the table
** while the session object is enabled will be recorded.
**
** Only tables that have a PRIMARY KEY defined may be attached. It does
** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
** or not.
*/
int sqlite3session_attach(
sqlite3_session *pSession, /* Session object */
const char *zName /* Table name */
){
int rc = SQLITE_OK;
sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
if( !zName ){
pSession->bAutoAttach = 1;
}else{
SessionTable *pTab; /* New table object (if required) */
int nName; /* Number of bytes in string zName */
/* First search for an existing entry. If one is found, this call is
** a no-op. Return early. */
nName = sqlite3Strlen30(zName);
for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
}
if( !pTab ){
/* Allocate new SessionTable object. */
int nByte = sizeof(SessionTable) + nName + 1;
pTab = (SessionTable*)sessionMalloc64(pSession, nByte);
if( !pTab ){
rc = SQLITE_NOMEM;
}else{
/* Populate the new SessionTable object and link it into the list.
** The new object must be linked onto the end of the list, not
** simply added to the start of it in order to ensure that tables
** appear in the correct order when a changeset or patchset is
** eventually generated. */
SessionTable **ppTab;
memset(pTab, 0, sizeof(SessionTable));
pTab->zName = (char *)&pTab[1];
memcpy(pTab->zName, zName, nName+1);
for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
*ppTab = pTab;
}
}
}
sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
return rc;
}
/*
** Ensure that there is room in the buffer to append nByte bytes of data.
** If not, use sqlite3_realloc() to grow the buffer so that there is.
**
** If successful, return zero. Otherwise, if an OOM condition is encountered,
** set *pRc to SQLITE_NOMEM and return non-zero.
*/
static int sessionBufferGrow(SessionBuffer *p, i64 nByte, int *pRc){
#define SESSION_MAX_BUFFER_SZ (0x7FFFFF00 - 1)
i64 nReq = p->nBuf + nByte;
if( *pRc==SQLITE_OK && nReq>p->nAlloc ){
u8 *aNew;
i64 nNew = p->nAlloc ? p->nAlloc : 128;
do {
nNew = nNew*2;
}while( nNew<nReq );
/* The value of SESSION_MAX_BUFFER_SZ is copied from the implementation
** of sqlite3_realloc64(). Allocations greater than this size in bytes
** always fail. It is used here to ensure that this routine can always
** allocate up to this limit - instead of up to the largest power of
** two smaller than the limit. */
if( nNew>SESSION_MAX_BUFFER_SZ ){
nNew = SESSION_MAX_BUFFER_SZ;
if( nNew<nReq ){
*pRc = SQLITE_NOMEM;
return 1;
}
}
aNew = (u8 *)sqlite3_realloc64(p->aBuf, nNew);
if( 0==aNew ){
*pRc = SQLITE_NOMEM;
}else{
p->aBuf = aNew;
p->nAlloc = nNew;
}
}
return (*pRc!=SQLITE_OK);
}
/*
** Append the value passed as the second argument to the buffer passed
** as the first.
**
** This function is a no-op if *pRc is non-zero when it is called.
** Otherwise, if an error occurs, *pRc is set to an SQLite error code
** before returning.
*/
static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
int rc = *pRc;
if( rc==SQLITE_OK ){
sqlite3_int64 nByte = 0;
rc = sessionSerializeValue(0, pVal, &nByte);
sessionBufferGrow(p, nByte, &rc);
if( rc==SQLITE_OK ){
rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
p->nBuf += nByte;
}else{
*pRc = rc;
}
}
}
/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwise, append a single byte to the buffer.
**
** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
** returning.
*/
static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
if( 0==sessionBufferGrow(p, 1, pRc) ){
p->aBuf[p->nBuf++] = v;
}
}
/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwise, append a single varint to the buffer.
**
** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
** returning.
*/
static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
if( 0==sessionBufferGrow(p, 9, pRc) ){
p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
}
}
/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwise, append a blob of data to the buffer.
**
** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
** returning.
*/
static void sessionAppendBlob(
SessionBuffer *p,
const u8 *aBlob,
int nBlob,
int *pRc
){
if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
p->nBuf += nBlob;
}
}
/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwise, append a string to the buffer. All bytes in the string
** up to (but not including) the nul-terminator are written to the buffer.
**
** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
** returning.
*/
static void sessionAppendStr(
SessionBuffer *p,
const char *zStr,
int *pRc
){
int nStr = sqlite3Strlen30(zStr);
if( 0==sessionBufferGrow(p, nStr, pRc) ){
memcpy(&p->aBuf[p->nBuf], zStr, nStr);
p->nBuf += nStr;
}
}
/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwise, append the string representation of integer iVal
** to the buffer. No nul-terminator is written.
**
** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
** returning.
*/
static void sessionAppendInteger(
SessionBuffer *p, /* Buffer to append to */
int iVal, /* Value to write the string rep. of */
int *pRc /* IN/OUT: Error code */
){
char aBuf[24];
sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
sessionAppendStr(p, aBuf, pRc);
}
/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwise, append the string zStr enclosed in quotes (") and
** with any embedded quote characters escaped to the buffer. No
** nul-terminator byte is written.
**
** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
** returning.
*/
static void sessionAppendIdent(
SessionBuffer *p, /* Buffer to a append to */
const char *zStr, /* String to quote, escape and append */
int *pRc /* IN/OUT: Error code */
){
int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
if( 0==sessionBufferGrow(p, nStr, pRc) ){
char *zOut = (char *)&p->aBuf[p->nBuf];
const char *zIn = zStr;
*zOut++ = '"';
while( *zIn ){
if( *zIn=='"' ) *zOut++ = '"';
*zOut++ = *(zIn++);
}
*zOut++ = '"';
p->nBuf = (int)((u8 *)zOut - p->aBuf);
}
}
/*
** This function is a no-op if *pRc is other than SQLITE_OK when it is
** called. Otherwse, it appends the serialized version of the value stored
** in column iCol of the row that SQL statement pStmt currently points
** to to the buffer.
*/
static void sessionAppendCol(
SessionBuffer *p, /* Buffer to append to */
sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
int iCol, /* Column to read value from */
int *pRc /* IN/OUT: Error code */
){
if( *pRc==SQLITE_OK ){
int eType = sqlite3_column_type(pStmt, iCol);
sessionAppendByte(p, (u8)eType, pRc);
if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
sqlite3_int64 i;
u8 aBuf[8];
if( eType==SQLITE_INTEGER ){
i = sqlite3_column_int64(pStmt, iCol);
}else{
double r = sqlite3_column_double(pStmt, iCol);
memcpy(&i, &r, 8);
}
sessionPutI64(aBuf, i);
sessionAppendBlob(p, aBuf, 8, pRc);
}
if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
u8 *z;
int nByte;
if( eType==SQLITE_BLOB ){
z = (u8 *)sqlite3_column_blob(pStmt, iCol);
}else{
z = (u8 *)sqlite3_column_text(pStmt, iCol);
}
nByte = sqlite3_column_bytes(pStmt, iCol);
if( z || (eType==SQLITE_BLOB && nByte==0) ){
sessionAppendVarint(p, nByte, pRc);
sessionAppendBlob(p, z, nByte, pRc);
}else{
*pRc = SQLITE_NOMEM;
}
}
}
}
/*
**
** This function appends an update change to the buffer (see the comments
** under "CHANGESET FORMAT" at the top of the file). An update change
** consists of:
**
** 1 byte: SQLITE_UPDATE (0x17)
** n bytes: old.* record (see RECORD FORMAT)
** m bytes: new.* record (see RECORD FORMAT)
**
** The SessionChange object passed as the third argument contains the
** values that were stored in the row when the session began (the old.*
** values). The statement handle passed as the second argument points
** at the current version of the row (the new.* values).
**
** If all of the old.* values are equal to their corresponding new.* value
** (i.e. nothing has changed), then no data at all is appended to the buffer.
**
** Otherwise, the old.* record contains all primary key values and the
** original values of any fields that have been modified. The new.* record
** contains the new values of only those fields that have been modified.
*/
static int sessionAppendUpdate(
SessionBuffer *pBuf, /* Buffer to append to */
int bPatchset, /* True for "patchset", 0 for "changeset" */
sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
SessionChange *p, /* Object containing old values */
u8 *abPK /* Boolean array - true for PK columns */
){
int rc = SQLITE_OK;
SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
int bNoop = 1; /* Set to zero if any values are modified */
int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
int i; /* Used to iterate through columns */
u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
assert( abPK!=0 );
sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
sessionAppendByte(pBuf, p->bIndirect, &rc);
for(i=0; i<sqlite3_column_count(pStmt); i++){
int bChanged = 0;
int nAdvance;
int eType = *pCsr;
switch( eType ){
case SQLITE_NULL:
nAdvance = 1;
if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
bChanged = 1;
}
break;
case SQLITE_FLOAT:
case SQLITE_INTEGER: {
nAdvance = 9;
if( eType==sqlite3_column_type(pStmt, i) ){
sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
if( eType==SQLITE_INTEGER ){
if( iVal==sqlite3_column_int64(pStmt, i) ) break;
}else{
double dVal;
memcpy(&dVal, &iVal, 8);
if( dVal==sqlite3_column_double(pStmt, i) ) break;
}
}
bChanged = 1;
break;
}
default: {
int n;
int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
nAdvance = nHdr + n;
if( eType==sqlite3_column_type(pStmt, i)
&& n==sqlite3_column_bytes(pStmt, i)
&& (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
){
break;
}
bChanged = 1;
}
}
/* If at least one field has been modified, this is not a no-op. */
if( bChanged ) bNoop = 0;
/* Add a field to the old.* record. This is omitted if this modules is
** currently generating a patchset. */
if( bPatchset==0 ){
if( bChanged || abPK[i] ){
sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
}else{
sessionAppendByte(pBuf, 0, &rc);
}
}
/* Add a field to the new.* record. Or the only record if currently
** generating a patchset. */
if( bChanged || (bPatchset && abPK[i]) ){
sessionAppendCol(&buf2, pStmt, i, &rc);
}else{
sessionAppendByte(&buf2, 0, &rc);
}
pCsr += nAdvance;
}
if( bNoop ){
pBuf->nBuf = nRewind;
}else{
sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
}
sqlite3_free(buf2.aBuf);
return rc;
}
/*
** Append a DELETE change to the buffer passed as the first argument. Use
** the changeset format if argument bPatchset is zero, or the patchset
** format otherwise.
*/
static int sessionAppendDelete(
SessionBuffer *pBuf, /* Buffer to append to */
int bPatchset, /* True for "patchset", 0 for "changeset" */
SessionChange *p, /* Object containing old values */
int nCol, /* Number of columns in table */
u8 *abPK /* Boolean array - true for PK columns */
){
int rc = SQLITE_OK;
sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
sessionAppendByte(pBuf, p->bIndirect, &rc);
if( bPatchset==0 ){
sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
}else{
int i;
u8 *a = p->aRecord;
for(i=0; i<nCol; i++){
u8 *pStart = a;
int eType = *a++;
switch( eType ){
case 0:
case SQLITE_NULL:
assert( abPK[i]==0 );
break;
case SQLITE_FLOAT:
case SQLITE_INTEGER:
a += 8;
break;
default: {
int n;
a += sessionVarintGet(a, &n);
a += n;
break;
}
}
if( abPK[i] ){
sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
}
}
assert( (a - p->aRecord)==p->nRecord );
}
return rc;
}
/*
** Formulate and prepare a SELECT statement to retrieve a row from table
** zTab in database zDb based on its primary key. i.e.
**
** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
*/
static int sessionSelectStmt(
sqlite3 *db, /* Database handle */
const char *zDb, /* Database name */
const char *zTab, /* Table name */
int nCol, /* Number of columns in table */
const char **azCol, /* Names of table columns */
u8 *abPK, /* PRIMARY KEY array */
sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
){
int rc = SQLITE_OK;
char *zSql = 0;
int nSql = -1;
if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
zSql = sqlite3_mprintf(
"SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
"idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
);
if( zSql==0 ) rc = SQLITE_NOMEM;
}else{
int i;
const char *zSep = "";
SessionBuffer buf = {0, 0, 0};
sessionAppendStr(&buf, "SELECT * FROM ", &rc);
sessionAppendIdent(&buf, zDb, &rc);
sessionAppendStr(&buf, ".", &rc);
sessionAppendIdent(&buf, zTab, &rc);
sessionAppendStr(&buf, " WHERE ", &rc);
for(i=0; i<nCol; i++){
if( abPK[i] ){
sessionAppendStr(&buf, zSep, &rc);
sessionAppendIdent(&buf, azCol[i], &rc);
sessionAppendStr(&buf, " IS ?", &rc);
sessionAppendInteger(&buf, i+1, &rc);
zSep = " AND ";
}
}
zSql = (char*)buf.aBuf;
nSql = buf.nBuf;
}
if( rc==SQLITE_OK ){
rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
}
sqlite3_free(zSql);
return rc;
}
/*
** Bind the PRIMARY KEY values from the change passed in argument pChange
** to the SELECT statement passed as the first argument. The SELECT statement
** is as prepared by function sessionSelectStmt().
**
** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
** error code (e.g. SQLITE_NOMEM) otherwise.
*/
static int sessionSelectBind(
sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
int nCol, /* Number of columns in table */
u8 *abPK, /* PRIMARY KEY array */
SessionChange *pChange /* Change structure */
){
int i;
int rc = SQLITE_OK;
u8 *a = pChange->aRecord;
for(i=0; i<nCol && rc==SQLITE_OK; i++){
int eType = *a++;
switch( eType ){
case 0:
case SQLITE_NULL:
assert( abPK[i]==0 );
break;
case SQLITE_INTEGER: {
if( abPK[i] ){
i64 iVal = sessionGetI64(a);
rc = sqlite3_bind_int64(pSelect, i+1, iVal);
}
a += 8;
break;
}
case SQLITE_FLOAT: {
if( abPK[i] ){
double rVal;
i64 iVal = sessionGetI64(a);
memcpy(&rVal, &iVal, 8);
rc = sqlite3_bind_double(pSelect, i+1, rVal);
}
a += 8;
break;
}
case SQLITE_TEXT: {
int n;
a += sessionVarintGet(a, &n);
if( abPK[i] ){
rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
}
a += n;
break;
}
default: {
int n;
assert( eType==SQLITE_BLOB );
a += sessionVarintGet(a, &n);
if( abPK[i] ){
rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
}
a += n;
break;
}
}
}
return rc;
}
/*
** This function is a no-op if *pRc is set to other than SQLITE_OK when it
** is called. Otherwise, append a serialized table header (part of the binary
** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
** SQLite error code before returning.
*/
static void sessionAppendTableHdr(
SessionBuffer *pBuf, /* Append header to this buffer */
int bPatchset, /* Use the patchset format if true */
SessionTable *pTab, /* Table object to append header for */
int *pRc /* IN/OUT: Error code */
){
/* Write a table header */
sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
sessionAppendVarint(pBuf, pTab->nCol, pRc);
sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
}
/*
** Generate either a changeset (if argument bPatchset is zero) or a patchset
** (if it is non-zero) based on the current contents of the session object
** passed as the first argument.
**
** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
** occurs, an SQLite error code is returned and both output variables set
** to 0.
*/
static int sessionGenerateChangeset(
sqlite3_session *pSession, /* Session object */
int bPatchset, /* True for patchset, false for changeset */
int (*xOutput)(void *pOut, const void *pData, int nData),
void *pOut, /* First argument for xOutput */
int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
void **ppChangeset /* OUT: Buffer containing changeset */
){
sqlite3 *db = pSession->db; /* Source database handle */
SessionTable *pTab; /* Used to iterate through attached tables */
SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
int rc; /* Return code */
assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0) );
assert( xOutput!=0 || (pnChangeset!=0 && ppChangeset!=0) );
/* Zero the output variables in case an error occurs. If this session
** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
** this call will be a no-op. */
if( xOutput==0 ){
assert( pnChangeset!=0 && ppChangeset!=0 );
*pnChangeset = 0;
*ppChangeset = 0;
}
if( pSession->rc ) return pSession->rc;
rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
if( rc!=SQLITE_OK ) return rc;
sqlite3_mutex_enter(sqlite3_db_mutex(db));
for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
if( pTab->nEntry ){
const char *zName = pTab->zName;
int nCol = 0; /* Number of columns in table */
u8 *abPK = 0; /* Primary key array */
const char **azCol = 0; /* Table columns */
int i; /* Used to iterate through hash buckets */
sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
int nRewind = buf.nBuf; /* Initial size of write buffer */
int nNoop; /* Size of buffer after writing tbl header */
/* Check the table schema is still Ok. */
rc = sessionTableInfo(0, db, pSession->zDb, zName, &nCol, 0,&azCol,&abPK);
if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
rc = SQLITE_SCHEMA;
}
/* Write a table header */
sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
/* Build and compile a statement to execute: */
if( rc==SQLITE_OK ){
rc = sessionSelectStmt(
db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
}
nNoop = buf.nBuf;
for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
SessionChange *p; /* Used to iterate through changes */
for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
rc = sessionSelectBind(pSel, nCol, abPK, p);
if( rc!=SQLITE_OK ) continue;
if( sqlite3_step(pSel)==SQLITE_ROW ){
if( p->op==SQLITE_INSERT ){
int iCol;
sessionAppendByte(&buf, SQLITE_INSERT, &rc);
sessionAppendByte(&buf, p->bIndirect, &rc);
for(iCol=0; iCol<nCol; iCol++){
sessionAppendCol(&buf, pSel, iCol, &rc);
}
}else{
assert( abPK!=0 ); /* Because sessionSelectStmt() returned ok */
rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
}
}else if( p->op!=SQLITE_INSERT ){
rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
}
if( rc==SQLITE_OK ){
rc = sqlite3_reset(pSel);
}
/* If the buffer is now larger than sessions_strm_chunk_size, pass
** its contents to the xOutput() callback. */
if( xOutput
&& rc==SQLITE_OK
&& buf.nBuf>nNoop
&& buf.nBuf>sessions_strm_chunk_size
){
rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
nNoop = -1;
buf.nBuf = 0;
}
}
}
sqlite3_finalize(pSel);
if( buf.nBuf==nNoop ){
buf.nBuf = nRewind;
}
sqlite3_free((char*)azCol); /* cast works around VC++ bug */
}
}
if( rc==SQLITE_OK ){
if( xOutput==0 ){
*pnChangeset = buf.nBuf;
*ppChangeset = buf.aBuf;
buf.aBuf = 0;
}else if( buf.nBuf>0 ){
rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
}
}
sqlite3_free(buf.aBuf);
sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
sqlite3_mutex_leave(sqlite3_db_mutex(db));
return rc;
}
/*
** Obtain a changeset object containing all changes recorded by the
** session object passed as the first argument.
**
** It is the responsibility of the caller to eventually free the buffer
** using sqlite3_free().
*/
int sqlite3session_changeset(
sqlite3_session *pSession, /* Session object */
int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
void **ppChangeset /* OUT: Buffer containing changeset */
){
int rc;
if( pnChangeset==0 || ppChangeset==0 ) return SQLITE_MISUSE;
rc = sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset,ppChangeset);
assert( rc || pnChangeset==0
|| pSession->bEnableSize==0 || *pnChangeset<=pSession->nMaxChangesetSize
);
return rc;
}
/*
** Streaming version of sqlite3session_changeset().
*/
int sqlite3session_changeset_strm(
sqlite3_session *pSession,
int (*xOutput)(void *pOut, const void *pData, int nData),
void *pOut
){
if( xOutput==0 ) return SQLITE_MISUSE;
return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
}
/*
** Streaming version of sqlite3session_patchset().
*/
int sqlite3session_patchset_strm(
sqlite3_session *pSession,
int (*xOutput)(void *pOut, const void *pData, int nData),
void *pOut
){
if( xOutput==0 ) return SQLITE_MISUSE;
return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
}
/*
** Obtain a patchset object containing all changes recorded by the
** session object passed as the first argument.
**
** It is the responsibility of the caller to eventually free the buffer
** using sqlite3_free().
*/
int sqlite3session_patchset(
sqlite3_session *pSession, /* Session object */
int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
void **ppPatchset /* OUT: Buffer containing changeset */
){
if( pnPatchset==0 || ppPatchset==0 ) return SQLITE_MISUSE;
return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
}
/*
** Enable or disable the session object passed as the first argument.
*/
int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
int ret;
sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
if( bEnable>=0 ){
pSession->bEnable = bEnable;
}
ret = pSession->bEnable;
sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
return ret;
}
/*
** Enable or disable the session object passed as the first argument.
*/
int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
int ret;
sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
if( bIndirect>=0 ){
pSession->bIndirect = bIndirect;
}
ret = pSession->bIndirect;
sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
return ret;
}
/*
** Return true if there have been no changes to monitored tables recorded
** by the session object passed as the only argument.
*/
int sqlite3session_isempty(sqlite3_session *pSession){
int ret = 0;
SessionTable *pTab;
sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
ret = (pTab->nEntry>0);
}
sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
return (ret==0);
}
/*
** Return the amount of heap memory in use.
*/
sqlite3_int64 sqlite3session_memory_used(sqlite3_session *pSession){
return pSession->nMalloc;
}
/*
** Configure the session object passed as the first argument.
*/
int sqlite3session_object_config(sqlite3_session *pSession, int op, void *pArg){
int rc = SQLITE_OK;
switch( op ){
case SQLITE_SESSION_OBJCONFIG_SIZE: {
int iArg = *(int*)pArg;
if( iArg>=0 ){
if( pSession->pTable ){
rc = SQLITE_MISUSE;
}else{
pSession->bEnableSize = (iArg!=0);
}
}
*(int*)pArg = pSession->bEnableSize;
break;
}
default:
rc = SQLITE_MISUSE;
}
return rc;
}
/*
** Return the maximum size of sqlite3session_changeset() output.
*/
sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession){
return pSession->nMaxChangesetSize;
}
/*
** Do the work for either sqlite3changeset_start() or start_strm().
*/
static int sessionChangesetStart(
sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
int (*xInput)(void *pIn, void *pData, int *pnData),
void *pIn,
int nChangeset, /* Size of buffer pChangeset in bytes */
void *pChangeset, /* Pointer to buffer containing changeset */
int bInvert, /* True to invert changeset */
int bSkipEmpty /* True to skip empty UPDATE changes */
){
sqlite3_changeset_iter *pRet; /* Iterator to return */
int nByte; /* Number of bytes to allocate for iterator */
assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
/* Zero the output variable in case an error occurs. */
*pp = 0;
/* Allocate and initialize the iterator structure. */
nByte = sizeof(sqlite3_changeset_iter);
pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
if( !pRet ) return SQLITE_NOMEM;
memset(pRet, 0, sizeof(sqlite3_changeset_iter));
pRet->in.aData = (u8 *)pChangeset;
pRet->in.nData = nChangeset;
pRet->in.xInput = xInput;
pRet->in.pIn = pIn;
pRet->in.bEof = (xInput ? 0 : 1);
pRet->bInvert = bInvert;
pRet->bSkipEmpty = bSkipEmpty;
/* Populate the output variable and return success. */
*pp = pRet;
return SQLITE_OK;
}
/*
** Create an iterator used to iterate through the contents of a changeset.
*/
int sqlite3changeset_start(
sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
int nChangeset, /* Size of buffer pChangeset in bytes */
void *pChangeset /* Pointer to buffer containing changeset */
){
return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, 0, 0);
}
int sqlite3changeset_start_v2(
sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
int nChangeset, /* Size of buffer pChangeset in bytes */
void *pChangeset, /* Pointer to buffer containing changeset */
int flags
){
int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, bInvert, 0);
}
/*
** Streaming version of sqlite3changeset_start().
*/
int sqlite3changeset_start_strm(
sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
int (*xInput)(void *pIn, void *pData, int *pnData),
void *pIn
){
return sessionChangesetStart(pp, xInput, pIn, 0, 0, 0, 0);
}
int sqlite3changeset_start_v2_strm(
sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
int (*xInput)(void *pIn, void *pData, int *pnData),
void *pIn,
int flags
){
int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
return sessionChangesetStart(pp, xInput, pIn, 0, 0, bInvert, 0);
}
/*
** If the SessionInput object passed as the only argument is a streaming
** object and the buffer is full, discard some data to free up space.
*/
static void sessionDiscardData(SessionInput *pIn){
if( pIn->xInput && pIn->iNext>=sessions_strm_chunk_size ){
int nMove = pIn->buf.nBuf - pIn->iNext;
assert( nMove>=0 );
if( nMove>0 ){
memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
}
pIn->buf.nBuf -= pIn->iNext;
pIn->iNext = 0;
pIn->nData = pIn->buf.nBuf;
}
}
/*
** Ensure that there are at least nByte bytes available in the buffer. Or,
** if there are not nByte bytes remaining in the input, that all available
** data is in the buffer.
**
** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
*/
static int sessionInputBuffer(SessionInput *pIn, int nByte){
int rc = SQLITE_OK;
if( pIn->xInput ){
while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
int nNew = sessions_strm_chunk_size;
if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
if( nNew==0 ){
pIn->bEof = 1;
}else{
pIn->buf.nBuf += nNew;
}
}
pIn->aData = pIn->buf.aBuf;
pIn->nData = pIn->buf.nBuf;
}
}
return rc;
}
/*
** When this function is called, *ppRec points to the start of a record
** that contains nCol values. This function advances the pointer *ppRec
** until it points to the byte immediately following that record.
*/
static void sessionSkipRecord(
u8 **ppRec, /* IN/OUT: Record pointer */
int nCol /* Number of values in record */
){
u8 *aRec = *ppRec;
int i;
for(i=0; i<nCol; i++){
int eType = *aRec++;
if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
int nByte;
aRec += sessionVarintGet((u8*)aRec, &nByte);
aRec += nByte;
}else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
aRec += 8;
}
}
*ppRec = aRec;
}
/*
** This function sets the value of the sqlite3_value object passed as the
** first argument to a copy of the string or blob held in the aData[]
** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
** error occurs.
*/
static int sessionValueSetStr(
sqlite3_value *pVal, /* Set the value of this object */
u8 *aData, /* Buffer containing string or blob data */
int nData, /* Size of buffer aData[] in bytes */
u8 enc /* String encoding (0 for blobs) */
){
/* In theory this code could just pass SQLITE_TRANSIENT as the final
** argument to sqlite3ValueSetStr() and have the copy created
** automatically. But doing so makes it difficult to detect any OOM
** error. Hence the code to create the copy externally. */
u8 *aCopy = sqlite3_malloc64((sqlite3_int64)nData+1);
if( aCopy==0 ) return SQLITE_NOMEM;
memcpy(aCopy, aData, nData);
sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
return SQLITE_OK;
}
/*
** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
** for details.
**
** When this function is called, *paChange points to the start of the record
** to deserialize. Assuming no error occurs, *paChange is set to point to
** one byte after the end of the same record before this function returns.
** If the argument abPK is NULL, then the record contains nCol values. Or,
** if abPK is other than NULL, then the record contains only the PK fields
** (in other words, it is a patchset DELETE record).
**
** If successful, each element of the apOut[] array (allocated by the caller)
** is set to point to an sqlite3_value object containing the value read
** from the corresponding position in the record. If that value is not
** included in the record (i.e. because the record is part of an UPDATE change
** and the field was not modified), the corresponding element of apOut[] is
** set to NULL.
**
** It is the responsibility of the caller to free all sqlite_value structures
** using sqlite3_free().
**
** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
** The apOut[] array may have been partially populated in this case.
*/
static int sessionReadRecord(
SessionInput *pIn, /* Input data */
int nCol, /* Number of values in record */
u8 *abPK, /* Array of primary key flags, or NULL */
sqlite3_value **apOut, /* Write values to this array */
int *pbEmpty
){
int i; /* Used to iterate through columns */
int rc = SQLITE_OK;
assert( pbEmpty==0 || *pbEmpty==0 );
if( pbEmpty ) *pbEmpty = 1;
for(i=0; i<nCol && rc==SQLITE_OK; i++){
int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
if( abPK && abPK[i]==0 ) continue;
rc = sessionInputBuffer(pIn, 9);
if( rc==SQLITE_OK ){
if( pIn->iNext>=pIn->nData ){
rc = SQLITE_CORRUPT_BKPT;
}else{
eType = pIn->aData[pIn->iNext++];
assert( apOut[i]==0 );
if( eType ){
if( pbEmpty ) *pbEmpty = 0;
apOut[i] = sqlite3ValueNew(0);
if( !apOut[i] ) rc = SQLITE_NOMEM;
}
}
}
if( rc==SQLITE_OK ){
u8 *aVal = &pIn->aData[pIn->iNext];
if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
int nByte;
pIn->iNext += sessionVarintGet(aVal, &nByte);
rc = sessionInputBuffer(pIn, nByte);
if( rc==SQLITE_OK ){
if( nByte<0 || nByte>pIn->nData-pIn->iNext ){
rc = SQLITE_CORRUPT_BKPT;
}else{
u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
pIn->iNext += nByte;
}
}
}
if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
sqlite3_int64 v = sessionGetI64(aVal);
if( eType==SQLITE_INTEGER ){
sqlite3VdbeMemSetInt64(apOut[i], v);
}else{
double d;
memcpy(&d, &v, 8);
sqlite3VdbeMemSetDouble(apOut[i], d);
}
pIn->iNext += 8;
}
}
}
return rc;
}
/*
** The input pointer currently points to the second byte of a table-header.
** Specifically, to the following:
**
** + number of columns in table (varint)
** + array of PK flags (1 byte per column),
** + table name (nul terminated).
**
** This function ensures that all of the above is present in the input
** buffer (i.e. that it can be accessed without any calls to xInput()).
** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
** The input pointer is not moved.
*/
static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
int rc = SQLITE_OK;
int nCol = 0;
int nRead = 0;
rc = sessionInputBuffer(pIn, 9);
if( rc==SQLITE_OK ){
nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
/* The hard upper limit for the number of columns in an SQLite
** database table is, according to sqliteLimit.h, 32676. So
** consider any table-header that purports to have more than 65536
** columns to be corrupt. This is convenient because otherwise,
** if the (nCol>65536) condition below were omitted, a sufficiently
** large value for nCol may cause nRead to wrap around and become
** negative. Leading to a crash. */
if( nCol<0 || nCol>65536 ){
rc = SQLITE_CORRUPT_BKPT;
}else{
rc = sessionInputBuffer(pIn, nRead+nCol+100);
nRead += nCol;
}
}
while( rc==SQLITE_OK ){
while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
nRead++;
}
if( (pIn->iNext + nRead)<pIn->nData ) break;
rc = sessionInputBuffer(pIn, nRead + 100);
}
*pnByte = nRead+1;
return rc;
}
/*
** The input pointer currently points to the first byte of the first field
** of a record consisting of nCol columns. This function ensures the entire
** record is buffered. It does not move the input pointer.
**
** If successful, SQLITE_OK is returned and *pnByte is set to the size of
** the record in bytes. Otherwise, an SQLite error code is returned. The
** final value of *pnByte is undefined in this case.
*/
static int sessionChangesetBufferRecord(
SessionInput *pIn, /* Input data */
int nCol, /* Number of columns in record */
int *pnByte /* OUT: Size of record in bytes */
){
int rc = SQLITE_OK;
int nByte = 0;
int i;
for(i=0; rc==SQLITE_OK && i<nCol; i++){
int eType;
rc = sessionInputBuffer(pIn, nByte + 10);
if( rc==SQLITE_OK ){
eType = pIn->aData[pIn->iNext + nByte++];
if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
int n;
nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
nByte += n;
rc = sessionInputBuffer(pIn, nByte);
}else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
nByte += 8;
}
}
}
*pnByte = nByte;
return rc;
}
/*
** The input pointer currently points to the second byte of a table-header.
** Specifically, to the following:
**
** + number of columns in table (varint)
** + array of PK flags (1 byte per column),
** + table name (nul terminated).
**
** This function decodes the table-header and populates the p->nCol,
** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
** also allocated or resized according to the new value of p->nCol. The
** input pointer is left pointing to the byte following the table header.
**
** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
** is returned and the final values of the various fields enumerated above
** are undefined.
*/
static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
int rc;
int nCopy;
assert( p->rc==SQLITE_OK );
rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
if( rc==SQLITE_OK ){
int nByte;
int nVarint;
nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
if( p->nCol>0 ){
nCopy -= nVarint;
p->in.iNext += nVarint;
nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
p->tblhdr.nBuf = 0;
sessionBufferGrow(&p->tblhdr, nByte, &rc);
}else{
rc = SQLITE_CORRUPT_BKPT;
}
}
if( rc==SQLITE_OK ){
size_t iPK = sizeof(sqlite3_value*)*p->nCol*2;
memset(p->tblhdr.aBuf, 0, iPK);
memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
p->in.iNext += nCopy;
}
p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
if( p->apValue==0 ){
p->abPK = 0;
p->zTab = 0;
}else{
p->abPK = (u8*)&p->apValue[p->nCol*2];
p->zTab = p->abPK ? (char*)&p->abPK[p->nCol] : 0;
}
return (p->rc = rc);
}
/*
** Advance the changeset iterator to the next change. The differences between
** this function and sessionChangesetNext() are that
**
** * If pbEmpty is not NULL and the change is a no-op UPDATE (an UPDATE
** that modifies no columns), this function sets (*pbEmpty) to 1.
**
** * If the iterator is configured to skip no-op UPDATEs,
** sessionChangesetNext() does that. This function does not.
*/
static int sessionChangesetNextOne(
sqlite3_changeset_iter *p, /* Changeset iterator */
u8 **paRec, /* If non-NULL, store record pointer here */
int *pnRec, /* If non-NULL, store size of record here */
int *pbNew, /* If non-NULL, true if new table */
int *pbEmpty
){
int i;
u8 op;
assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
assert( pbEmpty==0 || *pbEmpty==0 );
/* If the iterator is in the error-state, return immediately. */
if( p->rc!=SQLITE_OK ) return p->rc;
/* Free the current contents of p->apValue[], if any. */
if( p->apValue ){
for(i=0; i<p->nCol*2; i++){
sqlite3ValueFree(p->apValue[i]);
}
memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
}
/* Make sure the buffer contains at least 10 bytes of input data, or all
** remaining data if there are less than 10 bytes available. This is
** sufficient either for the 'T' or 'P' byte and the varint that follows
** it, or for the two single byte values otherwise. */
p->rc = sessionInputBuffer(&p->in, 2);
if( p->rc!=SQLITE_OK ) return p->rc;
/* If the iterator is already at the end of the changeset, return DONE. */
if( p->in.iNext>=p->in.nData ){
return SQLITE_DONE;
}
sessionDiscardData(&p->in);
p->in.iCurrent = p->in.iNext;
op = p->in.aData[p->in.iNext++];
while( op=='T' || op=='P' ){
if( pbNew ) *pbNew = 1;
p->bPatchset = (op=='P');
if( sessionChangesetReadTblhdr(p) ) return p->rc;
if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
p->in.iCurrent = p->in.iNext;
if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
op = p->in.aData[p->in.iNext++];
}
if( p->zTab==0 || (p->bPatchset && p->bInvert) ){
/* The first record in the changeset is not a table header. Must be a
** corrupt changeset. */
assert( p->in.iNext==1 || p->zTab );
return (p->rc = SQLITE_CORRUPT_BKPT);
}
p->op = op;
p->bIndirect = p->in.aData[p->in.iNext++];
if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
return (p->rc = SQLITE_CORRUPT_BKPT);
}
if( paRec ){
int nVal; /* Number of values to buffer */
if( p->bPatchset==0 && op==SQLITE_UPDATE ){
nVal = p->nCol * 2;
}else if( p->bPatchset && op==SQLITE_DELETE ){
nVal = 0;
for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
}else{
nVal = p->nCol;
}
p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
if( p->rc!=SQLITE_OK ) return p->rc;
*paRec = &p->in.aData[p->in.iNext];
p->in.iNext += *pnRec;
}else{
sqlite3_value **apOld = (p->bInvert ? &p->apValue[p->nCol] : p->apValue);
sqlite3_value **apNew = (p->bInvert ? p->apValue : &p->apValue[p->nCol]);
/* If this is an UPDATE or DELETE, read the old.* record. */
if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
u8 *abPK = p->bPatchset ? p->abPK : 0;
p->rc = sessionReadRecord(&p->in, p->nCol, abPK, apOld, 0);
if( p->rc!=SQLITE_OK ) return p->rc;
}
/* If this is an INSERT or UPDATE, read the new.* record. */
if( p->op!=SQLITE_DELETE ){
p->rc = sessionReadRecord(&p->in, p->nCol, 0, apNew, pbEmpty);
if( p->rc!=SQLITE_OK ) return p->rc;
}
if( (p->bPatchset || p->bInvert) && p->op==SQLITE_UPDATE ){
/* If this is an UPDATE that is part of a patchset, then all PK and
** modified fields are present in the new.* record. The old.* record
** is currently completely empty. This block shifts the PK fields from
** new.* to old.*, to accommodate the code that reads these arrays. */
for(i=0; i<p->nCol; i++){
assert( p->bPatchset==0 || p->apValue[i]==0 );
if( p->abPK[i] ){
assert( p->apValue[i]==0 );
p->apValue[i] = p->apValue[i+p->nCol];
if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT);
p->apValue[i+p->nCol] = 0;
}
}
}else if( p->bInvert ){
if( p->op==SQLITE_INSERT ) p->op = SQLITE_DELETE;
else if( p->op==SQLITE_DELETE ) p->op = SQLITE_INSERT;
}
}
return SQLITE_ROW;
}
/*
** Advance the changeset iterator to the next change.
**
** If both paRec and pnRec are NULL, then this function works like the public
** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
** sqlite3changeset_new() and old() APIs may be used to query for values.
**
** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
** record is written to *paRec before returning and the number of bytes in
** the record to *pnRec.
**
** Either way, this function returns SQLITE_ROW if the iterator is
** successfully advanced to the next change in the changeset, an SQLite
** error code if an error occurs, or SQLITE_DONE if there are no further
** changes in the changeset.
*/
static int sessionChangesetNext(
sqlite3_changeset_iter *p, /* Changeset iterator */
u8 **paRec, /* If non-NULL, store record pointer here */
int *pnRec, /* If non-NULL, store size of record here */
int *pbNew /* If non-NULL, true if new table */
){
int bEmpty;
int rc;
do {
bEmpty = 0;
rc = sessionChangesetNextOne(p, paRec, pnRec, pbNew, &bEmpty);
}while( rc==SQLITE_ROW && p->bSkipEmpty && bEmpty);
return rc;
}
/*
** Advance an iterator created by sqlite3changeset_start() to the next
** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
** or SQLITE_CORRUPT.
**
** This function may not be called on iterators passed to a conflict handler
** callback by changeset_apply().
*/
int sqlite3changeset_next(sqlite3_changeset_iter *p){
return sessionChangesetNext(p, 0, 0, 0);
}
/*
** The following function extracts information on the current change
** from a changeset iterator. It may only be called after changeset_next()
** has returned SQLITE_ROW.
*/
int sqlite3changeset_op(
sqlite3_changeset_iter *pIter, /* Iterator handle */
const char **pzTab, /* OUT: Pointer to table name */
int *pnCol, /* OUT: Number of columns in table */
int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
int *pbIndirect /* OUT: True if change is indirect */
){
*pOp = pIter->op;
*pnCol = pIter->nCol;
*pzTab = pIter->zTab;
if( pbIndirect ) *pbIndirect = pIter->bIndirect;
return SQLITE_OK;
}
/*
** Return information regarding the PRIMARY KEY and number of columns in
** the database table affected by the change that pIter currently points
** to. This function may only be called after changeset_next() returns
** SQLITE_ROW.
*/
int sqlite3changeset_pk(
sqlite3_changeset_iter *pIter, /* Iterator object */
unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
int *pnCol /* OUT: Number of entries in output array */
){
*pabPK = pIter->abPK;
if( pnCol ) *pnCol = pIter->nCol;
return SQLITE_OK;
}
/*
** This function may only be called while the iterator is pointing to an
** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
** Otherwise, SQLITE_MISUSE is returned.
**
** It sets *ppValue to point to an sqlite3_value structure containing the
** iVal'th value in the old.* record. Or, if that particular value is not
** included in the record (because the change is an UPDATE and the field
** was not modified and is not a PK column), set *ppValue to NULL.
**
** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
** not modified. Otherwise, SQLITE_OK.
*/
int sqlite3changeset_old(
sqlite3_changeset_iter *pIter, /* Changeset iterator */
int iVal, /* Index of old.* value to retrieve */
sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
){
if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
return SQLITE_MISUSE;
}
if( iVal<0 || iVal>=pIter->nCol ){
return SQLITE_RANGE;
}
*ppValue = pIter->apValue[iVal];
return SQLITE_OK;
}
/*
** This function may only be called while the iterator is pointing to an
** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
** Otherwise, SQLITE_MISUSE is returned.
**
** It sets *ppValue to point to an sqlite3_value structure containing the
** iVal'th value in the new.* record. Or, if that particular value is not
** included in the record (because the change is an UPDATE and the field
** was not modified), set *ppValue to NULL.
**
** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
** not modified. Otherwise, SQLITE_OK.
*/
int sqlite3changeset_new(
sqlite3_changeset_iter *pIter, /* Changeset iterator */
int iVal, /* Index of new.* value to retrieve */
sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
){
if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
return SQLITE_MISUSE;
}
if( iVal<0 || iVal>=pIter->nCol ){
return SQLITE_RANGE;
}
*ppValue = pIter->apValue[pIter->nCol+iVal];
return SQLITE_OK;
}
/*
** The following two macros are used internally. They are similar to the
** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
** they omit all error checking and return a pointer to the requested value.
*/
#define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
#define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
/*
** This function may only be called with a changeset iterator that has been
** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
**
** If successful, *ppValue is set to point to an sqlite3_value structure
** containing the iVal'th value of the conflicting record.
**
** If value iVal is out-of-range or some other error occurs, an SQLite error
** code is returned. Otherwise, SQLITE_OK.
*/
int sqlite3changeset_conflict(
sqlite3_changeset_iter *pIter, /* Changeset iterator */
int iVal, /* Index of conflict record value to fetch */
sqlite3_value **ppValue /* OUT: Value from conflicting row */
){
if( !pIter->pConflict ){
return SQLITE_MISUSE;
}
if( iVal<0 || iVal>=pIter->nCol ){
return SQLITE_RANGE;
}
*ppValue = sqlite3_column_value(pIter->pConflict, iVal);
return SQLITE_OK;
}
/*
** This function may only be called with an iterator passed to an
** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
** it sets the output variable to the total number of known foreign key
** violations in the destination database and returns SQLITE_OK.
**
** In all other cases this function returns SQLITE_MISUSE.
*/
int sqlite3changeset_fk_conflicts(
sqlite3_changeset_iter *pIter, /* Changeset iterator */
int *pnOut /* OUT: Number of FK violations */
){
if( pIter->pConflict || pIter->apValue ){
return SQLITE_MISUSE;
}
*pnOut = pIter->nCol;
return SQLITE_OK;
}
/*
** Finalize an iterator allocated with sqlite3changeset_start().
**
** This function may not be called on iterators passed to a conflict handler
** callback by changeset_apply().
*/
int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
int rc = SQLITE_OK;
if( p ){
int i; /* Used to iterate through p->apValue[] */
rc = p->rc;
if( p->apValue ){
for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
}
sqlite3_free(p->tblhdr.aBuf);
sqlite3_free(p->in.buf.aBuf);
sqlite3_free(p);
}
return rc;
}
static int sessionChangesetInvert(
SessionInput *pInput, /* Input changeset */
int (*xOutput)(void *pOut, const void *pData, int nData),
void *pOut,
int *pnInverted, /* OUT: Number of bytes in output changeset */
void **ppInverted /* OUT: Inverse of pChangeset */
){
int rc = SQLITE_OK; /* Return value */
SessionBuffer sOut; /* Output buffer */
int nCol = 0; /* Number of cols in current table */
u8 *abPK = 0; /* PK array for current table */
sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
/* Initialize the output buffer */
memset(&sOut, 0, sizeof(SessionBuffer));
/* Zero the output variables in case an error occurs. */
if( ppInverted ){
*ppInverted = 0;
*pnInverted = 0;
}
while( 1 ){
u8 eType;
/* Test for EOF. */
if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
if( pInput->iNext>=pInput->nData ) break;
eType = pInput->aData[pInput->iNext];
switch( eType ){
case 'T': {
/* A 'table' record consists of:
**
** * A constant 'T' character,
** * Number of columns in said table (a varint),
** * An array of nCol bytes (sPK),
** * A nul-terminated table name.
*/
int nByte;
int nVar;
pInput->iNext++;
if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
goto finished_invert;
}
nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
sPK.nBuf = 0;
sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
sessionAppendByte(&sOut, eType, &rc);
sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
if( rc ) goto finished_invert;
pInput->iNext += nByte;
sqlite3_free(apVal);
apVal = 0;
abPK = sPK.aBuf;
break;
}
case SQLITE_INSERT:
case SQLITE_DELETE: {
int nByte;
int bIndirect = pInput->aData[pInput->iNext+1];
int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
pInput->iNext += 2;
assert( rc==SQLITE_OK );
rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
sessionAppendByte(&sOut, eType2, &rc);
sessionAppendByte(&sOut, bIndirect, &rc);
sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
pInput->iNext += nByte;
if( rc ) goto finished_invert;
break;
}
case SQLITE_UPDATE: {
int iCol;
if( 0==apVal ){
apVal = (sqlite3_value **)sqlite3_malloc64(sizeof(apVal[0])*nCol*2);
if( 0==apVal ){
rc = SQLITE_NOMEM;
goto finished_invert;
}
memset(apVal, 0, sizeof(apVal[0])*nCol*2);
}
/* Write the header for the new UPDATE change. Same as the original. */
sessionAppendByte(&sOut, eType, &rc);
sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
/* Read the old.* and new.* records for the update change. */
pInput->iNext += 2;
rc = sessionReadRecord(pInput, nCol, 0, &apVal[0], 0);
if( rc==SQLITE_OK ){
rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol], 0);
}
/* Write the new old.* record. Consists of the PK columns from the
** original old.* record, and the other values from the original
** new.* record. */
for(iCol=0; iCol<nCol; iCol++){
sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
sessionAppendValue(&sOut, pVal, &rc);
}
/* Write the new new.* record. Consists of a copy of all values
** from the original old.* record, except for the PK columns, which
** are set to "undefined". */
for(iCol=0; iCol<nCol; iCol++){
sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
sessionAppendValue(&sOut, pVal, &rc);
}
for(iCol=0; iCol<nCol*2; iCol++){
sqlite3ValueFree(apVal[iCol]);
}
memset(apVal, 0, sizeof(apVal[0])*nCol*2);
if( rc!=SQLITE_OK ){
goto finished_invert;
}
break;
}
default:
rc = SQLITE_CORRUPT_BKPT;
goto finished_invert;
}
assert( rc==SQLITE_OK );
if( xOutput && sOut.nBuf>=sessions_strm_chunk_size ){
rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
sOut.nBuf = 0;
if( rc!=SQLITE_OK ) goto finished_invert;
}
}
assert( rc==SQLITE_OK );
if( pnInverted && ALWAYS(ppInverted) ){
*pnInverted = sOut.nBuf;
*ppInverted = sOut.aBuf;
sOut.aBuf = 0;
}else if( sOut.nBuf>0 && ALWAYS(xOutput!=0) ){
rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
}
finished_invert:
sqlite3_free(sOut.aBuf);
sqlite3_free(apVal);
sqlite3_free(sPK.aBuf);
return rc;
}
/*
** Invert a changeset object.
*/
int sqlite3changeset_invert(
int nChangeset, /* Number of bytes in input */
const void *pChangeset, /* Input changeset */
int *pnInverted, /* OUT: Number of bytes in output changeset */
void **ppInverted /* OUT: Inverse of pChangeset */
){
SessionInput sInput;
/* Set up the input stream */
memset(&sInput, 0, sizeof(SessionInput));
sInput.nData = nChangeset;
sInput.aData = (u8*)pChangeset;
return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
}
/*
** Streaming version of sqlite3changeset_invert().
*/
int sqlite3changeset_invert_strm(
int (*xInput)(void *pIn, void *pData, int *pnData),
void *pIn,
int (*xOutput)(void *pOut, const void *pData, int nData),
void *pOut
){
SessionInput sInput;
int rc;
/* Set up the input stream */
memset(&sInput, 0, sizeof(SessionInput));
sInput.xInput = xInput;
sInput.pIn = pIn;
rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
sqlite3_free(sInput.buf.aBuf);
return rc;
}
typedef struct SessionUpdate SessionUpdate;
struct SessionUpdate {
sqlite3_stmt *pStmt;
u32 *aMask;
SessionUpdate *pNext;
};
typedef struct SessionApplyCtx SessionApplyCtx;
struct SessionApplyCtx {
sqlite3 *db;
sqlite3_stmt *pDelete; /* DELETE statement */
sqlite3_stmt *pInsert; /* INSERT statement */
sqlite3_stmt *pSelect; /* SELECT statement */
int nCol; /* Size of azCol[] and abPK[] arrays */
const char **azCol; /* Array of column names */
u8 *abPK; /* Boolean array - true if column is in PK */
u32 *aUpdateMask; /* Used by sessionUpdateFind */
SessionUpdate *pUp;
int bStat1; /* True if table is sqlite_stat1 */
int bDeferConstraints; /* True to defer constraints */
int bInvertConstraints; /* Invert when iterating constraints buffer */
SessionBuffer constraints; /* Deferred constraints are stored here */
SessionBuffer rebase; /* Rebase information (if any) here */
u8 bRebaseStarted; /* If table header is already in rebase */
u8 bRebase; /* True to collect rebase information */
};
/* Number of prepared UPDATE statements to cache. */
#define SESSION_UPDATE_CACHE_SZ 12
/*
** Find a prepared UPDATE statement suitable for the UPDATE step currently
** being visited by the iterator. The UPDATE is of the form:
**
** UPDATE tbl SET col = ?, col2 = ? WHERE pk1 IS ? AND pk2 IS ?
*/
static int sessionUpdateFind(
sqlite3_changeset_iter *pIter,
SessionApplyCtx *p,
int bPatchset,
sqlite3_stmt **ppStmt
){
int rc = SQLITE_OK;
SessionUpdate *pUp = 0;
int nCol = pIter->nCol;
int nU32 = (pIter->nCol+33)/32;
int ii;
if( p->aUpdateMask==0 ){
p->aUpdateMask = sqlite3_malloc(nU32*sizeof(u32));
if( p->aUpdateMask==0 ){
rc = SQLITE_NOMEM;
}
}
if( rc==SQLITE_OK ){
memset(p->aUpdateMask, 0, nU32*sizeof(u32));
rc = SQLITE_CORRUPT;
for(ii=0; ii<pIter->nCol; ii++){
if( sessionChangesetNew(pIter, ii) ){
p->aUpdateMask[ii/32] |= (1<<(ii%32));
rc = SQLITE_OK;
}
}
}
if( rc==SQLITE_OK ){
if( bPatchset ) p->aUpdateMask[nCol/32] |= (1<<(nCol%32));
if( p->pUp ){
int nUp = 0;
SessionUpdate **pp = &p->pUp;
while( 1 ){
nUp++;
if( 0==memcmp(p->aUpdateMask, (*pp)->aMask, nU32*sizeof(u32)) ){
pUp = *pp;
*pp = pUp->pNext;
pUp->pNext = p->pUp;
p->pUp = pUp;
break;
}
if( (*pp)->pNext ){
pp = &(*pp)->pNext;
}else{
if( nUp>=SESSION_UPDATE_CACHE_SZ ){
sqlite3_finalize((*pp)->pStmt);
sqlite3_free(*pp);
*pp = 0;
}
break;
}
}
}
if( pUp==0 ){
int nByte = sizeof(SessionUpdate) * nU32*sizeof(u32);
int bStat1 = (sqlite3_stricmp(pIter->zTab, "sqlite_stat1")==0);
pUp = (SessionUpdate*)sqlite3_malloc(nByte);
if( pUp==0 ){
rc = SQLITE_NOMEM;
}else{
const char *zSep = "";
SessionBuffer buf;
memset(&buf, 0, sizeof(buf));
pUp->aMask = (u32*)&pUp[1];
memcpy(pUp->aMask, p->aUpdateMask, nU32*sizeof(u32));
sessionAppendStr(&buf, "UPDATE main.", &rc);
sessionAppendIdent(&buf, pIter->zTab, &rc);
sessionAppendStr(&buf, " SET ", &rc);
/* Create the assignments part of the UPDATE */
for(ii=0; ii<pIter->nCol; ii++){
if( p->abPK[ii]==0 && sessionChangesetNew(pIter, ii) ){
sessionAppendStr(&buf, zSep, &rc);
sessionAppendIdent(&buf, p->azCol[ii], &rc);
sessionAppendStr(&buf, " = ?", &rc);
sessionAppendInteger(&buf, ii*2+1, &rc);
zSep = ", ";
}
}
/* Create the WHERE clause part of the UPDATE */
zSep = "";
sessionAppendStr(&buf, " WHERE ", &rc);
for(ii=0; ii<pIter->nCol; ii++){
if( p->abPK[ii] || (bPatchset==0 && sessionChangesetOld(pIter, ii)) ){
sessionAppendStr(&buf, zSep, &rc);
if( bStat1 && ii==1 ){
assert( sqlite3_stricmp(p->azCol[ii], "idx")==0 );
sessionAppendStr(&buf,
"idx IS CASE "
"WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL "
"ELSE ?4 END ", &rc
);
}else{
sessionAppendIdent(&buf, p->azCol[ii], &rc);
sessionAppendStr(&buf, " IS ?", &rc);
sessionAppendInteger(&buf, ii*2+2, &rc);
}
zSep = " AND ";
}
}
if( rc==SQLITE_OK ){
char *zSql = (char*)buf.aBuf;
rc = sqlite3_prepare_v2(p->db, zSql, buf.nBuf, &pUp->pStmt, 0);
}
if( rc!=SQLITE_OK ){
sqlite3_free(pUp);
pUp = 0;
}else{
pUp->pNext = p->pUp;
p->pUp = pUp;
}
sqlite3_free(buf.aBuf);
}
}
}
assert( (rc==SQLITE_OK)==(pUp!=0) );
if( pUp ){
*ppStmt = pUp->pStmt;
}else{
*ppStmt = 0;
}
return rc;
}
/*
** Free all cached UPDATE statements.
*/
static void sessionUpdateFree(SessionApplyCtx *p){
SessionUpdate *pUp;
SessionUpdate *pNext;
for(pUp=p->pUp; pUp; pUp=pNext){
pNext = pUp->pNext;
sqlite3_finalize(pUp->pStmt);
sqlite3_free(pUp);
}
p->pUp = 0;
sqlite3_free(p->aUpdateMask);
p->aUpdateMask = 0;
}
/*
** Formulate a statement to DELETE a row from database db. Assuming a table
** structure like this:
**
** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
**
** The DELETE statement looks like this:
**
** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
**
** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
** matching b and d values, or 1 otherwise. The second case comes up if the
** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
**
** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
** pointing to the prepared version of the SQL statement.
*/
static int sessionDeleteRow(
sqlite3 *db, /* Database handle */
const char *zTab, /* Table name */
SessionApplyCtx *p /* Session changeset-apply context */
){
int i;
const char *zSep = "";
int rc = SQLITE_OK;
SessionBuffer buf = {0, 0, 0};
int nPk = 0;
sessionAppendStr(&buf, "DELETE FROM main.", &rc);
sessionAppendIdent(&buf, zTab, &rc);
sessionAppendStr(&buf, " WHERE ", &rc);
for(i=0; i<p->nCol; i++){
if( p->abPK[i] ){
nPk++;
sessionAppendStr(&buf, zSep, &rc);
sessionAppendIdent(&buf, p->azCol[i], &rc);
sessionAppendStr(&buf, " = ?", &rc);
sessionAppendInteger(&buf, i+1, &rc);
zSep = " AND ";
}
}
if( nPk<p->nCol ){
sessionAppendStr(&buf, " AND (?", &rc);
sessionAppendInteger(&buf, p->nCol+1, &rc);
sessionAppendStr(&buf, " OR ", &rc);
zSep = "";
for(i=0; i<p->nCol; i++){
if( !p->abPK[i] ){
sessionAppendStr(&buf, zSep, &rc);
sessionAppendIdent(&buf, p->azCol[i], &rc);
sessionAppendStr(&buf, " IS ?", &rc);
sessionAppendInteger(&buf, i+1, &rc);
zSep = "AND ";
}
}
sessionAppendStr(&buf, ")", &rc);
}
if( rc==SQLITE_OK ){
rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
}
sqlite3_free(buf.aBuf);
return rc;
}
/*
** Formulate and prepare an SQL statement to query table zTab by primary
** key. Assuming the following table structure:
**
** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
**
** The SELECT statement looks like this:
**
** SELECT * FROM x WHERE a = ?1 AND c = ?3
**
** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
** pointing to the prepared version of the SQL statement.
*/
static int sessionSelectRow(
sqlite3 *db, /* Database handle */
const char *zTab, /* Table name */
SessionApplyCtx *p /* Session changeset-apply context */
){
return sessionSelectStmt(
db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
}
/*
** Formulate and prepare an INSERT statement to add a record to table zTab.
** For example:
**
** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
**
** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
** pointing to the prepared version of the SQL statement.
*/
static int sessionInsertRow(
sqlite3 *db, /* Database handle */
const char *zTab, /* Table name */
SessionApplyCtx *p /* Session changeset-apply context */
){
int rc = SQLITE_OK;
int i;
SessionBuffer buf = {0, 0, 0};
sessionAppendStr(&buf, "INSERT INTO main.", &rc);
sessionAppendIdent(&buf, zTab, &rc);
sessionAppendStr(&buf, "(", &rc);
for(i=0; i<p->nCol; i++){
if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
sessionAppendIdent(&buf, p->azCol[i], &rc);
}
sessionAppendStr(&buf, ") VALUES(?", &rc);
for(i=1; i<p->nCol; i++){
sessionAppendStr(&buf, ", ?", &rc);
}
sessionAppendStr(&buf, ")", &rc);
if( rc==SQLITE_OK ){
rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
}
sqlite3_free(buf.aBuf);
return rc;
}
static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){
return sqlite3_prepare_v2(db, zSql, -1, pp, 0);
}
/*
** Prepare statements for applying changes to the sqlite_stat1 table.
** These are similar to those created by sessionSelectRow(),
** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for
** other tables.
*/
static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
int rc = sessionSelectRow(db, "sqlite_stat1", p);
if( rc==SQLITE_OK ){
rc = sessionPrepare(db, &p->pInsert,
"INSERT INTO main.sqlite_stat1 VALUES(?1, "
"CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, "
"?3)"
);
}
if( rc==SQLITE_OK ){
rc = sessionPrepare(db, &p->pDelete,
"DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS "
"CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END "
"AND (?4 OR stat IS ?3)"
);
}
return rc;
}
/*
** A wrapper around sqlite3_bind_value() that detects an extra problem.
** See comments in the body of this function for details.
*/
static int sessionBindValue(
sqlite3_stmt *pStmt, /* Statement to bind value to */
int i, /* Parameter number to bind to */
sqlite3_value *pVal /* Value to bind */
){
int eType = sqlite3_value_type(pVal);
/* COVERAGE: The (pVal->z==0) branch is never true using current versions
** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
** the (pVal->z) variable remains as it was or the type of the value is
** set to SQLITE_NULL. */
if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
/* This condition occurs when an earlier OOM in a call to
** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
return SQLITE_NOMEM;
}
return sqlite3_bind_value(pStmt, i, pVal);
}
/*
** Iterator pIter must point to an SQLITE_INSERT entry. This function
** transfers new.* values from the current iterator entry to statement
** pStmt. The table being inserted into has nCol columns.
**
** New.* value $i from the iterator is bound to variable ($i+1) of
** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
** are transfered to the statement. Otherwise, if abPK is not NULL, it points
** to an array nCol elements in size. In this case only those values for
** which abPK[$i] is true are read from the iterator and bound to the
** statement.
**
** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
*/
static int sessionBindRow(
sqlite3_changeset_iter *pIter, /* Iterator to read values from */
int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
int nCol, /* Number of columns */
u8 *abPK, /* If not NULL, bind only if true */
sqlite3_stmt *pStmt /* Bind values to this statement */
){
int i;
int rc = SQLITE_OK;
/* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
** argument iterator points to a suitable entry. Make sure that xValue
** is one of these to guarantee that it is safe to ignore the return
** in the code below. */
assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
for(i=0; rc==SQLITE_OK && i<nCol; i++){
if( !abPK || abPK[i] ){
sqlite3_value *pVal = 0;
(void)xValue(pIter, i, &pVal);
if( pVal==0 ){
/* The value in the changeset was "undefined". This indicates a
** corrupt changeset blob. */
rc = SQLITE_CORRUPT_BKPT;
}else{
rc = sessionBindValue(pStmt, i+1, pVal);
}
}
}
return rc;
}
/*
** SQL statement pSelect is as generated by the sessionSelectRow() function.
** This function binds the primary key values from the change that changeset
** iterator pIter points to to the SELECT and attempts to seek to the table
** entry. If a row is found, the SELECT statement left pointing at the row
** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
** has occured, the statement is reset and SQLITE_OK is returned. If an
** error occurs, the statement is reset and an SQLite error code is returned.
**
** If this function returns SQLITE_ROW, the caller must eventually reset()
** statement pSelect. If any other value is returned, the statement does
** not require a reset().
**
** If the iterator currently points to an INSERT record, bind values from the
** new.* record to the SELECT statement. Or, if it points to a DELETE or
** UPDATE, bind values from the old.* record.
*/
static int sessionSeekToRow(
sqlite3 *db, /* Database handle */
sqlite3_changeset_iter *pIter, /* Changeset iterator */
u8 *abPK, /* Primary key flags array */
sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
){
int rc; /* Return code */
int nCol; /* Number of columns in table */
int op; /* Changset operation (SQLITE_UPDATE etc.) */
const char *zDummy; /* Unused */
sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
rc = sessionBindRow(pIter,
op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
nCol, abPK, pSelect
);
if( rc==SQLITE_OK ){
rc = sqlite3_step(pSelect);
if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
}
return rc;
}
/*
** This function is called from within sqlite3changeset_apply_v2() when
** a conflict is encountered and resolved using conflict resolution
** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE)..
** It adds a conflict resolution record to the buffer in
** SessionApplyCtx.rebase, which will eventually be returned to the caller
** of apply_v2() as the "rebase" buffer.
**
** Return SQLITE_OK if successful, or an SQLite error code otherwise.
*/
static int sessionRebaseAdd(
SessionApplyCtx *p, /* Apply context */
int eType, /* Conflict resolution (OMIT or REPLACE) */
sqlite3_changeset_iter *pIter /* Iterator pointing at current change */
){
int rc = SQLITE_OK;
if( p->bRebase ){
int i;
int eOp = pIter->op;
if( p->bRebaseStarted==0 ){
/* Append a table-header to the rebase buffer */
const char *zTab = pIter->zTab;
sessionAppendByte(&p->rebase, 'T', &rc);
sessionAppendVarint(&p->rebase, p->nCol, &rc);
sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc);
sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc);
p->bRebaseStarted = 1;
}
assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT );
assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE );
sessionAppendByte(&p->rebase,
(eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc
);
sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc);
for(i=0; i<p->nCol; i++){
sqlite3_value *pVal = 0;
if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){
sqlite3changeset_old(pIter, i, &pVal);
}else{
sqlite3changeset_new(pIter, i, &pVal);
}
sessionAppendValue(&p->rebase, pVal, &rc);
}
}
return rc;
}
/*
** Invoke the conflict handler for the change that the changeset iterator
** currently points to.
**
** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
** If argument pbReplace is NULL, then the type of conflict handler invoked
** depends solely on eType, as follows:
**
** eType value Value passed to xConflict
** -------------------------------------------------
** CHANGESET_DATA CHANGESET_NOTFOUND
** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
**
** Or, if pbReplace is not NULL, then an attempt is made to find an existing
** record with the same primary key as the record about to be deleted, updated
** or inserted. If such a record can be found, it is available to the conflict
** handler as the "conflicting" record. In this case the type of conflict
** handler invoked is as follows:
**
** eType value PK Record found? Value passed to xConflict
** ----------------------------------------------------------------
** CHANGESET_DATA Yes CHANGESET_DATA
** CHANGESET_DATA No CHANGESET_NOTFOUND
** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
**
** If pbReplace is not NULL, and a record with a matching PK is found, and
** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
** is set to non-zero before returning SQLITE_OK.
**
** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
** returned. Or, if the conflict handler returns an invalid value,
** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
** this function returns SQLITE_OK.
*/
static int sessionConflictHandler(
int eType, /* Either CHANGESET_DATA or CONFLICT */
SessionApplyCtx *p, /* changeset_apply() context */
sqlite3_changeset_iter *pIter, /* Changeset iterator */
int(*xConflict)(void *, int, sqlite3_changeset_iter*),
void *pCtx, /* First argument for conflict handler */
int *pbReplace /* OUT: Set to true if PK row is found */
){
int res = 0; /* Value returned by conflict handler */
int rc;
int nCol;
int op;
const char *zDummy;
sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
/* Bind the new.* PRIMARY KEY values to the SELECT statement. */
if( pbReplace ){
rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
}else{
rc = SQLITE_OK;
}
if( rc==SQLITE_ROW ){
/* There exists another row with the new.* primary key. */
pIter->pConflict = p->pSelect;
res = xConflict(pCtx, eType, pIter);
pIter->pConflict = 0;
rc = sqlite3_reset(p->pSelect);
}else if( rc==SQLITE_OK ){
if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
/* Instead of invoking the conflict handler, append the change blob
** to the SessionApplyCtx.constraints buffer. */
u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
int nBlob = pIter->in.iNext - pIter->in.iCurrent;
sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
return SQLITE_OK;
}else{
/* No other row with the new.* primary key. */
res = xConflict(pCtx, eType+1, pIter);
if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
}
}
if( rc==SQLITE_OK ){
switch( res ){
case SQLITE_CHANGESET_REPLACE:
assert( pbReplace );
*pbReplace = 1;
break;
case SQLITE_CHANGESET_OMIT:
break;
case SQLITE_CHANGESET_ABORT:
rc = SQLITE_ABORT;
break;
default:
rc = SQLITE_MISUSE;
break;
}
if( rc==SQLITE_OK ){
rc = sessionRebaseAdd(p, res, pIter);
}
}
return rc;
}
/*
** Attempt to apply the change that the iterator passed as the first argument
** currently points to to the database. If a conflict is encountered, invoke
** the conflict handler callback.
**
** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
** one is encountered, update or delete the row with the matching primary key
** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
** to true before returning. In this case the caller will invoke this function
** again, this time with pbRetry set to NULL.
**
** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
** before retrying. In this case the caller attempts to remove the conflicting
** row before invoking this function again, this time with pbReplace set
** to NULL.
**
** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
** returned.
*/
static int sessionApplyOneOp(
sqlite3_changeset_iter *pIter, /* Changeset iterator */
SessionApplyCtx *p, /* changeset_apply() context */
int(*xConflict)(void *, int, sqlite3_changeset_iter *),
void *pCtx, /* First argument for the conflict handler */
int *pbReplace, /* OUT: True to remove PK row and retry */
int *pbRetry /* OUT: True to retry. */
){
const char *zDummy;
int op;
int nCol;
int rc = SQLITE_OK;
assert( p->pDelete && p->pInsert && p->pSelect );
assert( p->azCol && p->abPK );
assert( !pbReplace || *pbReplace==0 );
sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
if( op==SQLITE_DELETE ){
/* Bind values to the DELETE statement. If conflict handling is required,
** bind values for all columns and set bound variable (nCol+1) to true.
** Or, if conflict handling is not required, bind just the PK column
** values and, if it exists, set (nCol+1) to false. Conflict handling
** is not required if:
**
** * this is a patchset, or
** * (pbRetry==0), or
** * all columns of the table are PK columns (in this case there is
** no (nCol+1) variable to bind to).
*/
u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
}
if( rc!=SQLITE_OK ) return rc;
sqlite3_step(p->pDelete);
rc = sqlite3_reset(p->pDelete);
if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
rc = sessionConflictHandler(
SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
);
}else if( (rc&0xff)==SQLITE_CONSTRAINT ){
rc = sessionConflictHandler(
SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
);
}
}else if( op==SQLITE_UPDATE ){
int i;
sqlite3_stmt *pUp = 0;
int bPatchset = (pbRetry==0 || pIter->bPatchset);
rc = sessionUpdateFind(pIter, p, bPatchset, &pUp);
/* Bind values to the UPDATE statement. */
for(i=0; rc==SQLITE_OK && i<nCol; i++){
sqlite3_value *pOld = sessionChangesetOld(pIter, i);
sqlite3_value *pNew = sessionChangesetNew(pIter, i);
if( p->abPK[i] || (bPatchset==0 && pOld) ){
rc = sessionBindValue(pUp, i*2+2, pOld);
}
if( rc==SQLITE_OK && pNew ){
rc = sessionBindValue(pUp, i*2+1, pNew);
}
}
if( rc!=SQLITE_OK ) return rc;
/* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
** the result will be SQLITE_OK with 0 rows modified. */
sqlite3_step(pUp);
rc = sqlite3_reset(pUp);
if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
/* A NOTFOUND or DATA error. Search the table to see if it contains
** a row with a matching primary key. If so, this is a DATA conflict.
** Otherwise, if there is no primary key match, it is a NOTFOUND. */
rc = sessionConflictHandler(
SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
);
}else if( (rc&0xff)==SQLITE_CONSTRAINT ){
/* This is always a CONSTRAINT conflict. */
rc = sessionConflictHandler(
SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
);
}
}else{
assert( op==SQLITE_INSERT );
if( p->bStat1 ){
/* Check if there is a conflicting row. For sqlite_stat1, this needs
** to be done using a SELECT, as there is no PRIMARY KEY in the
** database schema to throw an exception if a duplicate is inserted. */
rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
if( rc==SQLITE_ROW ){
rc = SQLITE_CONSTRAINT;
sqlite3_reset(p->pSelect);
}
}
if( rc==SQLITE_OK ){
rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
if( rc!=SQLITE_OK ) return rc;
sqlite3_step(p->pInsert);
rc = sqlite3_reset(p->pInsert);
}
if( (rc&0xff)==SQLITE_CONSTRAINT ){
rc = sessionConflictHandler(
SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
);
}
}
return rc;
}
/*
** Attempt to apply the change that the iterator passed as the first argument
** currently points to to the database. If a conflict is encountered, invoke
** the conflict handler callback.
**
** The difference between this function and sessionApplyOne() is that this
** function handles the case where the conflict-handler is invoked and
** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
** retried in some manner.
*/
static int sessionApplyOneWithRetry(
sqlite3 *db, /* Apply change to "main" db of this handle */
sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
SessionApplyCtx *pApply, /* Apply context */
int(*xConflict)(void*, int, sqlite3_changeset_iter*),
void *pCtx /* First argument passed to xConflict */
){
int bReplace = 0;
int bRetry = 0;
int rc;
rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
if( rc==SQLITE_OK ){
/* If the bRetry flag is set, the change has not been applied due to an
** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
** a row with the correct PK is present in the db, but one or more other
** fields do not contain the expected values) and the conflict handler
** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
** but pass NULL as the final argument so that sessionApplyOneOp() ignores
** the SQLITE_CHANGESET_DATA problem. */
if( bRetry ){
assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
}
/* If the bReplace flag is set, the change is an INSERT that has not
** been performed because the database already contains a row with the
** specified primary key and the conflict handler returned
** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
** before reattempting the INSERT. */
else if( bReplace ){
assert( pIter->op==SQLITE_INSERT );
rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
if( rc==SQLITE_OK ){
rc = sessionBindRow(pIter,
sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
}
if( rc==SQLITE_OK ){
sqlite3_step(pApply->pDelete);
rc = sqlite3_reset(pApply->pDelete);
}
if( rc==SQLITE_OK ){
rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
}
if( rc==SQLITE_OK ){
rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
}
}
}
return rc;
}
/*
** Retry the changes accumulated in the pApply->constraints buffer.
*/
static int sessionRetryConstraints(
sqlite3 *db,
int bPatchset,
const char *zTab,
SessionApplyCtx *pApply,
int(*xConflict)(void*, int, sqlite3_changeset_iter*),
void *pCtx /* First argument passed to xConflict */
){
int rc = SQLITE_OK;
while( pApply->constraints.nBuf ){
sqlite3_changeset_iter *pIter2 = 0;
SessionBuffer cons = pApply->constraints;
memset(&pApply->constraints, 0, sizeof(SessionBuffer));
rc = sessionChangesetStart(
&pIter2, 0, 0, cons.nBuf, cons.aBuf, pApply->bInvertConstraints, 1
);
if( rc==SQLITE_OK ){
size_t nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
int rc2;
pIter2->bPatchset = bPatchset;
pIter2->zTab = (char*)zTab;
pIter2->nCol = pApply->nCol;
pIter2->abPK = pApply->abPK;
sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
}
rc2 = sqlite3changeset_finalize(pIter2);
if( rc==SQLITE_OK ) rc = rc2;
}
assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
sqlite3_free(cons.aBuf);
if( rc!=SQLITE_OK ) break;
if( pApply->constraints.nBuf>=cons.nBuf ){
/* No progress was made on the last round. */
pApply->bDeferConstraints = 0;
}
}
return rc;
}
/*
** Argument pIter is a changeset iterator that has been initialized, but
** not yet passed to sqlite3changeset_next(). This function applies the
** changeset to the main database attached to handle "db". The supplied
** conflict handler callback is invoked to resolve any conflicts encountered
** while applying the change.
*/
static int sessionChangesetApply(
sqlite3 *db, /* Apply change to "main" db of this handle */
sqlite3_changeset_iter *pIter, /* Changeset to apply */
int(*xFilter)(
void *pCtx, /* Copy of sixth arg to _apply() */
const char *zTab /* Table name */
),
int(*xConflict)(
void *pCtx, /* Copy of fifth arg to _apply() */
int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
sqlite3_changeset_iter *p /* Handle describing change and conflict */
),
void *pCtx, /* First argument passed to xConflict */
void **ppRebase, int *pnRebase, /* OUT: Rebase information */
int flags /* SESSION_APPLY_XXX flags */
){
int schemaMismatch = 0;
int rc = SQLITE_OK; /* Return code */
const char *zTab = 0; /* Name of current table */
int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
SessionApplyCtx sApply; /* changeset_apply() context object */
int bPatchset;
assert( xConflict!=0 );
pIter->in.bNoDiscard = 1;
memset(&sApply, 0, sizeof(sApply));
sApply.bRebase = (ppRebase && pnRebase);
sApply.bInvertConstraints = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
sqlite3_mutex_enter(sqlite3_db_mutex(db));
if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
}
if( rc==SQLITE_OK ){
rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
}
while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
int nCol;
int op;
const char *zNew;
sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
u8 *abPK;
rc = sessionRetryConstraints(
db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
);
if( rc!=SQLITE_OK ) break;
sessionUpdateFree(&sApply);
sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
sqlite3_finalize(sApply.pDelete);
sqlite3_finalize(sApply.pInsert);
sqlite3_finalize(sApply.pSelect);
sApply.db = db;
sApply.pDelete = 0;
sApply.pInsert = 0;
sApply.pSelect = 0;
sApply.nCol = 0;
sApply.azCol = 0;
sApply.abPK = 0;
sApply.bStat1 = 0;
sApply.bDeferConstraints = 1;
sApply.bRebaseStarted = 0;
memset(&sApply.constraints, 0, sizeof(SessionBuffer));
/* If an xFilter() callback was specified, invoke it now. If the
** xFilter callback returns zero, skip this table. If it returns
** non-zero, proceed. */
schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
if( schemaMismatch ){
zTab = sqlite3_mprintf("%s", zNew);
if( zTab==0 ){
rc = SQLITE_NOMEM;
break;
}
nTab = (int)strlen(zTab);
sApply.azCol = (const char **)zTab;
}else{
int nMinCol = 0;
int i;
sqlite3changeset_pk(pIter, &abPK, 0);
rc = sessionTableInfo(0,
db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
);
if( rc!=SQLITE_OK ) break;
for(i=0; i<sApply.nCol; i++){
if( sApply.abPK[i] ) nMinCol = i+1;
}
if( sApply.nCol==0 ){
schemaMismatch = 1;
sqlite3_log(SQLITE_SCHEMA,
"sqlite3changeset_apply(): no such table: %s", zTab
);
}
else if( sApply.nCol<nCol ){
schemaMismatch = 1;
sqlite3_log(SQLITE_SCHEMA,
"sqlite3changeset_apply(): table %s has %d columns, "
"expected %d or more",
zTab, sApply.nCol, nCol
);
}
else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
schemaMismatch = 1;
sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
"primary key mismatch for table %s", zTab
);
}
else{
sApply.nCol = nCol;
if( 0==sqlite3_stricmp(zTab, "sqlite_stat1") ){
if( (rc = sessionStat1Sql(db, &sApply) ) ){
break;
}
sApply.bStat1 = 1;
}else{
if( (rc = sessionSelectRow(db, zTab, &sApply))
|| (rc = sessionDeleteRow(db, zTab, &sApply))
|| (rc = sessionInsertRow(db, zTab, &sApply))
){
break;
}
sApply.bStat1 = 0;
}
}
nTab = sqlite3Strlen30(zTab);
}
}
/* If there is a schema mismatch on the current table, proceed to the
** next change. A log message has already been issued. */
if( schemaMismatch ) continue;
rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
}
bPatchset = pIter->bPatchset;
if( rc==SQLITE_OK ){
rc = sqlite3changeset_finalize(pIter);
}else{
sqlite3changeset_finalize(pIter);
}
if( rc==SQLITE_OK ){
rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
}
if( rc==SQLITE_OK ){
int nFk, notUsed;
sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, ¬Used, 0);
if( nFk!=0 ){
int res = SQLITE_CHANGESET_ABORT;
sqlite3_changeset_iter sIter;
memset(&sIter, 0, sizeof(sIter));
sIter.nCol = nFk;
res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
if( res!=SQLITE_CHANGESET_OMIT ){
rc = SQLITE_CONSTRAINT;
}
}
}
sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
if( rc==SQLITE_OK ){
rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
}else{
sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
}
}
assert( sApply.bRebase || sApply.rebase.nBuf==0 );
if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){
*ppRebase = (void*)sApply.rebase.aBuf;
*pnRebase = sApply.rebase.nBuf;
sApply.rebase.aBuf = 0;
}
sessionUpdateFree(&sApply);
sqlite3_finalize(sApply.pInsert);
sqlite3_finalize(sApply.pDelete);
sqlite3_finalize(sApply.pSelect);
sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
sqlite3_free((char*)sApply.constraints.aBuf);
sqlite3_free((char*)sApply.rebase.aBuf);
sqlite3_mutex_leave(sqlite3_db_mutex(db));
return rc;
}
/*
** Apply the changeset passed via pChangeset/nChangeset to the main
** database attached to handle "db".
*/
int sqlite3changeset_apply_v2(
sqlite3 *db, /* Apply change to "main" db of this handle */
int nChangeset, /* Size of changeset in bytes */
void *pChangeset, /* Changeset blob */
int(*xFilter)(
void *pCtx, /* Copy of sixth arg to _apply() */
const char *zTab /* Table name */
),
int(*xConflict)(
void *pCtx, /* Copy of sixth arg to _apply() */
int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
sqlite3_changeset_iter *p /* Handle describing change and conflict */
),
void *pCtx, /* First argument passed to xConflict */
void **ppRebase, int *pnRebase,
int flags
){
sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
int bInv = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset, bInv, 1);
if( rc==SQLITE_OK ){
rc = sessionChangesetApply(
db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
);
}
return rc;
}
/*
** Apply the changeset passed via pChangeset/nChangeset to the main database
** attached to handle "db". Invoke the supplied conflict handler callback
** to resolve any conflicts encountered while applying the change.
*/
int sqlite3changeset_apply(
sqlite3 *db, /* Apply change to "main" db of this handle */
int nChangeset, /* Size of changeset in bytes */
void *pChangeset, /* Changeset blob */
int(*xFilter)(
void *pCtx, /* Copy of sixth arg to _apply() */
const char *zTab /* Table name */
),
int(*xConflict)(
void *pCtx, /* Copy of fifth arg to _apply() */
int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
sqlite3_changeset_iter *p /* Handle describing change and conflict */
),
void *pCtx /* First argument passed to xConflict */
){
return sqlite3changeset_apply_v2(
db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0
);
}
/*
** Apply the changeset passed via xInput/pIn to the main database
** attached to handle "db". Invoke the supplied conflict handler callback
** to resolve any conflicts encountered while applying the change.
*/
int sqlite3changeset_apply_v2_strm(
sqlite3 *db, /* Apply change to "main" db of this handle */
int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
void *pIn, /* First arg for xInput */
int(*xFilter)(
void *pCtx, /* Copy of sixth arg to _apply() */
const char *zTab /* Table name */
),
int(*xConflict)(
void *pCtx, /* Copy of sixth arg to _apply() */
int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
sqlite3_changeset_iter *p /* Handle describing change and conflict */
),
void *pCtx, /* First argument passed to xConflict */
void **ppRebase, int *pnRebase,
int flags
){
sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse, 1);
if( rc==SQLITE_OK ){
rc = sessionChangesetApply(
db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
);
}
return rc;
}
int sqlite3changeset_apply_strm(
sqlite3 *db, /* Apply change to "main" db of this handle */
int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
void *pIn, /* First arg for xInput */
int(*xFilter)(
void *pCtx, /* Copy of sixth arg to _apply() */
const char *zTab /* Table name */
),
int(*xConflict)(
void *pCtx, /* Copy of sixth arg to _apply() */
int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
sqlite3_changeset_iter *p /* Handle describing change and conflict */
),
void *pCtx /* First argument passed to xConflict */
){
return sqlite3changeset_apply_v2_strm(
db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0
);
}
/*
** sqlite3_changegroup handle.
*/
struct sqlite3_changegroup {
int rc; /* Error code */
int bPatch; /* True to accumulate patchsets */
SessionTable *pList; /* List of tables in current patch */
};
/*
** This function is called to merge two changes to the same row together as
** part of an sqlite3changeset_concat() operation. A new change object is
** allocated and a pointer to it stored in *ppNew.
*/
static int sessionChangeMerge(
SessionTable *pTab, /* Table structure */
int bRebase, /* True for a rebase hash-table */
int bPatchset, /* True for patchsets */
SessionChange *pExist, /* Existing change */
int op2, /* Second change operation */
int bIndirect, /* True if second change is indirect */
u8 *aRec, /* Second change record */
int nRec, /* Number of bytes in aRec */
SessionChange **ppNew /* OUT: Merged change */
){
SessionChange *pNew = 0;
int rc = SQLITE_OK;
if( !pExist ){
pNew = (SessionChange *)sqlite3_malloc64(sizeof(SessionChange) + nRec);
if( !pNew ){
return SQLITE_NOMEM;
}
memset(pNew, 0, sizeof(SessionChange));
pNew->op = op2;
pNew->bIndirect = bIndirect;
pNew->aRecord = (u8*)&pNew[1];
if( bIndirect==0 || bRebase==0 ){
pNew->nRecord = nRec;
memcpy(pNew->aRecord, aRec, nRec);
}else{
int i;
u8 *pIn = aRec;
u8 *pOut = pNew->aRecord;
for(i=0; i<pTab->nCol; i++){
int nIn = sessionSerialLen(pIn);
if( *pIn==0 ){
*pOut++ = 0;
}else if( pTab->abPK[i]==0 ){
*pOut++ = 0xFF;
}else{
memcpy(pOut, pIn, nIn);
pOut += nIn;
}
pIn += nIn;
}
pNew->nRecord = pOut - pNew->aRecord;
}
}else if( bRebase ){
if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){
*ppNew = pExist;
}else{
sqlite3_int64 nByte = nRec + pExist->nRecord + sizeof(SessionChange);
pNew = (SessionChange*)sqlite3_malloc64(nByte);
if( pNew==0 ){
rc = SQLITE_NOMEM;
}else{
int i;
u8 *a1 = pExist->aRecord;
u8 *a2 = aRec;
u8 *pOut;
memset(pNew, 0, nByte);
pNew->bIndirect = bIndirect || pExist->bIndirect;
pNew->op = op2;
pOut = pNew->aRecord = (u8*)&pNew[1];
for(i=0; i<pTab->nCol; i++){
int n1 = sessionSerialLen(a1);
int n2 = sessionSerialLen(a2);
if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){
*pOut++ = 0xFF;
}else if( *a2==0 ){
memcpy(pOut, a1, n1);
pOut += n1;
}else{
memcpy(pOut, a2, n2);
pOut += n2;
}
a1 += n1;
a2 += n2;
}
pNew->nRecord = pOut - pNew->aRecord;
}
sqlite3_free(pExist);
}
}else{
int op1 = pExist->op;
/*
** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
** op1=INSERT, op2=UPDATE -> INSERT.
** op1=INSERT, op2=DELETE -> (none)
**
** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
** op1=UPDATE, op2=UPDATE -> UPDATE.
** op1=UPDATE, op2=DELETE -> DELETE.
**
** op1=DELETE, op2=INSERT -> UPDATE.
** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
*/
if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
|| (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
|| (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
|| (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
){
pNew = pExist;
}else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
sqlite3_free(pExist);
assert( pNew==0 );
}else{
u8 *aExist = pExist->aRecord;
sqlite3_int64 nByte;
u8 *aCsr;
/* Allocate a new SessionChange object. Ensure that the aRecord[]
** buffer of the new object is large enough to hold any record that
** may be generated by combining the input records. */
nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
pNew = (SessionChange *)sqlite3_malloc64(nByte);
if( !pNew ){
sqlite3_free(pExist);
return SQLITE_NOMEM;
}
memset(pNew, 0, sizeof(SessionChange));
pNew->bIndirect = (bIndirect && pExist->bIndirect);
aCsr = pNew->aRecord = (u8 *)&pNew[1];
if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
u8 *a1 = aRec;
assert( op2==SQLITE_UPDATE );
pNew->op = SQLITE_INSERT;
if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
}else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
assert( op2==SQLITE_INSERT );
pNew->op = SQLITE_UPDATE;
if( bPatchset ){
memcpy(aCsr, aRec, nRec);
aCsr += nRec;
}else{
if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
sqlite3_free(pNew);
pNew = 0;
}
}
}else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
u8 *a1 = aExist;
u8 *a2 = aRec;
assert( op1==SQLITE_UPDATE );
if( bPatchset==0 ){
sessionSkipRecord(&a1, pTab->nCol);
sessionSkipRecord(&a2, pTab->nCol);
}
pNew->op = SQLITE_UPDATE;
if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
sqlite3_free(pNew);
pNew = 0;
}
}else{ /* UPDATE + DELETE */
assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
pNew->op = SQLITE_DELETE;
if( bPatchset ){
memcpy(aCsr, aRec, nRec);
aCsr += nRec;
}else{
sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
}
}
if( pNew ){
pNew->nRecord = (int)(aCsr - pNew->aRecord);
}
sqlite3_free(pExist);
}
}
*ppNew = pNew;
return rc;
}
/*
** Add all changes in the changeset traversed by the iterator passed as
** the first argument to the changegroup hash tables.
*/
static int sessionChangesetToHash(
sqlite3_changeset_iter *pIter, /* Iterator to read from */
sqlite3_changegroup *pGrp, /* Changegroup object to add changeset to */
int bRebase /* True if hash table is for rebasing */
){
u8 *aRec;
int nRec;
int rc = SQLITE_OK;
SessionTable *pTab = 0;
while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, 0) ){
const char *zNew;
int nCol;
int op;
int iHash;
int bIndirect;
SessionChange *pChange;
SessionChange *pExist = 0;
SessionChange **pp;
if( pGrp->pList==0 ){
pGrp->bPatch = pIter->bPatchset;
}else if( pIter->bPatchset!=pGrp->bPatch ){
rc = SQLITE_ERROR;
break;
}
sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
/* Search the list for a matching table */
int nNew = (int)strlen(zNew);
u8 *abPK;
sqlite3changeset_pk(pIter, &abPK, 0);
for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
}
if( !pTab ){
SessionTable **ppTab;
pTab = sqlite3_malloc64(sizeof(SessionTable) + nCol + nNew+1);
if( !pTab ){
rc = SQLITE_NOMEM;
break;
}
memset(pTab, 0, sizeof(SessionTable));
pTab->nCol = nCol;
pTab->abPK = (u8*)&pTab[1];
memcpy(pTab->abPK, abPK, nCol);
pTab->zName = (char*)&pTab->abPK[nCol];
memcpy(pTab->zName, zNew, nNew+1);
/* The new object must be linked on to the end of the list, not
** simply added to the start of it. This is to ensure that the
** tables within the output of sqlite3changegroup_output() are in
** the right order. */
for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
*ppTab = pTab;
}else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
rc = SQLITE_SCHEMA;
break;
}
}
if( sessionGrowHash(0, pIter->bPatchset, pTab) ){
rc = SQLITE_NOMEM;
break;
}
iHash = sessionChangeHash(
pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
);
/* Search for existing entry. If found, remove it from the hash table.
** Code below may link it back in.
*/
for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
int bPkOnly1 = 0;
int bPkOnly2 = 0;
if( pIter->bPatchset ){
bPkOnly1 = (*pp)->op==SQLITE_DELETE;
bPkOnly2 = op==SQLITE_DELETE;
}
if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
pExist = *pp;
*pp = (*pp)->pNext;
pTab->nEntry--;
break;
}
}
rc = sessionChangeMerge(pTab, bRebase,
pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
);
if( rc ) break;
if( pChange ){
pChange->pNext = pTab->apChange[iHash];
pTab->apChange[iHash] = pChange;
pTab->nEntry++;
}
}
if( rc==SQLITE_OK ) rc = pIter->rc;
return rc;
}
/*
** Serialize a changeset (or patchset) based on all changesets (or patchsets)
** added to the changegroup object passed as the first argument.
**
** If xOutput is not NULL, then the changeset/patchset is returned to the
** user via one or more calls to xOutput, as with the other streaming
** interfaces.
**
** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
** buffer containing the output changeset before this function returns. In
** this case (*pnOut) is set to the size of the output buffer in bytes. It
** is the responsibility of the caller to free the output buffer using
** sqlite3_free() when it is no longer required.
**
** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
** are both set to 0 before returning.
*/
static int sessionChangegroupOutput(
sqlite3_changegroup *pGrp,
int (*xOutput)(void *pOut, const void *pData, int nData),
void *pOut,
int *pnOut,
void **ppOut
){
int rc = SQLITE_OK;
SessionBuffer buf = {0, 0, 0};
SessionTable *pTab;
assert( xOutput==0 || (ppOut==0 && pnOut==0) );
/* Create the serialized output changeset based on the contents of the
** hash tables attached to the SessionTable objects in list p->pList.
*/
for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
int i;
if( pTab->nEntry==0 ) continue;
sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
for(i=0; i<pTab->nChange; i++){
SessionChange *p;
for(p=pTab->apChange[i]; p; p=p->pNext){
sessionAppendByte(&buf, p->op, &rc);
sessionAppendByte(&buf, p->bIndirect, &rc);
sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
if( rc==SQLITE_OK && xOutput && buf.nBuf>=sessions_strm_chunk_size ){
rc = xOutput(pOut, buf.aBuf, buf.nBuf);
buf.nBuf = 0;
}
}
}
}
if( rc==SQLITE_OK ){
if( xOutput ){
if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
}else if( ppOut ){
*ppOut = buf.aBuf;
if( pnOut ) *pnOut = buf.nBuf;
buf.aBuf = 0;
}
}
sqlite3_free(buf.aBuf);
return rc;
}
/*
** Allocate a new, empty, sqlite3_changegroup.
*/
int sqlite3changegroup_new(sqlite3_changegroup **pp){
int rc = SQLITE_OK; /* Return code */
sqlite3_changegroup *p; /* New object */
p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
if( p==0 ){
rc = SQLITE_NOMEM;
}else{
memset(p, 0, sizeof(sqlite3_changegroup));
}
*pp = p;
return rc;
}
/*
** Add the changeset currently stored in buffer pData, size nData bytes,
** to changeset-group p.
*/
int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
int rc; /* Return code */
rc = sqlite3changeset_start(&pIter, nData, pData);
if( rc==SQLITE_OK ){
rc = sessionChangesetToHash(pIter, pGrp, 0);
}
sqlite3changeset_finalize(pIter);
return rc;
}
/*
** Obtain a buffer containing a changeset representing the concatenation
** of all changesets added to the group so far.
*/
int sqlite3changegroup_output(
sqlite3_changegroup *pGrp,
int *pnData,
void **ppData
){
return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
}
/*
** Streaming versions of changegroup_add().
*/
int sqlite3changegroup_add_strm(
sqlite3_changegroup *pGrp,
int (*xInput)(void *pIn, void *pData, int *pnData),
void *pIn
){
sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
int rc; /* Return code */
rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
if( rc==SQLITE_OK ){
rc = sessionChangesetToHash(pIter, pGrp, 0);
}
sqlite3changeset_finalize(pIter);
return rc;
}
/*
** Streaming versions of changegroup_output().
*/
int sqlite3changegroup_output_strm(
sqlite3_changegroup *pGrp,
int (*xOutput)(void *pOut, const void *pData, int nData),
void *pOut
){
return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
}
/*
** Delete a changegroup object.
*/
void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
if( pGrp ){
sessionDeleteTable(0, pGrp->pList);
sqlite3_free(pGrp);
}
}
/*
** Combine two changesets together.
*/
int sqlite3changeset_concat(
int nLeft, /* Number of bytes in lhs input */
void *pLeft, /* Lhs input changeset */
int nRight /* Number of bytes in rhs input */,
void *pRight, /* Rhs input changeset */
int *pnOut, /* OUT: Number of bytes in output changeset */
void **ppOut /* OUT: changeset (left <concat> right) */
){
sqlite3_changegroup *pGrp;
int rc;
rc = sqlite3changegroup_new(&pGrp);
if( rc==SQLITE_OK ){
rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
}
if( rc==SQLITE_OK ){
rc = sqlite3changegroup_add(pGrp, nRight, pRight);
}
if( rc==SQLITE_OK ){
rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
}
sqlite3changegroup_delete(pGrp);
return rc;
}
/*
** Streaming version of sqlite3changeset_concat().
*/
int sqlite3changeset_concat_strm(
int (*xInputA)(void *pIn, void *pData, int *pnData),
void *pInA,
int (*xInputB)(void *pIn, void *pData, int *pnData),
void *pInB,
int (*xOutput)(void *pOut, const void *pData, int nData),
void *pOut
){
sqlite3_changegroup *pGrp;
int rc;
rc = sqlite3changegroup_new(&pGrp);
if( rc==SQLITE_OK ){
rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
}
if( rc==SQLITE_OK ){
rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
}
if( rc==SQLITE_OK ){
rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
}
sqlite3changegroup_delete(pGrp);
return rc;
}
/*
** Changeset rebaser handle.
*/
struct sqlite3_rebaser {
sqlite3_changegroup grp; /* Hash table */
};
/*
** Buffers a1 and a2 must both contain a sessions module record nCol
** fields in size. This function appends an nCol sessions module
** record to buffer pBuf that is a copy of a1, except that for
** each field that is undefined in a1[], swap in the field from a2[].
*/
static void sessionAppendRecordMerge(
SessionBuffer *pBuf, /* Buffer to append to */
int nCol, /* Number of columns in each record */
u8 *a1, int n1, /* Record 1 */
u8 *a2, int n2, /* Record 2 */
int *pRc /* IN/OUT: error code */
){
sessionBufferGrow(pBuf, n1+n2, pRc);
if( *pRc==SQLITE_OK ){
int i;
u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
for(i=0; i<nCol; i++){
int nn1 = sessionSerialLen(a1);
int nn2 = sessionSerialLen(a2);
if( *a1==0 || *a1==0xFF ){
memcpy(pOut, a2, nn2);
pOut += nn2;
}else{
memcpy(pOut, a1, nn1);
pOut += nn1;
}
a1 += nn1;
a2 += nn2;
}
pBuf->nBuf = pOut-pBuf->aBuf;
assert( pBuf->nBuf<=pBuf->nAlloc );
}
}
/*
** This function is called when rebasing a local UPDATE change against one
** or more remote UPDATE changes. The aRec/nRec buffer contains the current
** old.* and new.* records for the change. The rebase buffer (a single
** record) is in aChange/nChange. The rebased change is appended to buffer
** pBuf.
**
** Rebasing the UPDATE involves:
**
** * Removing any changes to fields for which the corresponding field
** in the rebase buffer is set to "replaced" (type 0xFF). If this
** means the UPDATE change updates no fields, nothing is appended
** to the output buffer.
**
** * For each field modified by the local change for which the
** corresponding field in the rebase buffer is not "undefined" (0x00)
** or "replaced" (0xFF), the old.* value is replaced by the value
** in the rebase buffer.
*/
static void sessionAppendPartialUpdate(
SessionBuffer *pBuf, /* Append record here */
sqlite3_changeset_iter *pIter, /* Iterator pointed at local change */
u8 *aRec, int nRec, /* Local change */
u8 *aChange, int nChange, /* Record to rebase against */
int *pRc /* IN/OUT: Return Code */
){
sessionBufferGrow(pBuf, 2+nRec+nChange, pRc);
if( *pRc==SQLITE_OK ){
int bData = 0;
u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
int i;
u8 *a1 = aRec;
u8 *a2 = aChange;
*pOut++ = SQLITE_UPDATE;
*pOut++ = pIter->bIndirect;
for(i=0; i<pIter->nCol; i++){
int n1 = sessionSerialLen(a1);
int n2 = sessionSerialLen(a2);
if( pIter->abPK[i] || a2[0]==0 ){
if( !pIter->abPK[i] && a1[0] ) bData = 1;
memcpy(pOut, a1, n1);
pOut += n1;
}else if( a2[0]!=0xFF ){
bData = 1;
memcpy(pOut, a2, n2);
pOut += n2;
}else{
*pOut++ = '\0';
}
a1 += n1;
a2 += n2;
}
if( bData ){
a2 = aChange;
for(i=0; i<pIter->nCol; i++){
int n1 = sessionSerialLen(a1);
int n2 = sessionSerialLen(a2);
if( pIter->abPK[i] || a2[0]!=0xFF ){
memcpy(pOut, a1, n1);
pOut += n1;
}else{
*pOut++ = '\0';
}
a1 += n1;
a2 += n2;
}
pBuf->nBuf = (pOut - pBuf->aBuf);
}
}
}
/*
** pIter is configured to iterate through a changeset. This function rebases
** that changeset according to the current configuration of the rebaser
** object passed as the first argument. If no error occurs and argument xOutput
** is not NULL, then the changeset is returned to the caller by invoking
** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL,
** then (*ppOut) is set to point to a buffer containing the rebased changeset
** before this function returns. In this case (*pnOut) is set to the size of
** the buffer in bytes. It is the responsibility of the caller to eventually
** free the (*ppOut) buffer using sqlite3_free().
**
** If an error occurs, an SQLite error code is returned. If ppOut and
** pnOut are not NULL, then the two output parameters are set to 0 before
** returning.
*/
static int sessionRebase(
sqlite3_rebaser *p, /* Rebaser hash table */
sqlite3_changeset_iter *pIter, /* Input data */
int (*xOutput)(void *pOut, const void *pData, int nData),
void *pOut, /* Context for xOutput callback */
int *pnOut, /* OUT: Number of bytes in output changeset */
void **ppOut /* OUT: Inverse of pChangeset */
){
int rc = SQLITE_OK;
u8 *aRec = 0;
int nRec = 0;
int bNew = 0;
SessionTable *pTab = 0;
SessionBuffer sOut = {0,0,0};
while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){
SessionChange *pChange = 0;
int bDone = 0;
if( bNew ){
const char *zTab = pIter->zTab;
for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){
if( 0==sqlite3_stricmp(pTab->zName, zTab) ) break;
}
bNew = 0;
/* A patchset may not be rebased */
if( pIter->bPatchset ){
rc = SQLITE_ERROR;
}
/* Append a table header to the output for this new table */
sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc);
sessionAppendVarint(&sOut, pIter->nCol, &rc);
sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc);
sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc);
}
if( pTab && rc==SQLITE_OK ){
int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange);
for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){
if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){
break;
}
}
}
if( pChange ){
assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT );
switch( pIter->op ){
case SQLITE_INSERT:
if( pChange->op==SQLITE_INSERT ){
bDone = 1;
if( pChange->bIndirect==0 ){
sessionAppendByte(&sOut, SQLITE_UPDATE, &rc);
sessionAppendByte(&sOut, pIter->bIndirect, &rc);
sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc);
sessionAppendBlob(&sOut, aRec, nRec, &rc);
}
}
break;
case SQLITE_UPDATE:
bDone = 1;
if( pChange->op==SQLITE_DELETE ){
if( pChange->bIndirect==0 ){
u8 *pCsr = aRec;
sessionSkipRecord(&pCsr, pIter->nCol);
sessionAppendByte(&sOut, SQLITE_INSERT, &rc);
sessionAppendByte(&sOut, pIter->bIndirect, &rc);
sessionAppendRecordMerge(&sOut, pIter->nCol,
pCsr, nRec-(pCsr-aRec),
pChange->aRecord, pChange->nRecord, &rc
);
}
}else{
sessionAppendPartialUpdate(&sOut, pIter,
aRec, nRec, pChange->aRecord, pChange->nRecord, &rc
);
}
break;
default:
assert( pIter->op==SQLITE_DELETE );
bDone = 1;
if( pChange->op==SQLITE_INSERT ){
sessionAppendByte(&sOut, SQLITE_DELETE, &rc);
sessionAppendByte(&sOut, pIter->bIndirect, &rc);
sessionAppendRecordMerge(&sOut, pIter->nCol,
pChange->aRecord, pChange->nRecord, aRec, nRec, &rc
);
}
break;
}
}
if( bDone==0 ){
sessionAppendByte(&sOut, pIter->op, &rc);
sessionAppendByte(&sOut, pIter->bIndirect, &rc);
sessionAppendBlob(&sOut, aRec, nRec, &rc);
}
if( rc==SQLITE_OK && xOutput && sOut.nBuf>sessions_strm_chunk_size ){
rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
sOut.nBuf = 0;
}
if( rc ) break;
}
if( rc!=SQLITE_OK ){
sqlite3_free(sOut.aBuf);
memset(&sOut, 0, sizeof(sOut));
}
if( rc==SQLITE_OK ){
if( xOutput ){
if( sOut.nBuf>0 ){
rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
}
}else if( ppOut ){
*ppOut = (void*)sOut.aBuf;
*pnOut = sOut.nBuf;
sOut.aBuf = 0;
}
}
sqlite3_free(sOut.aBuf);
return rc;
}
/*
** Create a new rebaser object.
*/
int sqlite3rebaser_create(sqlite3_rebaser **ppNew){
int rc = SQLITE_OK;
sqlite3_rebaser *pNew;
pNew = sqlite3_malloc(sizeof(sqlite3_rebaser));
if( pNew==0 ){
rc = SQLITE_NOMEM;
}else{
memset(pNew, 0, sizeof(sqlite3_rebaser));
}
*ppNew = pNew;
return rc;
}
/*
** Call this one or more times to configure a rebaser.
*/
int sqlite3rebaser_configure(
sqlite3_rebaser *p,
int nRebase, const void *pRebase
){
sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */
int rc; /* Return code */
rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);
if( rc==SQLITE_OK ){
rc = sessionChangesetToHash(pIter, &p->grp, 1);
}
sqlite3changeset_finalize(pIter);
return rc;
}
/*
** Rebase a changeset according to current rebaser configuration
*/
int sqlite3rebaser_rebase(
sqlite3_rebaser *p,
int nIn, const void *pIn,
int *pnOut, void **ppOut
){
sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn);
if( rc==SQLITE_OK ){
rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut);
sqlite3changeset_finalize(pIter);
}
return rc;
}
/*
** Rebase a changeset according to current rebaser configuration
*/
int sqlite3rebaser_rebase_strm(
sqlite3_rebaser *p,
int (*xInput)(void *pIn, void *pData, int *pnData),
void *pIn,
int (*xOutput)(void *pOut, const void *pData, int nData),
void *pOut
){
sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
if( rc==SQLITE_OK ){
rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0);
sqlite3changeset_finalize(pIter);
}
return rc;
}
/*
** Destroy a rebaser object
*/
void sqlite3rebaser_delete(sqlite3_rebaser *p){
if( p ){
sessionDeleteTable(0, p->grp.pList);
sqlite3_free(p);
}
}
/*
** Global configuration
*/
int sqlite3session_config(int op, void *pArg){
int rc = SQLITE_OK;
switch( op ){
case SQLITE_SESSION_CONFIG_STRMSIZE: {
int *pInt = (int*)pArg;
if( *pInt>0 ){
sessions_strm_chunk_size = *pInt;
}
*pInt = sessions_strm_chunk_size;
break;
}
default:
rc = SQLITE_MISUSE;
break;
}
return rc;
}
#endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
|
the_stack_data/105802.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 long input[1] , unsigned long output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void RandomFunc(unsigned long input[1] , unsigned long output[1] )
{
unsigned long state[1] ;
char copy11 ;
unsigned short copy12 ;
{
state[0UL] = (input[0UL] + 51238316UL) + 274866410UL;
if ((state[0UL] >> 4UL) & 1UL) {
state[0UL] += state[0UL];
state[0UL] += state[0UL];
} else {
copy11 = *((char *)(& state[0UL]) + 3);
*((char *)(& state[0UL]) + 3) = *((char *)(& state[0UL]) + 2);
*((char *)(& state[0UL]) + 2) = copy11;
copy12 = *((unsigned short *)(& state[0UL]) + 3);
*((unsigned short *)(& state[0UL]) + 3) = *((unsigned short *)(& state[0UL]) + 2);
*((unsigned short *)(& state[0UL]) + 2) = copy12;
copy12 = *((unsigned short *)(& state[0UL]) + 0);
*((unsigned short *)(& state[0UL]) + 0) = *((unsigned short *)(& state[0UL]) + 1);
*((unsigned short *)(& state[0UL]) + 1) = copy12;
}
output[0UL] = (state[0UL] * 943156777UL) * 495144311008221650UL;
}
}
void megaInit(void)
{
{
}
}
int main(int argc , char *argv[] )
{
unsigned long input[1] ;
unsigned long output[1] ;
int randomFuns_i5 ;
unsigned long 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 = strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 4242424242UL) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%lu\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
|
the_stack_data/48575959.c | // /*
// ** $Id: luadevil.c,v 1.1 2007-02-12 21:03:04 darkyojimbo Exp $
// ** Lua stand-alone interpreter
// ** See Copyright Notice in lua.h
// */
//
//
// #include <signal.h>
// #include <stdio.h>
// #include <stdlib.h>
// #include <string.h>
//
// #define lua_c
//
// #include "lua.h"
//
// #include "lauxlib.h"
// #include "lualib.h"
//
//
//
// static lua_State *globalL = NULL;
//
// static const char *progname = LUA_PROGNAME;
//
//
//
// static void lstop (lua_State *L, lua_Debug *ar) {
// (void)ar; /* unused arg. */
// lua_sethook(L, NULL, 0, 0);
// luaL_error(L, "interrupted!");
// }
//
//
// static void laction (int i) {
// signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
// terminate process (default action) */
// lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
// }
//
//
// static void print_usage (void) {
// fprintf(stderr,
// "usage: %s [options] [script [args]].\n"
// "Available options are:\n"
// " -e stat execute string " LUA_QL("stat") "\n"
// " -l name require library " LUA_QL("name") "\n"
// " -i enter interactive mode after executing " LUA_QL("script") "\n"
// " -v show version information\n"
// " -- stop handling options\n"
// " - execute stdin and stop handling options\n"
// ,
// progname);
// fflush(stderr);
// }
//
//
// static void l_message (const char *pname, const char *msg) {
// if (pname) fprintf(stderr, "%s: ", pname);
// fprintf(stderr, "%s\n", msg);
// fflush(stderr);
// }
//
//
// static int report (lua_State *L, int status) {
// if (status && !lua_isnil(L, -1)) {
// const char *msg = lua_tostring(L, -1);
// if (msg == NULL) msg = "(error object is not a string)";
// l_message(progname, msg);
// lua_pop(L, 1);
// }
// return status;
// }
//
//
// static int traceback (lua_State *L) {
// lua_getfield(L, LUA_GLOBALSINDEX, "debug");
// if (!lua_istable(L, -1)) {
// lua_pop(L, 1);
// return 1;
// }
// lua_getfield(L, -1, "traceback");
// if (!lua_isfunction(L, -1)) {
// lua_pop(L, 2);
// return 1;
// }
// lua_pushvalue(L, 1); /* pass error message */
// lua_pushinteger(L, 2); /* skip this function and traceback */
// lua_call(L, 2, 1); /* call debug.traceback */
// return 1;
// }
//
//
// static int docall (lua_State *L, int narg, int clear) {
// int status;
// int base = lua_gettop(L) - narg; /* function index */
// lua_pushcfunction(L, traceback); /* push traceback function */
// lua_insert(L, base); /* put it under chunk and args */
// signal(SIGINT, laction);
// status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
// signal(SIGINT, SIG_DFL);
// lua_remove(L, base); /* remove traceback function */
// /* force a complete garbage collection in case of errors */
// if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);
// return status;
// }
//
//
// static void print_version (void) {
// l_message(NULL, LUA_RELEASE " " LUA_COPYRIGHT);
// }
//
//
// static int getargs (lua_State *L, char **argv, int n) {
// int narg;
// int i;
// int argc = 0;
// while (argv[argc]) argc++; /* count total number of arguments */
// narg = argc - (n + 1); /* number of arguments to the script */
// luaL_checkstack(L, narg + 3, "too many arguments to script");
// for (i=n+1; i < argc; i++)
// lua_pushstring(L, argv[i]);
// lua_createtable(L, narg, n + 1);
// for (i=0; i < argc; i++) {
// lua_pushstring(L, argv[i]);
// lua_rawseti(L, -2, i - n);
// }
// return narg;
// }
//
//
// static int dofile (lua_State *L, const char *name) {
// int status = luaL_loadfile(L, name) || docall(L, 0, 1);
// return report(L, status);
// }
//
//
// static int dostring (lua_State *L, const char *s, const char *name) {
// int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1);
// return report(L, status);
// }
//
//
// static int dolibrary (lua_State *L, const char *name) {
// lua_getglobal(L, "require");
// lua_pushstring(L, name);
// return report(L, lua_pcall(L, 1, 0, 0));
// }
//
//
// static const char *get_prompt (lua_State *L, int firstline) {
// const char *p;
// lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
// p = lua_tostring(L, -1);
// if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
// lua_pop(L, 1); /* remove global */
// return p;
// }
//
//
// static int incomplete (lua_State *L, int status) {
// if (status == LUA_ERRSYNTAX) {
// size_t lmsg;
// const char *msg = lua_tolstring(L, -1, &lmsg);
// const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
// if (strstr(msg, LUA_QL("<eof>")) == tp) {
// lua_pop(L, 1);
// return 1;
// }
// }
// return 0; /* else... */
// }
//
//
// static int pushline (lua_State *L, int firstline) {
// char buffer[LUA_MAXINPUT];
// char *b = buffer;
// size_t l;
// const char *prmt = get_prompt(L, firstline);
// if (lua_readline(L, b, prmt) == 0)
// return 0; /* no input */
// l = strlen(b);
// if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
// b[l-1] = '\0'; /* remove it */
// if (firstline && b[0] == '=') /* first line starts with `=' ? */
// lua_pushfstring(L, "return %s", b+1); /* change it to `return' */
// else
// lua_pushstring(L, b);
// lua_freeline(L, b);
// return 1;
// }
//
//
// static int loadline (lua_State *L) {
// int status;
// lua_settop(L, 0);
// if (!pushline(L, 1))
// return -1; /* no input */
// for (;;) { /* repeat until gets a complete line */
// status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
// if (!incomplete(L, status)) break; /* cannot try to add lines? */
// if (!pushline(L, 0)) /* no more input? */
// return -1;
// lua_pushliteral(L, "\n"); /* add a new line... */
// lua_insert(L, -2); /* ...between the two lines */
// lua_concat(L, 3); /* join them */
// }
// lua_saveline(L, 1);
// lua_remove(L, 1); /* remove line */
// return status;
// }
//
//
// static void dotty (lua_State *L) {
// int status;
// const char *oldprogname = progname;
// progname = NULL;
// while ((status = loadline(L)) != -1) {
// if (status == 0) status = docall(L, 0, 0);
// report(L, status);
// if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */
// lua_getglobal(L, "print");
// lua_insert(L, 1);
// if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
// l_message(progname, lua_pushfstring(L,
// "error calling " LUA_QL("print") " (%s)",
// lua_tostring(L, -1)));
// }
// }
// lua_settop(L, 0); /* clear stack */
// fputs("\n", stdout);
// fflush(stdout);
// progname = oldprogname;
// }
//
//
// static int handle_script (lua_State *L, char **argv, int n) {
// int status;
// const char *fname;
// int narg = getargs(L, argv, n); /* collect arguments */
// lua_setglobal(L, "arg");
// fname = argv[n];
// if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
// fname = NULL; /* stdin */
// status = luaL_loadfile(L, fname);
// lua_insert(L, -(narg+1));
// if (status == 0)
// status = docall(L, narg, 0);
// else
// lua_pop(L, narg);
// return report(L, status);
// }
//
//
// /* check that argument has no extra characters at the end */
// #define notail(x) {if ((x)[2] != '\0') return -1;}
//
//
// static int collectargs (char **argv, int *pi, int *pv, int *pe) {
// int i;
// for (i = 1; argv[i] != NULL; i++) {
// if (argv[i][0] != '-') /* not an option? */
// return i;
// switch (argv[i][1]) { /* option */
// case '-':
// notail(argv[i]);
// return (argv[i+1] != NULL ? i+1 : 0);
// case '\0':
// return i;
// case 'i':
// notail(argv[i]);
// *pi = 1; /* go through */
// case 'v':
// notail(argv[i]);
// *pv = 1;
// break;
// case 'e':
// *pe = 1; /* go through */
// case 'l':
// if (argv[i][2] == '\0') {
// i++;
// if (argv[i] == NULL) return -1;
// }
// break;
// default: return -1; /* invalid option */
// }
// }
// return 0;
// }
//
//
// static int runargs (lua_State *L, char **argv, int n) {
// int i;
// for (i = 1; i < n; i++) {
// if (argv[i] == NULL) continue;
// lua_assert(argv[i][0] == '-');
// switch (argv[i][1]) { /* option */
// case 'e': {
// const char *chunk = argv[i] + 2;
// if (*chunk == '\0') chunk = argv[++i];
// lua_assert(chunk != NULL);
// if (dostring(L, chunk, "=(command line)") != 0)
// return 1;
// break;
// }
// case 'l': {
// const char *filename = argv[i] + 2;
// if (*filename == '\0') filename = argv[++i];
// lua_assert(filename != NULL);
// if (dolibrary(L, filename))
// return 1; /* stop if file fails */
// break;
// }
// default: break;
// }
// }
// return 0;
// }
//
//
// static int handle_luainit (lua_State *L) {
// const char *init = getenv(LUA_INIT);
// if (init == NULL) return 0; /* status OK */
// else if (init[0] == '@')
// return dofile(L, init+1);
// else
// return dostring(L, init, "=" LUA_INIT);
// }
//
//
// struct Smain {
// int argc;
// char **argv;
// int status;
// };
//
//
// static int pmain (lua_State *L) {
// struct Smain *s = (struct Smain *)lua_touserdata(L, 1);
// char **argv = s->argv;
// int script;
// int has_i = 0, has_v = 0, has_e = 0;
// globalL = L;
// if (argv[0] && argv[0][0]) progname = argv[0];
// lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
// luaL_openlibs(L); /* open libraries */
// lua_gc(L, LUA_GCRESTART, 0);
// s->status = handle_luainit(L);
// if (s->status != 0) return 0;
// script = collectargs(argv, &has_i, &has_v, &has_e);
// if (script < 0) { /* invalid args? */
// print_usage();
// s->status = 1;
// return 0;
// }
// if (has_v) print_version();
// s->status = runargs(L, argv, (script > 0) ? script : s->argc);
// if (s->status != 0) return 0;
// if (script)
// s->status = handle_script(L, argv, script);
// if (s->status != 0) return 0;
// if (has_i)
// dotty(L);
// else if (script == 0 && !has_e && !has_v) {
// if (lua_stdin_is_tty()) {
// print_version();
// dotty(L);
// }
// else dofile(L, NULL); /* executes stdin as a file */
// }
// return 0;
// }
//
//
// int main (int argc, char **argv) {
// int status;
// struct Smain s;
// lua_State *L = lua_open(); /* create state */
// printf("DevIL embedded lua interpreter\n");
// //@TODO: Where the heck is this defined?
// //Devil_Init(L);
// if (L == NULL) {
// l_message(argv[0], "cannot create state: not enough memory");
// return EXIT_FAILURE;
// }
// s.argc = argc;
// s.argv = argv;
// status = lua_cpcall(L, &pmain, &s);
// report(L, status);
// lua_close(L);
// return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS;
// }
//
|
the_stack_data/70449610.c | /*
* Copyright (c) 2016, 2018, Oracle and/or its affiliates.
*
* 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.
*/
int main() {
int out;
__asm__("xorl %%eax, %%eax; movb $1, %%ah; movb %%ah, %%al; xorb %%ah, %%ah;" : "=a"(out));
return out;
}
|
the_stack_data/970161.c | /************************************************************************/
/* */
/* Board_Data.c -- Board Customization Data for Digilent chipKIT WF32 */
/* */
/************************************************************************/
/* Author: Gene Apperson */
/* Copyright 2011, Digilent. All rights reserved */
/************************************************************************/
/* File Description: */
/* */
/* This file contains the board specific declartions and data structure */
/* to customize the chipKIT MPIDE for use with the Digilent chipKIT */
/* Uno32 board. */
/* */
/* This code is based on earlier work: */
/* Copyright (c) 2010, 2011 by Mark Sproul */
/* Copyright (c) 2005, 2006 by David A. Mellis */
/* */
/************************************************************************/
/* Revision History: */
/* */
/* 11/28/2011(GeneA): Created by splitting data out of Board_Defs.h */
/* */
/************************************************************************/
//* This library is free software; you can redistribute it and/or
//* modify it under the terms of the GNU Lesser General Public
//* License as published by the Free Software Foundation; either
//* version 2.1 of the License, or (at your option) any later version.
//*
//* This library is distributed in the hope that it will be useful,
//* but WITHOUT ANY WARRANTY; without even the implied warranty of
//* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//* Lesser General Public License for more details.
//*
//* You should have received a copy of the GNU Lesser General
//* Public License along with this library; if not, write to the
//* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
//* Boston, MA 02111-1307 USA
/************************************************************************/
#if !defined(BOARD_DATA_C)
#define BOARD_DATA_C
#include <inttypes.h>
/* ------------------------------------------------------------ */
/* Data Tables */
/* ------------------------------------------------------------ */
/* The following declarations define data used in pin mapping. */
/* ------------------------------------------------------------ */
#if defined(OPT_BOARD_DATA)
/* ------------------------------------------------------------ */
/* This table is used to map from port number to the address of
** the TRIS register for the port. This is used for setting the
** pin direction.
*/
const uint32_t port_to_tris_PGM[] = {
NOT_A_PORT, //index value 0 is not used
#if defined(_PORTA)
(uint32_t)&TRISA,
#else
NOT_A_PORT,
#endif
#if defined(_PORTB)
(uint32_t)&TRISB,
#else
NOT_A_PORT,
#endif
#if defined(_PORTC)
(uint32_t)&TRISC,
#else
NOT_A_PORT,
#endif
#if defined(_PORTD)
(uint32_t)&TRISD,
#else
NOT_A_PORT,
#endif
#if defined(_PORTE)
(uint32_t)&TRISE,
#else
NOT_A_PORT,
#endif
#if defined(_PORTF)
(uint32_t)&TRISF,
#else
NOT_A_PORT,
#endif
#if defined(_PORTG)
(uint32_t)&TRISG,
#else
NOT_A_PORT,
#endif
NOT_A_PORT,
};
/* ------------------------------------------------------------ */
/* This table is used to map the digital pin number to the port
** containing that pin.
*/
const uint8_t digital_pin_to_port_PGM[] = {
_IOPORT_PF, // 0 RF02 SDA3/SDI3/U1RX/RF2
_IOPORT_PF, // 1 RF08 SCL3/SDO3/U1TX/RF8
_IOPORT_PE, // 2 RE08 AERXD0/INT1/RE8
_IOPORT_PD, // 3 RD00 SDO1/OC1/INT0/RD0
_IOPORT_PF, // 4 RF01 ETXD0/PMD10/RF1
_IOPORT_PD, // 5 RD01 OC2/RD1
_IOPORT_PD, // 6 RD02 OC3/RD2
_IOPORT_PE, // 7 RE09 AERXD1/INT2/RE9
_IOPORT_PA, // 8 RA14 AETXCLK/SCL1/INT3/RA14
_IOPORT_PD, // 9 RD03 OC4/RD3
_IOPORT_PD, // 10 RD04 OC5/PMWR/CN13/RD4
_IOPORT_PG, // 11 RG08 ERXDV/AERXDV/ECRSDV/AECRSDV/SCL4/SDO2/U3TX/PMA3/CN10/RG8
_IOPORT_PG, // 12 RG07 ECRS/SDA4/SDI2/U3RX/PMA4/CN9/RG7
_IOPORT_PG, // 13 RG06 ECOL/SCK2/U6TX/U3RTS/PMA5/CN8/RG6 (SPI_SCK, User LED1)
_IOPORT_PB, // 14 RB02 AN2/C2IN-/CN4/RB2
_IOPORT_PB, // 15 RB04 AN4/C1IN-/CN6/RB4
_IOPORT_PB, // 16 RB08 AN8/C1OUT/RB8
_IOPORT_PB, // 17 RB00 PGED1/AN0/CN2/RB0
_IOPORT_PB, // 18 RB10 AN10/CVrefout/PMA13/RB10
_IOPORT_PB, // 19 RB11 AN11/ERXERR/AETXERR/PMA12/RB11
_IOPORT_PB, // 20 RB03 AN3/C2IN+/CN5/RB3
_IOPORT_PB, // 21 RB05 AN5/C1IN+/VBUSON/CN7/RB5
_IOPORT_PB, // 22 RB09 AN9/C2OUT/RB9
_IOPORT_PB, // 23 RB01 PGEC1/AN1/CN3/RB1
_IOPORT_PB, // 24 RB14 AN14/ERXD2/AETXD3/PMALH/PMA1/RB14
_IOPORT_PB, // 25 RB15 AN15/ERXD3/AETXD2/OCFB/PMALL/PMA0/CN12/RB15
_IOPORT_PE, // 26 RE00 PMD0/RE0
_IOPORT_PE, // 27 RE01 PMD1/RE1
_IOPORT_PE, // 28 RE02 PMD2/RE2
_IOPORT_PE, // 29 RE03 PMD3/RE3
_IOPORT_PE, // 30 RE04 PMD4/RE4
_IOPORT_PE, // 31 RE05 PMD5/RE5
_IOPORT_PE, // 32 RE06 PMD6/RE6
_IOPORT_PE, // 33 RE07 PMD7/RE7
_IOPORT_PD, // 34 RD05 PMRD/CN14/RD5
_IOPORT_PD, // 35 RD11 EMDC/AEMDC/IC4/PMCS1/PMA14/RD11
_IOPORT_PD, // 36 RD06 ETXEN/PMD14/CN15/RD6
_IOPORT_PD, // 37 RD07 ETXCLK/PMD15/CN16/RD7
_IOPORT_PC, // 38 RC04 T5CK/SDI1/RC4
_IOPORT_PD, // 39 RD14 AETXD0/SS3/U4RX/U1CTS/CN20/RD14
_IOPORT_PD, // 40 RD15 AETXD1/SCK3/U4TX/U1RTS/CN21/RD15
_IOPORT_PA, // 41 RA09 Vref-/CVref-/AERXD2/PMA7/RA9
_IOPORT_PA, // 42 RA10 Vref+/CVref+/AERXD3/PMA6/RA10 (Pin A; VREF+)
// these are above the highest pin on the board
_IOPORT_PF, // 43 RF00 ETXD1/PMD11/RF0 (User LED2)
_IOPORT_PG, // 44 RG09 ERXCLK/AERXCLK/EREFCLK/AEREFCLK/SS2/U6RX/U3CTS/PMA2/CN11/RG9 (SPI_SS (JPR to digital pin 10 position))
_IOPORT_PA, // 45 RA02 SCL2/RA2 (I2C, wire (jumper to A5) shared with pin 19)
_IOPORT_PA, // 46 RA03 SDA2/RA3 (I2C, wire (jumper to A4) shared with pin 18)
_IOPORT_PA, // 47 RA00 TMS/RA0 (User LED4)
_IOPORT_PA, // 48 RA01 TCK/RA1 (User LED3)
// SD Card
_IOPORT_PG, // 49 RG15 AERXERR/RG15 (SD Card)
_IOPORT_PG, // 50 RG14 TRD2/RG14 (SD Card)
_IOPORT_PG, // 51 RG12 TRD1/RG12 (SD Card)
_IOPORT_PG, // 52 RG13 TRD0/RG13 (SD Card)
// MRF24-G WiFi Module
_IOPORT_PF, // 53 RF13 SCK4/U5TX/U2RTS/RF13 (MRF24 SPI)
_IOPORT_PF, // 54 RF12 SS4/U5RX/U2CTS/RF12 (MRF24 SPI)
_IOPORT_PF, // 55 RF04 SDA5/SDI4/U2RX/PMA9/CN17/RF4 (MRF24 SPI)
_IOPORT_PF, // 56 RF05 SCL5/SDO4/U2TX/PMA8/CN18/RF5 (MRF24 SPI)
_IOPORT_PA, // 57 RA15 AETXEN/SDA1/INT4/RA15 (MRF24 INT)
_IOPORT_PG, // 58 RG01 ETXERR/PMD9/RG1 (MRF24 HIBERNATE)
_IOPORT_PG, // 59 RG00 PMD8/RG0 (MRF24 RESET)
// surplus pins
_IOPORT_PB, // 60 RB12 AN12/ERXD0/AECRS/PMA11/RB12 (Power Supply Monitor)
_IOPORT_PB, // 61 RB13 AN13/ERXD1/AECOL/PMA10/RB13 (POT)
_IOPORT_PA, // 62 RA04 TDI/RA4 (SDA pullup)
_IOPORT_PA, // 63 RA05 TDO/RA5 (SCL pullup)
_IOPORT_PD, // 64 RD13 ETXD3/PMD13/CN19/RD13 (Power Supply Enable)
_IOPORT_PA, // 65 RA06 TRCLK/RA6 (BTN1)
_IOPORT_PA, // 66 RA07 TRD3/RA7 (BTN1)
// shared pins
_IOPORT_PC, // 67 RC01 T2CK/RC1 (shared with digital pin 34)
_IOPORT_PC, // 68 RC02 T3CK/RC2 (shared with digital pin 35)
_IOPORT_PC, // 69 RC03 T4CK/RC3 (shared with digital pin 36)
_IOPORT_PD, // 70 RD08 RTCC/EMDIO/AEMDIO/IC1/RD8 (shared with digital pin 2)
_IOPORT_PD, // 71 RD09 SS1/IC2/RD9 (shared with digital pin 7)
_IOPORT_PD, // 72 RD10 SCK1/IC3/PMCS2/PMA15/RD10 (shared with digital pin 8)
_IOPORT_PD, // 73 RD12 ETXD2/IC5/PMD12/RD12 (shared with digital pin 10)
};
/* ------------------------------------------------------------ */
/* This table is used to map from digital pin number to a bit mask
** for the corresponding bit within the port.
*/
const uint16_t digital_pin_to_bit_mask_PGM[] =
{
_BV( 2 ), // 0 RF02 SDA3/SDI3/U1RX/RF2
_BV( 8 ), // 1 RF08 SCL3/SDO3/U1TX/RF8
_BV( 8 ), // 2 RE08 AERXD0/INT1/RE8
_BV( 0 ), // 3 RD00 SDO1/OC1/INT0/RD0
_BV( 1 ), // 4 RF01 ETXD0/PMD10/RF1
_BV( 1 ), // 5 RD01 OC2/RD1
_BV( 2 ), // 6 RD02 OC3/RD2
_BV( 9 ), // 7 RE09 AERXD1/INT2/RE9
_BV( 14 ), // 8 RA14 AETXCLK/SCL1/INT3/RA14
_BV( 3 ), // 9 RD03 OC4/RD3
_BV( 4 ), // 10 RD04 OC5/PMWR/CN13/RD4
_BV( 8 ), // 11 RG08 ERXDV/AERXDV/ECRSDV/AECRSDV/SCL4/SDO2/U3TX/PMA3/CN10/RG8
_BV( 7 ), // 12 RG07 ECRS/SDA4/SDI2/U3RX/PMA4/CN9/RG7
_BV( 6 ), // 13 RG06 ECOL/SCK2/U6TX/U3RTS/PMA5/CN8/RG6 (SPI_SCK, User LED)
_BV( 2 ), // 14 RB02 AN2/C2IN-/CN4/RB2
_BV( 4 ), // 15 RB04 AN4/C1IN-/CN6/RB4
_BV( 8 ), // 16 RB08 AN8/C1OUT/RB8
_BV( 0 ), // 17 RB00 PGED1/AN0/CN2/RB0
_BV( 10 ), // 18 RB10 AN10/CVrefout/PMA13/RB10
_BV( 11 ), // 19 RB11 AN11/ERXERR/AETXERR/PMA12/RB11
_BV( 3 ), // 20 RB03 AN3/C2IN+/CN5/RB3
_BV( 5 ), // 21 RB05 AN5/C1IN+/VBUSON/CN7/RB5
_BV( 9 ), // 22 RB09 AN9/C2OUT/RB9
_BV( 1 ), // 23 RB01 PGEC1/AN1/CN3/RB1
_BV( 14 ), // 24 RB14 AN14/ERXD2/AETXD3/PMALH/PMA1/RB14
_BV( 15 ), // 25 RB15 AN15/ERXD3/AETXD2/OCFB/PMALL/PMA0/CN12/RB15
_BV( 0 ), // 26 RE00 PMD0/RE0
_BV( 1 ), // 27 RE01 PMD1/RE1
_BV( 2 ), // 28 RE02 PMD2/RE2
_BV( 3 ), // 29 RE03 PMD3/RE3
_BV( 4 ), // 30 RE04 PMD4/RE4
_BV( 5 ), // 31 RE05 PMD5/RE5
_BV( 6 ), // 32 RE06 PMD6/RE6
_BV( 7 ), // 33 RE07 PMD7/RE7
_BV( 5 ), // 34 RD05 PMRD/CN14/RD5
_BV( 11 ), // 35 RD11 EMDC/AEMDC/IC4/PMCS1/PMA14/RD11
_BV( 6 ), // 36 RD06 ETXEN/PMD14/CN15/RD6
_BV( 7 ), // 37 RD07 ETXCLK/PMD15/CN16/RD7
_BV( 4 ), // 38 RC04 T5CK/SDI1/RC4
_BV( 14 ), // 39 RD14 AETXD0/SS3/U4RX/U1CTS/CN20/RD14
_BV( 15 ), // 40 RD15 AETXD1/SCK3/U4TX/U1RTS/CN21/RD15
_BV( 9 ), // 41 RA09 Vref-/CVref-/AERXD2/PMA7/RA9
_BV( 10 ), // 42 RA10 Vref+/CVref+/AERXD3/PMA6/RA10 (Pin A; VREF+)
// these are above the highest pin on the board
_BV( 0 ), // 43 RF00 ETXD1/PMD11/RF0 (User LED)
_BV( 9 ), // 44 RG09 ERXCLK/AERXCLK/EREFCLK/AEREFCLK/SS2/U6RX/U3CTS/PMA2/CN11/RG9 (SPI_SS (JPR to digital pin 10 position))
_BV( 2 ), // 45 RA02 SCL2/RA2 (I2C, wire (jumper to A5) shared with pin 19)
_BV( 3 ), // 46 RA03 SDA2/RA3 (I2C, wire (jumper to A4) shared with pin 18)
_BV( 0 ), // 47 RA00 TMS/RA0 (User LED)
_BV( 1 ), // 48 RA01 TCK/RA1 (User LED)
// SD Card
_BV( 15 ), // 49 RG15 AERXERR/RG15 (SD Card)
_BV( 14 ), // 50 RG14 TRD2/RG14 (SD Card)
_BV( 12 ), // 51 RG12 TRD1/RG12 (SD Card)
_BV( 13 ), // 52 RG13 TRD0/RG13 (SD Card)
// MRF24-G WiFi Module
_BV( 13 ), // 53 RF13 SCK4/U5TX/U2RTS/RF13 (MRF24 SPI)
_BV( 12 ), // 54 RF12 SS4/U5RX/U2CTS/RF12 (MRF24 SPI)
_BV( 4 ), // 55 RF04 SDA5/SDI4/U2RX/PMA9/CN17/RF4 (MRF24 SPI)
_BV( 5 ), // 56 RF05 SCL5/SDO4/U2TX/PMA8/CN18/RF5 (MRF24 SPI)
_BV( 15 ), // 57 RA15 AETXEN/SDA1/INT4/RA15 (MRF24 INT)
_BV( 1 ), // 58 RG01 ETXERR/PMD9/RG1 (MRF24 HIBERNATE)
_BV( 0 ), // 59 RG00 PMD8/RG0 (MRF24 RESET)
// surplus pins
_BV( 12 ), // 60 RB12 AN12/ERXD0/AECRS/PMA11/RB12 (Power Supply Monitor)
_BV( 13), // 61 RB13 AN13/ERXD1/AECOL/PMA10/RB13 (POT)
_BV( 4 ), // 62 RA04 TDI/RA4 (SDA pullup)
_BV( 5 ), // 63 RA05 TDO/RA5 (SCL pullup)
_BV( 13 ), // 64 RD13 ETXD3/PMD13/CN19/RD13 (Power Supply Enable)
_BV( 6 ), // 65 RA06 TRCLK/RA6 (BTN1)
_BV( 7 ), // 66 RA07 TRD3/RA7 (BTN1)
// shared pins
_BV( 1 ), // 67 RC01 T2CK/RC1 (shared with digital pin 34)
_BV( 2 ), // 68 RC02 T3CK/RC2 (shared with digital pin 35)
_BV( 3 ), // 69 RC03 T4CK/RC3 (shared with digital pin 36)
_BV( 8 ), // 70 RD08 RTCC/EMDIO/AEMDIO/IC1/RD8 (shared with digital pin 2)
_BV( 9 ), // 71 RD09 SS1/IC2/RD9 (shared with digital pin 7)
_BV( 10 ), // 72 RD10 SCK1/IC3/PMCS2/PMA15/RD10 (shared with digital pin 8)
_BV( 12 ), // 73 RD12 ETXD2/IC5/PMD12/RD12 (shared with digital pin 10)
};
/* ------------------------------------------------------------ */
/* This table is used to map from digital pin number to the output
** compare number, input capture number, and timer external clock
** input associated with that pin.
*/
const uint16_t digital_pin_to_timer_PGM[] =
{
NOT_ON_TIMER, // 0 RF02 SDA3/SDI3/U1RX/RF2
NOT_ON_TIMER, // 1 RF08 SCL3/SDO3/U1TX/RF8
NOT_ON_TIMER, // 2 RE08 AERXD0/INT1/RE8
_TIMER_OC1, // 3 RD00 SDO1/OC1/INT0/RD0
NOT_ON_TIMER, // 4 RF01 ETXD0/PMD10/RF1
_TIMER_OC2, // 5 RD01 OC2/RD1
_TIMER_OC3, // 6 RD02 OC3/RD2
NOT_ON_TIMER, // 7 RE09 AERXD1/INT2/RE9
NOT_ON_TIMER, // 8 RA14 AETXCLK/SCL1/INT3/RA14
_TIMER_OC4, // 9 RD03 OC4/RD3
_TIMER_OC5, // 10 RD04 OC5/PMWR/CN13/RD4
NOT_ON_TIMER, // 11 RG08 ERXDV/AERXDV/ECRSDV/AECRSDV/SCL4/SDO2/U3TX/PMA3/CN10/RG8
NOT_ON_TIMER, // 12 RG07 ECRS/SDA4/SDI2/U3RX/PMA4/CN9/RG7
NOT_ON_TIMER, // 13 RG06 ECOL/SCK2/U6TX/U3RTS/PMA5/CN8/RG6 (SPI_SCK, User LED)
NOT_ON_TIMER, // 14 RB02 AN2/C2IN-/CN4/RB2
NOT_ON_TIMER, // 15 RB04 AN4/C1IN-/CN6/RB4
NOT_ON_TIMER, // 16 RB08 AN8/C1OUT/RB8
NOT_ON_TIMER, // 17 RB00 PGED1/AN0/CN2/RB0
NOT_ON_TIMER, // 18 RB10 AN10/CVrefout/PMA13/RB10
NOT_ON_TIMER, // 19 RB11 AN11/ERXERR/AETXERR/PMA12/RB11
NOT_ON_TIMER, // 20 RB03 AN3/C2IN+/CN5/RB3
NOT_ON_TIMER, // 21 RB05 AN5/C1IN+/VBUSON/CN7/RB5
NOT_ON_TIMER, // 22 RB09 AN9/C2OUT/RB9
NOT_ON_TIMER, // 23 RB01 PGEC1/AN1/CN3/RB1
NOT_ON_TIMER, // 24 RB14 AN14/ERXD2/AETXD3/PMALH/PMA1/RB14
NOT_ON_TIMER, // 25 RB15 AN15/ERXD3/AETXD2/OCFB/PMALL/PMA0/CN12/RB15
NOT_ON_TIMER, // 26 RE00 PMD0/RE0
NOT_ON_TIMER, // 27 RE01 PMD1/RE1
NOT_ON_TIMER, // 28 RE02 PMD2/RE2
NOT_ON_TIMER, // 29 RE03 PMD3/RE3
NOT_ON_TIMER, // 30 RE04 PMD4/RE4
NOT_ON_TIMER, // 31 RE05 PMD5/RE5
NOT_ON_TIMER, // 32 RE06 PMD6/RE6
NOT_ON_TIMER, // 33 RE07 PMD7/RE7
NOT_ON_TIMER, // 34 RD05 PMRD/CN14/RD5
_TIMER_IC4, // 35 RD11 EMDC/AEMDC/IC4/PMCS1/PMA14/RD11
NOT_ON_TIMER, // 36 RD06 ETXEN/PMD14/CN15/RD6
NOT_ON_TIMER, // 37 RD07 ETXCLK/PMD15/CN16/RD7
_TIMER_TCK5, // 38 RC04 T5CK/SDI1/RC4
NOT_ON_TIMER, // 39 RD14 AETXD0/SS3/U4RX/U1CTS/CN20/RD14
NOT_ON_TIMER, // 40 RD15 AETXD1/SCK3/U4TX/U1RTS/CN21/RD15
NOT_ON_TIMER, // 41 RA09 Vref-/CVref-/AERXD2/PMA7/RA9
NOT_ON_TIMER, // 42 RA10 Vref+/CVref+/AERXD3/PMA6/RA10 (Pin A; VREF+)
// these are above the highest pin on the board
NOT_ON_TIMER, // 43 RF00 ETXD1/PMD11/RF0 (User LED)
NOT_ON_TIMER, // 44 RG09 ERXCLK/AERXCLK/EREFCLK/AEREFCLK/SS2/U6RX/U3CTS/PMA2/CN11/RG9 (SPI_SS (JPR to digital pin 10 position))
NOT_ON_TIMER, // 45 RA02 SCL2/RA2 (I2C, wire (jumper to A5) shared with pin 19)
NOT_ON_TIMER, // 46 RA03 SDA2/RA3 (I2C, wire (jumper to A4) shared with pin 18)
NOT_ON_TIMER, // 47 RA00 TMS/RA0 (User LED)
NOT_ON_TIMER, // 48 RA01 TCK/RA1 (User LED)
// SD Card
NOT_ON_TIMER, // 49 RG15 AERXERR/RG15 (SD Card)
NOT_ON_TIMER, // 50 RG14 TRD2/RG14 (SD Card)
NOT_ON_TIMER, // 51 RG12 TRD1/RG12 (SD Card)
NOT_ON_TIMER, // 52 RG13 TRD0/RG13 (SD Card)
// MRF24-G WiFi Module
NOT_ON_TIMER, // 53 RF13 SCK4/U5TX/U2RTS/RF13 (MRF24 SPI)
NOT_ON_TIMER, // 54 RF12 SS4/U5RX/U2CTS/RF12 (MRF24 SPI)
NOT_ON_TIMER, // 55 RF04 SDA5/SDI4/U2RX/PMA9/CN17/RF4 (MRF24 SPI)
NOT_ON_TIMER, // 56 RF05 SCL5/SDO4/U2TX/PMA8/CN18/RF5 (MRF24 SPI)
NOT_ON_TIMER, // 57 RA15 AETXEN/SDA1/INT4/RA15 (MRF24 INT)
NOT_ON_TIMER, // 58 RG01 ETXERR/PMD9/RG1 (MRF24 HIBERNATE)
NOT_ON_TIMER, // 59 RG00 PMD8/RG0 (MRF24 RESET)
// surplus pins
NOT_ON_TIMER, // 60 RB12 AN12/ERXD0/AECRS/PMA11/RB12 (Power Supply Monitor)
NOT_ON_TIMER, // 61 RB13 AN13/ERXD1/AECOL/PMA10/RB13 (POT)
NOT_ON_TIMER, // 62 RA04 TDI/RA4 (SDA pullup)
NOT_ON_TIMER, // 63 RA05 TDO/RA5 (SCL pullup)
NOT_ON_TIMER, // 64 RD13 ETXD3/PMD13/CN19/RD13 (Power Supply Enable)
NOT_ON_TIMER, // 65 RA06 TRCLK/RA6 (BTN1)
NOT_ON_TIMER, // 66 RA07 TRD3/RA7 (BTN1)
// shared pins
_TIMER_TCK2, // 67 RC01 T2CK/RC1 (shared with digital pin 34)
_TIMER_TCK3, // 68 RC02 T3CK/RC2 (shared with digital pin 35)
_TIMER_TCK4, // 69 RC03 T4CK/RC3 (shared with digital pin 36)
_TIMER_IC1, // 70 RD08 RTCC/EMDIO/AEMDIO/IC1/RD8 (shared with digital pin 2)
_TIMER_IC2, // 71 RD09 SS1/IC2/RD9 (shared with digital pin 7)
_TIMER_IC3, // 72 RD10 SCK1/IC3/PMCS2/PMA15/RD10 (shared with digital pin 8)
_TIMER_IC5, // 73 RD12 ETXD2/IC5/PMD12/RD12 (shared with digital pin 10)
};
const uint8_t digital_pin_to_analog_PGM[] = {
NOT_ANALOG_PIN, // 0 RF02 SDA3/SDI3/U1RX/RF2
NOT_ANALOG_PIN, // 1 RF08 SCL3/SDO3/U1TX/RF8
NOT_ANALOG_PIN, // 2 RE08 AERXD0/INT1/RE8
NOT_ANALOG_PIN, // 3 RD00 SDO1/OC1/INT0/RD0
NOT_ANALOG_PIN, // 4 RF01 ETXD0/PMD10/RF1
NOT_ANALOG_PIN, // 5 RD01 OC2/RD1
NOT_ANALOG_PIN, // 6 RD02 OC3/RD2
NOT_ANALOG_PIN, // 7 RE09 AERXD1/INT2/RE9
NOT_ANALOG_PIN, // 8 RA14 AETXCLK/SCL1/INT3/RA14
NOT_ANALOG_PIN, // 9 RD03 OC4/RD3
NOT_ANALOG_PIN, // 10 RD04 OC5/PMWR/CN13/RD4
NOT_ANALOG_PIN, // 11 RG08 ERXDV/AERXDV/ECRSDV/AECRSDV/SCL4/SDO2/U3TX/PMA3/CN10/RG8
NOT_ANALOG_PIN, // 12 RG07 ECRS/SDA4/SDI2/U3RX/PMA4/CN9/RG7
NOT_ANALOG_PIN, // 13 RG06 ECOL/SCK2/U6TX/U3RTS/PMA5/CN8/RG6 (SPI_SCK, User LED)
_BOARD_AN0, // 14 RB02 AN2/C2IN-/CN4/RB2
_BOARD_AN1, // 15 RB04 AN4/C1IN-/CN6/RB4
_BOARD_AN2, // 16 RB08 AN8/C1OUT/RB8
_BOARD_AN3, // 17 RB00 PGED1/AN0/CN2/RB0
_BOARD_AN4, // 18 RB10 AN10/CVrefout/PMA13/RB10
_BOARD_AN5, // 19 RB11 AN11/ERXERR/AETXERR/PMA12/RB11
_BOARD_AN6, // 20 RB03 AN3/C2IN+/CN5/RB3
_BOARD_AN7, // 21 RB05 AN5/C1IN+/VBUSON/CN7/RB5
_BOARD_AN8, // 22 RB09 AN9/C2OUT/RB9
_BOARD_AN9, // 23 RB01 PGEC1/AN1/CN3/RB1
_BOARD_AN10, // 24 RB14 AN14/ERXD2/AETXD3/PMALH/PMA1/RB14
_BOARD_AN11, // 25 RB15 AN15/ERXD3/AETXD2/OCFB/PMALL/PMA0/CN12/RB15
NOT_ANALOG_PIN, // 26 RE00 PMD0/RE0
NOT_ANALOG_PIN, // 27 RE01 PMD1/RE1
NOT_ANALOG_PIN, // 28 RE02 PMD2/RE2
NOT_ANALOG_PIN, // 29 RE03 PMD3/RE3
NOT_ANALOG_PIN, // 30 RE04 PMD4/RE4
NOT_ANALOG_PIN, // 31 RE05 PMD5/RE5
NOT_ANALOG_PIN, // 32 RE06 PMD6/RE6
NOT_ANALOG_PIN, // 33 RE07 PMD7/RE7
NOT_ANALOG_PIN, // 34 RD05 PMRD/CN14/RD5
NOT_ANALOG_PIN, // 35 RD11 EMDC/AEMDC/IC4/PMCS1/PMA14/RD11
NOT_ANALOG_PIN, // 36 RD06 ETXEN/PMD14/CN15/RD6
NOT_ANALOG_PIN, // 37 RD07 ETXCLK/PMD15/CN16/RD7
NOT_ANALOG_PIN, // 38 RC04 T5CK/SDI1/RC4
NOT_ANALOG_PIN, // 39 RD14 AETXD0/SS3/U4RX/U1CTS/CN20/RD14
NOT_ANALOG_PIN, // 40 RD15 AETXD1/SCK3/U4TX/U1RTS/CN21/RD15
NOT_ANALOG_PIN, // 41 RA09 Vref-/CVref-/AERXD2/PMA7/RA9
NOT_ANALOG_PIN, // 42 RA10 Vref+/CVref+/AERXD3/PMA6/RA10 (Pin A; VREF+)
// these are above the highest pin on the board
NOT_ANALOG_PIN, // 43 RF00 ETXD1/PMD11/RF0 (User LED)
NOT_ANALOG_PIN, // 44 RG09 ERXCLK/AERXCLK/EREFCLK/AEREFCLK/SS2/U6RX/U3CTS/PMA2/CN11/RG9 (SPI_SS (JPR to digital pin 10 position))
NOT_ANALOG_PIN, // 45 RA02 SCL2/RA2 (I2C, wire (jumper to A5) shared with pin 19)
NOT_ANALOG_PIN, // 46 RA03 SDA2/RA3 (I2C, wire (jumper to A4) shared with pin 18)
NOT_ANALOG_PIN, // 47 RA00 TMS/RA0 (User LED)
NOT_ANALOG_PIN, // 48 RA01 TCK/RA1 (User LED)
// SD Card
NOT_ANALOG_PIN, // 49 RG15 AERXERR/RG15 (SD Card)
NOT_ANALOG_PIN, // 50 RG14 TRD2/RG14 (SD Card)
NOT_ANALOG_PIN, // 51 RG12 TRD1/RG12 (SD Card)
NOT_ANALOG_PIN, // 52 RG13 TRD0/RG13 (SD Card)
// MRF24-G WiFi Module
NOT_ANALOG_PIN, // 53 RF13 SCK4/U5TX/U2RTS/RF13 (MRF24 SPI)
NOT_ANALOG_PIN, // 54 RF12 SS4/U5RX/U2CTS/RF12 (MRF24 SPI)
NOT_ANALOG_PIN, // 55 RF04 SDA5/SDI4/U2RX/PMA9/CN17/RF4 (MRF24 SPI)
NOT_ANALOG_PIN, // 56 RF05 SCL5/SDO4/U2TX/PMA8/CN18/RF5 (MRF24 SPI)
NOT_ANALOG_PIN, // 57 RA15 AETXEN/SDA1/INT4/RA15 (MRF24 INT)
NOT_ANALOG_PIN, // 58 RG01 ETXERR/PMD9/RG1 (MRF24 HIBERNATE)
NOT_ANALOG_PIN, // 59 RG00 PMD8/RG0 (MRF24 RESET)
// surplus pins
_BOARD_AN12, // 60 RB12 AN12/ERXD0/AECRS/PMA11/RB12 (Power Supply Monitor)
_BOARD_AN13, // 61 RB13 AN13/ERXD1/AECOL/PMA10/RB13 (POT)
NOT_ANALOG_PIN, // 62 RA04 TDI/RA4 (SDA pullup)
NOT_ANALOG_PIN, // 63 RA05 TDO/RA5 (SCL pullup)
NOT_ANALOG_PIN, // 64 RD13 ETXD3/PMD13/CN19/RD13 (Power Supply Enable)
NOT_ANALOG_PIN, // 65 RA06 TRCLK/RA6 (BTN1)
NOT_ANALOG_PIN, // 66 RA07 TRD3/RA7 (BTN1)
// shared pins
NOT_ANALOG_PIN, // 67 RC01 T2CK/RC1 (shared with digital pin 34)
NOT_ANALOG_PIN, // 68 RC02 T3CK/RC2 (shared with digital pin 35)
NOT_ANALOG_PIN, // 69 RC03 T4CK/RC3 (shared with digital pin 36)
NOT_ANALOG_PIN, // 70 RD08 RTCC/EMDIO/AEMDIO/IC1/RD8 (shared with digital pin 2)
NOT_ANALOG_PIN, // 71 RD09 SS1/IC2/RD9 (shared with digital pin 7)
NOT_ANALOG_PIN, // 72 RD10 SCK1/IC3/PMCS2/PMA15/RD10 (shared with digital pin 8)
NOT_ANALOG_PIN, // 73 RD12 ETXD2/IC5/PMD12/RD12 (shared with digital pin 10)
};
/* ------------------------------------------------------------ */
/* This table is used to map from the analog pin number to the
** actual A/D converter channel used for that pin.
*/
const uint8_t analog_pin_to_channel_PGM[] =
{
//* chipKIT Pin PIC32 Analog channel
2, //* A0 AN2
4, //* A1 AN4
8, //* A2 AN8
0, //* A3 AN0
10, //* A4 AN10
11, //* A5 AN11
3, //* A6 AN3
5, //* A7 AN5
9, //* A8 AN9
1, //* A9 AN1
14, //* A10 AN14
15, //* A11 AN15
12, //* A12 AN12
13, //* A13 AN13
};
/* ------------------------------------------------------------ */
/* Board Customization Functions */
/* ------------------------------------------------------------ */
/* */
/* The following can be used to customize the behavior of some */
/* of the core API functions. These provide hooks that can be */
/* used to extend or replace the default behavior of the core */
/* functions. To use one of these functions, add the desired */
/* code to the function skeleton below and then set the value */
/* of the appropriate compile switch above to 1. This will */
/* cause the hook function to be compiled into the build and */
/* to cause the code to call the hook function to be compiled */
/* into the appropriate core function. */
/* */
/* ------------------------------------------------------------ */
/*** _board_init
**
** Parameters:
** none
**
** Return Value:
** none
**
** Errors:
** none
**
** Description:
** This function is called from the core init() function.
** This can be used to perform any board specific init
** that needs to be done when the processor comes out of
** reset and before the user sketch is run.
*/
#if (OPT_BOARD_INIT != 0)
void _board_init(void) {
}
#endif
/* ------------------------------------------------------------ */
/*** _board_pinMode
**
** Parameters:
** pin - digital pin number to configure
** mode - mode to which the pin should be configured
**
** Return Value:
** Returns 0 if not handled, !0 if handled.
**
** Errors:
** none
**
** Description:
** This function is called at the beginning of the pinMode
** function. It can perform any special processing needed
** when setting the pin mode. If this function returns zero,
** control will pass through the normal pinMode code. If
** it returns a non-zero value the normal pinMode code isn't
** executed.
*/
#if (OPT_BOARD_DIGITAL_IO != 0)
int _board_pinMode(uint8_t pin, uint8_t mode) {
return 0;
}
#endif
/* ------------------------------------------------------------ */
/*** _board_getPinMode
**
** Parameters:
** pin - digital pin number
** mode - pointer to variable to receive mode value
**
** Return Value:
** Returns 0 if not handled, !0 if handled.
**
** Errors:
** none
**
** Description:
** This function is called at the beginning of the getPinMode
** function. It can perform any special processing needed
** when getting the pin mode. If this function returns zero,
** control will pass through the normal getPinMode code. If
** it returns a non-zero value the normal getPinMode code isn't
** executed.
*/
#if (OPT_BOARD_DIGITAL_IO != 0)
int _board_getPinMode(uint8_t pin, uint8_t * mode) {
return 0;
}
#endif
/* ------------------------------------------------------------ */
/*** _board_digitalWrite
**
** Parameters:
** pin - digital pin number
** val - value to write to the pin
**
** Return Value:
** Returns 0 if not handled, !0 if handled.
**
** Errors:
** none
**
** Description:
** This function is called at the beginning of the digitalWrite
** function. It can perform any special processing needed
** in writing to the pin. If this function returns zero,
** control will pass through the normal digitalWrite code. If
** it returns a non-zero value the normal digitalWrite code isn't
** executed.
*/
#if (OPT_BOARD_DIGITAL_IO != 0)
int _board_digitalWrite(uint8_t pin, uint8_t val) {
return 0;
}
#endif
/* ------------------------------------------------------------ */
/*** _board_digitalRead
**
** Parameters:
** pin - digital pin number
** val - pointer to variable to receive pin value
**
** Return Value:
** Returns 0 if not handled, !0 if handled.
**
** Errors:
** none
**
** Description:
** This function is called at the beginning of the digitalRead
** function. It can perform any special processing needed
** in reading from the pin. If this function returns zero,
** control will pass through the normal digitalRead code. If
** it returns a non-zero value the normal digitalRead code isn't
** executed.
*/
#if (OPT_BOARD_DIGITAL_IO != 0)
int _board_digitalRead(uint8_t pin, uint8_t * val) {
return 0;
}
#endif
/* ------------------------------------------------------------ */
/*** _board_analogRead
**
** Parameters:
** pin - analog channel number
** val - pointer to variable to receive analog value
**
** Return Value:
** Returns 0 if not handled, !0 if handled.
**
** Errors:
** none
**
** Description:
** This function is called at the beginning of the analogRead
** function. It can perform any special processing needed
** in reading from the pin. If this function returns zero,
** control will pass through the normal analogRead code. If
** it returns a non-zero value the normal analogRead code isn't
** executed.
*/
#if (OPT_BOARD_ANALOG_READ != 0)
int _board_analogRead(uint8_t pin, int * val) {
return 0;
}
#endif
/* ------------------------------------------------------------ */
/*** _board_analogReference
**
** Parameters:
**
** Return Value:
** Returns 0 if not handled, !0 if handled.
**
** Errors:
** none
**
** Description:
** This function is called at the beginning of the analogReference
** function. It can perform any special processing needed
** to set the reference voltage. If this function returns zero,
** control will pass through the normal analogReference code. If
** it returns a non-zero value the normal analogReference code isn't
** executed.
*/
#if (OPT_BOARD_ANALOG_READ != 0)
int _board_analogReference(uint8_t mode) {
return 0;
}
#endif
/* ------------------------------------------------------------ */
/*** _board_analogWrite
**
** Parameters:
** pin - pin number
** val - analog value to write
**
** Return Value:
** Returns 0 if not handled, !0 if handled.
**
** Errors:
** none
**
** Description:
** This function is called at the beginning of the analogWrite
** function. It can perform any special processing needed
** in writing to the pin. If this function returns zero,
** control will pass through the normal analogWrite code. If
** it returns a non-zero value the normal analogWrite code isn't
** executed.
*/
#if (OPT_BOARD_ANALOG_WRITE != 0)
int _board_analogWrite(uint8_t pin, int val) {
return 0;
}
#endif
#endif // OPT_BOARD_DATA
/* ------------------------------------------------------------ */
#endif // BOARD_DATA_C
/************************************************************************/
|
the_stack_data/64479.c | /* Copyright (C) 2002-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>, 2002.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#define _GNU_SOURCE 1
#include <argp.h>
#include <error.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/param.h>
#include <sys/types.h>
#ifndef MAX_THREADS
# define MAX_THREADS 100000
#endif
#ifndef DEFAULT_THREADS
# define DEFAULT_THREADS 50
#endif
#define OPT_TO_THREAD 300
#define OPT_TO_PROCESS 301
#define OPT_SYNC_SIGNAL 302
#define OPT_SYNC_JOIN 303
#define OPT_TOPLEVEL 304
static const struct argp_option options[] =
{
{ NULL, 0, NULL, 0, "\
This is a test for threads so we allow ther user to selection the number of \
threads which are used at any one time. Independently the total number of \
rounds can be selected. This is the total number of threads which will have \
run when the process terminates:" },
{ "threads", 't', "NUMBER", 0, "Number of threads used at once" },
{ "starts", 's', "NUMBER", 0, "Total number of working threads" },
{ "toplevel", OPT_TOPLEVEL, "NUMBER", 0,
"Number of toplevel threads which start the other threads; this \
implies --sync-join" },
{ NULL, 0, NULL, 0, "\
Each thread can do one of two things: sleep or do work. The latter is 100% \
CPU bound. The work load is the probability a thread does work. All values \
from zero to 100 (inclusive) are valid. How often each thread repeats this \
can be determined by the number of rounds. The work cost determines how long \
each work session (not sleeping) takes. If it is zero a thread would \
effectively nothing. By setting the number of rounds to zero the thread \
does no work at all and pure thread creation times can be measured." },
{ "workload", 'w', "PERCENT", 0, "Percentage of time spent working" },
{ "workcost", 'c', "NUMBER", 0,
"Factor in the cost of each round of working" },
{ "rounds", 'r', "NUMBER", 0, "Number of rounds each thread runs" },
{ NULL, 0, NULL, 0, "\
There are a number of different methods how thread creation can be \
synchronized. Synchronization is necessary since the number of concurrently \
running threads is limited." },
{ "sync-signal", OPT_SYNC_SIGNAL, NULL, 0,
"Synchronize using a signal (default)" },
{ "sync-join", OPT_SYNC_JOIN, NULL, 0, "Synchronize using pthread_join" },
{ NULL, 0, NULL, 0, "\
One parameter for each threads execution is the size of the stack. If this \
parameter is not used the system's default stack size is used. If many \
threads are used the stack size should be chosen quite small." },
{ "stacksize", 'S', "BYTES", 0, "Size of threads stack" },
{ "guardsize", 'g', "BYTES", 0,
"Size of stack guard area; must fit into the stack" },
{ NULL, 0, NULL, 0, "Signal options:" },
{ "to-thread", OPT_TO_THREAD, NULL, 0, "Send signal to main thread" },
{ "to-process", OPT_TO_PROCESS, NULL, 0,
"Send signal to process (default)" },
{ NULL, 0, NULL, 0, "Administrative options:" },
{ "progress", 'p', NULL, 0, "Show signs of progress" },
{ "timing", 'T', NULL, 0,
"Measure time from startup to the last thread finishing" },
{ NULL, 0, NULL, 0, NULL }
};
/* Prototype for option handler. */
static error_t parse_opt (int key, char *arg, struct argp_state *state);
/* Data structure to communicate with argp functions. */
static struct argp argp =
{
options, parse_opt
};
static unsigned long int threads = DEFAULT_THREADS;
static unsigned long int workload = 75;
static unsigned long int workcost = 20;
static unsigned long int rounds = 10;
static long int starts = 5000;
static unsigned long int stacksize;
static long int guardsize = -1;
static bool progress;
static bool timing;
static bool to_thread;
static unsigned long int toplevel = 1;
static long int running;
static pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
static pid_t pid;
static pthread_t tmain;
static clockid_t cl;
static struct timespec start_time;
static pthread_mutex_t sum_mutex = PTHREAD_MUTEX_INITIALIZER;
unsigned int sum;
static enum
{
sync_signal,
sync_join
}
sync_method;
/* We use 64bit values for the times. */
typedef unsigned long long int hp_timing_t;
/* Attributes for all created threads. */
static pthread_attr_t attr;
static void *
work (void *arg)
{
unsigned long int i;
unsigned int state = (unsigned long int) arg;
for (i = 0; i < rounds; ++i)
{
/* Determine what to do. */
unsigned int rnum;
/* Uniform distribution. */
do
rnum = rand_r (&state);
while (rnum >= UINT_MAX - (UINT_MAX % 100));
rnum %= 100;
if (rnum < workload)
{
int j;
int a[4] = { i, rnum, i + rnum, rnum - i };
if (progress)
write (STDERR_FILENO, "c", 1);
for (j = 0; j < workcost; ++j)
{
a[0] += a[3] >> 12;
a[1] += a[2] >> 20;
a[2] += a[1] ^ 0x3423423;
a[3] += a[0] - a[1];
}
pthread_mutex_lock (&sum_mutex);
sum += a[0] + a[1] + a[2] + a[3];
pthread_mutex_unlock (&sum_mutex);
}
else
{
/* Just sleep. */
struct timespec tv;
tv.tv_sec = 0;
tv.tv_nsec = 10000000;
if (progress)
write (STDERR_FILENO, "w", 1);
nanosleep (&tv, NULL);
}
}
return NULL;
}
static void *
thread_function (void *arg)
{
work (arg);
pthread_mutex_lock (&running_mutex);
if (--running <= 0 && starts <= 0)
{
/* We are done. */
if (progress)
write (STDERR_FILENO, "\n", 1);
if (timing)
{
struct timespec end_time;
if (clock_gettime (cl, &end_time) == 0)
{
end_time.tv_sec -= start_time.tv_sec;
end_time.tv_nsec -= start_time.tv_nsec;
if (end_time.tv_nsec < 0)
{
end_time.tv_nsec += 1000000000;
--end_time.tv_sec;
}
printf ("\nRuntime: %lu.%09lu seconds\n",
(unsigned long int) end_time.tv_sec,
(unsigned long int) end_time.tv_nsec);
}
}
printf ("Result: %08x\n", sum);
exit (0);
}
pthread_mutex_unlock (&running_mutex);
if (sync_method == sync_signal)
{
if (to_thread)
/* This code sends a signal to the main thread. */
pthread_kill (tmain, SIGUSR1);
else
/* Use this code to test sending a signal to the process. */
kill (pid, SIGUSR1);
}
if (progress)
write (STDERR_FILENO, "f", 1);
return NULL;
}
struct start_info
{
unsigned int starts;
unsigned int threads;
};
static void *
start_threads (void *arg)
{
struct start_info *si = arg;
unsigned int starts = si->starts;
pthread_t ths[si->threads];
unsigned int state = starts;
unsigned int n;
unsigned int i = 0;
int err;
if (progress)
write (STDERR_FILENO, "T", 1);
memset (ths, '\0', sizeof (pthread_t) * si->threads);
while (starts-- > 0)
{
if (ths[i] != 0)
{
/* Wait for the threads in the order they were created. */
err = pthread_join (ths[i], NULL);
if (err != 0)
error (EXIT_FAILURE, err, "cannot join thread");
if (progress)
write (STDERR_FILENO, "f", 1);
}
err = pthread_create (&ths[i], &attr, work,
(void *) (long) (rand_r (&state) + starts + i));
if (err != 0)
error (EXIT_FAILURE, err, "cannot start thread");
if (progress)
write (STDERR_FILENO, "t", 1);
if (++i == si->threads)
i = 0;
}
n = i;
do
{
if (ths[i] != 0)
{
err = pthread_join (ths[i], NULL);
if (err != 0)
error (EXIT_FAILURE, err, "cannot join thread");
if (progress)
write (STDERR_FILENO, "f", 1);
}
if (++i == si->threads)
i = 0;
}
while (i != n);
if (progress)
write (STDERR_FILENO, "F", 1);
return NULL;
}
int
main (int argc, char *argv[])
{
int remaining;
sigset_t ss;
pthread_t th;
pthread_t *ths = NULL;
int empty = 0;
int last;
bool cont = true;
/* Parse and process arguments. */
argp_parse (&argp, argc, argv, 0, &remaining, NULL);
if (sync_method == sync_join)
{
ths = (pthread_t *) calloc (threads, sizeof (pthread_t));
if (ths == NULL)
error (EXIT_FAILURE, errno,
"cannot allocate memory for thread descriptor array");
last = threads;
}
else
{
ths = &th;
last = 1;
}
if (toplevel > threads)
{
printf ("resetting number of toplevel threads to %lu to not surpass number to concurrent threads\n",
threads);
toplevel = threads;
}
if (timing)
{
if (clock_getcpuclockid (0, &cl) != 0
|| clock_gettime (cl, &start_time) != 0)
timing = false;
}
/* We need this later. */
pid = getpid ();
tmain = pthread_self ();
/* We use signal SIGUSR1 for communication between the threads and
the main thread. We only want sychronous notification. */
if (sync_method == sync_signal)
{
sigemptyset (&ss);
sigaddset (&ss, SIGUSR1);
if (sigprocmask (SIG_BLOCK, &ss, NULL) != 0)
error (EXIT_FAILURE, errno, "cannot set signal mask");
}
/* Create the thread attributes. */
pthread_attr_init (&attr);
/* If the user provided a stack size use it. */
if (stacksize != 0
&& pthread_attr_setstacksize (&attr, stacksize) != 0)
puts ("could not set stack size; will use default");
/* And stack guard size. */
if (guardsize != -1
&& pthread_attr_setguardsize (&attr, guardsize) != 0)
puts ("invalid stack guard size; will use default");
/* All threads are created detached if we are not using pthread_join
to synchronize. */
if (sync_method != sync_join)
pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
if (sync_method == sync_signal)
{
while (1)
{
int err;
bool do_wait = false;
pthread_mutex_lock (&running_mutex);
if (starts-- < 0)
cont = false;
else
do_wait = ++running >= threads && starts > 0;
pthread_mutex_unlock (&running_mutex);
if (! cont)
break;
if (progress)
write (STDERR_FILENO, "t", 1);
err = pthread_create (&ths[empty], &attr, thread_function,
(void *) starts);
if (err != 0)
error (EXIT_FAILURE, err, "cannot start thread %lu", starts);
if (++empty == last)
empty = 0;
if (do_wait)
sigwaitinfo (&ss, NULL);
}
/* Do nothing anymore. On of the threads will terminate the program. */
sigfillset (&ss);
sigdelset (&ss, SIGINT);
while (1)
sigsuspend (&ss);
}
else
{
pthread_t ths[toplevel];
struct start_info si[toplevel];
unsigned int i;
for (i = 0; i < toplevel; ++i)
{
unsigned int child_starts = starts / (toplevel - i);
unsigned int child_threads = threads / (toplevel - i);
int err;
si[i].starts = child_starts;
si[i].threads = child_threads;
err = pthread_create (&ths[i], &attr, start_threads, &si[i]);
if (err != 0)
error (EXIT_FAILURE, err, "cannot start thread");
starts -= child_starts;
threads -= child_threads;
}
for (i = 0; i < toplevel; ++i)
{
int err = pthread_join (ths[i], NULL);
if (err != 0)
error (EXIT_FAILURE, err, "cannot join thread");
}
/* We are done. */
if (progress)
write (STDERR_FILENO, "\n", 1);
if (timing)
{
struct timespec end_time;
if (clock_gettime (cl, &end_time) == 0)
{
end_time.tv_sec -= start_time.tv_sec;
end_time.tv_nsec -= start_time.tv_nsec;
if (end_time.tv_nsec < 0)
{
end_time.tv_nsec += 1000000000;
--end_time.tv_sec;
}
printf ("\nRuntime: %lu.%09lu seconds\n",
(unsigned long int) end_time.tv_sec,
(unsigned long int) end_time.tv_nsec);
}
}
printf ("Result: %08x\n", sum);
exit (0);
}
/* NOTREACHED */
return 0;
}
/* Handle program arguments. */
static error_t
parse_opt (int key, char *arg, struct argp_state *state)
{
unsigned long int num;
long int snum;
switch (key)
{
case 't':
num = strtoul (arg, NULL, 0);
if (num <= MAX_THREADS)
threads = num;
else
printf ("\
number of threads limited to %u; recompile with a higher limit if necessary",
MAX_THREADS);
break;
case 'w':
num = strtoul (arg, NULL, 0);
if (num <= 100)
workload = num;
else
puts ("workload must be between 0 and 100 percent");
break;
case 'c':
workcost = strtoul (arg, NULL, 0);
break;
case 'r':
rounds = strtoul (arg, NULL, 0);
break;
case 's':
starts = strtoul (arg, NULL, 0);
break;
case 'S':
num = strtoul (arg, NULL, 0);
if (num >= PTHREAD_STACK_MIN)
stacksize = num;
else
printf ("minimum stack size is %d\n", PTHREAD_STACK_MIN);
break;
case 'g':
snum = strtol (arg, NULL, 0);
if (snum < 0)
printf ("invalid guard size %s\n", arg);
else
guardsize = snum;
break;
case 'p':
progress = true;
break;
case 'T':
timing = true;
break;
case OPT_TO_THREAD:
to_thread = true;
break;
case OPT_TO_PROCESS:
to_thread = false;
break;
case OPT_SYNC_SIGNAL:
sync_method = sync_signal;
break;
case OPT_SYNC_JOIN:
sync_method = sync_join;
break;
case OPT_TOPLEVEL:
num = strtoul (arg, NULL, 0);
if (num < MAX_THREADS)
toplevel = num;
else
printf ("\
number of threads limited to %u; recompile with a higher limit if necessary",
MAX_THREADS);
sync_method = sync_join;
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static hp_timing_t
get_clockfreq (void)
{
/* We read the information from the /proc filesystem. It contains at
least one line like
cpu MHz : 497.840237
or also
cpu MHz : 497.841
We search for this line and convert the number in an integer. */
static hp_timing_t result;
int fd;
/* If this function was called before, we know the result. */
if (result != 0)
return result;
fd = open ("/proc/cpuinfo", O_RDONLY);
if (__glibc_likely (fd != -1))
{
/* XXX AFAIK the /proc filesystem can generate "files" only up
to a size of 4096 bytes. */
char buf[4096];
ssize_t n;
n = read (fd, buf, sizeof buf);
if (__builtin_expect (n, 1) > 0)
{
char *mhz = memmem (buf, n, "cpu MHz", 7);
if (__glibc_likely (mhz != NULL))
{
char *endp = buf + n;
int seen_decpoint = 0;
int ndigits = 0;
/* Search for the beginning of the string. */
while (mhz < endp && (*mhz < '0' || *mhz > '9') && *mhz != '\n')
++mhz;
while (mhz < endp && *mhz != '\n')
{
if (*mhz >= '0' && *mhz <= '9')
{
result *= 10;
result += *mhz - '0';
if (seen_decpoint)
++ndigits;
}
else if (*mhz == '.')
seen_decpoint = 1;
++mhz;
}
/* Compensate for missing digits at the end. */
while (ndigits++ < 6)
result *= 10;
}
}
close (fd);
}
return result;
}
int
clock_getcpuclockid (pid_t pid, clockid_t *clock_id)
{
/* We don't allow any process ID but our own. */
if (pid != 0 && pid != getpid ())
return EPERM;
#ifdef CLOCK_PROCESS_CPUTIME_ID
/* Store the number. */
*clock_id = CLOCK_PROCESS_CPUTIME_ID;
return 0;
#else
/* We don't have a timer for that. */
return ENOENT;
#endif
}
#ifdef i386
#define HP_TIMING_NOW(Var) __asm__ __volatile__ ("rdtsc" : "=A" (Var))
#elif defined __x86_64__
# define HP_TIMING_NOW(Var) \
({ unsigned int _hi, _lo; \
asm volatile ("rdtsc" : "=a" (_lo), "=d" (_hi)); \
(Var) = ((unsigned long long int) _hi << 32) | _lo; })
#elif defined __ia64__
#define HP_TIMING_NOW(Var) __asm__ __volatile__ ("mov %0=ar.itc" : "=r" (Var) : : "memory")
#else
#error "HP_TIMING_NOW missing"
#endif
/* Get current value of CLOCK and store it in TP. */
int
clock_gettime (clockid_t clock_id, struct timespec *tp)
{
int retval = -1;
switch (clock_id)
{
case CLOCK_PROCESS_CPUTIME_ID:
{
static hp_timing_t freq;
hp_timing_t tsc;
/* Get the current counter. */
HP_TIMING_NOW (tsc);
if (freq == 0)
{
freq = get_clockfreq ();
if (freq == 0)
return EINVAL;
}
/* Compute the seconds. */
tp->tv_sec = tsc / freq;
/* And the nanoseconds. This computation should be stable until
we get machines with about 16GHz frequency. */
tp->tv_nsec = ((tsc % freq) * UINT64_C (1000000000)) / freq;
retval = 0;
}
break;
default:
errno = EINVAL;
break;
}
return retval;
}
|
the_stack_data/68886577.c | /**
* Use the mouse in a X11 terminal
*
* Some terminfo sequences:
* * smcup = \E[?1049h enter alternate screen (enter_ca_mode)
* * rmcup = \E[?1049l exit alternate screen (exit_ca_mode)
* * cup 1 2 = \E[2;3H set cursor pos to 2nd column, 3rd line (x=1, y=2)
* * civis = \E[?25l make cursor invisible
* * cnorm = \E[?12l\E[?25h make cursor normal
* * cvvis = \E[?12;25h make cursor very visible
* * el = \E[K clear to end of line
* * ed = \E[J clear to end to screen
* * clear = \E[H\E[2J clear screen and home cursor
* * XM 1 = \E[?1002h enable "any event" mouse mode (xterm-1002)
* * XM 0 = \E[?1002l disable "any event" mouse mode (xterm-1002)
* * \E[?1006h enable mouse protocol
* * \E[?1006l disable mouse protocol
*
* Note: the escape sequences can be obtained with something like:
* strace -ewrite -o/proc/self/fd/3 -s500 tput -T$TERM smcup 3>&1 >/dev/null 2>&1
*
* Some documentation:
* * terminfo sequences related to mouse are "XM" and "xm" in
* http://invisible-island.net/ncurses/terminfo.src.html
* * ncurses implements a mouse interface in ncurses/base/lib_mouse.c:
* http://fossies.org/dox/ncurses-5.9/lib__mouse_8c_source.html
* * ... the associated man page is curs_mouse(3x):
* http://www.manpagez.com/man/3/curs_mouse/
*/
#ifndef _GNU_SOURCE
# define _GNU_SOURCE /* for sigaction, sigemptyset, snprintf */
#endif
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
/**
* Global variables
*/
static int tty_fd = -1;
static volatile unsigned int win_cols;
static volatile unsigned int win_rows;
static struct termios tty_attr_orig;
/**
* Callback to update win_cols and win_rows according to the size of tty_fd
*/
static int update_winsize(void)
{
struct winsize window_size;
if (tty_fd < 0) {
return 0;
}
if (ioctl(tty_fd, TIOCGWINSZ, &window_size) < 0) {
perror("ioctl(tty, TIOCGWINSZ)");
return 0;
}
win_cols = window_size.ws_col;
win_rows = window_size.ws_row;
return 1;
}
/**
* Write every byte to the tty
*/
static int tty_write(const char *buffer, size_t count)
{
if (tty_fd < 0) {
return 0;
}
while (count > 0) {
ssize_t ret = write(tty_fd, buffer, count);
if (ret >= 0) {
buffer += ret;
count -= (size_t)ret;
} else if (errno != EINTR) {
perror("write(tty)");
return 0;
}
}
return 1;
}
static int tty_print(const char *string)
{
return tty_write(string, strlen(string));
}
/**
* Initialize the tty
*/
static int tty_init(void)
{
const char *tty_name = "/dev/tty";
struct termios tty_attr;
/* Open a RW file descriptor to the current tty, using stdout or /dev/tty */
if (isatty(STDOUT_FILENO)) {
tty_name = ttyname(STDOUT_FILENO);
if (!tty_name) {
perror("ttyname");
return 0;
}
}
tty_fd = open(tty_name, O_RDWR | O_CLOEXEC);
if (tty_fd == -1) {
perror("open(tty)");
return 0;
}
/* Setup terminal attributes */
if (tcgetattr(tty_fd, &tty_attr) == -1) {
perror("tcgetattr");
close(tty_fd);
tty_fd = -1;
return 0;
}
tty_attr_orig = tty_attr;
tty_attr.c_lflag &= ~(unsigned)ICANON; /* Disable canonical mode */
tty_attr.c_lflag &= ~(unsigned)ECHO; /* Don't echo input characters */
tty_attr.c_lflag |= ISIG; /* Convert INT and QUIT chars to signal */
if (tcsetattr(tty_fd, TCSAFLUSH, &tty_attr) == -1) {
perror("tcsetattr");
return 0;
}
/* Get the window size */
if (!update_winsize()) {
return 0;
}
/* Enter alternate screen, make cursor invisible and enable mouse protocol */
if (!tty_print("\033[?1049h\033[?25l\033[?1002;1006h")) {
return 0;
}
return 1;
}
/**
* Revert everything tty_init did
*/
static void tty_reset(void)
{
if (tty_fd == -1) {
return;
}
/* Exit alternate screen, make cursor normal and disable mouse protocol */
tty_print("\033[?1049l\033[?12l\033[?25h\033[?1002;1006l");
/* Restore initial terminal attributes and drop unread input */
if (tcsetattr(tty_fd, TCSAFLUSH, &tty_attr_orig) == -1) {
perror("tcsetattr");
}
close(tty_fd);
tty_fd = -1;
}
/**
* Quit nicely when handling the interrupt signal
*/
static void __attribute__ ((noreturn)) handle_sigterm(int signum)
{
assert(signum == SIGINT || signum == SIGQUIT || signum == SIGTERM);
tty_reset();
exit(0);
}
/**
* Handle window change signal
*/
static void handle_sigwinch(int signum)
{
assert(signum == SIGWINCH);
update_winsize();
}
int main(void)
{
struct sigaction sa;
unsigned char buffer[1024];
char textbuf[200];
ssize_t count;
size_t i, curpos, textbufpos;
int saved_errno;
unsigned int mouse_buttons, mouse_x, mouse_y;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handle_sigterm;
if (sigaction(SIGINT, &sa, NULL) == -1) {
perror("sigaction(SIGINT)");
return 1;
}
if (sigaction(SIGQUIT, &sa, NULL) == -1) {
perror("sigaction(SIGQUIT)");
return 1;
}
if (sigaction(SIGTERM, &sa, NULL) == -1) {
perror("sigaction(SIGTERM)");
return 1;
}
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handle_sigwinch;
if (sigaction(SIGWINCH, &sa, NULL) == -1) {
perror("sigaction(SIGWINCH)");
return 1;
}
if (!tty_init()) {
tty_reset();
return 1;
}
snprintf(textbuf, sizeof(textbuf),
"Window size: %u x %u\n",
win_cols, win_rows);
tty_print(textbuf);
curpos = 0;
for (;;) {
assert(curpos < sizeof(buffer));
count = read(tty_fd, buffer + curpos, (size_t)(sizeof(buffer) - curpos));
if (count == -1) {
if (errno == EINTR) {
/* display current window size */
snprintf(textbuf, sizeof(textbuf),
"\033[HWindow size: %u x %u\033[K\n",
win_cols, win_rows);
tty_print(textbuf);
continue;
}
saved_errno = errno;
tty_reset();
errno = saved_errno;
perror("read");
return 1;
}
/* There are curpos+count available bytes in the buffer */
count += curpos;
curpos = 0;
for (i = 0; i < (size_t)count; i++) {
if (buffer[i] == '\003' || buffer[i] == 'q' || buffer[i] == 'Q') {
/* Quit if Received ^C, q or Q from the terminal */
tty_reset();
return 0;
} else if (buffer[i] == 'c' || buffer[i] == 'C') {
/* Clear screen */
tty_print("\033[H\033[2J");
continue;
} else if (buffer[i] != '\033') {
/* Received something else than escape sequence, continue */
continue;
}
/* Mouse is \e[M and 3 characters */
if (i + 6 > (size_t)count) {
/* The sequence has not been completely read, keep its beginning */
curpos = ((size_t)count) - i;
memmove(buffer, buffer + i, curpos);
break;
}
if (buffer[i + 1] != '[' && buffer[i + 2] != 'M') {
continue;
}
/* Retrieve mouse state from buffer */
mouse_buttons = (unsigned int)(buffer[i + 3] - ' ');
mouse_x = (unsigned int)(buffer[i + 4] - ' ' - 1) & 0xff;
mouse_y = (unsigned int)(buffer[i + 5] - ' ' - 1) & 0xff;
/* Display a pattern */
textbuf[0] = '\0';
/* Change the color depending on the button state */
switch (mouse_buttons) {
case 0:
/* Left button pressed */
snprintf(textbuf, sizeof(textbuf), "\033[31m");
break;
case 1:
/* Middle button pressed */
snprintf(textbuf, sizeof(textbuf), "\033[32m");
break;
case 2:
/* Right button pressed */
snprintf(textbuf, sizeof(textbuf), "\033[34m");
break;
case 3:
/* Button released */
snprintf(textbuf, sizeof(textbuf), "\033[37m");
break;
case 0x20:
/* Move with left button pressed */
snprintf(textbuf, sizeof(textbuf), "\033[41m");
break;
case 0x21:
/* Move with middle button pressed */
snprintf(textbuf, sizeof(textbuf), "\033[42m");
break;
case 0x22:
/* Move with right button pressed */
snprintf(textbuf, sizeof(textbuf), "\033[44m");
break;
case 0x40:
/* Mouse wheel up */
snprintf(textbuf, sizeof(textbuf), "\033[43m");
break;
case 0x41:
/* Mouse wheel down */
snprintf(textbuf, sizeof(textbuf), "\033[46m");
}
textbufpos = strlen(textbuf);
/* Show a cross on cursor position */
if (mouse_y >= 1) {
snprintf(textbuf + textbufpos, sizeof(textbuf) - textbufpos,
"\033[%u;%uH|", mouse_y, mouse_x + 1);
textbufpos += strlen(textbuf + textbufpos);
}
if (mouse_x == 0) {
snprintf(textbuf + textbufpos, sizeof(textbuf) - textbufpos,
"\033[%u;1HX-", mouse_y + 1);
} else if (mouse_x + 1 >= win_cols) {
snprintf(textbuf + textbufpos, sizeof(textbuf) - textbufpos,
"\033[%u;%uH-X", mouse_y + 1, mouse_x);
} else {
snprintf(textbuf + textbufpos, sizeof(textbuf) - textbufpos,
"\033[%u;%uH-X-", mouse_y + 1, mouse_x);
}
textbufpos += strlen(textbuf + textbufpos);
if (mouse_y + 1 < win_rows) {
snprintf(textbuf + textbufpos, sizeof(textbuf) - textbufpos,
"\033[%u;%uH|", mouse_y + 2, mouse_x + 1);
textbufpos += strlen(textbuf + textbufpos);
}
assert(textbufpos + 3 < sizeof(textbuf));
snprintf(textbuf + textbufpos, sizeof(textbuf) - textbufpos, "\033[m");
tty_print(textbuf);
/* printf("\033[H0x%02x, %u, %u\033[K\n", mouse_buttons, mouse_x, mouse_y); */
i += 5;
}
}
}
|
the_stack_data/72013220.c | // clang-format off
// RUN: %c-to-llvm %s | %apply-typeart -typeart-alloca -typeart-filter-pointer-alloca=true -S 2>&1 | %filecheck %s
// clang-format on
int main(int argc, char** argv) {
int n = argc * 2;
int* x;
int* y = &n;
return 0;
}
// CHECK: > Stack Memory
// CHECK-NEXT: Alloca : 6.00
// CHECK-NEXT: Stack call filtered % : 0.00
// CHECK-NEXT: Alloca of pointer discarded : 3.00
|
the_stack_data/34831.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#define WIDTH 640
#define HEIGHT 480
int main(int argc, char *argv) {
char fname[1000];
char size[200];
int n = getpid();
sprintf(fname, "/home/httpd/video/image%d.jpg", n);
unlink(fname);
if (fork() == 0) {
sprintf(size, "%dx%d", WIDTH, HEIGHT);
execl("/bin/vidcat", "vidcat",
"-f", "jpeg",
"-s", size,
"-o", fname,
NULL);
exit(1);
}
wait(NULL);
/* Output HTML header */
printf("Content-type: text/html\n");
printf("\n");
printf("<html><head>\n");
printf("<meta http-equiv=\"refresh\" content=\"7; URL=/cgi-bin/snapshot\">\n");
printf("<title>Image Capture</title>\n</head>\n");
printf("<body>\n");
printf("<h1>Current image</h1><p>\n");
printf("<img src=\"/video/image%d.jpg\" width=\"%d\" height=\"%d\">\n", n,
WIDTH/2, HEIGHT/2);
printf("<h1>Saved image</h1><p>\n");
printf("<img src=\"/video/image.jpg\" width=\"640\" height=\"480\">\n");
printf("</body></html>\n");
fflush(NULL);
if (fork() == 0) {
/* Wait a little while and delete our temp file */
close(0);
close(1);
close(2);
sleep(5);
unlink(fname);
}
}
|
the_stack_data/866058.c | // BUG: unable to handle kernel paging request in do_con_write
// https://syzkaller.appspot.com/bug?id=dc5c6b1ae4952a5d72d0e82de0eeeb9e5f767efc
// status:open
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
static long syz_open_dev(volatile long a0, volatile long a1, volatile long a2)
{
if (a0 == 0xc || a0 == 0xb) {
char buf[128];
sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block", (uint8_t)a1,
(uint8_t)a2);
return open(buf, O_RDWR, 0);
} else {
char buf[1024];
char* hash;
strncpy(buf, (char*)a0, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = 0;
while ((hash = strchr(buf, '#'))) {
*hash = '0' + (char)(a1 % 10);
a1 /= 10;
}
return open(buf, a2, 0);
}
}
uint64_t r[2] = {0xffffffffffffffff, 0xffffffffffffffff};
int main(void)
{
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 3ul, 0x32ul, -1, 0);
intptr_t res = 0;
memcpy((void*)0x20000180, "/dev/fb0\000", 9);
res = syscall(__NR_openat, 0xffffffffffffff9cul, 0x20000180ul, 0ul, 0ul);
if (res != -1)
r[0] = res;
*(uint32_t*)0x20000000 = 0;
*(uint32_t*)0x20000004 = 0x800;
*(uint32_t*)0x20000008 = 0;
*(uint32_t*)0x2000000c = 0;
*(uint32_t*)0x20000010 = 0;
*(uint32_t*)0x20000014 = 0;
*(uint32_t*)0x20000018 = 8;
*(uint32_t*)0x2000001c = 0;
*(uint32_t*)0x20000020 = 0;
*(uint32_t*)0x20000024 = 0;
*(uint32_t*)0x20000028 = 0;
*(uint32_t*)0x2000002c = 0;
*(uint32_t*)0x20000030 = 0;
*(uint32_t*)0x20000034 = 0;
*(uint32_t*)0x20000038 = 0;
*(uint32_t*)0x2000003c = 0;
*(uint32_t*)0x20000040 = 0;
*(uint32_t*)0x20000044 = 0;
*(uint32_t*)0x20000048 = 0;
*(uint32_t*)0x2000004c = 0;
*(uint32_t*)0x20000050 = 0;
*(uint32_t*)0x20000054 = 0;
*(uint32_t*)0x20000058 = 0;
*(uint32_t*)0x2000005c = 0;
*(uint32_t*)0x20000060 = 0;
*(uint32_t*)0x20000064 = 0;
*(uint32_t*)0x20000068 = 0;
*(uint32_t*)0x2000006c = 0;
*(uint32_t*)0x20000070 = 0;
*(uint32_t*)0x20000074 = 0;
*(uint32_t*)0x20000078 = 0;
*(uint32_t*)0x2000007c = 0;
*(uint32_t*)0x20000080 = 0;
*(uint32_t*)0x20000084 = 0;
*(uint32_t*)0x20000088 = 0;
*(uint32_t*)0x2000008c = 0;
*(uint32_t*)0x20000090 = 0;
*(uint32_t*)0x20000094 = 0;
*(uint32_t*)0x20000098 = 0;
*(uint32_t*)0x2000009c = 0;
syscall(__NR_ioctl, r[0], 0x4601ul, 0x20000000ul);
res = syz_open_dev(0xc, 4, 0x14);
if (res != -1)
r[1] = res;
*(uint8_t*)0x20000000 = 0x1b;
*(uint8_t*)0x20000001 = 0x5d;
*(uint8_t*)0x20000002 = 0x50;
*(uint8_t*)0x20000003 = 0x9b;
*(uint8_t*)0x20000004 = 0x4b;
*(uint8_t*)0x20000005 = 0;
*(uint8_t*)0x20000006 = 0;
*(uint8_t*)0x20000007 = 0;
*(uint64_t*)0x20000008 = 0;
*(uint16_t*)0x20000010 = 0;
*(uint16_t*)0x20000012 = 0;
*(uint32_t*)0x20000014 = 0;
*(uint64_t*)0x20000018 = 0;
*(uint64_t*)0x20000020 = 0x40;
*(uint64_t*)0x20000028 = 0;
*(uint32_t*)0x20000030 = 0;
*(uint16_t*)0x20000034 = 0;
*(uint16_t*)0x20000036 = 0x38;
*(uint16_t*)0x20000038 = 0;
*(uint16_t*)0x2000003a = 0;
*(uint16_t*)0x2000003c = 0;
*(uint16_t*)0x2000003e = 0;
*(uint32_t*)0x20000040 = 0;
*(uint32_t*)0x20000044 = 0;
*(uint64_t*)0x20000048 = 0;
*(uint64_t*)0x20000050 = 0;
*(uint64_t*)0x20000058 = 0;
*(uint64_t*)0x20000060 = 0;
*(uint64_t*)0x20000068 = 0;
*(uint64_t*)0x20000070 = 0;
syscall(__NR_write, r[1], 0x20000000ul, 0x78ul);
return 0;
}
|
the_stack_data/4374.c | /**
* ------------------
* SET A Question 2
* ------------------
* Create a scenario where there are three threads -
* One is writing the value of the shared variable
* and the other two are reading the value of the shared
* variable. Whne thread is writinh, no thrad is allowed to
* read and there can be concurrent reads by 2 threads.
* Synchronize the threads.
*
* NOTE: Compile with `gcc -lpthread`
*
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int shared_variable = 0;
pthread_mutex_t mutex1, mutex2;
void *readProcess1()
{
pthread_mutex_lock(&mutex1);
int x = shared_variable;
sleep(1);
printf("In read process1, Read value of shared variable is %d\n", x);
pthread_mutex_unlock(&mutex1);
}
void *readProcess2()
{
pthread_mutex_lock(&mutex2);
int x = shared_variable;
sleep(1);
printf("In read process2, Read value of shared variable is %d\n", x);
pthread_mutex_unlock(&mutex2);
}
void *writeProcess()
{
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
int x = shared_variable;
sleep(1);
x++;
shared_variable = x;
printf("In write process, Updated the shared variable to %d\n", x);
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex2);
}
int main()
{
pthread_mutex_init(&mutex1, 0);
pthread_mutex_init(&mutex2, 0);
pthread_t thread1, thread2, thread3;
// pthread_create(&thread2, NULL, &readProcess1, NULL);
// pthread_create(&thread3, NULL, &readProcess2, NULL);
printf("Initial value of shared variable is %d\n", shared_variable);
pthread_create(&thread1, NULL, &writeProcess, NULL);
pthread_create(&thread2, NULL, &readProcess1, NULL);
pthread_create(&thread3, NULL, &readProcess2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
return 0;
}
|
the_stack_data/1165917.c | #include <stdio.h>
#define SIZE 144
void print(char *list,int size){
for(int i=0;i<size;++i){
for(int j=0;j<size;++j){
if(list[i*size+j]==' ')printf("x");
else printf("Q");
}
printf("\n");
}
printf("\n");
}
int checkStraight(char *list,int size,int enter){
for(int i=0;i<size;++i){
if(list[i*size+enter]!=' ')return 0;
}
return 1;
}
int checkSlash(char *list,int size,int level,int enter){
for(int i=enter+1,j=level+1;i<size && j<size;++i,++j){
if(list[j*size+i]!=' ')return 0;
}
for(int i=enter-1,j=level+1;i>=0 && j<size;--i,++j){
if(list[j*size+i]!=' ')return 0;
}
for(int i=enter+1,j=level-1;i<size && j>=0;++i,--j){
if(list[j*size+i]!=' ')return 0;
}
for(int i=enter-1,j=level-1;i>=0 && j>=0;--i,--j){
if(list[j*size+i]!=' ')return 0;
}
return 1;
}
void dfs(int m,int size,char *list,int *ans,int level){
//print(list,size);
if(!m){
for(int i=0;i<size;++i){
for(int j=0;j<size;++j){
if(list[i*size+j]=='*'){
if(!checkSlash(list,size,i,j)){
//printf("ERROR i=%d j=%d\n",i,j);
return;
}
}
}
}
print(list,size);
++(*ans);
//printf("++ans %d\n",*ans);
}
else{
for(int i=0;i<size;++i){
if(checkStraight(list,size,i) && checkSlash(list,size,level,i)){
//printf("level=%d enter %d m\n",level,i);
list[level*size+i]='*';
dfs(m-1,size,list,ans,level+1);
list[level*size+i]=' ';
}
}
}
}
int main(){
int m;
scanf("%d",&m);
while(m){
char list[SIZE];
for(int i=0;i<SIZE;++i)list[i]=' ';
int ans=0;
dfs(m,m,list,&ans,0);
//if(!ans)printf("\n");
printf("%d\n\n",ans);
scanf("%d",&m);
}
}
|
the_stack_data/11224.c | #include <stdio.h>
#include <string.h>
void *realloc(void *ptr, size_t size) {
if (ptr == NULL) {
if (size == 0) {
free(ptr);
return NULL;
}
return malloc(size);
}
void* new_ptr = malloc(size);
memcpy(new_ptr, ptr, size);
free(ptr);
return new_ptr;
}
int main() {
// Usage example
int n = 3, new_n = 5;
int* arr = malloc(n * sizeof(int));
arr = realloc(arr, new_n * sizeof(int));
return 0;
} |
the_stack_data/1128940.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef BYTE_T
#define BYTE_T
typedef unsigned char byte;
#endif
#ifndef SBYTE_T
#define SBYTE_T
typedef signed char sbyte;
#endif
#ifndef __cplusplus
#ifndef BOOL_T
#define BOOL_T
typedef unsigned char bool;
#endif
#ifndef false
#define false 0
#endif
#ifndef true
#define true 1
#endif
#endif
#ifndef PDLIB_INT_BITS_T
#define PDLIB_INT_BITS_T
typedef unsigned short u16;
typedef signed short s16;
typedef unsigned int u32;
typedef signed int s32;
typedef unsigned long long u64;
typedef signed long long s64;
#endif
#ifndef F32_T
#define F32_T
typedef float f32;
#endif
#ifndef F64_T
#define F64_T
typedef double f64;
#endif
#define BSVM2_OPZ_INT 0
#define BSVM2_OPZ_LONG 1
#define BSVM2_OPZ_FLOAT 2
#define BSVM2_OPZ_DOUBLE 3
#define BSVM2_OPZ_ADDRESS 4
#define BSVM2_OPZ_UINT 5
#define BSVM2_OPZ_UBYTE 6
#define BSVM2_OPZ_SHORT 7
#define BSVM2_OPZ_SBYTE 8
#define BSVM2_OPZ_USHORT 9
#define BSVM2_OPZ_ULONG 10
#define BSVM2_OPZ_CONST 11
#define BSVM2_OPZ_NLONG 12
#define BSVM2_OPZ_UNLONG 13
#define BSVM2_OPZ_X128 14
#define BSVM2_OPZ_ADDR 4
// #define BSVM2_OPZ_VARIANT 4
#define BSVM2_OPZ_VOID 11
#define BS2CC_TYZ_VEC4F 14
#define BSVM2_EXS_CALLUNDEF -2
#define BS2VM_API
#define BSVM2_DBGTRAP
typedef union BGBDT_TagValue_s BGBDT_TagValue;
typedef union BGBDT_TagValue_s dtVal;
typedef union BSVM2_Value_u BSVM2_Value;
typedef union BSVM2_ValX128_u BSVM2_ValX128;
typedef struct BSVM2_Opcode_s BSVM2_Opcode;
typedef struct BSVM2_TailOpcode_s BSVM2_TailOpcode;
typedef struct BSVM2_Trace_s BSVM2_Trace;
typedef struct BSVM2_Frame_s BSVM2_Frame;
typedef struct BSVM2_Context_s BSVM2_Context;
typedef struct BSVM2_ImageGlobal_s BSVM2_ImageGlobal;
union BGBDT_TagValue_s {
struct { u32 lo, hi; };
u64 vi;
void *vp;
};
union BSVM2_Value_u {
struct { s32 i, j; };
struct { u32 ui, uj; };
struct { f32 fx, fy; };
s64 l;
u64 ul;
f32 f;
f64 d;
dtVal a;
void *p;
};
union BSVM2_ValX128_u {
struct { s32 ia, ib, ic, id; };
struct { u32 ua, ub, uc, ud; };
struct { f32 fx, fy, fz, fw; };
struct { s64 la, lb; };
struct { u64 ula, ulb; };
struct { f64 dx, dy; };
};
/** VM Opcode, Everything before Run is serialized in JIT */
struct BSVM2_Opcode_s {
short i0, i1, i2;
short t0, t1, t2;
BSVM2_Value v;
void (*Run)(BSVM2_Frame *frm, BSVM2_Opcode *op);
short opn, opn2;
byte z, o;
int opfl;
};
/** VM Opcode, Everything before Run is serialized in JIT */
struct BSVM2_TailOpcode_s {
short i0, i1;
short t0, t1;
BSVM2_Value v;
BSVM2_Trace *nexttrace;
BSVM2_Trace *jmptrace;
BSVM2_Trace *(*Run)(BSVM2_Frame *frm,
BSVM2_TailOpcode *op);
byte *jcs;
short opn, opn2;
byte z, o;
};
struct BSVM2_Trace_s {
BSVM2_Trace *(*Run)(BSVM2_Frame *frm,
BSVM2_Trace *tr);
BSVM2_TailOpcode *top;
BSVM2_Trace *jnext; //next trace to jump to
//BSVM2_CodeBlock *cblk; //code block
s64 runcnt; //execution count
s64 rsv[3];
BSVM2_Opcode **ops;
byte *cs; //bytecode addr for trace
byte *jcs; //bytecode addr for jump
char *gensym; //trace gensym
char *gensym_fn; //trace gensym (function)
void *t_ops[6];
int n_ops;
u64 trfl;
//BSVM2_JitTraceTemp *jitmp; //JIT temp data
};
struct BSVM2_Frame_s {
BSVM2_Context *ctx; //owning context
BSVM2_Value *stack; //stack base
BSVM2_Value *local; //locals base
BSVM2_Value *lxvar; //lexical vars
BSVM2_Frame *rnext; //return frame
BSVM2_Trace *rtrace; //return trace
int rcsrv; //return call save return value
int tstkpos; //tstackpos
dtVal self; //essentially, the 'this' value.
};
struct BSVM2_Context_s {
BSVM2_Context *next; //next context
BSVM2_Frame *cstack; //call stack
BSVM2_Value *tstack; //temp stack (locals and stack)
int tstackref; //ref position of temp stack
BSVM2_Frame *freeframe; //free frames
void *freex128; //free X128 vectors
BSVM2_Frame *frame; //current frame
BSVM2_Trace *trace; //current trace
BSVM2_Value *dynenv; //dynamic environment
int szdynenv; //allocated size of dynamic environment
int status; //status code
dtVal thrownex; //thrown exception object
BSVM2_Trace *ehstack_tr[256]; //exception handler stack trace
BSVM2_Frame *ehstack_fr[256]; //exception handler stack frame
int ehstackpos; //exception handler stackpos
};
struct BSVM2_ImageGlobal_s {
char *name; //name of variable
char *qname; //qname of variable
char *sig; //signature string
char *flagstr; //flags string
int *figix; //field/package GIX
int *ifgix; //interface GIX
int gix; //variable index
short nargs; //number of arguments
short nfigix; //number of fields
short nifgix; //number of interfaces
// int sugix; //superclass GIX
int giobj; //GIX of owner or superclass
u32 tag; //TLV type tag
s64 nameh; //name hash
s64 qnameh; //qname hash
u64 flags; //variable flags (decoded from string)
s64 runcnt; //execution count
BSVM2_Trace *ctrace; //call trace
byte brty; //base return type (functions)
union {
s64 batl[4];
byte baty[32]; //base arg type (functions)
};
BSVM2_Value *gvalue; //global value
void *objinf; //object info
//BSVM2_CodeImage *img;
BSVM2_ImageGlobal *pkg;
BSVM2_ImageGlobal *obj;
//BSVM2_CodeBlock *cblk;
};
#define DTV_NULL DTV_MagicConst(0)
// #define DTV_NULL DTV_MagicNull()
#define DTV_UNDEFINED DTV_MagicConst(1)
#define DTV_FALSE DTV_MagicConst(2)
#define DTV_TRUE DTV_MagicConst(3)
#define DTV_EMPTYLIST DTV_MagicConst(4)
dtVal DTV_MagicConst(int id)
{
dtVal val;
// val.hi=BGBDT_TAG_MCONST;
val.lo=id;
return(val);
}
dtVal dtvWrapPtr(void *ptr)
{
dtVal val;
val.vp=ptr;
return(val);
}
void *dtvUnwrapPtr(dtVal val)
{
return(val.vp);
}
dtVal dtvWrapInt(s32 val)
{
}
dtVal dtvWrapUInt(u32 val)
{
}
dtVal dtvWrapLong(s64 val)
{
}
dtVal dtvWrapFloat(f32 val)
{
}
dtVal dtvWrapDouble(f64 val)
{
}
s32 dtvUnwrapInt(dtVal val)
{
return(val.vi);
}
s64 dtvUnwrapLong(dtVal val)
{
return(val.vi);
}
s64 dtvUnwrapFloat(dtVal val)
{
return(val.vi);
}
s64 dtvUnwrapDouble(dtVal val)
{
return(val.vi);
}
char *bsvm2_natcall_nhashn[4096];
void *bsvm2_natcall_nhashv[4096];
BS2VM_API void *BSVM2_NatCall_GetProcAddress(char *name)
{
char *s;
void *p;
int i, j, h;
if(!name)
return(NULL);
// h=BGBDT_MM_QHashName(name);
for(i=0; i<256; i++)
{
j=(h>>12)&4095;
s=bsvm2_natcall_nhashn[j];
if(!s)
break;
if(!strcmp(s, name))
{
p=bsvm2_natcall_nhashv[j];
return(p);
}
h=h*4093+1;
}
if(i<256)
{
// p=BIPRO_LookupLabel(name);
p=NULL;
printf("BSVM2_NatCall_GetProcAddress: %s %p\n", name, p);
// bsvm2_natcall_nhashn[j]=bgbdt_mm_strdup(name);
bsvm2_natcall_nhashv[j]=p;
return(p);
}
// p=BIPRO_LookupLabel(name);
p=NULL;
printf("BSVM2_NatCall_GetProcAddress: %s %p\n", name, p);
return(p);
// return(NULL);
}
BS2VM_API int BSVM2_NatCall_RegisterProcAddress(char *name, void *addr)
{
// BIPRO_AddSym(name, addr);
return(0);
}
void BSVM2_NatCall_Call_0_V(void *fptr,
BSVM2_Value *rv, BSVM2_Value *av)
{ void (*fcn)(void); fcn=fptr; fcn(); }
void BSVM2_NatCall_Call_0_I(void *fptr,
BSVM2_Value *rv, BSVM2_Value *av)
{ int (*fcn)(void); fcn=fptr; rv->i=fcn(); }
void BSVM2_NatCall_Call_0_L(void *fptr,
BSVM2_Value *rv, BSVM2_Value *av)
{ s64 (*fcn)(void); fcn=fptr; rv->l=fcn(); }
void BSVM2_NatCall_Call_0_F(void *fptr,
BSVM2_Value *rv, BSVM2_Value *av)
{ float (*fcn)(void); fcn=fptr; rv->f=fcn(); }
void BSVM2_NatCall_Call_0_D(void *fptr,
BSVM2_Value *rv, BSVM2_Value *av)
{ double (*fcn)(void); fcn=fptr; rv->d=fcn(); }
void BSVM2_NatCall_Call_0_P(void *fptr,
BSVM2_Value *rv, BSVM2_Value *av)
{ void *(*fcn)(void); fcn=fptr; rv->p=fcn(); }
void BSVM2_NatCall_Call_0_A(void *fptr,
BSVM2_Value *rv, BSVM2_Value *av)
{ dtVal (*fcn)(void); fcn=fptr; rv->a=fcn(); }
#define BSVM2_NC_CALL1V(N, T0, P0) \
static void BSVM2_NatCall_Call##N(void *fptr, \
BSVM2_Value *rv, BSVM2_Value *av) \
{ void (*fcn)(T0); fcn=fptr; fcn(av[0].P0); }
#define BSVM2_NC_CALL1T(N, RT, RP, T0, P0) \
static void BSVM2_NatCall_Call##N(void *fptr, \
BSVM2_Value *rv, BSVM2_Value *av) \
{ RT (*fcn)(T0); fcn=fptr; rv->RP=fcn(av[0].P0); }
#define BSVM2_NC_CALL1(N, T0, P0) \
BSVM2_NC_CALL1V(N##V, T0, P0) \
BSVM2_NC_CALL1T(N##I, int, i, T0, P0) \
BSVM2_NC_CALL1T(N##L, s64, l, T0, P0) \
BSVM2_NC_CALL1T(N##F, f32, f, T0, P0) \
BSVM2_NC_CALL1T(N##D, f64, d, T0, P0) \
BSVM2_NC_CALL1T(N##P, void*, p, T0, P0) \
BSVM2_NC_CALL1T(N##A, dtVal, a, T0, P0)
#if 0
BSVM2_NC_CALL1(I, s32, i)
BSVM2_NC_CALL1(L, s64, l)
BSVM2_NC_CALL1(F, f32, f)
BSVM2_NC_CALL1(D, f64, d)
BSVM2_NC_CALL1(P, void*, p)
BSVM2_NC_CALL1(A, dtVal, a)
#endif
#define BSVM2_NC_CALL2V(N, T0, P0, T1, P1) \
static void BSVM2_NatCall_Call##N(void *fptr, \
BSVM2_Value *rv, BSVM2_Value *av) \
{ void (*fcn)(T0, T1); fcn=fptr; fcn(av[0].P0, av[1].P1); }
#define BSVM2_NC_CALL2T(N, RT, RP, T0, P0, T1, P1) \
static void BSVM2_NatCall_Call##N(void *fptr, \
BSVM2_Value *rv, BSVM2_Value *av) \
{ RT (*fcn)(T0, T1); fcn=fptr; rv->RP=fcn(av[0].P0, av[1].P1); }
#define BSVM2_NC_CALL2A(N, T0, P0, T1, P1) \
BSVM2_NC_CALL2V(N##V, T0, P0, T1, P1) \
BSVM2_NC_CALL2T(N##I, int, i, T0, P0, T1, P1) \
BSVM2_NC_CALL2T(N##L, s64, l, T0, P0, T1, P1) \
BSVM2_NC_CALL2T(N##F, f32, f, T0, P0, T1, P1) \
BSVM2_NC_CALL2T(N##D, f64, d, T0, P0, T1, P1) \
BSVM2_NC_CALL2T(N##P, void*, p, T0, P0, T1, P1) \
BSVM2_NC_CALL2T(N##A, dtVal, a, T0, P0, T1, P1)
#define BSVM2_NC_CALL2B(N, T0, P0) \
BSVM2_NC_CALL2A(N##I, T0, P0, s32, i) \
BSVM2_NC_CALL2A(N##L, T0, P0, s64, l) \
BSVM2_NC_CALL2A(N##F, T0, P0, f32, f) \
BSVM2_NC_CALL2A(N##D, T0, P0, f64, d) \
BSVM2_NC_CALL2A(N##P, T0, P0, void*, p) \
BSVM2_NC_CALL2A(N##A, T0, P0, dtVal, a)
#if 0
BSVM2_NC_CALL2B(I, s32, i)
BSVM2_NC_CALL2B(L, s64, l)
BSVM2_NC_CALL2B(F, f32, f)
BSVM2_NC_CALL2B(D, f64, d)
BSVM2_NC_CALL2B(P, void*, p)
BSVM2_NC_CALL2B(A, dtVal, a)
#endif
#if 0
BSVM2_Trace *BSVM2_TrOp_NatCallGFx(BSVM2_Frame *frm, BSVM2_TailOpcode *op)
{
BSVM2_NatCall_Call_N(op->v.p, op->i1,
frm->stack+op->t0, frm->stack+op->t1);
return(op->nexttrace);
}
#endif
#define BSVM2_NC_CASTCALL0T(N, RT, RP) \
case (N): rv->RP=((RT(*)(void))fcn)(); break;
#define BSVM2_NC_CASTCALL1T(N, RT, RP, T0, P0) \
case (N): rv->RP=((RT(*)(T0))fcn)(av[0].P0); break;
#define BSVM2_NC_CASTCALL2T(N, RT, RP, T0, P0, T1, P1) \
case (N): rv->RP=((RT(*)(T0, T1))fcn)(av[0].P0, av[1].P1); break;
#define BSVM2_NC_CASTCALL3T(N, RT, RP, T0, P0, T1, P1, T2, P2) \
case (N): rv->RP=((RT(*)(T0, T1, T2))fcn) \
(av[0].P0, av[1].P1, av[2].P2); break;
#define BSVM2_NC_CASTCALL4T(N, RT, RP, T0, P0, T1, P1, T2, P2, T3, P3) \
case (N): rv->RP=((RT(*)(T0, T1, T2, T3))fcn) \
(av[0].P0, av[1].P1, av[2].P2, av[3].P3); break;
#define BSVM2_NC_CASTCALL0A(N) \
BSVM2_NC_CASTCALL0T(((N)*6)+0, s32, i) \
BSVM2_NC_CASTCALL0T(((N)*6)+1, s64, l) \
BSVM2_NC_CASTCALL0T(((N)*6)+2, f32, f) \
BSVM2_NC_CASTCALL0T(((N)*6)+3, f64, d) \
BSVM2_NC_CASTCALL0T(((N)*6)+4, dtVal, a) \
BSVM2_NC_CASTCALL0T(((N)*6)+5, void*, p)
#define BSVM2_NC_CASTCALL1A(N, T0, P0) \
BSVM2_NC_CASTCALL1T(((N)*6)+0, s32, i, T0, P0) \
BSVM2_NC_CASTCALL1T(((N)*6)+1, s64, l, T0, P0) \
BSVM2_NC_CASTCALL1T(((N)*6)+2, f32, f, T0, P0) \
BSVM2_NC_CASTCALL1T(((N)*6)+3, f64, d, T0, P0) \
BSVM2_NC_CASTCALL1T(((N)*6)+4, dtVal, a, T0, P0) \
BSVM2_NC_CASTCALL1T(((N)*6)+5, void*, p, T0, P0)
#define BSVM2_NC_CASTCALL1B(N) \
BSVM2_NC_CASTCALL1A(((N)*6)+0, s32, i) \
BSVM2_NC_CASTCALL1A(((N)*6)+1, s64, l) \
BSVM2_NC_CASTCALL1A(((N)*6)+2, f32, f) \
BSVM2_NC_CASTCALL1A(((N)*6)+3, f64, d) \
BSVM2_NC_CASTCALL1A(((N)*6)+4, dtVal, a) \
BSVM2_NC_CASTCALL1A(((N)*6)+5, void*, p)
#define BSVM2_NC_CASTCALL2A(N, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL2T(((N)*6)+0, s32, i, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL2T(((N)*6)+1, s64, l, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL2T(((N)*6)+2, f32, f, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL2T(((N)*6)+3, f64, d, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL2T(((N)*6)+4, dtVal, a, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL2T(((N)*6)+5, void*, p, T0, P0, T1, P1)
#if 0
#define BSVM2_NC_CASTCALL2B(N, T0, P0) \
BSVM2_NC_CASTCALL2A(((N)*6)+0, s32, i, T0, P0) \
BSVM2_NC_CASTCALL2A(((N)*6)+1, s64, l, T0, P0) \
BSVM2_NC_CASTCALL2A(((N)*6)+2, f32, f, T0, P0) \
BSVM2_NC_CASTCALL2A(((N)*6)+3, f64, d, T0, P0) \
BSVM2_NC_CASTCALL2A(((N)*6)+4, dtVal, a, T0, P0) \
BSVM2_NC_CASTCALL2A(((N)*6)+5, void*, p, T0, P0)
#endif
#if 1
#define BSVM2_NC_CASTCALL2B(N, T0, P0) \
BSVM2_NC_CASTCALL2A(((N)*6)+0, T0, P0, s32, i) \
BSVM2_NC_CASTCALL2A(((N)*6)+1, T0, P0, s64, l) \
BSVM2_NC_CASTCALL2A(((N)*6)+2, T0, P0, f32, f) \
BSVM2_NC_CASTCALL2A(((N)*6)+3, T0, P0, f64, d) \
BSVM2_NC_CASTCALL2A(((N)*6)+4, T0, P0, dtVal, a) \
BSVM2_NC_CASTCALL2A(((N)*6)+5, T0, P0, void*, p)
#endif
#define BSVM2_NC_CASTCALL2C(N) \
BSVM2_NC_CASTCALL2B(((N)*6)+0, s32, i) \
BSVM2_NC_CASTCALL2B(((N)*6)+1, s64, l) \
BSVM2_NC_CASTCALL2B(((N)*6)+2, f32, f) \
BSVM2_NC_CASTCALL2B(((N)*6)+3, f64, d) \
BSVM2_NC_CASTCALL2B(((N)*6)+4, dtVal, a) \
BSVM2_NC_CASTCALL2B(((N)*6)+5, void*, p)
#define BSVM2_NC_CASTCALL3A(N, T0, P0, T1, P1, T2, P2) \
BSVM2_NC_CASTCALL3T(((N)*6)+0, s32, i, T0, P0, T1, P1, T2, P2) \
BSVM2_NC_CASTCALL3T(((N)*6)+1, s64, l, T0, P0, T1, P1, T2, P2) \
BSVM2_NC_CASTCALL3T(((N)*6)+2, f32, f, T0, P0, T1, P1, T2, P2) \
BSVM2_NC_CASTCALL3T(((N)*6)+3, f64, d, T0, P0, T1, P1, T2, P2) \
BSVM2_NC_CASTCALL3T(((N)*6)+4, dtVal, a, T0, P0, T1, P1, T2, P2) \
BSVM2_NC_CASTCALL3T(((N)*6)+5, void*, p, T0, P0, T1, P1, T2, P2)
#if 0
#define BSVM2_NC_CASTCALL3B(N, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL3A(((N)*6)+0, s32, i, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL3A(((N)*6)+1, s64, l, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL3A(((N)*6)+2, f32, f, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL3A(((N)*6)+3, f64, d, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL3A(((N)*6)+4, dtVal, a, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL3A(((N)*6)+5, void*, p, T0, P0, T1, P1)
#define BSVM2_NC_CASTCALL3C(N, T0, P0) \
BSVM2_NC_CASTCALL3B(((N)*6)+0, s32, i, T0, P0) \
BSVM2_NC_CASTCALL3B(((N)*6)+1, s64, l, T0, P0) \
BSVM2_NC_CASTCALL3B(((N)*6)+2, f32, f, T0, P0) \
BSVM2_NC_CASTCALL3B(((N)*6)+3, f64, d, T0, P0) \
BSVM2_NC_CASTCALL3B(((N)*6)+4, dtVal, a, T0, P0) \
BSVM2_NC_CASTCALL3B(((N)*6)+5, void*, p, T0, P0)
#endif
#if 1
#define BSVM2_NC_CASTCALL3B(N, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL3A(((N)*6)+0, T0, P0, T1, P1, s32, i) \
BSVM2_NC_CASTCALL3A(((N)*6)+1, T0, P0, T1, P1, s64, l) \
BSVM2_NC_CASTCALL3A(((N)*6)+2, T0, P0, T1, P1, f32, f) \
BSVM2_NC_CASTCALL3A(((N)*6)+3, T0, P0, T1, P1, f64, d) \
BSVM2_NC_CASTCALL3A(((N)*6)+4, T0, P0, T1, P1, dtVal, a) \
BSVM2_NC_CASTCALL3A(((N)*6)+5, T0, P0, T1, P1, void*, p)
#define BSVM2_NC_CASTCALL3C(N, T0, P0) \
BSVM2_NC_CASTCALL3B(((N)*6)+0, T0, P0, s32, i) \
BSVM2_NC_CASTCALL3B(((N)*6)+1, T0, P0, s64, l) \
BSVM2_NC_CASTCALL3B(((N)*6)+2, T0, P0, f32, f) \
BSVM2_NC_CASTCALL3B(((N)*6)+3, T0, P0, f64, d) \
BSVM2_NC_CASTCALL3B(((N)*6)+4, T0, P0, dtVal, a) \
BSVM2_NC_CASTCALL3B(((N)*6)+5, T0, P0, void*, p)
#endif
#define BSVM2_NC_CASTCALL3D(N) \
BSVM2_NC_CASTCALL3C(((N)*6)+0, s32, i) \
BSVM2_NC_CASTCALL3C(((N)*6)+1, s64, l) \
BSVM2_NC_CASTCALL3C(((N)*6)+2, f32, f) \
BSVM2_NC_CASTCALL3C(((N)*6)+3, f64, d) \
BSVM2_NC_CASTCALL3C(((N)*6)+4, dtVal, a) \
BSVM2_NC_CASTCALL3C(((N)*6)+5, void*, p)
#define BSVM2_NC_CASTCALL4A(N, T0, P0, T1, P1, T2, P2, T3, P3) \
BSVM2_NC_CASTCALL4T(((N)*6)+0, s32, i, T0, P0, T1, P1, T2, P2, T3, P3) \
BSVM2_NC_CASTCALL4T(((N)*6)+1, s64, l, T0, P0, T1, P1, T2, P2, T3, P3) \
BSVM2_NC_CASTCALL4T(((N)*6)+2, f32, f, T0, P0, T1, P1, T2, P2, T3, P3) \
BSVM2_NC_CASTCALL4T(((N)*6)+3, f64, d, T0, P0, T1, P1, T2, P2, T3, P3) \
BSVM2_NC_CASTCALL4T(((N)*6)+4, dtVal, a, T0, P0, T1, P1, T2, P2, T3, P3) \
BSVM2_NC_CASTCALL4T(((N)*6)+5, void*, p, T0, P0, T1, P1, T2, P2, T3, P3)
#if 0
#define BSVM2_NC_CASTCALL4B(N, T0, P0, T1, P1, T2, P2) \
BSVM2_NC_CASTCALL4A(((N)*6)+0, s32, i, T0, P0, T1, P1, T2, P2) \
BSVM2_NC_CASTCALL4A(((N)*6)+1, s64, l, T0, P0, T1, P1, T2, P2) \
BSVM2_NC_CASTCALL4A(((N)*6)+2, f32, f, T0, P0, T1, P1, T2, P2) \
BSVM2_NC_CASTCALL4A(((N)*6)+3, f64, d, T0, P0, T1, P1, T2, P2) \
BSVM2_NC_CASTCALL4A(((N)*6)+4, dtVal, a, T0, P0, T1, P1, T2, P2) \
BSVM2_NC_CASTCALL4A(((N)*6)+5, void*, p, T0, P0, T1, P1, T2, P2)
#define BSVM2_NC_CASTCALL4C(N, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL4B(((N)*6)+0, s32, i, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL4B(((N)*6)+1, s64, l, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL4B(((N)*6)+2, f32, f, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL4B(((N)*6)+3, f64, d, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL4B(((N)*6)+4, dtVal, a, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL4B(((N)*6)+5, void*, p, T0, P0, T1, P1)
#define BSVM2_NC_CASTCALL4D(N, T0, P0) \
BSVM2_NC_CASTCALL4C(((N)*6)+0, s32, i, T0, P0) \
BSVM2_NC_CASTCALL4C(((N)*6)+1, s64, l, T0, P0) \
BSVM2_NC_CASTCALL4C(((N)*6)+2, f32, f, T0, P0) \
BSVM2_NC_CASTCALL4C(((N)*6)+3, f64, d, T0, P0) \
BSVM2_NC_CASTCALL4C(((N)*6)+4, dtVal, a, T0, P0) \
BSVM2_NC_CASTCALL4C(((N)*6)+5, void*, p, T0, P0)
#endif
#if 1
#define BSVM2_NC_CASTCALL4B(N, T0, P0, T1, P1, T2, P2) \
BSVM2_NC_CASTCALL4A(((N)*6)+0, T0, P0, T1, P1, T2, P2, s32, i) \
BSVM2_NC_CASTCALL4A(((N)*6)+1, T0, P0, T1, P1, T2, P2, s64, l) \
BSVM2_NC_CASTCALL4A(((N)*6)+2, T0, P0, T1, P1, T2, P2, f32, f) \
BSVM2_NC_CASTCALL4A(((N)*6)+3, T0, P0, T1, P1, T2, P2, f64, d) \
BSVM2_NC_CASTCALL4A(((N)*6)+4, T0, P0, T1, P1, T2, P2, dtVal, a) \
BSVM2_NC_CASTCALL4A(((N)*6)+5, T0, P0, T1, P1, T2, P2, void*, p)
#define BSVM2_NC_CASTCALL4C(N, T0, P0, T1, P1) \
BSVM2_NC_CASTCALL4B(((N)*6)+0, T0, P0, T1, P1, s32, i) \
BSVM2_NC_CASTCALL4B(((N)*6)+1, T0, P0, T1, P1, s64, l) \
BSVM2_NC_CASTCALL4B(((N)*6)+2, T0, P0, T1, P1, f32, f) \
BSVM2_NC_CASTCALL4B(((N)*6)+3, T0, P0, T1, P1, f64, d) \
BSVM2_NC_CASTCALL4B(((N)*6)+4, T0, P0, T1, P1, dtVal, a) \
BSVM2_NC_CASTCALL4B(((N)*6)+5, T0, P0, T1, P1, void*, p)
#define BSVM2_NC_CASTCALL4D(N, T0, P0) \
BSVM2_NC_CASTCALL4C(((N)*6)+0, T0, P0, s32, i) \
BSVM2_NC_CASTCALL4C(((N)*6)+1, T0, P0, s64, l) \
BSVM2_NC_CASTCALL4C(((N)*6)+2, T0, P0, f32, f) \
BSVM2_NC_CASTCALL4C(((N)*6)+3, T0, P0, f64, d) \
BSVM2_NC_CASTCALL4C(((N)*6)+4, T0, P0, dtVal, a) \
BSVM2_NC_CASTCALL4C(((N)*6)+5, T0, P0, void*, p)
#endif
#define BSVM2_NC_CASTCALL4E(N) \
BSVM2_NC_CASTCALL4D(((N)*6)+0, s32, i) \
BSVM2_NC_CASTCALL4D(((N)*6)+1, s64, l) \
BSVM2_NC_CASTCALL4D(((N)*6)+2, f32, f) \
BSVM2_NC_CASTCALL4D(((N)*6)+3, f64, d) \
BSVM2_NC_CASTCALL4D(((N)*6)+4, dtVal, a) \
BSVM2_NC_CASTCALL4D(((N)*6)+5, void*, p)
void BSVM2_NatCall_Call_N(void *fcn, int nc,
BSVM2_Value *rv, BSVM2_Value *av)
{
switch(nc)
{
BSVM2_NC_CASTCALL0A(1)
BSVM2_NC_CASTCALL1B(1)
BSVM2_NC_CASTCALL2C(1)
BSVM2_NC_CASTCALL3D(1)
BSVM2_NC_CASTCALL4E(1)
default:
BSVM2_DBGTRAP
break;
}
}
BS2VM_API BSVM2_Trace *BSVM2_TrOp_NatCallG0(
BSVM2_Frame *frm, BSVM2_TailOpcode *op)
{
static int rec=0;
if(op->i0!=99)
{
printf("BSVM2_TrOp_NatCallG0: %p ix=%d\n", op->v.p, op->i1);
op->i0=99;
}
if(rec>=16)
{
printf("BSVM2_TrOp_NatCallG0: Recursion Limit\n");
return(op->nexttrace);
}
if(rec>0)
{
printf("BSVM2_TrOp_NatCallG0: Rec %d\n", rec);
}
rec++;
BSVM2_NatCall_Call_N(op->v.p, op->i1,
frm->stack+op->t0, frm->stack+op->t1);
rec--;
return(op->nexttrace);
}
char *BSVM2_NatCall_SigNext(char *sig)
{
char *s;
s=sig;
if((*s>='a') && (*s<='z'))
return(s+1);
if((*s=='C') || (*s=='D') || (*s=='R'))
{
return(BSVM2_NatCall_SigNext(s+1));
}
if(*s=='P')
{
while(*s=='P')s++;
return(BSVM2_NatCall_SigNext(s));
}
if(*s=='Q')
{
while(*s=='Q')s++;
return(BSVM2_NatCall_SigNext(s));
}
if((*s=='X') || (*s=='L') || (*s=='U'))
{
s++;
if((*s>='0') && (*s<='9'))
{
while((*s>='0') && (*s<='9'))
s++;
}else
{
while(*s && (*s!=';'))
s++;
if(*s==';')
s++;
}
return(s);
}
if(*s=='A')
{
s++;
if((*s>='0') && (*s<='9'))
{
while((*s>='0') && (*s<='9'))
s++;
return(BSVM2_NatCall_SigNext(s));
}else
{
return(BSVM2_NatCall_SigNext(s+1));
// while(*s && (*s!=';'))
// s++;
// if(*s==';')
// s++;
}
// return(BSVM2_NatCall_SigNext(s));
}
return(s);
}
char *BSVM2_NatCall_SigGetRet(char *sig)
{
char *s;
if(*sig=='(')
{
s=sig+1;
while(*s && (*s!=')'))
{ s=BSVM2_NatCall_SigNext(s); }
if(*s==')')
return(s+1);
return(NULL);
}
return(NULL);
}
int BSVM2_NatCall_GetSigOpZ(char *sig)
{
int i;
switch(*sig)
{
case 'a': case 'b': case 'c': case 'h':
case 'i': case 'k':
case 's': case 't': case 'w':
i=BSVM2_OPZ_INT; break;
case 'j':
i=BSVM2_OPZ_UINT; break;
case 'l': case 'x':
i=BSVM2_OPZ_LONG; break;
case 'm': case 'y':
i=BSVM2_OPZ_ULONG; break;
case 'f':
i=BSVM2_OPZ_FLOAT; break;
case 'd': case 'e':
i=BSVM2_OPZ_DOUBLE; break;
case 'g': case 'n': case 'o':
// i=BS2CC_TYZ_INT128;
break;
case 'p': case 'q': case 'r':
i=BSVM2_OPZ_ADDRESS; break;
case 'C':
if((sig[1]=='b') || (sig[1]=='c') ||
(sig[1]=='d') || (sig[1]=='e') ||
(sig[1]=='h') ||
(sig[1]=='q'))
{ i=BS2CC_TYZ_VEC4F; break; }
i=BSVM2_OPZ_ADDRESS; break;
case 'Q':
case 'X': case 'L':
i=BSVM2_OPZ_ADDRESS; break;
case 'v':
i=BSVM2_OPZ_VOID; break;
case 'z':
i=BSVM2_OPZ_ADDR; break;
case 'P':
i=BSVM2_OPZ_ADDR; break;
// i=5; break;
case 'A':
i=BSVM2_OPZ_ADDR; break;
default:
i=-1; break;
}
return(i);
}
int BSVM2_NatCall_GetSigBType(char *sig)
{
int i;
switch(*sig)
{
case 'a': case 'b': case 'c': case 'h':
case 'i': case 'j': case 'k':
case 's': case 't': case 'w':
i=0; break;
case 'l': case 'm':
case 'x': case 'y':
i=1; break;
case 'f': i=2; break;
case 'd': case 'e':
i=3; break;
case 'g': case 'n': case 'o':
case 'p': case 'q': case 'r':
i=4; break;
case 'C':
// if(sig[1]=='s')
// { i=-1; break; }
if((sig[1]=='b') || (sig[1]=='c') ||
(sig[1]=='d') || (sig[1]=='e') ||
(sig[1]=='h') ||
(sig[1]=='q'))
{ i=5; break; }
i=4; break;
case 'Q':
case 'X': case 'L':
i=4; break;
case 'v':
i=0; break;
case 'z':
i=-1; break;
case 'P':
i=-1; break;
// i=5; break;
case 'R':
i=5; break;
default:
i=-1; break;
}
return(i);
}
int BSVM2_NatCall_GetSigIndexG0(char *sig)
{
char *s;
int i, j;
if(*sig!='(')
return(-1);
s=sig; i=1;
if(*s=='(')s++;
while(*s && (*s!=')'))
{
j=BSVM2_NatCall_GetSigBType(s);
if(j<0)
return(-1);
i=i*6+j;
s=BSVM2_NatCall_SigNext(s);
}
if(*s==')')
{
s++;
j=BSVM2_NatCall_GetSigBType(s);
if(j<0)
return(-1);
i=i*6+j;
}
return(i);
}
#if 0
int BSVM2_NatCall_GetSigIndexG1(char *sig,
BSVM2_Value *iav, BSVM2_Value *oav)
{
BSVM2_Value *avs, *avt;
dtVal va, v0;
char *s;
int i, j, k, l;
if(*sig!='(')
return(-1);
s=sig; i=1;
avs=iav;
avt=oav;
if(*s=='(')s++;
while(*s && (*s!=')'))
{
if(*s=='z')break;
if(*s=='P')
{
if(s[1]=='c')
{
s+=2;
avt->p=BGBDT_TagStr_GetUtf8(avs->a);
avt++; avs++;
i=i*6+5;
continue;
}
s=BSVM2_NatCall_SigNext(s);
avt->p=dtvUnwrapPtr(avs->a);
avt++; avs++;
i=i*6+5;
continue;
}
if(*s=='C')
{
#if 0
if(s[1]=='s')
{
s+=2;
avt->p=BGBDT_TagStr_GetUtf8(avs->a);
avt++; avs++;
i=i*6+5;
continue;
}
#endif
}
*avt++=*avs++;
j=BSVM2_NatCall_GetSigBType(s);
if(j<0)
return(-1);
i=i*6+j;
s=BSVM2_NatCall_SigNext(s);
}
if(*s=='z')
{
s++;
va=avs->a;
if(dtvIsArrayP(va))
{
l=dtvArrayGetSize(va);
for(j=0; j<l; j++)
{
// v0=dtvArrayGetIndexDtVal(va, j);
if(dtvIsSmallIntP(v0))
{ avt->i=dtvUnwrapInt(v0);
avt++; i=i*6+0; continue; }
if(dtvIsSmallLongP(v0))
{ avt->l=dtvUnwrapLong(v0);
avt++; i=i*6+1; continue; }
if(dtvIsSmallDoubleP(v0))
{ avt->d=dtvUnwrapDouble(v0);
avt++; i=i*6+3; continue; }
avt->a=v0;
avt++;
i=i*6+4;
continue;
}
}
}
if(*s==')')
{
s++;
if(*s=='P')
{
i=i*6+5;
}else
{
j=BSVM2_NatCall_GetSigBType(s);
if(j<0)
return(-1);
i=i*6+j;
}
}
return(i);
}
#endif
BS2VM_API BSVM2_Trace *BSVM2_TrOp_NatCallG1(
BSVM2_Frame *frm, BSVM2_TailOpcode *op)
{
BSVM2_Value argt[64];
BSVM2_ImageGlobal *vi;
void *p;
int ic;
vi=op->v.p;
p=BSVM2_NatCall_GetProcAddress(vi->name);
// ic=BSVM2_NatCall_GetSigIndexG1(vi->sig,
// frm->stack+op->t1, argt);
BSVM2_NatCall_Call_N(p, ic,
frm->stack+op->t0, argt);
return(op->nexttrace);
}
dtVal BSVM2_Sig_GetSigPtrDtVal(void *ptr, char *sig)
{
dtVal v;
int i;
switch(*sig)
{
case 'a': case 'c':
v=dtvWrapInt(*(sbyte *)ptr); break;
case 'b': case 'h':
v=dtvWrapInt(*(byte *)ptr); break;
case 'k':
case 's':
v=dtvWrapInt(*(s16 *)ptr); break;
case 't': case 'w':
v=dtvWrapInt(*(u16 *)ptr); break;
case 'i':
v=dtvWrapInt(*(s32 *)ptr); break;
case 'j':
v=dtvWrapUInt(*(u32 *)ptr); break;
case 'l': case 'm':
v=dtvWrapLong(*(long *)ptr); break;
case 'x': case 'y':
v=dtvWrapLong(*(s64 *)ptr); break;
case 'f':
v=dtvWrapFloat(*(f32 *)ptr); break;
case 'd': case 'e':
v=dtvWrapDouble(*(f64 *)ptr); break;
case 'g': case 'n': case 'o':
case 'p': case 'q': case 'r':
v=*(dtVal *)ptr; break;
case 'C':
if((sig[1]=='b') || (sig[1]=='c') ||
(sig[1]=='d') || (sig[1]=='e') ||
(sig[1]=='h') ||
(sig[1]=='q'))
{
i=BS2CC_TYZ_VEC4F; break;
}
v=*(dtVal *)ptr; break;
case 'Q':
case 'X': case 'L':
v=*(dtVal *)ptr; break;
case 'v':
i=BSVM2_OPZ_VOID; break;
case 'z':
i=BSVM2_OPZ_ADDR; break;
case 'P':
v=dtvWrapPtr(*(void **)ptr); break;
// i=BSVM2_OPZ_ADDR;
break;
// i=5; break;
default:
v=DTV_UNDEFINED;
break;
}
return(v);
}
dtVal BSVM2_Sig_SetSigPtrDtVal(void *ptr, char *sig, dtVal v)
{
int i;
switch(*sig)
{
case 'a': case 'c':
*(sbyte *)ptr=dtvUnwrapInt(v); break;
case 'b': case 'h':
*(byte *)ptr=dtvUnwrapInt(v); break;
case 'k':
case 's':
*(s16 *)ptr=dtvUnwrapInt(v); break;
case 't': case 'w':
*(u16 *)ptr=dtvUnwrapInt(v); break;
case 'i':
*(s32 *)ptr=dtvUnwrapInt(v); break;
case 'j':
*(u32 *)ptr=dtvUnwrapInt(v); break;
case 'l': case 'm':
*(long *)ptr=dtvUnwrapLong(v); break;
case 'x': case 'y':
*(s64 *)ptr=dtvUnwrapLong(v); break;
case 'f':
*(f32 *)ptr=dtvUnwrapFloat(v); break;
case 'd': case 'e':
*(f64 *)ptr=dtvUnwrapDouble(v); break;
case 'g': case 'n': case 'o':
case 'p': case 'q': case 'r':
*(dtVal *)ptr=v; break;
case 'C':
if((sig[1]=='b') || (sig[1]=='c') ||
(sig[1]=='d') || (sig[1]=='e') ||
(sig[1]=='h') ||
(sig[1]=='q'))
{
i=BS2CC_TYZ_VEC4F; break;
}
*(dtVal *)ptr=v; break;
case 'Q':
case 'X': case 'L':
*(dtVal *)ptr=v; break;
case 'v':
break;
case 'z':
break;
case 'P':
*(void **)ptr=dtvUnwrapPtr(v); break;
break;
default:
break;
}
return(v);
}
BSVM2_Trace *BSVM2_TrOp_NatCallFail(BSVM2_Frame *frm, BSVM2_TailOpcode *op)
{
frm->ctx->status=BSVM2_EXS_CALLUNDEF;
return(NULL);
}
int main()
{
BSVM2_Value argt[64];
void *p;
int i, j, k;
p=(void *)(rand()); j=rand();
for(i=0; i<256; i++)
{
j=j*251+1;
BSVM2_NatCall_Call_N(p, j, argt, argt);
}
} |
the_stack_data/119795.c | /* LL raised several warnings, ignore them */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#ifdef STM32F0xx
#include "stm32f0xx_ll_dac.c"
#elif STM32F1xx
#include "stm32f1xx_ll_dac.c"
#elif STM32F2xx
#include "stm32f2xx_ll_dac.c"
#elif STM32F3xx
#include "stm32f3xx_ll_dac.c"
#elif STM32F4xx
#include "stm32f4xx_ll_dac.c"
#elif STM32F7xx
#include "stm32f7xx_ll_dac.c"
#elif STM32G0xx
#include "stm32g0xx_ll_dac.c"
#elif STM32G4xx
#include "stm32g4xx_ll_dac.c"
#elif STM32H7xx
#include "stm32h7xx_ll_dac.c"
#elif STM32L0xx
#include "stm32l0xx_ll_dac.c"
#elif STM32L1xx
#include "stm32l1xx_ll_dac.c"
#elif STM32L4xx
#include "stm32l4xx_ll_dac.c"
#elif STM32L5xx
#include "stm32l5xx_ll_dac.c"
#elif STM32WLxx
#include "stm32wlxx_ll_dac.c"
#endif
#pragma GCC diagnostic pop
|
the_stack_data/36562.c | // random numbers example
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *generate(void);
int main()
{
int x;
int *a;
puts("Here are 10 random numbers:");
a = generate();
for (x = 0; x < 10; x++)
printf(" %3d", a[x]);
putchar('\n');
return (0);
}
int *generate(void)
{
static int array[10];
int x;
srand((unsigned)time(NULL));
for (x = 0; x < 10; x++)
array[x] = rand() % 100 + 1;
return (array);
}
|
the_stack_data/242331143.c | #if 0
/* SPDX-License-Identifier: MIT */
/*
* Authors: Rolf Neugebauer
* Grzegorz Milos
* Costin Lupu <[email protected]>
*
* Copyright (c) 2003-2005, Intel Research Cambridge
* Copyright (c) 2017, NEC Europe Ltd., NEC Corporation. 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.
*/
/*
* Thread definitions
* Ported from Mini-OS
*/
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <uk/plat/config.h>
#include <uk/plat/time.h>
#include <uk/thread.h>
#include <uk/sched.h>
#include <uk/wait.h>
#include <uk/print.h>
#include <uk/assert.h>
#include <uk/arch/tls.h>
/* Pushes the specified value onto the stack of the specified thread */
static void stack_push(unsigned long *sp, unsigned long value)
{
*sp -= sizeof(unsigned long);
*((unsigned long *) *sp) = value;
}
static void init_sp(unsigned long *sp, char *stack,
void (*function)(void *), void *data)
{
*sp = (unsigned long) stack + STACK_SIZE;
#if defined(__X86_64__)
/* Must ensure that (%rsp + 8) is 16-byte aligned
* at the start of thread_starter.
*/
stack_push(sp, 0);
#endif
stack_push(sp, (unsigned long) function);
stack_push(sp, (unsigned long) data);
}
#ifdef CONFIG_LIBNEWLIBC
static void reent_init(struct _reent *reent)
{
_REENT_INIT_PTR(reent);
#if 0
/* TODO initialize basic signal handling */
_init_signal_r(myreent);
#endif
}
struct _reent *__getreent(void)
{
struct _reent *_reent;
struct uk_sched *s = uk_sched_get_default();
if (!s || !uk_sched_started(s))
_reent = _impure_ptr;
else
_reent = &uk_thread_current()->reent;
return _reent;
}
#endif /* CONFIG_LIBNEWLIBC */
int uk_thread_init(struct uk_thread *thread,
struct ukplat_ctx_callbacks *cbs, struct uk_alloc *allocator,
const char *name, void *stack, void *tls,
void (*function)(void *), void *arg)
{
unsigned long sp;
UK_ASSERT(thread != NULL);
UK_ASSERT(stack != NULL);
UK_ASSERT(!have_tls_area() || tls != NULL);
/* Save pointer to the thread on the stack to get current thread */
*((unsigned long *) stack) = (unsigned long) thread;
init_sp(&sp, stack, function, arg);
/* Call platform specific setup. */
thread->ctx = ukplat_thread_ctx_create(cbs, allocator, sp,
(uintptr_t)ukarch_tls_pointer(tls));
if (thread->ctx == NULL)
return -1;
thread->name = name;
thread->stack = stack;
thread->tls = tls;
/* Not runnable, not exited, not sleeping */
thread->flags = 0;
thread->wakeup_time = 0LL;
thread->detached = false;
uk_waitq_init(&thread->waiting_threads);
thread->sched = NULL;
thread->prv = NULL;
#ifdef CONFIG_LIBNEWLIBC
reent_init(&thread->reent);
#endif
uk_pr_info("Thread \"%s\": pointer: %p, stack: %p, tls: %p\n",
name, thread, thread->stack, thread->tls);
return 0;
}
void uk_thread_fini(struct uk_thread *thread, struct uk_alloc *allocator)
{
UK_ASSERT(thread != NULL);
ukplat_thread_ctx_destroy(allocator, thread->ctx);
}
static void uk_thread_block_until(struct uk_thread *thread, __snsec until)
{
unsigned long flags;
flags = ukplat_lcpu_save_irqf();
thread->wakeup_time = until;
clear_runnable(thread);
uk_sched_thread_blocked(thread->sched, thread);
ukplat_lcpu_restore_irqf(flags);
}
void uk_thread_block_timeout(struct uk_thread *thread, __nsec nsec)
{
__snsec until = (__snsec) ukplat_monotonic_clock() + nsec;
uk_thread_block_until(thread, until);
}
void uk_thread_block(struct uk_thread *thread)
{
uk_thread_block_until(thread, 0LL);
}
void uk_thread_wake(struct uk_thread *thread)
{
unsigned long flags;
flags = ukplat_lcpu_save_irqf();
if (!is_runnable(thread)) {
uk_sched_thread_woken(thread->sched, thread);
thread->wakeup_time = 0LL;
set_runnable(thread);
}
ukplat_lcpu_restore_irqf(flags);
}
void uk_thread_exit(struct uk_thread *thread)
{
UK_ASSERT(thread);
set_exited(thread);
if (!thread->detached)
uk_waitq_wake_up(&thread->waiting_threads);
uk_pr_debug("Thread \"%s\" exited.\n", thread->name);
}
int uk_thread_wait(struct uk_thread *thread)
{
UK_ASSERT(thread);
/* TODO critical region */
if (thread->detached)
return -EINVAL;
uk_waitq_wait_event(&thread->waiting_threads, is_exited(thread));
thread->detached = true;
uk_sched_thread_destroy(thread->sched, thread);
return 0;
}
int uk_thread_detach(struct uk_thread *thread)
{
UK_ASSERT(thread);
thread->detached = true;
return 0;
}
int uk_thread_set_prio(struct uk_thread *thread, prio_t prio)
{
if (!thread)
return -EINVAL;
return uk_sched_thread_set_prio(thread->sched, thread, prio);
}
int uk_thread_get_prio(const struct uk_thread *thread, prio_t *prio)
{
if (!thread)
return -EINVAL;
return uk_sched_thread_get_prio(thread->sched, thread, prio);
}
int uk_thread_set_timeslice(struct uk_thread *thread, int timeslice)
{
if (!thread)
return -EINVAL;
return uk_sched_thread_set_timeslice(thread->sched, thread, timeslice);
}
int uk_thread_get_timeslice(const struct uk_thread *thread, int *timeslice)
{
if (!thread)
return -EINVAL;
return uk_sched_thread_get_timeslice(thread->sched, thread, timeslice);
}
#endif |
the_stack_data/140765760.c | /* DataToC output of file <octahedron_lib_glsl> */
extern int datatoc_octahedron_lib_glsl_size;
extern char datatoc_octahedron_lib_glsl[];
int datatoc_octahedron_lib_glsl_size = 956;
char datatoc_octahedron_lib_glsl[] = {
13, 10,118,101, 99, 50, 32,109, 97,112,112,105,110,103, 95,111, 99,116, 97,104,101,100,114,111,110, 40,118,101, 99, 51, 32, 99,117, 98,101,118,101, 99, 44, 32,118,101, 99, 50, 32,116,101,120,101,108, 95,115,105,122,101, 41, 13, 10,123, 13, 10, 9, 47, 42, 32,112,114,111,106,101, 99,116,105,111,110, 32,111,110,116,111, 32,111, 99,116, 97,104,101,100,114,111,110, 32, 42, 47, 13, 10, 9, 99,117, 98,101,118,101, 99, 32, 47, 61, 32,100,111,116, 40, 32,118,101, 99, 51, 40, 49, 41, 44, 32, 97, 98,115, 40, 99,117, 98,101,118,101, 99, 41, 32, 41, 59, 13, 10, 13, 10, 9, 47, 42, 32,111,117,116, 45,102,111,108,100,105,110,103, 32,111,102, 32,116,104,101, 32,100,111,119,110,119, 97,114,100, 32,102, 97, 99,101,115, 32, 42, 47, 13, 10, 9,105,102, 32, 40, 32, 99,117, 98,101,118,101, 99, 46,122, 32, 60, 32, 48, 46, 48, 32, 41, 32,123, 13, 10, 9, 9, 99,117, 98,101,118,101, 99, 46,120,121, 32, 61, 32, 40, 49, 46, 48, 32, 45, 32, 97, 98,115, 40, 99,117, 98,101,118,101, 99, 46,121,120, 41, 41, 32, 42, 32,115,105,103,110, 40, 99,117, 98,101,118,101, 99, 46,120,121, 41, 59, 13, 10, 9,125, 13, 10, 13, 10, 9, 47, 42, 32,109, 97,112,112,105,110,103, 32,116,111, 32, 91, 48, 59, 49, 93,203,134, 50, 32,116,101,120,116,117,114,101, 32,115,112, 97, 99,101, 32, 42, 47, 13, 10, 9,118,101, 99, 50, 32,117,118,115, 32, 61, 32, 99,117, 98,101,118,101, 99, 46,120,121, 32, 42, 32, 40, 48, 46, 53, 41, 32, 43, 32, 48, 46, 53, 59, 13, 10, 13, 10, 9, 47, 42, 32,101,100,103,101, 32,102,105,108,116,101,114,105,110,103, 32,102,105,120, 32, 42, 47, 13, 10, 9,117,118,115, 32, 61, 32, 40, 49, 46, 48, 32, 45, 32, 50, 46, 48, 32, 42, 32,116,101,120,101,108, 95,115,105,122,101, 41, 32, 42, 32,117,118,115, 32, 43, 32,116,101,120,101,108, 95,115,105,122,101, 59, 13, 10, 13, 10, 9,114,101,116,117,114,110, 32,117,118,115, 59, 13, 10,125, 13, 10, 13, 10,118,101, 99, 52, 32,116,101,120,116,117,114,101, 76,111,100, 95,111, 99,116, 97,104,101,100,114,111,110, 40,115, 97,109,112,108,101,114, 50, 68, 65,114,114, 97,121, 32,116,101,120, 44, 32,118,101, 99, 52, 32, 99,117, 98,101,118,101, 99, 44, 32,102,108,111, 97,116, 32,108,111,100, 44, 32,102,108,111, 97,116, 32,108,111,100, 95,109, 97,120, 41, 13, 10,123, 13, 10, 9,118,101, 99, 50, 32,116,101,120,101,108, 83,105,122,101, 32, 61, 32, 49, 46, 48, 32, 47, 32,118,101, 99, 50, 40,116,101,120,116,117,114,101, 83,105,122,101, 40,116,101,120, 44, 32,105,110,116, 40,108,111,100, 95,109, 97,120, 41, 41, 41, 59, 13, 10, 13, 10, 9,118,101, 99, 50, 32,117,118,115, 32, 61, 32,109, 97,112,112,105,110,103, 95,111, 99,116, 97,104,101,100,114,111,110, 40, 99,117, 98,101,118,101, 99, 46,120,121,122, 44, 32,116,101,120,101,108, 83,105,122,101, 41, 59, 13, 10, 13, 10, 9,114,101,116,117,114,110, 32,116,101,120,116,117,114,101, 76,111,100, 40,116,101,120, 44, 32,118,101, 99, 51, 40,117,118,115, 44, 32, 99,117, 98,101,118,101, 99, 46,119, 41, 44, 32,108,111,100, 41, 59, 13, 10,125, 13, 10, 13, 10,118,101, 99, 52, 32,116,101,120,116,117,114,101, 95,111, 99,116, 97,104,101,100,114,111,110, 40,115, 97,109,112,108,101,114, 50, 68, 65,114,114, 97,121, 32,116,101,120, 44, 32,118,101, 99, 52, 32, 99,117, 98,101,118,101, 99, 41, 13, 10,123, 13, 10, 9,118,101, 99, 50, 32,116,101,120,101,108, 83,105,122,101, 32, 61, 32, 49, 46, 48, 32, 47, 32,118,101, 99, 50, 40,116,101,120,116,117,114,101, 83,105,122,101, 40,116,101,120, 44, 32, 48, 41, 41, 59, 13, 10, 13, 10, 9,118,101, 99, 50, 32,117,118,115, 32, 61, 32,109, 97,112,112,105,110,103, 95,111, 99,116, 97,104,101,100,114,111,110, 40, 99,117, 98,101,118,101, 99, 46,120,121,122, 44, 32,116,101,120,101,108, 83,105,122,101, 41, 59, 13, 10, 13, 10, 9,114,101,116,117,114,110, 32,116,101,120,116,117,114,101, 40,116,101,120, 44, 32,118,101, 99, 51, 40,117,118,115, 44, 32, 99,117, 98,101,118,101, 99, 46,119, 41, 41, 59, 13, 10,125, 13, 10,0
};
|
the_stack_data/79866.c | #include <stdio.h>
#include <string.h>
#define LIMIT 28
void fit(char *,unsigned int);
int main(void){
char msg[]="good good study, day day up! fighting, fighting!!!";
printf("origin msg is :\"%s\"\n",msg);
fit(msg,LIMIT);
printf("fit msg is :\"%s\"\n",msg);
printf("msg+%d is :\"%s\"\n",LIMIT+1,msg+LIMIT+1);
return 0;
}
void fit(char *str,unsigned int size){
if( strlen(str)>size){
str[size]='\0';
}
}
|
the_stack_data/1140302.c | /* Test step/next in a shared library
Copyright 2004, Free Software Foundation, Inc.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
int hithere2()
{
int a;
a = 21;
return a;
}
|
the_stack_data/159516641.c | /* To illustrate the interprocedural issues with free() */
#include <stdlib.h>
int ordered_free01(int *fp) {
int *fq = fp;
free(fp);
fp = (int *) malloc(sizeof(int));
return 0;
}
int main()
{
int *p = (int *) malloc(sizeof(int));
ordered_free01(p);
// Here we may not know that p has been freed but we should know
// that p may have been freed
return 0;
}
|
the_stack_data/90766481.c | #include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/wait.h>
#define MSGSIZE 5
int main(int argc, char* argv[]){
int pid, j, piped[2];
char mess[MSGSIZE];
char inpbuf[MSGSIZE];
int pidfiglio, status, ritorno;
if(argc != 2){
printf("numero dei param errato %d;: ci vuuole un singolo param\n", argc);
exit(1);
}
if(pipe(piped) < 0){
printf("errore creazione pipe\n");
exit(2);
}
if((pid = fork()) < 0){
printf("errore creazione figlio\n");
exit(3);
}
if(pid == 0){
int fd;
close(piped[0]);
if((fd = open(argv[1], O_RDONLY)) < 0){
printf("errore in apertura file %s\n", argv[1]);
exit(-1);
}
printf("figlio %d sta per iniziare a scrivere una serie di messaggi, ognuno di lunghezzza %d, sulla pipe dopo averli letti dal file passato come parametro\n", getpid(), MSGSIZE);
while(read(fd, mess, MSGSIZE)){
mess[MSGSIZE-1]='\0';
write(piped[1], mess, MSGSIZE);
j++;
}
printf("figlio %d ha scritto %d messaggi sulla pipe\n", getpid(), j);
}
//padre
close(piped[1]);
printf("padre %d sta per iniziare a leggere i messaggi della pipe\n", getpid());j = 0;
while(read(piped[0], inpbuf, MSGSIZE)){
printf("%d: %s\n", j, inpbuf);
j++;
}
printf("padre %d ketto %d messaggi dalla pipe\n", getpid(), j);
pidfiglio= wait(&status);
if(pidfiglio < 0){
printf("errore wait\n");
exit(4);
}
if(pipe(piped) < 0){
printf("figlio con pid %d terminato in modo anomalo\n", pidfiglio);
} else {
ritorno = (int) ((status >> 8) & 0xFF);
printf("Il figlio con pid=%d ha ritornato %d\n", pidfiglio, ritorno);
}
exit(0);
}
|
the_stack_data/148855.c | #include <stdio.h>
int main() {
char flag[39];
flag[0] = 'b';
flag[1] = '0';
flag[2] = 'c';
flag[3] = 't';
flag[4] = 'f';
flag[5] = '{';
flag[6] = 'w';
flag[7] = 'h';
flag[8] = '4';
flag[9] = 't';
flag[10] = '_';
flag[11] = '4';
flag[12] = 'r';
flag[13] = 'e';
flag[14] = '_';
flag[15] = 'y';
flag[16] = '3';
flag[17] = '_';
flag[18] = 'd';
flag[19] = '0';
flag[20] = '1';
flag[21] = 'n';
flag[22] = 'g';
flag[23] = '_';
flag[24] = 'i';
flag[25] = 'n';
flag[26] = '_';
flag[27] = 'm';
flag[28] = 'y';
flag[30] = '_';
flag[31] = 's';
flag[32] = 'w';
flag[33] = '4';
flag[34] = 'm';
flag[35] = 'p';
flag[36] = '?';
flag[37] = '}';
flag[38] = '\0';
char * shrek = "....................................................................................................\n"
"...........................................................................................,;;.;;...\n"
".........................................,,,,,,,,.........................................,;*.++....\n"
"......................................,::;;;;;;;;::,,............................,........+;,*+;,...\n"
"....................................,;+*+++;;;::;;::::,,.........................+;,.....,++.**+....\n"
".............,....................,;****+++;;:::::::::::,,.......................*:;.....;;;;***....\n"
"...........,;??:,...............,:******+***?++;;;;;::::::,,.....................,*+....,;*++?*.....\n"
"..........,;%SS%,..............,+**??**?**?????++++;;;:::::,,.....................+;....+**+**?.....\n"
"..........:%SSS%;,............,+*??*???????**?+;;;:;;;;:::::,,....................,+:..++*+*++......\n"
".........,%SSSS%+,...........,+??*??*;;+;+++**??++;;;::;;;::::,..............,,....+;,++*++++:......\n"
"........,+%SSSS%+:,.........,;?**;;;;;;;;;+++**%?%;;;;;:::::::,,............,?+%;..;::;***++*,......\n"
"........,?%SSSS%*;,.........:**%?%%?*+++;+;+***%?%%*++;;;;;;;*:,,..........,+%%SS%.;:::+**++,.......\n"
"........,+%%%SSS?+:,.......,*%SSSSS%%%%?**?*%%*%?%%%S%?+***%??*;:,.........,?%%S%%%+:,+++;+,........\n"
".........,+%SSSSS?+,......,;SSSSSSS#SSSSSSSS%??%?%%SSSSS%SSSSS%+*;.........:%%*%%%%?;;*+;;*.........\n"
"...........,;?S#SS%*,.....,*%SS%S%%%S%S%##SS%%%%?%%SSS#SSSSSSS?+%?,.......,*%%?S%%%?;++;;*..........\n"
".............,:*SSSS*,...,+%S%%%%%%%%%S%SSSSSS%%%%%S%%%S%%%%??**;;+,......:%%S%S%*+;+?++*...........\n"
"...............,,*SSS?,.,;%%%%S%%SSSSSSSSSSSSS%%%%%S%%%%%%%%%%?*+;;,,....,?%SSSS%?+;+*?*:...........\n"
".................,+SSS?++?%SSSS%S%SSSSSSSSSSSS%%%%%%SS%%%S%%%%%%?*;;,...,*%%S%?+:,.:+*?.............\n"
"..................,+SS%%?%%SSSSS%%%#%S%SSSSSSS%%%%%%SSSS%%%%?%%%%?*;,,.,*%%%?:,.....+*+.............\n"
"...................,?S%%?%SSS%S#SSSSS#SSSSSSS%%%%%%%SSS%%%%?%*+;?%?+;++?%%%+,.......+*+.............\n"
"....................,%%??%%SS%SS?*#@S@*%#SSS%%%???%%SSSSSSS%SSS%*??*;:%%%%+,........:*+;............\n"
".....................+%??%%S%%%S%*##@#%?%#S%%%**+;:+SSSS?*#@#S;?%+**+:+%%+...........+*+............\n"
".....................;?????%%%%%%%%%%%%SS%%?*+;;;;;::SSS??#@@#::;;++;::?+,...........+*+............\n"
".....................;????????S%%%%SSSS%??*??****++;;:;SS%????*+;;;;;:,;,............:*+;...........\n"
".....................+?*?****?????????????%%%???****+;:::*S%%%?+;;;;:::,,.............+*;...........\n"
"....................,***********?????????%%%%%%??***++;:::;:*%S*;;;;::,,,............,;*++..........\n"
"....................:*****?*****????%??%%%%%%%%%??%??++;:::+;;;;;;;:::,,,.............:++;..........\n"
"....................+?*???????*????S%%%%%SS%%%%%%%??**+;;;::?+;;;;;;:,,,,,.............+*;;.........\n"
"...................,*????????????%S#%SSSSSS%%%%%%%%%?*++++;:S%*+;;;;:,,,,,.............+++;.........\n"
"...................,????????????%%S#SS####SSSS%%%%SS%****?*;?%??*+;;::,:,,,............,**+:........\n"
"...................;??????????%%SSSS##@@####SSSSSSSSS%%#@@S*%S%%%?+;;::::,,...........,,**++,.......\n"
"..................,*???%?%%%%%SSS#?%%%SSS#######SSSSS#####SSSSS%%??*;;::::,.........,;;::**;:.......\n"
"..................,????%%%%%SSSS%%????%%SSSSS######SSS%?*+;+%%SSS%%%*;;:::,......,:;;;+++++*;.......\n"
"..................:??%%%%%%SS#%%???????%%%%SSSSSSSS%?*;;;;::;?%%#SS%%?+;::,,...,;++++******,,.......\n"
"..................;??%%%%SSSS%%?%?????????%%%%%%%%%??+;;;;:::;*%%SSS%%%*;::;;;++++*??***+...........\n"
".................,+?%%%%%SS%%%%%%%?????%?????%???*???*;;;;;:::;*%%SSS%%?+;:;+++++???**,.............\n"
"..................+?%%%%%%S%?%%%%%%?%????????*++***???;;;;;;:;:;*?%%S%%?*;:;+++*??**................\n"
"..................???%%%%%%?%%%%%%%%%%%????*+;++***??*;;;;;:;;;:;**+%%%%*+:;****?;,,................\n"
"...............,.????%?%%%%?%SSSSSSS%%%%%???*+++*****+++;;;;;;;;+*%+;???+;::**+.....................\n"
"...............,*?????%?%%?%S#@@@@@####SSSS%??*******?%SSSSSSSSSSSS?:??*+;;:........................\n"
"...............*????????%%??%SS@@@#####S%###SSS%SSSSSS########@@@#%%:;*++;::,.......................\n"
".............,*??????????%?%%%S#####S%#?*?SS?%SS#SS%S#S%+S%%S#@@#S+*;:++;;::,.......................\n"
"............,????????????%?%%%SS####S%@?*??**??%%???+%%*::?;#@@@S?:;::+;;;::,.......................\n"
"...........,*????????%?????%%?%%S###SS#???%????%??**;*?*;;*+%#@S?*::::;;:;::,.......................\n"
"..........:*???*+,?%?%?%%??%%%%%%S@@S##@##@???%%**?*;?%**??+@@@?+;::::;;;:::........................\n"
".........,?????:.,??%???%???%?%%%%%#@@@@@@@@@@#@@%%?*@@@@@##@@%*+:::::;::;:,,.......................\n"
".........*+*%?...,+%??%?????%?%%%%%%S?@@@@@@@@#@@@@@@@@@@@@@#*++::::::;::::,........................\n"
".........*;:;.....,?%???%?%%?%%%%%%%%%S%??*@***+;@@?:#S*;@%*+++::::::;;:;::,........................\n"
".........*;:,......:?%???%?%%%%%%%%%%%?***+?**??+*?*;%*+++;;;;;;:::::;;::::,........................\n"
"........,*;:.......,*%??%%??%%%%%%%%%%%%?*++++;+;+;+;;;;;;;;;;;;:::::;;:::,,........................\n"
"........;*::.......,:%%?%%??%%%%%%%%%%%%%%%%%%%???********++;;;;::::::::;:,.........................\n"
"........*+:;........,+?%%%%??%%%%%%%%%%%%%%%%%%SS%%%%%%??*++++;;:::::;::::,.........................\n"
"........*+:;.........,%%???%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%?**++;;;;::;;::::,.........................\n"
"........*+::.........,;%??%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%?**++;;;::::::::,.........................\n"
"........*;:...........,*%?%??%%%%%S%%%%%%%%%%%%%%%%%%%%%%%??**+;;;::::::::,.........................\n"
"........*;;............,??%%?%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%?*+;;:::;::::,..........................\n"
".......:*;;............,*?%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*?++;;::;;::::,..........................\n"
".......++;,..............*?%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%???++;;;;:::::,,..........................\n"
".......*+:...............*??%%%%%%%%%%%%%%%%%%%%%%%%%%%%??+*+;;;;;;;;;::,...........................\n"
".......*+:...............+%??%%%%%%%%%??%?%??%??%%%%?????*+;;::;:;;;;;:,............................\n"
"......,*+:...............*??%?%%%%%%%%%?%%%????%?%%????*?+;;;:;;;;;;;:,.............................\n"
"......+*;:...............*?????%%%%%%%%%%?%????????????**+;;;::;;;;+:,..............................\n"
"......??+:...............*???*+:?%%%%%%%%%?%??%%%?%?????**+;;;;;+;;:,...............................\n"
"......%%*+:..............????*;,,+%%%%%%%%%%%%%%%%%?%%%???*++++++;,.................................\n"
".....,%%*++..............*??**...,:?S%%%%%%%%%%%%%%%%%%%?%?****;,...................................\n"
"......%%?*+,............:???*+.....,:?%S%S%%%%%%%%%%%%%%%%%??+:,....................................\n"
".....:%%??+;............+???*:.......,:;*%%%SS%%%%%%%%%%%%%?*,......................................\n"
".....:%???*;............*???*...........,,:;+**??????**%%%?++.......................................\n"
".....+%??%?+............***?+,...............,,,,,,,,,,*??*+;.......................................\n"
".....?%?*S%*............****:...........................?**;;.......................................\n"
".....?%*;.S%............*++*,...........................**+;;.......................................\n"
".....%%*+,%%,..........,*+++,...........................**+;;.......................................\n"
".....*%?+.??;..........;*;+,............................,*+;;.......................................\n"
"......?%+.:**..........**+;..............................++;:.......................................\n"
"......%S*..%*..........???*..............................++;;.......................................\n"
"......?%?,.,+..........:%%*..............................+**;.......................................\n"
".......%%+.............,??*............................,.****.......................................\n"
".......%%?;............,%?*.............................+???,.......................................\n"
"........%S*:...........:%?*............................+*??*........................................\n"
".........S%*...........;%%?...........................,*?*?.........................................\n"
"..........%*,..........;%?*...........................+***:.........................................\n"
"...........,:;:.;:,,:**?+;:+..........................++*+?,........................................\n"
"..........,;:;;+;;++;;;:;:;;,........................+**+;+.........................................\n"
".........,;?+::*++****;;;++++.......................;*?**+;:........................................\n"
"........,*%%?+*%**?*++++***??....................*?:***??**+++,.....................................\n"
"..........%%%%%??%%%?%?????%:..................????*?????%???+****;++;:.............................\n"
"...........,;*???%%%%%%%%+....................%%%?%%%%?%%%????****+;;+;;;,..........................\n"
"...................;%*,.......................%%SSS%%SSS%%%%%%%???*+*:*+**..........................\n"
".................................................%%...%%SSSS%%%%%??*%*;**?;.........................\n"
"..........................................................:+%%S%%%%%?%???%:,........................\n"
"................................................................+%%%%S%%%%,.........................\n";
printf("%s\n", shrek);
printf("%s\n", "WHAT ARE YOU DOING IN MY SWAMP?");
}
|
the_stack_data/173579275.c | /* Miscellaneous simulator utilities.
Copyright (C) 1997-2021 Free Software Foundation, Inc.
Contributed by Cygnus Support.
This file is part of GDB, the GNU debugger.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void
gen_struct (void)
{
printf ("\n");
printf ("typedef struct _test_tuples {\n");
printf (" int line;\n");
printf (" int row;\n");
printf (" int col;\n");
printf (" unsigned64 val;\n");
printf (" unsigned64 check;\n");
printf ("} test_tuples;\n");
printf ("\n");
printf ("typedef struct _test_spec {\n");
printf (" const char *file;\n");
printf (" const char *macro;\n");
printf (" int nr_rows;\n");
printf (" int nr_cols;\n");
printf (" test_tuples *tuples;\n");
printf ("} test_spec;\n");
}
void
gen_bit (int bitsize,
int msb,
const char *macro,
int nr_bits)
{
int i;
printf ("\n/* Test the %s macro */\n", macro);
printf ("test_tuples %s_tuples[%d] = {\n", macro, nr_bits);
for (i = 0; i < nr_bits; i++)
{
/* compute what we think the value is */
unsigned long long bit = 1;
if (msb == 0)
bit <<= nr_bits - i - 1;
else
bit <<= i;
if (bitsize == 32)
bit &= 0xffffffff; /* truncate it! */
/* write it out */
printf (" { __LINE__, ");
printf ("%d, %2d, ", -1, i);
printf ("%s (%2d), ", macro, i);
printf ("UNSIGNED64 (0x%016llx), ", bit);
printf ("},\n");
}
printf ("};\n");
printf ("\n");
printf ("test_spec %s_test = { __FILE__, \"%s\", 1, %d, %s_tuples, };\n",
macro, macro, nr_bits, macro);
printf ("\n");
}
void
gen_enum (const char *macro,
int nr_bits)
{
int i;
printf ("\n/* Test the %s macro in an enum */\n", macro);
printf ("enum enum_%s {\n", macro);
for (i = 0; i < nr_bits; i++)
{
printf (" elem_%s_%d = %s (%d),\n", macro, i, macro, i);
}
printf ("};\n");
printf ("\n");
}
void
gen_mask (int bitsize,
const char *msb,
const char *macro,
int nr_bits)
{
int l;
int h;
printf ("\n/* Test the %s%s macro */\n", msb, macro);
printf ("test_tuples %s_tuples[%d][%d] = {\n", macro, nr_bits, nr_bits);
for (l = 0; l < nr_bits; l++)
{
printf (" {\n");
for (h = 0; h < nr_bits; h++)
{
printf (" { __LINE__, ");
if ((strcmp (msb, "MS") == 0 && l <= h)
|| (strcmp (msb, "MS") != 0 && l >= h)
|| (strcmp (macro, "") == 0))
{
/* compute the mask */
unsigned long long mask = 0;
int b;
for (b = 0; b < nr_bits; b++)
{
unsigned long long bit = 1;
if (strcmp (msb, "MS") == 0)
{
if ((l <= b && b <= h)
|| (h < l && (b <= h || b >= l)))
bit <<= (nr_bits - b - 1);
else
bit = 0;
}
else
{
if ((l >= b && b >= h)
|| (h > l && (b >= h || b <= l)))
bit <<= b;
else
bit = 0;
}
mask |= bit;
}
if (bitsize == 32)
mask &= 0xffffffff;
printf ("%d, %d, ", l, h);
printf ("%s%s (%2d, %2d), ", msb, macro, l, h);
printf ("UNSIGNED64 (0x%llx), ", mask);
}
else
printf ("-1, -1, ");
printf ("},\n");
}
printf (" },\n");
}
printf ("};\n");
printf ("\n");
printf ("test_spec %s_test = { __FILE__, \"%s%s\", %d, %d, &%s_tuples[0][0], };\n",
macro, msb, macro, nr_bits, nr_bits, macro);
printf ("\n");
}
void
usage (int reason)
{
fprintf (stderr, "Usage:\n");
fprintf (stderr, " bits-gen <nr-bits> <msb> <byte-order>\n");
fprintf (stderr, "Generate a test case for the simulator bit manipulation code\n");
fprintf (stderr, " <nr-bits> = { 32 | 64 }\n");
fprintf (stderr, " <msb> = { 0 | { 31 | 63 } }\n");
fprintf (stderr, " <byte-order> = { big | little }\n");
switch (reason)
{
case 1: fprintf (stderr, "Wrong number of arguments\n");
break;
case 2:
fprintf (stderr, "Invalid <nr-bits> argument\n");
break;
case 3:
fprintf (stderr, "Invalid <msb> argument\n");
break;
case 4:
fprintf (stderr, "Invalid <byte-order> argument\n");
break;
}
exit (1);
}
int
main (int argc, char *argv[])
{
int bitsize;
int msb;
char *ms;
int big_endian;
if (argc != 4)
usage (1);
if (strcmp (argv [1], "32") == 0)
bitsize = 32;
else if (strcmp (argv [1], "64") == 0)
bitsize = 64;
else
usage (2);
if (strcmp (argv [2], "0") == 0)
msb = 0;
else if (strcmp (argv [2], "31") == 0 && bitsize == 32)
msb = 31;
else if (strcmp (argv [2], "63") == 0 && bitsize == 64)
msb = 63;
else
usage (3);
if (msb == 0)
ms = "MS";
else
ms = "LS";
if (strcmp (argv [3], "big") == 0)
big_endian = 1;
else if (strcmp (argv [3], "little") == 0)
big_endian = 0;
else
usage (4);
printf ("#define WITH_TARGET_WORD_BITSIZE %d\n", bitsize);
printf ("#define WITH_TARGET_WORD_MSB %d\n", msb);
printf ("#define WITH_HOST_WORD_BITSIZE %zu\n", sizeof (int) * 8);
printf ("#define WITH_TARGET_BYTE_ORDER %s\n", big_endian ? "BFD_ENDIAN_BIG" : "BFD_ENDIAN_LITTLE");
printf ("\n");
printf ("#define SIM_BITS_INLINE (ALL_H_INLINE)\n");
printf ("\n");
printf ("#define ASSERT(X) do { if (!(X)) abort(); } while (0)\n");
printf ("\n");
printf ("#define PACKAGE \"sim\"\n");
printf ("#include <stdlib.h>\n");
printf ("#include <string.h>\n");
printf ("#include \"sim-basics.h\"\n");
gen_struct ();
printf ("#define DO_BIT_TESTS\n");
gen_bit ( 4, msb, "BIT4", 4);
gen_bit ( 5, msb, "BIT5", 5);
gen_bit ( 8, msb, "BIT8", 8);
gen_bit (10, msb, "BIT10", 10);
gen_bit (16, msb, "BIT16", 16);
gen_bit (32, msb, "BIT32", 32);
gen_bit (64, msb, "BIT64", 64);
gen_bit (bitsize, msb, "BIT", 64);
gen_bit ( 8, 8 - 1, "LSBIT8", 8);
gen_bit (16, 16 - 1, "LSBIT16", 16);
gen_bit (32, 32 - 1, "LSBIT32", 32);
gen_bit (64, 64 - 1, "LSBIT64", 64);
gen_bit (bitsize, bitsize - 1, "LSBIT", 64);
gen_bit ( 8, 0, "MSBIT8", 8);
gen_bit (16, 0, "MSBIT16", 16);
gen_bit (32, 0, "MSBIT32", 32);
gen_bit (64, 0, "MSBIT64", 64);
gen_bit (bitsize, 0, "MSBIT", 64);
printf ("test_spec *(bit_tests[]) = {\n");
printf (" &BIT4_test,\n");
printf (" &BIT5_test,\n");
printf (" &BIT8_test,\n");
printf (" &BIT10_test,\n");
printf (" &BIT16_test,\n");
printf (" &BIT32_test,\n");
printf (" &BIT64_test,\n");
printf (" &BIT_test,\n");
printf (" &LSBIT8_test,\n");
printf (" &LSBIT16_test,\n");
printf (" &LSBIT32_test,\n");
printf (" &LSBIT64_test,\n");
printf (" &LSBIT_test,\n");
printf (" &MSBIT8_test,\n");
printf (" &MSBIT16_test,\n");
printf (" &MSBIT32_test,\n");
printf (" &MSBIT64_test,\n");
printf (" &MSBIT_test,\n");
printf (" 0,\n");
printf ("};\n\n");
gen_enum ("BIT", 64);
gen_enum ("LSBIT", 64);
gen_enum ("MSBIT", 64);
gen_enum ("BIT32", 32);
gen_enum ("LSBIT32", 32);
gen_enum ("MSBIT32", 32);
printf ("#define DO_MASK_TESTS\n");
gen_mask ( 8, ms, "MASK8", 8);
gen_mask (16, ms, "MASK16", 16);
gen_mask (32, ms, "MASK32", 32);
gen_mask (64, ms, "MASK64", 64);
gen_mask (bitsize, ms, "MASK", 64);
printf ("test_spec *(mask_tests[]) = {\n");
printf (" &MASK8_test,\n");
printf (" &MASK16_test,\n");
printf (" &MASK32_test,\n");
printf (" &MASK64_test,\n");
printf (" &MASK_test,\n");
printf (" 0,\n");
printf ("};\n\n");
return 0;
}
|
the_stack_data/82951350.c | #include <stdio.h>
#include <string.h>
#include <ctype.h>
char tokens[5][4] = {"ID", "NUM", "PYC", "CMP", "ASG"};
char frase[80] = {"Mary;@123 45=califa;==82fin"};
char lexema[30];
int ind = 0;
void imprimeToken(int num)
{
printf("Token: %s Lexema: %s\n", tokens[num], lexema);
}
int main(void)
{
int n = strlen(frase);
int i, edo = 1;
while (i < n)
{
switch (edo)
{
case 1:
if (isalpha(frase[i]))
{
edo = 2;
lexema[ind++] = frase[i++];
}
else
{
if (isdigit(frase[i]))
{
edo = 3;
lexema[ind++] = frase[i++];
}
else
{
if (frase[i] == ';')
{
lexema[ind++] = frase[i++];
//se encontro PYC
lexema[ind] = '\0';
imprimeToken(2);
edo = 1;
ind = 0;
}
else
{
if (frase[i] == '=')
{
lexema[ind++] = frase[i++];
edo = 4;
}
else
{
printf("%c\n", frase[i++]);
}
}
}
}
break;
case 2:
if (isalpha(frase[i]) || isdigit(frase[i]))
{
lexema[ind++] = frase[i++];
}
else
{
//se encontro ID
lexema[ind] = '\0';
imprimeToken(0);
edo = 1;
ind = 0;
}
break;
case 3:
if (isdigit(frase[i]))
{
lexema[ind++] = frase[i++];
}
else
{
//se encontro NUM
lexema[ind] = '\0';
imprimeToken(1);
edo = 1;
ind = 0;
}
break;
case 4:
if (frase[i] == '=')
{
lexema[ind++] = frase[i++];
//se encontro CMP
lexema[ind] = '\0';
imprimeToken(3);
edo = 1;
ind = 0;
}
else
{
//se encontro ASG
lexema[ind] = '\0';
imprimeToken(4);
edo = 1;
ind = 0;
}
break;
}
}
return 0;
} |
the_stack_data/153267626.c | /**
* @author SANKALP SAXENA
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, *arr, i;
scanf("%d", &num);
arr = (int*) malloc(num * sizeof(int));
for(i = 0; i < num; i++) {
scanf("%d", arr + i);
}
for (i = num - 1; i >= 0; i--) {
printf("%d ", *(arr + i));
}
return 0;
}
|
the_stack_data/107551.c | /*
* Sequential Mandelbrot program
*
* This program computes and displays all or part of the Mandelbrot
* set. By default, it examines all points in the complex plane
* that have both real and imaginary parts between -2 and 2.
* Command-line parameters allow zooming in on a specific part of
* this range.
*
* Usage:
* mandel [-i maxiter -c x0 y0 -s size -w windowsize]
* where
* maxiter denotes the maximum number of iterations at each point -- by default 1000
* x0, y0, and size specify the range to examine (a square
* centered at (x0 + iy0) of size 2*size by 2*size -- by default,
* a square of size 4 by 4 centered at the origin)
* windowsize denotes the size of the image (diplay window) to compute
*
* Input: none, except the optional command-line arguments
* Output: a graphical display as described in Wilkinson & Allen,
* displayed using the X Window system, plus text output to
* standard output showing the above parameters, plus execution
* time in seconds.
*
* Code based on the original code from Web site for Wilkinson and Allen's
* text on parallel programming:
* http://www.cs.uncc.edu/~abw/parallel/par_prog/
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <malloc.h>
#if _DISPLAY_
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#endif
#include <sys/time.h>
double getusec_() {
struct timeval time;
gettimeofday(&time, NULL);
return ((double)time.tv_sec * (double)1e6 + (double)time.tv_usec);
}
#define START_COUNT_TIME stamp = getusec_();
#define STOP_COUNT_TIME(_m) stamp = getusec_() - stamp;\
stamp = stamp/1e6;\
printf ("%s: %0.6fs\n",(_m), stamp);
/* Default values for things. */
#define N 2 /* size of problem space (x, y from -N to N) */
#define NPIXELS 800 /* size of display window in pixels */
int row, col; // variables used to traverse the problem space
/* Structure definition for complex numbers */
typedef struct {
double real, imag;
} complex;
#if _DISPLAY_
/* Functions for GUI */
#include "mandelbrot-gui.h" /* has setup(), interact() */
#endif
void mandelbrot(int height,
int width,
double real_min,
double imag_min,
double scale_real,
double scale_imag,
int maxiter,
#if _DISPLAY_
int setup_return,
Display *display,
Window win,
GC gc,
double scale_color,
double min_color)
#else
int ** output)
#endif
{
/* Calculate points and save/display */
//#pragma omp for schedule(runtime)
#pragma omp parallel private(row)
for (row = 0; row < height; ++row) {
#pragma omp parallel for schedule(runtime) private(col) nowait
for (col = 0; col < width; ++col) {
{
complex z, c;
z.real = z.imag = 0;
/* Scale display coordinates to actual region */
c.real = real_min + ((double) col * scale_real);
c.imag = imag_min + ((double) (height-1-row) * scale_imag);
/* height-1-row so y axis displays
* with larger values at top
*/
/* Calculate z0, z1, .... until divergence or maximum iterations */
int k = 0;
double lengthsq, temp;
do {
temp = z.real*z.real - z.imag*z.imag + c.real;
z.imag = 2*z.real*z.imag + c.imag;
z.real = temp;
lengthsq = z.real*z.real + z.imag*z.imag;
++k;
} while (lengthsq < (N*N) && k < maxiter);
#if _DISPLAY_
/* Scale color and display point */
long color = (long) ((k-1) * scale_color) + min_color;
if (setup_return == EXIT_SUCCESS) {
#pragma omp critical
{
XSetForeground (display, gc, color);
XDrawPoint (display, win, gc, col, row);
}
}
#else
output[row][col]=k;
#endif
}
}
}
}
int main(int argc, char *argv[]) {
int maxiter = 1000;
double real_min;
double real_max;
double imag_min;
double imag_max;
int width = NPIXELS; /* dimensions of display window */
int height = NPIXELS;
double size=N, x0 = 0, y0 = 0;
#if _DISPLAY_
Display *display;
Window win;
GC gc;
int setup_return;
long min_color = 0, max_color = 0;
double scale_color;
#else
int ** output;
FILE *fp = NULL;
#endif
double scale_real, scale_imag;
/* Process command-line arguments */
for (int i=1; i<argc; i++) {
if (strcmp(argv[i], "-i")==0) {
maxiter = atoi(argv[++i]);
}
else if (strcmp(argv[i], "-w")==0) {
width = atoi(argv[++i]);
height = width;
}
else if (strcmp(argv[i], "-s")==0) {
size = atof(argv[++i]);
}
#if !_DISPLAY_
else if (strcmp(argv[i], "-o")==0) {
if((fp=fopen("mandel.out", "wb"))==NULL) {
fprintf(stderr, "Unable to open file\n");
return EXIT_FAILURE;
}
}
#endif
else if (strcmp(argv[i], "-c")==0) {
x0 = atof(argv[++i]);
y0 = atof(argv[++i]);
}
else {
#if _DISPLAY_
fprintf(stderr, "Usage: %s [-i maxiter -w windowsize -c x0 y0 -s size]\n", argv[0]);
#else
fprintf(stderr, "Usage: %s [-o -i maxiter -w windowsize -c x0 y0 -s size]\n", argv[0]);
fprintf(stderr, " -o to write computed image to disk (default no file generated)\n");
#endif
fprintf(stderr, " -i to specify maximum number of iterations at each point (default 1000)\n");
#if _DISPLAY_
fprintf(stderr, " -w to specify the size of the display window (default 800x800 pixels)\n");
#else
fprintf(stderr, " -w to specify the size of the image to compute (default 800x800 elements)\n");
#endif
fprintf(stderr, " -c to specify the center x0+iy0 of the square to compute (default origin)\n");
fprintf(stderr, " -s to specify the size of the square to compute (default 2, i.e. size 4 by 4)\n");
return EXIT_FAILURE;
}
}
real_min = x0 - size;
real_max = x0 + size;
imag_min = y0 - size;
imag_max = y0 + size;
/* Produce text output */
fprintf(stdout, "\n");
fprintf(stdout, "Mandelbrot program\n");
fprintf(stdout, "center = (%g, %g), size = %g\n",
(real_max + real_min)/2, (imag_max + imag_min)/2,
(real_max - real_min)/2);
fprintf(stdout, "maximum iterations = %d\n", maxiter);
fprintf(stdout, "\n");
#if _DISPLAY_
/* Initialize for graphical display */
setup_return =
setup(width, height, &display, &win, &gc, &min_color, &max_color);
if (setup_return != EXIT_SUCCESS) {
fprintf(stderr, "Unable to initialize display, continuing\n");
return EXIT_FAILURE;
}
#else
output = malloc(height*sizeof(int *));
for (int row = 0; row < height; ++row)
output[row] = malloc(width*sizeof(int));
#endif
/* Compute factors to scale computational region to window */
scale_real = (double) (real_max - real_min) / (double) width;
scale_imag = (double) (imag_max - imag_min) / (double) height;
#if _DISPLAY_
/* Compute factor for color scaling */
scale_color = (double) (max_color - min_color) / (double) (maxiter - 1);
#endif
/* Start timing */
double stamp;
START_COUNT_TIME;
#if _DISPLAY_
mandelbrot(height,width,real_min, imag_min, scale_real, scale_imag, maxiter,
setup_return, display, win, gc, scale_color, min_color);
#else
mandelbrot(height,width,real_min, imag_min, scale_real, scale_imag, maxiter,
output);
#endif
/* End timing */
STOP_COUNT_TIME("Total execution time");
/* Be sure all output is written */
#if _DISPLAY_
if (setup_return == EXIT_SUCCESS) {
XFlush (display);
}
#else
if (fp != NULL)
{
for (int row = 0; row < height; ++row)
if(fwrite(output[row], sizeof(int), width, fp) != width) {
fprintf(stderr, "Output file not written correctly\n");
}
}
#endif
#if _DISPLAY_
/* Wait for user response, then exit program */
if (setup_return == EXIT_SUCCESS) {
interact(display, &win, width, height,
real_min, real_max, imag_min, imag_max);
}
return EXIT_SUCCESS;
#endif
}
|
the_stack_data/120217.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
while (1)
{
scanf("%d", &a);
printf("%d", a % 11);
}
}
|
the_stack_data/165764807.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2012-2014 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stdlib.h>
static volatile int infcall_var;
static int
gdb_test_infcall (void)
{
return ++infcall_var;
}
int
main (void)
{
void *p;
gdb_test_infcall ();
p = malloc (1);
if (p == NULL)
return 1;
free (p);
free (p); /* double-free */
return 0;
}
|
the_stack_data/269030.c | //OBS: O centro geométrico é definido como um ponto cujas coordenadas x e y são a média dos valores de
//x e de y, respectivamente
//importação de bibliotecas
#include <stdio.h>
//definindo estrutura para um ponto e usando como pseudônimo o nome 'Ponto'
typedef struct ponto
{
float x;
float y;
} Ponto;
//função que retorna o centro geométrico
Ponto centro_geometrico(int n, Ponto *v);
//função principal
int main(void)
{
int n, i;
Ponto c;
printf("Quantos pontos deseja setar: ");
scanf("%d", &n);
//declarando um vetor de estruturas para cada ponto
Ponto p[n];
//lendo os pontos
for(i = 0; i < n; i++)
{
printf("Digite o ponto (x, y): ");
scanf(" %f %f", &p[i].x, &p[i].y);
}
//calculando centro geométrico
c = centro_geometrico(n, p);
//mostrando resultados
printf("Centro geometrico: (%.2f, %.2f)", c.x, c.y);
return 0;
}
Ponto centro_geometrico(int n, Ponto *v)
{
int i;
//declarando ponto que conterá o centro geométrio e inicializando-o
Ponto centro = {0.0f, 0.0f};
for(i = 0; i < n; i++)
{
centro.x += v[i].x;
centro.y += v[i].y;
}
//calculando a media
centro.x /= n;
centro.y /= n;
//retornando centro geométrico
return centro;
}
|
the_stack_data/108547.c | int depth_0() {}
|
the_stack_data/86075530.c | // PARAM: --disable exp.unsoundbasic --set ana.activated[+] "'var_eq'" --set ana.activated[+] "'symb_locks'"
#include<pthread.h>
struct s {
int datum;
pthread_mutex_t mutex;
};
extern struct s *get_s();
void *t_fun(void *arg) {
struct s *s;
s = get_s();
pthread_mutex_lock(&s->mutex);
s->datum = 5; // NORACE
pthread_mutex_lock(&s->mutex);
return NULL;
}
int main () {
int *d;
struct s *s;
pthread_t id;
pthread_mutex_t *m;
s = get_s();
m = &s->mutex;
d = &s->datum;
pthread_create(&id,NULL,t_fun,NULL);
pthread_mutex_lock(m);
*d = 8; // NORACE
pthread_mutex_unlock(m);
return 0;
}
|
the_stack_data/147843.c | #include <stdio.h>
#include <string.h>
int main()
{
const char haystack[20] = "RUNxxx";
const char needle[10] = "NOOB";
char *ret;
ret = strstr(haystack, needle);
printf("子str: %s \n",ret);
return 0;
} |
the_stack_data/178266595.c | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_2__ TYPE_1__ ;
/* Type definitions */
typedef int /*<<< orphan*/ zdev_t ;
typedef int u8_t ;
typedef scalar_t__ u32_t ;
typedef scalar_t__ u16_t ;
struct zsHpPriv {int isSiteSurvey; int latestBw40; int latestExtOffset; scalar_t__ dot11Mode; scalar_t__ hwFrequency; int OpFlags; int hwBw40; int halCapability; int hwExtOffset; scalar_t__ strongRSSI; scalar_t__ rxStrongRSSI; scalar_t__ latestFrequency; scalar_t__ coldResetNeedFreq; } ;
struct TYPE_2__ {struct zsHpPriv* hpPrivate; } ;
/* Variables and functions */
scalar_t__ ZM_CH_G_1 ;
scalar_t__ ZM_CH_G_14 ;
scalar_t__ ZM_CH_G_2 ;
int ZM_CMD_BITAND ;
int ZM_CMD_FREQUENCY ;
int ZM_CMD_FREQ_STRAT ;
int ZM_CMD_RF_INIT ;
int /*<<< orphan*/ ZM_CMD_SET_FREQUENCY ;
scalar_t__ ZM_HAL_80211_MODE_IBSS_GENERAL ;
scalar_t__ ZM_HAL_80211_MODE_IBSS_WPA2PSK ;
int ZM_HP_CAP_11N_ONE_TX_STREAM ;
int /*<<< orphan*/ ZM_LV_1 ;
int ZM_MAC_REG_AC0_CW ;
int /*<<< orphan*/ ZM_OID_INTERNAL_WRITE ;
int /*<<< orphan*/ reg_write (int,int) ;
TYPE_1__* wd ;
int /*<<< orphan*/ zfDelayWriteInternalReg (int /*<<< orphan*/ *,int,int) ;
int /*<<< orphan*/ zfFlushDelayWrite (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ zfGetHwTurnOffdynParam (int /*<<< orphan*/ *,scalar_t__,int,int,int*,int*,int*,int*) ;
int /*<<< orphan*/ zfInitPhy (int /*<<< orphan*/ *,scalar_t__,int) ;
scalar_t__ zfIssueCmd (int /*<<< orphan*/ *,scalar_t__*,int,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ zfSelAdcClk (int /*<<< orphan*/ *,int,scalar_t__) ;
int /*<<< orphan*/ zfSetBank4AndPowerTable (int /*<<< orphan*/ *,scalar_t__,int,int) ;
int /*<<< orphan*/ zfSetPowerCalTable (int /*<<< orphan*/ *,scalar_t__,int,int) ;
int /*<<< orphan*/ zfSetRfRegs (int /*<<< orphan*/ *,scalar_t__) ;
int /*<<< orphan*/ zm_debug_msg0 (char*) ;
int /*<<< orphan*/ zm_msg0_scan (int /*<<< orphan*/ ,char*) ;
int /*<<< orphan*/ zm_msg1_scan (int /*<<< orphan*/ ,char*,int) ;
int /*<<< orphan*/ zmw_get_wlan_dev (int /*<<< orphan*/ *) ;
void zfHpSetFrequencyEx(zdev_t* dev, u32_t frequency, u8_t bw40,
u8_t extOffset, u8_t initRF)
{
u32_t cmd[9];
u32_t cmdB[3];
u16_t ret;
u8_t old_band;
u8_t new_band;
u32_t checkLoopCount;
u32_t tmpValue;
int delta_slope_coeff_exp;
int delta_slope_coeff_man;
int delta_slope_coeff_exp_shgi;
int delta_slope_coeff_man_shgi;
struct zsHpPriv* hpPriv;
zmw_get_wlan_dev(dev);
hpPriv = wd->hpPrivate;
zm_msg1_scan(ZM_LV_1, "Frequency = ", frequency);
zm_msg1_scan(ZM_LV_1, "bw40 = ", bw40);
zm_msg1_scan(ZM_LV_1, "extOffset = ", extOffset);
if ( hpPriv->coldResetNeedFreq )
{
hpPriv->coldResetNeedFreq = 0;
initRF = 2;
zm_debug_msg0("zfHpSetFrequencyEx: Do ColdReset ");
}
if ( hpPriv->isSiteSurvey == 2 )
{
/* wait time for AGC and noise calibration : not in sitesurvey and connected */
checkLoopCount = 2000; /* 2000*100 = 200ms */
}
else
{
/* wait time for AGC and noise calibration : in sitesurvey */
checkLoopCount = 1000; /* 1000*100 = 100ms */
}
hpPriv->latestFrequency = frequency;
hpPriv->latestBw40 = bw40;
hpPriv->latestExtOffset = extOffset;
if ((hpPriv->dot11Mode == ZM_HAL_80211_MODE_IBSS_GENERAL) ||
(hpPriv->dot11Mode == ZM_HAL_80211_MODE_IBSS_WPA2PSK))
{
if ( frequency <= ZM_CH_G_14 )
{
/* workaround for 11g Ad Hoc beacon distribution */
zfDelayWriteInternalReg(dev, ZM_MAC_REG_AC0_CW, 0x7f0007);
//zfDelayWriteInternalReg(dev, ZM_MAC_REG_AC1_AC0_AIFS, 0x1c04901c);
}
}
/* AHB, DAC, ADC clock selection by static20/ht2040 */
zfSelAdcClk(dev, bw40, frequency);
/* clear bb_heavy_clip_enable */
reg_write(0x99e0, 0x200);
zfFlushDelayWrite(dev);
/* Set CTS/RTS rate */
if ( frequency > ZM_CH_G_14 )
{
//zfHpSetRTSCTSRate(dev, 0x10b010b); /* OFDM 6M */
new_band = 1;
}
else
{
//zfHpSetRTSCTSRate(dev, 0x30003); /* CCK 11M */
new_band = 0;
}
if (((struct zsHpPriv*)wd->hpPrivate)->hwFrequency > ZM_CH_G_14)
old_band = 1;
else
old_band = 0;
//Workaround for 2.4GHz only device
if ((hpPriv->OpFlags & 0x1) == 0)
{
if ((((struct zsHpPriv*)wd->hpPrivate)->hwFrequency == ZM_CH_G_1) && (frequency == ZM_CH_G_2))
{
/* Force to do band switching */
old_band = 1;
}
}
/* Notify channel switch to firmware */
/* TX/RX must be stopped by now */
cmd[0] = 0 | (ZM_CMD_FREQ_STRAT << 8);
ret = zfIssueCmd(dev, cmd, 8, ZM_OID_INTERNAL_WRITE, 0);
if ((initRF != 0) || (new_band != old_band)
|| (((struct zsHpPriv*)wd->hpPrivate)->hwBw40 != bw40))
{
/* band switch */
zm_msg0_scan(ZM_LV_1, "=====band switch=====");
if (initRF == 2 )
{
//Cold reset BB/ADDA
zfDelayWriteInternalReg(dev, 0x1d4004, 0x800);
zfFlushDelayWrite(dev);
zm_msg0_scan(ZM_LV_1, "Do cold reset BB/ADDA");
}
else
{
//Warm reset BB/ADDA
zfDelayWriteInternalReg(dev, 0x1d4004, 0x400);
zfFlushDelayWrite(dev);
}
/* reset workaround state to default */
hpPriv->rxStrongRSSI = 0;
hpPriv->strongRSSI = 0;
zfDelayWriteInternalReg(dev, 0x1d4004, 0x0);
zfFlushDelayWrite(dev);
zfInitPhy(dev, frequency, bw40);
// zfiCheckRifs(dev);
/* Bank 0 1 2 3 5 6 7 */
zfSetRfRegs(dev, frequency);
/* Bank 4 */
zfSetBank4AndPowerTable(dev, frequency, bw40, extOffset);
cmd[0] = 32 | (ZM_CMD_RF_INIT << 8);
}
else //((new_band == old_band) && !initRF)
{
/* same band */
/* Force disable CR671 bit20 / 7823 */
/* The bug has to do with the polarity of the pdadc offset calibration. There */
/* is an initial calibration that is OK, and there is a continuous */
/* calibration that updates the pddac with the wrong polarity. Fortunately */
/* the second loop can be disabled with a bit called en_pd_dc_offset_thr. */
#if 0
cmdB[0] = 8 | (ZM_CMD_BITAND << 8);;
cmdB[1] = (0xa27c + 0x1bc000);
cmdB[2] = 0xffefffff;
ret = zfIssueCmd(dev, cmdB, 12, ZM_OID_INTERNAL_WRITE, 0);
#endif
/* Bank 4 */
zfSetBank4AndPowerTable(dev, frequency, bw40, extOffset);
cmd[0] = 32 | (ZM_CMD_FREQUENCY << 8);
}
/* Compatibility for new layout UB83 */
/* Setting code at CR1 here move from the func:zfHwHTEnable() in firmware */
if (((struct zsHpPriv*)wd->hpPrivate)->halCapability & ZM_HP_CAP_11N_ONE_TX_STREAM)
{
/* UB83 : one stream */
tmpValue = 0;
}
else
{
/* UB81, UB82 : two stream */
tmpValue = 0x100;
}
if (1) //if (((struct zsHpPriv*)wd->hpPrivate)->hw_HT_ENABLE == 1)
{
if (bw40 == 1)
{
if (extOffset == 1) {
reg_write(0x9804, tmpValue | 0x2d4); //3d4 for real
}
else {
reg_write(0x9804, tmpValue | 0x2c4); //3c4 for real
}
//# Dyn HT2040.Refer to Reg 1.
//#[3]:single length (4us) 1st HT long training symbol; use Walsh spatial spreading for 2 chains 2 streams TX
//#[c]:allow short GI for HT40 packets; enable HT detection.
//#[4]:enable 20/40 MHz channel detection.
}
else
{
reg_write(0x9804, tmpValue | 0x240);
//# Static HT20
//#[3]:single length (4us) 1st HT long training symbol; use Walsh spatial spreading for 2 chains 2 streams TX
//#[4]:Otus don't allow short GI for HT20 packets yet; enable HT detection.
//#[0]:disable 20/40 MHz channel detection.
}
}
else
{
reg_write(0x9804, 0x0);
//# Legacy;# Direct Mapping for each chain.
//#Be modified by Oligo to add dynanic for legacy.
if (bw40 == 1)
{
reg_write(0x9804, 0x4); //# Dyn Legacy .Refer to reg 1.
}
else
{
reg_write(0x9804, 0x0); //# Static Legacy
}
}
zfFlushDelayWrite(dev);
/* end of ub83 compatibility */
/* Set Power, TPC, Gain table... */
zfSetPowerCalTable(dev, frequency, bw40, extOffset);
/* store frequency */
((struct zsHpPriv*)wd->hpPrivate)->hwFrequency = (u16_t)frequency;
((struct zsHpPriv*)wd->hpPrivate)->hwBw40 = bw40;
((struct zsHpPriv*)wd->hpPrivate)->hwExtOffset = extOffset;
zfGetHwTurnOffdynParam(dev,
frequency, bw40, extOffset,
&delta_slope_coeff_exp,
&delta_slope_coeff_man,
&delta_slope_coeff_exp_shgi,
&delta_slope_coeff_man_shgi);
/* related functions */
frequency = frequency*1000;
/* len[36] : type[0x30] : seq[?] */
// cmd[0] = 28 | (ZM_CMD_FREQUENCY << 8);
cmd[1] = frequency;
cmd[2] = bw40;//((struct zsHpPriv*)wd->hpPrivate)->hw_DYNAMIC_HT2040_EN;
cmd[3] = (extOffset<<2)|0x1;//((wd->ExtOffset << 2) | ((struct zsHpPriv*)wd->hpPrivate)->hw_HT_ENABLE);
cmd[4] = delta_slope_coeff_exp;
cmd[5] = delta_slope_coeff_man;
cmd[6] = delta_slope_coeff_exp_shgi;
cmd[7] = delta_slope_coeff_man_shgi;
cmd[8] = checkLoopCount;
ret = zfIssueCmd(dev, cmd, 36, ZM_CMD_SET_FREQUENCY, 0);
// delay temporarily, wait for new PHY and RF
//zfwSleep(dev, 1000);
} |
the_stack_data/26438.c | #include<stdio.h>
#define MAX_N 500001
#define INF (1<<30)
int cnt=0;
int L[MAX_N],R[MAX_N];
void merge(int *A,int left,int mid,int right){
int i,j,k;
int n1=mid-left;
int n2=right-mid;
for(i=0;i<n1;i++)L[i]=A[left+i];
for(i=0;i<n2;i++)R[i]=A[mid+i];
L[n1]=INF;
R[n2]=INF;
i=0;
j=0;
for(k=left;k<right;k++,cnt++){
if(L[i]<=R[j]){
A[k]=L[i];
i=i+1;
}
else {
A[k]=R[j];
j=j+1;
}
}
}
void mergeSort(int *A,int left,int right){
if(left+1<right){
int mid=(left+right)/2;
mergeSort(A,left,mid);
mergeSort(A,mid,right);
merge(A,left,mid,right);
}
}
int main(void){
int n,A[MAX_N],i;
scanf("%d",&n);
for(i=0;i<n;i++)scanf("%d",&A[i]);
mergeSort(A,0,n);
for(i=0;i<n;i++){
printf("%d%c",A[i],(i<n-1?' ':'\n'));
}
printf("%d\n",cnt);
return 0;
}
|
the_stack_data/621682.c | /**
******************************************************************************
* @file stm32f7xx_ll_exti.c
* @author MCD Application Team
* @version V1.2.0
* @date 30-December-2016
* @brief EXTI LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© 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 "stm32f7xx_ll_exti.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32F7xx_LL_Driver
* @{
*/
#if defined (EXTI)
/** @defgroup EXTI_LL EXTI
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup EXTI_LL_Private_Macros
* @{
*/
#define IS_LL_EXTI_LINE_0_31(__VALUE__) (((__VALUE__) & ~LL_EXTI_LINE_ALL_0_31) == 0x00000000U)
#define IS_LL_EXTI_MODE(__VALUE__) (((__VALUE__) == LL_EXTI_MODE_IT) \
|| ((__VALUE__) == LL_EXTI_MODE_EVENT) \
|| ((__VALUE__) == LL_EXTI_MODE_IT_EVENT))
#define IS_LL_EXTI_TRIGGER(__VALUE__) (((__VALUE__) == LL_EXTI_TRIGGER_NONE) \
|| ((__VALUE__) == LL_EXTI_TRIGGER_RISING) \
|| ((__VALUE__) == LL_EXTI_TRIGGER_FALLING) \
|| ((__VALUE__) == LL_EXTI_TRIGGER_RISING_FALLING))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup EXTI_LL_Exported_Functions
* @{
*/
/** @addtogroup EXTI_LL_EF_Init
* @{
*/
/**
* @brief De-initialize the EXTI registers to their default reset values.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: EXTI registers are de-initialized
* - ERROR: not applicable
*/
uint32_t LL_EXTI_DeInit(void)
{
/* Interrupt mask register set to default reset values */
LL_EXTI_WriteReg(IMR, 0x00000000U);
/* Event mask register set to default reset values */
LL_EXTI_WriteReg(EMR, 0x00000000U);
/* Rising Trigger selection register set to default reset values */
LL_EXTI_WriteReg(RTSR, 0x00000000U);
/* Falling Trigger selection register set to default reset values */
LL_EXTI_WriteReg(FTSR, 0x00000000U);
/* Software interrupt event register set to default reset values */
LL_EXTI_WriteReg(SWIER, 0x00000000U);
/* Pending register set to default reset values */
LL_EXTI_WriteReg(PR, 0x01FFFFFFU);
return SUCCESS;
}
/**
* @brief Initialize the EXTI registers according to the specified parameters in EXTI_InitStruct.
* @param EXTI_InitStruct pointer to a @ref LL_EXTI_InitTypeDef structure.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: EXTI registers are initialized
* - ERROR: not applicable
*/
uint32_t LL_EXTI_Init(LL_EXTI_InitTypeDef *EXTI_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_LL_EXTI_LINE_0_31(EXTI_InitStruct->Line_0_31));
assert_param(IS_FUNCTIONAL_STATE(EXTI_InitStruct->LineCommand));
assert_param(IS_LL_EXTI_MODE(EXTI_InitStruct->Mode));
/* ENABLE LineCommand */
if (EXTI_InitStruct->LineCommand != DISABLE)
{
assert_param(IS_LL_EXTI_TRIGGER(EXTI_InitStruct->Trigger));
/* Configure EXTI Lines in range from 0 to 31 */
if (EXTI_InitStruct->Line_0_31 != LL_EXTI_LINE_NONE)
{
switch (EXTI_InitStruct->Mode)
{
case LL_EXTI_MODE_IT:
/* First Disable Event on provided Lines */
LL_EXTI_DisableEvent_0_31(EXTI_InitStruct->Line_0_31);
/* Then Enable IT on provided Lines */
LL_EXTI_EnableIT_0_31(EXTI_InitStruct->Line_0_31);
break;
case LL_EXTI_MODE_EVENT:
/* First Disable IT on provided Lines */
LL_EXTI_DisableIT_0_31(EXTI_InitStruct->Line_0_31);
/* Then Enable Event on provided Lines */
LL_EXTI_EnableEvent_0_31(EXTI_InitStruct->Line_0_31);
break;
case LL_EXTI_MODE_IT_EVENT:
/* Directly Enable IT & Event on provided Lines */
LL_EXTI_EnableIT_0_31(EXTI_InitStruct->Line_0_31);
LL_EXTI_EnableEvent_0_31(EXTI_InitStruct->Line_0_31);
break;
default:
status = ERROR;
break;
}
if (EXTI_InitStruct->Trigger != LL_EXTI_TRIGGER_NONE)
{
switch (EXTI_InitStruct->Trigger)
{
case LL_EXTI_TRIGGER_RISING:
/* First Disable Falling Trigger on provided Lines */
LL_EXTI_DisableFallingTrig_0_31(EXTI_InitStruct->Line_0_31);
/* Then Enable Rising Trigger on provided Lines */
LL_EXTI_EnableRisingTrig_0_31(EXTI_InitStruct->Line_0_31);
break;
case LL_EXTI_TRIGGER_FALLING:
/* First Disable Rising Trigger on provided Lines */
LL_EXTI_DisableRisingTrig_0_31(EXTI_InitStruct->Line_0_31);
/* Then Enable Falling Trigger on provided Lines */
LL_EXTI_EnableFallingTrig_0_31(EXTI_InitStruct->Line_0_31);
break;
case LL_EXTI_TRIGGER_RISING_FALLING:
LL_EXTI_EnableRisingTrig_0_31(EXTI_InitStruct->Line_0_31);
LL_EXTI_EnableFallingTrig_0_31(EXTI_InitStruct->Line_0_31);
break;
default:
status = ERROR;
break;
}
}
}
}
/* DISABLE LineCommand */
else
{
/* De-configure EXTI Lines in range from 0 to 31 */
LL_EXTI_DisableIT_0_31(EXTI_InitStruct->Line_0_31);
LL_EXTI_DisableEvent_0_31(EXTI_InitStruct->Line_0_31);
}
return status;
}
/**
* @brief Set each @ref LL_EXTI_InitTypeDef field to default value.
* @param EXTI_InitStruct Pointer to a @ref LL_EXTI_InitTypeDef structure.
* @retval None
*/
void LL_EXTI_StructInit(LL_EXTI_InitTypeDef *EXTI_InitStruct)
{
EXTI_InitStruct->Line_0_31 = LL_EXTI_LINE_NONE;
EXTI_InitStruct->LineCommand = DISABLE;
EXTI_InitStruct->Mode = LL_EXTI_MODE_IT;
EXTI_InitStruct->Trigger = LL_EXTI_TRIGGER_FALLING;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined (EXTI) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/153268630.c | #include <assert.h>
#include <limits.h>
#include <stdio.h>
#include "string.h"
int test_ltoa_10() {
// ltoa_10 正常系
long l0 = 0;
long l9 = 9;
long l10 = 10;
long l100 = 100;
long l1000 = 1000;
long l10000 = 10000;
long l_1 = -1;
long l_10 = -10;
unsigned char err;
char str[5];
char str_max[21];
err = ltoa_10(l0, str, (sizeof(str) / sizeof(str[0])));
assert(str[0] == '0');
assert(str[1] == '\0');
assert(err == 0);
err = ltoa_10(l9, str, (sizeof(str) / sizeof(str[0])));
assert(str[0] == '9');
assert(str[1] == '\0');
assert(err == 0);
err = ltoa_10(l10, str, (sizeof(str) / sizeof(str[0])));
assert(str[0] == '1');
assert(str[1] == '0');
assert(str[2] == '\0');
assert(err == 0);
err = ltoa_10(l100, str, (sizeof(str) / sizeof(str[0])));
assert(str[0] == '1');
assert(str[1] == '0');
assert(str[2] == '0');
assert(str[3] == '\0');
assert(err == 0);
err = ltoa_10(l1000, str, (sizeof(str) / sizeof(str[0])));
assert(str[0] == '1');
assert(str[1] == '0');
assert(str[2] == '0');
assert(str[3] == '0');
assert(str[4] == '\0');
assert(err == 0);
err = ltoa_10(l_1, str, (sizeof(str) / sizeof(str[0])));
assert(str[0] == '-');
assert(str[1] == '1');
assert(str[2] == '\0');
assert(err == 0);
err = ltoa_10(l_10, str, (sizeof(str) / sizeof(str[0])));
assert(str[0] == '-');
assert(str[1] == '1');
assert(str[2] == '0');
assert(str[3] == '\0');
assert(err == 0);
err = ltoa_10(LONG_MAX, str_max, (sizeof(str_max) / sizeof(str_max[0])));
assert(str_max[0] == '9');
assert(str_max[1] == '2');
assert(str_max[2] == '2');
assert(str_max[3] == '3');
assert(str_max[4] == '3');
assert(str_max[5] == '7');
assert(str_max[6] == '2');
assert(str_max[7] == '0');
assert(str_max[8] == '3');
assert(str_max[9] == '6');
assert(str_max[10] == '8');
assert(str_max[11] == '5');
assert(str_max[12] == '4');
assert(str_max[13] == '7');
assert(str_max[14] == '7');
assert(str_max[15] == '5');
assert(str_max[16] == '8');
assert(str_max[17] == '0');
assert(str_max[18] == '7');
assert(str_max[19] == '\0');
err = ltoa_10(LONG_MIN, str_max, (sizeof(str_max) / sizeof(str_max[0])));
assert(str_max[0] == '-');
assert(str_max[1] == '9');
assert(str_max[2] == '2');
assert(str_max[3] == '2');
assert(str_max[4] == '3');
assert(str_max[5] == '3');
assert(str_max[6] == '7');
assert(str_max[7] == '2');
assert(str_max[8] == '0');
assert(str_max[9] == '3');
assert(str_max[10] == '6');
assert(str_max[11] == '8');
assert(str_max[12] == '5');
assert(str_max[13] == '4');
assert(str_max[14] == '7');
assert(str_max[15] == '7');
assert(str_max[16] == '5');
assert(str_max[17] == '8');
assert(str_max[18] == '0');
assert(str_max[19] == '8');
assert(str_max[20] == '\0');
// ltoa_10 異常系
err = ltoa_10(l10000, str, (sizeof(str) / sizeof(str[0])));
assert(err == 1);
}
int test_ltoa_radix_16() {
// ltoa 正常系
long l0 = 0;
long l15 = 15;
long l16 = 16;
long l65535 = 65535;
long l_1 = -1;
long l_16 = -16;
unsigned char err;
char str[5];
err = ltoa(l0, str, (sizeof(str) / sizeof(str[0])), 16);
assert(str[0] == '0');
assert(str[1] == '\0');
assert(err == 0);
err = ltoa(l15, str, (sizeof(str) / sizeof(str[0])), 16);
assert(str[0] == 'F');
assert(str[1] == '\0');
assert(err == 0);
err = ltoa(l16, str, (sizeof(str) / sizeof(str[0])), 16);
assert(str[0] == '1');
assert(str[1] == '0');
assert(str[2] == '\0');
assert(err == 0);
err = ltoa(l65535, str, (sizeof(str) / sizeof(str[0])), 16);
assert(str[0] == 'F');
assert(str[1] == 'F');
assert(str[2] == 'F');
assert(str[3] == 'F');
assert(str[4] == '\0');
assert(err == 0);
err = ltoa(l_1, str, (sizeof(str) / sizeof(str[0])), 16);
assert(str[0] == '-');
assert(str[1] == '1');
assert(str[2] == '\0');
assert(err == 0);
err = ltoa(l_16, str, (sizeof(str) / sizeof(str[0])), 16);
assert(str[0] == '-');
assert(str[1] == '1');
assert(str[2] == '0');
assert(str[3] == '\0');
assert(err == 0);
}
int test_ltoa_radix_2() {
// ltoa 正常系
long l0 = 0;
long l15 = 15;
long l16 = 16;
long l65535 = 65535;
long l_1 = -1;
long l_16 = -16;
unsigned char err;
char str[17];
err = ltoa(l0, str, (sizeof(str) / sizeof(str[0])), 2);
assert(str[0] == '0');
assert(str[1] == '\0');
assert(err == 0);
err = ltoa(l15, str, (sizeof(str) / sizeof(str[0])), 2);
assert(str[0] == '1');
assert(str[1] == '1');
assert(str[2] == '1');
assert(str[3] == '1');
assert(str[4] == '\0');
assert(err == 0);
err = ltoa(l16, str, (sizeof(str) / sizeof(str[0])), 2);
assert(str[0] == '1');
assert(str[1] == '0');
assert(str[2] == '0');
assert(str[3] == '0');
assert(str[4] == '0');
assert(str[5] == '\0');
assert(err == 0);
err = ltoa(l65535, str, (sizeof(str) / sizeof(str[0])), 2);
assert(str[0] == '1');
assert(str[1] == '1');
assert(str[2] == '1');
assert(str[3] == '1');
assert(str[4] == '1');
assert(str[5] == '1');
assert(str[6] == '1');
assert(str[7] == '1');
assert(str[8] == '1');
assert(str[9] == '1');
assert(str[10] == '1');
assert(str[11] == '1');
assert(str[12] == '1');
assert(str[13] == '1');
assert(str[14] == '1');
assert(str[15] == '1');
assert(str[16] == '\0');
assert(err == 0);
err = ltoa(l_1, str, (sizeof(str) / sizeof(str[0])), 2);
assert(str[0] == '-');
assert(str[1] == '1');
assert(str[2] == '\0');
assert(err == 0);
err = ltoa(l_16, str, (sizeof(str) / sizeof(str[0])), 2);
assert(str[0] == '-');
assert(str[1] == '1');
assert(str[2] == '0');
assert(str[3] == '0');
assert(str[4] == '0');
assert(str[5] == '0');
assert(str[6] == '\0');
assert(err == 0);
}
int test_ltoa() {
// ltoa 異常系
long l0 = 0;
long l10000 = 10000;
unsigned char err;
char str[5];
err = ltoa(l0, str, (sizeof(str) / sizeof(str[0])), 0);
assert(err == 3);
err = ltoa(l0, str, (sizeof(str) / sizeof(str[0])), 17);
assert(err == 3);
err = ltoa(l10000, str, (sizeof(str) / sizeof(str[0])), 10);
assert(err == 1);
}
int main() {
test_ltoa_10();
test_ltoa();
test_ltoa_radix_2();
test_ltoa_radix_16();
}
|
the_stack_data/248581347.c | #include <string.h> // memset()
void *harklexplicit(void *s, int c, size_t n)
{
void *(*func_ptr)(void*, int, size_t) = memset;
return func_ptr(s, c, n);
}
|
the_stack_data/20450846.c | #include <stdio.h>
#include <time.h>
/**
* 打印当前时间
*/
int main(int argc, const char *args[]) {
time_t mills;
struct tm *local;
time(&mills);
printf("current mills: %ld \n", mills);
local = localtime(&mills);
printf("year: %d \n", local -> tm_year + 1900);
printf("month: %d \n", local -> tm_mon + 1);
printf("day: %d \n", local -> tm_mday);
return 0;
} |
the_stack_data/76870.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2014-2020 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
int main (int argc, char **argv)
{
return 0;
}
|
the_stack_data/7949201.c | #include <stdio.h>
int main(void)
{
char operator;
float number, sum;
sum = 0.0;
printf("what is your number and operator?\n");
do {
scanf("%f %c", &number, &operator);
switch(operator)
{
case 'S':
sum = number;
printf("=%.6f\n", sum);
break;
case '+':
sum += number;
printf("=%.6f\n", sum);
break;
case '-':
sum -= number;
printf("=%.6f\n", sum);
break;
case '*':
sum *= number;
printf("=%.6f\n", sum);
break;
case '/':
if ((int) number == 0)
printf("Division by zero!\n");
else
sum /= number;
printf("=%.6f\n", sum);
break;
case 'E':
printf("=%.6f\n", sum);
break;
default:
printf("Unknown operator.\n");
break;
}
} while (operator != 'E');
printf("over\n");
return 0;
} |
the_stack_data/458152.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2004-2015 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <pthread.h>
static void *p;
static void
handler (int sig, siginfo_t *info, void *context)
{
/* Copy to local vars, as the test wants to read them, and si_addr,
etc. may be preprocessor defines. */
int ssi_errno = info->si_errno;
int ssi_signo = info->si_signo;
int ssi_code = info->si_code;
void *ssi_addr = info->si_addr;
_exit (0); /* set breakpoint here */
}
static void *
segv_thread (void *ptr)
{
*(int *)ptr = 0;
}
int
main (void)
{
pthread_t thr;
/* Set up unwritable memory. */
{
size_t len;
len = sysconf(_SC_PAGESIZE);
p = mmap (0, len, PROT_NONE, MAP_ANON|MAP_PRIVATE, -1, 0);
if (p == MAP_FAILED)
{
perror ("mmap");
return 1;
}
}
/* Set up the signal handler. */
{
struct sigaction action;
memset (&action, 0, sizeof (action));
action.sa_sigaction = handler;
action.sa_flags |= SA_SIGINFO;
if (sigaction (SIGSEGV, &action, NULL))
{
perror ("sigaction");
return 1;
}
}
/* Create a thread that will trigger SIGSEGV. */
pthread_create (&thr, NULL, segv_thread, p);
pthread_join (thr, NULL);
return 0;
}
|
the_stack_data/212642059.c | #include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
/* Funzione getopt() - Parsing delle opzioni - Header <getopt.h>
----------------------------------------------------------------
Un programma ha la possibilita' di ottenere argomenti ed opzioni allorquando
viene eseguito, il passaggio degli argomenti viene effettuato mediante i
parametri di default argc e argv[], della funzione main().
extern char *optarg;
--------------------
Il puntatore optarg referenzia l'indirizzo all'interno del quale e' collocato
il parametro relativo all'opzione in fase di elaborazione.
extern int optind;
------------------
La funzione getopt() incrementa il valore di optind di volta in volta che
sono elaborate tutte le opzioni presenti nelle successive chiamate; di
default optind assume il valore di 1, per cui il primo parametro ad essere
elaborato sara' argv[1], dopodiche', elaborate le restanti opzioni, optind
conterra' l'indice del successivo parametro.
extern int opterr;
------------------
La variabile esterna opterr assume anch'essa il valore di default 1 (true)
ed e' utilizzata come dato di input per la funzione getopt(). Se opterr e'
uguale a true sara' elaborato il carattere di opzione non valido e la
funzione getopt() fara' stampare su stderr un messaggio con l'opzione
corretta. Se invcece la variabile opterr risulta falsa, ossia impostata a 0,
non ci saranno messaggi di errore, pur avendo elaborato un'opzione non
valida. In tal modo si puo' controllare in maniera molto efficiente se
inserire un messaggio di errore e su quale stream inviarlo, invece impostando
opterr a 0 non saranno inviati messaggi d'errore.
extern int optopt;
-------------------
La variabile esterna optopt contiene il carattere dell'opzione non
riconosciuta.
extern int getopt(int argc, char *const *argv, const char *shortopts);
----------------------------------------------------------------------
Il primo parametro argc contiene il numero totale dei parametri contenuti in
argv[]; il secondo parametro argv e' un array di puntatori a stringa, contiene
le opzioni ed i parametri inseriti; il terzo ed ultimo parametro shortopts e'
un puntatore a stringa, che in un certo senso gestisce l'intera operazione
della getopt(), poiche' determina quali sono le opzioni valide e quali
accettano parametri propri. Esemplificando si potrebbe affermare che shortopts
contiene l'interfaccia del programma.
Come lavora la funzione getopt()
-----------------------------------------------------------------------------
Le opzioni solitamente sono precedute dal carattere '-', esso stesso e'
considerato un'opzione se inserito dopo '-', le opzioni sono formate da un
singolo carattere precedute da '-' e possono avere o meno un parametro.
La funzione getopt() prende le due variabili argc ed argv come argomenti
della funzione main(), inoltre lavora con una stringa per verificare quali
sono le opzioni valide; la getopt() effettua una sorta di scansione nella
lista degli argomenti (argv) cercando ogni stringa che cominci con '-',
shortopts indica alla getopt() quali sono le opzioni accettabili, da notare
che se un opzione deve ricevere un parametro, al carattere deve seguire il
simbolo ":".
Se il carattere non e' presente nella lista delle opzioni shortopts, non e'
valida e la getopt() restituisce '?'; se invece l'opzione e' presente nella
stringa shortopts, la getopt() verifica se questa opzione accetta o meno un
parametro, controllando la presenza del simbolo ':' dopo il carattere stesso,
in shortopts.
L'uso della getopt() appare ora piuttosto evidente, tutto sta nel richiamarla
in un ciclo fino a quando non restiuisce il valore -1, che identifica il caso
in cui non ci sono piu' opzioni.
Se non si inserisse un parametro a un'opzione che lo richieda, la funzione
getopt() restituirebbe ':'.
*/
int main(int argc, char* argv[])
{
/* Si disabilita la stampa di errori sullo stdout per le opzioni che non
sono state rinosciute */
opterr = 0;
int opt;
// La stringa contenente le opzioni, una con parametro
static char shortopts[] = "hU:v";
while ((opt = getopt(argc, argv, shortopts)) != -1)
switch (opt) {
case 'h':
puts("Processata l'opzione -h");
printf("optind = %d - argc = %d\n", optind, argc);
break;
case 'v':
puts("Processata l'opzione -v");
printf("optind = %d - argc = %d\n", optind, argc);
break;
case 'U':
printf("Opzione -U \"%s\" parametro \n", optarg);
break;
case '?':
printf("Parametro non valido \"?\"\n");
break;
default:
puts("Opzione sconosciuta");
}
for (; optind < argc; ++optind) {
printf("argv[%d] = %s\n", optind, argv[optind]);
printf("optind = %d - argc = %d\n", optind, argc);
}
return (EXIT_SUCCESS);
}
|
the_stack_data/1061427.c | /* { dg-do compile } */
/* { dg-options "-O1 -fdump-tree-dom3" } */
/* LLVM LOCAL test not applicable */
/* { dg-require-fdump "" } */
typedef unsigned int cppchar_t;
cppchar_t
cpp_parse_escape (pstr, limit, wide)
const unsigned char **pstr;
const unsigned char *limit;
int wide;
{
cppchar_t i = 0;
int overflow = 0;
cppchar_t mask = ~0;
while (*pstr < limit)
{
overflow |= i ^ (i << 4 >> 4);
i = oof ();
}
if (overflow | (i != (i & mask)))
foo();
}
/* There should be precisely three IF statements. If there is
more than two, then the dominator optimizations failed. */
/* { dg-final { scan-tree-dump-times "if " 3 "dom3"} } */
/* { dg-final { cleanup-tree-dump "dom3" } } */
|
the_stack_data/40762634.c | #include <stdio.h>
#include <assert.h>
int mainQ(int x1, int x2){
assert (x1 >= 0);
assert (x2 >= 1);
int y1,y2,y3;
y1 = 0;
y2 = 0;
y3 = x1;
while(1) {
//assert(y1* x2 + y2 + y3 == x1);
//%%%traces: int y1, int y2, int y3, int x1, int x2
if(!(y3 != 0)) break;
if (y2 + 1 == x2) {
y1 = y1 + 1;
y2 = 0;
y3 = y3 - 1;
}
else {
y2 = y2 + 1;
y3 = y3 - 1;
}
}
//assert(y1 == x1 / x2);
return y1;
}
int main(int argc, char **argv){
mainQ(atoi(argv[1]), atoi(argv[2]));
return 0;
}
|
the_stack_data/711375.c | /*
* @@name: acquire_release.3.c
* @@type: C
* @@compilable: yes
* @@linkable: yes
* @@expect: success
* @@version: omp_5.0
*/
#include <stdio.h>
#include <omp.h>
int main()
{
int x = 0, y = 0;
#pragma omp parallel num_threads(2)
{
int thrd = omp_get_thread_num();
if (thrd == 0) {
x = 10;
#pragma omp flush // or with acq_rel or release clause
#pragma omp atomic write // or with relaxed clause
y = 1;
} else {
int tmp = 0;
while (tmp == 0) {
#pragma omp atomic read // or with relaxed clause
tmp = y;
}
#pragma omp flush // or with acq_rel or acquire clause
printf("x = %d\n", x); // always "x = 10"
}
}
return 0;
}
|
the_stack_data/39574.c | #include <stdlib.h>
//min heap function series
void push_heap(int *ptr, int size)
{
if (size <= 1)
return;
int val = ptr[size - 1], hole = size - 1;
for (int i = (hole - 1) >> 1; hole > 0 && val < ptr[i]; i = (hole - 1) >> 1)
{
ptr[hole] = ptr[i];
hole = i;
}
ptr[hole] = val;
}
void pop_heap(int *ptr, int size)
{
if (size <= 0)
return;
int val = *ptr, non_leaf = (size - 1) >> 1, hole = 0, i = 0;
while (i < non_leaf)
{
i = 2 * i + 2;
if (ptr[i - 1] < ptr[i])
--i;
ptr[hole] = ptr[i];
hole = i;
}
if (i == non_leaf && size % 2 == 0)
{
ptr[hole] = ptr[size - 1];
hole = size - 1;
}
ptr[hole] = ptr[size - 1];
push_heap(ptr, hole + 1);
ptr[size - 1] = val;
}
void make_heap(int *ptr, int size)
{
for (int i = 1; i < size; ++i)
push_heap(ptr, i + 1);
}
/********end of min heap********/
typedef struct
{
int size;
int capacity;
int *data;
} KthLargest;
KthLargest *kthLargestCreate(int k, int *nums, int numsSize)
{
KthLargest *kthlargest = (KthLargest *)malloc(sizeof(KthLargest));
kthlargest->capacity = k;
kthlargest->size = 0;
kthlargest->data = (int *)malloc(sizeof(int) * kthlargest->capacity);
for (int i = 0; i < numsSize; ++i)
kthLargestAdd(kthlargest, nums[i]);
return kthlargest;
}
int kthLargestAdd(KthLargest *obj, int val)
{
if (obj->size < obj->capacity)
{
obj->data[obj->size++] = val;
push_heap(obj->data, obj->size);
}
else if (obj->data[0] < val)
{
pop_heap(obj->data, obj->size);
obj->data[obj->size - 1] = val;
push_heap(obj->data, obj->size);
}
return obj->data[0];
}
void kthLargestFree(KthLargest *obj)
{
if (obj)
free(obj);
}
/**
* Your KthLargest struct will be instantiated and called as such:
* KthLargest* obj = kthLargestCreate(k, nums, numsSize);
* int param_1 = kthLargestAdd(obj, val);
* kthLargestFree(obj);
*/ |
the_stack_data/116783.c | #include <stdio.h>
#define MAX_BUFFER_SIZE 100
// Struct for Stack data structure implementation.
typedef struct {
int idx;
int buffer[MAX_BUFFER_SIZE];
} Stack;
// Generate empty stack. Initialize with start index 0.
Stack empty_stack() {
Stack stack;
stack.idx = 0;
return stack;
}
// Push `data` into `stack`.
// Returns:
// 1 for success.
// 0 for failure.
// Failure:
// Try pushing data to full stack.
int push(Stack* stack, int data) {
if (stack->idx >= MAX_BUFFER_SIZE) {
return 0;
}
stack->buffer[stack->idx++] = data;
return 1;
}
// Pop element from `stack` and store it to `res`.
// Returns:
// 1 for success.
// 0 for failure.
// Failure:
// Try popping from empty stack.
int pop(Stack* stack, int* res) {
if (stack->idx < 1) {
return 0;
}
--stack->idx;
if (res != NULL) {
*res = stack->buffer[stack->idx];
}
return 1;
}
// Validate if stack is empty.
int empty(Stack* stack) {
return stack->idx < 1;
}
// Get top element from stack.
int top(Stack* stack) {
return stack->buffer[stack->idx - 1];
}
// Get precedence from given operator.
// Returns:
// 2 for *, /, %
// 1 for +, -
// 0 for otherwise
int prec(char oper) {
switch (oper) {
case '*':
case '/':
case '%':
return 2;
case '+':
case '-':
return 1;
default:
return 0;
}
}
// Calculate operator with given operands.
int operate(char oper, int n1, int n2) {
switch (oper) {
case '*':
return n1 * n2;
case '/':
return n1 / n2;
case '%':
return n1 % n2;
case '+':
return n1 + n2;
case '-':
return n1 - n2;
default:
return 0;
}
}
// Convert infix form `input` to postfix form `output`.
// Condition:
// #-terminated string `input`
int make_postfix(char* output, char* input) {
int res;
int i = -1;
int idx = 0;
Stack oper_stack = empty_stack();
// #-terminated string
while (input[++i] != '#') {
// If digit
if (input[i] >= '0' && input[i] <= '9') {
output[idx++] = input[i];
}
// If open parenthesis
else if (input[i] == '(') {
push(&oper_stack, '(');
}
// If close parenthesis
else if (input[i] == ')') {
// Until finding open parenthesis
while (top(&oper_stack) != '(') {
output[idx++] = top(&oper_stack);
pop(&oper_stack, NULL);
}
// Pop open parenthesis
pop(&oper_stack, NULL);
}
// If stack is empty
// If precedence of top operator is lower than current operator.
else if (empty(&oper_stack) || prec(top(&oper_stack)) < prec(input[i])) {
push(&oper_stack, input[i]);
}
// If precedence of top operator is higher than current operator.
else {
// Until lower precedence operator appears
while (prec(top(&oper_stack)) >= prec(input[i])) {
pop(&oper_stack, &res);
output[idx++] = res;
}
push(&oper_stack, input[i]);
}
}
// Clear operator stack
while (!empty(&oper_stack)) {
pop(&oper_stack, &res);
output[idx++] = res;
}
return idx;
}
// Calculate postfix form `input`.
int calc_postfix(char* input, int len) {
Stack num_stack = empty_stack();
int i, n1, n2;
for (i = 0; i < len; ++i) {
// If digit
if (input[i] >= '0' && input[i] <= '9') {
push(&num_stack, input[i] - '0');
}
// If operator
else {
pop(&num_stack, &n2);
pop(&num_stack, &n1);
push(&num_stack, operate(input[i], n1, n2));
}
}
return top(&num_stack);
}
int main() {
// Prepare for file I/O.
FILE* input = fopen("input.txt", "r");
FILE* output = fopen("output.txt", "w");
char infix[MAX_BUFFER_SIZE + 1] = { 0, };
fscanf(input, "%s", infix);
// Convert to postfix form.
char postfix[MAX_BUFFER_SIZE + 1] = { 0, };
int size = make_postfix(postfix, infix);
// Calculate postfix form.
int result = calc_postfix(postfix, size);
// Convert #-terminated string to NULL-terminated string
int idx = -1;
while (infix[++idx] != '#');
infix[idx] = 0;
// Log
fprintf(output, "Infix Form : %s\n", infix);
fprintf(output, "Postfix Form : %s\n", postfix);
fprintf(output, "Evaluation Result : %d\n", result);
fclose(input);
fclose(output);
return 0;
} |
the_stack_data/59511715.c | #include <errno.h>
int errno;
long
_propagate_errno(long returned) {
if(returned >= 0) {
return returned;
} else {
errno = -returned;
return -1;
}
}
|
the_stack_data/132952927.c | #include "stdio.h"
int main(void) {
printf("%6d, %4d", 86, 1040);
printf("%12.5e", 30.253);
printf("%.4f", 83.162);
printf("%-6.2g", .0000009979);
return 0;
}
|
the_stack_data/179830466.c | /*-
* Copyright (c) 1983 The Regents of the University of California.
* All rights reserved.
*
* %sccs.include.proprietary.c%
*/
#ifndef lint
char copyright[] =
"@(#) Copyright (c) 1983 The Regents of the University of California.\n\
All rights reserved.\n";
#endif /* not lint */
#ifndef lint
static char sccsid[] = "@(#)pr.c 4.9 (Berkeley) 04/18/91";
#endif /* not lint */
/*
* print file with headings
* 2+head+2+page[56]+5
*/
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
/* Making putcp a macro sped things up by 14%. */
#define putcp(c) if (page >= fpage) putchar(c)
int ncol = 1;
char *header;
int col;
int icol;
FILE *file;
char *bufp;
#define BUFS 9000 /* at least 66 * 132 */
char buffer[BUFS]; /* for multi-column output */
char obuf[BUFSIZ];
#define FF 014
int line;
char *colp[72];
int nofile;
char isclosed[10];
FILE *ifile[10];
char **lastarg;
int peekc;
int fpage;
int page;
int colw;
int nspace;
int width = 72;
int length = 66;
int plength = 61;
int margin = 10;
int ntflg;
int fflg;
int mflg;
int tabc;
char *tty;
int mode;
char *ttyname();
char *ctime();
main(argc, argv)
char **argv;
{
int nfdone;
void onintr();
setbuf(stdout, obuf);
if (signal(SIGINT, SIG_IGN) != SIG_IGN)
signal(SIGINT, onintr);
lastarg = &argv[argc-1];
fixtty();
for (nfdone=0; argc>1; argc--) {
argv++;
if (**argv == '-') {
switch (*++*argv) {
case 'h': /* define page header */
if (argc>=2) {
header = *++argv;
argc--;
}
continue;
case 't': /* don't print page headers */
ntflg++;
continue;
case 'f': /* use form feeds */
fflg++;
plength = 60;
continue;
case 'l': /* length of page */
length = atoi(++*argv);
continue;
case 'w': /* width of page */
width = atoi(++*argv);
continue;
case 's': /* col separator */
if (*++*argv)
tabc = **argv;
else
tabc = '\t';
continue;
case 'm': /* all files at once */
mflg++;
continue;
default:
if (numeric(*argv)) { /* # of cols */
if ((ncol = atoi(*argv)) == 0) {
fprintf(stderr, "can't print 0 cols, using 1 instead.\n");
ncol = 1;
}
} else {
fprintf(stderr, "pr: bad key %s\n", *argv);
exit(1);
}
continue;
}
} else if (**argv == '+') { /* start at page ++*argv */
fpage = atoi(++*argv);
} else {
print(*argv, argv);
nfdone++;
if (mflg)
break;
}
}
if (nfdone==0)
print((char *)0, (char **)0);
done();
}
done()
{
if (tty)
chmod(tty, mode);
exit(0);
}
/* numeric -- returns 1 if str is numeric, elsewise 0 */
numeric(str)
char *str;
{
for (; *str ; str++) {
if (*str > '9' || *str < '0') {
return(0);
}
}
return(1);
}
void
onintr()
{
if (tty)
chmod(tty, mode);
_exit(1);
}
fixtty()
{
struct stat sbuf;
tty = ttyname(1);
if (tty == 0)
return;
stat(tty, &sbuf);
mode = sbuf.st_mode&0777;
chmod(tty, 0600);
}
/* print -- print file */
print(fp, argp)
char *fp;
char **argp;
{
struct stat sbuf;
register sncol;
register char *sheader;
register char *cbuf;
char linebuf[150], *cp;
if (ntflg)
margin = 0;
else
margin = 10;
if (length <= margin)
length = 66;
if (width <= 0)
width = 72;
if (ncol>72 || ncol>width) {
fprintf(stderr, "pr: No room for columns.\n");
done();
}
if (mflg) {
mopen(argp);
ncol = nofile;
}
colw = width/(ncol==0? 1 : ncol);
sncol = ncol;
sheader = header;
plength = length-5;
if (ntflg)
plength = length;
if (--ncol<0)
ncol = 0;
if (mflg)
fp = 0;
if (fp) {
if((file=fopen(fp, "r"))==NULL) {
if (tty==NULL)
perror(fp);
ncol = sncol;
header = sheader;
return;
}
stat(fp, &sbuf);
} else {
file = stdin;
time(&sbuf.st_mtime);
}
if (header == 0)
header = fp?fp:"";
cbuf = ctime(&sbuf.st_mtime);
cbuf[16] = '\0';
cbuf[24] = '\0';
page = 1;
icol = 0;
colp[ncol] = bufp = buffer;
if (mflg==0)
nexbuf();
while (mflg&&nofile || (!mflg)&&tpgetc(ncol)>0) {
if (mflg==0) {
colp[ncol]--;
if (colp[ncol] < buffer)
colp[ncol] = &buffer[BUFS - 1];
}
line = 0;
if (ntflg==0) {
if (fflg) {
/* Assume a ff takes two blank lines at the
top of the page. */
line = 2;
(void)sprintf(linebuf, "%s %s %s Page %d\n\n\n",
cbuf+4, cbuf+20, header, page);
} else
(void)sprintf(linebuf, "\n\n%s %s %s Page %d\n\n\n",
cbuf+4, cbuf+20, header, page);
for(cp=linebuf;*cp;) put(*cp++);
}
putpage();
if (ntflg==0) {
if (fflg)
put('\f');
else
while(line<length)
put('\n');
}
page++;
}
fclose(file);
ncol = sncol;
header = sheader;
}
mopen(ap)
char **ap;
{
register char **p, *p1;
p = ap;
while((p1 = *p) && p++ <= lastarg) {
if((ifile[nofile]=fopen(p1, "r")) == NULL){
isclosed[nofile] = 1;
nofile--;
}
else
isclosed[nofile] = 0;
if(++nofile>=10) {
fprintf(stderr, "pr: Too many args\n");
done();
}
}
}
putpage()
{
register int lastcol, i, c;
int j;
if (ncol==0) {
while (line<plength) {
while((c = tpgetc(0)) && c!='\n' && c!=FF)
putcp(c);
if (c==0) break;
putcp('\n');
line++;
if (c==FF)
break;
}
return;
}
colp[0] = colp[ncol];
if (mflg==0) for (i=1; i<=ncol; i++) {
colp[i] = colp[i-1];
for (j = margin; j<length; j++)
while((c=tpgetc(i))!='\n')
if (c==0)
break;
}
while (line<plength) {
lastcol = colw;
for (i=0; i<ncol; i++) {
while ((c=pgetc(i)) && c!='\n')
if (col<lastcol || tabc!=0)
put(c);
if (c==0)
continue;
if (tabc)
put(tabc);
else while (col<lastcol)
put(' ');
lastcol += colw;
}
while ((c = pgetc(ncol)) && c!='\n')
put(c);
put('\n');
}
}
nexbuf()
{
register int n;
register char *rbufp;
rbufp = bufp;
n = &buffer[BUFS] - rbufp;
if (n>512)
n = 512;
if((n=fread(rbufp,1,n,file)) <= 0){
fclose(file);
*rbufp = 0376;
}
else {
rbufp += n;
if (rbufp >= &buffer[BUFS])
rbufp = buffer;
*rbufp = 0375;
}
bufp = rbufp;
}
tpgetc(ai)
{
register char **p;
register int c, i;
i = ai;
if (mflg) {
if((c=getc(ifile[i])) == EOF) {
if (isclosed[i]==0) {
isclosed[i] = 1;
if (--nofile <= 0)
return(0);
}
return('\n');
}
if (c==FF && ncol>0)
c = '\n';
return(c);
}
loop:
c = **(p = &colp[i]) & 0377;
if (c == 0375) {
nexbuf();
c = **p & 0377;
}
if (c == 0376)
return(0);
(*p)++;
if (*p >= &buffer[BUFS])
*p = buffer;
if (c==0)
goto loop;
return(c);
}
pgetc(i)
{
register int c;
if (peekc) {
c = peekc;
peekc = 0;
} else
c = tpgetc(i);
if (tabc)
return(c);
switch (c) {
case '\t':
icol++;
if ((icol&07) != 0)
peekc = '\t';
return(' ');
case '\n':
icol = 0;
break;
case 010:
case 033:
icol--;
break;
}
if (c >= ' ')
icol++;
return(c);
}
put(ac)
{
register int ns, c;
c = ac;
if (tabc) {
putcp(c);
if (c=='\n')
line++;
return;
}
switch (c) {
case ' ':
nspace++;
col++;
return;
case '\n':
col = 0;
nspace = 0;
line++;
break;
case 010:
case 033:
if (--col<0)
col = 0;
if (--nspace<0)
nspace = 0;
}
while(nspace) {
if (nspace>2 && col > (ns=((col-nspace)|07))) {
nspace = col-ns-1;
putcp('\t');
} else {
nspace--;
putcp(' ');
}
}
if (c >= ' ')
col++;
putcp(c);
}
|
the_stack_data/74523.c | /*
Copyright <2017> <Scaleable and Concurrent Systems Lab;
Thayer School of Engineering at Dartmouth College>
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.
*/
/*
* tprinter - a basic test to make sure printf can print basic values
*/
#include <stdio.h>
#include <stdlib.h>
#define BUFFLEN 256
int main(void) {
int ret,i;
double f;
i = -9;
f = 3.142;
printf(" {%d,%s,%.2lf}\n", i,"hi",f);
fflush(stdout);
return(EXIT_SUCCESS);
}
|
the_stack_data/53265.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
printf("Je suis file_4.c dans Module_1 dans Projet_3");
return;
}
|
the_stack_data/115958.c | //file: _insn_test_xor_Y1.c
//op=333
#include <stdio.h>
#include <stdlib.h>
void func_exit(void) {
printf("%s\n", __func__);
exit(0);
}
void func_call(void) {
printf("%s\n", __func__);
exit(0);
}
unsigned long mem[2] = { 0x4f4d9c00e64f18fd, 0x1894984f8a4b9b67 };
int main(void) {
unsigned long a[4] = { 0, 0 };
asm __volatile__ (
"moveli r23, 15126\n"
"shl16insli r23, r23, -17631\n"
"shl16insli r23, r23, 31423\n"
"shl16insli r23, r23, 10557\n"
"moveli r20, -9320\n"
"shl16insli r20, r20, -29957\n"
"shl16insli r20, r20, 7281\n"
"shl16insli r20, r20, 3173\n"
"moveli r33, 2487\n"
"shl16insli r33, r33, 6184\n"
"shl16insli r33, r33, 10965\n"
"shl16insli r33, r33, -25198\n"
"{ fnop ; xor r23, r20, r33 ; ld r63, r54 }\n"
"move %0, r23\n"
"move %1, r20\n"
"move %2, r33\n"
:"=r"(a[0]),"=r"(a[1]),"=r"(a[2]));
printf("%016lx\n", a[0]);
printf("%016lx\n", a[1]);
printf("%016lx\n", a[2]);
return 0;
}
|
the_stack_data/94065.c | // blibioteca
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//funçao principal
int main()
{
//variaveis
int num, quadrado, raiz;
//saida para coleta de dados
printf("Digite um numero: ");
scanf("%d", &num);
//condiçao
if (num % 2 == 0)
{
//formula para numeros pares
quadrado = num * num;
raiz = sqrt(num);
printf("\nO numero %d elevado ao quadrado equivale: %d\n", num, quadrado);
printf("E sua raiz eh: %d\n", raiz);
}
return(0);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.