file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/45450707.c | /**
* 枚举类型
* */
#include <stdio.h>
#include <stdlib.h>
enum spectrum {
red,
orange,
yellow,
green,
blue,
violet
};
int main(void)
{
//TODO c++ 不支持color++操作,需要将声明成:int colort;
enum spectrum color;
int c;
color = blue;
if(color == blue) {
printf("current color = %d \n", color);
}
for(color = red; color <= violet; color++) {
printf("spectrum colors: %d\n", color);
}
return 0;
}
|
the_stack_data/86076059.c | #include <stdio.h>
void foo(FILE *f) { fclose(f); }
int main(int argc, char **argv) {
FILE *f;
fclose(f);
f = fopen(argv[1], "r");
foo(f);
return 0;
} |
the_stack_data/25151.c | //Estructuras selectivas
/*Realiza un programa de tres numeros enteros positivos
distintos e imprima el mayor y el menor valor de los tres.
Intente que el programa realice el menor numero de comparaciones
posibles entre los numeros*/
#include <stdio.h>
int main(){
int a,b,c;
int max,min;
printf("Introduce el valor de a: \n");
scanf("%i",&a);
printf("Introduce el valor de b: \n");
scanf("%i",&b);
printf("Introduce el valor de c: \n");
scanf("%i",&c);
if(a > b){
if(a > c){
max = a;
}
else{
max = c;
}
}
else{
if(b > c){
max = b;
}
else{
max = c;
}
}
printf("El mayor de los 3 numeros es: %i \n",max);
if(a < b){
if(a < c){
min = a;
}
else{
min = c;
}
}
else{
if(b < c){
min = b;
}
else{
min = c;
}
}
printf("El menor de los 3 numeros es: %i \n",min);
return 0;
} |
the_stack_data/243181.c | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern float strtof(char const *str , char const *endptr ) ;
extern void signal(int sig , void *func ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned char input[1] , unsigned char output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void megaInit(void)
{
{
}
}
int main(int argc , char *argv[] )
{
unsigned char input[1] ;
unsigned char output[1] ;
int randomFuns_i5 ;
unsigned char randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = (unsigned char )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == (unsigned char)42) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
void RandomFunc(unsigned char input[1] , unsigned char output[1] )
{
unsigned char state[1] ;
{
state[0UL] = input[0UL] + (unsigned char)219;
if (state[0UL] & (unsigned char)1) {
if ((state[0UL] >> (unsigned char)2) & (unsigned char)1) {
if ((state[0UL] >> (unsigned char)3) & (unsigned char)1) {
state[0UL] |= (state[0UL] & (unsigned char)15) << 2UL;
state[0UL] |= (state[0UL] & (unsigned char)63) << 4UL;
} else {
state[0UL] = (state[0UL] << (((state[0UL] >> (unsigned char)2) & (unsigned char)15) | 1UL)) | (state[0UL] >> (8 - (((state[0UL] >> (unsigned char)2) & (unsigned char)15) | 1UL)));
state[0UL] += state[0UL];
}
} else
if ((state[0UL] >> (unsigned char)4) & (unsigned char)1) {
state[0UL] |= (state[0UL] & (unsigned char)15) << 2UL;
state[0UL] |= (state[0UL] & (unsigned char)15) << 2UL;
} else {
state[0UL] |= (state[0UL] & (unsigned char)7) << 2UL;
state[0UL] |= (state[0UL] & (unsigned char)15) << 3UL;
}
} else {
state[0UL] |= (state[0UL] & (unsigned char)63) << 4UL;
state[0UL] |= ((state[0UL] >> ((state[0UL] & (unsigned char)7) | 1UL)) & (unsigned char)15) << 3UL;
}
output[0UL] = (state[0UL] | 93321148UL) ^ (unsigned char)139;
}
}
|
the_stack_data/87637478.c | // RUN: %clang_cc1 -triple=x86_64-apple-darwin -fsyntax-only -verify %s
typedef long long __m128i __attribute__((__vector_size__(16)));
typedef float __m128 __attribute__((__vector_size__(16)));
typedef double __m128d __attribute__((__vector_size__(16)));
typedef float __m512 __attribute__((__vector_size__(64)));
typedef double __m512d __attribute__((__vector_size__(64)));
typedef unsigned char __mmask8;
typedef unsigned short __mmask16;
__m128 test__builtin_ia32_cmpps(__m128 __a, __m128 __b) {
__builtin_ia32_cmpps(__a, __b, 32); // expected-error {{argument should be a value from 0 to 31}}
}
__m128d test__builtin_ia32_cmppd(__m128d __a, __m128d __b) {
__builtin_ia32_cmppd(__a, __b, 32); // expected-error {{argument should be a value from 0 to 31}}
}
__m128 test__builtin_ia32_cmpss(__m128 __a, __m128 __b) {
__builtin_ia32_cmpss(__a, __b, 32); // expected-error {{argument should be a value from 0 to 31}}
}
__m128d test__builtin_ia32_cmpsd(__m128d __a, __m128d __b) {
__builtin_ia32_cmpsd(__a, __b, 32); // expected-error {{argument should be a value from 0 to 31}}
}
__mmask16 test__builtin_ia32_cmpps512_mask(__m512d __a, __m512d __b) {
__builtin_ia32_cmpps512_mask(__a, __b, 32, -1, 4); // expected-error {{argument should be a value from 0 to 31}}
}
__mmask8 test__builtin_ia32_cmppd512_mask(__m512d __a, __m512d __b) {
__builtin_ia32_cmppd512_mask(__a, __b, 32, -1, 4); // expected-error {{argument should be a value from 0 to 31}}
}
__m128i test__builtin_ia32_vpcomub(__m128i __a, __m128i __b) {
__builtin_ia32_vpcomub(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
}
__m128i test__builtin_ia32_vpcomuw(__m128i __a, __m128i __b) {
__builtin_ia32_vpcomuw(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
}
__m128i test__builtin_ia32_vpcomud(__m128i __a, __m128i __b) {
__builtin_ia32_vpcomud(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
}
__m128i test__builtin_ia32_vpcomuq(__m128i __a, __m128i __b) {
__builtin_ia32_vpcomuq(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
}
__m128i test__builtin_ia32_vpcomb(__m128i __a, __m128i __b) {
__builtin_ia32_vpcomub(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
}
__m128i test__builtin_ia32_vpcomw(__m128i __a, __m128i __b) {
__builtin_ia32_vpcomuw(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
}
__m128i test__builtin_ia32_vpcomd(__m128i __a, __m128i __b) {
__builtin_ia32_vpcomud(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
}
__m128i test__builtin_ia32_vpcomq(__m128i __a, __m128i __b) {
__builtin_ia32_vpcomuq(__a, __b, 8); // expected-error {{argument should be a value from 0 to 7}}
}
__mmask16 test__builtin_ia32_cmpps512_mask_rounding(__m512 __a, __m512 __b, __mmask16 __u) {
__builtin_ia32_cmpps512_mask(__a, __b, 0, __u, 0); // expected-error {{invalid rounding argument}}
}
|
the_stack_data/133624.c | /* */
#include <sys/types.h>
#include <ctype.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <inttypes.h>
#include <langinfo.h>
int main(void){return 0;}
|
the_stack_data/114162.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_40__ TYPE_9__ ;
typedef struct TYPE_39__ TYPE_8__ ;
typedef struct TYPE_38__ TYPE_7__ ;
typedef struct TYPE_37__ TYPE_6__ ;
typedef struct TYPE_36__ TYPE_5__ ;
typedef struct TYPE_35__ TYPE_4__ ;
typedef struct TYPE_34__ TYPE_3__ ;
typedef struct TYPE_33__ TYPE_2__ ;
typedef struct TYPE_32__ TYPE_1__ ;
typedef struct TYPE_31__ TYPE_15__ ;
typedef struct TYPE_30__ TYPE_14__ ;
typedef struct TYPE_29__ TYPE_13__ ;
typedef struct TYPE_28__ TYPE_12__ ;
typedef struct TYPE_27__ TYPE_11__ ;
typedef struct TYPE_26__ TYPE_10__ ;
/* Type definitions */
typedef int /*<<< orphan*/ u_char ;
typedef size_t ngx_uint_t ;
struct TYPE_34__ {scalar_t__ len; } ;
struct TYPE_35__ {int len; scalar_t__ data; } ;
struct TYPE_37__ {TYPE_3__ value; TYPE_4__ key; } ;
typedef TYPE_6__ ngx_keyval_t ;
typedef scalar_t__ ngx_int_t ;
struct TYPE_38__ {int skip_empty; TYPE_3__ value; TYPE_4__ key; } ;
typedef TYPE_7__ ngx_http_upstream_param_t ;
struct TYPE_39__ {int len; void* code; } ;
typedef TYPE_8__ ngx_http_script_copy_code_t ;
struct TYPE_40__ {int /*<<< orphan*/ ** values; int /*<<< orphan*/ ** lengths; int /*<<< orphan*/ * flushes; TYPE_3__* source; TYPE_14__* cf; } ;
typedef TYPE_9__ ngx_http_script_compile_t ;
typedef void* ngx_http_script_code_pt ;
struct TYPE_32__ {void* buckets; } ;
struct TYPE_26__ {size_t number; TYPE_1__ hash; int /*<<< orphan*/ * lengths; int /*<<< orphan*/ * values; int /*<<< orphan*/ flushes; } ;
typedef TYPE_10__ ngx_http_fastcgi_params_t ;
struct TYPE_27__ {TYPE_2__* params_source; } ;
typedef TYPE_11__ ngx_http_fastcgi_loc_conf_t ;
struct TYPE_36__ {int len; scalar_t__ data; } ;
struct TYPE_28__ {void* value; TYPE_5__ key; int /*<<< orphan*/ key_hash; } ;
typedef TYPE_12__ ngx_hash_key_t ;
struct TYPE_29__ {int max_size; int bucket_size; char* name; int /*<<< orphan*/ * temp_pool; int /*<<< orphan*/ pool; int /*<<< orphan*/ (* key ) (scalar_t__,int) ;TYPE_1__* hash; } ;
typedef TYPE_13__ ngx_hash_init_t ;
struct TYPE_30__ {int /*<<< orphan*/ pool; int /*<<< orphan*/ temp_pool; } ;
typedef TYPE_14__ ngx_conf_t ;
struct TYPE_31__ {size_t nelts; TYPE_7__* elts; } ;
typedef TYPE_15__ ngx_array_t ;
struct TYPE_33__ {size_t nelts; TYPE_7__* elts; } ;
/* Variables and functions */
scalar_t__ NGX_ERROR ;
scalar_t__ NGX_OK ;
void* ngx_array_create (int /*<<< orphan*/ ,int,int) ;
scalar_t__ ngx_array_init (TYPE_15__*,int /*<<< orphan*/ ,int,int) ;
void* ngx_array_push (TYPE_15__*) ;
void* ngx_array_push_n (int /*<<< orphan*/ *,int) ;
scalar_t__ ngx_hash_init (TYPE_13__*,TYPE_7__*,size_t) ;
int /*<<< orphan*/ ngx_hash_key_lc (scalar_t__,int) ;
scalar_t__ ngx_http_script_compile (TYPE_9__*) ;
void* ngx_http_script_copy_code ;
scalar_t__ ngx_http_script_copy_len_code ;
int /*<<< orphan*/ ngx_memcpy (int /*<<< orphan*/ *,scalar_t__,int) ;
int /*<<< orphan*/ ngx_memzero (TYPE_9__*,int) ;
scalar_t__ ngx_strcasecmp (scalar_t__,scalar_t__) ;
scalar_t__ ngx_strncmp (scalar_t__,char*,int) ;
__attribute__((used)) static ngx_int_t
ngx_http_fastcgi_init_params(ngx_conf_t *cf, ngx_http_fastcgi_loc_conf_t *conf,
ngx_http_fastcgi_params_t *params, ngx_keyval_t *default_params)
{
u_char *p;
size_t size;
uintptr_t *code;
ngx_uint_t i, nsrc;
ngx_array_t headers_names, params_merged;
ngx_keyval_t *h;
ngx_hash_key_t *hk;
ngx_hash_init_t hash;
ngx_http_upstream_param_t *src, *s;
ngx_http_script_compile_t sc;
ngx_http_script_copy_code_t *copy;
if (params->hash.buckets) {
return NGX_OK;
}
if (conf->params_source == NULL && default_params == NULL) {
params->hash.buckets = (void *) 1;
return NGX_OK;
}
params->lengths = ngx_array_create(cf->pool, 64, 1);
if (params->lengths == NULL) {
return NGX_ERROR;
}
params->values = ngx_array_create(cf->pool, 512, 1);
if (params->values == NULL) {
return NGX_ERROR;
}
if (ngx_array_init(&headers_names, cf->temp_pool, 4, sizeof(ngx_hash_key_t))
!= NGX_OK)
{
return NGX_ERROR;
}
if (conf->params_source) {
src = conf->params_source->elts;
nsrc = conf->params_source->nelts;
} else {
src = NULL;
nsrc = 0;
}
if (default_params) {
if (ngx_array_init(¶ms_merged, cf->temp_pool, 4,
sizeof(ngx_http_upstream_param_t))
!= NGX_OK)
{
return NGX_ERROR;
}
for (i = 0; i < nsrc; i++) {
s = ngx_array_push(¶ms_merged);
if (s == NULL) {
return NGX_ERROR;
}
*s = src[i];
}
h = default_params;
while (h->key.len) {
src = params_merged.elts;
nsrc = params_merged.nelts;
for (i = 0; i < nsrc; i++) {
if (ngx_strcasecmp(h->key.data, src[i].key.data) == 0) {
goto next;
}
}
s = ngx_array_push(¶ms_merged);
if (s == NULL) {
return NGX_ERROR;
}
s->key = h->key;
s->value = h->value;
s->skip_empty = 1;
next:
h++;
}
src = params_merged.elts;
nsrc = params_merged.nelts;
}
for (i = 0; i < nsrc; i++) {
if (src[i].key.len > sizeof("HTTP_") - 1
&& ngx_strncmp(src[i].key.data, "HTTP_", sizeof("HTTP_") - 1) == 0)
{
hk = ngx_array_push(&headers_names);
if (hk == NULL) {
return NGX_ERROR;
}
hk->key.len = src[i].key.len - 5;
hk->key.data = src[i].key.data + 5;
hk->key_hash = ngx_hash_key_lc(hk->key.data, hk->key.len);
hk->value = (void *) 1;
if (src[i].value.len == 0) {
continue;
}
}
copy = ngx_array_push_n(params->lengths,
sizeof(ngx_http_script_copy_code_t));
if (copy == NULL) {
return NGX_ERROR;
}
copy->code = (ngx_http_script_code_pt) (void *)
ngx_http_script_copy_len_code;
copy->len = src[i].key.len;
copy = ngx_array_push_n(params->lengths,
sizeof(ngx_http_script_copy_code_t));
if (copy == NULL) {
return NGX_ERROR;
}
copy->code = (ngx_http_script_code_pt) (void *)
ngx_http_script_copy_len_code;
copy->len = src[i].skip_empty;
size = (sizeof(ngx_http_script_copy_code_t)
+ src[i].key.len + sizeof(uintptr_t) - 1)
& ~(sizeof(uintptr_t) - 1);
copy = ngx_array_push_n(params->values, size);
if (copy == NULL) {
return NGX_ERROR;
}
copy->code = ngx_http_script_copy_code;
copy->len = src[i].key.len;
p = (u_char *) copy + sizeof(ngx_http_script_copy_code_t);
ngx_memcpy(p, src[i].key.data, src[i].key.len);
ngx_memzero(&sc, sizeof(ngx_http_script_compile_t));
sc.cf = cf;
sc.source = &src[i].value;
sc.flushes = ¶ms->flushes;
sc.lengths = ¶ms->lengths;
sc.values = ¶ms->values;
if (ngx_http_script_compile(&sc) != NGX_OK) {
return NGX_ERROR;
}
code = ngx_array_push_n(params->lengths, sizeof(uintptr_t));
if (code == NULL) {
return NGX_ERROR;
}
*code = (uintptr_t) NULL;
code = ngx_array_push_n(params->values, sizeof(uintptr_t));
if (code == NULL) {
return NGX_ERROR;
}
*code = (uintptr_t) NULL;
}
code = ngx_array_push_n(params->lengths, sizeof(uintptr_t));
if (code == NULL) {
return NGX_ERROR;
}
*code = (uintptr_t) NULL;
params->number = headers_names.nelts;
hash.hash = ¶ms->hash;
hash.key = ngx_hash_key_lc;
hash.max_size = 512;
hash.bucket_size = 64;
hash.name = "fastcgi_params_hash";
hash.pool = cf->pool;
hash.temp_pool = NULL;
return ngx_hash_init(&hash, headers_names.elts, headers_names.nelts);
} |
the_stack_data/6388608.c |
/* keyseq.c */
/* Code to get the sequence of codes for keys. */
/* Very useful for getting codes for keys with */
/* more than one character (e.g. arrow keys) */
/* This code is released to the public domain. */
/* "Share and enjoy....... " ;) */
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
/* Getch() from here - */
/* http://wesley.vidiqatch.org/ */
/* Thanks, Wesley! */
static struct termios old, new;
/* Initialize new terminal i/o settings */
void initTermios(int echo) {
tcgetattr(0, &old); /* grab old terminal i/o settings */
new = old; /* make new settings same as old settings */
new.c_lflag &= ~ICANON; /* disable buffered i/o */
new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */
}
/* Restore old terminal i/o settings */
void resetTermios(void) {
tcsetattr(0, TCSANOW, &old);
}
/* Read 1 character - echo defines echo mode */
char getch_(int echo) {
char ch;
initTermios(echo);
ch = getchar();
resetTermios();
return ch;
}
/* Read 1 character without echo */
char getch(void) {
return getch_(0);
}
/* Read 1 character with echo */
char getche(void) {
return getch_(1);
}
/* A struct to hold key sequence data. */
struct keyseq {
int ctrl;
int shf;
int esc;
int lbrack;
int del;
int key;
} ;
/* Create a new struct and set it to NULL. */
struct keyseq *k = NULL;
/* Print the struct data. */
void print_seq(struct keyseq *k)
{
printf( "k->ctrl = %d\n", (k->ctrl) );
printf( "k->shf = %d\n", (k->shf) );
printf( "k->esc = %d\n", (k->esc) );
printf( "k->lbrack = %d\n", (k->lbrack) );
printf( "k->del = %d\n", (k->del) );
printf( "k->key = %d\n", (k->key) );
puts("--------------------\n");
}
/* Function to add data to struct. */
struct keyseq *add_data(struct keyseq *k, int data)
{
/* Clear existing flags */
k->ctrl = k->del = k->esc = k->key = k->lbrack = k->shf = 0;
/* Set flags. */
switch (data)
{
case 1 ... 26: k->ctrl = 1; break;
case 27: k->esc = 1; break;
case 65 ... 90: k->shf = 1; break;
case 91: k->lbrack = 1; break;
case 127: k->del = 1; break;
default: break;
}
/* We do not include esc and lbrack keys here. */
switch (data)
{
case 1 ... 26: k->key = data; break;
case 32 ... 90: k->key = data; break;
case 92 ... 127: k->key = data; break;
default: break;
}
return k;
}
/* Function to add data to struct. */
void test(struct keyseq *k)
{
int c = getch();
while( (c > 0 && c < 127 ) )
{
c = getch();
switch (c)
{
case 4: break;
/* default: add_data(k, c); break; */
default: printf("%d \n", c); break;
}
} /* while */
print_seq(k);
}
int main()
{
/* Create a new list and set it to NULL. */
struct keyseq *k = NULL;
k = malloc(sizeof(struct keyseq));
while(1)
{
test(k) ;
}
return 0;
}
|
the_stack_data/1045608.c | /**********
* ZUCC Cprograming task
* Author: Takuron@github
**********/
#include <stdio.h>
int main () {
char a;
scanf("%s",&a);
printf("%c",a-'a'+'A');
return 0;
}
|
the_stack_data/150141537.c | #include<stdio.h>
int main(){
int i,s,t,a,b;
t=6;
for(i=1;i<=6;i++){
s=t-i;
for(a=1;a<=s;a++){
printf(" ");
}
for(b=1;b<=i;b++){
printf("*");
}
printf("\n");
}
return 0;
} |
the_stack_data/23576417.c | #include<stdio.h>
int main()
{
int n,x,i,s=0,k,f;
printf("\n Enter a number:");
scanf("%d",&n);
x=n;
while(n)
{
k=n%10; f=1;
for(i=1;i<=k;i++)
f=f*i;
s=s+f;
n=n/10;
}
if(s==x)
printf("\n The entered number is a peterson number.");
else
printf("\n The enetered number is not a peterson number.");
return 0;
}
|
the_stack_data/235907.c | /* empty C file for the Octave test-suite C tests is needed - build system workaround as the generated files for Octave are C++ files */
|
the_stack_data/132952295.c | /* PR tree-optimization/84478 */
long poolptr;
unsigned char *strpool;
static const char *poolfilearr[] = {
"mu",
"",
#define A "x",
#define B A "xx", A A "xxx", A A A A A
#define C B B B B B B B B B B
#define D C C C C C C C C C C
D C C C C C C C B B B
((void *)0)
};
__attribute__((noipa)) long
makestring (void)
{
return 1;
}
__attribute__((noipa)) long
loadpoolstrings (long spare_size)
{
const char *s;
long g = 0;
int i = 0, j = 0;
while ((s = poolfilearr[j++]))
{
int l = __builtin_strlen (s);
i += l;
if (i >= spare_size) return 0;
while (l-- > 0) strpool[poolptr++] = *s++;
g = makestring ();
}
return g;
}
int
main ()
{
strpool = __builtin_malloc (4000);
if (!strpool)
return 0;
asm volatile ("" : : : "memory");
volatile int r = loadpoolstrings (4000);
__builtin_free (strpool);
return 0;
}
|
the_stack_data/30.c | ///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
#if defined(_NITRO)
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// static variables
static int GSINitroErrno;
// prototypes of static functions
static int CheckRcode(int rcode, int errCode);
#define NITRO_SOCKET_ERROR -1
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
static int CheckRcode(int rcode, int errCode)
{
if (rcode >= 0)
return rcode;
GSINitroErrno = rcode;
return errCode;
}
int socket(int pf, int type, int protocol)
{
int rcode = SOC_Socket(pf, type, protocol);
return CheckRcode(rcode, INVALID_SOCKET);
}
int closesocket(SOCKET sock)
{
int rcode = SOC_Close(sock);
return CheckRcode(rcode, NITRO_SOCKET_ERROR);
}
int shutdown(SOCKET sock, int how)
{
int rcode = SOC_Shutdown(sock, how);
return CheckRcode(rcode, NITRO_SOCKET_ERROR);
}
int bind(SOCKET sock, const SOCKADDR* addr, int len)
{
SOCKADDR localAddr;
int rcode;
// with nitro, don't bind to 0, just start using the port
if (((const SOCKADDR_IN*)addr)->port == 0)
return 0;
memcpy(&localAddr, addr, sizeof(SOCKADDR));
localAddr.len = (u8)len;
rcode = SOC_Bind(sock, &localAddr);
return CheckRcode(rcode, NITRO_SOCKET_ERROR);
}
int connect(SOCKET sock, const SOCKADDR* addr, int len)
{
SOCKADDR remoteAddr;
int rcode;
memcpy(&remoteAddr, addr, sizeof(SOCKADDR));
remoteAddr.len = (u8)len;
rcode = SOC_Connect(sock, &remoteAddr);
return CheckRcode(rcode, NITRO_SOCKET_ERROR);
}
int listen(SOCKET sock, int backlog)
{
int rcode = SOC_Listen(sock, backlog);
return CheckRcode(rcode, NITRO_SOCKET_ERROR);
}
SOCKET accept(SOCKET sock, SOCKADDR* addr, int* len)
{
int rcode;
addr->len = (u8)*len;
rcode = SOC_Accept(sock, addr);
*len = addr->len;
return CheckRcode(rcode, NITRO_SOCKET_ERROR);
}
int recv(SOCKET sock, char* buf, int len, int flags)
{
int rcode = SOC_Recv(sock, buf, len, flags);
return CheckRcode(rcode, NITRO_SOCKET_ERROR);
}
int recvfrom(SOCKET sock, char* buf, int len, int flags, SOCKADDR* addr, int* fromlen)
{
int rcode;
addr->len = (u8)*fromlen;
rcode = SOC_RecvFrom(sock, buf, len, flags, addr);
*fromlen = addr->len;
return CheckRcode(rcode, NITRO_SOCKET_ERROR);
}
SOCKET send(SOCKET sock, const char* buf, int len, int flags)
{
int rcode = SOC_Send(sock, buf, len, flags);
return CheckRcode(rcode, NITRO_SOCKET_ERROR);
}
SOCKET sendto(SOCKET sock, const char* buf, int len, int flags, const SOCKADDR* addr, int tolen)
{
SOCKADDR remoteAddr;
int rcode;
memcpy(&remoteAddr, addr, sizeof(SOCKADDR));
remoteAddr.len = (u8)tolen;
rcode = SOC_SendTo(sock, buf, len, flags, &remoteAddr);
return CheckRcode(rcode, NITRO_SOCKET_ERROR);
}
int getsockopt(SOCKET sock, int level, int optname, char* optval, int* optlen)
{
int rcode = SOC_GetSockOpt(sock, level, optname, optval, optlen);
return CheckRcode(rcode, NITRO_SOCKET_ERROR);
}
SOCKET setsockopt(SOCKET sock, int level, int optname, const char* optval, int optlen)
{
int rcode = SOC_SetSockOpt(sock, level, optname, optval, optlen);
return CheckRcode(rcode, NITRO_SOCKET_ERROR);
}
int getsockname(SOCKET sock, SOCKADDR* addr, int* len)
{
int rcode;
addr->len = (u8)*len;
rcode = SOC_GetSockName(sock, addr);
*len = addr->len;
return CheckRcode(rcode, NITRO_SOCKET_ERROR);
}
unsigned long inet_addr(const char* name)
{
int rcode;
SOInAddr addr;
rcode = SOC_InetAtoN(name, &addr);
if (rcode == FALSE)
return INADDR_NONE;
return addr.addr;
}
int GOAGetLastError(SOCKET sock)
{
GSI_UNUSED(sock);
return GSINitroErrno;
}
int GSISocketSelect(SOCKET theSocket, int* theReadFlag, int* theWriteFlag, int* theExceptFlag)
{
SOPollFD pollFD;
int rcode;
pollFD.fd = theSocket;
pollFD.events = 0;
if (theReadFlag != NULL)
pollFD.events |= SOC_POLLRDNORM;
if (theWriteFlag != NULL)
pollFD.events |= SOC_POLLWRNORM;
pollFD.revents = 0;
rcode = SOC_Poll(&pollFD, 1, 0);
if (rcode < 0)
return NITRO_SOCKET_ERROR;
if (theReadFlag != NULL) {
if ((rcode > 0) && (pollFD.revents & (SOC_POLLRDNORM | SOC_POLLHUP)))
*theReadFlag = 1;
else
*theReadFlag = 0;
}
if (theWriteFlag != NULL) {
if ((rcode > 0) && (pollFD.revents & SOC_POLLWRNORM))
*theWriteFlag = 1;
else
*theWriteFlag = 0;
}
if (theExceptFlag != NULL) {
if ((rcode > 0) && (pollFD.revents & SOC_POLLERR))
*theExceptFlag = 1;
else
*theExceptFlag = 0;
}
return rcode;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
#endif // _NITRO |
the_stack_data/6386596.c | #include<stdio.h>
long long gcd(long long a,long long b){
if(b==0){
return a;
}else{
return gcd(b,a%b);
}
}//最大公约数
struct Num{
long long numerator,denominator;
}num,ans;
int main(){
int i,N,flaga,flagn;
long long pub,a,n,integer;
scanf("%d",&N);
scanf("%lld/%lld",&ans.numerator,&ans.denominator);
if(ans.numerator>=0){
flaga=1;
}else{
flaga=-1;
ans.numerator=-ans.numerator;
}
for(i=1;i<N;i++){
scanf("%lld/%lld",&num.numerator,&num.denominator);
if(num.numerator>=0){
flagn=1;
}else{
flagn=-1;
num.numerator=-num.numerator;
}
pub=gcd(ans.denominator,num.denominator);
a=ans.denominator/pub;
n=num.denominator/pub;
ans.denominator=a*n*pub;
ans.numerator=flaga*ans.numerator*n+flagn*num.numerator*a;
if(ans.numerator>=0){
flaga=1;
}else{
flaga=-1;
ans.numerator=-ans.numerator;
}
pub=gcd(ans.numerator,ans.denominator);
ans.denominator/=pub;
ans.numerator/=pub;
}
if(flaga==-1){
printf("-");
}
integer=ans.numerator/ans.denominator;
ans.numerator%=ans.denominator;
if(integer){
printf("%d",integer);
if(ans.numerator){
printf(" ");
}else{
printf("\n");
}
}
if(ans.numerator){
printf("%d/%d\n",ans.numerator,ans.denominator);
}
if(integer==0&&ans.numerator==0){
printf("0\n");
}
return 0;
}
|
the_stack_data/140766209.c | #include <stdio.h>
int main(){
/* Verify getchar() != EOF is 0 or 1 */
printf("Feed a value to getchar()\n");
printf("value of expression: %d", getchar() != EOF);
return 0;
}
/* Expression verification
The expression getchar() != EOF is equal with 1
on Windows the EOF char is accessible with CTRL+Z
on Unix like systems the EOF char is accessible with CTRL+D.
*/
|
the_stack_data/295153.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_ten_queens_puzzle.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lteresia <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/07 15:33:06 by lteresia #+# #+# */
/* Updated: 2021/09/07 15:33:08 by lteresia ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
void ft_print_solution(int *ar, int n)
{
int i;
char c;
i = 0;
while (i < n)
{
c = ar[i++] + '0';
write(1, &c, 1);
}
write(1, "\n", 1);
}
void ft_clean_columns(int *columns, int x)
{
while (x < 10)
columns[x++] = -1;
}
int ft_is_position_free(int x, int y, int *columns)
{
int i;
i = 0;
while (i < 10)
{
if ((y - (x - i) >= 0 && columns[i] == y - (x - i))
|| (y + (x - i) >= 0 && columns[i] == y + (x - i))
|| columns[i] == y)
return (0);
i++;
}
return (1);
}
int ft_put_queen(int x, int *columns, int n_solutions)
{
int j;
j = 0;
while (j < 10)
{
if (ft_is_position_free(x, j, columns))
{
columns[x] = j;
if (x == 9)
{
ft_print_solution(columns, 10);
n_solutions++;
}
else
n_solutions = ft_put_queen(x + 1, columns, n_solutions);
ft_clean_columns(columns, x);
}
j++;
}
return (n_solutions);
}
int ft_ten_queens_puzzle(void)
{
int i;
int columns[10];
int n_solutions;
i = 0;
while (i < 10)
columns[i++] = -1;
n_solutions = ft_put_queen(0, columns, 0);
return (n_solutions);
}
|
the_stack_data/72013992.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_print_comb2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dnascime <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/25 11:12:42 by dnascime #+# #+# */
/* Updated: 2019/11/25 16:51:10 by dnascime ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
void ft_putint(int n)
{
int one;
int two;
if (n > 9)
{
one = n / 10;
two = n % 10;
ft_putchar(one + 48);
ft_putchar(two + 48);
}
else
{
ft_putchar('0');
ft_putchar(n + 48);
}
}
void ft_print_comb2(void)
{
int d;
int e;
d = 0;
while (d <= 99)
{
e = d + 1;
while (e <= 99)
{
ft_putint(d);
ft_putchar(' ');
ft_putint(e);
if (d < 98)
{
ft_putchar(',');
ft_putchar(' ');
}
e++;
}
d++;
}
}
|
the_stack_data/34383.c | /* compress.c -- compress a memory buffer
* Copyright (C) 1995-2005 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id: compress.c,v 1.7 2010/04/21 20:36:23 drolon Exp $ */
#define ZLIB_INTERNAL
#include "zlib.h"
/* ===========================================================================
Compresses the source buffer into the destination buffer. The level
parameter has the same meaning as in deflateInit. sourceLen is the byte
length of the source buffer. Upon entry, destLen is the total size of the
destination buffer, which must be at least 0.1% larger than sourceLen plus
12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_BUF_ERROR if there was not enough room in the output buffer,
Z_STREAM_ERROR if the level parameter is invalid.
*/
int ZEXPORT compress2 (dest, destLen, source, sourceLen, level)
Bytef *dest;
uLongf *destLen;
const Bytef *source;
uLong sourceLen;
int level;
{
z_stream stream;
int err;
stream.next_in = (Bytef*)source;
stream.avail_in = (uInt)sourceLen;
#ifdef MAXSEG_64K
/* Check for source > 64K on 16-bit machine: */
if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
#endif
stream.next_out = dest;
stream.avail_out = (uInt)*destLen;
if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
stream.zalloc = (alloc_func)0;
stream.zfree = (free_func)0;
stream.opaque = (voidpf)0;
err = deflateInit(&stream, level);
if (err != Z_OK) return err;
err = deflate(&stream, Z_FINISH);
if (err != Z_STREAM_END) {
deflateEnd(&stream);
return err == Z_OK ? Z_BUF_ERROR : err;
}
*destLen = stream.total_out;
err = deflateEnd(&stream);
return err;
}
/* ===========================================================================
*/
int ZEXPORT compress (dest, destLen, source, sourceLen)
Bytef *dest;
uLongf *destLen;
const Bytef *source;
uLong sourceLen;
{
return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
}
/* ===========================================================================
If the default memLevel or windowBits for deflateInit() is changed, then
this function needs to be updated.
*/
uLong ZEXPORT compressBound (sourceLen)
uLong sourceLen;
{
return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
(sourceLen >> 25) + 13;
}
|
the_stack_data/159515328.c | // SPDX-License-Identifier: GPL-2.0
#ifdef HAVE_EVENTFD
/*
* Copyright (C) 2018 Davidlohr Bueso.
*
* This program benchmarks concurrent epoll_wait(2) monitoring multiple
* file descriptors under one or two load balancing models. The first,
* and default, is the single/combined queueing (which refers to a single
* epoll instance for N worker threads):
*
* |---> [worker A]
* |---> [worker B]
* [combined queue] .---> [worker C]
* |---> [worker D]
* |---> [worker E]
*
* While the second model, enabled via --multiq option, uses multiple
* queueing (which refers to one epoll instance per worker). For example,
* short lived tcp connections in a high throughput httpd server will
* ditribute the accept()'ing connections across CPUs. In this case each
* worker does a limited amount of processing.
*
* [queue A] ---> [worker]
* [queue B] ---> [worker]
* [queue C] ---> [worker]
* [queue D] ---> [worker]
* [queue E] ---> [worker]
*
* Naturally, the single queue will enforce more concurrency on the epoll
* instance, and can therefore scale poorly compared to multiple queues.
* However, this is a benchmark raw data and must be taken with a grain of
* salt when choosing how to make use of sys_epoll.
* Each thread has a number of private, nonblocking file descriptors,
* referred to as fdmap. A writer thread will constantly be writing to
* the fdmaps of all threads, minimizing each threads's chances of
* epoll_wait not finding any ready read events and blocking as this
* is not what we want to stress. The size of the fdmap can be adjusted
* by the user; enlarging the value will increase the chances of
* epoll_wait(2) blocking as the lineal writer thread will take "longer",
* at least at a high level.
*
* Note that because fds are private to each thread, this workload does
* not stress scenarios where multiple tasks are awoken per ready IO; ie:
* EPOLLEXCLUSIVE semantics.
*
* The end result/metric is throughput: number of ops/second where an
* operation consists of:
*
* epoll_wait(2) + [others]
*
* ... where [others] is the cost of re-adding the fd (EPOLLET),
* or rearming it (EPOLLONESHOT).
*
*
* The purpose of this is program is that it be useful for measuring
* kernel related changes to the sys_epoll, and not comparing different
* IO polling methods, for example. Hence everything is very adhoc and
* outputs raw microbenchmark numbers. Also this uses eventfd, similar
* tools tend to use pipes or sockets, but the result is the same.
*/
/* For the CLR_() macros */
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <inttypes.h>
#include <signal.h>
#include <stdlib.h>
#include <linux/compiler.h>
#include <linux/kernel.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/types.h>
#include <internal/cpumap.h>
#include <perf/cpumap.h>
#include "../util/stat.h"
#include <subcmd/parse-options.h>
#include "bench.h"
#include <err.h>
#define printinfo(fmt, arg...) \
do { if (__verbose) { printf(fmt, ## arg); fflush(stdout); } } while (0)
static unsigned int nthreads = 0;
static unsigned int nsecs = 8;
static bool wdone, done, __verbose, randomize, nonblocking;
/*
* epoll related shared variables.
*/
/* Maximum number of nesting allowed inside epoll sets */
#define EPOLL_MAXNESTS 4
static int epollfd;
static int *epollfdp;
static bool noaffinity;
static unsigned int nested = 0;
static bool et; /* edge-trigger */
static bool oneshot;
static bool multiq; /* use an epoll instance per thread */
/* amount of fds to monitor, per thread */
static unsigned int nfds = 64;
static pthread_mutex_t thread_lock;
static unsigned int threads_starting;
static struct stats throughput_stats;
static pthread_cond_t thread_parent, thread_worker;
struct worker {
int tid;
int epollfd; /* for --multiq */
pthread_t thread;
unsigned long ops;
int *fdmap;
};
static const struct option options[] = {
/* general benchmark options */
OPT_UINTEGER('t', "threads", &nthreads, "Specify amount of threads"),
OPT_UINTEGER('r', "runtime", &nsecs, "Specify runtime (in seconds)"),
OPT_UINTEGER('f', "nfds", &nfds, "Specify amount of file descriptors to monitor for each thread"),
OPT_BOOLEAN( 'n', "noaffinity", &noaffinity, "Disables CPU affinity"),
OPT_BOOLEAN('R', "randomize", &randomize, "Enable random write behaviour (default is lineal)"),
OPT_BOOLEAN( 'v', "verbose", &__verbose, "Verbose mode"),
/* epoll specific options */
OPT_BOOLEAN( 'm', "multiq", &multiq, "Use multiple epoll instances (one per thread)"),
OPT_BOOLEAN( 'B', "nonblocking", &nonblocking, "Nonblocking epoll_wait(2) behaviour"),
OPT_UINTEGER( 'N', "nested", &nested, "Nesting level epoll hierarchy (default is 0, no nesting)"),
OPT_BOOLEAN( 'S', "oneshot", &oneshot, "Use EPOLLONESHOT semantics"),
OPT_BOOLEAN( 'E', "edge", &et, "Use Edge-triggered interface (default is LT)"),
OPT_END()
};
static const char * const bench_epoll_wait_usage[] = {
"perf bench epoll wait <options>",
NULL
};
/*
* Arrange the N elements of ARRAY in random order.
* Only effective if N is much smaller than RAND_MAX;
* if this may not be the case, use a better random
* number generator. -- Ben Pfaff.
*/
static void shuffle(void *array, size_t n, size_t size)
{
char *carray = array;
void *aux;
size_t i;
if (n <= 1)
return;
aux = calloc(1, size);
if (!aux)
err(EXIT_FAILURE, "calloc");
for (i = 1; i < n; ++i) {
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
j *= size;
memcpy(aux, &carray[j], size);
memcpy(&carray[j], &carray[i*size], size);
memcpy(&carray[i*size], aux, size);
}
free(aux);
}
static void *workerfn(void *arg)
{
int fd, ret, r;
struct worker *w = (struct worker *) arg;
unsigned long ops = w->ops;
struct epoll_event ev;
uint64_t val;
int to = nonblocking? 0 : -1;
int efd = multiq ? w->epollfd : epollfd;
pthread_mutex_lock(&thread_lock);
threads_starting--;
if (!threads_starting)
pthread_cond_signal(&thread_parent);
pthread_cond_wait(&thread_worker, &thread_lock);
pthread_mutex_unlock(&thread_lock);
do {
/*
* Block undefinitely waiting for the IN event.
* In order to stress the epoll_wait(2) syscall,
* call it event per event, instead of a larger
* batch (max)limit.
*/
do {
ret = epoll_wait(efd, &ev, 1, to);
} while (ret < 0 && errno == EINTR);
if (ret < 0)
err(EXIT_FAILURE, "epoll_wait");
fd = ev.data.fd;
do {
r = read(fd, &val, sizeof(val));
} while (!done && (r < 0 && errno == EAGAIN));
if (et) {
ev.events = EPOLLIN | EPOLLET;
ret = epoll_ctl(efd, EPOLL_CTL_ADD, fd, &ev);
}
if (oneshot) {
/* rearm the file descriptor with a new event mask */
ev.events |= EPOLLIN | EPOLLONESHOT;
ret = epoll_ctl(efd, EPOLL_CTL_MOD, fd, &ev);
}
ops++;
} while (!done);
if (multiq)
close(w->epollfd);
w->ops = ops;
return NULL;
}
static void nest_epollfd(struct worker *w)
{
unsigned int i;
struct epoll_event ev;
int efd = multiq ? w->epollfd : epollfd;
if (nested > EPOLL_MAXNESTS)
nested = EPOLL_MAXNESTS;
epollfdp = calloc(nested, sizeof(*epollfdp));
if (!epollfdp)
err(EXIT_FAILURE, "calloc");
for (i = 0; i < nested; i++) {
epollfdp[i] = epoll_create(1);
if (epollfdp[i] < 0)
err(EXIT_FAILURE, "epoll_create");
}
ev.events = EPOLLHUP; /* anything */
ev.data.u64 = i; /* any number */
for (i = nested - 1; i; i--) {
if (epoll_ctl(epollfdp[i - 1], EPOLL_CTL_ADD,
epollfdp[i], &ev) < 0)
err(EXIT_FAILURE, "epoll_ctl");
}
if (epoll_ctl(efd, EPOLL_CTL_ADD, *epollfdp, &ev) < 0)
err(EXIT_FAILURE, "epoll_ctl");
}
static void toggle_done(int sig __maybe_unused,
siginfo_t *info __maybe_unused,
void *uc __maybe_unused)
{
/* inform all threads that we're done for the day */
done = true;
gettimeofday(&bench__end, NULL);
timersub(&bench__end, &bench__start, &bench__runtime);
}
static void print_summary(void)
{
unsigned long avg = avg_stats(&throughput_stats);
double stddev = stddev_stats(&throughput_stats);
printf("\nAveraged %ld operations/sec (+- %.2f%%), total secs = %d\n",
avg, rel_stddev_stats(stddev, avg),
(int)bench__runtime.tv_sec);
}
static int do_threads(struct worker *worker, struct perf_cpu_map *cpu)
{
pthread_attr_t thread_attr, *attrp = NULL;
cpu_set_t cpuset;
unsigned int i, j;
int ret = 0, events = EPOLLIN;
if (oneshot)
events |= EPOLLONESHOT;
if (et)
events |= EPOLLET;
printinfo("starting worker/consumer %sthreads%s\n",
noaffinity ? "":"CPU affinity ",
nonblocking ? " (nonblocking)":"");
if (!noaffinity)
pthread_attr_init(&thread_attr);
for (i = 0; i < nthreads; i++) {
struct worker *w = &worker[i];
if (multiq) {
w->epollfd = epoll_create(1);
if (w->epollfd < 0)
err(EXIT_FAILURE, "epoll_create");
if (nested)
nest_epollfd(w);
}
w->tid = i;
w->fdmap = calloc(nfds, sizeof(int));
if (!w->fdmap)
return 1;
for (j = 0; j < nfds; j++) {
int efd = multiq ? w->epollfd : epollfd;
struct epoll_event ev;
w->fdmap[j] = eventfd(0, EFD_NONBLOCK);
if (w->fdmap[j] < 0)
err(EXIT_FAILURE, "eventfd");
ev.data.fd = w->fdmap[j];
ev.events = events;
ret = epoll_ctl(efd, EPOLL_CTL_ADD,
w->fdmap[j], &ev);
if (ret < 0)
err(EXIT_FAILURE, "epoll_ctl");
}
if (!noaffinity) {
CPU_ZERO(&cpuset);
CPU_SET(cpu->map[i % cpu->nr], &cpuset);
ret = pthread_attr_setaffinity_np(&thread_attr, sizeof(cpu_set_t), &cpuset);
if (ret)
err(EXIT_FAILURE, "pthread_attr_setaffinity_np");
attrp = &thread_attr;
}
ret = pthread_create(&w->thread, attrp, workerfn,
(void *)(struct worker *) w);
if (ret)
err(EXIT_FAILURE, "pthread_create");
}
if (!noaffinity)
pthread_attr_destroy(&thread_attr);
return ret;
}
static void *writerfn(void *p)
{
struct worker *worker = p;
size_t i, j, iter;
const uint64_t val = 1;
ssize_t sz;
struct timespec ts = { .tv_sec = 0,
.tv_nsec = 500 };
printinfo("starting writer-thread: doing %s writes ...\n",
randomize? "random":"lineal");
for (iter = 0; !wdone; iter++) {
if (randomize) {
shuffle((void *)worker, nthreads, sizeof(*worker));
}
for (i = 0; i < nthreads; i++) {
struct worker *w = &worker[i];
if (randomize) {
shuffle((void *)w->fdmap, nfds, sizeof(int));
}
for (j = 0; j < nfds; j++) {
do {
sz = write(w->fdmap[j], &val, sizeof(val));
} while (!wdone && (sz < 0 && errno == EAGAIN));
}
}
nanosleep(&ts, NULL);
}
printinfo("exiting writer-thread (total full-loops: %zd)\n", iter);
return NULL;
}
static int cmpworker(const void *p1, const void *p2)
{
struct worker *w1 = (struct worker *) p1;
struct worker *w2 = (struct worker *) p2;
return w1->tid > w2->tid;
}
int bench_epoll_wait(int argc, const char **argv)
{
int ret = 0;
struct sigaction act;
unsigned int i;
struct worker *worker = NULL;
struct perf_cpu_map *cpu;
pthread_t wthread;
struct rlimit rl, prevrl;
argc = parse_options(argc, argv, options, bench_epoll_wait_usage, 0);
if (argc) {
usage_with_options(bench_epoll_wait_usage, options);
exit(EXIT_FAILURE);
}
memset(&act, 0, sizeof(act));
sigfillset(&act.sa_mask);
act.sa_sigaction = toggle_done;
sigaction(SIGINT, &act, NULL);
cpu = perf_cpu_map__new(NULL);
if (!cpu)
goto errmem;
/* a single, main epoll instance */
if (!multiq) {
epollfd = epoll_create(1);
if (epollfd < 0)
err(EXIT_FAILURE, "epoll_create");
/*
* Deal with nested epolls, if any.
*/
if (nested)
nest_epollfd(NULL);
}
printinfo("Using %s queue model\n", multiq ? "multi" : "single");
printinfo("Nesting level(s): %d\n", nested);
/* default to the number of CPUs and leave one for the writer pthread */
if (!nthreads)
nthreads = cpu->nr - 1;
worker = calloc(nthreads, sizeof(*worker));
if (!worker) {
goto errmem;
}
if (getrlimit(RLIMIT_NOFILE, &prevrl))
err(EXIT_FAILURE, "getrlimit");
rl.rlim_cur = rl.rlim_max = nfds * nthreads * 2 + 50;
printinfo("Setting RLIMIT_NOFILE rlimit from %" PRIu64 " to: %" PRIu64 "\n",
(uint64_t)prevrl.rlim_max, (uint64_t)rl.rlim_max);
if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
err(EXIT_FAILURE, "setrlimit");
printf("Run summary [PID %d]: %d threads monitoring%s on "
"%d file-descriptors for %d secs.\n\n",
getpid(), nthreads, oneshot ? " (EPOLLONESHOT semantics)": "", nfds, nsecs);
init_stats(&throughput_stats);
pthread_mutex_init(&thread_lock, NULL);
pthread_cond_init(&thread_parent, NULL);
pthread_cond_init(&thread_worker, NULL);
threads_starting = nthreads;
gettimeofday(&bench__start, NULL);
do_threads(worker, cpu);
pthread_mutex_lock(&thread_lock);
while (threads_starting)
pthread_cond_wait(&thread_parent, &thread_lock);
pthread_cond_broadcast(&thread_worker);
pthread_mutex_unlock(&thread_lock);
/*
* At this point the workers should be blocked waiting for read events
* to become ready. Launch the writer which will constantly be writing
* to each thread's fdmap.
*/
ret = pthread_create(&wthread, NULL, writerfn,
(void *)(struct worker *) worker);
if (ret)
err(EXIT_FAILURE, "pthread_create");
sleep(nsecs);
toggle_done(0, NULL, NULL);
printinfo("main thread: toggling done\n");
sleep(1); /* meh */
wdone = true;
ret = pthread_join(wthread, NULL);
if (ret)
err(EXIT_FAILURE, "pthread_join");
/* cleanup & report results */
pthread_cond_destroy(&thread_parent);
pthread_cond_destroy(&thread_worker);
pthread_mutex_destroy(&thread_lock);
/* sort the array back before reporting */
if (randomize)
qsort(worker, nthreads, sizeof(struct worker), cmpworker);
for (i = 0; i < nthreads; i++) {
unsigned long t = worker[i].ops / bench__runtime.tv_sec;
update_stats(&throughput_stats, t);
if (nfds == 1)
printf("[thread %2d] fdmap: %p [ %04ld ops/sec ]\n",
worker[i].tid, &worker[i].fdmap[0], t);
else
printf("[thread %2d] fdmap: %p ... %p [ %04ld ops/sec ]\n",
worker[i].tid, &worker[i].fdmap[0],
&worker[i].fdmap[nfds-1], t);
}
print_summary();
close(epollfd);
return ret;
errmem:
err(EXIT_FAILURE, "calloc");
}
#endif // HAVE_EVENTFD
|
the_stack_data/85905.c | // UBSAN: undefined-behaviour in hash_ipmac_create
// https://syzkaller.appspot.com/bug?id=f1f14b9d6fcde8864036
// status:0
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#define BITMASK(bf_off, bf_len) (((1ull << (bf_len)) - 1) << (bf_off))
#define STORE_BY_BITMASK(type, htobe, addr, val, bf_off, bf_len) \
*(type*)(addr) = \
htobe((htobe(*(type*)(addr)) & ~BITMASK((bf_off), (bf_len))) | \
(((type)(val) << (bf_off)) & BITMASK((bf_off), (bf_len))))
uint64_t r[2] = {0xffffffffffffffff, 0xffffffffffffffff};
int main(void)
{
syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
intptr_t res = 0;
res = syscall(__NR_pipe, 0x20000080ul);
if (res != -1) {
r[0] = *(uint32_t*)0x20000080;
r[1] = *(uint32_t*)0x20000084;
}
*(uint64_t*)0x200000c0 = 0x20000180;
memcpy((void*)0x20000180, "\x77\x69\x0a\xdd\xcf\xbe\x1f\xbb\x66\xec", 10);
*(uint64_t*)0x200000c8 = 0xff3b;
syscall(__NR_vmsplice, r[1], 0x200000c0ul, 1ul, 1ul);
syscall(__NR_close, r[1]);
syscall(__NR_socket, 0x10ul, 3ul, 0xc);
*(uint64_t*)0x200000c0 = 0;
*(uint32_t*)0x200000c8 = 0;
*(uint64_t*)0x200000d0 = 0x20000080;
*(uint64_t*)0x20000080 = 0x20000180;
*(uint32_t*)0x20000180 = 0x54;
*(uint8_t*)0x20000184 = 2;
*(uint8_t*)0x20000185 = 6;
*(uint16_t*)0x20000186 = 0x801;
*(uint32_t*)0x20000188 = 0;
*(uint32_t*)0x2000018c = 0;
*(uint8_t*)0x20000190 = 0;
*(uint8_t*)0x20000191 = 0;
*(uint16_t*)0x20000192 = htobe16(0);
*(uint16_t*)0x20000194 = 0x10;
*(uint16_t*)0x20000196 = 3;
memcpy((void*)0x20000198, "hash:ip,mac\000", 12);
*(uint16_t*)0x200001a4 = 5;
*(uint16_t*)0x200001a6 = 4;
*(uint8_t*)0x200001a8 = 0;
*(uint16_t*)0x200001ac = 9;
*(uint16_t*)0x200001ae = 2;
memcpy((void*)0x200001b0, "syz1\000", 5);
*(uint16_t*)0x200001b8 = 5;
*(uint16_t*)0x200001ba = 1;
*(uint8_t*)0x200001bc = 6;
*(uint16_t*)0x200001c0 = 5;
*(uint16_t*)0x200001c2 = 5;
*(uint8_t*)0x200001c4 = 0xa;
*(uint16_t*)0x200001c8 = 0xc;
STORE_BY_BITMASK(uint16_t, , 0x200001ca, 7, 0, 14);
STORE_BY_BITMASK(uint16_t, , 0x200001cb, 0, 6, 1);
STORE_BY_BITMASK(uint16_t, , 0x200001cb, 1, 7, 1);
*(uint16_t*)0x200001cc = 8;
STORE_BY_BITMASK(uint16_t, , 0x200001ce, 0x12, 0, 14);
STORE_BY_BITMASK(uint16_t, , 0x200001cf, 1, 6, 1);
STORE_BY_BITMASK(uint16_t, , 0x200001cf, 0, 7, 1);
*(uint32_t*)0x200001d0 = htobe32(0xfffffffe);
*(uint64_t*)0x20000088 = 0x54;
*(uint64_t*)0x200000d8 = 1;
*(uint64_t*)0x200000e0 = 0;
*(uint64_t*)0x200000e8 = 0;
*(uint32_t*)0x200000f0 = 0;
syscall(__NR_sendmsg, -1, 0x200000c0ul, 0ul);
syscall(__NR_splice, r[0], 0ul, r[1], 0ul, 0x100000000ul, 0ul);
return 0;
}
|
the_stack_data/90764260.c | /* strtoull( const char *, char **, int )
This file is part of the Public Domain C Library (PDCLib).
Permission is granted to use, modify, and / or redistribute at will.
*/
#include <limits.h>
#include <stdlib.h>
#ifndef REGTEST
#include <stdint.h>
unsigned long long int strtoull( const char * s, char ** endptr, int base )
{
unsigned long long int rc;
char sign = '+';
const char * p = _PDCLIB_strtox_prelim( s, &sign, &base );
if ( base < 2 || base > 36 )
{
return 0;
}
rc = _PDCLIB_strtox_main( &p, ( unsigned )base, ( uintmax_t )ULLONG_MAX, ( uintmax_t )( ULLONG_MAX / base ), ( int )( ULLONG_MAX % base ), &sign );
if ( endptr != NULL )
{
*endptr = ( p != NULL ) ? ( char * ) p : ( char * ) s;
}
return ( sign == '+' ) ? rc : -rc;
}
#endif
#ifdef TEST
#include "_PDCLIB_test.h"
#include <errno.h>
int main( void )
{
char * endptr;
/* this, to base 36, overflows even a 256 bit integer */
char overflow[] = "-ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ_";
/* tricky border case */
char tricky[] = "+0xz";
errno = 0;
/* basic functionality */
TESTCASE( strtoull( "123", NULL, 10 ) == 123 );
/* proper detecting of default base 10 */
TESTCASE( strtoull( "456", NULL, 0 ) == 456 );
/* proper functioning to smaller base */
TESTCASE( strtoull( "14", NULL, 8 ) == 12 );
/* proper autodetecting of octal */
TESTCASE( strtoull( "016", NULL, 0 ) == 14 );
/* proper autodetecting of hexadecimal, lowercase 'x' */
TESTCASE( strtoull( "0xFF", NULL, 0 ) == 255 );
/* proper autodetecting of hexadecimal, uppercase 'X' */
TESTCASE( strtoull( "0Xa1", NULL, 0 ) == 161 );
/* proper handling of border case: 0x followed by non-hexdigit */
TESTCASE( strtoull( tricky, &endptr, 0 ) == 0 );
/* newlib completely balks at this parse, so we _NOREG it */
TESTCASE_NOREG( endptr == tricky + 2 );
/* proper handling of border case: 0 followed by non-octdigit */
TESTCASE( strtoull( tricky, &endptr, 8 ) == 0 );
TESTCASE( endptr == tricky + 2 );
/* errno should still be 0 */
TESTCASE( errno == 0 );
/* correctly decoding zero */
TESTCASE( strtoull( "0", &endptr, 0 ) == 0 );
TESTCASE( *endptr == '\0' );
TESTCASE( errno == 0 );
/* overflowing subject sequence must still return proper endptr */
TESTCASE( strtoull( overflow, &endptr, 36 ) == ULLONG_MAX );
TESTCASE( errno == ERANGE );
TESTCASE( ( endptr - overflow ) == 53 );
/* same for positive */
errno = 0;
TESTCASE( strtoull( overflow + 1, &endptr, 36 ) == ULLONG_MAX );
TESTCASE( errno == ERANGE );
TESTCASE( ( endptr - overflow ) == 53 );
/* testing skipping of leading whitespace */
TESTCASE( strtoull( " \n\v\t\f789", NULL, 0 ) == 789 );
/* testing conversion failure */
TESTCASE( strtoull( overflow, &endptr, 10 ) == 0 );
TESTCASE( endptr == overflow );
endptr = NULL;
TESTCASE( strtoull( overflow, &endptr, 0 ) == 0 );
TESTCASE( endptr == overflow );
errno = 0;
/* long long -> 64 bit */
#if ULLONG_MAX >> 63 == 1
/* testing "even" overflow, i.e. base is power of two */
TESTCASE( strtoull( "18446744073709551615", NULL, 0 ) == ULLONG_MAX );
TESTCASE( errno == 0 );
TESTCASE( strtoull( "18446744073709551616", NULL, 0 ) == ULLONG_MAX );
TESTCASE( errno == ERANGE );
/* TODO: test "odd" overflow, i.e. base is not power of two */
/* long long -> 128 bit */
#elif ULLONG_MAX >> 127 == 1
/* testing "even" overflow, i.e. base is power of two */
TESTCASE( strtoull( "340282366920938463463374607431768211455", NULL, 0 ) == ULLONG_MAX );
TESTCASE( errno == 0 );
TESTCASE( strtoull( "340282366920938463463374607431768211456", NULL, 0 ) == ULLONG_MAX );
TESTCASE( errno == ERANGE );
/* TODO: test "odd" overflow, i.e. base is not power of two */
#else
#error Unsupported width of 'long long' (neither 64 nor 128 bit).
#endif
return TEST_RESULTS;
}
#endif
|
the_stack_data/104038.c | int main() {
labelOne:;
int x = 123;
if (x > 23) goto labelTwo;
else goto labelThree;
int y = 321;
labelTwo:
y += x;
labelThree:
return x * y;
}
|
the_stack_data/48574163.c | //Zombie Process
#include <sys/types.h>
#include <unistd.h>
#include<stdio.h>
#include <stdlib.h>
int main()
{pid_t child_pid = fork();
if (child_pid > 0)
sleep(40);
else
exit(0);
return 0;} |
the_stack_data/918091.c | static const char ident[] = "@(#) $Header: /cvstrac/cvstrac/makeheaders.c,v 1.4 2005/03/16 22:17:51 drh Exp $";
/*
** This program is free software; you can redistribute it and/or
** modify it under the terms of the Simplified BSD License (also
** known as the "2-Clause License" or "FreeBSD License".)
**
** Copyright 1993 D. Richard Hipp. 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.
**
** This software is provided "as is" and any express or implied warranties,
** including, but not limited to, the implied warranties of merchantability
** and fitness for a particular purpose are disclaimed. In no event shall
** the author or contributors be liable for any direct, indirect, incidental,
** special, exemplary, or consequential damages (including, but not limited
** to, procurement of substitute goods or services; loss of use, data or
** profits; or business interruption) however caused and on any theory of
** liability, whether in contract, strict liability, or tort (including
** negligence or otherwise) arising in any way out of the use of this
** software, even if advised of the possibility of such damage.
**
** 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.
** appropriate header files.
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <memory.h>
#include <sys/stat.h>
#include <assert.h>
#if defined( __MINGW32__) || defined(__DMC__) || defined(_MSC_VER) || defined(__POCC__)
# ifndef WIN32
# define WIN32
# endif
# include <string.h>
#else
# include <unistd.h>
#endif
/*
** Macros for debugging.
*/
#ifdef DEBUG
static int debugMask = 0;
# define debug0(F,M) if( (F)&debugMask ){ fprintf(stderr,M); }
# define debug1(F,M,A) if( (F)&debugMask ){ fprintf(stderr,M,A); }
# define debug2(F,M,A,B) if( (F)&debugMask ){ fprintf(stderr,M,A,B); }
# define debug3(F,M,A,B,C) if( (F)&debugMask ){ fprintf(stderr,M,A,B,C); }
# define PARSER 0x00000001
# define DECL_DUMP 0x00000002
# define TOKENIZER 0x00000004
#else
# define debug0(Flags, Format)
# define debug1(Flags, Format, A)
# define debug2(Flags, Format, A, B)
# define debug3(Flags, Format, A, B, C)
#endif
/*
** The following macros are purely for the purpose of testing this
** program on itself. They don't really contribute to the code.
*/
#define INTERFACE 1
#define EXPORT_INTERFACE 1
#define EXPORT
/*
** Each token in a source file is represented by an instance of
** the following structure. Tokens are collected onto a list.
*/
typedef struct Token Token;
struct Token {
const char *zText; /* The text of the token */
int nText; /* Number of characters in the token's text */
int eType; /* The type of this token */
int nLine; /* The line number on which the token starts */
Token *pComment; /* Most recent block comment before this token */
Token *pNext; /* Next token on the list */
Token *pPrev; /* Previous token on the list */
};
/*
** During tokenization, information about the state of the input
** stream is held in an instance of the following structure
*/
typedef struct InStream InStream;
struct InStream {
const char *z; /* Complete text of the input */
int i; /* Next character to read from the input */
int nLine; /* The line number for character z[i] */
};
/*
** Each declaration in the C or C++ source files is parsed out and stored as
** an instance of the following structure.
**
** A "forward declaration" is a declaration that an object exists that
** doesn't tell about the objects structure. A typical forward declaration
** is:
**
** struct Xyzzy;
**
** Not every object has a forward declaration. If it does, thought, the
** forward declaration will be contained in the zFwd field for C and
** the zFwdCpp for C++. The zDecl field contains the complete
** declaration text.
*/
typedef struct Decl Decl;
struct Decl {
char *zName; /* Name of the object being declared. The appearance
** of this name is a source file triggers the declaration
** to be added to the header for that file. */
char *zFile; /* File from which extracted. */
char *zIf; /* Surround the declaration with this #if */
char *zFwd; /* A forward declaration. NULL if there is none. */
char *zFwdCpp; /* Use this forward declaration for C++. */
char *zDecl; /* A full declaration of this object */
char *zExtra; /* Extra declaration text inserted into class objects */
int extraType; /* Last public:, protected: or private: in zExtraDecl */
struct Include *pInclude; /* #includes that come before this declaration */
int flags; /* See the "Properties" below */
Token *pComment; /* A block comment associated with this declaration */
Token tokenCode; /* Implementation of functions and procedures */
Decl *pSameName; /* Next declaration with the same "zName" */
Decl *pSameHash; /* Next declaration with same hash but different zName */
Decl *pNext; /* Next declaration with a different name */
};
/*
** Properties associated with declarations.
**
** DP_Forward and DP_Declared are used during the generation of a single
** header file in order to prevent duplicate declarations and definitions.
** DP_Forward is set after the object has been given a forward declaration
** and DP_Declared is set after the object gets a full declarations.
** (Example: A forward declaration is "typedef struct Abc Abc;" and the
** full declaration is "struct Abc { int a; float b; };".)
**
** The DP_Export and DP_Local flags are more permanent. They mark objects
** that have EXPORT scope and LOCAL scope respectively. If both of these
** marks are missing, then the object has library scope. The meanings of
** the scopes are as follows:
**
** LOCAL scope The object is only usable within the file in
** which it is declared.
**
** library scope The object is visible and usable within other
** files in the same project. By if the project is
** a library, then the object is not visible to users
** of the library. (i.e. the object does not appear
** in the output when using the -H option.)
**
** EXPORT scope The object is visible and usable everywhere.
**
** The DP_Flag is a temporary use flag that is used during processing to
** prevent an infinite loop. It's use is localized.
**
** The DP_Cplusplus, DP_ExternCReqd and DP_ExternReqd flags are permanent
** and are used to specify what type of declaration the object requires.
*/
#define DP_Forward 0x001 /* Has a forward declaration in this file */
#define DP_Declared 0x002 /* Has a full declaration in this file */
#define DP_Export 0x004 /* Export this declaration */
#define DP_Local 0x008 /* Declare in its home file only */
#define DP_Flag 0x010 /* Use to mark a subset of a Decl list
** for special processing */
#define DP_Cplusplus 0x020 /* Has C++ linkage and cannot appear in a
** C header file */
#define DP_ExternCReqd 0x040 /* Prepend 'extern "C"' in a C++ header.
** Prepend nothing in a C header */
#define DP_ExternReqd 0x080 /* Prepend 'extern "C"' in a C++ header if
** DP_Cplusplus is not also set. If DP_Cplusplus
** is set or this is a C header then
** prepend 'extern' */
/*
** Convenience macros for dealing with declaration properties
*/
#define DeclHasProperty(D,P) (((D)->flags&(P))==(P))
#define DeclHasAnyProperty(D,P) (((D)->flags&(P))!=0)
#define DeclSetProperty(D,P) (D)->flags |= (P)
#define DeclClearProperty(D,P) (D)->flags &= ~(P)
/*
** These are state properties of the parser. Each of the values is
** distinct from the DP_ values above so that both can be used in
** the same "flags" field.
**
** Be careful not to confuse PS_Export with DP_Export or
** PS_Local with DP_Local. Their names are similar, but the meanings
** of these flags are very different.
*/
#define PS_Extern 0x000800 /* "extern" has been seen */
#define PS_Export 0x001000 /* If between "#if EXPORT_INTERFACE"
** and "#endif" */
#define PS_Export2 0x002000 /* If "EXPORT" seen */
#define PS_Typedef 0x004000 /* If "typedef" has been seen */
#define PS_Static 0x008000 /* If "static" has been seen */
#define PS_Interface 0x010000 /* If within #if INTERFACE..#endif */
#define PS_Method 0x020000 /* If "::" token has been seen */
#define PS_Local 0x040000 /* If within #if LOCAL_INTERFACE..#endif */
#define PS_Local2 0x080000 /* If "LOCAL" seen. */
#define PS_Public 0x100000 /* If "PUBLIC" seen. */
#define PS_Protected 0x200000 /* If "PROTECTED" seen. */
#define PS_Private 0x400000 /* If "PRIVATE" seen. */
#define PS_PPP 0x700000 /* If any of PUBLIC, PRIVATE, PROTECTED */
/*
** The following set of flags are ORed into the "flags" field of
** a Decl in order to identify what type of object is being
** declared.
*/
#define TY_Class 0x00100000
#define TY_Subroutine 0x00200000
#define TY_Macro 0x00400000
#define TY_Typedef 0x00800000
#define TY_Variable 0x01000000
#define TY_Structure 0x02000000
#define TY_Union 0x04000000
#define TY_Enumeration 0x08000000
#define TY_Defunct 0x10000000 /* Used to erase a declaration */
/*
** Each nested #if (or #ifdef or #ifndef) is stored in a stack of
** instances of the following structure.
*/
typedef struct Ifmacro Ifmacro;
struct Ifmacro {
int nLine; /* Line number where this macro occurs */
char *zCondition; /* Text of the condition for this macro */
Ifmacro *pNext; /* Next down in the stack */
int flags; /* Can hold PS_Export, PS_Interface or PS_Local flags */
};
/*
** When parsing a file, we need to keep track of what other files have
** be #include-ed. For each #include found, we create an instance of
** the following structure.
*/
typedef struct Include Include;
struct Include {
char *zFile; /* The name of file include. Includes "" or <> */
char *zIf; /* If not NULL, #include should be enclosed in #if */
char *zLabel; /* A unique label used to test if this #include has
* appeared already in a file or not */
Include *pNext; /* Previous include file, or NULL if this is the first */
};
/*
** Identifiers found in a source file that might be used later to provoke
** the copying of a declaration into the corresponding header file are
** stored in a hash table as instances of the following structure.
*/
typedef struct Ident Ident;
struct Ident {
char *zName; /* The text of this identifier */
Ident *pCollide; /* Next identifier with the same hash */
Ident *pNext; /* Next identifier in a list of them all */
};
/*
** A complete table of identifiers is stored in an instance of
** the next structure.
*/
#define IDENT_HASH_SIZE 2237
typedef struct IdentTable IdentTable;
struct IdentTable {
Ident *pList; /* List of all identifiers in this table */
Ident *apTable[IDENT_HASH_SIZE]; /* The hash table */
};
/*
** The following structure holds all information for a single
** source file named on the command line of this program.
*/
typedef struct InFile InFile;
struct InFile {
char *zSrc; /* Name of input file */
char *zHdr; /* Name of the generated .h file for this input.
** Will be NULL if input is to be scanned only */
int flags; /* One or more DP_, PS_ and/or TY_ flags */
InFile *pNext; /* Next input file in the list of them all */
IdentTable idTable; /* All identifiers in this input file */
};
/*
** An unbounded string is able to grow without limit. We use these
** to construct large in-memory strings from lots of smaller components.
*/
typedef struct String String;
struct String {
int nAlloc; /* Number of bytes allocated */
int nUsed; /* Number of bytes used (not counting null terminator) */
char *zText; /* Text of the string */
};
/*
** The following structure contains a lot of state information used
** while generating a .h file. We put the information in this structure
** and pass around a pointer to this structure, rather than pass around
** all of the information separately. This helps reduce the number of
** arguments to generator functions.
*/
typedef struct GenState GenState;
struct GenState {
String *pStr; /* Write output to this string */
IdentTable *pTable; /* A table holding the zLabel of every #include that
* has already been generated. Used to avoid
* generating duplicate #includes. */
const char *zIf; /* If not NULL, then we are within a #if with
* this argument. */
int nErr; /* Number of errors */
const char *zFilename; /* Name of the source file being scanned */
int flags; /* Various flags (DP_ and PS_ flags above) */
};
/*
** The following text line appears at the top of every file generated
** by this program. By recognizing this line, the program can be sure
** never to read a file that it generated itself.
*/
const char zTopLine[] =
"/* \aThis file was automatically generated. Do not edit! */\n";
#define nTopLine (sizeof(zTopLine)-1)
/*
** The name of the file currently being parsed.
*/
static char *zFilename;
/*
** The stack of #if macros for the file currently being parsed.
*/
static Ifmacro *ifStack = 0;
/*
** A list of all files that have been #included so far in a file being
** parsed.
*/
static Include *includeList = 0;
/*
** The last block comment seen.
*/
static Token *blockComment = 0;
/*
** The following flag is set if the -doc flag appears on the
** command line.
*/
static int doc_flag = 0;
/*
** If the following flag is set, then makeheaders will attempt to
** generate prototypes for static functions and procedures.
*/
static int proto_static = 0;
/*
** A list of all declarations. The list is held together using the
** pNext field of the Decl structure.
*/
static Decl *pDeclFirst; /* First on the list */
static Decl *pDeclLast; /* Last on the list */
/*
** A hash table of all declarations
*/
#define DECL_HASH_SIZE 3371
static Decl *apTable[DECL_HASH_SIZE];
/*
** The TEST macro must be defined to something. Make sure this is the
** case.
*/
#ifndef TEST
# define TEST 0
#endif
#ifdef NOT_USED
/*
** We do our own assertion macro so that we can have more control
** over debugging.
*/
#define Assert(X) if(!(X)){ CantHappen(__LINE__); }
#define CANT_HAPPEN CantHappen(__LINE__)
static void CantHappen(int iLine){
fprintf(stderr,"Assertion failed on line %d\n",iLine);
*(char*)1 = 0; /* Force a core-dump */
}
#endif
/*
** Memory allocation functions that are guaranteed never to return NULL.
*/
static void *SafeMalloc(int nByte){
void *p = malloc( nByte );
if( p==0 ){
fprintf(stderr,"Out of memory. Can't allocate %d bytes.\n",nByte);
exit(1);
}
return p;
}
static void SafeFree(void *pOld){
if( pOld ){
free(pOld);
}
}
static void *SafeRealloc(void *pOld, int nByte){
void *p;
if( pOld==0 ){
p = SafeMalloc(nByte);
}else{
p = realloc(pOld, nByte);
if( p==0 ){
fprintf(stderr,
"Out of memory. Can't enlarge an allocation to %d bytes\n",nByte);
exit(1);
}
}
return p;
}
static char *StrDup(const char *zSrc, int nByte){
char *zDest;
if( nByte<=0 ){
nByte = strlen(zSrc);
}
zDest = SafeMalloc( nByte + 1 );
strncpy(zDest,zSrc,nByte);
zDest[nByte] = 0;
return zDest;
}
/*
** Return TRUE if the character X can be part of an identifier
*/
#define ISALNUM(X) ((X)=='_' || isalnum(X))
/*
** Routines for dealing with unbounded strings.
*/
static void StringInit(String *pStr){
pStr->nAlloc = 0;
pStr->nUsed = 0;
pStr->zText = 0;
}
static void StringReset(String *pStr){
SafeFree(pStr->zText);
StringInit(pStr);
}
static void StringAppend(String *pStr, const char *zText, int nByte){
if( nByte<=0 ){
nByte = strlen(zText);
}
if( pStr->nUsed + nByte >= pStr->nAlloc ){
if( pStr->nAlloc==0 ){
pStr->nAlloc = nByte + 100;
pStr->zText = SafeMalloc( pStr->nAlloc );
}else{
pStr->nAlloc = pStr->nAlloc*2 + nByte;
pStr->zText = SafeRealloc(pStr->zText, pStr->nAlloc);
}
}
strncpy(&pStr->zText[pStr->nUsed],zText,nByte);
pStr->nUsed += nByte;
pStr->zText[pStr->nUsed] = 0;
}
#define StringGet(S) ((S)->zText?(S)->zText:"")
/*
** Compute a hash on a string. The number returned is a non-negative
** value between 0 and 2**31 - 1
*/
static int Hash(const char *z, int n){
int h = 0;
if( n<=0 ){
n = strlen(z);
}
while( n-- ){
h = h ^ (h<<5) ^ *z++;
}
return h & 0x7fffffff;
}
/*
** Given an identifier name, try to find a declaration for that
** identifier in the hash table. If found, return a pointer to
** the Decl structure. If not found, return 0.
*/
static Decl *FindDecl(const char *zName, int len){
int h;
Decl *p;
if( len<=0 ){
len = strlen(zName);
}
h = Hash(zName,len) % DECL_HASH_SIZE;
p = apTable[h];
while( p && (strncmp(p->zName,zName,len)!=0 || p->zName[len]!=0) ){
p = p->pSameHash;
}
return p;
}
/*
** Install the given declaration both in the hash table and on
** the list of all declarations.
*/
static void InstallDecl(Decl *pDecl){
int h;
Decl *pOther;
h = Hash(pDecl->zName,0) % DECL_HASH_SIZE;
pOther = apTable[h];
while( pOther && strcmp(pDecl->zName,pOther->zName)!=0 ){
pOther = pOther->pSameHash;
}
if( pOther ){
pDecl->pSameName = pOther->pSameName;
pOther->pSameName = pDecl;
}else{
pDecl->pSameName = 0;
pDecl->pSameHash = apTable[h];
apTable[h] = pDecl;
}
pDecl->pNext = 0;
if( pDeclFirst==0 ){
pDeclFirst = pDeclLast = pDecl;
}else{
pDeclLast->pNext = pDecl;
pDeclLast = pDecl;
}
}
/*
** Look at the current ifStack. If anything declared at the current
** position must be surrounded with
**
** #if STUFF
** #endif
**
** Then this routine computes STUFF and returns a pointer to it. Memory
** to hold the value returned is obtained from malloc().
*/
static char *GetIfString(void){
Ifmacro *pIf;
char *zResult = 0;
int hasIf = 0;
String str;
for(pIf = ifStack; pIf; pIf=pIf->pNext){
if( pIf->zCondition==0 || *pIf->zCondition==0 ) continue;
if( !hasIf ){
hasIf = 1;
StringInit(&str);
}else{
StringAppend(&str," && ",4);
}
StringAppend(&str,pIf->zCondition,0);
}
if( hasIf ){
zResult = StrDup(StringGet(&str),0);
StringReset(&str);
}else{
zResult = 0;
}
return zResult;
}
/*
** Create a new declaration and put it in the hash table. Also
** return a pointer to it so that we can fill in the zFwd and zDecl
** fields, and so forth.
*/
static Decl *CreateDecl(
const char *zName, /* Name of the object being declared. */
int nName /* Length of the name */
){
Decl *pDecl;
pDecl = SafeMalloc( sizeof(Decl) + nName + 1);
memset(pDecl,0,sizeof(Decl));
pDecl->zName = (char*)&pDecl[1];
sprintf(pDecl->zName,"%.*s",nName,zName);
pDecl->zFile = zFilename;
pDecl->pInclude = includeList;
pDecl->zIf = GetIfString();
InstallDecl(pDecl);
return pDecl;
}
/*
** Insert a new identifier into an table of identifiers. Return TRUE if
** a new identifier was inserted and return FALSE if the identifier was
** already in the table.
*/
static int IdentTableInsert(
IdentTable *pTable, /* The table into which we will insert */
const char *zId, /* Name of the identifiers */
int nId /* Length of the identifier name */
){
int h;
Ident *pId;
if( nId<=0 ){
nId = strlen(zId);
}
h = Hash(zId,nId) % IDENT_HASH_SIZE;
for(pId = pTable->apTable[h]; pId; pId=pId->pCollide){
if( strncmp(zId,pId->zName,nId)==0 && pId->zName[nId]==0 ){
/* printf("Already in table: %.*s\n",nId,zId); */
return 0;
}
}
pId = SafeMalloc( sizeof(Ident) + nId + 1 );
pId->zName = (char*)&pId[1];
sprintf(pId->zName,"%.*s",nId,zId);
pId->pNext = pTable->pList;
pTable->pList = pId;
pId->pCollide = pTable->apTable[h];
pTable->apTable[h] = pId;
/* printf("Add to table: %.*s\n",nId,zId); */
return 1;
}
/*
** Check to see if the given value is in the given IdentTable. Return
** true if it is and false if it is not.
*/
static int IdentTableTest(
IdentTable *pTable, /* The table in which to search */
const char *zId, /* Name of the identifiers */
int nId /* Length of the identifier name */
){
int h;
Ident *pId;
if( nId<=0 ){
nId = strlen(zId);
}
h = Hash(zId,nId) % IDENT_HASH_SIZE;
for(pId = pTable->apTable[h]; pId; pId=pId->pCollide){
if( strncmp(zId,pId->zName,nId)==0 && pId->zName[nId]==0 ){
return 1;
}
}
return 0;
}
/*
** Remove every identifier from the given table. Reset the table to
** its initial state.
*/
static void IdentTableReset(IdentTable *pTable){
Ident *pId, *pNext;
for(pId = pTable->pList; pId; pId = pNext){
pNext = pId->pNext;
SafeFree(pId);
}
memset(pTable,0,sizeof(IdentTable));
}
#ifdef DEBUG
/*
** Print the name of every identifier in the given table, one per line
*/
static void IdentTablePrint(IdentTable *pTable, FILE *pOut){
Ident *pId;
for(pId = pTable->pList; pId; pId = pId->pNext){
fprintf(pOut,"%s\n",pId->zName);
}
}
#endif
/*
** Read an entire file into memory. Return a pointer to the memory.
**
** The memory is obtained from SafeMalloc and must be freed by the
** calling function.
**
** If the read fails for any reason, 0 is returned.
*/
static char *ReadFile(const char *zFilename){
struct stat sStat;
FILE *pIn;
char *zBuf;
int n;
if( stat(zFilename,&sStat)!=0
#ifndef WIN32
|| !S_ISREG(sStat.st_mode)
#endif
){
return 0;
}
pIn = fopen(zFilename,"r");
if( pIn==0 ){
return 0;
}
zBuf = SafeMalloc( sStat.st_size + 1 );
n = fread(zBuf,1,sStat.st_size,pIn);
zBuf[n] = 0;
fclose(pIn);
return zBuf;
}
/*
** Write the contents of a string into a file. Return the number of
** errors
*/
static int WriteFile(const char *zFilename, const char *zOutput){
FILE *pOut;
pOut = fopen(zFilename,"w");
if( pOut==0 ){
return 1;
}
fwrite(zOutput,1,strlen(zOutput),pOut);
fclose(pOut);
return 0;
}
/*
** Major token types
*/
#define TT_Space 1 /* Contiguous white space */
#define TT_Id 2 /* An identifier */
#define TT_Preprocessor 3 /* Any C preprocessor directive */
#define TT_Comment 4 /* Either C or C++ style comment */
#define TT_Number 5 /* Any numeric constant */
#define TT_String 6 /* String or character constants. ".." or '.' */
#define TT_Braces 7 /* All text between { and a matching } */
#define TT_EOF 8 /* End of file */
#define TT_Error 9 /* An error condition */
#define TT_BlockComment 10 /* A C-Style comment at the left margin that
* spans multple lines */
#define TT_Other 0 /* None of the above */
/*
** Get a single low-level token from the input file. Update the
** file pointer so that it points to the first character beyond the
** token.
**
** A "low-level token" is any token except TT_Braces. A TT_Braces token
** consists of many smaller tokens and is assembled by a routine that
** calls this one.
**
** The function returns the number of errors. An error is an
** unterminated string or character literal or an unterminated
** comment.
**
** Profiling shows that this routine consumes about half the
** CPU time on a typical run of makeheaders.
*/
static int GetToken(InStream *pIn, Token *pToken){
int i;
const char *z;
int cStart;
int c;
int startLine; /* Line on which a structure begins */
int nlisc = 0; /* True if there is a new-line in a ".." or '..' */
int nErr = 0; /* Number of errors seen */
z = pIn->z;
i = pIn->i;
pToken->nLine = pIn->nLine;
pToken->zText = &z[i];
switch( z[i] ){
case 0:
pToken->eType = TT_EOF;
pToken->nText = 0;
break;
case '#':
if( i==0 || z[i-1]=='\n' || (i>1 && z[i-1]=='\r' && z[i-2]=='\n')){
/* We found a preprocessor statement */
pToken->eType = TT_Preprocessor;
i++;
while( z[i]!=0 && z[i]!='\n' ){
if( z[i]=='\\' ){
i++;
if( z[i]=='\n' ) pIn->nLine++;
}
i++;
}
pToken->nText = i - pIn->i;
}else{
/* Just an operator */
pToken->eType = TT_Other;
pToken->nText = 1;
}
break;
case ' ':
case '\t':
case '\r':
case '\f':
case '\n':
while( isspace(z[i]) ){
if( z[i]=='\n' ) pIn->nLine++;
i++;
}
pToken->eType = TT_Space;
pToken->nText = i - pIn->i;
break;
case '\\':
pToken->nText = 2;
pToken->eType = TT_Other;
if( z[i+1]=='\n' ){
pIn->nLine++;
pToken->eType = TT_Space;
}else if( z[i+1]==0 ){
pToken->nText = 1;
}
break;
case '\'':
case '\"':
cStart = z[i];
startLine = pIn->nLine;
do{
i++;
c = z[i];
if( c=='\n' ){
if( !nlisc ){
fprintf(stderr,
"%s:%d: (warning) Newline in string or character literal.\n",
zFilename, pIn->nLine);
nlisc = 1;
}
pIn->nLine++;
}
if( c=='\\' ){
i++;
c = z[i];
if( c=='\n' ){
pIn->nLine++;
}
}else if( c==cStart ){
i++;
c = 0;
}else if( c==0 ){
fprintf(stderr, "%s:%d: Unterminated string or character literal.\n",
zFilename, startLine);
nErr++;
}
}while( c );
pToken->eType = TT_String;
pToken->nText = i - pIn->i;
break;
case '/':
if( z[i+1]=='/' ){
/* C++ style comment */
while( z[i] && z[i]!='\n' ){ i++; }
pToken->eType = TT_Comment;
pToken->nText = i - pIn->i;
}else if( z[i+1]=='*' ){
/* C style comment */
int isBlockComment = i==0 || z[i-1]=='\n';
i += 2;
startLine = pIn->nLine;
while( z[i] && (z[i]!='*' || z[i+1]!='/') ){
if( z[i]=='\n' ){
pIn->nLine++;
if( isBlockComment ){
if( z[i+1]=='*' || z[i+2]=='*' ){
isBlockComment = 2;
}else{
isBlockComment = 0;
}
}
}
i++;
}
if( z[i] ){
i += 2;
}else{
isBlockComment = 0;
fprintf(stderr,"%s:%d: Unterminated comment\n",
zFilename, startLine);
nErr++;
}
pToken->eType = isBlockComment==2 ? TT_BlockComment : TT_Comment;
pToken->nText = i - pIn->i;
}else{
/* A divide operator */
pToken->eType = TT_Other;
pToken->nText = 1 + (z[i+1]=='+');
}
break;
case '0':
if( z[i+1]=='x' || z[i+1]=='X' ){
/* A hex constant */
i += 2;
while( isxdigit(z[i]) ){ i++; }
}else{
/* An octal constant */
while( isdigit(z[i]) ){ i++; }
}
pToken->eType = TT_Number;
pToken->nText = i - pIn->i;
break;
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
while( isdigit(z[i]) ){ i++; }
if( (c=z[i])=='.' ){
i++;
while( isdigit(z[i]) ){ i++; }
c = z[i];
if( c=='e' || c=='E' ){
i++;
if( ((c=z[i])=='+' || c=='-') && isdigit(z[i+1]) ){ i++; }
while( isdigit(z[i]) ){ i++; }
c = z[i];
}
if( c=='f' || c=='F' || c=='l' || c=='L' ){ i++; }
}else if( c=='e' || c=='E' ){
i++;
if( ((c=z[i])=='+' || c=='-') && isdigit(z[i+1]) ){ i++; }
while( isdigit(z[i]) ){ i++; }
}else if( c=='L' || c=='l' ){
i++;
c = z[i];
if( c=='u' || c=='U' ){ i++; }
}else if( c=='u' || c=='U' ){
i++;
c = z[i];
if( c=='l' || c=='L' ){ i++; }
}
pToken->eType = TT_Number;
pToken->nText = i - pIn->i;
break;
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B':
case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I':
case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W':
case 'X': case 'Y': case 'Z': case '_':
while( isalnum(z[i]) || z[i]=='_' ){ i++; };
pToken->eType = TT_Id;
pToken->nText = i - pIn->i;
break;
case ':':
pToken->eType = TT_Other;
pToken->nText = 1 + (z[i+1]==':');
break;
case '=':
case '<':
case '>':
case '+':
case '-':
case '*':
case '%':
case '^':
case '&':
case '|':
pToken->eType = TT_Other;
pToken->nText = 1 + (z[i+1]=='=');
break;
default:
pToken->eType = TT_Other;
pToken->nText = 1;
break;
}
pIn->i += pToken->nText;
return nErr;
}
/*
** This routine recovers the next token from the input file which is
** not a space or a comment or any text between an "#if 0" and "#endif".
**
** This routine returns the number of errors encountered. An error
** is an unterminated token or unmatched "#if 0".
**
** Profiling shows that this routine uses about a quarter of the
** CPU time in a typical run.
*/
static int GetNonspaceToken(InStream *pIn, Token *pToken){
int nIf = 0;
int inZero = 0;
const char *z;
int value;
int startLine;
int nErr = 0;
startLine = pIn->nLine;
while( 1 ){
nErr += GetToken(pIn,pToken);
/* printf("%04d: Type=%d nIf=%d [%.*s]\n",
pToken->nLine,pToken->eType,nIf,pToken->nText,
pToken->eType!=TT_Space ? pToken->zText : "<space>"); */
pToken->pComment = blockComment;
switch( pToken->eType ){
case TT_Comment:
case TT_Space:
break;
case TT_BlockComment:
if( doc_flag ){
blockComment = SafeMalloc( sizeof(Token) );
*blockComment = *pToken;
}
break;
case TT_EOF:
if( nIf ){
fprintf(stderr,"%s:%d: Unterminated \"#if\"\n",
zFilename, startLine);
nErr++;
}
return nErr;
case TT_Preprocessor:
z = &pToken->zText[1];
while( *z==' ' || *z=='\t' ) z++;
if( sscanf(z,"if %d",&value)==1 && value==0 ){
nIf++;
inZero = 1;
}else if( inZero ){
if( strncmp(z,"if",2)==0 ){
nIf++;
}else if( strncmp(z,"endif",5)==0 ){
nIf--;
if( nIf==0 ) inZero = 0;
}
}else{
return nErr;
}
break;
default:
if( !inZero ){
return nErr;
}
break;
}
}
/* NOT REACHED */
}
/*
** This routine looks for identifiers (strings of contiguous alphanumeric
** characters) within a preprocessor directive and adds every such string
** found to the given identifier table
*/
static void FindIdentifiersInMacro(Token *pToken, IdentTable *pTable){
Token sToken;
InStream sIn;
int go = 1;
sIn.z = pToken->zText;
sIn.i = 1;
sIn.nLine = 1;
while( go && sIn.i < pToken->nText ){
GetToken(&sIn,&sToken);
switch( sToken.eType ){
case TT_Id:
IdentTableInsert(pTable,sToken.zText,sToken.nText);
break;
case TT_EOF:
go = 0;
break;
default:
break;
}
}
}
/*
** This routine gets the next token. Everything contained within
** {...} is collapsed into a single TT_Braces token. Whitespace is
** omitted.
**
** If pTable is not NULL, then insert every identifier seen into the
** IdentTable. This includes any identifiers seen inside of {...}.
**
** The number of errors encountered is returned. An error is an
** unterminated token.
*/
static int GetBigToken(InStream *pIn, Token *pToken, IdentTable *pTable){
const char *z, *zStart;
int iStart;
int nBrace;
int c;
int nLine;
int nErr;
nErr = GetNonspaceToken(pIn,pToken);
switch( pToken->eType ){
case TT_Id:
if( pTable!=0 ){
IdentTableInsert(pTable,pToken->zText,pToken->nText);
}
return nErr;
case TT_Preprocessor:
if( pTable!=0 ){
FindIdentifiersInMacro(pToken,pTable);
}
return nErr;
case TT_Other:
if( pToken->zText[0]=='{' ) break;
return nErr;
default:
return nErr;
}
z = pIn->z;
iStart = pIn->i;
zStart = pToken->zText;
nLine = pToken->nLine;
nBrace = 1;
while( nBrace ){
nErr += GetNonspaceToken(pIn,pToken);
/* printf("%04d: nBrace=%d [%.*s]\n",pToken->nLine,nBrace,
pToken->nText,pToken->zText); */
switch( pToken->eType ){
case TT_EOF:
fprintf(stderr,"%s:%d: Unterminated \"{\"\n",
zFilename, nLine);
nErr++;
pToken->eType = TT_Error;
return nErr;
case TT_Id:
if( pTable ){
IdentTableInsert(pTable,pToken->zText,pToken->nText);
}
break;
case TT_Preprocessor:
if( pTable!=0 ){
FindIdentifiersInMacro(pToken,pTable);
}
break;
case TT_Other:
if( (c = pToken->zText[0])=='{' ){
nBrace++;
}else if( c=='}' ){
nBrace--;
}
break;
default:
break;
}
}
pToken->eType = TT_Braces;
pToken->nText = 1 + pIn->i - iStart;
pToken->zText = zStart;
pToken->nLine = nLine;
return nErr;
}
/*
** This routine frees up a list of Tokens. The pComment tokens are
** not cleared by this. So we leak a little memory when using the -doc
** option. So what.
*/
static void FreeTokenList(Token *pList){
Token *pNext;
while( pList ){
pNext = pList->pNext;
SafeFree(pList);
pList = pNext;
}
}
/*
** Tokenize an entire file. Return a pointer to the list of tokens.
**
** Space for each token is obtained from a separate malloc() call. The
** calling function is responsible for freeing this space.
**
** If pTable is not NULL, then fill the table with all identifiers seen in
** the input file.
*/
static Token *TokenizeFile(const char *zFile, IdentTable *pTable){
InStream sIn;
Token *pFirst = 0, *pLast = 0, *pNew;
int nErr = 0;
sIn.z = zFile;
sIn.i = 0;
sIn.nLine = 1;
blockComment = 0;
while( sIn.z[sIn.i]!=0 ){
pNew = SafeMalloc( sizeof(Token) );
nErr += GetBigToken(&sIn,pNew,pTable);
debug3(TOKENIZER, "Token on line %d: [%.*s]\n",
pNew->nLine, pNew->nText<50 ? pNew->nText : 50, pNew->zText);
if( pFirst==0 ){
pFirst = pLast = pNew;
pNew->pPrev = 0;
}else{
pLast->pNext = pNew;
pNew->pPrev = pLast;
pLast = pNew;
}
if( pNew->eType==TT_EOF ) break;
}
if( pLast ) pLast->pNext = 0;
blockComment = 0;
if( nErr ){
FreeTokenList(pFirst);
pFirst = 0;
}
return pFirst;
}
#if TEST==1
/*
** Use the following routine to test or debug the tokenizer.
*/
void main(int argc, char **argv){
char *zFile;
Token *pList, *p;
IdentTable sTable;
if( argc!=2 ){
fprintf(stderr,"Usage: %s filename\n",*argv);
exit(1);
}
memset(&sTable,0,sizeof(sTable));
zFile = ReadFile(argv[1]);
if( zFile==0 ){
fprintf(stderr,"Can't read file \"%s\"\n",argv[1]);
exit(1);
}
pList = TokenizeFile(zFile,&sTable);
for(p=pList; p; p=p->pNext){
int j;
switch( p->eType ){
case TT_Space:
printf("%4d: Space\n",p->nLine);
break;
case TT_Id:
printf("%4d: Id %.*s\n",p->nLine,p->nText,p->zText);
break;
case TT_Preprocessor:
printf("%4d: Preprocessor %.*s\n",p->nLine,p->nText,p->zText);
break;
case TT_Comment:
printf("%4d: Comment\n",p->nLine);
break;
case TT_BlockComment:
printf("%4d: Block Comment\n",p->nLine);
break;
case TT_Number:
printf("%4d: Number %.*s\n",p->nLine,p->nText,p->zText);
break;
case TT_String:
printf("%4d: String %.*s\n",p->nLine,p->nText,p->zText);
break;
case TT_Other:
printf("%4d: Other %.*s\n",p->nLine,p->nText,p->zText);
break;
case TT_Braces:
for(j=0; j<p->nText && j<30 && p->zText[j]!='\n'; j++){}
printf("%4d: Braces %.*s...}\n",p->nLine,j,p->zText);
break;
case TT_EOF:
printf("%4d: End of file\n",p->nLine);
break;
default:
printf("%4d: type %d\n",p->nLine,p->eType);
break;
}
}
FreeTokenList(pList);
SafeFree(zFile);
IdentTablePrint(&sTable,stdout);
}
#endif
#ifdef DEBUG
/*
** For debugging purposes, write out a list of tokens.
*/
static void PrintTokens(Token *pFirst, Token *pLast){
int needSpace = 0;
int c;
pLast = pLast->pNext;
while( pFirst!=pLast ){
switch( pFirst->eType ){
case TT_Preprocessor:
printf("\n%.*s\n",pFirst->nText,pFirst->zText);
needSpace = 0;
break;
case TT_Id:
case TT_Number:
printf("%s%.*s", needSpace ? " " : "", pFirst->nText, pFirst->zText);
needSpace = 1;
break;
default:
c = pFirst->zText[0];
printf("%s%.*s",
(needSpace && (c=='*' || c=='{')) ? " " : "",
pFirst->nText, pFirst->zText);
needSpace = pFirst->zText[0]==',';
break;
}
pFirst = pFirst->pNext;
}
}
#endif
/*
** Convert a sequence of tokens into a string and return a pointer
** to that string. Space to hold the string is obtained from malloc()
** and must be freed by the calling function.
**
** Certain keywords (EXPORT, PRIVATE, PUBLIC, PROTECTED) are always
** skipped.
**
** If pSkip!=0 then skip over nSkip tokens beginning with pSkip.
**
** If zTerm!=0 then append the text to the end.
*/
static char *TokensToString(
Token *pFirst, /* First token in the string */
Token *pLast, /* Last token in the string */
char *zTerm, /* Terminate the string with this text if not NULL */
Token *pSkip, /* Skip this token if not NULL */
int nSkip /* Skip a total of this many tokens */
){
char *zReturn;
String str;
int needSpace = 0;
int c;
int iSkip = 0;
int skipOne = 0;
StringInit(&str);
pLast = pLast->pNext;
while( pFirst!=pLast ){
if( pFirst==pSkip ){ iSkip = nSkip; }
if( iSkip>0 ){
iSkip--;
pFirst=pFirst->pNext;
continue;
}
switch( pFirst->eType ){
case TT_Preprocessor:
StringAppend(&str,"\n",1);
StringAppend(&str,pFirst->zText,pFirst->nText);
StringAppend(&str,"\n",1);
needSpace = 0;
break;
case TT_Id:
switch( pFirst->zText[0] ){
case 'E':
if( pFirst->nText==6 && strncmp(pFirst->zText,"EXPORT",6)==0 ){
skipOne = 1;
}
break;
case 'P':
switch( pFirst->nText ){
case 6: skipOne = !strncmp(pFirst->zText,"PUBLIC", 6); break;
case 7: skipOne = !strncmp(pFirst->zText,"PRIVATE",7); break;
case 9: skipOne = !strncmp(pFirst->zText,"PROTECTED",9); break;
default: break;
}
break;
default:
break;
}
if( skipOne ){
pFirst = pFirst->pNext;
continue;
}
/* Fall thru to the next case */
case TT_Number:
if( needSpace ){
StringAppend(&str," ",1);
}
StringAppend(&str,pFirst->zText,pFirst->nText);
needSpace = 1;
break;
default:
c = pFirst->zText[0];
if( needSpace && (c=='*' || c=='{') ){
StringAppend(&str," ",1);
}
StringAppend(&str,pFirst->zText,pFirst->nText);
/* needSpace = pFirst->zText[0]==','; */
needSpace = 0;
break;
}
pFirst = pFirst->pNext;
}
if( zTerm && *zTerm ){
StringAppend(&str,zTerm,strlen(zTerm));
}
zReturn = StrDup(StringGet(&str),0);
StringReset(&str);
return zReturn;
}
/*
** This routine is called when we see one of the keywords "struct",
** "enum", "union" or "class". This might be the beginning of a
** type declaration. This routine will process the declaration and
** remove the declaration tokens from the input stream.
**
** If this is a type declaration that is immediately followed by a
** semicolon (in other words it isn't also a variable definition)
** then set *pReset to ';'. Otherwise leave *pReset at 0. The
** *pReset flag causes the parser to skip ahead to the next token
** that begins with the value placed in the *pReset flag, if that
** value is different from 0.
*/
static int ProcessTypeDecl(Token *pList, int flags, int *pReset){
Token *pName, *pEnd;
Decl *pDecl;
String str;
int need_to_collapse = 1;
int type = 0;
*pReset = 0;
if( pList==0 || pList->pNext==0 || pList->pNext->eType!=TT_Id ){
return 0;
}
pName = pList->pNext;
/* Catch the case of "struct Foo;" and skip it. */
if( pName->pNext && pName->pNext->zText[0]==';' ){
*pReset = ';';
return 0;
}
for(pEnd=pName->pNext; pEnd && pEnd->eType!=TT_Braces; pEnd=pEnd->pNext){
switch( pEnd->zText[0] ){
case '(':
case '*':
case '[':
case '=':
case ';':
return 0;
}
}
if( pEnd==0 ){
return 0;
}
/*
** At this point, we know we have a type declaration that is bounded
** by pList and pEnd and has the name pName.
*/
/*
** If the braces are followed immedately by a semicolon, then we are
** dealing a type declaration only. There is not variable definition
** following the type declaration. So reset...
*/
if( pEnd->pNext==0 || pEnd->pNext->zText[0]==';' ){
*pReset = ';';
need_to_collapse = 0;
}else{
need_to_collapse = 1;
}
if( proto_static==0 && (flags & (PS_Local|PS_Export|PS_Interface))==0 ){
/* Ignore these objects unless they are explicitly declared as interface,
** or unless the "-local" command line option was specified. */
*pReset = ';';
return 0;
}
#ifdef DEBUG
if( debugMask & PARSER ){
printf("**** Found type: %.*s %.*s...\n",
pList->nText, pList->zText, pName->nText, pName->zText);
PrintTokens(pList,pEnd);
printf(";\n");
}
#endif
/*
** Create a new Decl object for this definition. Actually, if this
** is a C++ class definition, then the Decl object might already exist,
** so check first for that case before creating a new one.
*/
switch( *pList->zText ){
case 'c': type = TY_Class; break;
case 's': type = TY_Structure; break;
case 'e': type = TY_Enumeration; break;
case 'u': type = TY_Union; break;
default: /* Can't Happen */ break;
}
if( type!=TY_Class ){
pDecl = 0;
}else{
pDecl = FindDecl(pName->zText, pName->nText);
if( pDecl && (pDecl->flags & type)!=type ) pDecl = 0;
}
if( pDecl==0 ){
pDecl = CreateDecl(pName->zText,pName->nText);
}
if( (flags & PS_Static) || !(flags & (PS_Interface|PS_Export)) ){
DeclSetProperty(pDecl,DP_Local);
}
DeclSetProperty(pDecl,type);
/* The object has a full declaration only if it is contained within
** "#if INTERFACE...#endif" or "#if EXPORT_INTERFACE...#endif" or
** "#if LOCAL_INTERFACE...#endif". Otherwise, we only give it a
** forward declaration.
*/
if( flags & (PS_Local | PS_Export | PS_Interface) ){
pDecl->zDecl = TokensToString(pList,pEnd,";\n",0,0);
}else{
pDecl->zDecl = 0;
}
pDecl->pComment = pList->pComment;
StringInit(&str);
StringAppend(&str,"typedef ",0);
StringAppend(&str,pList->zText,pList->nText);
StringAppend(&str," ",0);
StringAppend(&str,pName->zText,pName->nText);
StringAppend(&str," ",0);
StringAppend(&str,pName->zText,pName->nText);
StringAppend(&str,";\n",2);
pDecl->zFwd = StrDup(StringGet(&str),0);
StringReset(&str);
StringInit(&str);
StringAppend(&str,pList->zText,pList->nText);
StringAppend(&str," ",0);
StringAppend(&str,pName->zText,pName->nText);
StringAppend(&str,";\n",2);
pDecl->zFwdCpp = StrDup(StringGet(&str),0);
StringReset(&str);
if( flags & PS_Export ){
DeclSetProperty(pDecl,DP_Export);
}else if( flags & PS_Local ){
DeclSetProperty(pDecl,DP_Local);
}
/* Here's something weird. ANSI-C doesn't allow a forward declaration
** of an enumeration. So we have to build the typedef into the
** definition.
*/
if( pDecl->zDecl && DeclHasProperty(pDecl, TY_Enumeration) ){
StringInit(&str);
StringAppend(&str,pDecl->zDecl,0);
StringAppend(&str,pDecl->zFwd,0);
SafeFree(pDecl->zDecl);
SafeFree(pDecl->zFwd);
pDecl->zFwd = 0;
pDecl->zDecl = StrDup(StringGet(&str),0);
StringReset(&str);
}
if( pName->pNext->zText[0]==':' ){
DeclSetProperty(pDecl,DP_Cplusplus);
}
if( pName->nText==5 && strncmp(pName->zText,"class",5)==0 ){
DeclSetProperty(pDecl,DP_Cplusplus);
}
/*
** Remove all but pList and pName from the input stream.
*/
if( need_to_collapse ){
while( pEnd!=pName ){
Token *pPrev = pEnd->pPrev;
pPrev->pNext = pEnd->pNext;
pEnd->pNext->pPrev = pPrev;
SafeFree(pEnd);
pEnd = pPrev;
}
}
return 0;
}
/*
** Given a list of tokens that declare something (a function, procedure,
** variable or typedef) find the token which contains the name of the
** thing being declared.
**
** Algorithm:
**
** The name is:
**
** 1. The first identifier that is followed by a "[", or
**
** 2. The first identifier that is followed by a "(" where the
** "(" is followed by another identifier, or
**
** 3. The first identifier followed by "::", or
**
** 4. If none of the above, then the last identifier.
**
** In all of the above, certain reserved words (like "char") are
** not considered identifiers.
*/
static Token *FindDeclName(Token *pFirst, Token *pLast){
Token *pName = 0;
Token *p;
int c;
if( pFirst==0 || pLast==0 ){
return 0;
}
pLast = pLast->pNext;
for(p=pFirst; p && p!=pLast; p=p->pNext){
if( p->eType==TT_Id ){
static IdentTable sReserved;
static int isInit = 0;
static char *aWords[] = { "char", "class",
"const", "double", "enum", "extern", "EXPORT", "ET_PROC",
"float", "int", "long",
"PRIVATE", "PROTECTED", "PUBLIC",
"register", "static", "struct", "sizeof", "signed", "typedef",
"union", "volatile", "virtual", "void", };
if( !isInit ){
int i;
for(i=0; i<sizeof(aWords)/sizeof(aWords[0]); i++){
IdentTableInsert(&sReserved,aWords[i],0);
}
isInit = 1;
}
if( !IdentTableTest(&sReserved,p->zText,p->nText) ){
pName = p;
}
}else if( p==pFirst ){
continue;
}else if( (c=p->zText[0])=='[' && pName ){
break;
}else if( c=='(' && p->pNext && p->pNext->eType==TT_Id && pName ){
break;
}else if( c==':' && p->zText[1]==':' && pName ){
break;
}
}
return pName;
}
/*
** This routine is called when we see a method for a class that begins
** with the PUBLIC, PRIVATE, or PROTECTED keywords. Such methods are
** added to their class definitions.
*/
static int ProcessMethodDef(Token *pFirst, Token *pLast, int flags){
Token *pCode;
Token *pClass;
char *zDecl;
Decl *pDecl;
String str;
int type;
pCode = pLast;
pLast = pLast->pPrev;
while( pFirst->zText[0]=='P' ){
int rc = 1;
switch( pFirst->nText ){
case 6: rc = strncmp(pFirst->zText,"PUBLIC",6); break;
case 7: rc = strncmp(pFirst->zText,"PRIVATE",7); break;
case 9: rc = strncmp(pFirst->zText,"PROTECTED",9); break;
default: break;
}
if( rc ) break;
pFirst = pFirst->pNext;
}
pClass = FindDeclName(pFirst,pLast);
if( pClass==0 ){
fprintf(stderr,"%s:%d: Unable to find the class name for this method\n",
zFilename, pFirst->nLine);
return 1;
}
pDecl = FindDecl(pClass->zText, pClass->nText);
if( pDecl==0 || (pDecl->flags & TY_Class)!=TY_Class ){
pDecl = CreateDecl(pClass->zText, pClass->nText);
DeclSetProperty(pDecl, TY_Class);
}
StringInit(&str);
if( pDecl->zExtra ){
StringAppend(&str, pDecl->zExtra, 0);
SafeFree(pDecl->zExtra);
pDecl->zExtra = 0;
}
type = flags & PS_PPP;
if( pDecl->extraType!=type ){
if( type & PS_Public ){
StringAppend(&str, "public:\n", 0);
pDecl->extraType = PS_Public;
}else if( type & PS_Protected ){
StringAppend(&str, "protected:\n", 0);
pDecl->extraType = PS_Protected;
}else if( type & PS_Private ){
StringAppend(&str, "private:\n", 0);
pDecl->extraType = PS_Private;
}
}
StringAppend(&str, " ", 0);
zDecl = TokensToString(pFirst, pLast, ";\n", pClass, 2);
StringAppend(&str, zDecl, 0);
SafeFree(zDecl);
pDecl->zExtra = StrDup(StringGet(&str), 0);
StringReset(&str);
return 0;
}
/*
** This routine is called when we see a function or procedure definition.
** We make an entry in the declaration table that is a prototype for this
** function or procedure.
*/
static int ProcessProcedureDef(Token *pFirst, Token *pLast, int flags){
Token *pName;
Decl *pDecl;
Token *pCode;
if( pFirst==0 || pLast==0 ){
return 0;
}
if( flags & PS_Method ){
if( flags & PS_PPP ){
return ProcessMethodDef(pFirst, pLast, flags);
}else{
return 0;
}
}
if( (flags & PS_Static)!=0 && !proto_static ){
return 0;
}
pCode = pLast;
while( pLast && pLast!=pFirst && pLast->zText[0]!=')' ){
pLast = pLast->pPrev;
}
if( pLast==0 || pLast==pFirst || pFirst->pNext==pLast ){
fprintf(stderr,"%s:%d: Unrecognized syntax.\n",
zFilename, pFirst->nLine);
return 1;
}
if( flags & (PS_Interface|PS_Export|PS_Local) ){
fprintf(stderr,"%s:%d: Missing \"inline\" on function or procedure.\n",
zFilename, pFirst->nLine);
return 1;
}
pName = FindDeclName(pFirst,pLast);
if( pName==0 ){
fprintf(stderr,"%s:%d: Malformed function or procedure definition.\n",
zFilename, pFirst->nLine);
return 1;
}
/*
** At this point we've isolated a procedure declaration between pFirst
** and pLast with the name pName.
*/
#ifdef DEBUG
if( debugMask & PARSER ){
printf("**** Found routine: %.*s on line %d...\n", pName->nText,
pName->zText, pFirst->nLine);
PrintTokens(pFirst,pLast);
printf(";\n");
}
#endif
pDecl = CreateDecl(pName->zText,pName->nText);
pDecl->pComment = pFirst->pComment;
if( pCode && pCode->eType==TT_Braces ){
pDecl->tokenCode = *pCode;
}
DeclSetProperty(pDecl,TY_Subroutine);
pDecl->zDecl = TokensToString(pFirst,pLast,";\n",0,0);
if( (flags & (PS_Static|PS_Local2))!=0 ){
DeclSetProperty(pDecl,DP_Local);
}else if( (flags & (PS_Export2))!=0 ){
DeclSetProperty(pDecl,DP_Export);
}
if( flags & DP_Cplusplus ){
DeclSetProperty(pDecl,DP_Cplusplus);
}else{
DeclSetProperty(pDecl,DP_ExternCReqd);
}
return 0;
}
/*
** This routine is called whenever we see the "inline" keyword. We
** need to seek-out the inline function or procedure and make a
** declaration out of the entire definition.
*/
static int ProcessInlineProc(Token *pFirst, int flags, int *pReset){
Token *pName;
Token *pEnd;
Decl *pDecl;
for(pEnd=pFirst; pEnd; pEnd = pEnd->pNext){
if( pEnd->zText[0]=='{' || pEnd->zText[0]==';' ){
*pReset = pEnd->zText[0];
break;
}
}
if( pEnd==0 ){
*pReset = ';';
fprintf(stderr,"%s:%d: incomplete inline procedure definition\n",
zFilename, pFirst->nLine);
return 1;
}
pName = FindDeclName(pFirst,pEnd);
if( pName==0 ){
fprintf(stderr,"%s:%d: malformed inline procedure definition\n",
zFilename, pFirst->nLine);
return 1;
}
#ifdef DEBUG
if( debugMask & PARSER ){
printf("**** Found inline routine: %.*s on line %d...\n",
pName->nText, pName->zText, pFirst->nLine);
PrintTokens(pFirst,pEnd);
printf("\n");
}
#endif
pDecl = CreateDecl(pName->zText,pName->nText);
pDecl->pComment = pFirst->pComment;
DeclSetProperty(pDecl,TY_Subroutine);
pDecl->zDecl = TokensToString(pFirst,pEnd,";\n",0,0);
if( (flags & (PS_Static|PS_Local|PS_Local2)) ){
DeclSetProperty(pDecl,DP_Local);
}else if( flags & (PS_Export|PS_Export2) ){
DeclSetProperty(pDecl,DP_Export);
}
if( flags & DP_Cplusplus ){
DeclSetProperty(pDecl,DP_Cplusplus);
}else{
DeclSetProperty(pDecl,DP_ExternCReqd);
}
return 0;
}
/*
** Determine if the tokens between pFirst and pEnd form a variable
** definition or a function prototype. Return TRUE if we are dealing
** with a variable defintion and FALSE for a prototype.
**
** pEnd is the token that ends the object. It can be either a ';' or
** a '='. If it is '=', then assume we have a variable definition.
**
** If pEnd is ';', then the determination is more difficult. We have
** to search for an occurance of an ID followed immediately by '('.
** If found, we have a prototype. Otherwise we are dealing with a
** variable definition.
*/
static int isVariableDef(Token *pFirst, Token *pEnd){
if( pEnd && pEnd->zText[0]=='=' &&
(pEnd->pPrev->nText!=8 || strncmp(pEnd->pPrev->zText,"operator",8)!=0)
){
return 1;
}
while( pFirst && pFirst!=pEnd && pFirst->pNext && pFirst->pNext!=pEnd ){
if( pFirst->eType==TT_Id && pFirst->pNext->zText[0]=='(' ){
return 0;
}
pFirst = pFirst->pNext;
}
return 1;
}
/*
** This routine is called whenever we encounter a ";" or "=". The stuff
** between pFirst and pLast constitutes either a typedef or a global
** variable definition. Do the right thing.
*/
static int ProcessDecl(Token *pFirst, Token *pEnd, int flags){
Token *pName;
Decl *pDecl;
int isLocal = 0;
int isVar;
int nErr = 0;
if( pFirst==0 || pEnd==0 ){
return 0;
}
if( flags & PS_Typedef ){
if( (flags & (PS_Export2|PS_Local2))!=0 ){
fprintf(stderr,"%s:%d: \"EXPORT\" or \"LOCAL\" ignored before typedef.\n",
zFilename, pFirst->nLine);
nErr++;
}
if( (flags & (PS_Interface|PS_Export|PS_Local|DP_Cplusplus))==0 ){
/* It is illegal to duplicate a typedef in C (but OK in C++).
** So don't record typedefs that aren't within a C++ file or
** within #if INTERFACE..#endif */
return nErr;
}
if( (flags & (PS_Interface|PS_Export|PS_Local))==0 && proto_static==0 ){
/* Ignore typedefs that are not with "#if INTERFACE..#endif" unless
** the "-local" command line option is used. */
return nErr;
}
if( (flags & (PS_Interface|PS_Export))==0 ){
/* typedefs are always local, unless within #if INTERFACE..#endif */
isLocal = 1;
}
}else if( flags & (PS_Static|PS_Local2) ){
if( proto_static==0 && (flags & PS_Local2)==0 ){
/* Don't record static variables unless the "-local" command line
** option was specified or the "LOCAL" keyword is used. */
return nErr;
}
while( pFirst!=0 && pFirst->pNext!=pEnd &&
((pFirst->nText==6 && strncmp(pFirst->zText,"static",6)==0)
|| (pFirst->nText==5 && strncmp(pFirst->zText,"LOCAL",6)==0))
){
/* Lose the initial "static" or local from local variables.
** We'll prepend "extern" later. */
pFirst = pFirst->pNext;
isLocal = 1;
}
if( pFirst==0 || !isLocal ){
return nErr;
}
}else if( flags & PS_Method ){
/* Methods are declared by their class. Don't declare separately. */
return nErr;
}
isVar = (flags & (PS_Typedef|PS_Method))==0 && isVariableDef(pFirst,pEnd);
if( isVar && (flags & (PS_Interface|PS_Export|PS_Local))!=0
&& (flags & PS_Extern)==0 ){
fprintf(stderr,"%s:%d: Can't define a variable in this context\n",
zFilename, pFirst->nLine);
nErr++;
}
pName = FindDeclName(pFirst,pEnd->pPrev);
if( pName==0 ){
fprintf(stderr,"%s:%d: Can't find a name for the object declared here.\n",
zFilename, pFirst->nLine);
return nErr+1;
}
#ifdef DEBUG
if( debugMask & PARSER ){
if( flags & PS_Typedef ){
printf("**** Found typedef %.*s at line %d...\n",
pName->nText, pName->zText, pName->nLine);
}else if( isVar ){
printf("**** Found variable %.*s at line %d...\n",
pName->nText, pName->zText, pName->nLine);
}else{
printf("**** Found prototype %.*s at line %d...\n",
pName->nText, pName->zText, pName->nLine);
}
PrintTokens(pFirst,pEnd->pPrev);
printf(";\n");
}
#endif
pDecl = CreateDecl(pName->zText,pName->nText);
if( (flags & PS_Typedef) ){
DeclSetProperty(pDecl, TY_Typedef);
}else if( isVar ){
DeclSetProperty(pDecl,DP_ExternReqd | TY_Variable);
if( !(flags & DP_Cplusplus) ){
DeclSetProperty(pDecl,DP_ExternCReqd);
}
}else{
DeclSetProperty(pDecl, TY_Subroutine);
if( !(flags & DP_Cplusplus) ){
DeclSetProperty(pDecl,DP_ExternCReqd);
}
}
pDecl->pComment = pFirst->pComment;
pDecl->zDecl = TokensToString(pFirst,pEnd->pPrev,";\n",0,0);
if( isLocal || (flags & (PS_Local|PS_Local2))!=0 ){
DeclSetProperty(pDecl,DP_Local);
}else if( flags & (PS_Export|PS_Export2) ){
DeclSetProperty(pDecl,DP_Export);
}
if( flags & DP_Cplusplus ){
DeclSetProperty(pDecl,DP_Cplusplus);
}
return nErr;
}
/*
** Push an if condition onto the if stack
*/
static void PushIfMacro(
const char *zPrefix, /* A prefix, like "define" or "!" */
const char *zText, /* The condition */
int nText, /* Number of characters in zText */
int nLine, /* Line number where this macro occurs */
int flags /* Either 0, PS_Interface, PS_Export or PS_Local */
){
Ifmacro *pIf;
int nByte;
nByte = sizeof(Ifmacro);
if( zText ){
if( zPrefix ){
nByte += strlen(zPrefix) + 2;
}
nByte += nText + 1;
}
pIf = SafeMalloc( nByte );
if( zText ){
pIf->zCondition = (char*)&pIf[1];
if( zPrefix ){
sprintf(pIf->zCondition,"%s(%.*s)",zPrefix,nText,zText);
}else{
sprintf(pIf->zCondition,"%.*s",nText,zText);
}
}else{
pIf->zCondition = 0;
}
pIf->nLine = nLine;
pIf->flags = flags;
pIf->pNext = ifStack;
ifStack = pIf;
}
/*
** This routine is called to handle all preprocessor directives.
**
** This routine will recompute the value of *pPresetFlags to be the
** logical or of all flags on all nested #ifs. The #ifs that set flags
** are as follows:
**
** conditional flag set
** ------------------------ --------------------
** #if INTERFACE PS_Interface
** #if EXPORT_INTERFACE PS_Export
** #if LOCAL_INTERFACE PS_Local
**
** For example, if after processing the preprocessor token given
** by pToken there is an "#if INTERFACE" on the preprocessor
** stack, then *pPresetFlags will be set to PS_Interface.
*/
static int ParsePreprocessor(Token *pToken, int flags, int *pPresetFlags){
const char *zCmd;
int nCmd;
const char *zArg;
int nArg;
int nErr = 0;
Ifmacro *pIf;
zCmd = &pToken->zText[1];
while( isspace(*zCmd) && *zCmd!='\n' ){
zCmd++;
}
if( !isalpha(*zCmd) ){
return 0;
}
nCmd = 1;
while( isalpha(zCmd[nCmd]) ){
nCmd++;
}
if( nCmd==5 && strncmp(zCmd,"endif",5)==0 ){
/*
** Pop the if stack
*/
pIf = ifStack;
if( pIf==0 ){
fprintf(stderr,"%s:%d: extra '#endif'.\n",zFilename,pToken->nLine);
return 1;
}
ifStack = pIf->pNext;
SafeFree(pIf);
}else if( nCmd==6 && strncmp(zCmd,"define",6)==0 ){
/*
** Record a #define if we are in PS_Interface or PS_Export
*/
Decl *pDecl;
if( !(flags & (PS_Local|PS_Interface|PS_Export)) ){ return 0; }
zArg = &zCmd[6];
while( *zArg && isspace(*zArg) && *zArg!='\n' ){
zArg++;
}
if( *zArg==0 || *zArg=='\n' ){ return 0; }
for(nArg=0; ISALNUM(zArg[nArg]); nArg++){}
if( nArg==0 ){ return 0; }
pDecl = CreateDecl(zArg,nArg);
pDecl->pComment = pToken->pComment;
DeclSetProperty(pDecl,TY_Macro);
pDecl->zDecl = SafeMalloc( pToken->nText + 2 );
sprintf(pDecl->zDecl,"%.*s\n",pToken->nText,pToken->zText);
if( flags & PS_Export ){
DeclSetProperty(pDecl,DP_Export);
}else if( flags & PS_Local ){
DeclSetProperty(pDecl,DP_Local);
}
}else if( nCmd==7 && strncmp(zCmd,"include",7)==0 ){
/*
** Record an #include if we are in PS_Interface or PS_Export
*/
Include *pInclude;
char *zIf;
if( !(flags & (PS_Interface|PS_Export)) ){ return 0; }
zArg = &zCmd[7];
while( *zArg && isspace(*zArg) ){ zArg++; }
for(nArg=0; !isspace(zArg[nArg]); nArg++){}
if( (zArg[0]=='"' && zArg[nArg-1]!='"')
||(zArg[0]=='<' && zArg[nArg-1]!='>')
){
fprintf(stderr,"%s:%d: malformed #include statement.\n",
zFilename,pToken->nLine);
return 1;
}
zIf = GetIfString();
if( zIf ){
pInclude = SafeMalloc( sizeof(Include) + nArg*2 + strlen(zIf) + 10 );
pInclude->zFile = (char*)&pInclude[1];
pInclude->zLabel = &pInclude->zFile[nArg+1];
sprintf(pInclude->zFile,"%.*s",nArg,zArg);
sprintf(pInclude->zLabel,"%.*s:%s",nArg,zArg,zIf);
pInclude->zIf = &pInclude->zLabel[nArg+1];
SafeFree(zIf);
}else{
pInclude = SafeMalloc( sizeof(Include) + nArg + 1 );
pInclude->zFile = (char*)&pInclude[1];
sprintf(pInclude->zFile,"%.*s",nArg,zArg);
pInclude->zIf = 0;
pInclude->zLabel = pInclude->zFile;
}
pInclude->pNext = includeList;
includeList = pInclude;
}else if( nCmd==2 && strncmp(zCmd,"if",2)==0 ){
/*
** Push an #if. Watch for the special cases of INTERFACE
** and EXPORT_INTERFACE and LOCAL_INTERFACE
*/
zArg = &zCmd[2];
while( *zArg && isspace(*zArg) && *zArg!='\n' ){
zArg++;
}
if( *zArg==0 || *zArg=='\n' ){ return 0; }
nArg = pToken->nText + (int)(pToken->zText - zArg);
if( nArg==9 && strncmp(zArg,"INTERFACE",9)==0 ){
PushIfMacro(0,0,0,pToken->nLine,PS_Interface);
}else if( nArg==16 && strncmp(zArg,"EXPORT_INTERFACE",16)==0 ){
PushIfMacro(0,0,0,pToken->nLine,PS_Export);
}else if( nArg==15 && strncmp(zArg,"LOCAL_INTERFACE",15)==0 ){
PushIfMacro(0,0,0,pToken->nLine,PS_Local);
}else{
PushIfMacro(0,zArg,nArg,pToken->nLine,0);
}
}else if( nCmd==5 && strncmp(zCmd,"ifdef",5)==0 ){
/*
** Push an #ifdef.
*/
zArg = &zCmd[5];
while( *zArg && isspace(*zArg) && *zArg!='\n' ){
zArg++;
}
if( *zArg==0 || *zArg=='\n' ){ return 0; }
nArg = pToken->nText + (int)(pToken->zText - zArg);
PushIfMacro("defined",zArg,nArg,pToken->nLine,0);
}else if( nCmd==6 && strncmp(zCmd,"ifndef",6)==0 ){
/*
** Push an #ifndef.
*/
zArg = &zCmd[6];
while( *zArg && isspace(*zArg) && *zArg!='\n' ){
zArg++;
}
if( *zArg==0 || *zArg=='\n' ){ return 0; }
nArg = pToken->nText + (int)(pToken->zText - zArg);
PushIfMacro("!defined",zArg,nArg,pToken->nLine,0);
}else if( nCmd==4 && strncmp(zCmd,"else",4)==0 ){
/*
** Invert the #if on the top of the stack
*/
if( ifStack==0 ){
fprintf(stderr,"%s:%d: '#else' without an '#if'\n",zFilename,
pToken->nLine);
return 1;
}
pIf = ifStack;
if( pIf->zCondition ){
ifStack = ifStack->pNext;
PushIfMacro("!",pIf->zCondition,strlen(pIf->zCondition),pIf->nLine,0);
SafeFree(pIf);
}else{
pIf->flags = 0;
}
}else{
/*
** This directive can be safely ignored
*/
return 0;
}
/*
** Recompute the preset flags
*/
*pPresetFlags = 0;
for(pIf = ifStack; pIf; pIf=pIf->pNext){
*pPresetFlags |= pIf->flags;
}
return nErr;
}
/*
** Parse an entire file. Return the number of errors.
**
** pList is a list of tokens in the file. Whitespace tokens have been
** eliminated, and text with {...} has been collapsed into a
** single TT_Brace token.
**
** initFlags are a set of parse flags that should always be set for this
** file. For .c files this is normally 0. For .h files it is PS_Interface.
*/
static int ParseFile(Token *pList, int initFlags){
int nErr = 0;
Token *pStart = 0;
int flags = initFlags;
int presetFlags = initFlags;
int resetFlag = 0;
includeList = 0;
while( pList ){
switch( pList->eType ){
case TT_EOF:
goto end_of_loop;
case TT_Preprocessor:
nErr += ParsePreprocessor(pList,flags,&presetFlags);
pStart = 0;
presetFlags |= initFlags;
flags = presetFlags;
break;
case TT_Other:
switch( pList->zText[0] ){
case ';':
nErr += ProcessDecl(pStart,pList,flags);
pStart = 0;
flags = presetFlags;
break;
case '=':
if( pList->pPrev->nText==8
&& strncmp(pList->pPrev->zText,"operator",8)==0 ){
break;
}
nErr += ProcessDecl(pStart,pList,flags);
pStart = 0;
while( pList && pList->zText[0]!=';' ){
pList = pList->pNext;
}
if( pList==0 ) goto end_of_loop;
flags = presetFlags;
break;
case ':':
if( pList->zText[1]==':' ){
flags |= PS_Method;
}
break;
default:
break;
}
break;
case TT_Braces:
nErr += ProcessProcedureDef(pStart,pList,flags);
pStart = 0;
flags = presetFlags;
break;
case TT_Id:
if( pStart==0 ){
pStart = pList;
flags = presetFlags;
}
resetFlag = 0;
switch( pList->zText[0] ){
case 'c':
if( pList->nText==5 && strncmp(pList->zText,"class",5)==0 ){
nErr += ProcessTypeDecl(pList,flags,&resetFlag);
}
break;
case 'E':
if( pList->nText==6 && strncmp(pList->zText,"EXPORT",6)==0 ){
flags |= PS_Export2;
/* pStart = 0; */
}
break;
case 'e':
if( pList->nText==4 && strncmp(pList->zText,"enum",4)==0 ){
if( pList->pNext && pList->pNext->eType==TT_Braces ){
pList = pList->pNext;
}else{
nErr += ProcessTypeDecl(pList,flags,&resetFlag);
}
}else if( pList->nText==6 && strncmp(pList->zText,"extern",6)==0 ){
pList = pList->pNext;
if( pList && pList->nText==3 && strncmp(pList->zText,"\"C\"",3)==0 ){
pList = pList->pNext;
flags &= ~DP_Cplusplus;
}else{
flags |= PS_Extern;
}
pStart = pList;
}
break;
case 'i':
if( pList->nText==6 && strncmp(pList->zText,"inline",6)==0 ){
nErr += ProcessInlineProc(pList,flags,&resetFlag);
}
break;
case 'L':
if( pList->nText==5 && strncmp(pList->zText,"LOCAL",5)==0 ){
flags |= PS_Local2;
pStart = pList;
}
break;
case 'P':
if( pList->nText==6 && strncmp(pList->zText, "PUBLIC",6)==0 ){
flags |= PS_Public;
pStart = pList;
}else if( pList->nText==7 && strncmp(pList->zText, "PRIVATE",7)==0 ){
flags |= PS_Private;
pStart = pList;
}else if( pList->nText==9 && strncmp(pList->zText,"PROTECTED",9)==0 ){
flags |= PS_Protected;
pStart = pList;
}
break;
case 's':
if( pList->nText==6 && strncmp(pList->zText,"struct",6)==0 ){
if( pList->pNext && pList->pNext->eType==TT_Braces ){
pList = pList->pNext;
}else{
nErr += ProcessTypeDecl(pList,flags,&resetFlag);
}
}else if( pList->nText==6 && strncmp(pList->zText,"static",6)==0 ){
flags |= PS_Static;
}
break;
case 't':
if( pList->nText==7 && strncmp(pList->zText,"typedef",7)==0 ){
flags |= PS_Typedef;
}
break;
case 'u':
if( pList->nText==5 && strncmp(pList->zText,"union",5)==0 ){
if( pList->pNext && pList->pNext->eType==TT_Braces ){
pList = pList->pNext;
}else{
nErr += ProcessTypeDecl(pList,flags,&resetFlag);
}
}
break;
default:
break;
}
if( resetFlag!=0 ){
while( pList && pList->zText[0]!=resetFlag ){
pList = pList->pNext;
}
if( pList==0 ) goto end_of_loop;
pStart = 0;
flags = presetFlags;
}
break;
case TT_String:
case TT_Number:
break;
default:
pStart = pList;
flags = presetFlags;
break;
}
pList = pList->pNext;
}
end_of_loop:
/* Verify that all #ifs have a matching "#endif" */
while( ifStack ){
Ifmacro *pIf = ifStack;
ifStack = pIf->pNext;
fprintf(stderr,"%s:%d: This '#if' has no '#endif'\n",zFilename,
pIf->nLine);
SafeFree(pIf);
}
return nErr;
}
/*
** If the given Decl object has a non-null zExtra field, then the text
** of that zExtra field needs to be inserted in the middle of the
** zDecl field before the last "}" in the zDecl. This routine does that.
** If the zExtra is NULL, this routine is a no-op.
**
** zExtra holds extra method declarations for classes. The declarations
** have to be inserted into the class definition.
*/
static void InsertExtraDecl(Decl *pDecl){
int i;
String str;
if( pDecl==0 || pDecl->zExtra==0 || pDecl->zDecl==0 ) return;
i = strlen(pDecl->zDecl) - 1;
while( i>0 && pDecl->zDecl[i]!='}' ){ i--; }
StringInit(&str);
StringAppend(&str, pDecl->zDecl, i);
StringAppend(&str, pDecl->zExtra, 0);
StringAppend(&str, &pDecl->zDecl[i], 0);
SafeFree(pDecl->zDecl);
SafeFree(pDecl->zExtra);
pDecl->zDecl = StrDup(StringGet(&str), 0);
StringReset(&str);
pDecl->zExtra = 0;
}
/*
** Reset the DP_Forward and DP_Declared flags on all Decl structures.
** Set both flags for anything that is tagged as local and isn't
** in the file zFilename so that it won't be printing in other files.
*/
static void ResetDeclFlags(char *zFilename){
Decl *pDecl;
for(pDecl = pDeclFirst; pDecl; pDecl = pDecl->pNext){
DeclClearProperty(pDecl,DP_Forward|DP_Declared);
if( DeclHasProperty(pDecl,DP_Local) && pDecl->zFile!=zFilename ){
DeclSetProperty(pDecl,DP_Forward|DP_Declared);
}
}
}
/*
** Forward declaration of the ScanText() function.
*/
static void ScanText(const char*, GenState *pState);
/*
** The output in pStr is currently within an #if CONTEXT where context
** is equal to *pzIf. (*pzIf might be NULL to indicate that we are
** not within any #if at the moment.) We are getting ready to output
** some text that needs to be within the context of "#if NEW" where
** NEW is zIf. Make an appropriate change to the context.
*/
static void ChangeIfContext(
const char *zIf, /* The desired #if context */
GenState *pState /* Current state of the code generator */
){
if( zIf==0 ){
if( pState->zIf==0 ) return;
StringAppend(pState->pStr,"#endif\n",0);
pState->zIf = 0;
}else{
if( pState->zIf ){
if( strcmp(zIf,pState->zIf)==0 ) return;
StringAppend(pState->pStr,"#endif\n",0);
pState->zIf = 0;
}
ScanText(zIf, pState);
if( pState->zIf!=0 ){
StringAppend(pState->pStr,"#endif\n",0);
}
StringAppend(pState->pStr,"#if ",0);
StringAppend(pState->pStr,zIf,0);
StringAppend(pState->pStr,"\n",0);
pState->zIf = zIf;
}
}
/*
** Add to the string pStr a #include of every file on the list of
** include files pInclude. The table pTable contains all files that
** have already been #included at least once. Don't add any
** duplicates. Update pTable with every new #include that is added.
*/
static void AddIncludes(
Include *pInclude, /* Write every #include on this list */
GenState *pState /* Current state of the code generator */
){
if( pInclude ){
if( pInclude->pNext ){
AddIncludes(pInclude->pNext,pState);
}
if( IdentTableInsert(pState->pTable,pInclude->zLabel,0) ){
ChangeIfContext(pInclude->zIf,pState);
StringAppend(pState->pStr,"#include ",0);
StringAppend(pState->pStr,pInclude->zFile,0);
StringAppend(pState->pStr,"\n",1);
}
}
}
/*
** Add to the string pStr a declaration for the object described
** in pDecl.
**
** If pDecl has already been declared in this file, detect that
** fact and abort early. Do not duplicate a declaration.
**
** If the needFullDecl flag is false and this object has a forward
** declaration, then supply the forward declaration only. A later
** call to CompleteForwardDeclarations() will finish the declaration
** for us. But if needFullDecl is true, we must supply the full
** declaration now. Some objects do not have a forward declaration.
** For those objects, we must print the full declaration now.
**
** Because it is illegal to duplicate a typedef in C, care is taken
** to insure that typedefs for the same identifier are only issued once.
*/
static void DeclareObject(
Decl *pDecl, /* The thing to be declared */
GenState *pState, /* Current state of the code generator */
int needFullDecl /* Must have the full declaration. A forward
* declaration isn't enough */
){
Decl *p; /* The object to be declared */
int flag;
int isCpp; /* True if generating C++ */
int doneTypedef = 0; /* True if a typedef has been done for this object */
/* printf("BEGIN %s of %s\n",needFullDecl?"FULL":"PROTOTYPE",pDecl->zName);*/
/*
** For any object that has a forward declaration, go ahead and do the
** forward declaration first.
*/
isCpp = (pState->flags & DP_Cplusplus) != 0;
for(p=pDecl; p; p=p->pSameName){
if( p->zFwd ){
if( !DeclHasProperty(p,DP_Forward) ){
DeclSetProperty(p,DP_Forward);
if( strncmp(p->zFwd,"typedef",7)==0 ){
if( doneTypedef ) continue;
doneTypedef = 1;
}
ChangeIfContext(p->zIf,pState);
StringAppend(pState->pStr,isCpp ? p->zFwdCpp : p->zFwd,0);
}
}
}
/*
** Early out if everything is already suitably declared.
**
** This is a very important step because it prevents us from
** executing the code the follows in a recursive call to this
** function with the same value for pDecl.
*/
flag = needFullDecl ? DP_Declared|DP_Forward : DP_Forward;
for(p=pDecl; p; p=p->pSameName){
if( !DeclHasProperty(p,flag) ) break;
}
if( p==0 ){
return;
}
/*
** Make sure we have all necessary #includes
*/
for(p=pDecl; p; p=p->pSameName){
AddIncludes(p->pInclude,pState);
}
/*
** Go ahead an mark everything as being declared, to prevent an
** infinite loop thru the ScanText() function. At the same time,
** we decide which objects need a full declaration and mark them
** with the DP_Flag bit. We are only able to use DP_Flag in this
** way because we know we'll never execute this far into this
** function on a recursive call with the same pDecl. Hence, recursive
** calls to this function (through ScanText()) can never change the
** value of DP_Flag out from under us.
*/
for(p=pDecl; p; p=p->pSameName){
if( !DeclHasProperty(p,DP_Declared)
&& (p->zFwd==0 || needFullDecl)
&& p->zDecl!=0
){
DeclSetProperty(p,DP_Forward|DP_Declared|DP_Flag);
}else{
DeclClearProperty(p,DP_Flag);
}
}
/*
** Call ScanText() recusively (this routine is called from ScanText())
** to include declarations required to come before these declarations.
*/
for(p=pDecl; p; p=p->pSameName){
if( DeclHasProperty(p,DP_Flag) ){
if( p->zDecl[0]=='#' ){
ScanText(&p->zDecl[1],pState);
}else{
InsertExtraDecl(p);
ScanText(p->zDecl,pState);
}
}
}
/*
** Output the declarations. Do this in two passes. First
** output everything that isn't a typedef. Then go back and
** get the typedefs by the same name.
*/
for(p=pDecl; p; p=p->pSameName){
if( DeclHasProperty(p,DP_Flag) && !DeclHasProperty(p,TY_Typedef) ){
if( DeclHasAnyProperty(p,TY_Enumeration) ){
if( doneTypedef ) continue;
doneTypedef = 1;
}
ChangeIfContext(p->zIf,pState);
if( !isCpp && DeclHasAnyProperty(p,DP_ExternReqd) ){
StringAppend(pState->pStr,"extern ",0);
}else if( isCpp && DeclHasProperty(p,DP_Cplusplus|DP_ExternReqd) ){
StringAppend(pState->pStr,"extern ",0);
}else if( isCpp && DeclHasAnyProperty(p,DP_ExternCReqd|DP_ExternReqd) ){
StringAppend(pState->pStr,"extern \"C\" ",0);
}
InsertExtraDecl(p);
StringAppend(pState->pStr,p->zDecl,0);
if( !isCpp && DeclHasProperty(p,DP_Cplusplus) ){
fprintf(stderr,
"%s: C code ought not reference the C++ object \"%s\"\n",
pState->zFilename, p->zName);
pState->nErr++;
}
DeclClearProperty(p,DP_Flag);
}
}
for(p=pDecl; p && !doneTypedef; p=p->pSameName){
if( DeclHasProperty(p,DP_Flag) ){
/* This has to be a typedef */
doneTypedef = 1;
ChangeIfContext(p->zIf,pState);
InsertExtraDecl(p);
StringAppend(pState->pStr,p->zDecl,0);
}
}
}
/*
** This routine scans the input text given, and appends to the
** string in pState->pStr the text of any declarations that must
** occur before the text in zText.
**
** If an identifier in zText is immediately followed by '*', then
** only forward declarations are needed for that identifier. If the
** identifier name is not followed immediately by '*', we must supply
** a full declaration.
*/
static void ScanText(
const char *zText, /* The input text to be scanned */
GenState *pState /* Current state of the code generator */
){
int nextValid = 0; /* True is sNext contains valid data */
InStream sIn; /* The input text */
Token sToken; /* The current token being examined */
Token sNext; /* The next non-space token */
/* printf("BEGIN SCAN TEXT on %s\n", zText); */
sIn.z = zText;
sIn.i = 0;
sIn.nLine = 1;
while( sIn.z[sIn.i]!=0 ){
if( nextValid ){
sToken = sNext;
nextValid = 0;
}else{
GetNonspaceToken(&sIn,&sToken);
}
if( sToken.eType==TT_Id ){
int needFullDecl; /* True if we need to provide the full declaration,
** not just the forward declaration */
Decl *pDecl; /* The declaration having the name in sToken */
/*
** See if there is a declaration in the database with the name given
** by sToken.
*/
pDecl = FindDecl(sToken.zText,sToken.nText);
if( pDecl==0 ) continue;
/*
** If we get this far, we've found an identifier that has a
** declaration in the database. Now see if we the full declaration
** or just a forward declaration.
*/
GetNonspaceToken(&sIn,&sNext);
if( sNext.zText[0]=='*' ){
needFullDecl = 0;
}else{
needFullDecl = 1;
nextValid = sNext.eType==TT_Id;
}
/*
** Generate the needed declaration.
*/
DeclareObject(pDecl,pState,needFullDecl);
}else if( sToken.eType==TT_Preprocessor ){
sIn.i -= sToken.nText - 1;
}
}
/* printf("END SCANTEXT\n"); */
}
/*
** Provide a full declaration to any object which so far has had only
** a foward declaration.
*/
static void CompleteForwardDeclarations(GenState *pState){
Decl *pDecl;
int progress;
do{
progress = 0;
for(pDecl=pDeclFirst; pDecl; pDecl=pDecl->pNext){
if( DeclHasProperty(pDecl,DP_Forward)
&& !DeclHasProperty(pDecl,DP_Declared)
){
DeclareObject(pDecl,pState,1);
progress = 1;
assert( DeclHasProperty(pDecl,DP_Declared) );
}
}
}while( progress );
}
/*
** Generate an include file for the given source file. Return the number
** of errors encountered.
**
** if nolocal_flag is true, then we do not generate declarations for
** objected marked DP_Local.
*/
static int MakeHeader(InFile *pFile, FILE *report, int nolocal_flag){
int nErr = 0;
GenState sState;
String outStr;
IdentTable includeTable;
Ident *pId;
char *zNewVersion;
char *zOldVersion;
if( pFile->zHdr==0 || *pFile->zHdr==0 ) return 0;
sState.pStr = &outStr;
StringInit(&outStr);
StringAppend(&outStr,zTopLine,nTopLine);
sState.pTable = &includeTable;
memset(&includeTable,0,sizeof(includeTable));
sState.zIf = 0;
sState.nErr = 0;
sState.zFilename = pFile->zSrc;
sState.flags = pFile->flags & DP_Cplusplus;
ResetDeclFlags(nolocal_flag ? "no" : pFile->zSrc);
for(pId = pFile->idTable.pList; pId; pId=pId->pNext){
Decl *pDecl = FindDecl(pId->zName,0);
if( pDecl ){
DeclareObject(pDecl,&sState,1);
}
}
CompleteForwardDeclarations(&sState);
ChangeIfContext(0,&sState);
nErr += sState.nErr;
zOldVersion = ReadFile(pFile->zHdr);
zNewVersion = StringGet(&outStr);
if( report ) fprintf(report,"%s: ",pFile->zHdr);
if( zOldVersion==0 ){
if( report ) fprintf(report,"updated\n");
if( WriteFile(pFile->zHdr,zNewVersion) ){
fprintf(stderr,"%s: Can't write to file\n",pFile->zHdr);
nErr++;
}
}else if( strncmp(zOldVersion,zTopLine,nTopLine)!=0 ){
if( report ) fprintf(report,"error!\n");
fprintf(stderr,
"%s: Can't overwrite this file because it wasn't previously\n"
"%*s generated by 'makeheaders'.\n",
pFile->zHdr, (int)strlen(pFile->zHdr), "");
nErr++;
}else if( strcmp(zOldVersion,zNewVersion)!=0 ){
if( report ) fprintf(report,"updated\n");
if( WriteFile(pFile->zHdr,zNewVersion) ){
fprintf(stderr,"%s: Can't write to file\n",pFile->zHdr);
nErr++;
}
}else if( report ){
fprintf(report,"unchanged\n");
}
SafeFree(zOldVersion);
IdentTableReset(&includeTable);
StringReset(&outStr);
return nErr;
}
/*
** Generate a global header file -- a header file that contains all
** declarations. If the forExport flag is true, then only those
** objects that are exported are included in the header file.
*/
static int MakeGlobalHeader(int forExport){
GenState sState;
String outStr;
IdentTable includeTable;
Decl *pDecl;
sState.pStr = &outStr;
StringInit(&outStr);
/* StringAppend(&outStr,zTopLine,nTopLine); */
sState.pTable = &includeTable;
memset(&includeTable,0,sizeof(includeTable));
sState.zIf = 0;
sState.nErr = 0;
sState.zFilename = "(all)";
sState.flags = 0;
ResetDeclFlags(0);
for(pDecl=pDeclFirst; pDecl; pDecl=pDecl->pNext){
if( forExport==0 || DeclHasProperty(pDecl,DP_Export) ){
DeclareObject(pDecl,&sState,1);
}
}
ChangeIfContext(0,&sState);
printf("%s",StringGet(&outStr));
IdentTableReset(&includeTable);
StringReset(&outStr);
return 0;
}
#ifdef DEBUG
/*
** Return the number of characters in the given string prior to the
** first newline.
*/
static int ClipTrailingNewline(char *z){
int n = strlen(z);
while( n>0 && (z[n-1]=='\n' || z[n-1]=='\r') ){ n--; }
return n;
}
/*
** Dump the entire declaration list for debugging purposes
*/
static void DumpDeclList(void){
Decl *pDecl;
for(pDecl = pDeclFirst; pDecl; pDecl=pDecl->pNext){
printf("**** %s from file %s ****\n",pDecl->zName,pDecl->zFile);
if( pDecl->zIf ){
printf("If: [%.*s]\n",ClipTrailingNewline(pDecl->zIf),pDecl->zIf);
}
if( pDecl->zFwd ){
printf("Decl: [%.*s]\n",ClipTrailingNewline(pDecl->zFwd),pDecl->zFwd);
}
if( pDecl->zDecl ){
InsertExtraDecl(pDecl);
printf("Def: [%.*s]\n",ClipTrailingNewline(pDecl->zDecl),pDecl->zDecl);
}
if( pDecl->flags ){
static struct {
int mask;
char *desc;
} flagSet[] = {
{ TY_Class, "class" },
{ TY_Enumeration, "enum" },
{ TY_Structure, "struct" },
{ TY_Union, "union" },
{ TY_Variable, "variable" },
{ TY_Subroutine, "function" },
{ TY_Typedef, "typedef" },
{ TY_Macro, "macro" },
{ DP_Export, "export" },
{ DP_Local, "local" },
{ DP_Cplusplus, "C++" },
};
int i;
printf("flags:");
for(i=0; i<sizeof(flagSet)/sizeof(flagSet[0]); i++){
if( flagSet[i].mask & pDecl->flags ){
printf(" %s", flagSet[i].desc);
}
}
printf("\n");
}
if( pDecl->pInclude ){
Include *p;
printf("includes:");
for(p=pDecl->pInclude; p; p=p->pNext){
printf(" %s",p->zFile);
}
printf("\n");
}
}
}
#endif
/*
** When the "-doc" command-line option is used, this routine is called
** to print all of the database information to standard output.
*/
static void DocumentationDump(void){
Decl *pDecl;
static struct {
int mask;
char flag;
} flagSet[] = {
{ TY_Class, 'c' },
{ TY_Enumeration, 'e' },
{ TY_Structure, 's' },
{ TY_Union, 'u' },
{ TY_Variable, 'v' },
{ TY_Subroutine, 'f' },
{ TY_Typedef, 't' },
{ TY_Macro, 'm' },
{ DP_Export, 'x' },
{ DP_Local, 'l' },
{ DP_Cplusplus, '+' },
};
for(pDecl = pDeclFirst; pDecl; pDecl=pDecl->pNext){
int i;
int nLabel = 0;
char *zDecl;
char zLabel[50];
for(i=0; i<sizeof(flagSet)/sizeof(flagSet[0]); i++){
if( DeclHasProperty(pDecl,flagSet[i].mask) ){
zLabel[nLabel++] = flagSet[i].flag;
}
}
if( nLabel==0 ) continue;
zLabel[nLabel] = 0;
InsertExtraDecl(pDecl);
zDecl = pDecl->zDecl;
if( zDecl==0 ) zDecl = pDecl->zFwd;
printf("%s %s %s %p %d %d %d %d %d\n",
pDecl->zName,
zLabel,
pDecl->zFile,
pDecl->pComment,
pDecl->pComment ? pDecl->pComment->nText+1 : 0,
pDecl->zIf ? (int)strlen(pDecl->zIf)+1 : 0,
zDecl ? (int)strlen(zDecl) : 0,
pDecl->pComment ? pDecl->pComment->nLine : 0,
pDecl->tokenCode.nText ? pDecl->tokenCode.nText+1 : 0
);
if( pDecl->pComment ){
printf("%.*s\n",pDecl->pComment->nText, pDecl->pComment->zText);
}
if( pDecl->zIf ){
printf("%s\n",pDecl->zIf);
}
if( zDecl ){
printf("%s",zDecl);
}
if( pDecl->tokenCode.nText ){
printf("%.*s\n",pDecl->tokenCode.nText, pDecl->tokenCode.zText);
}
}
}
/*
** Given the complete text of an input file, this routine prints a
** documentation record for the header comment at the beginning of the
** file (if the file has a header comment.)
*/
void PrintModuleRecord(const char *zFile, const char *zFilename){
int i;
static int addr = 5;
while( isspace(*zFile) ){ zFile++; }
if( *zFile!='/' || zFile[1]!='*' ) return;
for(i=2; zFile[i] && (zFile[i-1]!='/' || zFile[i-2]!='*'); i++){}
if( zFile[i]==0 ) return;
printf("%s M %s %d %d 0 0 0 0\n%.*s\n",
zFilename, zFilename, addr, i+1, i, zFile);
addr += 4;
}
/*
** Given an input argument to the program, construct a new InFile
** object.
*/
static InFile *CreateInFile(char *zArg, int *pnErr){
int nSrc;
char *zSrc;
InFile *pFile;
int i;
/*
** Get the name of the input file to be scanned. The input file is
** everything before the first ':' or the whole file if no ':' is seen.
**
** Except, on windows, ignore any ':' that occurs as the second character
** since it might be part of the drive specifier. So really, the ":' has
** to be the 3rd or later character in the name. This precludes 1-character
** file names, which really should not be a problem.
*/
zSrc = zArg;
for(nSrc=2; zSrc[nSrc] && zArg[nSrc]!=':'; nSrc++){}
pFile = SafeMalloc( sizeof(InFile) );
memset(pFile,0,sizeof(InFile));
pFile->zSrc = StrDup(zSrc,nSrc);
/* Figure out if we are dealing with C or C++ code. Assume any
** file with ".c" or ".h" is C code and all else is C++.
*/
if( nSrc>2 && zSrc[nSrc-2]=='.' && (zSrc[nSrc-1]=='c' || zSrc[nSrc-1]=='h' || zSrc[nSrc-1]=='m')){
pFile->flags &= ~DP_Cplusplus;
}else{
pFile->flags |= DP_Cplusplus;
}
/*
** If a separate header file is specified, use it
*/
if( zSrc[nSrc]==':' ){
int nHdr;
char *zHdr;
zHdr = &zSrc[nSrc+1];
for(nHdr=0; zHdr[nHdr] && zHdr[nHdr]!=':'; nHdr++){}
pFile->zHdr = StrDup(zHdr,nHdr);
}
/* Look for any 'c' or 'C' in the suffix of the file name and change
** that character to 'h' or 'H' respectively. If no 'c' or 'C' is found,
** then assume we are dealing with a header.
*/
else{
int foundC = 0;
pFile->zHdr = StrDup(zSrc,nSrc);
for(i = nSrc-1; i>0 && pFile->zHdr[i]!='.'; i--){
if( pFile->zHdr[i]=='c' || pFile->zHdr[i]=='m' ){
foundC = 1;
pFile->zHdr[i] = 'h';
}else if( pFile->zHdr[i]=='C' ){
foundC = 1;
pFile->zHdr[i] = 'H';
}
}
if( !foundC ){
SafeFree(pFile->zHdr);
pFile->zHdr = 0;
}
}
/*
** If pFile->zSrc contains no 'c' or 'C' in its extension, it
** must be a header file. In that case, we need to set the
** PS_Interface flag.
*/
pFile->flags |= PS_Interface;
for(i=nSrc-1; i>0 && zSrc[i]!='.'; i--){
if( zSrc[i]=='c' || zSrc[i]=='C' || zSrc[i]=='m' ){
pFile->flags &= ~PS_Interface;
break;
}
}
/* Done!
*/
return pFile;
}
/* MS-Windows and MS-DOS both have the following serious OS bug: the
** length of a command line is severely restricted. But this program
** occasionally requires long command lines. Hence the following
** work around.
**
** If the parameters "-f FILENAME" appear anywhere on the command line,
** then the named file is scanned for additional command line arguments.
** These arguments are substituted in place of the "FILENAME" argument
** in the original argument list.
**
** This first parameter to this routine is the index of the "-f"
** parameter in the argv[] array. The argc and argv are passed by
** pointer so that they can be changed.
**
** Parsing of the parameters in the file is very simple. Parameters
** can be separated by any amount of white-space (including newlines
** and carriage returns.) There are now quoting characters of any
** kind. The length of a token is limited to about 1000 characters.
*/
static void AddParameters(int index, int *pArgc, char ***pArgv){
int argc = *pArgc; /* The original argc value */
char **argv = *pArgv; /* The original argv value */
int newArgc; /* Value for argc after inserting new arguments */
char **zNew = 0; /* The new argv after this routine is done */
char *zFile; /* Name of the input file */
int nNew = 0; /* Number of new entries in the argv[] file */
int nAlloc = 0; /* Space allocated for zNew[] */
int i; /* Loop counter */
int n; /* Number of characters in a new argument */
int c; /* Next character of input */
int startOfLine = 1; /* True if we are where '#' can start a comment */
FILE *in; /* The input file */
char zBuf[1000]; /* A single argument is accumulated here */
if( index+1==argc ) return;
zFile = argv[index+1];
in = fopen(zFile,"r");
if( in==0 ){
fprintf(stderr,"Can't open input file \"%s\"\n",zFile);
exit(1);
}
c = ' ';
while( c!=EOF ){
while( c!=EOF && isspace(c) ){
if( c=='\n' ){
startOfLine = 1;
}
c = getc(in);
if( startOfLine && c=='#' ){
while( c!=EOF && c!='\n' ){
c = getc(in);
}
}
}
n = 0;
while( c!=EOF && !isspace(c) ){
if( n<sizeof(zBuf)-1 ){ zBuf[n++] = c; }
startOfLine = 0;
c = getc(in);
}
zBuf[n] = 0;
if( n>0 ){
nNew++;
if( nNew + argc > nAlloc ){
if( nAlloc==0 ){
nAlloc = 100 + argc;
zNew = malloc( sizeof(char*) * nAlloc );
}else{
nAlloc *= 2;
zNew = realloc( zNew, sizeof(char*) * nAlloc );
}
}
if( zNew ){
int j = nNew + index;
zNew[j] = malloc( n + 1 );
if( zNew[j] ){
strcpy( zNew[j], zBuf );
}
}
}
}
newArgc = argc + nNew - 1;
for(i=0; i<=index; i++){
zNew[i] = argv[i];
}
for(i=nNew + index + 1; i<newArgc; i++){
zNew[i] = argv[i + 1 - nNew];
}
zNew[newArgc] = 0;
*pArgc = newArgc;
*pArgv = zNew;
}
#ifdef NOT_USED
/*
** Return the time that the given file was last modified. If we can't
** locate the file (because, for example, it doesn't exist), then
** return 0.
*/
static unsigned int ModTime(const char *zFilename){
unsigned int mTime = 0;
struct stat sStat;
if( stat(zFilename,&sStat)==0 ){
mTime = sStat.st_mtime;
}
return mTime;
}
#endif
/*
** Print a usage comment for this program.
*/
static void Usage(const char *argv0, const char *argvN){
fprintf(stderr,"%s: Illegal argument \"%s\"\n",argv0,argvN);
fprintf(stderr,"Usage: %s [options] filename...\n"
"Options:\n"
" -h Generate a single .h to standard output.\n"
" -H Like -h, but only output EXPORT declarations.\n"
" -v (verbose) Write status information to the screen.\n"
" -doc Generate no header files. Instead, output information\n"
" that can be used by an automatic program documentation\n"
" and cross-reference generator.\n"
" -local Generate prototypes for \"static\" functions and\n"
" procedures.\n"
" -f FILE Read additional command-line arguments from the file named\n"
" \"FILE\".\n"
#ifdef DEBUG
" -! MASK Set the debugging mask to the number \"MASK\".\n"
#endif
" -- Treat all subsequent comment-line parameters as filenames,\n"
" even if they begin with \"-\".\n",
argv0
);
}
/*
** The following text contains a few simple #defines that we want
** to be available to every file.
*/
static char zInit[] =
"#define INTERFACE 0\n"
"#define EXPORT_INTERFACE 0\n"
"#define LOCAL_INTERFACE 0\n"
"#define EXPORT\n"
"#define LOCAL static\n"
"#define PUBLIC\n"
"#define PRIVATE\n"
"#define PROTECTED\n"
;
#if TEST==0
int main(int argc, char **argv){
int i; /* Loop counter */
int nErr = 0; /* Number of errors encountered */
Token *pList; /* List of input tokens for one file */
InFile *pFileList = 0;/* List of all input files */
InFile *pTail = 0; /* Last file on the list */
InFile *pFile; /* for looping over the file list */
int h_flag = 0; /* True if -h is present. Output unified header */
int H_flag = 0; /* True if -H is present. Output EXPORT header */
int v_flag = 0; /* Verbose */
int noMoreFlags; /* True if -- has been seen. */
FILE *report; /* Send progress reports to this, if not NULL */
noMoreFlags = 0;
for(i=1; i<argc; i++){
if( argv[i][0]=='-' && !noMoreFlags ){
switch( argv[i][1] ){
case 'h': h_flag = 1; break;
case 'H': H_flag = 1; break;
case 'v': v_flag = 1; break;
case 'd': doc_flag = 1; proto_static = 1; break;
case 'l': proto_static = 1; break;
case 'f': AddParameters(i, &argc, &argv); break;
case '-': noMoreFlags = 1; break;
#ifdef DEBUG
case '!': i++; debugMask = strtol(argv[i],0,0); break;
#endif
default: Usage(argv[0],argv[i]); return 1;
}
}else{
pFile = CreateInFile(argv[i],&nErr);
if( pFile ){
if( pFileList ){
pTail->pNext = pFile;
pTail = pFile;
}else{
pFileList = pTail = pFile;
}
}
}
}
if( h_flag && H_flag ){
h_flag = 0;
}
if( v_flag ){
report = (h_flag || H_flag) ? stderr : stdout;
}else{
report = 0;
}
if( nErr>0 ){
return nErr;
}
for(pFile=pFileList; pFile; pFile=pFile->pNext){
char *zFile;
zFilename = pFile->zSrc;
if( zFilename==0 ) continue;
zFile = ReadFile(zFilename);
if( zFile==0 ){
fprintf(stderr,"Can't read input file \"%s\"\n",zFilename);
nErr++;
continue;
}
if( strncmp(zFile,zTopLine,nTopLine)==0 ){
pFile->zSrc = 0;
}else{
if( report ) fprintf(report,"Reading %s...\n",zFilename);
pList = TokenizeFile(zFile,&pFile->idTable);
if( pList ){
nErr += ParseFile(pList,pFile->flags);
FreeTokenList(pList);
}else if( zFile[0]==0 ){
fprintf(stderr,"Input file \"%s\" is empty.\n", zFilename);
nErr++;
}else{
fprintf(stderr,"Errors while processing \"%s\"\n", zFilename);
nErr++;
}
}
if( !doc_flag ) SafeFree(zFile);
if( doc_flag ) PrintModuleRecord(zFile,zFilename);
}
if( nErr>0 ){
return nErr;
}
#ifdef DEBUG
if( debugMask & DECL_DUMP ){
DumpDeclList();
return nErr;
}
#endif
if( doc_flag ){
DocumentationDump();
return nErr;
}
zFilename = "--internal--";
pList = TokenizeFile(zInit,0);
if( pList==0 ){
return nErr+1;
}
ParseFile(pList,PS_Interface);
FreeTokenList(pList);
if( h_flag || H_flag ){
nErr += MakeGlobalHeader(H_flag);
}else{
for(pFile=pFileList; pFile; pFile=pFile->pNext){
if( pFile->zSrc==0 ) continue;
nErr += MakeHeader(pFile,report,0);
}
}
return nErr;
}
#endif
|
the_stack_data/117327859.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
double f1(double x,double a){
double tem=a-x*x;
tem=pow(tem,0.5L);
return fabs(tem);
}
double f2(double x,double a){
double tem=(a*x*x*x+7.0L*x)/pow(a+x,0.5L);
return fabs(tem);
}
double (*farr[2])(double,double)={f1,f2};
double t(double (*fun)(double ,double),double a,double p,double q,int n){
double out=0.0;
double up=(q-p)/n;
double d=2.0;
int i;
for(i=0;i<n+1;i++){
double tem=fun(p+i*up,a);
if(i!=0&&i!=n)tem*=2.0L;
out+=tem;
}
return out/2.0L*up;
}
int input(){
int intype=0;
int i,j;
double p,q,a,err;
long long int n=1;
scanf("%d",&intype);
if(intype==0)return 0;
scanf("%lf%lf%lf%lf",&a,&p,&q,&err);
double last=0.0;
double now=0.0;
while(1){
now=t(farr[intype-1],a,p,q,n);
if(n!=1){
if(fabs(now-last)<pow(0.1,err)){
printf("%.12lf\n",now);
break;
}
}
n=n<<1;
last=now;
}
input();
}
int main(){
input();
return 0;
}
|
the_stack_data/231393228.c | double r_sqrt(x)
float *x;
{
double sqrt();
return( sqrt(*x) );
}
|
the_stack_data/168893398.c | /*
*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2019 Broadcom Inc. All rights reserved.
*
* File: test.c
* Purpose: entry point for all tr related routines
*/
#ifdef INCLUDE_TEST
#include <shared/bsl.h>
#include <sal/types.h>
#include <sal/core/libc.h>
#include <shared/bsl.h>
#include <soc/debug.h>
#include <soc/drv.h>
#include <appl/diag/system.h>
#include <appl/diag/test.h>
#include <appl/diag/progress.h>
#ifndef NO_CTRL_C
#include <setjmp.h>
#endif
#ifdef __KERNEL__
#define atoi _shr_ctoi
#endif
/*
* Variable: test_XXX_usage
* Purpose: usage strings for various tests.
*/
#define TEST_ID_USAGE \
"\"Test ID\" is a test #, test name, or \"*\"\n"
char test_list_usage[] =
"Parameters: [Test ID] ...\n\t"
"Display the tests specified by [Test ID] in table format,\n\t"
"A=active, S=selected, # Runs = number times test dispatched, \n\t"
"# Pass = number times test completed successfully, \n\t"
"# Fail = number times test completed with a failure\n\t"
TEST_ID_USAGE;
static test_t *test_active = NULL; /* Pointer to active test */
static sal_thread_t test_thread = NULL; /* Pointer to test thread */
/*
* variables: test_active_jmp
* Purpose: Long jump buffer used to return from a running
* test such as "test_exit" call.
*/
#ifndef NO_CTRL_C
static jmp_buf test_active_jmp; /* test_exit Long jump */
#endif
/*
* Defines: TEST_XXX
* Purpose: Return values from longjmp indicating action to
* take (also return value from some of the "run"
* routines.
*
* TEST_RUNNING - (0), normal return from longjmp
* TEST_ABORT - (1), abort current test, continue running
* test sequence.
* TEST_STOP - (2), abort current test, AND test sequence.
* TEST_CONTINUE- (3), continue running test and sequence
* TEST_INTR - (4), test aborted by CTRL-C
*/
#define TEST_RUNNING 0
#define TEST_ABORT 1
#define TEST_STOP 2
#define TEST_CONTINUE 3
#define TEST_INTR 4
#define TEST_O_SOE 0x01 /* Stop on Error */
#define TEST_O_AOE 0x02 /* Abort on Error */
#define TEST_O_BATCH 0x04 /* Batch Mode */
#define TEST_O_RANDOM 0x08 /* Random Mode */
#define TEST_O_PROGRESS 0x10 /* Print test progress */
#define TEST_O_SILENT 0x20 /* Don't print test error msgs */
#define TEST_O_RUN 0x40 /* Print msg when test run */
#define TEST_O_OVERRIDE 0x80 /* Override Chips */
#define TEST_O_QUIET 0x100 /* Don't print messages */
#define TEST_O_NO_REINIT 0x200 /* No reinit */
static uint32 test_options = 0; /* Run options */
static int last_test_status[SOC_MAX_NUM_DEVICES] = {0}; /* Store the last test runs status */
/*
* Approach changed from 1 global testlist to dynamic list assignment for whatever reason one chose
* It may be SOC_IS based as in case of Jericho2/Ramon, or any other one
* So this routine allows caller to assigns test_list and test_cnt local values instead of global ones
*/
static test_t *get_test_list(int unit, int *test_cnt_p)
{
#if defined(BCM_SAND_SUPPORT)
/* For now only Jericho 2 and Ramon will utilize sand_test_list, but we may consider to moving all the dune
* chip families due to lack of bits in common_test_list
*/
if(SOC_IS_DNX(unit) || SOC_IS_DNXF(unit))
{
*test_cnt_p = sand_test_cnt;
return sand_test_list;
}
else
#endif
{
*test_cnt_p = common_test_cnt;
return common_test_list;
}
}
int
test_is_no_reinit_mode(int unit)
{
return ((test_options & TEST_O_NO_REINIT) > 0);
}
int
test_get_last_test_status(int unit)
{
assert((unit < SOC_MAX_NUM_DEVICES) && (unit >= 0));
return last_test_status[unit];
}
STATIC uint32
_test_chip(int unit)
/*
* Function: _test_chip
* Purpose: Return current T56xx mask based on unit #.
* Parameters: Unit - Strata Swtich unit #.
* Returns: Mask.
*/
{
if (!soc_attached(unit)) {
return(0);
}
switch (SOC_CHIP_GROUP(unit)) {
#if defined (BCM_SAND_SUPPORT)
case SOC_CHIP_BCM88650: return(T88650);
case SOC_CHIP_BCM88660: return(T88650);
case SOC_CHIP_BCM88675: return(T88675);
case SOC_CHIP_BCM88375: return(T88675);
case SOC_CHIP_BCM88680: return(T88675);
case SOC_CHIP_BCM88470: return(T88675);
case SOC_CHIP_BCM83208: return(T88675);
case SOC_CHIP_BCM88202: return(T88650);
case SOC_CHIP_BCM88750: return(T88750);
case SOC_CHIP_BCM88270: return(T88675);
case SOC_CHIP_BCM88950: return(T88750);
case SOC_CHIP_BCM88952: return(T88750);
case SOC_CHIP_BCM88752: return(T88750);
/* Starting from Jericho 2 and Ramon there is another test_list with new bitmap TSxxxxx instead of Txxxxx */
case SOC_CHIP_BCM8869X: return(TS88690);
case SOC_CHIP_BCM8879X: return(TS88790);
#endif
#if defined(BCM_ESW_SUPPORT)
case SOC_CHIP_BCM5675: return(T5675);
case SOC_CHIP_BCM56102: return(T56504);
case SOC_CHIP_BCM56304: return(T56504);
case SOC_CHIP_BCM56112: return(T56504);
case SOC_CHIP_BCM56314: return(T56504);
case SOC_CHIP_BCM56504: return(T56504);
case SOC_CHIP_BCM56514: return(T56504);
case SOC_CHIP_BCM56800:
if (SOC_IS_HUMV(unit)) {
return(T56700);
} else {
return(T56504);
}
case SOC_CHIP_BCM56820: return(T56820);
case SOC_CHIP_BCM56725: return(T56700);
case SOC_CHIP_BCM56624: return(T56624);
case SOC_CHIP_BCM56680: return(T56624);
case SOC_CHIP_BCM56218: return(T56218);
case SOC_CHIP_BCM56224: return(T56224);
case SOC_CHIP_BCM53314: return(T53314);
case SOC_CHIP_BCM56634: return(T56634);
case SOC_CHIP_BCM56524: return(T56634);
case SOC_CHIP_BCM56685: return(T56634);
case SOC_CHIP_BCM56334: return(T56334);
case SOC_CHIP_BCM56142: return(T56142);
case SOC_CHIP_BCM56150: return(T56150);
case SOC_CHIP_BCM56160: return(T56160);
case SOC_CHIP_BCM53540: return(T56160);
case SOC_CHIP_BCM53400: return(T53400);
case SOC_CHIP_BCM88732: return(T88732);
case SOC_CHIP_BCM56840: return(T56840);
case SOC_CHIP_BCM56640: return(T56640);
case SOC_CHIP_BCM56340: return(T56340);
case SOC_CHIP_BCM56440: return(T56440);
case SOC_CHIP_BCM56450: return(T56450);
case SOC_CHIP_BCM56260: return(T56260);
case SOC_CHIP_BCM56270: return(T56270);
case SOC_CHIP_BCM56850: return(T56850);
case SOC_CHIP_BCM56860: return(T56860);
case SOC_CHIP_BCM56960: return(T56960);
case SOC_CHIP_BCM56965: return(T56960);
case SOC_CHIP_BCM56980: return(T56980);
case SOC_CHIP_BCM56560: return(T56560);
case SOC_CHIP_BCM56870: return(T56870);
case SOC_CHIP_BCM53570: return(T53570);
case SOC_CHIP_BCM56970: return(T56970);
case SOC_CHIP_BCM56770: return(T56770);
case SOC_CHIP_BCM56370: return(T56370);
case SOC_CHIP_BCM56670: return(T56670);
#endif
default: return(0);
}
}
static test_t *
test_find(char *key, test_t *test_list, int test_cnt)
/*
* Function: test_find
* Purpose: Location a matching entry in the TEST test list.
* Parameters: key - key to lookup name on
* Returns: Pointer to entry if found, NULL if no match
* Notes: If key is all digits (0-9), it is assumed top be a test
* number otherwise it is a test name.
*/
{
test_t *test = NULL;
int ki, kl; /* Key integer/length */
int i;
if (isint(key)) { /* Locate on test number */
ki = atoi(key);
for (i = 0; !test && (i < test_cnt); i++) {
if (test_list[i].t_test == ki) {
test = &test_list[i];
}
}
} else { /* Locate Based on name */
kl = strlen(key);
for (i = 0; !test && (i < test_cnt); i++) {
if (!sal_strncasecmp(key, test_list[i].t_name, kl)) {
test = &test_list[i];
}
}
}
return(test);
}
void
test_done(int u, test_t *test, int status)
/*
* Function: test_done
* Purpose: Process the completion of a test
* Parameters: u - unit number.
* test - pointer to test completed.
* status - exit status of test.
* Returns: Nothing.
*/
{
if (status || (test->t_flags & T_F_ERROR)) {
last_test_status[u] = -1;
test->t_fail++;
LOG_INFO(BSL_LS_APPL_TESTS,
(BSL_META_U(u,
"Test %d (%s) Completed with error (%d)\n"),
test->t_test, test->t_name, status));
/*
* If Stop-on-error not processed yet, give user a chance
* now.
*/
if ((status == TEST_ABORT) || (status == TEST_STOP)) {
cli_out("Test %d (%s) Aborted\n", test->t_test, test->t_name);
} else if ((test_options & TEST_O_SOE) &&
!(test->t_flags & T_F_STOP)) {
test_error(u,
"Stop-on-error: Test %d (%s) completed with error\n",
test->t_test, test->t_name);
}
} else {
last_test_status[u] = 0;
test->t_success++;
LOG_INFO(BSL_LS_APPL_TESTS,
(BSL_META_U(u,
"Test %d (%s) Completed successfully\n"),
test->t_test, test->t_name));
}
}
void
test_exit(int u, int status)
/*
* Function: test_exit
* Purpose: To exit the currently running test.
* Parameters: status - the exit status, 0 for success, -1 for failure.
* Returns: Does not return
*/
{
test_done(u, test_active, status);
#ifndef NO_CTRL_C
longjmp(test_active_jmp, 1);
#endif
}
int
test_test_init(int u, test_t *test, args_t *a, void **fp)
/*
* Function: test_test_init
* Purpose: Run initialization scripts and routines for a specified test.
* Parameters: u - unit #
* test - pointer to test description.
* a - pointer to arguments.
* fp - cookie passed back to test routine.
* Returns: 0 - success
* -1 - failed.
*/
{
int rv = 0;
*fp = NULL;
if (sh_set_rctest && (test->t_flags & T_F_RC)) {
var_set_integer("testinit", test->t_test, 0, 0);
#if defined(BCM_ESW_SUPPORT)
#ifndef NO_SAL_APPL
if (SOC_IS_XGS(u)) {
if (diag_rc_load(u) != CMD_OK) {
cli_out("Test: ERROR: RC init script for test %d (%s) failed\n",
test->t_test, test->t_name);
rv = -1;
}
}
#endif
#endif
var_unset("testinit", 0, 1, 0);
if (rv) {
return(rv);
}
}
if (test->t_init_f) { /* Call init function */
rv = test->t_init_f(u, a, fp);
/* check if return value is != BCM_E_UNAVAIL because the memory test on the internal
* memories will return BCM_E_UNAVAIL if External TCAM is present. Those memories shouldn't
* be tested instead should be skipped. */
if (rv && (rv != BCM_E_UNAVAIL)) {
cli_out("Test: ERROR: Init function for test %d (%s) failed\n",
test->t_test, test->t_name);
rv = -1;
}
}
return(rv);
}
/*
* Function: test_test_done
* Purpose: Run done scripts and routines for a specified test.
* Parameters: u - unit #
* test - pointer to test description.
* fp - value returned from init function.
* Returns: 0 - success
* -1 - failed.
*/
int
test_test_done(int u, test_t *test, void *fp)
{
int rv = 0;
if (test->t_done_f) { /* Call done function */
if (test->t_done_f(u, fp)) {
cli_out("Test: ERROR: Done function for test %d (%s) failed\n",
test->t_test, test->t_name);
rv = -1;
}
}
test->t_flags &= ~(T_F_ACTIVE|T_F_STOP|T_F_ERROR);
test_active = NULL;
test_thread = NULL;
if (test_options & TEST_O_RUN) {
cli_out("Test %d (%s) Completed\n", test->t_test, test->t_name);
}
return(rv);
}
int
test_dispatch(int u, test_t *test, int loops, args_t *a)
/*
* Function: test_dispatch
* Purpose: Run a selected test.
* Parameters: test - Pointer to test entry to run.
* loops - # of iterations, if -1 count taken from test default.
* a - arguments to pass to test.
* Returns: TEST_XXX
*/
{
jmp_buf jmp; /* ^C out of tests must be trapped */
int i; /* Loop counter */
int error; /* No error */
int arg_saved;
volatile int vloops = loops; /* "loops"/setjmp clobber war */
args_t * volatile av = a;
args_t * volatile args = 0;
void * volatile fp; /* Test function pointer parameter */
volatile int cleanup = FALSE;
int rv;
/* Check if test supported */
if (!(test->t_flags & _test_chip(u))) {
if (test_options & TEST_O_OVERRIDE) {
cli_out("Warning: Running test %d (%s) not supported on %s\n",
test->t_test, test->t_name, SOC_UNIT_GROUP(u));
}
}
if (test_options & TEST_O_RUN) {
cli_out("Test %d (%s) Started\n", test->t_test, test->t_name);
}
COMPILER_REFERENCE(cleanup);
error = TEST_RUNNING;
#ifndef NO_CTRL_C
if (TEST_RUNNING != (error = setjmp(jmp))) { /* Control C handler */
if (test_active) {
if (cleanup) {
cli_out("Warning: Cleanup aborted - "
"continue at your own risk\n");
} else {
cleanup = TRUE;
cli_out("Warning: cleaning up active test: %s\n",
test_active->t_name);
test->t_flags |= T_F_STOP; /* Say processed stop */
test_done(u, test_active, error);
test_test_done(u, test_active, fp);
if (args) {
sal_free(args);
}
}
sh_pop_ctrl_c();
test_thread = NULL;
test_active = NULL;
return(TEST_INTR);
}
}
#endif
sh_push_ctrl_c(&jmp);
test_thread = sal_thread_self();
/* If no arguments passed in, use default args */
error = TEST_ABORT;
if (!av) {
if ((av = args = sal_alloc(sizeof(args_t), "test_args")) == NULL) {
goto return_no_free;
}
if (diag_parse_args(test->t_override_string ?
test->t_override_string : test->t_default_string,
NULL,
av)) {
test->t_fail++;
last_test_status[u] = -1;
goto return_with_free;
}
}
fp = NULL;
if (-1 == vloops) { /* Assign AFTER setjmp */
vloops = test->t_loops; /* Use default */
}
test_active = test;
test->t_flags |= T_F_ACTIVE;
arg_saved = av->a_arg; /* Some may be consumed */
rv = test_test_init(u, test, av, (void **)&fp);
/* check if return value is != BCM_E_UNAVAIL because the memory test on the internal
* memories will return BCM_E_UNAVAIL if External TCAM is present. Those memories shouldn't
* be tested instead should be skipped. */
if ((rv != BCM_E_UNAVAIL) && (rv)){
test->t_runs++; /* Increment RUN/FAIL count */
test->t_fail++;
last_test_status[u] = -1;
test->t_flags &= ~T_F_ACTIVE;
test_active = NULL;
test_thread = NULL;
goto return_with_free;
}
#ifndef NO_CTRL_C
if (TEST_RUNNING != (error = setjmp(test_active_jmp))) {
if (cleanup) {
cli_out("Warning: Cleanup aborted - "
"continue at your own risk\n");
} else {
cleanup = TRUE;
test_done(u, test, error);
}
} else {
#endif
/* If progress reporting requested, set it up ... */
if (test_options & TEST_O_PROGRESS) {
progress_init(vloops, 0, FALSE);
progress_status(test->t_name);
}
for (i = 0; i < vloops; i++) {
if (vloops > 1) {
LOG_VERBOSE(BSL_LS_APPL_TESTS,
(BSL_META_U(u,
"Test %d: %s. Starting interation %d.\n"),
test->t_test, test->t_name, i+1));
}
test->t_runs++; /* Let-em know we ran */
av->a_arg = arg_saved; /* Reset ARG pointer */
test->t_flags &= ~(T_F_STOP|T_F_ERROR);
/* Skip if rv is BCM_E_UNAVAIL as we mentioned above */
if (rv != BCM_E_UNAVAIL) {
error = test->t_test_f(u, av, fp);/* Run Test */
} else {
error = 0;
}
if (error == 0 && test->t_flags & T_F_ERROR) {
/* Some tests call test_error but fail to return error */
error = -1;
}
test_done(u, test, error);
if (test_options & TEST_O_PROGRESS) {
progress_report(1);
}
}
if (test_options & TEST_O_PROGRESS) {
progress_done();
}
#ifndef NO_CTRL_C
}
#endif
/* Skip if rv is BCM_E_UNAVAIL as we mentioned above */
if (rv != BCM_E_UNAVAIL) {
(void)test_test_done(u, test, fp); /* Run done routines/scripts */
} else {
/* If Return Value is BCM_E_UNAVAIL it is assumed that the internal
* memories are being tested for External TCAm devices and the test has
* not supported these memories. Even though the test is not executed
* increasing the test success count in order to show up in the final test
* results as not failed.
*/
test_active = NULL;
test_thread = NULL;
test->t_success++;
}
return_with_free:
if (args != NULL) {
sh_block_ctrl_c(TRUE);
sal_free(args);
args = 0;
sh_block_ctrl_c(FALSE);
}
return_no_free:
sh_pop_ctrl_c();
if (test_options & TEST_O_RUN) {
cli_out("Completed test (%d) %s\n", test->t_test, test->t_name);
}
if (a != NULL)
ARG_DISCARD(a);
return(error);
}
void
test_msg(const char *fmt, ...)
/*
* Function: test_msg
* Purpose: Print an informational message from a test.
* Parameters: Printf style string.
* Returns: Nothing
*/
{
va_list varg;
va_start(varg, fmt);
if (!(test_options & TEST_O_QUIET)) {
(void)bsl_vprintf(fmt, varg);
}
va_end(varg);
}
void
test_error(int u, const char *fmt, ...)
/*
* Function: test_error
* Purpose: Print an Error Message for test failure, stopping if
* Stop-on-Error is requested.
* Parameters: Printf style string.
* Returns: Nothing
*/
{
char pfx[64];
va_list varg;
int o_spl;
va_start(varg, fmt);
if (sal_thread_self() != test_thread) {
/*
* If this is not the test thread itself, then longjump
* will not work - so only option is to continue.
*/
cli_out("\n"
"****************************************\n"
"TEST ERROR: Warning: Not in test thread, "
"continuing ...\n");
(void)bsl_vprintf(fmt, varg);
cli_out("****************************************\n");
va_end(varg);
return;
}
o_spl = sal_splhi();
test_active->t_flags |= T_F_ERROR; /* Indicate error seen */
sal_spl(o_spl);
if (!(test_options & TEST_O_SILENT)) {
cli_out("\n"
"****************************************\n"
"TEST ERROR %s:\n", test_active->t_name);
(void)bsl_vprintf(fmt, varg);
cli_out("****************************************\n");
}
if (test_options & TEST_O_SOE) { /* Stop on error? */
o_spl = sal_splhi();
test_active->t_flags |= T_F_STOP; /* Indicate stopped once */
sal_spl(o_spl);
while (1) {
char *c, b[64];
int bl;
cli_out("\n\n *** Stop-on-Error *** \n"
"\t\"bcm\" to enter recursive BCM shell\n"
"\t\"continue\" to continue running current test\n\n"
"\t\"stop\" to stop all tests\n"
"\t\"abort\" to abort current test and start next test\n");
c = sal_readline("Stop-on-Error action? ", b, sizeof(b), "bcm");
if (c) {
b[sizeof(b) - 1] = '\0'; /* Be sure null terminated */
bl = strlen(c);
if (!sal_strncasecmp("bcm", b, bl)) {
cli_out("\nType \"exit\" to return from sh\n\n");
sal_sprintf(pfx, "FAILED(%s)", test_active->t_name);
(void)sh_process(u, pfx, TRUE);
} else if (!sal_strncasecmp("stop", b, bl)) {
#ifndef NO_CTRL_C
longjmp(test_active_jmp, TEST_STOP);
#endif
} else if (!sal_strncasecmp("abort", b, bl)) {
#ifndef NO_CTRL_C
longjmp(test_active_jmp, TEST_ABORT);
#endif
} else if (!sal_strncasecmp("continue", b, bl)) {
va_end(varg);
return;
}
}
}
} else if (test_options & TEST_O_AOE) { /* Abort on error */
cli_out("\nAborting test\n");
#ifndef NO_CTRL_C
longjmp(test_active_jmp, TEST_ABORT);
#endif
}
va_end(varg);
return; /* Continue */
}
void
test_print_header(int status_report)
/*
* Function: test_print_header
* Purpose: Print header string for output.
* Parameters: None.
* Returns: Nothing
*/
{
if (status_report) {
cli_out("-----+----+--- TEST STATUS REPORT ----+"
"-----+-----+-----+-----+-----------\n");
}
cli_out("U/A/S|Test| Test |Loop | Run |Pass |Fail |"
" Arguments\n");
cli_out(" | # | Name |Count|Count|Count|Count|"
"\n");
}
void
test_print_separator(void)
/*
* Function: test_print_header
* Purpose: Print header string for output.
* Parameters: None.
* Returns: Nothing
*/
{
cli_out("-----+----+---------------------------+-----+-----+-----+-----+"
"-----------\n");
}
void
test_print_summary(int loops, int runs, int successes, int failures)
/*
* Function: test_print_summary
* Purpose: Print summary values
* Parameters: Summary values
* Returns: Nothing
*/
{
cli_out(" | | %-26s|%5d|%5d|%5d|%5d|\n",
"TOTAL", loops, runs, successes, failures);
}
void
test_print_entry(int unit, test_t *test)
/*
* Function: test_print_entry
* Purpose: Print a single test entry in a pretty formatted way.
* Parameters: unit - Strata Switch unit #
* test - pointer to test list entry to print
* Returns: Nothing
*/
{
int selected;
uint32 chip = _test_chip(unit);
selected = (test->t_flags & T_F_SEL_ALL) ||
((test->t_flags & T_F_SEL_CHIP) && (test->t_flags & chip));
cli_out(" %c%c%c |%4d| %-26s|%5d|%5d|%5d|%5d| %s\n",
test->t_flags & _test_chip(unit) ? ' ' : 'U',
test->t_flags & T_F_ACTIVE ? 'A' : ' ',
selected ? 'S' : ' ',
test->t_test, test->t_name, test->t_loops, test->t_runs,
test->t_success, test->t_fail,
test->t_override_string ?
test->t_override_string :
test->t_default_string ? test->t_default_string : "(none)");
}
cmd_result_t
test_print_list(int u, args_t *a)
/*
* Function: test_print_list
* Purpose: Print some/all of the tests and status.
* Parameters: u - unit #
* "*" for all tests
* List of tests
* Nothing for all (same as *)
* Returns: CMD_OK - success
* CMD_FAIL - failed to find test or if a test failed.
*/
{
test_t *test;
char *s;
int header = FALSE;
int i, supported, all, fail;
cmd_result_t result = CMD_OK;
uint32 chip = _test_chip(u);
int num_fail = 0;
test_t *test_list;
int test_cnt;
test_list = get_test_list(u, &test_cnt);
COMPILER_REFERENCE(u);
/* Check for print all */
if (ARG_CNT(a) > 0) {
supported = (0 == strcmp(_ARG_CUR(a), "*"));
all = (0 == sal_strcasecmp(_ARG_CUR(a), "all"));
fail = (0 == sal_strcasecmp(_ARG_CUR(a), "fail"));
if (supported || all || fail) { /* Consume Argument */
ARG_NEXT(a);
}
} else if (ARG_CNT(a) == 0) {
supported = TRUE;
all = FALSE;
fail = FALSE;
} else {
supported = FALSE;
all = FALSE;
fail = FALSE;
}
/* If "all" or supported, consume argument and list tests */
if (fail) {
for (i = 0; i < test_cnt; i++) {
if (test_list[i].t_fail) {
cli_out("%d ", test_list[i].t_test);
num_fail++;
}
}
if (num_fail == 0) {
cli_out("All tests passed");
}
cli_out("\n");
return(result);
}
if (all || supported) {
int t_loops = 0, t_runs = 0, t_success = 0, t_fail = 0;
if (chip == 0) { /* No chip - print all */
all = TRUE;
}
test_print_header(TRUE);
test_print_separator();
for (i = 0; i < test_cnt; i++) {
if (all ||
(supported && (chip & test_list[i].t_flags))
|| (test_list[i].t_flags & T_F_SEL_ALL)) {
test_print_entry(u, &test_list[i]);
t_loops += test_list[i].t_loops;
t_runs += test_list[i].t_runs;
t_success += test_list[i].t_success;
t_fail += test_list[i].t_fail;
}
}
test_print_summary(t_loops, t_runs, t_success, t_fail);
test_print_separator();
/*
In order for the automated tests to automatically diagnose
that a test failed, we need this function to return
something when an individual test fails.
*/
if (t_runs == 0) {
/*
* We want return CMD_FAIL if no tests were run
*/
result = CMD_FAIL;
} else if (t_fail > 0) {
/*
* We also want to return CMD_FAIL if any tests failed.
*/
result = CMD_FAIL;
}
return(result);
}
while ((s = ARG_GET(a)) != NULL) {
test = test_find(s, test_list, test_cnt);
if (!test) {
cli_out("%s: Unable to locate test: %s\n", ARG_CMD(a), s);
result = CMD_FAIL;
continue;
}
if (!header) {
test_print_header(FALSE);
test_print_separator();
header = TRUE;
}
test_print_entry(u, test);
}
return(result);
}
/*
* Function: test_run_selected
* Purpose: Run selected tests.
* Parameters: u - unit number to run tests on.
* Returns: Nothing.
*/
static int
test_run_selected(int u, test_t *test_list, int test_cnt)
{
int i;
if (test_options & TEST_O_RANDOM) {
cli_out("Test: Random mode not supported yet\n");
return(TEST_STOP);
}
for (i = 0; i < test_cnt; i++) {
if ((test_list[i].t_flags & T_F_SEL_ALL) ||
((test_list[i].t_flags & T_F_SEL_CHIP) &&
(test_list[i].t_flags & _test_chip(u))))
{
int rv;
switch((rv = test_dispatch(u, &test_list[i], -1, NULL))) {
case TEST_STOP:
case TEST_INTR:
return(rv);
}
}
}
return(TEST_RUNNING);
}
char test_run_usage[] =
"Parameters: [Test ID] [arguments]\n\t"
" With no parameters runs all selected tests with the set\n\t"
" loop counts and set parameters. Otherwise, runs a specific\n\t"
" test with the specified loop count and arguments. You may\n\t"
" want to use \"set RCTest=true\" so that some tests (like\n\t"
" loopback) will properly initialize using rc.soc).\n";
cmd_result_t
test_run(int u, args_t *a)
/*
* Function: test_run
* Purpose: Perform "run" command for test.
* Parameters: none - Run all selected tests with loaded parameters.
* "test [options]"
* Returns: Test result.
*/
{
test_t *test;
int rv;
int loops = -1;
test_t *test_list;
int test_cnt;
test_list = get_test_list(u, &test_cnt);
if (test_active && !SOC_IS_SAND(u)) {
cli_out("%s: Already running: %s\n", ARG_CMD(a), test_active->t_name);
return(CMD_FAIL);
} else if (!sh_check_attached(ARG_CMD(a), u)) {
return(CMD_FAIL);
}
if (!ARG_CNT(a)) {
rv = test_run_selected(u, test_list, test_cnt);
} else {
if (NULL == (test = test_find(ARG_CUR(a), test_list, test_cnt))) {
cli_out("%s: Unknown test: %s\n", ARG_CMD(a), ARG_CUR(a));
return(CMD_FAIL);
}
if (!(test->t_flags & _test_chip(u)) &&
!(test_options & TEST_O_OVERRIDE)) {
cli_out("Error: Test %d (%s) not supported on %s\n"
"Error: use \"testmode +override\" to override and run\n",
test->t_test, test->t_name, SOC_UNIT_GROUP(u));
return(CMD_FAIL);
}
ARG_NEXT(a); /* Move arg pointer */
/* If there is an argument which is an integer, it's a loop count */
if (ARG_CUR(a) && isint(ARG_CUR(a))) {
loops = strtoul(_ARG_GET(a), NULL, 10);
}
rv = test_dispatch(u, test, loops, ARG_CNT(a) ? a : NULL);
}
return(rv == TEST_INTR ? CMD_INTR : rv);
}
STATIC int
_test_select(int u, test_t *t, int only_if_available)
{
uint32 chip = _test_chip(u);
if (only_if_available) { /* Only select available tests */
if (t->t_flags & chip) {
t->t_flags |= T_F_SEL_CHIP;
}
} else {
if (!(t->t_flags & chip)) {
if (test_options & TEST_O_OVERRIDE) {
cli_out("Warning: Selecting test %d (%s) "
"not supported on %s\n",
t->t_test, t->t_name, SOC_UNIT_GROUP(u));
} else {
cli_out("Error: Test %d (%s) not supported on %s\n"
"use \"testmode +override\" to override and run\n",
t->t_test, t->t_name, SOC_UNIT_GROUP(u));
return(CMD_FAIL);
}
}
t->t_flags |= T_F_SEL_ALL;
}
return(CMD_OK);
}
STATIC void
_test_unselect(int u, test_t *t)
{
uint32 chip = _test_chip(u);
t->t_flags &= ~T_F_SEL_ALL;
if (t->t_flags & chip) {
t->t_flags &= ~T_F_SEL_CHIP;
}
}
STATIC int
_test_select_check(int u, test_t *t)
{
uint32 chip = _test_chip(u);
return((t->t_flags & T_F_SEL_ALL) ||
((t->t_flags & T_F_SEL_CHIP) && (t->t_flags & chip)));
}
char test_select_usage[] =
"Parameters: [+|-][Test ID] ... - Select specified tests\n\t"
" If + specified before a test it is added to the\n\t"
" run list. If - is specified it is removed from\n\t"
" the run list. If neither + or - is specified then\n\t"
" the current select status for a test is inverted\n\t"
TEST_ID_USAGE;
cmd_result_t
test_select(int u, args_t *a)
/*
* Function: test_select
* Purpose: Select a set of tests, prefix with + to add, - to remove.
* Parameters: u - unit #
* a - list of tests to select, deselect (* means all)
* Returns: 0 - success, -1 failed.
*/
{
enum {ADD, DEL, XOR} option;
int silent;
cmd_result_t error = CMD_OK;
char *s;
test_t *ts, *te; /* Test start/end pointers */
test_t *test_list;
int test_cnt;
test_list = get_test_list(u, &test_cnt);
COMPILER_REFERENCE(u);
while ((s = ARG_GET(a)) != NULL) {
if ('+' == *s) {
option = ADD;
s++;
} else if ('-' == *s) {
option = DEL;
s++;
} else {
option = XOR;
}
if (!strcmp("*", s)) { /* Do it to all of the tests */
ts = &test_list[0];
te = &test_list[test_cnt-1];
silent = TRUE;
} else {
silent = FALSE;
ts = te = test_find(s, test_list, test_cnt);
if (!ts) {
cli_out("%s: Unable to locate test: %s\n", ARG_CMD(a), s);
return(CMD_FAIL);
}
}
while (ts <= te) {
switch(option) {
case ADD:
error = _test_select(u, ts, silent);
break;
case DEL:
_test_unselect(u, ts);
break;
case XOR:
if (_test_select_check(u, ts)) {
_test_unselect(u, ts);
} else {
error = _test_select(u, ts, silent);
}
break;
}
ts++;
}
}
return(error);
}
char test_mode_usage[] =
"Parameters: [+/-][StopOnError|Random|Progress|SIlent|Run|Override] ... \n"
#ifndef COMPILER_STRING_CONST_LIMIT
"\t - StopOnError requests a diagnostic shell be invoked when\n\t"
" a test fails. This allows the user to inspect SOC state\n\t"
" using the diagshell.\n\t"
" - Abortonerror requests a test be aborted on failure, and \n\t"
" execution continues with next test.\n\t"
" - Random requests tests be run in pseudo random order\n\t"
" - Progress requests a simple progress report be displayed\n\t"
" as tests are run\n\t"
" - Silent requests test error messages not be printed, but\n\t"
" errors are counted\n\t"
" - Run requests a message is printed when a test is dispatched\n\t"
" Prefixing the flag with + turns on the option, - turns\n\t"
" off the option, no +/- toggles the current option\n\t"
" - Override allows tests not supported on the specified chip to\n\t"
" be selected and run. WARNING: these is a high probablility the\n\t"
" system will crash when running unsupported chips\n"
#endif
;
cmd_result_t
test_mode(int u, args_t *a)
/*
* Function: test_mode
* Purpose: Set test test mode
* Parameters: [+/-] "soe" or "stoponerror"
* Returns: 0 - success,
* -1 - failed.
*/
{
static parse_pm_t options[] = {
{"@SOE", TEST_O_SOE},
{"@AOE", TEST_O_AOE},
{"Stoponerror", TEST_O_SOE},
{"Abortonerror",TEST_O_AOE},
{"Quiet", TEST_O_QUIET},
{"Progress", TEST_O_PROGRESS},
{"RANDom", TEST_O_RANDOM},
{"SIlent", TEST_O_SILENT},
{"Run", TEST_O_RUN},
{"Override", TEST_O_OVERRIDE},
{"NoReinit", TEST_O_NO_REINIT},
{NULL, 0}
};
char *c;
COMPILER_REFERENCE(u);
if (0 == ARG_CNT(a)) {
cli_out("Test: Options: ");
parse_mask_format(80, options, test_options);
cli_out("\n");
return(CMD_OK);
}
while ((c = ARG_GET(a)) != NULL) {
if (parse_mask(c, options, &test_options)) {
cli_out("%s: Error: invalid option ignored: %s\n", ARG_CMD(a), c);
}
}
return(CMD_OK);
}
char test_parameters_usage[] =
"Parameters: [Test Name | Test #] [\"Parameter String\"] ...\n\t"
" Override the default parameters for the test specified\n\t"
" by [Test ID]. Multiple tests may be listed and the parameter\n\t"
" string must be quoted if more that 1 argument is specified (\").\n\t"
" To clear a previously set parameter list, pass a NULL string\n\t"
" as an argument (\"\").\n";
cmd_result_t
test_parameters(int u, args_t *a)
/*
* Function: test_parameters
* Purpose: Set the parameters for the specified tests.
* Parameters: u - unit number
* a - arguments, expects tuples of the form:
* [Test name/#] Arguments.
* if arguments is null string ("") then previously
* set arguments are discarded and defaults used.
* Returns: cmd_result_t.
*/
{
char *tid, *p; /* Testid, parameters */
test_t *t; /* Test pointer */
test_t *test_list;
int test_cnt;
test_list = get_test_list(u, &test_cnt);
COMPILER_REFERENCE(u);
if (0 == ARG_CNT(a)) {
return(CMD_USAGE);
}
while (NULL != (tid = ARG_GET(a))) {
p = ARG_GET(a); /* Parameter */
t = test_find(tid, test_list, test_cnt);
if (NULL == t) {
cli_out("%s: Error: Unable to find test: %s\n", ARG_CMD(a), tid);
return(CMD_FAIL);
}
if (!p || !*p) { /* Clear parameter */
if (!t->t_override_string) {
cli_out("%s: Warning: No arguments to clear for test: %s\n",
ARG_CMD(a), t->t_name);
continue;
}
sal_free(t->t_override_string);
t->t_override_string = NULL;
} else { /* Set Arguments */
if (t->t_override_string) {
sal_free(t->t_override_string);
}
if (!(t->t_override_string =
(char *)sal_alloc(strlen(p) + 1, "test_parm"))) {
cli_out("%s: Error: Out of memory\n", ARG_CMD(a));
return(CMD_FAIL);
}
sal_strncpy(t->t_override_string, p, sal_strlen(p) + 1);
cli_out("%s: Parameter set: %s(\"%s\")\n", ARG_CMD(a), t->t_name,
t->t_override_string);
}
}
return(CMD_OK);
}
char test_clear_usage[] =
"Parameters: [Test Name | Test #]\n\t"
"Clear the run, success, and failure statistics for the test\n\t"
"specified by [Test ID]. Multiple tests may be listed, and \"*\"\n\t"
"may be used to represent all tests.\n";
cmd_result_t
test_clear(int u, args_t *a)
/*
* Function: test_clear
* Purpose: Clear previous test results for a test.
* Parameters: u - unit number
* a - arguments, expects testname/#.
* Returns: cmd_result_t
*/
{
char *tid;
test_t *t;
test_t *test_list;
int test_cnt;
test_list = get_test_list(u, &test_cnt);
COMPILER_REFERENCE(u);
if (0 == ARG_CNT(a)) {
return(CMD_USAGE);
}
while (NULL != (tid = ARG_GET(a))) {
if (!strcmp(tid, "*")) { /* Clear all tests */
for (t = test_list; t < &test_list[test_cnt]; t++) {
t->t_runs = 0;
t->t_success = 0;
t->t_fail = 0;
}
} else { /* Clear specific test */
t = test_find(tid, test_list, test_cnt);
if (NULL == t) {
cli_out("%s: Error: Unable to find test: %s\n",
ARG_CMD(a), tid);
return(CMD_FAIL);
}
t->t_runs = 0;
t->t_success = 0;
t->t_fail = 0;
}
}
return(CMD_OK);
}
#endif /* INCLUDE_TEST */
int _diag_test_not_empty;
|
the_stack_data/66298.c | typedef unsigned long longtype;
typedef longtype partidtype ;
typedef char parttype[10] ;
typedef struct Connection_Type {
partidtype to ;
parttype type ;
longtype length ;
} Connection ;
extern void printf(char *, ...);
#define E(n) { printf("Error %d\n", n); return(1); }
// From VORTEX
int main() {
static Connection link[3] =
{{1, "link1", 10}, {2, "link2", 20}, {3, "link3", 30}};
if (sizeof(long) == 4) {
if(sizeof(link[0]) != 4 + 10 + 2 + 4) E(1);
} else if (sizeof(long) == 8) {
if(sizeof(link[0]) != 8 + 10 + 6 + 8) E(1);
}
if(link[0].length != 10) E(2);
if(link[2].length != 30) E(3);
if(strcmp("link2", link[1].type)) E(4);
if(link[1].type[6] != 0) E(5);
printf("Success\n");
return 0;
}
|
the_stack_data/421270.c | #include <stdio.h>
// Quantidade de aumento em porcentagem
// Deixe sempre com um "." (Exemplo: 8.0) para a variável ser um float.
#define AUMENTO 8.0
int main() {
// Guardaremos o alário inicial de todos os trabalhadores em um array, faremos o mesmo com os novos salários.
float salarios[8], reajustados[8];
// Usando um for loop para lermos o salário de 8 pessoas
for(int i = 0;i < 8;i++) {
float salario;
printf("Insira o salário da pessoa %d: ", i + 1);
while(scanf("%f", &salario)!=1 && salario < 1) {
// Salário inválido ou menor que 1.
printf("%f\n", salario);
if(!salario || salario < 1) {
printf("Insira um valor válido.\n");
// Limpar buffer do stdin
printf("Insira o salário da pessoa %d: ", i + 1);
while((getchar()) != '\n');
continue;
} else {
break;
}
}
// Guardando salário inicial
salarios[i] = salario;
// Guardando salário com reajuste
reajustados[i] = salario + (float)((float)(AUMENTO / 100) * salario);
}
printf("\nCom aumento de %d%%, os novos salários são:\n", AUMENTO);
for(int i = 0;i < 8;i++) {
printf("Pessoa %d: %.2f -> %.2f\n", i + 1, salarios[i], reajustados[i]);
}
return 0;
}
|
the_stack_data/1136036.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
int n, n100, n50, n20, n10, n5, n2, n1, resto;
scanf("%d", &n);
n100= n/100;
resto=n%100;
n50= resto/50;
resto=resto%50;
n20= resto/20;
resto=resto%20;
n10= resto/10;
resto=resto%10;
n5= resto/5;
resto=resto%5;
n2= resto/2;
resto=resto%2;
n1= resto;
printf("%d\n%d nota(s) de R$ 100,00\n%d nota(s) de R$ 50,00\n%d nota(s) de R$ 20,00\n%d nota(s) de R$ 10,00\n%d nota(s) de R$ 5,00\n%d nota(s) de R$ 2,00\n%d nota(s) de R$ 1,00\n", n, n100, n50, n20, n10, n5, n2, n1);
return 0;
}
|
the_stack_data/87456.c | #include <stdio.h>
#include <string.h>
/* Bibliotecas obrigatorias para se poder utilizar sockets */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 22222
#define IP "127.0.0.1"
#define MSG_LEN 100
int main(int argc, char const *argv[]) {
/* Inicializacao do cliente */
struct sockaddr_in client_addr; /* armazena o endereco do cliente */
socklen_t addr_len = sizeof (client_addr); /* define o tamanho do endereco do servidor local */
int sockfd, /* socket cliente */
msgLength; /* tamanho da mensagem */
char msg[MSG_LEN];
/* Inicializar o socket
* PF_INET - para indicar que queremos usar IP
* SOCK_STREAM - para indicar que queremos usar TCP
* 0 - para indicar que estamos num unico protocolo
*/
sockfd = socket (PF_INET, SOCK_STREAM, 0); /* criacao do socket do servidor */
if (sockfd < 0) {
printf ("Ocorreu um erro ao criar o socket.");
return -1;
}
client_addr. sin_family = AF_INET;
client_addr.sin_port = htons (PORT);
inet_aton (IP, &client_addr.sin_addr);
/* Estabelece-se a ligação */
connect (sockfd, (struct sockaddr*)&client_addr, addr_len); /* o cliente bloqueia até conseguir a ligacao */
while (1){ /* envia continuamente dados, enquanto nao enviar # */
/* Enviar e receber dados */
fgets (msg, 100, stdin);
msg [strlen(msg)-1] = '\0'; /* elimina o caracter enter do fgets */
msgLength = send (sockfd /* confirmar esta variavel */, msg, strlen(msg)+1, 0);
if (msgLength < 0) {
printf("Ocorreu um erro ao receber a mensagem.\n");
return -1;
}
if (msg[0] == '#')
break;
msgLength = recv (sockfd, msg, msgLength, 0);
if (msgLength < 0) {
printf("Ocorreu um erro ao receber a mensagem.\n");
return -1;
}
printf("%s\n",msg);
}
shutdown (sockfd, 2);
close (sockfd);
return 0;
}
|
the_stack_data/406536.c | /*
* Copyright (c) 2007, Kohsuke Ohtani
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <unistd.h>
#include <errno.h>
gid_t
getgid(void)
{
return (uid_t)1;
}
|
the_stack_data/111077519.c | int main()
{
return 20 == 3;
} |
the_stack_data/168892010.c | /*
* gif.c --
*
* This file provides access to gif pixmaps.
*
* Copyright (c) 1993 by Sven Delmas
* All rights reserved.
* See the file COPYRIGHT for the copyright notes.
*
*
* adapted from code by Alfred Kayser, DNPAP (the package is named xgif).
*
* Copyright by Alfred Kayser, DNPAP
*
*
* minor pieces of code have been taken from the code published by
* jim frost and kirk johnson (xloadimage)
*
* Copyright 1989, 1990 Kirk L. Johnson
*
* Permission to use, copy, modify, distribute, and sell this
* software and its documentation for any purpose is hereby granted
* without fee, provided that the above copyright notice appear in
* all copies and that both that copyright notice and this
* permission notice appear in supporting documentation. The
* author makes no representations about the suitability of this
* software for any purpose. It is provided "as is" without express
* or implied warranty.
*
* 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, 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.
*
*
* Copyright 1989, 1990 Jim Frost
*
* Permission to use, copy, modify, distribute, and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. The author makes no representations
* about the suitability of this software for any purpose. It is
* provided "as is" without express or implied warranty.
*
* 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, 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.
*/
#if defined (USE_GIF)
#ifndef lint
static char *AtFSid = "$Header: gif.c[6.0] Mon Jul 25 18:06:17 1994 [email protected] frozen $";
#endif /* not lint */
/* include files */
#include "tkConfig.h"
#include "tcl.h"
#include "tk.h"
#define MAX_ARGS 100
#define WHERE static
typedef unsigned char byte;
/* X stuff */
WHERE Display *theDisp;
WHERE int theScreen, dispcells, dispWIDE, dispHIGH;
WHERE Colormap theCmap, LocalCmap;
WHERE Window rootW, mainW;
WHERE GC theGC;
WHERE Visual *theVisual;
WHERE XImage *theImage;
/* global vars */
WHERE unsigned long cols[256];
WHERE XColor defs[256];
WHERE int quiet, local, DEBUG;
#define IMAGESEP 0x2c
#define EXTENSION 0x21
#define INTERLACEMASK 0x40
#define COLORMAPMASK 0x80
#define ADDTOPIXEL(a) if (Quick) Image[Offset++]=a; else AddToPixel(a)
#define ALLOCATED 3
static int EGApalette[16][3] = {
{0,0,0}, {0,0,128}, {0,128,0}, {0,128,128},
{128,0,0}, {128,0,128}, {128,128,0}, {200,200,200},
{100,100,100}, {100,100,255}, {100,255,100}, {100,255,255},
{255,100,100}, {255,100,255}, {255,255,100}, {255,255,255} };
static int BitOffset, /* Bit Offset of next code */
XC, YC, /* Output X and Y coords of current pixel */
Offset, /* Offset in output array */
Pass, /* Used by output routine if interlaced pic */
Width, Height, /* image dimensions */
BytesPerScanline, /* bytes per scanline in output raster */
ColorMapSize, /* number of colors */
Background, /* background color */
NumUsed, /* Number of colors really used */
CodeSize, /* Code size, read from GIF header */
ReadMask, /* Code AND mask for current code size */
Interlace,
HasColormap;
static byte *Image; /* The result array */
static byte *Raster; /* The raster data stream, unblocked */
/* The GIF headers found in the file */
static byte gifheader[13];
static byte imageheader[9];
static byte colormap[3*256];
/* The hash table used by the decompressor */
static int Prefix[4096];
static int Suffix[4096];
/* An output array used by the decompressor */
static byte OutCode[1025];
/* The color map, read from the GIF header */
static byte Red[256], Green[256], Blue[256], used[256];
static char id[] = "GIF";
int
ReadImageData(fp)
FILE *fp;
{
/* Read the raster data. Here we just transpose it from the GIF array
* to the Raster array, turning it from a series of blocks into one long
* data stream, which makes life much easier for ReadCode().
*/
long filesize, filepos;
int ch;
byte *ptr1;
/* find the size of the file */
filepos = ftell(fp);
fseek(fp, 0L, 2);
filesize = ftell(fp)-filepos;
fseek(fp, filepos, 0);
if (!(Raster = (byte *) malloc(filesize)))
return 1;
ptr1 = Raster;
while ((ch = getc(fp))>0)
{
if ((int) fread(ptr1, 1, ch, fp) < (int) ch)
return 1;
ptr1 += ch;
}
return 0;
}
/* Fetch the next code from the raster data stream. The codes can be
* any length from 3 to 12 bits, packed into 8-bit bytes, so we have to
* maintain our location in the Raster array as a BIT Offset. We compute
* the byte Offset into the raster array by dividing this by 8, pick up
* three bytes, compute the bit Offset into our 24-bit chunk, shift to
* bring the desired code to the bottom, then mask it off and return it.
*/
int
ReadCode()
{
int RawCode, ByteOffset, BitShift;
ByteOffset = BitOffset / 8;
BitShift = BitOffset % 8;
BitOffset += CodeSize;
if (BitShift+CodeSize<8)
return (Raster[ByteOffset]>>BitShift) & ReadMask;
else
{
RawCode = Raster[ByteOffset] + (0x100 * Raster[ByteOffset + 1]);
if (BitShift+CodeSize >= 16)
RawCode += (0x10000 * Raster[ByteOffset + 2]);
return((RawCode>>BitShift) & ReadMask);
}
}
void
AddToPixel(Index)
byte Index;
{
if (YC<Height) /* Might be of importance when reading interlaced gifs */
Image[YC*BytesPerScanline+XC] = Index;
if (!used[Index]) { used[Index]=True; NumUsed++; }
if (++XC == Width)
{
XC = 0;
if (Interlace)
{
switch (Pass)
{
case 0: YC += 8; if (YC >= Height) { Pass++; YC = 4; } break;
case 1: YC += 8; if (YC >= Height) { Pass++; YC = 2; } break;
case 2: YC += 4; if (YC >= Height) { Pass++; YC = 1; } break;
case 3: YC += 2; break;
default: break;
}
}
else
YC++;
}
}
int
DecodeImage()
{
/* Start reading the raster data. First we get the intial code size
* and compute decompressor constant values, based on this code size.
*/
int Quick = 0, /* True, when not interlaced and local Cmap */
InitCodeSize = 0, /* Starting code size, used during Clear */
InCode = 0, /* Value returned by ReadCode */
MaxCode = 0, /* limiting value for current code size */
ClearCode = 0, /* GIF clear code */
EOFCode = 0, /* GIF end-of-information code */
CurCode = 0, OldCode = 0, /* Decompressor variables */
FreeCode = 0, /* Decompressor, next free slot in hashtable */
OutCount = 0, /* Decompressor output 'stack count' */
FinChar = 0, /* Decompressor variable */
BitMask = 0; /* AND mask for data size */
BitMask = ColorMapSize - 1;
ClearCode = (1 << CodeSize);
EOFCode = ClearCode + 1;
FreeCode = ClearCode + 2;
/* The GIF spec has it that the code size is the code size used to
* compute the above values is the code size given in the file, but the
* code size used in compression/decompression is the code size given in
* the file plus one. (thus the ++).
*/
CodeSize++;
InitCodeSize = CodeSize;
MaxCode = (1 << CodeSize);
ReadMask = MaxCode - 1;
/* Allocate the X Image */
if (!(Image = (byte *) malloc(Width*Height)))
return 1;
BytesPerScanline = Width;
/* Decompress the file, continuing until you see the GIF EOF code.
* One obvious enhancement is to add checking for corrupt files here.
*/
Quick = (local && !Interlace);
Offset = 0;
if (DEBUG) fprintf(stderr,"Decoding...\n");
InCode = ReadCode();
while (InCode != EOFCode) {
/* Clear code sets everything back to its initial value, then reads the
* immediately subsequent code as uncompressed data.
*/
if (InCode == ClearCode) {
CodeSize = InitCodeSize;
MaxCode = (1 << CodeSize);
ReadMask = MaxCode - 1;
FreeCode = ClearCode + 2;
CurCode = OldCode = InCode = ReadCode();
FinChar = CurCode & BitMask;
ADDTOPIXEL(FinChar);
}
else {
/* If not a clear code, then must be data: save same as CurCode */
CurCode = InCode;
/* If greater or equal to FreeCode, not in the hash table yet;
* repeat the last character decoded
*/
if (CurCode >= FreeCode) {
CurCode = OldCode;
OutCode[OutCount++] = FinChar;
}
/* Unless this code is raw data, pursue the chain pointed to by CurCode
* through the hash table to its end; each code in the chain puts its
* associated output code on the output queue.
*/
while (CurCode > BitMask) {
if (OutCount >= 1024) {
fprintf(stderr,"\nCorrupt GIF file (OutCount)!\n");
exit(1);
}
OutCode[OutCount++] = Suffix[CurCode];
CurCode = Prefix[CurCode];
}
/* The last code in the chain is treated as raw data. */
/* OutCode[OutCount++] = FinChar = CurCode &BitMask*/;
FinChar = CurCode & BitMask;
ADDTOPIXEL(FinChar);
/* Now we put the data out to the Output routine.
* It's been stacked LIFO, so deal with it that way... */
while (OutCount>0)
ADDTOPIXEL(OutCode[--OutCount]);
/* Build the hash table on-the-fly. No table is stored in the file. */
Prefix[FreeCode] = OldCode;
Suffix[FreeCode] = FinChar;
OldCode = InCode;
/* Point to the next slot in the table. If we exceed the current
* MaxCode value, increment the code size unless it's already 12. If it
* is, do nothing: the next code decompressed better be CLEAR
*/
FreeCode++;
if (FreeCode >= MaxCode) {
if (CodeSize < 12) {
CodeSize++;
MaxCode *= 2;
ReadMask = (1 << CodeSize) - 1;
}
}
}
InCode = ReadCode();
}
free(Raster);
return 0;
}
int
ColorDicking()
{
/* we've got the picture loaded, we know what colors are needed. get 'em */
int i,j;
register byte *ptr;
if (!HasColormap)
{
if (DEBUG) fprintf(stderr,"Using EGA palette as default\n");
for (i=0; i<ColorMapSize; i++) {
Red[i] = EGApalette[i&15][0];
Green[i] = EGApalette[i&15][1];
Blue[i] = EGApalette[i&15][2];
used[i] = True;
}
}
for (i=j=0; i<ColorMapSize; i++)
{
if (local || used[i])
{
defs[i].red = Red[i]<<8;
defs[i].green = Green[i]<<8;
defs[i].blue = Blue[i]<<8;
defs[i].flags = DoRed | DoGreen | DoBlue;
defs[i].pixel = i;
}
}
if (local && HasColormap)
{
LocalCmap=XCreateColormap(theDisp,mainW,theVisual,AllocAll);
XStoreColors(theDisp,LocalCmap,defs,ColorMapSize);
return 0;
}
if (!quiet) fprintf(stderr,"Allocating %d colors...\n",NumUsed);
/* Allocate the X colors for this picture */
for (i=j=0; i<ColorMapSize; i++)
{
if (local || used[i])
{
if (!XAllocColor(theDisp,theCmap,&defs[i])
|| defs[i].red != Red[i]<<8
|| defs[i].green != Green[i]<<8
|| defs[i].blue != Blue[i]<<8) /* Not an exact match! */
{
j++;
defs[i].pixel = 0xffff;
}
else used[i]=ALLOCATED;
cols[i] = defs[i].pixel;
}
else cols[i]=i;
}
if (j) /* failed to pull it off */
{
XColor ctab[256];
int dc = (dispcells<256) ? dispcells : 256;
if (!quiet)
fprintf(stderr,"Failed to allocate %d out of %d colors. \n%s",
j,NumUsed, " Searching for resembling colors\n");
/* read in the color table */
for (i=0; i<dc; i++) ctab[i].pixel = i;
XQueryColors(theDisp, theCmap, ctab, dc);
/* run through the used colors. any used color that has a pixel
value of 0xffff wasn't allocated. for such colors, run through
the entire X colormap and pick the closest color */
for (i=0; i<ColorMapSize; i++)
{
if (used[i] && cols[i]==0xffff) /* an unallocated pixel */
{
long mdist = 0x7FFFFFFL; /* MAXLONG */
int close = -1;
long d;
long r = Red[i]<<8;
long g = Green[i]<<8;
long b = Blue[i]<<8;
for (j=0; j<dc; j++)
{
d = 5*abs(r-ctab[j].red)
+ 3*abs(g-ctab[j].green) +
1*abs(b-ctab[j].blue);
if (d<mdist) { mdist=d; close=j; }
}
if (close<0) return 1;
cols[i] = ctab[close].pixel;
}
}
}
if (!quiet) fprintf(stderr, "Building XImage...\n");
ptr = Image;
for (i=0; i<Height; i++)
for (j=0; j<Width; j++,ptr++)
*ptr = (byte) cols[*ptr];
return 0;
}
void
ReadColormap(fp)
FILE *fp;
{
byte *ptr=colormap;
int i;
if (DEBUG) fprintf(stderr,"Reading Color map...\n");
fread(colormap, ColorMapSize, 3, fp);
for (i = 0; i < ColorMapSize; i++) {
Red[i] = (*ptr++);
Green[i] = (*ptr++);
Blue[i] = (*ptr++);
used[i] = 0;
}
NumUsed=0;
}
/*****************************/
int
LoadGIF(fname)
char *fname;
/*****************************/
{
register byte ch;
FILE *fp;
BitOffset = 0, /* Bit Offset of next code */
XC = 0, YC = 0, /* Output X and Y coords of current pixel */
Offset = 0, /* Offset in output array */
Pass = 0; /* Used by output routine if interlaced pic */
ColorMapSize = 0;
Image = NULL;
fp = fopen(fname,"r");
if (!fp) return 1;
if ( (fread(gifheader, sizeof(gifheader), 1, fp)!=1)
|| (strncmp((char *) gifheader, id, 3)!=0)) {
fclose(fp);
return 1;
}
if (strncmp((char *) gifheader+3, "87a", 3) &&
strncmp((char *) gifheader+3, "89a", 3))
fprintf(stderr,"Warning: %s contains unknown version %c%c%c",
fname,gifheader[3],gifheader[4],gifheader[5]);
HasColormap = ((gifheader[10] & COLORMAPMASK) ? True : False);
ColorMapSize = 1 << (gifheader[10]&7)+1;
Background = gifheader[11]; /* background color... not used. */
/* Read in global colormap. */
if (HasColormap) ReadColormap(fp);
/* Check for image extension */
while ((ch=getc(fp)) == EXTENSION)
{
getc(fp); /* skip extension code */
while ((ch=getc(fp))>0)
fseek(fp, ch, 1); /* skip it */
}
if (ch != IMAGESEP) {
fclose(fp);
return 1;
}
fread(imageheader,sizeof(imageheader),1,fp);
Width = imageheader[4] + 0x100 * imageheader[5];
Height = imageheader[6] + 0x100 * imageheader[7];
if (!quiet)
fprintf(stderr,"%s: %dx%dx%d\n", fname, Width, Height, ColorMapSize);
Interlace = ((imageheader[8] & INTERLACEMASK) ? True : False);
if (imageheader[8] & COLORMAPMASK)
{
HasColormap = True;
ColorMapSize = 1 << (imageheader[8]&7)+1;
ReadColormap(fp);
}
CodeSize = getc(fp);
if (!ReadImageData(fp)) {
fclose(fp);
if (DecodeImage())
return 1;
return 0;
} else {
fclose(fp);
return 1;
}
}
/*
*----------------------------------------------------------------------
*
* InternalGifGet --
*
* This procedure is invoked to read a Gif file.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* None
*
*----------------------------------------------------------------------
*/
int
InternalGifGet(interp, tkwin, filename, width, height, depth, pixmap,
clipMask)
Tcl_Interp *interp; /* Current interpreter. */
Tk_Window tkwin; /* The window */
char *filename; /* The filename to load. */
unsigned int *width; /* The pixmap width. */
unsigned int *height; /* The pixmap height. */
unsigned int *depth; /* The pixmap depth. */
Pixmap *pixmap; /* The resulting pixmap. */
Pixmap *clipMask; /* The resulting clipmask. */
{
XGCValues gcv;
GC gc;
DEBUG = 0;
Image = NULL;
quiet = 1;
local = 0;
LocalCmap = 0;
theDisp = Tk_Display(tkwin);
theScreen = Tk_ScreenNumber(tkwin);
theCmap = Tk_Colormap(tkwin);
rootW = RootWindow(theDisp, theScreen);
theGC = DefaultGC(theDisp, theScreen);
theVisual = DefaultVisual(theDisp, theScreen);
dispcells = DisplayCells(theDisp, theScreen);
dispWIDE = DisplayWidth(theDisp, theScreen);
dispHIGH = DisplayHeight(theDisp, theScreen);
/* load and prepare gif */
if (LoadGIF(filename)) {
goto error;
}
if (ColorDicking()) {
goto error;
}
/* create pixmap */
*pixmap = XCreatePixmap(theDisp, Tk_WindowId(tkwin),
Width, Height,
DefaultDepth(theDisp, theScreen));
if (DefaultDepth(theDisp, theScreen) == 1) {
gcv.function = GXcopy;
gcv.foreground = BlackPixel(theDisp, theScreen);
gcv.background = WhitePixel(theDisp, theScreen);
gc = XCreateGC(theDisp, *pixmap, GCFunction | GCForeground |
GCBackground, &gcv);
theImage = XCreateImage(theDisp, theVisual,
DefaultDepth(theDisp, theScreen),
XYBitmap, (int) NULL, Image,
Width, Height, 8, (int) NULL);
theImage->bitmap_bit_order = MSBFirst;
theImage->byte_order = MSBFirst;
XPutImage(theDisp, *pixmap, gc, theImage, 0, 0, 0, 0,
theImage->width, theImage->height);
} else {
if (DefaultDepth(theDisp, theScreen) % 8) {
goto error;
} else {
gcv.function = GXcopy;
gc = XCreateGC(theDisp, *pixmap, GCFunction, &gcv);
theImage = XCreateImage(theDisp, theVisual, 8, ZPixmap, 0,
Image, Width, Height, 8, Width);
theImage->byte_order = MSBFirst;
XPutImage(theDisp, *pixmap, gc, theImage, 0, 0, 0, 0,
theImage->width, theImage->height);
}
}
*width = theImage->width;
*height = theImage->height;
*depth = 0;
if (clipMask == (Pixmap) NULL) {
*clipMask = None;
}
/* clean up */
if (theImage) {
XDestroyImage(theImage);
theImage = NULL;
} else {
if (Image) {
XFree(Image);
Image = NULL;
}
}
XFreeGC(theDisp, gc);
return TCL_OK;
error:
if (theImage) {
XDestroyImage(theImage);
theImage = NULL;
} else {
if (Image) {
XFree(Image);
Image = NULL;
}
}
return TCL_ERROR;
}
#endif
/* eof */
|
the_stack_data/226686.c |
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
//先计算节点的高度,然后比较每个节点左右子树的高度。向上递归。
int m_max(int a, int b) { return a > b ? a : b;}
int height(struct TreeNode *root) {
if (root == NULL) { return -1; }
return 1 + m_max(height(root->left), height(root->right));
}
bool isBalanced(struct TreeNode* root){
if (root == NULL) { return true; }
return abs(height(root->right) - height(root->left)) < 2 && isBalanced(root->left) && isBalanced(root->right);
}
int main(int argc, const char * argv[]) {
struct TreeNode n11 = {1, NULL, NULL};
struct TreeNode n12 = {2, NULL, NULL};
struct TreeNode n1 = {3, &n11, &n12};
struct TreeNode n21 = {1, NULL, NULL};
struct TreeNode n22 = {2, NULL, NULL};
struct TreeNode n2 = {3, &n21, &n22};
struct TreeNode n = {0, &n1, &n2};
printf("= %d\n", isBalanced(&n));
return 0;
}
|
the_stack_data/788511.c | #include <stdio.h>
int main(){
int t;
scanf("%d",&t);
for(int i=0;i<t;i++){
int a,b,c,d;
scanf("%d %d %d %d",&a,&b,&c,&d);
if ((a==b && c==d) || (a==c && b==d) || (b==c && a==d)){
printf("YES\n");
} else {
printf("NO\n");
}
}
return 0;
} |
the_stack_data/111076691.c | #include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
#ifdef _MSC_VER
static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;}
static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;}
static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;}
static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;}
#else
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#endif
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#ifdef _MSC_VER
#define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);}
#define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);}
#else
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#endif
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conjf(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimagf(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#ifdef _MSC_VER
static _Fcomplex cpow_ui(complex x, integer n) {
complex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i;
for(u = n; ; ) {
if(u & 01) pow.r *= x.r, pow.i *= x.i;
if(u >>= 1) x.r *= x.r, x.i *= x.i;
else break;
}
}
_Fcomplex p={pow.r, pow.i};
return p;
}
#else
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#endif
#ifdef _MSC_VER
static _Dcomplex zpow_ui(_Dcomplex x, integer n) {
_Dcomplex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1];
for(u = n; ; ) {
if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1];
if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1];
else break;
}
}
_Dcomplex p = {pow._Val[0], pow._Val[1]};
return p;
}
#else
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#endif
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
#endif
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
#endif
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* Table of constant values */
static doublereal c_b7 = 1.;
static integer c__1 = 1;
static doublereal c_b10 = -1.;
/* > \brief \b DORHR_COL */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download DORHR_COL + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dorhr_c
ol.f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dorhr_c
ol.f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dorhr_c
ol.f"> */
/* > [TXT]</a> */
/* > */
/* Definition: */
/* =========== */
/* SUBROUTINE DORHR_COL( M, N, NB, A, LDA, T, LDT, D, INFO ) */
/* INTEGER INFO, LDA, LDT, M, N, NB */
/* DOUBLE PRECISION A( LDA, * ), D( * ), T( LDT, * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > DORHR_COL takes an M-by-N real matrix Q_in with orthonormal columns */
/* > as input, stored in A, and performs Householder Reconstruction (HR), */
/* > i.e. reconstructs Householder vectors V(i) implicitly representing */
/* > another M-by-N matrix Q_out, with the property that Q_in = Q_out*S, */
/* > where S is an N-by-N diagonal matrix with diagonal entries */
/* > equal to +1 or -1. The Householder vectors (columns V(i) of V) are */
/* > stored in A on output, and the diagonal entries of S are stored in D. */
/* > Block reflectors are also returned in T */
/* > (same output format as DGEQRT). */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] M */
/* > \verbatim */
/* > M is INTEGER */
/* > The number of rows of the matrix A. M >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The number of columns of the matrix A. M >= N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] NB */
/* > \verbatim */
/* > NB is INTEGER */
/* > The column block size to be used in the reconstruction */
/* > of Householder column vector blocks in the array A and */
/* > corresponding block reflectors in the array T. NB >= 1. */
/* > (Note that if NB > N, then N is used instead of NB */
/* > as the column block size.) */
/* > \endverbatim */
/* > */
/* > \param[in,out] A */
/* > \verbatim */
/* > A is DOUBLE PRECISION array, dimension (LDA,N) */
/* > */
/* > On entry: */
/* > */
/* > The array A contains an M-by-N orthonormal matrix Q_in, */
/* > i.e the columns of A are orthogonal unit vectors. */
/* > */
/* > On exit: */
/* > */
/* > The elements below the diagonal of A represent the unit */
/* > lower-trapezoidal matrix V of Householder column vectors */
/* > V(i). The unit diagonal entries of V are not stored */
/* > (same format as the output below the diagonal in A from */
/* > DGEQRT). The matrix T and the matrix V stored on output */
/* > in A implicitly define Q_out. */
/* > */
/* > The elements above the diagonal contain the factor U */
/* > of the "modified" LU-decomposition: */
/* > Q_in - ( S ) = V * U */
/* > ( 0 ) */
/* > where 0 is a (M-N)-by-(M-N) zero matrix. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= f2cmax(1,M). */
/* > \endverbatim */
/* > */
/* > \param[out] T */
/* > \verbatim */
/* > T is DOUBLE PRECISION array, */
/* > dimension (LDT, N) */
/* > */
/* > Let NOCB = Number_of_output_col_blocks */
/* > = CEIL(N/NB) */
/* > */
/* > On exit, T(1:NB, 1:N) contains NOCB upper-triangular */
/* > block reflectors used to define Q_out stored in compact */
/* > form as a sequence of upper-triangular NB-by-NB column */
/* > blocks (same format as the output T in DGEQRT). */
/* > The matrix T and the matrix V stored on output in A */
/* > implicitly define Q_out. NOTE: The lower triangles */
/* > below the upper-triangular blcoks will be filled with */
/* > zeros. See Further Details. */
/* > \endverbatim */
/* > */
/* > \param[in] LDT */
/* > \verbatim */
/* > LDT is INTEGER */
/* > The leading dimension of the array T. */
/* > LDT >= f2cmax(1,f2cmin(NB,N)). */
/* > \endverbatim */
/* > */
/* > \param[out] D */
/* > \verbatim */
/* > D is DOUBLE PRECISION array, dimension f2cmin(M,N). */
/* > The elements can be only plus or minus one. */
/* > */
/* > D(i) is constructed as D(i) = -SIGN(Q_in_i(i,i)), where */
/* > 1 <= i <= f2cmin(M,N), and Q_in_i is Q_in after performing */
/* > i-1 steps of “modified” Gaussian elimination. */
/* > See Further Details. */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit */
/* > < 0: if INFO = -i, the i-th argument had an illegal value */
/* > \endverbatim */
/* > */
/* > \par Further Details: */
/* ===================== */
/* > */
/* > \verbatim */
/* > */
/* > The computed M-by-M orthogonal factor Q_out is defined implicitly as */
/* > a product of orthogonal matrices Q_out(i). Each Q_out(i) is stored in */
/* > the compact WY-representation format in the corresponding blocks of */
/* > matrices V (stored in A) and T. */
/* > */
/* > The M-by-N unit lower-trapezoidal matrix V stored in the M-by-N */
/* > matrix A contains the column vectors V(i) in NB-size column */
/* > blocks VB(j). For example, VB(1) contains the columns */
/* > V(1), V(2), ... V(NB). NOTE: The unit entries on */
/* > the diagonal of Y are not stored in A. */
/* > */
/* > The number of column blocks is */
/* > */
/* > NOCB = Number_of_output_col_blocks = CEIL(N/NB) */
/* > */
/* > where each block is of order NB except for the last block, which */
/* > is of order LAST_NB = N - (NOCB-1)*NB. */
/* > */
/* > For example, if M=6, N=5 and NB=2, the matrix V is */
/* > */
/* > */
/* > V = ( VB(1), VB(2), VB(3) ) = */
/* > */
/* > = ( 1 ) */
/* > ( v21 1 ) */
/* > ( v31 v32 1 ) */
/* > ( v41 v42 v43 1 ) */
/* > ( v51 v52 v53 v54 1 ) */
/* > ( v61 v62 v63 v54 v65 ) */
/* > */
/* > */
/* > For each of the column blocks VB(i), an upper-triangular block */
/* > reflector TB(i) is computed. These blocks are stored as */
/* > a sequence of upper-triangular column blocks in the NB-by-N */
/* > matrix T. The size of each TB(i) block is NB-by-NB, except */
/* > for the last block, whose size is LAST_NB-by-LAST_NB. */
/* > */
/* > For example, if M=6, N=5 and NB=2, the matrix T is */
/* > */
/* > T = ( TB(1), TB(2), TB(3) ) = */
/* > */
/* > = ( t11 t12 t13 t14 t15 ) */
/* > ( t22 t24 ) */
/* > */
/* > */
/* > The M-by-M factor Q_out is given as a product of NOCB */
/* > orthogonal M-by-M matrices Q_out(i). */
/* > */
/* > Q_out = Q_out(1) * Q_out(2) * ... * Q_out(NOCB), */
/* > */
/* > where each matrix Q_out(i) is given by the WY-representation */
/* > using corresponding blocks from the matrices V and T: */
/* > */
/* > Q_out(i) = I - VB(i) * TB(i) * (VB(i))**T, */
/* > */
/* > where I is the identity matrix. Here is the formula with matrix */
/* > dimensions: */
/* > */
/* > Q(i){M-by-M} = I{M-by-M} - */
/* > VB(i){M-by-INB} * TB(i){INB-by-INB} * (VB(i))**T {INB-by-M}, */
/* > */
/* > where INB = NB, except for the last block NOCB */
/* > for which INB=LAST_NB. */
/* > */
/* > ===== */
/* > NOTE: */
/* > ===== */
/* > */
/* > If Q_in is the result of doing a QR factorization */
/* > B = Q_in * R_in, then: */
/* > */
/* > B = (Q_out*S) * R_in = Q_out * (S * R_in) = O_out * R_out. */
/* > */
/* > So if one wants to interpret Q_out as the result */
/* > of the QR factorization of B, then corresponding R_out */
/* > should be obtained by R_out = S * R_in, i.e. some rows of R_in */
/* > should be multiplied by -1. */
/* > */
/* > For the details of the algorithm, see [1]. */
/* > */
/* > [1] "Reconstructing Householder vectors from tall-skinny QR", */
/* > G. Ballard, J. Demmel, L. Grigori, M. Jacquelin, H.D. Nguyen, */
/* > E. Solomonik, J. Parallel Distrib. Comput., */
/* > vol. 85, pp. 3-31, 2015. */
/* > \endverbatim */
/* > */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date November 2019 */
/* > \ingroup doubleOTHERcomputational */
/* > \par Contributors: */
/* ================== */
/* > */
/* > \verbatim */
/* > */
/* > November 2019, Igor Kozachenko, */
/* > Computer Science Division, */
/* > University of California, Berkeley */
/* > */
/* > \endverbatim */
/* ===================================================================== */
/* Subroutine */ int dorhr_col_(integer *m, integer *n, integer *nb,
doublereal *a, integer *lda, doublereal *t, integer *ldt, doublereal *
d__, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, t_dim1, t_offset, i__1, i__2, i__3, i__4;
/* Local variables */
extern /* Subroutine */ int dlaorhr_col_getrfnp_(integer *, integer *,
doublereal *, integer *, doublereal *, integer *);
integer nplusone, i__, j;
extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *,
integer *);
integer iinfo;
extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *,
doublereal *, integer *), dtrsm_(char *, char *, char *, char *,
integer *, integer *, doublereal *, doublereal *, integer *,
doublereal *, integer *);
integer jb;
extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen);
integer jbtemp1, jbtemp2, jnb;
/* -- LAPACK computational routine (version 3.9.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* November 2019 */
/* ===================================================================== */
/* Test the input parameters */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
t_dim1 = *ldt;
t_offset = 1 + t_dim1 * 1;
t -= t_offset;
--d__;
/* Function Body */
*info = 0;
if (*m < 0) {
*info = -1;
} else if (*n < 0 || *n > *m) {
*info = -2;
} else if (*nb < 1) {
*info = -3;
} else if (*lda < f2cmax(1,*m)) {
*info = -5;
} else /* if(complicated condition) */ {
/* Computing MAX */
i__1 = 1, i__2 = f2cmin(*nb,*n);
if (*ldt < f2cmax(i__1,i__2)) {
*info = -7;
}
}
/* Handle error in the input parameters. */
if (*info != 0) {
i__1 = -(*info);
xerbla_("DORHR_COL", &i__1, (ftnlen)9);
return 0;
}
/* Quick return if possible */
if (f2cmin(*m,*n) == 0) {
return 0;
}
/* On input, the M-by-N matrix A contains the orthogonal */
/* M-by-N matrix Q_in. */
/* (1) Compute the unit lower-trapezoidal V (ones on the diagonal */
/* are not stored) by performing the "modified" LU-decomposition. */
/* Q_in - ( S ) = V * U = ( V1 ) * U, */
/* ( 0 ) ( V2 ) */
/* where 0 is an (M-N)-by-N zero matrix. */
/* (1-1) Factor V1 and U. */
dlaorhr_col_getrfnp_(n, n, &a[a_offset], lda, &d__[1], &iinfo);
/* (1-2) Solve for V2. */
if (*m > *n) {
i__1 = *m - *n;
dtrsm_("R", "U", "N", "N", &i__1, n, &c_b7, &a[a_offset], lda, &a[*n
+ 1 + a_dim1], lda);
}
/* (2) Reconstruct the block reflector T stored in T(1:NB, 1:N) */
/* as a sequence of upper-triangular blocks with NB-size column */
/* blocking. */
/* Loop over the column blocks of size NB of the array A(1:M,1:N) */
/* and the array T(1:NB,1:N), JB is the column index of a column */
/* block, JNB is the column block size at each step JB. */
nplusone = *n + 1;
i__1 = *n;
i__2 = *nb;
for (jb = 1; i__2 < 0 ? jb >= i__1 : jb <= i__1; jb += i__2) {
/* (2-0) Determine the column block size JNB. */
/* Computing MIN */
i__3 = nplusone - jb;
jnb = f2cmin(i__3,*nb);
/* (2-1) Copy the upper-triangular part of the current JNB-by-JNB */
/* diagonal block U(JB) (of the N-by-N matrix U) stored */
/* in A(JB:JB+JNB-1,JB:JB+JNB-1) into the upper-triangular part */
/* of the current JNB-by-JNB block T(1:JNB,JB:JB+JNB-1) */
/* column-by-column, total JNB*(JNB+1)/2 elements. */
jbtemp1 = jb - 1;
i__3 = jb + jnb - 1;
for (j = jb; j <= i__3; ++j) {
i__4 = j - jbtemp1;
dcopy_(&i__4, &a[jb + j * a_dim1], &c__1, &t[j * t_dim1 + 1], &
c__1);
}
/* (2-2) Perform on the upper-triangular part of the current */
/* JNB-by-JNB diagonal block U(JB) (of the N-by-N matrix U) stored */
/* in T(1:JNB,JB:JB+JNB-1) the following operation in place: */
/* (-1)*U(JB)*S(JB), i.e the result will be stored in the upper- */
/* triangular part of T(1:JNB,JB:JB+JNB-1). This multiplication */
/* of the JNB-by-JNB diagonal block U(JB) by the JNB-by-JNB */
/* diagonal block S(JB) of the N-by-N sign matrix S from the */
/* right means changing the sign of each J-th column of the block */
/* U(JB) according to the sign of the diagonal element of the block */
/* S(JB), i.e. S(J,J) that is stored in the array element D(J). */
i__3 = jb + jnb - 1;
for (j = jb; j <= i__3; ++j) {
if (d__[j] == 1.) {
i__4 = j - jbtemp1;
dscal_(&i__4, &c_b10, &t[j * t_dim1 + 1], &c__1);
}
}
/* (2-3) Perform the triangular solve for the current block */
/* matrix X(JB): */
/* X(JB) * (A(JB)**T) = B(JB), where: */
/* A(JB)**T is a JNB-by-JNB unit upper-triangular */
/* coefficient block, and A(JB)=V1(JB), which */
/* is a JNB-by-JNB unit lower-triangular block */
/* stored in A(JB:JB+JNB-1,JB:JB+JNB-1). */
/* The N-by-N matrix V1 is the upper part */
/* of the M-by-N lower-trapezoidal matrix V */
/* stored in A(1:M,1:N); */
/* B(JB) is a JNB-by-JNB upper-triangular right-hand */
/* side block, B(JB) = (-1)*U(JB)*S(JB), and */
/* B(JB) is stored in T(1:JNB,JB:JB+JNB-1); */
/* X(JB) is a JNB-by-JNB upper-triangular solution */
/* block, X(JB) is the upper-triangular block */
/* reflector T(JB), and X(JB) is stored */
/* in T(1:JNB,JB:JB+JNB-1). */
/* In other words, we perform the triangular solve for the */
/* upper-triangular block T(JB): */
/* T(JB) * (V1(JB)**T) = (-1)*U(JB)*S(JB). */
/* Even though the blocks X(JB) and B(JB) are upper- */
/* triangular, the routine DTRSM will access all JNB**2 */
/* elements of the square T(1:JNB,JB:JB+JNB-1). Therefore, */
/* we need to set to zero the elements of the block */
/* T(1:JNB,JB:JB+JNB-1) below the diagonal before the call */
/* to DTRSM. */
/* (2-3a) Set the elements to zero. */
jbtemp2 = jb - 2;
i__3 = jb + jnb - 2;
for (j = jb; j <= i__3; ++j) {
i__4 = *nb;
for (i__ = j - jbtemp2; i__ <= i__4; ++i__) {
t[i__ + j * t_dim1] = 0.;
}
}
/* (2-3b) Perform the triangular solve. */
dtrsm_("R", "L", "T", "U", &jnb, &jnb, &c_b7, &a[jb + jb * a_dim1],
lda, &t[jb * t_dim1 + 1], ldt);
}
return 0;
/* End of DORHR_COL */
} /* dorhr_col__ */
|
the_stack_data/40656.c | //11. Practice a program on count the number of conscuative even number of one's
#include<stdio.h>
void displayBits(int num)
{
int mask,i;
for(i = 31;i >= 0;i--)
{
mask = 1 << i;
putchar((num&mask) ? '1' : '0');
if(i%4 == 0)
{
printf(" ");
}
}
printf("\n");
}
void main()
{
int num,count = 0,even_count = 0;
printf("Enter the number\n");
scanf("%x",&num);
displayBits(num);
for(int i = 0;i <= 31;i++)
{
if(num&(1<<i))
{
count++;
}
else
{
if(count%2 == 0 && count != 0)
{
even_count++;
}
count = 0;
}
}
printf("Even count %d\n",even_count);
}
|
the_stack_data/67110.c | #include "stdio.h"
int main()
{
float a[64],s;
int i,j,d,k=1;
scanf("%f", &a[0]);
for(i=1 ; scanf("%f", &a[i])!=EOF ; i++)
{
d=i;
for(j=0;j<i;j++)
{
if(a[i]==a[j])
{
i--;
break;
}
}
if(d==i)k++;
}
printf("%d",k);
for(j=0;j<i;j++)
{
while(a[j]>=k)
{
a[j]=a[j]-k;
}
s=s+a[j];
}
printf("\n%.3f",s);
return 0;
}
|
the_stack_data/449832.c | #include <stdio.h>
#define MAX 1000
/* Exercise 3-2. Write a function escape(s, t) that converts characters like
newline and tab into visible escape sequences like \n \t as it copies the
string t to s. Use a swith. Write a function for the other direction as well,
converting escape sequences into the real characters. */
int escape(char s[], char t[])
{
int i, j;
i = 0;
j = 0;
while((s[j] = t[i]) != '\0'){
switch (s[j]) {
case '\t':
s[j] = '\\';
s[++j] = 't';
break;
case '\n':
s[j] = '\\';
s[++j] = 'n';
break;
}
j++;
i++;
}
s[j] = '\0';
return 0;
} |
the_stack_data/238442.c | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
unsigned int seconds = 0;
unsigned int numCtrlC = 0; // contador de CTRL+C
void sigint_handler (int signum) {
numCtrlC ++;
printf("\n[received %d] %d seconds passed\n", signum, seconds);
}
void sigquit_handler (int signum) {
printf("\n[received %d] CRTL+C called %d times\n", signum, numCtrlC);
exit(0); // terminar o programa
}
void sigalrm_handler (int signum) {
seconds++;
alarm(1);
}
int main (int argc, char* argv[]) {
// Registar handlers de sinais SIGINT, SIGQUIT e SIGALRM
signal(SIGINT, sigint_handler);
signal(SIGQUIT, sigquit_handler);
signal(SIGALRM, sigalrm_handler);
alarm(1);
while (1){
pause();
printf("executing ...\n");
}
return 0;
} |
the_stack_data/154829088.c | #ifdef USE_OPENGL
#ifdef WIN32
#include <windows.h>
#endif
#include <GL/gl.h>
#include <GL/glu.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "iup.h"
#include "iupgl.h"
#include "iupglcontrols.h"
#include "iupcontrols.h"
#include "iupim.h"
static unsigned char img_close[16 * 16] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
static unsigned char img_open[16 * 16] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
static Ihandle* load_image_Tecgraf(void)
{
unsigned char imgdata[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 88, 95, 108, 1, 90, 100, 117, 99, 123, 138, 166, 126, 137, 152, 181, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 105, 123, 147, 122, 137, 165, 255, 136, 152, 183, 255, 132, 149, 179, 250, 133, 149, 178, 69, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 92, 100, 115, 43, 111, 125, 150, 253, 140, 158, 190, 255, 135, 151, 182, 255, 132, 149, 179, 255, 131, 147, 177, 217, 153, 164, 188, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 113, 134, 148, 134, 151, 182, 255, 137, 154, 185, 255, 115, 129, 154, 252, 114, 128, 155, 255, 130, 146, 175, 255, 132, 147, 175, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 158, 159, 162, 3, 108, 121, 145, 230, 144, 162, 195, 255, 137, 154, 185, 197, 74, 79, 86, 45, 41, 46, 55, 246, 120, 134, 162, 255, 129, 145, 174, 156, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 101, 113, 48, 124, 139, 167, 255, 144, 161, 194, 255, 138, 155, 186, 67, 0, 0, 0, 0, 49, 54, 62, 150, 87, 98, 118, 255, 128, 144, 173, 223, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 102, 113, 132, 105, 137, 154, 185, 255, 139, 156, 188, 231, 143, 159, 187, 3, 0, 0, 0, 0, 64, 68, 76, 61, 70, 79, 95, 255, 127, 143, 172, 254, 134, 149, 175, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 109, 121, 142, 153, 141, 159, 191, 255, 139, 156, 188, 164, 0, 0, 0, 0, 0, 0, 0, 0, 79, 82, 87, 3, 69, 77, 92, 241, 122, 137, 165, 255, 127, 142, 170, 70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 110, 122, 146, 191, 145, 163, 196, 255, 139, 156, 188, 107, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 77, 86, 101, 190, 115, 129, 156, 255, 126, 141, 170, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 112, 125, 149, 227, 150, 168, 201, 255, 141, 157, 188, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 82, 91, 107, 144, 113, 127, 153, 255, 125, 140, 169, 144, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 163, 165, 167, 2, 112, 125, 150, 252, 155, 173, 203, 255, 143, 159, 189, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 85, 94, 110, 109, 114, 128, 155, 255, 125, 140, 168, 175, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 160, 167, 181, 1, 120, 130, 149, 33, 48, 53, 59, 69, 43, 46, 52, 100, 50, 54, 59, 137, 116, 130, 156, 255, 155, 171, 201, 255, 105, 118, 142, 155, 104, 117, 141, 151, 105, 118, 141, 151, 105, 118, 142, 151, 101, 113, 136, 185, 111, 124, 150, 255, 116, 130, 156, 220, 112, 125, 148, 95, 115, 127, 150, 67, 123, 134, 156, 33, 168, 176, 190, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 119, 129, 147, 5, 109, 121, 142, 71, 106, 118, 140, 140, 105, 117, 140, 197, 107, 120, 144, 242, 120, 135, 162, 255, 123, 137, 163, 255, 44, 49, 58, 255, 28, 32, 39, 255, 125, 139, 164, 255, 150, 167, 197, 255, 138, 155, 186, 255, 131, 148, 178, 255, 125, 141, 170, 255, 119, 134, 162, 255, 114, 128, 154, 255, 108, 122, 147, 255, 104, 117, 141, 255, 102, 115, 138, 255, 103, 116, 139, 255, 107, 120, 145, 255, 111, 124, 149, 245, 113, 126, 151, 200, 113, 127, 152, 140, 116, 129, 154, 71, 122, 135, 158, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 118, 128, 145, 14, 106, 118, 140, 130, 104, 116, 139, 234, 105, 118, 142, 255, 128, 144, 173, 255, 147, 165, 199, 255, 157, 177, 213, 255, 150, 168, 202, 255, 140, 156, 187, 229, 41, 45, 52, 196, 39, 43, 51, 183, 130, 143, 168, 255, 144, 161, 192, 233, 109, 122, 145, 109, 105, 116, 138, 109, 99, 110, 130, 109, 92, 103, 123, 109, 91, 100, 117, 145, 97, 109, 131, 255, 95, 106, 128, 248, 74, 83, 97, 193, 64, 72, 85, 227, 56, 63, 75, 255, 55, 62, 75, 255, 65, 73, 88, 255, 90, 101, 121, 255, 111, 125, 150, 255, 114, 128, 154, 236, 116, 129, 155, 130, 127, 140, 165, 16, 0, 0, 0, 0,
95, 101, 113, 22, 103, 115, 137, 220, 103, 116, 140, 255, 110, 123, 148, 255, 146, 165, 198, 255, 147, 165, 197, 232, 142, 158, 188, 147, 131, 144, 169, 78, 115, 123, 139, 20, 0, 0, 0, 0, 0, 0, 0, 0, 91, 97, 108, 68, 128, 142, 167, 255, 144, 162, 193, 212, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 100, 107, 31, 120, 135, 163, 255, 133, 150, 180, 231, 0, 0, 0, 0, 0, 0, 0, 0, 86, 89, 93, 20, 50, 54, 61, 73, 37, 40, 46, 141, 33, 36, 42, 230, 46, 52, 63, 255, 107, 120, 144, 255, 116, 130, 157, 255, 118, 133, 159, 223, 132, 147, 174, 24,
76, 83, 95, 114, 104, 117, 140, 255, 105, 117, 141, 255, 118, 133, 160, 253, 139, 155, 184, 116, 134, 143, 161, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93, 100, 110, 74, 122, 137, 163, 255, 143, 160, 191, 200, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 110, 114, 120, 31, 123, 138, 166, 255, 136, 153, 183, 228, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90, 93, 97, 5, 42, 45, 51, 111, 86, 97, 117, 253, 118, 133, 160, 255, 119, 133, 161, 255, 133, 149, 180, 116,
46, 50, 56, 109, 67, 76, 91, 255, 105, 118, 142, 255, 107, 120, 145, 254, 112, 125, 149, 131, 127, 139, 161, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93, 98, 109, 74, 116, 130, 156, 255, 142, 159, 190, 200, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 112, 115, 122, 31, 128, 143, 172, 255, 141, 157, 185, 228, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 124, 137, 163, 7, 122, 136, 162, 122, 120, 135, 162, 254, 121, 136, 164, 255, 136, 152, 184, 255, 126, 141, 168, 116,
71, 74, 79, 17, 31, 35, 41, 206, 42, 47, 57, 255, 77, 87, 105, 255, 103, 116, 140, 255, 110, 124, 149, 239, 112, 125, 150, 157, 115, 128, 153, 89, 122, 134, 158, 30, 147, 158, 177, 2, 0, 0, 0, 0, 81, 87, 96, 65, 109, 123, 148, 255, 141, 158, 190, 212, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 98, 103, 112, 31, 135, 151, 180, 255, 141, 156, 183, 231, 0, 0, 0, 0, 153, 164, 183, 1, 134, 147, 171, 30, 124, 138, 165, 84, 123, 138, 165, 154, 122, 137, 164, 235, 127, 143, 172, 255, 140, 157, 189, 255, 144, 162, 195, 255, 129, 144, 172, 218, 126, 138, 161, 22,
0, 0, 0, 0, 64, 68, 73, 7, 39, 43, 49, 118, 32, 36, 42, 225, 30, 35, 42, 255, 50, 57, 68, 255, 72, 81, 97, 255, 91, 102, 123, 255, 105, 118, 142, 255, 113, 127, 152, 240, 115, 129, 155, 204, 111, 124, 149, 196, 111, 125, 150, 255, 126, 141, 170, 234, 119, 133, 159, 120, 120, 134, 160, 116, 121, 135, 161, 117, 121, 135, 162, 119, 116, 130, 155, 152, 127, 142, 170, 255, 125, 140, 168, 248, 123, 138, 166, 199, 130, 145, 173, 235, 140, 155, 183, 255, 143, 160, 190, 255, 143, 161, 193, 255, 147, 165, 199, 255, 145, 164, 197, 255, 132, 148, 177, 230, 127, 140, 166, 126, 124, 134, 151, 12, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 138, 141, 144, 3, 55, 58, 63, 58, 37, 40, 46, 126, 34, 38, 44, 184, 34, 38, 44, 235, 35, 39, 47, 254, 49, 55, 66, 255, 64, 72, 87, 255, 77, 87, 104, 255, 88, 98, 118, 255, 96, 108, 130, 255, 103, 116, 139, 255, 108, 122, 147, 255, 113, 127, 153, 255, 118, 133, 160, 255, 124, 140, 168, 255, 133, 148, 176, 255, 141, 156, 183, 255, 146, 161, 187, 255, 144, 159, 186, 255, 131, 146, 174, 254, 127, 141, 168, 237, 126, 141, 168, 188, 123, 137, 162, 131, 112, 123, 143, 61, 128, 132, 140, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 91, 94, 98, 19, 64, 68, 73, 56, 53, 57, 65, 82, 62, 67, 76, 116, 66, 74, 89, 255, 95, 107, 129, 255, 80, 88, 103, 155, 81, 90, 105, 151, 86, 95, 112, 151, 95, 104, 122, 151, 98, 109, 128, 180, 124, 139, 166, 255, 109, 122, 146, 218, 100, 110, 128, 84, 96, 104, 118, 56, 105, 109, 117, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 173, 174, 176, 2, 74, 83, 98, 252, 131, 147, 178, 255, 140, 155, 184, 29, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 122, 134, 157, 114, 151, 169, 203, 255, 123, 138, 165, 174, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 76, 90, 224, 122, 137, 165, 255, 136, 152, 182, 69, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 125, 139, 165, 147, 146, 164, 198, 255, 122, 137, 165, 144, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 69, 81, 191, 110, 124, 149, 255, 134, 151, 181, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 143, 170, 193, 142, 160, 192, 255, 122, 137, 164, 111, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 58, 63, 74, 150, 94, 105, 127, 255, 133, 149, 179, 166, 0, 0, 0, 0, 0, 0, 0, 0, 115, 119, 128, 5, 130, 145, 174, 242, 137, 154, 186, 255, 125, 139, 166, 70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54, 58, 66, 102, 72, 81, 97, 255, 132, 148, 178, 236, 148, 161, 187, 5, 0, 0, 0, 0, 110, 121, 140, 64, 140, 157, 189, 255, 127, 142, 171, 254, 131, 144, 169, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 65, 71, 43, 47, 52, 63, 255, 127, 143, 172, 255, 132, 148, 177, 75, 0, 0, 0, 0, 121, 134, 158, 160, 139, 156, 188, 255, 123, 138, 165, 223, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 154, 156, 158, 1, 36, 39, 46, 227, 106, 119, 143, 255, 130, 145, 175, 203, 114, 125, 147, 51, 123, 138, 166, 247, 131, 147, 177, 255, 123, 138, 165, 151, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 41, 47, 143, 68, 77, 93, 255, 128, 144, 174, 255, 126, 141, 170, 252, 129, 145, 174, 255, 123, 138, 166, 255, 127, 141, 167, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 68, 73, 40, 34, 38, 46, 250, 117, 131, 158, 255, 126, 142, 171, 255, 124, 140, 168, 255, 125, 139, 166, 214, 140, 152, 172, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 41, 44, 50, 134, 58, 66, 79, 255, 123, 138, 166, 255, 123, 138, 166, 250, 127, 140, 165, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 154, 156, 158, 1, 46, 50, 55, 83, 82, 89, 102, 123, 106, 116, 136, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
Ihandle* image = IupImageRGBA(32, 32, imgdata);
return image;
}
static Ihandle* load_image_FileSave(void)
{
unsigned char imgdata[] = {
255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255,
255, 0, 255, 255, 183, 182, 245, 255, 183, 182, 245, 255, 179, 178, 243, 255, 174, 173, 241, 255, 168, 167, 238, 255, 162, 161, 234, 255, 155, 154, 231, 255, 148, 147, 228, 255, 143, 142, 224, 255, 136, 135, 221, 255, 129, 128, 218, 255, 123, 122, 214, 255, 117, 116, 211, 255, 112, 111, 209, 255, 255, 0, 255, 255,
255, 0, 255, 255, 179, 178, 243, 255, 190, 189, 255, 255, 147, 146, 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 248, 251, 255, 75, 88, 190, 255, 89, 88, 176, 255, 89, 88, 176, 255, 255, 0, 255, 255,
255, 0, 255, 255, 173, 172, 240, 255, 190, 189, 255, 255, 138, 137, 239, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 248, 251, 255, 234, 238, 246, 255, 63, 82, 184, 255, 51, 51, 103, 255, 86, 85, 170, 255, 255, 0, 255, 255,
255, 0, 255, 255, 167, 166, 237, 255, 190, 189, 255, 255, 129, 128, 230, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 248, 251, 255, 234, 238, 246, 255, 222, 229, 240, 255, 52, 77, 179, 255, 122, 121, 223, 255, 83, 82, 164, 255, 255, 0, 255, 255,
255, 0, 255, 255, 159, 158, 233, 255, 190, 189, 255, 255, 119, 118, 220, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 248, 251, 255, 234, 238, 246, 255, 222, 229, 240, 255, 210, 219, 234, 255, 40, 71, 173, 255, 114, 113, 215, 255, 80, 79, 159, 255, 255, 0, 255, 255,
255, 0, 255, 255, 152, 151, 229, 255, 190, 189, 255, 255, 110, 109, 211, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 248, 251, 255, 234, 238, 246, 255, 222, 229, 240, 255, 210, 219, 234, 255, 198, 209, 229, 255, 28, 65, 167, 255, 103, 103, 204, 255, 77, 77, 154, 255, 255, 0, 255, 255,
255, 0, 255, 255, 146, 145, 226, 255, 190, 189, 255, 255, 103, 102, 204, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 248, 251, 255, 234, 238, 246, 255, 222, 229, 240, 255, 210, 219, 234, 255, 198, 209, 229, 255, 189, 202, 225, 255, 17, 59, 161, 255, 92, 93, 194, 255, 74, 74, 148, 255, 255, 0, 255, 255,
255, 0, 255, 255, 139, 138, 223, 255, 188, 187, 255, 255, 183, 182, 255, 255, 96, 99, 201, 255, 86, 94, 196, 255, 75, 88, 190, 255, 63, 82, 184, 255, 52, 77, 179, 255, 40, 71, 173, 255, 28, 65, 167, 255, 17, 59, 161, 255, 92, 93, 193, 255, 84, 86, 186, 255, 71, 71, 143, 255, 255, 0, 255, 255,
255, 0, 255, 255, 132, 131, 219, 255, 180, 179, 255, 255, 174, 173, 255, 255, 164, 163, 252, 255, 143, 142, 244, 255, 135, 134, 236, 255, 129, 128, 230, 255, 122, 121, 223, 255, 114, 113, 215, 255, 108, 107, 209, 255, 92, 93, 193, 255, 84, 86, 186, 255, 76, 80, 178, 255, 68, 68, 137, 255, 255, 0, 255, 255,
255, 0, 255, 255, 124, 123, 215, 255, 170, 169, 255, 255, 160, 159, 251, 255, 148, 147, 245, 255, 75, 91, 113, 255, 75, 91, 113, 255, 75, 91, 113, 255, 75, 91, 113, 255, 82, 98, 118, 255, 91, 106, 125, 255, 84, 86, 186, 255, 76, 79, 178, 255, 68, 73, 170, 255, 65, 65, 131, 255, 255, 0, 255, 255,
255, 0, 255, 255, 118, 117, 212, 255, 160, 159, 255, 255, 145, 144, 245, 255, 135, 134, 236, 255, 75, 91, 113, 255, 0, 0, 0, 255, 52, 60, 71, 255, 206, 217, 233, 255, 212, 221, 236, 255, 103, 116, 133, 255, 67, 75, 174, 255, 68, 73, 170, 255, 60, 66, 163, 255, 62, 62, 125, 255, 255, 0, 255, 255,
255, 0, 255, 255, 112, 111, 209, 255, 154, 153, 255, 255, 135, 134, 236, 255, 129, 128, 230, 255, 75, 91, 113, 255, 52, 60, 71, 255, 104, 120, 141, 255, 216, 224, 237, 255, 224, 231, 241, 255, 115, 127, 143, 255, 53, 65, 163, 255, 60, 66, 162, 255, 53, 61, 156, 255, 60, 59, 120, 255, 255, 0, 255, 255,
255, 0, 255, 255, 108, 107, 207, 255, 143, 142, 243, 255, 129, 128, 230, 255, 36, 68, 170, 255, 33, 50, 71, 255, 171, 180, 195, 255, 179, 187, 198, 255, 188, 193, 202, 255, 196, 200, 206, 255, 72, 77, 86, 255, 51, 62, 158, 255, 54, 61, 156, 255, 49, 57, 152, 255, 57, 57, 114, 255, 255, 0, 255, 255,
255, 0, 255, 255, 108, 107, 207, 84, 101, 100, 195, 255, 86, 85, 170, 255, 83, 82, 164, 255, 80, 79, 159, 255, 77, 77, 154, 255, 74, 74, 148, 255, 71, 71, 143, 255, 68, 68, 137, 255, 65, 65, 131, 255, 60, 59, 120, 255, 60, 59, 120, 255, 57, 57, 114, 255, 55, 54, 110, 255, 255, 0, 255, 255,
255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255 };
Ihandle* image = IupImageRGBA(16, 16, imgdata);
return image;
}
static Ihandle* load_image_Test(void)
{
Ihandle *image;
unsigned char image_data_32[16 * 16 * 4] = {
255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0,
255, 0, 255, 0, 183, 182, 245, 255, 183, 182, 245, 255, 179, 178, 243, 255, 174, 173, 241, 255, 168, 167, 238, 255, 162, 161, 234, 255, 155, 154, 231, 255, 148, 147, 228, 255, 143, 142, 224, 255, 136, 135, 221, 255, 129, 128, 218, 255, 123, 122, 214, 255, 117, 116, 211, 255, 112, 111, 209, 255, 255, 0, 255, 0,
255, 0, 255, 0, 179, 178, 243, 255, 190, 189, 255, 255, 147, 146, 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 248, 251, 255, 75, 88, 190, 255, 89, 88, 176, 255, 89, 88, 176, 255, 255, 0, 255, 0,
255, 0, 255, 0, 173, 172, 240, 255, 190, 189, 255, 255, 138, 137, 239, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 248, 251, 255, 234, 238, 246, 255, 63, 82, 184, 255, 51, 51, 103, 255, 86, 85, 170, 255, 255, 0, 255, 0,
255, 0, 255, 0, 167, 166, 237, 255, 190, 189, 255, 255, 129, 128, 230, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 248, 251, 255, 234, 238, 246, 255, 222, 229, 240, 255, 52, 77, 179, 255, 122, 121, 223, 255, 83, 82, 164, 255, 255, 0, 255, 0,
255, 0, 255, 0, 159, 158, 233, 255, 190, 189, 255, 255, 119, 118, 220, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 248, 251, 255, 234, 238, 246, 255, 222, 229, 240, 255, 210, 219, 234, 255, 40, 71, 173, 255, 114, 113, 215, 255, 80, 79, 159, 255, 255, 0, 255, 0,
255, 0, 255, 0, 152, 151, 229, 255, 190, 189, 255, 255, 110, 109, 211, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 248, 251, 255, 234, 238, 246, 255, 222, 229, 240, 255, 210, 219, 234, 255, 198, 209, 229, 255, 28, 65, 167, 255, 103, 103, 204, 255, 77, 77, 154, 255, 255, 0, 255, 0,
255, 0, 255, 0, 146, 145, 226, 255, 190, 189, 255, 255, 103, 102, 204, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 248, 251, 255, 234, 238, 246, 255, 222, 229, 240, 255, 210, 219, 234, 255, 198, 209, 229, 255, 189, 202, 225, 255, 17, 59, 161, 255, 92, 93, 194, 255, 74, 74, 148, 255, 255, 0, 255, 0,
255, 0, 255, 0, 139, 138, 223, 255, 188, 187, 255, 255, 183, 182, 255, 255, 96, 99, 201, 255, 86, 94, 196, 255, 75, 88, 190, 255, 63, 82, 184, 255, 52, 77, 179, 255, 40, 71, 173, 255, 28, 65, 167, 255, 17, 59, 161, 255, 92, 93, 193, 255, 84, 86, 186, 255, 71, 71, 143, 255, 255, 0, 255, 0,
255, 0, 255, 0, 132, 131, 219, 255, 180, 179, 255, 255, 174, 173, 255, 255, 164, 163, 252, 255, 143, 142, 244, 255, 135, 134, 236, 255, 129, 128, 230, 255, 122, 121, 223, 255, 114, 113, 215, 255, 108, 107, 209, 255, 92, 93, 193, 255, 84, 86, 186, 255, 76, 80, 178, 255, 68, 68, 137, 255, 255, 0, 255, 0,
255, 0, 255, 0, 124, 123, 215, 255, 170, 169, 255, 255, 160, 159, 251, 255, 148, 147, 245, 255, 75, 91, 113, 255, 75, 91, 113, 255, 75, 91, 113, 255, 75, 91, 113, 255, 82, 98, 118, 255, 91, 106, 125, 255, 84, 86, 186, 255, 76, 79, 178, 255, 68, 73, 170, 255, 65, 65, 131, 255, 255, 0, 255, 0,
255, 0, 255, 0, 118, 117, 212, 255, 160, 159, 255, 255, 145, 144, 245, 255, 135, 134, 236, 255, 75, 91, 113, 255, 0, 0, 0, 255, 52, 60, 71, 255, 206, 217, 233, 255, 212, 221, 236, 255, 103, 116, 133, 255, 67, 75, 174, 255, 68, 73, 170, 255, 60, 66, 163, 255, 62, 62, 125, 255, 255, 0, 255, 0,
255, 0, 255, 0, 112, 111, 209, 255, 154, 153, 255, 255, 135, 134, 236, 255, 129, 128, 230, 255, 75, 91, 113, 255, 52, 60, 71, 255, 104, 120, 141, 255, 216, 224, 237, 255, 224, 231, 241, 255, 115, 127, 143, 255, 53, 65, 163, 255, 60, 66, 162, 255, 53, 61, 156, 255, 60, 59, 120, 255, 255, 0, 255, 0,
255, 0, 255, 0, 108, 107, 207, 255, 143, 142, 243, 255, 129, 128, 230, 255, 36, 68, 170, 255, 33, 50, 71, 255, 171, 180, 195, 255, 179, 187, 198, 255, 188, 193, 202, 255, 196, 200, 206, 255, 72, 77, 86, 255, 51, 62, 158, 255, 54, 61, 156, 255, 49, 57, 152, 255, 57, 57, 114, 255, 255, 0, 255, 0,
255, 0, 255, 0, 108, 107, 207, 84, 101, 100, 195, 255, 86, 85, 170, 255, 83, 82, 164, 255, 80, 79, 159, 255, 77, 77, 154, 255, 74, 74, 148, 255, 71, 71, 143, 255, 68, 68, 137, 255, 65, 65, 131, 255, 60, 59, 120, 255, 60, 59, 120, 255, 57, 57, 114, 255, 55, 54, 110, 255, 255, 0, 255, 0,
255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0 };
image = IupImageRGBA(16, 16, image_data_32);
return image;
}
typedef struct _color3D
{
double r;
double g;
double b;
} color3D;
static void add_color_vertex(const color3D* c)
{
glColor3d(c->r, c->g, c->b);
glVertex3d(c->r, c->g, c->b);
}
static void draw_cube_face(const color3D* c1, const color3D* c2, const color3D* c3, const color3D* c4)
{
color3D cm;
cm.r = (c1->r + c2->r + c3->r + c4->r)/4;
cm.g = (c1->g + c2->g + c3->g + c4->g)/4;
cm.b = (c1->b + c2->b + c3->b + c4->b)/4;
add_color_vertex(&cm);
add_color_vertex(c1);
add_color_vertex(c2);
add_color_vertex(&cm);
add_color_vertex(c2);
add_color_vertex(c3);
add_color_vertex(&cm);
add_color_vertex(c3);
add_color_vertex(c4);
add_color_vertex(&cm);
add_color_vertex(c4);
add_color_vertex(c1);
}
const color3D c3D_black = {0.0, 0.0, 0.0};
const color3D c3D_red = {1.0, 0.0, 0.0};
const color3D c3D_green = {0.0, 1.0, 0.0};
const color3D c3D_blue = {0.0, 0.0, 1.0};
const color3D c3D_cian = {0.0, 1.0, 1.0};
const color3D c3D_magenta = {1.0, 0.0, 1.0};
const color3D c3D_yellow = {1.0, 1.0, 0.0};
const color3D c3D_white = {1.0, 1.0, 1.0};
static void draw_cube(void)
{
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_TRIANGLES);
draw_cube_face(&c3D_black, &c3D_blue, &c3D_magenta, &c3D_red);
draw_cube_face(&c3D_black, &c3D_green, &c3D_cian, &c3D_blue);
draw_cube_face(&c3D_black, &c3D_red, &c3D_yellow, &c3D_green);
draw_cube_face(&c3D_white, &c3D_cian, &c3D_blue, &c3D_magenta);
draw_cube_face(&c3D_white, &c3D_cian, &c3D_green, &c3D_yellow);
draw_cube_face(&c3D_white, &c3D_magenta, &c3D_red, &c3D_yellow);
glEnd();
}
static double model_view_matrix[16];
static int use_model_matrix = 0;
static void init(void)
{
glClearColor(1, 1, 1, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, 1, 1, 10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.5, 0.5, 3.0, /* posicao do observador */
0.5, 0.5, 0.0, /* ponto de referencia */
0.0, 1.0, 0.0); /* vup */
glEnable(GL_DEPTH_TEST);
glClearDepth(1.0);
if (use_model_matrix)
glLoadMatrixd(model_view_matrix);
}
static int pos_x, pos_y;
static int move = 0;
static int button_cb(Ihandle *ih,int but,int pressed,int x,int y,char* status)
{
(void)ih;
(void)status;
if (but==IUP_BUTTON1)
{
if (pressed)
{
pos_x = x;
pos_y = y;
move = 1;
}
else
{
move = 0;
}
}
return IUP_DEFAULT;
}
#define INVERT_Y(_y) (height-y)
static int motion_cb(Ihandle *ih,int x,int y,char* status)
{
(void)status;
if (move)
{
double dif_x, dif_y;
double dx, dy, dz;
double x1, y1, z1;
double x2, y2, z2;
double angle, norma;
int height = IupGetInt2(ih, "RASTERSIZE");
double mv[16];
double pm[16];
int vp[4];
IupGLMakeCurrent(ih);
glGetDoublev(GL_MODELVIEW_MATRIX, mv);
glGetDoublev(GL_PROJECTION_MATRIX, pm);
glGetIntegerv(GL_VIEWPORT, vp);
dif_x = x - pos_x;
dif_y = y - pos_y;
if (dif_x == 0 && dif_y == 0)
return IUP_DEFAULT;
pos_x = x;
pos_y = y;
angle = sqrt(dif_x*dif_x + dif_y*dif_y);
gluUnProject(pos_x, INVERT_Y(pos_y), 0.0,
mv, pm, vp,
&x1, &y1, &z1);
gluUnProject((double)(dif_y + pos_x), (double)(dif_x + INVERT_Y(pos_y)), 0.0,
mv, pm, vp,
&x2, &y2, &z2);
dx = x2-x1; dy = y2-y1; dz = z2-z1;
norma = sqrt(dx*dx + dy*dy + dz*dz);
dx /= norma; dy /= norma; dz /= norma;
glMatrixMode(GL_MODELVIEW);
glTranslated(0.5, 0.5, 0.5);
glRotated (angle, dx, dy, dz);
glTranslated(-0.5, -0.5, -0.5);
glGetDoublev(GL_MODELVIEW_MATRIX, model_view_matrix);
use_model_matrix = 1;
draw_cube();
IupGLSwapBuffers(ih);
}
return IUP_DEFAULT;
}
static int action(Ihandle *ih)
{
IupGLMakeCurrent(ih);
init();
draw_cube();
IupGLSwapBuffers(ih);
return IUP_DEFAULT;
}
static int button_action_cb(Ihandle *ih)
{
printf("ACTION_CB(%s) NAME=%s\n", IupGetClassName(ih), IupGetAttribute(ih, "NAME"));
return IUP_DEFAULT;
}
static int toggle_action_cb(Ihandle *ih, int state)
{
printf("ACTION_CB(%s, state=%d) NAME=%s\n", IupGetClassName(ih), state, IupGetAttribute(ih, "NAME"));
return IUP_DEFAULT;
}
static int link_action_cb(Ihandle *ih, const char* url)
{
printf("ACTION_CB(%s, url=%s)\n", IupGetClassName(ih), url);
return IUP_DEFAULT;
}
static int val_action_cb(Ihandle *ih)
{
Ihandle* pbar = (Ihandle*)IupGetAttribute(ih, "PROGRESSBAR");
IupSetStrAttribute(pbar, "VALUE", IupGetAttribute(ih, "VALUE"));
printf("ACTION_CB(%s, value=%0.1f) NAME=%s\n", IupGetClassName(ih), IupGetFloat(ih, "VALUE"), IupGetAttribute(ih, "NAME"));
return IUP_DEFAULT;
}
static int expand_cb(Ihandle *ih)
{
printf("ACTION(%s)\n", IupGetClassName(ih));
return IUP_DEFAULT;
}
static int extrabutton_cb(Ihandle *ih, int button, int pressed)
{
printf("EXTRABUTTON_CB(%s, but=%d, press=%d)\n", IupGetClassName(ih), button, pressed);
return IUP_DEFAULT;
}
void GLCanvasCubeTest(void)
{
Ihandle *dlg, *canvas, *box, *gtoggle, *gtoggle1, *gtoggle2,
*hbox, *vbox, *glabel, *gsep1, *gsep2, *gbutton1, *gbutton2,
*pbar1, *pbar2, *glink, *gval1, *gval2, *gframe1, *gframe2,
*gexp1, *gexp2, *image_open, *image_close, *image_high,
*gframe3, *vbox2, *gtoggle3, *gtoggle4, *gtoggle5, *gsbox,
*text, *vbox3, *matrix, *image_val, *gtext;
IupGLCanvasOpen();
IupGLControlsOpen();
IupControlsOpen();
glabel = IupGLLabel("Label");
// IupSetAttribute(glabel, "FGCOLOR", "255 255 255");
IupSetAttribute(glabel, "FONT", "Helvetica, 24");
IupSetAttributeHandle(glabel, "IMAGE", load_image_Tecgraf());
gbutton1 = IupGLButton("Button");
IupSetAttribute(gbutton1, "PADDING", "5x5");
//IupSetAttribute(gbutton1, "BGCOLOR", "245 0 245 92");
IupSetCallback(gbutton1, "ACTION", button_action_cb);
IupSetAttribute(gbutton1, "NAME", "button1");
IupSetAttribute(gbutton1, "TIP", "Button Tip");
// IupSetAttribute(gbutton1, "RASTERSIZE", "x100");
if (0)
{
Ihandle* pressed_back = IupLoadImage("../test/pressed_back.png");
Ihandle* enabled_back = IupLoadImage("../test/enabled_back.png");
Ihandle* highlighted_back = IupLoadImage("../test/highlighted_back.png");
IupSetAttributeHandle(gbutton1, "BACKIMAGE", enabled_back);
IupSetAttributeHandle(gbutton1, "BACKIMAGEPRESS", pressed_back);
IupSetAttributeHandle(gbutton1, "BACKIMAGEHIGHLIGHT", highlighted_back);
IupSetAttribute(gbutton1, "BORDERCOLOR", "0 0 0 0");
}
gbutton2 = IupGLButton(NULL);
IupSetAttribute(gbutton2, "PADDING", "5x5");
IupSetAttributeHandle(gbutton2, "IMAGE", load_image_FileSave());
IupSetCallback(gbutton2, "ACTION", button_action_cb);
IupSetAttribute(gbutton2, "NAME", "button2");
gtoggle = IupGLToggle("Toggle");
IupSetAttribute(gtoggle, "PADDING", "5x5");
IupSetCallback(gtoggle, "ACTION", (Icallback)toggle_action_cb);
IupSetAttribute(gtoggle, "NAME", "toggle");
gtoggle1 = IupGLToggle(NULL);
IupSetAttribute(gtoggle1, "PADDING", "5x5");
IupSetAttributeHandle(gtoggle1, "IMAGE", load_image_Test());
IupSetCallback(gtoggle1, "ACTION", (Icallback)toggle_action_cb);
IupSetAttribute(gtoggle1, "NAME", "toggle1");
gtoggle2 = IupGLToggle(NULL);
IupSetAttribute(gtoggle2, "PADDING", "5x5");
IupSetAttributeHandle(gtoggle2, "IMAGE", load_image_Test());
IupSetCallback(gtoggle2, "ACTION", (Icallback)toggle_action_cb);
IupSetAttribute(gtoggle2, "NAME", "toggle2");
gsep1 = IupGLSeparator();
glink = IupGLLink("http://www.tecgraf.puc-rio.br/iup", "IUP Toolkit");
IupSetCallback(glink, "ACTION", (Icallback)link_action_cb);
pbar1 = IupGLProgressBar();
IupSetAttribute(pbar1, "VALUE", "0.3");
IupSetAttribute(pbar1, "SHOWTEXT", "Yes");
//image_val = IupLoadImage("../test/slider_handler.png");
gval1 = IupGLVal();
IupSetAttribute(gval1, "VALUE", "0.3");
IupSetCallback(gval1, "VALUECHANGED_CB", val_action_cb);
IupSetAttribute(gval1, "PROGRESSBAR", (char*)pbar1);
IupSetAttribute(gval1, "NAME", "val1");
IupSetAttribute(gval1, "TIP", "Val Tip");
//IupSetAttributeHandle(gval1, "IMAGE", image_val);
hbox = IupHbox(glabel, gsep1, gbutton1, gtoggle, glink, pbar1, gval1, NULL);
IupSetAttribute(hbox, "ALIGNMENT", "ACENTER");
IupSetAttribute(hbox, "MARGIN", "5x5");
IupSetAttribute(hbox, "GAP", "5");
pbar2 = IupGLProgressBar();
IupSetAttribute(pbar2, "VALUE", "0.3");
IupSetAttribute(pbar2, "ORIENTATION", "VERTICAL");
gval2 = IupGLVal();
IupSetAttribute(gval2, "VALUE", "0.3");
IupSetAttribute(gval2, "ORIENTATION", "VERTICAL");
IupSetCallback(gval2, "VALUECHANGED_CB", val_action_cb);
IupSetAttribute(gval2, "PROGRESSBAR", (char*)pbar2);
IupSetAttribute(gval2, "NAME", "val2");
gsep2 = IupGLSeparator();
IupSetAttribute(gsep2, "ORIENTATION", "HORIZONTAL");
vbox = IupVbox(gbutton2, gsep2,
IupRadio(IupSetAttributes(IupVbox(gtoggle1, gtoggle2, NULL), "MARGIN=0x0")),
pbar2,
gval2,
NULL);
IupSetAttribute(vbox, "ALIGNMENT", "ACENTER");
IupSetAttribute(vbox, "MARGIN", "5x5");
IupSetAttribute(vbox, "GAP", "5");
gtoggle5 = IupGLToggle("Toggle");
IupSetAttribute(gtoggle5, "PADDING", "5x5");
IupSetCallback(gtoggle5, "ACTION", (Icallback)toggle_action_cb);
IupSetAttribute(gtoggle5, "NAME", "toggle5");
IupSetAttribute(gtoggle5, "CHECKMARK", "Yes");
// IupSetAttribute(gtoggle5, "RIGHTBUTTON", "Yes");
gtoggle3 = IupGLToggle("Radio Toggle");
IupSetAttribute(gtoggle3, "PADDING", "5x5");
IupSetCallback(gtoggle3, "ACTION", (Icallback)toggle_action_cb);
IupSetAttribute(gtoggle3, "NAME", "toggle3");
IupSetAttribute(gtoggle3, "CHECKMARK", "Yes");
gtoggle4 = IupGLToggle("Radio Toggle");
IupSetAttribute(gtoggle4, "PADDING", "5x5");
IupSetAttributeHandle(gtoggle4, "IMAGE", load_image_Test());
IupSetCallback(gtoggle4, "ACTION", (Icallback)toggle_action_cb);
IupSetAttribute(gtoggle4, "NAME", "toggle4");
IupSetAttribute(gtoggle4, "CHECKMARK", "Yes");
// IupSetAttribute(gtoggle4, "RIGHTBUTTON", "Yes");
gtext = IupGLText();
IupSetAttribute(gtext, "NAME", "text");
IupSetAttribute(gtext, "VALUE", "text edit very long");
// IupSetAttribute(gtext, "FONTSIZE", "24");
// IupSetAttribute(gtext, "RASTERSIZE", "100x50");
vbox2 = IupVbox(
IupRadio(IupSetAttributes(IupVbox(gtoggle3, gtoggle4, NULL), "MARGIN=0x0")),
gtoggle5,
gtext,
NULL);
gsbox = IupSetAttributes(IupGLScrollBox(vbox2), "RASTERSIZE=90x90");
gsbox = IupGLSizeBox(gsbox);
gframe1 = IupSetAttributes(IupGLFrame(hbox), "TITLE=Frame1");
gframe2 = IupSetAttributes(IupGLFrame(vbox), "BACKCOLOR=\"250 250 160 128\", FRAMECOLOR=\"250 250 160\"");
gframe3 = IupSetAttributes(IupGLFrame(gsbox), "TITLE=Frame3, TITLEBOX=Yes");
// IupSetAttributeHandle(gframe3, "TITLEBACKIMAGE", load_image_Tecgraf());
gexp1 = IupSetAttributes(IupGLExpander(gframe1), "TITLE=Expander");
gexp2 = IupSetAttributes(IupGLExpander(gframe2), "BARPOSITION=LEFT");
text = IupText(NULL);
IupSetAttribute(text, "VALUE", "Text");
matrix = IupMatrix(NULL);
IupSetAttribute(matrix, "NUMLIN", "3");
IupSetAttribute(matrix, "NUMCOL", "2");
IupSetAttribute(matrix, "NUMLIN_VISIBLE", "3");
IupSetAttribute(matrix, "NUMCOL_VISIBLE", "2");
IupSetAttribute(matrix, "0:0", "Inflation");
IupSetAttribute(matrix, "1:0", "Medicine");
IupSetAttribute(matrix, "2:0", "Food");
IupSetAttribute(matrix, "3:0", "Energy");
IupSetAttribute(matrix, "0:1", "January 2000");
IupSetAttribute(matrix, "0:2", "February 2000");
IupSetAttribute(matrix, "1:1", "5.6");
IupSetAttribute(matrix, "2:1", "2.2");
IupSetAttribute(matrix, "3:1", "4.1");
IupSetAttribute(matrix, "1:2", "10");
IupSetAttribute(matrix, "2:2", "1");
IupSetAttribute(matrix, "3:2", "0.5");
// IupSetAttribute(matrix, "EXPAND", "No");
IupSetAttribute(matrix, "SCROLLBAR", "No");
vbox3 = IupVbox(
text,
matrix,
NULL);
vbox3 = IupSetAttributes(IupGLFrame(vbox3), "TITLE=Frame4");
#if 0
canvas = IupGLCanvas(
NULL);
#else
canvas = IupGLCanvasBox(
IupSetAttributes(gexp1, "HORIZONTALALIGN=ACENTER, VERTICALALIGN=ATOP, MOVEABLE=Yes, MOVETOTOP=Yes"),
IupSetAttributes(gexp2, "HORIZONTALALIGN=ALEFT, VERTICALALIGN=ACENTER"),
IupSetAttributes(gframe3, "MOVEABLE=Yes, POSITION=\"550,200\", MOVETOTOP=Yes"),
IupSetAttributes(vbox3, "MOVEABLE=Yes, POSITION=\"250,350\""),
NULL);
#endif
IupSetAttribute(canvas, "DEPTH_SIZE", "16");
image_open = IupImage(16, 16, img_open);
image_close = IupImage(16, 16, img_close);
image_high = IupImage(16, 16, img_close);
IupSetAttribute(image_open, "0", "BGCOLOR");
IupSetAttribute(image_open, "1", "192 192 192");
IupSetAttribute(image_close, "0", "BGCOLOR");
IupSetAttribute(image_close, "1", "192 192 192");
IupSetAttribute(image_high, "1", "192 192 192");
// IupSetAttribute(gexp1, "BARSIZE", "50");
// IupSetAttributeHandle(gexp1, "IMAGE", image_close);
// IupSetAttributeHandle(gexp1, "IMOPEN", image_open);
// IupSetAttribute(gexp1, "IMAGE", "img1");
IupSetCallback(gexp1, "ACTION", (Icallback)expand_cb);
IupSetAttribute(gexp1, "EXTRABUTTONS", "3");
IupSetCallback(gexp1, "EXTRABUTTON_CB", (Icallback)extrabutton_cb);
IupSetAttributeHandle(gexp1, "IMAGEEXTRA1", image_close);
IupSetAttributeHandle(gexp1, "IMAGEEXTRAPRESS1", image_open);
IupSetAttributeHandle(gexp1, "IMAGEEXTRAHIGHLIGHT1", image_high);
IupSetAttributeHandle(gexp1, "IMAGEEXTRA2", image_close);
IupSetAttributeHandle(gexp1, "IMAGEEXTRAPRESS2", image_open);
IupSetAttributeHandle(gexp1, "IMAGEEXTRAHIGHLIGHT2", image_high);
IupSetAttributeHandle(gexp1, "IMAGEEXTRA3", image_close);
IupSetAttributeHandle(gexp1, "IMAGEEXTRAPRESS3", image_open);
IupSetAttributeHandle(gexp1, "IMAGEEXTRAHIGHLIGHT3", image_high);
//IupSetAttribute(gexp1, "REDRAWALL", "No");
IupSetCallback(canvas, "ACTION", action);
IupSetCallback(canvas, "BUTTON_CB", (Icallback)button_cb);
IupSetCallback(canvas, "MOTION_CB", (Icallback)motion_cb);
IupSetAttribute(canvas, "BUFFER", "DOUBLE");
IupSetAttribute(canvas, "MARGIN", "10x10");
box = IupVbox(canvas, NULL);
IupSetAttribute(box, "MARGIN", "25x25");
dlg = IupDialog(box);
IupSetAttribute(dlg, "TITLE", "IupGLCanvas Test");
IupSetAttribute(dlg, "RASTERSIZE", "800x600");
IupMap(dlg);
IupGLMakeCurrent(canvas);
printf("Vendor: %s\n", glGetString(GL_VENDOR));
printf("Renderer: %s\n", glGetString(GL_RENDERER));
printf("Version: %s\n", glGetString(GL_VERSION));
IupShowXY(dlg, IUP_CENTER, IUP_CENTER);
IupSetAttribute(dlg, "RASTERSIZE", NULL);
}
#ifndef BIG_TEST
int main(int argc, char* argv[])
{
IupOpen(&argc, &argv);
GLCanvasCubeTest();
IupMainLoop();
IupClose();
return EXIT_SUCCESS;
}
#endif
#endif
|
the_stack_data/242330979.c | /* Example code for Exercises in C.
Copyright 2016 Allen B. Downey
License: MIT License https://opensource.org/licenses/MIT
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>
#include <wait.h>
// errno is an external global variable that contains
// error information
extern int errno;
const char *A_STRING = "Hello there!";
// get_seconds returns the number of seconds since the
// beginning of the day, with microsecond precision
double get_seconds() {
struct timeval tv[1];
gettimeofday(tv, NULL);
return tv->tv_sec + tv->tv_usec / 1e6;
}
void child_code(int i)
{
double secs = get_seconds();
char *mallocedC = (char *) malloc(sizeof(char));
sleep(i);
printf("Hello from child %d.\n", i);
printf("Child %d has secs addr (stack) of %p\n", i, &secs);
printf("Child %d has mallocedC addr (heap) of %p\n", i, mallocedC);
printf("Child %d has A_STRING (const) addr of %p\n", i, &A_STRING);
/*
Output:
Creating child 0.
Creating child 1.
Hello from the parent.
Hello from child 0.
Child 0 has secs addr (stack) of 0x7ffe6a13d198
Child 0 has mallocedC addr (heap) of 0x55e64b537670
Child 0 has A_STRING (const) addr of 0x55e64a2b0010
Child 30873 exited with error code 0.
Hello from child 1.
Child 1 has secs addr (stack) of 0x7ffe6a13d198
Child 1 has mallocedC addr (heap) of 0x55e64b537670
Child 1 has A_STRING (const) addr of 0x55e64a2b0010
Child 30874 exited with error code 1.
Elapsed time = 1.002449 seconds.
Since the virtual addresses are the same but each process must not have
access to the other processes' data, then the processes must have different
memory segments.
I can't think of a way to check whether or not they share the same code and
static segments. They should share the code segment, per the last comment
on https://www.geeksforgeeks.org/fork-memory-shared-bw-processes-created-using/,
and (also per that comment) it seems that static should be shared until
one of them changes their copy.
*/
}
// main takes two parameters: argc is the number of command-line
// arguments; argv is an array of strings containing the command
// line arguments
int main(int argc, char *argv[])
{
int status;
pid_t pid;
double start, stop;
int i, num_children;
// the first command-line argument is the name of the executable.
// if there is a second, it is the number of children to create.
if (argc == 2) {
num_children = atoi(argv[1]);
} else {
num_children = 1;
}
// get the start time
start = get_seconds();
for (i=0; i<num_children; i++) {
// create a child process
printf("Creating child %d.\n", i);
pid = fork();
/* check for an error */
if (pid == -1) {
fprintf(stderr, "fork failed: %s\n", strerror(errno));
perror(argv[0]);
exit(1);
}
/* see if we're the parent or the child */
if (pid == 0) {
child_code(i);
exit(i);
}
}
/* parent continues */
printf("Hello from the parent.\n");
for (i=0; i<num_children; i++) {
pid = wait(&status);
if (pid == -1) {
fprintf(stderr, "wait failed: %s\n", strerror(errno));
perror(argv[0]);
exit(1);
}
// check the exit status of the child
status = WEXITSTATUS(status);
printf("Child %d exited with error code %d.\n", pid, status);
}
// compute the elapsed time
stop = get_seconds();
printf("Elapsed time = %f seconds.\n", stop - start);
exit(0);
}
|
the_stack_data/171665.c | int my_array[100];
int main()
{
int *p=my_array;
char *q;
int diff;
q=(char *)p;
q+=30*sizeof(int);
p=(int *)q;
*p=1;
assert(my_array[30]==1);
}
|
the_stack_data/3262085.c | int SUBST_chroot = 1;
int porting_dbg(const char *fmt,...);
int chroot(const char *path)
{
porting_dbg("chroot(%s) not supported",path);
return -1;
}
|
the_stack_data/6595.c | #include <stdio.h>
int main(int argc, char** argv)
{
for (int i = 0; i < argc; i++) {
int rc = puts(argv[i]);
if (rc == EOF) {
perror("Failed to put string.");
}
}
return 0;
}
|
the_stack_data/154828300.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_isascii.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: awindham <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/28 13:50:41 by awindham #+# #+# */
/* Updated: 2018/11/29 22:00:32 by awindham ### ########.fr */
/* */
/* ************************************************************************** */
int ft_isascii(int c)
{
return ((c >= 0x0 && c <= 0x7F));
}
|
the_stack_data/99692.c | #include <stdio.h>
#define TAM 5
typedef struct PILHA {
int elem[TAM];
int topo;
} PILHA;
void inicializar(PILHA *pilha) {
pilha->topo = -1;
}
int pilhaVazia(PILHA *pilha) {
if (pilha->topo == -1)
return 1;
return 0;
}
int pilhaCheia(PILHA *pilha) {
if (pilha->topo == TAM - 1)
return 1;
return 0;
}
int push(PILHA *pilha, int elemento) {
if (pilhaCheia(pilha)) {
printf("\nERRO! Pilha Cheia.");
return 0;
}
pilha->elem[pilha->topo+1] = elemento;
pilha->topo++;
return 1;
}
int pop(PILHA *pilha) {
int removido = -1;
if (pilhaVazia (pilha)) {
printf("Nao ha elemento para remover.");
return removido;
}
removido = pilha->elem[pilha->topo];
pilha->topo--;
return removido;
}
int topoEl(PILHA *pilha) {
int topo = -1;
if (pilhaVazia (pilha)) {
printf ("Nao ha elemento.");
return topo;
}
topo = pilha->elem[pilha->topo];
return topo;
}
int main() {
PILHA p;
inicializar (&p);
push(&p, 5);
printf("\n%d", topoEl(&p));
push(&p, 15);
printf("\n%d", topoEl(&p));
push(&p, 2);
printf("\n%d", topoEl(&p));
pop (&p);
printf("\n%d", topoEl(&p));
return 0;
}
|
the_stack_data/11996.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 short input[1] , unsigned short output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
int main(int argc , char *argv[] )
{
unsigned short input[1] ;
unsigned short output[1] ;
int randomFuns_i5 ;
unsigned short 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 short )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 46641) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
void RandomFunc(unsigned short input[1] , unsigned short output[1] )
{
unsigned short state[1] ;
char copy11 ;
{
state[0UL] = (input[0UL] & 914778474UL) << (unsigned short)7;
if ((state[0UL] >> (unsigned short)1) & (unsigned short)1) {
if ((state[0UL] >> (unsigned short)1) & (unsigned short)1) {
copy11 = *((char *)(& state[0UL]) + 1);
*((char *)(& state[0UL]) + 1) = *((char *)(& state[0UL]) + 0);
*((char *)(& state[0UL]) + 0) = copy11;
} else {
state[0UL] <<= (state[0UL] & (unsigned short)7) | 1UL;
}
}
output[0UL] = state[0UL] | 610055729UL;
}
}
void megaInit(void)
{
{
}
}
|
the_stack_data/62638061.c | #include <stdio.h>
#define STLEN 10
int main(void) {
char words[STLEN];
int i;
puts("Enter strings (empty line to quit):");
while (fgets(words, STLEN, stdin) != NULL && words[0] != '\n') {
i = 0;
while (words[i] != '\n' && words[i] != '\0') {
i++;
}
if (words[i] == '\n') words[i] = '\0';
else {
while (getchar() != '\n') {
continue;
}
}
puts(words);
}
puts("done");
return 0;
} |
the_stack_data/15762643.c | /*** includes ***/
#define _DEFAULT_SOURCE
#define _BSD_SOURCE
#define _GNU_SOURCE
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
//#include <time.h>
#include <sys/time.h>
/*** defines ***/
#define SCRIB_VERSION "0.1.0"
#define TAB_WIDTH 2
#define CTRL_KEY(k) ((k) & 0x1f)
enum editorKey {
BACKSPACE = 127,
ARROW_LEFT = 1000,
ARROW_RIGHT,
ARROW_UP,
ARROW_DOWN,
DEL_KEY,
HOME_KEY,
END_KEY,
PAGE_UP,
PAGE_DOWN
};
/*** data ***/
struct editorConfig {
int cx, cy;
int rowoff;
int coloff;
int screenrows;
int screencols;
int numrows;
int dirty;
int *rowNums;
char *filename;
char statusmsg[80];
time_t statusmsg_time;
struct termios orig_termios;
};
struct editorConfig E;
struct abuf {
char *b;
int len;
};
#define ABUF_INIT {NULL, 0}
char *original;
char *added;
int bufferIndex;
int bufferSize;
typedef struct piece {
int linecount;
int *lines;
int offset;
int start;
int end;
char *buffer;
int bufferType;
struct piece *next;
struct piece *prev;
} pieceNode;
pieceNode *head = NULL;
pieceNode *tail = NULL;
typedef struct stack {
pieceNode *frontptr;
pieceNode *backptr;
struct stack *next;
struct stack *prev;
} stackNode;
stackNode *undoHead = NULL;
stackNode *undoTail = NULL;
stackNode *redoHead = NULL;
stackNode *redoTail = NULL;
/******************************************************/
stackNode* getNewStackNode(pieceNode *front, pieceNode *backr);
stackNode* popStack(stackNode* stack);
int isStackEmpty(stackNode* stack);
void pushStack(stackNode* stack, pieceNode *front, pieceNode *back);
int countLines();
pieceNode *getNewPieceNode (char *text, int start, int end, int bufferType);
void splitNode(pieceNode *curr, int splitIndex);
void insertChar (int line, int pos);
void splitNodeDelete(pieceNode *curr, int splitIndex);
void deleteChar (int line, int pos);
void undo();
void redo();
void die(const char *s);
void disableRawMode();
void enableRawMode();
int editorReadKey();
int getCursorPosition(int *rows, int *cols);
int getWindowSize(int *rows, int *cols);
int is_separator(int c);
void editorOpen(char *filename);
void editorSave();
void abAppend(struct abuf *ab, const char *s, int len);
void abFree(struct abuf *ab);
void printlines(struct abuf *ab, int topLine, int botLine);
void editorScroll();
void editorDrawRows(struct abuf *ab);
void editorDrawStatusBar(struct abuf *ab);
void editorDrawMessageBar(struct abuf *ab);
void editorRefreshScreen();
void editorSetStatusMessage(const char *fmt, ...);
void editorMoveCursor(int key);
void editorProcessKeypress();
char *editorPrompt(char *prompt);
void initEditor();
int main(int argc, char *argv[]);
/******************************************************/
void debugNode(pieceNode* curr) {
printf ("[(%d) %d,%d,%d]\r\n", curr->bufferType, curr->start, curr->end, curr->linecount);
}
void debugList (int opt){
pieceNode *curr = head;
while (curr != NULL && opt == 0) {
debugNode(curr);
curr = curr->next;
}
while (curr != NULL && opt == 1) {
printf ("[ ");
for (int i = 0; i < curr->linecount; i++) {
printf ("%d ", *(curr->lines + i));
}
printf ("]");
curr = curr->next;
}
while (curr != NULL && opt == 2) {
//printf ("[ ");
printf("%.*s", curr->end - curr->start, curr->start + original);
printf ("/");
curr = curr->next;
}
printf ("\r\n");
}
void debugStack(stackNode *head) {
stackNode* curr = head;
while (curr != NULL) {
if (curr->frontptr != NULL) debugNode(curr->frontptr);
if (curr->backptr != NULL) debugNode(curr->backptr);
curr = curr->next;
}
printf("[]\r\n");
}
stackNode* getNewStackNode(pieceNode *front, pieceNode *back) {
stackNode *tmp = (stackNode *) malloc(sizeof(stackNode));
tmp->frontptr = front;
tmp->backptr = back;
tmp->next = NULL;
tmp->prev = NULL;
return tmp;
}
stackNode* popStack(stackNode* stack) {
if (isStackEmpty(stack) > 0) {
stackNode *element = stack->next;
stack->next = element->next;
stack->next->prev = stack;
element->next = NULL;
element->prev = NULL;
return element;
}
return NULL;
}
stackNode* peekStack(stackNode* stack) {
return (isStackEmpty(stack) > 0) ? stack->next : NULL;
}
int isStackEmpty(stackNode* stack) {
return (stack->next->frontptr != NULL) ? 1 : 0;
}
void pushStack(stackNode* stack, pieceNode *front, pieceNode *back) {
stackNode *element = getNewStackNode(front, back);
element->next = stack->next;
element->prev = stack;
stack->next->prev = element;
stack->next = element;
}
int countLines() {
pieceNode *curr = head;
int count = 0;
while (curr != tail) {
count += curr->linecount;
curr = curr->next;
}
return count;
}
pieceNode *getNewPieceNode (char *text, int start, int end, int bufferType){
int* a = (int *)calloc(1, sizeof(int));
int count = 0;
int offset = 0;
for (int i = start; i <= end; i++){
offset++;
if (text[i] == '\n') {
a[count++] = offset;
offset = 0;
a = (int *)realloc(a, (count + 1) * sizeof(int));
}
}
pieceNode *tmp = (pieceNode *) malloc (sizeof (pieceNode));
tmp->linecount = count;
tmp->lines = a;
tmp->start = start;
tmp->end = end;
tmp->buffer = text;
tmp->bufferType = bufferType;
//free(a);
return tmp;
}
void splitNode(pieceNode *curr, int splitIndex) {
pieceNode *front = curr->prev;
pieceNode *back = curr->next;
pieceNode *leftSplit = getNewPieceNode(curr->buffer, curr->start, curr->start + splitIndex - 1, curr->bufferType);
pieceNode *newNode = getNewPieceNode(added, bufferIndex, bufferIndex, 1);
pieceNode *rightSplit = getNewPieceNode(curr->buffer, curr->start + splitIndex, curr->end, curr->bufferType);
leftSplit->next = newNode;
leftSplit->prev = front;
newNode->next = rightSplit;
newNode->prev = leftSplit;
rightSplit->next = back;
rightSplit->prev = newNode;
front->next = leftSplit;
back->prev = rightSplit;
pushStack(undoHead, curr, curr);
}
void insertChar (int line, int pos){
pieceNode *curr = head->next;
int currLine = 1;
while (curr != tail && currLine < line) {
if (currLine + curr->linecount >= line) break;
currLine += curr->linecount;
curr = curr->next;
}
int offset = 0;
for (int i = 0; i < line - currLine; i++) {
offset += curr->lines[i];
}
if (currLine + curr->linecount == line) {
int posLeft = pos - (curr->end - curr->start + 1 - offset);
if (posLeft > 0) curr = curr->next;
int splitIndex = posLeft + curr->end - curr->start + 1;
while (curr != tail && 0 < posLeft) {
posLeft -= (curr->linecount == 0) ? curr->end - curr->start + 1 : curr->lines[0];
if (posLeft > 0) curr = curr->next;
splitIndex = (curr->linecount == 0) ? posLeft + curr->end - curr->start + 1 : curr->lines[0] + posLeft;
}
if (posLeft == 0 && curr->bufferType == 1) {
if (curr->buffer[bufferIndex] == '\n') {
//printf("err!\n");
int newLineSum = 0;
for (int i = 0; i < curr->linecount; i++) newLineSum += curr->lines[i];
curr->linecount++;
curr->end++;
curr->lines = (int *) realloc(curr->lines, (curr->linecount + 1) * sizeof(int));
curr->lines[curr->linecount - 1] = curr->end - curr->start + 1 - newLineSum;
} else {
curr->end++;
}
} else if (posLeft == 0) {
pieceNode *newNode = getNewPieceNode(added, bufferIndex, bufferIndex, 1);
newNode->next = curr->next;
newNode->prev = curr;
curr->next->prev = newNode;
curr->next = newNode;
pushStack(undoHead, newNode, newNode);
E.dirty++;
} else {
splitNode(curr, splitIndex);
E.dirty++;
}
} else if (offset == 0 && pos == 0) {
pieceNode *deepCopy = getNewPieceNode(curr->buffer, curr->start, curr->end, curr->bufferType);
deepCopy->next = curr->next;
deepCopy->prev = curr->prev;
pieceNode *newNode = getNewPieceNode(added, bufferIndex, bufferIndex, 1);
newNode->next = curr;
newNode->prev = curr->prev;
curr->prev->next = newNode;
curr->prev = newNode;
pushStack(undoHead, deepCopy, deepCopy);
E.dirty++;
} else {
offset += pos;
splitNode(curr, offset);
E.dirty++;
}
bufferIndex++;
}
void splitNodeDelete(pieceNode *curr, int splitIndex) {
//printf ("[(%d),%d,%d,%d]\n", curr->bufferType, curr->start, curr->end, curr->linecount);
pieceNode *front = curr->prev;
pieceNode *back = curr->next;
pieceNode *leftSplit = getNewPieceNode(curr->buffer, curr->start, curr->start + splitIndex - 2, curr->bufferType);
pieceNode *newNode = getNewPieceNode(curr->buffer, curr->start + (splitIndex - 1), curr->start + (splitIndex - 1), curr->bufferType);
pieceNode *rightSplit = getNewPieceNode(curr->buffer, curr->start + splitIndex, curr->end, curr->bufferType);
if (curr->buffer[curr->start + splitIndex - 1] == '\n') {
if (E.cy > 0) E.cy--;
E.numrows--;
E.cx = E.rowNums[E.cy - E.rowoff] > 1 ? E.rowNums[E.cy - E.rowoff] : 0;
}
leftSplit->next = rightSplit;
leftSplit->prev = front;
rightSplit->next = back;
rightSplit->prev = leftSplit;
front->next = leftSplit;
back->prev = rightSplit;
newNode->next = rightSplit;
newNode->prev = leftSplit;
pushStack(undoHead, newNode, newNode);
}
void deleteChar (int line, int pos){
if (line == 1 && pos == 0) return;
pieceNode *curr = head->next;
int currLine = 1;
while (curr != tail && currLine < line) {
if (currLine + curr->linecount >= line) break;
currLine += curr->linecount;
curr = curr->next;
}
int offset = 0;
for (int i = 0; i < line - currLine; i++) {
offset += curr->lines[i];
}
if (currLine + curr->linecount == line) { // edge case!
int posLeft = pos - (curr->end - curr->start + 1 - offset);
if (posLeft > 0) curr = curr->next;
int splitIndex = posLeft + curr->end - curr->start + 1;
while (curr != tail && 0 < posLeft) {
posLeft -= (curr->linecount == 0) ? curr->end - curr->start + 1 : curr->lines[0];
if (posLeft > 0) curr = curr->next;
splitIndex = (curr->linecount == 0) ? posLeft + curr->end - curr->start + 1 : curr->lines[0] + posLeft;
}
if (posLeft == 0) { // we've reached the end of the node
if (curr->end - curr->start == 0) {
if (curr->buffer[curr->end] == '\n') {
if (E.cy > 0) E.cy--;
E.numrows--;
E.cx = E.rowNums[E.cy - E.rowoff] > 1 ? E.rowNums[E.cy - E.rowoff] : 0;
}
curr->prev->next = curr->next;
curr->next->prev = curr->prev;
pushStack(undoHead, curr, curr);
E.dirty++;
} else if (curr->buffer[curr->end] == '\n') {
if (E.cy > 0) E.cy--;
E.numrows--;
E.cx = E.rowNums[E.cy - E.rowoff] > 1 ? E.rowNums[E.cy - E.rowoff] : 0;
curr->lines = (int *) realloc(curr->lines, (curr->linecount - 1) * sizeof(int));
curr->linecount--;
curr->end--;
pieceNode *newNode = getNewPieceNode(curr->buffer, curr->end + 1, curr->end + 1, curr->bufferType);
newNode->next = isStackEmpty(undoHead) > 0 ? peekStack(undoHead)->frontptr : curr->next;
newNode->prev = curr;
pushStack(undoHead, newNode, newNode);
E.dirty++;
} else {
curr->end--;
stackNode *node = peekStack(undoHead);
if (node != NULL) {
pieceNode *topNode = node->frontptr;
if (topNode->start == curr->end + 2) {
topNode->start--;
} else {
pieceNode *newNode = getNewPieceNode(curr->buffer, curr->end + 1, curr->end + 1, curr->bufferType);
newNode->next = topNode;
newNode->prev = curr;
pushStack(undoHead, newNode, newNode);
E.dirty++;
}
}
}
} else { //
splitNodeDelete(curr, splitIndex);
E.dirty++;
}
} else if (offset == 0 && pos == 0) { // delete from previous node
curr = curr->prev;
if (curr->end - curr->start == 0) {
if (curr->buffer[curr->end] == '\n') {
E.numrows--;
if (E.cy > 0) E.cy--;
E.cx = E.rowNums[E.cy - E.rowoff] > 1 ? E.rowNums[E.cy - E.rowoff] : 0;
}
curr->prev->next = curr->next;
curr->next->prev = curr->prev;
pushStack(undoHead, curr, curr);
} else if (curr->buffer[curr->end] == '\n') {
if (E.cy > 0) E.cy--;
E.numrows--;
E.cx = E.rowNums[E.cy - E.rowoff] > 1 ? E.rowNums[E.cy - E.rowoff] : 0;
curr->lines = (int *) realloc(curr->lines, (curr->linecount - 1) * sizeof(int));
curr->linecount--;
curr->end--;
pieceNode *newNode = getNewPieceNode(curr->buffer, curr->end + 1, curr->end + 1, curr->bufferType);
newNode->next = isStackEmpty(undoHead) > 0 ? peekStack(undoHead)->frontptr : curr->next;
newNode->prev = curr;
pushStack(undoHead, newNode, newNode);
E.dirty++;
} else {
curr->end--;
stackNode *node = peekStack(undoHead);
if (node != NULL) {
pieceNode *topNode = node->frontptr;
if (topNode->start == curr->end + 2) {
topNode->start--;
} else {
pieceNode *newNode = getNewPieceNode(curr->buffer, curr->end + 1, curr->end + 1, curr->bufferType);
newNode->next = topNode;
newNode->prev = curr;
pushStack(undoHead, newNode, newNode);
E.dirty++;
}
}
}
} else if (offset == 0 && pos == 1) { // add new node to front of the currentNode
if (curr->buffer[curr->start + pos] == '\n') {
if (E.cy > 0) E.cy--;
E.numrows--;
E.cx = E.rowNums[E.cy - E.rowoff] > 1 ? E.rowNums[E.cy - E.rowoff] : 0;
curr->lines = (int *) realloc(curr->lines, (curr->linecount - 1) * sizeof(int));
curr->linecount--;
curr->start++;
} else {
curr->start++;
}
pieceNode *newNode = getNewPieceNode(curr->buffer, curr->start--, curr->start--, curr->bufferType);
newNode->next = curr;
newNode->prev = curr->prev;
pushStack(undoHead, newNode, newNode);
E.dirty++;
} else { // split middle of the node
offset += pos;
splitNodeDelete(curr, offset);
E.dirty++;
}
}
void undo() {
stackNode *node = popStack(undoHead);
if (node != NULL) {
pieceNode *frontNode = node->frontptr->prev->next;
pieceNode *backNode = node->backptr->next->prev;
pushStack(redoHead, frontNode, backNode);
node->frontptr->prev->next = node->frontptr;
node->backptr->next->prev = node->backptr;
E.dirty--;
}
E.numrows = countLines();
}
void redo() {
stackNode *node = popStack(redoHead);
if (node != NULL) {
pieceNode *frontNode = node->frontptr->prev->next;
pieceNode *backNode = node->backptr->next->prev;
pushStack(undoHead, frontNode, backNode);
node->frontptr->prev->next = node->frontptr;
node->backptr->next->prev = node->backptr;
E.dirty++;
}
E.numrows = countLines();
}
/*** terminal ***/
void die(const char *s) {
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[H", 3);
perror(s);
exit(1);
}
void disableRawMode() {
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &E.orig_termios) == -1)
die("tcsetattr");
}
void enableRawMode() {
if (tcgetattr(STDIN_FILENO, &E.orig_termios) == -1) die("tcgetattr");
atexit(disableRawMode);
struct termios raw = E.orig_termios;
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
raw.c_oflag &= ~(OPOST);
raw.c_cflag |= (CS8);
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 1;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) die("tcsetattr");
}
int editorReadKey() {
int nread;
char c;
while ((nread = read(STDIN_FILENO, &c, 1)) != 1) {
if (nread == -1 && errno != EAGAIN) die("read");
}
if (c == '\x1b') {
char seq[3];
if (read(STDIN_FILENO, &seq[0], 1) != 1) return '\x1b';
if (read(STDIN_FILENO, &seq[1], 1) != 1) return '\x1b';
// printf("%c", seq[0]);
// printf("%c", seq[1]);
if (seq[0] == '[') {
if (seq[1] >= '0' && seq[1] <= '9') {
if (read(STDIN_FILENO, &seq[2], 1) != 1) return '\x1b';
if (seq[2] == '~') {
switch (seq[1]) {
case '1': return HOME_KEY;
case '3': return DEL_KEY;
case '4': return END_KEY;
case '5': return PAGE_UP;
case '6': return PAGE_DOWN;
case '7': return HOME_KEY;
case '8': return END_KEY;
}
}
} else {
switch (seq[1]) {
case 'A': return ARROW_UP;
case 'B': return ARROW_DOWN;
case 'C': return ARROW_RIGHT;
case 'D': return ARROW_LEFT;
case 'H': return HOME_KEY;
case 'F': return END_KEY;
}
}
} else if (seq[0] == 'O') {
switch (seq[1]) {
case 'H': return HOME_KEY;
case 'F': return END_KEY;
}
} else if (seq[0] == 'b' || seq[0] == 98) {
return PAGE_UP;
} else if (seq[0] == 'f' || seq[0] == 102) {
return PAGE_DOWN;
}
return '\x1b';
} else {
return c;
}
}
int getCursorPosition(int *rows, int *cols) {
char buf[32];
unsigned int i = 0;
if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) return -1;
while (i < sizeof(buf) - 1) {
if (read(STDIN_FILENO, &buf[i], 1) != 1) break;
if (buf[i] == 'R') break;
i++;
}
buf[i] = '\0';
if (buf[0] != '\x1b' || buf[1] != '[') return -1;
if (sscanf(&buf[2], "%d;%d", rows, cols) != 2) return -1;
return 0;
}
int getWindowSize(int *rows, int *cols) {
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12) return -1;
return getCursorPosition(rows, cols);
} else {
*cols = ws.ws_col;
*rows = ws.ws_row;
return 0;
}
}
int is_separator(int c) {
return isspace(c) || c == '\0' || strchr(",.()+-/*=~%<>[];", c) != NULL;
}
/*** file i/o ***/
void editorOpen(char *filename) {
free(E.filename);
E.filename = strdup(filename);
FILE *f = fopen (filename, "rb");
fseek (f, 0, SEEK_END);
long fsize = ftell (f);
fseek (f, 0, SEEK_SET); /* same as rewind(f); */
original = malloc (fsize + 1);
fread (original, 1, fsize, f);
head = getNewPieceNode ("", -1, -1, 0);
tail = getNewPieceNode ("", -1, -1, 0);
head->next = tail;
tail->prev = head;
pieceNode *curr = head;
pieceNode *newNode = getNewPieceNode (original, 0, fsize - 1, 0);
newNode->next = curr->next;
newNode->prev = curr;
curr->next->prev = newNode; //newNode will be the previous node of temp->next node
curr->next = newNode;
E.numrows = curr->next->linecount;
fclose(f);
E.dirty = 0;
}
void editorSave() {
if (E.filename == NULL) {
E.filename = editorPrompt("Save as: %s (ESC to cancel)");
if (E.filename == NULL) {
editorSetStatusMessage("Save attempt failed");
return;
}
}
FILE *fp = fopen(E.filename, "w+");
if (fp != NULL) {
int fileByteSize = 0;
pieceNode *curr = head;
while (curr != tail) {
fprintf(fp, "%.*s", curr->end - curr->start + 1, curr->start + curr->buffer);
if (curr != head) fileByteSize += curr->end - curr->start + 1;
curr = curr->next;
}
editorSetStatusMessage("%d bytes written to disk", fileByteSize);
E.dirty = 0;
return;
}
fclose(fp);
editorSetStatusMessage("Unable to save file! I/O error: %s", strerror(errno));
}
/*** append buffer ***/
void abAppend(struct abuf *ab, const char *s, int len) {
char *new = realloc(ab->b, ab->len + len);
//printf ("[%c, %d]", s[0], len);
if (new == NULL) return;
memcpy(&new[ab->len], s, len);
ab->b = new;
ab->len += len;
}
void abFree(struct abuf *ab) {
free(ab->b);
}
void printlines(struct abuf *ab, int topLine, int botLine) {
pieceNode *curr = head->next;
int currLine = 1;
while (curr != tail && currLine < topLine) {
if (currLine + curr->linecount >= topLine) break;
currLine += curr->linecount;
curr = curr->next;
}
int *rowLimits = (int *)calloc(botLine - topLine + 1, sizeof(int));
int rowIndex = 0;
int lineSum = 0;
while (curr != tail && currLine <= botLine) {
int topRange = 0;
int f = topLine - currLine > 0 ? topLine - currLine : 0;
for (int i = 0; i < f; i++) topRange += curr->lines[i];
for (int i = topRange + curr->start; i <= curr->end; i++) {
if (lineSum == botLine - topLine + 1) break;
char *buf = curr->bufferType == 0 ? original : added;
rowIndex++;
//if (rowIndex < E.screencols + E.screencols) {
if (buf[i] == '\n') {
abAppend(ab, "\r\n", 2);
rowLimits[lineSum] = rowIndex;
lineSum++;
rowIndex = 0;
} else {
if (rowIndex > E.coloff && rowIndex <= E.coloff + E.screencols) {
if (isdigit(buf[i])) {
abAppend(ab, "\x1b[31m", 5);
abAppend(ab, &buf[i], 1);
abAppend(ab, "\x1b[39m", 5);
} else {
abAppend(ab, &buf[i], 1);
}
}
}
}
currLine += curr->linecount;
curr = curr->next;
}
//for(int i = 0; i < botLine - topLine + 1; i++) printf("%d ", rowLimits[i]);
E.rowNums = rowLimits;
}
/*** output ***/
void editorScroll() {
if (E.cy < E.rowoff) {
E.rowoff = E.cy;
}
if (E.cy >= E.rowoff + E.screenrows) {
E.rowoff = E.cy - E.screenrows + 1;
}
if (E.cx < E.coloff) {
E.coloff = E.cx;
}
if (E.cx >= E.coloff + E.screencols) {
E.coloff = E.cx - E.screencols + 1;
}
}
void editorDrawRows(struct abuf *ab) {
if (E.filename == NULL && E.dirty == 0) {
int y;
for (y = 0; y < E.screenrows; y++) {
int filerow = y + E.rowoff;
if (filerow >= E.numrows) {
if (y == E.screenrows / 3) {
char welcome[80];
int welcomelen = snprintf(welcome, sizeof(welcome),
"Scrib Editor -- Version %s", SCRIB_VERSION);
if (welcomelen > E.screencols) welcomelen = E.screencols;
int padding = (E.screencols - welcomelen) / 2;
if (padding) {
abAppend(ab, "~", 1);
padding--;
}
while (padding--) abAppend(ab, " ", 1);
abAppend(ab, welcome, welcomelen);
} else {
abAppend(ab, "~", 1);
}
}
abAppend(ab, "\r\n", 2);
}
} else {
int last = E.rowoff + E.screenrows > E.numrows? E.numrows : E.rowoff + E.screenrows;
printlines(ab, E.rowoff + 1, last);
int i;
for (i = last; i < E.screenrows; i++) {
abAppend(ab, "~\r\n", 3);
}
}
}
void editorDrawStatusBar(struct abuf *ab) {
abAppend(ab, "\x1b[7m", 4);
char status[80], rstatus[80];
int len = snprintf(status, sizeof(status), "%.20s - %d lines %s",
E.filename ? E.filename : "[No Name]", E.numrows, E.dirty ? "(modified)" : "");
int rightLen = snprintf(rstatus, sizeof(rstatus), "[%d, %d]", E.cy + 1, E.cx);
if (len > E.screencols) len = E.screencols;
abAppend(ab, status, len);
while (len < E.screencols) {
if (E.screencols - len == rightLen) {
abAppend(ab, rstatus, rightLen);
break;
} else {
abAppend(ab, " ", 1);
len++;
}
}
abAppend(ab, "\x1b[m", 3);
abAppend(ab, "\r\n", 2);
}
void editorDrawMessageBar(struct abuf *ab) {
abAppend(ab, "\x1b[K", 3);
int msglen = strlen(E.statusmsg);
if (msglen > E.screencols) msglen = E.screencols;
if (msglen && time(NULL) - E.statusmsg_time < 5)
abAppend(ab, E.statusmsg, msglen);
}
void editorRefreshScreen() {
//printf("derp[%d]\r\n", bufferIndex);
//printf("._.");
if (getWindowSize(&E.screenrows, &E.screencols) == -1) die("getWindowSize");
E.screenrows -= 2;
E.rowNums = (int *)realloc(E.rowNums, (E.screenrows + 1) * sizeof(int));
//printf("._.");
editorScroll();
struct abuf ab = ABUF_INIT;
abAppend(&ab, "\x1b[?25l", 6);
abAppend(&ab, "\x1b[2J", 4);
abAppend(&ab, "\x1b[H", 3);
//printf("._.");
editorDrawRows(&ab);
//printf("._.");
editorDrawStatusBar(&ab);
//printf("._.");
editorDrawMessageBar(&ab);
//printf("derp[%d]\r\n", bufferIndex);
char buf[32];
snprintf(buf, sizeof(buf), "\x1b[%d;%dH", (E.cy - E.rowoff) + 1, (E.cx - E.coloff) + 1);
abAppend(&ab, buf, strlen(buf));
abAppend(&ab, "\x1b[?25h", 6);
write(STDOUT_FILENO, ab.b, ab.len);
abFree(&ab);
}
void editorSetStatusMessage(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vsnprintf(E.statusmsg, sizeof(E.statusmsg), fmt, ap);
va_end(ap);
E.statusmsg_time = time(NULL);
}
/*** input ***/
void editorMoveCursor(int key) {
switch (key) {
case ARROW_LEFT:
if (E.cx != 0) { //limit left scroll
E.cx--;
} else if (E.cy > 0) { //moving left at start of a line
E.cy--;
E.cx = E.rowNums[E.cy - E.rowoff] > 1 ? E.rowNums[E.cy - E.rowoff] - 1 : 0;
}
break;
case ARROW_RIGHT:
if (E.cy < E.numrows && E.rowNums[E.cy - E.rowoff] - 1 > E.cx) { //limit right scroll
E.cx++;
} else if (E.cy + 1 < E.numrows){
E.cy++;
E.cx = 0;
}
break;
case ARROW_UP:
if (E.cy > 0) {
E.cy--;
}
break;
case ARROW_DOWN:
if (E.cy + 1 < E.numrows) {
E.cy++;
}
break;
}
// snap cursor to end of line
if (E.cy < E.numrows && E.rowNums[E.cy - E.rowoff] - 1 < E.cx) {
E.cx = E.rowNums[E.cy - E.rowoff] > 1 ? E.rowNums[E.cy - E.rowoff] - 1 : 0;
}
}
void editorProcessKeypress() {
int c = editorReadKey();
switch (c) {
case CTRL_KEY('q'):
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[H", 3);
exit(0);
break;
case CTRL_KEY('s'):
editorSave();
break;
case CTRL_KEY('u'):
undo();
if (E.cy > E.numrows - 1) {
E.cy = E.numrows - 1;
}
E.cx = 0;
break;
case CTRL_KEY('r'):
redo();
if (E.cy > E.numrows - 1) {
E.cy = E.numrows - 1;
E.cx = 0;
}
break;
case 27:
break;
case HOME_KEY:
E.cx = 0;
break;
case END_KEY:
E.cx = E.screencols - 1;
break;
case BACKSPACE:
//printf("blep");
deleteChar(E.cy + 1, E.cx);
if (E.cx > 0) E.cx--;
break;
case PAGE_UP:
case PAGE_DOWN:
//printf("derp");
{
if (c == PAGE_UP) {
E.cy = E.rowoff;
} else if (c == PAGE_DOWN) {
E.cy = E.rowoff + E.screenrows - 1;
if (E.cy > E.numrows) E.cy = E.numrows;
}
int times = E.screenrows;
while (times--) editorMoveCursor(c == PAGE_UP ? ARROW_UP : ARROW_DOWN);
}
break;
case ARROW_UP:
case ARROW_DOWN:
case ARROW_LEFT:
case ARROW_RIGHT:
editorMoveCursor(c);
break;
default:
c = (c == 13) ? '\n' : c;
if (bufferIndex >= bufferSize - 1) {
bufferSize *= 2;
added = (char *)realloc(added, bufferSize * sizeof(char));
}
added[bufferIndex] = c;
insertChar(E.cy + 1, E.cx);
if (c == '\n') {
E.cx = 0;
E.cy++;
E.numrows++;
} else {
E.cx++;
}
break;
}
}
/*** init ***/
char *editorPrompt(char *prompt) {
size_t bufsize = 512;
char *buf = malloc(bufsize);
size_t buflen = 0;
buf[0] = '\0';
while (1) {
editorSetStatusMessage(prompt, buf);
editorRefreshScreen();
int c = editorReadKey();
if (c == DEL_KEY || c == CTRL_KEY('h') || c == BACKSPACE) {
if (buflen != 0) buf[--buflen] = '\0';
} else if (c == 27) {
editorSetStatusMessage("");
free(buf);
return NULL;
} else if (c == '\r') {
if (buflen != 0) {
editorSetStatusMessage("");
return buf;
}
} else if (!iscntrl(c) && c < 128) {
if (buflen == bufsize - 1) {
bufsize *= 2;
buf = realloc(buf, bufsize);
}
buf[buflen++] = c;
buf[buflen] = '\0';
}
}
}
void initEditor() {
E.cx = 0;
E.cy = 0;
E.rowoff = 0;
E.coloff = 0;
E.numrows = 0;
E.filename = NULL;
E.statusmsg[0] = '\0';
E.statusmsg_time = 0;
E.dirty = 0;
bufferIndex = 0;
bufferSize = 1000;
added = (char*) malloc(bufferSize * sizeof (char));
if (getWindowSize(&E.screenrows, &E.screencols) == -1) die("getWindowSize");
E.screenrows -= 2;
E.rowNums = (int *)calloc(E.screenrows + 1, sizeof(int));
}
int main(int argc, char *argv[]) {
//printf ("[done]");
enableRawMode();
initEditor();
undoHead = getNewStackNode(NULL, NULL);
undoTail = getNewStackNode(NULL, NULL);
undoHead->next = undoTail;
undoTail->prev = undoHead;
redoHead = getNewStackNode(NULL, NULL);
redoTail = getNewStackNode(NULL, NULL);
redoHead->next = redoTail;
redoTail->prev = redoHead;
if (argc >= 2) {
editorOpen(argv[1]);
} else {
original = "\n";
head = getNewPieceNode ("", -1, -1, 0);
tail = getNewPieceNode ("", -1, -1, 0);
head->next = tail;
tail->prev = head;
pieceNode *curr = head;
pieceNode *newNode = getNewPieceNode (original, 0, 0, 0);
newNode->next = curr->next;
newNode->prev = curr;
curr->next->prev = newNode; //newNode will be the previous node of temp->next node
curr->next = newNode;
E.numrows = curr->next->linecount;
}
editorSetStatusMessage("HELP: Ctrl-S = save | Ctrl-Q = quit");
while (1) {
editorRefreshScreen();
editorProcessKeypress();
}
return 0;
}
|
the_stack_data/179829722.c | /*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char**argv ) {
int i, iterations;
if ( argc != 2 ) {
fprintf( stderr, "Usage: HelloWorld <iterations>\n" );
exit(1);
}
iterations = atoi( argv[1] );
for ( i = 0; i < iterations; i++ ) {
fprintf( stdout, "%d: hello world out\n", i );
fprintf( stderr, "%d: hello world err\n", i );
fflush( stdout ); fflush( stderr );
}
exit(0);
}
|
the_stack_data/142490.c |
void v_result( const double *A, const double *B, double *C )
/**********************************************************/
/* Vektorbetrag: C = Vektor(B)-Vektor(A) == Vector(AB)*/
/**********************************************************/
{
C[0]=B[0]-A[0];
C[1]=B[1]-A[1];
C[2]=B[2]-A[2];
}
|
the_stack_data/325184.c | #include <stdio.h>
int main(){
int n;
puts("Introduce un numero ENTERO POSITIVO");
scanf("%d",&n);
if(n > 0) puts ("EL NUMERO ES POSITIVO");
else puts("EL NUMERO ES NEGATIVO");
return 0;
} |
the_stack_data/1252220.c | #include <sys/utsname.h>
#include <unistd.h>
int gethostname(char* name, size_t len) {
size_t i;
struct utsname uts;
if (uname(&uts))
return -1;
if (len > sizeof uts.nodename)
len = sizeof uts.nodename;
for (i = 0; i < len && (name[i] = uts.nodename[i]); i++)
;
if (i == len)
name[i - 1] = 0;
return 0;
}
|
the_stack_data/185690.c | #include <math.h>
static double sign(double a, double b) {
return b >= 0 ? fabs(a) : -fabs(a);
}
/**
* @brief Clausen function \f$\mathrm{Cl}_2(x)\f$
* @param x real argument
* @return \f$\mathrm{Cl}_2(x)\f$
* @author K.S. Kölbig
* @note Implementation translated by Alexander Voigt from CERNLIB DCLAUS function C326
*
* Journal of Computational and Applied Mathematics 64 (1995) 295-297.
*
* Implemented as a truncated series expansion in terms of Chebyshev
* polynomials, see [Yudell L. Luke: Mathematical functions and their
* approximations, Academic Press Inc., New York 1975, p.67].
*/
double clausen_2_koelbig(double X)
{
const double R1 = 1, HF = R1/2;
const double PI = 3.14159265358979324;
const double PI2 = 2*PI, PIH = PI/2, RPIH = 2/PI;
const double A[9] = {
0.0279528319735756613,
0.0001763088743898116,
0.0000012662741461157,
0.0000000117171818134,
0.0000000001230064129,
0.0000000000013952729,
0.0000000000000166908,
0.0000000000000002076,
0.0000000000000000027
};
const double B[14] = {
0.639097088857265341,
-0.054980569301851716,
-0.000961261945950606,
-0.000032054686822550,
-0.000001329461695426,
-0.000000062093601824,
-0.000000003129600656,
-0.000000000166351954,
-0.000000000009196527,
-0.000000000000524004,
-0.000000000000030580,
-0.000000000000001820,
-0.000000000000000110,
-0.000000000000000007,
};
double ALFA, B0, B1, B2, H, U, S, V;
V = fmod(fabs(X), PI2);
S = sign(R1, X);
if (V > PI) {
V = PI2 - V;
S = -S;
}
if (V == 0 || V == PI) {
H = 0;
} else if (V < PIH) {
U = RPIH*V;
H = 2*U*U - 1;
ALFA = H + H;
B1 = 0;
B2 = 0;
for (int i = 8; i >= 0; i--) {
B0 = A[i] + ALFA*B1 - B2;
B2 = B1;
B1 = B0;
}
H = V*(1 - log(V) + HF*V*V*(B0 - H*B2));
} else {
U = RPIH*V - 2;
H = 2*U*U - 1;
ALFA = H + H;
B1 = 0;
B2 = 0;
for (int i = 13; i >= 0; i--) {
B0 = B[i] + ALFA*B1 - B2;
B2 = B1;
B1 = B0;
}
H = (PI - V)*(B0 - H*B2);
}
return S*H;
}
/**
* @brief Clausen function \f$\mathrm{Cl}_2(\theta) = \mathrm{Im}(\mathrm{Li}_2(e^{i\theta}))\f$ with long double precision
* @param x real angle
* @return \f$\mathrm{Cl}_2(\theta)\f$
* @author K.S. Kölbig
* @note Implementation translated from CERNLIB DCLAUS function C326
* and extended to long double precision by Alexander Voigt.
*
* Journal of Computational and Applied Mathematics 64 (1995) 295-297.
*/
long double clausen_2l_koelbig(long double x)
{
const long double PI = 3.14159265358979323846264338327950288L;
const long double PI2 = 2*PI, PIH = PI/2, RPIH = 2/PI;
const long double A[19] = {
0.0279528319735756613494585924765551791L,
0.0001763088743898115653057636473920103L,
0.0000012662741461156530021975187159184L,
0.0000000117171818134392379295428166866L,
0.0000000001230064128833746922855709386L,
0.0000000000013952728970012911958374309L,
0.0000000000000166907761628567345146740L,
0.0000000000000002076091315145432983502L,
0.0000000000000000026609198306058056092L,
0.0000000000000000000349249563561378275L,
0.0000000000000000000004673313082962865L,
0.0000000000000000000000063542322337428L,
0.0000000000000000000000000875698871820L,
0.0000000000000000000000000012208003299L,
0.0000000000000000000000000000171890569L,
0.0000000000000000000000000000002441331L,
0.0000000000000000000000000000000034940L,
0.0000000000000000000000000000000000503L,
0.0000000000000000000000000000000000007L
};
const double B[30] = {
0.6390970888572653413071869135953864197L,
-0.0549805693018517156397035696498958507L,
-0.0009612619459506064293859076874070709L,
-0.0000320546868225504765586825318112711L,
-0.0000013294616954255450141343828695514L,
-0.0000000620936018243975194590942773212L,
-0.0000000031296006563911126723262365339L,
-0.0000000001663519538192669775933926077L,
-0.0000000000091965272507194254496027281L,
-0.0000000000005240037738758450093649037L,
-0.0000000000000305803841873659454134183L,
-0.0000000000000018196918249487950988000L,
-0.0000000000000001100398263196261522324L,
-0.0000000000000000067451775715424687730L,
-0.0000000000000000004182784651572477035L,
-0.0000000000000000000261987180876106127L,
-0.0000000000000000000016553211620337322L,
-0.0000000000000000000001053943580037580L,
-0.0000000000000000000000067562822456482L,
-0.0000000000000000000000004357492971838L,
-0.0000000000000000000000000282576222954L,
-0.0000000000000000000000000018415141361L,
-0.0000000000000000000000000001205472536L,
-0.0000000000000000000000000000079233873L,
-0.0000000000000000000000000000005227403L,
-0.0000000000000000000000000000000346060L,
-0.0000000000000000000000000000000022982L,
-0.0000000000000000000000000000000001531L,
-0.0000000000000000000000000000000000102L,
-0.0000000000000000000000000000000000007L
};
long double sgn = 1;
if (x < 0) {
x = -x;
sgn = -1;
}
if (x >= PI2) {
x = fmodl(x, PI2);
}
if (x > PI) {
const long double p0 = 6.28125L;
const long double p1 = 0.0019353071795864769252867665590057683943L;
x = (p0 - x) + p1;
sgn = -sgn;
}
if (x == 0 || x == PI) {
return 0;
}
long double h = 0;
if (x < PIH) {
const long double u = RPIH*x;
h = 2*u*u - 1;
const long double alfa = h + h;
long double b0 = 0, b1 = 0, b2 = 0;
for (int i = 18; i >= 0; i--) {
b0 = A[i] + alfa*b1 - b2;
b2 = b1;
b1 = b0;
}
h = x*(1 - logl(x) + x*x*(b0 - h*b2)/2);
} else {
const long double u = RPIH*x - 2;
h = 2*u*u - 1;
const long double alfa = h + h;
long double b0 = 0, b1 = 0, b2 = 0;
for (int i = 29; i >= 0; i--) {
b0 = B[i] + alfa*b1 - b2;
b2 = b1;
b1 = b0;
}
h = (PI - x)*(b0 - h*b2);
}
return sgn*h;
}
/**
* @brief Real dilogarithm \f$\mathrm{Li}_2(x)\f$
* @param x real argument
* @return \f$\mathrm{Li}_2(x)\f$
* @author K.S. Kölbig
* @note Implementation translated by R.Brun from CERNLIB DILOG function C332
*
* Implemented as a truncated series expansion in terms of Chebyshev
* polynomials, see [Yudell L. Luke: Mathematical functions and their
* approximations, Academic Press Inc., New York 1975, p.67].
*/
double koelbig_dilog(double x)
{
const double PI = 3.141592653589793;
const double HF = 0.5;
const double PI2 = PI*PI;
const double PI3 = PI2/3;
const double PI6 = PI2/6;
const double PI12 = PI2/12;
const double C[20] = { 0.42996693560813697, 0.40975987533077106,
-0.01858843665014592, 0.00145751084062268,-0.00014304184442340,
0.00001588415541880,-0.00000190784959387, 0.00000024195180854,
-0.00000003193341274, 0.00000000434545063,-0.00000000060578480,
0.00000000008612098,-0.00000000001244332, 0.00000000000182256,
-0.00000000000027007, 0.00000000000004042,-0.00000000000000610,
0.00000000000000093,-0.00000000000000014, 0.00000000000000002};
double T, H, Y, S, A, ALFA, B1, B2, B0;
if (x == 1) {
H = PI6;
} else if (x == -1) {
H = -PI12;
} else {
T = -x;
if (T <= -2) {
Y = -1/(1+T);
S = 1;
B1= log(-T);
B2= log(1+1/T);
A = -PI3+HF*(B1*B1-B2*B2);
} else if (T < -1) {
Y = -1-T;
S = -1;
A = log(-T);
A = -PI6+A*(A+log(1+1/T));
} else if (T <= -0.5) {
Y = -(1+T)/T;
S = 1;
A = log(-T);
A = -PI6+A*(-HF*A+log(1+T));
} else if (T < 0) {
Y = -T/(1+T);
S = -1;
B1= log(1+T);
A = HF*B1*B1;
} else if (T <= 1) {
Y = T;
S = 1;
A = 0;
} else {
Y = 1/T;
S = -1;
B1= log(T);
A = PI6+HF*B1*B1;
}
H = Y+Y-1;
ALFA = H+H;
B1 = 0;
B2 = 0;
for (int i = 19; i >= 0; i--) {
B0 = C[i] + ALFA*B1-B2;
B2 = B1;
B1 = B0;
}
H = -(S*(B0-H*B2)+A);
}
return H;
}
/**
* @brief Real dilogarithm \f$\mathrm{Li}_2(z)\f$ with long double precision
* @param x real argument
* @return \f$\mathrm{Li}_2(z)\f$
* @author K.S. Kölbig
* @note Implementation based on translation by R.Brun from CERNLIB
* DILOG function C332, extended by Alexander Voigt to quadruple
* precision
*
* Implemented as a truncated series expansion in terms of Chebyshev
* polynomials, see [Yudell L. Luke: Mathematical functions and their
* approximations, Academic Press Inc., New York 1975, p.67].
*/
long double koelbig_dilogl(long double x)
{
const long double PI = 3.14159265358979323846264338327950288L;
const long double HF = 0.5L;
const long double PI2 = PI*PI;
const long double PI3 = PI2/3;
const long double PI6 = PI2/6;
const long double PI12 = PI2/12;
const long double C[] = {
0.4299669356081369720370336786993879912L,
0.4097598753307710584682637109252552781L,
-0.0185884366501459196476416491402122676L,
0.0014575108406226785536739284164594927L,
-0.0001430418444234004877488301200908765L,
0.0000158841554187955323619055047167740L,
-0.0000019078495938658272271963211420884L,
0.0000002419518085416474949946146434290L,
-0.0000000319334127425178346049601414286L,
0.0000000043454506267691229879571784782L,
-0.0000000006057848011840744442970533091L,
0.0000000000861209779935949824428368452L,
-0.0000000000124433165993886798964242137L,
0.0000000000018225569623573633006554774L,
-0.0000000000002700676604911465180857223L,
0.0000000000000404220926315266464883286L,
-0.0000000000000061032514526918795037783L,
0.0000000000000009286297533019575861303L,
-0.0000000000000001422602085511244683975L,
0.0000000000000000219263171815395735398L,
-0.0000000000000000033979732421589786340L,
#if LDBL_DIG > 18
0.0000000000000000005291954244833147146L,
-0.0000000000000000000827858081427899765L,
0.0000000000000000000130037173454556037L,
-0.0000000000000000000020502222425528249L,
0.0000000000000000000003243578549148930L,
-0.0000000000000000000000514779990334321L,
0.0000000000000000000000081938774771716L,
-0.0000000000000000000000013077835405713L,
0.0000000000000000000000002092562930580L,
-0.0000000000000000000000000335616615054L,
0.0000000000000000000000000053946577714L,
-0.0000000000000000000000000008689193209L,
0.0000000000000000000000000001402281687L,
-0.0000000000000000000000000000226715578L,
0.0000000000000000000000000000036717417L,
-0.0000000000000000000000000000005956152L,
0.0000000000000000000000000000000967662L,
-0.0000000000000000000000000000000157439L,
0.0000000000000000000000000000000025650L,
-0.0000000000000000000000000000000004185L,
0.0000000000000000000000000000000000683L,
-0.0000000000000000000000000000000000112L,
0.0000000000000000000000000000000000018L,
-0.0000000000000000000000000000000000003L
#endif
};
long double T, H, Y, S, A, ALFA, B1, B2, B0;
if (x == 1) {
H = PI6;
} else if (x == -1) {
H = -PI12;
} else {
T = -x;
if (T <= -2) {
Y = -1/(1+T);
S = 1;
B1= logl(-T);
B2= logl(1+1/T);
A = -PI3+HF*(B1*B1-B2*B2);
} else if (T < -1) {
Y = -1-T;
S = -1;
A = logl(-T);
A = -PI6+A*(A+logl(1+1/T));
} else if (T <= -0.5L) {
Y = -(1+T)/T;
S = 1;
A = logl(-T);
A = -PI6+A*(-HF*A+logl(1+T));
} else if (T < 0) {
Y = -T/(1+T);
S = -1;
B1= logl(1+T);
A = HF*B1*B1;
} else if (T <= 1) {
Y = T;
S = 1;
A = 0;
} else {
Y = 1/T;
S = -1;
B1= logl(T);
A = PI6+HF*B1*B1;
}
H = Y+Y-1;
ALFA = H+H;
B1 = 0;
B2 = 0;
for (int i = sizeof(C)/sizeof(C[0]) - 1; i >= 0; i--) {
B0 = C[i] + ALFA*B1-B2;
B2 = B1;
B1 = B0;
}
H = -(S*(B0-H*B2)+A);
}
return H;
}
|
the_stack_data/143718.c | #include <stdio.h>
#include <unistd.h>
int main() {
setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);
char buf[0x18];
printf("what's your name: ");
read(0, buf, 0x80);
printf("Hello, %s. Your comment: ", buf);
read(0, buf, 0x80);
printf("Thanks! We've received it: %s\n", buf);
read(0, buf, 0x30);
}
|
the_stack_data/176705413.c | /*
* Copyright (C) 2014, Galois, Inc.
* This sotware is distributed under a standard, three-clause BSD license.
* Please see the file LICENSE, distributed with this software, for specific
* terms and conditions.
*/
#include <stdlib.h>
char *getenv(const char *name __attribute__((unused)))
{
return NULL; // There is no environment, so this always returns "not found"
}
|
the_stack_data/26698933.c | # include <stdlib.h>
# include <stdio.h>
# include <math.h>
# include <time.h>
# include <omp.h>
int main ( int argc, char *argv[] );
double f ( double x );
double cpu_time ( void );
void timestamp ( void );
/******************************************************************************/
int main ( int argc, char *argv[] )
/******************************************************************************/
/*
Purpose:
MAIN is the main program for QUAD_OPENMP.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
14 December 2011
Author:
John Burkardt
*/
{
double a = 0.0;
double b = 10.0;
double error;
double exact = 0.49936338107645674464;
int i;
int n = 10000000;
double total;
double wtime;
double x;
timestamp ( );
printf ( "\n" );
printf ( "QUAD_OPENMP:\n" );
printf ( " C version\n" );
printf ( " Use OpenMP for parallel execution.\n" );
printf ( " Estimate the integral of f(x) from A to B.\n" );
printf ( " f(x) = 50 / ( pi * ( 2500 * x * x + 1 ) ).\n" );
printf ( "\n" );
printf ( " A = %f\n", a );
printf ( " B = %f\n", b );
printf ( " N = %d\n", n );
printf ( " Exact = %24.16f\n", exact );
wtime = omp_get_wtime ( );
total = 0.0;
# pragma omp parallel shared ( a, b, n ) private ( i, x )
# pragma omp for reduction ( + : total )
for ( i = 0; i < n; i++ )
{
x = ( ( double ) ( n - i - 1 ) * a + ( double ) ( i ) * b ) / ( double ) ( n - 1 );
total = total + f ( x );
}
wtime = omp_get_wtime ( ) - wtime;
total = ( b - a ) * total / ( double ) n;
error = fabs ( total - exact );
printf ( "\n" );
printf ( " Estimate = %24.16f\n", total );
printf ( " Error = %e\n", error );
printf ( " Time = %f\n", wtime );
/*
Terminate.
*/
printf ( "\n" );
printf ( "QUAD_OPENMP:\n" );
printf ( " Normal end of execution.\n" );
printf ( "\n" );
timestamp ( );
return 0;
}
/*******************************************************************************/
double f ( double x )
/*******************************************************************************/
/*
Purpose:
F evaluates the function.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
18 July 2010
Author:
John Burkardt
Parameters:
Input, double X, the argument.
Output, double F, the value of the function.
*/
{
double pi = 3.141592653589793;
double value;
value = 50.0 / ( pi * ( 2500.0 * x * x + 1.0 ) );
return value;
}
/*******************************************************************************/
double cpu_time ( void )
/*******************************************************************************/
/*
Purpose:
CPU_TIME reports the total CPU time for a program.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
27 September 2005
Author:
John Burkardt
Parameters:
Output, double CPU_TIME, the current total elapsed CPU time in second.
*/
{
double value;
value = ( double ) clock ( ) / ( double ) CLOCKS_PER_SEC;
return value;
}
/******************************************************************************/
void timestamp ( void )
/******************************************************************************/
/*
Purpose:
TIMESTAMP prints the current YMDHMS date as a time stamp.
Example:
31 May 2001 09:45:54 AM
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
24 September 2003
Author:
John Burkardt
Parameters:
None
*/
{
# define TIME_SIZE 40
static char time_buffer[TIME_SIZE];
const struct tm *tm;
time_t now;
now = time ( NULL );
tm = localtime ( &now );
strftime ( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm );
printf ( "%s\n", time_buffer );
return;
# undef TIME_SIZE
}
|
the_stack_data/941575.c | void my_module_(void)
{
}
|
the_stack_data/353902.c | #include <pthread.h>
int g;
void *t1(void *arg)
{
pthread_exit(0);
g=1;
}
int main()
{
pthread_t id1;
int arg1=10;
g=10;
pthread_create(&id1, NULL, t1, &arg1);
assert(g==10);
return 0;
}
|
the_stack_data/412085.c | /*
Operadores de Incremento (++) e Decremento (--)
Diferença entre a=b++ e a=++b || a = b-- e a = --b
a = b++; -> aqui primeiro 'a' recebe 'b' e depois ele faz o incremento +1;
a = ++b; -> aqui primeiro soma +1 a 'b' para depois 'a' receber o valor;
a = b--; -> aqui primeiro 'a' recebe 'b' e depois ele faz o decremento -1;
a = --b; -> aqui primeiro subtrai -1 a 'b' para depois 'a' receber o valor;
*/
#include <stdio.h>
int main()
{
int a,
b=1;
printf("b = %d\n",b);
printf("a = b++\n");
a = b++;
printf("\nAgora: \na = %d\n",a);
printf("b = %d\n",b);
printf("\na = ++b\n");
a = ++b;
printf("\nAgora: a = %d",a);
} |
the_stack_data/849688.c | /* Return basename of given pathname according to the weird XPG specification.
Copyright (C) 1997-2015 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, see
<http://www.gnu.org/licenses/>. */
#include <string.h>
#include <libgen.h>
char *
__xpg_basename (char *filename)
{
char *p;
if (filename == NULL || filename[0] == '\0')
/* We return a pointer to a static string containing ".". */
p = (char *) ".";
else
{
p = strrchr (filename, '/');
if (p == NULL)
/* There is no slash in the filename. Return the whole string. */
p = filename;
else
{
if (p[1] == '\0')
{
/* We must remove trailing '/'. */
while (p > filename && p[-1] == '/')
--p;
/* Now we can be in two situations:
a) the string only contains '/' characters, so we return
'/'
b) p points past the last component, but we have to remove
the trailing slash. */
if (p > filename)
{
*p-- = '\0';
while (p > filename && p[-1] != '/')
--p;
}
else
/* The last slash we already found is the right position
to return. */
while (p[1] != '\0')
++p;
}
else
/* Go to the first character of the name. */
++p;
}
}
return p;
}
|
the_stack_data/111603.c | /* -*- coding: utf-8-with-signature; tab-width: 8; indent-tabs-mode: t; -*- */
/*
* Suika 2
* Copyright (C) 2001-2016, TABATA Keiichi. All rights reserved.
*/
/*
* パッケージャ
*
* [Changes]
* - 2016/07/14 作成
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <dirent.h>
#endif
/* ファイルエントリの最大数 */
#define ENTRY_SIZE (65536)
/* ファイル名のサイズ */
#define FILE_NAME_SIZE (256)
/* アーカイブ先頭に書き出すファイル数のバイト数 */
#define FILE_COUNT_BYTES (8)
/* ファイルエントリのサイズ */
#define ENTRY_BYTES (256 + 8 + 8)
/* パッケージファイル名 */
#define PACKAGE_FILE_NAME "data01.arc"
/* ディレクトリ名 */
const char *dir_names[] = {
"bg", "bgm", "ch", "cg", "cv", "conf", "font", "se", "txt"
};
/* ディレクトリ名の数 */
#define DIR_COUNT (sizeof(dir_names) / sizeof(const char *))
/* ファイルエントリ */
struct entry {
/* ファイル名 */
char name[FILE_NAME_SIZE];
/* ファイルサイズ */
uint64_t size;
/* ファイルのアーカイブ内でのオフセット */
uint64_t offset;
} entry[ENTRY_SIZE];
/* ファイル数 */
uint64_t file_count;
/* 現在処理中のファイルのアーカイブ内でのオフセット */
uint64_t offset;
/* 前方参照 */
bool write_file_entries(FILE *fp);
bool write_file_bodies(FILE *fp);
#ifdef _WIN32
/*
* ディレクトリのファイル一覧を取得する(Windows版)
*/
bool get_file_names(const char *dir)
{
char path[256];
HANDLE hFind;
WIN32_FIND_DATA wfd;
/* ディレクトリの内容を取得する */
snprintf(path, sizeof(path), "%s\\*.*", dir);
hFind = FindFirstFile(path, &wfd);
if(hFind == INVALID_HANDLE_VALUE)
{
printf("Directory %s not found.\n", dir);
return false;
}
do
{
if(!(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
snprintf(entry[file_count].name, FILE_NAME_SIZE,
"%s/%s", dir, wfd.cFileName);
printf(" %s\n", entry[file_count].name);
file_count++;
}
} while (FindNextFile(hFind, &wfd));
FindClose(hFind);
return true;
}
#else
/*
* ディレクトリのファイル一覧を取得する(UNIX版)
*/
bool get_file_names(const char *dir)
{
char path[FILE_NAME_SIZE];
struct dirent **names;
int i, count;
/* ディレクトリの内容を取得する */
count = scandir(dir, &names, NULL, alphasort);
if (count < 0) {
printf("Directory %s not found.\n", dir);
return false;
}
if (count > ENTRY_SIZE) {
printf("Too many files.");
return false; /* Intentional memory leak. */
}
for (i = 0; i < count; i++) {
if (names[i]->d_name[0] == '.')
continue;
snprintf(entry[file_count].name, FILE_NAME_SIZE,
"%s/%s", dir, names[i]->d_name);
printf(" %s\n", entry[file_count].name);
free(names[i]);
file_count++;
}
free(names);
return true;
}
#endif
/*
* 各ファイルのサイズを求める
*/
bool get_file_sizes(void)
{
uint64_t i;
FILE *fp;
/* 各ファイルのサイズを求め、オフセットを計算する */
offset = FILE_COUNT_BYTES + ENTRY_BYTES * file_count;
for (i = 0; i < file_count; i++) {
#ifdef _WIN32
char *path = strdup(entry[i].name);
*strchr(path, '/') = '\\';
fp = fopen(path, "rb");
#else
fp = fopen(entry[i].name, "r");
#endif
if (fp == NULL) {
printf("Can't open file %s\n", entry[i].name);
return false;
}
fseek(fp, 0, SEEK_END);
entry[i].size = ftell(fp);
entry[i].offset = offset;
fclose(fp);
#ifdef _WIN32
free(path);
#endif
offset += entry[i].size;
}
return true;
}
/* アーカイブファイルを書き出す */
bool write_archive_file(void)
{
FILE *fp;
bool success;
fp = fopen(PACKAGE_FILE_NAME, "wb");
if (fp == NULL) {
printf("Can't open %s\n", PACKAGE_FILE_NAME);
return false;
}
success = false;
do {
if (fwrite(&file_count, sizeof(uint64_t), 1, fp) < 1)
break;
if (!write_file_entries(fp))
break;
if (!write_file_bodies(fp))
break;
} while (0);
return true;
}
/* ファイルのエントリを出力する */
bool write_file_entries(FILE *fp)
{
uint64_t i;
for (i = 0; i < file_count; i++) {
if (fwrite(&entry[i].name, FILE_NAME_SIZE, 1, fp) < 1)
return false;
if (fwrite(&entry[i].size, sizeof(uint64_t), 1, fp) < 1)
return false;
if (fwrite(&entry[i].offset, sizeof(uint64_t), 1, fp) < 1)
return false;
}
return true;
}
/* ファイルのエントリを出力する */
bool write_file_bodies(FILE *fp)
{
char buf[8192];
FILE *fpin;
uint64_t i;
size_t len;
for (i = 0; i < file_count; i++) {
#ifdef _WIN32
char *path = strdup(entry[i].name);
*strchr(path, '/') = '\\';
fpin = fopen(path, "rb");
#else
fpin = fopen(entry[i].name, "rb");
#endif
if (fpin == NULL) {
printf("Can't open %s\n", entry[i].name);
return false;
}
do {
len = fread(buf, 1, sizeof(buf), fpin);
if (len > 0)
if (fwrite(buf, len, 1, fp) < 1)
return false;
} while (len == sizeof(buf));
#ifdef _WIN32
free(path);
#endif
fclose(fpin);
}
return true;
}
int main(int argc, char *argv[])
{
int i;
printf("Hello, this is Suika2's packager.\n");
/* ファイルの一覧を取得する */
printf("Searching files...\n");
for (i = 0; i < DIR_COUNT; i++)
if (!get_file_names(dir_names[i]))
return 1;
/* ファイルのサイズを取得し、アーカイブ内でのオフセットを決定する */
printf("Checking file sizes...\n");
if (!get_file_sizes())
return 1;
/* アーカイブファイルを書き出す */
printf("Writing archive files...\n");
if (!write_archive_file())
return 1;
printf("Done.\n");
return 0;
}
|
the_stack_data/136145.c | #include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define map_dims 5
enum {timisoara, oradea, cluj_napoca, iasi, bucuresti};
char *cities[] = {"Timisoara", "Oradea", "Cluj-Napoca", "Iasi", "Bucuresti"};
unsigned minimum_distance = INT_MAX;
unsigned minimum_order[map_dims];
unsigned visited[map_dims] = {0};
int check_visited (unsigned *visited)
{
for (int i = 0; i < map_dims; i++)
{
if (visited[i] == 0)
return -1;
}
return 1;
}
int verify_all(unsigned *order)
{
for (int i = 0; i < map_dims; i++)
{
if (order[i] == (map_dims - 1))
return 1;
}
return 0;
}
unsigned calculate_distance (unsigned *route, unsigned map[][map_dims])
{
unsigned sum = 0;
for (int i = 0; i < map_dims; i++)
{
for (int j = 0; j < map_dims; j++)
{
if ( route[j] == (route[i]+1) )
sum += map[i][j];
}
}
return sum;
}
void copy_order(unsigned *destination, unsigned *from_here)
{
for (int i = 0; i < map_dims; i++)
destination[i] = from_here[i];
}
void back(unsigned map[][map_dims], unsigned city, unsigned first_city)
{
unsigned distance;
static int order = -1;
order++;
for (int i = 0; i < map_dims; i++)
{
if (map[city][i] != 0 && visited[i] == 0)
{
visited[city] = order;
back(map, i, first_city);
distance = calculate_distance(visited, map);
if ( (verify_all(visited)) && (visited[0] == first_city) && (distance < minimum_distance) )
{
minimum_distance = distance;
copy_order(minimum_order, visited);
}
visited[i] = 0;
order--;
}
}
}
void print_minimum_route ()
{
for (int i = 0; i < map_dims; i++)
printf("%s ", cities[minimum_order[i]]);
printf("\n");
}
int main (int argc, char **argv)
{
if (argc < 2)
{
printf("Please introduce the map as c l a\n");
exit(1);
}
FILE *fp = fopen (argv[1], "r");
if (!fp)
{
printf("Couldn't open file\n");
exit(1);
}
unsigned map[map_dims][map_dims];
for (int i = 0 ; i < map_dims; i++)
{
for (int j = 0; j < map_dims; j++)
fscanf(fp,"%u ", &map[i][j]);
}
fclose(fp);
back (map, timisoara, timisoara);
printf("Route:\n");
print_minimum_route();
printf("Minimum distance: ");
printf("%u\n", minimum_distance);
return 0;
} |
the_stack_data/215766841.c | /*
*************************************************************************
* Ralink Tech Inc.
* 5F., No.36, Taiyuan St., Jhubei City,
* Hsinchu County 302,
* Taiwan, R.O.C.
*
* (c) Copyright 2002-2010, Ralink Technology, 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 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. *
* *
*************************************************************************/
#ifdef RTMP_MAC_USB
#include "rt_config.h"
#define MAX_VENDOR_REQ_RETRY_COUNT 10
/*
========================================================================
Routine Description: NIC initialization complete
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
void usb_cfg_read_v1(PRTMP_ADAPTER ad, u32 *value)
{
RTUSBReadMACRegister(ad, USB_DMA_CFG, value);
}
void usb_cfg_write_v1(PRTMP_ADAPTER ad, u32 value)
{
RTUSBWriteMACRegister(ad, USB_DMA_CFG, value, FALSE);
}
void usb_cfg_read_v2(PRTMP_ADAPTER ad, u32 *value)
{
int ret;
u32 io_value;
ret = RTUSB_VendorRequest(ad,
(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
DEVICE_VENDOR_REQUEST_IN,
0x47,
0,
U3DMA_WLCFG,
&io_value,
4);
*value = le2cpu32(io_value);
if (ret)
*value = 0xffffffff;
}
void usb_cfg_write_v2(PRTMP_ADAPTER ad, u32 value)
{
int ret;
u32 io_value;
io_value = cpu2le32(value);
ret = RTUSB_VendorRequest(ad,
USBD_TRANSFER_DIRECTION_OUT,
DEVICE_VENDOR_REQUEST_OUT,
0x46,
0,
U3DMA_WLCFG,
&io_value,
4);
if (ret) {
DBGPRINT(RT_DEBUG_ERROR, ("usb cfg write fail\n"));
return;
}
}
static NTSTATUS RTUSBFirmwareRun(
IN PRTMP_ADAPTER pAd)
{
NTSTATUS Status;
Status = RTUSB_VendorRequest(
pAd,
USBD_TRANSFER_DIRECTION_OUT,
DEVICE_VENDOR_REQUEST_OUT,
0x01,
0x8,
0,
NULL,
0);
return Status;
}
/*
========================================================================
Routine Description: Get current firmware operation mode (Return Value)
Arguments:
Return Value:
0 or 1 = Downloaded by host driver
others = Driver doesn't download firmware
IRQL =
Note:
========================================================================
*/
NTSTATUS RTUSBFirmwareOpmode(
IN PRTMP_ADAPTER pAd,
OUT PULONG pValue)
{
NTSTATUS Status;
Status = RTUSB_VendorRequest(
pAd,
(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
DEVICE_VENDOR_REQUEST_IN,
0x1,
0x11,
0,
pValue,
4);
return Status;
}
/*
========================================================================
Routine Description: Write Firmware to NIC.
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
NTSTATUS RTUSBFirmwareWrite(
IN PRTMP_ADAPTER pAd,
IN PUCHAR pFwImage,
IN ULONG FwLen)
{
UINT32 MacReg;
NTSTATUS Status;
/* ULONG i;*/
USHORT writeLen;
/*ULONG FMode = 0;*/
Status = RTUSBReadMACRegister(pAd, MAC_CSR0, &MacReg);
/* write firmware */
writeLen = FwLen;
#ifdef USB_FIRMWARE_MULTIBYTE_WRITE
DBGPRINT(RT_DEBUG_TRACE, ("USB_FIRMWARE_MULTIBYTE_WRITE defined! Write_Bytes = %d\n", MULTIWRITE_BYTES));
RTUSBMultiWrite_nBytes(pAd, FIRMWARE_IMAGE_BASE, pFwImage, writeLen, MULTIWRITE_BYTES);
#else
DBGPRINT(RT_DEBUG_TRACE, ("USB_FIRMWARE_MULTIBYTE_WRITE not defined!\n"));
RTUSBMultiWrite(pAd, FIRMWARE_IMAGE_BASE, pFwImage, writeLen, FALSE);
#endif
Status = RTUSBWriteMACRegister(pAd, 0x7014, 0xffffffff, FALSE);
Status = RTUSBWriteMACRegister(pAd, 0x701c, 0xffffffff, FALSE);
/* change 8051 from ROM to RAM */
Status = RTUSBFirmwareRun(pAd);
return Status;
}
NTSTATUS RTUSBVenderReset(
IN PRTMP_ADAPTER pAd)
{
NTSTATUS Status;
DBGPRINT_RAW(RT_DEBUG_ERROR, ("-->RTUSBVenderReset\n"));
Status = RTUSB_VendorRequest(
pAd,
USBD_TRANSFER_DIRECTION_OUT,
DEVICE_VENDOR_REQUEST_OUT,
0x01,
0x1,
0,
NULL,
0);
DBGPRINT_RAW(RT_DEBUG_ERROR, ("<--RTUSBVenderReset\n"));
return Status;
}
/*
========================================================================
Routine Description: Read various length data from RT2573
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
NTSTATUS RTUSBMultiRead(
IN PRTMP_ADAPTER pAd,
IN USHORT Offset,
OUT PUCHAR pData,
IN USHORT length)
{
NTSTATUS Status;
Status = RTUSB_VendorRequest(
pAd,
(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
DEVICE_VENDOR_REQUEST_IN,
0x7,
0,
Offset,
pData,
length);
return Status;
}
/*
========================================================================
Routine Description: Write various length data to RT USB Wifi device, the maxima length should not large than 65535 bytes.
Arguments:
Return Value:
IRQL =
Note:
Use this funciton carefully cause it may not stable in some special USB host controllers.
========================================================================
*/
NTSTATUS RTUSBMultiWrite_nBytes(
IN PRTMP_ADAPTER pAd,
IN USHORT Offset,
IN PUCHAR pData,
IN USHORT length,
IN USHORT batchLen)
{
NTSTATUS Status = STATUS_SUCCESS;
USHORT index = Offset, actLen = batchLen, leftLen = length;
PUCHAR pSrc = pData;
do
{
actLen = (actLen > batchLen ? batchLen : actLen);
Status = RTUSB_VendorRequest(
pAd,
USBD_TRANSFER_DIRECTION_OUT,
DEVICE_VENDOR_REQUEST_OUT,
0x6,
0,
index,
pSrc,
actLen);
if (Status != STATUS_SUCCESS)
{
DBGPRINT(RT_DEBUG_ERROR, ("VendrCmdMultiWrite_nBytes failed!\n"));
break;
}
index += actLen;
leftLen -= actLen;
pSrc = pSrc + actLen;
}while(leftLen > 0);
return Status;
}
/*
========================================================================
Routine Description: Write various length data to RT2573
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
NTSTATUS RTUSBMultiWrite_OneByte(
IN PRTMP_ADAPTER pAd,
IN USHORT Offset,
IN PUCHAR pData)
{
NTSTATUS Status;
/* TODO: In 2870, use this funciton carefully cause it's not stable.*/
Status = RTUSB_VendorRequest(
pAd,
USBD_TRANSFER_DIRECTION_OUT,
DEVICE_VENDOR_REQUEST_OUT,
0x6,
0,
Offset,
pData,
1);
return Status;
}
NTSTATUS RTUSBMultiWrite(
IN PRTMP_ADAPTER pAd,
IN USHORT Offset,
IN PUCHAR pData,
IN USHORT length,
IN BOOLEAN bWriteHigh)
{
NTSTATUS Status;
USHORT index = 0,Value;
PUCHAR pSrc = pData;
USHORT resude = 0;
resude = length % 2;
length += resude;
do
{
Value =(USHORT)( *pSrc | (*(pSrc + 1) << 8));
Status = RTUSBSingleWrite(pAd,Offset + index, Value, bWriteHigh);
index +=2;
length -= 2;
pSrc = pSrc + 2;
}while(length > 0);
return Status;
}
NTSTATUS RTUSBSingleWrite(
IN RTMP_ADAPTER *pAd,
IN USHORT Offset,
IN USHORT Value,
IN BOOLEAN WriteHigh)
{
NTSTATUS Status;
Status = RTUSB_VendorRequest(
pAd,
USBD_TRANSFER_DIRECTION_OUT,
DEVICE_VENDOR_REQUEST_OUT,
(WriteHigh == TRUE) ? 0x10 : 0x2,
Value,
Offset,
NULL,
0);
return Status;
}
/*
========================================================================
Routine Description: Read 32-bit MAC register
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
NTSTATUS RTUSBReadMACRegister(
IN PRTMP_ADAPTER pAd,
IN USHORT Offset,
OUT PUINT32 pValue)
{
NTSTATUS Status = 0;
UINT32 localVal;
Status = RTUSB_VendorRequest(
pAd,
(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
DEVICE_VENDOR_REQUEST_IN,
0x7,
0,
Offset,
&localVal,
4);
*pValue = le2cpu32(localVal);
if (Status != 0)
*pValue = 0xffffffff;
return Status;
}
/*
========================================================================
Routine Description: Write 32-bit MAC register
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
NTSTATUS RTUSBWriteMACRegister(
IN RTMP_ADAPTER *pAd,
IN USHORT Offset,
IN UINT32 Value,
IN BOOLEAN bWriteHigh)
{
NTSTATUS Status;
UINT32 localVal;
localVal = Value;
/* MT76xx HW has 4 byte alignment constrained */
if (IS_MT76xx(pAd)) {
Status = RTUSBMultiWrite_nBytes(
pAd,
Offset,
(PUCHAR)&Value,
4,
4);
} else {
Status = RTUSBSingleWrite(pAd, Offset, (USHORT)(localVal & 0xffff), bWriteHigh);
Status = RTUSBSingleWrite(pAd, Offset + 2, (USHORT)((localVal & 0xffff0000) >> 16), bWriteHigh);
}
return Status;
}
int write_reg(
RTMP_ADAPTER *ad,
u32 base,
u16 offset,
u32 value)
{
int ret;
u8 req;
u32 io_value;
if (base == 0x40)
req = 0x46;
io_value = cpu2le32(value);
ret = RTUSB_VendorRequest(ad,
USBD_TRANSFER_DIRECTION_OUT,
DEVICE_VENDOR_REQUEST_OUT,
req,
0,
offset,
&io_value,
4);
if (ret) {
DBGPRINT(RT_DEBUG_ERROR, ("write reg fail\n"));
}
return ret; /* CK */
}
int read_reg(
RTMP_ADAPTER *ad,
u32 base,
u16 offset,
u32 *value)
{
int ret;
u8 req = 0;
u32 io_value;
if (base == 0x40)
req = 0x47;
else if (base == 0x41)
req = 0x7;
ret = RTUSB_VendorRequest(ad,
(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
DEVICE_VENDOR_REQUEST_IN,
req,
0,
offset,
&io_value,
4);
*value = le2cpu32(io_value);
if (ret)
*value = 0xffffffff;
return ret; /* CK */
}
/*
========================================================================
Routine Description: Read 8-bit BBP register via firmware
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
NTSTATUS RTUSBReadBBPRegister(
IN PRTMP_ADAPTER pAd,
IN UCHAR Id,
IN PUCHAR pValue)
{
BBP_CSR_CFG_STRUC BbpCsr;
int i, k, ret;
RTMP_SEM_EVENT_WAIT(&pAd->reg_atomic, ret);
if (ret != 0)
{
DBGPRINT(RT_DEBUG_ERROR, ("reg_atomic get failed(ret=%d)\n", ret));
return STATUS_UNSUCCESSFUL;
}
for (i=0; i<MAX_BUSY_COUNT; i++)
{
RTUSBReadMACRegister(pAd, H2M_BBP_AGENT, &BbpCsr.word);
if (BbpCsr.field.Busy == BUSY)
continue;
BbpCsr.word = 0;
BbpCsr.field.fRead = 1;
BbpCsr.field.BBP_RW_MODE = 1;
BbpCsr.field.Busy = 1;
BbpCsr.field.RegNum = Id;
RTUSBWriteMACRegister(pAd, H2M_BBP_AGENT, BbpCsr.word, FALSE);
AsicSendCommandToMcu(pAd, 0x80, 0xff, 0x0, 0x0, TRUE);
for (k=0; k<MAX_BUSY_COUNT; k++)
{
RTUSBReadMACRegister(pAd, H2M_BBP_AGENT, &BbpCsr.word);
if (BbpCsr.field.Busy == IDLE)
break;
}
if ((BbpCsr.field.Busy == IDLE) &&
(BbpCsr.field.RegNum == Id))
{
*pValue = (UCHAR)BbpCsr.field.Value;
break;
}
}
RTMP_SEM_EVENT_UP(&pAd->reg_atomic);
if (BbpCsr.field.Busy == BUSY)
{
DBGPRINT_ERR(("BBP read R%d=0x%x fail\n", Id, BbpCsr.word));
*pValue = pAd->BbpWriteLatch[Id];
return STATUS_UNSUCCESSFUL;
}
return STATUS_SUCCESS;
}
/*
========================================================================
Routine Description: Write 8-bit BBP register via firmware
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
NTSTATUS RTUSBWriteBBPRegister(
IN PRTMP_ADAPTER pAd,
IN UCHAR Id,
IN UCHAR Value)
{
BBP_CSR_CFG_STRUC BbpCsr;
int BusyCnt;
int ret;
RTMP_SEM_EVENT_WAIT(&pAd->reg_atomic, ret);
if (ret != 0)
{
DBGPRINT(RT_DEBUG_ERROR, ("reg_atomic get failed(ret=%d)\n", ret));
return STATUS_UNSUCCESSFUL;
}
for (BusyCnt=0; BusyCnt<MAX_BUSY_COUNT; BusyCnt++)
{
RTMP_IO_READ32(pAd, H2M_BBP_AGENT, &BbpCsr.word);
if (BbpCsr.field.Busy == BUSY)
continue;
BbpCsr.word = 0;
BbpCsr.field.fRead = 0;
BbpCsr.field.BBP_RW_MODE = 1;
BbpCsr.field.Busy = 1;
BbpCsr.field.Value = Value;
BbpCsr.field.RegNum = Id;
RTMP_IO_WRITE32(pAd, H2M_BBP_AGENT, BbpCsr.word);
AsicSendCommandToMcu(pAd, 0x80, 0xff, 0x0, 0x0, TRUE);
pAd->BbpWriteLatch[Id] = Value;
break;
}
RTMP_SEM_EVENT_UP(&pAd->reg_atomic);
if (BusyCnt == MAX_BUSY_COUNT)
{
DBGPRINT_ERR(("BBP write R%d=0x%x fail\n", Id, BbpCsr.word));
return STATUS_UNSUCCESSFUL;
}
return STATUS_SUCCESS;
}
/*
========================================================================
Routine Description: Write RF register through MAC
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
NTSTATUS RTUSBWriteRFRegister(
IN PRTMP_ADAPTER pAd,
IN UINT32 Value)
{
RF_CSR_CFG0_STRUC PhyCsr4;
UINT i = 0;
NTSTATUS status;
NdisZeroMemory(&PhyCsr4, sizeof(RF_CSR_CFG0_STRUC));
RTMP_SEM_EVENT_WAIT(&pAd->reg_atomic, status);
if (status != 0) {
DBGPRINT(RT_DEBUG_ERROR, ("reg_atomic get failed(ret=%d)\n", status));
return STATUS_UNSUCCESSFUL;
}
status = STATUS_UNSUCCESSFUL;
do
{
status = RTUSBReadMACRegister(pAd, RF_CSR_CFG0, &PhyCsr4.word);
if (status >= 0)
{
if (!(PhyCsr4.field.Busy))
break;
}
DBGPRINT(RT_DEBUG_TRACE, ("RTUSBWriteRFRegister(RF_CSR_CFG0):retry count=%d!\n", i));
i++;
}
while ((i < RETRY_LIMIT) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)));
if ((i == RETRY_LIMIT) || (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
{
DBGPRINT_RAW(RT_DEBUG_ERROR, ("Retry count exhausted or device removed!!!\n"));
goto done;
}
RTUSBWriteMACRegister(pAd, RF_CSR_CFG0, Value, FALSE);
status = STATUS_SUCCESS;
done:
RTMP_SEM_EVENT_UP(&pAd->reg_atomic);
return status;
}
/*
========================================================================
Routine Description:
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
NTSTATUS RTUSBReadEEPROM(
IN PRTMP_ADAPTER pAd,
IN USHORT Offset,
OUT PUCHAR pData,
IN USHORT length)
{
NTSTATUS Status = STATUS_SUCCESS;
Status = RTUSB_VendorRequest(
pAd,
(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
DEVICE_VENDOR_REQUEST_IN,
0x9,
0,
Offset,
pData,
length);
return Status;
}
/*
========================================================================
Routine Description:
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
NTSTATUS RTUSBWriteEEPROM(
IN PRTMP_ADAPTER pAd,
IN USHORT Offset,
IN PUCHAR pData,
IN USHORT length)
{
NTSTATUS Status = STATUS_SUCCESS;
Status = RTUSB_VendorRequest(
pAd,
USBD_TRANSFER_DIRECTION_OUT,
DEVICE_VENDOR_REQUEST_OUT,
0x8,
0,
Offset,
pData,
length);
return Status;
}
NTSTATUS RTUSBReadEEPROM16(
IN PRTMP_ADAPTER pAd,
IN USHORT offset,
OUT PUSHORT pData)
{
NTSTATUS status;
USHORT localData;
status = RTUSBReadEEPROM(pAd, offset, (PUCHAR)(&localData), 2);
if (status == STATUS_SUCCESS)
*pData = le2cpu16(localData);
return status;
}
NTSTATUS RTUSBWriteEEPROM16(
IN RTMP_ADAPTER *pAd,
IN USHORT offset,
IN USHORT value)
{
USHORT tmpVal;
tmpVal = cpu2le16(value);
return RTUSBWriteEEPROM(pAd, offset, (PUCHAR)&(tmpVal), 2);
}
/*
========================================================================
Routine Description:
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
VOID RTUSBPutToSleep(
IN PRTMP_ADAPTER pAd)
{
UINT32 value;
/* Timeout 0x40 x 50us*/
value = (SLEEPCID<<16)+(OWNERMCU<<24)+ (0x40<<8)+1;
RTUSBWriteMACRegister(pAd, 0x7010, value, FALSE);
RTUSBWriteMACRegister(pAd, 0x404, 0x30, FALSE);
/*RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS); */
DBGPRINT_RAW(RT_DEBUG_ERROR, ("Sleep Mailbox testvalue %x\n", value));
}
/*
========================================================================
Routine Description:
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
NTSTATUS RTUSBWakeUp(
IN PRTMP_ADAPTER pAd)
{
NTSTATUS Status;
Status = RTUSB_VendorRequest(
pAd,
USBD_TRANSFER_DIRECTION_OUT,
DEVICE_VENDOR_REQUEST_OUT,
0x01,
0x09,
0,
NULL,
0);
return Status;
}
/*
========================================================================
Routine Description:
Arguments:
Return Value:
IRQL =
Note:
========================================================================
*/
NDIS_STATUS RTUSBEnqueueCmdFromNdis(
IN PRTMP_ADAPTER pAd,
IN NDIS_OID Oid,
IN BOOLEAN SetInformation,
IN PVOID pInformationBuffer,
IN UINT32 InformationBufferLength)
{
NDIS_STATUS status;
PCmdQElmt cmdqelmt = NULL;
RTMP_OS_TASK *pTask = &pAd->cmdQTask;
RTMP_OS_TASK_LEGALITY(pTask)
;
else
return (NDIS_STATUS_RESOURCES);
status = os_alloc_mem(pAd, (PUCHAR *)(&cmdqelmt), sizeof(CmdQElmt));
if ((status != NDIS_STATUS_SUCCESS) || (cmdqelmt == NULL))
return (NDIS_STATUS_RESOURCES);
cmdqelmt->buffer = NULL;
if (pInformationBuffer != NULL)
{
status = os_alloc_mem(pAd, (PUCHAR *)&cmdqelmt->buffer, InformationBufferLength);
if ((status != NDIS_STATUS_SUCCESS) || (cmdqelmt->buffer == NULL))
{
/* kfree(cmdqelmt);*/
os_free_mem(NULL, cmdqelmt);
return (NDIS_STATUS_RESOURCES);
}
else
{
NdisMoveMemory(cmdqelmt->buffer, pInformationBuffer, InformationBufferLength);
cmdqelmt->bufferlength = InformationBufferLength;
}
}
else
cmdqelmt->bufferlength = 0;
cmdqelmt->command = Oid;
cmdqelmt->CmdFromNdis = TRUE;
if (SetInformation == TRUE)
cmdqelmt->SetOperation = TRUE;
else
cmdqelmt->SetOperation = FALSE;
NdisAcquireSpinLock(&pAd->CmdQLock);
if (pAd->CmdQ.CmdQState & RTMP_TASK_CAN_DO_INSERT)
{
EnqueueCmd((&pAd->CmdQ), cmdqelmt);
status = NDIS_STATUS_SUCCESS;
}
else
{
status = NDIS_STATUS_FAILURE;
}
NdisReleaseSpinLock(&pAd->CmdQLock);
if (status == NDIS_STATUS_FAILURE)
{
if (cmdqelmt->buffer)
os_free_mem(pAd, cmdqelmt->buffer);
os_free_mem(pAd, cmdqelmt);
}
else
RTCMDUp(&pAd->cmdQTask);
return(NDIS_STATUS_SUCCESS);
}
/*
========================================================================
Routine Description:
RTUSB_VendorRequest - Builds a ralink specific request, sends it off to USB endpoint zero and waits for completion
Arguments:
@pAd:
@TransferFlags:
@RequestType: USB message request type value
@Request: USB message request value
@Value: USB message value
@Index: USB message index value
@TransferBuffer: USB data to be sent
@TransferBufferLength: Lengths in bytes of the data to be sent
Context: ! in atomic context
Return Value:
NDIS_STATUS_SUCCESS
NDIS_STATUS_FAILURE
Note:
This function sends a simple control message to endpoint zero
and waits for the message to complete, or CONTROL_TIMEOUT_JIFFIES timeout.
Because it is synchronous transfer, so don't use this function within an atomic context,
otherwise system will hang, do be careful.
TransferBuffer may located in stack region which may not in DMA'able region in some embedded platforms,
so need to copy TransferBuffer to UsbVendorReqBuf allocated by kmalloc to do DMA transfer.
Use UsbVendorReq_semaphore to protect this region which may be accessed by multi task.
Normally, coherent issue is resloved by low-level HC driver, so do not flush this zone by RTUSB_VendorRequest.
========================================================================
*/
NTSTATUS RTUSB_VendorRequest(
IN PRTMP_ADAPTER pAd,
IN UINT32 TransferFlags,
IN UCHAR RequestType,
IN UCHAR Request,
IN USHORT Value,
IN USHORT Index,
IN PVOID TransferBuffer,
IN UINT32 TransferBufferLength)
{
int RET = 0;
POS_COOKIE pObj = (POS_COOKIE) pAd->OS_Cookie;
if(in_interrupt())
{
DBGPRINT(RT_DEBUG_ERROR, ("BUG: RTUSB_VendorRequest is called from invalid context\n"));
return NDIS_STATUS_FAILURE;
}
if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
{
DBGPRINT(RT_DEBUG_ERROR, ("WIFI device has been disconnected\n"));
return NDIS_STATUS_FAILURE;
}
else if (RTMP_TEST_PSFLAG(pAd, fRTMP_PS_MCU_SLEEP))
{
DBGPRINT(RT_DEBUG_ERROR, ("MCU has entered sleep mode\n"));
return NDIS_STATUS_FAILURE;
}
else
{
int RetryCount = 0; /* RTUSB_CONTROL_MSG retry counts*/
ASSERT(TransferBufferLength <MAX_PARAM_BUFFER_SIZE);
RTMP_SEM_EVENT_WAIT(&(pAd->UsbVendorReq_semaphore), RET);
if (RET != 0)
{
DBGPRINT(RT_DEBUG_ERROR, ("UsbVendorReq_semaphore get failed\n"));
return NDIS_STATUS_FAILURE;
}
if ((TransferBufferLength > 0) && (RequestType == DEVICE_VENDOR_REQUEST_OUT))
NdisMoveMemory(pAd->UsbVendorReqBuf, TransferBuffer, TransferBufferLength);
do {
RTUSB_CONTROL_MSG(pObj->pUsb_Dev, 0, Request, RequestType, Value, Index, pAd->UsbVendorReqBuf, TransferBufferLength, CONTROL_TIMEOUT_JIFFIES, RET);
if (RET < 0 ) {
DBGPRINT(RT_DEBUG_OFF, ("#\n"));
if (RET == RTMP_USB_CONTROL_MSG_ENODEV)
{
RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST);
break;
}
RetryCount++;
RTMPusecDelay(5000); /* wait for 5ms*/
}
} while((RET < 0 ) && (RetryCount < MAX_VENDOR_REQ_RETRY_COUNT));
if ( (!(RET < 0)) && (TransferBufferLength > 0) && (RequestType == DEVICE_VENDOR_REQUEST_IN))
NdisMoveMemory(TransferBuffer, pAd->UsbVendorReqBuf, TransferBufferLength);
RTMP_SEM_EVENT_UP(&(pAd->UsbVendorReq_semaphore));
if (RET < 0) {
DBGPRINT(RT_DEBUG_ERROR, ("RTUSB_VendorRequest failed(%d),TxFlags=0x%x, ReqType=%s, Req=0x%x, Idx=0x%x,pAd->Flags=0x%lx\n",
RET, TransferFlags, (RequestType == DEVICE_VENDOR_REQUEST_OUT ? "OUT" : "IN"), Request, Index, pAd->Flags));
if (Request == 0x2)
DBGPRINT(RT_DEBUG_ERROR, ("\tRequest Value=0x%04x!\n", Value));
if ((!TransferBuffer) && (TransferBufferLength > 0))
hex_dump("Failed TransferBuffer value", TransferBuffer, TransferBufferLength);
if (RET == RTMP_USB_CONTROL_MSG_ENODEV)
RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST);
}
}
if (RET < 0)
return NDIS_STATUS_FAILURE;
else
return NDIS_STATUS_SUCCESS;
}
/*
========================================================================
Routine Description:
Creates an IRP to submite an IOCTL_INTERNAL_USB_RESET_PORT
synchronously. Callers of this function must be running at
PASSIVE LEVEL.
Arguments:
Return Value:
Note:
========================================================================
*/
NTSTATUS RTUSB_ResetDevice(
IN PRTMP_ADAPTER pAd)
{
NTSTATUS Status = TRUE;
DBGPRINT_RAW(RT_DEBUG_TRACE, ("--->USB_ResetDevice\n"));
/*RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS);*/
return Status;
}
NTSTATUS CheckGPIOHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
#ifdef RALINK_ATE
if (ATE_ON(pAd))
{
DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
return NDIS_STATUS_SUCCESS;
}
#endif /* RALINK_ATE */
IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
{
UINT32 data;
/* Read GPIO pin2 as Hardware controlled radio state*/
RTUSBReadMACRegister( pAd, GPIO_CTRL_CFG, &data);
if (data & 0x04)
{
pAd->StaCfg.bHwRadio = TRUE;
}
else
{
pAd->StaCfg.bHwRadio = FALSE;
}
if (pAd->StaCfg.bRadio != (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio))
{
pAd->StaCfg.bRadio = (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio);
if (pAd->StaCfg.bRadio == TRUE)
{
DBGPRINT_RAW(RT_DEBUG_ERROR, ("!!! Radio On !!!\n"));
MlmeRadioOn(pAd);
/* Update extra information */
pAd->ExtraInfo = EXTRA_INFO_CLEAR;
}
else
{
DBGPRINT_RAW(RT_DEBUG_ERROR, ("!!! Radio Off !!!\n"));
MlmeRadioOff(pAd);
/* Update extra information */
pAd->ExtraInfo = HW_RADIO_OFF;
}
}
} /* end IF_DEV_CONFIG_OPMODE_ON_STA*/
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS ResetBulkOutHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
INT32 MACValue = 0;
UCHAR Index = 0;
int ret=0;
PHT_TX_CONTEXT pHTTXContext;
/* RTMP_TX_RING *pTxRing;*/
unsigned long IrqFlags;
DBGPRINT(RT_DEBUG_TRACE, ("CMDTHREAD_RESET_BULK_OUT(ResetPipeid=0x%0x)===>\n", pAd->bulkResetPipeid));
/* All transfers must be aborted or cancelled before attempting to reset the pipe. */
/*RTUSBCancelPendingBulkOutIRP(pAd);*/
/* Wait 10ms to let previous packet that are already in HW FIFO to clear. by MAXLEE 12-25-2007*/
do
{
if(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
break;
RTUSBReadMACRegister(pAd, TXRXQ_PCNT, &MACValue);
if ((MACValue & 0xf00000/*0x800000*/) == 0)
break;
Index++;
RTMPusecDelay(10000);
}while(Index < 100);
RTUSBReadMACRegister(pAd, USB_DMA_CFG, &MACValue);
/* 2nd, to prevent Read Register error, we check the validity.*/
if ((MACValue & 0xc00000) == 0)
RTUSBReadMACRegister(pAd, USB_DMA_CFG, &MACValue);
/* 3rd, to prevent Read Register error, we check the validity.*/
if ((MACValue & 0xc00000) == 0)
RTUSBReadMACRegister(pAd, USB_DMA_CFG, &MACValue);
MACValue |= 0x80000;
RTUSBWriteMACRegister(pAd, USB_DMA_CFG, MACValue, FALSE);
/* Wait 1ms to prevent next URB to bulkout before HW reset. by MAXLEE 12-25-2007*/
RTMPusecDelay(1000);
MACValue &= (~0x80000);
RTUSBWriteMACRegister(pAd, USB_DMA_CFG, MACValue, FALSE);
DBGPRINT(RT_DEBUG_TRACE, ("\tSet 0x2a0 bit19. Clear USB DMA TX path\n"));
/* Wait 5ms to prevent next URB to bulkout before HW reset. by MAXLEE 12-25-2007*/
/*RTMPusecDelay(5000);*/
if ((pAd->bulkResetPipeid & BULKOUT_MGMT_RESET_FLAG) == BULKOUT_MGMT_RESET_FLAG)
{
RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
if (pAd->MgmtRing.TxSwFreeIdx < MGMT_RING_SIZE /* pMLMEContext->bWaitingBulkOut == TRUE */)
RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_MLME);
RTUSBKickBulkOut(pAd);
DBGPRINT(RT_DEBUG_TRACE, ("\tTX MGMT RECOVER Done!\n"));
}
else
{
pHTTXContext = &(pAd->TxContext[pAd->bulkResetPipeid]);
/*NdisAcquireSpinLock(&pAd->BulkOutLock[pAd->bulkResetPipeid]);*/
RTMP_INT_LOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
if ( pAd->BulkOutPending[pAd->bulkResetPipeid] == FALSE)
{
pAd->BulkOutPending[pAd->bulkResetPipeid] = TRUE;
pHTTXContext->IRPPending = TRUE;
pAd->watchDogTxPendingCnt[pAd->bulkResetPipeid] = 1;
/* no matter what, clean the flag*/
RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
/*NdisReleaseSpinLock(&pAd->BulkOutLock[pAd->bulkResetPipeid]);*/
RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
#ifdef RALINK_ATE
if (ATE_ON(pAd))
ret = ATEResetBulkOut(pAd);
else
#endif /* RALINK_ATE */
{
RTUSBInitHTTxDesc(pAd, pHTTXContext, pAd->bulkResetPipeid,
pHTTXContext->BulkOutSize,
RtmpUsbBulkOutDataPacketComplete);
if ((ret = RTUSB_SUBMIT_URB(pHTTXContext->pUrb))!=0)
{
RTMP_INT_LOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
pAd->BulkOutPending[pAd->bulkResetPipeid] = FALSE;
pHTTXContext->IRPPending = FALSE;
pAd->watchDogTxPendingCnt[pAd->bulkResetPipeid] = 0;
RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
DBGPRINT(RT_DEBUG_ERROR, ("CMDTHREAD_RESET_BULK_OUT:Submit Tx URB failed %d\n", ret));
}
else
{
RTMP_INT_LOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
DBGPRINT(RT_DEBUG_TRACE,("\tCMDTHREAD_RESET_BULK_OUT: TxContext[%d]:CWPos=%ld, NBPos=%ld, ENBPos=%ld, bCopy=%d, pending=%d!\n",
pAd->bulkResetPipeid, pHTTXContext->CurWritePosition, pHTTXContext->NextBulkOutPosition,
pHTTXContext->ENextBulkOutPosition, pHTTXContext->bCopySavePad,
pAd->BulkOutPending[pAd->bulkResetPipeid]));
DBGPRINT(RT_DEBUG_TRACE,("\t\tBulkOut Req=0x%lx, Complete=0x%lx, Other=0x%lx\n",
pAd->BulkOutReq, pAd->BulkOutComplete, pAd->BulkOutCompleteOther));
RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
DBGPRINT(RT_DEBUG_TRACE, ("\tCMDTHREAD_RESET_BULK_OUT: Submit Tx DATA URB for failed BulkReq(0x%lx) Done, status=%d!\n",
pAd->bulkResetReq[pAd->bulkResetPipeid],
RTMP_USB_URB_STATUS_GET(pHTTXContext->pUrb)));
}
}
}
else
{
/*NdisReleaseSpinLock(&pAd->BulkOutLock[pAd->bulkResetPipeid]);*/
/*RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);*/
DBGPRINT(RT_DEBUG_ERROR, ("CmdThread : TX DATA RECOVER FAIL for BulkReq(0x%lx) because BulkOutPending[%d] is TRUE!\n",
pAd->bulkResetReq[pAd->bulkResetPipeid], pAd->bulkResetPipeid));
if (pAd->bulkResetPipeid == 0)
{
UCHAR pendingContext = 0;
PHT_TX_CONTEXT pHTTXContext = (PHT_TX_CONTEXT)(&pAd->TxContext[pAd->bulkResetPipeid ]);
PTX_CONTEXT pMLMEContext = (PTX_CONTEXT)(pAd->MgmtRing.Cell[pAd->MgmtRing.TxDmaIdx].AllocVa);
PTX_CONTEXT pNULLContext = (PTX_CONTEXT)(&pAd->PsPollContext);
PTX_CONTEXT pPsPollContext = (PTX_CONTEXT)(&pAd->NullContext);
if (pHTTXContext->IRPPending)
pendingContext |= 1;
else if (pMLMEContext->IRPPending)
pendingContext |= 2;
else if (pNULLContext->IRPPending)
pendingContext |= 4;
else if (pPsPollContext->IRPPending)
pendingContext |= 8;
else
pendingContext = 0;
DBGPRINT(RT_DEBUG_ERROR, ("\tTX Occupied by %d!\n", pendingContext));
}
/* no matter what, clean the flag*/
RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);
RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
RTUSB_SET_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_NORMAL << pAd->bulkResetPipeid));
}
RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
/*RTUSBKickBulkOut(pAd);*/
}
DBGPRINT_RAW(RT_DEBUG_TRACE, ("CmdThread : CMDTHREAD_RESET_BULK_OUT<===\n"));
return NDIS_STATUS_SUCCESS;
}
/* All transfers must be aborted or cancelled before attempting to reset the pipe.*/
static NTSTATUS ResetBulkInHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
UINT32 MACValue;
NTSTATUS ntStatus;
DBGPRINT_RAW(RT_DEBUG_TRACE, ("CmdThread : CMDTHREAD_RESET_BULK_IN === >\n"));
if(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_IDLE_RADIO_OFF))
{
RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BULKIN_RESET);
return NDIS_STATUS_SUCCESS;
}
#ifdef RALINK_ATE
if (ATE_ON(pAd))
ATEResetBulkIn(pAd);
else
#endif /* RALINK_ATE */
{
/*while ((atomic_read(&pAd->PendingRx) > 0) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))) */
if((pAd->PendingRx > 0) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
{
DBGPRINT_RAW(RT_DEBUG_ERROR, ("BulkIn IRP Pending!!!\n"));
RTUSBCancelPendingBulkInIRP(pAd);
RTMPusecDelay(100000);
pAd->PendingRx = 0;
}
}
/* Wait 10ms before reading register.*/
RTMPusecDelay(10000);
ntStatus = RTUSBReadMACRegister(pAd, MAC_CSR0, &MACValue);
/* It must be removed. Or ATE will have no RX success. */
if ((NT_SUCCESS(ntStatus) == TRUE) &&
(!(RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS | fRTMP_ADAPTER_RADIO_OFF |
fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST)))))
{
UCHAR i;
if (RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS | fRTMP_ADAPTER_RADIO_OFF |
fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST)))
return NDIS_STATUS_SUCCESS;
pAd->NextRxBulkInPosition = pAd->RxContext[pAd->NextRxBulkInIndex].BulkInOffset;
DBGPRINT(RT_DEBUG_TRACE, ("BULK_IN_RESET: NBIIdx=0x%x,NBIRIdx=0x%x, BIRPos=0x%lx. BIReq=x%lx, BIComplete=0x%lx, BICFail0x%lx\n",
pAd->NextRxBulkInIndex, pAd->NextRxBulkInReadIndex, pAd->NextRxBulkInPosition, pAd->BulkInReq, pAd->BulkInComplete, pAd->BulkInCompleteFail));
for (i = 0; i < RX_RING_SIZE; i++)
{
DBGPRINT(RT_DEBUG_TRACE, ("\tRxContext[%d]: IRPPending=%d, InUse=%d, Readable=%d!\n"
, i, pAd->RxContext[i].IRPPending, pAd->RxContext[i].InUse, pAd->RxContext[i].Readable));
}
RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BULKIN_RESET);
for (i = 0; i < pAd->CommonCfg.NumOfBulkInIRP; i++)
{
/*RTUSBBulkReceive(pAd);*/
PRX_CONTEXT pRxContext;
PURB pUrb;
int ret = 0;
unsigned long IrqFlags;
RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
pRxContext = &(pAd->RxContext[pAd->NextRxBulkInIndex]);
if ((pAd->PendingRx > 0) || (pRxContext->Readable == TRUE) || (pRxContext->InUse == TRUE))
{
RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
return NDIS_STATUS_SUCCESS;
}
pRxContext->InUse = TRUE;
pRxContext->IRPPending = TRUE;
pAd->PendingRx++;
pAd->BulkInReq++;
RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
/* Init Rx context descriptor*/
RTUSBInitRxDesc(pAd, pRxContext);
pUrb = pRxContext->pUrb;
if ((ret = RTUSB_SUBMIT_URB(pUrb))!=0)
{ /* fail*/
RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
pRxContext->InUse = FALSE;
pRxContext->IRPPending = FALSE;
pAd->PendingRx--;
pAd->BulkInReq--;
RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
DBGPRINT(RT_DEBUG_ERROR, ("CMDTHREAD_RESET_BULK_IN: Submit Rx URB failed(%d), status=%d\n", ret, RTMP_USB_URB_STATUS_GET(pUrb)));
}
else
{ /* success*/
/*DBGPRINT(RT_DEBUG_TRACE, ("BIDone, Pend=%d,BIIdx=%d,BIRIdx=%d!\n", */
/* pAd->PendingRx, pAd->NextRxBulkInIndex, pAd->NextRxBulkInReadIndex));*/
DBGPRINT_RAW(RT_DEBUG_TRACE, ("CMDTHREAD_RESET_BULK_IN: Submit Rx URB Done, status=%d!\n", RTMP_USB_URB_STATUS_GET(pUrb)));
ASSERT((pRxContext->InUse == pRxContext->IRPPending));
}
}
}
else
{
/* Card must be removed*/
if (NT_SUCCESS(ntStatus) != TRUE)
{
RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST);
DBGPRINT_RAW(RT_DEBUG_ERROR, ("CMDTHREAD_RESET_BULK_IN: Read Register Failed!Card must be removed!!\n\n"));
}
else
DBGPRINT_RAW(RT_DEBUG_ERROR, ("CMDTHREAD_RESET_BULK_IN: Cannot do bulk in because flags(0x%lx) on !\n", pAd->Flags));
}
DBGPRINT_RAW(RT_DEBUG_TRACE, ("CmdThread : CMDTHREAD_RESET_BULK_IN <===\n"));
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS SetAsicWcidHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
RT_SET_ASIC_WCID SetAsicWcid;
USHORT offset;
UINT32 MACValue, MACRValue = 0;
SetAsicWcid = *((PRT_SET_ASIC_WCID)(CMDQelmt->buffer));
if (SetAsicWcid.WCID >= MAX_LEN_OF_MAC_TABLE)
return NDIS_STATUS_FAILURE;
offset = MAC_WCID_BASE + ((UCHAR)SetAsicWcid.WCID)*HW_WCID_ENTRY_SIZE;
DBGPRINT_RAW(RT_DEBUG_TRACE, ("CmdThread : CMDTHREAD_SET_ASIC_WCID : WCID = %ld, SetTid = %lx, DeleteTid = %lx.\n",
SetAsicWcid.WCID, SetAsicWcid.SetTid, SetAsicWcid.DeleteTid));
MACValue = (pAd->MacTab.Content[SetAsicWcid.WCID].Addr[3]<<24)+(pAd->MacTab.Content[SetAsicWcid.WCID].Addr[2]<<16)+(pAd->MacTab.Content[SetAsicWcid.WCID].Addr[1]<<8)+(pAd->MacTab.Content[SetAsicWcid.WCID].Addr[0]);
DBGPRINT_RAW(RT_DEBUG_TRACE, ("1-MACValue= %x,\n", MACValue));
RTUSBWriteMACRegister(pAd, offset, MACValue, FALSE);
/* Read bitmask*/
RTUSBReadMACRegister(pAd, offset+4, &MACRValue);
if ( SetAsicWcid.DeleteTid != 0xffffffff)
MACRValue &= (~SetAsicWcid.DeleteTid);
if (SetAsicWcid.SetTid != 0xffffffff)
MACRValue |= (SetAsicWcid.SetTid);
MACRValue &= 0xffff0000;
MACValue = (pAd->MacTab.Content[SetAsicWcid.WCID].Addr[5]<<8)+pAd->MacTab.Content[SetAsicWcid.WCID].Addr[4];
MACValue |= MACRValue;
RTUSBWriteMACRegister(pAd, offset+4, MACValue, FALSE);
DBGPRINT_RAW(RT_DEBUG_TRACE, ("2-MACValue= %x,\n", MACValue));
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS DelAsicWcidHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
RT_SET_ASIC_WCID SetAsicWcid;
SetAsicWcid = *((PRT_SET_ASIC_WCID)(CMDQelmt->buffer));
if (SetAsicWcid.WCID >= MAX_LEN_OF_MAC_TABLE)
return NDIS_STATUS_FAILURE;
AsicDelWcidTab(pAd, (UCHAR)SetAsicWcid.WCID);
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS SetWcidSecInfoHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
PRT_ASIC_WCID_SEC_INFO pInfo;
pInfo = (PRT_ASIC_WCID_SEC_INFO)CMDQelmt->buffer;
RTMPSetWcidSecurityInfo(pAd,
pInfo->BssIdx,
pInfo->KeyIdx,
pInfo->CipherAlg,
pInfo->Wcid,
pInfo->KeyTabFlag);
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS SetAsicWcidIVEIVHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
PRT_ASIC_WCID_IVEIV_ENTRY pInfo;
pInfo = (PRT_ASIC_WCID_IVEIV_ENTRY)CMDQelmt->buffer;
AsicUpdateWCIDIVEIV(pAd,
pInfo->Wcid,
pInfo->Iv,
pInfo->Eiv);
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS SetAsicWcidAttrHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
PRT_ASIC_WCID_ATTR_ENTRY pInfo;
pInfo = (PRT_ASIC_WCID_ATTR_ENTRY)CMDQelmt->buffer;
AsicUpdateWcidAttributeEntry(pAd,
pInfo->BssIdx,
pInfo->KeyIdx,
pInfo->CipherAlg,
pInfo->Wcid,
pInfo->KeyTabFlag);
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS SETAsicSharedKeyHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
PRT_ASIC_SHARED_KEY pInfo;
pInfo = (PRT_ASIC_SHARED_KEY)CMDQelmt->buffer;
AsicAddSharedKeyEntry(pAd,
pInfo->BssIndex,
pInfo->KeyIdx,
&pInfo->CipherKey);
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS SetAsicPairwiseKeyHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
PRT_ASIC_PAIRWISE_KEY pInfo;
pInfo = (PRT_ASIC_PAIRWISE_KEY)CMDQelmt->buffer;
AsicAddPairwiseKeyEntry(pAd,
pInfo->WCID,
&pInfo->CipherKey);
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS SetPortSecuredHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
STA_PORT_SECURED(pAd);
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS RemovePairwiseKeyHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
UCHAR Wcid = *((PUCHAR)(CMDQelmt->buffer));
AsicRemovePairwiseKeyEntry(pAd, Wcid);
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS SetClientMACEntryHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
PRT_SET_ASIC_WCID pInfo;
pInfo = (PRT_SET_ASIC_WCID)CMDQelmt->buffer;
AsicUpdateRxWCIDTable(pAd, pInfo->WCID, pInfo->Addr);
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS UpdateProtectHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
PRT_ASIC_PROTECT_INFO pAsicProtectInfo;
pAsicProtectInfo = (PRT_ASIC_PROTECT_INFO)CMDQelmt->buffer;
AsicUpdateProtect(pAd, pAsicProtectInfo->OperationMode, pAsicProtectInfo->SetMask,
pAsicProtectInfo->bDisableBGProtect, pAsicProtectInfo->bNonGFExist);
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS SetPSMBitHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
{
USHORT *pPsm = (USHORT *)CMDQelmt->buffer;
MlmeSetPsmBit(pAd, *pPsm);
}
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS ForceWakeUpHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
AsicForceWakeup(pAd, TRUE);
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS ForceSleepAutoWakeupHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
USHORT TbttNumToNextWakeUp;
USHORT NextDtim = pAd->StaCfg.DtimPeriod;
ULONG Now;
NdisGetSystemUpTime(&Now);
NextDtim -= (USHORT)(Now - pAd->StaCfg.LastBeaconRxTime)/pAd->CommonCfg.BeaconPeriod;
TbttNumToNextWakeUp = pAd->StaCfg.DefaultListenCount;
if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM) && (TbttNumToNextWakeUp > NextDtim))
TbttNumToNextWakeUp = NextDtim;
RTMP_SET_PSM_BIT(pAd, PWR_SAVE);
/* if WMM-APSD is failed, try to disable following line*/
AsicSleepThenAutoWakeup(pAd, TbttNumToNextWakeUp);
return NDIS_STATUS_SUCCESS;
}
NTSTATUS QkeriodicExecutHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
StaQuickResponeForRateUpExec(NULL, pAd, NULL, NULL);
return NDIS_STATUS_SUCCESS;
}
#ifdef LED_CONTROL_SUPPORT
static NTSTATUS SetLEDStatusHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
UCHAR LEDStatus = *((PUCHAR)(CMDQelmt->buffer));
RTMPSetLEDStatus(pAd, LEDStatus);
DBGPRINT(RT_DEBUG_TRACE, ("%s: CMDTHREAD_SET_LED_STATUS (LEDStatus = %d)\n",
__FUNCTION__, LEDStatus));
return NDIS_STATUS_SUCCESS;
}
#endif /* LED_CONTROL_SUPPORT */
#ifdef LINUX
#ifdef RT_CFG80211_SUPPORT
static NTSTATUS RegHintHdlr (IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
RT_CFG80211_CRDA_REG_HINT(pAd, CMDQelmt->buffer, CMDQelmt->bufferlength);
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS RegHint11DHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
RT_CFG80211_CRDA_REG_HINT11D(pAd, CMDQelmt->buffer, CMDQelmt->bufferlength);
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS RT_Mac80211_ScanEnd(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
RT_CFG80211_SCAN_END(pAd, FALSE);
return NDIS_STATUS_SUCCESS;
}
static NTSTATUS RT_Mac80211_ConnResultInfom(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
RT_CFG80211_CONN_RESULT_INFORM(pAd,
pAd->MlmeAux.Bssid,
CMDQelmt->buffer, CMDQelmt->bufferlength,
CMDQelmt->buffer, CMDQelmt->bufferlength,
1);
return NDIS_STATUS_SUCCESS;
}
#endif /* RT_CFG80211_SUPPORT */
#endif /* LINUX */
#ifdef STREAM_MODE_SUPPORT
static NTSTATUS UpdateTXChainAddress(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
AsicUpdateTxChainAddress(pAd, CMDQelmt->buffer);
return NDIS_STATUS_SUCCESS;
}
#endif /* STREAM_MODE_SUPPORT */
extern MSG_EVENT_HANDLER msg_event_handler_tb[];
static NTSTATUS CmdRspEventCallback(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
RXFCE_INFO_CMD *pFceInfo = CMDQelmt->buffer;
(*msg_event_handler_tb[pFceInfo->evt_type])(pAd, CMDQelmt->buffer,
CMDQelmt->bufferlength);
return NDIS_STATUS_SUCCESS;
}
typedef NTSTATUS (*CMDHdlr)(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt);
static CMDHdlr CMDHdlrTable[] = {
ResetBulkOutHdlr, /* CMDTHREAD_RESET_BULK_OUT*/
ResetBulkInHdlr, /* CMDTHREAD_RESET_BULK_IN*/
CheckGPIOHdlr, /* CMDTHREAD_CHECK_GPIO */
SetAsicWcidHdlr, /* CMDTHREAD_SET_ASIC_WCID*/
DelAsicWcidHdlr, /* CMDTHREAD_DEL_ASIC_WCID*/
SetClientMACEntryHdlr, /* CMDTHREAD_SET_CLIENT_MAC_ENTRY*/
SetPSMBitHdlr, /* CMDTHREAD_SET_PSM_BIT*/
ForceWakeUpHdlr, /* CMDTHREAD_FORCE_WAKE_UP*/
ForceSleepAutoWakeupHdlr, /* CMDTHREAD_FORCE_SLEEP_AUTO_WAKEUP*/
QkeriodicExecutHdlr, /* CMDTHREAD_QKERIODIC_EXECUT*/
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
#ifdef LED_CONTROL_SUPPORT
SetLEDStatusHdlr, /* CMDTHREAD_SET_LED_STATUS*/
#else
NULL,
#endif /* LED_CONTROL_SUPPORT */
NULL,
/* Security related */
SetWcidSecInfoHdlr, /* CMDTHREAD_SET_WCID_SEC_INFO*/
SetAsicWcidIVEIVHdlr, /* CMDTHREAD_SET_ASIC_WCID_IVEIV*/
SetAsicWcidAttrHdlr, /* CMDTHREAD_SET_ASIC_WCID_ATTR*/
SETAsicSharedKeyHdlr, /* CMDTHREAD_SET_ASIC_SHARED_KEY*/
SetAsicPairwiseKeyHdlr, /* CMDTHREAD_SET_ASIC_PAIRWISE_KEY*/
RemovePairwiseKeyHdlr, /* CMDTHREAD_REMOVE_PAIRWISE_KEY*/
SetPortSecuredHdlr, /* CMDTHREAD_SET_PORT_SECURED*/
NULL,
UpdateProtectHdlr, /* CMDTHREAD_UPDATE_PROTECT*/
#ifdef LINUX
#ifdef RT_CFG80211_SUPPORT
RegHintHdlr,
RegHint11DHdlr,
RT_Mac80211_ScanEnd,
RT_Mac80211_ConnResultInfom,
#else
NULL,
NULL,
NULL,
NULL,
#endif /* RT_CFG80211_SUPPORT */
#else
NULL,
NULL,
NULL,
NULL,
#endif /* LINUX */
NULL,
NULL,
#ifdef STREAM_MODE_SUPPORT
UpdateTXChainAddress, /* CMDTHREAD_UPDATE_TX_CHAIN_ADDRESS */
#else
NULL,
#endif
CmdRspEventCallback, /* CMDTHREAD_RESPONSE_EVENT_CALLBACK */
};
static inline BOOLEAN ValidCMD(IN PCmdQElmt CMDQelmt)
{
SHORT CMDIndex = CMDQelmt->command - CMDTHREAD_FIRST_CMD_ID;
USHORT CMDHdlrTableLength= sizeof(CMDHdlrTable) / sizeof(CMDHdlr);
if ( (CMDIndex >= 0) && (CMDIndex < CMDHdlrTableLength))
{
if (CMDHdlrTable[CMDIndex] > 0)
return TRUE;
else
{
DBGPRINT(RT_DEBUG_ERROR, ("No corresponding CMDHdlr for this CMD(%x)\n", CMDQelmt->command));
return FALSE;
}
}
else
{
DBGPRINT(RT_DEBUG_ERROR, ("CMD(%x) is out of boundary\n", CMDQelmt->command));
return FALSE;
}
}
VOID CMDHandler(
IN PRTMP_ADAPTER pAd)
{
PCmdQElmt cmdqelmt;
NDIS_STATUS NdisStatus = NDIS_STATUS_SUCCESS;
NTSTATUS ntStatus;
/* unsigned long IrqFlags;*/
while (pAd && pAd->CmdQ.size > 0)
{
NdisStatus = NDIS_STATUS_SUCCESS;
NdisAcquireSpinLock(&pAd->CmdQLock);
RTThreadDequeueCmd(&pAd->CmdQ, &cmdqelmt);
NdisReleaseSpinLock(&pAd->CmdQLock);
if (cmdqelmt == NULL)
break;
if(!(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST) || RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)))
{
if(ValidCMD(cmdqelmt))
ntStatus = (*CMDHdlrTable[cmdqelmt->command - CMDTHREAD_FIRST_CMD_ID])(pAd, cmdqelmt);
}
if (cmdqelmt->CmdFromNdis == TRUE)
{
if (cmdqelmt->buffer != NULL)
os_free_mem(pAd, cmdqelmt->buffer);
os_free_mem(pAd, cmdqelmt);
}
else
{
if ((cmdqelmt->buffer != NULL) && (cmdqelmt->bufferlength != 0))
os_free_mem(pAd, cmdqelmt->buffer);
os_free_mem(pAd, cmdqelmt);
}
} /* end of while */
}
VOID RTUSBWatchDog(IN RTMP_ADAPTER *pAd)
{
PHT_TX_CONTEXT pHTTXContext;
int idx;
ULONG irqFlags;
PURB pUrb;
BOOLEAN needDumpSeq = FALSE;
UINT32 MACValue;
if(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
return;
if(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_IDLE_RADIO_OFF))
return;
idx = 0;
RTMP_IO_READ32(pAd, TXRXQ_PCNT, &MACValue);
if ((MACValue & 0xff) !=0 )
{
DBGPRINT(RT_DEBUG_TRACE, ("TX QUEUE 0 Not EMPTY(Value=0x%0x). !!!!!!!!!!!!!!!\n", MACValue));
RTMP_IO_WRITE32(pAd, PBF_CFG, 0xf40012);
while((MACValue &0xff) != 0 && (idx++ < 10))
{
RTMP_IO_READ32(pAd, TXRXQ_PCNT, &MACValue);
RTMPusecDelay(1);
}
RTMP_IO_WRITE32(pAd, PBF_CFG, 0xf40006);
}
idx = 0;
if ((MACValue & 0xff00) !=0 )
{
DBGPRINT(RT_DEBUG_TRACE, ("TX QUEUE 1 Not EMPTY(Value=0x%0x). !!!!!!!!!!!!!!!\n", MACValue));
RTMP_IO_WRITE32(pAd, PBF_CFG, 0xf4000a);
while((MACValue &0xff00) != 0 && (idx++ < 10))
{
RTMP_IO_READ32(pAd, TXRXQ_PCNT, &MACValue);
RTMPusecDelay(1);
}
RTMP_IO_WRITE32(pAd, PBF_CFG, 0xf40006);
}
if (pAd->watchDogRxOverFlowCnt >= 2)
{
DBGPRINT(RT_DEBUG_TRACE, ("Maybe the Rx Bulk-In hanged! Cancel the pending Rx bulks request!\n"));
if ((!RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS |
fRTMP_ADAPTER_BULKIN_RESET |
fRTMP_ADAPTER_HALT_IN_PROGRESS |
fRTMP_ADAPTER_NIC_NOT_EXIST))))
{
DBGPRINT(RT_DEBUG_TRACE, ("Call CMDTHREAD_RESET_BULK_IN to cancel the pending Rx Bulk!\n"));
RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKIN_RESET);
RTEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_IN, NULL, 0);
needDumpSeq = TRUE;
}
pAd->watchDogRxOverFlowCnt = 0;
}
for (idx = 0; idx < NUM_OF_TX_RING; idx++)
{
pUrb = NULL;
RTMP_IRQ_LOCK(&pAd->BulkOutLock[idx], irqFlags);
/* if ((pAd->BulkOutPending[idx] == TRUE) && pAd->watchDogTxPendingCnt)*/
if (pAd->BulkOutPending[idx] == TRUE)
{
pAd->watchDogTxPendingCnt[idx]++;
if ((pAd->watchDogTxPendingCnt[idx] > 2) &&
(!RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS | fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST | fRTMP_ADAPTER_BULKOUT_RESET)))
)
{
/* FIXME: Following code just support single bulk out. If you wanna support multiple bulk out. Modify it!*/
pHTTXContext = (PHT_TX_CONTEXT)(&pAd->TxContext[idx]);
if (pHTTXContext->IRPPending)
{ /* Check TxContext.*/
pUrb = pHTTXContext->pUrb;
}
else if (idx == MGMTPIPEIDX)
{
PTX_CONTEXT pMLMEContext, pNULLContext, pPsPollContext;
/*Check MgmtContext.*/
pMLMEContext = (PTX_CONTEXT)(pAd->MgmtRing.Cell[pAd->MgmtRing.TxDmaIdx].AllocVa);
pPsPollContext = (PTX_CONTEXT)(&pAd->PsPollContext);
pNULLContext = (PTX_CONTEXT)(&pAd->NullContext);
if (pMLMEContext->IRPPending)
{
ASSERT(pMLMEContext->IRPPending);
pUrb = pMLMEContext->pUrb;
}
else if (pNULLContext->IRPPending)
{
ASSERT(pNULLContext->IRPPending);
pUrb = pNULLContext->pUrb;
}
else if (pPsPollContext->IRPPending)
{
ASSERT(pPsPollContext->IRPPending);
pUrb = pPsPollContext->pUrb;
}
}
RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[idx], irqFlags);
DBGPRINT(RT_DEBUG_TRACE, ("Maybe the Tx Bulk-Out hanged! Cancel the pending Tx bulks request of idx(%d)!\n", idx));
if (pUrb)
{
DBGPRINT(RT_DEBUG_TRACE, ("Unlink the pending URB!\n"));
/* unlink it now*/
RTUSB_UNLINK_URB(pUrb);
/* Sleep 200 microseconds to give cancellation time to work*/
RTMPusecDelay(200);
needDumpSeq = TRUE;
}
else
{
DBGPRINT(RT_DEBUG_ERROR, ("Unkonw bulkOut URB maybe hanged!!!!!!!!!!!!\n"));
}
}
else
{
RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[idx], irqFlags);
}
}
else
{
RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[idx], irqFlags);
}
}
#ifdef DOT11_N_SUPPORT
/* For Sigma debug, dump the ba_reordering sequence.*/
if((needDumpSeq == TRUE) && (pAd->CommonCfg.bDisableReordering == 0))
{
USHORT Idx;
PBA_REC_ENTRY pBAEntry = NULL;
UCHAR count = 0;
struct reordering_mpdu *mpdu_blk;
Idx = pAd->MacTab.Content[BSSID_WCID].BARecWcidArray[0];
pBAEntry = &pAd->BATable.BARecEntry[Idx];
if((pBAEntry->list.qlen > 0) && (pBAEntry->list.next != NULL))
{
DBGPRINT(RT_DEBUG_TRACE, ("NICUpdateRawCounters():The Queueing pkt in reordering buffer:\n"));
NdisAcquireSpinLock(&pBAEntry->RxReRingLock);
mpdu_blk = pBAEntry->list.next;
while (mpdu_blk)
{
DBGPRINT(RT_DEBUG_TRACE, ("\t%d:Seq-%d, bAMSDU-%d!\n", count, mpdu_blk->Sequence, mpdu_blk->bAMSDU));
mpdu_blk = mpdu_blk->next;
count++;
}
DBGPRINT(RT_DEBUG_TRACE, ("\npBAEntry->LastIndSeq=%d!\n", pBAEntry->LastIndSeq));
NdisReleaseSpinLock(&pBAEntry->RxReRingLock);
}
}
#endif /* DOT11_N_SUPPORT */
}
#endif /* RTMP_MAC_USB */
|
the_stack_data/943826.c | #include <assert.h>
int main(int argc, char *argv[])
{
// Test how well we can represent pointers to structs
struct int_float
{
int a;
float b;
};
struct int_float x={0, 1.0};
x.a=0;
x.b=1.0;
struct int_float *p=&x;
__CPROVER_assert((*p).a == 0, "(*p).a==0");
__CPROVER_assert((*p).a == 1, "(*p).a==1");
// Test alternative syntax
__CPROVER_assert(p->a == 0, "p->a==0");
__CPROVER_assert(p->a == 1, "p->a==1");
// Test writing to the struct through the pointer
p->b=2.0;
__CPROVER_assert(p->b == 2.0, "p->b==2.0");
__CPROVER_assert(p->b == 1.0, "p->b==1.0");
// pointers to components
int *comp_p = &x.a;
__CPROVER_assert(comp_p == &x.a, "comp_p==&x.a");
__CPROVER_assert(comp_p == &x.b, "comp_p==&x.b");
__CPROVER_assert(*comp_p == 0, "*comp_p==0");
__CPROVER_assert(*comp_p == 1, "*comp_p==1");
float *compb_p = &x.b;
__CPROVER_assert(compb_p == &x.a, "compb_p==&x.a");
__CPROVER_assert(compb_p == &x.b, "compb_p==&x.b");
__CPROVER_assert(*compb_p == 2.0, "*compb_p==2.0");
__CPROVER_assert(*compb_p == 1.0, "*compb_p==1.0");
// Use pointer implicitly pointing at the first component
int *implicit_p = &x;
__CPROVER_assert(implicit_p == &x.a, "implicit_p==&x.a");
__CPROVER_assert(implicit_p == &x, "implicit_p==&x");
__CPROVER_assert(*implicit_p == 0, "*implicit_p==0");
__CPROVER_assert(*implicit_p == 1, "*implicit_p==1");
// Write through pointer implicitly pointing at the first component
*implicit_p = 5;
__CPROVER_assert(x.a == 5, "x.a==5");
__CPROVER_assert(x.a == 1, "x.a==1");
return 0;
}
|
the_stack_data/103265667.c | /*****************************************************************************
* Name: write_struct.c
*
* Summary: Demo of writing structs to file.
*
* Adapted: Fri, 22 Dec 2000 19:24:00 (Bob Heckel -- from New C Primer Plus
* Prata p. 494)
* Modified: Mon 22 Oct 2001 10:14:17 (Bob Heckel -- direct assignment to
* structs)
*****************************************************************************
*/
#include <stdio.h>
#include <stdlib.h>
#define MAXTIT 40
#define MAXAUT 40
#define MAXBKS 3
/* Set up template. */
struct bookstruct {
char title[MAXTIT];
char author[MAXAUT];
float value;
};
int main(void) {
/* Array of structs. */
struct bookstruct mylibr[MAXBKS];
int count = 0;
int index;
int filecount;
FILE *pbooks;
int size = sizeof(struct bookstruct);
/* Assign directly to a struct. Use this form to initialize an *array* of
* structs:
* struct mylibr[MAXBKS] = { {"title1", "auth1", 66.01}, {"title2", "auth2", 66.02} };
*/
struct bookstruct the_bkstruct = { "my_title", "my_auth", 42.66 };
printf("Testing direct assignment before we get started %.3f %s\n\n",
the_bkstruct.value,
the_bkstruct.author);
if ( (pbooks = fopen("junk.dat", "a+b")) == NULL ) {
fputs("Can't open junk.dat\n", stderr);
exit(1);
}
rewind(pbooks);
while ( count < MAXBKS && fread(&mylibr[count], size, 1, pbooks) == 1 ) {
if ( count == 0 )
puts("Current contents:");
printf("%s by %s: $%.2f\n", mylibr[count].title,
mylibr[count].author,
mylibr[count].value);
count++;
}
filecount = count;
if ( count == MAXBKS ) {
fputs("The junk.dat file is full\n", stderr);
exit(2);
}
puts("Enter new title, enter a blank line to stop.");
while ( count < MAXBKS && gets(mylibr[count].title) != NULL
&& mylibr[count].title[0] != '\0' ) {
puts("Now enter author");
gets(mylibr[count].author);
puts("Now enter value");
scanf("%f", &mylibr[count++].value);
while ( getchar() != '\n' )
continue;
if ( count < MAXBKS )
puts("Enter next title");
}
puts("Here are your bks");
for ( index=0; index<count; index++ )
printf("%s by %s: $%.2f\n", mylibr[index].title,
mylibr[index].author,
mylibr[index].value);
/* Go to end of file. */
fseek(pbooks, 0L, SEEK_END);
fwrite(&mylibr[filecount], size, count-filecount, pbooks);
fclose(pbooks);
return 0;
}
|
the_stack_data/212644251.c | /* shm_unlink -- remove a POSIX shared memory object. Generic POSIX version.
Copyright (C) 2001,2002,2005 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <unistd.h>
#if ! _POSIX_MAPPED_FILES
#include <rt/shm_unlink.c>
#else
#include <errno.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <paths.h>
#define SHMDIR (_PATH_DEV "shm/")
/* Remove shared memory object. */
int
shm_unlink (const char *name)
{
size_t namelen;
char *fname;
/* Construct the filename. */
while (name[0] == '/')
++name;
if (name[0] == '\0')
{
/* The name "/" is not supported. */
__set_errno (EINVAL);
return -1;
}
namelen = strlen (name);
fname = (char *) __alloca (sizeof SHMDIR - 1 + namelen + 1);
__mempcpy (__mempcpy (fname, SHMDIR, sizeof SHMDIR - 1),
name, namelen + 1);
return unlink (name);
}
#endif
|
the_stack_data/36075148.c | #include<stdio.h>
int main()
{
int i, j, rowNum, space;
printf("Enter the Number of Rows:"); //Size of Diamond
scanf("%d",&rowNum);
space = rowNum-1;
for(i=1; i<=rowNum; i++)
{
for(j=1; j<=space; j++) //For Upper Half Of The Diamomd
printf(" ");
space--;
for(j=1; j<=(2*i-1); j++)
printf("*");
printf("\n");
}
space = 1;
for(i=1; i<=(rowNum-1); i++)
{
for(j=1; j<=space; j++) //For Lower Half Of The Diamomd
printf(" ");
space++;
for(j=1; j<=(2*(rowNum-i)-1); j++)
printf("*");
printf("\n");
}
printf("\n");
return 0;
}
|
the_stack_data/150144256.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct drag{
int st;
int bon;
} drag;
int comp(const void *a, const void *b){
const drag *A = a, *B = b;
return A->st - B->st;
}
int main(){
int stren, ndrag;
scanf("%d%d", &stren, &ndrag);
drag *lista = malloc(sizeof(drag) * ndrag);
for(int i = 0; i < ndrag; ++i){
scanf("%d%d", &lista[i].st, &lista[i].bon);
}
qsort(lista, ndrag, sizeof(drag), comp);
for(int i = 0; i < ndrag; ++i){
if(stren > lista[i].st) stren += lista[i].bon;
else{
stren = -1;
break;
}
}
if(stren == -1){
printf("NO\n");
}else {
printf("YES\n");
}
} |
the_stack_data/28262708.c | #include <stdio.h>
int function(char *);
int main()
{
function("Hello World\n");
return 0;
}
|
the_stack_data/396651.c | extern void def(void *, unsigned int);
static int bar(void)
{
int x[2] = { 1, 2 };
def(x, sizeof(x));
return x[1];
}
/*
* check-name: eval/addressable-degen
* check-command: test-linearize -fdump-ir $file
*
* check-output-ignore
* check-output-contains: load\\.
*/
|
the_stack_data/28263480.c | // Copyright (c) 2017-2018 Intel Corporation
//
// 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.
#if defined(LINUX32)
#include <sys/time.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <assert.h>
#include "vm_event.h"
static void vm_event_set_invalid_internal(vm_event *event)
{
memset(event, 0, sizeof(vm_event));
event->state = -1;
}
/* Invalidate an event */
void vm_event_set_invalid(vm_event *event)
{
/* check error(s) */
if (NULL == event)
return;
vm_event_set_invalid_internal(event);
} /* void vm_event_set_invalid(vm_event *event) */
/* Verify if an event is valid */
int32_t vm_event_is_valid(vm_event *event)
{
/* check error(s) */
if (NULL == event)
return 0;
return event->state >= 0;
} /* int32_t vm_event_is_valid(vm_event *event) */
/* Init an event. Event is created unset. return 1 if success */
vm_status vm_event_init(vm_event *event, int32_t manual, int32_t state)
{
int res = 0;
/* check error(s) */
if (NULL == event)
return VM_NULL_PTR;
event->manual = manual;
event->state = state ? 1 : 0;
res = pthread_cond_init(&event->cond, 0);
if (!res)
{
res = pthread_mutex_init(&event->mutex, 0);
if (res)
{
int cres = pthread_cond_destroy(&event->cond);
assert(!cres); // we experienced undefined behavior
vm_event_set_invalid_internal(event);
}
}
return (res)? VM_OPERATION_FAILED: VM_OK;
} /* vm_status vm_event_init(vm_event *event, int32_t manual, int32_t state) */
vm_status vm_event_named_init(vm_event * event,
int32_t manual, int32_t state, const char * pcName)
{
(void)event;
(void)manual;
(void)state;
(void)pcName;
/* linux version of named events is not supported by now */
return VM_OPERATION_FAILED;
} /* vm_status vm_event_named_init(vm_event *event, */
/* Set the event to either HIGH (1) or LOW (0) state */
vm_status vm_event_signal(vm_event *event)
{
vm_status umc_status = VM_NOT_INITIALIZED;
int res = 0;
/* check error(s) */
if (NULL == event)
return VM_NULL_PTR;
if (0 <= event->state)
{
res = pthread_mutex_lock(&event->mutex);
if (!res)
{
umc_status = VM_OK;
if (0 == event->state)
{
event->state = 1;
if (event->manual)
{
res = pthread_cond_broadcast(&event->cond);
if (res)
{
umc_status = VM_OPERATION_FAILED;
}
}
else
{
res = pthread_cond_signal(&event->cond);
if (res)
{
umc_status = VM_OPERATION_FAILED;
}
}
}
if (0 != pthread_mutex_unlock(&event->mutex))
{
umc_status = VM_OPERATION_FAILED;
}
}
else
{
umc_status = VM_OPERATION_FAILED;
}
}
return umc_status;
} /* vm_status vm_event_signal(vm_event *event) */
vm_status vm_event_reset(vm_event *event)
{
vm_status umc_status = VM_NOT_INITIALIZED;
int res = 0;
/* check error(s) */
if (NULL == event)
return VM_NULL_PTR;
if (0 <= event->state)
{
res = pthread_mutex_lock(&event->mutex);
if (!res)
{
umc_status = VM_OK;
if (1 == event->state)
event->state = 0;
if (0 != pthread_mutex_unlock(&event->mutex))
{
umc_status = VM_OPERATION_FAILED;
}
}
else
{
umc_status = VM_OPERATION_FAILED;
}
}
return umc_status;
} /* vm_status vm_event_reset(vm_event *event) */
/* Pulse the event 0 -> 1 -> 0 */
vm_status vm_event_pulse(vm_event *event)
{
vm_status umc_status = VM_NOT_INITIALIZED;
int res = 0;
/* check error(s) */
if (NULL == event)
return VM_NULL_PTR;
if (0 <= event->state)
{
res = pthread_mutex_lock(&event->mutex);
if (!res)
{
umc_status = VM_OK;
if (event->manual)
{
res = pthread_cond_broadcast(&event->cond);
if (res)
{
umc_status = VM_OPERATION_FAILED;
}
}
else
{
res = pthread_cond_signal(&event->cond);
if (res)
{
umc_status = VM_OPERATION_FAILED;
}
}
event->state = 0;
if (0 != pthread_mutex_unlock(&event->mutex))
{
umc_status = VM_OPERATION_FAILED;
}
}
else
{
umc_status = VM_OPERATION_FAILED;
}
}
return umc_status;
} /* vm_status vm_event_pulse(vm_event *event) */
/* Wait for event to be high with blocking */
vm_status vm_event_wait(vm_event *event)
{
vm_status umc_status = VM_NOT_INITIALIZED;
int res;
/* check error(s) */
if (NULL == event)
return VM_NULL_PTR;
if (0 <= event->state)
{
res = pthread_mutex_lock(&event->mutex);
if (!res)
{
umc_status = VM_OK;
if (!event->state)
{
while (!res && !event->state)
{
res = pthread_cond_wait(&event->cond,&event->mutex);
}
if (res)
{
umc_status = VM_OPERATION_FAILED;
}
}
if (!event->manual)
event->state = 0;
if (0 != pthread_mutex_unlock(&event->mutex))
{
umc_status = VM_OPERATION_FAILED;
}
}
else
{
umc_status = VM_OPERATION_FAILED;
}
}
return umc_status;
} /* vm_status vm_event_wait(vm_event *event) */
/* Wait for event to be high without blocking, return 1 if successful */
vm_status vm_event_timed_wait(vm_event *event, uint32_t msec)
{
vm_status umc_status = VM_NOT_INITIALIZED;
int res = 0;
/* check error(s) */
if (NULL == event)
return VM_NULL_PTR;
if (0 <= event->state)
{
res = pthread_mutex_lock(&event->mutex);
if (!res)
{
if (0 == event->state)
{
if (0 == msec)
{
umc_status = VM_TIMEOUT;
}
else
{
struct timeval tval;
struct timespec tspec;
int32_t i_res;
unsigned long long micro_sec;
gettimeofday(&tval, NULL);
// NOTE: micro_sec _should_ be unsigned long long, not uint32_t to avoid overflow
micro_sec = 1000 * msec + tval.tv_usec;
tspec.tv_sec = tval.tv_sec + (uint32_t)(micro_sec / 1000000);
tspec.tv_nsec = (uint32_t)(micro_sec % 1000000) * 1000;
i_res = 0;
while (!i_res && !event->state)
{
i_res = pthread_cond_timedwait(&event->cond,
&event->mutex,
&tspec);
}
if (0 == i_res)
umc_status = VM_OK;
else if (ETIMEDOUT == i_res)
umc_status = VM_TIMEOUT;
else
umc_status = VM_OPERATION_FAILED;
}
}
else
umc_status = VM_OK;
if (!event->manual)
event->state = 0;
}
else
{
umc_status = VM_OPERATION_FAILED;
}
if(pthread_mutex_unlock(&event->mutex))
{
umc_status = VM_OPERATION_FAILED;
}
}
return umc_status;
} /* vm_status vm_event_timed_wait(vm_event *event, uint32_t msec) */
/* Destory the event */
void vm_event_destroy(vm_event *event)
{
/* check error(s) */
if (NULL == event)
return;
if (event->state >= 0)
{
int res = pthread_cond_destroy(&event->cond);
assert(!res); // we experienced undefined behavior
res = pthread_mutex_destroy(&event->mutex);
assert(!res); // we experienced undefined behavior
vm_event_set_invalid_internal(event);
}
} /* void vm_event_destroy(vm_event *event) */
#else
# pragma warning( disable: 4206 )
#endif /* LINUX32 */
|
the_stack_data/14200754.c | a, b, c, d;
e(f) {
int g;
h(f ? b : a);
for (; c && g;)
for (; c < d; g++)
if (f)
i();
if (d)
j(f == 0);
if (c)
k();
}
|
the_stack_data/151705677.c | #include <stdio.h>
#include <pthread.h>
struct struct_print_chars {
char c;
int count;
};
void* print_chars(void* in) {
printf("Created thread");
struct struct_print_chars* sPC = (struct struct_print_chars*) in;
int i = 0;
for (i = 0; i < sPC->count; ++i) {
fputc(sPC->c, stderr);
}
return NULL;
}
int main(int argc, char* argv[]) {
pthread_t thread1;
pthread_t thread2;
struct struct_print_chars param_1;
struct struct_print_chars param_2;
param_1.c = '*';
param_1.count = 200;
param_2.c = '=';
param_2.count = 400;
pthread_create(&thread1, NULL, &print_chars, ¶m_1);
pthread_create(&thread2, NULL, &print_chars, ¶m_2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
|
the_stack_data/129009.c | /* Studente: Lorenzo Gezzi
Classe:3INA
Data:15/04/2017
Versione: 1.0
*/
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
char parola1[100];
char parola2[100];
int i;
int uguali;
printf("Inserire la prima parola ");
scanf("%s",parola1);
printf("\nInserire la seconda parola ");
scanf("%s",parola2);
i=0;
uguali=1;
while((uguali==1)&&(parola1[i]!='\0'||parola2[i]!='\0')){
if(parola1[i]!=parola2[i]){
uguali=0;
}
i++;
}
if(uguali==1){
printf("\nLe due parole sono uguali");
}
else{
printf("\nLe due parole sono diverse");
}
printf("\n");
system("PAUSE");
}
|
the_stack_data/7950145.c | /*
Função: Ler a velocidade em Km/h e converter para m/s
Autor: Gabriel Maciel dos Santos
Data: 11/03/18
*/
#include <stdio.h>
int main(){
float km, ms;
printf("Informe a velocidade em Km/h:\n");
scanf("%f", &km);
ms = (km / 3.6);
printf("A velocidade em m/s: %.2f\n", ms);
return 0;
}
|
the_stack_data/1156050.c | /*
* Copyright (c) 1983 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char rcsid[] = "$OpenBSD: signame.c,v 1.2 1996/08/19 08:26:11 tholo Exp $";
#endif /* LIBC_SCCS and not lint */
#include <signal.h>
#include <unistd.h>
const char *const sys_signame[NSIG] = {
"Signal 0",
"HUP", /* SIGHUP */
"INT", /* SIGINT */
"QUIT", /* SIGQUIT */
"ILL", /* SIGILL */
"TRAP", /* SIGTRAP */
"ABRT", /* SIGABRT */
"EMT", /* SIGEMT */
"FPE", /* SIGFPE */
"KILL", /* SIGKILL */
"BUS", /* SIGBUS */
"SEGV", /* SIGSEGV */
"SYS", /* SIGSYS */
"PIPE", /* SIGPIPE */
"ALRM", /* SIGALRM */
"TERM", /* SIGTERM */
"URG", /* SIGURG */
"STOP", /* SIGSTOP */
"TSTP", /* SIGTSTP */
"CONT", /* SIGCONT */
"CHLD", /* SIGCHLD */
"TTIN", /* SIGTTIN */
"TTOU", /* SIGTTOU */
"IO", /* SIGIO */
"XCPU", /* SIGXCPU */
"XFSZ", /* SIGXFSZ */
"VTALRM", /* SIGVTALRM */
"PROF", /* SIGPROF */
"WINCH", /* SIGWINCH */
"INFO", /* SIGINFO */
"USR1", /* SIGUSR1 */
"USR2" /* SIGUSR2 */
};
|
the_stack_data/1078763.c | #include <stdio.h>
int diff(FILE *, FILE *);
int main(int argc, char * argv[]) {
FILE * f1, * f2;
if(argc >= 3) {
if(f1 = fopen(argv[1], "r")) {
if(f2 = fopen(argv[2], "r")) {
printf("%d\n", diff(f1, f2));
fclose(f1); fclose(f2);
} else {
printf("Error opening file 2\n");
fclose(f1);
}
} else
printf("Error opening file 1\n");
} else
printf("Not enough args\n");
return 0;
}
int diff(FILE * f1, FILE * f2) {
int eq;
char c1, c2;
eq = 1;
c1 = getc(f1);
c2 = getc(f2);
while(!feof(f1) && !feof(f2) && eq) {
eq = c1==c2;
c1 = getc(f1);
c2 = getc(f2);
}
if((c1==EOF && c2!=EOF) || (c1!=EOF && c2==EOF))
eq = 0;
printf("\n%d\t\n", eq);
return eq;
}
|
the_stack_data/125139460.c | #include <stdio.h>
int invert_end(int num, int bits);
int main(int argc, char *argv[])
{
int m = 4, num = 0;
puts("Enter a number :");
scanf("%d", &num);
while(getchar()!= 10);
printf("num ^ mask = %d\n", invert_end(num, m) );
return 0;
}
int invert_end(int num, int bits)
{
int mask = 0, bitval = 1;
while ( bits-- > 0)
{
mask |= bitval;
bitval <<= 1;
}
return num ^ mask;
} |
the_stack_data/128381.c | int a;
int b;
int c;
int d;
int * p;
int * q;
int * r;
int ** pq;
int ** pp;
void (*fptr)(int**);
void callee1(int ** ptr1)
{
*ptr1 = q;
}
void callee2(int ** ptr2)
{
*ptr2 = r;
}
void caller()
{
fptr(pp);
}
void setup()
{
q = &a;
r = &b;
pp = &p;
fptr = &callee1;
fptr = &callee2;
}
|
the_stack_data/148576756.c | // https://syzkaller.appspot.com/bug?id=6bf66320a69bdd28d53479163fb54fdd3187b2a6
// 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[1] = {0xffffffffffffffff};
int main(void)
{
syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul);
syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul);
intptr_t res = 0;
memcpy((void*)0x200000c0, "/dev/vbi#\000", 10);
res = -1;
res = syz_open_dev(0x200000c0, 1, 2);
if (res != -1)
r[0] = res;
*(uint32_t*)0x20000000 = 7;
*(uint32_t*)0x20000004 = 5;
*(uint32_t*)0x20000008 = 2;
*(uint32_t*)0x2000000c = 0;
*(uint32_t*)0x20000010 = 0;
syscall(__NR_ioctl, r[0], 0xc0145608, 0x20000000ul);
*(uint32_t*)0x20000140 = 0;
*(uint32_t*)0x20000144 = 5;
*(uint32_t*)0x20000148 = 4;
*(uint32_t*)0x2000014c = 0;
*(uint32_t*)0x20000150 = 0;
*(uint64_t*)0x20000158 = 0;
*(uint64_t*)0x20000160 = 0;
*(uint32_t*)0x20000168 = 0;
*(uint32_t*)0x2000016c = 0;
*(uint8_t*)0x20000170 = 0;
*(uint8_t*)0x20000171 = 0;
*(uint8_t*)0x20000172 = 0;
*(uint8_t*)0x20000173 = 0;
memcpy((void*)0x20000174, "\xbc\x4c\x74\xc7", 4);
*(uint32_t*)0x20000178 = 0;
*(uint32_t*)0x2000017c = 2;
*(uint32_t*)0x20000180 = 0x400040;
*(uint32_t*)0x20000188 = 0x10feff;
*(uint32_t*)0x2000018c = 0;
*(uint32_t*)0x20000190 = -1;
syscall(__NR_ioctl, r[0], 0xc058560f, 0x20000140ul);
return 0;
} |
the_stack_data/20630.c | /****************************************************************************//**
\file spiMemInterface.c
\brief Implementation of external spi memory interface.
\author
Atmel Corporation: http://www.atmel.com \n
Support email: [email protected]
Copyright (c) 2008-2013, Atmel Corporation. All rights reserved.
Licensed under Atmel's Limited License Agreement (BitCloudTM).
\internal
History:
14/08/09 A. Khromykh - Created
*******************************************************************************/
/******************************************************************************
Includes section
******************************************************************************/
#ifdef EXT_MEMORY
#include <spiMemInterface.h>
/******************************************************************************
Define(s) section
******************************************************************************/
#define UCPHA0 1
#define UCPOL0 0
/******************************************************************************
Implementations section
******************************************************************************/
/**************************************************************************//**
\brief Initializes usart as spi.
******************************************************************************/
void spiMemInit(void)
{
// Set MSPI mode
UCSRCSPI = (1 << UMSEL01) | (1 << UMSEL00);
// Set spi mode 3 and MSB order
UCSRCSPI |= (1 << UCPOL0) | (1 << UCPHA0);
// Set sck pin as output
GPIO_XCK_make_out();
// Enable receiver and transmitter
UCSRBSPI = (1 << RXEN0) | (1 << TXEN0);
// Set maximum baud rate
UBRRSPI = 0;
// Set cs pin as output
GPIO_EXT_MEM_CS_make_out();
GPIO_EXT_MEM_CS_set();
}
/**************************************************************************//**
\brief Writes or reads a length bytes from the external spi memory.
\param[in]
type - transaction type;
\param[in]
buffer - pointer to the data buffer;
\param[in]
length - number bytes for transfer;
******************************************************************************/
void spiMemTransac(TransactionType_t type, uint8_t *buffer, uint16_t length)
{
uint16_t i;
uint8_t temp;
wdt_reset();
for (i = 0; i < length; i++)
{
// Wait for empty transmit buffer
while (!(UCSRASPI & (1 << UDRE0)));
// Send data
UDRSPI = *(buffer + i);
// Wait for data to be received
while (!(UCSRASPI & (1 << RXC0)));
// receives data to clear received usart buffer
if (SPI_TRANSACTION_TYPE_WRITE == type)
temp = UDRSPI;
else
*(buffer + i) = UDRSPI;
}
(void)temp;
}
#endif //EXT_MEMORY
// eof spiMemInterface.c
|
the_stack_data/234518056.c | #include <assert.h>
#include <stdio.h>
int main() {
FILE* file = fopen("/sandbox/input.txt", "r");
assert(file != NULL);
char c = fgetc(file);
while (c != EOF) {
int wrote = fputc(c, stdout);
assert(wrote != EOF);
c = fgetc(file);
}
}
|
the_stack_data/15761898.c | // Copyright (c) 2020, devgo.club
// All rights reserved.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
struct student
{
struct
{
int64_t id;
int64_t coin;
};
int64_t work_years;
};
int main(int argc, char const *argv[])
{
struct student s =
{
{
.id = 135,
.coin = 1024,
},
.work_years = 10,
};
printf("s: id=%ld, coin=%ld, work_years=%ld\n", s.id, s.coin, s.work_years);
return EXIT_SUCCESS;
} |
the_stack_data/127397.c | #include <stdio.h>
int main(void)
{
printf(" ( )\n");
printf(" (oo)\n");
printf(" /-------\\/\n");
printf(" / | %%%% ||\n");
printf("* ||----|| \n");
printf(" \"\" \"\"\n");
return 0;
}
|
the_stack_data/190769443.c | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
char * skipspaces (char * p)
{
while (*p == ' ' || *p == '\t') ++p;
return p;
}
int findit(char * str)
{
str = skipspaces(str);
return !strncmp(str, "PROCEDURE", 9) || !strncmp(str, "VAR", 3) ||
!strncmp(str, "TYPE", 4) || !strncmp(str, "CONST", 5);
}
int endofmodule(char * str, char * nmod)
{
str = skipspaces(str);
if (!strncmp(str, "END", 3))
{
str += 3;
str = skipspaces(str);
if (!strncmp(str, nmod, strlen(nmod)))
{
str += strlen(nmod);
str = skipspaces(str);
return *str == '.';
}
return 0;
}
else return 0;
}
void main()
{
FILE * fi, * fo;
char listname[] = "build\\list";
char outname[] = "os9k.def";
char modulename[]="os9k";
char pragmas[] = "build\\pragmas";
char list[40][40];
int j, i = 0;
char buffer[256];
/* reading the listfile */
fi = fopen(listname, "r");
if (!fi) { printf("Error: file %s not found", listname); exit(1); }
while (fscanf(fi,"%s", list[i]) != EOF) i++;
fclose(fi);
fo = fopen(outname, "w");
if (!fo) { printf("Error: file %s could not be opened for writing", outname); exit(1);}
fi = fopen(pragmas, "r");
if (!fi) { printf("Error: file %s not found", pragmas); exit(1); }
while (fgets(buffer, 256, fi))
{ int error;
error = fputs(buffer, fo);
if (error==EOF)
{ printf("Error: cannot write to %s file", outname);
exit(1);
}
}
fclose(fi);
fprintf(fo, "DEFINITION MODULE [\"C\"] %s;\n", modulename);
fprintf(fo,"\nIMPORT SYSTEM;\n");
for (j=0; j<i; j++)
{ /* fopen the regular file and add its body to our file */
char fname[40+4];
strcpy(fname, list[j]);
fi = fopen(strcat(fname,".def"), "r");
if (!fi)
{ printf("Error: file %s not found", fname);
exit(1);
}
/* Search the string begining with PROCEDURE or VAR or TYPE */
while (!findit(fgets(buffer, 256, fi)));
while (!endofmodule(buffer, list[j]))
{ /* process the buffer and output it */
char * bufpoint = buffer;
char outputstr[256];
char * outpoint = outputstr;
int k;
while (*bufpoint)
{
for (k = 0; k<i; k++)
{
int length;
length = strlen(list[k]);
if (!strncmp(bufpoint, list[k], length) && bufpoint[length] =='.')
bufpoint += length+1;
}
*(outpoint++) = *(bufpoint++);
}
*outpoint = '\0';
fputs(outputstr, fo);
fgets(buffer, 256, fi);
}
fclose(fi);
}
fprintf(fo,"END %s.\n", modulename);
fclose(fo);
} |
the_stack_data/234517040.c | /* Capstone Disassembly Engine */
/* By Nguyen Anh Quynh, 2018 */
#ifdef CAPSTONE_HAS_EVM
#include "../../cs_priv.h"
#include "EVMDisassembler.h"
#include "EVMInstPrinter.h"
#include "EVMMapping.h"
#include "EVMModule.h"
cs_err EVM_global_init(cs_struct *ud)
{
// verify if requested mode is valid
if (ud->mode)
return CS_ERR_MODE;
ud->printer = EVM_printInst;
ud->printer_info = NULL;
ud->insn_id = EVM_get_insn_id;
ud->insn_name = EVM_insn_name;
ud->group_name = EVM_group_name;
ud->disasm = EVM_getInstruction;
return CS_ERR_OK;
}
cs_err EVM_option(cs_struct *handle, cs_opt_type type, size_t value)
{
return CS_ERR_OK;
}
#endif
|
the_stack_data/211081932.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error(); }; return; }
int __global_lock;
void __VERIFIER_atomic_begin() { __VERIFIER_assume(__global_lock==0); __global_lock=1; return; }
void __VERIFIER_atomic_end() { __VERIFIER_assume(__global_lock==1); __global_lock=0; return; }
#include <assert.h>
#include <pthread.h>
#ifndef TRUE
#define TRUE (_Bool)1
#endif
#ifndef FALSE
#define FALSE (_Bool)0
#endif
#ifndef NULL
#define NULL ((void*)0)
#endif
#ifndef FENCE
#define FENCE(x) ((void)0)
#endif
#ifndef IEEE_FLOAT_EQUAL
#define IEEE_FLOAT_EQUAL(x,y) (x==y)
#endif
#ifndef IEEE_FLOAT_NOTEQUAL
#define IEEE_FLOAT_NOTEQUAL(x,y) (x!=y)
#endif
void * P0(void *arg);
void * P1(void *arg);
void * P2(void *arg);
void fence();
void isync();
void lwfence();
int __unbuffered_cnt;
int __unbuffered_cnt = 0;
int __unbuffered_p0_EAX;
int __unbuffered_p0_EAX = 0;
int __unbuffered_p2_EAX;
int __unbuffered_p2_EAX = 0;
_Bool __unbuffered_p2_EAX$flush_delayed;
int __unbuffered_p2_EAX$mem_tmp;
_Bool __unbuffered_p2_EAX$r_buff0_thd0;
_Bool __unbuffered_p2_EAX$r_buff0_thd1;
_Bool __unbuffered_p2_EAX$r_buff0_thd2;
_Bool __unbuffered_p2_EAX$r_buff0_thd3;
_Bool __unbuffered_p2_EAX$r_buff1_thd0;
_Bool __unbuffered_p2_EAX$r_buff1_thd1;
_Bool __unbuffered_p2_EAX$r_buff1_thd2;
_Bool __unbuffered_p2_EAX$r_buff1_thd3;
_Bool __unbuffered_p2_EAX$read_delayed;
int *__unbuffered_p2_EAX$read_delayed_var;
int __unbuffered_p2_EAX$w_buff0;
_Bool __unbuffered_p2_EAX$w_buff0_used;
int __unbuffered_p2_EAX$w_buff1;
_Bool __unbuffered_p2_EAX$w_buff1_used;
_Bool main$tmp_guard0;
_Bool main$tmp_guard1;
int x;
int x = 0;
_Bool x$flush_delayed;
int x$mem_tmp;
_Bool x$r_buff0_thd0;
_Bool x$r_buff0_thd1;
_Bool x$r_buff0_thd2;
_Bool x$r_buff0_thd3;
_Bool x$r_buff1_thd0;
_Bool x$r_buff1_thd1;
_Bool x$r_buff1_thd2;
_Bool x$r_buff1_thd3;
_Bool x$read_delayed;
int *x$read_delayed_var;
int x$w_buff0;
_Bool x$w_buff0_used;
int x$w_buff1;
_Bool x$w_buff1_used;
int y;
int y = 0;
_Bool weak$$choice0;
_Bool weak$$choice1;
_Bool weak$$choice2;
void * P0(void *arg)
{
__VERIFIER_atomic_begin();
y = 2;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
weak$$choice0 = nondet_0();
weak$$choice2 = nondet_0();
x$flush_delayed = weak$$choice2;
x$mem_tmp = x;
x = !x$w_buff0_used || !x$r_buff0_thd1 && !x$w_buff1_used || !x$r_buff0_thd1 && !x$r_buff1_thd1 ? x : (x$w_buff0_used && x$r_buff0_thd1 ? x$w_buff0 : x$w_buff1);
x$w_buff0 = weak$$choice2 ? x$w_buff0 : (!x$w_buff0_used || !x$r_buff0_thd1 && !x$w_buff1_used || !x$r_buff0_thd1 && !x$r_buff1_thd1 ? x$w_buff0 : (x$w_buff0_used && x$r_buff0_thd1 ? x$w_buff0 : x$w_buff0));
x$w_buff1 = weak$$choice2 ? x$w_buff1 : (!x$w_buff0_used || !x$r_buff0_thd1 && !x$w_buff1_used || !x$r_buff0_thd1 && !x$r_buff1_thd1 ? x$w_buff1 : (x$w_buff0_used && x$r_buff0_thd1 ? x$w_buff1 : x$w_buff1));
x$w_buff0_used = weak$$choice2 ? x$w_buff0_used : (!x$w_buff0_used || !x$r_buff0_thd1 && !x$w_buff1_used || !x$r_buff0_thd1 && !x$r_buff1_thd1 ? x$w_buff0_used : (x$w_buff0_used && x$r_buff0_thd1 ? FALSE : x$w_buff0_used));
x$w_buff1_used = weak$$choice2 ? x$w_buff1_used : (!x$w_buff0_used || !x$r_buff0_thd1 && !x$w_buff1_used || !x$r_buff0_thd1 && !x$r_buff1_thd1 ? x$w_buff1_used : (x$w_buff0_used && x$r_buff0_thd1 ? FALSE : FALSE));
x$r_buff0_thd1 = weak$$choice2 ? x$r_buff0_thd1 : (!x$w_buff0_used || !x$r_buff0_thd1 && !x$w_buff1_used || !x$r_buff0_thd1 && !x$r_buff1_thd1 ? x$r_buff0_thd1 : (x$w_buff0_used && x$r_buff0_thd1 ? FALSE : x$r_buff0_thd1));
x$r_buff1_thd1 = weak$$choice2 ? x$r_buff1_thd1 : (!x$w_buff0_used || !x$r_buff0_thd1 && !x$w_buff1_used || !x$r_buff0_thd1 && !x$r_buff1_thd1 ? x$r_buff1_thd1 : (x$w_buff0_used && x$r_buff0_thd1 ? FALSE : FALSE));
__unbuffered_p0_EAX = x;
x = x$flush_delayed ? x$mem_tmp : x;
x$flush_delayed = FALSE;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_1();
}
void * P1(void *arg)
{
__VERIFIER_atomic_begin();
x = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = 2;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd2 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd2 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd2 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd2 || x$w_buff1_used && x$r_buff1_thd2 ? FALSE : x$w_buff1_used;
x$r_buff0_thd2 = x$w_buff0_used && x$r_buff0_thd2 ? FALSE : x$r_buff0_thd2;
x$r_buff1_thd2 = x$w_buff0_used && x$r_buff0_thd2 || x$w_buff1_used && x$r_buff1_thd2 ? FALSE : x$r_buff1_thd2;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_1();
}
void * P2(void *arg)
{
__VERIFIER_atomic_begin();
weak$$choice0 = nondet_0();
weak$$choice2 = nondet_0();
x$flush_delayed = weak$$choice2;
x$mem_tmp = x;
x = !x$w_buff0_used || !x$r_buff0_thd3 && !x$w_buff1_used || !x$r_buff0_thd3 && !x$r_buff1_thd3 ? x : (x$w_buff0_used && x$r_buff0_thd3 ? x$w_buff0 : x$w_buff1);
x$w_buff0 = weak$$choice2 ? x$w_buff0 : (!x$w_buff0_used || !x$r_buff0_thd3 && !x$w_buff1_used || !x$r_buff0_thd3 && !x$r_buff1_thd3 ? x$w_buff0 : (x$w_buff0_used && x$r_buff0_thd3 ? x$w_buff0 : x$w_buff0));
x$w_buff1 = weak$$choice2 ? x$w_buff1 : (!x$w_buff0_used || !x$r_buff0_thd3 && !x$w_buff1_used || !x$r_buff0_thd3 && !x$r_buff1_thd3 ? x$w_buff1 : (x$w_buff0_used && x$r_buff0_thd3 ? x$w_buff1 : x$w_buff1));
x$w_buff0_used = weak$$choice2 ? x$w_buff0_used : (!x$w_buff0_used || !x$r_buff0_thd3 && !x$w_buff1_used || !x$r_buff0_thd3 && !x$r_buff1_thd3 ? x$w_buff0_used : (x$w_buff0_used && x$r_buff0_thd3 ? FALSE : x$w_buff0_used));
x$w_buff1_used = weak$$choice2 ? x$w_buff1_used : (!x$w_buff0_used || !x$r_buff0_thd3 && !x$w_buff1_used || !x$r_buff0_thd3 && !x$r_buff1_thd3 ? x$w_buff1_used : (x$w_buff0_used && x$r_buff0_thd3 ? FALSE : FALSE));
x$r_buff0_thd3 = weak$$choice2 ? x$r_buff0_thd3 : (!x$w_buff0_used || !x$r_buff0_thd3 && !x$w_buff1_used || !x$r_buff0_thd3 && !x$r_buff1_thd3 ? x$r_buff0_thd3 : (x$w_buff0_used && x$r_buff0_thd3 ? FALSE : x$r_buff0_thd3));
x$r_buff1_thd3 = weak$$choice2 ? x$r_buff1_thd3 : (!x$w_buff0_used || !x$r_buff0_thd3 && !x$w_buff1_used || !x$r_buff0_thd3 && !x$r_buff1_thd3 ? x$r_buff1_thd3 : (x$w_buff0_used && x$r_buff0_thd3 ? FALSE : FALSE));
__unbuffered_p2_EAX$read_delayed = TRUE;
__unbuffered_p2_EAX$read_delayed_var = &x;
__unbuffered_p2_EAX = x;
x = x$flush_delayed ? x$mem_tmp : x;
x$flush_delayed = FALSE;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
y = 1;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd3 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd3 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd3 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd3 || x$w_buff1_used && x$r_buff1_thd3 ? FALSE : x$w_buff1_used;
x$r_buff0_thd3 = x$w_buff0_used && x$r_buff0_thd3 ? FALSE : x$r_buff0_thd3;
x$r_buff1_thd3 = x$w_buff0_used && x$r_buff0_thd3 || x$w_buff1_used && x$r_buff1_thd3 ? FALSE : x$r_buff1_thd3;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
__unbuffered_cnt = __unbuffered_cnt + 1;
__VERIFIER_atomic_end();
return nondet_1();
}
void fence()
{
}
void isync()
{
}
void lwfence()
{
}
int main()
{
pthread_create(NULL, NULL, P0, NULL);
pthread_create(NULL, NULL, P1, NULL);
pthread_create(NULL, NULL, P2, NULL);
__VERIFIER_atomic_begin();
main$tmp_guard0 = __unbuffered_cnt == 3;
__VERIFIER_atomic_end();
__VERIFIER_assume(main$tmp_guard0);
__VERIFIER_atomic_begin();
x = x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd0 ? x$w_buff1 : x);
x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$w_buff0_used;
x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd0 || x$w_buff1_used && x$r_buff1_thd0 ? FALSE : x$w_buff1_used;
x$r_buff0_thd0 = x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$r_buff0_thd0;
x$r_buff1_thd0 = x$w_buff0_used && x$r_buff0_thd0 || x$w_buff1_used && x$r_buff1_thd0 ? FALSE : x$r_buff1_thd0;
__VERIFIER_atomic_end();
__VERIFIER_atomic_begin();
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
weak$$choice0 = nondet_0();
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
weak$$choice2 = nondet_0();
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
x$flush_delayed = weak$$choice2;
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
x$mem_tmp = x;
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
x = !x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : x$w_buff1);
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
x$w_buff0 = weak$$choice2 ? x$w_buff0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff0 : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : x$w_buff0));
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
x$w_buff1 = weak$$choice2 ? x$w_buff1 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff1 : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff1 : x$w_buff1));
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
x$w_buff0_used = weak$$choice2 ? x$w_buff0_used : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff0_used : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$w_buff0_used));
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
x$w_buff1_used = weak$$choice2 ? x$w_buff1_used : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff1_used : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : FALSE));
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
x$r_buff0_thd0 = weak$$choice2 ? x$r_buff0_thd0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$r_buff0_thd0 : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$r_buff0_thd0));
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
x$r_buff1_thd0 = weak$$choice2 ? x$r_buff1_thd0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$r_buff1_thd0 : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : FALSE));
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
weak$$choice1 = nondet_0();
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
__unbuffered_p2_EAX = __unbuffered_p2_EAX$read_delayed ? (weak$$choice1 ? *__unbuffered_p2_EAX$read_delayed_var : __unbuffered_p2_EAX) : __unbuffered_p2_EAX;
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
main$tmp_guard1 = !(x == 2 && y == 2 && __unbuffered_p0_EAX == 0 && __unbuffered_p2_EAX == 2);
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
x = x$flush_delayed ? x$mem_tmp : x;
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
x$flush_delayed = FALSE;
__VERIFIER_atomic_end();
/* Program was expected to be safe for X86, model checker should have said NO.
This likely is a bug in the tool chain. */
__VERIFIER_assert(main$tmp_guard1);
return 0;
}
|
the_stack_data/145452132.c | #include<stdio.h>
#include<stdlib.h>
struct LL
{
int data;
struct LL *next;
};
// Function to return number of nodes in linked list
int ListTraverse (struct LL **head) {
struct LL *current = *head;
int count = 0;
while(current){
count++;
current = current -> next;
}
return count;
}
// Function to print linked list
void ListPrint (struct LL **head) {
struct LL *current = *head;
while(current){
printf("%d -> ", current -> data);
current = current -> next;
}
printf("NULL \n");
}
// Function to insert node at the beginning of the list
void InsertStart (struct LL **head, int data) {
struct LL *temp, *newNode;
temp = *head;
newNode = (struct LL *)malloc(sizeof(struct LL));
newNode -> data = data;
newNode -> next = temp;
*head = newNode;
ListPrint(head);
}
// Function to insert node at the last position of the list
void InsertEnd (struct LL **head, int data) {
struct LL *p, *newNode;
newNode = (struct LL *)malloc(sizeof(struct LL));
newNode -> data = data;
newNode -> next = NULL;
if (*head == NULL) {
*head = newNode;
printf("The linked list is not created yet, therefore inserting at first position, \n");
}
else {
int count=0;
p = *head;
while (p -> next!=NULL)
{
p = p->next;
count++;
}
p -> next = newNode;
}
ListPrint(head);
}
// Function to insert node at the specific position of the list
void InsertPosition (struct LL **head, int data , int position) {
struct LL *p, *q, *newNode;
int k=1;
newNode = (struct LL *)malloc(sizeof(struct LL));
newNode -> data = data;
p=*head;
if (*head == NULL) {
*head = newNode;
printf("The linked list is not created yet, therefore inserting at first position, \n");
}
else if (position == 1) {
newNode->next = p;
*head = newNode;
}
else {
while (p != NULL && k<position) {
q = p;
p = p->next;
k++;
}
if (k != position)
printf("Given position exceeds the total number of nodes, therefore inserting at the end. \n");
q ->next = newNode;
newNode->next = p;
}
ListPrint(head);
}
int main() {
struct LL *head = NULL;
int opt = 0, count = 0;
char c='N';
int n=0,f=0,d=0,p=0;
loop:;
printf("\n");
printf("1. Append nodes. \n");
printf("2. Insert new node at start. \n");
printf("3. Insert new node at end. \n");
printf("4. Insert new node at position. \n");
printf("5. Traverse List. \n");
printf("6. Print list. \n\n");
printf("Choose your option : ");
scanf("%d",&opt);
switch (opt)
{
case 1 :
printf("Enter no. of nodes : ");
scanf("%d",&n);
for (int i = 1; i <= n; i++)
{
printf("Enter the data of node %d : ",i);
scanf("%d",&d);
InsertEnd(&head,d);
}
printf("\n");
printf("Want to choose more?(Y/N) : ");
scanf(" %c",&c);
// clear screen function in linux
system("clear"); // Use < system("cls"); > in windows
if (c=='y' || c=='Y')
goto loop;
break;
case 2 :
printf("Enter the data of node 1 : ");
scanf("%d",&f);
InsertStart(&head,f);
printf("\n");
printf("Want to choose more?(Y/N) : ");
scanf(" %c",&c);
// clear screen function in linux
system("clear"); // Use < system("cls"); > in windows
if (c=='y' || c=='Y')
goto loop;
break;
case 3 :
printf("Enter the data of last node : ");
scanf("%d",&d);
InsertEnd(&head,d);
printf("\n");
printf("Want to choose more?(Y/N) : ");
scanf(" %c",&c);
// clear screen function in linux
system("clear"); // Use < system("cls"); > in windows
if (c=='y' || c=='Y')
goto loop;
break;
case 4 :
printf("Enter the position : ");
scanf("%d", &p);
printf("Enter the data of node %d : ",p);
scanf("%d",&d);
InsertPosition(&head,d,p);
printf("\n");
printf("Want to choose more?(Y/N) : ");
scanf(" %c",&c);
// clear screen function in linux
system("clear"); // Use < system("cls"); > in windows
if (c=='y' || c=='Y')
goto loop;
break;
case 5 :
count = ListTraverse(&head);
printf("Total number of nodes in Linked List : %d\n", count);
printf("\n");
printf("Want to choose more?(Y/N) : ");
scanf(" %c",&c);
// clear screen function in linux
system("clear"); // Use < system("cls"); > in windows
if (c=='y' || c=='Y')
goto loop;
case 6 :
ListPrint(&head);
printf("\n");
printf("Want to choose more?(Y/N) : ");
scanf(" %c",&c);
// clear screen function in linux
system("clear"); // Use < system("cls"); > in windows
if (c=='y' || c=='Y')
goto loop;
break;
default:
printf("Wrong option \n");
printf("\n");
printf("Want to choose more?(Y/N) : ");
scanf(" %c",&c);
// clear screen function in linux
system("clear"); // Use < system("cls"); > in windows
if (c=='y' || c=='Y')
goto loop;
break;
}
return 0;
} |
the_stack_data/1159046.c | // RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify %s
void clang_analyzer_eval(int);
void clang_analyzer_warnOnDeadSymbol(int);
void clang_analyzer_numTimesReached();
void clang_analyzer_warnIfReached();
void exit(int);
int conjure_index();
void test_that_expr_inspection_works() {
do {
int x = conjure_index();
clang_analyzer_warnOnDeadSymbol(x);
} while(0); // expected-warning{{SYMBOL DEAD}}
// Make sure we don't accidentally split state in ExprInspection.
clang_analyzer_numTimesReached(); // expected-warning{{1}}
}
// These tests verify the reaping of symbols that are only referenced as
// index values in element regions. Most of the time, depending on where
// the element region, as Loc value, is stored, it is possible to
// recover the index symbol in checker code, which is also demonstrated
// in the return_ptr_range.c test file.
int arr[3];
int *test_element_index_lifetime_in_environment_values() {
int *ptr;
do {
int x = conjure_index();
clang_analyzer_warnOnDeadSymbol(x);
ptr = arr + x;
} while (0);
return ptr;
}
void test_element_index_lifetime_in_store_keys() {
do {
int x = conjure_index();
clang_analyzer_warnOnDeadSymbol(x);
arr[x] = 1;
if (x) {}
} while (0); // no-warning
}
int *ptr;
void test_element_index_lifetime_in_store_values() {
do {
int x = conjure_index();
clang_analyzer_warnOnDeadSymbol(x);
ptr = arr + x;
} while (0); // no-warning
}
struct S1 {
int field;
};
struct S2 {
struct S1 array[5];
} s2;
struct S3 {
void *field;
};
struct S1 *conjure_S1();
struct S3 *conjure_S3();
void test_element_index_lifetime_with_complicated_hierarchy_of_regions() {
do {
int x = conjure_index();
clang_analyzer_warnOnDeadSymbol(x);
s2.array[x].field = 1;
if (x) {}
} while (0); // no-warning
}
void test_loc_as_integer_element_index_lifetime() {
do {
int x;
struct S3 *s = conjure_S3();
clang_analyzer_warnOnDeadSymbol((int)s);
x = (int)&(s->field);
ptr = &arr[x];
if (s) {}
} while (0);
}
// Test below checks lifetime of SymbolRegionValue in certain conditions.
int **ptrptr;
void test_region_lifetime_as_store_value(int *x) {
clang_analyzer_warnOnDeadSymbol((int) x);
*x = 1;
ptrptr = &x;
(void)0; // No-op; make sure the environment forgets things and the GC runs.
clang_analyzer_eval(**ptrptr); // expected-warning{{TRUE}}
} // no-warning
int *produce_region_referenced_only_through_field_in_environment_value() {
struct S1 *s = conjure_S1();
clang_analyzer_warnOnDeadSymbol((int) s);
int *x = &s->field;
return x;
}
void test_region_referenced_only_through_field_in_environment_value() {
produce_region_referenced_only_through_field_in_environment_value();
} // expected-warning{{SYMBOL DEAD}}
void test_region_referenced_only_through_field_in_store_value() {
struct S1 *s = conjure_S1();
clang_analyzer_warnOnDeadSymbol((int) s);
ptr = &s->field; // Write the symbol into a global. It should live forever.
if (!s) {
exit(0); // no-warning (symbol should not die here)
// exit() is noreturn.
clang_analyzer_warnIfReached(); // no-warning
}
if (!ptr) { // no-warning (symbol should not die here)
// We exit()ed under these constraints earlier.
clang_analyzer_warnIfReached(); // no-warning
}
// The exit() call invalidates globals. The symbol will die here because
// the exit() statement itself is already over and there's no better statement
// to put the diagnostic on.
} // expected-warning{{SYMBOL DEAD}}
void test_zombie_referenced_only_through_field_in_store_value() {
struct S1 *s = conjure_S1();
clang_analyzer_warnOnDeadSymbol((int) s);
int *x = &s->field;
} // expected-warning{{SYMBOL DEAD}}
void double_dereference_of_implicit_value_aux1(int *p) {
*p = 0;
}
void double_dereference_of_implicit_value_aux2(int *p) {
if (*p != 0)
clang_analyzer_warnIfReached(); // no-warning
}
void test_double_dereference_of_implicit_value(int **x) {
clang_analyzer_warnOnDeadSymbol(**x);
int **y = x;
{
double_dereference_of_implicit_value_aux1(*y);
// Give time for symbol reaping to happen.
((void)0);
// The symbol for **y was cleaned up from the Store at this point,
// even though it was not perceived as dead when asked explicitly.
// For that reason the SYMBOL DEAD warning never appeared at this point.
double_dereference_of_implicit_value_aux2(*y);
}
// The symbol is generally reaped here regardless.
((void)0); // expected-warning{{SYMBOL DEAD}}
}
|
the_stack_data/100141397.c | void main()
{
int a,b,c;
printf("Enter fist number:");
scanf("%d",&a);
printf("Enter second number:");
scanf("%d",&b);
c=a/b;
printf("%d/%d=%d",a,b,c);
}
|
the_stack_data/187642943.c |
#if defined(MEDUSA_TCPSOCKET_OPENSSL_ENABLE) && (MEDUSA_TCPSOCKET_OPENSSL_ENABLE ==1)
#define MEDUSA_TEST_TCPSOCKET_SSL 1
#include "tcpsocket-22.c"
#else
#include <stdio.h>
int main (int argc, char *argv[])
{
(void) argc;
(void) argv;
fprintf(stderr, "medusa tcpsocket openssl support is disabled\n");
return 0;
}
#endif
|
the_stack_data/126702881.c | /*
** libgcc support for software floating point.
** Copyright (C) 1991 by Pipeline Associates, Inc. All rights reserved.
** Permission is granted to do *anything* you want with this file,
** commercial or otherwise, provided this message remains intact. So there!
** I would appreciate receiving any updates/patches/changes that anyone
** makes, and am willing to be the repository for said changes (am I
** making a big mistake?).
Warning! Only single-precision is actually implemented. This file
won't really be much use until double-precision is supported.
However, once that is done, this file might make possible
cross-compilation for an IEEE target machine from a non-IEEE
host such as a VAX.
If you'd like to work on completing this, please talk to [email protected].
--> Double precision floating support added by James Carlson on 20 April 1998.
**
** Pat Wood
** Pipeline Associates, Inc.
** [email protected] or
** sun!pipeline!phw or
** uunet!motown!pipeline!phw
**
** 05/01/91 -- V1.0 -- first release to gcc mailing lists
** 05/04/91 -- V1.1 -- added float and double prototypes and return values
** -- fixed problems with adding and subtracting zero
** -- fixed rounding in truncdfsf2
** -- fixed SWAP define and tested on 386
*/
/*
** The following are routines that replace the libgcc soft floating point
** routines that are called automatically when -msoft-float is selected.
** The support single and double precision IEEE format, with provisions
** for byte-swapped machines (tested on 386). Some of the double-precision
** routines work at full precision, but most of the hard ones simply punt
** and call the single precision routines, producing a loss of accuracy.
** long long support is not assumed or included.
** Overall accuracy is close to IEEE (actually 68882) for single-precision
** arithmetic. I think there may still be a 1 in 1000 chance of a bit
** being rounded the wrong way during a multiply. I'm not fussy enough to
** bother with it, but if anyone is, knock yourself out.
**
** Efficiency has only been addressed where it was obvious that something
** would make a big difference. Anyone who wants to do this right for
** best speed should go in and rewrite in assembler.
**
** I have tested this only on a 68030 workstation and 386/ix integrated
** in with -msoft-float.
*/
/* the following deal with IEEE single-precision numbers */
#define EXCESS 126
#define SIGNBIT 0x80000000
#define HIDDEN (1 << 23)
#define SIGN(fp) ((fp) & SIGNBIT)
#define EXP(fp) (((fp) >> 23) & 0xFF)
#define MANT(fp) (((fp) & 0x7FFFFF) | HIDDEN)
#define PACK(s,e,m) ((s) | ((e) << 23) | (m))
/* the following deal with IEEE double-precision numbers */
#define EXCESSD 1022
#define HIDDEND (1 << 20)
#define EXPD(fp) (((fp.l.upper) >> 20) & 0x7FF)
#define SIGND(fp) ((fp.l.upper) & SIGNBIT)
#define MANTD(fp) (((((fp.l.upper) & 0xFFFFF) | HIDDEND) << 10) | \
(fp.l.lower >> 22))
#define HIDDEND_LL ((long long)1 << 52)
#define MANTD_LL(fp) ((fp.ll & (HIDDEND_LL-1)) | HIDDEND_LL)
#define PACKD_LL(s,e,m) (((long long)((s)+((e)<<20))<<32)|(m))
/* define SWAP for 386/960 reverse-byte-order brain-damaged CPUs */
union double_long {
double d;
#ifdef SWAP
struct {
#ifdef KEY
int upper;
unsigned int lower;
#else
unsigned long lower;
long upper;
#endif
} l;
#else
struct {
#ifdef KEY
unsigned int lower;
int upper;
#else
long upper;
unsigned long lower;
#endif
} l;
#endif
long long ll;
};
union float_long
{
float f;
long l;
};
/* add two floats */
float
__addsf3 (float a1, float a2)
{
long mant1, mant2;
union float_long fl1, fl2;
int exp1, exp2;
int sign = 0;
fl1.f = a1;
fl2.f = a2;
/* check for zero args */
if (!fl1.l) {
fl1.f = fl2.f;
goto test_done;
}
if (!fl2.l)
goto test_done;
exp1 = EXP (fl1.l);
exp2 = EXP (fl2.l);
if (exp1 > exp2 + 25)
goto test_done;
if (exp2 > exp1 + 25) {
fl1.f = fl2.f;
goto test_done;
}
/* do everything in excess precision so's we can round later */
mant1 = MANT (fl1.l) << 6;
mant2 = MANT (fl2.l) << 6;
if (SIGN (fl1.l))
mant1 = -mant1;
if (SIGN (fl2.l))
mant2 = -mant2;
if (exp1 > exp2)
{
mant2 >>= exp1 - exp2;
}
else
{
mant1 >>= exp2 - exp1;
exp1 = exp2;
}
mant1 += mant2;
if (mant1 < 0)
{
mant1 = -mant1;
sign = SIGNBIT;
}
else if (!mant1) {
fl1.f = 0;
goto test_done;
}
/* normalize up */
while (!(mant1 & 0xE0000000))
{
mant1 <<= 1;
exp1--;
}
/* normalize down? */
if (mant1 & (1 << 30))
{
mant1 >>= 1;
exp1++;
}
/* round to even */
mant1 += (mant1 & 0x40) ? 0x20 : 0x1F;
/* normalize down? */
if (mant1 & (1 << 30))
{
mant1 >>= 1;
exp1++;
}
/* lose extra precision */
mant1 >>= 6;
/* turn off hidden bit */
mant1 &= ~HIDDEN;
/* pack up and go home */
fl1.l = PACK (sign, exp1, mant1);
test_done:
return (fl1.f);
}
/* subtract two floats */
float
__subsf3 (float a1, float a2)
{
union float_long fl1, fl2;
fl1.f = a1;
fl2.f = a2;
/* check for zero args */
if (!fl2.l)
return (fl1.f);
if (!fl1.l)
return (-fl2.f);
/* twiddle sign bit and add */
fl2.l ^= SIGNBIT;
return __addsf3 (a1, fl2.f);
}
/* compare two floats */
long
__cmpsf2 (float a1, float a2)
{
union float_long fl1, fl2;
fl1.f = a1;
fl2.f = a2;
if (SIGN (fl1.l) && SIGN (fl2.l))
{
fl1.l ^= SIGNBIT;
fl2.l ^= SIGNBIT;
}
if (fl1.l < fl2.l)
return (-1);
if (fl1.l > fl2.l)
return (1);
return (0);
}
/* multiply two floats */
float
__mulsf3 (float a1, float a2)
{
union float_long fl1, fl2;
unsigned long result;
int exp;
int sign;
fl1.f = a1;
fl2.f = a2;
if (!fl1.l || !fl2.l) {
fl1.f = 0;
goto test_done;
}
/* compute sign and exponent */
sign = SIGN (fl1.l) ^ SIGN (fl2.l);
exp = EXP (fl1.l) - EXCESS;
exp += EXP (fl2.l);
fl1.l = MANT (fl1.l);
fl2.l = MANT (fl2.l);
/* the multiply is done as one 16x16 multiply and two 16x8 multiples */
result = (fl1.l >> 8) * (fl2.l >> 8);
result += ((fl1.l & 0xFF) * (fl2.l >> 8)) >> 8;
result += ((fl2.l & 0xFF) * (fl1.l >> 8)) >> 8;
result >>= 2;
if (result & 0x20000000)
{
/* round */
result += 0x20;
result >>= 6;
}
else
{
/* round */
result += 0x10;
result >>= 5;
exp--;
}
if (result & (HIDDEN<<1)) {
result >>= 1;
exp++;
}
result &= ~HIDDEN;
/* pack up and go home */
fl1.l = PACK (sign, exp, result);
test_done:
return (fl1.f);
}
/* divide two floats */
float
__divsf3 (float a1, float a2)
{
union float_long fl1, fl2;
int result;
int mask;
int exp, sign;
fl1.f = a1;
fl2.f = a2;
/* subtract exponents */
exp = EXP (fl1.l) - EXP (fl2.l) + EXCESS;
/* compute sign */
sign = SIGN (fl1.l) ^ SIGN (fl2.l);
/* divide by zero??? */
if (!fl2.l)
/* return NaN or -NaN */
return (sign ? 0xFFFFFFFF : 0x7FFFFFFF);
/* numerator zero??? */
if (!fl1.l)
return (0);
/* now get mantissas */
fl1.l = MANT (fl1.l);
fl2.l = MANT (fl2.l);
/* this assures we have 25 bits of precision in the end */
if (fl1.l < fl2.l)
{
fl1.l <<= 1;
exp--;
}
/* now we perform repeated subtraction of fl2.l from fl1.l */
mask = 0x1000000;
result = 0;
while (mask)
{
if (fl1.l >= fl2.l)
{
result |= mask;
fl1.l -= fl2.l;
}
fl1.l <<= 1;
mask >>= 1;
}
/* round */
result += 1;
/* normalize down */
exp++;
result >>= 1;
result &= ~HIDDEN;
/* pack up and go home */
fl1.l = PACK (sign, exp, result);
return (fl1.f);
}
/* convert int to double */
double
__floatsidf (long a1)
{
int sign = 0, exp = 31 + EXCESSD;
union double_long dl;
if (!a1)
{
dl.l.upper = dl.l.lower = 0;
return (dl.d);
}
if (a1 < 0)
{
sign = SIGNBIT;
a1 = -a1;
}
while (a1 < 0x1000000)
{
a1 <<= 4;
exp -= 4;
}
while (a1 < 0x40000000)
{
a1 <<= 1;
exp--;
}
/* pack up and go home */
dl.l.upper = sign;
dl.l.upper |= exp << 20;
dl.l.upper |= (a1 >> 10) & ~HIDDEND;
dl.l.lower = a1 << 22;
return (dl.d);
}
double
__floatdidf (long long a1)
{
int exp = 63 + EXCESSD;
union double_long dl;
dl.l.upper = dl.l.lower = 0;
if (a1 == 0)
return (dl.d);
if (a1 < 0) {
dl.l.upper = SIGNBIT;
a1 = -a1;
}
while (a1 < (long long)1<<54) {
a1 <<= 8;
exp -= 8;
}
while (a1 < (long long)1<<62) {
a1 <<= 1;
exp -= 1;
}
/* pack up and go home */
dl.ll |= (a1 >> 10) & ~HIDDEND_LL;
dl.l.upper |= exp << 20;
return (dl.d);
}
float
__floatsisf (long a1)
{
(float)__floatsidf(a1);
}
float
__floatdisf (long long a1)
{
(float)__floatdidf(a1);
}
/* negate a float */
float
__negsf2 (float a1)
{
union float_long fl1;
fl1.f = a1;
if (!fl1.l)
return (0);
fl1.l ^= SIGNBIT;
return (fl1.f);
}
/* negate a double */
double
__negdf2 (double a1)
{
union double_long dl1;
dl1.d = a1;
if (!dl1.l.upper && !dl1.l.lower)
return (dl1.d);
dl1.l.upper ^= SIGNBIT;
return (dl1.d);
}
/* convert float to double */
double
__extendsfdf2 (float a1)
{
union float_long fl1;
union double_long dl;
int exp;
fl1.f = a1;
if (!fl1.l)
{
dl.l.upper = dl.l.lower = 0;
return (dl.d);
}
dl.l.upper = SIGN (fl1.l);
exp = EXP (fl1.l) - EXCESS + EXCESSD;
dl.l.upper |= exp << 20;
dl.l.upper |= (MANT (fl1.l) & ~HIDDEN) >> 3;
dl.l.lower = MANT (fl1.l) << 29;
return (dl.d);
}
/* convert double to float */
float
__truncdfsf2 (double a1)
{
int exp;
long mant;
union float_long fl;
union double_long dl1;
dl1.d = a1;
if (!dl1.l.upper && !dl1.l.lower)
return (float)(0);
exp = EXPD (dl1) - EXCESSD + EXCESS;
/* shift double mantissa 6 bits so we can round */
mant = MANTD (dl1) >> 6;
/* now round and shift down */
mant += 1;
mant >>= 1;
/* did the round overflow? */
if (mant & 0xFE000000)
{
mant >>= 1;
exp++;
}
mant &= ~HIDDEN;
/* pack up and go home */
fl.l = PACK (SIGND (dl1), exp, mant);
return (fl.f);
}
/* compare two doubles */
long
__cmpdf2 (double a1, double a2)
{
union double_long dl1, dl2;
dl1.d = a1;
dl2.d = a2;
if (SIGND (dl1) && SIGND (dl2))
{
dl1.l.upper ^= SIGNBIT;
dl2.l.upper ^= SIGNBIT;
}
if (dl1.l.upper < dl2.l.upper)
return (-1);
if (dl1.l.upper > dl2.l.upper)
return (1);
if (dl1.l.lower < dl2.l.lower)
return (-1);
if (dl1.l.lower > dl2.l.lower)
return (1);
return (0);
}
/* convert double to int */
long
__fixdfsi (double a1)
{
union double_long dl1;
int exp;
long l;
dl1.d = a1;
if (!dl1.l.upper && !dl1.l.lower)
return (0);
exp = EXPD (dl1) - EXCESSD - 31;
l = MANTD (dl1);
if (exp > 0)
return SIGND(dl1) ? (1<<31) : ((1ul<<31)-1);
/* shift down until exp = 0 or l = 0 */
if (exp < 0 && exp > -32 && l)
l >>= -exp;
else
return (0);
return (SIGND (dl1) ? -l : l);
}
/* convert double to int */
long long
__fixdfdi (double a1)
{
union double_long dl1;
int exp;
long long l;
dl1.d = a1;
if (!dl1.l.upper && !dl1.l.lower)
return (0);
exp = EXPD (dl1) - EXCESSD - 64;
l = MANTD_LL(dl1);
if (exp > 0) {
l = (long long)1<<63;
if (!SIGND(dl1))
l--;
return l;
}
/* shift down until exp = 0 or l = 0 */
if (exp < 0 && exp > -64 && l)
l >>= -exp;
else
return (0);
return (SIGND (dl1) ? -l : l);
}
/* convert double to unsigned int */
unsigned long
__fixunsdfsi (double a1)
{
union double_long dl1;
int exp;
unsigned long l;
dl1.d = a1;
if (!dl1.l.upper && !dl1.l.lower)
return (0);
exp = EXPD (dl1) - EXCESSD - 32;
l = (((((dl1.l.upper) & 0xFFFFF) | HIDDEND) << 11) | (dl1.l.lower >> 21));
if (exp > 0)
return (0xFFFFFFFFul); /* largest integer */
/* shift down until exp = 0 or l = 0 */
if (exp < 0 && exp > -32 && l)
l >>= -exp;
else
return (0);
return (l);
}
/* convert double to unsigned int */
unsigned long long
__fixunsdfdi (double a1)
{
union double_long dl1;
int exp;
unsigned long long l;
dl1.d = a1;
if (dl1.ll == 0)
return (0);
exp = EXPD (dl1) - EXCESSD - 64;
l = dl1.ll;
if (exp > 0)
return (unsigned long long)-1;
/* shift down until exp = 0 or l = 0 */
if (exp < 0 && exp > -64 && l)
l >>= -exp;
else
return (0);
return (l);
}
/* addtwo doubles */
double
__adddf3 (double a1, double a2)
{
long long mant1, mant2;
union double_long fl1, fl2;
int exp1, exp2;
int sign = 0;
fl1.d = a1;
fl2.d = a2;
/* check for zero args */
if (!fl2.ll)
goto test_done;
if (!fl1.ll) {
fl1.d = fl2.d;
goto test_done;
}
exp1 = EXPD(fl1);
exp2 = EXPD(fl2);
if (exp1 > exp2 + 54)
goto test_done;
if (exp2 > exp1 + 54) {
fl1.d = fl2.d;
goto test_done;
}
/* do everything in excess precision so's we can round later */
mant1 = MANTD_LL(fl1) << 9;
mant2 = MANTD_LL(fl2) << 9;
if (SIGND(fl1))
mant1 = -mant1;
if (SIGND(fl2))
mant2 = -mant2;
if (exp1 > exp2)
mant2 >>= exp1 - exp2;
else {
mant1 >>= exp2 - exp1;
exp1 = exp2;
}
mant1 += mant2;
if (mant1 < 0) {
mant1 = -mant1;
sign = SIGNBIT;
} else if (!mant1) {
fl1.d = 0;
goto test_done;
}
/* normalize up */
while (!(mant1 & ((long long)7<<61))) {
mant1 <<= 1;
exp1--;
}
/* normalize down? */
if (mant1 & ((long long)3<<62)) {
mant1 >>= 1;
exp1++;
}
/* round to even */
mant1 += (mant1 & (1<<9)) ? (1<<8) : ((1<<8)-1);
/* normalize down? */
if (mant1 & ((long long)3<<62)) {
mant1 >>= 1;
exp1++;
}
/* lose extra precision */
mant1 >>= 9;
/* turn off hidden bit */
mant1 &= ~HIDDEND_LL;
/* pack up and go home */
fl1.ll = PACKD_LL(sign,exp1,mant1);
test_done:
return (fl1.d);
}
/* subtract two doubles */
double
__subdf3 (double a1, double a2)
{
union double_long fl1, fl2;
fl1.d = a1;
fl2.d = a2;
/* check for zero args */
if (!fl2.ll)
return (fl1.d);
/* twiddle sign bit and add */
fl2.l.upper ^= SIGNBIT;
if (!fl1.ll)
return (fl2.d);
return __adddf3 (a1, fl2.d);
}
/* multiply two doubles */
double
__muldf3 (double a1, double a2)
{
union double_long fl1, fl2;
unsigned long long result;
int exp;
int sign;
fl1.d = a1;
fl2.d = a2;
if (!fl1.ll || !fl2.ll) {
fl1.d = 0;
goto test_done;
}
/* compute sign and exponent */
sign = SIGND(fl1) ^ SIGND(fl2);
exp = EXPD(fl1) - EXCESSD;
exp += EXPD(fl2);
fl1.ll = MANTD_LL(fl1);
fl2.ll = MANTD_LL(fl2);
/* the multiply is done as one 31x31 multiply and two 31x21 multiples */
result = (fl1.ll >> 21) * (fl2.ll >> 21);
result += ((fl1.ll & 0x1FFFFF) * (fl2.ll >> 21)) >> 21;
result += ((fl2.ll & 0x1FFFFF) * (fl1.ll >> 21)) >> 21;
result >>= 2;
if (result & ((long long)1<<61)) {
/* round */
result += 1<<8;
result >>= 9;
} else {
/* round */
result += 1<<7;
result >>= 8;
exp--;
}
if (result & (HIDDEND_LL<<1)) {
result >>= 1;
exp++;
}
result &= ~HIDDEND_LL;
/* pack up and go home */
fl1.ll = PACKD_LL(sign,exp,result);
test_done:
return (fl1.d);
}
/* divide two doubles */
double
__divdf3 (double a1, double a2)
{
union double_long fl1, fl2;
long long mask,result;
int exp, sign;
fl1.d = a1;
fl2.d = a2;
/* subtract exponents */
exp = EXPD(fl1) - EXPD(fl2) + EXCESSD;
/* compute sign */
sign = SIGND(fl1) ^ SIGND(fl2);
/* numerator zero??? */
if (fl1.ll == 0) {
/* divide by zero??? */
if (fl2.ll == 0)
fl1.ll = ((unsigned long long)1<<63)-1; /* NaN */
else
fl1.ll = 0;
goto test_done;
}
/* return +Inf or -Inf */
if (fl2.ll == 0) {
fl1.ll = PACKD_LL(SIGND(fl1),2047,0);
goto test_done;
}
/* now get mantissas */
fl1.ll = MANTD_LL(fl1);
fl2.ll = MANTD_LL(fl2);
/* this assures we have 54 bits of precision in the end */
if (fl1.ll < fl2.ll) {
fl1.ll <<= 1;
exp--;
}
/* now we perform repeated subtraction of fl2.ll from fl1.ll */
mask = (long long)1<<53;
result = 0;
while (mask) {
if (fl1.ll >= fl2.ll)
{
result |= mask;
fl1.ll -= fl2.ll;
}
fl1.ll <<= 1;
mask >>= 1;
}
/* round */
result += 1;
/* normalize down */
exp++;
result >>= 1;
result &= ~HIDDEND_LL;
/* pack up and go home */
fl1.ll = PACKD_LL(sign, exp, result);
test_done:
return (fl1.d);
}
int
__gtdf2 (double a1, double a2)
{
return __cmpdf2 ((float) a1, (float) a2) > 0;
}
int
__gedf2 (double a1, double a2)
{
return (__cmpdf2 ((float) a1, (float) a2) >= 0) - 1;
}
int
__ltdf2 (double a1, double a2)
{
return - (__cmpdf2 ((float) a1, (float) a2) < 0);
}
int
__ledf2 (double a1, double a2)
{
return __cmpdf2 ((float) a1, (float) a2) > 0;
}
int
__eqdf2 (double a1, double a2)
{
return *(long long *) &a1 == *(long long *) &a2;
}
int
__nedf2 (double a1, double a2)
{
return *(long long *) &a1 != *(long long *) &a2;
}
|
the_stack_data/488388.c | # 1 "D:/opt/source/Vivado/Vivado_HLS_Tutorial/Interface_Synthesis/lab4/axi_interfaces_prj/solution2/.autopilot/db/axi_interfaces.pragma.1.c"
# 1 "D:/opt/source/Vivado/Vivado_HLS_Tutorial/Interface_Synthesis/lab4/axi_interfaces_prj/solution2/.autopilot/db/axi_interfaces.pragma.1.c" 1
# 1 "<built-in>" 1
# 1 "<built-in>" 3
# 147 "<built-in>" 3
# 1 "<command line>" 1
# 1 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/common/technology/autopilot\\etc/autopilot_ssdm_op.h" 1
/* autopilot_ssdm_op.h*/
/*
#- (c) Copyright 2011-2015 Xilinx, Inc. All rights reserved.
#-
#- This file contains confidential and proprietary information
#- of Xilinx, Inc. and is protected under U.S. and
#- international copyright and other intellectual property
#- laws.
#-
#- DISCLAIMER
#- This disclaimer is not a license and does not grant any
#- rights to the materials distributed herewith. Except as
#- otherwise provided in a valid license issued to you by
#- Xilinx, and to the maximum extent permitted by applicable
#- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
#- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
#- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
#- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
#- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
#- (2) Xilinx shall not be liable (whether in contract or tort,
#- including negligence, or under any other theory of
#- liability) for any loss or damage of any kind or nature
#- related to, arising under or in connection with these
#- materials, including for any direct, or any indirect,
#- special, incidental, or consequential loss or damage
#- (including loss of data, profits, goodwill, or any type of
#- loss or damage suffered as a result of any action brought
#- by a third party) even if such damage or loss was
#- reasonably foreseeable or Xilinx had been advised of the
#- possibility of the same.
#-
#- CRITICAL APPLICATIONS
#- Xilinx products are not designed or intended to be fail-
#- safe, or for use in any application requiring fail-safe
#- performance, such as life-support or safety devices or
#- systems, Class III medical devices, nuclear facilities,
#- applications related to the deployment of airbags, or any
#- other applications that could lead to death, personal
#- injury, or severe property or environmental damage
#- (individually and collectively, "Critical
#- Applications"). Customer assumes the sole risk and
#- liability of any use of Xilinx products in Critical
#- Applications, subject only to applicable laws and
#- regulations governing limitations on product liability.
#-
#- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
#- PART OF THIS FILE AT ALL TIMES.
#- ************************************************************************
*
* $Id$
*/
# 280 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/common/technology/autopilot\\etc/autopilot_ssdm_op.h"
/*#define AP_SPEC_ATTR __attribute__ ((pure))*/
/****** SSDM Intrinsics: OPERATIONS ***/
// Interface operations
//typedef unsigned int __attribute__ ((bitwidth(1))) _uint1_;
void _ssdm_op_IfRead() __attribute__ ((nothrow));
void _ssdm_op_IfWrite() __attribute__ ((nothrow));
//_uint1_ _ssdm_op_IfNbRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_op_IfNbWrite() SSDM_OP_ATTR;
//_uint1_ _ssdm_op_IfCanRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_op_IfCanWrite() SSDM_OP_ATTR;
// Stream Intrinsics
void _ssdm_StreamRead() __attribute__ ((nothrow));
void _ssdm_StreamWrite() __attribute__ ((nothrow));
//_uint1_ _ssdm_StreamNbRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_StreamNbWrite() SSDM_OP_ATTR;
//_uint1_ _ssdm_StreamCanRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_StreamCanWrite() SSDM_OP_ATTR;
// Misc
void _ssdm_op_MemShiftRead() __attribute__ ((nothrow));
void _ssdm_op_Wait() __attribute__ ((nothrow));
void _ssdm_op_Poll() __attribute__ ((nothrow));
void _ssdm_op_Return() __attribute__ ((nothrow));
/* SSDM Intrinsics: SPECIFICATIONS */
void _ssdm_op_SpecSynModule() __attribute__ ((nothrow));
void _ssdm_op_SpecTopModule() __attribute__ ((nothrow));
void _ssdm_op_SpecProcessDecl() __attribute__ ((nothrow));
void _ssdm_op_SpecProcessDef() __attribute__ ((nothrow));
void _ssdm_op_SpecPort() __attribute__ ((nothrow));
void _ssdm_op_SpecConnection() __attribute__ ((nothrow));
void _ssdm_op_SpecChannel() __attribute__ ((nothrow));
void _ssdm_op_SpecSensitive() __attribute__ ((nothrow));
void _ssdm_op_SpecModuleInst() __attribute__ ((nothrow));
void _ssdm_op_SpecPortMap() __attribute__ ((nothrow));
void _ssdm_op_SpecReset() __attribute__ ((nothrow));
void _ssdm_op_SpecPlatform() __attribute__ ((nothrow));
void _ssdm_op_SpecClockDomain() __attribute__ ((nothrow));
void _ssdm_op_SpecPowerDomain() __attribute__ ((nothrow));
int _ssdm_op_SpecRegionBegin() __attribute__ ((nothrow));
int _ssdm_op_SpecRegionEnd() __attribute__ ((nothrow));
void _ssdm_op_SpecLoopName() __attribute__ ((nothrow));
void _ssdm_op_SpecLoopTripCount() __attribute__ ((nothrow));
int _ssdm_op_SpecStateBegin() __attribute__ ((nothrow));
int _ssdm_op_SpecStateEnd() __attribute__ ((nothrow));
void _ssdm_op_SpecInterface() __attribute__ ((nothrow));
void _ssdm_op_SpecPipeline() __attribute__ ((nothrow));
void _ssdm_op_SpecDataflowPipeline() __attribute__ ((nothrow));
void _ssdm_op_SpecLatency() __attribute__ ((nothrow));
void _ssdm_op_SpecParallel() __attribute__ ((nothrow));
void _ssdm_op_SpecProtocol() __attribute__ ((nothrow));
void _ssdm_op_SpecOccurrence() __attribute__ ((nothrow));
void _ssdm_op_SpecResource() __attribute__ ((nothrow));
void _ssdm_op_SpecResourceLimit() __attribute__ ((nothrow));
void _ssdm_op_SpecCHCore() __attribute__ ((nothrow));
void _ssdm_op_SpecFUCore() __attribute__ ((nothrow));
void _ssdm_op_SpecIFCore() __attribute__ ((nothrow));
void _ssdm_op_SpecIPCore() __attribute__ ((nothrow));
void _ssdm_op_SpecKeepValue() __attribute__ ((nothrow));
void _ssdm_op_SpecMemCore() __attribute__ ((nothrow));
void _ssdm_op_SpecExt() __attribute__ ((nothrow));
/*void* _ssdm_op_SpecProcess() SSDM_SPEC_ATTR;
void* _ssdm_op_SpecEdge() SSDM_SPEC_ATTR; */
/* Presynthesis directive functions */
void _ssdm_SpecArrayDimSize() __attribute__ ((nothrow));
void _ssdm_RegionBegin() __attribute__ ((nothrow));
void _ssdm_RegionEnd() __attribute__ ((nothrow));
void _ssdm_Unroll() __attribute__ ((nothrow));
void _ssdm_UnrollRegion() __attribute__ ((nothrow));
void _ssdm_InlineAll() __attribute__ ((nothrow));
void _ssdm_InlineLoop() __attribute__ ((nothrow));
void _ssdm_Inline() __attribute__ ((nothrow));
void _ssdm_InlineSelf() __attribute__ ((nothrow));
void _ssdm_InlineRegion() __attribute__ ((nothrow));
void _ssdm_SpecArrayMap() __attribute__ ((nothrow));
void _ssdm_SpecArrayPartition() __attribute__ ((nothrow));
void _ssdm_SpecArrayReshape() __attribute__ ((nothrow));
void _ssdm_SpecStream() __attribute__ ((nothrow));
void _ssdm_SpecExpr() __attribute__ ((nothrow));
void _ssdm_SpecExprBalance() __attribute__ ((nothrow));
void _ssdm_SpecDependence() __attribute__ ((nothrow));
void _ssdm_SpecLoopMerge() __attribute__ ((nothrow));
void _ssdm_SpecLoopFlatten() __attribute__ ((nothrow));
void _ssdm_SpecLoopRewind() __attribute__ ((nothrow));
void _ssdm_SpecFuncInstantiation() __attribute__ ((nothrow));
void _ssdm_SpecFuncBuffer() __attribute__ ((nothrow));
void _ssdm_SpecFuncExtract() __attribute__ ((nothrow));
void _ssdm_SpecConstant() __attribute__ ((nothrow));
void _ssdm_DataPack() __attribute__ ((nothrow));
void _ssdm_SpecDataPack() __attribute__ ((nothrow));
void _ssdm_op_SpecBitsMap() __attribute__ ((nothrow));
void _ssdm_op_SpecLicense() __attribute__ ((nothrow));
/*#define _ssdm_op_WaitUntil(X) while (!(X)) _ssdm_op_Wait(1);
#define _ssdm_op_Delayed(X) X */
# 7 "<command line>" 2
# 1 "<built-in>" 2
# 1 "D:/opt/source/Vivado/Vivado_HLS_Tutorial/Interface_Synthesis/lab4/axi_interfaces_prj/solution2/.autopilot/db/axi_interfaces.pragma.1.c" 2
# 1 "axi_interfaces.c"
# 1 "axi_interfaces.c" 1
# 1 "<built-in>" 1
# 1 "<built-in>" 3
# 147 "<built-in>" 3
# 1 "<command line>" 1
# 1 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/common/technology/autopilot\\etc/autopilot_ssdm_op.h" 1
/* autopilot_ssdm_op.h*/
/*
#- (c) Copyright 2011-2015 Xilinx, Inc. All rights reserved.
#-
#- This file contains confidential and proprietary information
#- of Xilinx, Inc. and is protected under U.S. and
#- international copyright and other intellectual property
#- laws.
#-
#- DISCLAIMER
#- This disclaimer is not a license and does not grant any
#- rights to the materials distributed herewith. Except as
#- otherwise provided in a valid license issued to you by
#- Xilinx, and to the maximum extent permitted by applicable
#- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
#- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
#- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
#- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
#- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
#- (2) Xilinx shall not be liable (whether in contract or tort,
#- including negligence, or under any other theory of
#- liability) for any loss or damage of any kind or nature
#- related to, arising under or in connection with these
#- materials, including for any direct, or any indirect,
#- special, incidental, or consequential loss or damage
#- (including loss of data, profits, goodwill, or any type of
#- loss or damage suffered as a result of any action brought
#- by a third party) even if such damage or loss was
#- reasonably foreseeable or Xilinx had been advised of the
#- possibility of the same.
#-
#- CRITICAL APPLICATIONS
#- Xilinx products are not designed or intended to be fail-
#- safe, or for use in any application requiring fail-safe
#- performance, such as life-support or safety devices or
#- systems, Class III medical devices, nuclear facilities,
#- applications related to the deployment of airbags, or any
#- other applications that could lead to death, personal
#- injury, or severe property or environmental damage
#- (individually and collectively, "Critical
#- Applications"). Customer assumes the sole risk and
#- liability of any use of Xilinx products in Critical
#- Applications, subject only to applicable laws and
#- regulations governing limitations on product liability.
#-
#- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
#- PART OF THIS FILE AT ALL TIMES.
#- ************************************************************************
*
* $Id$
*/
# 280 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/common/technology/autopilot\\etc/autopilot_ssdm_op.h"
/*#define AP_SPEC_ATTR __attribute__ ((pure))*/
/****** SSDM Intrinsics: OPERATIONS ***/
// Interface operations
//typedef unsigned int __attribute__ ((bitwidth(1))) _uint1_;
void _ssdm_op_IfRead() __attribute__ ((nothrow));
void _ssdm_op_IfWrite() __attribute__ ((nothrow));
//_uint1_ _ssdm_op_IfNbRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_op_IfNbWrite() SSDM_OP_ATTR;
//_uint1_ _ssdm_op_IfCanRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_op_IfCanWrite() SSDM_OP_ATTR;
// Stream Intrinsics
void _ssdm_StreamRead() __attribute__ ((nothrow));
void _ssdm_StreamWrite() __attribute__ ((nothrow));
//_uint1_ _ssdm_StreamNbRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_StreamNbWrite() SSDM_OP_ATTR;
//_uint1_ _ssdm_StreamCanRead() SSDM_OP_ATTR;
//_uint1_ _ssdm_StreamCanWrite() SSDM_OP_ATTR;
// Misc
void _ssdm_op_MemShiftRead() __attribute__ ((nothrow));
void _ssdm_op_Wait() __attribute__ ((nothrow));
void _ssdm_op_Poll() __attribute__ ((nothrow));
void _ssdm_op_Return() __attribute__ ((nothrow));
/* SSDM Intrinsics: SPECIFICATIONS */
void _ssdm_op_SpecSynModule() __attribute__ ((nothrow));
void _ssdm_op_SpecTopModule() __attribute__ ((nothrow));
void _ssdm_op_SpecProcessDecl() __attribute__ ((nothrow));
void _ssdm_op_SpecProcessDef() __attribute__ ((nothrow));
void _ssdm_op_SpecPort() __attribute__ ((nothrow));
void _ssdm_op_SpecConnection() __attribute__ ((nothrow));
void _ssdm_op_SpecChannel() __attribute__ ((nothrow));
void _ssdm_op_SpecSensitive() __attribute__ ((nothrow));
void _ssdm_op_SpecModuleInst() __attribute__ ((nothrow));
void _ssdm_op_SpecPortMap() __attribute__ ((nothrow));
void _ssdm_op_SpecReset() __attribute__ ((nothrow));
void _ssdm_op_SpecPlatform() __attribute__ ((nothrow));
void _ssdm_op_SpecClockDomain() __attribute__ ((nothrow));
void _ssdm_op_SpecPowerDomain() __attribute__ ((nothrow));
int _ssdm_op_SpecRegionBegin() __attribute__ ((nothrow));
int _ssdm_op_SpecRegionEnd() __attribute__ ((nothrow));
void _ssdm_op_SpecLoopName() __attribute__ ((nothrow));
void _ssdm_op_SpecLoopTripCount() __attribute__ ((nothrow));
int _ssdm_op_SpecStateBegin() __attribute__ ((nothrow));
int _ssdm_op_SpecStateEnd() __attribute__ ((nothrow));
void _ssdm_op_SpecInterface() __attribute__ ((nothrow));
void _ssdm_op_SpecPipeline() __attribute__ ((nothrow));
void _ssdm_op_SpecDataflowPipeline() __attribute__ ((nothrow));
void _ssdm_op_SpecLatency() __attribute__ ((nothrow));
void _ssdm_op_SpecParallel() __attribute__ ((nothrow));
void _ssdm_op_SpecProtocol() __attribute__ ((nothrow));
void _ssdm_op_SpecOccurrence() __attribute__ ((nothrow));
void _ssdm_op_SpecResource() __attribute__ ((nothrow));
void _ssdm_op_SpecResourceLimit() __attribute__ ((nothrow));
void _ssdm_op_SpecCHCore() __attribute__ ((nothrow));
void _ssdm_op_SpecFUCore() __attribute__ ((nothrow));
void _ssdm_op_SpecIFCore() __attribute__ ((nothrow));
void _ssdm_op_SpecIPCore() __attribute__ ((nothrow));
void _ssdm_op_SpecKeepValue() __attribute__ ((nothrow));
void _ssdm_op_SpecMemCore() __attribute__ ((nothrow));
void _ssdm_op_SpecExt() __attribute__ ((nothrow));
/*void* _ssdm_op_SpecProcess() SSDM_SPEC_ATTR;
void* _ssdm_op_SpecEdge() SSDM_SPEC_ATTR; */
/* Presynthesis directive functions */
void _ssdm_SpecArrayDimSize() __attribute__ ((nothrow));
void _ssdm_RegionBegin() __attribute__ ((nothrow));
void _ssdm_RegionEnd() __attribute__ ((nothrow));
void _ssdm_Unroll() __attribute__ ((nothrow));
void _ssdm_UnrollRegion() __attribute__ ((nothrow));
void _ssdm_InlineAll() __attribute__ ((nothrow));
void _ssdm_InlineLoop() __attribute__ ((nothrow));
void _ssdm_Inline() __attribute__ ((nothrow));
void _ssdm_InlineSelf() __attribute__ ((nothrow));
void _ssdm_InlineRegion() __attribute__ ((nothrow));
void _ssdm_SpecArrayMap() __attribute__ ((nothrow));
void _ssdm_SpecArrayPartition() __attribute__ ((nothrow));
void _ssdm_SpecArrayReshape() __attribute__ ((nothrow));
void _ssdm_SpecStream() __attribute__ ((nothrow));
void _ssdm_SpecExpr() __attribute__ ((nothrow));
void _ssdm_SpecExprBalance() __attribute__ ((nothrow));
void _ssdm_SpecDependence() __attribute__ ((nothrow));
void _ssdm_SpecLoopMerge() __attribute__ ((nothrow));
void _ssdm_SpecLoopFlatten() __attribute__ ((nothrow));
void _ssdm_SpecLoopRewind() __attribute__ ((nothrow));
void _ssdm_SpecFuncInstantiation() __attribute__ ((nothrow));
void _ssdm_SpecFuncBuffer() __attribute__ ((nothrow));
void _ssdm_SpecFuncExtract() __attribute__ ((nothrow));
void _ssdm_SpecConstant() __attribute__ ((nothrow));
void _ssdm_DataPack() __attribute__ ((nothrow));
void _ssdm_SpecDataPack() __attribute__ ((nothrow));
void _ssdm_op_SpecBitsMap() __attribute__ ((nothrow));
void _ssdm_op_SpecLicense() __attribute__ ((nothrow));
/*#define _ssdm_op_WaitUntil(X) while (!(X)) _ssdm_op_Wait(1);
#define _ssdm_op_Delayed(X) X */
# 7 "<command line>" 2
# 1 "<built-in>" 2
# 1 "axi_interfaces.c" 2
/*******************************************************************************
Vendor: Xilinx
Associated Filename: axi_interfaces.c
Purpose: Vivado HLS tutorial example
Device: All
Revision History: March 1, 2013 - initial release
*******************************************************************************
Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
This file contains confidential and proprietary information of Xilinx, Inc. and
is protected under U.S. and international copyright and other intellectual
property laws.
DISCLAIMER
This disclaimer is not a license and does not grant any rights to the materials
distributed herewith. Except as otherwise provided in a valid license issued to
you by Xilinx, and to the maximum extent permitted by applicable law:
(1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND WITH ALL FAULTS, AND XILINX
HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT, OR
FITNESS FOR ANY PARTICULAR PURPOSE; and (2) Xilinx shall not be liable (whether
in contract or tort, including negligence, or under any other theory of
liability) for any loss or damage of any kind or nature related to, arising under
or in connection with these materials, including for any direct, or any indirect,
special, incidental, or consequential loss or damage (including loss of data,
profits, goodwill, or any type of loss or damage suffered as a result of any
action brought by a third party) even if such damage or loss was reasonably
foreseeable or Xilinx had been advised of the possibility of the same.
CRITICAL APPLICATIONS
Xilinx products are not designed or intended to be fail-safe, or for use in any
application requiring fail-safe performance, such as life-support or safety
devices or systems, Class III medical devices, nuclear facilities, applications
related to the deployment of airbags, or any other applications that could lead
to death, personal injury, or severe property or environmental damage
(individually and collectively, "Critical Applications"). Customer asresultes the
sole risk and liability of any use of Xilinx products in Critical Applications,
subject only to applicable laws and regulations governing limitations on product
liability.
THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS PART OF THIS FILE AT
ALL TIMES.
*******************************************************************************/
# 1 "./axi_interfaces.h" 1
/*******************************************************************************
Vendor: Xilinx
Associated Filename: axi_interfaces.h
Purpose: Vivado HLS tutorial example
Device: All
Revision History: March 1, 2013 - initial release
*******************************************************************************
Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
This file contains confidential and proprietary information of Xilinx, Inc. and
is protected under U.S. and international copyright and other intellectual
property laws.
DISCLAIMER
This disclaimer is not a license and does not grant any rights to the materials
distributed herewith. Except as otherwise provided in a valid license issued to
you by Xilinx, and to the maximum extent permitted by applicable law:
(1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND WITH ALL FAULTS, AND XILINX
HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT, OR
FITNESS FOR ANY PARTICULAR PURPOSE; and (2) Xilinx shall not be liable (whether
in contract or tort, including negligence, or under any other theory of
liability) for any loss or damage of any kind or nature related to, arising under
or in connection with these materials, including for any direct, or any indirect,
special, incidental, or consequential loss or damage (including loss of data,
profits, goodwill, or any type of loss or damage suffered as a result of any
action brought by a third party) even if such damage or loss was reasonably
foreseeable or Xilinx had been advised of the possibility of the same.
CRITICAL APPLICATIONS
Xilinx products are not designed or intended to be fail-safe, or for use in any
application requiring fail-safe performance, such as life-support or safety
devices or systems, Class III medical devices, nuclear facilities, applications
related to the deployment of airbags, or any other applications that could lead
to death, personal injury, or severe property or environmental damage
(individually and collectively, "Critical Applications"). Customer asresultes the
sole risk and liability of any use of Xilinx products in Critical Applications,
subject only to applicable laws and regulations governing limitations on product
liability.
THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS PART OF THIS FILE AT
ALL TIMES.
*******************************************************************************/
# 1 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 1 3
/**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the w64 mingw-runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
# 1 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 1 3
/**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the w64 mingw-runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
# 1 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include/_mingw_mac.h" 1 3
/**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the w64 mingw-runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
# 18 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include/_mingw_mac.h" 3
/* mingw.org's version macros: these make gcc to define
MINGW32_SUPPORTS_MT_EH and to use the _CRT_MT global
and the __mingwthr_key_dtor() function from the MinGW
CRT in its private gthr-win32.h header. */
/* MS does not prefix symbols by underscores for 64-bit. */
/* As we have to support older gcc version, which are using underscores
as symbol prefix for x64, we have to check here for the user label
prefix defined by gcc. */
# 62 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include/_mingw_mac.h" 3
/* Use alias for msvcr80 export of get/set_output_format. */
/* Set VC specific compiler target macros. */
# 10 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 2 3
/* C/C++ specific language defines. */
# 32 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
/* Note the extern. This is needed to work around GCC's
limitations in handling dllimport attribute. */
# 147 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
/* Attribute `nonnull' was valid as of gcc 3.3. We don't use GCC's
variadiac macro facility, because variadic macros cause syntax
errors with --traditional-cpp. */
# 225 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
/* High byte is the major version, low byte is the minor. */
# 247 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
/*typedef int __int128 __attribute__ ((__mode__ (TI)));*/
# 277 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
# 1 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\vadefs.h" 1 3
/**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the w64 mingw-runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
# 14 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\vadefs.h" 3
# 1 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 1 3
/**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the w64 mingw-runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
# 674 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
# 1 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include/sdks/_mingw_directx.h" 1 3
# 674 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 2 3
# 1 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include/sdks/_mingw_ddk.h" 1 3
# 675 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 2 3
# 13 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\vadefs.h" 2 3
#pragma pack(push,_CRT_PACKING)
typedef __builtin_va_list __gnuc_va_list;
typedef __gnuc_va_list va_list;
# 46 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\vadefs.h" 3
/* Use GCC builtins */
# 102 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\vadefs.h" 3
#pragma pack(pop)
# 277 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 2 3
#pragma pack(push,_CRT_PACKING)
# 316 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
/* We have to define _DLL for gcc based mingw version. This define is set
by VC, when DLL-based runtime is used. So, gcc based runtime just have
DLL-base runtime, therefore this define has to be set.
As our headers are possibly used by windows compiler having a static
C-runtime, we make this definition gnu compiler specific here. */
# 370 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
__extension__ typedef unsigned long long size_t;
# 380 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
__extension__ typedef long long ssize_t;
# 392 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
__extension__ typedef long long intptr_t;
# 405 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
__extension__ typedef unsigned long long uintptr_t;
# 418 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
__extension__ typedef long long ptrdiff_t;
# 428 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
typedef unsigned short wchar_t;
typedef unsigned short wint_t;
typedef unsigned short wctype_t;
# 456 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
typedef int errno_t;
typedef long __time32_t;
__extension__ typedef long long __time64_t;
typedef __time64_t time_t;
# 518 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
/* _dowildcard is an int that controls the globbing of the command line.
* The MinGW32 (mingw.org) runtime calls it _CRT_glob, so we are adding
* a compatibility definition here: you can use either of _CRT_glob or
* _dowildcard .
* If _dowildcard is non-zero, the command line will be globbed: *.*
* will be expanded to be all files in the startup directory.
* In the mingw-w64 library a _dowildcard variable is defined as being
* 0, therefore command line globbing is DISABLED by default. To turn it
* on and to leave wildcard command line processing MS's globbing code,
* include a line in one of your source modules defining _dowildcard and
* setting it to -1, like so:
* int _dowildcard = -1;
*/
# 605 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw.h" 3
/* MSVC-isms: */
struct threadlocaleinfostruct;
struct threadmbcinfostruct;
typedef struct threadlocaleinfostruct *pthreadlocinfo;
typedef struct threadmbcinfostruct *pthreadmbcinfo;
struct __lc_time_data;
typedef struct localeinfo_struct {
pthreadlocinfo locinfo;
pthreadmbcinfo mbcinfo;
} _locale_tstruct,*_locale_t;
typedef struct tagLC_ID {
unsigned short wLanguage;
unsigned short wCountry;
unsigned short wCodePage;
} LC_ID,*LPLC_ID;
typedef struct threadlocaleinfostruct {
int refcount;
unsigned int lc_codepage;
unsigned int lc_collate_cp;
unsigned long lc_handle[6];
LC_ID lc_id[6];
struct {
char *locale;
wchar_t *wlocale;
int *refcount;
int *wrefcount;
} lc_category[6];
int lc_clike;
int mb_cur_max;
int *lconv_intl_refcount;
int *lconv_num_refcount;
int *lconv_mon_refcount;
struct lconv *lconv;
int *ctype1_refcount;
unsigned short *ctype1;
const unsigned short *pctype;
const unsigned char *pclmap;
const unsigned char *pcumap;
struct __lc_time_data *lc_time_curr;
} threadlocinfo;
/* mingw-w64 specific functions: */
const char *__mingw_get_crt_info (void);
#pragma pack(pop)
# 9 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 2 3
# 1 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw_print_push.h" 1 3
/**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the w64 mingw-runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
/* Undefine __mingw_<printf> macros. */
# 11 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 2 3
#pragma pack(push,_CRT_PACKING)
# 26 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 3
struct _iobuf {
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname;
};
typedef struct _iobuf FILE;
# 84 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 3
typedef long _off_t;
typedef long off_t;
__extension__ typedef long long _off64_t;
__extension__ typedef long long off64_t;
__attribute__ ((__dllimport__)) FILE * __iob_func(void);
# 120 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 3
__extension__ typedef long long fpos_t;
# 157 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 3
__attribute__ ((__dllimport__)) int _filbuf(FILE *_File);
__attribute__ ((__dllimport__)) int _flsbuf(int _Ch,FILE *_File);
__attribute__ ((__dllimport__)) FILE * _fsopen(const char *_Filename,const char *_Mode,int _ShFlag);
void clearerr(FILE *_File);
int fclose(FILE *_File);
__attribute__ ((__dllimport__)) int _fcloseall(void);
__attribute__ ((__dllimport__)) FILE * _fdopen(int _FileHandle,const char *_Mode);
int feof(FILE *_File);
int ferror(FILE *_File);
int fflush(FILE *_File);
int fgetc(FILE *_File);
__attribute__ ((__dllimport__)) int _fgetchar(void);
int fgetpos(FILE * __restrict__ _File ,fpos_t * __restrict__ _Pos);
char * fgets(char * __restrict__ _Buf,int _MaxCount,FILE * __restrict__ _File);
__attribute__ ((__dllimport__)) int _fileno(FILE *_File);
__attribute__ ((__dllimport__)) char * _tempnam(const char *_DirName,const char *_FilePrefix);
__attribute__ ((__dllimport__)) int _flushall(void);
FILE * fopen(const char * __restrict__ _Filename,const char * __restrict__ _Mode) ;
FILE *fopen64(const char * __restrict__ filename,const char * __restrict__ mode);
int fprintf(FILE * __restrict__ _File,const char * __restrict__ _Format,...);
int fputc(int _Ch,FILE *_File);
__attribute__ ((__dllimport__)) int _fputchar(int _Ch);
int fputs(const char * __restrict__ _Str,FILE * __restrict__ _File);
size_t fread(void * __restrict__ _DstBuf,size_t _ElementSize,size_t _Count,FILE * __restrict__ _File);
FILE * freopen(const char * __restrict__ _Filename,const char * __restrict__ _Mode,FILE * __restrict__ _File) ;
int fscanf(FILE * __restrict__ _File,const char * __restrict__ _Format,...) ;
int _fscanf_l(FILE * __restrict__ _File,const char * __restrict__ _Format,_locale_t locale,...) ;
int fsetpos(FILE *_File,const fpos_t *_Pos);
int fseek(FILE *_File,long _Offset,int _Origin);
int fseeko64(FILE* stream, _off64_t offset, int whence);
long ftell(FILE *_File);
_off64_t ftello64(FILE * stream);
__extension__ int _fseeki64(FILE *_File,long long _Offset,int _Origin);
__extension__ long long _ftelli64(FILE *_File);
size_t fwrite(const void * __restrict__ _Str,size_t _Size,size_t _Count,FILE * __restrict__ _File);
int getc(FILE *_File);
int getchar(void);
__attribute__ ((__dllimport__)) int _getmaxstdio(void);
char * gets(char *_Buffer) ;
int _getw(FILE *_File);
void perror(const char *_ErrMsg);
__attribute__ ((__dllimport__)) int _pclose(FILE *_File);
__attribute__ ((__dllimport__)) FILE * _popen(const char *_Command,const char *_Mode);
int printf(const char * __restrict__ _Format,...);
int putc(int _Ch,FILE *_File);
int putchar(int _Ch);
int puts(const char *_Str);
__attribute__ ((__dllimport__)) int _putw(int _Word,FILE *_File);
int remove(const char *_Filename);
int rename(const char *_OldFilename,const char *_NewFilename);
__attribute__ ((__dllimport__)) int _unlink(const char *_Filename);
int unlink(const char *_Filename) ;
void rewind(FILE *_File);
__attribute__ ((__dllimport__)) int _rmtmp(void);
int scanf(const char * __restrict__ _Format,...) ;
int _scanf_l(const char * __restrict__ format,_locale_t locale,... ) ;
void setbuf(FILE * __restrict__ _File,char * __restrict__ _Buffer) ;
__attribute__ ((__dllimport__)) int _setmaxstdio(int _Max);
__attribute__ ((__dllimport__)) unsigned int _set_output_format(unsigned int _Format);
__attribute__ ((__dllimport__)) unsigned int _get_output_format(void);
unsigned int __mingw_set_output_format(unsigned int _Format);
unsigned int __mingw_get_output_format(void);
int setvbuf(FILE * __restrict__ _File,char * __restrict__ _Buf,int _Mode,size_t _Size);
__attribute__ ((__dllimport__)) int _scprintf(const char * __restrict__ _Format,...);
int sscanf(const char * __restrict__ _Src,const char * __restrict__ _Format,...) ;
int _sscanf_l(const char * __restrict__ buffer,const char * __restrict__ format,_locale_t locale,...) ;
__attribute__ ((__dllimport__)) int _snscanf(const char * __restrict__ _Src,size_t _MaxCount,const char * __restrict__ _Format,...) ;
__attribute__ ((__dllimport__)) int _snscanf_l(const char * __restrict__ input,size_t length,const char * __restrict__ format,_locale_t locale,...) ;
FILE * tmpfile(void) ;
char * tmpnam(char *_Buffer);
int ungetc(int _Ch,FILE *_File);
int vfprintf(FILE * __restrict__ _File,const char * __restrict__ _Format,va_list _ArgList);
int vprintf(const char * __restrict__ _Format,va_list _ArgList);
/* Make sure macros are not defined. */
extern
__attribute__((__format__ (gnu_printf, 3, 0))) __attribute__ ((__nonnull__ (3)))
int __mingw_vsnprintf(char * __restrict__ _DstBuf,size_t _MaxCount,const char * __restrict__ _Format,
va_list _ArgList);
extern
__attribute__((__format__ (gnu_printf, 3, 4))) __attribute__ ((__nonnull__ (3)))
int __mingw_snprintf(char * __restrict__ s, size_t n, const char * __restrict__ format, ...);
extern
__attribute__((__format__ (gnu_printf, 1, 2))) __attribute__ ((__nonnull__ (1)))
int __mingw_printf(const char * __restrict__ , ... ) __attribute__ ((__nothrow__));
extern
__attribute__((__format__ (gnu_printf, 1, 0))) __attribute__ ((__nonnull__ (1)))
int __mingw_vprintf (const char * __restrict__ , va_list) __attribute__ ((__nothrow__));
extern
__attribute__((__format__ (gnu_printf, 2, 3))) __attribute__ ((__nonnull__ (2)))
int __mingw_fprintf (FILE * __restrict__ , const char * __restrict__ , ...) __attribute__ ((__nothrow__));
extern
__attribute__((__format__ (gnu_printf, 2, 0))) __attribute__ ((__nonnull__ (2)))
int __mingw_vfprintf (FILE * __restrict__ , const char * __restrict__ , va_list) __attribute__ ((__nothrow__));
extern
__attribute__((__format__ (gnu_printf, 2, 3))) __attribute__ ((__nonnull__ (2)))
int __mingw_sprintf (char * __restrict__ , const char * __restrict__ , ...) __attribute__ ((__nothrow__));
extern
__attribute__((__format__ (gnu_printf, 2, 0))) __attribute__ ((__nonnull__ (2)))
int __mingw_vsprintf (char * __restrict__ , const char * __restrict__ , va_list) __attribute__ ((__nothrow__));
__attribute__ ((__dllimport__)) int _snprintf(char * __restrict__ _Dest,size_t _Count,const char * __restrict__ _Format,...) ;
__attribute__ ((__dllimport__)) int _snprintf_l(char * __restrict__ buffer,size_t count,const char * __restrict__ format,_locale_t locale,...) ;
__attribute__ ((__dllimport__)) int _vsnprintf(char * __restrict__ _Dest,size_t _Count,const char * __restrict__ _Format,va_list _Args) ;
__attribute__ ((__dllimport__)) int _vsnprintf_l(char * __restrict__ buffer,size_t count,const char * __restrict__ format,_locale_t locale,va_list argptr) ;
int sprintf(char * __restrict__ _Dest,const char * __restrict__ _Format,...) ;
int _sprintf_l(char * __restrict__ buffer,const char * __restrict__ format,_locale_t locale,...) ;
int vsprintf(char * __restrict__ _Dest,const char * __restrict__ _Format,va_list _Args) ;
/* this is here to deal with software defining
* vsnprintf as _vsnprintf, eg. libxml2. */
int vsnprintf(char * __restrict__ _DstBuf,size_t _MaxCount,const char * __restrict__ _Format,va_list _ArgList) ;
int snprintf(char * __restrict__ s, size_t n, const char * __restrict__ format, ...);
# 312 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 3
int vscanf(const char * __restrict__ Format, va_list argp);
int vfscanf (FILE * __restrict__ fp, const char * __restrict__ Format,va_list argp);
int vsscanf (const char * __restrict__ _Str,const char * __restrict__ Format,va_list argp);
__attribute__ ((__dllimport__)) int _vscprintf(const char * __restrict__ _Format,va_list _ArgList);
__attribute__ ((__dllimport__)) int _set_printf_count_output(int _Value);
__attribute__ ((__dllimport__)) int _get_printf_count_output(void);
# 330 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 3
__attribute__ ((__dllimport__)) FILE * _wfsopen(const wchar_t *_Filename,const wchar_t *_Mode,int _ShFlag);
wint_t fgetwc(FILE *_File);
__attribute__ ((__dllimport__)) wint_t _fgetwchar(void);
wint_t fputwc(wchar_t _Ch,FILE *_File);
__attribute__ ((__dllimport__)) wint_t _fputwchar(wchar_t _Ch);
wint_t getwc(FILE *_File);
wint_t getwchar(void);
wint_t putwc(wchar_t _Ch,FILE *_File);
wint_t putwchar(wchar_t _Ch);
wint_t ungetwc(wint_t _Ch,FILE *_File);
wchar_t * fgetws(wchar_t * __restrict__ _Dst,int _SizeInWords,FILE * __restrict__ _File);
int fputws(const wchar_t * __restrict__ _Str,FILE * __restrict__ _File);
__attribute__ ((__dllimport__)) wchar_t * _getws(wchar_t *_String) ;
__attribute__ ((__dllimport__)) int _putws(const wchar_t *_Str);
int fwprintf(FILE * __restrict__ _File,const wchar_t * __restrict__ _Format,...);
int wprintf(const wchar_t * __restrict__ _Format,...);
__attribute__ ((__dllimport__)) int _scwprintf(const wchar_t * __restrict__ _Format,...);
int vfwprintf(FILE * __restrict__ _File,const wchar_t * __restrict__ _Format,va_list _ArgList);
int vwprintf(const wchar_t * __restrict__ _Format,va_list _ArgList);
__attribute__ ((__dllimport__)) int swprintf(wchar_t * __restrict__ , const wchar_t * __restrict__ , ...) ;
__attribute__ ((__dllimport__)) int _swprintf_l(wchar_t * __restrict__ buffer,size_t count,const wchar_t * __restrict__ format,_locale_t locale,... ) ;
__attribute__ ((__dllimport__)) int vswprintf(wchar_t * __restrict__ , const wchar_t * __restrict__ ,va_list) ;
__attribute__ ((__dllimport__)) int _swprintf_c(wchar_t * __restrict__ _DstBuf,size_t _SizeInWords,const wchar_t * __restrict__ _Format,...);
__attribute__ ((__dllimport__)) int _vswprintf_c(wchar_t * __restrict__ _DstBuf,size_t _SizeInWords,const wchar_t * __restrict__ _Format,va_list _ArgList);
__attribute__ ((__dllimport__)) int _snwprintf(wchar_t * __restrict__ _Dest,size_t _Count,const wchar_t * __restrict__ _Format,...) ;
__attribute__ ((__dllimport__)) int _vsnwprintf(wchar_t * __restrict__ _Dest,size_t _Count,const wchar_t * __restrict__ _Format,va_list _Args) ;
int snwprintf (wchar_t * __restrict__ s, size_t n, const wchar_t * __restrict__ format, ...);
int vsnwprintf (wchar_t * __restrict__ , size_t, const wchar_t * __restrict__ , va_list);
# 373 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 3
int vwscanf (const wchar_t * __restrict__ , va_list);
int vfwscanf (FILE * __restrict__ ,const wchar_t * __restrict__ ,va_list);
int vswscanf (const wchar_t * __restrict__ ,const wchar_t * __restrict__ ,va_list);
__attribute__ ((__dllimport__)) int _fwprintf_p(FILE * __restrict__ _File,const wchar_t * __restrict__ _Format,...);
__attribute__ ((__dllimport__)) int _wprintf_p(const wchar_t * __restrict__ _Format,...);
__attribute__ ((__dllimport__)) int _vfwprintf_p(FILE * __restrict__ _File,const wchar_t * __restrict__ _Format,va_list _ArgList);
__attribute__ ((__dllimport__)) int _vwprintf_p(const wchar_t * __restrict__ _Format,va_list _ArgList);
__attribute__ ((__dllimport__)) int _swprintf_p(wchar_t * __restrict__ _DstBuf,size_t _MaxCount,const wchar_t * __restrict__ _Format,...);
__attribute__ ((__dllimport__)) int _vswprintf_p(wchar_t * __restrict__ _DstBuf,size_t _MaxCount,const wchar_t * __restrict__ _Format,va_list _ArgList);
__attribute__ ((__dllimport__)) int _scwprintf_p(const wchar_t * __restrict__ _Format,...);
__attribute__ ((__dllimport__)) int _vscwprintf_p(const wchar_t * __restrict__ _Format,va_list _ArgList);
__attribute__ ((__dllimport__)) int _wprintf_l(const wchar_t * __restrict__ _Format,_locale_t _Locale,...);
__attribute__ ((__dllimport__)) int _wprintf_p_l(const wchar_t * __restrict__ _Format,_locale_t _Locale,...);
__attribute__ ((__dllimport__)) int _vwprintf_l(const wchar_t * __restrict__ _Format,_locale_t _Locale,va_list _ArgList);
__attribute__ ((__dllimport__)) int _vwprintf_p_l(const wchar_t * __restrict__ _Format,_locale_t _Locale,va_list _ArgList);
__attribute__ ((__dllimport__)) int _fwprintf_l(FILE * __restrict__ _File,const wchar_t * __restrict__ _Format,_locale_t _Locale,...);
__attribute__ ((__dllimport__)) int _fwprintf_p_l(FILE * __restrict__ _File,const wchar_t * __restrict__ _Format,_locale_t _Locale,...);
__attribute__ ((__dllimport__)) int _vfwprintf_l(FILE * __restrict__ _File,const wchar_t * __restrict__ _Format,_locale_t _Locale,va_list _ArgList);
__attribute__ ((__dllimport__)) int _vfwprintf_p_l(FILE * __restrict__ _File,const wchar_t * __restrict__ _Format,_locale_t _Locale,va_list _ArgList);
__attribute__ ((__dllimport__)) int _swprintf_c_l(wchar_t * __restrict__ _DstBuf,size_t _MaxCount,const wchar_t * __restrict__ _Format,_locale_t _Locale,...);
__attribute__ ((__dllimport__)) int _swprintf_p_l(wchar_t * __restrict__ _DstBuf,size_t _MaxCount,const wchar_t * __restrict__ _Format,_locale_t _Locale,...);
__attribute__ ((__dllimport__)) int _vswprintf_c_l(wchar_t * __restrict__ _DstBuf,size_t _MaxCount,const wchar_t * __restrict__ _Format,_locale_t _Locale,va_list _ArgList);
__attribute__ ((__dllimport__)) int _vswprintf_p_l(wchar_t * __restrict__ _DstBuf,size_t _MaxCount,const wchar_t * __restrict__ _Format,_locale_t _Locale,va_list _ArgList);
__attribute__ ((__dllimport__)) int _scwprintf_l(const wchar_t * __restrict__ _Format,_locale_t _Locale,...);
__attribute__ ((__dllimport__)) int _scwprintf_p_l(const wchar_t * __restrict__ _Format,_locale_t _Locale,...);
__attribute__ ((__dllimport__)) int _vscwprintf_p_l(const wchar_t * __restrict__ _Format,_locale_t _Locale,va_list _ArgList);
__attribute__ ((__dllimport__)) int _snwprintf_l(wchar_t * __restrict__ _DstBuf,size_t _MaxCount,const wchar_t * __restrict__ _Format,_locale_t _Locale,...);
__attribute__ ((__dllimport__)) int _vsnwprintf_l(wchar_t * __restrict__ _DstBuf,size_t _MaxCount,const wchar_t * __restrict__ _Format,_locale_t _Locale,va_list _ArgList) ;
__attribute__ ((__dllimport__)) int _swprintf(wchar_t * __restrict__ _Dest,const wchar_t * __restrict__ _Format,...);
__attribute__ ((__dllimport__)) int _vswprintf(wchar_t * __restrict__ _Dest,const wchar_t * __restrict__ _Format,va_list _Args);
__attribute__ ((__dllimport__)) int __swprintf_l(wchar_t * __restrict__ _Dest,const wchar_t * __restrict__ _Format,_locale_t _Plocinfo,...) ;
__attribute__ ((__dllimport__)) int _vswprintf_l(wchar_t * __restrict__ buffer,size_t count,const wchar_t * __restrict__ format,_locale_t locale,va_list argptr) ;
__attribute__ ((__dllimport__)) int __vswprintf_l(wchar_t * __restrict__ _Dest,const wchar_t * __restrict__ _Format,_locale_t _Plocinfo,va_list _Args) ;
# 417 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 3
__attribute__ ((__dllimport__)) wchar_t * _wtempnam(const wchar_t *_Directory,const wchar_t *_FilePrefix);
__attribute__ ((__dllimport__)) int _vscwprintf(const wchar_t * __restrict__ _Format,va_list _ArgList);
__attribute__ ((__dllimport__)) int _vscwprintf_l(const wchar_t * __restrict__ _Format,_locale_t _Locale,va_list _ArgList);
int fwscanf(FILE * __restrict__ _File,const wchar_t * __restrict__ _Format,...) ;
__attribute__ ((__dllimport__)) int _fwscanf_l(FILE * __restrict__ _File,const wchar_t * __restrict__ _Format,_locale_t _Locale,...) ;
int swscanf(const wchar_t * __restrict__ _Src,const wchar_t * __restrict__ _Format,...) ;
__attribute__ ((__dllimport__)) int _swscanf_l(const wchar_t * __restrict__ _Src,const wchar_t * __restrict__ _Format,_locale_t _Locale,...) ;
__attribute__ ((__dllimport__)) int _snwscanf(const wchar_t * __restrict__ _Src,size_t _MaxCount,const wchar_t * __restrict__ _Format,...);
__attribute__ ((__dllimport__)) int _snwscanf_l(const wchar_t * __restrict__ _Src,size_t _MaxCount,const wchar_t * __restrict__ _Format,_locale_t _Locale,...);
int wscanf(const wchar_t * __restrict__ _Format,...) ;
__attribute__ ((__dllimport__)) int _wscanf_l(const wchar_t * __restrict__ _Format,_locale_t _Locale,...) ;
__attribute__ ((__dllimport__)) FILE * _wfdopen(int _FileHandle ,const wchar_t *_Mode);
__attribute__ ((__dllimport__)) FILE * _wfopen(const wchar_t * __restrict__ _Filename,const wchar_t *__restrict__ _Mode) ;
__attribute__ ((__dllimport__)) FILE * _wfreopen(const wchar_t * __restrict__ _Filename,const wchar_t * __restrict__ _Mode,FILE * __restrict__ _OldFile) ;
__attribute__ ((__dllimport__)) void _wperror(const wchar_t *_ErrMsg);
__attribute__ ((__dllimport__)) FILE * _wpopen(const wchar_t *_Command,const wchar_t *_Mode);
__attribute__ ((__dllimport__)) int _wremove(const wchar_t *_Filename);
__attribute__ ((__dllimport__)) wchar_t * _wtmpnam(wchar_t *_Buffer);
__attribute__ ((__dllimport__)) wint_t _fgetwc_nolock(FILE *_File);
__attribute__ ((__dllimport__)) wint_t _fputwc_nolock(wchar_t _Ch,FILE *_File);
__attribute__ ((__dllimport__)) wint_t _ungetwc_nolock(wint_t _Ch,FILE *_File);
# 475 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 3
__attribute__ ((__dllimport__)) void _lock_file(FILE *_File);
__attribute__ ((__dllimport__)) void _unlock_file(FILE *_File);
__attribute__ ((__dllimport__)) int _fclose_nolock(FILE *_File);
__attribute__ ((__dllimport__)) int _fflush_nolock(FILE *_File);
__attribute__ ((__dllimport__)) size_t _fread_nolock(void * __restrict__ _DstBuf,size_t _ElementSize,size_t _Count,FILE * __restrict__ _File);
__attribute__ ((__dllimport__)) int _fseek_nolock(FILE *_File,long _Offset,int _Origin);
__attribute__ ((__dllimport__)) long _ftell_nolock(FILE *_File);
__extension__ __attribute__ ((__dllimport__)) int _fseeki64_nolock(FILE *_File,long long _Offset,int _Origin);
__extension__ __attribute__ ((__dllimport__)) long long _ftelli64_nolock(FILE *_File);
__attribute__ ((__dllimport__)) size_t _fwrite_nolock(const void * __restrict__ _DstBuf,size_t _Size,size_t _Count,FILE * __restrict__ _File);
__attribute__ ((__dllimport__)) int _ungetc_nolock(int _Ch,FILE *_File);
char * tempnam(const char *_Directory,const char *_FilePrefix) ;
int fcloseall(void) ;
FILE * fdopen(int _FileHandle,const char *_Format) ;
int fgetchar(void) ;
int fileno(FILE *_File) ;
int flushall(void) ;
int fputchar(int _Ch) ;
int getw(FILE *_File) ;
int putw(int _Ch,FILE *_File) ;
int rmtmp(void) ;
#pragma pack(pop)
# 1 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\sec_api/stdio_s.h" 1 3
/**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the w64 mingw-runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
# 1 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 1 3
/**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the w64 mingw-runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
# 9 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\sec_api/stdio_s.h" 2 3
# 509 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 2 3
# 1 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\_mingw_print_pop.h" 1 3
/**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the w64 mingw-runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
/* Define __mingw_<printf> macros. */
# 511 "C:/opt/winprog/Xilinx/Vivado_HLS/2015.2/win64/tools/clang/bin/../lib/clang/3.1/../../../x86_64-w64-mingw32/include\\stdio.h" 2 3
# 49 "./axi_interfaces.h" 2
typedef short din_t;
typedef short dout_t;
typedef int dacc_t;
void axi_interfaces (dout_t d_o[8 * 4], din_t d_i[8 * 4]);
# 47 "axi_interfaces.c" 2
// The data comes in organized in a single array.
// - The first sample for the first channel (CHAN)
// - Then the first sample for the 2nd channel etc.
// The channels are accumulated independently
// E.g. For 8 channels:
// Array Order : 0 1 2 3 4 5 6 7 8 9 10 etc. 16 etc...
// Sample Order: A0 B0 C0 D0 E0 F0 G0 H0 A1 B1 C2 etc. A2 etc...
// Output Order: A0 B0 C0 D0 E0 F0 G0 H0 A0+A1 B0+B1 C0+C2 etc. A0+A1+A2 etc...
void axi_interfaces (dout_t d_o[8 * 4], din_t d_i[8 * 4]) {_ssdm_SpecArrayDimSize(d_o,8 * 4);_ssdm_SpecArrayDimSize(d_i,8 * 4);
_ssdm_op_SpecInterface(0, "s_axilite", 0, 0, 0, 0, "", "", "");
# 57 "axi_interfaces.c"
_ssdm_op_SpecInterface(d_i, "axis", 0, 0, 0, 0, "", "", "");
# 57 "axi_interfaces.c"
_ssdm_SpecArrayPartition( d_i, 1, "CYCLIC", 8, "");
# 57 "axi_interfaces.c"
_ssdm_op_SpecInterface(d_o, "axis", 0, 0, 0, 0, "", "", "");
# 57 "axi_interfaces.c"
_ssdm_SpecArrayPartition( d_o, 1, "CYCLIC", 8, "");
# 57 "axi_interfaces.c"
int i, rem;
// Store accumulated data
static dacc_t acc[8];
// Accumulate each channel
For_Loop: for (i=0;i<8 * 4;i++) {
_ssdm_op_SpecPipeline(1, 1, 1, 0, ""); _ssdm_SpecLoopRewind(0, "");
# 64 "axi_interfaces.c"
_ssdm_Unroll(1, 0, 8, "");
# 64 "axi_interfaces.c"
rem=i%8;
acc[rem] = acc[rem] + d_i[i];
d_o[i] = acc[rem];
}
}
|
the_stack_data/387483.c | /**
******************************************************************************
* @file stm32l1xx_ll_dac.c
* @author MCD Application Team
* @version V1.2.0
* @date 01-July-2016
* @brief DAC 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 "stm32l1xx_ll_dac.h"
#include "stm32l1xx_ll_bus.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32L1xx_LL_Driver
* @{
*/
#if defined (DAC1)
/** @addtogroup DAC_LL DAC
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup DAC_LL_Private_Macros
* @{
*/
#define IS_LL_DAC_CHANNEL(__DACX__, __DAC_CHANNEL__) \
( \
((__DAC_CHANNEL__) == LL_DAC_CHANNEL_1) \
|| ((__DAC_CHANNEL__) == LL_DAC_CHANNEL_2) \
)
#define IS_LL_DAC_TRIGGER_SOURCE(__TRIGGER_SOURCE__) \
( ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_SOFTWARE) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM2_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM4_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM6_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM7_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_TIM9_TRGO) \
|| ((__TRIGGER_SOURCE__) == LL_DAC_TRIG_EXT_EXTI_LINE9) \
)
#define IS_LL_DAC_WAVE_AUTO_GENER_MODE(__WAVE_AUTO_GENERATION_MODE__) \
( ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_NONE) \
|| ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_NOISE) \
|| ((__WAVE_AUTO_GENERATION_MODE__) == LL_DAC_WAVE_AUTO_GENERATION_TRIANGLE) \
)
#define IS_LL_DAC_WAVE_AUTO_GENER_CONFIG(__WAVE_AUTO_GENERATION_CONFIG__) \
( ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BIT0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS1_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS2_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS3_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS4_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS5_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS6_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS7_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS8_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS9_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS10_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_NOISE_LFSR_UNMASK_BITS11_0) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_1) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_3) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_7) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_15) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_31) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_63) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_127) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_255) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_511) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_1023) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_2047) \
|| ((__WAVE_AUTO_GENERATION_CONFIG__) == LL_DAC_TRIANGLE_AMPLITUDE_4095) \
)
#define IS_LL_DAC_OUTPUT_BUFFER(__OUTPUT_BUFFER__) \
( ((__OUTPUT_BUFFER__) == LL_DAC_OUTPUT_BUFFER_ENABLE) \
|| ((__OUTPUT_BUFFER__) == LL_DAC_OUTPUT_BUFFER_DISABLE) \
)
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup DAC_LL_Exported_Functions
* @{
*/
/** @addtogroup DAC_LL_EF_Init
* @{
*/
/**
* @brief De-initialize registers of the selected DAC instance
* to their default reset values.
* @param DACx DAC instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: DAC registers are de-initialized
* - ERROR: not applicable
*/
ErrorStatus LL_DAC_DeInit(DAC_TypeDef *DACx)
{
/* Check the parameters */
assert_param(IS_DAC_ALL_INSTANCE(DACx));
/* Force reset of DAC clock */
LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_DAC1);
/* Release reset of DAC clock */
LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_DAC1);
return SUCCESS;
}
/**
* @brief Initialize some features of DAC instance.
* @note The setting of these parameters by function @ref LL_DAC_Init()
* is conditioned to DAC state:
* DAC instance must be disabled.
* @param DACx DAC instance
* @param DAC_Channel This parameter can be one of the following values:
* @arg @ref LL_DAC_CHANNEL_1
* @arg @ref LL_DAC_CHANNEL_2
* @param DAC_InitStruct Pointer to a @ref LL_DAC_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: DAC registers are initialized
* - ERROR: DAC registers are not initialized
*/
ErrorStatus LL_DAC_Init(DAC_TypeDef *DACx, uint32_t DAC_Channel, LL_DAC_InitTypeDef *DAC_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_DAC_ALL_INSTANCE(DACx));
assert_param(IS_LL_DAC_CHANNEL(DACx, DAC_Channel));
assert_param(IS_LL_DAC_TRIGGER_SOURCE(DAC_InitStruct->TriggerSource));
assert_param(IS_LL_DAC_OUTPUT_BUFFER(DAC_InitStruct->OutputBuffer));
assert_param(IS_LL_DAC_WAVE_AUTO_GENER_MODE(DAC_InitStruct->WaveAutoGeneration));
if (DAC_InitStruct->WaveAutoGeneration != LL_DAC_WAVE_AUTO_GENERATION_NONE)
{
assert_param(IS_LL_DAC_WAVE_AUTO_GENER_CONFIG(DAC_InitStruct->WaveAutoGenerationConfig));
}
/* Note: Hardware constraint (refer to description of this function) */
/* DAC instance must be disabled. */
if(LL_DAC_IsEnabled(DACx, DAC_Channel) == 0U)
{
/* Configuration of DAC channel: */
/* - TriggerSource */
/* - WaveAutoGeneration */
/* - OutputBuffer */
if (DAC_InitStruct->WaveAutoGeneration != LL_DAC_WAVE_AUTO_GENERATION_NONE)
{
MODIFY_REG(DACx->CR,
( DAC_CR_TSEL1
| DAC_CR_WAVE1
| DAC_CR_MAMP1
| DAC_CR_BOFF1
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
,
( DAC_InitStruct->TriggerSource
| DAC_InitStruct->WaveAutoGeneration
| DAC_InitStruct->WaveAutoGenerationConfig
| DAC_InitStruct->OutputBuffer
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
);
}
else
{
MODIFY_REG(DACx->CR,
( DAC_CR_TSEL1
| DAC_CR_WAVE1
| DAC_CR_BOFF1
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
,
( DAC_InitStruct->TriggerSource
| LL_DAC_WAVE_AUTO_GENERATION_NONE
| DAC_InitStruct->OutputBuffer
) << (DAC_Channel & DAC_CR_CHX_BITOFFSET_MASK)
);
}
}
else
{
/* Initialization error: DAC instance is not disabled. */
status = ERROR;
}
return status;
}
/**
* @brief Set each @ref LL_DAC_InitTypeDef field to default value.
* @param DAC_InitStruct pointer to a @ref LL_DAC_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_DAC_StructInit(LL_DAC_InitTypeDef *DAC_InitStruct)
{
/* Set DAC_InitStruct fields to default values */
DAC_InitStruct->TriggerSource = LL_DAC_TRIG_SOFTWARE;
DAC_InitStruct->WaveAutoGeneration = LL_DAC_WAVE_AUTO_GENERATION_NONE;
/* Note: Parameter discarded if wave auto generation is disabled, */
/* set anyway to its default value. */
DAC_InitStruct->WaveAutoGenerationConfig = LL_DAC_NOISE_LFSR_UNMASK_BIT0;
DAC_InitStruct->OutputBuffer = LL_DAC_OUTPUT_BUFFER_ENABLE;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* DAC1 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/101759.c | #include <stdio.h>
#include <time.h>
#include <math.h>
int h[50];
void heapify(int h[],int n)
{
int i,j,n1,k,heap,v;
n1=n;
for(i=n/2; i>=1; i--)
{
k=i;
v=h[k];
heap=0;
while(!(heap)&&(2*k)<=n1)
{
j=2*k;
if(j<n1)
if(h[j]<h[j++])
j=j+1;
if(v>=h[j])
heap=1;
else
{
h[k]=h[j];
k=j;
}
}
h[k]=v;
}
}
void main()
{
int i,n,size,t;
printf("Enter the value of n \n");
scanf("%d",&n);
printf("Enter the array elements \n");
for(i=1; i<=n; i++)
scanf("%d",&h[i]);
heapify(h,n);
printf("Elements heapified \n");
for(i=1; i<=n; i++)
printf("%d \t",h[i]);
for(i=n; i>=1; i--)
{
t=h[1];
h[1]=h[i];
h[i]=t;
size=i-1;
heapify(h,size);
}
printf("ROtated elements are: \n");
for(i=1; i<=n; i++)
printf("%d \t",h[i]);
}
|
the_stack_data/90761501.c | #ifdef CS333_P3P4
#include "user.h"
#include "types.h"
int
main(){
printf(1, "forking process\n");
int rc = fork();
if(rc == 0){
printf(1,"Child is asleep\n");
sleep(10000); //sleep for 5 seconds to allow user kill
}
else if(rc < 0){
printf(2,"Fork error");
exit();
}
else{
printf(1,"Parent is asleep, kill child process before I wake up!\n");
sleep(10000); // allow user to see that the parent is a zombie
wait();
}
exit();
}
#endif
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.