file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/242330623.c | #include <stdlib.h>
#include <stdio.h>
char* buffer;
FILE* istream;
FILE* ostream;
char c;
int main( int argc, char * argv[] )
{
if (argc == 3)
{
istream = fopen(argv[1], "r");
if (istream)
{
ostream = fopen(argv[2], "w");
fputs("#include <stdio.h>\nchar array[30000] = {0}; char* ptr = array;\nint main() {\n\t", ostream);
while ((c = fgetc(istream)) != EOF)
{
switch (c)
{
case '>': fputs("++ptr; ", ostream); break;
case '<': fputs("--ptr; ", ostream); break;
case '+': fputs("++*ptr; ", ostream); break;
case '-': fputs("--*ptr; ", ostream); break;
case '.': fputs("putchar(*ptr); ", ostream); break;
case ',': fputs("*ptr = getchar(); ", ostream); break;
case '[': fputs("while (*ptr) { ", ostream); break;
case ']': fputs(" }", ostream); break;
default: break;
}
}
fclose(istream);
fputs("\n\treturn 0;\n}\n", ostream);
fclose(ostream);
}
else
{
fprintf(stderr, "Could not open file: %s", argv[1]);
exit(1);
}
}
else
{
fprintf(stderr, "Expected source and output arguments");
exit(1);
}
return 0;
}
|
the_stack_data/7947.c | /*
* Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
* Copyright [2016-2017] EMBL-European Bioinformatics Institute
*
* 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.
*/
/* autocomplete.c -- generates autocomplete suggestion dictionary. In C
* for speed as it traverses all indices.
*
* link with libm (math) ie -lm
*
* Author: Dan Sheppard (ds23)
*/
/* This file is divided into sections identified by comments:
* UTILS -- misc helpers used by other sections.
* PROCESSOR -- processes words.
* LEXER -- reads the file and breaks it into words and states.
* CONTROLLER -- handles system interaction, logging, yadda-yadda.
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <stddef.h>
#define READBUFFER 65536
int max_index_size = 100000; /* Overridden by option */
/* Fields to exclude from autocomplete altogether (with 0 on end of list) */
char * bad_fields[] = {"domain_url",0};
/************************************************************************
* UTILS -- misc helpers used by other sections. *
************************************************************************/
struct pool {
char **a;
int n;
};
char * pmem(struct pool *p,int amt) {
p->a = realloc(p->a,(p->n+1)*sizeof(char *));
p->a[p->n] = malloc(amt);
return p->a[p->n];
}
void pfree(struct pool *p) {
int i;
if(!p->a) return;
for(i=0;i<p->n;i++)
free(p->a[i]);
free(p->a);
p->a = 0;
p->n = 0;
}
/************************************************************************
* PROCESSOR -- processes words. *
************************************************************************/
/* Checks for membership of list of strings. If present returns 0, else
* returns new length with string added. Compact representation is \0
* terminated strings, followed by extra \0. NULL is acceptable as
* zero-length list. Cannot store empty string.
*/
int strl_member(char **str,char *data,int max) {
char *c,*d;
int len,n=0;
ptrdiff_t p;
len = strlen(data);
if(!len)
return 0;
if(!*str && max) { /* Initial malloc of zero-length list */
*str = malloc(1);
**str = '\0';
}
c=*str;
while(*c) {
for(d=data;*c && *c == *d;c++,d++)
;
if(!*c && !*d)
return 0;
for(;*c;c++)
;
c++;
n++;
}
if(max==-1 || n<max) {
p = c-*str; /* Remap c after realloc, also = length of alloc-1 */
*str = realloc(*str,p+len+2);
c = *str+p;
strcpy(c,data);
*(c+len+1) = '\0';
n++;
}
return n;
}
/* Converts to more standard string array */
char **strl_strings(char *strl) {
int len,i;
char **out,*d;
if(!strl)
return 0;
len = 1;
for(d=strl;*d || *(d+1);d++) {
if(!*d)
len++;
}
out = malloc(sizeof(char *)*(len+1));
for(d=strl,i=0; *d; i++,d+=strlen(d)+1)
out[i] = d;
out[i] = 0;
return out;
}
/* Simple hash function converts string into number at most mod */
int quick_hash(char *str,int seed,int mod) {
unsigned int hash = 0;
for(;*str;str++)
hash = (hash * 37 + (*str ^ seed));
return hash % mod;
}
/* "Effort" is a heuristic, supposed to correlate with the difficulty of
* remembering (and so likelihood of entering) a term. For example, it
* is more likely a user will enter KINASE1 than Q792Z.3X, all other things
* being equal, in part because it's easier to remember. At the moment we
* simply count digits as four and everything else as one, but this may
* change.
*
* This method returns a prefix of its input upto the effortlimit. All
* strings which begin with this prefix are considered muddleable-up,
* and so are placed in the same bin. If many different words end up in
* the same bin, then that is considered an unlikely term to memorise
* and enter, so these are discarded.
*
* eg Q792Z.3X -> prefix Q792 (eff=13) -+--> two in this bin
* Q792G.7R -> prefix Q792 (eff=13) -'
* BRCA1 -> prefix BRCA1 (eff=8) ----> one in this bin
* BRCA2 -> prefix BRCA2 (eff=8) ----> one in this bin
*
* "Effort" is the primary method by which we choose which terms to add to
* the autocomplete. (The other is "annoyingness").
*/
#define EFFORTLIMIT 12
char * make_effort(char *data) {
char *effort;
int limit,i,num=0,len,off;
limit = EFFORTLIMIT;
len = strlen(data);
off = len;
for(i=0;i<len;i++) {
if(isdigit(data[i]))
num += 4;
else
num++;
if(num>limit) {
off = i+1;
break;
}
}
if(off<1) off=1;
effort = malloc(off+1);
strncpy(effort,data,off);
effort[off]='\0';
return effort;
}
/* A prefix counter is the central datastructure in implementing the
* bins required for finding clashing prefixes in our effort calculations.
* It is a hash table, keyed by a hash of the prefix. Each value is the
* prefix and a list of words. Each entry in the table is a linked list.
*
* The hash table grows by calling boost_table which actually
* simply creates a replacement table (delegated to make_table)
* and then refiles the entries.
*
* inc_counter handles adding a word to the prefix counter and requesting
* the table grow, when needed.
*
* We also use a separate instance of this structure to record sections
* in which each word appears for later dumping.
*/
struct counter {
char * prefix;
char *words;
struct counter * next;
};
struct word_table {
int size,num;
struct counter ** counter;
};
struct word_table *prefixes,*sections;
struct word_table * make_table(int size) {
struct word_table *out;
int i;
out = malloc(sizeof(struct word_table));
if(size) {
out->size = size;
out->num = 0;
out->counter = malloc(sizeof(struct counter *)*size);
for(i=0;i<size;i++)
out->counter[i] = 0;
} else {
*out = (struct word_table){0,0,0};
}
return out;
}
void boost_table(struct word_table *in) {
struct word_table *out;
struct counter *c,*d;
int i,hash;
out = make_table(in->size*3/2+16);
for(i=0;i<in->size;i++)
for(c=in->counter[i];c;c=d) {
d = c->next;
hash = quick_hash(c->prefix,0,out->size);
c->next = out->counter[hash];
out->counter[hash] = c;
}
out->num = in->num;
*in = *out;
}
long long int stat_naughty=0,stat_good=0,stat_words=0;
#define NAUGHTY_THRESHOLD 12
/* 0 = new, 1 = old, 2 = naughty */
int inc_counter(struct word_table *pc,char *prefix,char *word) {
int hash,num;
struct counter *c,*rec=0;
if(pc->num >= pc->size/3)
boost_table(pc);
hash = quick_hash(prefix,0,pc->size);
for(c=pc->counter[hash];c;c=c->next) {
if(!strcmp(c->prefix,prefix))
rec = c;
}
if(!rec) {
c = malloc(sizeof(struct counter));
c->prefix = malloc(strlen(prefix)+1);
strcpy(c->prefix,prefix);
c->words = 0;
c->next = pc->counter[hash];
pc->counter[hash] = c;
pc->num++;
rec = c;
} else if(!rec->words) {
stat_naughty++;
return 2;
}
num = strl_member(&(rec->words),word,NAUGHTY_THRESHOLD);
if(num>=NAUGHTY_THRESHOLD) {
free(rec->words);
rec->words = 0;
stat_naughty++;
return 2;
}
stat_good++;
if(num==0) {
return 1;
}
return 0;
}
void add_section(struct word_table *ss,char *word,char *section) {
int hash;
struct counter *c,*rec=0;
if(ss->num >= ss->size/3)
boost_table(ss);
hash = quick_hash(word,0,ss->size);
for(c=ss->counter[hash];c;c=c->next) {
if(!strcmp(c->prefix,word))
rec = c;
}
if(!rec) {
c = malloc(sizeof(struct counter));
c->prefix = malloc(strlen(word)+1);
strcpy(c->prefix,word);
c->words = 0;
c->next = ss->counter[hash];
ss->counter[hash] = c;
ss->num++;
rec = c;
}
strl_member(&(rec->words),section,-1);
}
char ** get_sections(struct word_table *ss,char *word) {
struct counter *c,*rec=0;
int hash;
if(!ss->size)
return 0;
hash = quick_hash(word,0,ss->size);
for(c=ss->counter[hash];c;c=c->next) {
if(!strcmp(c->prefix,word))
rec = c;
}
if(rec && rec->words) {
return strl_strings(rec->words);
}
return 0;
}
/* "annoyingness" is an heuristic supposed to correlate with the difficulty
* in speaking or typing a search term. We assume that if a term is a
* pain to type then we will not use it if an easier term is
* available. For example, if a gene is known as CHEESE3, GDTDRF7 and
* Q450163 then even if all three of these are well known and disitinctive,
* (such that the "effort" heuristic accepts them) all other things
* being equal, a user is more likely to enter or communicate "CHEESE3".
*
* The heuristic assumes that English words are easy, letters are quite
* easy, and everything else isn't. "English" is approximated by looking
* for an approximately alternating pattern of vowels and consonants.
*
* The second kind of annoyingness handled here is that it's most annoying
* to have to type in longer words as shorter words can be entered easily
* without its aid. Therefore we penalise short words by dividing by
* overall length.
*
* We use annoyngness as a post-filter on our terms (unlike effort, which
* is applied during parsing). We remember the annoyingness of each term
* and consider the number of terms which a user requested in determining
* the correct threshold.
*/
/* -100*log(letter_frequency in english). Add scores and divide by length
* to get an accurate score for unlikeliness of a letter sequence in
* English.
*/
int freq[] = {
109,182,156,136, 92,163,169,122,113,298,216,140,158,
115,111,174,294,122,120,104,154,195,167,276,167,315
};
int annoyingness(char *data) {
int n=0,len=0,v=0,f=0,letlen=0;
char *c;
for(c=data;*c;c++) {
len++;
if(!isalpha(*c))
n+=100;
if(strspn(c,"aeiou") > 2)
n+=50; /* Too many vowels in a row */
if(strcspn(c,"aeiou") > 3)
n+=10; /* Too many consonants in a row */
if(strspn(c,"aeiou"))
v=1;
if(*c>='a' && *c<='z') {
f += freq[*c-'a'];
letlen++;
}
}
if(len) n/=len;
if(letlen) f/= letlen; else f = 500;
if(f>150)
n += (f-150); /* unusual letters */
else
n += f/20; /* Mainly to avoid ties */
if(!v)
n += 30; /* no vowels */
if(!len) return 0;
n = (n*20)/len; /* Reward long matches, painful to type */
return n;
}
#define MAX_ANNOYINGNESS 200
int annoyingness_size[MAX_ANNOYINGNESS];
void reset_annoyingness() {
int i;
for(i=0;i<MAX_ANNOYINGNESS;i++)
annoyingness_size[i] = 0;
}
void register_annoyingness(int ann) {
int i;
for(i=ann;i<MAX_ANNOYINGNESS;i++)
annoyingness_size[i]++;
}
int last_val = -1;
int annoyingness_threshold(int num) {
int i;
/* This method is on the critical path, so use a cache */
if(last_val>=0) {
if(last_val == MAX_ANNOYINGNESS-1 && annoyingness_size[MAX_ANNOYINGNESS-1]<num)
return MAX_ANNOYINGNESS-1;
if(annoyingness_size[last_val]<=num && annoyingness_size[last_val+1]>num)
return last_val;
}
for(i=1;i<MAX_ANNOYINGNESS;i++) {
if(annoyingness_size[i]>num) {
last_val = i-1;
return i-1;
}
}
last_val = MAX_ANNOYINGNESS-1;
return MAX_ANNOYINGNESS-1;
}
/* Dump the appropriate number of words (by calculating the correct
* annoyingness threshold).
*/
void dump_words(struct word_table *pc,int threshold) {
struct counter *c;
int i,thresh,ann;
double value;
char *d,**ss,**s;
thresh = annoyingness_threshold(max_index_size);
for(i=0;i<pc->size;i++)
for(c=pc->counter[i];c;c=c->next) {
d=c->words;
if(d) {
while(*d) {
ann = annoyingness(d);
if(ann<thresh) {
value = ann*strlen(d);
if(value > 0.5) {
value = 12.0 - log10(value);
} else {
value = 12.0;
}
if(strlen(d)>6)
value -= 0.1 * (strlen(d)-6);
if(value >= threshold) {
ss = get_sections(sections,d);
if(ss) {
for(s=ss;*s;s++)
printf("%s%s\t%1.1f\n",*s,d,value);
free(ss);
} else {
printf("%s\t%1.1f\n",d,value);
}
}
}
d += strlen(d)+1;
}
}
}
}
/* What we do to each word */
void process_word(char **ss,char *data) {
char *effort,**s;
int thresh,ann,i;
if(!*data)
return;
stat_words++;
effort = make_effort(data);
i = inc_counter(prefixes,effort,data);
if(i==0 || i==1) {
if(ss)
for(s=ss;*s;s++)
add_section(sections,data,*s);
}
if(!i) {
thresh = annoyingness_threshold(max_index_size);
ann = annoyingness(data);
if(ann<thresh) {
register_annoyingness(ann);
}
}
free(effort);
}
/***************************************************************
* LEXER - reads the file and breaks it into words and states. *
***************************************************************/
/* A good field is a field which should not be ignored for the purposes
* of autocomplete. It uses a fixed array.
*/
int in_good_field = 0;
int good_field(char *name) {
char **b;
for(b=bad_fields;*b;b++)
if(!strcmp(name,*b))
return 0;
return 1;
}
/* Here's a tag. Set whether or not we are in a good field. This is a
* one-bit state which determines whether any textual content in the XML
* should be added to the autocomplete index.
*/
void process_tag(char *data) {
char * field,*f;
if(!strncmp(data,"field ",6)) {
/* FIELD */
if((field = strstr(data,"name=\""))) {
f = index(field+6,'"');
if(f)
*f = '\0';
if(good_field(field+6))
in_good_field = 1;
}
} else if(!strcmp(data,"/field")) {
in_good_field = 0;
}
}
/* Punctuation which tends to separate words */
int isseparator(char c) {
return c == '/' || c == ':' || c == ';' || c == '-' || c == '_' || c == '(' || c == ')';
}
/* Split some XML text into words and call process_word on each */
void process_text(char **ss,char *data) {
char *c,*d;
if(!in_good_field)
return;
/* Remove punctuation attached to starts and ends of words */
d = data;
for(c=data;*c;c++) {
if(ispunct(*c)) {
if(c==data || !*(c+1) ||
!isalnum(*(c-1)) || !isalnum(*(c+1)) ||
isseparator(*c))
*c = ' ';
}
if(isspace(*c)) {
*c = '\0';
if(*d)
process_word(ss,d);
d = c+1;
} else {
*c = tolower(*c);
}
}
process_word(ss,d);
}
int tag_mode=0;
char *tagstr = 0;
/* Process this text which is either the contents of <...> or else some
* text between such.
*
* eg <a>hello <b>world</b></a> =>
* lex_part("a",1); lex_part("hello ",0); lex_part("b",1);
* lex_part("world",0); lex_part("/b",1); lex_part("/a",1);
*/
void lex_part(char **ss,char *part,int tag) {
if(tag_mode != tag) {
/* Do stuff */
if(tag_mode) {
process_tag(tagstr);
} else {
process_text(ss,tagstr);
}
free(tagstr);
tagstr = 0;
tag_mode = tag;
}
if(!tagstr) {
tagstr = malloc(1);
tagstr[0] = '\0';
}
if(strlen(part)) {
tagstr = realloc(tagstr,strlen(tagstr)+strlen(part)+1);
strcat(tagstr,part);
}
}
/* Take a string and call lext_part the right number of times, with the
* right fragments.
*/
int in_tag = 0;
/* at top level we just extract tag / non-tag and pass it down */
void lex(char **ss,char *data) {
char *hit;
while(*data) {
hit = index(data,in_tag?'>':'<');
if(hit)
*hit = '\0';
lex_part(ss,data,in_tag);
if(hit) {
in_tag = !in_tag;
data = hit+1;
} else {
break;
}
}
}
/*******************************************************************
* CONTROLLER -- handles system interaction, logging, yadda-yadda. *
*******************************************************************/
/* Used by string returning functions: remember to free it! */
struct pool smem = {0,0};
/* Abbreviated filename for log messages */
char * short_name(char *in) {
char *out,*c,*d,*e;
out = malloc(strlen(in)+1);
e = rindex(in,'.');
c = rindex(in,'/');
if(!c) c = in;
for(d=out;*c && c!=e;c++)
if(c==in || isdigit(*c))
*(d++) = *c;
else if(isupper(*c))
*(d++) = tolower(*c);
else if(isalpha(*c) && !isalpha(*(c-1)))
*(d++) = *c;
else if(ispunct(*c) && !isalpha(*(c-1)))
*(d++) = '-';
*d = '\0';
return out;
}
/* Display a number of bytes with appropriate multiplier eg 1024 -> 1k */
char *mult = " kMGTPE";
char * size(off_t amt) {
char *out;
int i;
out = pmem(&smem,10);
for(i=0;mult[i];i++) {
if(amt<1024) {
sprintf(out,"%ld%c",amt,mult[i]);
return out;
}
amt /= 1024;
}
sprintf(out,"lots");
return out;
}
/* Display a time in H:M:S */
#define MAXTIME 256
char * time_str(time_t when) {
struct tm tm;
char *out;
if(!localtime_r(&when,&tm))
return "";
out = pmem(&smem,MAXTIME);
strftime(out,MAXTIME-1,"%H:%M:%S",&tm);
return out;
}
/* Get file size */
off_t file_size(char *fn) {
struct stat sb;
off_t size;
if(stat(fn,&sb) == -1) {
fprintf(stderr,"Cannot stat '%s': %s\n",fn,strerror(errno));
exit(1);
}
size = sb.st_size;
return size;
}
/* Read and call lex on a file */
int meg=0,bytes=0,repmeg=0;
time_t all_start,block_start,block_end;
off_t stat_all=0;
off_t stat_read = 0;
#define MEG (1024*1024)
void process_file(char **ss,char *fn) {
int r,fd;
char buf[READBUFFER];
long long int total;
time_t eta;
fprintf(stderr,"File: %-15s %10s\n",short_name(fn),size(file_size(fn)));
pfree(&smem);
fd = open(fn,O_RDONLY);
if(fd==-1) {
fprintf(stderr,"Cannot open '%s': %s\n",fn,strerror(errno));
exit(1);
}
while(1) {
r = read(fd,buf,READBUFFER-1);
if(r>0) {
stat_read += r;
buf[r] = '\0';
lex(ss,buf);
bytes += r;
if(bytes > MEG) {
meg += bytes/MEG;
bytes -= (bytes/MEG)*MEG;
}
} else if(r==0) {
break;
} else {
perror("Read of stdin failed");
exit(1);
}
if(!(meg%100) && repmeg != meg) {
block_end = time(0);
total = (stat_naughty+stat_good+1);
fprintf(stderr,"Run : %dMb in %lds (%lds).\nMem : "
"n/g(%%)=%s/%s (%lld) p/s=%s/%s. a=%d.\n",
meg,block_end-all_start,block_end-block_start,
size(stat_good),size(stat_naughty),
stat_good*100/total,
size(prefixes->num),size(stat_words),
annoyingness_threshold(max_index_size));
eta = all_start+(block_end-all_start)*stat_all/stat_read;
fprintf(stderr,"ETA : read/all = %s/%s (%ld%%) at %s\n",
size(stat_read),size(stat_all),stat_read*100/stat_all,
time_str(eta));
pfree(&smem);
block_start = block_end;
repmeg=meg;
}
}
lex_part(ss,"",0);
close(fd);
}
/* List of files we need to process */
struct file {
char *filename;
char *sections;
struct file *next;
};
char * global_sections = 0;
struct file *files = 0;
void add_file(char *fn) {
struct file *f;
char *fn2;
fn2 = malloc(strlen(fn)+1);
strcpy(fn2,fn);
f = malloc(sizeof(struct file));
f->filename = fn2;
f->sections = 0;
f->next = files;
files = f;
}
void add_file_section(char *section) {
if(files)
strl_member(&(files->sections),section,-1);
else
strl_member(&global_sections,section,-1);
}
void add_file_spec(char *spec) {
char *at,*at2,**ss,**s,*in;
in = malloc(strlen(spec)+1);
strcpy(in,spec);
ss = strl_strings(global_sections);
at = index(in,'@');
if(at) *at = '\0';
add_file(in);
if(ss)
for(s=ss;*s;s++)
add_file_section(*s);
while(at) {
at2 = index(at+1,'@');
if(at2) *at2 = '\0';
add_file_section(at+1);
at = at2;
}
free(in);
free(ss);
}
/* Handle options, read in list of files and submit one-by-one */
/* max bytes of filename on stdin */
#define MAXLINE 16384
int main(int argc,char *argv[]) {
int idx,c,from_stdin=0,threshold=6;
char *fn,*p,**ss;
struct file *f;
all_start = block_start = time(0);
while((c = getopt(argc,argv,"cn:s:t:")) != -1) {
switch (c) {
case 'n':
max_index_size = atoi(optarg);
if(max_index_size < 1) {
fprintf(stderr,"Bad index size '%s'\n",optarg);
return 1;
}
break;
case 'c':
from_stdin = 1;
break;
case 's':
add_file_section(optarg);
break;
case 't':
threshold = atoi(optarg);
if(threshold<1) {
fprintf(stderr,"Bad threshold '%s'\n",optarg);
return 1;
}
break;
case '?':
fprintf(stderr,"Bad command line options\n");
return 1;
default:
abort();
}
}
reset_annoyingness();
prefixes = make_table(0);
sections = make_table(0);
if(from_stdin) {
while(1) {
fn = malloc(MAXLINE);
if(!fgets(fn,MAXLINE,stdin)) {
if(ferror(stdin)) {
perror("Could not read from stdin\n");
exit(1);
}
free(fn);
break;
}
for(p=fn;*p && !isspace(*p);p++)
;
*p = '\0';
add_file_spec(fn);
}
} else {
for (idx=optind;idx<argc;idx++) {
add_file_spec(argv[idx]);
}
}
for(f=files;f;f=f->next)
stat_all += file_size(f->filename);
for(f=files;f;f=f->next) {
ss = strl_strings(f->sections);
process_file(ss,f->filename);
free(ss);
}
dump_words(prefixes,threshold);
fprintf(stderr,"Success.\n");
return 0;
}
|
the_stack_data/140765388.c | #include <stdlib.h>
//! Convert string representation of a floating point number into a double
//
//! This function handles converting floating point numbers from an ENDF 11
//! character field into a double, covering all the corner cases. Floating point
//! numbers are allowed to contain whitespace (which is ignored). Also, in
//! exponential notation, it allows the 'e' to be omitted. A field containing
//! only whitespace is to be interpreted as a zero.
//
//! \param buffer character input from an ENDF file
//! \param n Length of character input
//! \return Floating point number
double cfloat_endf(const char* buffer, int n)
{
char arr[12]; // 11 characters plus a null terminator
int j = 0; // current position in arr
int found_significand = 0;
int found_exponent = 0;
// limit n to 11 characters
n = n > 11 ? 11 : n;
int i;
for (i = 0; i < n; ++i) {
char c = buffer[i];
// Skip whitespace characters
if (c == ' ') continue;
if (found_significand) {
if (!found_exponent) {
if (c == '+' || c == '-') {
// In the case that we encounter +/- and we haven't yet encountered
// e/E, we manually add it
arr[j++] = 'e';
found_exponent = 1;
} else if (c == 'e' || c == 'E' || c == 'd' || c == 'D') {
arr[j++] = 'e';
found_exponent = 1;
continue;
}
}
} else if (c == '.' || (c >= '0' && c <= '9')) {
found_significand = 1;
}
// Copy character
arr[j++] = c;
}
// Done copying. Add null terminator and convert to double
arr[j] = '\0';
return atof(arr);
}
|
the_stack_data/578117.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef MAC
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif
int main() {
/* Host data structures */
cl_platform_id *platforms;
cl_uint num_platforms;
cl_int i, err, platform_index = -1;
/* Extension data */
char* ext_data;
size_t ext_size;
const char icd_ext[] = "cl_khr_icd";
/* Find number of platforms */
err = clGetPlatformIDs(1, NULL, &num_platforms);
if(err < 0) {
perror("Couldn't find any platforms.");
exit(1);
}
/* Access all installed platforms */
platforms = (cl_platform_id*)
malloc(sizeof(cl_platform_id) * num_platforms);
clGetPlatformIDs(num_platforms, platforms, NULL);
/* Find extensions of all platforms */
for(i=0; i<num_platforms; i++) {
/* Find size of extension data */
err = clGetPlatformInfo(platforms[i],
CL_PLATFORM_EXTENSIONS, 0, NULL, &ext_size);
if(err < 0) {
perror("Couldn't read extension data.");
exit(1);
}
/* Access extension data */
ext_data = (char*)malloc(ext_size);
clGetPlatformInfo(platforms[i], CL_PLATFORM_EXTENSIONS,
ext_size, ext_data, NULL);
printf("Platform %d supports extensions: %s\n", i, ext_data);
/* Look for ICD extension */
if(strstr(ext_data, icd_ext) != NULL) {
free(ext_data);
platform_index = i;
break;
}
free(ext_data);
}
/* Display whether ICD extension is supported */
if(platform_index > -1)
printf("Platform %d supports the %s extension.\n",
platform_index, icd_ext);
else
printf("No platforms support the %s extension.\n", icd_ext);
/* Deallocate resources */
free(platforms);
return 0;
}
|
the_stack_data/211079850.c | #include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#ifdef __IS_LIBK
#include <kernel/tty.h>
#endif
// System call for write. Passing in a size of zero will use the null terminator
// to determine length.
#define SIZE_UNSPECIFIED 0
static int write(const char *str, size_t size) {
#ifdef __IS_LIBK
if (size == SIZE_UNSPECIFIED)
tty_writestring(str);
else tty_write(str, size);
return 0;
#else
// TODO: Implement the write system call
return EOF;
#endif
}
// Returns number of characters written
static int putint(int n) {
if (n == 0) {
putchar('0');
return 1;
}
bool neg = false;
if (n < 0) {
putchar('-');
n = -n;
neg = true;
}
char temp[16]; // Do not make the buffer smaller than this
size_t digits = 0;
while (n != 0) {
temp[digits] = n % 10 + '0';
n /= 10;
digits += 1;
}
for (size_t i = 0; i < digits; i++) putchar(temp[digits - i - 1]);
return neg ? digits + 1 : digits;
}
// Returns number of characters written
static int puthex(uint32_t n) {
char temp[8] = {'0', '0', '0', '0', '0','0', '0', '0'};
size_t i;
for (i = 7; n != 0; i--, n >>= 4) {
int four_bits = n & 15;
temp[i] = four_bits < 10 ? four_bits + '0' : four_bits - 10 + 'A';
}
i = 0;
write("0x", SIZE_UNSPECIFIED);
while (i < 8) putchar(temp[i++]);
return 10;
}
int printf(const char* restrict format, ...) {
va_list parameters;
va_start(parameters, format);
int written = 0;
size_t amount;
bool rejected_bad_specifier = false;
while (*format) {
if (*format != '%') {
print_chars:
amount = 1;
while (format[amount] && format[amount] != '%')
amount++;
write(format, amount);
format += amount;
written += amount;
continue;
}
// We are at a '%'
const char* format_begun_at = format;
if (*(++format) == '%')
goto print_chars; // Print '%' and following text
else if (*format == 'c') {
format++;
putchar((char)va_arg(parameters, int)); // Print single character
written += 1;
}
else if (*format == 's') {
format++;
const char* s = va_arg(parameters, const char*);
size_t len = strlen(s);
write(s, len);
written += len;
}
else if (*format == 'd') {
format++;
written += putint(va_arg(parameters, int));
}
else if (*format == 'x') {
format++;
written += puthex(va_arg(parameters, uint32_t));
}
else
goto incomprehensible_conversion;
if (rejected_bad_specifier) {
incomprehensible_conversion:
rejected_bad_specifier = true;
format = format_begun_at;
goto print_chars;
}
}
va_end(parameters);
return written;
}
int putchar(int c) {
return write((const char *)(&c), 1);
}
int puts(const char *str) {
int r1 = write(str, SIZE_UNSPECIFIED);
int r2 = putchar('\n');
return r1 || r2;
} |
the_stack_data/8951.c | /**
* Exercise 2-1.
* Write a program to determine the ranges of char, short, int, and long variables,
* both signed and unsigned, by printing appropriate values from standard headers
* and by direct computation. Harder if you compute them:
* determine the ranges of the various floating-point types.
*/
#include <stdio.h>
#include <limits.h>
int main(void)
{
printf("\nBits of type char: %d\n\n", CHAR_BIT); /* IV */
printf("Maximum numeric value of type char: %d\n", CHAR_MAX); /* IV */
printf("Minimum numeric value of type char: %d\n\n", CHAR_MIN); /* IV */
printf("Maximum value of type signed char: %d\n", SCHAR_MAX); /* IV */
printf("Minimum value of type signed char: %d\n\n", SCHAR_MIN); /* IV */
printf("Maximum value of type unsigned char: %u\n\n", (unsigned)UCHAR_MAX); /* SF */ /* IV */
printf("Maximum value of type short: %d\n", SHRT_MAX); /* IV */
printf("Minimum value of type short: %d\n\n", SHRT_MIN); /* IV */
printf("Maximum value of type unsigned short: %u\n\n", (unsigned)USHRT_MAX); /* SF */ /* IV */
printf("Maximum value of type int: %d\n", INT_MAX); /* IV */
printf("Minimum value of type int: %d\n\n", INT_MIN); /* IV */
printf("Maximum value of type unsigned int: %u\n\n", UINT_MAX); /* RB */ /* IV */
printf("Maximum value of type long: %ld\n", LONG_MAX); /* RB */ /* IV */
printf("Minimum value of type long: %ld\n\n", LONG_MIN); /* RB */ /* IV */
printf("Maximum value of type unsigned long: %lu\n\n", ULONG_MAX); /* RB */ /* IV */
return 0;
} |
the_stack_data/50856.c | #include<stdio.h>
#define MAX 30
typedef struct edge
{
int u,v,w;
}edge;
typedef struct edgelist
{
edge data[MAX];
int n;
}edgelist;
edgelist elist;
int G[MAX][MAX],n;
edgelist spanlist;
void kruskal();
int find(int belongs[],int vertexno);
void union1(int belongs[],int c1,int c2);
void sort();
void print();
void main()
{
int i,j,total_cost;
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
kruskal();
print();
}
void kruskal()
{
int belongs[MAX],i,j,cno1,cno2;
elist.n=0;
for(i=1;i<n;i++)
for(j=0;j<i;j++)
{
if(G[i][j]!=0)
{
elist.data[elist.n].u=i;
elist.data[elist.n].v=j;
elist.data[elist.n].w=G[i][j];
elist.n++;
}
}
sort();
for(i=0;i<n;i++)
belongs[i]=i;
spanlist.n=0;
for(i=0;i<elist.n;i++)
{
cno1=find(belongs,elist.data[i].u);
cno2=find(belongs,elist.data[i].v);
if(cno1!=cno2)
{
spanlist.data[spanlist.n]=elist.data[i];
spanlist.n=spanlist.n+1;
union1(belongs,cno1,cno2);
}
}
}
int find(int belongs[],int vertexno)
{
return(belongs[vertexno]);
}
void union1(int belongs[],int c1,int c2)
{
int i;
for(i=0;i<n;i++)
if(belongs[i]==c2)
belongs[i]=c1;
}
void sort()
{
int i,j;
edge temp;
for(i=1;i<elist.n;i++)
for(j=0;j<elist.n-1;j++)
if(elist.data[j].w>elist.data[j+1].w)
{
temp=elist.data[j];
elist.data[j]=elist.data[j+1];
elist.data[j+1]=temp;
}
}
void print()
{
int i,cost=0;
for(i=0;i<spanlist.n;i++)
{
printf("\n%d\t%d\t%d",spanlist.data[i].u,spanlist.data[i].v,spanlist.data[i].w);
cost=cost+spanlist.data[i].w;
}
printf("\n\nCost of the spanning tree=%d",cost);
} |
the_stack_data/212643739.c | #include <stdlib.h>
typedef struct
{
char* history[5000];
int top;
int size;
} BrowserHistory;
BrowserHistory* browserHistoryCreate(char* homepage)
{
BrowserHistory* res = (BrowserHistory*)malloc(sizeof(BrowserHistory));
res->history[0] = homepage;
res->top = 0;
res->size = 1;
return res;
}
void browserHistoryVisit(BrowserHistory* obj, char* url)
{
obj->size = ++obj->top + 1;
obj->history[obj->top] = url;
}
char* browserHistoryBack(BrowserHistory* obj, int steps)
{
obj->top -= steps;
if (obj->top < 0)
obj->top = 0;
return obj->history[obj->top];
}
char* browserHistoryForward(BrowserHistory* obj, int steps)
{
obj->top += steps;
if (obj->top >= obj->size)
obj->top = obj->size - 1;
return obj->history[obj->top];
}
void browserHistoryFree(BrowserHistory* obj)
{
if (obj)
free(obj);
}
/**
* Your BrowserHistory struct will be instantiated and called as such:
* BrowserHistory* obj = browserHistoryCreate(homepage);
* browserHistoryVisit(obj, url);
* char * param_2 = browserHistoryBack(obj, steps);
* char * param_3 = browserHistoryForward(obj, steps);
* browserHistoryFree(obj);
*/
|
the_stack_data/1060347.c | #include <stdio.h>
#include <stdlib.h>
inline static int
max(int a, int b) {
return a > b ? a : b;
}
inline static int
max_slice(int A[], int start, int stop) {
int current_max = 0;
int total_max = 0;
int i;
for (i = start; i < stop; i++) {
current_max = max(0, current_max + A[i]);
total_max = max(total_max, current_max);
}
return total_max;
}
int solution(int A[], int N) {
int i;
int *l_arr = NULL;
int *r_arr = NULL;
int max_val = 0;
l_arr = calloc(sizeof(int), N);
r_arr = calloc(sizeof(int), N);
for (i = 1; i < N - 1; i++) {
l_arr[i] = max(l_arr[i - 1] + A[i], 0);
}
for (i = N - 2; i > 0; i--) {
r_arr[i] = max(r_arr[i + 1] + A[i], 0);
}
for (i = 1; i < N - 1; i++) {
max_val = max(max_val, l_arr[i - 1] + r_arr[i + 1]);
}
free(r_arr);
free(l_arr);
return max_val;
}
int main() {
int A[] = { 3, 2, 6, -1, 4, 5, -1, 2};
printf("Result: %d\n", solution(A, 8));
return 0;
}
|
the_stack_data/40763154.c | /*
* File I/O functions
*
* Copyright (C) 2006-2013 Mathias Lafeldt <[email protected]>
*
* This file is part of cb2util, the CodeBreaker PS2 File Utility.
*
* cb2util is licensed under the terms of the MIT License. See LICENSE file.
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int read_file(uint8_t **buf, size_t *size, const char *path)
{
FILE *fp;
fp = fopen(path, "rb");
if (fp == NULL)
return -1;
fseek(fp, 0, SEEK_END);
*size = ftell(fp);
*buf = malloc(*size);
if (*buf == NULL) {
fclose(fp);
return -1;
}
fseek(fp, 0, SEEK_SET);
if (fread(*buf, *size, 1, fp) != 1) {
fclose(fp);
return -1;
}
fclose(fp);
return 0;
}
int write_file(const uint8_t *buf, size_t size, const char *path)
{
FILE *fp;
fp = fopen(path, "wb");
if (fp == NULL)
return -1;
if (fwrite(buf, size, 1, fp) != 1) {
fclose(fp);
return -1;
}
fclose(fp);
return 0;
}
|
the_stack_data/23575596.c | #include <stdio.h>
float main(){
float a, b;
printf("Digite um número real: \n");
scanf("%f", &a);
printf("Digite outro número real: \n");
scanf("%f", &b);
if(a>0 && b>0){
printf("São valores válidos");
}else {
printf("São valores inválidos");
}
}
|
the_stack_data/38214.c | // this is from Alexander Monakov
#include <stdio.h>
#define N 32
int a[N], pfx[N];
int prefix_sum(void) {
int i, accum;
for (i = 0, accum = a[0]; i < N && accum >= 0; i++, accum += a[i])
pfx[i] = accum;
return accum;
}
int main(void) {
printf("%d\n", prefix_sum());
return 0;
}
|
the_stack_data/279582.c | #include <stdio.h>
int main() {
float X, Y;
scanf("%f %f", &X, &Y);
if (X == 0.00 && Y ==0.00)
{
printf("Origem\n");
}
else if (X == 0.00 && Y !=0.00)
{
printf("Eixo Y\n");
}
else if (Y == 0.00 && X !=0.00)
{
printf("Eixo X\n");
}
else if (X>0.00 && Y>0.00)
{
printf("Q1\n");
}
else if (X>0.00 && Y<0.00)
{
printf("Q4\n");
}
else if (X<0.00 && Y>0.00)
{
printf("Q2\n");
}
else if (X<0.00 && Y<0.00)
{
printf("Q3\n");
}
return 0;
}
|
the_stack_data/89892.c | #include <stdio.h>
float conversao (float);
float conversao (float f)
{
float c;
c = 5.0f * (f - 32.0f) / 9.0f;
if ((c <= -268) && (c >=-278))
{
printf("zero absoluto\n");
}
else
{
if(c >= 5 && c <= 5)
{
printf("congelamento da água\n");
}
else
{
if(c >= 95 && c <= 105)
{
printf("ebuliçao da água\n");
}
}
}
return c;
}
float main(void)
{
float f;
float tc;
printf("escreva a temperatura em fahrenheit: ");
scanf("%f", &f);
tc = conversao(f);
printf("o valor da temperatura em celcius é %fC\n", tc);
return 0;
}
|
the_stack_data/109227.c | #include <math.h>
#define JMAX 40
double rtbis(double (*func)(double), double x1, double x2, double xacc)
{
void nrerror(char error_text[]);
int j;
double dx,f,fmid,xmid,rtb;
f=(*func)(x1);
fmid=(*func)(x2);
if (isnan(f)==1 || isnan(fmid)==1) return NAN;
if (f*fmid >= 0.0) nrerror("Root must be bracketed for bisection in rtbis");
rtb = f < 0.0 ? (dx=x2-x1,x1) : (dx=x1-x2,x2);
for (j=1;j<=JMAX;j++) {
fmid=(*func)(xmid=rtb+(dx *= 0.5));
if (fmid <= 0.0) rtb=xmid;
if (fabs(dx) < xacc || fmid == 0.0) return rtb;
}
//nrerror("Too many bisections in rtbis");
return NAN;
}
#undef JMAX
|
the_stack_data/240000.c | /*
* Copyright (c) 2014 - Qeo LLC
*
* The source code form of this Qeo Open Source Project component is subject
* to the terms of the Clear BSD license.
*
* You can redistribute it and/or modify it under the terms of the Clear BSD
* License (http://directory.fsf.org/wiki/License:ClearBSD). See LICENSE file
* for more details.
*
* The Qeo Open Source Project also includes third party Open Source Software.
* See LICENSE file for more details.
*/
/* ri_tls.c -- RTPS over SSL/TLS transports. */
#if defined (DDS_SECURITY) && defined (DDS_TCP)
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#ifdef _WIN32
#include "win.h"
#define ERRNO WSAGetLastError()
#else
#include <unistd.h>
#include <errno.h>
#include <poll.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
#define ERRNO errno
#endif
#include "sock.h"
#include "log.h"
#include "error.h"
#include "debug.h"
#include "openssl/bio.h"
#include "openssl/err.h"
#include "openssl/ssl.h"
#include "openssl/rand.h"
#include "security.h"
#include "ri_data.h"
#include "ri_tls.h"
#include "ri_tcp.h"
#include "ri_tcp_sock.h"
#include "dds/dds_security.h"
#ifdef DDS_TCP_NODELAY
#include <netinet/tcp.h>
#endif
#ifdef ANDROID
#include "sys/socket.h"
#endif
int tls_available = 1;
int server_mode = 0;
#define COOKIE_SECRET_LENGTH 16
static SSL_CTX *tls_server_ctx;
static SSL_CTX *tls_client_ctx;
static int cookie_initialized;
static unsigned char cookie_secret [COOKIE_SECRET_LENGTH];
typedef enum {
TLS_CLIENT,
TLS_SERVER
} TLS_CX_SIDE;
typedef struct {
SSL *ssl; /* SSL context. */
int fd;
TLS_SSL_STATE state;
int ssl_pending_possible;
TCP_MSG *recv_msg; /* Context in which we can asynchronously receive messages. */
TCP_MSG *send_msg; /* Context in which we can asynchronously send messages. */
} TLS_CX;
/***********/
/* TRACING */
/***********/
#ifdef DDS_DEBUG
/*#define LOG_CERT_CHAIN_DETAILS ** trace if certificates are expired or not */
/*#define TRACE_STATE_CHANGES ** trace all the fd event state changes */
/*#define TRACE_ENTER_FUNCTION ** trace all the function calls */
/*#define TRACE_TLS_SPECIFIC ** trace tls specific calls */
/*#define TRACE_POLL_EVENTS ** Trace poll events */
/*#define TRACE_READ_OPS ** Trace read() calls */
/*#define TRACE_WRITE_OPS ** Trace write()/send() calls */
/*#define TRACE_SERVER ** Trace server side operations (listen, accept ...) */
/*#define TRACE_CLIENT ** Trace client side operations (connect, ...) */
#endif
#ifdef TRACE_STATE_CHANGES
static void trace_poll_states (char *state, int to, int fd, const char *func)
{
ARG_NOT_USED (func)
log_printf (RTPS_ID, 0, "TLS: changing from %s to %d on [%d]\r\n", state, to, fd);
}
#define trace_state(arg1, arg2, arg3, arg4) trace_poll_states (arg1, arg2, arg3, arg4);
#else
#define trace_state(arg1, arg2, arg3, arg4)
#endif
#ifdef TRACE_ENTER_FUNCTION
#define trace_func() log_printf (RTPS_ID, 0, "Entering function %s.\r\n", __FUNCTION__);
#else
#define trace_func()
#endif
#ifdef TRACE_TLS_SPECIFIC
#define trace_tls(msg, args) log_printf (RTPS_ID, 0, msg, (args))
#else
#define trace_tls(msg, args)
#endif
#ifdef TRACE_POLL_EVENTS
#define trace_poll_events(fd,events,arg) log_printf (RTPS_ID, 0, "tls-poll [%d] %s: revents=%s arg=%p\r\n", (fd), __FUNCTION__, dbg_poll_event_str ((events)), (arg))
#else
#define trace_poll_events(fd,events,arg) ARG_NOT_USED ((fd)) ARG_NOT_USED ((events)) ARG_NOT_USED ((arg))
#endif
#if defined (TRACE_READ_OPS) || defined (TRACE_WRITE_OPS) || defined (TRACE_SERVER) || defined (TRACE_CLIENT)
static void trace_log_errno (int res, int err)
{
if (res == -1)
log_printf (RTPS_ID, 0, " e:%d %s", errno, strerror (err));
}
#endif
#if defined (TRACE_READ_OPS) || defined (TRACE_WRITE_OPS)
static void trace_rw(const char *rw, ssize_t res,int fd, size_t sz)
{
int saved = ERRNO;
log_printf (RTPS_ID, 0, "tls-%s [%d] s:%lu r:%ld", rw, fd,
(unsigned long) sz, (long) res);
trace_log_errno (res, saved);
log_printf (RTPS_ID, 0, "\r\n");
ERRNO = saved;
}
#endif
#if defined (TRACE_SERVER) || defined (TRACE_CLIENT)
static void trace_call (const char *op, int res, int fd)
{
int saved = ERRNO;
log_printf (RTPS_ID, 0, "tls-%s [%d] r:%d", op, fd, res);
trace_log_errno (res, saved);
log_printf (RTPS_ID, 0, "\r\n");
ERRNO = saved;
}
#endif
#ifdef TRACE_SERVER
#define trace_server(op,res,fd) trace_call ((op), (res), (fd))
#else
#define trace_server(op,res,fd)
#endif
#ifdef TRACE_CLIENT
#define trace_client(op,res,fd) trace_call ((op), (res), (fd))
#else
#define trace_client(op,res,fd)
#endif
#ifdef TRACE_CLIENT
#endif
#ifdef TRACE_READ_OPS
#define trace_read(res,fd,sz) trace_rw ("read", (res), (fd), (sz))
#else
#define trace_read(res,fd,sz)
#endif
#ifdef TRACE_WRITE_OPS
#define trace_write(res,fd,sz) trace_rw ("write", (res), (fd), (sz))
#else
#define trace_write(res,fd,sz)
#endif
/***********/
/* OPENSSL */
/***********/
static void tls_dump_openssl_error_stack (const char *msg)
{
unsigned long err;
const char *file, *data;
int line, flags;
char buf [256];
log_printf (RTPS_ID, 0, "%s", msg);
while ((err = ERR_get_error_line_data (&file, &line, &data, &flags)))
log_printf (RTPS_ID, 0, " err %lu @ %s:%d -- %s\n", err, file, line,
ERR_error_string (err, buf));
}
static int tls_verify_callback (int ok, X509_STORE_CTX *store)
{
char data[256];
int depth;
X509 *cert;
trace_func ();
depth = X509_STORE_CTX_get_error_depth (store);
cert = X509_STORE_CTX_get_current_cert (store);
#ifdef LOG_CERT_CHAIN_DETAILS
if (cert) {
X509_NAME_oneline (X509_get_subject_name (cert), data, sizeof (data));
log_printf (RTPS_ID, 0, "TLS: depth %2i: subject = %s\r\n", depth, data);
X509_NAME_oneline (X509_get_issuer_name (cert), data, sizeof (data));
log_printf (RTPS_ID, 0, "TLS: issuer = %s\r\n", data);
}
#endif
if (!ok) {
int err = X509_STORE_CTX_get_error (store);
if (cert)
X509_NAME_oneline (X509_get_subject_name (cert), data, sizeof (data));
else
strcpy (data, "<Unknown>");
err_printf ("err %i @ depth %i for issuer: %s\r\n\t%s\r\n", err, depth, data, X509_verify_cert_error_string (err));
#ifdef NO_CERTIFICATE_TIME_VALIDITY_CHECK
/* Exceptions */
if (err == X509_V_ERR_CERT_NOT_YET_VALID) {
#ifdef LOG_CERT_CHAIN_DETAILS
log_printf (SEC_ID, 0, "TLS: Certificate verify callback. The certificate is not yet valid, but this is allowed. \r\n");
#endif
ok = 1;
}
if (err == X509_V_ERR_CERT_HAS_EXPIRED) {
ok = 1;
#ifdef LOG_CERT_CHAIN_DETAILS
log_printf (SEC_ID, 0, "TLS: Certificate verify callback. The certificate has expired, but this is allowed. \r\n");
#endif
}
#endif
}
return (ok);
}
#if 1
static int generate_cookie (SSL *ssl, unsigned char *cookie, unsigned *cookie_len)
{
unsigned char *buffer, result[EVP_MAX_MD_SIZE];
unsigned int length = 0, resultlength;
union {
struct sockaddr_storage ss;
struct sockaddr_in6 s6;
struct sockaddr_in s4;
} peer;
log_printf (RTPS_ID, 0, "TLS: Generate cookie.\r\n");
/* Initialize a random secret */
if (!cookie_initialized) {
if (!RAND_bytes (cookie_secret, COOKIE_SECRET_LENGTH)) {
fatal_printf ("error setting random cookie secret\n");
return (0);
}
cookie_initialized = 1;
}
/* Read peer information */
(void) BIO_dgram_get_peer (SSL_get_rbio (ssl), &peer);
/* Create buffer with peer's address and port */
length = 0;
switch (peer.ss.ss_family) {
case AF_INET:
length += sizeof (struct in_addr);
length += sizeof (peer.s4.sin_port);
break;
case AF_INET6:
length += sizeof (struct in6_addr);
length += sizeof (peer.s4.sin_port);
break;
default:
OPENSSL_assert (0);
break;
}
buffer = (unsigned char*) OPENSSL_malloc (length);
if (!buffer)
fatal_printf ("DDS: generate_cookie (): out of memory!");
switch (peer.ss.ss_family) {
case AF_INET:
memcpy (buffer, &peer.s4.sin_port, sizeof (peer.s4.sin_port));
memcpy (buffer + sizeof (peer.s4.sin_port), &peer.s4.sin_addr, sizeof (struct in_addr));
break;
case AF_INET6:
memcpy (buffer, &peer.s6.sin6_port, sizeof (peer.s6.sin6_port));
memcpy (buffer + sizeof (peer.s6.sin6_port), &peer.s6.sin6_addr, sizeof (struct in6_addr));
break;
default:
OPENSSL_assert (0);
break;
}
/* Calculate HMAC of buffer using the secret */
/*sign_with_private_key (NID_sha1, buffer, length,
&result [0], &resultlength, local_identity); */
HMAC (EVP_sha1 (),
(const void *) cookie_secret, COOKIE_SECRET_LENGTH,
(const unsigned char*) buffer, length,
result, &resultlength);
OPENSSL_free (buffer);
memcpy (cookie, result, resultlength);
*cookie_len = resultlength;
return (1);
}
static int verify_cookie (SSL *ssl, unsigned char *cookie, unsigned int cookie_len)
{
unsigned char *buffer, result[EVP_MAX_MD_SIZE];
unsigned int length = 0, resultlength;
union {
struct sockaddr_storage ss;
struct sockaddr_in6 s6;
struct sockaddr_in s4;
} peer;
log_printf (RTPS_ID, 0, "TLS: Verify cookie.\r\n");
/* If secret isn't initialized yet, the cookie can't be valid */
if (!cookie_initialized)
return (0);
/* Read peer information */
(void) BIO_dgram_get_peer (SSL_get_rbio (ssl), &peer);
/* Create buffer with peer's address and port */
length = 0;
switch (peer.ss.ss_family) {
case AF_INET:
length += sizeof (struct in_addr);
length += sizeof (peer.s4.sin_port);
break;
case AF_INET6:
length += sizeof (struct in6_addr);
length += sizeof (peer.s6.sin6_port);
break;
default:
OPENSSL_assert (0);
break;
}
buffer = (unsigned char*) OPENSSL_malloc (length);
if (!buffer)
fatal_printf ("TLS: verify_cookie(): out of memory!");
switch (peer.ss.ss_family) {
case AF_INET:
memcpy (buffer, &peer.s4.sin_port, sizeof (peer.s4.sin_port));
memcpy (buffer + sizeof (peer.s4.sin_port), &peer.s4.sin_addr, sizeof (struct in_addr));
break;
case AF_INET6:
memcpy (buffer, &peer.s6.sin6_port, sizeof (peer.s6.sin6_port));
memcpy (buffer + sizeof (peer.s6.sin6_port), &peer.s6.sin6_addr, sizeof (struct in6_addr));
break;
default:
OPENSSL_assert (0);
break;
}
/* Calculate HMAC of buffer using the secret */
HMAC (EVP_sha1 (),
(const void*) cookie_secret, COOKIE_SECRET_LENGTH,
(const unsigned char*) buffer, length,
result, &resultlength);
OPENSSL_free (buffer);
if (cookie_len == resultlength && memcmp (result, cookie, resultlength) == 0)
return (1);
return (0);
}
#endif
#define DEPTH_CHECK 5
/* Fill the SSL_CTX with certificate and key */
static SSL_CTX *create_ssl_tls_ctx (TLS_CX_SIDE purpose)
{
SSL_CTX *ctx = NULL;
X509 *cert;
X509 *ca_cert_list[10];
X509 *ca_cert_ptr = NULL;
int nbOfCA;
int j;
EVP_PKEY *privateKey;
static int warned = 0;
trace_func ();
switch (purpose)
{
case TLS_CLIENT:
if ((ctx = SSL_CTX_new (TLSv1_client_method ())) == NULL)
fatal_printf ("TLS - %s () - Failed to create new SSL context", __FUNCTION__);
break;
case TLS_SERVER:
if ((ctx = SSL_CTX_new (TLSv1_server_method ())) == NULL)
fatal_printf ("TLS - %s () - Failed to create new SSL context", __FUNCTION__);
break;
default:
fatal_printf ("TLS - %s () - invalid purpose for new SSL context", __FUNCTION__);
break;
}
if (!SSL_CTX_set_cipher_list (ctx, "AES:!aNULL:!eNULL"))
fatal_printf ("TLS %s (): failed to set cipher list", __FUNCTION__);
SSL_CTX_set_session_cache_mode (ctx, SSL_SESS_CACHE_OFF);
if (get_certificate (&cert, local_identity) ||
!SSL_CTX_use_certificate (ctx, cert)) {
if (!warned) {
warn_printf ("TLS: no client certificate found!");
warned = 1;
}
SSL_CTX_free (ctx);
return (NULL);
}
/* for the client we have to add the client cert to the trusted ca certs */
if (purpose == TLS_CLIENT) {
/* Add extra cert does not automatically up the reference */
SSL_CTX_add_extra_chain_cert (ctx, cert);
cert->references ++;
}
if (get_nb_of_CA_certificates (&nbOfCA, local_identity) ||
nbOfCA == 0)
fatal_printf ("TLS: Did not find any trusted CA certificates");
get_CA_certificate_list (&ca_cert_list[0], local_identity);
for (j = 0; j < nbOfCA ; j++) {
ca_cert_ptr = ca_cert_list[j];
X509_STORE_add_cert (SSL_CTX_get_cert_store (ctx), ca_cert_ptr);
}
if (get_private_key (&privateKey, local_identity) ||
!SSL_CTX_use_PrivateKey (ctx, privateKey))
fatal_printf ("TLS: no private key found!");
SSL_CTX_set_verify (ctx,
SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
tls_verify_callback);
/*Check the private key*/
if (!SSL_CTX_check_private_key (ctx))
fatal_printf ("TLS: invalid private key!");
SSL_CTX_set_verify_depth (ctx, DEPTH_CHECK);
SSL_CTX_set_read_ahead (ctx, 1);
if (purpose == TLS_SERVER) {
SSL_CTX_set_cookie_generate_cb (ctx, generate_cookie);
SSL_CTX_set_cookie_verify_cb (ctx, verify_cookie);
}
return (ctx);
}
/* Initialize the ssl tls server and client contexts */
static int initialize_ssl_tls_ctx (void)
{
log_printf (RTPS_ID, 0, "TLS: Contexts initialized.\r\n");
dds_ssl_init ();
tls_server_ctx = create_ssl_tls_ctx (TLS_SERVER);
if (!tls_server_ctx)
return (1);
tls_client_ctx = create_ssl_tls_ctx (TLS_CLIENT);
if (!tls_client_ctx) {
SSL_CTX_free (tls_server_ctx);
return (1);
}
return (0);
}
/* Cleanup of the tls server and client contexts */
static void cleanup_ssl_tls_ctx (void)
{
SSL_CTX_free (tls_client_ctx);
SSL_CTX_free (tls_server_ctx);
tls_client_ctx = tls_server_ctx = NULL;
dds_ssl_finish ();
log_printf (RTPS_ID, 0, "TLS: Contexts freed.\r\n");
}
/***********/
/* TLS CTX */
/***********/
/* create a tls ctx and a new ssl object */
static TLS_CX *create_tls_ctx (int fd, TLS_CX_SIDE role)
{
TLS_CX *tls;
#ifdef __APPLE__
int yes = 1;
#endif
trace_func ();
trace_tls("TLS: Create TLS context [%d].\r\n", fd);
tls = xmalloc (sizeof (TLS_CX));
if (!tls) {
err_printf ("%s (): out of memory for TLS context!", __FUNCTION__);
return (NULL);
}
if (role == TLS_SERVER) {
if ((tls->ssl = SSL_new (tls_server_ctx)) == NULL) {
err_printf ("%s (): failed to alloc SSL connection context", __FUNCTION__);
goto fail;
}
}
else {
if ((tls->ssl = SSL_new (tls_client_ctx)) == NULL) {
err_printf ("%s (): failed to alloc SSL connection context", __FUNCTION__);
goto fail;
}
}
#ifdef __APPLE__
/* MSG_NOSIGNAL does not exist for Apple OS, but a equivalent socket option is available */
if (setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &yes, sizeof(yes)) < 0){
err_printf("%s: setsockopt()", __FUNCTION__);
}
#endif
tls->fd = fd;
tls->state = SSL_NONE;
tls->ssl_pending_possible = 0;
tls->recv_msg = NULL;
tls->send_msg = NULL;
SSL_set_fd (tls->ssl, fd);
return (tls);
fail:
xfree (tls);
return (NULL);
}
int tls_do_connect (TCP_CON_REQ_ST *p);
void tls_cleanup_ctx (IP_CX *cxp)
{
sock_fd_remove_socket (cxp->fd);
cxp->stream_cb->on_close (cxp);
}
static void pollout_on (int fd)
{
trace_state ("POLLOUT", 1, fd, __FUNCTION__);
sock_fd_event_socket (fd, POLLOUT, 1);
}
static void pollout_off (int fd)
{
trace_state ("POLLOUT", 0, fd, __FUNCTION__);
sock_fd_event_socket (fd, POLLOUT, 0);
}
static void pollin_on (int fd)
{
trace_state ("POLLIN", 1, fd, __FUNCTION__);
sock_fd_event_socket (fd, POLLIN, 1);
}
static void pollin_off (int fd)
{
trace_state ("POLLIN", 0, fd, __FUNCTION__);
sock_fd_event_socket (fd, POLLIN, 0);
}
static TLS_CX *get_tls_ctx (IP_CX *cxp)
{
TLS_CX *tls = (TLS_CX *) cxp->sproto;
trace_func ();
if (!tls) {
if (cxp->paired && cxp->fd == cxp->paired->fd) {
tls = cxp->paired->sproto;
if (!tls)
fatal_printf ("TLS: no valid tls ctx found for [%d] via shared", cxp->fd);
}
else {
fatal_printf ("TLS: no valid tls ctx found for [%d]", cxp->fd);
tls = NULL;
}
}
#if 0
if (cxp->fd_owner) {
if (cxp->sproto != tls)
warn_printf ("TLS: the tls context is not attached to the owner");
} else if (cxp->paired && cxp->paired->fd_owner) {
if (cxp->paired->sproto != tls)
warn_printf ("TLS: the tls context is not attached to the owner");
} else
warn_printf ("TLS: There is no fd owner");
#endif
return (tls);
}
static void handle_pollout (IP_CX *cxp)
{
TLS_CX *tls = get_tls_ctx (cxp);
if (!tls)
return;
/* If WANT_WRITE then set POLLOUT = 1 and POLLIN = 0 */
if (tls->state == SSL_WRITE_WANT_WRITE ||
tls->state == SSL_READ_WANT_WRITE) {
pollout_on (cxp->fd);
pollin_off (cxp->fd);
}
/* If WANT_READ then set POLLOUT = 0 and POLLIN = 1 */
else if (tls->state == SSL_READ_WANT_READ ||
tls->state == SSL_WRITE_WANT_READ) {
pollout_off (cxp->fd);
pollin_on (cxp->fd);
}
/* Error case then remove socket */
else if (tls->state == SSL_ERROR) {
#ifdef TRACE_STATE_CHANGES
log_printf (RTPS_ID, 0, "TLS: sock_fd_remove_sock [%d] (%d)\r\n", cxp->fd, cxp->handle);
#endif
sock_fd_remove_socket (cxp->fd);
}
/* Default POLLOUT = 0 and POLLIN = 1 */
else {
pollout_off (cxp->fd);
pollin_on (cxp->fd);
}
}
static void tls_receive_message (IP_CX *cxp);
/* Write/send (the next part of) a msg (fragment). */
static void tls_write_msg_fragment (IP_CX *cxp)
{
ssize_t n;
unsigned char *sp;
TLS_CX *tls = get_tls_ctx (cxp);
int len, error;
trace_func ();
if (!tls)
return;
trace_tls ("TLS: completing a pending write for fd [%d].\r\n", cxp->fd);
sp = tls->send_msg->buffer + tls->send_msg->used;
while (tls->send_msg->used < tls->send_msg->size) {
len = tls->send_msg->size - tls->send_msg->used;
n = SSL_write (tls->ssl, sp, len);
if (n > 0) {
tls->send_msg->used += n;
sp += n;
}
error = SSL_get_error (tls->ssl, n);
trace_write (n, cxp->fd, len);
/* log_printf (RTPS_ID, 0, "in %s\r\n", __FUNCTION__); */
switch (error) {
case SSL_ERROR_NONE:
/* Write successful. */
#ifdef MSG_TRACE
if (cxp->trace)
rtps_ip_trace (cxp->handle, 'T',
&cxp->locator->locator,
cxp->dst_addr, cxp->dst_port,
len);
#endif
trace_tls ("SSL_write: Error none for fd [%d]\r\n", cxp->fd);
break;
case SSL_ERROR_WANT_WRITE:
trace_tls ("SSL_write: ERROR want write for fd [%d]\r\n", cxp->fd);
tls->state = SSL_WRITE_WANT_WRITE;
handle_pollout (cxp);
return;
case SSL_ERROR_WANT_READ:
trace_tls ("SSL_write: ERROR want read for fd [%d]\r\n", cxp->fd);
tls->state = SSL_WRITE_WANT_READ;
handle_pollout (cxp);
return;
case SSL_ERROR_ZERO_RETURN:
trace_tls ("SSL_write: ERROR zero return for fd [%d]\r\n",cxp->fd);
handle_pollout (cxp);
tls_cleanup_ctx (cxp);
return;
case SSL_ERROR_SSL:
default:
trace_tls ("SSL_write: ERROR for fd [%d]\r\n", cxp->fd);
tls_dump_openssl_error_stack ("SSL_write () error");
xfree (tls->send_msg->buffer);
xfree (tls->send_msg);
tls->send_msg = NULL;
tls->state = SSL_ERROR;
handle_pollout (cxp);
tls_cleanup_ctx (cxp);
return;
}
}
xfree (tls->send_msg->buffer);
xfree (tls->send_msg);
tls->send_msg = NULL;
/* Change own state to none */
tls->state = SSL_NONE;
handle_pollout (cxp);
/* If we wanted to read during prev write, retry */
if (tls->ssl_pending_possible) {
tls->ssl_pending_possible = 0;
tls_receive_message (cxp);
}
if (cxp->stream_cb->on_write_completed)
cxp->stream_cb->on_write_completed (cxp);
else if (cxp->paired &&
cxp->paired->fd == cxp->fd &&
cxp->paired->stream_cb->on_write_completed)
cxp->paired->stream_cb->on_write_completed (cxp->paired);
}
/* Receive (the next part of) a msg (fragment).
A message is complete when msg->read == msg->size; the data is then available in msg->buffer.
It is assumed that fd is set to nonblocking beforehand.
Returns:
0: success (the read(s) went well, msg not necessarilly complete).
-1: Some problem with read (see ERRNO for details). Connection should most
probably be closed. */
static int tls_receive_message_fragment (IP_CX *cxp, TCP_MSG *msg)
{
unsigned char *dp;
ssize_t n;
uint32_t l;
int error;
TLS_CX *tls = get_tls_ctx (cxp);
trace_func ();
if (!tls)
return (-1);
if (!msg->size) {
/* Start of a new message. Expect at least a message header */
msg->used = 0;
msg->size = sizeof (CtrlHeader);
}
if (msg->used < sizeof (CtrlHeader))
/* (Still) reading the msg header */
dp = (unsigned char*) &msg->header + msg->used;
else
/* Continue reading 'til the end of the message */
dp = msg->buffer + msg->used;
continue_reading:
while (msg->used < msg->size) {
n = SSL_read (tls->ssl, dp, msg->size - msg->used);
if (n > 0) {
msg->used += n;
dp += n;
}
error = SSL_get_error (tls->ssl, n);
trace_read (n, cxp->fd, msg->size - msg->used);
switch (error) {
case SSL_ERROR_NONE:
trace_tls ("SSL_read: Error none for fd [%d]\r\n", cxp->fd);
break;
case SSL_ERROR_ZERO_RETURN:
trace_tls ("SSL_read: Error zero return for fd [%d]\r\n", cxp->fd);
goto error;
case SSL_ERROR_WANT_WRITE:
trace_tls ("SSL_read: Error want write for fd [%d]\r\n", cxp->fd);
tls->state = SSL_READ_WANT_WRITE;
handle_pollout (cxp);
return (0);
case SSL_ERROR_WANT_READ:
trace_tls ("SSL_read: Error want read for fd [%d]\r\n", cxp->fd);
tls->state = SSL_READ_WANT_READ;
handle_pollout (cxp);
return (0);
default:
trace_tls ("SSL_read: Error for fd [%d]\r\n", cxp->fd);
tls_dump_openssl_error_stack ("TLS(C): SSL_read () error:");
goto error;
}
}
if (!msg->buffer) {
/* Just received a CtrlHeader - see what else is needed? */
if (ctrl_protocol_valid (&msg->header))
msg->size += msg->header.length;
else if (protocol_valid (&msg->header)) {
memcpy (&l, &msg->header.msg_kind, sizeof (l));
msg->size += l;
}
else {
/* Data not recognized as either a RTPS nor a RPSC message */
msg->size = msg->used = 0;
goto error;
}
msg->buffer = xmalloc (msg->size);
if (!msg->buffer) {
msg->size = msg->used = 0;
goto error;
}
memcpy (msg->buffer, &msg->header, sizeof (CtrlHeader));
dp = msg->buffer + msg->used;
goto continue_reading;
}
if (SSL_pending (tls->ssl))
log_printf (RTPS_ID, 0, "TLS: SSL_pending says there are %d more data bytes to read.\r\n", SSL_pending (tls->ssl));
/* Change own state to none */
tls->state = SSL_NONE;
handle_pollout (cxp);
return (0);
error:
tls->state = SSL_ERROR;
handle_pollout (cxp);
return (-1);
}
static void tls_receive_message (IP_CX *cxp)
{
TCP_MSG *recv_msg;
int r;
TLS_CX *tls = get_tls_ctx (cxp);
trace_func ();
if (!tls)
return;
try_next:
tls->ssl_pending_possible = 0;
if (!tls->recv_msg) {
/* Prepare for receiving messages */
tls->recv_msg = xmalloc (sizeof (TCP_MSG));
if (!tls->recv_msg) {
tls_cleanup_ctx (cxp);
return;
}
tls->recv_msg->size = tls->recv_msg->used = 0;
tls->recv_msg->buffer = NULL;
}
r = tls_receive_message_fragment (cxp, tls->recv_msg);
if (r == -1)
tls_cleanup_ctx (cxp);
else if (tls->recv_msg->used == tls->recv_msg->size) {
recv_msg = tls->recv_msg;
tls->recv_msg = NULL;
if (cxp->stream_cb->on_new_message)
r = cxp->stream_cb->on_new_message (cxp,
recv_msg->buffer,
recv_msg->size);
else
r = cxp->paired->stream_cb->on_new_message (cxp,
recv_msg->buffer,
recv_msg->size);
xfree (recv_msg->buffer);
xfree (recv_msg);
/* If we're not done, check whether another message is present
in the SSL buffers. */
if (r &&
(tls->state == SSL_WRITE_WANT_WRITE ||
tls->state == SSL_WRITE_WANT_READ)) {
tls->ssl_pending_possible = 1;
return;
}
if (r)
goto try_next;
}
}
static void tls_socket_activity (SOCKET fd, short revents, void *arg)
{
IP_CX *cxp = (IP_CX *) arg;
int err, r;
socklen_t sz;
TLS_CX *tls = get_tls_ctx (cxp);
trace_func ();
trace_poll_events (fd, revents, arg);
if (fd != cxp->fd)
fatal_printf ("TLS: tls_socket_activity: fd != cxp->fd");
if (!tls)
return;
if ((revents & (POLLERR | POLLNVAL)) != 0) {
sz = sizeof (err);
r = getsockopt(cxp->fd, SOL_SOCKET, SO_ERROR, &err, &sz);
if ((r == -1) || err) {
log_printf (RTPS_ID, 0, "POLLERR | POLLNVAL [%d]: %d %s\r\n", cxp->fd, err, strerror (err));
tls_cleanup_ctx (cxp);
return;
}
}
if ((revents & POLLHUP) != 0) {
tls_cleanup_ctx (cxp);
return;
}
if ((revents & POLLOUT) != 0) {
if (tls->state == SSL_WRITE_WANT_WRITE)
tls_write_msg_fragment (cxp);
else if (tls->state == SSL_READ_WANT_WRITE)
tls_receive_message (cxp);
else
handle_pollout (cxp);
return;
}
if ((revents & POLLIN) != 0) {
if (tls->state == SSL_WRITE_WANT_READ)
tls_write_msg_fragment (cxp);
else if (tls->state == SSL_READ_WANT_READ)
tls_receive_message (cxp);
else if (tls->state == SSL_NONE)
tls_receive_message (cxp);
else
handle_pollout (cxp);
}
}
static void tls_ssl_connect (SOCKET fd, short revents, void *arg)
{
IP_CX *cxp = (IP_CX *) arg;
TLS_CX *tls = (TLS_CX *) cxp->sproto;
int error;
trace_func ();
trace_tls ("SSL_connect: ssl connect for fd [%d]\r\n", fd);
log_printf (RTPS_ID, 0, "%p\r\n", (void *) cxp);
trace_poll_events (fd, revents, arg);
if ((revents & POLLERR) != 0 || (revents & POLLHUP) != 0) {
log_printf (RTPS_ID, 0, "tls_ssl_connect received POLLERR | POLLHUP for fd [%d]\r\n", fd);
tls_cleanup_ctx (cxp);
}
else if ((revents & POLLOUT) != 0 || (revents & POLLIN) != 0) {
/* Create a tls context */
if (!tls) {
if ((tls = create_tls_ctx (fd, TLS_CLIENT)) == NULL)
return;
cxp->sproto = tls;
}
error = SSL_get_error (tls->ssl, SSL_connect (tls->ssl));
switch (error) {
case SSL_ERROR_NONE:
trace_tls ("SSL_connect: Connect completed for fd [%d]\r\n", fd);
cxp->cx_state = CXS_OPEN;
cxp->stream_cb->on_connected (cxp);
/* Don't change the events */
/* update the userdata function */
#ifdef TRACE_STATE_CHANGES
log_printf (RTPS_ID, 0, "TLS: sock_fd_udata_socket [%d] (%d)\r\n", cxp->fd, cxp->handle);
#endif
sock_fd_udata_socket (cxp->fd, cxp);
/* update the callback function */
log_printf (RTPS_ID, 0, "TLS: Set activity(1) -- [%d], owner=%d, cxp=%p\r\n", cxp->fd, cxp->fd_owner, (void *) cxp);
#ifdef TRACE_STATE_CHANGES
log_printf (RTPS_ID, 0, "TLS: sock_fd_fct_socket [%d] (%d)\r\n", cxp->fd, cxp->handle);
#endif
sock_fd_fct_socket (cxp->fd,
tls_socket_activity);
break;
case SSL_ERROR_ZERO_RETURN:
trace_tls ("SSL_connect: Error zero return for fd [%d]\r\n", fd);
break;
case SSL_ERROR_WANT_WRITE:
trace_tls ("SSL_connect: Error want write for fd [%d]\r\n", fd);
trace_state ("POLLOUT", 1, cxp->fd, __FUNCTION__);
sock_fd_event_socket (cxp->fd, POLLOUT, 1);
break;
case SSL_ERROR_WANT_READ:
trace_tls ("SSL_connect: Error want read for fd [%d]\r\n", fd);
trace_state ("POLLOUT", 0, cxp->fd, __FUNCTION__);
sock_fd_event_socket (cxp->fd, POLLOUT, 0);
break;
default:
trace_tls ("SSL_connect: Default error [%d]\r\n", fd);
tls_dump_openssl_error_stack ("TLS(C): SSL_connect () error:");
tls_cleanup_ctx (cxp);
break;
}
}
/* TODO catch other revents */
}
static void tls_wait_connect_complete (SOCKET fd, short revents, void *arg)
{
TCP_CON_REQ_ST *p = (TCP_CON_REQ_ST *) arg;
IP_CX *cxp = p->cxp;
socklen_t s;
int err, r;
socklen_t sz;
trace_func ();
trace_poll_events (fd, revents, arg);
p = tcp_clear_pending_connect (p);
do {
if ((revents & (POLLERR | POLLNVAL)) != 0) {
sz = sizeof (err);
r = getsockopt(cxp->fd, SOL_SOCKET, SO_ERROR, &err, &sz);
if ((r == -1) || err) {
log_printf (RTPS_ID, 0, "POLLERR | POLLNVAL [%d]: %d %s\r\n", cxp->fd, err, strerror (err));
tls_cleanup_ctx (cxp);
break;
}
}
if ((revents & POLLHUP) != 0) {
tls_cleanup_ctx (cxp);
break;
}
if ((revents & POLLOUT) != 0) {
s = sizeof (err);
r = getsockopt (cxp->fd, SOL_SOCKET, SO_ERROR, &err, &s);
if (r || err) {
warn_printf ("cc_control: getsockopt(SOL_SOCKET/SO_ERROR)");
perror ("cc_control: getsockopt(SOL_SOCKET/SO_ERROR)");
tls_cleanup_ctx (cxp);
break;
}
trace_tls ("Connect completed, trying SSL_connect for fd [%d].\r\n", fd);
/* Don't change the events */
/* update the userdata function */
#ifdef TRACE_STATE_CHANGES
log_printf (RTPS_ID, 0, "TLS: sock_fd_udata_socket [%d] (%d)\r\n", cxp->fd, cxp->handle);
#endif
sock_fd_udata_socket (cxp->fd, cxp);
/* update the callback function */
#ifdef TRACE_STATE_CHANGES
log_printf (RTPS_ID, 0, "TLS: sock_fd_fct_socket [%d] (%d)\r\n", cxp->fd, cxp->handle);
#endif
sock_fd_fct_socket (cxp->fd,
tls_ssl_connect);
tls_ssl_connect (cxp->fd, POLLOUT, cxp);
}
}
while (0);
if (p)
tls_do_connect (p);
}
/********************/
/* CONNECTION SETUP */
/********************/
static void tls_pending_free (TCP_FD *pp)
{
TCP_FD *xpp, *prev_pp;
trace_func ();
for (prev_pp = NULL, xpp = pp->parent->pending;
xpp;
prev_pp = xpp, xpp = xpp->next)
if (xpp == pp) {
if (prev_pp)
prev_pp->next = pp->next;
else
pp->parent->pending = pp->next;
xfree (pp);
break;
}
}
static void tls_close_pending_connection (TCP_FD *pp)
{
TLS_CX *tls = (TLS_CX *) pp->sproto;
int err;
#ifdef TRACE_TLS_SPECIFIC
int mode;
#endif
#ifdef TRACE_SERVER
int r;
#endif
trace_func ();
if (tmr_active (&pp->timer))
tmr_stop (&pp->timer);
sock_fd_remove_socket (pp->fd);
if (tls) {
if (tls->ssl) {
if (server_mode) {
err = SSL_shutdown (tls->ssl);
if (err == 0) {
shutdown (pp->fd, 1);
err = SSL_shutdown (tls->ssl);
}
switch (err) {
case 1:
break;
case 0:
case -1:
default:
#ifdef TRACE_TLS_SPECIFIC
log_printf (RTPS_ID, 0, "TLS: socket [%d] not closed gracefully", pp->fd);
#endif
break;
}
SSL_free (tls->ssl);
} else {
err = SSL_shutdown (tls->ssl);
switch (err) {
case 1:
break;
case 0:
case -1:
default:
#ifdef TRACE_TLS_SPECIFIC
log_printf (RTPS_ID, 0, "TLS: socket [%d] not closed gracefully", pp->fd);
#endif
break;
}
SSL_free (tls->ssl);
}
}
xfree (tls);
}
#ifdef TRACE_SERVER
r = close (pp->fd);
trace_server ("close", r, pp->fd);
#else
close (pp->fd);
#endif
pp->fd = -1;
tls_pending_free (pp);
}
static void tls_pending_timeout (uintptr_t user)
{
TCP_FD *pp = (TCP_FD *) user;
log_printf (RTPS_ID, 0, "tls_pending_timeout: connection close!\r\n");
tls_close_pending_connection (pp);
}
static void tls_pending_first_message (SOCKET fd, short revents, void *arg)
{
TCP_FD *pp = (TCP_FD *) arg;
IP_CX *cxp = NULL;
IP_CX tmp;
trace_func ();
trace_poll_events (fd, revents, arg);
/* Check if connection unexpectedly closed. */
if ((revents & POLLHUP) != 0) {
trace_tls ("TLS(Sp): connection error for [%d]!\r\n", fd);
tls_close_pending_connection (pp);
return;
}
/* we need a tmp CX_IP to keep track of the correct TLS_CX */
tmp.sproto = pp->sproto;
tmp.fd = pp->fd;
tmp.paired = NULL;
tmp.fd_owner = 1;
if (tls_receive_message_fragment (&tmp, &pp->recv_msg) == -1) {
tls_close_pending_connection (pp);
return;
}
if (pp->recv_msg.used != pp->recv_msg.size)
return; /* message (still) incomplete */
cxp = pp->parent->stream_cb->on_new_connection (pp, pp->recv_msg.buffer, pp->recv_msg.size);
xfree (pp->recv_msg.buffer);
pp->recv_msg.buffer = NULL;
pp->recv_msg.size = pp->recv_msg.used = 0;
if (!cxp) {
/* pending connection could not be 'promoted' to an IP_CX */
tls_close_pending_connection (pp);
return;
}
cxp->sproto = pp->sproto;
cxp->cx_state = CXS_OPEN;
/* Don't change the events */
/* update the userdata function */
#ifdef TRACE_STATE_CHANGES
log_printf (RTPS_ID, 0, "TLS: sock_fd_udata_socket [%d] (%d)\r\n", cxp->fd, cxp->handle);
#endif
sock_fd_udata_socket (cxp->fd, cxp);
/* update the callback function */
log_printf (RTPS_ID, 0, "TLS: Set activity(2) -- [%d], owner=%d\r\n", cxp->fd, cxp->fd_owner);
#ifdef TRACE_STATE_CHANGES
log_printf (RTPS_ID, 0, "TLS: sock_fd_fct_socket [%d] (%d)\r\n", cxp->fd, cxp->handle);
#endif
sock_fd_fct_socket (cxp->fd,
tls_socket_activity);
tmr_stop (&pp->timer);
tls_pending_free (pp);
}
static void tls_ssl_accept (SOCKET fd, short revents, void *arg)
{
TCP_FD *pp = (TCP_FD *) arg;
TLS_CX *tls = pp->sproto;
int error;
trace_func ();
trace_poll_events (fd, revents, arg);
trace_tls ("SSL_accept: ssl accept for fd [%d]\r\n", fd);
if ((revents & POLLOUT) != 0 || (revents & POLLIN) != 0) {
error = SSL_accept (tls->ssl);
error = SSL_get_error (tls->ssl, error);
switch (error) {
case SSL_ERROR_NONE:
/* Accept successful. */
#ifdef TRACE_MSGS
if (rtps_trace && (mp->element.flags & RME_TRACE) != 0) {
trace_msg ('T', loc2sockaddr (
pp->parent->locator->locator.kind,
pp->parent->dst_port,
pp->parent->dst_addr,
sabuf), len);
}
#endif
trace_tls ("SSL_accept: Completed for fd [%d]\r\n", fd);
pp->parent->cx_state = CXS_OPEN;
/* Don't change the events */
/* update the userdata function */
sock_fd_udata_socket (fd, pp);
/* update the callback function */
sock_fd_fct_socket (fd,
tls_pending_first_message);
break;
case SSL_ERROR_WANT_WRITE:
trace_tls ("SSL_accept: Error want write for fd [%d]\r\n", fd);
/* SSL_accept wants to write, so it needs to wait for a timeslot
that the socket can write data out */
trace_state ("POLLOUT", 1, pp->fd, __FUNCTION__);
sock_fd_event_socket (fd, POLLOUT, 1);
break;
case SSL_ERROR_WANT_READ:
trace_tls ("SSL_accept: Error want read for fd [%d]\r\n", fd);
/* SSL_accept wants to read, so it needs to wait for a timeslot
that the socket has data available to read */
trace_state ("POLLOUT", 0, pp->fd, __FUNCTION__);
sock_fd_event_socket (fd, POLLOUT, 0);
break;
case SSL_ERROR_ZERO_RETURN:
trace_tls ("SSL_accept: Error zero return for fd [%d]\r\n", fd);
break;
case SSL_ERROR_SYSCALL:
trace_tls ("SSL_accept: Error syscall for fd [%d] --> ", fd);
if (ERRNO == 0)
trace_tls ("No syscall error for fd [%d]\r\n", fd);
else {
trace_tls ("Unknown error for fd [%d]\r\n", fd);
}
break;
default:
trace_tls ("SSL_accept: Error other for fd [%d]\r\n", fd);
tls_dump_openssl_error_stack ("SSL_accept () default\r\n");
/* The accept has not yet succeeded, so quietly shutdown ssl connection */
SSL_set_quiet_shutdown (tls->ssl, 1);
tls_close_pending_connection (pp);
}
}
}
static void tls_server_accept (SOCKET fd, short revents, void *arg)
{
IP_CX *scxp = (IP_CX *) arg;
TCP_FD *pp;
struct sockaddr_in peer_addr;
#ifdef DDS_IPV6
struct sockaddr_in6 peer_addr_v6;
#endif
struct sockaddr *caddr;
socklen_t size;
uint32_t a4;
int r, err;
#ifdef TRACE_TLS_SPECIFIC
int mode;
#endif
#ifdef TRACE_SERVER
int ofcmode;
#endif
TLS_CX *tls;
trace_func ();
trace_poll_events (fd, revents, arg);
log_printf (RTPS_ID, 0, "TLS: server accept on [%d].\r\n", fd);
memset (&scxp->dst_addr, 0, sizeof (scxp->dst_addr));
if (scxp->locator->locator.kind == LOCATOR_KIND_TCPv4) {
peer_addr.sin_family = AF_INET;
caddr = (struct sockaddr *) &peer_addr;
size = sizeof (struct sockaddr_in);
}
#ifdef DDS_IPV6
else if (scxp->locator->locator.kind == LOCATOR_KIND_TCPv6) {
peer_addr_v6.sin6_family = AF_INET6;
caddr = (struct sockaddr *) &peer_addr_v6;
size = sizeof (struct sockaddr_in6);
}
#endif
else {
warn_printf ("TLS(S): unknown address family!");
return;
}
scxp->cx_state = CXS_LISTEN;
log_printf (RTPS_ID, 0, "TLS: The socket [%d] is now listening\r\n", scxp->fd);
r = accept (fd, caddr, &size);
trace_server ("accept", r, fd);
if (r < 0) {
perror ("tls_server_accept: accept()");
log_printf (RTPS_ID, 0, "tls_server_accept: accept() failed - errno = %d.\r\n", ERRNO);
return;
}
#ifdef DDS_TCP_NODELAY
sock_set_tcp_nodelay (r);
#endif
/* Create a new tls context */
if ((tls = create_tls_ctx (r, TLS_SERVER)) == NULL) {
close (r);
return;
}
/* Create a new pending TCP connection. */
pp = xmalloc (sizeof (TCP_FD));
if (!pp) {
if (tls) {
if (tls->ssl) {
if (server_mode) {
err = SSL_shutdown (tls->ssl);
if (err == 0) {
shutdown (r, 1);
err = SSL_shutdown (tls->ssl);
}
switch (err) {
case 1:
break;
case 0:
case -1:
default:
#ifdef TRACE_TLS_SPECIFIC
log_printf (RTPS_ID, 0, "TLS: socket [%d] not closed gracefully", pp->fd);
#endif
break;
}
SSL_free (tls->ssl);
} else {
err = SSL_shutdown (tls->ssl);
switch (r) {
case 1:
break;
case 0:
case -1:
default:
#ifdef TRACE_TLS_SPECIFIC
log_printf (RTPS_ID, 0, "TLS: socket [%d] not closed gracefully", pp->fd);
#endif
break;
}
SSL_free (tls->ssl);
}
}
xfree (tls);
}
#ifdef TRACE_SERVER
ofcmode = close (r); /* bad reuse of variable in error case */
trace_server ("close", ofcmode, r);
#else
close (r);
#endif
log_printf (RTPS_ID, 0, "TLS(S): allocation failure!\r\n");
return;
}
pp->sproto = tls;
pp->fd = r;
if (scxp->locator->locator.kind == LOCATOR_KIND_TCPv4) {
a4 = ntohl (peer_addr.sin_addr.s_addr);
memset (pp->dst_addr, 0, 12);
pp->dst_addr [12] = a4 >> 24;
pp->dst_addr [13] = (a4 >> 16) & 0xff;
pp->dst_addr [14] = (a4 >> 8) & 0xff;
pp->dst_addr [15] = a4 & 0xff;
pp->dst_port = ntohs (peer_addr.sin_port);
}
#ifdef DDS_IPV6
else if (scxp->locator->locator.kind == LOCATOR_KIND_TCPv6) {
memcpy (&pp->dst_addr, &peer_addr_v6.sin6_addr, 16);
pp->dst_port = ntohs (peer_addr_v6.sin6_port);
}
#endif
else {
r = close (pp->fd);
trace_server ("close", r, pp->fd);
xfree (pp);
log_printf (RTPS_ID, 0, "TLS(S): unsupported connection family!\r\n");
return;
}
tmr_init (&pp->timer, "TLS-Pending");
pp->parent = scxp;
pp->next = scxp->pending;
scxp->pending = pp;
pp->recv_msg.used = pp->recv_msg.size = 0;
pp->recv_msg.buffer = NULL;
tmr_start (&pp->timer, TICKS_PER_SEC * 2, (uintptr_t) pp, tls_pending_timeout);
/* Set socket as non-blocking. */
sock_set_socket_nonblocking (pp->fd);
#ifdef TRACE_STATE_CHANGES
log_printf (RTPS_ID, 0, "TLS: sock_fd_add_sock [%d] \r\n", pp->fd);
#endif
sock_fd_add_socket (pp->fd,
POLLIN | POLLPRI | POLLHUP | POLLNVAL /*| POLLOUT*/,
tls_ssl_accept,
pp,
"DDS.TLS-A");
tls_ssl_accept (pp->fd, POLLIN, pp);
}
/**************/
/* STREAM API */
/**************/
/* Start the tls server based on the ip context */
int tls_start_server (IP_CX *scxp)
{
struct sockaddr_in sa_v4;
#ifdef DDS_IPV6
struct sockaddr_in6 sa_v6;
#endif
struct sockaddr *sa;
size_t size;
int fd, r;
unsigned family;
trace_func ();
/* initialize ssl context */
if (!tls_server_ctx && initialize_ssl_tls_ctx ())
return (-1);
server_mode = 1;
#ifdef DDS_IPV6
if (scxp->locator->locator.kind == LOCATOR_KIND_TCPv4) {
#endif
sa_v4.sin_family = family = AF_INET;
memset (&sa_v4.sin_addr, 0, 4);
sa_v4.sin_port = htons (scxp->locator->locator.port);
sa = (struct sockaddr *) &sa_v4;
size = sizeof (sa_v4);
log_printf (RTPS_ID, 0, "TCP: Starting secure TCPv4 server on port %d.\r\n", scxp->locator->locator.port);
#ifdef DDS_IPV6
}
else {
sa_v6.sin6_family = family = AF_INET6;
memset (&sa_v6.sin6_addr, 0, 16);
sa_v6.sin6_port = htons (scxp->locator->locator.port);
sa = (struct sockaddr *) &sa_v6;
size = sizeof (sa_v6);
log_printf (RTPS_ID, 0, "TCP: Starting secure TCPv6 server on port %d.\r\n", scxp->locator->locator.port);
}
#endif
fd = socket (family, SOCK_STREAM, IPPROTO_TCP);
log_printf (RTPS_ID, 0, "TCP: Secure listening socket created on [%d].\r\n", fd);
trace_server ("socket", fd, -1);
if (fd < 0) {
perror ("TLS: socket()");
log_printf (RTPS_ID, 0, "TLS: socket() failed - errno = %d.\r\n", ERRNO);
return (-1);
}
r = bind (fd, sa, size);
trace_server ("bind", r, fd);
if (r) {
perror ("TLS: bind()");
log_printf (RTPS_ID, 0, "TLS: bind() failed - errno = %d.\r\n", ERRNO);
r = close (fd);
trace_server ("close", r, fd);
return (-1);
}
r = listen (fd, 32);
trace_server ("listen", r, fd);
if (r) {
perror ("TLS: listen()");
log_printf (RTPS_ID, 0, "TLS: listen() failed - errno = %d.\r\n", ERRNO);
r = close (fd);
trace_server ("close", r, fd);
return (-1);
}
#ifdef DDS_TCP_NODELAY
/* Set TCP_NODELAY flag */
sock_set_tcp_nodelay (fd);
#endif
/* Set socket as non-blocking. */
sock_set_socket_nonblocking (fd);
/* Secure locator stuff */
locator_lock (&scxp->locator->locator);
scxp->locator->locator.flags = LOCF_SECURE | LOCF_SERVER;
scxp->locator->locator.handle = scxp->handle;
locator_release (&scxp->locator->locator);
scxp->cx_type = CXT_TCP_TLS;
scxp->cx_mode = ICM_ROOT;
scxp->fd = fd;
scxp->fd_owner = 1;
log_printf (RTPS_ID, 0, "TCP: The secure socket [%d] is now listening.\r\n", fd);
scxp->cx_state = CXS_LISTEN;
#ifdef TRACE_STATE_CHANGES
log_printf (RTPS_ID, 0, "TLS: sock_fd_add_sock [%d] (%d)\r\n", scxp->fd, scxp->handle);
#endif
sock_fd_add_socket (scxp->fd,
POLLIN | POLLPRI | POLLHUP | POLLNVAL,
tls_server_accept,
scxp,
"DDS.TLS-S");
log_printf (RTPS_ID, 0, "TCP: Secure server started.\r\n");
return (0);
}
/* Stop a previously started server */
void tls_stop_server (IP_CX *scxp)
{
trace_func ();
log_printf (RTPS_ID, 0, "TCP: Stopping secure server on [%d]\r\n", scxp->fd);
#ifdef TRACE_STATE_CHANGES
log_printf (RTPS_ID, 0, "TLS: sock_fd_remove_sock [%d] (%d)\r\n", scxp->fd, scxp->handle);
#endif
sock_fd_remove_socket (scxp->fd);
if (close (scxp->fd))
warn_printf ("TCP: Could not close [%d]", scxp->fd);
scxp->fd = -1;
scxp->fd_owner = 0;
log_printf (RTPS_ID, 0, "TCP: Secure server stopped.\r\n");
cleanup_ssl_tls_ctx ();
}
int tls_do_connect (TCP_CON_REQ_ST *p)
{
TCP_CON_LIST_ST *hp;
struct sockaddr_in sa_v4;
#ifdef DDS_IPV6
struct sockaddr_in6 sa_v6;
#endif
struct sockaddr *sa;
socklen_t len;
unsigned family;
int fd, r, err;
short events;
trace_func ();
if (!tls_client_ctx) {
if (initialize_ssl_tls_ctx ())
return (-2);
}
do {
hp = p->head;
if ((hp->locator.kind & LOCATOR_KINDS_IPv4) != 0) {
sa_v4.sin_family = family = AF_INET;
sa_v4.sin_port = htons (hp->locator.port);
sa = (struct sockaddr *) &sa_v4;
len = sizeof (sa_v4);
sa_v4.sin_addr.s_addr = htonl ((hp->locator.address [12] << 24) |
(hp->locator.address [13] << 16) |
(hp->locator.address [14] << 8) |
hp->locator.address [15]);
}
#ifdef DDS_IPV6
else if ((hp->locator.kind & LOCATOR_KINDS_IPv6) != 0) {
sa_v6.sin6_family = family = AF_INET6;
memcpy (&sa_v6.sin6_addr, hp->locator.address, 16);
sa_v6.sin6_port = htons (hp->locator.port);
sa = (struct sockaddr *) &sa_v6;
len = sizeof (sa_v6);
}
#endif
else
return (-2);
fd = socket (family, SOCK_STREAM, IPPROTO_TCP);
trace_client ("socket", fd, -1);
if (fd < 0) {
perror ("tls_connect: socket()");
log_printf (RTPS_ID, 0, "tls_connect: socket() failed - errno = %d.\r\n", ERRNO);
return (-2);
}
log_printf (RTPS_ID, 0, "TLS: created a new socket on [%d] (%p).\r\n", fd, (void *) p->cxp);
p->cxp->fd = fd;
p->cxp->fd_owner = 1;
#ifdef DDS_TCP_NODELAY
/* Set TCP_NODELAY flag */
sock_set_tcp_nodelay (fd);
#endif
sock_set_socket_nonblocking (fd);
events = POLLIN | POLLPRI | POLLHUP | POLLNVAL;
for (;;) {
r = connect (fd, sa, len);
trace_client ("connect", r, fd);
if (r == -1) {
err = ERRNO;
if (err == EINTR)
continue;
if (err != EINPROGRESS) {
perror ("tls_connect: connect()");
log_printf (RTPS_ID, 0, "tls_connect: connect() failed - errno = %d.\r\n", ERRNO);
close (fd);
p->cxp->fd = -1;
p->cxp->fd_owner = 0;
trace_server ("close", r, fd);
}
else {
log_printf (RTPS_ID, 0, "TLS: connecting to server [%d] ...\r\n", fd);
p->cxp->cx_state = CXS_CONNECT;
sock_fd_add_socket (fd, events | POLLOUT, tls_wait_connect_complete, p, "DDS.TLS-C");
return (-1);
}
}
else {
log_printf (RTPS_ID, 0, "TLS: Connected to server on [%d]\r\n", fd);
p->cxp->cx_state = CXS_SAUTH;
sock_fd_add_socket (fd, events, tls_ssl_connect, p->cxp, "DDS.TLS-C");
tls_ssl_connect (fd, events, p->cxp);
}
break;
}
p = tcp_clear_pending_connect (p);
}
while (p);
return (r);
}
int tls_connect (IP_CX *cxp, unsigned port)
{
log_printf (RTPS_ID, 0, "Put (%p) in the connect queue\r\n", (void *) cxp);
return (tcp_connect_enqueue (cxp, port, tls_do_connect));
}
void tls_disconnect (IP_CX *cxp)
{
TCP_CON_REQ_ST *next_p = NULL;
TLS_CX *tls;
int r;
#ifdef TRACE_TLS_SPECIFIC
int mode;
#endif
trace_func ();
log_printf (RTPS_ID, 0, "TLS: sock_fd_remove_sock [%d] (%d)\r\n", cxp->fd, cxp->handle);
if (cxp->fd_owner)
sock_fd_remove_socket (cxp->fd);
if (cxp->cx_state == CXS_CONREQ || cxp->cx_state == CXS_CONNECT) {
next_p = tcp_pending_connect_remove (cxp);
if (cxp->cx_state == CXS_CONREQ) {
if (next_p)
tls_do_connect (next_p);
return;
}
}
if ((tls = (TLS_CX *) cxp->sproto) != NULL) {
cxp->sproto = NULL;
if (tls->ssl) {
if (server_mode) {
r = SSL_shutdown (tls->ssl);
if (r == 0) {
shutdown (cxp->fd, 1);
r = SSL_shutdown (tls->ssl);
}
switch (r) {
case 1:
break;
case 0:
case -1:
default:
#ifdef TRACE_TLS_SPECIFIC
log_printf (RTPS_ID, 0, "TLS: socket [%d] not closed gracefully", cxp->fd);
#endif
break;
}
SSL_free (tls->ssl);
} else {
r = SSL_shutdown (tls->ssl);
switch (r) {
case 1:
break;
case 0:
case -1:
default:
#ifdef TRACE_TLS_SPECIFIC
log_printf (RTPS_ID, 0, "TLS: socket [%d] not closed gracefully", cxp->fd);
#endif
break;
}
SSL_free (tls->ssl);
}
/* Cleanup the send and recv buffers */
if (tls->recv_msg) {
if (tls->recv_msg->buffer) {
xfree (tls->recv_msg->buffer);
tls->recv_msg->buffer = NULL;
}
xfree (tls->recv_msg);
tls->recv_msg = NULL;
}
if (tls->send_msg) {
if (tls->send_msg->buffer) {
xfree (tls->send_msg->buffer);
tls->send_msg->buffer = NULL;
}
xfree (tls->send_msg);
tls->send_msg = NULL;
}
}
xfree (tls);
}
do {
r = close (cxp->fd);
trace_server ("close", r, cxp->fd);
}
while (r == -1 && ERRNO == EINTR);
log_printf (RTPS_ID, 0, "TLS: The socket [%d] (%d) is now closed\r\n", cxp->fd, cxp->handle);
cxp->fd = -1;
cxp->fd_owner = 0;
if (next_p)
tls_do_connect (next_p);
}
static WR_RC tls_enqueue (IP_CX *cxp,
unsigned char *msg,
unsigned char *sp,
size_t left)
{
TCP_MSG **send_msg, *p;
TLS_CX *tls = get_tls_ctx (cxp);
/* Save message in current context -- fd owner or not! */
send_msg = &tls->send_msg;
/* Make arrangements for fragmented write. */
p = *send_msg = xmalloc (sizeof (TCP_MSG));
if (!p) {
xfree (msg);
return (WRITE_ERROR);
}
p->msg = msg;
p->buffer = sp;
p->size = left;
p->used = 0;
return (WRITE_PENDING);
}
WR_RC tls_write_msg (IP_CX *cxp, unsigned char *msg, size_t len)
{
TLS_CX *tls = get_tls_ctx (cxp);
ssize_t n;
size_t left;
unsigned char *sp = msg;
int error;
WR_RC rc;
trace_func ();
if (!tls) {
xfree (msg);
return (WRITE_FATAL);
}
if (tls->send_msg) {
xfree (msg);
return (WRITE_BUSY);
}
if (cxp->cx_state != CXS_OPEN) {
trace_tls ("SSL_write: Socket [%d] is not open.\r\n", cxp->fd);
xfree (msg);
return (WRITE_BUSY);
}
left = len;
while (left) {
/* We're using send() here iso write() so that we can indicate to the kernel *not* to send
a SIGPIPE in case the other already closed this connection. A return code of -1 and ERRNO
to EPIPE is given instead */
n = SSL_write (tls->ssl, sp, left);
if (n > 0) {
left -= n;
sp += n;
}
error = SSL_get_error (tls->ssl, n);
trace_write (n, cxp->fd, left);
/*log_printf (RTPS_ID, 0, "in %s\r\n", __FUNCTION__);*/
switch (error) {
case SSL_ERROR_NONE:
/* Write successful. */
#ifdef MSG_TRACE
if (cxp->trace)
rtps_ip_trace (cxp->handle, 'T',
&cxp->locator->locator,
cxp->dst_addr, cxp->dst_port,
len);
#endif
trace_tls ("SSL_write: Error none for [%d]\r\n", cxp->fd);
break;
case SSL_ERROR_WANT_WRITE:
trace_tls ("SSL_write: ERROR want write for [%d]\r\n", cxp->fd);
rc = tls_enqueue (cxp, msg, sp, left);
if (rc == WRITE_PENDING) {
tls->state = SSL_WRITE_WANT_WRITE;
handle_pollout (cxp);
}
return (rc);
case SSL_ERROR_WANT_READ:
/* This can happen when a renegotiation of handshake happens
So we can't ignore this */
trace_tls ("SSL_write: ERROR want read for [%d]\r\n", cxp->fd);
rc = tls_enqueue (cxp, msg, sp, left);
if (rc == WRITE_PENDING) {
tls->state = SSL_WRITE_WANT_READ;
handle_pollout (cxp);
}
return (rc);
case SSL_ERROR_ZERO_RETURN:
trace_tls ("SSL_write: ERROR zero return for [%d]\r\n",cxp-> fd);
goto error;
case SSL_ERROR_SSL:
default:
trace_tls ("SSL_write: Error for [%d]\r\n", cxp->fd);
tls_dump_openssl_error_stack ("SSL_write () error");
goto error;
}
}
/* Change own state to none */
tls->state = SSL_NONE;
handle_pollout (cxp);
xfree (msg);
return (WRITE_OK);
error:
xfree (msg);
tls->state = SSL_ERROR;
handle_pollout (cxp);
return (WRITE_FATAL);
}
/* Initialize the SSL/TLS support. */
void rtps_tls_init (void)
{
log_printf (RTPS_ID, 0, "TLS: Initialization.\r\n");
initialize_ssl_tls_ctx ();
}
/* Finalize the SSL/TLS support. */
void rtps_tls_finish (void)
{
log_printf (RTPS_ID, 0, "TLS: Cleanup.\r\n");
cleanup_ssl_tls_ctx ();
}
STREAM_API tls_functions = {
tls_start_server,
tls_stop_server,
tls_connect,
tls_disconnect,
tls_write_msg
};
#else
int tls_available = 0;
#endif
|
the_stack_data/86074250.c | /* Check intermediate returns */
#include <stdio.h>
void for_loop08()
{
int i;
for(i=0;i!=5;i++) {
if (i == 3) {
printf("i=%d\n",i);
return;
}
}
printf("Exit with %d\n",i);
}
main()
{
for_loop08();
return 0;
}
|
the_stack_data/173577503.c | /*
* CS:APP Data Lab
*
* <Please put your name and userid here>
*
* bits.c - Source file with your solutions to the Lab.
* This is the file you will hand in to your instructor.
*
* WARNING: Do not include the <stdio.h> header; it confuses the dlc
* compiler. You can still use printf for debugging without including
* <stdio.h>, although you might get a compiler warning. In general,
* it's not good practice to ignore compiler warnings, but in this
* case it's OK.
*/
#if 0
/*
* Instructions to Students:
*
* STEP 1: Read the following instructions carefully.
*/
You will provide your solution to the Data Lab by
editing the collection of functions in this source file.
INTEGER CODING RULES:
Replace the "return" statement in each function with one
or more lines of C code that implements the function. Your code
must conform to the following style:
int Funct(arg1, arg2, ...) {
/* brief description of how your implementation works */
int var1 = Expr1;
...
int varM = ExprM;
varJ = ExprJ;
...
varN = ExprN;
return ExprR;
}
Each "Expr" is an expression using ONLY the following:
1. Integer constants 0 through 255 (0xFF), inclusive. You are
not allowed to use big constants such as 0xffffffff.
2. Function arguments and local variables (no global variables).
3. Unary integer operations ! ~
4. Binary integer operations & ^ | + << >>
Some of the problems restrict the set of allowed operators even further.
Each "Expr" may consist of multiple operators. You are not restricted to
one operator per line.
You are expressly forbidden to:
1. Use any control constructs such as if, do, while, for, switch, etc.
2. Define or use any macros.
3. Define any additional functions in this file.
4. Call any functions.
5. Use any other operations, such as &&, ||, -, or ?:
6. Use any form of casting.
7. Use any data type other than int. This implies that you
cannot use arrays, structs, or unions.
You may assume that your machine:
1. Uses 2s complement, 32-bit representations of integers.
2. Performs right shifts arithmetically.
3. Has unpredictable behavior when shifting an integer by more
than the word size.
EXAMPLES OF ACCEPTABLE CODING STYLE:
/*
* pow2plus1 - returns 2^x + 1, where 0 <= x <= 31
*/
int pow2plus1(int x) {
/* exploit ability of shifts to compute powers of 2 */
return (1 << x) + 1;
}
/*
* pow2plus4 - returns 2^x + 4, where 0 <= x <= 31
*/
int pow2plus4(int x) {
/* exploit ability of shifts to compute powers of 2 */
int result = (1 << x);
result += 4;
return result;
}
FLOATING POINT CODING RULES
For the problems that require you to implent floating-point operations,
the coding rules are less strict. You are allowed to use looping and
conditional control. You are allowed to use both ints and unsigneds.
You can use arbitrary integer and unsigned constants.
You are expressly forbidden to:
1. Define or use any macros.
2. Define any additional functions in this file.
3. Call any functions.
4. Use any form of casting.
5. Use any data type other than int or unsigned. This means that you
cannot use arrays, structs, or unions.
6. Use any floating point data types, operations, or constants.
NOTES:
1. Use the dlc (data lab checker) compiler (described in the handout) to
check the legality of your solutions.
2. Each function has a maximum number of operators (! ~ & ^ | + << >>)
that you are allowed to use for your implementation of the function.
The max operator count is checked by dlc. Note that '=' is not
counted; you may use as many of these as you want without penalty.
3. Use the btest test harness to check your functions for correctness.
4. Use the BDD checker to formally verify your functions
5. The maximum number of ops for each function is given in the
header comment for each function. If there are any inconsistencies
between the maximum ops in the writeup and in this file, consider
this file the authoritative source.
/*
* STEP 2: Modify the following functions according the coding rules.
*
* IMPORTANT. TO AVOID GRADING SURPRISES:
* 1. Use the dlc compiler to check that your solutions conform
* to the coding rules.
* 2. Use the BDD checker to formally verify that your solutions produce
* the correct answers.
*/
#endif
/* Copyright (C) 1991-2016 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, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses Unicode 8.0.0. Version 8.0 of the Unicode Standard is
synchronized with ISO/IEC 10646:2014, plus Amendment 1 (published
2015-05-15). */
/* We do not support C11 <threads.h>. */
/*
* testAndSet: if low 16-bit of x == y, then let high 16-bit of x = z and
* return x, otherwise return x directly.
* x is a 32-bit integer, both y and z are 16-bit integers.
* Example: testAndSet(0xFFFFFFFF, 0xEEEE, 0xDDDD) = 0xFFFFFFFF,
* testAndSet(0xFFFFFFFF, 0xFFFF, 0xDDDD) = 0xDDDDFFFF,
* Legal ops: ~ | ^ & << >> + !
* Max ops: 20
* Rating: 2
*/
int testAndSet(int x, int y, int z) {
int x1=((!((x<<16)^(y<<16)))<<31)>>31;
int x2=(x1&(z<<16))|((~x1)&x);
return x2|(x&((0xFF<<8)|0xFF));
}
/*
* oneMoreThan - return 1 if y is one more than x, and 0 otherwise
* Examples oneMoreThan(0, 1) = 1, oneMoreThan(-1, 1) = 0
* Legal ops: ~ & ! ^ | + << >>
* Max ops: 15
* Rating: 2
*/
int oneMoreThan(int x, int y) {
return (!((x+1)^y))&(!(!(x^(~(1<<31)))));
}
/*
* isTmin - returns 1 if x is the minimum, two's complement number,
* and 0 otherwise
* Legal ops: ! ~ & ^ | +
* Max ops: 10
* Rating: 1
*/
int isTmin(int x) {
return (!((~x+1)^x))&(!(!x));
}
/*
* halfAdd - single-bit add using bit-wise operations only.
* Both x and y belong to {0, 1}.
* Example: halfAdd(1, 0) = 1,
* halfAdd(1, 1) = 2,
* Legal ops: ~ | ^ & << >>
* Max ops: 7
* Rating: 1
*/
int halfAdd(int x, int y) {
return ((x&y)<<1)|(x^y);
}
/*
* sameSign - return 1 if x and y have same sign, and 0 otherwise
* Examples sameSign(0x12345678, 0) = 1, sameSign(0xFFFFFFFF,0x1) = 0
* Legal ops: ! ~ & ! ^ | + << >>
* Max ops: 5
* Rating: 2
*/
int sameSign(int x, int y) {
return !((x^y)>>31);
}
/*
* fullAdd - 4-bits add using bit-wise operations only.
* (0 <= x, y < 16)
* Example: fullAdd(12, 7) = 3,
* fullAdd(7, 8) = 15,
* Legal ops: ~ | ^ & << >>
* Max ops: 30
* Rating: 2
*/
int fullAdd(int x, int y) {
int x0=x^y,j1=(x&y)<<1;
int x1=x0^j1,j2=(x0&j1)<<1;
int x2=x1^j2,j3=(x1&j2)<<1;
int x3=x2^j3;
return x3&0xF;
}
/*
* negate - return -x
* Example: negate(1) = -1.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 5
* Rating: 2
*/
int negate(int x) {
return (~x)+1;
}
/*
* subOK - Determine if can compute x-y without overflow
* Example: subOK(0x80000000,0x80000000) = 1,
* subOK(0x80000000,0x70000000) = 0,
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 20
* Rating: 3
*/
int subOK(int x, int y) {
int sum=x+(~y+1);
int sgx=(x>>31)&1,sgy=(y>>31)&1,sgs=(sum>>31)&1;
return !(((!sgx)&sgy&sgs)|(sgx&(!sgy)&(!sgs)));
}
/*
* negPerByte: negate each byte of x, then return x.
* Example: negPerByte(0xF8384CA9) = 0x08C8B457,
* Legal ops: ~ | ^ & << >> + !
* Max ops: 30
* Rating: 3
*/
int negPerByte(int x) {
int y=~x;
int x1=((y>>24)+1)&0xFF;
int x2=((y>>16)+1)&0xFF;
int x3=((y>>8)+1)&0xFF;
int x4=(y+1)&0xFF;
return (x1<<24)|(x2<<16)|(x3<<8)|x4;
}
/*
* isGreater - if x > y then return 1, else return 0
* Example: isGreater(4,5) = 0, isGreater(5,4) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 24
* Rating: 3
*/
int isGreater(int x, int y) {
int sgx=(x>>31)&1;
int sgy=(y>>31)&1;
int cha=x+((~y)+1);
int sgc=((cha>>31)&1)|(sgx&(!sgy));
return ((!sgx)&sgy)|((!sgc)&(!(!(x^y))));
}
/*
* zeroByte - return 1 if one of four bytes of x is zero, and 0 otherwise
* Example: zeroByte(0xFF00EEDD) = 1, zeroByte(-0x12345678) = 0
* Legal ops: ~ & ! | + << >>
* Max ops: 24
* Rating: 3
*/
int zeroByte(int x) {
return (!(x&0xFF))|(!((x>>8)&0xFF))|(!((x>>16)&0xFF))|(!((x>>24)&0xFF));
}
/*
* modThree - calculate x mod 3 without using %.
* Example: modThree(12) = 0,
* modThree(2147483647) = 1,
* modThree(-8) = -2,
* Legal ops: ~ ! | ^ & << >> +
* Max ops: 60
* Rating: 4
*/
int modThree(int x) {
/* int sg=x>>31;
int x0=((~sg)&x)|(sg&(~x+1));
int j=(!(x0|0))&(!(!x));
int x1=(x0>>16)+(x0&(~((~0)<<16)));
int x2=((x1>>8)&0xFF)+(x1&0xFF)+(x1>>16);
int x3=((x2>>4)&0xF)+(x2&0xF)+(x2>>8);
int x4=((x3>>2)&3)+(x3&3)+(x3>>4);
int x5=(x4&3)+(x4>>2);
int d=(((x5>>1)&((~x5)&1))<<1)|((x5&1)&(!(x5>>1)));
d=(((d>>1)|j)<<1)|(d&(!j));
d=((~sg)&d)|(sg&(~d+1));
return d;*/
int sg=x>>31;
int x0=((~sg)&x)|(sg&(~x+1));
//int j=(!((~x+1)^x))&(!(!x));
int x1=((x0>>24)&0xFF)+((x0>>16)&0xFF)+((x0>>8)&0xFF)+(x0&0xFF);
int x2=(x1&3)+((x1>>2)&3)+((x1>>4)&3)+((x1>>6)&3)+((x1>>8)&3);
int x3=(x2&3)+((x2>>2)&3);
int x4=(x3&3)+((x3>>2)&3);
int d=(((x4>>1)&((~x4)&1))<<1)|((x4&1)&(!(x4>>1)));
//d=(((d>>1)|j)<<1)|(d&(!j));
d=((~sg)&d)|(sg&(~d+1));
return d;
}
/* howManyBits - return the minimum number of bits required to represent x in
* two's complement
* Examples: howManyBits(12) = 5
* howManyBits(298) = 10
* howManyBits(-5) = 4
* howManyBits(0) = 1
* howManyBits(-1) = 1
* howManyBits(0x80000000) = 32
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 90
* Rating: 4
*/
int howManyBits(int x) {
/* int sg=(x>>31)&1,wh=0;
int re1,re2,re3,re4, re5,j1,x1,x2,x3,x4,x5,k1,k2,k3,k4;
int ws1,ws2,ws3,ws4,ws5,judge,judge0;
ws1=(x&(~((sg<<31)>>31)))|((~x+1)&((sg<<31)>>31));
judge0=(((!!x)<<31)>>31);
judge=((!((~x+1)^x)<<31)>>31)&judge0;
ws1=(ws1&(~judge))|(judge&(~(1<<31)));
j1=(0xFF<<8)|(0xFF);//0xFFFF
x1=ws1>>16;
re1=!!((x1&j1)^0);
wh+=(re1<<4);
k1=((re1<<31)>>31),ws2=(k1&x1)|((~k1)&ws1);
x2=ws2>>8;
re2=!!((x2&0xFF)^0);
wh+=(re2<<3);
k2=((re2<<31)>>31),ws3=(k2&x2)|((~k2)&ws2);
x3=ws3>>4;
re3=!!((x3&0xF)^0);
wh+=(re3<<2);
k3=((re3<<31)>>31),ws4=(k3&x3)|((~k3)&ws3);
x4=ws4>>2;
re4=!!((x4&3)^0);
wh+=(re4<<1);
k4=((re4<<31)>>31),ws5=(k4&x4)|((~k4)&ws4);
x5=ws5>>1;
re5=((x5&1)^0);
re5=!!(ws5&2)
wh=wh+1+re5;
return wh+(1&judge0&(!!(~x)));*/
int sg=x>>31,wh=0;
int c=(~((~0)<<16));
int re1,re2,re3,re4,re5,x1,x2,x3,x4;
int ws1,ws2,ws3,ws4,ws5;
ws1=(x&(~sg))|((~(x+1)+1)&sg);
ws1<<=1;
x1=(ws1>>16);
re1=!!(x1&c);wh+=(re1<<4);
re1=((re1<<31)>>31);
ws2=(re1&x1)|((~re1)&(ws1&c));
x2=(ws2>>8);
re2=!!(x2&0xFF);wh+=(re2<<3);
re2=((re2<<31)>>31);
ws3=(re2&x2)|((~re2)&(ws2&0xFF));
x3=(ws3>>4);
re3=!!(x3&0xF);wh+=(re3<<2);
re3=((re3<<31)>>31);
ws4=(re3&x3)|((~re3)&(ws3&0xF));
x4=(ws4>>2);
re4=!!(x4&3);wh+=(re4<<1);
re4=((re4<<31)>>31);
ws5=(re4&x4)|((~re4)&(ws4&3));
re5=!!(ws5&2);
wh+=re5;
return wh+1;
}
/*
* float_half - Return bit-level equivalent of expression 0.5*f for
* floating point argument f.
* Both the argument and result are passed as unsigned int's, but
* they are to be interpreted as the bit-level representation of
* single-precision floating point values.
* When argument is NaN, return argument
* Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
* Max ops: 30
* Rating: 4
*/
unsigned float_half(unsigned uf) {
int sg=uf&(1<<31);
int ws=(~(1<<31))&uf;
int ex=((~0)<<23)&ws;
int fr=(~((~0)<<23))&ws;
if(ex==(0xFF<<23))return uf;
if(ex==(1<<23)||ex==0){
fr>>=1;
if((ws&3)==3)
fr+=1;
if(ex!=0)
fr+=(1<<22);
ex=0;
}
else{
ex-=(1<<23);
}
return sg|ex|fr;
}
/*
* float_negpwr2 - Return bit-level equivalent of the expression 2.0^-x
* (2.0 raised to the power -x) for any 32-bit integer x.
*
* The unsigned value that is returned should have the identical bit
* representation as the single-precision floating-point number 2.0^-x.
* If the result is too small to be represented as a denorm, return
* 0. If too large, return +INF.
*
* Legal ops: Any integer/unsigned operations incl. ||, &&. Also if, while
* Max ops: 30
* Rating: 4
*/
unsigned float_negpwr2(int x) {
if(x<-127)return ((~0)<<23)&(~(1<<31));
if(x>149)return 0;
if(x>=127&&x<=149)return 1<<(149-x);
else{
int ex=127-x;
ex&=(~((~0)<<8));
return ex<<23;
}
}
|
the_stack_data/933640.c | /* f2c.h -- Standard Fortran to C header file */
/** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed."
- From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */
#ifndef F2C_INCLUDE
#define F2C_INCLUDE
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimag(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* Table of constant values */
static doublereal c_b4 = 1.;
static doublereal c_b10 = 0.;
/* > \brief \b DTPLQT2 computes a LQ factorization of a real or complex "triangular-pentagonal" matrix, which
is composed of a triangular block and a pentagonal block, using the compact WY representation for Q.
*/
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download DTPLQT2 + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dtplqt2
.f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dtplqt2
.f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dtplqt2
.f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE DTPLQT2( M, N, L, A, LDA, B, LDB, T, LDT, INFO ) */
/* INTEGER INFO, LDA, LDB, LDT, N, M, L */
/* DOUBLE PRECISION A( LDA, * ), B( LDB, * ), T( LDT, * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > DTPLQT2 computes a LQ a factorization of a real "triangular-pentagonal" */
/* > matrix C, which is composed of a triangular block A and pentagonal block B, */
/* > using the compact WY representation for Q. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] M */
/* > \verbatim */
/* > M is INTEGER */
/* > The total number of rows of the matrix B. */
/* > M >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The number of columns of the matrix B, and the order of */
/* > the triangular matrix A. */
/* > N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] L */
/* > \verbatim */
/* > L is INTEGER */
/* > The number of rows of the lower trapezoidal part of B. */
/* > MIN(M,N) >= L >= 0. See Further Details. */
/* > \endverbatim */
/* > */
/* > \param[in,out] A */
/* > \verbatim */
/* > A is DOUBLE PRECISION array, dimension (LDA,M) */
/* > On entry, the lower triangular M-by-M matrix A. */
/* > On exit, the elements on and below the diagonal of the array */
/* > contain the lower triangular matrix L. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= f2cmax(1,M). */
/* > \endverbatim */
/* > */
/* > \param[in,out] B */
/* > \verbatim */
/* > B is DOUBLE PRECISION array, dimension (LDB,N) */
/* > On entry, the pentagonal M-by-N matrix B. The first N-L columns */
/* > are rectangular, and the last L columns are lower trapezoidal. */
/* > On exit, B contains the pentagonal matrix V. See Further Details. */
/* > \endverbatim */
/* > */
/* > \param[in] LDB */
/* > \verbatim */
/* > LDB is INTEGER */
/* > The leading dimension of the array B. LDB >= f2cmax(1,M). */
/* > \endverbatim */
/* > */
/* > \param[out] T */
/* > \verbatim */
/* > T is DOUBLE PRECISION array, dimension (LDT,M) */
/* > The N-by-N upper triangular factor T of the block reflector. */
/* > See Further Details. */
/* > \endverbatim */
/* > */
/* > \param[in] LDT */
/* > \verbatim */
/* > LDT is INTEGER */
/* > The leading dimension of the array T. LDT >= f2cmax(1,M) */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit */
/* > < 0: if INFO = -i, the i-th argument had an illegal value */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date June 2017 */
/* > \ingroup doubleOTHERcomputational */
/* > \par Further Details: */
/* ===================== */
/* > */
/* > \verbatim */
/* > */
/* > The input matrix C is a M-by-(M+N) matrix */
/* > */
/* > C = [ A ][ B ] */
/* > */
/* > */
/* > where A is an lower triangular M-by-M matrix, and B is M-by-N pentagonal */
/* > matrix consisting of a M-by-(N-L) rectangular matrix B1 left of a M-by-L */
/* > upper trapezoidal matrix B2: */
/* > */
/* > B = [ B1 ][ B2 ] */
/* > [ B1 ] <- M-by-(N-L) rectangular */
/* > [ B2 ] <- M-by-L lower trapezoidal. */
/* > */
/* > The lower trapezoidal matrix B2 consists of the first L columns of a */
/* > N-by-N lower triangular matrix, where 0 <= L <= MIN(M,N). If L=0, */
/* > B is rectangular M-by-N; if M=L=N, B is lower triangular. */
/* > */
/* > The matrix W stores the elementary reflectors H(i) in the i-th row */
/* > above the diagonal (of A) in the M-by-(M+N) input matrix C */
/* > */
/* > C = [ A ][ B ] */
/* > [ A ] <- lower triangular M-by-M */
/* > [ B ] <- M-by-N pentagonal */
/* > */
/* > so that W can be represented as */
/* > */
/* > W = [ I ][ V ] */
/* > [ I ] <- identity, M-by-M */
/* > [ V ] <- M-by-N, same form as B. */
/* > */
/* > Thus, all of information needed for W is contained on exit in B, which */
/* > we call V above. Note that V has the same form as B; that is, */
/* > */
/* > W = [ V1 ][ V2 ] */
/* > [ V1 ] <- M-by-(N-L) rectangular */
/* > [ V2 ] <- M-by-L lower trapezoidal. */
/* > */
/* > The rows of V represent the vectors which define the H(i)'s. */
/* > The (M+N)-by-(M+N) block reflector H is then given by */
/* > */
/* > H = I - W**T * T * W */
/* > */
/* > where W^H is the conjugate transpose of W and T is the upper triangular */
/* > factor of the block reflector. */
/* > \endverbatim */
/* > */
/* ===================================================================== */
/* Subroutine */ int dtplqt2_(integer *m, integer *n, integer *l, doublereal *
a, integer *lda, doublereal *b, integer *ldb, doublereal *t, integer *
ldt, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, b_dim1, b_offset, t_dim1, t_offset, i__1, i__2,
i__3;
/* Local variables */
extern /* Subroutine */ int dger_(integer *, integer *, doublereal *,
doublereal *, integer *, doublereal *, integer *, doublereal *,
integer *);
integer i__, j, p;
doublereal alpha;
extern /* Subroutine */ int dgemv_(char *, integer *, integer *,
doublereal *, doublereal *, integer *, doublereal *, integer *,
doublereal *, doublereal *, integer *), dtrmv_(char *,
char *, char *, integer *, doublereal *, integer *, doublereal *,
integer *);
integer mp, np;
extern /* Subroutine */ int dlarfg_(integer *, doublereal *, doublereal *,
integer *, doublereal *), xerbla_(char *, integer *, ftnlen);
/* -- LAPACK computational routine (version 3.7.1) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* June 2017 */
/* ===================================================================== */
/* Test the input arguments */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
b_dim1 = *ldb;
b_offset = 1 + b_dim1 * 1;
b -= b_offset;
t_dim1 = *ldt;
t_offset = 1 + t_dim1 * 1;
t -= t_offset;
/* Function Body */
*info = 0;
if (*m < 0) {
*info = -1;
} else if (*n < 0) {
*info = -2;
} else if (*l < 0 || *l > f2cmin(*m,*n)) {
*info = -3;
} else if (*lda < f2cmax(1,*m)) {
*info = -5;
} else if (*ldb < f2cmax(1,*m)) {
*info = -7;
} else if (*ldt < f2cmax(1,*m)) {
*info = -9;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("DTPLQT2", &i__1, (ftnlen)7);
return 0;
}
/* Quick return if possible */
if (*n == 0 || *m == 0) {
return 0;
}
i__1 = *m;
for (i__ = 1; i__ <= i__1; ++i__) {
/* Generate elementary reflector H(I) to annihilate B(I,:) */
p = *n - *l + f2cmin(*l,i__);
i__2 = p + 1;
dlarfg_(&i__2, &a[i__ + i__ * a_dim1], &b[i__ + b_dim1], ldb, &t[i__ *
t_dim1 + 1]);
if (i__ < *m) {
/* W(M-I:1) := C(I+1:M,I:N) * C(I,I:N) [use W = T(M,:)] */
i__2 = *m - i__;
for (j = 1; j <= i__2; ++j) {
t[*m + j * t_dim1] = a[i__ + j + i__ * a_dim1];
}
i__2 = *m - i__;
dgemv_("N", &i__2, &p, &c_b4, &b[i__ + 1 + b_dim1], ldb, &b[i__ +
b_dim1], ldb, &c_b4, &t[*m + t_dim1], ldt);
/* C(I+1:M,I:N) = C(I+1:M,I:N) + alpha * C(I,I:N)*W(M-1:1)^H */
alpha = -t[i__ * t_dim1 + 1];
i__2 = *m - i__;
for (j = 1; j <= i__2; ++j) {
a[i__ + j + i__ * a_dim1] += alpha * t[*m + j * t_dim1];
}
i__2 = *m - i__;
dger_(&i__2, &p, &alpha, &t[*m + t_dim1], ldt, &b[i__ + b_dim1],
ldb, &b[i__ + 1 + b_dim1], ldb);
}
}
i__1 = *m;
for (i__ = 2; i__ <= i__1; ++i__) {
/* T(I,1:I-1) := C(I:I-1,1:N) * (alpha * C(I,I:N)^H) */
alpha = -t[i__ * t_dim1 + 1];
i__2 = i__ - 1;
for (j = 1; j <= i__2; ++j) {
t[i__ + j * t_dim1] = 0.;
}
/* Computing MIN */
i__2 = i__ - 1;
p = f2cmin(i__2,*l);
/* Computing MIN */
i__2 = *n - *l + 1;
np = f2cmin(i__2,*n);
/* Computing MIN */
i__2 = p + 1;
mp = f2cmin(i__2,*m);
/* Triangular part of B2 */
i__2 = p;
for (j = 1; j <= i__2; ++j) {
t[i__ + j * t_dim1] = alpha * b[i__ + (*n - *l + j) * b_dim1];
}
dtrmv_("L", "N", "N", &p, &b[np * b_dim1 + 1], ldb, &t[i__ + t_dim1],
ldt);
/* Rectangular part of B2 */
i__2 = i__ - 1 - p;
dgemv_("N", &i__2, l, &alpha, &b[mp + np * b_dim1], ldb, &b[i__ + np *
b_dim1], ldb, &c_b10, &t[i__ + mp * t_dim1], ldt);
/* B1 */
i__2 = i__ - 1;
i__3 = *n - *l;
dgemv_("N", &i__2, &i__3, &alpha, &b[b_offset], ldb, &b[i__ + b_dim1],
ldb, &c_b4, &t[i__ + t_dim1], ldt);
/* T(1:I-1,I) := T(1:I-1,1:I-1) * T(I,1:I-1) */
i__2 = i__ - 1;
dtrmv_("L", "T", "N", &i__2, &t[t_offset], ldt, &t[i__ + t_dim1], ldt);
/* T(I,I) = tau(I) */
t[i__ + i__ * t_dim1] = t[i__ * t_dim1 + 1];
t[i__ * t_dim1 + 1] = 0.;
}
i__1 = *m;
for (i__ = 1; i__ <= i__1; ++i__) {
i__2 = *m;
for (j = i__ + 1; j <= i__2; ++j) {
t[i__ + j * t_dim1] = t[j + i__ * t_dim1];
t[j + i__ * t_dim1] = 0.;
}
}
/* End of DTPLQT2 */
return 0;
} /* dtplqt2_ */
|
the_stack_data/27358.c | #include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
// #include <linux/msg.h>
#include <assert.h>
struct mymsgbuf {
long mtype; /* Message type */
int some1;
double some2;
} msg;
int get_qid(void);
int open_queue(key_t keyval);
int remove_queue(int qid);
int send_message(int qid, struct mymsgbuf *qbuf);
int read_message(int qid, long type, struct mymsgbuf *qbuf);
int get_queue_ds(int qid, struct msqid_ds *qbuf);
#define check_error(val, msg) \
do { \
if ((val) == -1) { \
perror((msg)); \
abort(); \
} \
} while (0);
int main() {
int qid = get_qid();
/* Load up the message with arbitrary test data */
msg.mtype = 9; /* Message type must be a positive number! */
msg.some1 = 99;
msg.some2 = 999.0;
check_error(send_message(qid, &msg), "send message");
msg.mtype = 0;
msg.some1 = 0;
msg.some2 = 0;
check_error(read_message(qid, 9, &msg), "read message");
assert(msg.mtype == 9);
assert(msg.some1 == 99);
assert(msg.some2 == 999.0);
struct msqid_ds mqs;
check_error(get_queue_ds(qid, &mqs), "Read msqid_ds");
check_error(remove_queue(qid), "remove queue");
return EXIT_SUCCESS;
}
int get_qid(void) {
int qid;
key_t msgkey;
/* Generate our IPC key value */
msgkey = ftok(".", 'm');
check_error(msgkey, "Generate our IPC key");
/* Open/create the queue */
qid = open_queue(msgkey);
check_error(qid, "Open/create the queue");
return qid;
}
int open_queue(key_t keyval) {
return msgget(keyval, IPC_CREAT | IPC_EXCL | 0660); //
}
int remove_queue(int qid) {
return msgctl(qid, IPC_RMID, NULL);
}
int send_message(int qid, struct mymsgbuf *qbuf) {
int length = sizeof(struct mymsgbuf) - sizeof(long);
return msgsnd(qid, qbuf, length, 0);
}
int read_message(int qid, long type, struct mymsgbuf *qbuf) {
int length = sizeof(struct mymsgbuf) - sizeof(long);
return msgrcv(qid, qbuf, length, type, 0);
}
int peek_message(int qid, long type) {
if (msgrcv(qid, NULL, 0, type, IPC_NOWAIT) == -1) {
return errno == E2BIG;
}
return 0;
}
int get_queue_ds(int qid, struct msqid_ds *qbuf) {
return msgctl(qid, IPC_STAT, qbuf);
}
|
the_stack_data/914106.c | // gcc barrier.c -o barrier -pthread
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <semaphore.h>
#include <pthread.h>
#include <string.h>
sem_t sem; // pentru a astepta la bariera
pthread_mutex_t mtx; // pentru contorizarea firelor ajunse la bariera
int procese ; // numarul de procese
void barrier_point()
{
static int vizitate = 0; // procesele care au vizitat deja bariera
pthread_mutex_lock( &mtx ); // blochez mutexul pentru a lucra cu nr de procese
vizitate ++;
pthread_mutex_unlock( &mtx ); // deblockez mutexul
if (procese == vizitate) // au trecut toate procesele
{
sem_post(&sem); // verifica daca sunt thread-uri blocate la semafor
// eliberandu-l pe cel care asteapta de cel mai mult timp
return;
}
sem_wait( &sem );
//scade valoarea cu o unitate; daca este 0, asteapta sa fie mai intai incrementata
sem_post( &sem ); // am iesit din semafor
// creste valoarea cu 1 si verifica daca sunt thread-uri blocate la semafor
// eliberandu-l pe cel care asteapta de cel mai mult timp
}
void *tfun (void *v) //functia executata de fiecare fir
{
int *tid = (int *) v; // tid este numarul threadului pornit
printf("%d reached the barrier \n",*tid);
barrier_point();
printf("%d passed the barrier \n", *tid);
free(tid);
return NULL;
}
int main()
{
sem_init(&sem, 0, 0); // creez semaforul, iar initial va avea valoarea 0
if( pthread_mutex_init( &mtx, NULL) ) // creez mutex-ul
{
perror("Eroare -> Creare Mutex.\n");
return errno ;
}
printf("Nr procese: \n $ ");
scanf("%d", &procese);
pthread_t* threads = malloc(sizeof(threads) * procese);
for(int i = 0; i < procese; i++)
{
int* add = malloc(sizeof add);
*add = i;
if( pthread_create( threads + i, NULL, tfun, add ) )//se creaza un thread nou
//initializeaza thread-ul cu noul fir de executie lansat de functia tfun oferind argumentul add
{
perror("Eroare -> Nu s-a putut crea thread-ul.\n");
return errno;
}
}
for(int i = 0; i < procese; i++)
{
if( pthread_join( threads[i], NULL ) ) // asteapta finalizarea executiei unui thread
{
perror("Eroare.\n");
return errno;
}
}
sem_destroy(&sem); //eliberez resursele ocupate
pthread_mutex_destroy( &mtx ); // distrug mutexul
free(threads); // eliberez memorie
return 0;
}
|
the_stack_data/153269150.c | #include <stdbool.h>
bool areAlmostEqual(const char* s1, const char* s2){
char a, b;
int diff = 0;
while (*s1 != '\0') {
if (*s1 != *s2) {
if (diff) {
if (a != *s2 || b != *s1)
return false;
}
if (!diff) {
a = *s1;
b = *s2;
}
diff++;
if (diff > 2) return false;
}
s1++;
s2++;
}
if (diff == 0) return true;
if (diff == 1) return false;
return true;
}
|
the_stack_data/248580427.c | /*
* This file and its contents are supplied under the terms of the
* Common Development and Distribution License ("CDDL"), version 1.0.
* You may only use this file in accordance with the terms of version
* 1.0 of the CDDL.
*
* A full copy of the text of the CDDL should have accompanied this
* source. A copy of the CDDL is also available via the Internet at
* http://www.illumos.org/license/CDDL.
*/
/*
* Copyright 2012, Richard Lowe.
*/
#include <stdio.h>
#include <unistd.h>
struct foo {
long a;
long b;
long c;
};
struct foo
test(long a, long b, long c, long d, long e, long f, long g, long h)
{
printf("%ld %ld %ld %ld %ld %ld %ld %ld\n", a, b, c, d, e, f, g, h);
for (;;)
sleep(60);
}
int
main(int argc, char **argv)
{
test(1, 2, 3, 4, 5, 6, 7, 8);
return (0);
}
|
the_stack_data/175142859.c | /* Copyright (c) (2015,2016,2017,2018,2019) Apple Inc. All rights reserved.
*
* corecrypto is licensed under Apple Inc.’s Internal Use License Agreement (which
* is contained in the License.txt file distributed with corecrypto) and only to
* people who accept that license. IMPORTANT: Any license rights granted to you by
* Apple Inc. (if any) are limited to internal use within your organization only on
* devices and computers you own or control, for the sole purpose of verifying the
* security characteristics and correct functioning of the Apple Software. You may
* not, directly or indirectly, redistribute the Apple Software or any portions thereof.
*/
|
the_stack_data/117328715.c | #include <limits.h>
int main(void)
{
return -(INT_MIN);
}
|
the_stack_data/165768222.c | #include <stdio.h>
int check_key(int key) {
if (((key-100)*2)%100 == 0) {
return 1;
return 0;
}
}
int main() {
int key,return_value;
printf("Enter Key: ");
scanf("%d",&key);
return_value = check_key(key);
if (return_value == 1) {
puts("Correct Key! Now Keygen Me.");
}
else {
puts("Wrong Key!");
}
}
|
the_stack_data/26701266.c | /* C Library for Skeleton 2-1/2D Darwin MPI PIC Code field */
/* diagnostics */
/* Wrappers for calling the Fortran routines from a C main program */
#include <complex.h>
void ppotp2_(float complex *q, float complex *pot, float complex *ffc,
float *we, int *nx, int *ny, int *kstrt, int *nyv,
int *kxp, int *nyhd);
void ppdivf2_(float complex *f, float complex *df, int *nx, int *ny,
int *kstrt, int *ndim, int *nyv, int *kxp);
void ppgradf2_(float complex *df, float complex *f, int *nx, int *ny,
int *kstrt, int *ndim, int *nyv, int *kxp);
void ppcurlf2_(float complex *f, float complex *g, int *nx, int *ny,
int *kstrt, int *nyv, int *kxp);
void ppapotp23_(float complex *cu, float complex *axy,
float complex *ffc, float *ci, float *wm, int *nx,
int *ny, int *kstrt, int *nyv, int *kxp, int *nyhd);
void ppsmooth2_(float complex *q, float complex *qs, float complex *ffc,
int *nx, int *ny, int *kstrt, int *nyv, int *kxp,
int *nyhd);
void ppsmooth23_(float complex *cu, float complex *cus,
float complex *ffc, int *nx, int *ny, int *kstrt,
int *nyv, int *kxp, int *nyhd);
void pprdmodes2_(float complex *pot, float complex *pott, int *nx,
int *ny, int *modesx, int *modesy, int *kstrt,
int *nyv, int *kxp, int *modesxpd, int *modesyd);
void ppwrmodes2_(float complex *pot, float complex *pott, int *nx,
int *ny, int *modesx, int *modesy, int *kstrt,
int *nyv, int *kxp, int *modesxpd, int *modesyd);
void pprdvmodes2_(float complex *vpot, float complex *vpott, int *nx,
int *ny, int *modesx, int *modesy, int *ndim,
int *kstrt, int *nyv, int *kxp, int *modesxpd,
int *modesyd);
void ppwrvmodes2_(float complex *vpot, float complex *vpott, int *nx,
int *ny, int *modesx, int *modesy, int *ndim,
int *kstrt, int *nyv, int *kxp, int *modesxpd,
int *modesyd);
/* Interfaces to C */
/*--------------------------------------------------------------------*/
void cppotp2(float complex q[], float complex pot[],
float complex ffc[], float *we, int nx, int ny, int kstrt,
int nyv, int kxp, int nyhd) {
ppotp2_(q,pot,ffc,we,&nx,&ny,&kstrt,&nyv,&kxp,&nyhd);
return;
}
/*--------------------------------------------------------------------*/
void cppdivf2(float complex f[], float complex df[], int nx, int ny,
int kstrt, int ndim, int nyv, int kxp) {
ppdivf2_(f,df,&nx,&ny,&kstrt,&ndim,&nyv,&kxp);
return;
}
/*--------------------------------------------------------------------*/
void cppgradf2(float complex df[], float complex f[], int nx, int ny,
int kstrt, int ndim, int nyv, int kxp) {
ppgradf2_(df,f,&nx,&ny,&kstrt,&ndim,&nyv,&kxp);
return;
}
/*--------------------------------------------------------------------*/
void cppcurlf2(float complex f[], float complex g[], int nx, int ny,
int kstrt, int nyv, int kxp) {
ppcurlf2_(f,g,&nx,&ny,&kstrt,&nyv,&kxp);
return;
}
/*--------------------------------------------------------------------*/
void cppapotp23(float complex cu[], float complex axy[],
float complex ffc[], float ci, float *wm, int nx,
int ny, int kstrt, int nyv, int kxp, int nyhd) {
ppapotp23_(cu,axy,ffc,&ci,wm,&nx,&ny,&kstrt,&nyv,&kxp,&nyhd);
return;
}
/*--------------------------------------------------------------------*/
void cppsmooth2(float complex q[], float complex qs[],
float complex ffc[], int nx, int ny, int kstrt, int nyv,
int kxp, int nyhd) {
ppsmooth2_(q,qs,ffc,&nx,&ny,&kstrt,&nyv,&kxp, &nyhd);
return;
}
/*--------------------------------------------------------------------*/
void cppsmooth23(float complex cu[], float complex cus[],
float complex ffc[], int nx, int ny, int kstrt,
int nyv, int kxp, int nyhd) {
ppsmooth23_(cu,cus,ffc,&nx,&ny,&kstrt,&nyv,&kxp,&nyhd);
return;
}
/*--------------------------------------------------------------------*/
void cpprdmodes2(float complex pot[], float complex pott[], int nx,
int ny, int modesx, int modesy, int kstrt, int nyv,
int kxp, int modesxpd, int modesyd) {
pprdmodes2_(pot,pott,&nx,&ny,&modesx,&modesy,&kstrt,&nyv,&kxp,
&modesxpd,&modesyd);
return;
}
/*--------------------------------------------------------------------*/
void cppwrmodes2(float complex pot[], float complex pott[], int nx,
int ny, int modesx, int modesy, int kstrt, int nyv,
int kxp, int modesxpd, int modesyd) {
ppwrmodes2_(pot,pott,&nx,&ny,&modesx,&modesy,&kstrt,&nyv,&kxp,
&modesxpd,&modesyd);
return;
}
/*--------------------------------------------------------------------*/
void cpprdvmodes2(float complex vpot[], float complex vpott[], int nx,
int ny, int modesx, int modesy, int ndim, int kstrt,
int nyv, int kxp, int modesxpd, int modesyd) {
pprdvmodes2_(vpot,vpott,&nx,&ny,&modesx,&modesy,&ndim,&kstrt,&nyv,
&kxp,&modesxpd,&modesyd);
return;
}
/*--------------------------------------------------------------------*/
void cppwrvmodes2(float complex vpot[], float complex vpott[], int nx,
int ny, int modesx, int modesy, int ndim, int kstrt,
int nyv, int kxp, int modesxpd, int modesyd) {
ppwrvmodes2_(vpot,vpott,&nx,&ny,&modesx,&modesy,&ndim,&kstrt,&nyv,
&kxp,&modesxpd,&modesyd);
return;
}
|
the_stack_data/61076587.c | /*
* Date: 2014-06-08
* Author: [email protected]
*
*
* This is Example 3.3 from the test suit used in
*
* Termination Proofs for Linear Simple Loops.
* Hong Yi Chen, Shaked Flur, and Supratik Mukhopadhyay.
* SAS 2012.
*
* The test suite is available at the following URL.
* https://tigerbytes2.lsu.edu/users/hchen11/lsl/LSL_benchmark.txt
*
* Comment: terminating, non-linear
*/
typedef enum {false, true} bool;
extern int __VERIFIER_nondet_int(void);
int main() {
int x, y, z;
x = __VERIFIER_nondet_int();
y = __VERIFIER_nondet_int();
z = __VERIFIER_nondet_int();
while (x > 0) {
x = x + y;
y = y + z;
z = z - 1;
}
return 0;
}
|
the_stack_data/765248.c | #include <stdio.h>
float mid_num_string();
int main(){
//Applying function
printf("La media e': %G",mid_num_string());
}
float mid_num_string(){
int sum = 0;
int cont = 0;
int n;
printf("Inserire la stringa di cifre: ");
while(scanf("%d",&n) && n>0){
sum += n;
cont++;
}
return (float) sum/cont;
} |
the_stack_data/67324594.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct {
float x;
float y;
float z;
} point;
void pointPrintPoint(point p) {
printf("Point has coordinates (%f, %f, %f) \n", p.x, p.y, p.z);
}
void pointSetZero(point *p) {
//(*p).x = 0.;
//(*p).y = 0.;
//(*p).z = 0.;
//also valid
//point pp = *p;
//pp.x = 0.;
//pp.y = 0.;
//pp.z = 0.;
//and so is this
p->x = 0.;
p->y = 0.;
p->z = 0.;
}
float pointDistanceToOrigin(point p) {
float dist = sqrt(p.x * p.x + p.y * p.y + p.z * p.z);
return dist;
}
void main() {
point p;
//access variables in structure with '.'
p.x = 1.0;
p.y = 2.0;
p.z = 3.0;
float dist;
dist = pointDistanceToOrigin(p);
printf("dist = %f\n", dist);
pointSetZero(&p);
pointPrintPoint(p);
}
|
the_stack_data/784486.c |
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if.h>
#include <linux/atm.h>
int main (void) { return 0; }
|
the_stack_data/304022.c | #include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define size 1000
int main(){
time_t now;
time(&now);
struct tm mbeg;
mbeg = *localtime(&now);
mbeg.tm_hour = 0;
mbeg.tm_min = 0;
mbeg.tm_sec = 0;
mbeg.tm_mday = 1;
double dff = difftime(now,mktime(&mbeg))/3600;
printf("%f hours\n",dff);
return 0;
}
|
the_stack_data/144270.c | #include <stdio.h>
int main(void)
{
// A no. is said to be palindrome if the number when reversed equals to the same no. eg: 121*
int n, reversedInteger = 0, remainder, originalInteger;
printf("Enter an integer: ");
scanf("%d", &n);
originalInteger = n;
// reversed integer is stored in variable
while(n != 0)
{
remainder = n % 10;
reversedInteger = reversedInteger * 10 + remainder;
n /= 10;
}
// palindrome if orignalInteger and reversedInteger are equal
if(originalInteger == reversedInteger)
printf("%d is a palindrome.", originalInteger);
else
printf("%d is not a palindrome.", originalInteger);
printf("\n");
return 0;
}
|
the_stack_data/68889189.c | #include "syscall.h"
int factorial(int n){
if (n == 1) {
return 1;
} else {
int step = factorial(n-1);
return (n * step);
}
}
int main() {
int res = factorial(5);
PutString(" *Début du processus factorielle*\n");
PutString(" *");
PutInt(res);
PutString("*");
PutChar('\n');
PutString(" *Fin du processus factorielle*\n");
return 0;
}
|
the_stack_data/156393687.c | /* { dg-do compile } */
/* { dg-options "-O2 --param tree-reassoc-width=2 -fdump-tree-reassoc1" } */
unsigned int
foo (void)
{
unsigned int a = 0;
unsigned int b;
asm volatile ("" : "=r" (b) : "0" (0));
a += b;
asm volatile ("" : "=r" (b) : "0" (0));
a += b;
asm volatile ("" : "=r" (b) : "0" (0));
a += b;
asm volatile ("" : "=r" (b) : "0" (0));
a += b;
return a;
}
/* Verify there are two pairs of __asm__ statements with no
intervening stmts. */
/* { dg-final { scan-tree-dump-times "__asm__\[^;\n]*;\n *__asm__" 2 "reassoc1"} } */
|
the_stack_data/218894057.c | #include <assert.h>
#include <stdio.h>
#include <stdint.h>
#define SIMD_ALIGN __attribute__((aligned(16)))
#define MAX_INT 2147483647
uint32_t powers_a[4] SIMD_ALIGN = {
9,
99,
999,
9999
};
uint32_t powers_b[4] SIMD_ALIGN = {
99999,
999999,
9999999,
99999999
};
uint32_t powers_c[4] SIMD_ALIGN = {
999999999,
MAX_INT,
MAX_INT,
MAX_INT,
};
int decimal_digits_sse(const int x) {
assert(x >= 0);
uint32_t result;
__asm__ volatile(
"movd %%eax, %%xmm0 \n" // xmm0 = [x, 0, 0, 0]
"pshufd $0, %%xmm0, %%xmm0 \n" // xmm0 = [x, x, x, x]
"movapd %%xmm0, %%xmm1 \n"
"movapd %%xmm0, %%xmm2 \n"
"pcmpgtd powers_a, %%xmm0 \n" // xmm0 = [x > 10^1 - 1, x > 10^2 - 1, x > 10^3 - 1, x > 10^4 - 1]
"pcmpgtd powers_b, %%xmm1 \n" // xmm1 = [x > 10^5 - 1, x > 10^6 - 1, x > 10^7 - 1, x > 10^8 - 1]
"pcmpgtd powers_c, %%xmm2 \n" // xmm2 = [x > 10^9 - 1, 0 , 0 , 0 ]
// result of comparisons are: 0 (false) or -1 (true)
// for example:
// xmm0 = packed_dword(-1, -1, -1, -1)
// xmm1 = packed_dword( 0, 0, -1, -1)
// xmm2 = packed_dword( 0, 0, 0, 0)
"psrld $31, %%xmm0 \n" // xmm0 = packed_dword( 1, 1, 1, 1)
"psubd %%xmm1, %%xmm0 \n" // xmm0 = packed_dword( 1, 1, 2, 2)
"psubd %%xmm2, %%xmm0 \n" // xmm0 = packed_dword( 1, 1, 2, 2) -- no change
"pxor %%xmm1, %%xmm1 \n" // convert packed_dword to packed_word
"packssdw %%xmm1, %%xmm0 \n" // xmm0 = packed_word(0, 0, 0, 0, 1, 1, 2, 2)
// max value of word in xmm0 is 3, so higher
// bytes are always zero
"psadbw %%xmm1, %%xmm0 \n" // xmm0 = packded_qword(0, 6)
"movd %%xmm0, %%eax \n" // eax = 6
: "=a" (result)
: "a" (x)
);
return result + 1;
}
|
the_stack_data/179831306.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
#include <stdlib.h>
extern int __VERIFIER_nondet_int(void);
static void fail(void) {
ERROR: __VERIFIER_error();
}
#define ___SL_ASSERT(cond) do { \
if (!(cond)) \
fail(); \
} while (0)
#ifndef PREDATOR
# define ___sl_plot(...) do { } while (0)
#endif
struct node {
struct node *next;
struct node *prev;
};
static struct node* alloc_node(void)
{
struct node *ptr = malloc(sizeof *ptr);
if (!ptr)
abort();
ptr->next = NULL;
ptr->prev = NULL;
return ptr;
}
static void chain_node(struct node **ppnode)
{
struct node *node = alloc_node();
node->next = *ppnode;
*ppnode = node;
}
static struct node* create_sll(const struct node **pp1, const struct node **pp2)
{
struct node *list = NULL;
do
chain_node(&list);
while (__VERIFIER_nondet_int());
*pp2 = list;
do
chain_node(&list);
while (__VERIFIER_nondet_int());
*pp1 = list;
do
chain_node(&list);
while (__VERIFIER_nondet_int());
return list;
}
void init_back_link(struct node *list) {
for (;;) {
struct node *next = list->next;
if (!next)
return;
next->prev = list;
list = next;
}
}
void reverse_dll(struct node *list) {
while (list) {
struct node *next = list->next;
list->next = list->prev;
list->prev = next;
list = next;
}
}
void remove_fw_link(struct node *list) {
while (list) {
struct node *next = list->next;
list->next = NULL;
list = next;
}
}
void check_seq_next(const struct node *beg, const struct node *const end) {
___SL_ASSERT(beg);
___SL_ASSERT(end);
for (beg = beg->next; end != beg; beg = beg->next)
___SL_ASSERT(beg);
}
void check_seq_prev(const struct node *beg, const struct node *const end) {
___SL_ASSERT(beg);
___SL_ASSERT(end);
for (beg = beg->prev; end != beg; beg = beg->prev)
___SL_ASSERT(beg);
}
int main()
{
const struct node *p1, *p2;
struct node *list = create_sll(&p1, &p2);
___sl_plot(NULL, &list, &p1, &p2);
check_seq_next(p1, p2);
___SL_ASSERT(!p1->prev);
___SL_ASSERT(!p2->prev);
init_back_link(list);
___sl_plot(NULL, &list, &p1, &p2);
check_seq_next(p1, p2);
check_seq_prev(p2, p1);
reverse_dll(list);
___sl_plot(NULL, &list, &p1, &p2);
check_seq_prev(p1, p2);
check_seq_next(p2, p1);
remove_fw_link(list);
___sl_plot(NULL, &list, &p1, &p2);
check_seq_prev(p1, p2);
while (list) {
struct node *prev = list->prev;
free(list);
list = prev;
}
return 0;
}
|
the_stack_data/75243.c | #include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[])
{
int m,n,x=1,y=1,i;
scanf("%d%d",&m,&n);
for(i=m;i>m-n;i--)
x=x*i;
for(i=1;i<=n;i++)
y=y*i;
printf("%d",x/y);
return 0;
} |
the_stack_data/52505.c | #include <stdio.h>
enum opcao{soma=1, subtracao=2, divisao=3, multiplicacao=4};
int main(){
enum opcao op;
op= soma;
printf("%s", op);
return 0;
} |
the_stack_data/6388952.c | #include <stdio.h>
/* qsort: sort v[left] ... v[right] into increasing order */
void swap(int v[], int i, int j) {
int tmp = v[i];
v[i] = v[j];
v[j] = tmp;
}
int partition(int v[], int left, int right) {
int pivot = right;
int i = left;
int j;
for (j = i; j < right; j++) {
if (v[j] < v[pivot]) {
swap(v, i++, j);
}
}
swap(v, i, pivot);
return i;
}
void qsort(int v[], int left, int right) {
int p;
if (left < right) {
p = partition(v, left, right);
qsort(v, left, p - 1);
qsort(v, p + 1, right);
}
}
int main() {
int arr[] = {1, 5, 2, 9, 14, 33, 0, 1, 24, 58, 3, 4, 18, 9, 0, 1, 0};
int len = sizeof(arr) / sizeof(*arr);
qsort(arr, 0, len - 1);
for(int i = 0; i < len; i++)
printf("%d ", arr[i]);
printf("\n");
}
|
the_stack_data/1204888.c | #include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<pthread.h>
#include<unistd.h>
#include<semaphore.h>
#define SIZE 3
sem_t full,empty,mutex;
int data[SIZE];
#define TIMES 5
void* producer(void* arg){
int outVar;
for(int i=0;i<TIMES;i++){
sem_wait(&empty);
sem_wait(&mutex);
sem_getvalue(&full,&outVar);
*(data+outVar) = random()%20;
printf("I: %d\n",data[outVar]);
//scanf("%d",data +outVar);
sem_post(&mutex);
sem_post(&full);
}
return NULL;
}
void* consumer(void* arg){
int outVar;
for(int i=0;i<TIMES;i++){
sem_wait(&full);
sem_wait(&mutex);
sem_getvalue(&full,&outVar);
printf("P: %d\n",data[outVar]);
sem_post(&mutex);
sem_post(&empty);
}
return NULL;
}
int main(){
pthread_t producer_t,consumer_t;
//sem_t full,empty,mutex;
sem_init(&full,0,0);
sem_init(&empty,0,SIZE-1);
sem_init(&mutex,0,1);
pthread_create(&producer_t,NULL,producer,NULL);
pthread_create(&consumer_t,NULL,consumer,NULL);
pthread_join(producer_t,NULL);
pthread_join(consumer_t,NULL);
return 0;
}
|
the_stack_data/68888201.c | // Copyright 2020 Lassi Kortela
// SPDX-License-Identifier: ISC
#ifdef _WIN32
#define UNISIG_WINDOWS
#else
#define UNISIG_UNIX
#endif
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef UNISIG_WINDOWS
#include <fcntl.h>
#include <io.h>
#endif
#ifdef UNISIG_UNIX
#include <unistd.h>
#endif
#ifdef __BORLANDC__
#define _setmode setmode
#endif
#ifndef PROGNAME
#define PROGNAME "unisig"
#endif
#ifndef PROGVERSION
#define PROGVERSION "0.1.0"
#endif
static unsigned char buffer[4096];
static const char *binary_input_name;
static const char *binary_output_name;
static FILE *binary_input;
static FILE *binary_output;
static const unsigned char magic[7]
= { 0xDC, 0xDC, 0x0D, 0x0A, 0x1A, 0x0A, 0x00 };
static unsigned char *const head = buffer;
static unsigned char *const tail = head + sizeof(magic) + 1;
static const char *oflag;
static void generic_usage(FILE *stream, int status);
static unsigned int gettaillen(void) { return head[sizeof(magic)]; }
static int is_uuid(void) { return gettaillen() == 0; }
static void panic(const char *msg)
{
fprintf(stderr, "%s: %s\n", PROGNAME, msg);
exit(2);
}
static void panic_s(const char *msg, const char *s)
{
fprintf(stderr, "%s: %s%s\n", PROGNAME, msg, s);
exit(2);
}
#ifdef UNISIG_WINDOWS
static void binary_stdin(void) { _setmode(_fileno(stdin), _O_BINARY); }
#endif
#ifdef UNISIG_WINDOWS
static void binary_stdout(void) { _setmode(_fileno(stdout), _O_BINARY); }
#endif
#ifdef UNISIG_UNIX
static void binary_stdin(void)
{
if (isatty(STDIN_FILENO)) {
panic("cannot read binary data from terminal");
}
}
#endif
#ifdef UNISIG_UNIX
static void binary_stdout(void)
{
if (isatty(STDOUT_FILENO)) {
panic("cannot write binary data to terminal");
}
}
#endif
static void binary_input_file_close(void)
{
if (fclose(binary_input) == EOF) {
panic("cannot close file");
}
binary_input_name = 0;
binary_input = 0;
}
static void binary_output_file_close(void)
{
if (fclose(binary_output) == EOF) {
panic("cannot close file");
}
binary_output_name = 0;
binary_output = 0;
}
static void binary_input_std(void)
{
binary_input_name = "<stdin>";
binary_input = stdin;
binary_stdin();
}
static void binary_output_std(void)
{
binary_output_name = "<stdout>";
binary_output = stdout;
binary_stdout();
}
static void binary_input_file_open(const char *filename)
{
binary_input_name = filename;
if (!(binary_input = fopen(filename, "rb"))) {
panic_s("cannot open ", filename);
}
}
static void binary_output_file_open(const char *filename)
{
binary_output_name = filename;
if (!(binary_output = fopen(filename, "wb"))) {
panic_s("cannot open ", filename);
}
}
static size_t binary_input_at_most_n_bytes(void *bytes, size_t nbyte)
{
size_t nread;
nread = fread(bytes, 1, nbyte, binary_input);
if (ferror(binary_input)) {
panic("cannot read from");
}
return nread;
}
static void binary_input_exactly_n_bytes(void *bytes, size_t nbyte)
{
if (binary_input_at_most_n_bytes(bytes, nbyte) != nbyte) {
panic("cannot read enough data");
}
}
static void output_exactly_n_bytes(const void *bytes, size_t nbyte)
{
if (fwrite(bytes, 1, nbyte, binary_output) != nbyte) {
panic("cannot write");
}
if (ferror(binary_output)) {
panic("cannot write to");
}
}
static void binary_input_random(void *bytes, size_t nbyte)
{
binary_input_file_open("/dev/random");
binary_input_exactly_n_bytes(bytes, nbyte);
binary_input_file_close();
}
static unsigned int parse_hex_digit(int ch)
{
const char digits[] = "0123456789abcdef";
const char *digitp;
if (!(digitp = strchr(digits, tolower(ch))))
return (unsigned int)-1;
return (unsigned int)(digitp - digits);
}
static int parse_hex_bytes(
const char **hexp, unsigned char **bytesp, size_t nbyte, int nextch)
{
const char *hex = *hexp;
unsigned char *bytes = *bytesp;
unsigned int digit;
unsigned int byte;
for (; nbyte; nbyte--) {
byte = 0;
{
if ((digit = parse_hex_digit(*hex)) == (unsigned int)-1)
return 0;
hex++;
byte |= digit;
}
byte <<= 4;
{
if ((digit = parse_hex_digit(*hex)) == (unsigned int)-1)
return 0;
hex++;
byte |= digit;
}
*bytes++ = byte;
}
if (*hex != nextch)
return 0;
hex++;
*hexp = hex;
*bytesp = bytes;
return 1;
}
static int parse_uuid(const char *s, unsigned char outbuf[16])
{
unsigned char *out;
out = outbuf;
if (!parse_hex_bytes(&s, &out, 4, '-')) {
return 0;
}
if (!parse_hex_bytes(&s, &out, 2, '-')) {
return 0;
}
if (!parse_hex_bytes(&s, &out, 2, '-')) {
return 0;
}
if (!parse_hex_bytes(&s, &out, 2, '-')) {
return 0;
}
if (!parse_hex_bytes(&s, &out, 6, '\0')) {
return 0;
}
return 1;
}
static void uuid_patch(unsigned int version)
{
tail[6] = (tail[6] & 0x0f) | version;
tail[8] = (tail[8] & 0x3f) | 0x80;
}
static void generate_uuid_variant_1_version_four(void)
{
binary_input_random(tail, 16);
uuid_patch(0x40);
}
static int is_safe_unisig_uri_char(int ch)
{
return (((ch >= '0') && (ch <= '9')) || ((ch >= 'A') && (ch <= 'Z'))
|| ((ch >= 'a') && (ch <= 'z')) || (!!strchr("/.-#", ch)));
}
static void make_unisig_from_arg(const char *arg)
{
size_t nbyte;
const char *cp;
int ch;
nbyte = strlen(arg);
if (nbyte > 255) {
panic("signature cannot be longer than 255 bytes");
}
if (parse_uuid(arg, tail)) {
nbyte = 0;
} else {
for (cp = arg; (ch = *cp); cp++) {
if (!is_safe_unisig_uri_char(ch)) {
panic("bad char");
}
}
memcpy(tail, arg, nbyte);
}
memcpy(head, magic, sizeof(magic));
head[sizeof(magic)] = nbyte;
}
static void print_hex_byte(unsigned int byte) { printf("%02x", byte); }
static void print_tail_uuid(void)
{
print_hex_byte(tail[0]);
print_hex_byte(tail[1]);
print_hex_byte(tail[2]);
print_hex_byte(tail[3]);
printf("-");
print_hex_byte(tail[4]);
print_hex_byte(tail[5]);
printf("-");
print_hex_byte(tail[6]);
print_hex_byte(tail[7]);
printf("-");
print_hex_byte(tail[8]);
print_hex_byte(tail[9]);
printf("-");
print_hex_byte(tail[10]);
print_hex_byte(tail[11]);
print_hex_byte(tail[12]);
print_hex_byte(tail[13]);
print_hex_byte(tail[14]);
print_hex_byte(tail[15]);
}
static void binary_input_read_unisig(void)
{
size_t lenbyte;
size_t taillen;
binary_input_exactly_n_bytes(head, sizeof(magic) + 1);
if (memcmp(head, magic, sizeof(magic))) {
panic("bad magic");
}
lenbyte = head[sizeof(magic)];
taillen = lenbyte ? lenbyte : 16;
binary_input_exactly_n_bytes(tail, taillen);
}
static void binary_output_write_unisig(void)
{
size_t nbyte;
nbyte = gettaillen();
nbyte = nbyte ? nbyte : 16;
nbyte += 8;
output_exactly_n_bytes(head, nbyte);
}
static void copy_remaining_binary_input_to_output(void)
{
size_t n;
while ((n = binary_input_at_most_n_bytes(buffer, sizeof(buffer)))) {
output_exactly_n_bytes(buffer, n);
}
}
static void print_tail_ascii(void)
{
size_t i, n;
int ch;
n = gettaillen();
for (i = 0; i < n; i++) {
ch = tail[i];
if (is_safe_unisig_uri_char(ch)) {
printf("%c", ch);
} else {
printf("?");
}
}
}
static void subcmd_prepend(void)
{
binary_output_write_unisig();
copy_remaining_binary_input_to_output();
}
static void subcmd_change(void)
{
binary_input_read_unisig();
subcmd_prepend();
}
static void subcmd_remove(void)
{
binary_input_read_unisig();
copy_remaining_binary_input_to_output();
}
static void subcmd_read(void)
{
binary_input_read_unisig();
if (binary_input != stdin) {
printf("%s: ", binary_input_name);
}
if (is_uuid()) {
printf("UUID ");
print_tail_uuid();
} else {
print_tail_ascii();
}
printf("\n");
}
static void subcmd_uuidgen(void)
{
generate_uuid_variant_1_version_four();
print_tail_uuid();
printf("\n");
}
static void subcmd_version(void) { printf("%s %s\n", PROGNAME, PROGVERSION); }
static void subcmd_help(void) { generic_usage(stdout, 0); }
#define TEXT 0
#define BINARY 1
struct cmd {
void (*visit)(void);
const char *name;
unsigned int narg;
unsigned int input_is_binary;
unsigned int output_is_binary;
};
static const struct cmd cmds[] = {
{ subcmd_prepend, "prepend", 1, BINARY, BINARY },
{ subcmd_change, "change", 1, BINARY, BINARY },
{ subcmd_remove, "remove", 0, BINARY, BINARY },
{ subcmd_read, "read", 0, BINARY, TEXT },
{ subcmd_uuidgen, "uuidgen", 0, TEXT, TEXT },
{ subcmd_version, "version", 0, TEXT, TEXT },
{ subcmd_help, "help", 0, TEXT, TEXT },
};
static const size_t ncmd = sizeof(cmds) / sizeof(cmds[0]);
static void generic_usage(FILE *stream, int status)
{
fprintf(stream, "usage: %s %s\n", PROGNAME,
"prepend sig [file ...] [-o output]");
fprintf(stream, "usage: %s %s\n", PROGNAME,
"change sig [file ...] [-o output]");
fprintf(
stream, "usage: %s %s\n", PROGNAME, "remove [file ...] [-o output]");
fprintf(stream, "usage: %s %s\n", PROGNAME, "read [file ...]");
fprintf(stream, "usage: %s %s\n", PROGNAME, "uuidgen");
fprintf(stream, "usage: %s %s\n", PROGNAME, "version");
fprintf(stream, "usage: %s %s\n", PROGNAME, "help");
exit(status);
}
static void usage(const char *msg)
{
if (msg) {
if (msg[0]) {
fprintf(stderr, "%s: %s\n", PROGNAME, msg);
} else {
fprintf(stderr, "\n");
}
}
generic_usage(stderr, 2);
}
typedef void (*visit_func_t)(void);
static const char *oflag;
static const struct cmd *cmd_by_name(const char *name)
{
const struct cmd *cmd;
for (cmd = cmds; cmd < cmds + ncmd; cmd++) {
if (!strcmp(cmd->name, name))
return cmd;
}
return 0;
}
static void run_cmd(const struct cmd *cmd, char **args)
{
const char *filename;
if (cmd->narg) {
if (*args) {
make_unisig_from_arg(*args++);
} else {
usage("too few arguments");
}
}
if (cmd->input_is_binary && cmd->output_is_binary) {
if (oflag) {
if (!args[0]) {
binary_input_std();
binary_output_file_open(oflag);
cmd->visit();
binary_output_file_close();
} else if (!args[1]) {
filename = args[0];
binary_input_std();
binary_output_file_open(oflag);
binary_input_file_open(filename);
cmd->visit();
binary_input_file_close();
binary_output_file_close();
} else {
usage("cannot use -o option with more than one input file");
}
} else if (args[0]) {
for (; (filename = *args); args++) {
binary_input_file_open(filename);
binary_output_file_open(filename);
cmd->visit();
binary_input_file_close();
binary_output_file_close();
}
} else {
binary_input_std();
binary_output_std();
cmd->visit();
}
} else if (cmd->input_is_binary) {
if (oflag) {
usage("cannot use -o option with this subcommand");
} else if (args[0]) {
for (; (filename = *args); args++) {
binary_input_file_open(filename);
cmd->visit();
binary_input_file_close();
}
} else {
binary_input_std();
cmd->visit();
}
} else {
if (oflag) {
usage("cannot use -o option with this subcommand");
} else if (args[0]) {
usage("too many arguments");
} else {
cmd->visit();
}
}
}
int main(int argc, char **argv)
{
const char *subcmd;
const struct cmd *cmd;
int ch;
while ((ch = getopt(argc, argv, "Vho:")) != -1) {
switch (ch) {
case 'V':
subcmd_version();
exit(0);
break;
case 'h':
subcmd_help();
exit(0);
break;
case 'o':
oflag = optarg;
break;
default:
usage(0);
break;
}
}
if (argc < 2) {
usage(0);
}
argv++;
subcmd = *argv++;
if (!(cmd = cmd_by_name(subcmd))) {
usage("unknown subcommand");
}
run_cmd(cmd, argv);
return 0;
}
|
the_stack_data/95705.c | /* Copyright (c) 2011 The WebM project authors. All Rights Reserved. */
/* */
/* Use of this source code is governed by a BSD-style license */
/* that can be found in the LICENSE file in the root of the source */
/* tree. An additional intellectual property rights grant can be found */
/* in the file PATENTS. All contributing project authors may */
/* be found in the AUTHORS file in the root of the source tree. */
static const char* const cfg = "--target=armv7-android-gcc --disable-runtime-cpu-detect --sdk-path=/usr/local/google/home/hkuang/Downloads/android-ndk-r8e --disable-vp9-encoder --disable-examples --disable-docs --enable-realtime-only";
const char *vpx_codec_build_config(void) {return cfg;}
|
the_stack_data/220455124.c | /* strings.c -- string formatting */
#include <stdio.h>
#define BLURB "Authentic imitation!"
int main(void)
{
printf("/%2s/\n", BLURB);
printf("/%24s/\n", BLURB);
printf("/%24.5s/\n", BLURB);
printf("/%-24.5s/\n", BLURB);
return 0;
}
|
the_stack_data/161080347.c | /* Formatted output to a stream.
Copyright (C) 2007, 2010-2012 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
/* Specification. */
#include <stdio.h>
#include <stdarg.h>
/* Print formatted output to standard output.
Return string length of formatted string. On error, return a negative
value. */
int
printf (const char *format, ...)
{
int retval;
va_list args;
va_start (args, format);
retval = vfprintf (stdout, format, args);
va_end (args);
return retval;
}
|
the_stack_data/736190.c | /* { dg-options "-std=c99" } */
int (*foo)(int (*a)[*]);
|
the_stack_data/40762397.c | /*----------------------------------------------------------------------------*/
/* Xymon monitor library. */
/* */
/* This is a library module, part of libxymon. */
/* It contains routines for time-specs in CRON format. */
/* */
/* Copyright (C) 2010-2011 Henrik Storner <[email protected]> */
/* Copyright (C) 2010 Milan Kocian <[email protected]> */
/* */
/* This program is released under the GNU General Public License (GPL), */
/* version 2 (see the file "COPYING" for details), except as listed below. */
/* */
/*----------------------------------------------------------------------------*/
/*
* A large part of this file was adapted from the "cron" sources by Paul
* Vixie. It contains this copyright notice:
* ------------------------------------------------------------------------
* Copyright 1988,1990,1993,1994 by Paul Vixie
* All rights reserved
*
* Distribute freely, except: don't remove my name from the source or
* documentation (don't take credit for my work), mark your changes (don't
* get me blamed for your possible bugs), don't alter or remove this
* notice. May be sold if buildable source is provided to buyer. No
* warrantee of any kind, express or implied, is included with this
* software; use at your own risk, responsibility for damages (if any) to
* anyone resulting from the use of this software rests entirely with the
* user.
* ------------------------------------------------------------------------
* Adjusted by Milan Kocian <[email protected]> so don't tease original autor
* for my bugs.
*
* Major change is that functions operate on string instead on file.
* And it's used only time part of cronline (no user, cmd, etc.)
* Also, the file "bitstring.h" was used from the cron sources. This file
* carries the following copyright notice:
* ------------------------------------------------------------------------
* Copyright (c) 1989 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Paul Vixie.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* @(#)bitstring.h 5.2 (Berkeley) 4/4/90
* ------------------------------------------------------------------------
*
*/
static char rcsid[] = "$Id$";
/* -------------------- bitstring.h begins -----------------------------*/
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
typedef unsigned char bitstr_t;
/* internal macros */
/* byte of the bitstring bit is in */
#define _bit_byte(bit) \
((bit) >> 3)
/* mask for the bit within its byte */
#define _bit_mask(bit) \
(1 << ((bit)&0x7))
/* external macros */
/* bytes in a bitstring of nbits bits */
#define bitstr_size(nbits) \
((((nbits) - 1) >> 3) + 1)
/* allocate a bitstring */
#define bit_alloc(nbits) \
(bitstr_t *)malloc(1, \
(unsigned int)bitstr_size(nbits) * sizeof(bitstr_t))
/* allocate a bitstring on the stack */
#define bit_decl(name, nbits) \
(name)[bitstr_size(nbits)]
/* is bit N of bitstring name set? */
#define bit_test(name, bit) \
((name)[_bit_byte(bit)] & _bit_mask(bit))
/* set bit N of bitstring name */
#define bit_set(name, bit) \
(name)[_bit_byte(bit)] |= _bit_mask(bit)
/* clear bit N of bitstring name */
#define bit_clear(name, bit) \
(name)[_bit_byte(bit)] &= ~_bit_mask(bit)
/* clear bits start ... stop in bitstring */
#define bit_nclear(name, start, stop) { \
register bitstr_t *_name = name; \
register int _start = start, _stop = stop; \
register int _startbyte = _bit_byte(_start); \
register int _stopbyte = _bit_byte(_stop); \
if (_startbyte == _stopbyte) { \
_name[_startbyte] &= ((0xff >> (8 - (_start&0x7))) | \
(0xff << ((_stop&0x7) + 1))); \
} else { \
_name[_startbyte] &= 0xff >> (8 - (_start&0x7)); \
while (++_startbyte < _stopbyte) \
_name[_startbyte] = 0; \
_name[_stopbyte] &= 0xff << ((_stop&0x7) + 1); \
} \
}
/* set bits start ... stop in bitstring */
#define bit_nset(name, start, stop) { \
register bitstr_t *_name = name; \
register int _start = start, _stop = stop; \
register int _startbyte = _bit_byte(_start); \
register int _stopbyte = _bit_byte(_stop); \
if (_startbyte == _stopbyte) { \
_name[_startbyte] |= ((0xff << (_start&0x7)) & \
(0xff >> (7 - (_stop&0x7)))); \
} else { \
_name[_startbyte] |= 0xff << ((_start)&0x7); \
while (++_startbyte < _stopbyte) \
_name[_startbyte] = 0xff; \
_name[_stopbyte] |= 0xff >> (7 - (_stop&0x7)); \
} \
}
/* find first bit clear in name */
#define bit_ffc(name, nbits, value) { \
register bitstr_t *_name = name; \
register int _byte, _nbits = nbits; \
register int _stopbyte = _bit_byte(_nbits), _value = -1; \
for (_byte = 0; _byte <= _stopbyte; ++_byte) \
if (_name[_byte] != 0xff) { \
_value = _byte << 3; \
for (_stopbyte = _name[_byte]; (_stopbyte&0x1); \
++_value, _stopbyte >>= 1); \
break; \
} \
*(value) = _value; \
}
/* find first bit set in name */
#define bit_ffs(name, nbits, value) { \
register bitstr_t *_name = name; \
register int _byte, _nbits = nbits; \
register int _stopbyte = _bit_byte(_nbits), _value = -1; \
for (_byte = 0; _byte <= _stopbyte; ++_byte) \
if (_name[_byte]) { \
_value = _byte << 3; \
for (_stopbyte = _name[_byte]; !(_stopbyte&0x1); \
++_value, _stopbyte >>= 1); \
break; \
} \
*(value) = _value; \
}
/* -------------------- end of bitstring.h ------------------------------- */
/* --------------------- crondate from Paul Vixie cron ------------------ */
#define TRUE 1
#define FALSE 0
#define MAX_TEMPSTR 1000
#define Skip_Blanks(c) \
while (*c == '\t' || *c == ' ') \
c++;
#define Skip_Nonblanks(c) \
while (*c!='\t' && *c!=' ' && *c!='\n' && *c!='\0') \
c++;
#define SECONDS_PER_MINUTE 60
#define FIRST_MINUTE 0
#define LAST_MINUTE 59
#define MINUTE_COUNT (LAST_MINUTE - FIRST_MINUTE + 1)
#define FIRST_HOUR 0
#define LAST_HOUR 23
#define HOUR_COUNT (LAST_HOUR - FIRST_HOUR + 1)
#define FIRST_DOM 1
#define LAST_DOM 31
#define DOM_COUNT (LAST_DOM - FIRST_DOM + 1)
#define FIRST_MONTH 1
#define LAST_MONTH 12
#define MONTH_COUNT (LAST_MONTH - FIRST_MONTH + 1)
/* note on DOW: 0 and 7 are both Sunday, for compatibility reasons. */
#define FIRST_DOW 0
#define LAST_DOW 7
#define DOW_COUNT (LAST_DOW - FIRST_DOW + 1)
typedef struct {
bitstr_t bit_decl(minute, MINUTE_COUNT);
bitstr_t bit_decl(hour, HOUR_COUNT);
bitstr_t bit_decl(dom, DOM_COUNT);
bitstr_t bit_decl(month, MONTH_COUNT);
bitstr_t bit_decl(dow, DOW_COUNT);
int flags;
#define DOM_STAR 0x01
#define DOW_STAR 0x02
#define WHEN_REBOOT 0x04
#define MIN_STAR 0x08
#define HR_STAR 0x10
} c_bits_t;
#define PPC_NULL ((char **)NULL)
static
char *MonthNames[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
NULL
};
static
char *DowNames[] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun",
NULL
};
static char *
get_number(numptr, low, names, ch)
int *numptr; /* where does the result go? */
int low; /* offset applied to result if symbolic enum used */
char *names[]; /* symbolic names, if any, for enums */
char *ch; /* current character */
{
char temp[MAX_TEMPSTR], *pc;
int len, i, all_digits;
/* collect alphanumerics into our fixed-size temp array
*/
pc = temp;
len = 0;
all_digits = TRUE;
while (isalnum((int)*ch)) {
if (++len >= MAX_TEMPSTR)
return(NULL);
*pc++ = *ch;
if (!isdigit((int)*ch))
all_digits = FALSE;
ch++;
}
*pc = '\0';
if (len == 0) {
return(NULL);
}
/* try to find the name in the name list
*/
if (names) {
for (i = 0; names[i] != NULL; i++) {
if (!strcasecmp(names[i], temp)) {
*numptr = i+low;
return ch;
}
}
}
/* no name list specified, or there is one and our string isn't
* in it. either way: if it's all digits, use its magnitude.
* otherwise, it's an error.
*/
if (all_digits) {
*numptr = atoi(temp);
return ch;
}
return(NULL) ;
}
static int
set_element(bits, low, high, number)
bitstr_t *bits; /* one bit per flag, default=FALSE */
int low;
int high;
int number;
{
if (number < low || number > high)
return(-1);
bit_set(bits, (number-low));
return(0);
}
static char *
get_range(bits, low, high, names, ch, last)
bitstr_t *bits; /* one bit per flag, default=FALSE */
int low, high; /* bounds, impl. offset for bitstr */
char *names[]; /* NULL or names of elements */
char *ch; /* current character being processed */
int last; /* processing last value */
{
/* range = number | number "-" number [ "/" number ]
*/
register int i;
auto int num1, num2, num3;
if (*ch == '*') {
/* '*' means "first-last" but can still be modified by /step
*/
num1 = low;
num2 = high;
ch++;
if (!*ch) {
if (!last) /* string is too short (if not last)*/
return(NULL);
}
} else {
ch = get_number(&num1, low, names, ch);
if (!ch)
return (NULL);
if (*ch != '-') {
/* not a range, it's a single number.
*/
if (set_element(bits, low, high, num1))
return(NULL);
return ch;
} else {
/* eat the dash
*/
ch++;
if (!*ch)
return(NULL);
/* get the number following the dash
*/
ch = get_number(&num2, low, names, ch);
if (!ch)
return(NULL);
}
}
/* check for step size
*/
if (*ch == '/') {
/* eat the slash
*/
ch++;
if (!*ch)
return(NULL);
/* get the step size -- note: we don't pass the
* names here, because the number is not an
* element id, it's a step size. 'low' is
* sent as a 0 since there is no offset either.
*/
ch = get_number(&num3, 0, PPC_NULL, ch);
if (!ch || num3 <= 0)
return(NULL) ;
} else {
/* no step. default==1.
*/
num3 = 1;
}
/* Explicitly check for sane values. Certain combinations of ranges and
* steps which should return EOF don't get picked up by the code below,
* eg:
* 5-64/30 * * * * touch /dev/null
*
* Code adapted from set_elements() where this error was probably intended
* to be catched.
*/
if (num1 < low || num1 > high || num2 < low || num2 > high)
return(NULL);
/* range. set all elements from num1 to num2, stepping
* by num3. (the step is a downward-compatible extension
* proposed conceptually by bob@acornrc, syntactically
* designed then implmented by paul vixie).
*/
for (i = num1; i <= num2; i += num3)
if (set_element(bits, low, high, i))
return(NULL);
return ch;
}
static char *
get_list(bits, low, high, names, ch, last)
bitstr_t *bits; /* one bit per flag, default=FALSE */
int low, high; /* bounds, impl. offset for bitstr */
char *names[]; /* NULL or *[] of names for these elements */
char *ch; /* current character being processed */
int last; /* processing last value */
{
register int done;
/* we know that we point to a non-blank character here;
* must do a Skip_Blanks before we exit, so that the
* next call (or the code that picks up the cmd) can
* assume the same thing.
*/
/* clear the bit string, since the default is 'off'.
*/
bit_nclear(bits, 0, (high-low+1));
/* process all ranges
*/
done = FALSE;
while (!done) {
ch = get_range(bits, low, high, names, ch, last);
if (ch && *ch == ',')
ch++;
else
done = TRUE;
}
/* exiting. skip to some blanks, then skip over the blanks.
*/
if (ch) {
Skip_Nonblanks(ch)
Skip_Blanks(ch)
}
return ch;
}
/* parse cron time */
void * parse_cron_time(char * ch) {
c_bits_t *e;
e = (c_bits_t *) calloc(1, sizeof(c_bits_t));
if (!e)
return(NULL);
if (ch[0] == '@') {
if (!strcmp("yearly", ch + 1) || !strcmp("annually", ch + 1)) {
bit_set(e->minute, 0);
bit_set(e->hour, 0);
bit_set(e->dom, 0);
bit_set(e->month, 0);
bit_nset(e->dow, 0, (LAST_DOW-FIRST_DOW+1));
e->flags |= DOW_STAR;
} else if (!strcmp("monthly", ch + 1)) {
bit_set(e->minute, 0);
bit_set(e->hour, 0);
bit_set(e->dom, 0);
bit_nset(e->month, 0, (LAST_MONTH-FIRST_MONTH+1));
bit_nset(e->dow, 0, (LAST_DOW-FIRST_DOW+1));
e->flags |= DOW_STAR;
} else if (!strcmp("weekly", ch + 1)) {
bit_set(e->minute, 0);
bit_set(e->hour, 0);
bit_nset(e->dom, 0, (LAST_DOM-FIRST_DOM+1));
e->flags |= DOM_STAR;
bit_nset(e->month, 0, (LAST_MONTH-FIRST_MONTH+1));
bit_nset(e->dow, 0,0);
} else if (!strcmp("daily", ch + 1) || !strcmp("midnight", ch + 1)) {
bit_set(e->minute, 0);
bit_set(e->hour, 0);
bit_nset(e->dom, 0, (LAST_DOM-FIRST_DOM+1));
bit_nset(e->month, 0, (LAST_MONTH-FIRST_MONTH+1));
bit_nset(e->dow, 0, (LAST_DOW-FIRST_DOW+1));
} else if (!strcmp("hourly", ch + 1)) {
bit_set(e->minute, 0);
bit_nset(e->hour, 0, (LAST_HOUR-FIRST_HOUR+1));
bit_nset(e->dom, 0, (LAST_DOM-FIRST_DOM+1));
bit_nset(e->month, 0, (LAST_MONTH-FIRST_MONTH+1));
bit_nset(e->dow, 0, (LAST_DOW-FIRST_DOW+1));
e->flags |= HR_STAR;
} else {
free(e);
return(NULL);
}
} else { /* end of '@' and begin for * * .. */
if (*ch == '*')
e->flags |= MIN_STAR;
ch = get_list(e->minute, FIRST_MINUTE, LAST_MINUTE, PPC_NULL, ch, 0);
if (!ch) {
free(e);
return(NULL);
}
/* hours
*/
if (*ch == '*')
e->flags |= HR_STAR;
ch = get_list(e->hour, FIRST_HOUR, LAST_HOUR, PPC_NULL, ch, 0);
if (!ch) {
free(e);
return(NULL);
}
/* DOM (days of month)
*/
if (*ch == '*')
e->flags |= DOM_STAR;
ch = get_list(e->dom, FIRST_DOM, LAST_DOM, PPC_NULL, ch, 0);
if (!ch) {
free(e);
return(NULL);
}
/* month
*/
ch = get_list(e->month, FIRST_MONTH, LAST_MONTH, MonthNames, ch, 0);
if (!ch) {
free(e);
return(NULL);
}
/* DOW (days of week)
*/
if (*ch == '*')
e->flags |= DOW_STAR;
ch = get_list(e->dow, FIRST_DOW, LAST_DOW, DowNames, ch, 1);
if (!ch) {
free(e);
return(NULL);
}
}
/* make sundays equivilent */
if (bit_test(e->dow, 0) || bit_test(e->dow, 7)) {
bit_set(e->dow, 0);
bit_set(e->dow, 7);
}
/* end of * * ... parse */
return e;
} /* END of cron date-time parser */
/*----------------- End of code from Paul Vixie's cron sources ----------------*/
void crondatefree(void *vcdate)
{
c_bits_t *cdate = (c_bits_t *)vcdate;
free(cdate);
}
static int minute=-1, hour=-1, dom=-1, month=-1, dow=-1;
void crongettime(void)
{
time_t now;
struct tm tt;
now = time(NULL); /* we need real clock, not monotonic from gettimer */
localtime_r(&now, &tt);
minute = tt.tm_min -FIRST_MINUTE;
hour = tt.tm_hour -FIRST_HOUR;
dom = tt.tm_mday -FIRST_DOM;
month = tt.tm_mon +1 /* 0..11 -> 1..12 */ -FIRST_MONTH;
dow = tt.tm_wday -FIRST_DOW;
}
int cronmatch(void *vcdate)
{
c_bits_t *cdate = (c_bits_t *)vcdate;
if (minute == -1) crongettime();
return cdate
&& bit_test(cdate->minute, minute)
&& bit_test(cdate->hour, hour)
&& bit_test(cdate->month, month)
&& ( ((cdate->flags & DOM_STAR) || (cdate->flags & DOW_STAR))
? (bit_test(cdate->dow,dow) && bit_test(cdate->dom,dom))
: (bit_test(cdate->dow,dow) || bit_test(cdate->dom,dom)));
}
|
the_stack_data/23574755.c | #include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define R(mul,shift,x,y) \
_=x; \
x -= mul*y>>shift; \
y += mul*_>>shift; \
_ = 3145728-x*x-y*y>>11; \
x = x*_>>10; \
y = y*_>>10;
int8_t b[1760], z[1760];
void main() {
int sA=1024,cA=0,sB=1024,cB=0,_;
for (;;) {
memset(b, 32, 1760); // text buffer
memset(z, 127, 1760); // z buffer
int sj=0, cj=1024;
for (int j = 0; j < 90; j++) {
int si = 0, ci = 1024; // sine and cosine of angle i
for (int i = 0; i < 324; i++) {
int R1 = 1, R2 = 2048, K2 = 5120*1024;
int x0 = R1*cj + R2,
x1 = ci*x0 >> 10,
x2 = cA*sj >> 10,
x3 = si*x0 >> 10,
x4 = R1*x2 - (sA*x3 >> 10),
x5 = sA*sj >> 10,
x6 = K2 + R1*1024*x5 + cA*x3,
x7 = cj*si >> 10,
x = 40 + 30*(cB*x1 - sB*x4)/x6,
y = 12 + 15*(cB*x4 + sB*x1)/x6,
N = (-cA*x7 - cB*((-sA*x7>>10) + x2) - ci*(cj*sB >> 10) >> 10) - x5 >> 7;
int o = x + 80 * y;
int8_t zz = (x6-K2)>>15;
if (22 > y && y > 0 && x > 0 && 80 > x && zz < z[o]) {
z[o] = zz;
b[o] = ".,-~:;=!*#$@"[N > 0 ? N : 0];
}
R(5, 8, ci, si) // rotate i
}
R(9, 7, cj, sj) // rotate j
}
for (int k = 0; 1761 > k; k++)
putchar(k % 80 ? b[k] : 10);
R(5, 7, cA, sA);
R(5, 8, cB, sB);
/* usleep(1000); */
printf("\x1b[23A");
}
}
|
the_stack_data/167331982.c | #include <pwd.h>
#include <string.h>
struct passwd *getpwnam (const char *name)
{
struct passwd *ptr;
setpwent(); /* 開啟使用者資料庫 */
while((ptr = getpwent()) != NULL) {
if (strcmp(name, ptr->pw_name) == 0)
break; /* 找到比對項 */
}
endpwent(); /* 關閉使用者資料庫 */
return(ptr); /* 找不到比對時ptr為NULL */
}
|
the_stack_data/1249994.c | #define _POSIX_C_SOURCE 200809L
#include "stdlib.h"
#include "math.h"
#include "sys/time.h"
#include "xmmintrin.h"
#include "pmmintrin.h"
#include "omp.h"
#include <stdio.h>
#define min(a, b) (((a) < (b)) ? (a) : (b))
#define max(a, b) (((a) > (b)) ? (a) : (b))
struct dataobj
{
void *restrict data;
int *size;
int *npsize;
int *dsize;
int *hsize;
int *hofs;
int *oofs;
};
struct profiler
{
double section0;
double section1;
double section2;
};
void bf0(float *restrict r18_vec, float *restrict r19_vec, float *restrict r20_vec, float *restrict r21_vec, float *restrict r34_vec, float *restrict r35_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, const int x_size, const int y_size, const int z_size, const int time, const int t0, const int x0_blk0_size, const int x_M, const int x_m, const int y0_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, const int tw);
void bf1(struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict epsilon_vec, float *restrict r17_vec, float *restrict r18_vec, float *restrict r19_vec, float *restrict r20_vec, float *restrict r21_vec, float *restrict r34_vec, float *restrict r35_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict save_src_v_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, const int x_size, const int y_size, const int z_size, const int time, const int t0, const int t1, const int t2, const int x1_blk0_size, const int x_M, const int x_m, const int y1_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int sp_zi_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, const int tw);
int ForwardTTI(struct dataobj *restrict block_sizes_vec, struct dataobj *restrict damp_vec, struct dataobj *restrict delta_vec, const float dt, struct dataobj *restrict epsilon_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict phi_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict save_src_v_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict theta_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, const int x_size, const int y_size, const int z_size, const int sp_zi_m, const int time_M, const int time_m, struct profiler *timers, const int x1_blk0_size, const int x_M, const int x_m, const int y1_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, const int nthreads_nonaffine)
{
int(*restrict block_sizes) __attribute__((aligned(64))) = (int(*))block_sizes_vec->data;
float(*restrict delta)[delta_vec->size[1]][delta_vec->size[2]] __attribute__((aligned(64))) = (float(*)[delta_vec->size[1]][delta_vec->size[2]])delta_vec->data;
int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data;
float(*restrict phi)[phi_vec->size[1]][phi_vec->size[2]] __attribute__((aligned(64))) = (float(*)[phi_vec->size[1]][phi_vec->size[2]])phi_vec->data;
float(*restrict save_src_u)[save_src_u_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_u_vec->size[1]])save_src_u_vec->data;
float(*restrict save_src_v)[save_src_v_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_v_vec->size[1]])save_src_v_vec->data;
int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data;
int(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data;
int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data;
float(*restrict theta)[theta_vec->size[1]][theta_vec->size[2]] __attribute__((aligned(64))) = (float(*)[theta_vec->size[1]][theta_vec->size[2]])theta_vec->data;
float(*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__((aligned(64))) = (float(*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]])u_vec->data;
float(*restrict v)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]])v_vec->data;
float(*r21)[y_size + 1][z_size + 1];
posix_memalign((void **)&r21, 64, sizeof(float[x_size + 1][y_size + 1][z_size + 1]));
float(*r20)[y_size + 1][z_size + 1];
posix_memalign((void **)&r20, 64, sizeof(float[x_size + 1][y_size + 1][z_size + 1]));
float(*r19)[y_size + 1][z_size + 1];
posix_memalign((void **)&r19, 64, sizeof(float[x_size + 1][y_size + 1][z_size + 1]));
float(*r18)[y_size + 1][z_size + 1];
posix_memalign((void **)&r18, 64, sizeof(float[x_size + 1][y_size + 1][z_size + 1]));
float(*r17)[y_size + 1][z_size + 1];
posix_memalign((void **)&r17, 64, sizeof(float[x_size + 1][y_size + 1][z_size + 1]));
float(*r34)[y_size + 1][z_size + 1];
posix_memalign((void **)&r34, 64, sizeof(float[x_size + 1][y_size + 1][z_size + 1]));
float(*r35)[y_size + 1][z_size + 1];
posix_memalign((void **)&r35, 64, sizeof(float[x_size + 1][y_size + 1][z_size + 1]));
/* Flush denormal numbers to zero in hardware */
_MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
struct timeval start_section0, end_section0;
gettimeofday(&start_section0, NULL);
/* Begin section0 */
#pragma omp parallel num_threads(nthreads)
{
#pragma omp for collapse(2) schedule(static, 1)
for (int x = x_m - 1; x <= x_M; x += 1)
{
for (int y = y_m - 1; y <= y_M; y += 1)
{
#pragma omp simd aligned(delta, phi, theta : 32)
for (int z = z_m - 1; z <= z_M; z += 1)
{
r21[x + 1][y + 1][z + 1] = cos(phi[x + 4][y + 4][z + 4]);
r20[x + 1][y + 1][z + 1] = sin(theta[x + 4][y + 4][z + 4]);
r19[x + 1][y + 1][z + 1] = sin(phi[x + 4][y + 4][z + 4]);
r18[x + 1][y + 1][z + 1] = cos(theta[x + 4][y + 4][z + 4]);
r17[x + 1][y + 1][z + 1] = sqrt(2 * delta[x + 4][y + 4][z + 4] + 1);
}
}
}
}
/* End section0 */
gettimeofday(&end_section0, NULL);
timers->section0 += (double)(end_section0.tv_sec - start_section0.tv_sec) + (double)(end_section0.tv_usec - start_section0.tv_usec) / 1000000;
int y0_blk0_size = block_sizes[3];
int x0_blk0_size = block_sizes[2];
int yb_size = block_sizes[1];
int xb_size = block_sizes[0];
int sf = 2;
int t_blk_size = 2 * sf * (time_M - time_m);
printf(" Tiles: %d, %d ::: Blocks %d, %d \n", xb_size, yb_size, x0_blk0_size, y0_blk0_size);
for (int t_blk = time_m; t_blk <= 1 + sf * (time_M - time_m); t_blk += sf * t_blk_size) // for each t block
{
for (int xb = x_m - 1; xb <= (x_M + sf * (time_M - time_m)); xb += xb_size)
{
//printf(" Change of outer xblock %d \n", xb);
for (int yb = y_m - 1; yb <= (y_M + sf * (time_M - time_m)); yb += yb_size)
{
//printf(" Timestep tw: %d, Updating x: %d y: %d \n", xb, yb);
for (int time = t_blk, t0 = (time) % (3), t1 = (time + 1) % (3), t2 = (time + 2) % (3); time <= 2 + min(t_blk + t_blk_size - 1, sf * (time_M - time_m)); time += sf, t0 = (((time / sf) % (time_M - time_m + 1))) % (3), t1 = (((time / sf) % (time_M - time_m + 1)) + 1) % (3), t2 = (((time / sf) % (time_M - time_m + 1)) + 2) % (3))
{
int tw = ((time / sf) % (time_M - time_m + 1));
struct timeval start_section1, end_section1;
gettimeofday(&start_section1, NULL);
/* Begin section1 */
bf0((float *)r18, (float *)r19, (float *)r20, (float *)r21, (float *)r34, (float *)r35, u_vec, v_vec, x_size, y_size, z_size, time, t0, x0_blk0_size, x_M, x_m - 1, y0_blk0_size, y_M, y_m - 1, z_M, z_m, nthreads, xb, yb, xb_size, yb_size, tw);
//printf("\n BF0 - 1 IS OVER");
/*==============================================*/
bf1(damp_vec, dt, epsilon_vec, (float *)r17, (float *)r18, (float *)r19, (float *)r20, (float *)r21, (float *)r34, (float *)r35, u_vec, v_vec, vp_vec, nnz_sp_source_mask_vec, sp_source_mask_vec, save_src_u_vec, save_src_v_vec, source_id_vec, source_mask_vec, x_size, y_size, z_size, time, t0, t1, t2, x0_blk0_size, x_M, x_m, y0_blk0_size, y_M, y_m, z_M, z_m, sp_zi_m, nthreads, xb, yb, xb_size, yb_size, tw);
//printf("\n BF1 - 1 IS OVER");
/* End section1 */
gettimeofday(&end_section1, NULL);
timers->section1 += (double)(end_section1.tv_sec - start_section1.tv_sec) + (double)(end_section1.tv_usec - start_section1.tv_usec) / 1000000;
}
}
}
}
free(r21);
free(r20);
free(r19);
free(r18);
free(r17);
free(r34);
free(r35);
return 0;
}
void bf0(float *restrict r18_vec, float *restrict r19_vec, float *restrict r20_vec, float *restrict r21_vec, float *restrict r34_vec, float *restrict r35_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, const int x_size, const int y_size, const int z_size, const int time, const int t0, const int x0_blk0_size, const int x_M, const int x_m, const int y0_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, const int tw)
{
float(*restrict r18)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r18_vec;
float(*restrict r19)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r19_vec;
float(*restrict r20)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r20_vec;
float(*restrict r21)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r21_vec;
float(*restrict r34)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r34_vec;
float(*restrict r35)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r35_vec;
float(*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__((aligned(64))) = (float(*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]])u_vec->data;
float(*restrict v)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]])v_vec->data;
#pragma omp parallel num_threads(nthreads)
{
#pragma omp for collapse(2) schedule(dynamic, 1)
for (int x0_blk0 = max((x_m + time), xb); x0_blk0 <= min((x_M + time), (xb + xb_size)); x0_blk0 += x0_blk0_size)
{
for (int y0_blk0 = max((y_m + time), yb); y0_blk0 <= min((y_M + time), (yb + yb_size)); y0_blk0 += y0_blk0_size)
{
//printf(" Change of inner x0_blk0 %d \n", x0_blk0);
for (int x = x0_blk0; x <= min(min((x_M + time), (xb + xb_size - 1)), (x0_blk0 + x0_blk0_size - 1)); x++)
{
//printf(" bf0 Timestep tw: %d, Updating x: %d \n", tw, x - time + 1);
for (int y = y0_blk0; y <= min(min((y_M + time), (yb + yb_size - 1)), (y0_blk0 + y0_blk0_size - 1)); y++)
{
// printf(" bf0 Timestep tw: %d, Updating x: %d y: %d \n", tw, x - time + 1, y - time + 1);
#pragma omp simd aligned(u, v : 32)
for (int z = z_m - 1 ; z <= z_M; z += 1)
{
//printf(" bf0 Updating x: %d y: %d z: %d \n", x - time + 1, y - time + 1, z + 1);
float r39 = -v[t0][x - time + 4][y - time + 4][z + 4];
r35[x - time + 1][y - time + 1][z + 1] = 1.0e-1F * (-(r39 + v[t0][x - time + 4][y - time + 4][z + 5]) * r18[x - time + 1][y - time + 1][z + 1] - (r39 + v[t0][x - time + 4][y - time + 5][z + 4]) * r19[x - time + 1][y - time + 1][z + 1] * r20[x - time + 1][y - time + 1][z + 1] - (r39 + v[t0][x - time + 5][y - time + 4][z + 4]) * r20[x - time + 1][y - time + 1][z + 1] * r21[x - time + 1][y - time + 1][z + 1]);
float r40 = -u[t0][x - time + 4][y - time + 4][z + 4];
r34[x - time + 1][y - time + 1][z + 1] = 1.0e-1F * (-(r40 + u[t0][x - time + 4][y - time + 4][z + 5]) * r18[x - time + 1][y - time + 1][z + 1] - (r40 + u[t0][x - time + 4][y - time + 5][z + 4]) * r19[x - time + 1][y - time + 1][z + 1] * r20[x - time + 1][y - time + 1][z + 1] - (r40 + u[t0][x - time + 5][y - time + 4][z + 4]) * r20[x - time + 1][y - time + 1][z + 1] * r21[x - time + 1][y - time + 1][z + 1]);
}
}
}
}
}
}
}
void bf1(struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict epsilon_vec, float *restrict r17_vec, float *restrict r18_vec, float *restrict r19_vec, float *restrict r20_vec, float *restrict r21_vec, float *restrict r34_vec, float *restrict r35_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict save_src_v_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, const int x_size, const int y_size, const int z_size, const int time, const int t0, const int t1, const int t2, const int x1_blk0_size, const int x_M, const int x_m, const int y1_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int sp_zi_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, const int tw)
{
float(*restrict damp)[damp_vec->size[1]][damp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[damp_vec->size[1]][damp_vec->size[2]])damp_vec->data;
float(*restrict epsilon)[epsilon_vec->size[1]][epsilon_vec->size[2]] __attribute__((aligned(64))) = (float(*)[epsilon_vec->size[1]][epsilon_vec->size[2]])epsilon_vec->data;
float(*restrict r17)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r17_vec;
float(*restrict r18)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r18_vec;
float(*restrict r19)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r19_vec;
float(*restrict r20)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r20_vec;
float(*restrict r21)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r21_vec;
float(*restrict r34)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r34_vec;
float(*restrict r35)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r35_vec;
float(*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__((aligned(64))) = (float(*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]])u_vec->data;
float(*restrict v)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]])v_vec->data;
float(*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[vp_vec->size[1]][vp_vec->size[2]])vp_vec->data;
int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data;
float(*restrict save_src_u)[save_src_u_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_u_vec->size[1]])save_src_u_vec->data;
float(*restrict save_src_v)[save_src_v_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_v_vec->size[1]])save_src_v_vec->data;
int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data;
int(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data;
int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data;
//printf("In bf1 \n");
if (x1_blk0_size == 0)
{
return;
}
#pragma omp parallel num_threads(nthreads)
{
#pragma omp for collapse(2) schedule(dynamic, 1)
for (int x1_blk0 = max((x_m + time), xb - 0 ); x1_blk0 <= +min((x_M + time), (xb - 0 + xb_size)); x1_blk0 += x1_blk0_size)
{
//printf(" Change of inner x1_blk0 %d \n", x1_blk0);
for (int y1_blk0 = max((y_m + time), yb - 0 ); y1_blk0 <= +min((y_M + time), (yb - 0 + yb_size)); y1_blk0 += y1_blk0_size)
{
for (int x = x1_blk0; x <= min(min((x_M + time), (xb - 0 + xb_size - 1)), (x1_blk0 + x1_blk0_size - 1)); x++)
{
//printf(" bf1 Timestep tw: %d, Updating x: %d \n", tw, x - time + 4);
for (int y = y1_blk0; y <= min(min((y_M + time), (yb - 0 + yb_size - 1)), (y1_blk0 + y1_blk0_size - 1)); y++)
{
//printf(" bf1 Timestep tw: %d, Updating x: %d y: %d \n", tw, x - time + 4, y - time + 4);
#pragma omp simd aligned(damp, epsilon, u, v, vp : 32)
for (int z = z_m ; z <= z_M; z += 1)
{
//printf(" bf1 Updating x: %d y: %d z: %d \n", x - time + 4, y - time + 4, z + 4);
//printf(" bf1 Updating x: %d y: %d z: %d \n", x - time + 4, y - time + 4, z + 4);
float r46 = 1.0 / dt;
float r45 = 1.0 / (dt * dt);
float r44 = r18[x - time + 1][y - time + 1][z] * r35[x - time + 1][y - time + 1][z] - r18[x - time + 1][y - time + 1][z + 1] * r35[x - time + 1][y - time + 1][z + 1] + r19[x - time + 1][y - time][z + 1] * r20[x - time + 1][y - time][z + 1] * r35[x - time + 1][y - time][z + 1] - r19[x - time + 1][y - time + 1][z + 1] * r20[x - time + 1][y - time + 1][z + 1] * r35[x - time + 1][y - time + 1][z + 1] + r20[x - time][y - time + 1][z + 1] * r21[x - time][y - time + 1][z + 1] * r35[x - time][y - time + 1][z + 1] - r20[x - time + 1][y - time + 1][z + 1] * r21[x - time + 1][y - time + 1][z + 1] * r35[x - time + 1][y - time + 1][z + 1];
float r43 = pow(vp[x - time + 4][y - time + 4][z + 4], -2);
float r42 = 1.0e-1F * (-r18[x - time + 1][y - time + 1][z] * r34[x - time + 1][y - time + 1][z] + r18[x - time + 1][y - time + 1][z + 1] * r34[x - time + 1][y - time + 1][z + 1] - r19[x - time + 1][y - time][z + 1] * r20[x - time + 1][y - time][z + 1] * r34[x - time + 1][y - time][z + 1] + r19[x - time + 1][y - time + 1][z + 1] * r20[x - time + 1][y - time + 1][z + 1] * r34[x - time + 1][y - time + 1][z + 1] - r20[x - time][y - time + 1][z + 1] * r21[x - time][y - time + 1][z + 1] * r34[x - time][y - time + 1][z + 1] + r20[x - time + 1][y - time + 1][z + 1] * r21[x - time + 1][y - time + 1][z + 1] * r34[x - time + 1][y - time + 1][z + 1]) - 8.33333315e-4F * (u[t0][x - time + 2][y - time + 4][z + 4] + u[t0][x - time + 4][y - time + 2][z + 4] + u[t0][x - time + 4][y - time + 4][z + 2] + u[t0][x - time + 4][y - time + 4][z + 6] + u[t0][x - time + 4][y - time + 6][z + 4] + u[t0][x - time + 6][y - time + 4][z + 4]) + 1.3333333e-2F * (u[t0][x - time + 3][y - time + 4][z + 4] + u[t0][x - time + 4][y - time + 3][z + 4] + u[t0][x - time + 4][y - time + 4][z + 3] + u[t0][x - time + 4][y - time + 4][z + 5] + u[t0][x - time + 4][y - time + 5][z + 4] + u[t0][x - time + 5][y - time + 4][z + 4]) - 7.49999983e-2F * u[t0][x - time + 4][y - time + 4][z + 4];
float r41 = 1.0 / (r43 * r45 + r46 * damp[x - time + 1][y - time + 1][z + 1]);
float r32 = r45 * (-2.0F * u[t0][x - time + 4][y - time + 4][z + 4] + u[t2][x - time + 4][y - time + 4][z + 4]);
float r33 = r45 * (-2.0F * v[t0][x - time + 4][y - time + 4][z + 4] + v[t2][x - time + 4][y - time + 4][z + 4]);
u[t1][x - time + 4][y - time + 4][z + 4] = r41 * ((-r32) * r43 + r42 * (2 * epsilon[x - time + 4][y - time + 4][z + 4] + 1) + 1.0e-1F * r44 * r17[x - time + 1][y - time + 1][z + 1] + r46 * (damp[x - time + 1][y - time + 1][z + 1] * u[t0][x - time + 4][y - time + 4][z + 4]));
v[t1][x - time + 4][y - time + 4][z + 4] = r41 * ((-r33) * r43 + r42 * r17[x - time + 1][y - time + 1][z + 1] + 1.0e-1F * r44 + r46 * (damp[x - time + 1][y - time + 1][z + 1] * v[t0][x - time + 4][y - time + 4][z + 4]));
}
//int sp_zi_M = nnz_sp_source_mask[x - time][y - time] - 1;
for (int sp_zi = sp_zi_m; sp_zi <= nnz_sp_source_mask[x - time][y - time] - 1; sp_zi += 1)
{
int zind = sp_source_mask[x - time][y - time][sp_zi];
float r22 = save_src_u[tw][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind];
//#pragma omp atomic update
u[t1][x - time + 4][y - time + 4][zind + 4] += r22;
float r23 = save_src_v[tw][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind];
//#pragma omp atomic update
v[t1][x - time + 4][y - time + 4][zind + 4] += r23;
//printf("Source injection at time %d , at : x: %d, y: %d, %d, %f, %f \n", tw, x - time + 4, y - time + 4, zind + 4, r22, r23);
}
}
}
}
}
}
}
|
the_stack_data/212643672.c | #include <stdio.h>
#include <stdlib.h>
#define FILENAME "output.txt"
int write_file()
{
FILE *handle;
handle = fopen(FILENAME, "w");
if (!handle) {
perror("open file for writing");
return 1;
}
fputs("A line of text\n", handle);
fputs("Another line of text\n", handle);
fclose(handle);
return 0;
}
int read_file()
{
char *line = NULL;
ssize_t read;
size_t len = 0;
FILE *handle;
handle = fopen(FILENAME, "r");
if (!handle) {
perror("open file for reading");
return 1;
}
while ((read = getline(&line, &len, handle)) != -1) {
printf("%s", line);
}
fclose(handle);
free(line);
return 0;
}
int main(int argc, char **argv)
{
int rc;
rc = write_file();
if (rc != 0) {
return EXIT_FAILURE;
}
rc = read_file();
if (rc != 0) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
the_stack_data/596684.c | #include <stdio.h>
#include <stdlib.h>
#define TAM 1024
int DOWN = 1, UP = -1;
void geraAleatorios(int numero[])
{
srand(time(NULL));
int valor;
for (int i = 0; i < TAM; i++)
{
valor = rand() % 1000;
numero[i] = valor;
}
}
void swap(int a[], int i, int j, int dir)
{
int test = (dir == DOWN && a[i] < a[j]) || (dir == UP && a[i] > a[j]);
if (test)
{
int k = a[j];
a[j] = a[i];
a[i] = k;
}
}
void bitonic_internal(int num[], int ini, int tam, int dir)
{
int passo, i, j;
for (passo = tam; passo > 1; passo /= 2)
{
for (j = 0; j < tam / passo; j++)
{
for (i = passo * j; i < passo * j + passo / 2; i++)
{
swap(num, ini + i, ini + i + passo / 2, dir);
}
}
}
}
void bitonic(int num[])
{
int passo, i, dir = UP;
for (passo = 2; passo <= TAM; passo *= 2)
{
#pragma omp parallel for shared(num)
for (i = 0; i < TAM; i += passo)
{
if (i == 0 && passo != 2)
{
dir = DOWN;
}
bitonic_internal(num, i, passo, dir);
dir *= -1;
}
}
}
int main(void)
{
int i, j, valores[TAM];
geraAleatorios(valores);
bitonic(valores);
// for (i = 0; i < TAM; i++)
// {
// printf("%d: %d\n", i, valores[i]);
// }
} |
the_stack_data/150143675.c | #define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/errno.h>
#include <time.h>
#include <assert.h>
#define BUFFER_SIZE 1024
#define PORT 13
#ifndef max
#define max(a, b) ( ((a) > (b)) ? (a) : (b) )
#endif
int main(int argc, char *argv[]) {
// Server socket, Client Socket
int server_sockfd, client_sockfd = -1, ret;
// Length of socket len
socklen_t sin_size;
// Addr struct, client struct
struct sockaddr_in server_addr, client_addr;
// Buffer Size
char buf[BUFFER_SIZE];
// Reset data
memset(&server_addr, 0, sizeof(server_addr));
// Port, IPV4 and Any Address
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
// Create Socket
if ((server_sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
perror("ERROR: Socket error");
return 1;
}
// Bind socket to server
if (bind(server_sockfd, (struct sockaddr *) &server_addr, sizeof(struct sockaddr)) < 0) {
perror("ERROR: Bind error");
return 1;
}
// Listen to request
if (listen(server_sockfd, 5) < 0) {
perror("ERROR: Listen error");
return 1;
}
printf("Accepting connections on port %d\n", PORT);
fd_set read_fds;
int max_fd = server_sockfd;
while (1) {
FD_ZERO(&read_fds);
FD_SET(server_sockfd, &read_fds);
if (client_sockfd > 0) {
FD_SET(client_sockfd, &read_fds);
max_fd = max(client_sockfd, max_fd);
}
ret = select(max_fd + 1, &read_fds, NULL, NULL, NULL);
if (ret == -1 && errno == EINTR) {
continue;
}
if (ret == -1) {
perror("ERROR: Select error");
return 1;
}
// Clients incoming
if (FD_ISSET(server_sockfd, &read_fds)) {
sin_size = sizeof(client_addr);
// Close if we Already have
if (client_sockfd > 0) {
close(client_sockfd);
}
if ((client_sockfd = accept(server_sockfd, (struct sockaddr *) &client_addr, &sin_size)) < 0) {
perror("ERROR: Accept error");
return 1;
}
// Send back daytime
printf("Accept Client %s\n", inet_ntoa(client_addr.sin_addr));
time_t t = time(NULL);
struct tm *tm = localtime(&t);
assert(strftime(buf, sizeof(buf), "%c\n", tm));
send(client_sockfd, buf, strnlen(buf, BUFFER_SIZE), 0);
close(client_sockfd);
client_sockfd = -1;
}
}
return 0;
} |
the_stack_data/96895.c | //
// Created by lucas on 01/04/2021.
//
#include <stdio.h>
int main() {
int a, b, c;
printf("Digite 2 numeros:");
scanf("%i %i", &a, &b);
c = (a == b) ? a + b : a * b;
printf("%i", c);
}
|
the_stack_data/116220.c | /*
* Verify the COMMPAGE emulation
*
* The ARM commpage is a set of user space helper functions provided
* by the kernel in an effort to ease portability of user space code
* between different CPUs with potentially different capabilities. It
* is a 32 bit invention and similar to the vdso segment in many ways.
*
* The ABI is documented in the Linux kernel:
* Documentation/arm/kernel_userspace_helpers.rst
*
* Copyright (c) 2020 Linaro Ltd
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#define ARM_COMMPAGE (0xffff0f00u)
#define ARM_KUSER_VERSION (*(int32_t *)(ARM_COMMPAGE + 0xfc))
typedef void * (get_tls_fn)(void);
#define ARM_KUSER_GET_TLS (*(get_tls_fn *)(ARM_COMMPAGE + 0xe0))
typedef int (cmpxchg_fn)(int oldval, int newval, volatile int *ptr);
#define ARM_KUSER_CMPXCHG (*(cmpxchg_fn *)(ARM_COMMPAGE + 0xc0))
typedef void (dmb_fn)(void);
#define ARM_KUSER_DMB (*(dmb_fn *)(ARM_COMMPAGE + 0xa0))
typedef int (cmpxchg64_fn)(const int64_t *oldval,
const int64_t *newval,
volatile int64_t *ptr);
#define ARM_KUSER_CMPXCHG64 (*(cmpxchg64_fn *)(ARM_COMMPAGE + 0x60))
#define fail_unless(x) \
do { \
if (!(x)) { \
fprintf(stderr, "FAILED at %s:%d\n", __FILE__, __LINE__); \
exit(EXIT_FAILURE); \
} \
} while (0)
int main(int argc, char *argv[argc])
{
void *kuser_tls;
int val = 1;
const int64_t oldval = 1, newval = 2;
int64_t val64 = 1;
fail_unless(ARM_KUSER_VERSION == 0x5);
kuser_tls = ARM_KUSER_GET_TLS();
printf("TLS = %p\n", kuser_tls);
fail_unless(kuser_tls != 0);
fail_unless(ARM_KUSER_CMPXCHG(1, 2, &val) == 0);
printf("val = %d\n", val);
/* this is a crash test, not checking an actual barrier occurs */
ARM_KUSER_DMB();
fail_unless(ARM_KUSER_CMPXCHG64(&oldval, &newval, &val64) == 0);
printf("val64 = %lld\n", val64);
return 0;
}
|
the_stack_data/131566.c | /*****************************************************************/
/* Class: Computer Programming, Fall 2019 */
/* Author: 林天佑 */
/* ID: 108820003 */
/* Date: 2019.09.17 */
/* Purpose: Be the best student. */
/* GitHub: https://github.com/Xanonymous-GitHub/main/tree/HW */
/*****************************************************************/
#include<stdio.h>
int main(int argc,char* argv[]){
//show a message that tells user there is the input place.
printf("Enter phone number [(xxx) xxx-xxxx]: ");
//init three variables to store the user datas
int a,b,c;
//get the data that user inputed.
scanf("(%d) %d-%d",&a,&b,&c);
//output the result.
printf("You entered %d.%d.%d",a,b,c);
return 0;
} |
the_stack_data/356072.c | /*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IMAGE - Image Manipulation and Processing Routines
FILE: MASKS.C
AUTHOR: Michael Garris
DATE: 04/28/1989
Contains global bit mask declarations used to address bits in
a byte of data.
***********************************************************************/
unsigned char bit_masks[8] = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};
|
the_stack_data/237642915.c | #include <stdio.h>
#include <stdlib.h>
void pr_stdio(const char *name, FILE *fp){
printf("stream = %s ", name);
if(fp->_flags & _IONBF)
printf("unbuffered\n");
else if(fp->_flags & _IOLBF)
printf("line buffered\n");
else
printf("fully buffered\n");
//printf(", buffer size =%d\n", fp->buflen);
}
/**
* 判断一个流是不是缓存的
*/
int main(){
FILE *fp;
fputs("enter any character\n",stdout);
if(getchar() == EOF){
perror("getchar error");
}
fputs("one line to standard error\n", stderr);
pr_stdio("stdin", stdin);
pr_stdio("stdout", stdout);
pr_stdio("stderr",stderr);
if((fp = fopen("/etc/motd","r")) == NULL){
perror("fopen error\n");
}
if(getc(fp) == EOF){
perror("getc error\n");
}
pr_stdio("/etc/motd", fp);
exit(0);
}
|
the_stack_data/86075093.c | #include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdlib.h>
// 信号监听函数
static void sig_handler(int signo)
{
int status;
pid_t pid;
// 0代表进程组ID与父进程ID相同的所有子进程
// WNOHANG指定没有子进程结束,立即返回
while ((pid = waitpid(0, &status, WNOHANG)) > 0){
if (WIFEXITED(status)) // 判断子进程是否是正常结束
printf("子进程(%d)正常结束,结果码为:%d\n", pid, WEXITSTATUS(status));
else if (WIFSIGNALED(status)) // 判断子进程是否是因为信号结束
printf("子进程(%d)收到信号结束,信号编号为:%d\n", pid, WTERMSIG(status));
}
}
static void sys_err(const char *errInfo)
{
perror(errInfo);
exit(1);
}
int main()
{
pid_t pid;
int i;
for (i = 0; i<10; i++) {
if ((pid = fork()) == 0)
break;
else if (pid < 0)
sys_err("fork");
}
if (pid == 0) {
int n = 40;
while(n--) {
printf("子进程(%d)正在运行\n", getpid());
sleep(1);
}
return i;
}
else if (pid > 0) {
struct sigaction act;
act.sa_handler = sig_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGCHLD, &act, NULL);
while(1) {
printf("父进程(%d)正在运行\n", getpid());
sleep(1);
}
}
return 0;
}
|
the_stack_data/175142912.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
float salarioBruto, salarioLiquido;
printf("Qual o seu salario bruto? ");
if(scanf("%f", &salarioBruto) == 1 && salarioBruto > 0){
if(salarioBruto >= 0 && salarioBruto <= 350){
salarioLiquido = (salarioBruto * 0.93) + 100;
printf("Seu novo salario e: R$%.2f\n\n", salarioLiquido);
}
else if(salarioBruto > 350 && salarioBruto < 600){
salarioLiquido = (salarioBruto * 0.93) + 75;
printf("Seu novo salario e: R$%.2f\n\n", salarioLiquido);
}
else if(salarioBruto >= 600 && salarioBruto <= 900){
salarioLiquido = (salarioBruto * 0.93) + 50;
printf("Seu novo salario e: R$%.2f\n\n", salarioLiquido);
}
else{
salarioLiquido = (salarioBruto * 0.93) + 35;
printf("Seu novo salario e: R$%.2f\n\n", salarioLiquido);
}
}
else{
printf("Por favor, informe um numero inteiro maior que 0 valido!\n\n");
}
system("PAUSE");
return 0;
}
|
the_stack_data/173577448.c | /*
* test_component: Read in a component and execute it
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
int read_and_exec_file(char* file)
{
char* buf = malloc(10000);
int f, n;
if ((f = open(file, O_RDONLY, 0)) < 0) {
perror("open");
exit(EXIT_FAILURE);
}
if ((n = read(f, buf, 100000)) < 0) {
perror("read");
exit(EXIT_FAILURE);
}
//printf("==> Read %d bytes, executing component...\n", n);
((void(*)(void))buf)();
printf("==> Done.\n");
return 0;
}
int create_read_and_exec_thread(char* file)
{
int err;
pthread_t pthread;
void* return_value;
if ((err = pthread_create(&pthread, NULL,
read_and_exec_file, (void*)file)) != 0) {
fprintf(stderr, "pthread_create: %s\n", strerror(err));
return -1;
}
if ((err = pthread_join(pthread, &return_value)) != 0) {
fprintf(stderr, "pthread_join: %s\n", strerror(err));
return -1;
}
return 0;
}
int main(int argc, char* argv[])
{
int c;
int threaded = 0;
while ((c = getopt(argc, argv, "tp:")) != EOF) {
switch (c) {
case 't':
threaded = 1;
break;
default:
fprintf(stderr, "usage: %s [ -t ] payload_bin\n", argv[0]);
exit(EXIT_FAILURE);
}
}
if (threaded)
create_read_and_exec_thread(argv[optind]);
else
read_and_exec_file(argv[optind]);
}
|
the_stack_data/25137289.c | void corrdim ( double * epss, double * ce, double * distsq, int Nepss, int Nd2)
{
int i,k;
for (i = 0; i < Nd2; i++)
{
for (k = 0; k < Nepss; k++)
{
if (distsq[i] <= epss[k]*epss[k])
{
ce[k]++;
}
}
}
} |
the_stack_data/27213.c | void test() {
int i = 0;
i += 5; expecti(i, 5);
i -= 4; expecti(i, 1);
i *= 100; expecti(i, 100);
i /= 2; expecti(i, 50);
i %= 6; expecti(i, 2);
i &= 1; expecti(i, 0);
i |= 8; expecti(i, 8);
i ^= 2; expecti(i, 10);
i <<= 2; expecti(i, 40);
i >>= 2; expecti(i, 10);
}
int main() {
init("compound assignment operators");
test();
return ok();
}
|
the_stack_data/153268393.c |
/*
finding the minimum and maximum with
less than twice the cost
Walk through elements by pairs
Compare each element in pair to the other
Compare the largest to maximum, smallest to minimum
Total cost: 3 comparisons per 2 elements = 3n/2
*/
#include <stdio.h>
#include <limits.h>
int main()
{
int N,i;
printf("Enter the size of the array\n");
scanf("%d",&N);
int a[N];
printf("Enter the elements\n");
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
int max=INT_MIN,min=INT_MAX;
for(int i=0;i<N;i+=2)
{
if(i+1==N)//checking for odd sized array
{
if(a[i]>max)
max=a[i];
else if(a[i]<min)
min=a[i];
}
else// for all other even sized array
{
if(a[i]>a[i+1])
{
if(a[i]>max)
max=a[i];
if(a[i+1]<min)
min=a[i+1];
}
else
{
if(a[i+1]>max)
max=a[i+1];
if(a[i]<min)
min=a[i];
}
}
}
printf("The maximum is %d\n",max);
printf("The minimum is %d",min);
return 0;
} |
the_stack_data/31387361.c | /*
* Program: Rename file
*
* Author: Mark Crispin
* Networks and Distributed Computing
* Computing & Communications
* University of Washington
* Administration Building, AG-44
* Seattle, WA 98195
* Internet: [email protected]
*
* Date: 20 May 1996
* Last Edited: 24 October 2000
*
* The IMAP toolkit provided in this Distribution is
* Copyright 2000 University of Washington.
* The full text of our legal notices is contained in the file called
* CPYRIGHT, included with this Distribution.
*/
/* Emulator for working Unix rename() call
* Accepts: old file name
* new file name
* Returns: 0 if success, -1 if error with error in errno
*/
int Rename (char *oldname,char *newname)
{
int ret;
unlink (newname); /* make sure the old name doesn't exist */
/* link to new name, unlink old name */
if (!(ret = link (oldname,newname))) unlink (oldname);
return ret;
}
|
the_stack_data/184517016.c | #include <curses.h>
#include <menu.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
#define CTRLD 4
char *choices[] = {
"Choice 1", "Choice 2", "Choice 3", "Choice 4", "Choice 5",
"Choice 6", "Choice 7", "Choice 8", "Choice 9", "Choice 10",
"Choice 11", "Choice 12", "Choice 13", "Choice 14", "Choice 15",
"Choice 16", "Choice 17", "Choice 18", "Choice 19", "Choice 20",
"Exit",
(char *)NULL,
};
int main()
{ ITEM **my_items;
int c;
MENU *my_menu;
WINDOW *my_menu_win;
int n_choices, i;
/* Initialize curses */
initscr();
start_color();
cbreak();
noecho();
keypad(stdscr, TRUE);
init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, COLOR_CYAN, COLOR_BLACK);
/* Create items */
n_choices = ARRAY_SIZE(choices);
my_items = (ITEM **)calloc(n_choices, sizeof(ITEM *));
for(i = 0; i < n_choices; ++i)
my_items[i] = new_item(choices[i], choices[i]);
/* Crate menu */
my_menu = new_menu((ITEM **)my_items);
/* Set menu option not to show the description */
menu_opts_off(my_menu, O_SHOWDESC);
/* Create the window to be associated with the menu */
my_menu_win = newwin(10, 70, 4, 4);
keypad(my_menu_win, TRUE);
/* Set main window and sub window */
set_menu_win(my_menu, my_menu_win);
set_menu_sub(my_menu, derwin(my_menu_win, 6, 68, 3, 1));
set_menu_format(my_menu, 5, 3);
set_menu_mark(my_menu, " * ");
/* Print a border around the main window and print a title */
box(my_menu_win, 0, 0);
attron(COLOR_PAIR(2));
mvprintw(LINES - 3, 0, "Use PageUp and PageDown to scroll");
mvprintw(LINES - 2, 0, "Use Arrow Keys to navigate (F1 to Exit)");
attroff(COLOR_PAIR(2));
refresh();
/* Post the menu */
post_menu(my_menu);
wrefresh(my_menu_win);
while((c = wgetch(my_menu_win)) != KEY_F(1))
{ switch(c)
{ case KEY_DOWN:
menu_driver(my_menu, REQ_DOWN_ITEM);
break;
case KEY_UP:
menu_driver(my_menu, REQ_UP_ITEM);
break;
case KEY_LEFT:
menu_driver(my_menu, REQ_LEFT_ITEM);
break;
case KEY_RIGHT:
menu_driver(my_menu, REQ_RIGHT_ITEM);
break;
case KEY_NPAGE:
menu_driver(my_menu, REQ_SCR_DPAGE);
break;
case KEY_PPAGE:
menu_driver(my_menu, REQ_SCR_UPAGE);
break;
}
wrefresh(my_menu_win);
}
/* Unpost and free all the memory taken up */
unpost_menu(my_menu);
free_menu(my_menu);
for(i = 0; i < n_choices; ++i)
free_item(my_items[i]);
endwin();
}
|
the_stack_data/178266036.c | #include <stdint.h>
#include <stdio.h>
static int
hamming_weight(uint32_t n)
{
int i;
int weight;
weight = 0;
for (i = 0; i < 32; i++) {
weight += (n >> i) & 1;
}
return weight;
}
int
main(void)
{
printf("hamming_weight(%d) -> %d\n", 1, hamming_weight(1));
printf("hamming_weight(%d) -> %d\n", 2, hamming_weight(2));
printf("hamming_weight(%d) -> %d\n", 3, hamming_weight(3));
printf("hamming_weight(%d) -> %d\n", 4, hamming_weight(4));
printf("hamming_weight(%d) -> %d\n", 5, hamming_weight(5));
printf("hamming_weight(%d) -> %d\n", 6, hamming_weight(6));
return 0;
}
|
the_stack_data/304169.c |
// Extracts random patterns from a file
#include <time.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
static int Seed;
#define ACMa 16807
#define ACMm 2147483647
#define ACMq 127773
#define ACMr 2836
#define hi (Seed / ACMq)
#define lo (Seed % ACMq)
static int fst = 1;
/*
* returns a random integer in 0..top-1
*/
int
aleat(top)
{
long test;
struct timeval t;
if (fst) {
gettimeofday(&t, NULL);
Seed = t.tv_sec * t.tv_usec;
fst = 0;
}
{
Seed = ((test =
ACMa * lo - ACMr * hi) > 0) ? test : test + ACMm;
return ((double) Seed) * top / ACMm;
}
}
void parse_forbid(unsigned char* forbid, unsigned char** forbide)
{
int len, i, j;
len = strlen(forbid);
*forbide = (unsigned char*) malloc((len+1)*sizeof(unsigned char));
if (*forbide == NULL) {
fprintf(stderr, "Error: cannot allocate %i bytes\n", len+1);
fprintf(stderr, "errno = %i\n", errno);
exit(1);
}
for (i = 0, j = 0; i < len; i++) {
if (forbid[i] != '\\') {
if (forbid[i] != '\n')
(*forbide)[j++] = forbid[i];
} else {
i++;
if (i == len) {
forbid[i-1] = '\0';
(*forbide)[j] = '\0';
fprintf(stderr, "Not correct forbidden string: only one \\\n");
return;
}
switch (forbid[i]) {
case'n': (*forbide)[j++] = '\n'; break;
case'\\': (*forbide)[j++] = '\\'; break;
case'b': (*forbide)[j++] = '\b'; break;
case'e': (*forbide)[j++] = '\e'; break;
case'f': (*forbide)[j++] = '\f'; break;
case'r': (*forbide)[j++] = '\r'; break;
case't': (*forbide)[j++] = '\t'; break;
case'v': (*forbide)[j++] = '\v'; break;
case'a': (*forbide)[j++] = '\a'; break;
case'c':
if (i+3 >= len) {
forbid[i-1] = '\0';
(*forbide)[j] = '\0';
fprintf(stderr, "Not correct forbidden string: 3 digits after \\c\n");
return;
}
(*forbide)[j++] = (forbid[i+1]-48)*100 +
(forbid[i+2]-48)*10 + (forbid[i+3]-48);
i+=3;
break;
default:
fprintf(stdout, "Unknown escape sequence '\\%c'in forbidden string\n", forbid[i]);
break;
}
}
}
(*forbide)[j] = '\0';
}
main(int argc, char** argv)
{
int n, m, J, t;
struct stat sdata;
FILE* ifile, *ofile;
unsigned char* buff;
unsigned char* forbid, *forbide = NULL;
if (argc < 5) {
fprintf(stderr,
"Usage: genpatterns <file> <length> <number> <patterns file> <forbidden>\n"
" randomly extracts <number> substrings of length <length> from <file>,\n"
" avoiding substrings containing characters in <forbidden>.\n"
" The output file, <patterns file> has a first line of the form:\n"
" # number=<number> length=<length> file=<file> forbidden=<forbidden>\n"
" and then the <number> patterns come successively without any separator.\n"
" <forbidden> uses \\n, \\t, etc. for nonprintable chracters or \\cC\n"
" where C is the ASCII code of the character written using 3 digits.\n\n");
exit(1);
}
if (stat(argv[1], &sdata) != 0) {
fprintf(stderr, "Error: cannot stat file %s\n", argv[1]);
fprintf(stderr, " errno = %i\n", errno);
exit(1);
}
n = sdata.st_size;
m = atoi(argv[2]);
if ((m <= 0) || (m > n)) {
fprintf(stderr,
"Error: length must be >= 1 and <= file length"
" (%i)\n", n);
exit(1);
}
J = atoi(argv[3]);
if (J < 1) {
fprintf(stderr, "Error: number of patterns must be >= 1\n");
exit(1);
}
if (argc > 5) {
forbid = argv[5];
parse_forbid(forbid, &forbide);
} else
forbid = NULL;
ifile = fopen(argv[1], "r");
if (ifile == NULL) {
fprintf(stderr, "Error: cannot open file %s for reading\n", argv[1]);
fprintf(stderr, " errno = %i\n", errno);
exit(1);
}
buff = (unsigned char*) malloc(n);
if (buff == NULL) {
fprintf(stderr, "Error: cannot allocate %i bytes\n", n);
fprintf(stderr, " errno = %i\n", errno);
exit(1);
}
if (fread(buff, n, 1, ifile) != 1) {
fprintf(stderr, "Error: cannot read file %s\n", argv[1]);
fprintf(stderr, " errno = %i\n", errno);
exit(1);
}
fclose(ifile);
ofile = fopen(argv[4], "w");
if (ofile == NULL) {
fprintf(stderr, "Error: cannot open file %s for writing\n",
argv[4]);
fprintf(stderr, " errno = %i\n", errno);
exit(1);
}
if (fprintf(ofile, "# number=%i length=%i file=%s forbidden=%s\n",
J, m, argv[1],
forbid == NULL ? "" : (char*) forbid) <= 0) {
fprintf(stderr, "Error: cannot write file %s\n", argv[4]);
fprintf(stderr, " errno = %i\n", errno);
exit(1);
}
for (t = 0; t < J; t++) {
int j, l;
if (!forbide)
j = aleat(n - m + 1);
else {
do {
j = aleat(n - m + 1);
for (l = 0; l < m; l++)
if (strchr(forbide, buff[j + l]))
break;
} while (l < m);
}
for (l = 0; l < m; l++)
if (putc(buff[j + l], ofile) != buff[j + l]) {
fprintf(stderr,
"Error: cannot write file %s\n",
argv[4]);
fprintf(stderr, " errno = %i\n", errno);
exit(1);
}
}
if (fclose(ofile) != 0) {
fprintf(stderr, "Error: cannot write file %s\n", argv[4]);
fprintf(stderr, " errno = %i\n", errno);
exit(1);
}
fprintf(stderr, "File %s successfully generated\n", argv[4]);
free(forbide);
exit(0);
}
|
the_stack_data/45450916.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void good(const int *src, int *dst, size_t len) {
memcpy(dst, src, len);
}
void bad_read(const int *q, size_t len) {
void *p = memchr(q, 1, len);
if (!p)
printf("Not found!\n");
}
void bad_write(const int *src, int *dst, size_t len) {
memcpy(dst, src, len);
}
int main() {
size_t big = 42;
size_t small = 41;
int *src = malloc(big);
int *dst = malloc(small);
good(src, dst, small);
bad_read(dst, big);
bad_write(src, dst, big);
free(src);
free(dst);
return 0;
}
|
the_stack_data/67325757.c |
/*
* Ram.C - Memory management utilities
*/
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
char error_message[262144] = {"\0"};
#define ALF(_s0) sprintf( _s0 + strlen(_s0), "\n\nFILE: %s LINE: %i", __FILE__, __LINE__ )
#define P_MESS(a,b) printf( "\nERROR MESSAGE\nRoutine: %s\n%s\n", a, b );
/*********************************************************************
start of stuff to be included in all programs that use this package
*********************************************************************/
typedef struct Ram_Block_Data__ {
char *head;
char *tail;
size_t size;
size_t left;
size_t used;
struct Ram_Block_Data__ *next;
} Ram_Block_Data;
int ram_init( size_t block_size );
char *ram_more(int ram_block_number, size_t more_bytes );
int ram_free(int ram_block_number );
int ram_free_all( void );
Ram_Block_Data *ram_querey( int ram_block_number );
void ram_toggle_debug( int flag );
/*********************************************************************
end of stuff to be included in all programs that use this package
*********************************************************************/
#define MAX_RAM_BLOCKS 128
#define DEFAULT_BLOCK_SIZE 4096
static int not_first_call_to_init = 0;
static int ram_debug_enabled = 0;
static struct Ram_Block_Data__ *ram_block_entries[ MAX_RAM_BLOCKS ];
static int ram_block_sizes[ MAX_RAM_BLOCKS ];
extern void ram_dump( char *routine );
/*********************************************************************
toggle the debugger
*********************************************************************/
void ram_toggle_debug( int flag )
{
if( flag > 1 ) flag = 1;
if( flag < 0 ) flag = 0;
ram_debug_enabled = flag;
return;
}
/*********************************************************************
delete a current block and zero the memory
no input error checking
*********************************************************************/
void ram_free_block( Ram_Block_Data *this_block )
{
/* zero the memory in the block*/
memset( this_block->head, 0,
sizeof( char )*this_block->size );
this_block->tail = NULL;
this_block->size = 0;
this_block->used = 0;
this_block->left = 0;
this_block->next = NULL;
/* free the memmory in the block */
free( this_block->head );
this_block->head = NULL;
/* free the memory for the block structure */
free( this_block ); this_block = NULL;
return;
}
/*********************************************************************
free an entire link
*********************************************************************/
/* the free function */
int ram_free( block_number )
int block_number;
{
Ram_Block_Data *this_block, *that_block;
/* make sure block number in bounds */
if(block_number < 1 ||
block_number > MAX_RAM_BLOCKS-1)
{
error_message[0] = '\0';
sprintf( error_message+strlen(error_message),
"Block %i\nblock_number out of range\n",
block_number);
sprintf( error_message+strlen(error_message),
"Allowable min = 1 Allowable max = %i ",
MAX_RAM_BLOCKS-1);
ALF(error_message);
P_MESS( "ram_free", error_message );
return(-1);
}
if( ram_block_entries[ block_number ] == NULL )
{
error_message[0] = '\0';
sprintf( error_message+strlen(error_message),
"Block %i\ncan't free block - it has a NULL head",
block_number);
ALF(error_message);
P_MESS( "ram_free", error_message );
return(-1);
}
/* descend and free */
this_block = ram_block_entries[ block_number ];
while( this_block != NULL )
{
that_block = this_block->next;
ram_free_block( this_block );
this_block = that_block;
}
/* don't forget the head!! */
ram_block_entries[ block_number ] = NULL;
/* finally, the list */
ram_block_sizes[ block_number ] = 0;
/* debug printing */
if( ram_debug_enabled == 1 ) ram_dump( "ram_free" );
/* return the number of bytes free'd */
return(0);
}
/*********************************************************************
free all the links
no input error checking
*********************************************************************/
int ram_free_all()
{
int ii;
int ireturn_val=0;
for( ii=1; ii<MAX_RAM_BLOCKS; ii++ )
{
if( ram_block_entries[ ii ] != NULL)
{
/* free the data in this link */
ireturn_val += ram_free( ii );
}
}
/* debug printing */
if( ram_debug_enabled == 1 ) ram_dump( "ram_free_all" );
return( ireturn_val );
}
/*********************************************************************
initialize all of the head pointers to NULL
no input error checking
*********************************************************************/
void ram_init_first_pass( void )
{
int ii;
memset( ram_block_entries, 0,
sizeof( Ram_Block_Data *)*MAX_RAM_BLOCKS );
memset( ram_block_sizes, 0,
sizeof(int)*MAX_RAM_BLOCKS );
not_first_call_to_init = 1;
return;
}
/*********************************************************************
create a new empty block
no input error checking
*********************************************************************/
Ram_Block_Data *ram_add_block( int block_number, size_t block_size )
{
Ram_Block_Data *this_block;
/* get the structure for the block */
this_block = (Ram_Block_Data *) malloc( sizeof(Ram_Block_Data) );
if( this_block == NULL )
{
error_message[0] = '\0';
sprintf( error_message+strlen(error_message),
"Block %i\nmalloc failure: can't malloc %i bytes for the block structure", block_number, sizeof(Ram_Block_Data) );
ALF(error_message);
P_MESS( "ram_add_block", error_message );
return( NULL );
}
/* get the memory for the block */
this_block->head = (char *) malloc( block_size );
if( this_block->head == NULL )
{
error_message[0] = '\0';
sprintf( error_message+strlen(error_message),
"Block %i\nmalloc failure: can't malloc %i bytes for the block data", block_number, block_size );
ALF(error_message);
P_MESS( "ram_block_add", error_message );
return( NULL );
}
/* initialize the remaining parts of the structure */
this_block->tail = this_block->head;
this_block->size = block_size;
this_block->used = 0;
this_block->left = block_size;
this_block->next = NULL;
/* return the new block number */
return( this_block );
}
/*********************************************************************
initialize the head structure of a link with a new empty block
*********************************************************************/
/* the init function */
int ram_init( size_t block_size )
{
int block_number;
Ram_Block_Data *this_block;
/* Is this the first call to init? */
if( not_first_call_to_init == 0 )
{
ram_init_first_pass();
}
/* make sure block size is reasonable */
if( block_size < 0 )
{
error_message[0] = '\0';
sprintf( error_message+strlen(error_message),
"Invalid block size = %i",
block_size );
ALF(error_message);
P_MESS( "ram_init", error_message );
return(-1);
}
/* allow for a default block size */
if( block_size == 0 ) block_size = DEFAULT_BLOCK_SIZE;
/* search for the first free block
NB - block 0 is reserved for future use */
for(block_number=1;
block_number < MAX_RAM_BLOCKS &&
ram_block_entries[ block_number ] != NULL;
block_number++ ){}
/* signal error if all blocks used and return 0*/
if( block_number == MAX_RAM_BLOCKS )
{
error_message[0] = '\0';
sprintf( error_message+strlen(error_message),
"\nAll %i blocks currently in use",
MAX_RAM_BLOCKS );
ALF(error_message);
P_MESS( "ram_init", error_message );
return(-1);
}
/* add a new block and put it at the head */
ram_block_entries[ block_number ]
= ram_add_block( block_number, block_size );
if( ram_block_entries[ block_number ] == NULL )
{
return( (int) NULL );
}
/* save the block size for future use */
ram_block_sizes[ block_number ] = block_size;
/* debug printing */
if( ram_debug_enabled == 1 ) ram_dump( "ram_init" );
/* return the new block number */
return( block_number );
}
/*********************************************************************
get more memory from a list
*********************************************************************/
char *ram_more(int block_number, size_t more_bytes )
{
div_t mydiv;
size_t new_bytes;
int factor;
char *return_val;
Ram_Block_Data *this_block;
/* make sure block number in bounds */
if(block_number < 1 ||
block_number > MAX_RAM_BLOCKS-1)
{
error_message[0] = '\0';
sprintf( error_message+strlen(error_message),
"Block %i\nblock_number out of range\n",
block_number);
sprintf( error_message+strlen(error_message),
"Allowable minimum = 1 Allowable maximum = %i ",
MAX_RAM_BLOCKS-1);
ALF(error_message);
P_MESS( "ram_more", error_message );
return(NULL);
}
/* make sure the size requested makes sense */
if( more_bytes < 1 )
{
error_message[0] = '\0';
sprintf( error_message+strlen(error_message),
"Block = %i\nrequested # bytes = %i out of range",
block_number, more_bytes);
ALF(error_message);
P_MESS( "ram_more", error_message );
return(NULL);
}
/* make sure this block has been init'ed properly */
if( ram_block_entries[block_number] == NULL )
{
error_message[0] = '\0';
sprintf( error_message+strlen(error_message),
"\nrequested block = %i has NULL head (not init'ed)",
block_number);
ALF(error_message);
P_MESS( "ram_more", error_message );
return(NULL);
}
/* no more memory needed */
this_block = ram_block_entries[ block_number ];
if( more_bytes <= this_block->left )
{
this_block->used += more_bytes;
this_block->left -= more_bytes;
return_val = this_block->tail;
this_block->tail += more_bytes;
/* is the block full */
if( this_block->left == 0 )
{
this_block->tail = NULL;
}
/* debug printing */
if( ram_debug_enabled == 1 ) ram_dump( "ram_more" );
return( return_val );
}
/* first truncate the existing block */
this_block = ram_block_entries[ block_number ];
/* watch for zero length blocks - remove if possible */
/* don't remove the head if there is only one link */
if( this_block->used == 0 ) this_block->used = 1;
this_block->head
= (char *) realloc( this_block->head, this_block->used );
if( this_block->head == NULL )
{
error_message[0] = '\0';
sprintf( error_message+strlen(error_message),
"Block %i\nrealloc failure\nexisting bytes = %i requested bytes = %i",
block_number, this_block->size, this_block->used );
sprintf( error_message+strlen(error_message),
"\n\nERR: %s", strerror(errno) );
ALF(error_message);
P_MESS( "ram_more" , error_message );
return(NULL);
}
/* adjust the information in this block */
this_block = ram_block_entries[ block_number ];
this_block->size = this_block->used;
this_block->left = 0;
this_block->tail = NULL;
/* now create a new block */
/* allow for exact block fills */
mydiv = div( more_bytes, ram_block_sizes[ block_number ] );
if( mydiv.rem == 0 )
{
new_bytes = mydiv.quot * ram_block_sizes[ block_number ];
}
else
{
new_bytes = (mydiv.quot+1) * ram_block_sizes[ block_number ];
}
/* create the new block */
this_block = ram_add_block( block_number, new_bytes );
if( this_block == NULL )
{
/* debug printing */
if( ram_debug_enabled == 1 ) ram_dump( "ram_more" );
return( NULL );
}
/* put it at the head of the list and return*/
this_block->next = ram_block_entries[ block_number ];
ram_block_entries[ block_number ] = this_block;
/* adjust for memory being returned */
this_block = ram_block_entries[ block_number ];
this_block->used = more_bytes;
this_block->left = this_block->size - more_bytes;
return_val = this_block->tail;
this_block->tail = this_block->head + more_bytes;
if( this_block->left == 0 )
{
this_block->tail = NULL;
}
return_val = this_block->head;
/* debug printing */
if( ram_debug_enabled == 1 ) ram_dump( "ram_more" );
return( return_val );
}
/*********************************************************************
querey the blocks
*********************************************************************/
/* the querey function */
Ram_Block_Data *ram_querey( block_number )
int block_number;
{
int ii;
Ram_Block_Data *this_block;
/* make sure block number in bounds */
if(block_number < 0 ||
block_number > MAX_RAM_BLOCKS-1)
{
error_message[0] = '\0';
sprintf( error_message+strlen(error_message),
"Block %i\nblock_number out of range",
block_number);
sprintf( error_message+strlen(error_message),
"Allowable min = 0 Allowable max = %i ",
MAX_RAM_BLOCKS);
ALF(error_message);
P_MESS( "ram_querey", error_message );
return(NULL);
}
/* do a window if all requested */
if( block_number == 0 )
{
error_message[0] = '\0';
for(ii=0; ii< MAX_RAM_BLOCKS; ii++ )
{
this_block = ram_block_entries[ ii ];
if( this_block != NULL )
{
sprintf( error_message+strlen(error_message),
"\nblock head tail size used left next block P ");
sprintf( error_message+strlen(error_message),
"\n------ -------- -------- ------ ------ ------ -------- --------");
while( this_block != NULL )
{
sprintf( error_message+strlen(error_message),
"\n%6i %8p %8p %6i %6i %6i %8p %8p",
ii,
this_block->head,
this_block->tail,
this_block->size,
this_block->used,
this_block->left,
this_block->next,
this_block );
this_block = this_block->next;
}
}
}
P_MESS( "ram_querey", error_message );
return(NULL);
}
/* debug printing */
/*
if( ram_debug_enabled == 1 ) ram_dump( "ram_more" );
*/
/* return a single */
this_block = ram_block_entries[ block_number ];
return(this_block);
}
/*********************************************************************
debug printing
*********************************************************************/
void ram_dump( routine )
char *routine;
{
int ii;
float total_size = 0.0e0, total_used = 0.0e0;
Ram_Block_Data *this_block;
printf( "\n\n\n------------------------ BEGIN ------------------------");
printf( "\n\n%s <- calling procedure", routine );
/* dump it all */
for(ii=0; ii< MAX_RAM_BLOCKS; ii++ )
{
this_block = ram_block_entries[ ii ];
if( this_block != NULL )
{
printf( "\nblock head tail size used left next block P ");
printf( "\n------ -------- -------- ---------- ---------- ---------- -------- --------");
while( this_block != NULL )
{
printf( "\n%6i %8p %8p %10i %10i %10i %8p %8p",
ii,
this_block->head,
this_block->tail,
this_block->size,
this_block->used,
this_block->left,
this_block->next,
this_block );
total_size += (float) this_block->size;
total_used += (float) this_block->used;
this_block = this_block->next;
}
}
}
printf( "\n total_size -> %g Mbyte %g Kbyte %g byte",
total_size/1024000.0e0,
total_size/1024.0e0,
total_size );
printf( "\n total_used -> %g Mbyte %g Kbyte %g byte",
total_used/1024000.0e0,
total_used/1024.0e0,
total_used );
printf( "\n\n------------------------ END --------------------------");
fflush( stdout );
return;
}
|
the_stack_data/165768369.c | // Fork and Wait
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
// In this one, the parent waits on the child process to complete before resuming.
int main(int argc, char *argv[]) {
printf("hello world (pid: %d)\n", (int) getpid());
int rc = fork();
if (rc < 0) {
fprintf(stderr, "fork failed\n");
exit(1);
} else if (rc == 0) {
printf("hello, I am child (pid: %d)\n", (int) getpid());
} else {
int rc_wait = wait(NULL);
printf("hello, I am parent of %d (rc_wait: %d) (pid: %d)\n", rc, rc_wait, (int) getpid());
}
} |
the_stack_data/74080.c |
//{{BLOCK(VueMasterImage6)
//======================================================================
//
// VueMasterImage6, 8x5176@2,
// + 647 tiles not compressed
// Total size: 10352 = 10352
//
// Exported by Cearn's GBA Image Transmogrifier, v0.8.6
// ( http://www.coranac.com/projects/#grit )
//
//======================================================================
const unsigned int VueMasterImage6Tiles[2588] __attribute__((aligned(4)))=
{
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0xF9005000,0xFFFDFFE0,
0x00000000,0xAA500000,0xFFFFFFFE,0xFFFFFFFF,0x00000000,0x16AB0000,0xFFFFBFFF,0xFFFFFFFF,
0x00000000,0x00000000,0x006F0005,0x0BFF02FF,0x00000000,0x00000000,0x00000000,0x50000000,
0x00000000,0x00000000,0x00000000,0xFFEA5500,0x00000000,0x00000000,0x00000000,0xAFFF0055,
0x00000000,0x00000000,0xF4004000,0xFFD0FE00,0x00000000,0xFFA45400,0xFFFFFFFE,0xFFFFFFFF,
0x00000000,0x16FF0005,0xFFFFBFFF,0xFFFFFFFF,0x00000000,0x00000000,0x002F0001,0x1BFF01FF,
0x00000000,0x00000000,0x00000000,0xD0004000,0xF8009000,0xFFD0FE40,0xFFFDFFF4,0xFFFFFFFF,
0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xEAAAFFFF,
0xFFFF7FFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x00010000,0x001F0007,0x02FF00BF,0x2FFF0BFF,
0x00000000,0x00000000,0x00000000,0xF9009000,0x00000000,0xF9009000,0xFFF9FF90,0xFFFFFFFF,
0xFFF9FA40,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x1BFF016F,0xFFFFBFFF,0xFFFFFFFF,0xFFFFFFFF,
0x00000000,0x001B0001,0x02FF007F,0x2FFF0BFF,0x00000000,0xD0004000,0xFD00F400,0xFF40FE00,
0xFFFDFFF4,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xE555FFFF,
0x00020000,0x007F000B,0x0BFF01FF,0xFFFF7FFF,0x00000000,0x00000000,0x00000000,0x00010000,
0x00000000,0x00000000,0x00000000,0xF4008000,0x00000000,0xFE009000,0xFFF9FFD0,0xFFFFFFFF,
0x00000000,0xFFFF5AAA,0xFFFFFFFF,0xFFFFFFFF,0x00000000,0x000A0000,0x07FF00BF,0xBFFF2FFF,
0xF800F400,0xFF40FE00,0xFFD0FF80,0xFFF4FFF0,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x1FFF2FFF,
0x7FFF7FFF,0x2FFF3FFF,0x1FFF1FFF,0x00000A95,0x00004000,0x00000000,0x00000000,0x00004000,
0xFFFDFFFF,0xFFFEFFFD,0xFFFFFFFE,0xFE41FFFF,0x00070001,0x007F001F,0x0BFF02FF,0xFFFF6FFF,
0x00000000,0x00000000,0x00000000,0xFFFF0555,0x00000000,0x00000000,0x00000000,0xAAAF0000,
0x00000000,0x00000000,0x00000000,0x555A0000,0x00000000,0x00000000,0x00000000,0x00150000,
0xFFF9FF90,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xBFFFFFFF,0x7FFF7FFF,
0xFFFFFFFF,0xFFFFFFFF,0x5540FFFF,0x00000000,0xFFFFFFFF,0xFFFFFFFF,0xFFF9FFFF,0xFFC0FFE0,
0xFFFFBFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x00020000,0x000F0007,0x003F002F,0x00FF00BF,
0xFFE0FFC0,0xFFF4FFF0,0xFFFCFFF8,0xFFFEFFFD,0x3FFF3FFF,0x3FFF3FFF,0x296F7FFF,0x00020001,
0x8000C000,0x8000C000,0x80008000,0x00004000,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xF400F955,
0x006F000B,0x0BFF01FF,0xFFFF6FFF,0xFFFFFFFF,0x00000000,0x00000000,0xFFFF0555,0xFFFFFFFF,
0x00000000,0x00000000,0x5AAB0000,0xFFFFFFFF,0x00000000,0x00000000,0x01550000,0xFFFFFFFF,
0x00000000,0x00000000,0x00000000,0xFFFF56AA,0x00000000,0x00000000,0xE0008000,0xFFFFF955,
0xFF80FE00,0xFFFDFFE4,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xAAAFFFFF,0x001F001F,
0xFFFFFFFF,0xFFFFFFFF,0xFFFEFFFF,0xFFF4FFF4,0x000F0007,0x00BF002F,0x03FF01FF,0x1FFF0BFF,
0x00000000,0x00000000,0x40004000,0x80008000,0xFFFDFFF8,0xFFFFFFFE,0xFFFFFFFF,0xFFFFFFFF,
0x07FF0BFF,0x02FF07FF,0x02FF01FF,0x5BFF03FF,0xD000F800,0xF000E000,0xF800F400,0xFD00FC00,
0xFFFFFFFF,0xFFFFFFFF,0x003F55BF,0x02FF00BF,0xFFFFFFFF,0xEFFFFFFF,0x00004555,0x00000000,
0xFFFFBFFF,0xFFFFFFFF,0x0000F950,0x00000000,0xFFFF6AAA,0xFFFFFFFF,0xFF95FFFF,0xFFE4FF80,
0xFFFF5555,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFF90,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0xFFFFFFFF,0xFFFFFFFF,0x01FF57FF,0x00BF01FF,0x3FFF7FFF,0x1FFF2FFF,0x04001FEA,0x00000000,
0xFFD0FFD0,0xFFE0FFE0,0x96A0FFF0,0x00000000,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFE4FFF8,
0x02FF01FF,0x07FF03FF,0x0BFF0BFF,0x1FFF1FFF,0xFFFEFFFE,0xFFFFFFFE,0xFFFEFFFF,0xFFFEFFFE,
0x00020002,0x00020002,0x055B0003,0xFFFFBFFF,0xF000F400,0xE000F000,0xF000E000,0xFFFEF555,
0xFFFFFFFF,0x000B5547,0x01FF006F,0xFFFF5BFF,0xFFFFFFFF,0x00009551,0x00000000,0xEAFF4001,
0xFFFFFFFF,0xFFD0FFFA,0xFFF8FFE0,0xFFFFFFFE,0xFFFFFFFF,0x6BFFFFFF,0x07FF07FF,0x0BFF07FF,
0x002F002F,0x0015002F,0x00000000,0x00000000,0xFFF4FFF4,0xFFF4FFF4,0x80009550,0x40004000,
0x7FFF2FFF,0xBFFF7FFF,0xFFFFFFFF,0xFFFFFFFF,0xC0008000,0xC000C000,0x80018001,0x40024002,
0x001F001F,0x0007000B,0x000B0007,0x055F001F,0xFE005400,0xFF80FF40,0xFFD0FFC0,0xFFF4FFE0,
0xFFFFFE55,0xBFFFFFFF,0x0FFF2FFF,0x07FF07FF,0xFEBFFFFF,0x4000D006,0x00000000,0x00000000,
0xFFFFFFFF,0xFFFFFFFF,0xFFFCFFFE,0xFFF8FFF8,0x6FFF0BFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0x00000000,0xFFFFAAFF,0xFFFFFFFF,0xFFFFFFFF,0xE0004000,0xFFFFFE5A,0xFFFFFFFF,0xFFFFFFFF,
0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x4007EABF,0x007F00BF,0x002F007F,0x001F002F,0xAFFF001F,
0xFF80FF80,0xFFD0FFD0,0xFFE0FFE0,0xFFF4FFF0,0x2FFF2FFF,0x7FFF3FFF,0x7FFF7FFF,0x7FFF7FFF,
0xFFFDFFFE,0xFFF8FFFD,0xFFF4FFF8,0xFFD0FFE0,0x00010001,0x00010001,0xAAAB4002,0xFFFFFFFF,
0xFFFDFFFE,0xFFFEFFFD,0xFFFFFFFF,0xFFFFFFFF,0x007F06FF,0x001F002F,0x001F001F,0x007F002F,
0xFFE0FFF9,0xFF80FFC0,0xFF40FF40,0xBF80FF40,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xF900FFAB,
0xFFFFFFFF,0x5BFFFFFF,0x01FF02FF,0x00FF00FF,0x0BFF0BFF,0xFFF55FFF,0xFF40FFD0,0xFE00FE00,
0x00000000,0x007F0005,0x00FF00BF,0x01FF01FF,0x40004000,0xE5408000,0xFF80FFC0,0xFF80FF40,
0x00030003,0x00070007,0x00030007,0x00020003,0xFFFEFFFF,0xFFF8FFFD,0xFFF8FFF8,0xFFF8FFF8,
0x07FF07FF,0x2FFF0FFF,0xFFFFBFFF,0xFFFFFFFF,0x00000000,0xD0004000,0xFFEBF900,0xFFFFFFFF,
0xAFFEFFFD,0x007F01FF,0x000B001F,0x00030007,0xFFFAFFFF,0xFF40FFD0,0xFC00FD00,0xF800F800,
0xFFFFFFFF,0xFFFFFFFF,0xBFFFFFFF,0x07FF1FFF,0xFFFFFFFF,0xFFFFFFFF,0xF905FFFF,0x4000D000,
0x2FFFBFFF,0x0BFF1FFF,0x07FF07FF,0x0FFF0BFF,0xFFF0FFF8,0xFFC0FFD0,0xFFC0FFC0,0xFFE0FFD0,
0x002F003F,0x001F001F,0x001F001F,0x001F001F,0xD0004000,0xE000D000,0xF400F400,0xF800F800,
0xFFFF5695,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFF9,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0x7FFF7FFF,0x3FFF3FFF,0x2FFF2FFF,0x0FFF1FFF,0xFF40FFC0,0xFD00FF00,0xF400FC00,0xE000F400,
0x5BFF01FF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x1FFD2FE0,0x0FFF0FFF,0x2FFF1FFF,0xFFFF7FFF,
0xD000E000,0x8000C000,0xC0008000,0xF902E000,0x00BF57FF,0x001F002F,0x001F001F,0x007F002F,
0x01F801FF,0x1FD007E0,0xFFC0FFC0,0xFFD0FFC0,0xFE00FE00,0xFFD0FF40,0xFFFFFFFE,0xFFFFFFFF,
0x56FF01FF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFF5FFD0,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0xFFFFFFFF,0xBFFFFFFF,0x2FFF7FFF,0x07FF0FFF,0x00010002,0x00000000,0x00000000,0x40004000,
0xFFFCFFF8,0xFFFDFFFD,0xFFFEFFFE,0xFFFFFFFF,0x00070003,0x001F000B,0xEBFF007F,0xFFFFFFFF,
0xFE00FC00,0xFFD0FF40,0xFFFFFFF9,0xFFFFFFFF,0x00FF01FF,0x00BF00BF,0x00FF00BF,0x07FF01FF,
0x00000000,0x00000000,0x00000000,0xE0008000,0x7FFD1FFE,0xFFFDFFFC,0xFFFEFFFD,0xFFFFFFFF,
0x00000000,0xFFFFE406,0xFFFFFFFF,0xFFFFFFFF,0xFFFEFFF8,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0xFFFF556F,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFD05,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0x07FF0BFF,0x02FF03FF,0x00BF01FF,0x002F007F,0xD000D000,0xC000C000,0x80008000,0x40008000,
0xFFFFFFAF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFEFFF4,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0x03FF07FF,0x03FF03FF,0x03FF03FF,0x07FF07FF,0xD0008000,0xE000D000,0xF800F400,0xFE00FD00,
0xFFFF1FFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFEAF900,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0xFFFFFFFF,0xFFFFFFFF,0x1FFF7FFF,0x02FF0BFF,0x0007000F,0x00000002,0x00000000,0x00000000,
0x40004000,0x40004000,0x40004000,0x40004000,0x07FF07FF,0x0BFF0BFF,0x4FFF0FFF,0xFFFFEFFF,
0xFF80FF40,0xFFF8FFE0,0xFFFFFFFD,0xFFFFFFFF,0x007F00FF,0x000F002F,0x00030007,0x00010001,
0x06FFBFFF,0x000B005F,0x000B000B,0x001F000F,0xFFFDFFFE,0xFFFDFFFD,0xFFFCFFFC,0xFFF8FFF8,
0xEFFFEBFF,0xAFFF9FFF,0x3FFF6FFF,0xBFFF7FFF,0x766A6565,0xAAAAAAAA,0xF59EB59E,0xE99FE99E,
0xEE9EFEA9,0x9DDEDDDE,0xA9DD9DDE,0x5ADDA9DD,0xA9FAF5FA,0x9DF79DF7,0x95F795F7,0xAAF6AAF6,
0xF7A5FBE9,0xF9AAFAAA,0xFDDDF8E9,0xFADDFDD9,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x0FFF9FFF,
0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFF94FFFF,0x7DBFBDBF,0xDEBF9EBF,0xB67FE67F,0x7D7F787F,
0xA4B2FFFA,0xDB399A76,0xF39DE76C,0x7E5BB95E,0xFF95FFFF,0x6CF67992,0x9E7C5DB9,0xDB6ECF7D,
0xFFFFFFFF,0x8FEFEFFF,0xD7D7DBDF,0xF3D5E7D3,0xFFFFFFFF,0xF57FFFFF,0xE75FE62F,0x76CFB39F,
0xFFFFFFFF,0xFFFFFFFF,0xF66CF781,0x779EB75D,0xFFFFFFFF,0xFFFFFFFF,0xFFF9FFFA,0xFFFEFFFD,
0x7FFFBFFF,0x3FFF7FFF,0x1FFF2FFF,0x0FFF1FFF,0x40004000,0x80008000,0xD000C000,0xE000D000,
0x001F001F,0x002F001F,0x002F002F,0x003F003F,0xFFF4FFF8,0xFFF4FFF4,0xFFF0FFF0,0xFFE0FFE0,
0xFFFFDD9F,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFEBFA96D,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0xEBAA9695,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFAE7FADA,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0x1FFF1FFF,0x1FFF1FFF,0x2FFF1FFF,0x2FFF2FFF,0x4000E400,0x00000000,0x00000000,0x00000000,
0xFFFEFFFF,0xFFF4FFFC,0xFFF0FFF4,0xFFE0FFE0,0xFFFFFFFF,0x06FFFFFF,0x007F00BF,0x001F002F,
0xFFFFFFFF,0x0000AAAF,0x00000000,0x00000000,0xFFFFFFFF,0xF800FFFF,0xFD00FC00,0xFF00FE00,
0x6F7F6E3F,0xDFFF9FBF,0xFFFFFFFF,0xFFFFFFFF,0x6EB77E67,0x9D766DB7,0xFFFFDFFF,0xFFFFFFFF,
0x739FE75E,0x19DB76CF,0xEBBF994B,0xFFFFFFFF,0xF9DAF6D9,0xFDA1F8EB,0xE467FD66,0xFFFFFAFF,
0x6C57398B,0x9DB65CF3,0xDB25CE75,0xAFFF4B95,0xD2DB57CF,0xF2E3E2E7,0xF9F5F5F6,0xFDBEFCF8,
0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFF4BFFCF,0x0BFF0BFF,0x07FF07FF,0x03FF07FF,0x03FF03FF,
0xF400F000,0xF800F400,0xFC00F800,0xFD00FD00,0x007F007F,0x007F007F,0x007F007F,0x007F007F,
0xFFD0FFE0,0xFFD0FFD0,0xFFC0FFD0,0xFF80FF80,0x2FFF2FFF,0x3FFF3FFF,0x3FFF3FFF,0x3FFF3FFF,
0xFFD0FFD0,0xFFC0FFD0,0xFF40FF80,0xFF40FF40,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x7FFFBFFF,
0x000B001F,0x00020007,0x00010001,0x00000000,0xFF40FF40,0xFFC0FF80,0xFFD0FFD0,0xFFF0FFE0,
0xFFFFFFFF,0xFFFFFFFF,0xBFFFFFFF,0x7FFFBFFF,0xF803FD07,0xD001E002,0x00004001,0x00000000,
0xFFFFFFFF,0xFFFFFFFF,0xFFFDFFFF,0x4000A540,0x03FF03FF,0x02FF03FF,0x02FF02FF,0x01FF02FF,
0xFE00FE00,0xFF00FE00,0xFF00FF00,0xFF40FF00,0xFF40FF80,0xFF40FF40,0xFF00FF40,0x0000B900,
0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x0000AAAA,0xFFFFFFFF,0xFFFFFFFF,0x6FFFFFFF,0x000006AA,
0x2FFF3FFF,0x01BF1FFF,0x0000001B,0x00000000,0xFF00FF00,0xFF80FF40,0xFFE0FFD0,0xFFF4FFF0,
0x1FFF2FFF,0x0BFF0FFF,0x02FF07FF,0x00FF01FF,0xFFF4FFF4,0xFFF8FFF8,0xFFFCFFF8,0xFFF8FFFD,
0x2FFF3FFF,0x0FFF1FFF,0x07FF0BFF,0x02FF07FF,0xC0008000,0xD000D000,0xE000E000,0xF400F400,
0x01FF01FF,0x01FF01FF,0x02FF01FF,0x02FF02FF,0xFF00FF40,0xFF00FF00,0xFF00FF00,0xFE00FF00,
0x00000000,0x00000000,0x40004000,0xD0008000,0xFFFCFFF8,0xFFFEFFFD,0xFFFFFFFF,0xFFFFFFFF,
0x007F00BF,0x001F002F,0x000B000F,0x00020007,0xFF80FFE0,0xFD00FF40,0xD000F400,0x00004000,
0x01FF02FF,0x00BF00FF,0x003F007F,0x001F002F,0xF800F400,0xFC00F800,0xFD00FD00,0xFE00FE00,
0x03FF03FF,0x07FF07FF,0x0BFF07FF,0x0BFF0BFF,0xFE00FE00,0xFE00FE00,0xFD00FD00,0xFD00FD00,
0xE000D000,0xF400F000,0xF800F400,0xFD00FC00,0xBFFFFFFF,0x3FFF7FFF,0x1FFF2FFF,0x0FFF0FFF,
0xFA90FFF8,0x00004000,0x00000000,0x00000000,0xFFFFFFFF,0x5000FEA5,0x00000000,0x00000000,
0xFFFFFFFF,0xFFE9FFFF,0x00005400,0x00000000,0xFFFFFFFF,0xFFFFFFFF,0x9500FFFA,0x00000000,
0xFFFFFFFF,0xFFFFFFFF,0xFFFEFFFF,0x0000A540,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xE954FFFF,
0x000F001F,0x0007000B,0x00020003,0x00010001,0xFF00FE00,0xFF40FF40,0xFF40FF40,0xFF80FF80,
0x1FFF0FFF,0x1FFF1FFF,0x2FFF1FFF,0x2FFF2FFF,0xF800FC00,0xF400F800,0xF400F400,0xE000E000,
0xFD00FD00,0xFE00FE00,0xFF00FE00,0xFF00FF00,0x0FFF0FFF,0x0BFF0FFF,0x0BFF0BFF,0x07FF07FF,
0x4000FA55,0x00000000,0x00000000,0x00000000,0xFEA5FFFF,0x00005000,0x00000000,0x00000000,
0x7FFFBFFF,0x00002FA9,0x00000000,0x00000000,0xFFC0FF80,0xFFD0FFD0,0xFFE0FFD0,0xFFE0FFE0,
0x2FFF2FFF,0x2FFF2FFF,0x2FFF2FFF,0x1FFF1FFF,0xD000D000,0x8000C000,0x00004000,0x00000000,
0xFF40FF00,0xFF40FF40,0xFF40FF40,0xFF40FF40,0x03FF07FF,0x01FF02FF,0x00FF01FF,0x00BF00BF,
0xFFF4FFF0,0xFFF4FFF4,0xFFF8FFF8,0xFFFDFFFC,0x1FFF1FFF,0x0FFF1FFF,0x0BFF0BFF,0x07FF0BFF,
0xFFF8FFFC,0xFFF0FFF4,0xFFD0FFE0,0xFF80FFC0,0xFF00FF00,0xFF00FF00,0xFE00FF00,0xFE00FE00,
0x003F007F,0x001F002F,0x000B001F,0x0007000B,0x00000000,0x00000000,0x40000000,0x80004000,
0xFFFDFFFD,0xFFFEFFFE,0xFFFFFFFF,0xFFFFFFFF,0x03FF07FF,0x02FF02FF,0x01FF01FF,0x00BF00FF,
0xFF00FF40,0xFD00FE00,0xF800F800,0xE000F400,0x00BF00BF,0x00BF00BF,0x00BF00BF,0x007F007F,
0xFE00FE00,0xFD00FD00,0xFD00FD00,0xFD00FD00,0xFFFFFFFF,0x2FFFBFFF,0x02FF0BFF,0x0007006F,
0x00010003,0x00000000,0x00000000,0x00000000,0xC0008000,0xD000D000,0xE000D000,0xF000E000,
0x007F00BF,0x002F007F,0x001F002F,0x000B000F,0x8000D000,0x00000000,0x00000000,0x00000000,
0xFFFFFFFF,0xFFFDFFFF,0xFE40FFE4,0x00005400,0xFFFFFFFF,0x7FFFFFFF,0x01BF1BFF,0x00000005,
0x000B001F,0x00000002,0x00000000,0x00000000,0xF800FC00,0xE000F400,0x8000D000,0x00000000,
0xFFFFFFFF,0xFFFFFFFF,0x7FFFBFFF,0x0BFF1FFF,0x00020003,0x00010001,0x00000000,0x00000000,
0xF400F400,0xF800F800,0xFC00FC00,0xFD00FD00,0xFFFFFFFF,0xFFFFFFFF,0xBFFFFFFF,0x3FFF7FFF,
0x00030007,0x00010002,0x00000001,0x00000000,0xFFE0FFF4,0xF900FF40,0x00009000,0x00000000,
0xFFFFFFFF,0xFFFFFFFF,0x00001BFE,0x00000000,0x007F02FF,0x0001001F,0x00000000,0x00000000,
0xFE00FE00,0xFF40FF00,0xFF40FF40,0xFF80FF80,0x1FFF2FFF,0x07FF0BFF,0x01FF02FF,0x007F00BF,
0xFFD0FFC0,0xFFD0FFD0,0xFFE0FFE0,0xFFF4FFF0,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x3FFFBFFF,
0x001F002F,0x0007000B,0x00010002,0x00000000,0xFFF4FFF4,0xFFF8FFF8,0xFFFDFFFC,0xFFFDFFFD,
0x0BFF1FFF,0x02FF07FF,0x007F00FF,0x001F002F,0xFFFDFFFD,0xFFF4FFF8,0xFFD0FFE0,0xFF00FF80,
0xFFFFFFFF,0xBFFFFFFF,0x2FFF7FFF,0x07FF1FFF,0x0007000B,0x00000001,0x00000000,0x00000000,
0x00000000,0x00000000,0x00030000,0xC00F0003,0x00000000,0x00000000,0x00330000,0x00330033,
0x00000000,0x00000000,0xFFFC0000,0x03000300,0x00000000,0x00000000,0xFF0C0000,0x030C030C,
0x00000000,0x00000000,0x030F0000,0x03300330,0x00000000,0x00000000,0x30000000,0xCC003000,
0x00000000,0x00000000,0x00C00000,0x030000C0,0x00000000,0x00000000,0xFFCC0000,0x00C300CC,
0x00000000,0x00000000,0xFFC30000,0x00C000C0,0x00000000,0x00000000,0x00030000,0x000C000C,
0x00000000,0x00000000,0x03000000,0x03000300,0x00000000,0x00000000,0x30000000,0x30003000,
0x00000000,0x00000000,0x00000000,0x00C000C0,0x00000000,0x00000000,0x00A00000,0x00200020,
0x00000000,0x00000000,0x20000000,0x20002000,0x00000000,0x00000000,0x00200000,0x00000000,
0x00000000,0x00000000,0x80000000,0x00002000,0x00000000,0x00000000,0xA80A0000,0x02200220,
0x00000000,0x00000000,0xA2000000,0x020202A2,0x00000000,0x00000000,0x802A0000,0x00080020,
0x00000000,0x00000000,0x00020000,0x00020002,0xF400FD00,0x4000E000,0x00000000,0x00000000,
0xFFFFFFFF,0xFFFFFFFF,0xFFD0FFFD,0x0000E900,0xFFFFFFFF,0xFFFFFFFF,0x7FFFFFFF,0x000006BF,
0x00FF02FF,0x001F007F,0x00000006,0x00000000,0x30333033,0x03030CC3,0x00030303,0x00000000,
0x00330033,0x00330033,0xFFC30033,0x00000000,0x00330033,0x00330033,0xFFF00033,0x00000000,
0x03000300,0x03000300,0x03000300,0x00000000,0xFF0C030C,0x030C030C,0x030C030C,0x00000000,
0x030F0330,0x03000300,0xFF000300,0x00000000,0x0300CC00,0xFF000300,0x00CF00C0,0x00000000,
0x3003CC00,0x30033003,0x300C300C,0x00000000,0xFFC000C0,0x00C000C0,0xFFC000C0,0x00000000,
0xFFC000C0,0x00C000C0,0x00C300C0,0x00000000,0x3003C00C,0x000CC00C,0xC00C300C,0x00000000,
0x0F30F30F,0x030C0303,0x030F0330,0x00000000,0xC00C3F03,0xC0CCFF0C,0xFF0CC0CC,0x00000000,
0x300C3FF0,0x300C300C,0x3FF0300C,0x00000000,0x330330FC,0x33033303,0xC0FCC303,0x00000000,
0x030C030C,0x03330333,0x00C000C0,0x00000000,0xCC00C3F0,0xCC0CCFF0,0xCFF0CC0C,0x00000000,
0x00C003CF,0x00C000C0,0x030000C0,0x00000000,0x00200020,0x00200020,0x00200020,0x00A00020,
0x0202A82A,0x0202AA02,0xA8020202,0x00000000,0x80A22A20,0x80208022,0x80208022,0x00000000,
0x20082AA0,0x20082008,0x2AA02008,0x00000000,0x2202A0A8,0x200222AA,0x20A82202,0x00000000,
0x28208822,0x08200820,0x08200820,0x00000000,0x0220A80A,0x02200220,0xA8200220,0xAA000000,
0x0008000A,0x80080008,0xA008200A,0x00020008,0x02080220,0x02000202,0xA82A0200,0x00000000,
0x02020202,0x82020202,0x82008202,0x00000000,0x00020008,0x00000002,0x00000000,0x80000000,
0x00020002,0x00020002,0x00020002,0x00020002,0x00000000,0x00000000,0x40000000,0xFF40F800,
0x00000000,0xA5000000,0xFFFFFFE4,0xFFFFFFFF,0x00000000,0x5ABA0000,0xFFFFFFFF,0xFFFFFFFF,
0x00000000,0x00000000,0x00BF001B,0x1FFF07FF,0x00000000,0x00000000,0x00000000,0xFFFA5540,
0x00000000,0x00000000,0x00000000,0x5AFF0015,0x00000000,0x00000000,0x00000000,0x80000000,
0x00000000,0x50000000,0xFFE0FE00,0xFFFFFFFD,0x00000000,0xFFFE5540,0xFFFFFFFF,0xFFFFFFFF,
0x00000000,0x016B0000,0xFFFF1BFF,0xFFFFFFFF,0x00000000,0x00000000,0x00060000,0x01FF002F,
0x00000000,0xE4008000,0xFF40FD00,0xFFF4FFD0,0xFFFDFFE4,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xEAABFFFF,0x00010000,0x001F0007,0x01FF007F,0x1FFF07FF,
0xFFF9FE40,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x00BF0006,0x6FFF07FF,0xFFFFFFFF,0xFFFFFFFF,
0x00000000,0x00000000,0x00070001,0x007F001F,0xF800E000,0xFF40FE00,0xFFF4FFD0,0xFFFDFFF8,
0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x55BFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFF95FFFF,
0x00000000,0x000B0001,0x01FF006F,0x7FFF0BFF,0x00000000,0x80000000,0xFE40F800,0xFFF8FFD0,
0x00000000,0xFFFFAA94,0xFFFFFFFF,0xFFFFFFFF,0x00000000,0x06FF005A,0xFFFFBFFF,0xFFFFFFFF,
0x00000000,0xC0004000,0xF407E000,0xFEFFF82F,0xFFFEFFF8,0xFFFFFFFF,0xFFFFFFFF,0xBFFFFFFF,
0xFFFFFFFF,0xBFFFFFFF,0x7FFF7FFF,0x00002A51,0x00010001,0x00000000,0x00000000,0x00000000,
0xFFF4FFFE,0xFFFCFFF8,0xFFFDFFFD,0xFF40FFFE,0x00000000,0x000B0002,0x00BF002F,0xFFFF56FF,
0x00000000,0x00000000,0x00000000,0xFFFF0055,0x00000000,0x00000000,0x00000000,0x6AAA0000,
0x00000000,0x00000000,0x00000000,0x15550000,0x00000000,0xF4004000,0xFFE4FE40,0xFFFFFFFE,
0xFFF8FF80,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x0BFFFFFF,0x03FF03FF,
0xFFFFFFFF,0xFFFFFFFF,0xE554FFFF,0x00004000,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFEFFFE,
0x02FF00BF,0x0BFF07FF,0x2FFF1FFF,0xFFFF7FFF,0x40000000,0xD000C000,0xF000E000,0xF400F400,
0xFFFFFFFF,0xFFFFFFFF,0x6FFFFFFF,0x02FF02FF,0x00FF00BF,0x00FF00FF,0x00A900FF,0x00000000,
0xFE00FE00,0xFE00FE00,0xFE00FE00,0x00005500,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFF80FFE5,
0x000B0001,0x02FF007F,0xFFFF6BFF,0xFFFFFFFF,0x00000000,0x00000000,0x6AAB0000,0xFFFFFFFF,
0x00000000,0x00000000,0x05550000,0xFFFFFFFF,0x00000000,0x00000000,0x00000000,0xFFFF6AAB,
0x00000000,0x00000000,0x00000000,0xFFFF8555,0xE0004000,0xFF40F900,0xFFFDFFE0,0xFFFFFFFF,
0xFFFFFFFF,0xFFFFFFFF,0xABFFFFFF,0x07FF07FF,0xFFFFFFFF,0xFFFFFFFF,0xFFAAFFFF,0xFD00FD00,
0x3FFF7FFF,0x1FFF2FFF,0x0BFF0BFF,0x7FFF2FFF,0xE000F900,0xF400F000,0xFC00F800,0xFE00FD00,
0xFFFFFFFF,0xFFFFFFFF,0x00005556,0x00070001,0xFFFFFFFF,0xFFFBFFFF,0x00001441,0x00000000,
0xFFFFAABF,0xFFFFFFFF,0xF540FFFE,0xF900F000,0xFFFF555A,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0xFFFFFE45,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x002FA57F,0x000F001F,
0x01FF02FF,0x00FF01FF,0x005000BE,0x00000000,0x40000000,0x80004000,0x8000C000,0x00000000,
0xFFFFFFFF,0xFFFFFFFF,0xFF96FFFF,0xE400F800,0x00070002,0x000F000B,0x002F001F,0x007F003F,
0xF800F800,0xF800F800,0xF800F800,0xF800F800,0x03FF03FF,0x03FF03FF,0x5BFF07FF,0xFFFFFFFF,
0x00000000,0x00000000,0x00150000,0x02FF01FF,0x00000000,0x00000000,0x00000000,0xFC005400,
0xFF80FF80,0xFF40FF40,0xFF40FF40,0xFFFFFF95,0xFFFFFFFF,0x00009545,0x00000000,0xABFF0001,
0xFFFFFFFF,0xFF40FFEA,0xFFE4FF80,0xFFFFFFFD,0xFFFFFFFF,0xFFFFFFFF,0xBFFFBFFF,0xFFFFFFFF,
0x0BFF0BFF,0x055A0BFF,0x00000000,0x00000000,0xFD00FD00,0xFD00FD00,0x00005400,0x00000000,
0xFFFFFFFF,0xFFFFFFFF,0xFFF4FFF9,0xFFF4FFF4,0x001F002F,0x000B000B,0x000F000B,0x057F002F,
0xFE005400,0xFF80FF00,0xFFD0FFD0,0xFFF4FFE0,0xFFFFFF95,0x1FFFBFFF,0x02FF07FF,0x00BF01FF,
0xFFEFFFFF,0xF400FD01,0xC000D000,0xC0008000,0x007F001F,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0x00000000,0xFFFF96AA,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x9006FAAF,
0x0007000B,0x00020007,0x00070002,0x5AFF0007,0xC0008000,0xE000D000,0xF400E000,0xF800F400,
0x00BF007F,0x00FF00BF,0x00FF00FF,0x01FF01FF,0x03FF02FF,0x03FF03FF,0xAFFF07FF,0xFFFFFFFF,
0xF800FC00,0xFC00F800,0xFEAAFD00,0xFFFFFFFF,0x0007906F,0x00010001,0x00010000,0x00070002,
0xFFFEFFFF,0xFFF4FFF8,0xFFF4FFF4,0x1FF8BFF4,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFF40FFEA,
0xFFFFFFFF,0xBFFFFFFF,0x0BFF1FFF,0x07FF07FF,0xFFFFFFFF,0xFF51FFFF,0xF400FD00,0xE000E000,
0x00010001,0x1FFF0056,0x2FFF2FFF,0x3FFF3FFF,0x00000000,0x50000000,0xF000F400,0xE000E000,
0xFFE0FFF0,0xFFE6FFD0,0xFFFFFFFF,0xFFFFFFFF,0x00BF00BF,0x03FF01FF,0xBFFF1BFF,0xFFFFFFFF,
0xE000D000,0xFE00F800,0x2FFE7F90,0x0FFF1FFF,0xFABFFFFF,0x00018007,0x00000000,0x00000000,
0xFFFFFFFF,0xFFFEFFFF,0xFFF4FFF8,0xFFF8FFF4,0xFFFFFFFF,0xFFFFFFFF,0xF906FFFF,0x4000D000,
0x1FFF7FFF,0x03FF0BFF,0x02FF02FF,0x03FF02FF,0xFFFDFFFF,0xFFF4FFF8,0xFFF8FFF4,0xFFFEFFFC,
0xBFFFFFFF,0x2FFF3FFF,0x2FFF2FFF,0xBFFF7FFF,0xFF805500,0xFFD0FFC0,0xFFF4FFF0,0xFFF8FFF8,
0x00FF00FF,0x00BF00FF,0x007F00BF,0x003F007F,0xFFFCFFFE,0xFFF0FFF4,0xFFC0FFD0,0xFF40FF80,
0xD5BF001F,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x02FF07FE,0x01FF01FF,0x03FF02FF,0x6FFF0BFF,
0xF800FD00,0xF000F400,0xF400F000,0xFF40FD00,0x02FF5BFF,0x007F00BF,0x007F007F,0x01FF00BF,
0x0FE00BF9,0xBF402F80,0xFE00FE00,0xFF40FF00,0xF000E000,0xFE01F400,0xFFFFFFEB,0xFFFFFFFF,
0x0FFF0FFF,0x7FFF1FFF,0xFFFFFFFF,0xFFFFFFFF,0x00000000,0xD0004000,0xFFABF901,0xFFFFFFFF,
0xFFFDFFF8,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x01FF03FF,0x00FF01FF,0x01FF00FF,0x07FF02FF,
0x00000000,0x00000000,0x40000000,0xF400D000,0x1FFD0BFE,0xFFFEBFFD,0xFFFFFFFF,0xFFFFFFFF,
0xD0004000,0xFFFFF901,0xFFFFFFFF,0xFFFFFFFF,0xFFFF0555,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0x001F002F,0x000B000F,0x00020007,0x00000001,0xFE00FF40,0xFE00FE00,0xFD00FD00,0xFD00FD00,
0xFFFFFFEB,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x6FFF07FF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0xFFEAFE40,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x2FFF7FFF,0x07FF1FFF,0x01FF02FF,0x002F007F,
0xFFFFFFFF,0x7FFFFFFF,0x1FFF2FFF,0x07FF0BFF,0x0003000B,0x00000001,0x00000000,0x00000000,
0xFE00FE00,0xFE00FE00,0xFF00FF00,0xFF40FF00,0xFFFFFFFF,0x6FFFFFFF,0x1FFF1FFF,0x1FFF1FFF,
0x1BFFFFFF,0x001501BF,0x00000000,0x00000000,0xFFFDFFFE,0xFFFCFFFC,0xFFF8FFF8,0xFFF8FFF8,
0xADFFADFF,0xDBFFAAFF,0xD7FFD7FF,0xDFFFDBFF,0xA9DD595D,0x6A9AA9D9,0x7D6A7D6A,0x7AA67DAA,
0xEF77FFBA,0xCB77DB77,0xAAA7DA67,0x56ABAAAB,0x99FAE5FE,0x9DFA9DFA,0x99F795F6,0xAAF6A9F7,
0xEB59FFBA,0xF5DDF69D,0xF6DDF5DD,0xF7DDF7DD,0xFFFFFFFF,0xFFFFFFFF,0xBFFFFFFF,0xBFFF7FFF,
0xFFFFFFFF,0xFFFFFFFF,0xFFFEFFFF,0xF800FE50,0x7FFFBFFF,0x7FFF7FFF,0x6FFF7FFF,0x5FFF6FFF,
0x1D9EFEAE,0xDA779D9B,0x676DE77A,0xD5DF529E,0xF969FFFF,0xDF799925,0xE79EDB6D,0x76DBB7DF,
0xFFFFFFFF,0x7EF6FEF7,0x6E3D7E79,0xDF5E9F1D,0xFFFFFFFF,0xE5FEFFFF,0xDB7FC97F,0x779FA76F,
0xFFFFFFFF,0xFFFFFFFF,0xB669F686,0x6ADE7A9D,0xFFFFFFFF,0xFFFFFFFF,0xFFFDFFFE,0xFFFFFFFE,
0x01FF02FF,0x00BF00FF,0x007F007F,0x002F002F,0xFF80FF40,0xFFC0FF80,0xFFD0FFD0,0xFFF0FFE0,
0x1FFF1FFF,0x1FFF1FFF,0x1FFF1FFF,0x2FFF2FFF,0xFFF4FFF4,0xFFF4FFF4,0xFFF0FFF0,0xFFE0FFE0,
0xFFFFEFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFF7776,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0xFBAF655F,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xEBEA96E6,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,
0xFBEBF7DA,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xBFFFBFFF,0xBFFFBFFF,0xBFFFBFFF,0xFFFFFFFF,
0xFF40FE00,0xFFE0FFD0,0xFFFDFFF8,0xFFFFFFFE,0xFFFFFFFF,0x5FFFFFFF,0x00BF02FF,0x002F007F,
0xFFFFFFFF,0x0000AAFF,0x00000000,0x00000000,0xFFFFFFFF,0xFFF4FFFA,0xFFF8FFF4,0xFFFDFFFD,
0xDFFF9FFF,0xFFFFEFFF,0xFFFFFFFF,0xFFFFFFFF,0xDDA7D9DB,0xDB7ADE77,0xFFFFEFFF,0xFFFFFFFF,
0x6DF779E7,0x9E799DB6,0xBEFF64BD,0xFFFFFFFF,0xE766DB67,0xF684F7A9,0xD49FF99A,0xFFFFEBFF,
0x684B755F,0xDDB79DE7,0xE765DA76,0xAFFF5796,0xE1E7D9DB,0xF9F6F5F7,0xFD7DFDB9,0xFF7FFE7D,
0xFFFFFFFF,0xFFFFFFFF,0xFEFFFFFF,0xD0BFF5FF,0x000F001F,0x000B000B,0x00070007,0x00020003,
0xFFF8FFF4,0xFFFDFFFC,0xFFFEFFFD,0xFFFFFFFF,0x2FFF2FFF,0x2FFF2FFF,0x2FFF2FFF,0x2FFF2FFF,
0xFFD0FFE0,0xFFD0FFD0,0xFFD0FFD0,0xFFC0FFC0,0x002F001F,0x00BF007F,0x01FF00FF,0x03FF02FF,
0x00000000,0x80004000,0xD000C000,0xE000E000,0x007F407F,0x001F002F,0x000B001F,0x00070007,
0xFFF8FFFF,0xFFD0FFE0,0xFFF0FFE0,0xFFF8FFF4,0xFFFFFFFF,0xFFFFFFFF,0x7FFFBFFF,0x3FFF7FFF,
0x40004000,0x80008000,0x80008000,0xC000C000,0xFF80FF80,0xFF40FF80,0xFF40FF40,0x0000BE00,
0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x40006AAA,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFE,
0x07FF07FF,0x0BFF0BFF,0x1FFF1FFF,0x2FFF1FFF,0xF400F000,0xF800F400,0xFC00F800,0xF800FC00,
0xFFFFFFFF,0xBFFFFFFF,0x3FFF7FFF,0x1FFF2FFF,0x00010002,0x00000000,0x80004000,0xD000C000,
0x1FFF2FFF,0x1FFF1FFF,0x1FFF1FFF,0x1FFF1FFF,0xC000C000,0xD000D000,0xC000D000,0xC000C000,
0x1FFF1FFF,0x1FFF1FFF,0x1FFF1FFF,0x0FFF1FFF,0xC0008000,0xE000D000,0xF800F400,0xFD00FC00,
0x3FFF2FFF,0x7FFF7FFF,0x7FFF7FFF,0xBFFFBFFF,0x4000E000,0x00000000,0x00000000,0x00000000,
0xFFFFFFFF,0xFFE4FFFD,0xFE00FF80,0xD000F400,0x0BFF0FFF,0x03FF07FF,0x01FF02FF,0x00BF00FF,
0xC000C000,0x80008000,0x80008000,0x40008000,0x0FFF0FFF,0x0FFF0FFF,0x0FFF0FFF,0x0FFF0FFF,
0xFF00FE00,0xFF80FF40,0xFFD0FF80,0xFFE0FFD0,0x00000000,0x00000000,0x00010001,0x00010001,
0xFFA4FFFE,0x00005400,0x00000000,0x00000000,0xFFFFFFFF,0xA500FFFA,0x00000000,0x00000000,
0xFFFFFFFF,0xFFFEFFFF,0x0000E950,0x00000000,0xFFFFFFFF,0xFFFFFFFF,0xFE95FFFF,0x00005000,
0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0x5400FFA9,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFAFFFF,
0xFE00FD00,0xFF00FE00,0xFF40FF40,0xFF80FF40,0xFFF0FFE0,0xFFF4FFF4,0xFFF8FFF4,0xFFF8FFF8,
0xFFFFFFFF,0xBFFFFFFF,0xBFFFBFFF,0x7FFF7FFF,0x0000A540,0x00000000,0x00000000,0x00000000,
0xFA54FFFF,0x00000000,0x00000000,0x00000000,0xFFFFFFFF,0x00007EA5,0x00000000,0x00000000,
0x00010002,0x00000000,0x00000000,0x00000000,0xFFC0FF80,0xFFD0FFD0,0xFFE0FFE0,0xFFF4FFF0,
0x2FFF2FFF,0x2FFF2FFF,0x1FFF1FFF,0x0FFF1FFF,0xFFF8FFFC,0xFFF4FFF4,0xFFE0FFE0,0xFFC0FFD0,
0xFFFCFFF8,0xFFFCFFFC,0xFFFCFFFC,0xFFFCFFFC,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xF7FFFBFF,
0x2FFF3FFF,0x1FFF2FFF,0x0FFF1FFF,0x07FF0BFF,0xFFF8FFF4,0xFFFCFFF8,0xFFFDFFFD,0xFFFEFFFE,
0x0BFF0FFF,0x07FF0BFF,0x03FF07FF,0x02FF02FF,0xFF40FF80,0xFE00FF00,0xF800FD00,0xF000F400,
0xFFFCFFFC,0xFFFCFFFC,0xFFFCFFFC,0xFFFCFFFC,0xE2FFF3FF,0xE0BFE1FF,0xE03FE07F,0xD01FD02F,
0x02FF07FF,0x01FF02FF,0x00BF00FF,0x007F007F,0x40000000,0x80004000,0xD000C000,0xE000D000,
0x01FF01FF,0x00BF00BF,0x007F007F,0x001F002F,0xD000E000,0x8000C000,0x00004000,0x00000000,
0x0FFF0FFF,0x0FFF0FFF,0x0BFF0BFF,0x07FF0BFF,0xFFF8FFF8,0xFFF8FFF8,0xFFF8FFF8,0xFFF4FFF8,
0x400B800F,0x00030007,0x00010002,0x00000001,0xFFFFFFFF,0xFFFCFFFE,0xFFD0FFF4,0xA400FE40,
0xFFFFFFFF,0xFFFFFFFF,0x2FFFBFFF,0x006B07FF,0x001F002F,0x00020007,0x00000000,0x00000000,
0xF400E000,0xF800F400,0xFC00F800,0xFD00FD00,0x000F001F,0x0007000B,0x00020003,0x00000001,
0xFFF0FFF8,0xFF80FFD0,0xE400FD00,0x00000000,0xFFFFFFFF,0xFFFFFFFF,0x1FFFFFFF,0x00000155,
0x00BF02FF,0x000B002F,0x00000001,0x00000000,0xFFF0FFF4,0xFFC0FFE0,0xFE00FF80,0xF400FD00,
0x7FFFBFFF,0x2FFF7FFF,0x0BFF1FFF,0x01FF07FF,0x7FFFBFFF,0x2FFF3FFF,0x0BFF1FFF,0x03FF07FF,
0xFFFFFFFF,0xFFE0FFFD,0x0000FA40,0x00000000,0xFFFFFFFF,0x1BFFBFFF,0x0000016F,0x00000000,
0x000B006F,0x00000001,0x00000000,0x00000000,0xFFE0FFD0,0xFFF0FFE0,0xFFF4FFF4,0xFFFCFFF8,
0x00FF01FF,0x007F00BF,0x001F002F,0x0007000B,0xFFFFFFFF,0x3FFFBFFF,0x0BFF1FFF,0x02FF07FF,
0xC0008000,0xD000D000,0xE000E000,0xF000F000,0x00BF01FF,0x001F003F,0x0007000B,0x00000002,
0xE000F000,0xD000E000,0x00008000,0x00000000,0x2FFF7FFF,0x0BFF1FFF,0x01FF07FF,0x007F00BF,
0x00000000,0x00000000,0x00300000,0x00F00030,0x00000000,0x00000000,0x03300000,0x033C0330,
0x00000000,0x00000000,0x03300000,0x03300330,0x00000000,0x00000000,0xFFC00000,0x30003000,
0x00000000,0x00000000,0xF0CF0000,0x30C030C0,0x00000000,0x00000000,0x30FF0000,0x33003300,
0x00000000,0x00000000,0x00000000,0xC0000000,0x00000000,0x00000000,0x0C030000,0x300C0C03,
0x00000000,0x00000000,0xFCC00000,0x0C300CC0,0x00000000,0x00000000,0xFC3F0000,0x0C000C00,
0x00000000,0x00000000,0x003F0000,0x00C000C0,0x00000000,0x00000000,0x00030000,0x00030003,
0x00000000,0x00000000,0x00000000,0x0C000C00,0x00000000,0x00000000,0x0A000000,0x02000200,
0x00000000,0x00000000,0x02000000,0x00000000,0x00000000,0x00000000,0x80A80000,0x22002202,
0x00000000,0x00000000,0x200A0000,0x20202A20,0x00000000,0x00000000,0x02AA0000,0x00800200,
0x00000000,0x00000000,0x00280000,0x00200020,0xFF80FFE0,0xF800FE00,0x0000D000,0x00000000,
0xFFFFFFFF,0xFFFFFFFF,0xFFFEFFFF,0x0000FE90,0xFFFFFFFF,0xBFFFFFFF,0x06FF2FFF,0x0000005A,
0x000B001F,0x00000003,0x00000000,0x00000000,0x03300330,0x3030CC30,0x00303030,0x00000000,
0x03330333,0x03300330,0xFC300330,0x00000000,0x03300330,0x03300330,0xFF0F0330,0x00000000,
0x30003000,0x30003000,0x300F3000,0x00000000,0xF0C030C0,0x30C030C0,0x30C030C0,0x00000000,
0x30FF3300,0x30003000,0xF0003000,0x00000000,0x3000C000,0xF0003000,0x0CFF0C00,0x00000000,
0x0030C00C,0x003F0030,0x00C000C0,0x00000000,0xFC030C0C,0x0C030C03,0xFC030C03,0x00000000,
0xFC0F0C00,0x0C000C00,0x0C3F0C00,0x00000000,0x003F00C0,0x00C000C0,0x00C000C0,0x00000000,
0xF30330FC,0x30C0303C,0x30FC3303,0x00000000,0x00C0F03F,0x0CC0F0C0,0xF0C00CC0,0x00000000,
0x00CCFF03,0x00CC00CF,0xFF0F00CC,0x00000000,0x30330FC3,0x30333033,0x0FC33033,0x00000000,
0x30C330C3,0x33333333,0x0C0C0C0C,0x00000000,0xC0003F00,0xC0C0FF00,0xFF00C0C0,0x00000000,
0x0C0C3CFC,0x0C0C0C0C,0x300C0C0C,0x00000000,0x02000200,0x02000200,0x02000200,0x0A000200,
0x202082A0,0x2020A020,0x80202020,0x00000000,0x0A20A20A,0x0200022A,0x020A0220,0x00000000,
0x0088AA02,0x00880088,0xAA080088,0x00000000,0x20220A82,0x00222AA2,0x0A822022,0x00000000,
0x8202822A,0x82028202,0x82028202,0x00000000,0x220280A8,0x22002200,0x82002200,0xA0000000,
0x008000AA,0x00800080,0x008A00A0,0x002A0080,0x20802200,0x20082020,0x82AA2002,0x00000000,
0x20202020,0x20202020,0x200A2020,0x00000000,0x00200080,0x00080020,0x00080008,0x00000000,
0x00200020,0x00200020,0x00200020,0x00280020,
};
//}}BLOCK(VueMasterImage6)
|
the_stack_data/156392444.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_18__ TYPE_9__ ;
typedef struct TYPE_17__ TYPE_8__ ;
typedef struct TYPE_16__ TYPE_7__ ;
typedef struct TYPE_15__ TYPE_6__ ;
typedef struct TYPE_14__ TYPE_5__ ;
typedef struct TYPE_13__ TYPE_4__ ;
typedef struct TYPE_12__ TYPE_3__ ;
typedef struct TYPE_11__ TYPE_2__ ;
typedef struct TYPE_10__ TYPE_1__ ;
/* Type definitions */
typedef scalar_t__ u64 ;
struct rtnl_link_stats64 {scalar_t__ tx_dropped; scalar_t__ rx_dropped; scalar_t__ tx_errors; scalar_t__ rx_errors; scalar_t__ tx_bytes; scalar_t__ rx_bytes; scalar_t__ tx_packets; scalar_t__ rx_packets; } ;
struct TYPE_16__ {int iq; int oq; } ;
struct TYPE_12__ {scalar_t__ fcs_err; scalar_t__ dmac_drop; scalar_t__ fifo_err; scalar_t__ ctl_rcvd; scalar_t__ runts; scalar_t__ total_mcst; scalar_t__ total_bcst; scalar_t__ bytes_rcvd; scalar_t__ total_rcvd; scalar_t__ fwd_rate; scalar_t__ fw_lro_aborts_timer; scalar_t__ fw_lro_aborts_tsval; scalar_t__ fw_lro_aborts_seq; scalar_t__ fw_lro_aborts_port; scalar_t__ fw_lro_aborts; scalar_t__ fw_total_lro; scalar_t__ fw_lro_octs; scalar_t__ fw_lro_pkts; scalar_t__ fw_rx_vxlan_err; scalar_t__ fw_rx_vxlan; scalar_t__ fw_err_drop; scalar_t__ fw_err_link; scalar_t__ fw_err_pko; scalar_t__ frame_err; scalar_t__ l2_err; scalar_t__ jabber_err; scalar_t__ fw_total_bcast; scalar_t__ fw_total_mcast; scalar_t__ fw_total_fwd; scalar_t__ fw_total_rcvd; scalar_t__ red_drops; } ;
struct TYPE_11__ {scalar_t__ runts; scalar_t__ fifo_err; scalar_t__ max_deferral_fail; scalar_t__ max_collision_fail; scalar_t__ multi_collision_sent; scalar_t__ one_collision_sent; scalar_t__ total_collisions; scalar_t__ ctl_sent; scalar_t__ bcast_pkts_sent; scalar_t__ mcast_pkts_sent; scalar_t__ total_bytes_sent; scalar_t__ total_pkts_sent; scalar_t__ fw_total_bcast_sent; scalar_t__ fw_total_mcast_sent; scalar_t__ fw_tx_vxlan; scalar_t__ fw_err_tso; scalar_t__ fw_tso_fwd; scalar_t__ fw_tso; scalar_t__ fw_err_drop; scalar_t__ fw_err_link; scalar_t__ fw_err_pki; scalar_t__ fw_err_pko; scalar_t__ fw_total_fwd; scalar_t__ fw_total_sent; } ;
struct TYPE_13__ {TYPE_3__ fromwire; TYPE_2__ fromhost; } ;
struct octeon_device {TYPE_9__** droq; TYPE_7__ io_qmask; TYPE_6__** instr_queue; TYPE_4__ link_stats; } ;
struct net_device {TYPE_1__* netdev_ops; } ;
struct lio {scalar_t__ link_changes; struct octeon_device* oct_dev; } ;
struct ethtool_stats {int dummy; } ;
struct TYPE_17__ {scalar_t__ rx_alloc_failure; scalar_t__ rx_vxlan; scalar_t__ dropped_nodispatch; scalar_t__ bytes_received; scalar_t__ pkts_received; scalar_t__ rx_dropped; scalar_t__ dropped_toomany; scalar_t__ dropped_nomem; scalar_t__ rx_bytes_received; scalar_t__ rx_pkts_received; } ;
struct TYPE_18__ {TYPE_8__ stats; } ;
struct TYPE_14__ {scalar_t__ tx_restart; scalar_t__ tx_vxlan; scalar_t__ tx_gso; scalar_t__ bytes_sent; scalar_t__ instr_dropped; scalar_t__ instr_processed; scalar_t__ instr_posted; scalar_t__ sgentry_sent; scalar_t__ tx_iq_busy; scalar_t__ tx_dropped; scalar_t__ tx_tot_bytes; scalar_t__ tx_done; } ;
struct TYPE_15__ {TYPE_5__ stats; } ;
struct TYPE_10__ {int /*<<< orphan*/ (* ndo_get_stats64 ) (struct net_device*,struct rtnl_link_stats64*) ;} ;
/* Variables and functions */
int BIT_ULL (int) ;
scalar_t__ CVM_CAST64 (scalar_t__) ;
struct lio* GET_LIO (struct net_device*) ;
int /*<<< orphan*/ LIO_IFSTATE_RESETTING ;
int MAX_OCTEON_INSTR_QUEUES (struct octeon_device*) ;
int MAX_OCTEON_OUTPUT_QUEUES (struct octeon_device*) ;
scalar_t__ ifstate_check (struct lio*,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ stub1 (struct net_device*,struct rtnl_link_stats64*) ;
__attribute__((used)) static void
lio_get_ethtool_stats(struct net_device *netdev,
struct ethtool_stats *stats __attribute__((unused)),
u64 *data)
{
struct lio *lio = GET_LIO(netdev);
struct octeon_device *oct_dev = lio->oct_dev;
struct rtnl_link_stats64 lstats;
int i = 0, j;
if (ifstate_check(lio, LIO_IFSTATE_RESETTING))
return;
netdev->netdev_ops->ndo_get_stats64(netdev, &lstats);
/*sum of oct->droq[oq_no]->stats->rx_pkts_received */
data[i++] = lstats.rx_packets;
/*sum of oct->instr_queue[iq_no]->stats.tx_done */
data[i++] = lstats.tx_packets;
/*sum of oct->droq[oq_no]->stats->rx_bytes_received */
data[i++] = lstats.rx_bytes;
/*sum of oct->instr_queue[iq_no]->stats.tx_tot_bytes */
data[i++] = lstats.tx_bytes;
data[i++] = lstats.rx_errors +
oct_dev->link_stats.fromwire.fcs_err +
oct_dev->link_stats.fromwire.jabber_err +
oct_dev->link_stats.fromwire.l2_err +
oct_dev->link_stats.fromwire.frame_err;
data[i++] = lstats.tx_errors;
/*sum of oct->droq[oq_no]->stats->rx_dropped +
*oct->droq[oq_no]->stats->dropped_nodispatch +
*oct->droq[oq_no]->stats->dropped_toomany +
*oct->droq[oq_no]->stats->dropped_nomem
*/
data[i++] = lstats.rx_dropped +
oct_dev->link_stats.fromwire.fifo_err +
oct_dev->link_stats.fromwire.dmac_drop +
oct_dev->link_stats.fromwire.red_drops +
oct_dev->link_stats.fromwire.fw_err_pko +
oct_dev->link_stats.fromwire.fw_err_link +
oct_dev->link_stats.fromwire.fw_err_drop;
/*sum of oct->instr_queue[iq_no]->stats.tx_dropped */
data[i++] = lstats.tx_dropped +
oct_dev->link_stats.fromhost.max_collision_fail +
oct_dev->link_stats.fromhost.max_deferral_fail +
oct_dev->link_stats.fromhost.total_collisions +
oct_dev->link_stats.fromhost.fw_err_pko +
oct_dev->link_stats.fromhost.fw_err_link +
oct_dev->link_stats.fromhost.fw_err_drop +
oct_dev->link_stats.fromhost.fw_err_pki;
/* firmware tx stats */
/*per_core_stats[cvmx_get_core_num()].link_stats[mdata->from_ifidx].
*fromhost.fw_total_sent
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.fw_total_sent);
/*per_core_stats[i].link_stats[port].fromwire.fw_total_fwd */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.fw_total_fwd);
/*per_core_stats[j].link_stats[i].fromhost.fw_err_pko */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.fw_err_pko);
/*per_core_stats[j].link_stats[i].fromhost.fw_err_pki */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.fw_err_pki);
/*per_core_stats[j].link_stats[i].fromhost.fw_err_link */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.fw_err_link);
/*per_core_stats[cvmx_get_core_num()].link_stats[idx].fromhost.
*fw_err_drop
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.fw_err_drop);
/*per_core_stats[cvmx_get_core_num()].link_stats[idx].fromhost.fw_tso */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.fw_tso);
/*per_core_stats[cvmx_get_core_num()].link_stats[idx].fromhost.
*fw_tso_fwd
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.fw_tso_fwd);
/*per_core_stats[cvmx_get_core_num()].link_stats[idx].fromhost.
*fw_err_tso
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.fw_err_tso);
/*per_core_stats[cvmx_get_core_num()].link_stats[idx].fromhost.
*fw_tx_vxlan
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.fw_tx_vxlan);
/* Multicast packets sent by this port */
data[i++] = oct_dev->link_stats.fromhost.fw_total_mcast_sent;
data[i++] = oct_dev->link_stats.fromhost.fw_total_bcast_sent;
/* mac tx statistics */
/*CVMX_BGXX_CMRX_TX_STAT5 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.total_pkts_sent);
/*CVMX_BGXX_CMRX_TX_STAT4 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.total_bytes_sent);
/*CVMX_BGXX_CMRX_TX_STAT15 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.mcast_pkts_sent);
/*CVMX_BGXX_CMRX_TX_STAT14 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.bcast_pkts_sent);
/*CVMX_BGXX_CMRX_TX_STAT17 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.ctl_sent);
/*CVMX_BGXX_CMRX_TX_STAT0 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.total_collisions);
/*CVMX_BGXX_CMRX_TX_STAT3 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.one_collision_sent);
/*CVMX_BGXX_CMRX_TX_STAT2 */
data[i++] =
CVM_CAST64(oct_dev->link_stats.fromhost.multi_collision_sent);
/*CVMX_BGXX_CMRX_TX_STAT0 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.max_collision_fail);
/*CVMX_BGXX_CMRX_TX_STAT1 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.max_deferral_fail);
/*CVMX_BGXX_CMRX_TX_STAT16 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.fifo_err);
/*CVMX_BGXX_CMRX_TX_STAT6 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromhost.runts);
/* RX firmware stats */
/*per_core_stats[cvmx_get_core_num()].link_stats[ifidx].fromwire.
*fw_total_rcvd
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fw_total_rcvd);
/*per_core_stats[cvmx_get_core_num()].link_stats[ifidx].fromwire.
*fw_total_fwd
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fw_total_fwd);
/* Multicast packets received on this port */
data[i++] = oct_dev->link_stats.fromwire.fw_total_mcast;
data[i++] = oct_dev->link_stats.fromwire.fw_total_bcast;
/*per_core_stats[core_id].link_stats[ifidx].fromwire.jabber_err */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.jabber_err);
/*per_core_stats[core_id].link_stats[ifidx].fromwire.l2_err */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.l2_err);
/*per_core_stats[core_id].link_stats[ifidx].fromwire.frame_err */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.frame_err);
/*per_core_stats[cvmx_get_core_num()].link_stats[ifidx].fromwire.
*fw_err_pko
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fw_err_pko);
/*per_core_stats[j].link_stats[i].fromwire.fw_err_link */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fw_err_link);
/*per_core_stats[cvmx_get_core_num()].link_stats[lro_ctx->ifidx].
*fromwire.fw_err_drop
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fw_err_drop);
/*per_core_stats[cvmx_get_core_num()].link_stats[lro_ctx->ifidx].
*fromwire.fw_rx_vxlan
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fw_rx_vxlan);
/*per_core_stats[cvmx_get_core_num()].link_stats[lro_ctx->ifidx].
*fromwire.fw_rx_vxlan_err
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fw_rx_vxlan_err);
/* LRO */
/*per_core_stats[cvmx_get_core_num()].link_stats[ifidx].fromwire.
*fw_lro_pkts
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fw_lro_pkts);
/*per_core_stats[cvmx_get_core_num()].link_stats[ifidx].fromwire.
*fw_lro_octs
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fw_lro_octs);
/*per_core_stats[j].link_stats[i].fromwire.fw_total_lro */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fw_total_lro);
/*per_core_stats[j].link_stats[i].fromwire.fw_lro_aborts */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fw_lro_aborts);
/*per_core_stats[cvmx_get_core_num()].link_stats[ifidx].fromwire.
*fw_lro_aborts_port
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fw_lro_aborts_port);
/*per_core_stats[cvmx_get_core_num()].link_stats[ifidx].fromwire.
*fw_lro_aborts_seq
*/
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fw_lro_aborts_seq);
/*per_core_stats[cvmx_get_core_num()].link_stats[ifidx].fromwire.
*fw_lro_aborts_tsval
*/
data[i++] =
CVM_CAST64(oct_dev->link_stats.fromwire.fw_lro_aborts_tsval);
/*per_core_stats[cvmx_get_core_num()].link_stats[ifidx].fromwire.
*fw_lro_aborts_timer
*/
/* intrmod: packet forward rate */
data[i++] =
CVM_CAST64(oct_dev->link_stats.fromwire.fw_lro_aborts_timer);
/*per_core_stats[j].link_stats[i].fromwire.fw_lro_aborts */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fwd_rate);
/* mac: link-level stats */
/*CVMX_BGXX_CMRX_RX_STAT0 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.total_rcvd);
/*CVMX_BGXX_CMRX_RX_STAT1 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.bytes_rcvd);
/*CVMX_PKI_STATX_STAT5 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.total_bcst);
/*CVMX_PKI_STATX_STAT5 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.total_mcst);
/*wqe->word2.err_code or wqe->word2.err_level */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.runts);
/*CVMX_BGXX_CMRX_RX_STAT2 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.ctl_rcvd);
/*CVMX_BGXX_CMRX_RX_STAT6 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fifo_err);
/*CVMX_BGXX_CMRX_RX_STAT4 */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.dmac_drop);
/*wqe->word2.err_code or wqe->word2.err_level */
data[i++] = CVM_CAST64(oct_dev->link_stats.fromwire.fcs_err);
/*lio->link_changes*/
data[i++] = CVM_CAST64(lio->link_changes);
for (j = 0; j < MAX_OCTEON_INSTR_QUEUES(oct_dev); j++) {
if (!(oct_dev->io_qmask.iq & BIT_ULL(j)))
continue;
/*packets to network port*/
/*# of packets tx to network */
data[i++] = CVM_CAST64(oct_dev->instr_queue[j]->stats.tx_done);
/*# of bytes tx to network */
data[i++] =
CVM_CAST64(oct_dev->instr_queue[j]->stats.tx_tot_bytes);
/*# of packets dropped */
data[i++] =
CVM_CAST64(oct_dev->instr_queue[j]->stats.tx_dropped);
/*# of tx fails due to queue full */
data[i++] =
CVM_CAST64(oct_dev->instr_queue[j]->stats.tx_iq_busy);
/*XXX gather entries sent */
data[i++] =
CVM_CAST64(oct_dev->instr_queue[j]->stats.sgentry_sent);
/*instruction to firmware: data and control */
/*# of instructions to the queue */
data[i++] =
CVM_CAST64(oct_dev->instr_queue[j]->stats.instr_posted);
/*# of instructions processed */
data[i++] = CVM_CAST64(
oct_dev->instr_queue[j]->stats.instr_processed);
/*# of instructions could not be processed */
data[i++] = CVM_CAST64(
oct_dev->instr_queue[j]->stats.instr_dropped);
/*bytes sent through the queue */
data[i++] =
CVM_CAST64(oct_dev->instr_queue[j]->stats.bytes_sent);
/*tso request*/
data[i++] = CVM_CAST64(oct_dev->instr_queue[j]->stats.tx_gso);
/*vxlan request*/
data[i++] = CVM_CAST64(oct_dev->instr_queue[j]->stats.tx_vxlan);
/*txq restart*/
data[i++] =
CVM_CAST64(oct_dev->instr_queue[j]->stats.tx_restart);
}
/* RX */
for (j = 0; j < MAX_OCTEON_OUTPUT_QUEUES(oct_dev); j++) {
if (!(oct_dev->io_qmask.oq & BIT_ULL(j)))
continue;
/*packets send to TCP/IP network stack */
/*# of packets to network stack */
data[i++] =
CVM_CAST64(oct_dev->droq[j]->stats.rx_pkts_received);
/*# of bytes to network stack */
data[i++] =
CVM_CAST64(oct_dev->droq[j]->stats.rx_bytes_received);
/*# of packets dropped */
data[i++] = CVM_CAST64(oct_dev->droq[j]->stats.dropped_nomem +
oct_dev->droq[j]->stats.dropped_toomany +
oct_dev->droq[j]->stats.rx_dropped);
data[i++] =
CVM_CAST64(oct_dev->droq[j]->stats.dropped_nomem);
data[i++] =
CVM_CAST64(oct_dev->droq[j]->stats.dropped_toomany);
data[i++] =
CVM_CAST64(oct_dev->droq[j]->stats.rx_dropped);
/*control and data path*/
data[i++] =
CVM_CAST64(oct_dev->droq[j]->stats.pkts_received);
data[i++] =
CVM_CAST64(oct_dev->droq[j]->stats.bytes_received);
data[i++] =
CVM_CAST64(oct_dev->droq[j]->stats.dropped_nodispatch);
data[i++] =
CVM_CAST64(oct_dev->droq[j]->stats.rx_vxlan);
data[i++] =
CVM_CAST64(oct_dev->droq[j]->stats.rx_alloc_failure);
}
} |
the_stack_data/235716.c | #include <omp.h>
#include <math.h>
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) floor(((double)(n))/((double)(d)))
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
typedef char base;
void kernel_nussinov(int n, base seq[ n + 0],
int table[ n + 0][n + 0])
{
int i, j, k;
/* Copyright (C) 1991-2015 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, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
int t1, t2, t3, t4, t5, t6, t7, t8, t9, t10;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
/* Start of CLooG code */
if (n >= 2) {
for (t2=max(-1,ceild(-n-29,32));t2<=floord(n-1,32);t2++) {
lbp=max(0,t2);
ubp=min(floord(n-1,32),floord(32*t2+n+29,32));
#pragma omp parallel for private(lbv,ubv,t5,t6,t7,t8,t9,t10)
for (t4=lbp;t4<=ubp;t4++) {
if ((t2 <= floord(32*t4-n+2,32)) && (t4 >= ceild(n-31,32))) {
table[(n-2)][(n-1)] = ((table[(n-2)][(n-1)] >= table[(n-2)][(n-1)-1]) ? table[(n-2)][(n-1)] : table[(n-2)][(n-1)-1]);;
table[(n-2)][(n-1)] = ((table[(n-2)][(n-1)] >= table[(n-2)+1][(n-1)]) ? table[(n-2)][(n-1)] : table[(n-2)+1][(n-1)]);;
table[(n-2)][(n-1)] = ((table[(n-2)][(n-1)] >= table[(n-2)+1][(n-1)-1]) ? table[(n-2)][(n-1)] : table[(n-2)+1][(n-1)-1]);;
}
if ((t2 == -1) && (t4 <= floord(n-32,32))) {
table[(32*t4+30)][(32*t4+31)] = ((table[(32*t4+30)][(32*t4+31)] >= table[(32*t4+30)][(32*t4+31)-1]) ? table[(32*t4+30)][(32*t4+31)] : table[(32*t4+30)][(32*t4+31)-1]);;
table[(32*t4+30)][(32*t4+31)] = ((table[(32*t4+30)][(32*t4+31)] >= table[(32*t4+30)+1][(32*t4+31)]) ? table[(32*t4+30)][(32*t4+31)] : table[(32*t4+30)+1][(32*t4+31)]);;
table[(32*t4+30)][(32*t4+31)] = ((table[(32*t4+30)][(32*t4+31)] >= table[(32*t4+30)+1][(32*t4+31)-1]) ? table[(32*t4+30)][(32*t4+31)] : table[(32*t4+30)+1][(32*t4+31)-1]);;
}
for (t5=max(max(-n+3,32*t2-32*t4),-32*t4-29);t5<=min(min(0,-32*t4+1),32*t2-32*t4+31);t5++) {
table[-t5][(-t5+1)] = ((table[-t5][(-t5+1)] >= table[-t5][(-t5+1)-1]) ? table[-t5][(-t5+1)] : table[-t5][(-t5+1)-1]);;
table[-t5][(-t5+1)] = ((table[-t5][(-t5+1)] >= table[-t5+1][(-t5+1)]) ? table[-t5][(-t5+1)] : table[-t5+1][(-t5+1)]);;
table[-t5][(-t5+1)] = ((table[-t5][(-t5+1)] >= table[-t5+1][(-t5+1)-1]) ? table[-t5][(-t5+1)] : table[-t5+1][(-t5+1)-1]);;
for (t7=-t5+2;t7<=min(n-1,32*t4+31);t7++) {
table[-t5][t7] = ((table[-t5][t7] >= table[-t5][t7-1]) ? table[-t5][t7] : table[-t5][t7-1]);;
table[-t5][t7] = ((table[-t5][t7] >= table[-t5+1][t7]) ? table[-t5][t7] : table[-t5+1][t7]);;
table[-t5][t7] = ((table[-t5][t7] >= table[-t5+1][t7-1]+(((seq[-t5])+(seq[t7])) == 3 ? 1 : 0)) ? table[-t5][t7] : table[-t5+1][t7-1]+(((seq[-t5])+(seq[t7])) == 3 ? 1 : 0));;
for (t9=-t5+1;t9<=t7-1;t9++) {
table[-t5][t7] = ((table[-t5][t7] >= table[-t5][t9] + table[t9+1][t7]) ? table[-t5][t7] : table[-t5][t9] + table[t9+1][t7]);;
}
}
}
for (t5=max(32*t2-32*t4,-32*t4+2);t5<=min(0,32*t2-32*t4+31);t5++) {
for (t7=32*t4;t7<=min(n-1,32*t4+31);t7++) {
table[-t5][t7] = ((table[-t5][t7] >= table[-t5][t7-1]) ? table[-t5][t7] : table[-t5][t7-1]);;
table[-t5][t7] = ((table[-t5][t7] >= table[-t5+1][t7]) ? table[-t5][t7] : table[-t5+1][t7]);;
table[-t5][t7] = ((table[-t5][t7] >= table[-t5+1][t7-1]+(((seq[-t5])+(seq[t7])) == 3 ? 1 : 0)) ? table[-t5][t7] : table[-t5+1][t7-1]+(((seq[-t5])+(seq[t7])) == 3 ? 1 : 0));;
for (t9=-t5+1;t9<=t7-1;t9++) {
table[-t5][t7] = ((table[-t5][t7] >= table[-t5][t9] + table[t9+1][t7]) ? table[-t5][t7] : table[-t5][t9] + table[t9+1][t7]);;
}
}
}
}
}
}
/* End of CLooG code */
}
|
the_stack_data/6388819.c | // Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#include <time.h>
#include <windows.h>
#else
#include <pthread.h>
#include <fenv.h>
#include <signal.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX_STRING 100
#define EXP_TABLE_SIZE 1000
#define MAX_EXP 6
#define MAX_SENTENCE_LENGTH 1000
#define MAX_CODE_LENGTH 40
const int vocab_hash_size = 30000000; // Maximum 30 * 0.7 = 21M words in the vocabulary
typedef float real; // Precision of float numbers
struct vocab_word {
long long cn;
int *point;
char *word, *code, codelen;
};
char train_file[MAX_STRING], output_file[MAX_STRING];
char save_vocab_file[MAX_STRING], read_vocab_file[MAX_STRING];
struct vocab_word *vocab;
int binary = 0, cbow = 1, debug_mode = 2, window = 5, min_count = 5, num_threads = 12, min_reduce = 1;
int *vocab_hash;
long long vocab_max_size = 1000, vocab_size = 0, layer1_size = 100;
long long train_words = 0, word_count_actual = 0, iter = 5, file_size = 0, classes = 0;
real alpha = 0.025, starting_alpha, sample = 1e-3;
real *syn0, *syn1, *syn1neg, *expTable;
clock_t start;
int hs = 0, negative = 5;
const int table_size = 1e8;
int *table;
void InitUnigramTable() {
int a, i;
double train_words_pow = 0;
double d1, power = 0.75;
table = (int *)malloc(table_size * sizeof(int));
for (a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power);
i = 0;
d1 = pow(vocab[i].cn, power) / train_words_pow;
for (a = 0; a < table_size; a++) {
table[a] = i;
if (a / (double)table_size > d1) {
i++;
d1 += pow(vocab[i].cn, power) / train_words_pow;
}
if (i >= vocab_size) i = vocab_size - 1;
}
}
// Reads a single word from a file, assuming space + tab + EOL to be word boundaries
void ReadWord(char *word, FILE *fin) {
int a = 0, ch;
while (!feof(fin)) {
ch = fgetc(fin);
if (ch == 13) continue;
if ((ch == ' ') || (ch == '\t') || (ch == '\n')) {
if (a > 0) {
if (ch == '\n') ungetc(ch, fin);
break;
}
if (ch == '\n') {
strcpy(word, (char *)"</s>");
return;
} else continue;
}
word[a] = ch;
a++;
if (a >= MAX_STRING - 1) a--; // Truncate too long words
}
word[a] = 0;
}
// Returns hash value of a word
int GetWordHash(char *word) {
unsigned long long a, hash = 0;
for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a];
hash = hash % vocab_hash_size;
return hash;
}
// Returns position of a word in the vocabulary;
// if the word is not found, returns -1
int SearchVocab(char *word) {
unsigned int hash = GetWordHash(word);
while (1) {
if (vocab_hash[hash] == -1) {
return -1;
}
// strcmp is misleading, the following actually checks
// whether word is equal to vocab[vocab_hash[hash]].word,
// that is, whether the hash for word is indeed associated
// with word
if (strcmp(word, vocab[vocab_hash[hash]].word) == 0) {
return vocab_hash[hash];
}
hash = (hash + 1) % vocab_hash_size;
}
return -1;
}
// Reads a word and returns its index in the vocabulary
int ReadWordIndex(FILE *fin) {
char word[MAX_STRING];
ReadWord(word, fin);
if (feof(fin)) return -1;
return SearchVocab(word);
}
// Adds a word to the vocabulary
int AddWordToVocab(char *word) {
unsigned int hash, length = strlen(word) + 1;
if (length > MAX_STRING) length = MAX_STRING;
vocab[vocab_size].word = (char *)calloc(length, sizeof(char));
strcpy(vocab[vocab_size].word, word);
vocab[vocab_size].cn = 0;
vocab_size++;
// Reallocate memory if needed
if (vocab_size + 2 >= vocab_max_size) {
vocab_max_size += 1000;
vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word));
}
hash = GetWordHash(word);
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
vocab_hash[hash] = vocab_size - 1;
return vocab_size - 1;
}
// Used later for sorting by word counts
int VocabCompare(const void *a, const void *b) {
return ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn;
}
// Sorts the vocabulary by frequency using word counts
void SortVocab() {
int a, size;
unsigned int hash;
// Sort the vocabulary and keep </s> at the first position
qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare);
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
size = vocab_size;
train_words = 0;
for (a = 0; a < size; a++) {
// Words occuring less than min_count times will be discarded from the vocab
if ((vocab[a].cn < min_count) && (a != 0)) {
vocab_size--;
free(vocab[a].word);
} else {
// Hash will be re-computed, as after the sorting it is not actual
hash=GetWordHash(vocab[a].word);
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
vocab_hash[hash] = a;
train_words += vocab[a].cn;
}
}
vocab = (struct vocab_word *)realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word));
// Allocate memory for the binary tree construction
for (a = 0; a < vocab_size; a++) {
vocab[a].code = (char *)calloc(MAX_CODE_LENGTH, sizeof(char));
vocab[a].point = (int *)calloc(MAX_CODE_LENGTH, sizeof(int));
}
}
// Reduces the vocabulary by removing infrequent tokens
void ReduceVocab() {
int a, b = 0;
unsigned int hash;
for (a = 0; a < vocab_size; a++) if (vocab[a].cn > min_reduce) {
vocab[b].cn = vocab[a].cn;
vocab[b].word = vocab[a].word;
b++;
} else free(vocab[a].word);
vocab_size = b;
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
for (a = 0; a < vocab_size; a++) {
// Hash will be re-computed, as it is not actual
hash = GetWordHash(vocab[a].word);
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
vocab_hash[hash] = a;
}
fflush(stdout);
min_reduce++;
}
// Create binary Huffman tree using the word counts
// Frequent words will have short unique binary codes
void CreateBinaryTree() {
long long point[MAX_CODE_LENGTH];
long long *binary = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
long long *parent_node = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
long long *count = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
for (long long a = 0; a < vocab_size; a++) {
count[a] = vocab[a].cn;
}
for (long long a = vocab_size; a < vocab_size * 2; a++) {
count[a] = 1e15;
}
// Following algorithm constructs the Huffman tree
// by adding one node at a time
long long pos1 = vocab_size - 1;
long long pos2 = vocab_size;
for (long long a = 0; a < vocab_size - 1; a++) {
long long min1i, min2i;
// First, find two smallest nodes 'min1, min2'
if (pos1 >= 0) {
if (count[pos1] < count[pos2]) {
min1i = pos1;
pos1--;
} else {
min1i = pos2;
pos2++;
}
} else {
min1i = pos2;
pos2++;
}
if (pos1 >= 0) {
if (count[pos1] < count[pos2]) {
min2i = pos1;
pos1--;
} else {
min2i = pos2;
pos2++;
}
} else {
min2i = pos2;
pos2++;
}
count[vocab_size + a] = count[min1i] + count[min2i];
parent_node[min1i] = vocab_size + a;
parent_node[min2i] = vocab_size + a;
binary[min2i] = 1;
}
// Now assign binary code to each vocabulary word
char code[MAX_CODE_LENGTH];
for (long long a = 0; a < vocab_size; a++) {
long long i = 0;
for (long long b = a; b < vocab_size * 2 - 2; b = parent_node[b]) {
code[i] = binary[b];
point[i] = b;
i++;
}
vocab[a].codelen = i;
vocab[a].point[0] = vocab_size - 2;
for (long long b = 0; b < i; b++) {
vocab[a].code[i - b - 1] = code[b];
vocab[a].point[i - b] = point[b] - vocab_size;
}
}
free(count);
free(binary);
free(parent_node);
}
void LearnVocabFromTrainFile() {
char word[MAX_STRING];
FILE *fin;
long long a, i;
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
fin = fopen(train_file, "rb");
if (fin == NULL) {
printf("ERROR: training data file not found!\n");
exit(1);
}
vocab_size = 0;
AddWordToVocab((char *)"</s>");
while (1) {
ReadWord(word, fin);
if (feof(fin)) break;
train_words++;
if ((debug_mode > 1) && (train_words % 100000 == 0)) {
printf("%lldK%c", train_words / 1000, 13);
fflush(stdout);
}
i = SearchVocab(word);
if (i == -1) {
a = AddWordToVocab(word);
vocab[a].cn = 1;
} else vocab[i].cn++;
if (vocab_size > vocab_hash_size * 0.7) ReduceVocab();
}
SortVocab();
if (debug_mode > 0) {
printf("Vocab size: %lld\n", vocab_size);
printf("Words in train file: %lld\n", train_words);
}
file_size = ftell(fin);
fclose(fin);
}
void SaveVocab() {
long long i;
FILE *fo = fopen(save_vocab_file, "wb");
for (i = 0; i < vocab_size; i++) fprintf(fo, "%s %lld\n", vocab[i].word, vocab[i].cn);
fclose(fo);
}
void ReadVocab() {
long long a, i = 0;
char c;
char word[MAX_STRING];
FILE *fin = fopen(read_vocab_file, "rb");
if (fin == NULL) {
printf("Vocabulary file not found\n");
exit(1);
}
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
vocab_size = 0;
while (1) {
ReadWord(word, fin);
if (feof(fin)) break;
a = AddWordToVocab(word);
fscanf(fin, "%lld%c", &vocab[a].cn, &c);
i++;
}
SortVocab();
if (debug_mode > 0) {
printf("Vocab size: %lld\n", vocab_size);
printf("Words in train file: %lld\n", train_words);
}
fin = fopen(train_file, "rb");
if (fin == NULL) {
printf("ERROR: training data file not found!\n");
exit(1);
}
fseek(fin, 0, SEEK_END);
file_size = ftell(fin);
fclose(fin);
}
void InitNet() {
#ifdef _MSC_VER
syn0 = _aligned_malloc((long long)vocab_size * layer1_size * sizeof(real), 128);
#elif defined linux
// layer1_size is the embedding size, obtained by the -size command line argument
// and defaulting to 100
// this allocates a matrix syn0 of vocab_size * layer1_size reals
posix_memalign((void **)&syn0, 128, (long long)vocab_size * layer1_size * sizeof(real));
#endif
if (syn0 == NULL) {
printf("Memory allocation failed\n"); exit(1);
}
// hs: hierarchical softmax
if (hs) {
#ifdef _MSC_VER
syn1 = _aligned_malloc((long long)vocab_size * layer1_size * sizeof(real), 128);
#elif defined linux
// allocate another matrix syn1 of vocab_size * layer1_size reals
posix_memalign((void **)&syn1, 128, (long long)vocab_size * layer1_size * sizeof(real));
#endif
if (syn1 == NULL) {
printf("Memory allocation failed\n"); exit(1);
}
for (long long a = 0; a < vocab_size; a++) {
for (long long b = 0; b < layer1_size; b++) {
syn1[a * layer1_size + b] = 0;
}
}
}
if ( negative > 0) {
// number of negative examples to sample
#ifdef _MSC_VER
syn1neg = _aligned_malloc((long long)vocab_size * layer1_size * sizeof(real), 128);
#elif defined linux
// allocate another matrix syn1neg of vocab_size * layer1_size reals
posix_memalign((void **)&syn1neg, 128, (long long)vocab_size * layer1_size * sizeof(real));
#endif
if (syn1neg == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
for (long long a = 0; a < vocab_size; a++) {
for (long long b = 0; b < layer1_size; b++) {
syn1neg[a * layer1_size + b] = 0;
}
}
}
unsigned long long next_random = 1;
for (long long a = 0; a < vocab_size; a++) {
for (long long b = 0; b < layer1_size; b++) {
next_random = next_random * (unsigned long long)25214903917 + 11;
// initialize hidden layer weights with random values between -0.5 and 0.5
// that, on average, sum up to one for each row
syn0[a * layer1_size + b] = (((next_random & 0xFFFF) / (real)0x10000) - 0.5) / layer1_size;
}
}
CreateBinaryTree();
}
// build a sentence composed of word indices extracted from the file fi,
// optionally discarding words according to the "sample" global parameter,
// and returns the built sentence's length
long long buildSentence(
long long sen[MAX_SENTENCE_LENGTH + 1],
FILE *fi,
unsigned long long *next_random
) {
long long sentence_length = 0;
while (1) {
long long word = ReadWordIndex(fi);
if (feof(fi)) {
// end of file, note that this check is useless
// because word will be -1 in this case
break;
}
if (word == -1) {
// word not in vocabulary
continue;
}
if (word == 0) {
// sentence end, i.e. special delimiter "</s>"
// encountered, inserted in place of newlines
// in the input file
break;
}
// The subsampling randomly discards frequent words
// while keeping the ranking same - this is the -sample command line arg,
// and defaults to 0.001
if (sample > 0) {
real f = vocab[word].cn / (sample * train_words);
real ran = (sqrt(f) + 1) / f;
*next_random = *next_random * (unsigned long long)25214903917 + 11;
if (ran < (*next_random & 0xFFFF) / (real)0x10000) {
continue;
}
}
sen[sentence_length] = word;
sentence_length++;
if (sentence_length >= MAX_SENTENCE_LENGTH) {
break;
}
}
return sentence_length;
}
void *TrainModelThread(void *id) {
long long sentence_length = 0, sentence_position = 0;
long long word_count = 0, last_word_count = 0, sen[MAX_SENTENCE_LENGTH + 1];
long long local_iter = iter;
unsigned long long next_random = (long long)id;
clock_t now;
// I believe these are used to store activations of neurons
real *neu1 = (real *)calloc(layer1_size, sizeof(real));
real *neu1e = (real *)calloc(layer1_size, sizeof(real));
FILE *fi = fopen(train_file, "rb");
fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET);
while (1) {
// reduce the learning rate alpha every 10,000 words processed
if (word_count - last_word_count > 10000) {
// not thread-safe, I believe
word_count_actual += word_count - last_word_count;
last_word_count = word_count;
if ((debug_mode > 1)) {
now=clock();
printf("%cAlpha: %f Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha,
word_count_actual / (real)(iter * train_words + 1) * 100,
word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000));
fflush(stdout);
}
alpha = starting_alpha * (1 - word_count_actual / (real)(iter * train_words + 1));
if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001;
}
// build a sentence
if (sentence_length == 0) {
sentence_length = buildSentence(sen, fi, &next_random);
word_count += sentence_length;
sentence_position = 0;
}
// check whether this thread's iteration is done
if (feof(fi) || (word_count > train_words / num_threads)) {
word_count_actual += word_count - last_word_count;
local_iter--;
if (local_iter == 0) {
break;
}
word_count = 0;
last_word_count = 0;
sentence_length = 0;
fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET);
continue;
}
long long centerWord = sen[sentence_position];
if (centerWord == -1) {
continue;
}
for (long long c = 0; c < layer1_size; c++) {
// reset hidden layer activation for centerWord
neu1[c] = 0;
// reset error for centerWord
neu1e[c] = 0;
}
next_random = next_random * (unsigned long long)25214903917 + 11;
long long b = next_random % window;
if (cbow) {
// train the cbow architecture
// in -> hidden
// cw: context words count
long long cw = 0;
for (long long a = b; a < window * 2 + 1 - b; a++) {
// if this is not the central word
if (a != window) {
// pos is the context word index in the sentence
long long pos = sentence_position - window + a;
if (pos < 0) {
continue;
}
if (pos >= sentence_length) {
continue;
}
if (sen[pos] == -1) {
continue;
}
// add to neu1 the embedding of the context word c
for (long long l = 0; l < layer1_size; l++) {
neu1[l] += syn0[sen[pos] * layer1_size + l];
}
cw++;
}
}
// if there are words in the window
if (cw) {
// average the context embeddings that were summed into neu1
for (long long l = 0; l < layer1_size; l++) {
neu1[l] /= cw;
}
// Hierarchical Softmax, by default not used
if (hs) {
for (long long d = 0; d < vocab[centerWord].codelen; d++) {
real f = 0;
long long l2 = vocab[centerWord].point[d] * layer1_size;
// Propagate hidden -> output
for (long long c = 0; c < layer1_size; c++) f += neu1[c] * syn1[l2 + c];
if (f <= -MAX_EXP) continue;
else if (f >= MAX_EXP) continue;
else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
// 'g' is the gradient multiplied by the learning rate
real g = (1 - vocab[centerWord].code[d] - f) * alpha;
// Propagate errors output -> hidden
for (long long c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[l2 + c];
// Learn weights hidden -> output
for (long long c = 0; c < layer1_size; c++) syn1[l2 + c] += g * neu1[c];
}
}
// Negative Sampling
if (negative > 0) {
long long target, label;
for (long long n = 0; n < negative + 1; n++) {
if (n == 0) {
target = centerWord;
label = 1;
} else {
next_random = next_random * (unsigned long long)25214903917 + 11;
target = table[(next_random >> 16) % table_size];
if (target == 0) {
target = next_random % (vocab_size - 1) + 1;
}
if (target == centerWord) {
continue;
}
label = 0;
}
long long tStart = target * layer1_size;
real f = 0, g;
// set f to be the scalar product of neu1 and the negative
// embeddings of the target word, in other words, a measure of
// the distance from the embedded context and the negative word
for (long long c = 0; c < layer1_size; c++) {
f += neu1[c] * syn1neg[tStart + c];
}
// set g to be an approximation of:
// g(f) = label - 1 / (1 + exp(-f))
if (f > MAX_EXP) {
g = label - 1;
} else if (f < -MAX_EXP) {
g = label - 0;
} else {
int x = (f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2);
g = label - expTable[x];
}
for (long long c = 0; c < layer1_size; c++) {
neu1e[c] += syn1neg[tStart + c] * g * alpha;
}
for (long long c = 0; c < layer1_size; c++) {
syn1neg[tStart + c] += neu1[c] * g * alpha;
}
}
}
// hidden -> in
for (long long a = b; a < window * 2 + 1 - b; a++) {
if (a != window) {
long long c = sentence_position - window + a;
if (c < 0) {
continue;
}
if (c >= sentence_length) {
continue;
}
if (sen[c] == -1) {
continue;
}
for (long long l = 0; l < layer1_size; l++) {
syn0[sen[c] * layer1_size + l] += neu1e[l];
}
}
}
}
} else {
//train skip-gram
for (long long a = b; a < window * 2 + 1 - b; a++) {
if (a != window) {
long long pos = sentence_position - window + a;
if (pos < 0) {
continue;
}
if (pos >= sentence_length) {
continue;
}
if (sen[pos] == -1) {
continue;
}
long long cStart = sen[pos] * layer1_size;
for (long long l = 0; l < layer1_size; l++) {
// reset error for context word
neu1e[l] = 0;
}
// Hierarchical Softmax
if (hs) {
for (long long d = 0; d < vocab[centerWord].codelen; d++) {
real f = 0;
long long l2 = vocab[centerWord].point[d] * layer1_size;
// Propagate hidden -> output
for (long long l = 0; l < layer1_size; l++) f += syn0[cStart + l] * syn1[l2 + l];
if (f <= -MAX_EXP) continue;
else if (f >= MAX_EXP) continue;
else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
// 'g' is the gradient multiplied by the learning rate
real g = (1 - vocab[centerWord].code[d] - f) * alpha;
// Propagate errors output -> hidden
for (pos = 0; pos < layer1_size; pos++) {
neu1e[pos] += g * syn1[l2 + pos];
}
// Learn weights hidden -> output
for (pos = 0; pos < layer1_size; pos++) {
syn1[l2 + pos] += g * syn0[cStart + pos];
}
}
}
// Negative Sampling
if (negative > 0) {
for (long long d = 0; d < negative + 1; d++) {
long long target, label;
if (d == 0) {
target = centerWord;
label = 1;
} else {
next_random = next_random * (unsigned long long)25214903917 + 11;
target = table[(next_random >> 16) % table_size];
if (target == 0) {
target = next_random % (vocab_size - 1) + 1;
}
if (target == centerWord) {
continue;
}
label = 0;
}
long long tStart = target * layer1_size;
real f = 0, g;
for (long long c = 0; c < layer1_size; c++) {
f += syn0[cStart + c] * syn1neg[tStart + c];
}
if (f > MAX_EXP) {
g = label - 1;
} else if (f < -MAX_EXP) {
g = label - 0;
} else {
g = label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
}
for (long long c = 0; c < layer1_size; c++) {
neu1e[c] += syn1neg[tStart + c] * alpha * g;
}
for (long long c = 0; c < layer1_size; c++) {
syn1neg[tStart + c] += syn0[cStart + c] * alpha * g;
}
}
}
// Learn weights input -> hidden
for (long long c = 0; c < layer1_size; c++) {
syn0[cStart + c] += neu1e[c];
}
}
}
}
sentence_position++;
if (sentence_position >= sentence_length) {
sentence_length = 0;
continue;
}
}
fclose(fi);
free(neu1);
free(neu1e);
#ifdef _MSC_VER
_endthreadex(0);
#elif defined linux
pthread_exit(NULL);
#endif
}
#ifdef _MSC_VER
DWORD WINAPI TrainModelThread_win(LPVOID tid){
TrainModelThread(tid);
return 0;
}
#endif
void TrainModel() {
long a, b, c, d;
FILE *fo;
printf("Starting training using file %s\n", train_file);
starting_alpha = alpha;
if (read_vocab_file[0] != 0) {
ReadVocab();
} else {
LearnVocabFromTrainFile();
}
if (save_vocab_file[0] != 0) {
SaveVocab();
}
if (output_file[0] == 0) {
return;
}
InitNet();
if (negative > 0) {
InitUnigramTable();
}
start = clock();
#ifdef _MSC_VER
HANDLE *pt = (HANDLE *)malloc(num_threads * sizeof(HANDLE));
for (int i = 0; i < num_threads; i++){
pt[i] = (HANDLE)_beginthreadex(NULL, 0, TrainModelThread_win, (void *)i, 0, NULL);
}
WaitForMultipleObjects(num_threads, pt, TRUE, INFINITE);
for (int i = 0; i < num_threads; i++){
CloseHandle(pt[i]);
}
free(pt);
#elif defined linux
pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t));
for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainModelThread, (void *)a);
for (a = 0; a < num_threads; a++) pthread_join(pt[a], NULL);
free(pt);
#endif
fo = fopen(output_file, "wb");
if (classes == 0) {
// Save the word vectors
fprintf(fo, "%lld %lld\n", vocab_size, layer1_size);
for (a = 0; a < vocab_size; a++) {
fprintf(fo, "%s ", vocab[a].word);
if (binary) for (b = 0; b < layer1_size; b++) fwrite(&syn0[a * layer1_size + b], sizeof(real), 1, fo);
else for (b = 0; b < layer1_size; b++) fprintf(fo, "%lf ", syn0[a * layer1_size + b]);
fprintf(fo, "\n");
}
} else {
// Run K-means on the word vectors
int clcn = classes, iter = 10, closeid;
int *centcn = (int *)malloc(classes * sizeof(int));
int *cl = (int *)calloc(vocab_size, sizeof(int));
real closev, x;
real *cent = (real *)calloc(classes * layer1_size, sizeof(real));
for (a = 0; a < vocab_size; a++) cl[a] = a % clcn;
for (a = 0; a < iter; a++) {
for (b = 0; b < clcn * layer1_size; b++) cent[b] = 0;
for (b = 0; b < clcn; b++) centcn[b] = 1;
for (c = 0; c < vocab_size; c++) {
for (d = 0; d < layer1_size; d++) cent[layer1_size * cl[c] + d] += syn0[c * layer1_size + d];
centcn[cl[c]]++;
}
for (b = 0; b < clcn; b++) {
closev = 0;
for (c = 0; c < layer1_size; c++) {
cent[layer1_size * b + c] /= centcn[b];
closev += cent[layer1_size * b + c] * cent[layer1_size * b + c];
}
closev = sqrt(closev);
for (c = 0; c < layer1_size; c++) cent[layer1_size * b + c] /= closev;
}
for (c = 0; c < vocab_size; c++) {
closev = -10;
closeid = 0;
for (d = 0; d < clcn; d++) {
x = 0;
for (b = 0; b < layer1_size; b++) x += cent[layer1_size * d + b] * syn0[c * layer1_size + b];
if (x > closev) {
closev = x;
closeid = d;
}
}
cl[c] = closeid;
}
}
// Save the K-means classes
for (a = 0; a < vocab_size; a++) fprintf(fo, "%s %d\n", vocab[a].word, cl[a]);
free(centcn);
free(cent);
free(cl);
}
fclose(fo);
}
int ArgPos(char *str, int argc, char **argv) {
int a;
for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) {
if (a == argc - 1) {
printf("Argument missing for %s\n", str);
exit(1);
}
return a;
}
return -1;
}
int main(int argc, char **argv) {
int i;
if (argc == 1) {
printf("WORD VECTOR estimation toolkit v 0.1c\n\n");
printf("Options:\n");
printf("Parameters for training:\n");
printf("\t-train <file>\n");
printf("\t\tUse text data from <file> to train the model\n");
printf("\t-output <file>\n");
printf("\t\tUse <file> to save the resulting word vectors / word clusters\n");
printf("\t-size <int>\n");
printf("\t\tSet size of word vectors; default is 100\n");
printf("\t-window <int>\n");
printf("\t\tSet max skip length between words; default is 5\n");
printf("\t-sample <float>\n");
printf("\t\tSet threshold for occurrence of words. Those that appear with higher frequency in the training data\n");
printf("\t\twill be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5)\n");
printf("\t-hs <int>\n");
printf("\t\tUse Hierarchical Softmax; default is 0 (not used)\n");
printf("\t-negative <int>\n");
printf("\t\tNumber of negative examples; default is 5, common values are 3 - 10 (0 = not used)\n");
printf("\t-threads <int>\n");
printf("\t\tUse <int> threads (default 12)\n");
printf("\t-iter <int>\n");
printf("\t\tRun more training iterations (default 5)\n");
printf("\t-min-count <int>\n");
printf("\t\tThis will discard words that appear less than <int> times; default is 5\n");
printf("\t-alpha <float>\n");
printf("\t\tSet the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\n");
printf("\t-classes <int>\n");
printf("\t\tOutput word classes rather than word vectors; default number of classes is 0 (vectors are written)\n");
printf("\t-debug <int>\n");
printf("\t\tSet the debug mode (default = 2 = more info during training)\n");
printf("\t-binary <int>\n");
printf("\t\tSave the resulting vectors in binary moded; default is 0 (off)\n");
printf("\t-save-vocab <file>\n");
printf("\t\tThe vocabulary will be saved to <file>\n");
printf("\t-read-vocab <file>\n");
printf("\t\tThe vocabulary will be read from <file>, not constructed from the training data\n");
printf("\t-cbow <int>\n");
printf("\t\tUse the continuous bag of words model; default is 1 (use 0 for skip-gram model)\n");
printf("\nExamples:\n");
printf("./word2vec -train data.txt -output vec.txt -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -cbow 1 -iter 3\n\n");
return 0;
}
output_file[0] = 0;
save_vocab_file[0] = 0;
read_vocab_file[0] = 0;
if ((i = ArgPos((char *)"-size", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-train", argc, argv)) > 0) strcpy(train_file, argv[i + 1]);
if ((i = ArgPos((char *)"-save-vocab", argc, argv)) > 0) strcpy(save_vocab_file, argv[i + 1]);
if ((i = ArgPos((char *)"-read-vocab", argc, argv)) > 0) strcpy(read_vocab_file, argv[i + 1]);
if ((i = ArgPos((char *)"-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-binary", argc, argv)) > 0) binary = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-cbow", argc, argv)) > 0) cbow = atoi(argv[i + 1]);
if (cbow) alpha = 0.05;
if ((i = ArgPos((char *)"-alpha", argc, argv)) > 0) alpha = atof(argv[i + 1]);
if ((i = ArgPos((char *)"-output", argc, argv)) > 0) strcpy(output_file, argv[i + 1]);
if ((i = ArgPos((char *)"-window", argc, argv)) > 0) window = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-sample", argc, argv)) > 0) sample = atof(argv[i + 1]);
if ((i = ArgPos((char *)"-hs", argc, argv)) > 0) hs = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-negative", argc, argv)) > 0) negative = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-threads", argc, argv)) > 0) num_threads = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-iter", argc, argv)) > 0) iter = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-classes", argc, argv)) > 0) classes = atoi(argv[i + 1]);
vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word));
vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int));
expTable = (real *)malloc((EXP_TABLE_SIZE + 1) * sizeof(real));
for (i = 0; i < EXP_TABLE_SIZE; i++) {
expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table
expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1)
}
#ifdef linux
feenableexcept(FE_DIVBYZERO | FE_OVERFLOW);
#endif
TrainModel();
return 0;
}
|
the_stack_data/43887367.c | #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
float xtals[] = {
0.032768, 3.579545, 3.6864, 4.9152, 6, 7, 8, 9.833, 10,
10.245, 12, 13.56, 13.433, 14.318, 16, 16.384, 16.9344,
17.7344, 20, 20.48, 24, 25, 27, 27.12, 28.224, 32, 48,
50, 72
/* 0.032768, 0.038, 0.128, 3.579545, 3.6864, 4, 4.9152, 6, 7, 8, 9.833, 10,
10.245, 10.7, 12, 12.288, 13.56, 13.433, 14.318, 16, 16.384, 16.9344,
17.7344, 18.432, 20, 20.48, 22.1184, 24, 25, 27, 27.12, 28.224, 32, 48,
50, 54, 72
*/
};
#define N_XTALS sizeof(xtals) / sizeof(xtals[0])
#define N_DIFFS sizeof(xtals) / sizeof(xtals[0]) * 2
float diff[N_DIFFS] = {0};
int ids[N_DIFFS] = {0};
#define swap(a, b) do {typeof(a) _t; _t = (a); (a) = (b); (b) = _t;} while(0);
int main(void)
{
int i;
char buf[64];
float freq;
for(i = 0; i < N_XTALS; i++) {
xtals[i] *= 1e6;
}
while(1) {
printf("Input needed frequency: ");
memset(buf, 0, 64);
fgets(buf, 64, stdin);
for(char *c = &(buf[strlen(buf) - 1]); *c == '\r' || *c == '\n';) {
*c = '\0';
c = &(buf[strlen(buf) - 1]);
}
sscanf(buf, "%f", &freq);
if(toupper(buf[strlen(buf) - 1]) == 'K')
freq *= 1000.0;
else if(toupper(buf[strlen(buf) - 1]) == 'M')
freq *= 1000000.0;
for(i = 0; i < N_XTALS; i++) {
unsigned long div = xtals[i] / freq;
diff[i * 2] = fabs(freq - xtals[i] / div);
diff[i * 2 + 1] = fabs(freq - xtals[i] / (div + 1));
}
for(i = 0; i < N_DIFFS; i++)
ids[i] = i;
for(i = 0; i < N_DIFFS - 1; i++) {
for(int j = i + 1; j < N_DIFFS; j++) {
if(diff[i] > diff[j]) {
swap(diff[i], diff[j]);
swap(ids[i], ids[j]);
}
}
}
for(i = 0; i < 5; i++) {
int min_id = ids[i];
int div = xtals[min_id / 2] / freq;
float freq_d, err;
if(min_id % 2 == 1)
div++;
freq_d = xtals[min_id / 2] / div;
err = (freq_d - freq) / freq * 1e6;
printf("%.3fM / %d = %.1f (%s%.0fppm)\n",
xtals[min_id / 2] / 1e6, div, freq_d, err > 0 ? "+" : "", err);
}
putchar('\n');
}
return 0;
}
|
the_stack_data/161081184.c | #include <stdlib.h>
extern void abort (void);
short g_3;
int main (void)
{
int l_2;
for (l_2 = -1; l_2 != 0; l_2 = (unsigned char)(l_2 - 1))
g_3 |= l_2;
if (g_3 != -1)
abort ();
return 0;
}
|
the_stack_data/75308.c | /*
>>~~ ACM PROBLEM ~~<<
ID: 146
Name: ID Codes
Author: Arash Shakery
Email: [email protected]
Language: C
*/
#include <string.h>
#include <stdio.h>
void swap(char* x,char* y){
*x+=*y;*y=*x-*y;*x-=*y;
}
int main(){
char line[60],c;
int i,j,k,min,len;
while (gets(line)){
if(line[0]=='#')break;
len=strlen(line);
min=300;
for(i=len-2;i>=0;i--){
for(j=i+1;j<len;j++)
if(line[j]>line[i] && line[j]<min){
k=j;
min=line[k];
}
if(min!=300){
swap(&line[i],&line[k]);
for(j=i+1;j<len;j++)
for(k=j+1;k<len;k++)
if(line[j]>line[k])swap(&line[j],&line[k]);
goto finish;
}
}
printf("No Successor\n");
continue;
finish:
printf("%s\n",line);
}
return 0;
}
|
the_stack_data/133835.c | #include <math.h>
/* Arccosine restricted to [0, 1]
*
* If x > 1, this function returns NaN to indicate complex result.
* If x < 0, the result is inaccurate.
*/
static double kernel_(double x)
{
const double c[] = {
1.5707963049952700155,
-2.1459880383414681170e-1,
8.8979049893610385888e-2,
-5.0174715211875860817e-2,
3.0893053200289071461e-2,
-1.7089810818777579223e-2,
6.6712932693206083568e-3,
-1.2628309202213843948e-3
};
return sqrt(1 - x) * (((((((c[7] * x + c[6]) * x + c[5]) * x + c[4])
* x + c[3]) * x + c[2]) * x + c[1]) * x + c[0]);
}
float acosf(float x)
{
const double pi = 3.14159265358979323846;
double y = kernel_(fabsf(x));
return x > 0 ? y : pi - y;
}
|
the_stack_data/72013783.c | #include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
typedef int index;
typedef int keytype;
//교환함수
void swap(keytype *itemA, keytype *itemB) {
keytype temp = *itemA;
*itemA = *itemB;
*itemB = temp;
}
void partition(index low, index high, index *pivotpoint, keytype S[]) {
index i, j;
keytype pivotitem;//pivot으로 삼을 값 저장
pivotitem = S[low];
j = low;//j로 pivotpoint 찿기
for(i = low + 1; i <= high; i++) {
//pivotitem보다 작은 값은 pivotitem 왼쪽으로 이동
if(S[i] < pivotitem) {
j++;
swap(&S[i], &S[j]);
}
}
*pivotpoint = j;
swap(&S[low], &S[*pivotpoint]);
}
void quicksort(index low, index high, keytype S[]) {
index pivotpoint;//pivot index 저장
if(high > low) {
partition(low, high, &pivotpoint, S);//pivotpoint를 중심으로 나눈다.
quicksort(low, pivotpoint - 1, S);//pivotpoint 왼쪽 정렬
quicksort(pivotpoint + 1, high, S);//pivotpoint 오른쪽 정렬
}
}
int main(void) {
keytype *S;
int N;
struct timeval begin, end;//quicksort 실행시간 측정
double time;
printf("입력할 데이터 개수: ");
scanf("%d", &N);
S = (keytype *)malloc(sizeof(keytype) * N);
printf("정렬할 데이터 입력: ");
for(index i = 0; i < N; i++)
scanf("%d", &S[i]);
gettimeofday(&begin, NULL);
quicksort(0, N - 1, S);
gettimeofday(&end, NULL);
time = (double)(end.tv_usec - begin.tv_usec) / 1000000 + (double)(end.tv_sec - begin.tv_sec);
for(index i = 0; i < N; i++)
printf("%d ", S[i]);
printf("\n");
printf("Total time: %lf seconds\n", time);
free(S);
return 0;
}
|
the_stack_data/43888371.c | /* James Moretti
* Apr 5, 2014
*
* McDropsMain.c - Main / driving file for Minecraft Drops
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#define NAME_LENGTH 16
#define MAX_LC_DIGITS 3
#define MINUTES_BETWEEN_DROPS 15
#define DEFAULT_ITEM 19 //Sponge
#define MAX_PLAYERS 20
typedef struct {
int itemId;
float dropChance;
float lowerThresh;
int bundleNum;
} DropItem;
typedef struct {
DropItem* item;
int length;
} DropTable;
/*
* Gets the number of items in DropTable.txt.
* Number of lines = number of items.
*/
int getDropTableLength() {
char lcbuff[MAX_LC_DIGITS + 1];
FILE* lcp = popen("wc -l < DropTable.txt", "r");
fgets(lcbuff, MAX_LC_DIGITS + 1, lcp);
int estat = pclose(lcp);
int lineCount = atoi( lcbuff );
// Error checking
if(estat == -1) {
printf("Failed to get drop table length!\n");
exit(1);
}
return lineCount;
}
/*
* Populate interal drop table from drop table file
*/
void populateDropTable(DropTable* table) {
FILE* fp = fopen("DropTable.txt", "r");
int i;
for (i = 0; i < table->length; i++) {
// %*[^\n] reads until the new line char, %*c reads the new line char
fscanf(fp, "%d,%f,%d%*[^\n]%*c",
&(table->item[i].itemId), &(table->item[i].dropChance),
&(table->item[i].bundleNum));
}
int estat = fclose(fp);
// Error checking
if(estat == -1) {
printf("Failed to read in drop table!\n");
exit(2);
}
}
/*
* Calculates drop chance percentage ranges for each item in the table.
*
* Items are initially read in with an arbirary integer weight for their
* chance of being dropped. This function sums up all of those weights
* then replaces each individual item's weight with a percentage and
* sum of the percentages before it (the lower percent threshold).
*
* For example, if an item has a drop chance of 10% and a lower
* threshold of 30%, then the item would drop if the random number generator
* hits between 30% and 40% (30% + 10%). The item directly after this one
* would have a lower threshold of 40%.
*/
void calcDropValues(DropTable* table) {
// Calcluate total weight
int i;
int totalWeight = 0;
for (i = 0; i < table->length; i++)
totalWeight += table->item[i].dropChance;
// Calculate item drop thresholds
float currentTotal = 0;
for (i = 0; i < table->length; i++) {
table->item[i].lowerThresh = currentTotal;
table->item[i].dropChance /= totalWeight;
currentTotal += table->item[i].dropChance;
}
}
/*
* Creates, populates, and returns a pointer to the drop table
*/
DropTable* genDropTable() {
printf("Populating drop table...\n");
DropTable* table = (DropTable*) malloc(sizeof(DropTable));
table->length = getDropTableLength();
table->item = (DropItem*) malloc(table->length * sizeof(DropItem));
populateDropTable(table);
printf("Calculating drop values...\n");
calcDropValues(table);
return table;
}
/*
* Populate list of players and return how many were read in
*/
int getPlayerList(char players[][NAME_LENGTH + 1]) {
FILE* plp = popen("./ListPlayers.sh", "r");
// Read player number from first line
int count = 0;
fscanf(plp, "%*s %*s %d %*s %*s %*s %*[\n]", &count);
// Read each player into the array. Ignore commas and newlines
int i;
for (i = 0; i < count; i++) {
fscanf(plp, "%[^,\n]%*2c", players[i]);
}
int estat = pclose(plp);
// Error checking
if(estat == -1) {
printf("Failed to read in player list!\n");
exit(3);
}
return count;
}
/*
* Generate a list of drops. One for each player.
*/
void genDropList(DropTable* table, DropItem* playerDrops, int numPlayers) {
float roll;
int i, j;
for (i = 0; i < numPlayers; i++) {
roll = (float)rand() / RAND_MAX; // Generate a percentage
// Match our roll to one of the drop items
for (j = 0; j < table->length; j++) {
if(table->item[j].lowerThresh <= roll &&
roll < table->item[j].lowerThresh + table->item[j].dropChance) {
playerDrops[i] = table->item[j];
}
}
// Catch the extremely rare situation where rand() generates RAND_MAX
if (roll == RAND_MAX) {
playerDrops[j].itemId = DEFAULT_ITEM;
playerDrops[j].bundleNum = 1;
}
}
}
/*
* Give a player his drop (and possibly alert him)
*/
void payout(char* player, DropItem drop) {
char cmd[50];
sprintf(cmd, "mcgive %s %d %d", player, drop.itemId, drop.bundleNum);
system(cmd);
}
/*
* Generates a list of drops for each player then gives them out
*/
void genAndGiveDrops(DropTable* table, char playerList[][NAME_LENGTH + 1]) {
// Populate player list
int numPlayers = getPlayerList(playerList);
// Get a drop for each player
DropItem playerDrops[numPlayers];
genDropList(table, playerDrops, numPlayers);
// Give each player their drop
int i;
for (i = 0; i < numPlayers; i++)
printf("Dropped %d %d's for %s\n",
playerDrops[i].bundleNum, playerDrops[i].itemId, playerList[i]);
//payout(playerList[i], playerDrops[i]);
printf("Items dropped for %d players.\n", numPlayers);
}
/*
* Program driver
*/
int main() {
printf("Starting MC Drops v2.0\n");
srand(time(NULL));
/* The player list probably doesn't need to be kept in main,
but this does avoid needing to re-allocate the player array
on every drop. I might move this in the future*/
char playerHolder[MAX_PLAYERS][NAME_LENGTH + 1];
DropTable* pdropTable = genDropTable();
printf("MC Drops successfully initialized. Use Ctrl+C to quit.\n\n");
// Run once every few minutes
while (1) {
genAndGiveDrops(pdropTable, playerHolder);
// Wait for next run
sleep(60 * MINUTES_BETWEEN_DROPS);
}
// This never gets called, but it's here for completeness' sake
free(pdropTable->item);
free(pdropTable);
return 0;
}
|
the_stack_data/753697.c | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <math.h>
float sum(int x, int y);
float sub(int x, int y);
float divi(int x, int y);
float mult(int x, int y);
float raiz(int x);
int main(int argc, char **argv){
setlocale(LC_ALL, "Portuguese");
int x, y,op,i;
x = 1;
while (x != 0)
{
printf("\n\n Calculadora Aritmética\n\n");
printf("1) Soma\n");
printf("2) Subtração\n");
printf("3) Divisão\n");
printf("4) Multiplicação\n");
printf("5) raiz quadrada\n\n");
printf("Digite uma opção:");
scanf("%d",&op);
if(op == 5){
printf("Digite um número\n");
printf(":");
scanf("%d", &x);
}else{
printf("Digite dois números\n");
printf(":");
scanf("%d", &x);
printf(":");
scanf("%d", &y);
}
if (x == 0)
{
return 0;
}
switch(op){
case 1:
printf("%.2f\n", sum(x, y));
break;
case 2:
printf("%.2f\n", sub(x, y));
break;
case 3:
printf("%.2f\n", divi(x, y));
break;
case 4:
printf("%.2f\n", mult(x, y));
break;
case 5:
printf("%.2f",raiz(x));
break;
default:
printf("opção incorreta!");
}
//#define ESC 27
//printf( "%c[2J", ESC );
sleep(2);
// for(i = 0; i < 22; i++){
// printf("\n");
// }
}
printf("none arguments!!");
system("pause");
return 0;
}
float sum(int x, int y)
{
float z;
z = x + y;
return z;
}
float sub(int x, int y)
{
float z;
z = x - y;
return z;
}
float divi(int x, int y)
{
float z;
z = x / y;
return z;
}
float mult(int x, int y)
{
float z;
z = x * y;
return z;
}
float raiz(int x){
return sqrt(x);
}
|
the_stack_data/840135.c | // RUN: %compile-run-and-check
#include <omp.h>
#include <stdio.h>
int main() {
int res = 0;
#pragma omp parallel num_threads(2) reduction(+:res)
{
int tid = omp_get_thread_num();
#pragma omp target teams distribute reduction(+:res)
for (int i = tid; i < 2; i++)
++res;
}
// The first thread makes 2 iterations, the second - 1. Expected result of the
// reduction res is 3.
// CHECK: res = 3.
printf("res = %d.\n", res);
return 0;
}
|
the_stack_data/1004683.c | // RUN: %clang_cc1 -triple i686-pc-linux-gnu -fsyntax-only -verify %s -Wabsolute-value
// RUN: %clang_cc1 -triple i686-pc-linux-gnu -fsyntax-only %s -Wabsolute-value -fdiagnostics-parseable-fixits 2>&1 | FileCheck %s
int abs(int);
long int labs(long int);
long long int llabs(long long int);
float fabsf(float);
double fabs(double);
long double fabsl(long double);
float cabsf(float _Complex);
double cabs(double _Complex);
long double cabsl(long double _Complex);
void test_int(int x) {
(void)abs(x);
(void)labs(x);
(void)llabs(x);
(void)fabsf(x);
// expected-warning@-1 {{using floating point absolute value function 'fabsf' when argument is of integer type}}
// expected-note@-2 {{use function 'abs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"abs"
(void)fabs(x);
// expected-warning@-1 {{using floating point absolute value function 'fabs' when argument is of integer type}}
// expected-note@-2 {{use function 'abs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"abs"
(void)fabsl(x);
// expected-warning@-1 {{using floating point absolute value function 'fabsl' when argument is of integer type}}
// expected-note@-2 {{use function 'abs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"abs"
(void)cabsf(x);
// expected-warning@-1 {{using complex absolute value function 'cabsf' when argument is of integer type}}
// expected-note@-2 {{use function 'abs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"abs"
(void)cabs(x);
// expected-warning@-1 {{using complex absolute value function 'cabs' when argument is of integer type}}
// expected-note@-2 {{use function 'abs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"abs"
(void)cabsl(x);
// expected-warning@-1 {{using complex absolute value function 'cabsl' when argument is of integer type}}
// expected-note@-2 {{use function 'abs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"abs"
(void)__builtin_abs(x);
(void)__builtin_labs(x);
(void)__builtin_llabs(x);
(void)__builtin_fabsf(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabsf' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_abs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_abs"
(void)__builtin_fabs(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabs' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_abs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_abs"
(void)__builtin_fabsl(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabsl' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_abs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_abs"
(void)__builtin_cabsf(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabsf' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_abs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_abs"
(void)__builtin_cabs(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabs' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_abs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_abs"
(void)__builtin_cabsl(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabsl' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_abs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_abs"
}
void test_long(long x) {
(void)abs(x); // no warning - int and long are same length for this target
(void)labs(x);
(void)llabs(x);
(void)fabsf(x);
// expected-warning@-1 {{using floating point absolute value function 'fabsf' when argument is of integer type}}
// expected-note@-2 {{use function 'labs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"labs"
(void)fabs(x);
// expected-warning@-1 {{using floating point absolute value function 'fabs' when argument is of integer type}}
// expected-note@-2 {{use function 'labs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"labs"
(void)fabsl(x);
// expected-warning@-1 {{using floating point absolute value function 'fabsl' when argument is of integer type}}
// expected-note@-2 {{use function 'labs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"labs"
(void)cabsf(x);
// expected-warning@-1 {{using complex absolute value function 'cabsf' when argument is of integer type}}
// expected-note@-2 {{use function 'labs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"labs"
(void)cabs(x);
// expected-warning@-1 {{using complex absolute value function 'cabs' when argument is of integer type}}
// expected-note@-2 {{use function 'labs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"labs"
(void)cabsl(x);
// expected-warning@-1 {{using complex absolute value function 'cabsl' when argument is of integer type}}
// expected-note@-2 {{use function 'labs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"labs"
(void)__builtin_abs(x); // no warning - int and long are same length for
// this target
(void)__builtin_labs(x);
(void)__builtin_llabs(x);
(void)__builtin_fabsf(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabsf' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_labs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_labs"
(void)__builtin_fabs(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabs' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_labs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_labs"
(void)__builtin_fabsl(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabsl' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_labs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_labs"
(void)__builtin_cabsf(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabsf' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_labs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_labs"
(void)__builtin_cabs(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabs' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_labs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_labs"
(void)__builtin_cabsl(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabsl' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_labs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_labs"
}
void test_long_long(long long x) {
(void)abs(x);
// expected-warning@-1{{absolute value function 'abs' given an argument of type 'long long' but has parameter of type 'int' which may cause truncation of value}}
// expected-note@-2{{use function 'llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:12}:"llabs"
(void)labs(x);
// expected-warning@-1{{absolute value function 'labs' given an argument of type 'long long' but has parameter of type 'long' which may cause truncation of value}}
// expected-note@-2{{use function 'llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"llabs"
(void)llabs(x);
(void)fabsf(x);
// expected-warning@-1 {{using floating point absolute value function 'fabsf' when argument is of integer type}}
// expected-note@-2 {{use function 'llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"llabs"
(void)fabs(x);
// expected-warning@-1 {{using floating point absolute value function 'fabs' when argument is of integer type}}
// expected-note@-2 {{use function 'llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"llabs"
(void)fabsl(x);
// expected-warning@-1 {{using floating point absolute value function 'fabsl' when argument is of integer type}}
// expected-note@-2 {{use function 'llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"llabs"
(void)cabsf(x);
// expected-warning@-1 {{using complex absolute value function 'cabsf' when argument is of integer type}}
// expected-note@-2 {{use function 'llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"llabs"
(void)cabs(x);
// expected-warning@-1 {{using complex absolute value function 'cabs' when argument is of integer type}}
// expected-note@-2 {{use function 'llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"llabs"
(void)cabsl(x);
// expected-warning@-1 {{using complex absolute value function 'cabsl' when argument is of integer type}}
// expected-note@-2 {{use function 'llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"llabs"
(void)__builtin_abs(x);
// expected-warning@-1{{absolute value function '__builtin_abs' given an argument of type 'long long' but has parameter of type 'int' which may cause truncation of value}}
// expected-note@-2{{use function '__builtin_llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:22}:"__builtin_llabs"
(void)__builtin_labs(x);
// expected-warning@-1{{absolute value function '__builtin_labs' given an argument of type 'long long' but has parameter of type 'long' which may cause truncation of value}}
// expected-note@-2{{use function '__builtin_llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_llabs"
(void)__builtin_llabs(x);
(void)__builtin_fabsf(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabsf' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_llabs"
(void)__builtin_fabs(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabs' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_llabs"
(void)__builtin_fabsl(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabsl' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_llabs"
(void)__builtin_cabsf(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabsf' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_llabs"
(void)__builtin_cabs(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabs' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_llabs"
(void)__builtin_cabsl(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabsl' when argument is of integer type}}
// expected-note@-2 {{use function '__builtin_llabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_llabs"
}
void test_float(float x) {
(void)abs(x);
// expected-warning@-1 {{using integer absolute value function 'abs' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:12}:"fabsf"
(void)labs(x);
// expected-warning@-1 {{using integer absolute value function 'labs' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"fabsf"
(void)llabs(x);
// expected-warning@-1 {{using integer absolute value function 'llabs' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"fabsf"
(void)fabsf(x);
(void)fabs(x);
(void)fabsl(x);
(void)cabsf(x);
// expected-warning@-1 {{using complex absolute value function 'cabsf' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"fabsf"
(void)cabs(x);
// expected-warning@-1 {{using complex absolute value function 'cabs' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"fabsf"
(void)cabsl(x);
// expected-warning@-1 {{using complex absolute value function 'cabsl' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"fabsf"
(void)__builtin_abs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_abs' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:22}:"__builtin_fabsf"
(void)__builtin_labs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_labs' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_fabsf"
(void)__builtin_llabs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_llabs' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_fabsf"
(void)__builtin_fabsf(x);
(void)__builtin_fabs(x);
(void)__builtin_fabsl(x);
(void)__builtin_cabsf(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabsf' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_fabsf"
(void)__builtin_cabs(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabs' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_fabsf"
(void)__builtin_cabsl(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabsl' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_fabsf"
}
void test_double(double x) {
(void)abs(x);
// expected-warning@-1 {{using integer absolute value function 'abs' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:12}:"fabs"
(void)labs(x);
// expected-warning@-1 {{using integer absolute value function 'labs' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"fabs"
(void)llabs(x);
// expected-warning@-1 {{using integer absolute value function 'llabs' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"fabs"
(void)fabsf(x);
// expected-warning@-1{{absolute value function 'fabsf' given an argument of type 'double' but has parameter of type 'float' which may cause truncation of value}}
// expected-note@-2{{use function 'fabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"fabs"
(void)fabs(x);
(void)fabsl(x);
(void)cabsf(x);
// expected-warning@-1 {{using complex absolute value function 'cabsf' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"fabs"
(void)cabs(x);
// expected-warning@-1 {{using complex absolute value function 'cabs' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"fabs"
(void)cabsl(x);
// expected-warning@-1 {{using complex absolute value function 'cabsl' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"fabs"
(void)__builtin_abs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_abs' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:22}:"__builtin_fabs"
(void)__builtin_labs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_labs' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_fabs"
(void)__builtin_llabs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_llabs' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_fabs"
(void)__builtin_fabsf(x);
// expected-warning@-1{{absolute value function '__builtin_fabsf' given an argument of type 'double' but has parameter of type 'float' which may cause truncation of value}}
// expected-note@-2{{use function '__builtin_fabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_fabs"
(void)__builtin_fabs(x);
(void)__builtin_fabsl(x);
(void)__builtin_cabsf(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabsf' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_fabs"
(void)__builtin_cabs(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabs' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_fabs"
(void)__builtin_cabsl(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabsl' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_fabs"
}
void test_long_double(long double x) {
(void)abs(x);
// expected-warning@-1 {{using integer absolute value function 'abs' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:12}:"fabsl"
(void)labs(x);
// expected-warning@-1 {{using integer absolute value function 'labs' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"fabsl"
(void)llabs(x);
// expected-warning@-1 {{using integer absolute value function 'llabs' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"fabsl"
(void)fabsf(x);
// expected-warning@-1{{absolute value function 'fabsf' given an argument of type 'long double' but has parameter of type 'float' which may cause truncation of value}}
// expected-note@-2{{use function 'fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"fabsl"
(void)fabs(x);
// expected-warning@-1{{absolute value function 'fabs' given an argument of type 'long double' but has parameter of type 'double' which may cause truncation of value}}
// expected-note@-2{{use function 'fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"fabsl"
(void)fabsl(x);
(void)cabsf(x);
// expected-warning@-1 {{using complex absolute value function 'cabsf' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"fabsl"
(void)cabs(x);
// expected-warning@-1 {{using complex absolute value function 'cabs' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"fabsl"
(void)cabsl(x);
// expected-warning@-1 {{using complex absolute value function 'cabsl' when argument is of floating point type}}
// expected-note@-2 {{use function 'fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"fabsl"
(void)__builtin_abs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_abs' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:22}:"__builtin_fabsl"
(void)__builtin_labs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_labs' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_fabsl"
(void)__builtin_llabs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_llabs' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_fabsl"
(void)__builtin_fabsf(x);
// expected-warning@-1{{absolute value function '__builtin_fabsf' given an argument of type 'long double' but has parameter of type 'float' which may cause truncation of value}}
// expected-note@-2{{use function '__builtin_fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_fabsl"
(void)__builtin_fabs(x);
// expected-warning@-1{{absolute value function '__builtin_fabs' given an argument of type 'long double' but has parameter of type 'double' which may cause truncation of value}}
// expected-note@-2{{use function '__builtin_fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_fabsl"
(void)__builtin_fabsl(x);
(void)__builtin_cabsf(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabsf' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_fabsl"
(void)__builtin_cabs(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabs' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_fabsl"
(void)__builtin_cabsl(x);
// expected-warning@-1 {{using complex absolute value function '__builtin_cabsl' when argument is of floating point type}}
// expected-note@-2 {{use function '__builtin_fabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_fabsl"
}
void test_complex_float(_Complex float x) {
(void)abs(x);
// expected-warning@-1 {{using integer absolute value function 'abs' when argument is of complex type}}
// expected-note@-2 {{use function 'cabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:12}:"cabsf"
(void)labs(x);
// expected-warning@-1 {{using integer absolute value function 'labs' when argument is of complex type}}
// expected-note@-2 {{use function 'cabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"cabsf"
(void)llabs(x);
// expected-warning@-1 {{using integer absolute value function 'llabs' when argument is of complex type}}
// expected-note@-2 {{use function 'cabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"cabsf"
(void)fabsf(x);
// expected-warning@-1 {{using floating point absolute value function 'fabsf' when argument is of complex type}}
// expected-note@-2 {{use function 'cabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"cabsf"
(void)fabs(x);
// expected-warning@-1 {{using floating point absolute value function 'fabs' when argument is of complex type}}
// expected-note@-2 {{use function 'cabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"cabsf"
(void)fabsl(x);
// expected-warning@-1 {{using floating point absolute value function 'fabsl' when argument is of complex type}}
// expected-note@-2 {{use function 'cabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"cabsf"
(void)cabsf(x);
(void)cabs(x);
(void)cabsl(x);
(void)__builtin_abs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_abs' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:22}:"__builtin_cabsf"
(void)__builtin_labs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_labs' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_cabsf"
(void)__builtin_llabs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_llabs' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_cabsf"
(void)__builtin_fabsf(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabsf' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_cabsf"
(void)__builtin_fabs(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabs' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_cabsf"
(void)__builtin_fabsl(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabsl' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabsf' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_cabsf"
(void)__builtin_cabsf(x);
(void)__builtin_cabs(x);
(void)__builtin_cabsl(x);
}
void test_complex_double(_Complex double x) {
(void)abs(x);
// expected-warning@-1 {{using integer absolute value function 'abs' when argument is of complex type}}
// expected-note@-2 {{use function 'cabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:12}:"cabs"
(void)labs(x);
// expected-warning@-1 {{using integer absolute value function 'labs' when argument is of complex type}}
// expected-note@-2 {{use function 'cabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"cabs"
(void)llabs(x);
// expected-warning@-1 {{using integer absolute value function 'llabs' when argument is of complex type}}
// expected-note@-2 {{use function 'cabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"cabs"
(void)fabsf(x);
// expected-warning@-1 {{using floating point absolute value function 'fabsf' when argument is of complex type}}
// expected-note@-2 {{use function 'cabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"cabs"
(void)fabs(x);
// expected-warning@-1 {{using floating point absolute value function 'fabs' when argument is of complex type}}
// expected-note@-2 {{use function 'cabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"cabs"
(void)fabsl(x);
// expected-warning@-1 {{using floating point absolute value function 'fabsl' when argument is of complex type}}
// expected-note@-2 {{use function 'cabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"cabs"
(void)cabsf(x);
// expected-warning@-1 {{absolute value function 'cabsf' given an argument of type '_Complex double' but has parameter of type '_Complex float' which may cause truncation of value}}
// expected-note@-2 {{use function 'cabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"cabs"
(void)cabs(x);
(void)cabsl(x);
(void)__builtin_abs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_abs' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:22}:"__builtin_cabs"
(void)__builtin_labs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_labs' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_cabs"
(void)__builtin_llabs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_llabs' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_cabs"
(void)__builtin_fabsf(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabsf' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_cabs"
(void)__builtin_fabs(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabs' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_cabs"
(void)__builtin_fabsl(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabsl' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_cabs"
(void)__builtin_cabsf(x);
// expected-warning@-1 {{absolute value function '__builtin_cabsf' given an argument of type '_Complex double' but has parameter of type '_Complex float' which may cause truncation of value}}
// expected-note@-2 {{use function '__builtin_cabs' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_cabs"
(void)__builtin_cabs(x);
(void)__builtin_cabsl(x);
}
void test_complex_long_double(_Complex long double x) {
(void)abs(x);
// expected-warning@-1 {{using integer absolute value function 'abs' when argument is of complex type}}
// expected-note@-2 {{use function 'cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:12}:"cabsl"
(void)labs(x);
// expected-warning@-1 {{using integer absolute value function 'labs' when argument is of complex type}}
// expected-note@-2 {{use function 'cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"cabsl"
(void)llabs(x);
// expected-warning@-1 {{using integer absolute value function 'llabs' when argument is of complex type}}
// expected-note@-2 {{use function 'cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"cabsl"
(void)fabsf(x);
// expected-warning@-1 {{using floating point absolute value function 'fabsf' when argument is of complex type}}
// expected-note@-2 {{use function 'cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"cabsl"
(void)fabs(x);
// expected-warning@-1 {{using floating point absolute value function 'fabs' when argument is of complex type}}
// expected-note@-2 {{use function 'cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"cabsl"
(void)fabsl(x);
// expected-warning@-1 {{using floating point absolute value function 'fabsl' when argument is of complex type}}
// expected-note@-2 {{use function 'cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"cabsl"
(void)cabsf(x);
// expected-warning@-1 {{absolute value function 'cabsf' given an argument of type '_Complex long double' but has parameter of type '_Complex float' which may cause truncation of value}}
// expected-note@-2 {{use function 'cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:"cabsl"
(void)cabs(x);
// expected-warning@-1 {{absolute value function 'cabs' given an argument of type '_Complex long double' but has parameter of type '_Complex double' which may cause truncation of value}}
// expected-note@-2 {{use function 'cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:"cabsl"
(void)cabsl(x);
(void)__builtin_abs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_abs' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:22}:"__builtin_cabsl"
(void)__builtin_labs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_labs' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_cabsl"
(void)__builtin_llabs(x);
// expected-warning@-1 {{using integer absolute value function '__builtin_llabs' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_cabsl"
(void)__builtin_fabsf(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabsf' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_cabsl"
(void)__builtin_fabs(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabs' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_cabsl"
(void)__builtin_fabsl(x);
// expected-warning@-1 {{using floating point absolute value function '__builtin_fabsl' when argument is of complex type}}
// expected-note@-2 {{use function '__builtin_cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_cabsl"
(void)__builtin_cabsf(x);
// expected-warning@-1 {{absolute value function '__builtin_cabsf' given an argument of type '_Complex long double' but has parameter of type '_Complex float' which may cause truncation of value}}
// expected-note@-2 {{use function '__builtin_cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:"__builtin_cabsl"
(void)__builtin_cabs(x);
// expected-warning@-1 {{absolute value function '__builtin_cabs' given an argument of type '_Complex long double' but has parameter of type '_Complex double' which may cause truncation of value}}
// expected-note@-2 {{use function '__builtin_cabsl' instead}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:"__builtin_cabsl"
(void)__builtin_cabsl(x);
}
void test_unsigned_int(unsigned int x) {
(void)abs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to 'abs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:12}:""
(void)labs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to 'labs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:""
(void)llabs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to 'llabs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:""
(void)fabsf(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to 'fabsf' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:""
(void)fabs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to 'fabs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:""
(void)fabsl(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to 'fabsl' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:""
(void)cabsf(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to 'cabsf' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:""
(void)cabs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to 'cabs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:""
(void)cabsl(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to 'cabsl' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:""
(void)__builtin_abs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_abs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:22}:""
(void)__builtin_labs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_labs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:""
(void)__builtin_llabs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_llabs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:""
(void)__builtin_fabsf(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_fabsf' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:""
(void)__builtin_fabs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_fabs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:""
(void)__builtin_fabsl(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_fabsl' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:""
(void)__builtin_cabsf(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_cabsf' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:""
(void)__builtin_cabs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_cabs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:""
(void)__builtin_cabsl(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned int' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_cabsl' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:""
}
void test_unsigned_long(unsigned long x) {
(void)abs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to 'abs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:12}:""
(void)labs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to 'labs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:""
(void)llabs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to 'llabs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:""
(void)fabsf(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to 'fabsf' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:""
(void)fabs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to 'fabs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:""
(void)fabsl(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to 'fabsl' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:""
(void)cabsf(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to 'cabsf' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:""
(void)cabs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to 'cabs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:13}:""
(void)cabsl(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to 'cabsl' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:14}:""
(void)__builtin_abs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_abs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:22}:""
(void)__builtin_labs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_labs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:""
(void)__builtin_llabs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_llabs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:""
(void)__builtin_fabsf(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_fabsf' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:""
(void)__builtin_fabs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_fabs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:""
(void)__builtin_fabsl(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_fabsl' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:""
(void)__builtin_cabsf(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_cabsf' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:""
(void)__builtin_cabs(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_cabs' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:23}:""
(void)__builtin_cabsl(x);
// expected-warning@-1 {{taking the absolute value of unsigned type 'unsigned long' has no effect}}
// expected-note@-2 {{remove the call to '__builtin_cabsl' since unsigned values cannot be negative}}
// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:9-[[@LINE-3]]:24}:""
}
|
the_stack_data/154261.c | /*
Jason Downing
Assignment 2
Operating Systems - COMP.3080
9/26/2016
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
/*
Sort command should look like:
sort -k3,3 -k1,1 FILE_TO_SORT
*/
#define READ 0
#define WRITE 1
#define LINE_WIDTH 80
int main (int argc, char *argv[]) {
pid_t child_pid;
int inPipe[2], outPipe[2];
int count = -1, total = 0, oldAreaCode = 0, curAreaCode = 0;
int bytes_read = 0, sort_file = 0;
char line_buffer[80], first[80], last[80];
FILE *outWrite, *sortData, *sortTemp;
// Check to see if the user used the program correctly
if (argc == 1 || argc > 2) {
printf("\nUsage: ./a2_sort file_name_to_sort\n\n");
exit(1);
}
// Create two pipes
if (pipe(outPipe) == -1 || pipe(inPipe) == -1) {
perror("\nParent pipe failure!\n\n");
exit(2);
}
// Fork to create a child process
child_pid = fork();
// Error case
if (child_pid == -1) {
perror("\nFailed to create a child process!\n");
exit(1);
}
//****************************************************************************
// Child case
//****************************************************************************
else if (child_pid == 0) {
// Channel plumbing for stdin
if (close(0) == -1) {
perror("\nCHILD pipe error!\n");
exit(3);
}
if (dup(outPipe[READ]) != 0) {
perror("\nCHILD pipe dup error: outPipe[READ].\n");
exit(3);
}
// Channel plumbing for stdout
if (close(1) == -1) {
perror("\nCHILD pipe error!\n");
exit(3);
}
if (dup(inPipe[WRITE]) != 1) {
perror("\nCHILD pipe dup error: inPipe[WRITE].\n");
exit(3);
}
// Close unneeded pipes
if (close(outPipe[READ]) == -1 || close(outPipe[WRITE]) == -1 ||
close( inPipe[READ]) == -1 || close( inPipe[WRITE]) == -1) {
perror("\nCHILD close error!\n");
exit(3);
}
// Run sort
execlp("sort", "sort", "-k3,3", "-k1,1", NULL);
perror("\nSort has failed to run correctly.\n");
exit(4);
}
//****************************************************************************
// Parent case
//****************************************************************************
// Open the out pipe as a file
outWrite = fdopen(outPipe[WRITE], "w");
// Open the file to be sent to the child (who runs sort on this data)
if ( (sortData = fopen(argv[1], "r")) == NULL) {
perror("\nError opening file!\n");
}
// Send each line of the grep file to the child
while (fgets(line_buffer, LINE_WIDTH, sortData) != NULL) {
fprintf(outWrite, "%s", line_buffer);
}
// close unneeded files and pipes
fflush(outWrite);
fclose(outWrite);
close(outPipe[READ]);
close(outPipe[WRITE]);
close(inPipe[WRITE]);
fclose(sortData);
// Open a temp file to write sorted data to
sortTemp = fopen("sorted_temp.txt", "w+");
sort_file = open("sorted_temp.txt", O_RDWR);
// Read each line back from the child into a buffer, and then write
// the buffer to a temporary grep file to process later
while ( (bytes_read = read(inPipe[READ], line_buffer, LINE_WIDTH)) != 0) {
// Check for write errors
if (write(sort_file, line_buffer, bytes_read) == -1) {
printf("Error writing to temp file!\n");
exit(4);
}
}
// Go through the sorted output file, line by line, and count up the total
// number of people in each area code
while (fgets(line_buffer, LINE_WIDTH, sortTemp) != NULL) {
sscanf(line_buffer, "%s %s %d\n", last, first, &curAreaCode);
// Detect the first areaCode
if (oldAreaCode == 0) {
oldAreaCode = curAreaCode;
count++;
}
// Count the number of people with the same area code
if (oldAreaCode == curAreaCode) {
count++;
total++;
}
else {
// Found a new area code, so print it and the count that we found
printf("Area code %d had %d unique names\n", oldAreaCode, count);
oldAreaCode = curAreaCode;
count = 1;
total++;
}
}
// Print the final area code / count
printf("Area code %d had %d unique names\n", oldAreaCode, count);
// Print out the total number of lines processed
printf("\n%d lines were processed in this report.\n", total);
// Close the temporary sort file and the last pipe
fclose(sortTemp);
close(inPipe[READ]);
return 0;
}
|
the_stack_data/65252.c | #include <stdio.h>
#include <stdlib.h>
struct Stack {
int * arr;
int size;
int top;
};
// Function to create a stack of given size
struct Stack* createStack (int size) {
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
stack->top = -1;
stack->size = size;
stack->arr = (int *) malloc(size * sizeof(int));
return stack;
}
int isFull (struct Stack* stack) {
return stack->top == stack->size - 1;
}
int isEmpty (struct Stack* stack) {
return stack->top == -1;
}
void push (struct Stack* stack, int data) {
if ( isFull(stack) ) {
printf("Stack Overflow");
return;
}
stack->arr[++stack->top] = data;
}
int pop (struct Stack* stack) {
if ( isEmpty(stack) ) {
printf("Stack Underflow");
return;
}
return stack->arr[stack->top--];
}
int main(int argc, char const *argv[]) {
struct Stack* stack = createStack(10);
push(stack, 10);
push(stack, 20);
push(stack, 30);
printf("%d popped from stack\n", pop(stack));
printf("%d popped from stack\n", pop(stack));
return 0;
} |
the_stack_data/42514.c | /*
* (C) 2001 Clemson University and The University of Chicago
*
* See COPYING in top-level directory.
*/
#undef _FILE_OFFSET_BITS
#include <unistd.h>
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <sys/uio.h>
#include <linux/unistd.h>
#if defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__)
#define __NR_readx 321
#define __NR_writex 322
#elif defined (x86_64) || defined (__x86_64__)
#define __NR_readx 280
#define __NR_writex 281
#endif
struct xtvec {
off_t xtv_off;
size_t xtv_len;
};
/* the _syscallXX apprroach is not portable. instead, we'll use syscall and
* sadly forego any type checking. For reference, here are the prototypes for
* the system calls
static ssize_t readx(unsigned long, const struct iovec *, unsigned long, const struct xtvec *, unsigned long);
static ssize_t writex(unsigned long, const struct iovec *, unsigned long, const struct xtvec *, unsigned long);
*/
#ifndef Ld
#define Ld(x) (x)
#endif
#ifndef FNAME
#define FNAME "/tmp/test.out"
#endif
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#ifndef MAX_REGIONS
#define MAX_REGIONS 2
#endif
#ifndef MAX_OFFSET
#define MAX_OFFSET 32768
#endif
#ifndef MAX_BUF_SIZE
#define MAX_BUF_SIZE 32768
#endif
static int max_regions = MAX_REGIONS;
static off_t max_offset = MAX_OFFSET;
static void usage(int argc, char** argv);
static double Wtime(void);
typedef size_t cm_count_t;
typedef off_t cm_offset_t;
typedef size_t cm_size_t;
typedef struct {
cm_count_t cf_valid_count;
cm_offset_t *cf_valid_start;
cm_size_t *cf_valid_size;
void *wr_buffer;
void *rd_buffer;
int buf_size;
} cm_frame_t;
static int construct_iovec(struct iovec **iov, cm_count_t valid_count,
cm_size_t *valid_size, cm_offset_t *valid_offset, char *buf)
{
int i;
*iov = (struct iovec *) malloc(valid_count * sizeof(struct iovec));
for (i = 0; i < valid_count; i++) {
(*iov)[i].iov_base = buf + valid_offset[i];
(*iov)[i].iov_len = valid_size[i];
}
return 0;
}
static int construct_xtvec(struct xtvec **xtv, cm_count_t valid_count,
cm_size_t *valid_size, cm_offset_t *valid_offset, cm_offset_t base_offset)
{
int i;
*xtv = (struct xtvec *) malloc(valid_count * sizeof(struct xtvec));
for (i = 0; i < valid_count; i++) {
(*xtv)[i].xtv_off = base_offset + valid_offset[i];
(*xtv)[i].xtv_len = valid_size[i];
}
return 0;
}
static size_t fillup_buffer(cm_frame_t *frame)
{
size_t c, size = sizeof(double), should_be = 0, chunk_size = 0;
srand(time(NULL));
if (frame->buf_size < 0 || frame->buf_size % size != 0)
{
fprintf(stderr, "buffer size [%ld] must be a multiple of %ld\n",
(long) frame->buf_size, (long) size);
return -1;
}
frame->wr_buffer = (char *) calloc(frame->buf_size, sizeof(char));
assert(frame->wr_buffer);
frame->rd_buffer = (char *) calloc(frame->buf_size, sizeof(char));
assert(frame->rd_buffer);
for (c = 0; c < frame->buf_size / size; c++)
{
*((int *) frame->wr_buffer + c) = c;
}
frame->cf_valid_count = (rand() % max_regions) + 1;
frame->cf_valid_start = (cm_offset_t *) calloc(sizeof(cm_offset_t), frame->cf_valid_count);
frame->cf_valid_size = (cm_size_t *) calloc(sizeof(cm_size_t), frame->cf_valid_count);
assert(frame->cf_valid_start && frame->cf_valid_size);
chunk_size = frame->buf_size / frame->cf_valid_count;
printf("Buffer size is %d bytes\n", frame->buf_size);
printf("Generating %ld valid regions\n", (long) frame->cf_valid_count);
for (c = 0; c < frame->cf_valid_count; c++)
{
int tmp_start;
tmp_start = rand() % chunk_size;
frame->cf_valid_start[c] = c * chunk_size + tmp_start;
frame->cf_valid_size[c] = (rand() % (chunk_size - tmp_start)) + 1;
assert(frame->cf_valid_start[c] + frame->cf_valid_size[c] <= frame->buf_size);
printf("(%ld): valid_start: %ld, valid_size: %ld\n",(long) c, (long) frame->cf_valid_start[c],
(long) frame->cf_valid_size[c]);
should_be += frame->cf_valid_size[c];
}
printf("readx/writex should xfer %ld bytes\n", (long) should_be);
return should_be;
}
int main(int argc, char **argv)
{
ssize_t ret = -1;
cm_offset_t offset;
char *fname = NULL;
double time1, time2;
int c;
size_t should_be = 0;
cm_frame_t frame;
int fh = -1;
struct iovec *rdiov = NULL, *wriov = NULL;
struct xtvec *xtv = NULL;
size_t file_size;
struct stat statbuf;
frame.cf_valid_count = 0;
frame.cf_valid_start = NULL;
frame.cf_valid_size = NULL;
frame.wr_buffer = NULL;
frame.rd_buffer = NULL;
frame.buf_size = MAX_BUF_SIZE;
while ((c = getopt(argc, argv, "o:r:b:f:h")) != EOF)
{
switch (c)
{
case 'o':
max_offset = atoi(optarg);
break;
case 'r':
max_regions = atoi(optarg);
break;
case 'f':
fname = optarg;
break;
case 'b':
frame.buf_size = atoi(optarg);
break;
case 'h':
default:
usage(argc, argv);
exit(1);
}
}
if (fname == NULL)
{
fname = FNAME;
}
if ((should_be = fillup_buffer(&frame)) < 0)
{
usage(argc, argv);
exit(1);
}
offset = rand() % max_offset;
/* start writing to the file */
ret = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0700);
if (ret < 0)
{
printf("open [1] failed [%ld]\n", (long) ret);
ret = -1;
goto main_out;
}
fh = ret;
printf("Writing at offset %ld\n", (long) offset);
construct_iovec(&rdiov, frame.cf_valid_count, frame.cf_valid_size, frame.cf_valid_start,
frame.rd_buffer);
construct_iovec(&wriov, frame.cf_valid_count, frame.cf_valid_size, frame.cf_valid_start,
frame.wr_buffer);
construct_xtvec(&xtv, frame.cf_valid_count, frame.cf_valid_size, frame.cf_valid_start, offset);
if (wriov == NULL || rdiov == NULL || xtv == NULL)
{
printf("could not construct iovec or xtvec\n");
ret = -1;
goto main_out;
}
time1 = Wtime();
/* write out the data */
ret = syscall(__NR_writex, fh, wriov, frame.cf_valid_count, xtv,
frame.cf_valid_count);
time2 = Wtime();
if (ret < 0)
{
printf("writex failed [%ld]\n", (unsigned long) ret);
ret = -1;
goto main_out;
}
/* sanity check */
if(should_be != ret)
{
fprintf(stderr, "Error: short write!\n");
fprintf(stderr, "Tried to write %ld bytes at offset %ld.\n",
(long) should_be, (long) offset);
fprintf(stderr, "Only got %ld bytes.\n",
(long) ret);
ret = -1;
goto main_out;
}
/* print some statistics */
printf("********************************************************\n");
printf("Writex Test Statistics:\n");
printf("********************************************************\n");
printf("Bytes written: %ld\n", (long) Ld(ret));
printf("Elapsed time: %f seconds\n", (time2-time1));
printf("Bandwidth: %f MB/second\n",
(((double)ret)/((double)(1024*1024))/(time2-time1)));
printf("********************************************************\n\n");
/* Get the size of the file as well */
ret = fstat(fh, &statbuf);
if (ret < 0)
{
printf("fstat failed [%ld]\n", (long) ret);
ret = -1;
goto main_out;
}
file_size = statbuf.st_size;
printf("Measured file size is %ld\n",(long)file_size);
/* try to reason the size of the file */
if (file_size != (offset + frame.cf_valid_start[frame.cf_valid_count - 1]
+ frame.cf_valid_size[frame.cf_valid_count - 1]))
{
printf("file size %ld is not equal to (%ld + %ld + %ld)\n",
(long) file_size, (long) offset, (long) frame.cf_valid_start[frame.cf_valid_count - 1],
(long) frame.cf_valid_size[frame.cf_valid_count - 1]);
ret = -1;
goto main_out;
}
/* close the file */
ret = close(fh);
if (ret < 0)
{
printf("close [1] failed [%ld]\n", (long) ret);
ret = -1;
goto main_out;
}
/* reopen the file and check the contents */
ret = open(fname, O_RDONLY);
if (ret < 0)
{
printf("open [2] failed [%ld]\n", (long) ret);
ret = -1;
goto main_out;
}
fh = ret;
/* now read it back from the file and make sure we have the correct data */
time1 = Wtime();
ret = syscall(__NR_readx, fh, rdiov, frame.cf_valid_count, xtv,
frame.cf_valid_count);
time2 = Wtime();
if(ret < 0)
{
printf("readx failed [%ld]\n", (long) ret);
ret = -1;
goto main_out;
}
/* sanity check */
if(should_be != ret)
{
fprintf(stderr, "Error: short reads!\n");
fprintf(stderr, "Tried to read %ld bytes at offset %ld.\n",
(long) should_be, (long) offset);
fprintf(stderr, "Only got %ld bytes.\n", (long) ret);
ret = -1;
goto main_out;
}
/* print some statistics */
printf("\n********************************************************\n");
printf("Readx Test Statistics:\n");
printf("********************************************************\n");
printf("Bytes read: %ld\n", (long) Ld(ret));
printf("Elapsed time: %f seconds\n", (time2-time1));
printf("Bandwidth: %f MB/second\n",
(((double)ret)/((double)(1024*1024))/(time2-time1)));
printf("********************************************************\n");
ret = 0;
/* now compare the relevant portions of what was written and what was read back */
for (c = 0; c < frame.cf_valid_count; c++)
{
if (memcmp((char *)frame.rd_buffer + frame.cf_valid_start[c],
(char *)frame.wr_buffer + frame.cf_valid_start[c],
frame.cf_valid_size[c]))
{
fprintf(stderr, "(%d) -> Read buffer did not match with write buffer from [%ld upto %ld bytes]\n",
c, (long) frame.cf_valid_start[c], (long) frame.cf_valid_size[c]);
ret = -1;
}
}
if (ret == 0)
{
fprintf(stdout, "Test passed!\n");
}
else
{
fprintf(stdout, "Test failed!\n");
}
main_out:
close(fh);
if (rdiov)
free(rdiov);
if (wriov)
free(wriov);
if (xtv)
free(xtv);
if(frame.rd_buffer)
free(frame.rd_buffer);
if(frame.wr_buffer)
free(frame.wr_buffer);
if(frame.cf_valid_start)
free(frame.cf_valid_start);
if(frame.cf_valid_size)
free(frame.cf_valid_size);
return(ret);
}
static void usage(int argc, char** argv)
{
fprintf(stderr, "Usage: %s -f [filename]\n", argv[0]);
fprintf(stderr, " -b [max. buffer size] default %d bytes.\n", MAX_BUF_SIZE);
fprintf(stderr, " -o [max. file offset] default %d bytes.\n", MAX_OFFSET);
fprintf(stderr, " -r [max. valid regions] default %d regions\n", MAX_REGIONS);
return;
}
static double Wtime(void)
{
struct timeval t;
gettimeofday(&t, NULL);
return((double)t.tv_sec + (double)(t.tv_usec) / 1000000);
}
/*
* Local variables:
* c-indent-level: 4
* c-basic-offset: 4
* End:
*
* vim: ts=8 sts=4 sw=4 noexpandtab
*/
|
the_stack_data/1055943.c | /* Program to introduce variables in C. */
#include <stdio.h>
main()
{
int v1 ; /* v1 is an integer variable. */
float v2 ; /* v2 is a floating-point variable. */
char v3 ; /* v3 is a character variable. */
/* Now assign some values to the variables. */
v1 = 65 ;
v2 = -18.23 ;
v3 = 'a' ;
/* Finally display the variable values on the screen. */
printf( "v1 has the value %d\n", v1 ) ;
printf( "v2 has the value %f\n", v2 ) ;
printf( "v3 has the value %c\n", v3 ) ;
printf( "End of program\n" ) ;
}
|
the_stack_data/117327648.c | //Classification: p/BO/AE/dA/D(A(v))/fr/ln
//Written by: Sergey Pomelov
//Reviewed by:
//Comment:
#include <stdio.h>
#include <malloc.h>
float *func(float *q) {
int i = 31;
q[i] = i;
return q;
}
int main(void)
{
float* a;
if((a = (float*)malloc(32*sizeof(float)))==NULL) {
printf("malloc error");
return 1;
}
printf("%f",*(func(a)+31));
free(a);
return 0;
}
|
the_stack_data/957384.c | /* { dg-do run } */
/* { dg-options "-O2 --save-temps" } */
extern void abort (void);
int z;
int
negs_si_test1 (int a, int b, int c)
{
int d = -b;
/* { dg-final { scan-assembler "negs\tw\[0-9\]+, w\[0-9\]+" } } */
if (d < 0)
return a + c;
z = d;
return b + c + d;
}
int
negs_si_test3 (int a, int b, int c)
{
int d = -(b) << 3;
/* { dg-final { scan-assembler "negs\tw\[0-9\]+, w\[0-9\]+, lsl 3" } } */
if (d == 0)
return a + c;
z = d;
return b + c + d;
}
typedef long long s64;
s64 zz;
s64
negs_di_test1 (s64 a, s64 b, s64 c)
{
s64 d = -b;
/* { dg-final { scan-assembler "negs\tx\[0-9\]+, x\[0-9\]+" } } */
if (d < 0)
return a + c;
zz = d;
return b + c + d;
}
s64
negs_di_test3 (s64 a, s64 b, s64 c)
{
s64 d = -(b) << 3;
/* { dg-final { scan-assembler "negs\tx\[0-9\]+, x\[0-9\]+, lsl 3" } } */
if (d == 0)
return a + c;
zz = d;
return b + c + d;
}
int main ()
{
int x;
s64 y;
x = negs_si_test1 (2, 12, 5);
if (x != 7)
abort ();
x = negs_si_test1 (1, 2, 32);
if (x != 33)
abort ();
x = negs_si_test3 (13, 14, 5);
if (x != -93)
abort ();
x = negs_si_test3 (15, 21, 2);
if (x != -145)
abort ();
y = negs_di_test1 (0x20202020ll,
0x65161611ll,
0x42434243ll);
if (y != 0x62636263ll)
abort ();
y = negs_di_test1 (0x1010101010101ll,
0x123456789abcdll,
0x5555555555555ll);
if (y != 0x6565656565656ll)
abort ();
y = negs_di_test3 (0x62523781ll,
0x64234978ll,
0x12345123ll);
if (y != 0xfffffffd553d4edbll)
abort ();
y = negs_di_test3 (0x763526268ll,
0x101010101ll,
0x222222222ll);
if (y != 0xfffffffb1b1b1b1bll)
abort ();
return 0;
}
|
the_stack_data/85714.c | #include<stdio.h>
#include<stdlib.h>
#define MAX_LENGTH 1000
int main () {
char c, palavra[MAX_LENGTH + 1];
palavra[MAX_LENGTH] = '\0';
int n, tamanho, i;
scanf("%d", &n);
scanf("%c", &c);
while (n) {
tamanho = 0;
scanf("%c", &c);
// executa as rodadas fora de ordem e ja durante a leitura
while (c != '\n') {
tamanho++;
palavra[MAX_LENGTH - tamanho] = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ? c + 3 : c;
if (tamanho % 2 != 0) palavra[MAX_LENGTH - ((tamanho + 1) / 2)] = palavra[MAX_LENGTH - ((tamanho + 1) / 2)] - 1;
scanf("%c", &c);
}
printf("%s\n", &palavra[MAX_LENGTH - tamanho]);
n--;
}
return 0;
}
|
the_stack_data/1214899.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
int x, res;
x = 5;
x %= 5;
res = ++x;
printf("El valor de x es: %i \n", res);
return 0;
}
|
the_stack_data/153267385.c | /*************************************************************************
> File Name: test_array_bounds.c
> Author: ziqiang
> Mail: [email protected]
> Created Time: Tue 27 Feb 2018 07:31:38 PM CST
************************************************************************/
#include <stdio.h>
int main()
{
int arr[4] = {0, 1, 2, 3};
arr[40] = 4;
printf("%d\n", arr[0]);
return 0;
}
|
the_stack_data/1070356.c | /*
* This file is part of libcuckoo
* It is free software under the LGPL 3.0
*
* @author Katharina "spacekookie" Sabel
*/
/* ====================================================================== */
/* The implementation here was originally done by Gary S. Brown. I have */
/* borrowed the tables directly, and made some minor changes to the */
/* crc32-function (including changing the interface) */
/* ====================================================================== */
/* */
/* COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or */
/* code or tables extracted from it, as desired without restriction. */
/* */
/* First, the polynomial itself and its table of feedback terms. The */
/* polynomial is */
/* X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+X^0 */
/* */
/* Note that we take it "backwards" and put the highest-order term in */
/* the lowest-order bit. The X^32 term is "implied"; the LSB is the */
/* X^31 term, etc. The X^0 term (usually shown as "+1") results in */
/* the MSB being 1. */
/* */
/* Note that the usual hardware shift register implementation, which */
/* is what we're using (we're merely optimizing it by doing eight-bit */
/* chunks at a time) shifts bits into the lowest-order term. In our */
/* implementation, that means shifting towards the right. Why do we */
/* do it this way? Because the calculated CRC must be transmitted in */
/* order from highest-order term to lowest-order term. UARTs transmit */
/* characters in order from LSB to MSB. By storing the CRC this way, */
/* we hand it to the UART in the order low-byte to high-byte; the UART */
/* sends each low-bit to hight-bit; and the result is transmission bit */
/* by bit from highest- to lowest-order term without requiring any bit */
/* shuffling on our part. Reception works similarly. */
/* */
/* The feedback terms table consists of 256, 32-bit entries. Notes: */
/* */
/* The table can be generated at runtime if desired; code to do so */
/* is shown later. It might not be obvious, but the feedback */
/* terms simply represent the results of eight shift/xor opera- */
/* tions for all combinations of data and CRC register values. */
/* */
/* The values must be right-shifted by eight bits by the "updcrc" */
/* logic; the shift must be unsigned (bring in zeroes). On some */
/* hardware you could probably optimize the shift in assembler by */
/* using byte-swap instructions. */
/* polynomial $edb88320 */
/* */
/* -------------------------------------------------------------------- */
static unsigned long crc32_tab[] = {
0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
0x2d02ef8dL
};
/* Return a 32-bit CRC of the contents of the buffer. */
unsigned long cuckoo_crc32(const unsigned char *s, unsigned int len) {
unsigned long crc32val = 0;
int i;
for (i = 0; i < len; i++)
crc32val = crc32_tab[(crc32val ^ s[i]) & 0xff] ^ (crc32val >> 8);
/** Return our constructed value */
return crc32val;
}
|
the_stack_data/40847.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2009-2020 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stdlib.h>
#include <unistd.h>
short hglob = 1;
short glob = 92;
void
bar()
{
if (glob == 0)
exit(1);
}
int commonfun() { bar(); return 0; } /* from hello */
int
hello(int x)
{
x *= 2;
return x + 45;
}
static void
hello_loop (void)
{
}
int
main()
{
int tmpx;
alarm (240);
bar();
tmpx = hello(glob);
commonfun();
glob = tmpx;
commonfun();
while (1)
{
hello_loop ();
usleep (20);
}
}
|
the_stack_data/25139117.c | /*
* Copyright (c) 2013, NVIDIA CORPORATION.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and/or associated documentation files (the
* "Materials"), to deal in the Materials without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Materials, and to
* permit persons to whom the Materials are furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* unaltered in all copies or substantial portions of the Materials.
* Any additions, deletions, or changes to the original source files
* must be clearly indicated in accompanying documentation.
*
* If only executable code is distributed, then the accompanying
* documentation must state that "this software is based in part on the
* work of the Khronos Group."
*
* THE MATERIALS ARE 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
* MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
#include <GL/glx.h>
#include <GL/gl.h>
#include <stdio.h>
#define PROC_DEFINES(ret, proc, params) \
typedef ret (*PTR_ ## proc) params ; \
static PTR_ ## proc p_ ## proc
#define CHECK_PROC(proc, args) do { \
printf("checking " #proc "\n"); \
if (!(p_ ## proc = \
(PTR_ ## proc)glXGetProcAddress((GLubyte *)#proc))) { \
printf("failed to get " #proc "!\n"); \
goto fail; \
} \
(*p_ ## proc) args; \
} while (0)
PROC_DEFINES(void *, glXGetProcAddress, (GLubyte *procName));
PROC_DEFINES(void, glXWaitGL, (void));
PROC_DEFINES(void, glVertex3fv, (GLfloat *v));
PROC_DEFINES(void, glXExampleExtensionFunction,
(Display *dpy, int screen, int *retval));
PROC_DEFINES(void, glBogusFunc1, (int a, int b, int c));
PROC_DEFINES(void, glBogusFunc2, (int a, int b, int c));
int main(int argc, char **argv)
{
Display *dpy = NULL;
int retval = 0;
/*
* Try GetProcAddress on different classes of API functions, and bogus
* functions. The API library should return entry point addresses for
* any function beginning with gl*(), though bogus functions will resolve
* to no-ops.
*/
dpy = XOpenDisplay(NULL);
if (dpy == NULL) {
printf("Can't open display\n");
goto fail;
}
/*
* Test core GLX dispatch functions implemented by API library. This
* simply returns the symbol exported by libGLX.
*/
CHECK_PROC(glXGetProcAddress, ((GLubyte *)"glBogusFunc1"));
CHECK_PROC(glXWaitGL, ());
/*
* Test a "GLX extension" function with a vendor-neutral dispatcher
* implemented by the vendor library (in this case, libGLX_dummy). If we
* successfully used libGLX_dummy's dispatcher, retval should be non-zero
* (a zero value indicates we might be calling into a no-op stub generated
* by libGLdispatch).
*/
CHECK_PROC(glXExampleExtensionFunction, (dpy, DefaultScreen(dpy), &retval));
if (!retval) {
printf("Unexpected glXExampleExtensionFunction() return value!\n");
goto fail;
}
/*
* Try getting the address of the core GL function glVertex3fv().
* This retrieves a static stub from glapi.
* Note calling this function with a NULL pointer is fine since this is a
* no-op function while there is no context current.
*/
CHECK_PROC(glVertex3fv, (NULL));
/*
* These are bogus functions, but will get a valid entry point since they
* are prefixed with "gl". The first GetProcAddress() will early out since
* there should be a cached copy from the explicit call made above, but
* the second one will go through glapi's dynamic stub generation path.
*
* Again, calling these functions should be a no-op.
*/
CHECK_PROC(glBogusFunc1, (0, 0, 0));
CHECK_PROC(glBogusFunc2, (1, 1, 1));
// Success!
return 0;
fail:
return -1;
}
|
the_stack_data/184518000.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stack
{
char* base;
char* top;
};
struct stack* stack_create(int length)
{
struct stack* tmp = (struct stack*)malloc(sizeof(struct stack));
tmp->base = tmp->top = (char*)malloc(length);
return tmp;
}
void stack_delete(struct stack* s)
{
free(s->base);
free(s);
}
char stack_get_top(struct stack* s)
{
return *s->top;
}
void stack_pop(struct stack* s)
{
s->top--;
}
void stack_push(struct stack* s,char e)
{
s->top++;
*s->top = e;
}
int stack_is_empty(struct stack* s)
{
return s->top == s->base;
}
int pivot(char op)
{
switch(op)
{
case '+':return 1;break;
case '-':return 1;break;
case '*':return 11;break;
case '/':return 11;break;
case '(':return -1;break;
default: return 0;
}
}
int main(int argc, char **argv)
{
int lines;
char input[1000];
char output[1000];
scanf("%d",&lines); getchar();
while(lines--)
{
gets(input);
int i,j,length = strlen(input);
struct stack* s = stack_create(length);
for(i=j=0;i<length;i++)
{
// 遇到操作数 直接添加
if(input[i]<='9'&&input[i]>='0')
output[j++] = input[i];
// 遇到左括号 直接入栈
else if(input[i] == '(')
stack_push(s,'(');
// 遇到右括号 一直出栈直到匹配
else if(input[i] == ')')
{
char op;
while((op=stack_get_top(s)) != '(')
{
output[j++] = op;
stack_pop(s);
}
stack_pop(s);
}
// 遇到其他运算符:加减乘除:
// 弹出所有优先级大于或者等于该运算符的栈顶元素,然后将该运算符入栈
else
{
char op;
while(!stack_is_empty(s))
{
op=stack_get_top(s);
if(pivot(op)>=pivot(input[i]))
{
output[j++] = op;
stack_pop(s);
}
else
break;
}
stack_push(s,input[i]);
}
}
while(!stack_is_empty(s))
{
output[j++] = stack_get_top(s);
stack_pop(s);
}
output[j] = '\0';
puts(output);
}
return 0;
}
|
the_stack_data/48576221.c | #include <stdlib.h>
#include <ctype.h>
char **parse(char *line) {
int i, fields;
char **rv;
for(i=0; isspace(line[i]); i++);
for(fields=i=0; line[i]; fields++) {
for(; line[i] && !isspace(line[i]); i++);
for(; isspace(line[i]); i++);
}
rv=(char **)malloc(sizeof(char *)*(fields+1));
for(; isspace(*line); line++);
for(i=0; *line; i++) {
rv[i]=line;
for(; *line && !isspace(*line); line++);
for(; isspace(*line); line++) *line='\0';
}
rv[i]=NULL;
return rv;
}
|
the_stack_data/111076880.c | #include<stdio.h>
int main()
{
int n,i,j;
int habibi[100];
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&habibi[i]);
}
for(j=n-1;j>=0;j--)
{
printf("%d\n",habibi[j]);
}
return 0;
}
|
the_stack_data/31388377.c | /*
*******************************************************************************
* Copyright (c) 2020-2021, STMicroelectronics
* All rights reserved.
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
*******************************************************************************
*/
#if defined(ARDUINO_GENERIC_F100V8TX) || defined(ARDUINO_GENERIC_F100VBTX)
#include "pins_arduino.h"
/**
* @brief System Clock Configuration
* @param None
* @retval None
*/
WEAK void SystemClock_Config(void)
{
/* SystemClock_Config can be generated by STM32CubeMX */
#warning "SystemClock_Config() is empty. Default clock at reset is used."
}
#endif /* ARDUINO_GENERIC_* */
|
Subsets and Splits